psychopy.tools.mathtools

Assorted math functions for working with vectors, matrices, and quaternions. These functions are intended to provide basic support for common mathematical operations associated with displaying stimuli (e.g. animation, posing, rendering, etc.)

For tools related to view transformations, see viewtools.

Vectors

Tools for working with 2D and 3D vectors.

length(v[, squared, out, dtype])

Get the length of a vector.

normalize(v[, out, dtype])

Normalize a vector or quaternion.

orthogonalize(v, n[, out, dtype])

Orthogonalize a vector relative to a normal vector.

reflect(v, n[, out, dtype])

Reflection of a vector.

dot(v0, v1[, out, dtype])

Dot product of two vectors.

cross(v0, v1[, out, dtype])

Cross product of 3D vectors.

project(v0, v1[, out, dtype])

Project a vector onto another.

perp(v, n[, norm, out, dtype])

Project v to be a perpendicular axis of n.

lerp(v0, v1, t[, out, dtype])

Linear interpolation (LERP) between two vectors/coordinates.

distance(v0, v1[, out, dtype])

Get the distance between vectors/coordinates.

angleTo(v, point[, degrees, out, dtype])

Get the relative angle to a point from a vector.

bisector(v0, v1[, norm, out, dtype])

Get the angle bisector.

surfaceNormal(tri[, norm, out, dtype])

Compute the surface normal of a given triangle.

surfaceBitangent(tri, uv[, norm, out, dtype])

Compute the bitangent vector of a given triangle.

surfaceTangent(tri, uv[, norm, out, dtype])

Compute the tangent vector of a given triangle.

vertexNormal(faceNorms[, norm, out, dtype])

Compute a vertex normal from shared triangles.

fixTangentHandedness(tangents, normals, ...)

Ensure the handedness of tangent vectors are all the same.

ortho3Dto2D(p, orig, normal, up[, right, dtype])

Get the planar coordinates of an orthogonal projection of a 3D point onto a 2D plane.

transform(pos, ori, points[, out, dtype])

Transform points using a position and orientation.

scale(sf, points[, out, dtype])

Scale points by a factor.

Quaternions

Tools for working with quaternions. Quaternions are used primarily here to represent rotations in 3D space.

articulate(boneVecs, boneOris[, dtype])

Articulate an armature.

slerp(q0, q1, t[, shortest, out, dtype])

Spherical linear interpolation (SLERP) between two quaternions.

quatToAxisAngle(q[, degrees, dtype])

Convert a quaternion to axis and angle representation.

quatFromAxisAngle(axis, angle[, degrees, dtype])

Create a quaternion to represent a rotation about axis vector by angle.

quatYawPitchRoll(q[, degrees, out, dtype])

Get the yaw, pitch, and roll of a quaternion's orientation relative to the world -Z axis.

alignTo(v, t[, out, dtype])

Compute a quaternion which rotates one vector to align with another.

quatMagnitude(q[, squared, out, dtype])

Get the magnitude of a quaternion.

multQuat(q0, q1[, out, dtype])

Multiply quaternion q0 and q1.

accumQuat(qlist[, out, dtype])

Accumulate quaternion rotations.

invertQuat(q[, out, dtype])

Get the multiplicative inverse of a quaternion.

applyQuat(q, points[, out, dtype])

Rotate points/coordinates using a quaternion.

quatToMatrix(q[, out, dtype])

Create a 4x4 rotation matrix from a quaternion.

Matrices

Tools to creating and using affine transformation matrices.

matrixToQuat(m[, out, dtype])

Convert a rotation matrix to a quaternion.

matrixFromEulerAngles(rx, ry, rz[, degrees, ...])

Construct a 4x4 rotation matrix from Euler angles.

scaleMatrix(s[, out, dtype])

Create a scaling matrix.

rotationMatrix(angle[, axis, out, dtype])

Create a rotation matrix.

translationMatrix(t[, out, dtype])

Create a translation matrix.

invertMatrix(m[, out, dtype])

Invert a square matrix.

