Python numpy 模块,arctan2() 实例源码
我们从Python开源项目中,提取了以下48个代码示例,用于说明如何使用numpy.arctan2()。
def check_visibility(camera, pts_w, zmin=0, zmax=100):
"""
Check if points are visible given fov of camera.
This method checks for both horizontal and vertical
fov.
camera: type Camera
"""
# Transform points in to camera's reference
# Camera: p_cw
pts_c = camera.c2w(pts_w.reshape(-1, 3))
# Determine look-at vector, and check angle
# subtended with camera's z-vector (3rd column)
z = pts_c[:,2]
v = pts_c / np.linalg.norm(pts_c, axis=1).reshape(-1, 1)
hangle, vangle = np.arctan2(v[:,0], v[:,2]), np.arctan2(-v[:,1], v[:,2])
# Provides inds mask for all points that are within fov
return np.fabs(hangle) < camera.fov[0] * 0.5 and \
np.fabs(vangle) < camera.fov[1] * 0.5 and \
z >= zmin and z <= zmax
def setFromQTransform(self, tr):
p1 = Point(tr.map(0., 0.))
p2 = Point(tr.map(1., 0.))
p3 = Point(tr.map(0., 1.))
dp2 = Point(p2-p1)
dp3 = Point(p3-p1)
## detect flipped axes
if dp2.angle(dp3) > 0:
#da = 180
da = 0
sy = -1.0
else:
da = 0
sy = 1.0
self._state = {
'pos': Point(p1),
'scale': Point(dp2.length(), dp3.length() * sy),
'angle': (np.arctan2(dp2[1], dp2[0]) * 180. / np.pi) + da
}
self.update()
def setFromQTransform(self, tr):
p1 = Point(tr.map(0., 0.))
p2 = Point(tr.map(1., 0.))
p3 = Point(tr.map(0., 1.))
dp2 = Point(p2-p1)
dp3 = Point(p3-p1)
## detect flipped axes
if dp2.angle(dp3) > 0:
#da = 180
da = 0
sy = -1.0
else:
da = 0
sy = 1.0
self._state = {
'pos': Point(p1),
'scale': Point(dp2.length(), dp3.length() * sy),
'angle': (np.arctan2(dp2[1], dp2[0]) * 180. / np.pi) + da
}
self.update()
def great_circle_dist(p1, p2):
"""Return the distance (in km) between two points in
geographical coordinates.
"""
lon0, lat0 = p1
lon1, lat1 = p2
EARTH_R = 6372.8
lat0 = np.radians(float(lat0))
lon0 = np.radians(float(lon0))
lat1 = np.radians(float(lat1))
lon1 = np.radians(float(lon1))
dlon = lon0 - lon1
y = np.sqrt(
(np.cos(lat1) * np.sin(dlon)) ** 2
+ (np.cos(lat0) * np.sin(lat1)
- np.sin(lat0) * np.cos(lat1) * np.cos(dlon)) ** 2)
x = np.sin(lat0) * np.sin(lat1) + \
np.cos(lat0) * np.cos(lat1) * np.cos(dlon)
c = np.arctan2(y, x)
return EARTH_R * c
def get_phases(self):
sizeimg = np.real(self.imgfft).shape
mag = np.zeros(sizeimg)
for x in range(sizeimg[0]):
for y in range(sizeimg[1]):
mag[x][y] = np.arctan2(np.real(self.imgfft[x][y]), np.imag(self.imgfft[x][y]))
rpic = MyImage(mag)
rpic.limit(1)
return rpic
# int my = y-output.height/2;
# int mx = x-output.width/2;
# float angle = atan2(my, mx) - HALF_PI ;
# float radius = sqrt(mx*mx+my*my) / factor;
# float ix = map(angle,-PI,PI,input.width,0);
# float iy = map(radius,0,height,0,input.height);
# int inputIndex = int(ix) + int(iy) * input.width;
# int outputIndex = x + y * output.width;
# if (inputIndex <= input.pixels.length-1) {
# output.pixels[outputIndex] = input.pixels[inputIndex];
def circles(self, x1, y1, x2, y2, r, nmin=2):
arc = self.ctx.arc
fill = self.ctx.fill
dx = x1-x2
dy = y1-y2
dd = sqrt(dx*dx+dy*dy)
n = int(dd/self.pix)
n = n if n>nmin else nmin
a = arctan2(dy, dx)
scale = linspace(0, dd, n)
xp = x1-scale*cos(a)
yp = y1-scale*sin(a)
for x, y in zip(xp, yp):
arc(x, y, r, 0, pi*2.)
fill()
def sandstroke_non_linear(self,xys,grains=10,left=True):
pix = self.pix
rectangle = self.ctx.rectangle
fill = self.ctx.fill
dx = xys[:,2] - xys[:,0]
dy = xys[:,3] - xys[:,1]
aa = arctan2(dy,dx)
directions = column_stack([cos(aa),sin(aa)])
dd = sqrt(square(dx)+square(dy))
for i,d in enumerate(dd):
rnd = sqrt(random((grains,1)))
if left:
rnd = 1.0-rnd
for x,y in xys[i,:2] + directions[i,:]*rnd*d:
rectangle(x,y,pix,pix)
fill()
def sandstroke(self,xys,grains=10):
pix = self.pix
rectangle = self.ctx.rectangle
fill = self.ctx.fill
dx = xys[:,2] - xys[:,0]
dy = xys[:,3] - xys[:,1]
aa = arctan2(dy,dx)
directions = column_stack([cos(aa),sin(aa)])
dd = sqrt(square(dx)+square(dy))
for i,d in enumerate(dd):
for x,y in xys[i,:2] + directions[i,:]*random((grains,1))*d:
rectangle(x,y,pix,pix)
fill()
def dir_threshold(img, sobel_kernel=3, thresh=(0, np.pi/2)):
# Apply the following steps to img
# 1) Convert to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
# 2) Take the gradient in x and y separately
sobelx = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=sobel_kernel)
sobely = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=sobel_kernel)
# 3) Take the absolute value of the x and y gradients
abs_sobelx = np.absolute(sobelx)
abs_sobely = np.absolute(sobely)
# 4) Use np.arctan2(abs_sobely, abs_sobelx) to calculate the direction of the gradient
absgraddir = np.arctan2(abs_sobely, abs_sobelx)
# 5) Create a binary mask where direction thresholds are met
binary_output = np.zeros_like(absgraddir)
binary_output[(absgraddir >= thresh[0]) & (absgraddir <= thresh[1])] = 1
# 6) Return this mask as your binary_output image
return binary_output
# Define a function that applies Sobel x and y,
# then computes the magnitude of the gradient
# and applies a threshold
def make_spiral(self, r=0.25, G=0.0001):
for k in range(10):
x = self.X[:, 0] - 0.5
y = self.X[:, 1] - 0.5
theta = np.arctan2(x, y)
ds = [r * (i + theta / (2 * np.pi)) for i in range(int(1 / r))]
alphas = [np.sqrt(x ** 2 + y ** 2) / d for d in ds]
for alpha in alphas:
d = np.concatenate([(x * (1 - alpha))[:, None], (y * (1 - alpha))[:, None]], axis=1)
f = -G * d / (d ** 2).sum(axis=1, keepdims=True)
self.X += f
self.X = np.clip(self.X, 0, 1)
rs = np.arange(0, 0.7, 0.001)
theta = 2 * np.pi * rs / r
y = rs * np.sin(theta) + 0.5
x = -rs * np.cos(theta) + 0.5
spiral = zip(x, y)
self.collection = matplotlib.collections.LineCollection([spiral], colors='k')
def ecc(self, val):
'''
We need to update the time of pericenter passage whenever the
eccentricty, longitude of pericenter, period, or time of transit
changes. See the appendix in Shields et al. (2016).
'''
self._ecc = val
fi = (3 * np.pi / 2.) - self._w
self.tperi0 = self.t0 + (self.per * np.sqrt(1. - self.ecc * self.ecc) /
(2. * np.pi) * (self.ecc * np.sin(fi) /
(1. + self.ecc * np.cos(fi)) - 2.
/ np.sqrt(1. - self.ecc * self.ecc)
* np.arctan2(np.sqrt(1. - self.ecc * self.ecc)
* np.tan(fi/2.), 1. + self.ecc)))
def preprocess_edges(self):
# Calculate the sobel edge features
denom = 3 * 255.
grey = np.sum(self.image/denom, axis=2, keepdims=False, dtype=np.float32)
sobel_x = scipy.ndimage.sobel(grey, axis=0)
sobel_y = scipy.ndimage.sobel(grey, axis=1)
self.edge_angles = np.arctan2(sobel_y, sobel_x) # Counterclockwise
self.edge_magnitues = (sobel_x ** 2 + sobel_y ** 2) ** .5
assert(self.edge_angles.dtype == np.float32)
assert(self.edge_magnitues.dtype == np.float32)
if False:
plt.figure("EDGES")
plt.subplot(1,2,1)
plt.imshow(self.edge_magnitues, interpolation='nearest')
plt.title("MAG")
plt.subplot(1,2,2)
plt.imshow(self.edge_angles, interpolation='nearest')
plt.title("ANG")
plt.show()
def azimuth(_lAz_data):
_inc = _lAz_data[0]
_lat = _lAz_data[1]
velocity_eq = _lAz_data[2]
@jit(nopython=True)
def _az_calc():
inert_az = np.arcsin(max(min(np.cos(np.deg2rad(_inc)) / np.cos(np.deg2rad(_lat)), 1), -1))
_VXRot = _lAz_data[3] * np.sin(inert_az) - velocity_eq * np.cos(np.deg2rad(_lat))
_VYRot = _lAz_data[3] * np.cos(inert_az)
return np.rad2deg(np.fmod(np.arctan2(_VXRot, _VYRot) + (2 * pi), (2 * pi)))
_az = _az_calc()
if _lAz_data[4] == "Ascending": return _az
if _lAz_data[4] == "Descending":
if _az <= 90: return 180 - _az
elif _az >= 270: return 540 - _az
def azimuth(_lAz_data):
_inc = _lAz_data[0]
_lat = _lAz_data[1]
velocity_eq = _lAz_data[2]
@jit(nopython=True)
def _az_calc():
inert_az = np.arcsin(max(min(np.cos(np.deg2rad(_inc)) / np.cos(np.deg2rad(_lat)), 1), -1))
_VXRot = _lAz_data[3] * np.sin(inert_az) - velocity_eq * np.cos(np.deg2rad(_lat))
_VYRot = _lAz_data[3] * np.cos(inert_az)
return np.rad2deg(np.fmod(np.arctan2(_VXRot, _VYRot) + (2 * pi), (2 * pi)))
_az = _az_calc()
if _lAz_data[4] == "Ascending": return _az
if _lAz_data[4] == "Descending":
if _az <= 90: return 180 - _az
elif _az >= 270: return 540 - _az
def azimuth(_lAz_data):
_inc = _lAz_data[0]
_lat = _lAz_data[1]
velocity_eq = _lAz_data[2]
@jit(nopython=True)
def _az_calc():
inert_az = np.arcsin(max(min(np.cos(np.deg2rad(_inc)) / np.cos(np.deg2rad(_lat)), 1), -1))
_VXRot = _lAz_data[3] * np.sin(inert_az) - velocity_eq * np.cos(np.deg2rad(_lat))
_VYRot = _lAz_data[3] * np.cos(inert_az)
return np.rad2deg(np.fmod(np.arctan2(_VXRot, _VYRot) + (2 * pi), (2 * pi)))
_az = _az_calc()
if _lAz_data[4] == "Ascending": return _az
if _lAz_data[4] == "Descending":
if _az <= 90: return 180 - _az
elif _az >= 270: return 540 - _az
def azimuth(_lAz_data):
_inc = _lAz_data[0]
_lat = _lAz_data[1]
velocity_eq = _lAz_data[2]
@jit(nopython=True)
def _az_calc():
inert_az = np.arcsin(max(min(np.cos(np.deg2rad(_inc)) / np.cos(np.deg2rad(_lat)), 1), -1))
_VXRot = _lAz_data[3] * np.sin(inert_az) - velocity_eq * np.cos(np.deg2rad(_lat))
_VYRot = _lAz_data[3] * np.cos(inert_az)
return np.rad2deg(np.fmod(np.arctan2(_VXRot, _VYRot) + 360, 360))
_az = _az_calc()
if _lAz_data[4] == "Ascending": return _az
if _lAz_data[4] == "Descending":
if _az <= 90: return 180 - _az
elif _az >= 270: return 540 - _az
def asSpherical(self):
'''
Computes and returns a representation of this point in spherical coordinates: (r,phi,theta).
r = radius or distance of the point from the origin.
phi = is the angle of the projection on the xy plain and the x axis
theta = is the angle with the z axis.
x = r*cos(phi)*sin(theta)
y = r*sin(phi)*sin(theta)
z = r*cos(theta)
'''
x,y,z,_ = self.asArray()
r = np.sqrt(x**2+y**2+z**2)
phi = np.arctan2(y,x)
theta = np.arctan2(np.sqrt(x**2+y**2),z)
return r,phi,theta
def __init__(self,jet,kernels,k,x,y,pt,subpixel):
self.jet = jet
self.kernels = kernels
self.k = k
self.x = x
self.y = y
re = np.real(jet)
im = np.imag(jet)
self.mag = np.sqrt(re*re + im*im)
self.phase = np.arctan2(re,im)
if subpixel:
d = np.array([[pt.X()-x],[pt.Y()-y]])
comp = np.dot(self.k,d)
self.phase -= comp.flatten()
self.jet = self.mag*np.exp(1.0j*self.phase)
def vector_angle_in_degrees(v):
'''
Given a vector, returns its elevation angle in degrees (-180..180).
>>> vector_angle_in_degrees([1, 0])
0.0
>>> vector_angle_in_degrees([1, 1])
45.0
>>> vector_angle_in_degrees([0, 1])
90.0
>>> vector_angle_in_degrees([-1, 1])
135.0
>>> vector_angle_in_degrees([-1, 0])
180.0
>>> vector_angle_in_degrees([-1, -1])
-135.0
>>> vector_angle_in_degrees([0, -1])
-90.0
>>> vector_angle_in_degrees([1, -1])
-45.0
'''
return np.arctan2(v[1], v[0]) * 180 / np.pi
def calcAngSepDeg(ra0, dec0, ra1, dec1):
'''Return the angular separation between two objects. Use the
special case of the Vincenty formula that is accurate for all
distances'''
C = numpy.pi / 180
d0 = C * dec0
d1 = C * dec1
r12 = C * (ra0 - ra1)
cd0 = numpy.cos(d0)
sd0 = numpy.sin(d0)
cd1 = numpy.cos(d1)
sd1 = numpy.sin(d1)
cr12 = numpy.cos(r12)
sr12 = numpy.sin(r12)
num = numpy.sqrt((cd0 * sr12) ** 2 + (cd1 * sd0 - sd1 * cd0 * cr12) ** 2)
den = sd0 * sd1 + cd0 * cd1 * cr12
return numpy.arctan2(num, den) / C
def nodeEpochsCalc(paramsDI,omegaDIoffset):
"""
Calculate the epochs for the Ascending and Descending nodes, might be in different orbital
periods and AN/DN might be the wrong order, but should work for plotting... I hope...
"""
taAtNodes = [-1.0*paramsDI[9]+omegaDIoffset,180.0-1.0*paramsDI[9]+omegaDIoffset]
nodeEpochs = []
for ta in taAtNodes:
if ta<0.0:
ta =ta+360.0
elif ta>360:
ta =ta-360.0
TA_s_rad = ta*(np.pi/180.0)
top = np.sqrt(1.0-paramsDI[4])*np.sin(TA_s_rad/2.0)
btm = np.sqrt(1.0+paramsDI[4])*np.cos(TA_s_rad/2.0)
ATAN_rad = np.arctan2(top, btm)
#NOTE: both math.atan2 and np.arctan2 tried with same results, both produce negatives rather than continuous 0-360
#thus, must correct for negative outputs
if ATAN_rad<0:
ATAN_rad = ATAN_rad+(2.0*np.pi)
M_s_rad = ATAN_rad*2.0-paramsDI[4]*np.sin(ATAN_rad*2.0)
delta_t = (M_s_rad*paramsDI[7]*days_per_year)/(2.0*np.pi)
nodeEpochs.append(paramsDI[5]+delta_t)
return nodeEpochs
def polar3d(x):
"""
Polar coordinate representation of a three-dimensional vector.
@param x: vector (i.e. rank one array)
@return: polar coordinates (radius and polar angles)
"""
if x.shape != (3,):
raise ValueError(x)
r = norm(x)
theta = numpy.arccos(x[2] / r)
phi = numpy.arctan2(x[1], x[0])
return numpy.array([r, theta, phi])
def strike_direction(x1, y1, x2, y2):
"""
Calculate strike direction between two points.
Actually calculates "initial bearing" from (x1,y1) in direction
towards (x2,y2), following
http://www.movable-type.co.uk/scripts/latlong.html
"""
x1 = x1*numpy.pi/180.
y1 = y1*numpy.pi/180.
x2 = x2*numpy.pi/180.
y2 = y2*numpy.pi/180.
dx = x2-x1
theta = numpy.arctan2(numpy.sin(dx)*numpy.cos(y2), \
numpy.cos(y1)*numpy.sin(y2) \
- numpy.sin(y1)*numpy.cos(y2)*numpy.cos(dx))
s = theta*180./numpy.pi
if s<0:
s = 360+s
return s
def strike_direction(x1, y1, x2, y2):
"""
Calculate strike direction between two points.
Actually calculates "initial bearing" from (x1,y1) in direction
towards (x2,y2), following
http://www.movable-type.co.uk/scripts/latlong.html
"""
x1 = x1*numpy.pi/180.
y1 = y1*numpy.pi/180.
x2 = x2*numpy.pi/180.
y2 = y2*numpy.pi/180.
dx = x2-x1
theta = numpy.arctan2(numpy.sin(dx)*numpy.cos(y2), \
numpy.cos(y1)*numpy.sin(y2) \
- numpy.sin(y1)*numpy.cos(y2)*numpy.cos(dx))
s = theta*180./numpy.pi
if s<0:
s = 360+s
return s
def value(self, xyz):
xyz = xyz.reshape(-1,3)
a = self.a
b = self.b
c = self.c
d = self.d
vec1 = xyz[b] - xyz[a]
vec2 = xyz[c] - xyz[b]
vec3 = xyz[d] - xyz[c]
cross1 = np.cross(vec2, vec3)
cross2 = np.cross(vec1, vec2)
arg1 = np.sum(np.multiply(vec1, cross1)) * \
np.sqrt(np.sum(vec2**2))
arg2 = np.sum(np.multiply(cross1, cross2))
answer = np.arctan2(arg1, arg2)
return answer
def value(self, xyz):
xyz = xyz.reshape(-1,3)
a = np.array(self.a)
b = self.b
c = self.c
d = np.array(self.d)
xyza = np.mean(xyz[a], axis=0)
xyzd = np.mean(xyz[d], axis=0)
vec1 = xyz[b] - xyza
vec2 = xyz[c] - xyz[b]
vec3 = xyzd - xyz[c]
cross1 = np.cross(vec2, vec3)
cross2 = np.cross(vec1, vec2)
arg1 = np.sum(np.multiply(vec1, cross1)) * \
np.sqrt(np.sum(vec2**2))
arg2 = np.sum(np.multiply(cross1, cross2))
answer = np.arctan2(arg1, arg2)
return answer
def value(self, xyz):
xyz = xyz.reshape(-1,3)
a = self.a
b = self.b
c = self.c
d = self.d
vec1 = xyz[b] - xyz[a]
vec2 = xyz[c] - xyz[b]
vec3 = xyz[d] - xyz[c]
cross1 = np.cross(vec2, vec3)
cross2 = np.cross(vec1, vec2)
arg1 = np.sum(np.multiply(vec1, cross1)) * \
np.sqrt(np.sum(vec2**2))
arg2 = np.sum(np.multiply(cross1, cross2))
answer = np.arctan2(arg1, arg2)
return answer
def q_to_euler(q):
"""Converts Quaternions to Euler angles.
Parameters
----------
q : array_like
Array holding Quaternions.
Returns
-------
phi : float
`phi` angle in radians.
theta :float
`theta` angle in radians.
psi : float
`psi` angle in radians.
"""
phi = np.arctan2(2*(q[0]*q[1]+q[2]*q[3]),(q[0]**2+q[3]**2-q[1]**2-q[2]**2))
theta = np.arcsin(2*(q[0]*q[2]-q[1]*q[3]))
psi = np.arctan2(2*(q[0]*q[3]+q[1]*q[2]),(q[0]**2+q[1]**2-q[2]**2-q[3]**2))
return phi, theta, psi
def _circle_reference(state,
time,
finished,
radius=None,
speed=None,
init_angle=None,
z_vel=None):
ref = StateVector()
angle = init_angle + speed / radius * time
ref.pos = array([radius * cos(angle),
radius * sin(angle),
z_vel * time])
ref.vel[:] = [-speed * sin(angle), speed * cos(angle), z_vel]
ref.euler[2] = pi + np.arctan2(state.pos[1], state.pos[0])
# reference.omega_b[2] = speed / radius
return ref
# private stationary reference function
def erf(xgoal, x):
"""
Returns error e given two states xgoal and x.
Angle differences are taken properly on SO3.
"""
e = xgoal - x
c = np.cos(x[2])
s = np.sin(x[2])
cg = np.cos(xgoal[2])
sg = np.sin(xgoal[2])
e[2] = np.arctan2(sg*c - cg*s, cg*c + sg*s)
return e
################################################# OBJECTIVES
# Initial condition and goal
def erf(xgoal, x):
"""
Returns error e given two states xgoal and x.
Angle differences are taken properly on SO3.
"""
e = xgoal - x
c = np.cos(x[2])
s = np.sin(x[2])
cg = np.cos(xgoal[2])
sg = np.sin(xgoal[2])
e[2] = np.arctan2(sg*c - cg*s, cg*c + sg*s)
return e
################################################# OBJECTIVES
# Initial condition and goal
def erf(xgoal, x):
"""
Returns error e given two states xgoal and x.
"""
e = xgoal - x
c = np.cos(x[2])
s = np.sin(x[2])
cg = np.cos(xgoal[2])
sg = np.sin(xgoal[2])
e[2] = np.arctan2(sg*c - cg*s, cg*c + sg*s)
return e
################################################# OBJECTIVES
# Initial condition and goal
def erf(xgoal, x):
"""
Returns error e given two states xgoal and x.
Angle differences are taken properly on SO3.
"""
e = xgoal - x
c = np.cos(x[2])
s = np.sin(x[2])
cg = np.cos(xgoal[2])
sg = np.sin(xgoal[2])
e[2] = np.arctan2(sg*c - cg*s, cg*c + sg*s)
return e
################################################# OBJECTIVES
# Initial condition and goal
def erf(qgoal, q):
"""
Returns error e given two states qgoal and xq.
"""
e = qgoal - q
for i in [0, 1]:
c = np.cos(q[i])
s = np.sin(q[i])
cg = np.cos(qgoal[i])
sg = np.sin(qgoal[i])
e[i] = np.arctan2(sg*c - cg*s, cg*c + sg*s)
return e
################################################# OBJECTIVES AND CONSTRAINTS
# What is goal
def SortByAngle(kNearestPoints, currentPoint, prevPoint):
''' Sorts the k nearest points given by angle '''
angles = np.zeros(kNearestPoints.shape[0])
i = 0
for NearestPoint in kNearestPoints:
# calculate the angle
angle = np.arctan2(NearestPoint[1]-currentPoint[1],
NearestPoint[0]-currentPoint[0]) - \
np.arctan2(prevPoint[1]-currentPoint[1],
prevPoint[0]-currentPoint[0])
angle = np.rad2deg(angle)
# only positive angles
angle = np.mod(angle+360,360)
#print NearestPoint[0], NearestPoint[1], angle
angles[i] = angle
i=i+1
return kNearestPoints[np.argsort(angles)]
def convert_to_euler(R):
"""Compute the euler angles of this rotation.
Refer to [http://www.staff.city.ac.uk/~sbbh653/publications/euler.pdf]"""
alpha, beta, gamma = 0, 0, 0
if not np.isclose(np.abs(R[2,0]), 1):
beta = - np.arcsin(R[2,0])
alpha = np.arctan2(R[2,1] / np.cos(beta), R[2,2] / np.cos(beta))
gamma = np.arctan2(R[1,0] / np.cos(beta), R[0,0] / np.cos(beta))
else:
gamma = 0
if np.isclose(R[2,0], -1):
beta = np.pi / 2
alpha = gamma + np.arctan2(R[0,1], R[0,2])
else:
beta = - np.pi / 2
alpha = - gamma + np.arctan2(-R[0,1], -R[0,2])
return np.array([alpha, beta, gamma])
def newmeans(datapointwts,seeds,theta):
newseeds = []; cost = 0; avgspeed = []; pointsperseed = [];
cluster, p2cluster = point2cluster(datapointwts, seeds,theta);
for cd in cluster:
if len(cluster[cd])>0:
hh = np.arctan2(sum([np.sin(xx[2]/360*2*np.pi) for xx in cluster[cd]]),sum([np.cos(xx[2]/360*2*np.pi) for xx in cluster[cd]]))*180/np.pi
newseeds.append((np.mean([xx[0] for xx in cluster[cd]]),np.mean([xx[1] for xx in cluster[cd]]),hh))
hh = [xx[3] for xx in cluster[cd] if xx[3]>0];
if len(hh)<1:
hh = [0]
avgspeed.append(np.mean(hh))
cost = cost+sum([taxidist(xx,newseeds[-1],theta) for xx in cluster[cd]])
else:
newseeds.append(seeds[cd])
avgspeed.append(0)
pointsperseed.append(len(cluster[cd]))
return(newseeds,cost,avgspeed,pointsperseed)
def _cart2polar(x, y):
"""
Transform Cartesian coordinates to polar
Parameters
----------
x, y : floats or arrays
Cartesian coordinates
Returns
-------
r, theta : floats or arrays
Polar coordinates
"""
r = np.sqrt(x**2 + y**2)
theta = np.arctan2(x, y) # ? referenced to vertical
return r, theta
def angle_map(self):
'''Returns a map of the angle for each pixel (w.r.t. origin).
0 degrees is vertical, +90 degrees is right, -90 degrees is left.'''
if self.angle_map_data is not None:
return self.angle_map_data
x = (np.arange(self.width) - self.x0)
y = (np.arange(self.height) - self.y0)
X,Y = np.meshgrid(x,y)
#M = np.degrees(np.arctan2(Y, X))
# Note intentional inversion of the usual (x,y) convention.
# This is so that 0 degrees is vertical.
#M = np.degrees(np.arctan2(X, Y))
# TODO: Lookup some internal parameter to determine direction
# of normal. (This is what should befine the angle convention.)
M = np.degrees(np.arctan2(X, -Y))
self.angle_map_data = M
return self.angle_map_data
def test_output_equation_function_kwarg():
with pytest.raises(ValueError, match=zero_dim_output_msg):
DynamicalSystem(input_=x)
args = np.random.rand(len(x)+1)
sys = DynamicalSystem(state=x,
state_equation=state_equation,
constants_values=constants)
npt.assert_allclose(
sys.output_equation_function(args[0], args[1:]).squeeze(),
args[1:]
)
sys = DynamicalSystem(state=x,
state_equation=state_equation,
output_equation=output_equation,
constants_values=constants)
npt.assert_allclose(
sys.output_equation_function(args[0], args[1:]).squeeze(),
np.r_[args[1]**2 + args[2]**2, np.arctan2(args[2], args[1])]
)
def calculate_sift_grid(self, image, gridH, gridW):
H, W = image.shape
Npatches = gridH.size
feaArr = np.zeros((Npatches, Nsamples * Nangles))
# calculate gradient
GH, GW = gen_dgauss(self.sigma)
IH = signal.convolve2d(image, GH, mode='same')
IW = signal.convolve2d(image, GW, mode='same')
Imag = np.sqrt(IH ** 2 + IW ** 2)
Itheta = np.arctan2(IH, IW)
Iorient = np.zeros((Nangles, H, W))
for i in range(Nangles):
Iorient[i] = Imag * np.maximum(np.cos(Itheta - angles[i]) ** alpha, 0)
for i in range(Npatches):
currFeature = np.zeros((Nangles, Nsamples))
for j in range(Nangles):
currFeature[j] = np.dot(self.weights, \
Iorient[j, gridH[i]:gridH[i] + self.pS, gridW[i]:gridW[i] + self.pS].flatten())
feaArr[i] = currFeature.flatten()
return feaArr
def extract_sift_patches(self, image, gridH, gridW):
# extracts the sift descriptor of patches
# in positions (gridH,gridW) in the image
H, W = image.shape
Npatches = gridH.size
feaArr = np.zeros((Npatches, Nsamples * Nangles))
# calculate gradient
GH, GW = gen_dgauss(self.sigma)
IH = signal.convolve2d(image, GH, mode='same')
IW = signal.convolve2d(image, GW, mode='same')
Imag = np.sqrt(IH ** 2 + IW ** 2)
Itheta = np.arctan2(IH, IW)
Iorient = np.zeros((Nangles, H, W))
for i in range(Nangles):
Iorient[i] = Imag * np.maximum(np.cos(Itheta - angles[i]) ** alpha, 0)
for i in range(Npatches):
currFeature = np.zeros((Nangles, Nsamples))
for j in range(Nangles):
currFeature[j] = np.dot(self.weights, \
Iorient[j, gridH[i]:gridH[i] + self.pS, gridW[i]:gridW[i] + self.pS].flatten())
feaArr[i] = currFeature.flatten()
# feaArr contains each descriptor in a row
feaArr = self.normalize_sift(feaArr)
return feaArr
def make_cosine_basis(self):
'''Makes a spatial cosine and sine basis.
Returns:
list: A list where each entry is a 2D array of size
:data:`(patch_size, patch_size)` specifing the spatial basis.
'''
patch_size = self.patch_size
cosine_mask = np.zeros((patch_size, patch_size))
sine_mask = np.zeros((patch_size, patch_size))
for row in np.arange(patch_size):
for col in np.arange(patch_size):
theta = np.arctan2(patch_size / 2 - row, col - patch_size / 2)
cosine_mask[row, col] = np.cos(theta)
sine_mask[row, col] = np.sin(theta)
spatial_basis = list()
spatial_basis.append(cosine_mask)
spatial_basis.append(sine_mask)
return spatial_basis
def compute_grad(self):
"""
precompute gradient's magnitude and angle of pyramid
where angle is between (0, 2?)
"""
for oct_ind, layer_ind, layer in self.enumerate():
# todo: better kernel can be used?
grad_x = cv2.filter2D(layer, cv2.CV_64F, np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]]))
grad_y = cv2.filter2D(layer, cv2.CV_64F, np.array([[-1, -2, -1], [0, 0, 0], [1, 2, 1]]))
grad_mag = np.sqrt(grad_x**2 + grad_y**2)
grad_ang = np.arctan2(grad_y, grad_x) # each element in (-?, ?)
grad_ang %= TAU # (-?, 0) is moved to (?, 2*?)
self._grad_mag[oct_ind][layer_ind] = grad_mag
self._grad_ang[oct_ind][layer_ind] = grad_ang
def process_coords_for_computations(self, coords_for_computations, t):
"""
"""
if self._teffext:
return coords_for_computations
x, y, z, r = coords_for_computations[:,0], coords_for_computations[:,1], coords_for_computations[:,2], np.sqrt((coords_for_computations**2).sum(axis=1))
theta = np.arccos(z/r)
phi = np.arctan2(y, x)
xi_r = self._radamp * Y(self._m, self._l, theta, phi) * np.exp(-1j*2*np.pi*self._freq*t)
xi_t = self._tanamp * self.dYdtheta(self._m, self._l, theta, phi) * np.exp(-1j*2*np.pi*self._freq*t)
xi_p = self._tanamp/np.sin(theta) * self.dYdphi(self._m, self._l, theta, phi) * np.exp(-1j*2*np.pi*self._freq*t)
new_coords = np.zeros(coords_for_computations.shape)
new_coords[:,0] = coords_for_computations[:,0] + xi_r * np.sin(theta) * np.cos(phi)
new_coords[:,1] = coords_for_computations[:,1] + xi_r * np.sin(theta) * np.sin(phi)
new_coords[:,2] = coords_for_computations[:,2] + xi_r * np.cos(theta)
return new_coords
def updateState(self, vessel, connection):
# self.altitude = numpy.linalg.norm(vessel.position(vessel.orbit.body.reference_frame)) # from center of body, not SL
# self.velocity = vessel.flight(vessel.orbit.body.non_rotating_reference_frame).horizontal_speed
# # self.velocity = math.sqrt(square(vessel.flight(vessel.orbit.body.non_rotating_reference_frame).speed) - square(vessel.flight(vessel.orbit.body.non_rotating_reference_frame).vertical_speed))
# self.verticalVelocity = vessel.flight(vessel.orbit.body.non_rotating_reference_frame).vertical_speed
self.angle = numpy.arctan2(self.velocity(), self.verticalVelocity())
self.thrust = 0.0
for engine in self.engineList:
self.thrust = self.thrust + engine.engine.max_thrust
self.acceleration = self.thrust / vessel.mass
if self.isp <= 0:
self.isp = self.StageVacuumSpecificImpulse(self.insertionStage)
if self.thrust > 0:
self.exhaustVelocity = self.isp * 9.80665# / self.thrust
else:
self.exhaustVelocity = 0.01
if self.mu <= 0.0:
self.mu = vessel.orbit.body.gravitational_parameter
def updateState(self, vessel, connection):
# self.altitude = numpy.linalg.norm(vessel.position(vessel.orbit.body.reference_frame)) # from center of body, not SL
# self.velocity = vessel.flight(vessel.orbit.body.non_rotating_reference_frame).horizontal_speed
# # self.velocity = math.sqrt(square(vessel.flight(vessel.orbit.body.non_rotating_reference_frame).speed) - square(vessel.flight(vessel.orbit.body.non_rotating_reference_frame).vertical_speed))
# self.verticalVelocity = vessel.flight(vessel.orbit.body.non_rotating_reference_frame).vertical_speed
self.angle = numpy.arctan2(self.velocity, self.verticalVelocity)
self.thrust = 0.0
for engine in self.engineList:
self.thrust = self.thrust + engine.thrust
self.acceleration = self.thrust / vessel.mass
if self.isp <= 0:
self.isp = self.StageVacuumSpecificImpulse(self.insertionStage)
if self.thrust > 0:
self.exhaustVelocity = self.isp * 9.80665# / self.thrust
else:
self.exhaustVelocity = 0.01
if self.mu <= 0.0:
self.mu = vessel.orbit.body.gravitational_parameter
def azimuth(_lAz_data):
_inc = _lAz_data[0]
_lat = _lAz_data[1]
velocity_eq = _lAz_data[2]
@jit(nopython=True)
def _az_calc():
inert_az = np.arcsin(max(min(np.cos(np.deg2rad(_inc)) / np.cos(np.deg2rad(_lat)), 1), -1))
_VXRot = _lAz_data[3] * np.sin(inert_az) - velocity_eq * np.cos(np.deg2rad(_lat))
_VYRot = _lAz_data[3] * np.cos(inert_az)
return np.rad2deg(np.fmod(np.arctan2(_VXRot, _VYRot) + (2 * pi), (2 * pi)))
_az = _az_calc()
if _lAz_data[4] == "Ascending": return _az
if _lAz_data[4] == "Descending":
if _az <= 90: return 180 - _az
elif _az >= 270: return 540 - _az