Here are the examples of the python api numpy.cross taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
156 Examples
3
Example 1
def collinear(a, b, c):
area = np.linalg.norm(np.cross(a-b, a-c))/2
if area < 1e-2: # break tends to be between 1e1 and 1e-4
return True
else:
return False
3
Example 2
def cross(a, b):
unit_a = getunit(a)
unit_b = getunit(b)
if not unit_a and not unit_b:
return np.cross(a, b)
else:
if not unit_a:
unit_a = u.dimensionless_unscaled
if not unit_b:
unit_b = u.dimensionless_unscaled
return np.cross(a, b)*unit_a*unit_b
3
Example 3
def __init__(self, verts, tris, m=10.0):
self._verts = verts
self._tris = tris
# precompute some stuff needed later on
e01 = verts[tris[:,1]] - verts[tris[:,0]]
e12 = verts[tris[:,2]] - verts[tris[:,1]]
e20 = verts[tris[:,0]] - verts[tris[:,2]]
self._triangle_area = .5 * veclen(np.cross(e01, e12))
unit_normal = normalized(np.cross(normalized(e01), normalized(e12)))
self._unit_normal_cross_e01 = np.cross(unit_normal, e01)
self._unit_normal_cross_e12 = np.cross(unit_normal, e12)
self._unit_normal_cross_e20 = np.cross(unit_normal, e20)
# parameters for heat method
h = np.mean(map(veclen, [e01, e12, e20]))
t = m * h ** 2
# pre-factorize poisson systems
Lc, A = compute_mesh_laplacian(verts, tris)
self._factored_AtLc = splu((A - t * Lc).tocsc()).solve
self._factored_L = splu(Lc.tocsc()).solve
3
Example 4
Project: tyssue Source File: bulk_gradients.py
def volume_grad(eptm):
cell_pos = eptm.upcast_cell(eptm.cell_df[eptm.coords])
face_pos = eptm.upcast_face(eptm.face_df[eptm.coords])
srce_pos = eptm.upcast_srce(eptm.vert_df[eptm.coords])
trgt_pos = eptm.upcast_trgt(eptm.vert_df[eptm.coords])
grad_v_srce = np.cross((srce_pos - cell_pos), (face_pos - cell_pos)) / 6
grad_v_trgt = -np.cross((trgt_pos - cell_pos), (face_pos - cell_pos)) / 6
return (pd.DataFrame(grad_v_srce, index=eptm.edge_df.index,
columns=eptm.coords),
pd.DataFrame(grad_v_trgt, index=eptm.edge_df.index,
columns=eptm.coords))
3
Example 5
Project: vispy Source File: perspective.py
def _get_dim_vectors(self):
# Specify up and forward vector
M = {'+z': [(0, 0, +1), (0, 1, 0)],
'-z': [(0, 0, -1), (0, 1, 0)],
'+y': [(0, +1, 0), (1, 0, 0)],
'-y': [(0, -1, 0), (1, 0, 0)],
'+x': [(+1, 0, 0), (0, 0, 1)],
'-x': [(-1, 0, 0), (0, 0, 1)],
}
up, forward = M[self.up]
right = np.cross(forward, up)
return np.array(up), np.array(forward), right
3
Example 6
def volume4(xyz1, xyz2, xyz3, xyz4):
r"""
Gets the volume, :math:`V`, of the tetrahedron.
.. math:: V = \frac{(a-d) \cdot \left( (b-d) \times (c-d) \right) }{6}
"""
V = -dot((xyz1 - xyz4), cross(xyz2 - xyz4, xyz3 - xyz4)) / 6.
#V = 1/6. * np.det(
#np.hstack(
#[1., 1., 1., 1.],
#np.vstack(n1, n2, n3, n4).T,
#),
#)
return V
3
Example 7
Project: pycortex Source File: polyutils.py
@property
@_memo
def face_areas(self):
"""Area of each face.
"""
# Compute normal vector (length is face area)
nnfnorms = np.cross(self.ppts[:,1] - self.ppts[:,0],
self.ppts[:,2] - self.ppts[:,0])
# Compute vector length
return np.sqrt((nnfnorms**2).sum(-1)) / 2
3
Example 8
Project: cartopy Source File: clip_path.py
def lines_intersect(p0, p1, p2, p3):
"""
Return whether the two lines defined by p0->p1 and p2->p3 intersect.
"""
x_1, y_1 = p0
x_2, y_2 = p1
x_3, y_3 = p2
x_4, y_4 = p3
return (x_1 - x_2) * (y_3 - y_4) - (y_1 - y_2) * (x_3 - x_4) != 0
cp1 = np.cross(p1 - p0, p2 - p0)
cp2 = np.cross(p1 - p0, p3 - p0)
return np.sign(cp1) == np.sign(cp2) and cp1 != 0
3
Example 9
Project: Printrun Source File: stltool.py
def genfacet(v):
veca = v[1] - v[0]
vecb = v[2] - v[1]
vecx = numpy.cross(veca, vecb)
vlen = numpy.linalg.norm(vecx)
if vlen == 0:
vlen = 1
normal = vecx / vlen
return (normal, v)
3
Example 10
def update_force( self , pset ):
self.__Fe[:] = 0.0
self.__Fm[:] = 0.0
for key in self.__el_fields.keys() :
self.__el_fields[key]( self.__E , pset.X[:] )
self.__Fe[:] = self.__Fe[:] + self.__Q[:] * self.__E[:]
for key in self.__ma_fields.keys() :
self.__ma_fields[key]( self.__B , pset.X[:] )
self.__Fm[:] = self.__Fm[:] + self.__Q[:] * np.cross( pset.V[:] , self.__B[:] )
self.__Fe[:] += self.__Fm[:]
self.__A[:] = self.__Fe[:] / self.__M[:]
return self.__A
3
Example 11
def _calculate_normals(self):
# Calculate the normals
tris = self.vertexes.reshape(self.vertex_count / 3, 3, 3)
normals = np.cross(tris[::, 1] - tris[::, 0], tris[::, 2] - tris[::, 0])
normals /= np.linalg.norm(normals)
n = np.concatenate((np.concatenate((normals, normals), axis=1), normals), axis=1)
self.normal = n.reshape(self.vertex_count, 3)
3
Example 12
def getIdx(M_out,M_in,i,j):
#i,j on plane M_in is index m,n on plane m_out, m_in and m_out should be parallel
#check parallel
d = np.cross(M_in[0],M_in[1]);
d2 = np.cross(M_out[0],M_out[1]);
p = np.sum(d*d2)/np.sqrt(np.sum(d**2)*np.sum(d2**2));
if np.abs(1.0-p)>1e-3:
print("!!!ERROR, plane is not parallel");
return i,j;
#find the index
xyz = getPos(M_in,i,j);
MM = np.stack((M_out[0],M_out[1],d2)).T;
r = np.linalg.solve(MM,xyz-M_out[2]);
return int(r[0]),int(r[1]);
3
Example 13
Project: pyNastran Source File: cpenta6.py
def tri_area_centroid(n1, n2, n3):
"""
Gets the area, :math:`A`, and centroid of a triangle.::
1-----2
| /
| /
3
"""
a = n1 - n2
b = n2 - n3
area = 0.5 * norm(cross(a, b), axis=1)
centroid = (n1 + n2 + n3) / 3.
return(area, centroid)
3
Example 14
@staticmethod
def update_normals(sheet):
'''
Updates the face_df `coords` columns as the face's vertices
center of mass.
'''
coords = sheet.coords
face_pos = sheet.upcast_face(sheet.face_df[coords]).values
srce_pos = sheet.upcast_srce(sheet.vert_df[coords]).values
trgt_pos = sheet.upcast_trgt(sheet.vert_df[coords]).values
normals = np.cross(srce_pos - face_pos, trgt_pos - srce_pos)
sheet.edge_df[sheet.ncoords] = normals
3
Example 15
Project: lfd Source File: registration.py
def orthogonalize3_cross(mats_n33):
"turns each matrix into a rotation"
x_n3 = mats_n33[:,:,0]
# y_n3 = mats_n33[:,:,1]
z_n3 = mats_n33[:,:,2]
znew_n3 = math_utils.normr(z_n3)
ynew_n3 = math_utils.normr(np.cross(znew_n3, x_n3))
xnew_n3 = math_utils.normr(np.cross(ynew_n3, znew_n3))
return np.concatenate([xnew_n3[:,:,None], ynew_n3[:,:,None], znew_n3[:,:,None]],2)
3
Example 16
def dihedral(a, b, c, d, e):
"""
Calculates dihedral angle between 4 points in 3D (array with x,y,z)
"""
v1 = getNormedVector(b - a)
v2 = getNormedVector(b - c)
v4 = getNormedVector(d - c)
v3 = getNormedVector(c - e)
v1v2 = np.cross(v1, v2)
v3v4 = np.cross(v3, v4)
sign = 1 if np.linalg.det([v2, v1v2, v3v4]) < 0 else -1
angle = getAngle(v1v2, v3v4)
return sign * angle
3
Example 17
def _get_normals_data(self, elements, nodes=None):
"""
This is intended as a submethod to help handle the problem of bad normals
"""
if nodes is None:
nodes = self.nodes
self.log.debug("get_normals...elements.shape %s" % str(elements.shape))
p1 = nodes[elements[:, 0]]
p2 = nodes[elements[:, 1]]
p3 = nodes[elements[:, 2]]
v12 = p2 - p1
v13 = p3 - p1
v123 = np.cross(v12, v13)
normals_norm = np.linalg.norm(v123, axis=1)
inan = np.where(normals_norm == 0)[0]
return v123, normals_norm, inan
3
Example 18
Project: laspy Source File: glviewer.py
def camera_pitch(self,theta):
pointing = self.focus - self.location
axis = np.cross(self.up, pointing)
newpointing = self.rotate_vector(pointing, axis, theta)
self.focus = newpointing + self.location
self.up = np.cross(newpointing, axis)
self.up /= np.sqrt(self.up.dot(self.up))
3
Example 19
def cross(self, other):
if hasattr(other, 'get_units'):
units = self.get_units() * other.get_units()
else:
units = self.get_units()
return units * np.cross(self, other)
3
Example 20
def distance_to(self, point):
"""Calculate the minimum distance from the line to a point.
Equations are from here: http://mathworld.wolfram.com/Point-LineDistance2-Dimensional.html #14
Parameters
----------
point : Point, iterable
The point to calculate distance to.
"""
point = Point(point).as_array()
lp1 = self.point1.as_array()
lp2 = self.point2.as_array()
numerator = np.sqrt(np.sum(np.power(np.cross((lp2 - lp1), (lp1 - point)), 2)))
denominator = np.sqrt(np.sum(np.power(lp2 - lp1, 2)))
return numerator/denominator
3
Example 21
Project: vispy Source File: triangulation.py
def _iscounterclockwise(self, a, b, c):
# Check if the points lie in counter-clockwise order or not
A = self.pts[a]
B = self.pts[b]
C = self.pts[c]
return np.cross(B-A, C-B) > 0
3
Example 22
def _orientation(self, edge, point):
""" Returns +1 if edge[0]->point is clockwise from edge[0]->edge[1],
-1 if counterclockwise, and 0 if parallel.
"""
v1 = self.pts[point] - self.pts[edge[0]]
v2 = self.pts[edge[1]] - self.pts[edge[0]]
c = np.cross(v1, v2) # positive if v1 is CW from v2
return 1 if c > 0 else (-1 if c < 0 else 0)
3
Example 23
def angular_momentum(position, velocity):
"""Return angular momentum.
:param position: Position (r) [m]
:type position: :py:class:`~orbital.utilities.Position`
:param velocity: Velocity (v) [m/s]
:type velocity: :py:class:`~orbital.utilities.Velocity`
:return: Angular momentum (h) [N·m·s]
:rtype: :py:class:`~orbital.utilities.XyzVector`
"""
return XyzVector.from_array(np.cross(position, velocity))
3
Example 24
Project: numpy-stl Source File: base.py
@classmethod
def remove_empty_areas(cls, data):
vectors = data['vectors']
v0 = vectors[:, 0]
v1 = vectors[:, 1]
v2 = vectors[:, 2]
normals = numpy.cross(v1 - v0, v2 - v0)
squared_areas = (normals ** 2).sum(axis=1)
return data[squared_areas > AREA_SIZE_THRESHOLD ** 2]
3
Example 25
Project: plip Source File: supplemental.py
def ring_is_planar(ring, r_atoms):
"""Given a set of ring atoms, check if the ring is sufficiently planar
to be considered aromatic"""
normals = []
for a in r_atoms:
adj = pybel.ob.OBAtomAtomIter(a.OBAtom)
# Check for neighboring atoms in the ring
n_coords = [pybel.Atom(neigh).coords for neigh in adj if ring.IsMember(neigh)]
vec1, vec2 = vector(a.coords, n_coords[0]), vector(a.coords, n_coords[1])
normals.append(np.cross(vec1, vec2))
# Given all normals of ring atoms and their neighbors, the angle between any has to be 5.0 deg or less
for n1, n2 in itertools.product(normals, repeat=2):
arom_angle = vecangle(n1, n2)
if all([arom_angle > config.AROMATIC_PLANARITY, arom_angle < 180.0 - config.AROMATIC_PLANARITY]):
return False
return True
3
Example 26
Project: NeuroM Source File: morphmath.py
def angle_3points(p0, p1, p2):
''' compute the angle in radians between three 3D points
Calculated as the angle between p1-p0 and p2-p0.
Args:
p0, p1, p2: indexable objects with
indices 0, 1, 2 corresponding to 3D cartesian coordinates.
Returns:
Angle in radians between (p1-p0) and (p2-p0).
0.0 if p0==p1 or p0==p2.
'''
vec1 = vector(p1, p0)
vec2 = vector(p2, p0)
return math.atan2(np.linalg.norm(np.cross(vec1, vec2)), np.dot(vec1, vec2))
3
Example 27
Project: orange Source File: owprimitives3d.py
def normal_from_points(p1, p2, p3):
if isinstance(p1, (list, tuple)):
v1 = [p2[0]-p1[0], p2[1]-p1[1], p2[2]-p1[2]]
v2 = [p3[0]-p1[0], p3[1]-p1[1], p3[2]-p1[2]]
else:
v1 = p2 - p1
v2 = p3 - p1
return normalize(numpy.cross(v1, v2))
3
Example 28
def Normal(a, b):
"""finds the unit normal vector of 2 vectors"""
vector = cross(a, b)
length = norm(vector)
normal = vector / length
assert allclose(norm(normal), 1.)
return normal
3
Example 29
@nb.jit
def reciprocal_vectors(box_vectors):
a, b, c = box_vectors
norm = a.dot(np.cross(b, c))
u = 2 * np.pi * np.cross(b,c)/norm
v = 2 * np.pi * np.cross(c,a)/norm
w = 2 * np.pi * np.cross(a,b)/norm
return np.array([u, v, w])
3
Example 30
@Operation.factory
def Cross(a, b):
"""
Cross product op.
"""
return np.cross(a, b),
3
Example 31
@staticmethod
def update_normals(sheet):
coords = sheet.coords
face_pos = sheet.upcast_face(sheet.face_df[coords]).values
srce_pos = sheet.upcast_srce(sheet.vert_df[coords]).values
trgt_pos = sheet.upcast_trgt(sheet.vert_df[coords]).values
normals = np.cross(srce_pos - face_pos, trgt_pos - srce_pos)
sheet.edge_df["nz"] = normals
3
Example 32
def volume4(n1, n2, n3, n4):
r"""
Gets the volume, :math:`V`, of the tetrahedron.
.. math:: V = \frac{(a-d) \cdot \left( (b-d) \times (c-d) \right) }{6}
"""
V = -dot((n1 - n4), cross(n2 - n4, n3 - n4)) / 6.
return V
3
Example 33
def calculate_normals(self):
"""
Calculate surface normals for model vertices.
"""
a = self.vertices[0::3] - self.vertices[1::3]
b = self.vertices[1::3] - self.vertices[2::3]
cross = numpy.cross(a, b)
# normalize the cross product
magnitudes = numpy.apply_along_axis(numpy.linalg.norm, 1, cross).reshape(-1, 1)
normals = cross / magnitudes
# each of 3 facet vertices shares the same normal
normals = normals.repeat(3, 0)
return normals
3
Example 34
Project: poliastro Source File: _base.py
def pqw(self):
"""Perifocal frame (PQW) vectors. """
if self.ecc < 1e-8:
if abs(self.inc.to(u.rad).value) > 1e-8:
node = np.cross([0, 0, 1], self.h_vec) / norm(self.h_vec)
p_vec = node / norm(node) # Circular inclined
else:
p_vec = [1, 0, 0] * u.one # Circular equatorial
else:
p_vec = self.e_vec / self.ecc
w_vec = self.h_vec / norm(self.h_vec)
q_vec = np.cross(w_vec, p_vec) * u.one
return p_vec, q_vec, w_vec
3
Example 35
def calculate_angle(v1,v2):
"""
Calculate the signed angle between the vector \e v1 and the vector \e v2
\param v1 <c>array(3)</c> : vector 1
\param v2 <c>array(3)</c> : vector 2
\retval angle <c>float radian</c> : the angle in the two vector plane
"""
v1 = v1/norm(v1)
v2 = v2/norm(v2)
return np.arctan2(norm(np.cross(v1,v2)),np.dot(v1,v2))
3
Example 36
Project: pyNastran Source File: panair_grid_patch.py
def get_subpanel_properties(self, ipanel):
(p1, p2, p3, p4) = self.get_panel_points(ipanel)
p5 = 0.5 * (p1 + p2)
p6 = 0.5 * (p2 + p3)
p7 = 0.5 * (p3 + p4)
p8 = 0.5 * (p4 + p1)
p9 = 0.25 * (p1 + p2 + p3 + p4) # centroid
p10 = 0.5 * (p5 + p6)
p11 = 0.5 * (p6 + p7)
p12 = 0.5 * (p7 + p8)
p13 = 0.5 * (p8 + p5)
N1 = np.cross(p10 - p12, p11 - p13)
n1 = N1 / np.linalg.norm(N1)
N2 = np.cross(p5 - p7, p6 - p8)
n2 = N2 / np.linalg.norm(N2)
return p9, n1, n2
3
Example 37
@property
@_memo
def face_normals(self):
"""Normal vector for each face.
"""
# Compute normal vector direction
nnfnorms = np.cross(self.ppts[:,1] - self.ppts[:,0],
self.ppts[:,2] - self.ppts[:,0])
# Normalize to norm 1
nfnorms = nnfnorms / np.sqrt((nnfnorms**2).sum(1))[:,np.newaxis]
# Ensure that there are no nans (shouldn't be a problem with well-formed surfaces)
return np.nan_to_num(nfnorms)
3
Example 38
def rotate(v,k,theta):
"""[Euler-Rogrigues rotation formula](http://en.wikipedia.org/wiki/Rodrigues'_rotation_formula)
"""
c = cos(theta)
s = sin(theta)
return v*c + cross(k,v)*s + k*dot(k,v)*(1-c)
3
Example 39
Project: pycortex Source File: polyutils.py
@property
@_memo
def _facenorm_cross_edge(self):
ppts = self.ppts
fnorms = self.face_normals
fe12 = np.cross(fnorms, ppts[:,1] - ppts[:,0])
fe23 = np.cross(fnorms, ppts[:,2] - ppts[:,1])
fe31 = np.cross(fnorms, ppts[:,0] - ppts[:,2])
return fe12, fe23, fe31
3
Example 40
Project: pyNastran Source File: data_in_material_coord.py
def calc_imat(normals, csysi):
"""
Calculates the i vector in the material coordinate system.
j = k x ihat
jhat = j / |j|
i = jhat x k
Note
----
i is not a unit vector because k (the element normal)
is not a unit vector.
"""
jmat = cross(normals, csysi) # k x i
jmat /= norm(jmat)
imat = cross(jmat, normals)
return imat
3
Example 41
Project: FreeCAD_drawing_dimensioning Source File: svgLib_dd.py
def t_of_position( self, pos ):
pos_element = numpy.linalg.solve( self.T_element, pos - self.c_element )
A = numpy.linalg.solve(self.T_ellipse, pos_element)
B = self.center_circular
C = B + array([cos(self.theta_start), sin(self.theta_start)])
AB = (A - B) / norm(A-B)
BC = C - B
theta = arccos2(dot(AB,BC))
D = array([ A[0] - B[0], A[1] - B[1], 0.0 ])
E = array([ A[0] - C[0], A[1] - C[1], 0.0 ])
F = cross(D,E)
if F[2] < 0:
theta = -theta
#print(theta, self.dtheta, theta / self.dtheta )
return theta / self.dtheta
3
Example 42
Project: pele Source File: heisenberg_spin_system.py
def interpolate_spin(v1, v2, t):
vx = np.cross(v2, v1)
theta = np.arccos(np.dot(v1, v2))
theta *= (1.0 - t)
aa = theta * vx / np.linalg.norm(vx)
mx = rotations.aa2mx(aa)
v3 = np.dot(mx, v2)
return v3 / np.linalg.norm(v3)
3
Example 43
Project: rayopt Source File: utils.py
@public
def sagittal_meridional(u, z):
s = np.cross(u, z)
axial = np.all(s == 0, axis=-1)[..., None]
s = np.where(axial, (1., 0, 0), s)
m = np.cross(u, s)
normalize(s)
normalize(m)
return s, m
3
Example 44
Project: mystic Source File: CubeSection.py
def PlaneNormal(a, b, c):
assert(a >= 0 and a <= 1)
assert(b >= 0 and b <= 1)
assert(c >= 0 and c <= 2)
A = array([a, 0.0, 0.0])
B = array([0.0, b, 0.0])
if c < 1:
C = array([c, 0.0, 1.0])
else:
C = array([1.0, c-1.0, 1.0])
BA = B-A
CA = C-A
return cross(BA, CA)
3
Example 45
def zeroAreas(vertex, triangle_raw, Area_null):
"""
Looks for "zero-areas", areas that are really small, almost zero. It appends
them to Area_null list.
"""
for i in range(len(triangle_raw)):
L0 = vertex[triangle_raw[i,1]] - vertex[triangle_raw[i,0]]
L2 = vertex[triangle_raw[i,0]] - vertex[triangle_raw[i,2]]
normal_aux = numpy.cross(L0,L2)
Area_aux = numpy.linalg.norm(normal_aux)/2
if Area_aux<1e-10:
Area_null.append(i)
return Area_null
3
Example 46
Project: pele Source File: group_rotation.py
def measure_dihedral(coords, atoms):
indices = [3 * atom + k for atom in atoms for k in range(3)]
coords_0 = coords[indices[0:3]]
coords_1 = coords[indices[3:6]]
coords_2 = coords[indices[6:9]]
coords_3 = coords[indices[9:12]]
b1 = coords_1 - coords_0
b2 = coords_2 - coords_1
b3 = coords_3 - coords_2
b2_b3 = np.cross(b2, b3)
b1_b2 = np.cross(b1, b2)
angle = np.arctan2(np.linalg.norm(b2) * np.dot(b1, b2_b3), np.dot(b1_b2, b2_b3) )
return angle
3
Example 47
Project: poliastro Source File: _base.py
@property
def h_vec(self):
"""Specific angular momentum vector. """
h_vec = np.cross(self.r.to(u.km).value,
self.v.to(u.km / u.s)) * u.km ** 2 / u.s
return h_vec
3
Example 48
Project: orbital Source File: utilities.py
def node_vector(angular_momentum):
"""Return node vector.
:param angular_momentum: Angular momentum (h) [N·m·s]
:type angular_momentum: :py:class:`numpy.ndarray`
:return: Node vector (n) [N·m·s]
:rtype: :py:class:`~orbital.utilities.XyzVector`
"""
return XyzVector.from_array(np.cross([0, 0, 1], angular_momentum))
3
Example 49
def volume(self):
"""
volume = dot(a-d, cross(b-d, c-d))/6
based on http://en.wikipedia.org/wiki/Tetrahedron
"""
if self._volume is None:
self._volume = dot(self.p0-self.p3, cross(self.p1-self.p3, self.p2-self.p3))/6.
else:
return self._volume
return self._volume
3
Example 50
Project: NeuroM Source File: morphmath.py
def dist_point_line(p, l1, l2):
'''compute the orthogonal distance between from the line that goes through
the points l1, l2 and the point p
Args:
p, l1, l2 : iterable
point
indices 0, 1, 2 corresponding to cartesian coordinates
'''
cross_prod = np.cross(l2 - l1, p - l1)
return np.linalg.norm(cross_prod) / np.linalg.norm(l2 - l1)