isOrthogonal(m)

Check if a square matrix is orthogonal.

isAffine(m)

Check if a 4x4 square matrix describes an affine transformation.

multMatrix(matrices[, reverse, out, dtype])

Chain multiplication of two or more matrices.

concatenate(matrices[, out, dtype])

Concatenate matrix transformations.

normalMatrix(modelMatrix[, out, dtype])

Get the normal matrix from a model matrix.

forwardProject(objPos, modelView, proj[, ...])

Project a point in a scene to a window coordinate.

reverseProject(winPos, modelView, proj[, ...])

Unproject window coordinates into object or scene coordinates.

applyMatrix(m, points[, out, dtype])

Apply a matrix over a 2D array of points.

posOriToMatrix(pos, ori[, out, dtype])

Convert a rigid body pose to a 4x4 transformation matrix.

Collisions

Tools for determining whether a vector intersects a solid or bounding volume.

fitBBox(points[, dtype])

Fit an axis-aligned bounding box around points.

computeBBoxCorners(extents[, dtype])

Get the corners of an axis-aligned bounding box.

intersectRayPlane(rayOrig, rayDir, ...[, dtype])

Get the point which a ray intersects a plane.

intersectRaySphere(rayOrig, rayDir[, ...])

Calculate the points which a ray/line intersects a sphere (if any).

intersectRayAABB(rayOrig, rayDir, ...[, dtype])

Find the point a ray intersects an axis-aligned bounding box (AABB).

intersectRayOBB(rayOrig, rayDir, ...[, dtype])

Find the point a ray intersects an oriented bounding box (OBB).

intersectRayTriangle(rayOrig, rayDir, tri[, ...])

Get the intersection of a ray and triangle(s).

Distortion

Functions for generating barrel/pincushion distortion meshes to correct image distortion. Such distortion is usually introduced by lenses in the optical path between the viewer and the display.

lensCorrection(xys[, coefK, distCenter, ...])

Lens correction (or distortion) using the division model with even polynomial terms.

lensCorrectionSpherical(xys[, coefK, ...])

Simple lens correction.

Miscellaneous

Miscellaneous and helper functions.

zeroFix(a[, inplace, threshold])

Fix zeros in an array.

Performance and Optimization

Most functions listed here are very fast, however they are optimized to work on arrays of values (vectorization). Calling functions repeatedly (for instance within a loop), should be avoided as the CPU overhead associated with each function call (not to mention the loop itself) can be considerable.

For example, one may want to normalize a bunch of randomly generated vectors by calling normalize() on each row:

v = np.random.uniform(-1.0, 1.0, (1000, 4,))  # 1000 length 4 vectors
vn = np.zeros((1000, 4))  # place to write values

# don't do this!
for i in range(1000):
    vn[i, :] = normalize(v[i, :])

The same operation is completed in considerably less time by passing the whole array to the function like so:

normalize(v, out=vn)  # very fast!
vn = normalize(v)  # also fast if `out` is not provided

Specifying an output array to out will improve performance by reducing overhead associated with allocating memory to store the result (functions do this automatically if out is not provided). However, out should only be provided if the output array is reused multiple times. Furthermore, the function still returns a value if out is provided, but the returned value is a reference to out, not a copy of it. If out is not provided, the function will return the result with a freshly allocated array.

Data Types

Sub-routines used by the functions here will perform arithmetic using 64-bit floating-point precision unless otherwise specified via the dtype argument. This functionality is helpful in certain applications where input and output arrays demand a specific type (eg. when working with data passed to and from OpenGL functions).

If a dtype is specified, input arguments will be coerced to match that type and all floating-point arithmetic will use the precision of the type. If input arrays have the same type as dtype, they will automatically pass-through without being recast as a different type. As a performance consideration, all input arguments should have matching types and dtype set accordingly.

Most functions have an out argument, where one can specify an array to write values to. The value of dtype is ignored if out is provided, and all input arrays will be converted to match the dtype of out (if not already). This ensures that the type of the destination array is used for all arithmetic.


Back to top