Debian Codegraph @

imgviz/external/transformations.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 # transformations.py
3
4 # Modified for inclusion in the `trimesh` library
5 # github.com/mikedh/trimesh
6 # -----------------------------------------------------------------------
7 #
8 # Copyright (c) 2006-2017, Christoph Gohlke
9 # Copyright (c) 2006-2017, The Regents of the University of California
10 # Produced at the Laboratory for Fluorescence Dynamics
11 # All rights reserved.
12 #
13 # Redistribution and use in source and binary forms, with or without
14 # modification, are permitted provided that the following conditions are met:
15 #
16 # * Redistributions of source code must retain the above copyright
17 # notice, this list of conditions and the following disclaimer.
18 # * Redistributions in binary form must reproduce the above copyright
19 # notice, this list of conditions and the following disclaimer in the
20 # documentation and/or other materials provided with the distribution.
21 # * Neither the name of the copyright holders nor the names of any
22 # contributors may be used to endorse or promote products derived
23 # from this software without specific prior written permission.
24 #
25 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
26 # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27 # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28 # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
29 # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
30 # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
31 # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
33 # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
34 # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
35 # POSSIBILITY OF SUCH DAMAGE.
36
37 """Homogeneous Transformation Matrices and Quaternions.
38
39 A library for calculating 4x4 matrices for translating, rotating, reflecting,
40 scaling, shearing, projecting, orthogonalizing, and superimposing arrays of
41 3D homogeneous coordinates as well as for converting between rotation matrices,
42 Euler angles, and quaternions. Also includes an Arcball control object and
43 functions to decompose transformation matrices.
44
45 :Author:
46 `Christoph Gohlke <http://www.lfd.uci.edu/~gohlke/>`_
47
48 :Organization:
49 Laboratory for Fluorescence Dynamics, University of California, Irvine
50
51 :Version: 2017.02.17
52
53 Requirements
54 ------------
55 * `CPython 2.7 or 3.4 <http://www.python.org>`_
56 * `numpy 1.9 <http://www.np.org>`_
57 * `Transformations.c 2015.03.19 <http://www.lfd.uci.edu/~gohlke/>`_
58 (recommended for speedup of some functions)
59
60 Notes
61 -----
62 The API is not stable yet and is expected to change between revisions.
63
64 This Python code is not optimized for speed. Refer to the transformations.c
65 module for a faster implementation of some functions.
66
67 Documentation in HTML format can be generated with epydoc.
68
69 Matrices (M) can be inverted using np.linalg.inv(M), be concatenated using
70 np.dot(M0, M1), or transform homogeneous coordinate arrays (v) using
71 np.dot(M, v) for shape (4, *) column vectors, respectively
72 np.dot(v, M.T) for shape (*, 4) row vectors ("array of points").
73
74 This module follows the "column vectors on the right" and "row major storage"
75 (C contiguous) conventions. The translation components are in the right column
76 of the transformation matrix, i.e. M[:3, 3].
77 The transpose of the transformation matrices may have to be used to interface
78 with other graphics systems, e.g. with OpenGL's glMultMatrixd(). See also [16].
79
80 Calculations are carried out with np.float64 precision.
81
82 Vector, point, quaternion, and matrix function arguments are expected to be
83 "array like", i.e. tuple, list, or numpy arrays.
84
85 Return types are numpy arrays unless specified otherwise.
86
87 Angles are in radians unless specified otherwise.
88
89 Quaternions w+ix+jy+kz are represented as [w, x, y, z].
90
91 A triple of Euler angles can be applied/interpreted in 24 ways, which can
92 be specified using a 4 character string or encoded 4-tuple:
93
94 *Axes 4-string*: e.g. 'sxyz' or 'ryxy'
95
96 - first character : rotations are applied to 's'tatic or 'r'otating frame
97 - remaining characters : successive rotation axis 'x', 'y', or 'z'
98
99 *Axes 4-tuple*: e.g. (0, 0, 0, 0) or (1, 1, 1, 1)
100
101 - inner axis: code of axis ('x':0, 'y':1, 'z':2) of rightmost matrix.
102 - parity : even (0) if inner axis 'x' is followed by 'y', 'y' is followed
103 by 'z', or 'z' is followed by 'x'. Otherwise odd (1).
104 - repetition : first and last axis are same (1) or different (0).
105 - frame : rotations are applied to static (0) or rotating (1) frame.
106
107 Other Python packages and modules for 3D transformations and quaternions:
108
109 * `Transforms3d <https://pypi.python.org/pypi/transforms3d>`_
110 includes most code of this module.
111 * `Blender.mathutils <http://www.blender.org/api/blender_python_api>`_
112 * `numpy-dtypes <https://github.com/numpy/numpy-dtypes>`_
113
114 References
115 ----------
116 (1) Matrices and transformations. Ronald Goldman.
117 In "Graphics Gems I", pp 472-475. Morgan Kaufmann, 1990.
118 (2) More matrices and transformations: shear and pseudo-perspective.
119 Ronald Goldman. In "Graphics Gems II", pp 320-323. Morgan Kaufmann, 1991.
120 (3) Decomposing a matrix into simple transformations. Spencer Thomas.
121 In "Graphics Gems II", pp 320-323. Morgan Kaufmann, 1991.
122 (4) Recovering the data from the transformation matrix. Ronald Goldman.
123 In "Graphics Gems II", pp 324-331. Morgan Kaufmann, 1991.
124 (5) Euler angle conversion. Ken Shoemake.
125 In "Graphics Gems IV", pp 222-229. Morgan Kaufmann, 1994.
126 (6) Arcball rotation control. Ken Shoemake.
127 In "Graphics Gems IV", pp 175-192. Morgan Kaufmann, 1994.
128 (7) Representing attitude: Euler angles, unit quaternions, and rotation
129 vectors. James Diebel. 2006.
130 (8) A discussion of the solution for the best rotation to relate two sets
131 of vectors. W Kabsch. Acta Cryst. 1978. A34, 827-828.
132 (9) Closed-form solution of absolute orientation using unit quaternions.
133 BKP Horn. J Opt Soc Am A. 1987. 4(4):629-642.
134 (10) Quaternions. Ken Shoemake.
135 http://www.sfu.ca/~jwa3/cmpt461/files/quatut.pdf
136 (11) From quaternion to matrix and back. JMP van Waveren. 2005.
137 http://www.intel.com/cd/ids/developer/asmo-na/eng/293748.htm
138 (12) Uniform random rotations. Ken Shoemake.
139 In "Graphics Gems III", pp 124-132. Morgan Kaufmann, 1992.
140 (13) Quaternion in molecular modeling. CFF Karney.
141 J Mol Graph Mod, 25(5):595-604
142 (14) New method for extracting the quaternion from a rotation matrix.
143 Itzhack Y Bar-Itzhack, J Guid Contr Dynam. 2000. 23(6): 1085-1087.
144 (15) Multiple View Geometry in Computer Vision. Hartley and Zissermann.
145 Cambridge University Press; 2nd Ed. 2004. Chapter 4, Algorithm 4.7, p 130.
146 (16) Column Vectors vs. Row Vectors.
147 http://steve.hollasch.net/cgindex/math/matrix/column-vec.html
148
149 Examples
150 --------
151 >>> alpha, beta, gamma = 0.123, -1.234, 2.345
152 >>> origin, xaxis, yaxis, zaxis = [0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1]
153 >>> I = identity_matrix()
154 >>> Rx = rotation_matrix(alpha, xaxis)
155 >>> Ry = rotation_matrix(beta, yaxis)
156 >>> Rz = rotation_matrix(gamma, zaxis)
157 >>> R = concatenate_matrices(Rx, Ry, Rz)
158 >>> euler = euler_from_matrix(R, 'rxyz')
159 >>> np.allclose([alpha, beta, gamma], euler)
160 True
161 >>> Re = euler_matrix(alpha, beta, gamma, 'rxyz')
162 >>> is_same_transform(R, Re)
163 True
164 >>> al, be, ga = euler_from_matrix(Re, 'rxyz')
165 >>> is_same_transform(Re, euler_matrix(al, be, ga, 'rxyz'))
166 True
167 >>> qx = quaternion_about_axis(alpha, xaxis)
168 >>> qy = quaternion_about_axis(beta, yaxis)
169 >>> qz = quaternion_about_axis(gamma, zaxis)
170 >>> q = quaternion_multiply(qx, qy)
171 >>> q = quaternion_multiply(q, qz)
172 >>> Rq = quaternion_matrix(q)
173 >>> is_same_transform(R, Rq)
174 True
175 >>> S = scale_matrix(1.23, origin)
176 >>> T = translation_matrix([1, 2, 3])
177 >>> Z = shear_matrix(beta, xaxis, origin, zaxis)
178 >>> R = random_rotation_matrix(np.random.rand(3))
179 >>> M = concatenate_matrices(T, R, Z, S)
180 >>> scale, shear, angles, trans, persp = decompose_matrix(M)
181 >>> np.allclose(scale, 1.23)
182 True
183 >>> np.allclose(trans, [1, 2, 3])
184 True
185 >>> np.allclose(shear, [0, math.tan(beta), 0])
186 True
187 >>> is_same_transform(R, euler_matrix(axes='sxyz', *angles))
188 True
189 >>> M1 = compose_matrix(scale, shear, angles, trans, persp)
190 >>> is_same_transform(M, M1)
191 True
192 >>> v0, v1 = random_vector(3), random_vector(3)
193 >>> M = rotation_matrix(angle_between_vectors(v0, v1), vector_product(v0, v1))
194 >>> v2 = np.dot(v0, M[:3,:3].T)
195 >>> np.allclose(unit_vector(v1), unit_vector(v2))
196 True
197
198 """
199
200 import math
201
202 import numpy as np
203
204 __version__ = "2017.02.17"
205 __docformat__ = "restructuredtext en"
206 __all__ = ()
207
208
209 def identity_matrix():
210 """Return 4x4 identity/unit matrix.
211
212 >>> I = identity_matrix()
213 >>> np.allclose(I, np.dot(I, I))
214 True
215 >>> np.sum(I), np.trace(I)
216 (4.0, 4.0)
217 >>> np.allclose(I, np.identity(4))
218 True
219
220 """
221 return np.identity(4)
222
223
224 def translation_matrix(direction):
225 """Return matrix to translate by direction vector.
226
227 >>> v = np.random.random(3) - 0.5
228 >>> np.allclose(v, translation_matrix(v)[:3, 3])
229 True
230
231 """
232 M = np.identity(4)
233 M[:3, 3] = direction[:3]
234 return M
235
236
237 def translation_from_matrix(matrix):
238 """Return translation vector from translation matrix.
239
240 >>> v0 = np.random.random(3) - 0.5
241 >>> v1 = translation_from_matrix(translation_matrix(v0))
242 >>> np.allclose(v0, v1)
243 True
244
245 """
246 return np.array(matrix, copy=False)[:3, 3].copy()
247
248
249 def reflection_matrix(point, normal):
250 """Return matrix to mirror at plane defined by point and normal vector.
251
252 >>> v0 = np.random.random(4) - 0.5
253 >>> v0[3] = 1.
254 >>> v1 = np.random.random(3) - 0.5
255 >>> R = reflection_matrix(v0, v1)
256 >>> np.allclose(2, np.trace(R))
257 True
258 >>> np.allclose(v0, np.dot(R, v0))
259 True
260 >>> v2 = v0.copy()
261 >>> v2[:3] += v1
262 >>> v3 = v0.copy()
263 >>> v2[:3] -= v1
264 >>> np.allclose(v2, np.dot(R, v3))
265 True
266
267 """
268 normal = unit_vector(normal[:3])
269 M = np.identity(4)
270 M[:3, :3] -= 2.0 * np.outer(normal, normal)
271 M[:3, 3] = (2.0 * np.dot(point[:3], normal)) * normal
272 return M
273
274
275 def reflection_from_matrix(matrix):
276 """Return mirror plane point and normal vector from reflection matrix.
277
278 >>> v0 = np.random.random(3) - 0.5
279 >>> v1 = np.random.random(3) - 0.5
280 >>> M0 = reflection_matrix(v0, v1)
281 >>> point, normal = reflection_from_matrix(M0)
282 >>> M1 = reflection_matrix(point, normal)
283 >>> is_same_transform(M0, M1)
284 True
285
286 """
287 M = np.array(matrix, dtype=np.float64, copy=False)
288 # normal: unit eigenvector corresponding to eigenvalue -1
289 w, V = np.linalg.eig(M[:3, :3])
290 i = np.where(abs(np.real(w) + 1.0) < 1e-8)[0]
291 if not len(i):
292 raise ValueError("no unit eigenvector corresponding to eigenvalue -1")
293 normal = np.real(V[:, i[0]]).squeeze()
294 # point: any unit eigenvector corresponding to eigenvalue 1
295 w, V = np.linalg.eig(M)
296 i = np.where(abs(np.real(w) - 1.0) < 1e-8)[0]
297 if not len(i):
298 raise ValueError("no unit eigenvector corresponding to eigenvalue 1")
299 point = np.real(V[:, i[-1]]).squeeze()
300 point /= point[3]
301 return point, normal
302
303
304 def rotation_matrix(angle, direction, point=None):
305 """
306 Return matrix to rotate about axis defined by point and
307 direction.
308
309 Parameters
310 -------------
311 angle : float, or sympy.Symbol
312 Angle, in radians or symbolic angle
313 direction : (3,) float
314 Unit vector along rotation axis
315 point : (3, ) float, or None
316 Origin point of rotation axis
317
318 Returns
319 -------------
320 matrix : (4, 4) float, or (4, 4) sympy.Matrix
321 Homogenous transformation matrix
322
323 Examples
324 -------------
325 >>> R = rotation_matrix(math.pi/2, [0, 0, 1], [1, 0, 0])
326 >>> np.allclose(np.dot(R, [0, 0, 0, 1]), [1, -1, 0, 1])
327 True
328 >>> angle = (random.random() - 0.5) * (2*math.pi)
329 >>> direc = np.random.random(3) - 0.5
330 >>> point = np.random.random(3) - 0.5
331 >>> R0 = rotation_matrix(angle, direc, point)
332 >>> R1 = rotation_matrix(angle-2*math.pi, direc, point)
333 >>> is_same_transform(R0, R1)
334 True
335 >>> R0 = rotation_matrix(angle, direc, point)
336 >>> R1 = rotation_matrix(-angle, -direc, point)
337 >>> is_same_transform(R0, R1)
338 True
339 >>> I = np.identity(4, np.float64)
340 >>> np.allclose(I, rotation_matrix(math.pi*2, direc))
341 True
342 >>> np.allclose(2, np.trace(rotation_matrix(math.pi/2,direc,point)))
343 True
344
345 """
346 # special case sympy symbolic angles
347 if type(angle).__name__ == "Symbol":
348 import sympy as sp
349
350 sina = sp.sin(angle)
351 cosa = sp.cos(angle)
352 else:
353 sina = math.sin(angle)
354 cosa = math.cos(angle)
355
356 direction = unit_vector(direction[:3])
357 # rotation matrix around unit vector
358 M = np.diag([cosa, cosa, cosa, 1.0])
359 M[:3, :3] += np.outer(direction, direction) * (1.0 - cosa)
360
361 direction = direction * sina
362 M[:3, :3] += np.array(
363 [
364 [0.0, -direction[2], direction[1]],
365 [direction[2], 0.0, -direction[0]],
366 [-direction[1], direction[0], 0.0],
367 ]
368 )
369
370 # if point is specified, rotation is not around origin
371 if point is not None:
372 point = np.array(point[:3], dtype=np.float64, copy=False)
373 M[:3, 3] = point - np.dot(M[:3, :3], point)
374
375 # return symbolic angles as sympy Matrix objects
376 if type(angle).__name__ == "Symbol":
377 return sp.Matrix(M)
378
379 return M
380
381
382 def rotation_from_matrix(matrix):
383 """Return rotation angle and axis from rotation matrix.
384
385 >>> angle = (random.random() - 0.5) * (2*math.pi)
386 >>> direc = np.random.random(3) - 0.5
387 >>> point = np.random.random(3) - 0.5
388 >>> R0 = rotation_matrix(angle, direc, point)
389 >>> angle, direc, point = rotation_from_matrix(R0)
390 >>> R1 = rotation_matrix(angle, direc, point)
391 >>> is_same_transform(R0, R1)
392 True
393
394 """
395 R = np.array(matrix, dtype=np.float64, copy=False)
396 R33 = R[:3, :3]
397 # direction: unit eigenvector of R33 corresponding to eigenvalue of 1
398 w, W = np.linalg.eig(R33.T)
399 i = np.where(abs(np.real(w) - 1.0) < 1e-8)[0]
400 if not len(i):
401 raise ValueError("no unit eigenvector corresponding to eigenvalue 1")
402 direction = np.real(W[:, i[-1]]).squeeze()
403 # point: unit eigenvector of R33 corresponding to eigenvalue of 1
404 w, Q = np.linalg.eig(R)
405 i = np.where(abs(np.real(w) - 1.0) < 1e-8)[0]
406 if not len(i):
407 raise ValueError("no unit eigenvector corresponding to eigenvalue 1")
408 point = np.real(Q[:, i[-1]]).squeeze()
409 point /= point[3]
410 # rotation angle depending on direction
411 cosa = (np.trace(R33) - 1.0) / 2.0
412 if abs(direction[2]) > 1e-8:
413 sina = (R[1, 0] + (cosa - 1.0) * direction[0] * direction[1]) / direction[2]
414 elif abs(direction[1]) > 1e-8:
415 sina = (R[0, 2] + (cosa - 1.0) * direction[0] * direction[2]) / direction[1]
416 else:
417 sina = (R[2, 1] + (cosa - 1.0) * direction[1] * direction[2]) / direction[0]
418 angle = math.atan2(sina, cosa)
419 return angle, direction, point
420
421
422 def scale_matrix(factor, origin=None, direction=None):
423 """Return matrix to scale by factor around origin in direction.
424
425 Use factor -1 for point symmetry.
426
427 >>> v = (np.random.rand(4, 5) - 0.5) * 20
428 >>> v[3] = 1
429 >>> S = scale_matrix(-1.234)
430 >>> np.allclose(np.dot(S, v)[:3], -1.234*v[:3])
431 True
432 >>> factor = random.random() * 10 - 5
433 >>> origin = np.random.random(3) - 0.5
434 >>> direct = np.random.random(3) - 0.5
435 >>> S = scale_matrix(factor, origin)
436 >>> S = scale_matrix(factor, origin, direct)
437
438 """
439 if direction is None:
440 # uniform scaling
441 M = np.diag([factor, factor, factor, 1.0])
442 if origin is not None:
443 M[:3, 3] = origin[:3]
444 M[:3, 3] *= 1.0 - factor
445 else:
446 # nonuniform scaling
447 direction = unit_vector(direction[:3])
448 factor = 1.0 - factor
449 M = np.identity(4)
450 M[:3, :3] -= factor * np.outer(direction, direction)
451 if origin is not None:
452 M[:3, 3] = (factor * np.dot(origin[:3], direction)) * direction
453 return M
454
455
456 def scale_from_matrix(matrix):
457 """Return scaling factor, origin and direction from scaling matrix.
458
459 >>> factor = random.random() * 10 - 5
460 >>> origin = np.random.random(3) - 0.5
461 >>> direct = np.random.random(3) - 0.5
462 >>> S0 = scale_matrix(factor, origin)
463 >>> factor, origin, direction = scale_from_matrix(S0)
464 >>> S1 = scale_matrix(factor, origin, direction)
465 >>> is_same_transform(S0, S1)
466 True
467 >>> S0 = scale_matrix(factor, origin, direct)
468 >>> factor, origin, direction = scale_from_matrix(S0)
469 >>> S1 = scale_matrix(factor, origin, direction)
470 >>> is_same_transform(S0, S1)
471 True
472
473 """
474 M = np.array(matrix, dtype=np.float64, copy=False)
475 M33 = M[:3, :3]
476 factor = np.trace(M33) - 2.0
477 try:
478 # direction: unit eigenvector corresponding to eigenvalue factor
479 w, V = np.linalg.eig(M33)
480 i = np.where(abs(np.real(w) - factor) < 1e-8)[0][0]
481 direction = np.real(V[:, i]).squeeze()
482 direction /= vector_norm(direction)
483 except IndexError:
484 # uniform scaling
485 factor = (factor + 2.0) / 3.0
486 direction = None
487 # origin: any eigenvector corresponding to eigenvalue 1
488 w, V = np.linalg.eig(M)
489 i = np.where(abs(np.real(w) - 1.0) < 1e-8)[0]
490 if not len(i):
491 raise ValueError("no eigenvector corresponding to eigenvalue 1")
492 origin = np.real(V[:, i[-1]]).squeeze()
493 origin /= origin[3]
494 return factor, origin, direction
495
496
497 def projection_matrix(point, normal, direction=None, perspective=None, pseudo=False):
498 """Return matrix to project onto plane defined by point and normal.
499
500 Using either perspective point, projection direction, or none of both.
501
502 If pseudo is True, perspective projections will preserve relative depth
503 such that Perspective = dot(Orthogonal, PseudoPerspective).
504
505 >>> P = projection_matrix([0, 0, 0], [1, 0, 0])
506 >>> np.allclose(P[1:, 1:], np.identity(4)[1:, 1:])
507 True
508 >>> point = np.random.random(3) - 0.5
509 >>> normal = np.random.random(3) - 0.5
510 >>> direct = np.random.random(3) - 0.5
511 >>> persp = np.random.random(3) - 0.5
512 >>> P0 = projection_matrix(point, normal)
513 >>> P1 = projection_matrix(point, normal, direction=direct)
514 >>> P2 = projection_matrix(point, normal, perspective=persp)
515 >>> P3 = projection_matrix(point, normal, perspective=persp, pseudo=True)
516 >>> is_same_transform(P2, np.dot(P0, P3))
517 True
518 >>> P = projection_matrix([3, 0, 0], [1, 1, 0], [1, 0, 0])
519 >>> v0 = (np.random.rand(4, 5) - 0.5) * 20
520 >>> v0[3] = 1
521 >>> v1 = np.dot(P, v0)
522 >>> np.allclose(v1[1], v0[1])
523 True
524 >>> np.allclose(v1[0], 3-v1[1])
525 True
526
527 """
528 M = np.identity(4)
529 point = np.array(point[:3], dtype=np.float64, copy=False)
530 normal = unit_vector(normal[:3])
531 if perspective is not None:
532 # perspective projection
533 perspective = np.array(perspective[:3], dtype=np.float64, copy=False)
534 M[0, 0] = M[1, 1] = M[2, 2] = np.dot(perspective - point, normal)
535 M[:3, :3] -= np.outer(perspective, normal)
536 if pseudo:
537 # preserve relative depth
538 M[:3, :3] -= np.outer(normal, normal)
539 M[:3, 3] = np.dot(point, normal) * (perspective + normal)
540 else:
541 M[:3, 3] = np.dot(point, normal) * perspective
542 M[3, :3] = -normal
543 M[3, 3] = np.dot(perspective, normal)
544 elif direction is not None:
545 # parallel projection
546 direction = np.array(direction[:3], dtype=np.float64, copy=False)
547 scale = np.dot(direction, normal)
548 M[:3, :3] -= np.outer(direction, normal) / scale
549 M[:3, 3] = direction * (np.dot(point, normal) / scale)
550 else:
551 # orthogonal projection
552 M[:3, :3] -= np.outer(normal, normal)
553 M[:3, 3] = np.dot(point, normal) * normal
554 return M
555
556
557 def projection_from_matrix(matrix, pseudo=False):
558 """Return projection plane and perspective point from projection matrix.
559
560 Return values are same as arguments for projection_matrix function:
561 point, normal, direction, perspective, and pseudo.
562
563 >>> point = np.random.random(3) - 0.5
564 >>> normal = np.random.random(3) - 0.5
565 >>> direct = np.random.random(3) - 0.5
566 >>> persp = np.random.random(3) - 0.5
567 >>> P0 = projection_matrix(point, normal)
568 >>> result = projection_from_matrix(P0)
569 >>> P1 = projection_matrix(*result)
570 >>> is_same_transform(P0, P1)
571 True
572 >>> P0 = projection_matrix(point, normal, direct)
573 >>> result = projection_from_matrix(P0)
574 >>> P1 = projection_matrix(*result)
575 >>> is_same_transform(P0, P1)
576 True
577 >>> P0 = projection_matrix(point, normal, perspective=persp, pseudo=False)
578 >>> result = projection_from_matrix(P0, pseudo=False)
579 >>> P1 = projection_matrix(*result)
580 >>> is_same_transform(P0, P1)
581 True
582 >>> P0 = projection_matrix(point, normal, perspective=persp, pseudo=True)
583 >>> result = projection_from_matrix(P0, pseudo=True)
584 >>> P1 = projection_matrix(*result)
585 >>> is_same_transform(P0, P1)
586 True
587
588 """
589 M = np.array(matrix, dtype=np.float64, copy=False)
590 M33 = M[:3, :3]
591 w, V = np.linalg.eig(M)
592 i = np.where(abs(np.real(w) - 1.0) < 1e-8)[0]
593 if not pseudo and len(i):
594 # point: any eigenvector corresponding to eigenvalue 1
595 point = np.real(V[:, i[-1]]).squeeze()
596 point /= point[3]
597 # direction: unit eigenvector corresponding to eigenvalue 0
598 w, V = np.linalg.eig(M33)
599 i = np.where(abs(np.real(w)) < 1e-8)[0]
600 if not len(i):
601 raise ValueError("no eigenvector corresponding to eigenvalue 0")
602 direction = np.real(V[:, i[0]]).squeeze()
603 direction /= vector_norm(direction)
604 # normal: unit eigenvector of M33.T corresponding to eigenvalue 0
605 w, V = np.linalg.eig(M33.T)
606 i = np.where(abs(np.real(w)) < 1e-8)[0]
607 if len(i):
608 # parallel projection
609 normal = np.real(V[:, i[0]]).squeeze()
610 normal /= vector_norm(normal)
611 return point, normal, direction, None, False
612 else:
613 # orthogonal projection, where normal equals direction vector
614 return point, direction, None, None, False
615 else:
616 # perspective projection
617 i = np.where(abs(np.real(w)) > 1e-8)[0]
618 if not len(i):
619 raise ValueError("no eigenvector not corresponding to eigenvalue 0")
620 point = np.real(V[:, i[-1]]).squeeze()
621 point /= point[3]
622 normal = -M[3, :3]
623 perspective = M[:3, 3] / np.dot(point[:3], normal)
624 if pseudo:
625 perspective -= normal
626 return point, normal, None, perspective, pseudo
627
628
629 def clip_matrix(left, right, bottom, top, near, far, perspective=False):
630 """Return matrix to obtain normalized device coordinates from frustum.
631
632 The frustum bounds are axis-aligned along x (left, right),
633 y (bottom, top) and z (near, far).
634
635 Normalized device coordinates are in range [-1, 1] if coordinates are
636 inside the frustum.
637
638 If perspective is True the frustum is a truncated pyramid with the
639 perspective point at origin and direction along z axis, otherwise an
640 orthographic canonical view volume (a box).
641
642 Homogeneous coordinates transformed by the perspective clip matrix
643 need to be dehomogenized (divided by w coordinate).
644
645 >>> frustum = np.random.rand(6)
646 >>> frustum[1] += frustum[0]
647 >>> frustum[3] += frustum[2]
648 >>> frustum[5] += frustum[4]
649 >>> M = clip_matrix(perspective=False, *frustum)
650 >>> a = np.dot(M, [frustum[0], frustum[2], frustum[4], 1])
651 >>> np.allclose(a, [-1., -1., -1., 1.])
652 True
653 >>> b = np.dot(M, [frustum[1], frustum[3], frustum[5], 1])
654 >>> np.allclose(b, [ 1., 1., 1., 1.])
655 True
656 >>> M = clip_matrix(perspective=True, *frustum)
657 >>> v = np.dot(M, [frustum[0], frustum[2], frustum[4], 1])
658 >>> c = v / v[3]
659 >>> np.allclose(c, [-1., -1., -1., 1.])
660 True
661 >>> v = np.dot(M, [frustum[1], frustum[3], frustum[4], 1])
662 >>> d = v / v[3]
663 >>> np.allclose(d, [ 1., 1., -1., 1.])
664 True
665
666 """
667 if left >= right or bottom >= top or near >= far:
668 raise ValueError("invalid frustum")
669 if perspective:
670 if near <= _EPS:
671 raise ValueError("invalid frustum: near <= 0")
672 t = 2.0 * near
673 M = [
674 [t / (left - right), 0.0, (right + left) / (right - left), 0.0],
675 [0.0, t / (bottom - top), (top + bottom) / (top - bottom), 0.0],
676 [0.0, 0.0, (far + near) / (near - far), t * far / (far - near)],
677 [0.0, 0.0, -1.0, 0.0],
678 ]
679 else:
680 M = [
681 [2.0 / (right - left), 0.0, 0.0, (right + left) / (left - right)],
682 [0.0, 2.0 / (top - bottom), 0.0, (top + bottom) / (bottom - top)],
683 [0.0, 0.0, 2.0 / (far - near), (far + near) / (near - far)],
684 [0.0, 0.0, 0.0, 1.0],
685 ]
686 return np.array(M)
687
688
689 def shear_matrix(angle, direction, point, normal):
690 """Return matrix to shear by angle along direction vector on shear plane.
691
692 The shear plane is defined by a point and normal vector. The direction
693 vector must be orthogonal to the plane's normal vector.
694
695 A point P is transformed by the shear matrix into P" such that
696 the vector P-P" is parallel to the direction vector and its extent is
697 given by the angle of P-P'-P", where P' is the orthogonal projection
698 of P onto the shear plane.
699
700 >>> angle = (random.random() - 0.5) * 4*math.pi
701 >>> direct = np.random.random(3) - 0.5
702 >>> point = np.random.random(3) - 0.5
703 >>> normal = np.cross(direct, np.random.random(3))
704 >>> S = shear_matrix(angle, direct, point, normal)
705 >>> np.allclose(1, np.linalg.det(S))
706 True
707
708 """
709 normal = unit_vector(normal[:3])
710 direction = unit_vector(direction[:3])
711 if abs(np.dot(normal, direction)) > 1e-6:
712 raise ValueError("direction and normal vectors are not orthogonal")
713 angle = math.tan(angle)
714 M = np.identity(4)
715 M[:3, :3] += angle * np.outer(direction, normal)
716 M[:3, 3] = -angle * np.dot(point[:3], normal) * direction
717 return M
718
719
720 def shear_from_matrix(matrix):
721 """Return shear angle, direction and plane from shear matrix.
722
723 >>> angle = np.pi / 2.0
724 >>> direct = [0.0, 1.0, 0.0]
725 >>> point = [0.0, 0.0, 0.0]
726 >>> normal = np.cross(direct, np.roll(direct,1))
727 >>> S0 = shear_matrix(angle, direct, point, normal)
728 >>> angle, direct, point, normal = shear_from_matrix(S0)
729 >>> S1 = shear_matrix(angle, direct, point, normal)
730 >>> is_same_transform(S0, S1)
731 True
732
733 """
734 M = np.array(matrix, dtype=np.float64, copy=False)
735 M33 = M[:3, :3]
736 # normal: cross independent eigenvectors corresponding to the eigenvalue 1
737 w, V = np.linalg.eig(M33)
738
739 i = np.where(abs(np.real(w) - 1.0) < 1e-4)[0]
740 if len(i) < 2:
741 raise ValueError("no two linear independent eigenvectors found %s" % w)
742 V = np.real(V[:, i]).squeeze().T
743 lenorm = -1.0
744 for i0, i1 in ((0, 1), (0, 2), (1, 2)):
745 n = np.cross(V[i0], V[i1])
746 w = vector_norm(n)
747 if w > lenorm:
748 lenorm = w
749 normal = n
750 normal /= lenorm
751 # direction and angle
752 direction = np.dot(M33 - np.identity(3), normal)
753 angle = vector_norm(direction)
754 direction /= angle
755 angle = math.atan(angle)
756 # point: eigenvector corresponding to eigenvalue 1
757 w, V = np.linalg.eig(M)
758
759 i = np.where(abs(np.real(w) - 1.0) < 1e-8)[0]
760 if not len(i):
761 raise ValueError("no eigenvector corresponding to eigenvalue 1")
762 point = np.real(V[:, i[-1]]).squeeze()
763 point /= point[3]
764 return angle, direction, point, normal
765
766
767 def decompose_matrix(matrix):
768 """Return sequence of transformations from transformation matrix.
769
770 matrix : array_like
771 Non-degenerative homogeneous transformation matrix
772
773 Return tuple of:
774 scale : vector of 3 scaling factors
775 shear : list of shear factors for x-y, x-z, y-z axes
776 angles : list of Euler angles about static x, y, z axes
777 translate : translation vector along x, y, z axes
778 perspective : perspective partition of matrix
779
780 Raise ValueError if matrix is of wrong type or degenerative.
781
782 >>> T0 = translation_matrix([1, 2, 3])
783 >>> scale, shear, angles, trans, persp = decompose_matrix(T0)
784 >>> T1 = translation_matrix(trans)
785 >>> np.allclose(T0, T1)
786 True
787 >>> S = scale_matrix(0.123)
788 >>> scale, shear, angles, trans, persp = decompose_matrix(S)
789 >>> scale[0]
790 0.123
791 >>> R0 = euler_matrix(1, 2, 3)
792 >>> scale, shear, angles, trans, persp = decompose_matrix(R0)
793 >>> R1 = euler_matrix(*angles)
794 >>> np.allclose(R0, R1)
795 True
796
797 """
798 M = np.array(matrix, dtype=np.float64, copy=True).T
799 if abs(M[3, 3]) < _EPS:
800 raise ValueError("M[3, 3] is zero")
801 M /= M[3, 3]
802 P = M.copy()
803 P[:, 3] = 0.0, 0.0, 0.0, 1.0
804 if not np.linalg.det(P):
805 raise ValueError("matrix is singular")
806
807 scale = np.zeros((3,))
808 shear = [0.0, 0.0, 0.0]
809 angles = [0.0, 0.0, 0.0]
810
811 if any(abs(M[:3, 3]) > _EPS):
812 perspective = np.dot(M[:, 3], np.linalg.inv(P.T))
813 M[:, 3] = 0.0, 0.0, 0.0, 1.0
814 else:
815 perspective = np.array([0.0, 0.0, 0.0, 1.0])
816
817 translate = M[3, :3].copy()
818 M[3, :3] = 0.0
819
820 row = M[:3, :3].copy()
821 scale[0] = vector_norm(row[0])
822 row[0] /= scale[0]
823 shear[0] = np.dot(row[0], row[1])
824 row[1] -= row[0] * shear[0]
825 scale[1] = vector_norm(row[1])
826 row[1] /= scale[1]
827 shear[0] /= scale[1]
828 shear[1] = np.dot(row[0], row[2])
829 row[2] -= row[0] * shear[1]
830 shear[2] = np.dot(row[1], row[2])
831 row[2] -= row[1] * shear[2]
832 scale[2] = vector_norm(row[2])
833 row[2] /= scale[2]
834 shear[1:] /= scale[2]
835
836 if np.dot(row[0], np.cross(row[1], row[2])) < 0:
837 np.negative(scale, scale)
838 np.negative(row, row)
839
840 angles[1] = math.asin(-row[0, 2])
841 if math.cos(angles[1]):
842 angles[0] = math.atan2(row[1, 2], row[2, 2])
843 angles[2] = math.atan2(row[0, 1], row[0, 0])
844 else:
845 angles[0] = math.atan2(-row[2, 1], row[1, 1])
846 angles[2] = 0.0
847
848 return scale, shear, angles, translate, perspective
849
850
851 def compose_matrix(
852 scale=None, shear=None, angles=None, translate=None, perspective=None
853 ):
854 """Return transformation matrix from sequence of transformations.
855
856 This is the inverse of the decompose_matrix function.
857
858 Sequence of transformations:
859 scale : vector of 3 scaling factors
860 shear : list of shear factors for x-y, x-z, y-z axes
861 angles : list of Euler angles about static x, y, z axes
862 translate : translation vector along x, y, z axes
863 perspective : perspective partition of matrix
864
865 >>> scale = np.random.random(3) - 0.5
866 >>> shear = np.random.random(3) - 0.5
867 >>> angles = (np.random.random(3) - 0.5) * (2*math.pi)
868 >>> trans = np.random.random(3) - 0.5
869 >>> persp = np.random.random(4) - 0.5
870 >>> M0 = compose_matrix(scale, shear, angles, trans, persp)
871 >>> result = decompose_matrix(M0)
872 >>> M1 = compose_matrix(*result)
873 >>> is_same_transform(M0, M1)
874 True
875
876 """
877 M = np.identity(4)
878 if perspective is not None:
879 P = np.identity(4)
880 P[3, :] = perspective[:4]
881 M = np.dot(M, P)
882 if translate is not None:
883 T = np.identity(4)
884 T[:3, 3] = translate[:3]
885 M = np.dot(M, T)
886 if angles is not None:
887 R = euler_matrix(angles[0], angles[1], angles[2], "sxyz")
888 M = np.dot(M, R)
889 if shear is not None:
890 Z = np.identity(4)
891 Z[1, 2] = shear[2]
892 Z[0, 2] = shear[1]
893 Z[0, 1] = shear[0]
894 M = np.dot(M, Z)
895 if scale is not None:
896 S = np.identity(4)
897 S[0, 0] = scale[0]
898 S[1, 1] = scale[1]
899 S[2, 2] = scale[2]
900 M = np.dot(M, S)
901 M /= M[3, 3]
902 return M
903
904
905 def orthogonalization_matrix(lengths, angles):
906 """Return orthogonalization matrix for crystallographic cell coordinates.
907
908 Angles are expected in degrees.
909
910 The de-orthogonalization matrix is the inverse.
911
912 >>> O = orthogonalization_matrix([10, 10, 10], [90, 90, 90])
913 >>> np.allclose(O[:3, :3], np.identity(3, float) * 10)
914 True
915 >>> O = orthogonalization_matrix([9.8, 12.0, 15.5], [87.2, 80.7, 69.7])
916 >>> np.allclose(np.sum(O), 43.063229)
917 True
918
919 """
920 a, b, c = lengths
921 angles = np.radians(angles)
922 sina, sinb, _ = np.sin(angles)
923 cosa, cosb, cosg = np.cos(angles)
924 co = (cosa * cosb - cosg) / (sina * sinb)
925 return np.array(
926 [
927 [a * sinb * math.sqrt(1.0 - co * co), 0.0, 0.0, 0.0],
928 [-a * sinb * co, b * sina, 0.0, 0.0],
929 [a * cosb, b * cosa, c, 0.0],
930 [0.0, 0.0, 0.0, 1.0],
931 ]
932 )
933
934
935 def affine_matrix_from_points(v0, v1, shear=True, scale=True, usesvd=True):
936 """Return affine transform matrix to register two point sets.
937
938 v0 and v1 are shape (ndims, *) arrays of at least ndims non-homogeneous
939 coordinates, where ndims is the dimensionality of the coordinate space.
940
941 If shear is False, a similarity transformation matrix is returned.
942 If also scale is False, a rigid/Euclidean transformation matrix
943 is returned.
944
945 By default the algorithm by Hartley and Zissermann [15] is used.
946 If usesvd is True, similarity and Euclidean transformation matrices
947 are calculated by minimizing the weighted sum of squared deviations
948 (RMSD) according to the algorithm by Kabsch [8].
949 Otherwise, and if ndims is 3, the quaternion based algorithm by Horn [9]
950 is used, which is slower when using this Python implementation.
951
952 The returned matrix performs rotation, translation and uniform scaling
953 (if specified).
954
955 >>> v0 = [[0, 1031, 1031, 0], [0, 0, 1600, 1600]]
956 >>> v1 = [[675, 826, 826, 677], [55, 52, 281, 277]]
957 >>> mat = affine_matrix_from_points(v0, v1)
958 >>> T = translation_matrix(np.random.random(3)-0.5)
959 >>> R = random_rotation_matrix(np.random.random(3))
960 >>> S = scale_matrix(random.random())
961 >>> M = concatenate_matrices(T, R, S)
962 >>> v0 = (np.random.rand(4, 100) - 0.5) * 20
963 >>> v0[3] = 1
964 >>> v1 = np.dot(M, v0)
965 >>> v0[:3] += np.random.normal(0, 1e-8, 300).reshape(3, -1)
966 >>> M = affine_matrix_from_points(v0[:3], v1[:3])
967 >>> check = np.allclose(v1, np.dot(M, v0))
968
969 More examples in superimposition_matrix()
970
971 """
972 v0 = np.array(v0, dtype=np.float64, copy=True)
973 v1 = np.array(v1, dtype=np.float64, copy=True)
974
975 ndims = v0.shape[0]
976 if ndims < 2 or v0.shape[1] < ndims or v0.shape != v1.shape:
977 raise ValueError("input arrays are of wrong shape or type")
978
979 # move centroids to origin
980 t0 = -np.mean(v0, axis=1)
981 M0 = np.identity(ndims + 1)
982 M0[:ndims, ndims] = t0
983 v0 += t0.reshape(ndims, 1)
984 t1 = -np.mean(v1, axis=1)
985 M1 = np.identity(ndims + 1)
986 M1[:ndims, ndims] = t1
987 v1 += t1.reshape(ndims, 1)
988
989 if shear:
990 # Affine transformation
991 A = np.concatenate((v0, v1), axis=0)
992 u, s, vh = np.linalg.svd(A.T)
993 vh = vh[:ndims].T
994 B = vh[:ndims]
995 C = vh[ndims : 2 * ndims]
996 t = np.dot(C, np.linalg.pinv(B))
997 t = np.concatenate((t, np.zeros((ndims, 1))), axis=1)
998 M = np.vstack((t, ((0.0,) * ndims) + (1.0,)))
999 elif usesvd or ndims != 3:
1000 # Rigid transformation via SVD of covariance matrix
1001 u, s, vh = np.linalg.svd(np.dot(v1, v0.T))
1002 # rotation matrix from SVD orthonormal bases
1003 R = np.dot(u, vh)
1004 if np.linalg.det(R) < 0.0:
1005 # R does not constitute right handed system
1006 R -= np.outer(u[:, ndims - 1], vh[ndims - 1, :] * 2.0)
1007 s[-1] *= -1.0
1008 # homogeneous transformation matrix
1009 M = np.identity(ndims + 1)
1010 M[:ndims, :ndims] = R
1011 else:
1012 # Rigid transformation matrix via quaternion
1013 # compute symmetric matrix N
1014 xx, yy, zz = np.sum(v0 * v1, axis=1)
1015 xy, yz, zx = np.sum(v0 * np.roll(v1, -1, axis=0), axis=1)
1016 xz, yx, zy = np.sum(v0 * np.roll(v1, -2, axis=0), axis=1)
1017 N = [
1018 [xx + yy + zz, 0.0, 0.0, 0.0],
1019 [yz - zy, xx - yy - zz, 0.0, 0.0],
1020 [zx - xz, xy + yx, yy - xx - zz, 0.0],
1021 [xy - yx, zx + xz, yz + zy, zz - xx - yy],
1022 ]
1023 # quaternion: eigenvector corresponding to most positive eigenvalue
1024 w, V = np.linalg.eigh(N)
1025 q = V[:, np.argmax(w)]
1026 q /= vector_norm(q) # unit quaternion
1027 # homogeneous transformation matrix
1028 M = quaternion_matrix(q)
1029
1030 if scale and not shear:
1031 # Affine transformation; scale is ratio of RMS deviations from centroid
1032 v0 *= v0
1033 v1 *= v1
1034 M[:ndims, :ndims] *= math.sqrt(np.sum(v1) / np.sum(v0))
1035
1036 # move centroids back
1037 M = np.dot(np.linalg.inv(M1), np.dot(M, M0))
1038 M /= M[ndims, ndims]
1039 return M
1040
1041
1042 def superimposition_matrix(v0, v1, scale=False, usesvd=True):
1043 """Return matrix to transform given 3D point set into second point set.
1044
1045 v0 and v1 are shape (3, *) or (4, *) arrays of at least 3 points.
1046
1047 The parameters scale and usesvd are explained in the more general
1048 affine_matrix_from_points function.
1049
1050 The returned matrix is a similarity or Euclidean transformation matrix.
1051 This function has a fast C implementation in transformations.c.
1052
1053 >>> v0 = np.random.rand(3, 10)
1054 >>> M = superimposition_matrix(v0, v0)
1055 >>> np.allclose(M, np.identity(4))
1056 True
1057 >>> R = random_rotation_matrix(np.random.random(3))
1058 >>> v0 = [[1,0,0], [0,1,0], [0,0,1], [1,1,1]]
1059 >>> v1 = np.dot(R, v0)
1060 >>> M = superimposition_matrix(v0, v1)
1061 >>> np.allclose(v1, np.dot(M, v0))
1062 True
1063 >>> v0 = (np.random.rand(4, 100) - 0.5) * 20
1064 >>> v0[3] = 1
1065 >>> v1 = np.dot(R, v0)
1066 >>> M = superimposition_matrix(v0, v1)
1067 >>> np.allclose(v1, np.dot(M, v0))
1068 True
1069 >>> S = scale_matrix(random.random())
1070 >>> T = translation_matrix(np.random.random(3)-0.5)
1071 >>> M = concatenate_matrices(T, R, S)
1072 >>> v1 = np.dot(M, v0)
1073 >>> v0[:3] += np.random.normal(0, 1e-9, 300).reshape(3, -1)
1074 >>> M = superimposition_matrix(v0, v1, scale=True)
1075 >>> np.allclose(v1, np.dot(M, v0))
1076 True
1077 >>> M = superimposition_matrix(v0, v1, scale=True, usesvd=False)
1078 >>> np.allclose(v1, np.dot(M, v0))
1079 True
1080 >>> v = np.empty((4, 100, 3))
1081 >>> v[:, :, 0] = v0
1082 >>> M = superimposition_matrix(v0, v1, scale=True, usesvd=False)
1083 >>> np.allclose(v1, np.dot(M, v[:, :, 0]))
1084 True
1085
1086 """
1087 v0 = np.array(v0, dtype=np.float64, copy=False)[:3]
1088 v1 = np.array(v1, dtype=np.float64, copy=False)[:3]
1089 return affine_matrix_from_points(v0, v1, shear=False, scale=scale, usesvd=usesvd)
1090
1091
1092 def euler_matrix(ai, aj, ak, axes="sxyz"):
1093 """Return homogeneous rotation matrix from Euler angles and axis sequence.
1094
1095 ai, aj, ak : Euler's roll, pitch and yaw angles
1096 axes : One of 24 axis sequences as string or encoded tuple
1097
1098 >>> R = euler_matrix(1, 2, 3, 'syxz')
1099 >>> np.allclose(np.sum(R[0]), -1.34786452)
1100 True
1101 >>> R = euler_matrix(1, 2, 3, (0, 1, 0, 1))
1102 >>> np.allclose(np.sum(R[0]), -0.383436184)
1103 True
1104 >>> ai, aj, ak = (4*math.pi) * (np.random.random(3) - 0.5)
1105 >>> for axes in _AXES2TUPLE.keys():
1106 ... R = euler_matrix(ai, aj, ak, axes)
1107 >>> for axes in _TUPLE2AXES.keys():
1108 ... R = euler_matrix(ai, aj, ak, axes)
1109
1110 """
1111 try:
1112 firstaxis, parity, repetition, frame = _AXES2TUPLE[axes]
1113 except (AttributeError, KeyError):
1114 _TUPLE2AXES[axes] # validation
1115 firstaxis, parity, repetition, frame = axes
1116
1117 i = firstaxis
1118 j = _NEXT_AXIS[i + parity]
1119 k = _NEXT_AXIS[i - parity + 1]
1120
1121 if frame:
1122 ai, ak = ak, ai
1123 if parity:
1124 ai, aj, ak = -ai, -aj, -ak
1125
1126 si, sj, sk = math.sin(ai), math.sin(aj), math.sin(ak)
1127 ci, cj, ck = math.cos(ai), math.cos(aj), math.cos(ak)
1128 cc, cs = ci * ck, ci * sk
1129 sc, ss = si * ck, si * sk
1130
1131 M = np.identity(4)
1132 if repetition:
1133 M[i, i] = cj
1134 M[i, j] = sj * si
1135 M[i, k] = sj * ci
1136 M[j, i] = sj * sk
1137 M[j, j] = -cj * ss + cc
1138 M[j, k] = -cj * cs - sc
1139 M[k, i] = -sj * ck
1140 M[k, j] = cj * sc + cs
1141 M[k, k] = cj * cc - ss
1142 else:
1143 M[i, i] = cj * ck
1144 M[i, j] = sj * sc - cs
1145 M[i, k] = sj * cc + ss
1146 M[j, i] = cj * sk
1147 M[j, j] = sj * ss + cc
1148 M[j, k] = sj * cs - sc
1149 M[k, i] = -sj
1150 M[k, j] = cj * si
1151 M[k, k] = cj * ci
1152 return M
1153
1154
1155 def euler_from_matrix(matrix, axes="sxyz"):
1156 """Return Euler angles from rotation matrix for specified axis sequence.
1157
1158 axes : One of 24 axis sequences as string or encoded tuple
1159
1160 Note that many Euler angle triplets can describe one matrix.
1161
1162 >>> R0 = euler_matrix(1, 2, 3, 'syxz')
1163 >>> al, be, ga = euler_from_matrix(R0, 'syxz')
1164 >>> R1 = euler_matrix(al, be, ga, 'syxz')
1165 >>> np.allclose(R0, R1)
1166 True
1167 >>> angles = (4*math.pi) * (np.random.random(3) - 0.5)
1168 >>> for axes in _AXES2TUPLE.keys():
1169 ... R0 = euler_matrix(axes=axes, *angles)
1170 ... R1 = euler_matrix(axes=axes, *euler_from_matrix(R0, axes))
1171 ... if not np.allclose(R0, R1): print(axes, "failed")
1172
1173 """
1174 try:
1175 firstaxis, parity, repetition, frame = _AXES2TUPLE[axes.lower()]
1176 except (AttributeError, KeyError):
1177 _TUPLE2AXES[axes] # validation
1178 firstaxis, parity, repetition, frame = axes
1179
1180 i = firstaxis
1181 j = _NEXT_AXIS[i + parity]
1182 k = _NEXT_AXIS[i - parity + 1]
1183
1184 M = np.array(matrix, dtype=np.float64, copy=False)[:3, :3]
1185 if repetition:
1186 sy = math.sqrt(M[i, j] * M[i, j] + M[i, k] * M[i, k])
1187 if sy > _EPS:
1188 ax = math.atan2(M[i, j], M[i, k])
1189 ay = math.atan2(sy, M[i, i])
1190 az = math.atan2(M[j, i], -M[k, i])
1191 else:
1192 ax = math.atan2(-M[j, k], M[j, j])
1193 ay = math.atan2(sy, M[i, i])
1194 az = 0.0
1195 else:
1196 cy = math.sqrt(M[i, i] * M[i, i] + M[j, i] * M[j, i])
1197 if cy > _EPS:
1198 ax = math.atan2(M[k, j], M[k, k])
1199 ay = math.atan2(-M[k, i], cy)
1200 az = math.atan2(M[j, i], M[i, i])
1201 else:
1202 ax = math.atan2(-M[j, k], M[j, j])
1203 ay = math.atan2(-M[k, i], cy)
1204 az = 0.0
1205
1206 if parity:
1207 ax, ay, az = -ax, -ay, -az
1208 if frame:
1209 ax, az = az, ax
1210 return ax, ay, az
1211
1212
1213 def euler_from_quaternion(quaternion, axes="sxyz"):
1214 """Return Euler angles from quaternion for specified axis sequence.
1215
1216 >>> angles = euler_from_quaternion([0.99810947, 0.06146124, 0, 0])
1217 >>> np.allclose(angles, [0.123, 0, 0])
1218 True
1219
1220 """
1221 return euler_from_matrix(quaternion_matrix(quaternion), axes)
1222
1223
1224 def quaternion_from_euler(ai, aj, ak, axes="sxyz"):
1225 """Return quaternion from Euler angles and axis sequence.
1226
1227 ai, aj, ak : Euler's roll, pitch and yaw angles
1228 axes : One of 24 axis sequences as string or encoded tuple
1229
1230 >>> q = quaternion_from_euler(1, 2, 3, 'ryxz')
1231 >>> np.allclose(q, [0.435953, 0.310622, -0.718287, 0.444435])
1232 True
1233
1234 """
1235 try:
1236 firstaxis, parity, repetition, frame = _AXES2TUPLE[axes.lower()]
1237 except (AttributeError, KeyError):
1238 _TUPLE2AXES[axes] # validation
1239 firstaxis, parity, repetition, frame = axes
1240
1241 i = firstaxis + 1
1242 j = _NEXT_AXIS[i + parity - 1] + 1
1243 k = _NEXT_AXIS[i - parity] + 1
1244
1245 if frame:
1246 ai, ak = ak, ai
1247 if parity:
1248 aj = -aj
1249
1250 ai /= 2.0
1251 aj /= 2.0
1252 ak /= 2.0
1253 ci = math.cos(ai)
1254 si = math.sin(ai)
1255 cj = math.cos(aj)
1256 sj = math.sin(aj)
1257 ck = math.cos(ak)
1258 sk = math.sin(ak)
1259 cc = ci * ck
1260 cs = ci * sk
1261 sc = si * ck
1262 ss = si * sk
1263
1264 q = np.empty((4,))
1265 if repetition:
1266 q[0] = cj * (cc - ss)
1267 q[i] = cj * (cs + sc)
1268 q[j] = sj * (cc + ss)
1269 q[k] = sj * (cs - sc)
1270 else:
1271 q[0] = cj * cc + sj * ss
1272 q[i] = cj * sc - sj * cs
1273 q[j] = cj * ss + sj * cc
1274 q[k] = cj * cs - sj * sc
1275 if parity:
1276 q[j] *= -1.0
1277
1278 return q
1279
1280
1281 def quaternion_about_axis(angle, axis):
1282 """Return quaternion for rotation about axis.
1283
1284 >>> q = quaternion_about_axis(0.123, [1, 0, 0])
1285 >>> np.allclose(q, [0.99810947, 0.06146124, 0, 0])
1286 True
1287
1288 """
1289 q = np.array([0.0, axis[0], axis[1], axis[2]])
1290 qlen = vector_norm(q)
1291 if qlen > _EPS:
1292 q *= math.sin(angle / 2.0) / qlen
1293 q[0] = math.cos(angle / 2.0)
1294 return q
1295
1296
1297 def quaternion_matrix(quaternion):
1298 """Return homogeneous rotation matrix from quaternion.
1299
1300 >>> M = quaternion_matrix([0.99810947, 0.06146124, 0, 0])
1301 >>> np.allclose(M, rotation_matrix(0.123, [1, 0, 0]))
1302 True
1303 >>> M = quaternion_matrix([1, 0, 0, 0])
1304 >>> np.allclose(M, np.identity(4))
1305 True
1306 >>> M = quaternion_matrix([0, 1, 0, 0])
1307 >>> np.allclose(M, np.diag([1, -1, -1, 1]))
1308 True
1309
1310 """
1311 q = np.array(quaternion, dtype=np.float64, copy=True)
1312 n = np.dot(q, q)
1313 if n < _EPS:
1314 return np.identity(4)
1315 q *= math.sqrt(2.0 / n)
1316 q = np.outer(q, q)
1317 return np.array(
1318 [
1319 [1.0 - q[2, 2] - q[3, 3], q[1, 2] - q[3, 0], q[1, 3] + q[2, 0], 0.0],
1320 [q[1, 2] + q[3, 0], 1.0 - q[1, 1] - q[3, 3], q[2, 3] - q[1, 0], 0.0],
1321 [q[1, 3] - q[2, 0], q[2, 3] + q[1, 0], 1.0 - q[1, 1] - q[2, 2], 0.0],
1322 [0.0, 0.0, 0.0, 1.0],
1323 ]
1324 )
1325
1326
1327 def quaternion_from_matrix(matrix, isprecise=False):
1328 """Return quaternion from rotation matrix.
1329
1330 If isprecise is True, the input matrix is assumed to be a precise rotation
1331 matrix and a faster algorithm is used.
1332
1333 >>> q = quaternion_from_matrix(np.identity(4), True)
1334 >>> np.allclose(q, [1, 0, 0, 0])
1335 True
1336 >>> q = quaternion_from_matrix(np.diag([1, -1, -1, 1]))
1337 >>> np.allclose(q, [0, 1, 0, 0]) or np.allclose(q, [0, -1, 0, 0])
1338 True
1339 >>> R = rotation_matrix(0.123, (1, 2, 3))
1340 >>> q = quaternion_from_matrix(R, True)
1341 >>> np.allclose(q, [0.9981095, 0.0164262, 0.0328524, 0.0492786])
1342 True
1343 >>> R = [[-0.545, 0.797, 0.260, 0], [0.733, 0.603, -0.313, 0],
1344 ... [-0.407, 0.021, -0.913, 0], [0, 0, 0, 1]]
1345 >>> q = quaternion_from_matrix(R)
1346 >>> np.allclose(q, [0.19069, 0.43736, 0.87485, -0.083611])
1347 True
1348 >>> R = [[0.395, 0.362, 0.843, 0], [-0.626, 0.796, -0.056, 0],
1349 ... [-0.677, -0.498, 0.529, 0], [0, 0, 0, 1]]
1350 >>> q = quaternion_from_matrix(R)
1351 >>> np.allclose(q, [0.82336615, -0.13610694, 0.46344705, -0.29792603])
1352 True
1353 >>> R = random_rotation_matrix()
1354 >>> q = quaternion_from_matrix(R)
1355 >>> is_same_transform(R, quaternion_matrix(q))
1356 True
1357 >>> is_same_quaternion(quaternion_from_matrix(R, isprecise=False),
1358 ... quaternion_from_matrix(R, isprecise=True))
1359 True
1360 >>> R = euler_matrix(0.0, 0.0, np.pi/2.0)
1361 >>> is_same_quaternion(quaternion_from_matrix(R, isprecise=False),
1362 ... quaternion_from_matrix(R, isprecise=True))
1363 True
1364
1365 """
1366 M = np.array(matrix, dtype=np.float64, copy=False)[:4, :4]
1367 if isprecise:
1368 q = np.empty((4,))
1369 t = np.trace(M)
1370 if t > M[3, 3]:
1371 q[0] = t
1372 q[3] = M[1, 0] - M[0, 1]
1373 q[2] = M[0, 2] - M[2, 0]
1374 q[1] = M[2, 1] - M[1, 2]
1375 else:
1376 i, j, k = 0, 1, 2
1377 if M[1, 1] > M[0, 0]:
1378 i, j, k = 1, 2, 0
1379 if M[2, 2] > M[i, i]:
1380 i, j, k = 2, 0, 1
1381 t = M[i, i] - (M[j, j] + M[k, k]) + M[3, 3]
1382 q[i] = t
1383 q[j] = M[i, j] + M[j, i]
1384 q[k] = M[k, i] + M[i, k]
1385 q[3] = M[k, j] - M[j, k]
1386 q = q[[3, 0, 1, 2]]
1387 q *= 0.5 / math.sqrt(t * M[3, 3])
1388 else:
1389 m00 = M[0, 0]
1390 m01 = M[0, 1]
1391 m02 = M[0, 2]
1392 m10 = M[1, 0]
1393 m11 = M[1, 1]
1394 m12 = M[1, 2]
1395 m20 = M[2, 0]
1396 m21 = M[2, 1]
1397 m22 = M[2, 2]
1398 # symmetric matrix K
1399 K = np.array(
1400 [
1401 [m00 - m11 - m22, 0.0, 0.0, 0.0],
1402 [m01 + m10, m11 - m00 - m22, 0.0, 0.0],
1403 [m02 + m20, m12 + m21, m22 - m00 - m11, 0.0],
1404 [m21 - m12, m02 - m20, m10 - m01, m00 + m11 + m22],
1405 ]
1406 )
1407 K /= 3.0
1408 # quaternion is eigenvector of K that corresponds to largest eigenvalue
1409 w, V = np.linalg.eigh(K)
1410 q = V[[3, 0, 1, 2], np.argmax(w)]
1411 if q[0] < 0.0:
1412 np.negative(q, q)
1413 return q
1414
1415
1416 def quaternion_multiply(quaternion1, quaternion0):
1417 """Return multiplication of two quaternions.
1418
1419 >>> q = quaternion_multiply([4, 1, -2, 3], [8, -5, 6, 7])
1420 >>> np.allclose(q, [28, -44, -14, 48])
1421 True
1422
1423 """
1424 w0, x0, y0, z0 = quaternion0
1425 w1, x1, y1, z1 = quaternion1
1426 return np.array(
1427 [
1428 -x1 * x0 - y1 * y0 - z1 * z0 + w1 * w0,
1429 x1 * w0 + y1 * z0 - z1 * y0 + w1 * x0,
1430 -x1 * z0 + y1 * w0 + z1 * x0 + w1 * y0,
1431 x1 * y0 - y1 * x0 + z1 * w0 + w1 * z0,
1432 ],
1433 dtype=np.float64,
1434 )
1435
1436
1437 def quaternion_conjugate(quaternion):
1438 """Return conjugate of quaternion.
1439
1440 >>> q0 = random_quaternion()
1441 >>> q1 = quaternion_conjugate(q0)
1442 >>> q1[0] == q0[0] and all(q1[1:] == -q0[1:])
1443 True
1444
1445 """
1446 q = np.array(quaternion, dtype=np.float64, copy=True)
1447 np.negative(q[1:], q[1:])
1448 return q
1449
1450
1451 def quaternion_inverse(quaternion):
1452 """Return inverse of quaternion.
1453
1454 >>> q0 = random_quaternion()
1455 >>> q1 = quaternion_inverse(q0)
1456 >>> np.allclose(quaternion_multiply(q0, q1), [1, 0, 0, 0])
1457 True
1458
1459 """
1460 q = np.array(quaternion, dtype=np.float64, copy=True)
1461 np.negative(q[1:], q[1:])
1462 return q / np.dot(q, q)
1463
1464
1465 def quaternion_real(quaternion):
1466 """Return real part of quaternion.
1467
1468 >>> quaternion_real([3, 0, 1, 2])
1469 3.0
1470
1471 """
1472 return float(quaternion[0])
1473
1474
1475 def quaternion_imag(quaternion):
1476 """Return imaginary part of quaternion.
1477
1478 >>> quaternion_imag([3, 0, 1, 2])
1479 array([0., 1., 2.])
1480
1481 """
1482 return np.array(quaternion[1:4], dtype=np.float64, copy=True)
1483
1484
1485 def quaternion_slerp(quat0, quat1, fraction, spin=0, shortestpath=True):
1486 """Return spherical linear interpolation between two quaternions.
1487
1488 >>> q0 = random_quaternion()
1489 >>> q1 = random_quaternion()
1490 >>> q = quaternion_slerp(q0, q1, 0)
1491 >>> np.allclose(q, q0)
1492 True
1493 >>> q = quaternion_slerp(q0, q1, 1, 1)
1494 >>> np.allclose(q, q1)
1495 True
1496 >>> q = quaternion_slerp(q0, q1, 0.5)
1497 >>> angle = math.acos(np.dot(q0, q))
1498 >>> np.allclose(2, math.acos(np.dot(q0, q1)) / angle) or \
1499 np.allclose(2, math.acos(-np.dot(q0, q1)) / angle)
1500 True
1501
1502 """
1503 q0 = unit_vector(quat0[:4])
1504 q1 = unit_vector(quat1[:4])
1505 if fraction == 0.0:
1506 return q0
1507 elif fraction == 1.0:
1508 return q1
1509 d = np.dot(q0, q1)
1510 if abs(abs(d) - 1.0) < _EPS:
1511 return q0
1512 if shortestpath and d < 0.0:
1513 # invert rotation
1514 d = -d
1515 np.negative(q1, q1)
1516 angle = math.acos(d) + spin * math.pi
1517 if abs(angle) < _EPS:
1518 return q0
1519 isin = 1.0 / math.sin(angle)
1520 q0 *= math.sin((1.0 - fraction) * angle) * isin
1521 q1 *= math.sin(fraction * angle) * isin
1522 q0 += q1
1523 return q0
1524
1525
1526 def random_quaternion(rand=None):
1527 """Return uniform random unit quaternion.
1528
1529 rand: array like or None
1530 Three independent random variables that are uniformly distributed
1531 between 0 and 1.
1532
1533 >>> q = random_quaternion()
1534 >>> np.allclose(1, vector_norm(q))
1535 True
1536 >>> q = random_quaternion(np.random.random(3))
1537 >>> len(q.shape), q.shape[0]==4
1538 (1, True)
1539
1540 """
1541 if rand is None:
1542 rand = np.random.rand(3)
1543 else:
1544 assert len(rand) == 3
1545 r1 = np.sqrt(1.0 - rand[0])
1546 r2 = np.sqrt(rand[0])
1547 pi2 = math.pi * 2.0
1548 t1 = pi2 * rand[1]
1549 t2 = pi2 * rand[2]
1550 return np.array(
1551 [np.cos(t2) * r2, np.sin(t1) * r1, np.cos(t1) * r1, np.sin(t2) * r2]
1552 )
1553
1554
1555 def random_rotation_matrix(rand=None):
1556 """Return uniform random rotation matrix.
1557
1558 rand: array like
1559 Three independent random variables that are uniformly distributed
1560 between 0 and 1 for each returned quaternion.
1561
1562 >>> R = random_rotation_matrix()
1563 >>> np.allclose(np.dot(R.T, R), np.identity(4))
1564 True
1565
1566 """
1567 return quaternion_matrix(random_quaternion(rand))
1568
1569
1570 class Arcball(object):
1571 """Virtual Trackball Control.
1572
1573 >>> ball = Arcball()
1574 >>> ball = Arcball(initial=np.identity(4))
1575 >>> ball.place([320, 320], 320)
1576 >>> ball.down([500, 250])
1577 >>> ball.drag([475, 275])
1578 >>> R = ball.matrix()
1579 >>> np.allclose(np.sum(R), 3.90583455)
1580 True
1581 >>> ball = Arcball(initial=[1, 0, 0, 0])
1582 >>> ball.place([320, 320], 320)
1583 >>> ball.setaxes([1, 1, 0], [-1, 1, 0])
1584 >>> ball.constrain = True
1585 >>> ball.down([400, 200])
1586 >>> ball.drag([200, 400])
1587 >>> R = ball.matrix()
1588 >>> np.allclose(np.sum(R), 0.2055924)
1589 True
1590 >>> ball.next()
1591
1592 """
1593
1594 def __init__(self, initial=None):
1595 """Initialize virtual trackball control.
1596
1597 initial : quaternion or rotation matrix
1598
1599 """
1600 self._axis = None
1601 self._axes = None
1602 self._radius = 1.0
1603 self._center = [0.0, 0.0]
1604 self._vdown = np.array([0.0, 0.0, 1.0])
1605 self._constrain = False
1606 if initial is None:
1607 self._qdown = np.array([1.0, 0.0, 0.0, 0.0])
1608 else:
1609 initial = np.array(initial, dtype=np.float64)
1610 if initial.shape == (4, 4):
1611 self._qdown = quaternion_from_matrix(initial)
1612 elif initial.shape == (4,):
1613 initial /= vector_norm(initial)
1614 self._qdown = initial
1615 else:
1616 raise ValueError("initial not a quaternion or matrix")
1617 self._qnow = self._qpre = self._qdown
1618
1619 def place(self, center, radius):
1620 """Place Arcball, e.g. when window size changes.
1621
1622 center : sequence[2]
1623 Window coordinates of trackball center.
1624 radius : float
1625 Radius of trackball in window coordinates.
1626
1627 """
1628 self._radius = float(radius)
1629 self._center[0] = center[0]
1630 self._center[1] = center[1]
1631
1632 def setaxes(self, *axes):
1633 """Set axes to constrain rotations."""
1634 if axes is None:
1635 self._axes = None
1636 else:
1637 self._axes = [unit_vector(axis) for axis in axes]
1638
1639 @property
1640 def constrain(self):
1641 """Return state of constrain to axis mode."""
1642 return self._constrain
1643
1644 @constrain.setter
1645 def constrain(self, value):
1646 """Set state of constrain to axis mode."""
1647 self._constrain = bool(value)
1648
1649 def down(self, point):
1650 """Set initial cursor window coordinates and pick constrain-axis."""
1651 self._vdown = arcball_map_to_sphere(point, self._center, self._radius)
1652 self._qdown = self._qpre = self._qnow
1653 if self._constrain and self._axes is not None:
1654 self._axis = arcball_nearest_axis(self._vdown, self._axes)
1655 self._vdown = arcball_constrain_to_axis(self._vdown, self._axis)
1656 else:
1657 self._axis = None
1658
1659 def drag(self, point):
1660 """Update current cursor window coordinates."""
1661 vnow = arcball_map_to_sphere(point, self._center, self._radius)
1662 if self._axis is not None:
1663 vnow = arcball_constrain_to_axis(vnow, self._axis)
1664 self._qpre = self._qnow
1665 t = np.cross(self._vdown, vnow)
1666 if np.dot(t, t) < _EPS:
1667 self._qnow = self._qdown
1668 else:
1669 q = [np.dot(self._vdown, vnow), t[0], t[1], t[2]]
1670 self._qnow = quaternion_multiply(q, self._qdown)
1671
1672 def next(self, acceleration=0.0):
1673 """Continue rotation in direction of last drag."""
1674 q = quaternion_slerp(self._qpre, self._qnow, 2.0 + acceleration, False)
1675 self._qpre, self._qnow = self._qnow, q
1676
1677 def matrix(self):
1678 """Return homogeneous rotation matrix."""
1679 return quaternion_matrix(self._qnow)
1680
1681
1682 def arcball_map_to_sphere(point, center, radius):
1683 """Return unit sphere coordinates from window coordinates."""
1684 v0 = (point[0] - center[0]) / radius
1685 v1 = (center[1] - point[1]) / radius
1686 n = v0 * v0 + v1 * v1
1687 if n > 1.0:
1688 # position outside of sphere
1689 n = math.sqrt(n)
1690 return np.array([v0 / n, v1 / n, 0.0])
1691 else:
1692 return np.array([v0, v1, math.sqrt(1.0 - n)])
1693
1694
1695 def arcball_constrain_to_axis(point, axis):
1696 """Return sphere point perpendicular to axis."""
1697 v = np.array(point, dtype=np.float64, copy=True)
1698 a = np.array(axis, dtype=np.float64, copy=True)
1699 v -= a * np.dot(a, v) # on plane
1700 n = vector_norm(v)
1701 if n > _EPS:
1702 if v[2] < 0.0:
1703 np.negative(v, v)
1704 v /= n
1705 return v
1706 if a[2] == 1.0:
1707 return np.array([1.0, 0.0, 0.0])
1708 return unit_vector([-a[1], a[0], 0.0])
1709
1710
1711 def arcball_nearest_axis(point, axes):
1712 """Return axis, which arc is nearest to point."""
1713 point = np.array(point, dtype=np.float64, copy=False)
1714 nearest = None
1715 mx = -1.0
1716 for axis in axes:
1717 t = np.dot(arcball_constrain_to_axis(point, axis), point)
1718 if t > mx:
1719 nearest = axis
1720 mx = t
1721 return nearest
1722
1723
1724 # epsilon for testing whether a number is close to zero
1725 _EPS = np.finfo(float).eps * 4.0
1726
1727 # axis sequences for Euler angles
1728 _NEXT_AXIS = [1, 2, 0, 1]
1729
1730 # map axes strings to/from tuples of inner axis, parity, repetition, frame
1731 _AXES2TUPLE = {
1732 "sxyz": (0, 0, 0, 0),
1733 "sxyx": (0, 0, 1, 0),
1734 "sxzy": (0, 1, 0, 0),
1735 "sxzx": (0, 1, 1, 0),
1736 "syzx": (1, 0, 0, 0),
1737 "syzy": (1, 0, 1, 0),
1738 "syxz": (1, 1, 0, 0),
1739 "syxy": (1, 1, 1, 0),
1740 "szxy": (2, 0, 0, 0),
1741 "szxz": (2, 0, 1, 0),
1742 "szyx": (2, 1, 0, 0),
1743 "szyz": (2, 1, 1, 0),
1744 "rzyx": (0, 0, 0, 1),
1745 "rxyx": (0, 0, 1, 1),
1746 "ryzx": (0, 1, 0, 1),
1747 "rxzx": (0, 1, 1, 1),
1748 "rxzy": (1, 0, 0, 1),
1749 "ryzy": (1, 0, 1, 1),
1750 "rzxy": (1, 1, 0, 1),
1751 "ryxy": (1, 1, 1, 1),
1752 "ryxz": (2, 0, 0, 1),
1753 "rzxz": (2, 0, 1, 1),
1754 "rxyz": (2, 1, 0, 1),
1755 "rzyz": (2, 1, 1, 1),
1756 }
1757
1758 _TUPLE2AXES = dict((v, k) for k, v in _AXES2TUPLE.items())
1759
1760
1761 def vector_norm(data, axis=None, out=None):
1762 """Return length, i.e. Euclidean norm, of ndarray along axis.
1763
1764 >>> v = np.random.random(3)
1765 >>> n = vector_norm(v)
1766 >>> np.allclose(n, np.linalg.norm(v))
1767 True
1768 >>> v = np.random.rand(6, 5, 3)
1769 >>> n = vector_norm(v, axis=-1)
1770 >>> np.allclose(n, np.sqrt(np.sum(v*v, axis=2)))
1771 True
1772 >>> n = vector_norm(v, axis=1)
1773 >>> np.allclose(n, np.sqrt(np.sum(v*v, axis=1)))
1774 True
1775 >>> v = np.random.rand(5, 4, 3)
1776 >>> n = np.empty((5, 3))
1777 >>> vector_norm(v, axis=1, out=n)
1778 >>> np.allclose(n, np.sqrt(np.sum(v*v, axis=1)))
1779 True
1780 >>> vector_norm([])
1781 0.0
1782 >>> vector_norm([1])
1783 1.0
1784
1785 """
1786 data = np.array(data, dtype=np.float64, copy=True)
1787 if out is None:
1788 if data.ndim == 1:
1789 return math.sqrt(np.dot(data, data))
1790 data *= data
1791 out = np.atleast_1d(np.sum(data, axis=axis))
1792 np.sqrt(out, out)
1793 return out
1794 else:
1795 data *= data
1796 np.sum(data, axis=axis, out=out)
1797 np.sqrt(out, out)
1798
1799
1800 def unit_vector(data, axis=None, out=None):
1801 """Return ndarray normalized by length, i.e. Euclidean norm, along axis.
1802
1803 >>> v0 = np.random.random(3)
1804 >>> v1 = unit_vector(v0)
1805 >>> np.allclose(v1, v0 / np.linalg.norm(v0))
1806 True
1807 >>> v0 = np.random.rand(5, 4, 3)
1808 >>> v1 = unit_vector(v0, axis=-1)
1809 >>> v2 = v0 / np.expand_dims(np.sqrt(np.sum(v0*v0, axis=2)), 2)
1810 >>> np.allclose(v1, v2)
1811 True
1812 >>> v1 = unit_vector(v0, axis=1)
1813 >>> v2 = v0 / np.expand_dims(np.sqrt(np.sum(v0*v0, axis=1)), 1)
1814 >>> np.allclose(v1, v2)
1815 True
1816 >>> v1 = np.empty((5, 4, 3))
1817 >>> unit_vector(v0, axis=1, out=v1)
1818 >>> np.allclose(v1, v2)
1819 True
1820 >>> list(unit_vector([]))
1821 []
1822 >>> list(unit_vector([1]))
1823 [1.0]
1824
1825 """
1826 if out is None:
1827 data = np.array(data, dtype=np.float64, copy=True)
1828 if data.ndim == 1:
1829 data /= math.sqrt(np.dot(data, data))
1830 return data
1831 else:
1832 if out is not data:
1833 out[:] = np.array(data, copy=False)
1834 data = out
1835 length = np.atleast_1d(np.sum(data * data, axis))
1836 np.sqrt(length, length)
1837 if axis is not None:
1838 length = np.expand_dims(length, axis)
1839 data /= length
1840 if out is None:
1841 return data
1842
1843
1844 def random_vector(size):
1845 """Return array of random doubles in the half-open interval [0.0, 1.0).
1846
1847 >>> v = random_vector(10000)
1848 >>> np.all(v >= 0) and np.all(v < 1)
1849 True
1850 >>> v0 = random_vector(10)
1851 >>> v1 = random_vector(10)
1852 >>> np.any(v0 == v1)
1853 False
1854
1855 """
1856 return np.random.random(size)
1857
1858
1859 def vector_product(v0, v1, axis=0):
1860 """Return vector perpendicular to vectors.
1861
1862 >>> v = vector_product([2, 0, 0], [0, 3, 0])
1863 >>> np.allclose(v, [0, 0, 6])
1864 True
1865 >>> v0 = [[2, 0, 0, 2], [0, 2, 0, 2], [0, 0, 2, 2]]
1866 >>> v1 = [[3], [0], [0]]
1867 >>> v = vector_product(v0, v1)
1868 >>> np.allclose(v, [[0, 0, 0, 0], [0, 0, 6, 6], [0, -6, 0, -6]])
1869 True
1870 >>> v0 = [[2, 0, 0], [2, 0, 0], [0, 2, 0], [2, 0, 0]]
1871 >>> v1 = [[0, 3, 0], [0, 0, 3], [0, 0, 3], [3, 3, 3]]
1872 >>> v = vector_product(v0, v1, axis=1)
1873 >>> np.allclose(v, [[0, 0, 6], [0, -6, 0], [6, 0, 0], [0, -6, 6]])
1874 True
1875
1876 """
1877 return np.cross(v0, v1, axis=axis)
1878
1879
1880 def angle_between_vectors(v0, v1, directed=True, axis=0):
1881 """Return angle between vectors.
1882
1883 If directed is False, the input vectors are interpreted as undirected axes,
1884 i.e. the maximum angle is pi/2.
1885
1886 >>> a = angle_between_vectors([1, -2, 3], [-1, 2, -3])
1887 >>> np.allclose(a, math.pi)
1888 True
1889 >>> a = angle_between_vectors([1, -2, 3], [-1, 2, -3], directed=False)
1890 >>> np.allclose(a, 0)
1891 True
1892 >>> v0 = [[2, 0, 0, 2], [0, 2, 0, 2], [0, 0, 2, 2]]
1893 >>> v1 = [[3], [0], [0]]
1894 >>> a = angle_between_vectors(v0, v1)
1895 >>> np.allclose(a, [0, 1.5708, 1.5708, 0.95532])
1896 True
1897 >>> v0 = [[2, 0, 0], [2, 0, 0], [0, 2, 0], [2, 0, 0]]
1898 >>> v1 = [[0, 3, 0], [0, 0, 3], [0, 0, 3], [3, 3, 3]]
1899 >>> a = angle_between_vectors(v0, v1, axis=1)
1900 >>> np.allclose(a, [1.5708, 1.5708, 1.5708, 0.95532])
1901 True
1902
1903 """
1904 v0 = np.array(v0, dtype=np.float64, copy=False)
1905 v1 = np.array(v1, dtype=np.float64, copy=False)
1906 dot = np.sum(v0 * v1, axis=axis)
1907 dot /= vector_norm(v0, axis=axis) * vector_norm(v1, axis=axis)
1908 return np.arccos(dot if directed else np.fabs(dot))
1909
1910
1911 def inverse_matrix(matrix):
1912 """Return inverse of square transformation matrix.
1913
1914 >>> M0 = random_rotation_matrix()
1915 >>> M1 = inverse_matrix(M0.T)
1916 >>> np.allclose(M1, np.linalg.inv(M0.T))
1917 True
1918 >>> for size in range(1, 7):
1919 ... M0 = np.random.rand(size, size)
1920 ... M1 = inverse_matrix(M0)
1921 ... if not np.allclose(M1, np.linalg.inv(M0)): print(size)
1922
1923 """
1924 return np.linalg.inv(matrix)
1925
1926
1927 def concatenate_matrices(*matrices):
1928 """Return concatenation of series of transformation matrices.
1929
1930 >>> M = np.random.rand(16).reshape((4, 4)) - 0.5
1931 >>> np.allclose(M, concatenate_matrices(M))
1932 True
1933 >>> np.allclose(np.dot(M, M.T), concatenate_matrices(M, M.T))
1934 True
1935
1936 """
1937 M = np.identity(4)
1938 for i in matrices:
1939 M = np.dot(M, i)
1940 return M
1941
1942
1943 def is_same_transform(matrix0, matrix1):
1944 """Return True if two matrices perform same transformation.
1945
1946 >>> is_same_transform(np.identity(4), np.identity(4))
1947 True
1948 >>> is_same_transform(np.identity(4), random_rotation_matrix())
1949 False
1950
1951 """
1952 matrix0 = np.array(matrix0, dtype=np.float64, copy=True)
1953 matrix0 /= matrix0[3, 3]
1954 matrix1 = np.array(matrix1, dtype=np.float64, copy=True)
1955 matrix1 /= matrix1[3, 3]
1956 return np.allclose(matrix0, matrix1)
1957
1958
1959 def is_same_quaternion(q0, q1):
1960 """Return True if two quaternions are equal."""
1961 q0 = np.array(q0)
1962 q1 = np.array(q1)
1963 return np.allclose(q0, q1) or np.allclose(q0, -q1)
1964
1965
1966 def transform_around(matrix, point):
1967 """
1968 Given a transformation matrix, apply its rotation
1969 around a point in space.
1970
1971 Parameters
1972 ----------
1973 matrix: (4,4) or (3, 3) float, transformation matrix
1974 point: (3,) or (2,) float, point in space
1975
1976 Returns
1977 ---------
1978 result: (4,4) transformation matrix
1979 """
1980 point = np.asanyarray(point)
1981 matrix = np.asanyarray(matrix)
1982 dim = len(point)
1983 if matrix.shape != (dim + 1, dim + 1):
1984 raise ValueError("matrix must be (d+1, d+1)")
1985
1986 translate = np.eye(dim + 1)
1987 translate[:dim, dim] = -point
1988 result = np.dot(matrix, translate)
1989 translate[:dim, dim] = point
1990 result = np.dot(translate, result)
1991
1992 return result
1993
1994
1995 def planar_matrix(offset=[0.0, 0.0], theta=0.0, point=None):
1996 """
1997 2D homogeonous transformation matrix
1998
1999 Parameters
2000 ----------
2001 offset: (2,) float, XY offset
2002 theta: float, rotation around Z in radians
2003 point: (2, ) float, point to rotate around
2004 Returns
2005 ----------
2006 matrix: (3,3) homogenous 2D transformation matrix
2007 """
2008 offset = np.asanyarray(offset, dtype=np.float64)
2009 theta = float(theta)
2010 if not np.isfinite(theta):
2011 raise ValueError("theta must be finite angle!")
2012 if offset.shape != (2,):
2013 raise ValueError("offset must be length 2!")
2014
2015 T = np.eye(3, dtype=np.float64)
2016 s = np.sin(theta)
2017 c = np.cos(theta)
2018
2019 T[0, 0:2] = [c, s]
2020 T[1, 0:2] = [-s, c]
2021 T[0:2, 2] = offset
2022
2023 if point is not None:
2024 T = transform_around(matrix=T, point=point)
2025
2026 return T
2027
2028
2029 def planar_matrix_to_3D(matrix_2D):
2030 """
2031 Given a 2D homogenous rotation matrix convert it to a 3D rotation
2032 matrix that is rotating around the Z axis
2033
2034 Parameters
2035 ----------
2036 matrix_2D: (3,3) float, homogenous 2D rotation matrix
2037
2038 Returns
2039 ----------
2040 matrix_3D: (4,4) float, homogenous 3D rotation matrix
2041 """
2042
2043 matrix_2D = np.asanyarray(matrix_2D, dtype=np.float64)
2044 if matrix_2D.shape != (3, 3):
2045 raise ValueError("Homogenous 2D transformation matrix required!")
2046
2047 matrix_3D = np.eye(4)
2048 # translation
2049 matrix_3D[0:2, 3] = matrix_2D[0:2, 2]
2050 # rotation from 2D to around Z
2051 matrix_3D[0:2, 0:2] = matrix_2D[0:2, 0:2]
2052
2053 return matrix_3D
2054
2055
2056 def spherical_matrix(theta, phi, axes="sxyz"):
2057 """
2058 Give a spherical coordinate vector, find the rotation that will
2059 transform a [0,0,1] vector to those coordinates
2060
2061 Parameters
2062 -----------
2063 theta: float, rotation angle in radians
2064 phi: float, rotation angle in radians
2065
2066 Returns
2067 ----------
2068 matrix: (4,4) rotation matrix where the following will
2069 be a cartesian vector in the direction of the
2070 input spherical coordinats:
2071 np.dot(matrix, [0,0,1,0])
2072
2073 """
2074 result = euler_matrix(0.0, phi, theta, axes=axes)
2075 return result
2076
2077
2078 def transform_points(points, matrix, translate=True):
2079 """
2080 Returns points, rotated by transformation matrix
2081
2082 If points is (n,2), matrix must be (3,3)
2083 if points is (n,3), matrix must be (4,4)
2084
2085 Parameters
2086 ----------
2087 points : (n, d) float
2088 Points where d is 2 or 3
2089 matrix : (3,3) or (4,4) float
2090 Homogenous rotation matrix
2091 translate : bool
2092 Apply translation from matrix or not
2093
2094 Returns
2095 ----------
2096 transformed : (n,d) float
2097 Transformed points
2098 """
2099 points = np.asanyarray(points, dtype=np.float64)
2100 matrix = np.asanyarray(matrix, dtype=np.float64)
2101 if len(points.shape) != 2 or (points.shape[1] + 1 != matrix.shape[1]):
2102 raise ValueError(
2103 "matrix shape ({}) doesn't match points ({})".format(
2104 matrix.shape, points.shape
2105 )
2106 )
2107
2108 # check to see if we've been passed an identity matrix
2109 identity = np.abs(matrix - np.eye(matrix.shape[0])).max()
2110 if identity < 1e-8:
2111 return np.ascontiguousarray(points.copy())
2112
2113 dimension = points.shape[1]
2114 column = np.zeros(len(points)) + int(bool(translate))
2115 stacked = np.column_stack((points, column))
2116 transformed = np.dot(matrix, stacked.T).T[:, :dimension]
2117 transformed = np.ascontiguousarray(transformed)
2118 return transformed
2119
2120
2121 def is_rigid(matrix):
2122 """
2123 Check to make sure a homogeonous transformation matrix is
2124 a rigid body transform.
2125
2126 Parameters
2127 -----------
2128 matrix: possibly a transformation matrix
2129
2130 Returns
2131 -----------
2132 check: bool, True if matrix is a valid (4,4) rigid body transform.
2133 """
2134
2135 matrix = np.asanyarray(matrix, dtype=np.float64)
2136
2137 if matrix.shape != (4, 4):
2138 return False
2139
2140 if not np.allclose(matrix[-1], [0, 0, 0, 1]):
2141 return False
2142
2143 check = np.dot(matrix[:3, :3], matrix[:3, :3].T)
2144
2145 return np.allclose(check, np.eye(3))