def get_sph_theta(coords, normal):
# The angle (theta) with respect to the normal (J), is the arccos
# of the dot product of the normal with the normalized coordinate
# vector.
res_normal = resize_vector(normal, coords)
# check if the normal vector is normalized
# since arccos requires the vector to be normalised
res_normal = normalize_vector(res_normal)
tile_shape = [1] + list(coords.shape)[1:]
J = np.tile(res_normal,tile_shape)
JdotCoords = np.sum(J*coords,axis=0)
with np.errstate(invalid='ignore'):
ret = np.arccos( JdotCoords / np.sqrt(np.sum(coords**2,axis=0)))
ret[np.isnan(ret)] = 0
return ret
python类arccos()的实例源码
def segment_angle(line1, line2):
""" Angle between two segments """
vector_a = np.array([line1[0][0]-line1[1][0],
line1[0][1]-line1[1][1]])
vector_b = np.array([line2[0][0]-line2[1][0],
line2[0][1]-line2[1][1]])
# Get dot prod
dot_prod = np.dot(vector_a, vector_b)
# Get magnitudes
magnitude_a = np.dot(vector_a, vector_a)**0.5
magnitude_b = np.dot(vector_b, vector_b)**0.5
# Get angle in radians and then convert to degrees
angle = np.arccos(dot_prod/magnitude_b/magnitude_a)
# Basically doing angle <- angle mod 360
ang_deg = np.rad2deg(angle)%360
if ang_deg-180 >= 0:
# As in if statement
return 360 - ang_deg
else:
return ang_deg
def eval(self, coords, grad=False):
v1 = (coords[self.i]-coords[self.j])/bohr
v2 = (coords[self.k]-coords[self.j])/bohr
dot_product = np.dot(v1, v2)/(norm(v1)*norm(v2))
if dot_product < -1:
dot_product = -1
elif dot_product > 1:
dot_product = 1
phi = np.arccos(dot_product)
if not grad:
return phi
if abs(phi) > pi-1e-6:
grad = [
(pi-phi)/(2*norm(v1)**2)*v1,
(1/norm(v1)-1/norm(v2))*(pi-phi)/(2*norm(v1))*v1,
(pi-phi)/(2*norm(v2)**2)*v2
]
else:
grad = [
1/np.tan(phi)*v1/norm(v1)**2-v2/(norm(v1)*norm(v2)*np.sin(phi)),
(v1+v2)/(norm(v1)*norm(v2)*np.sin(phi)) -
1/np.tan(phi)*(v1/norm(v1)**2+v2/norm(v2)**2),
1/np.tan(phi)*v2/norm(v2)**2-v1/(norm(v1)*norm(v2)*np.sin(phi))
]
return phi, grad
def angle(a,b,c):
# In case numpy.dot() returns larger than 1
# and we cannot take acos() to that number
acos_out_of_bound = 1.0
v1 = a - b
v2 = c - b
v1 = v1 / np.sqrt(v1[0]**2 + v1[1]**2 + v1[2]**2)
v2 = v2 / np.sqrt(v2[0]**2 + v2[1]**2 + v2[2]**2)
dot_product = np.dot(v1,v2)
if dot_product > acos_out_of_bound:
dot_product = acos_out_of_bound
if dot_product < -1.0 * acos_out_of_bound:
dot_product = -1.0 * acos_out_of_bound
return np.arccos(dot_product)
def cartesian_to_spherical(x,degrees=True,normalize=False):
'''
Coverts a cartesian vector in R3 to spherical coordinates
'''
r = np.linalg.norm(x)
theta = np.arccos(x[2]/r)
phi = np.arctan2(x[1],x[0])
if degrees:
theta = np.degrees(theta)
phi = np.degrees(phi)
s = [r,theta,phi]
if normalize:
s /= np.linalg.norm(s)
return s
def createCirclePolygon(h, k, r, dx):
"""Create shapely polygon of a circle.
usage: p = createCirclePolygon(h, k, r, dx)
Args:
h: x coordinate of center.
k: y coordinate of center.
r: radius of circle.
dx: approximate distance between points * 10.
Returns:
Tuple (x, y) of numpy arrays of x and y coordinates of points.
"""
D = 10.0
theta = 2 * np.arccos((r - (dx / D)) / r)
npoints = int(360.0 / theta)
x, y = getPointsInCircum(r, n=npoints, h=h, k=k)
p = Polygon(list(zip(x, y)))
return p
def _samp_sphere(self, radius = 1):
# from http://stackoverflow.com/a/5408843/2565317
if radius is not np.array:
radius = np.array(radius)
n = radius.size
phi = np.random.rand(n) * 2 * np.pi
costheta = np.random.rand(n) * 2 - 1
u = np.random.rand(n)
theta = np.arccos( costheta )
r = radius * u ** (1. / 3)
x = r * np.sin(theta) * np.cos(phi)
y = r * np.sin(theta) * np.sin(phi)
z = r * np.cos(theta)
return x, y, z
#%%
test_umath.py 文件源码
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda
作者: SignalMedia
项目源码
文件源码
阅读 30
收藏 0
点赞 0
评论 0
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
test_umath.py 文件源码
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda
作者: SignalMedia
项目源码
文件源码
阅读 38
收藏 0
点赞 0
评论 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
test_umath.py 文件源码
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda
作者: SignalMedia
项目源码
文件源码
阅读 37
收藏 0
点赞 0
评论 0
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 angle_between(v1, v2):
""" Returns the angle in radians between vectors 'v1' and 'v2'::
>>> angle_between((1, 0, 0), (0, 1, 0))
1.5707963267948966
>>> angle_between((1, 0, 0), (1, 0, 0))
0.0
>>> angle_between((1, 0, 0), (-1, 0, 0))
3.141592653589793
"""
v1_u = _unit_vector(v1)
v2_u = _unit_vector(v2)
angle = np.arccos(np.dot(v1_u, v2_u))
if np.isnan(angle):
if (v1_u == v2_u).all():
return 0.0
else:
return np.pi
return angle
def _malicious():
"""
This function places the malicious mote in the middle of the network, not too close by the root.
"""
global min_range, motes
# add the malicious mote in the middle of the network
# get the average of the squared x and y deltas
avg_x = average([sign(m['x']) * m['x'] ** 2 for m in motes])
x = sign(avg_x) * sqrt(abs(avg_x))
avg_y = average([sign(m['y']) * m['y'] ** 2 for m in motes])
y = sign(avg_y) * sqrt(abs(avg_y))
# if malicious mote is too close by the root, just push it away
radius = sqrt(x ** 2 + y ** 2)
if radius < min_range:
angle = arccos(x / radius)
x, y = min_range * cos(angle), min_range * sin(angle)
return {'id': len(motes), 'type': 'malicious', 'x': x, 'y': y, 'z': 0}
# ************************************** NETWORK GENERATION FUNCTIONS ****************************************
def iotaDistanceGrid( iota, distance, Niota, Ndistance, minDistance=1, maxDistance=1000, padding=2., **kwargs ):
'''
returns a grid over iota and distance
return iotaGRID, distanceGRID
'''
cosIotaGRID = np.outer(np.linspace(-1, 1, Niota), np.ones(Ndistance)) ### spacing of inclinations
### maximum allowed "scaling constant" for placing distance grid
### take into account the detectability (malmquist prior -> gets rid of a lot of otherwise very densely sampled parameter-space
cosIota2 = np.cos(iota)**2
dM3 = ( (padding*distance)**2 / (0.25*(1+cosIota2)**2+cosIota2) )**(3./2)
### minimum allowed "scaling constant" for distance grid
dm3 = (minDistance/2**0.5)**3
do = np.outer(np.ones(Niota), np.linspace(dm3, dM3, Ndistance)**(1./3)) ### constants for scaling relation
cosIota2GRID = cosIotaGRID**2
distanceGRID = do*(0.25*(1+cosIota2GRID)**2 + cosIota2GRID)**0.5
distanceGRID = distanceGRID.flatten()
truth = (distanceGRID>=minDistance)*(distanceGRID<=maxDistance) ### exclude points outside of prior bounds
return np.arccos(cosIotaGRID).flatten()[truth], distanceGRID[truth]
def initVelocities(velocities):
# Generate total velocity
speed = stats.maxwell.rvs(loc=0,scale=config.a,size=config.nParticles)
# Generate a random direction
phi = np.random.uniform(0, np.pi*2, config.nParticles)
costheta = np.random.uniform(-1, 1, config.nParticles)
theta = np.arccos( costheta )
# Initalize the velocity vectors
velocities[:,0] = speed * np.sin( theta ) * np.cos( phi )
velocities[:,1] = speed * np.sin( theta ) * np.sin( phi )
velocities[:,2] = speed * np.cos( theta )
# Set center of mass velocity to zero
velocities -= np.mean(velocities,axis=0);
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 calculate_angle(p1, p2, p3):
""" Calculate angle for three given points in space
p2 -> o
/ \
p1 -> o o <- p3
"""
p1 = np.array(p1)
p2 = np.array(p2)
p3 = np.array(p3)
v21 = p1 - p2
v23 = p3 - p2
angle = np.arccos(np.dot(v21, v23) / (np.linalg.norm(v21) * np.linalg.norm(v23)))
return np.degrees(angle)
transformations.py 文件源码
项目:Neural-Networks-for-Inverse-Kinematics
作者: paramrajpura
项目源码
文件源码
阅读 44
收藏 0
点赞 0
评论 0
def angle_between_vectors(v0, v1, directed=True, axis=0):
"""Return angle between vectors.
If directed is False, the input vectors are interpreted as undirected axes,
i.e. the maximum angle is pi/2.
>>> a = angle_between_vectors([1, -2, 3], [-1, 2, -3])
>>> numpy.allclose(a, math.pi)
True
>>> a = angle_between_vectors([1, -2, 3], [-1, 2, -3], directed=False)
>>> numpy.allclose(a, 0)
True
>>> v0 = [[2, 0, 0, 2], [0, 2, 0, 2], [0, 0, 2, 2]]
>>> v1 = [[3], [0], [0]]
>>> a = angle_between_vectors(v0, v1)
>>> numpy.allclose(a, [0, 1.5708, 1.5708, 0.95532])
True
>>> v0 = [[2, 0, 0], [2, 0, 0], [0, 2, 0], [2, 0, 0]]
>>> v1 = [[0, 3, 0], [0, 0, 3], [0, 0, 3], [3, 3, 3]]
>>> a = angle_between_vectors(v0, v1, axis=1)
>>> numpy.allclose(a, [1.5708, 1.5708, 1.5708, 0.95532])
True
"""
v0 = numpy.array(v0, dtype=numpy.float64, copy=False)
v1 = numpy.array(v1, dtype=numpy.float64, copy=False)
dot = numpy.sum(v0 * v1, axis=axis)
dot /= vector_norm(v0, axis=axis) * vector_norm(v1, axis=axis)
return numpy.arccos(dot if directed else numpy.fabs(dot))
def slerp(val, low, high):
"""Code from https://github.com/soumith/dcgan.torch/issues/14"""
omega = np.arccos(np.clip(np.dot(low/np.linalg.norm(low), high/np.linalg.norm(high)), -1, 1))
so = np.sin(omega)
if so == 0:
return (1.0-val) * low + val * high # L'Hopital's rule/LERP
return np.sin((1.0-val)*omega) / so * low + np.sin(val*omega) / so * high