
    -i#             
       j   d Z ddlZddlmZmZ ddlmZmZm	Z	  ej                  d      Zdej                  d<   d	 Zd
 Zd Zd Zd ZdtdZd ZdudZd ZdvdZdwdZdwdZd Zd Zd ZdxdZd ZdydZdzdZd{dZ d{dZ!d{dZ"d{d Z#d! Z$d" Z%dwd#Z&d$ Z'd% Z(d& Z)d' Z*d( Z+d|d)Z,d}d*Z-	 d~d+e	e   d,ed-e	e   fd.Z. G d/ d0      Z/d1 Z0d2 Z1d3 Z2 ejf                  e4      jj                  d4z  Z6g d5Z7i dd6d7d8d9d:d;d<d=d>d?d@dAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdQdRdSdTdUdVdWdXdYdZd[d\d]d^Z8e8js                         D  ci c]  \  } }|| 
 c}} Z:dud_Z;dud`Z<da Z=ddbZ>ddcZ?dd Z@de ZAdf ZBdg ZCdh ZDddiZEdj ZFd{dkZG	 ddledmed-eHdneej                     fdoZJddpZKddqZLdudrZMds ZNyc c}} w )a$  Homogeneous Transformation Matrices and Quaternions.

A library for calculating 4x4 matrices for translating, rotating, reflecting,
scaling, shearing, projecting, orthogonalizing, and superimposing arrays of
3D homogeneous coordinates as well as for converting between rotation matrices,
Euler angles, and quaternions. Also includes an Arcball control object and
functions to decompose transformation matrices.

:Author:
  `Christoph Gohlke <http://www.lfd.uci.edu/~gohlke/>`_

:Organization:
  Laboratory for Fluorescence Dynamics, University of California, Irvine

:Version: 2017.02.17

Requirements
------------
* `CPython 2.7 or 3.4 <http://www.python.org>`_
* `numpy 1.9 <http://www.np.org>`_
* `Transformations.c 2015.03.19 <http://www.lfd.uci.edu/~gohlke/>`_
  (recommended for speedup of some functions)

Notes
-----
The API is not stable yet and is expected to change between revisions.

This Python code is not optimized for speed. Refer to the transformations.c
module for a faster implementation of some functions.

Documentation in HTML format can be generated with epydoc.

Matrices (M) can be inverted using np.linalg.inv(M), be concatenated using
np.dot(M0, M1), or transform homogeneous coordinate arrays (v) using
np.dot(M, v) for shape (4, *) column vectors, respectively
np.dot(v, M.T) for shape (*, 4) row vectors ("array of points").

This module follows the "column vectors on the right" and "row major storage"
(C contiguous) conventions. The translation components are in the right column
of the transformation matrix, i.e. M[:3, 3].
The transpose of the transformation matrices may have to be used to interface
with other graphics systems, e.g. with OpenGL's glMultMatrixd(). See also [16].

Calculations are carried out with np.float64 precision.

Vector, point, quaternion, and matrix function arguments are expected to be
"array like", i.e. tuple, list, or numpy arrays.

Return types are numpy arrays unless specified otherwise.

Angles are in radians unless specified otherwise.

Quaternions w+ix+jy+kz are represented as [w, x, y, z].

A triple of Euler angles can be applied/interpreted in 24 ways, which can
be specified using a 4 character string or encoded 4-tuple:

  *Axes 4-string*: e.g. 'sxyz' or 'ryxy'

  - first character : rotations are applied to 's'tatic or 'r'otating frame
  - remaining characters : successive rotation axis 'x', 'y', or 'z'

  *Axes 4-tuple*: e.g. (0, 0, 0, 0) or (1, 1, 1, 1)

  - inner axis: code of axis ('x':0, 'y':1, 'z':2) of rightmost matrix.
  - parity : even (0) if inner axis 'x' is followed by 'y', 'y' is followed
    by 'z', or 'z' is followed by 'x'. Otherwise odd (1).
  - repetition : first and last axis are same (1) or different (0).
  - frame : rotations are applied to static (0) or rotating (1) frame.

Other Python packages and modules for 3D transformations and quaternions:

* `Transforms3d <https://pypi.python.org/pypi/transforms3d>`_
   includes most code of this module.
* `Blender.mathutils <http://www.blender.org/api/blender_python_api>`_
* `numpy-dtypes <https://github.com/numpy/numpy-dtypes>`_

References
----------
(1)  Matrices and transformations. Ronald Goldman.
     In "Graphics Gems I", pp 472-475. Morgan Kaufmann, 1990.
(2)  More matrices and transformations: shear and pseudo-perspective.
     Ronald Goldman. In "Graphics Gems II", pp 320-323. Morgan Kaufmann, 1991.
(3)  Decomposing a matrix into simple transformations. Spencer Thomas.
     In "Graphics Gems II", pp 320-323. Morgan Kaufmann, 1991.
(4)  Recovering the data from the transformation matrix. Ronald Goldman.
     In "Graphics Gems II", pp 324-331. Morgan Kaufmann, 1991.
(5)  Euler angle conversion. Ken Shoemake.
     In "Graphics Gems IV", pp 222-229. Morgan Kaufmann, 1994.
(6)  Arcball rotation control. Ken Shoemake.
     In "Graphics Gems IV", pp 175-192. Morgan Kaufmann, 1994.
(7)  Representing attitude: Euler angles, unit quaternions, and rotation
     vectors. James Diebel. 2006.
(8)  A discussion of the solution for the best rotation to relate two sets
     of vectors. W Kabsch. Acta Cryst. 1978. A34, 827-828.
(9)  Closed-form solution of absolute orientation using unit quaternions.
     BKP Horn. J Opt Soc Am A. 1987. 4(4):629-642.
(10) Quaternions. Ken Shoemake.
     http://www.sfu.ca/~jwa3/cmpt461/files/quatut.pdf
(11) From quaternion to matrix and back. JMP van Waveren. 2005.
     http://www.intel.com/cd/ids/developer/asmo-na/eng/293748.htm
(12) Uniform random rotations. Ken Shoemake.
     In "Graphics Gems III", pp 124-132. Morgan Kaufmann, 1992.
(13) Quaternion in molecular modeling. CFF Karney.
     J Mol Graph Mod, 25(5):595-604
(14) New method for extracting the quaternion from a rotation matrix.
     Itzhack Y Bar-Itzhack, J Guid Contr Dynam. 2000. 23(6): 1085-1087.
(15) Multiple View Geometry in Computer Vision. Hartley and Zissermann.
     Cambridge University Press; 2nd Ed. 2004. Chapter 4, Algorithm 4.7, p 130.
(16) Column Vectors vs. Row Vectors.
     http://steve.hollasch.net/cgindex/math/matrix/column-vec.html

Examples
--------
>>> alpha, beta, gamma = 0.123, -1.234, 2.345
>>> origin, xaxis, yaxis, zaxis = [0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1]
>>> I = identity_matrix()
>>> Rx = rotation_matrix(alpha, xaxis)
>>> Ry = rotation_matrix(beta, yaxis)
>>> Rz = rotation_matrix(gamma, zaxis)
>>> R = concatenate_matrices(Rx, Ry, Rz)
>>> euler = euler_from_matrix(R, 'rxyz')
>>> np.allclose([alpha, beta, gamma], euler)
True
>>> Re = euler_matrix(alpha, beta, gamma, 'rxyz')
>>> is_same_transform(R, Re)
True
>>> al, be, ga = euler_from_matrix(Re, 'rxyz')
>>> is_same_transform(Re, euler_matrix(al, be, ga, 'rxyz'))
True
>>> qx = quaternion_about_axis(alpha, xaxis)
>>> qy = quaternion_about_axis(beta, yaxis)
>>> qz = quaternion_about_axis(gamma, zaxis)
>>> q = quaternion_multiply(qx, qy)
>>> q = quaternion_multiply(q, qz)
>>> Rq = quaternion_matrix(q)
>>> is_same_transform(R, Rq)
True
>>> S = scale_matrix(1.23, origin)
>>> T = translation_matrix([1, 2, 3])
>>> Z = shear_matrix(beta, xaxis, origin, zaxis)
>>> R = random_rotation_matrix(np.random.rand(3))
>>> M = concatenate_matrices(T, R, Z, S)
>>> scale, shear, angles, trans, persp = decompose_matrix(M)
>>> np.allclose(scale, 1.23)
True
>>> np.allclose(trans, [1, 2, 3])
True
>>> np.allclose(shear, [0, np.tan(beta), 0])
True
>>> is_same_transform(R, euler_matrix(axes='sxyz', *angles))
True
>>> M1 = compose_matrix(scale, shear, angles, trans, persp)
>>> is_same_transform(M, M1)
True
>>> v0, v1 = random_vector(3), random_vector(3)
>>> M = rotation_matrix(angle_between_vectors(v0, v1), vector_product(v0, v1))
>>> v2 = np.dot(v0, M[:3,:3].T)
>>> np.allclose(unit_vector(v1), unit_vector(v2))
True

    N)	ArrayLikeNDArray   )IntegerNumberOptional   F	WRITEABLEc                  ,    t        j                  d      S )zReturn 4x4 identity/unit matrix.

    >>> I = identity_matrix()
    >>> np.allclose(I, np.dot(I, I))
    True
    >>> float(np.sum(I)), float(np.trace(I))
    (4.0, 4.0)
    >>> np.allclose(I, np.identity(4))
    True

    r	   )npidentity     S/mnt/e/genesis-system/.venv/lib/python3.12/site-packages/trimesh/transformations.pyidentity_matrixr      s     ;;q>r   c                     t        |       }t        d | D              rddlm}  ||dz         }nt	        j                  |dz         }| d| |d||f<   |S )z
    Return matrix to translate by direction vector.

    >>> v = np.random.random(3) - 0.5
    >>> np.allclose(v, translation_matrix(v)[:3, 3])
    True

    c              3   H   K   | ]  }d t        t        |            v   yw)sympyN)strtype).0vs     r   	<genexpr>z%translation_matrix.<locals>.<genexpr>   s     
6q7c$q'l"
6s    "r   )eyer   N)lenanyr   r   r   )	directiondimr   Ms       r   translation_matrixr       s\     i.C 
6I
66aLFF37O Tc?AdsdCiLHr   c                 V    t        j                  |       dddf   j                         S )zReturn translation vector from translation matrix.

    >>> v0 = np.random.random(3) - 0.5
    >>> v1 = translation_from_matrix(translation_matrix(v0))
    >>> np.allclose(v0, v1)
    True

    N   )r   asarraycopymatrixs    r   translation_from_matrixr'      s)     ::fbqb!e$))++r   c                     t        |dd       }t        j                  d      }|ddddfxx   dt        j                  ||      z  z  cc<   dt        j                  | dd |      z  |z  |dddf<   |S )a  Return matrix to mirror at plane defined by point and normal vector.

    >>> v0 = np.random.random(4) - 0.5
    >>> v0[3] = 1.
    >>> v1 = np.random.random(3) - 0.5
    >>> R = reflection_matrix(v0, v1)
    >>> np.allclose(2, np.trace(R))
    True
    >>> np.allclose(v0, np.dot(R, v0))
    True
    >>> v2 = v0.copy()
    >>> v2[:3] += v1
    >>> v3 = v0.copy()
    >>> v2[:3] -= v1
    >>> np.allclose(v2, np.dot(R, v3))
    True

    Nr"   r	          @)unit_vectorr   r   outerdot)pointnormalr   s      r   reflection_matrixr/     s|    & $F
AAbqb"1"fIrxx///IbffU2AY//69Abqb!eHHr   c                    t        j                  | t         j                        }t         j                  j	                  |ddddf         \  }}t        j
                  t        t        j                  |      dz         dk        d   }t        |      st        d      t        j                  |dd|d   f         j                         }t         j                  j	                  |      \  }}t        j
                  t        t        j                  |      dz
        dk        d   }t        |      st        d      t        j                  |dd|d	   f         j                         }||d   z  }||fS )
aK  Return mirror plane point and normal vector from reflection matrix.

    >>> v0 = np.random.random(3) - 0.5
    >>> v1 = np.random.random(3) - 0.5
    >>> M0 = reflection_matrix(v0, v1)
    >>> point, normal = reflection_from_matrix(M0)
    >>> M1 = reflection_matrix(point, normal)
    >>> is_same_transform(M0, M1)
    True

    dtypeNr"         ?:0yE>r   z2no unit eigenvector corresponding to eigenvalue -11no unit eigenvector corresponding to eigenvalue 1)r   r#   float64linalgeigwhereabsrealr   
ValueErrorsqueeze)r&   r   wVir.   r-   s          r   reflection_from_matrixrB   "  s,    	

6,A99==2A2rr6#DAq
RWWQZ#%&-.q1Aq6MNNWWQq!A$wZ ((*F99==DAq
RWWQZ#%&-.q1Aq6LMMGGAa2hK ((*E	U1XE&=r   c           
         dt        t        |             v r)ddl}d}|j                  |       }|j	                  |       }n,d}t        j                  |       }t        j                  |       }t        |dd       }t        j                  |||dg      }|ddddfxx   t        j                  ||      d|z
  z  z  cc<   ||z  }|ddddfxx   t        j                  d|d	    |d
   g|d	   d|d    g|d
    |d   dgg      z  cc<   |Qt        j                  |dd t
        j                        }|t        j                  |ddddf   |      z
  |dddf<   |rj                  |      S |S )a  
    Return matrix to rotate about axis defined by point and
    direction.

    Parameters
    -------------
    angle     : float, or sympy.Symbol
      Angle, in radians or symbolic angle
    direction : (3,) float
      Any vector along rotation axis
    point     : (3, ) float, or None
      Origin point of rotation axis

    Returns
    -------------
    matrix : (4, 4) float, or (4, 4) sympy.Matrix
      Homogeneous transformation matrix

    Examples
    -------------
    >>> R = rotation_matrix(np.pi/2, [0, 0, 1], [1, 0, 0])
    >>> np.allclose(np.dot(R, [0, 0, 0, 1]), [1, -1, 0, 1])
    True
    >>> angle = (random.random() - 0.5) * (2*np.pi)
    >>> direc = np.random.random(3) - 0.5
    >>> point = np.random.random(3) - 0.5
    >>> R0 = rotation_matrix(angle, direc, point)
    >>> R1 = rotation_matrix(angle-2*np.pi, direc, point)
    >>> is_same_transform(R0, R1)
    True
    >>> R0 = rotation_matrix(angle, direc, point)
    >>> R1 = rotation_matrix(-angle, -direc, point)
    >>> is_same_transform(R0, R1)
    True
    >>> I = np.identity(4, np.float64)
    >>> np.allclose(I, rotation_matrix(np.pi*2, direc))
    True
    >>> np.allclose(2, np.trace(rotation_matrix(np.pi/2,direc,point)))
    True

    r   r   NTFr"   r3              r   r1   )r   r   r   sincosr   r*   diagr+   arrayr#   r7   r,   Matrix)angler   r-   spsymbolicsinacosar   s           r   rotation_matrixrP   ?  s   T #d5k""vve}vve}vve}vve}IbqM*I 	tT3'(Abqb"1"fI)Y/3:>>ID Ibqb"1"fI9Q<-1.q\31.l]IaL#.	
 I 

5!9BJJ7266!BQBF)U33"1"a% yy|Hr   c                 d   t        j                  | t         j                        }|ddddf   }t         j                  j	                  |j
                        \  }}t        j                  t        t        j                  |      dz
        dk        d   }t        |      st        d      t        j                  |dd|d   f         j                         }t         j                  j	                  |      \  }}t        j                  t        t        j                  |      dz
        dk        d   }t        |      st        d      t        j                  |dd|d   f         j                         }||d   z  }t        j                  |      dz
  d	z  }	t        |d
         dkD  r|d   |	dz
  |d   z  |d   z  z   |d
   z  }
nLt        |d         dkD  r|d   |	dz
  |d   z  |d
   z  z   |d   z  }
n|d   |	dz
  |d   z  |d
   z  z   |d   z  }
t        j                  |
|	      }|||fS )a  Return rotation angle and axis from rotation matrix.

    >>> angle = (random.random() - 0.5) * (2*np.pi)
    >>> direc = np.random.random(3) - 0.5
    >>> point = np.random.random(3) - 0.5
    >>> R0 = rotation_matrix(angle, direc, point)
    >>> angle, direc, point = rotation_from_matrix(R0)
    >>> R1 = rotation_matrix(angle, direc, point)
    >>> is_same_transform(R0, R1)
    True

    r1   Nr"   r3   r4   r   r5   r6   r)   rE   r   r   r   r   rE   rE   r   )r   r#   r7   r8   r9   Tr:   r;   r<   r   r=   r>   tracearctan2)r&   RR33r?   WrA   r   Qr-   rO   rN   rK   s               r   rotation_from_matrixr\     s    	

6,A
BQBF)C99==DAq
RWWQZ#%&-.q1Aq6LMM!QrU($,,.I99==DAq
RWWQZ#%&-.q1Aq6LMMGGAa2hK ((*E	U1XEHHSMC3&D
9Q<4$4#:15	!DD	RST	Yq\	T	!$4#:15	!DD	RST$4#:15	!DD	RSTJJtT"E)U""r   c                 x   |=t        j                  | | | dg      }| |dd |dddf<   |dddfxx   d| z
  z  cc<   |S t        |dd       }d| z
  } t        j                  d      }|ddddfxx   | t        j                  ||      z  z  cc<   |&| t        j
                  |dd |      z  |z  |dddf<   |S )a  Return matrix to scale by factor around origin in direction.

    Use factor -1 for point symmetry.

    >>> v = (np.random.rand(4, 5) - 0.5) * 20
    >>> v[3] = 1
    >>> S = scale_matrix(-1.234)
    >>> np.allclose(np.dot(S, v)[:3], -1.234*v[:3])
    True
    >>> factor = random.random() * 10 - 5
    >>> origin = np.random.random(3) - 0.5
    >>> direct = np.random.random(3) - 0.5
    >>> S = scale_matrix(factor, origin)
    >>> S = scale_matrix(factor, origin, direct)

    Nr3   r"   r	   )r   rH   r*   r   r+   r,   )factororiginr   r   s       r   scale_matrixr`     s    " GGVVVS12bqzAbqb!eHbqb!eHf$H H  	"1.	vKKN	"1"bqb&	Vbhhy)<<<	r
I!>>)KAbqb!eHHr   c                 L   t        j                  | t         j                        }|ddddf   }t        j                  |      dz
  }	 t         j                  j                  |      \  }}t        j                  t        t        j                  |      |z
        dk        d   d   }t        j                  |dd|f         j                         }|t        |      z  }t         j                  j                  |      \  }}t        j                  t        t        j                  |      dz
        dk        d   }t        |      st        d	      t        j                  |dd|d
   f         j                         }||d   z  }|||fS # t        $ r |dz   dz  }d}Y w xY w)aW  Return scaling factor, origin and direction from scaling matrix.

    >>> factor = random.random() * 10 - 5
    >>> origin = np.random.random(3) - 0.5
    >>> direct = np.random.random(3) - 0.5
    >>> S0 = scale_matrix(factor, origin)
    >>> factor, origin, direction = scale_from_matrix(S0)
    >>> S1 = scale_matrix(factor, origin, direction)
    >>> is_same_transform(S0, S1)
    True
    >>> S0 = scale_matrix(factor, origin, direct)
    >>> factor, origin, direction = scale_from_matrix(S0)
    >>> S1 = scale_matrix(factor, origin, direction)
    >>> is_same_transform(S0, S1)
    True

    r1   Nr"   r)   r4   r         @r3   ,no eigenvector corresponding to eigenvalue 1r6   )r   r#   r7   rV   r8   r9   r:   r;   r<   r>   vector_norm
IndexErrorr   r=   )	r&   r   M33r^   r?   r@   rA   r   r_   s	            r   scale_from_matrixrg     sn   $ 	

6,A
BQBF)CXXc]S F	yy}}S!1HHSf,-45a8;GGAadG$,,.	[++	 99==DAq
RWWQZ#%&-.q1Aq6GHHWWQq!B%x[!))+F
fQiF69$$  3,#%	s   
BF F#"F#c                 \   t        j                  d      }t        j                  | dd t         j                        } t	        |dd       }|t        j                  |dd t         j                        }t        j
                  || z
  |      x|d<   x|d<   |d<   |ddddfxx   t        j                  ||      z  cc<   |rK|ddddfxx   t        j                  ||      z  cc<   t        j
                  | |      ||z   z  |dddf<   n t        j
                  | |      |z  |dddf<   | |dddf<   t        j
                  ||      |d<   |S |t        j                  |dd t         j                        }t        j
                  ||      }|ddddfxx   t        j                  ||      |z  z  cc<   |t        j
                  | |      |z  z  |dddf<   |S |ddddfxx   t        j                  ||      z  cc<   t        j
                  | |      |z  |dddf<   |S )	ae  Return matrix to project onto plane defined by point and normal.

    Using either perspective point, projection direction, or none of both.

    If pseudo is True, perspective projections will preserve relative depth
    such that Perspective = dot(Orthogonal, PseudoPerspective).

    >>> P = projection_matrix([0, 0, 0], [1, 0, 0])
    >>> np.allclose(P[1:, 1:], np.identity(4)[1:, 1:])
    True
    >>> point = np.random.random(3) - 0.5
    >>> normal = np.random.random(3) - 0.5
    >>> direct = np.random.random(3) - 0.5
    >>> persp = np.random.random(3) - 0.5
    >>> P0 = projection_matrix(point, normal)
    >>> P1 = projection_matrix(point, normal, direction=direct)
    >>> P2 = projection_matrix(point, normal, perspective=persp)
    >>> P3 = projection_matrix(point, normal, perspective=persp, pseudo=True)
    >>> is_same_transform(P2, np.dot(P0, P3))
    True
    >>> P = projection_matrix([3, 0, 0], [1, 1, 0], [1, 0, 0])
    >>> v0 = (np.random.rand(4, 5) - 0.5) * 20
    >>> v0[3] = 1
    >>> v1 = np.dot(P, v0)
    >>> np.allclose(v1[1], v0[1])
    True
    >>> np.allclose(v1[0], 3-v1[1])
    True

    r	   Nr"   r1   r   r   r   r   rE   rE   r"   r"   )r   r   r#   r7   r*   r,   r+   )r-   r.   r   perspectivepseudor   scales          r   projection_matrixrp     s   > 	AAJJuRay

3E$FjjRa

C&(ff[5-@&&II$I!D'AdG	"1"bqb&	RXXk622	bqb"1"fI&&11IvveV,f0DEAbqb!eHvveV,{:Abqb!eH7!RaR%&&f-$ H 
	JJy!}BJJ?	y&)	"1"bqb&	RXXi0588	uf 5 =>"1"a%
 H 	
"1"bqb&	RXXff--	66%(61"1"a%Hr   c                    t        j                  | t         j                        }|ddddf   }t         j                  j	                  |      \  }}t        j
                  t        t        j                  |      dz
        dk        d   }|st        |      rt        j                  |dd|d   f         j                         }||d   z  }t         j                  j	                  |      \  }}t        j
                  t        t        j                  |            dk        d   }t        |      st        d      t        j                  |dd|d   f         j                         }|t        |      z  }t         j                  j	                  |j                        \  }}t        j
                  t        t        j                  |            dk        d   }t        |      rBt        j                  |dd|d   f         j                         }	|	t        |	      z  }	||	|dd	fS ||ddd	fS t        j
                  t        t        j                  |            dkD        d   }t        |      st        d
      t        j                  |dd|d   f         j                         }||d   z  }|dddf    }	|dddf   t        j                  |dd |	      z  }
|r|
|	z  }
||	d|
|fS )a  Return projection plane and perspective point from projection matrix.

    Return values are same as arguments for projection_matrix function:
    point, normal, direction, perspective, and pseudo.

    >>> point = np.random.random(3) - 0.5
    >>> normal = np.random.random(3) - 0.5
    >>> direct = np.random.random(3) - 0.5
    >>> persp = np.random.random(3) - 0.5
    >>> P0 = projection_matrix(point, normal)
    >>> result = projection_from_matrix(P0)
    >>> P1 = projection_matrix(*result)
    >>> is_same_transform(P0, P1)
    True
    >>> P0 = projection_matrix(point, normal, direct)
    >>> result = projection_from_matrix(P0)
    >>> P1 = projection_matrix(*result)
    >>> is_same_transform(P0, P1)
    True
    >>> P0 = projection_matrix(point, normal, perspective=persp, pseudo=False)
    >>> result = projection_from_matrix(P0, pseudo=False)
    >>> P1 = projection_matrix(*result)
    >>> is_same_transform(P0, P1)
    True
    >>> P0 = projection_matrix(point, normal, perspective=persp, pseudo=True)
    >>> result = projection_from_matrix(P0, pseudo=True)
    >>> P1 = projection_matrix(*result)
    >>> is_same_transform(P0, P1)
    True

    r1   Nr"   r3   r4   r   r6   z,no eigenvector corresponding to eigenvalue 0Fz0no eigenvector not corresponding to eigenvalue 0)r   r#   r7   r8   r9   r:   r;   r<   r   r>   r=   rd   rU   r,   )r&   rn   r   rf   r?   r@   rA   r-   r   r.   rm   s              r   projection_from_matrixrr   ?  s   @ 	

6,A
BQBF)C99==DAq
RWWQZ#%&-.q1Ac!f!QrU($,,.qyy}}S!1HHS_t+,Q/1vKLLGGAa1gJ'//1	[++	yy}}SUU#1HHS_t+,Q/q6WWQq!A$wZ(002Fk&))F&)T588 )T466 HHS_t+,Q/1vOPP!QrU($,,.qArrE(Ahbq	6!::6!KfdK77r   c                    | |k\  s
||k\  s||k\  rt        d      |r^|t        k  rt        d      d|z  }|| |z
  z  d|| z   || z
  z  dgd|||z
  z  ||z   ||z
  z  dgdd||z   ||z
  z  ||z  ||z
  z  gg dg}nAd|| z
  z  dd|| z   | |z
  z  gdd||z
  z  d||z   ||z
  z  gddd||z
  z  ||z   ||z
  z  gg dg}t        j                  |      S )aC  Return matrix to obtain normalized device coordinates from frustum.

    The frustum bounds are axis-aligned along x (left, right),
    y (bottom, top) and z (near, far).

    Normalized device coordinates are in range [-1, 1] if coordinates are
    inside the frustum.

    If perspective is True the frustum is a truncated pyramid with the
    perspective point at origin and direction along z axis, otherwise an
    orthographic canonical view volume (a box).

    Homogeneous coordinates transformed by the perspective clip matrix
    need to be dehomogenized (divided by w coordinate).

    >>> frustum = np.random.rand(6)
    >>> frustum[1] += frustum[0]
    >>> frustum[3] += frustum[2]
    >>> frustum[5] += frustum[4]
    >>> M = clip_matrix(perspective=False, *frustum)
    >>> a = np.dot(M, [frustum[0], frustum[2], frustum[4], 1])
    >>> np.allclose(a, [-1., -1., -1.,  1.])
    True
    >>> b = np.dot(M, [frustum[1], frustum[3], frustum[5], 1])
    >>> np.allclose(b, [ 1.,  1.,  1.,  1.])
    True
    >>> M = clip_matrix(perspective=True, *frustum)
    >>> v = np.dot(M, [frustum[0], frustum[2], frustum[4], 1])
    >>> c = v / v[3]
    >>> np.allclose(c, [-1., -1., -1.,  1.])
    True
    >>> v = np.dot(M, [frustum[1], frustum[3], frustum[4], 1])
    >>> d = v / v[3]
    >>> np.allclose(d, [ 1.,  1., -1.,  1.])
    True

    zinvalid frustumzinvalid frustum: near <= 0r)   rD   )rD   rD         rD   rD   rD   rD   r3   )r=   _EPSr   rI   )	leftrightbottomtopnearfarrm   tr   s	            r   clip_matrixr~     s9   L u}#*++4<9::$J$,ut|&EsK!v|$sV|f&EsK#d
tcz2AGsTz4JK!	
 EDL!3edlte|-LM#v&cFlv|-LM#scDj)C$J4#:+FG 	
 88A;r   c                    t        |dd       }t        |dd       }t        t        j                  ||            dkD  rt	        d      t        j
                  |       } t        j                  d      }|ddddfxx   | t        j                  ||      z  z  cc<   |  t        j                  |dd |      z  |z  |dddf<   |S )a  Return matrix to shear by angle along direction vector on shear plane.

    The shear plane is defined by a point and normal vector. The direction
    vector must be orthogonal to the plane's normal vector.

    A point P is transformed by the shear matrix into P" such that
    the vector P-P" is parallel to the direction vector and its extent is
    given by the angle of P-P'-P", where P' is the orthogonal projection
    of P onto the shear plane.

    >>> angle = (random.random() - 0.5) * 4*np.pi
    >>> direct = np.random.random(3) - 0.5
    >>> point = np.random.random(3) - 0.5
    >>> normal = np.cross(direct, np.random.random(3))
    >>> S = shear_matrix(angle, direct, point, normal)
    >>> np.allclose(1, np.linalg.det(S))
    True

    Nr"   gư>z/direction and normal vectors are not orthogonalr	   )r*   r;   r   r,   r=   tanr   r+   )rK   r   r-   r.   r   s        r   shear_matrixr     s    ( $FIbqM*I
266&)$%,JKKFF5ME
AAbqb"1"fI)V444IvuRay&11I=Abqb!eHHr   c                 :   t        j                  | t         j                        }|ddddf   }t         j                  j	                  |      \  }}t        j
                  t        t        j                  |      dz
        dk        d   }t        |      dk  rt        d|       t        j                  |dd|f         j                         j                  }d	}d
D ]6  \  }}t        j                  ||   ||         }	t        |	      }||kD  s3|}|	}
8 
|z  }
t        j                  |t        j                  d      z
  |
      }t        |      }||z  }t        j                   |      }t         j                  j	                  |      \  }}t        j
                  t        t        j                  |      dz
        dk        d   }t        |      st        d      t        j                  |dd|d   f         j                         }||d   z  }||||
fS )a  Return shear angle, direction and plane from shear matrix.

    >>> angle  = np.pi / 2.0
    >>> direct = [0.0, 1.0, 0.0]
    >>> point  = [0.0, 0.0, 0.0]
    >>> normal = np.cross(direct, np.roll(direct,1))
    >>> S0 = shear_matrix(angle, direct, point, normal)
    >>> angle, direct, point, normal = shear_from_matrix(S0)
    >>> S1 = shear_matrix(angle, direct, point, normal)
    >>> is_same_transform(S0, S1)
    True

    r1   Nr"   r3   g-C6?r   rE   z-no two linear independent eigenvectors found rt   )r   r   rS   r   rE   r4   rc   r6   )r   r#   r7   r8   r9   r:   r;   r<   r   r=   r>   rU   crossrd   r,   r   arctan)r&   r   rf   r?   r@   rA   lenormi0i1nr.   r   rK   r-   s                 r   shear_from_matrixr     s    	

6,A
BQBF)C99==DAq
RWWQZ#%&-.q1A
1vzHLMM
!Q$  "$$AF* BHHQrUAbE"Nv:FF fFsR[[^+V4I	"EIIIeE99==DAq
RWWQZ#%&-.q1Aq6GHHGGAa2hK ((*E	U1XE)UF**r   c                 8   t        j                  | t         j                        j                  }t	        |d         t
        k  rt        d      ||d   z  }|j                         }d|dddf<   t         j                  j                  |      st        d      t        j                  d      }g d	}g d	}t        t	        |dddf         t
        kD        rNt        j                  |dddf   t         j                  j                  |j                              }d|dddf<   nt        j                  g d      }|dddf   j                         }d
|dddf<   |ddddf   j                         }t        |d         |d<   |dxx   |d   z  cc<   t        j                  |d   |d         |d<   |dxx   |d   |d   z  z  cc<   t        |d         |d<   |dxx   |d   z  cc<   |dxx   |d   z  cc<   t        j                  |d   |d         |d<   |dxx   |d   |d   z  z  cc<   t        j                  |d   |d         |d<   |dxx   |d   |d   z  z  cc<   t        |d         |d<   |dxx   |d   z  cc<   |ddxxx |d   z  ccc t        j                  |d   t        j                  |d   |d               dk  r,t        j                   ||       t        j                   ||       t        j"                  |d          |d<   t        j$                  |d         r?t        j&                  |d   |d         |d<   t        j&                  |d   |d         |d<   n%t        j&                  |d    |d         |d<   d
|d<   |||||fS )a  Return sequence of transformations from transformation matrix.

    matrix : array_like
        Non-degenerative homogeneous transformation matrix

    Return tuple of:
        scale : vector of 3 scaling factors
        shear : list of shear factors for x-y, x-z, y-z axes
        angles : list of Euler angles about static x, y, z axes
        translate : translation vector along x, y, z axes
        perspective : perspective partition of matrix

    Raise ValueError if matrix is of wrong type or degenerative.

    >>> T0 = translation_matrix([1, 2, 3])
    >>> scale, shear, angles, trans, persp = decompose_matrix(T0)
    >>> T1 = translation_matrix(trans)
    >>> np.allclose(T0, T1)
    True
    >>> S = scale_matrix(0.123)
    >>> scale, shear, angles, trans, persp = decompose_matrix(S)
    >>> bool(np.isclose(scale[0], 0.123))
    True
    >>> R0 = euler_matrix(1, 2, 3)
    >>> scale, shear, angles, trans, persp = decompose_matrix(R0)
    >>> R1 = euler_matrix(*angles)
    >>> np.allclose(R0, R1)
    True

    r1   rl   zM[3, 3] is zeroru   Nr"   zmatrix is singular)r"   )rD   rD   rD   rD   r   r   rE   rS   r   rk   r   ri   rT   rj   )r   rI   r7   rU   r;   rv   r=   r$   r8   detzerosr   r,   invrd   r   negativearcsinrG   rW   )	r&   r   Pro   shearanglesrm   	translaterows	            r   decompose_matrixr     sM   > 	rzz*,,A
1T7|d*++4LA	A AadG99==-..HHTNEEF
3q!Qx=4 ffQq!tWbiimmACC&89$!Q$hh34!RaR%IAa!eH
BQBF)..
C3q6"E!HFeAhFvvc!fc!f%E!HFc!fuQxF3q6"E!HFeAhF	!HaHvvc!fc!f%E!HFc!fuQxFvvc!fc!f%E!HFc!fuQxF3q6"E!HFeAhF	!"IqI	vvc!fbhhs1vs1v./!3
E5!
C		3t9*%F1I	vvfQiJJs4y#d)4q	JJs4y#d)4q	JJD	z3t95q	q	%K77r   c                    t        j                  d      }|7t        j                  d      }|dd |dddf<   t        j                  ||      }|7t        j                  d      }|dd |dddf<   t        j                  ||      }|-t        |d   |d   |d   d      }t        j                  ||      }|Ct        j                  d      }	|d   |	d<   |d   |	d	<   |d   |	d
<   t        j                  ||	      }| Ct        j                  d      }
| d   |
d<   | d   |
d<   | d   |
d<   t        j                  ||
      }||d   z  }|S )aR  Return transformation matrix from sequence of transformations.

    This is the inverse of the decompose_matrix function.

    Sequence of transformations:
        scale : vector of 3 scaling factors
        shear : list of shear factors for x-y, x-z, y-z axes
        angles : list of Euler angles about static x, y, z axes
        translate : translation vector along x, y, z axes
        perspective : perspective partition of matrix

    >>> scale = np.random.random(3) - 0.5
    >>> shear = np.random.random(3) - 0.5
    >>> angles = (np.random.random(3) - 0.5) * (2*np.pi)
    >>> trans = np.random.random(3) - 0.5
    >>> persp = np.random.random(4) - 0.5
    >>> M0 = compose_matrix(scale, shear, angles, trans, persp)
    >>> result = decompose_matrix(M0)
    >>> M1 = compose_matrix(*result)
    >>> is_same_transform(M0, M1)
    True

    r	   Nr"   r   r   rE   sxyzr   rS   r   ri   rj   rk   rl   )r   r   r,   euler_matrix)ro   r   r   r   rm   r   r   rU   rX   ZSs              r   compose_matrixr   e  sT   0 	AAKKNbq/!Q$FF1aLKKNRa="1"a%FF1aLF1Ivay&AFF1aLKKN($($($FF1aLKKN($($($FF1aL4LAHr   c                 d   | \  }}}t        j                  |      }t        j                  |      \  }}}t        j                  |      \  }}	}
||	z  |
z
  ||z  z  }t        j                  ||z  t        j
                  d||z  z
        z  dddg| |z  |z  ||z  ddg||	z  ||z  |dgg dg      S )a  Return orthogonalization matrix for crystallographic cell coordinates.

    Angles are expected in degrees.

    The de-orthogonalization matrix is the inverse.

    >>> O = orthogonalization_matrix([10, 10, 10], [90, 90, 90])
    >>> np.allclose(O[:3, :3], np.identity(3, float) * 10)
    True
    >>> O = orthogonalization_matrix([9.8, 12.0, 15.5], [87.2, 80.7, 69.7])
    >>> np.allclose(np.sum(O), 43.063229)
    True

    r3   rD   ru   )r   radiansrF   rG   rI   sqrt)lengthsr   abcrN   sinb_rO   cosbcosgcos               r   orthogonalization_matrixr     s     GAq!ZZFFF6NMD$vvf~D$
+
	-B88Xb2g..S#>R$Y^QXsC0Xq4xC( 		
 r   c           	      	   t        j                  | t         j                        } t        j                  |t         j                        }| j                  d   }|dk  s+| j                  d   |k  s| j                  |j                  k7  rt	        d      t        j
                  | d       }t        j                  |dz         }||d||f<   | |j                  |d      z  } t        j
                  |d       }t        j                  |dz         }	||	d||f<   ||j                  |d      z  }|rt        j                  | |fd      }
t         j                  j                  |
j                        \  }}}|d| j                  }|d| }||d|z   }t        j                  |t         j                  j                  |            }t        j                  |t        j                  |df      fd      }t        j                  |d|z  d	z   f      }n|s|d
k7  rt         j                  j                  t        j                  || j                              \  }}}t        j                  ||      }t         j                  j!                  |      dk  r=|t        j"                  |dd|dz
  f   ||dz
  ddf   dz        z  }|dxx   dz  cc<   t        j                  |dz         }||d|d|f<   nt        j$                  | |z  d      \  }}}t        j$                  | t        j&                  |dd      z  d      \  }}}t        j$                  | t        j&                  |dd      z  d      \  }}}||z   |z   dddg||z
  ||z
  |z
  ddg||z
  ||z   ||z
  |z
  dg||z
  ||z   ||z   ||z
  |z
  gg}t         j                  j)                  |      \  }}|ddt        j*                  |      f   }|t-        |      z  }t/        |      }|r[|sY| | z  } ||z  }|d|d|fxx   t        j0                  t        j$                  |      t        j$                  |       z        z  cc<   t        j                  t         j                  j3                  |	      t        j                  ||            }||||f   z  }|S )a  Return affine transform matrix to register two point sets.

    v0 and v1 are shape (ndims, *) arrays of at least ndims non-homogeneous
    coordinates, where ndims is the dimensionality of the coordinate space.

    If shear is False, a similarity transformation matrix is returned.
    If also scale is False, a rigid/Euclidean transformation matrix
    is returned.

    By default the algorithm by Hartley and Zissermann [15] is used.
    If usesvd is True, similarity and Euclidean transformation matrices
    are calculated by minimizing the weighted sum of squared deviations
    (RMSD) according to the algorithm by Kabsch [8].
    Otherwise, and if ndims is 3, the quaternion based algorithm by Horn [9]
    is used, which is slower when using this Python implementation.

    The returned matrix performs rotation, translation and uniform scaling
    (if specified).

    >>> v0 = [[0, 1031, 1031, 0], [0, 0, 1600, 1600]]
    >>> v1 = [[675, 826, 826, 677], [55, 52, 281, 277]]
    >>> mat = affine_matrix_from_points(v0, v1)
    >>> T = translation_matrix(np.random.random(3)-0.5)
    >>> R = random_rotation_matrix(np.random.random(3))
    >>> S = scale_matrix(random.random())
    >>> M = concatenate_matrices(T, R, S)
    >>> v0 = (np.random.rand(4, 100) - 0.5) * 20
    >>> v0[3] = 1
    >>> v1 = np.dot(M, v0)
    >>> v0[:3] += np.random.normal(0, 1e-8, 300).reshape(3, -1)
    >>> M = affine_matrix_from_points(v0[:3], v1[:3])
    >>> check = np.allclose(v1, np.dot(M, v0))

    More examples in superimposition_matrix()

    r1   r   rE   r   z'input arrays are of wrong shape or typeaxisNrD   )r3   r"   rD   r)   r6   rt   )r   rI   r7   shaper=   meanr   reshapeconcatenater8   svdrU   r,   pinvr   vstackr   r+   sumrolleighargmaxrd   quaternion_matrixr   r   ) v0v1r   ro   usesvdndimst0M0t1M1AusvhBCr}   r   rX   xxyyzzxyyzzxxzyxzyNr?   r@   qs                                    r   affine_matrix_from_pointsr     s+   J 
"BJJ	'B	"BJJ	'BHHQKEqyBHHQK%'288rxx+?BCC ''"1
	B	UQY	BBvvu}"**UA
B
''"1
	B	UQY	BBvvu}"**UA
BNNB8!,99==%1bZ\\vJuq5y!FF1biinnQ'(NNArxx
341=IIq6E>V345	5A:99==BDD!121bFF1bM99==c!!AuqyL/2eail+;c+ABBAbETMEKK	"&5&&5&. VVBG!,
BVVBRa!88qA
BVVBRa!88qA
B"Wr\3S)"Wb2glC-"Wb2grBw|S1"Wb2grBwR"5	
 yy~~a 1a1o	[^a U
b
b	&5&&5&.RWWRVVBZ"&&*%<== 	ryy}}R "&&B-0A5%<AHr   c                     t        j                  | t         j                        dd } t        j                  |t         j                        dd }t        | |d||      S )a#  Return matrix to transform given 3D point set into second point set.

    v0 and v1 are shape (3, *) or (4, *) arrays of at least 3 points.

    The parameters scale and usesvd are explained in the more general
    affine_matrix_from_points function.

    The returned matrix is a similarity or Euclidean transformation matrix.
    This function has a fast C implementation in transformations.c.

    >>> v0 = np.random.rand(3, 10)
    >>> M = superimposition_matrix(v0, v0)
    >>> np.allclose(M, np.identity(4))
    True
    >>> R = random_rotation_matrix(np.random.random(3))
    >>> v0 = [[1,0,0], [0,1,0], [0,0,1], [1,1,1]]
    >>> v1 = np.dot(R, v0)
    >>> M = superimposition_matrix(v0, v1)
    >>> np.allclose(v1, np.dot(M, v0))
    True
    >>> v0 = (np.random.rand(4, 100) - 0.5) * 20
    >>> v0[3] = 1
    >>> v1 = np.dot(R, v0)
    >>> M = superimposition_matrix(v0, v1)
    >>> np.allclose(v1, np.dot(M, v0))
    True
    >>> S = scale_matrix(random.random())
    >>> T = translation_matrix(np.random.random(3)-0.5)
    >>> M = concatenate_matrices(T, R, S)
    >>> v1 = np.dot(M, v0)
    >>> v0[:3] += np.random.normal(0, 1e-9, 300).reshape(3, -1)
    >>> M = superimposition_matrix(v0, v1, scale=True)
    >>> np.allclose(v1, np.dot(M, v0))
    True
    >>> M = superimposition_matrix(v0, v1, scale=True, usesvd=False)
    >>> np.allclose(v1, np.dot(M, v0))
    True
    >>> v = np.zeros((4, 100, 3))
    >>> v[:, :, 0] = v0
    >>> M = superimposition_matrix(v0, v1, scale=True, usesvd=False)
    >>> np.allclose(v1, np.dot(M, v[:, :, 0]))
    True

    r1   Nr"   F)r   ro   r   )r   r#   r7   r   )r   r   ro   r   s       r   superimposition_matrixr   "  sN    Z 
Bbjj	)"1	-B	Bbjj	)"1	-B$R5fUUr   r   c                    	 t         |   \  }}}}|}t        ||z      }	t        ||z
  dz      }
|r|| }} |r	|  | | }}} dt        t        |             v rddlm}m	}m
}  |d      }n5t        j                  t        j                  }}t        j                  d      } ||        ||       ||      }}} ||        ||       ||      }}}||z  ||z  }}||z  ||z  }}|rh||||f<   ||z  |||	f<   ||z  |||
f<   ||z  ||	|f<   | |z  |z   ||	|	f<   | |z  |z
  ||	|
f<   | |z  ||
|f<   ||z  |z   ||
|	f<   ||z  |z
  ||
|
f<   |S ||z  |||f<   ||z  |z
  |||	f<   ||z  |z   |||
f<   ||z  ||	|f<   ||z  |z   ||	|	f<   ||z  |z
  ||	|
f<   | ||
|f<   ||z  ||
|	f<   ||z  ||
|
f<   |S # t        t        f$ r t        |    |\  }}}}Y w xY w)av  Return homogeneous rotation matrix from Euler angles and axis sequence.

    ai, aj, ak : Euler's roll, pitch and yaw angles
    axes : One of 24 axis sequences as string or encoded tuple

    >>> R = euler_matrix(1, 2, 3, 'syxz')
    >>> np.allclose(np.sum(R[0]), -1.34786452)
    True
    >>> R = euler_matrix(1, 2, 3, (0, 1, 0, 1))
    >>> np.allclose(np.sum(R[0]), -0.383436184)
    True
    >>> ai, aj, ak = (4*np.pi) * (np.random.random(3) - 0.5)
    >>> for axes in _AXES2TUPLE.keys():
    ...    R = euler_matrix(ai, aj, ak, axes)
    >>> for axes in _TUPLE2AXES.keys():
    ...    R = euler_matrix(ai, aj, ak, axes)

    r   r   r   )rG   r   rF   r	   )_AXES2TUPLEAttributeErrorKeyError_TUPLE2AXES
_NEXT_AXISr   r   r   rG   r   rF   r   )aiajakaxes	firstaxisparity
repetitionframerA   jkrG   r   rF   r   sisjskcicjckcccsscsss                            r   r   r   T  s   &4/:4/@,	6:u
 	A1v:A1v:>"ARBS2#sB#d2h- 	('F66266SFF1IR#b'3r7BBR#b'3r7BB"Wb2gB"Wb2gB!Q$r'!Q$r'!Q$r'!Q$#(R-!Q$#(R-!Q$#(!Q$r'B,!Q$r'B,!Q$ H r'!Q$r'B,!Q$r'B,!Q$r'!Q$r'B,!Q$r'B,!Q$#!Q$r'!Q$r'!Q$Ha H% 4D/3,	6:u4s   F0 0GGc                    	 t         |j                            \  }}}}|}t
        ||z      }t
        ||z
  dz      }t        j                  | t        j                        ddddf   }	|rt        j                  |	||f   |	||f   z  |	||f   |	||f   z  z         }
|
t        kD  r^t        j                  |	||f   |	||f         }t        j                  |
|	||f         }t        j                  |	||f   |	||f          }nt        j                  |	||f    |	||f         }t        j                  |
|	||f         }d}nt        j                  |	||f   |	||f   z  |	||f   |	||f   z  z         }|t        kD  r]t        j                  |	||f   |	||f         }t        j                  |	||f    |      }t        j                  |	||f   |	||f         }n?t        j                  |	||f    |	||f         }t        j                  |	||f    |      }d}|r	| | | }}}|r||}}|||fS # t        t        f$ r t        |    |\  }}}}Y 4w xY w)a  Return Euler angles from rotation matrix for specified axis sequence.

    axes : One of 24 axis sequences as string or encoded tuple

    Note that many Euler angle triplets can describe one matrix.

    >>> R0 = euler_matrix(1, 2, 3, 'syxz')
    >>> al, be, ga = euler_from_matrix(R0, 'syxz')
    >>> R1 = euler_matrix(al, be, ga, 'syxz')
    >>> np.allclose(R0, R1)
    True
    >>> angles = (4*np.pi) * (np.random.random(3) - 0.5)
    >>> for axes in _AXES2TUPLE.keys():
    ...    R0 = euler_matrix(axes=axes, *angles)
    ...    R1 = euler_matrix(axes=axes, *euler_from_matrix(R0, axes))
    ...    if not np.allclose(R0, R1): print(axes, "failed")

    r   r1   Nr"   rD   )r   lowerr   r   r   r   r   r#   r7   r   rv   rW   )r&   r   r   r   r   r   rA   r   r   r   syaxayazcys                  r   euler_from_matrixr     s   &4/:4::</H,	6:u
 	A1v:A1v:>"A


6,RaR!V4AWWQq!tWqAw&1a41QT7)::;9AadGQq!tW-BB!Q$(BAadGa1gX.BQq!tWHa1g.BB!Q$(BBWWQq!tWqAw&1a41QT7)::;9AadGQq!tW-BQq!tWHb)BAadGQq!tW-BQq!tWHa1g.BQq!tWHb)BBS2#sBRBr2:E H% 4D/3,	6:u4s   H0 0IIc                 ,    t        t        |       |      S )zReturn Euler angles from quaternion for specified axis sequence.

    >>> angles = euler_from_quaternion([0.99810947, 0.06146124, 0, 0])
    >>> np.allclose(angles, [0.123, 0, 0])
    True

    )r   r   )
quaternionr   s     r   euler_from_quaternionr     s     .z:DAAr   c                 F   	 t         |j                            \  }}}}|dz   }t
        ||z   dz
     dz   }	t
        ||z
     dz   }
|r|| }} |r| }| dz  } |dz  }|dz  }t        j                  |       }t        j                  |       }t        j                  |      }t        j                  |      }t        j                  |      }t        j                  |      }||z  }||z  }||z  }||z  }t        j                  d      }|r-|||z
  z  |d<   |||z   z  ||<   |||z   z  ||	<   |||z
  z  ||
<   n8||z  ||z  z   |d<   ||z  ||z  z
  ||<   ||z  ||z  z   ||	<   ||z  ||z  z
  ||
<   |r||	xx   dz  cc<   |S # t        t        f$ r t        |    |\  }}}}Y w xY w)a/  Return quaternion from Euler angles and axis sequence.

    ai, aj, ak : Euler's roll, pitch and yaw angles
    axes : One of 24 axis sequences as string or encoded tuple

    >>> q = quaternion_from_euler(1, 2, 3, 'ryxz')
    >>> np.allclose(q, [0.435953, 0.310622, -0.718287, 0.444435])
    True

    r   r)   r	   r   rt   )
r   r   r   r   r   r   r   rG   rF   r   )r   r   r   r   r   r   r   r   rA   r   r   r   r   r   r   r   r   r   r   r   r   r   s                         r   quaternion_from_eulerr     s   4/:4::</H,	6:u
 	AA1v:>"Q&A1v:"ARBS#IB#IB#IB	B	B	B	B	B	B	bB	bB	bB	bB
AR"W~!R"W~!R"W~!R"W~!Bwb !Bwb !Bwb !Bwb !	!HS H% 4D/3,	6:u4s   E= =F F c                     t        j                  d|d   |d   |d   g      }t        |      }|t        kD  r|t        j                  | dz        |z  z  }t        j
                  | dz        |d<   |S )zReturn quaternion for rotation about axis.

    >>> q = quaternion_about_axis(0.123, [1, 0, 0])
    >>> np.allclose(q, [0.99810947, 0.06146124, 0, 0])
    True

    rD   r   r   rE   r)   )r   rI   rd   rv   rF   rG   )rK   r   r   qlens       r   quaternion_about_axisr    sn     	#tAwQa12Aq>Dd{	RVVECK 4''66%#+AaDHr   c           	          t        j                  | t         j                        j                  d      }t        j                  d||      }t        |      }|t        k  }|| ddfxx   t        j                  d|| df   z        z  cc<   t        j                  d||      }t        j                  |ddf      }d|ddd	d	f   z
  |ddd
d
f   z
  |ddddf<   |dddd	f   |ddd
df   z
  |ddddf<   |dddd
f   |ddd	df   z   |dddd	f<   |dddd	f   |ddd
df   z   |ddddf<   d|ddddf   z
  |ddd
d
f   z
  |ddddf<   |ddd	d
f   |ddddf   z
  |dddd	f<   |dddd
f   |ddd	df   z
  |ddd	df<   |ddd	d
f   |ddddf   z   |ddd	df<   d|ddddf   z
  |ddd	d	f   z
  |ddd	d	f<   d|ddd
d
f<   t        j                  d      d   ||<   |j                         S )a  
    Return a homogeneous rotation matrix from quaternion.

    >>> M = quaternion_matrix([0.99810947, 0.06146124, 0, 0])
    >>> np.allclose(M, rotation_matrix(0.123, [1, 0, 0]))
    True
    >>> M = quaternion_matrix([1, 0, 0, 0])
    >>> np.allclose(M, np.identity(4))
    True
    >>> M = quaternion_matrix([0, 1, 0, 0])
    >>> np.allclose(M, np.diag([1, -1, -1, 1]))
    True
    >>> M = quaternion_matrix([[1, 0, 0, 0],[0, 1, 0, 0]])
    >>> np.allclose(M, np.array([np.identity(4), np.diag([1, -1, -1, 1])]))
    True


    r1   )r6   r	   zij,ij->iNr)   z
ij,ik->ikjr	   r3   rE   r"   r   r   )N.)r   rI   r7   r   einsumr   rv   r   r   r   r>   )r   r   r   num_qs
identitiesrets         r   r   r   *  sI   & 	2::.66w?A
		*a#AVFTJzk1nq*d):';!;<<
		,1%A ((FAq>
"C 1a7#a1aj0C1aLQ1W:!Q'
*C1aLQ1W:!Q'
*C1aLQ1W:!Q'
*C1aL1a7#a1aj0C1aLQ1W:!Q'
*C1aLQ1W:!Q'
*C1aLQ1W:!Q'
*C1aL1a7#a1aj0C1aLC1aLffQi	*C
O;;=r   c           
      D   t        j                  | t         j                        ddddf   }|rt        j                  d      }t        j                  |      }||d   kD  r0||d<   |d   |d   z
  |d	<   |d
   |d   z
  |d<   |d   |d   z
  |d<   nd\  }}}|d   |d   kD  rd\  }}}|d   |||f   kD  rd\  }}}|||f   |||f   |||f   z   z
  |d   z   }|||<   |||f   |||f   z   ||<   |||f   |||f   z   ||<   |||f   |||f   z
  |d	<   |g d   }|dt        j
                  ||d   z        z  z  }n|d   }|d   }	|d
   }
|d   }|d   }|d   }|d   }|d   }|d   }t        j                  ||z
  |z
  dddg|	|z   ||z
  |z
  ddg|
|z   ||z   ||z
  |z
  dg||z
  |
|z
  ||	z
  ||z   |z   gg      }|dz  }t         j                  j                  |      \  }}|g dt        j                  |      f   }|d   dk  rt        j                  ||       |S )a   Return quaternion from rotation matrix.

    If isprecise is True, the input matrix is assumed to be a precise rotation
    matrix and a faster algorithm is used.

    >>> q = quaternion_from_matrix(np.identity(4), True)
    >>> np.allclose(q, [1, 0, 0, 0])
    True
    >>> q = quaternion_from_matrix(np.diag([1, -1, -1, 1]))
    >>> np.allclose(q, [0, 1, 0, 0]) or np.allclose(q, [0, -1, 0, 0])
    True
    >>> R = rotation_matrix(0.123, (1, 2, 3))
    >>> q = quaternion_from_matrix(R, True)
    >>> np.allclose(q, [0.9981095, 0.0164262, 0.0328524, 0.0492786])
    True
    >>> R = [[-0.545, 0.797, 0.260, 0], [0.733, 0.603, -0.313, 0],
    ...      [-0.407, 0.021, -0.913, 0], [0, 0, 0, 1]]
    >>> q = quaternion_from_matrix(R)
    >>> np.allclose(q, [0.19069, 0.43736, 0.87485, -0.083611])
    True
    >>> R = [[0.395, 0.362, 0.843, 0], [-0.626, 0.796, -0.056, 0],
    ...      [-0.677, -0.498, 0.529, 0], [0, 0, 0, 1]]
    >>> q = quaternion_from_matrix(R)
    >>> np.allclose(q, [0.82336615, -0.13610694, 0.46344705, -0.29792603])
    True
    >>> R = random_rotation_matrix()
    >>> q = quaternion_from_matrix(R)
    >>> is_same_transform(R, quaternion_matrix(q))
    True
    >>> is_same_quaternion(quaternion_from_matrix(R, isprecise=False),
    ...                    quaternion_from_matrix(R, isprecise=True))
    True
    >>> R = euler_matrix(0.0, 0.0, np.pi/2.0)
    >>> is_same_quaternion(quaternion_from_matrix(R, isprecise=False),
    ...                    quaternion_from_matrix(R, isprecise=True))
    True

    r1   Nr	   r   rl   r   rR   r   r"   rS   )rE   r   rE   rT   r   r   )r   r   rE   rj   ri   )r   rE   r   rk   )rE   r   r   )r"   r   r   rE         ?rD   rb   )r   r#   r7   r   rV   r   rI   r8   r   r   r   )r&   	ispreciser   r   r}   rA   r   r   m00m01m02m10m11m12m20m21m22Kr?   r@   s                       r   quaternion_from_matrixr  Y  s   N 	

6,RaR!V4AHHTNHHQKqw;AaDT7QtW$AaDT7QtW$AaDT7QtW$AaDGAq!w4 !1aw1a4 !1a!Q$1QT7Qq!tW,-$7AAaDQT7Qq!tW$AaDQT7Qq!tW$AaDQT7Qq!tW$AaD,A	S2771qw;'''gggggggggHHsS#sC0sC#IOS#6sC#IsSy3<sC#IsSy#)c/B	
 	
Syy~~a 1lBIIaL()tcz
AqHr   c                    |\  }}}}| \  }}}}	t        j                  | |z  ||z  z
  |	|z  z
  ||z  z   ||z  ||z  z   |	|z  z
  ||z  z   | |z  ||z  z   |	|z  z   ||z  z   ||z  ||z  z
  |	|z  z   ||z  z   gt         j                        S )zReturn multiplication of two quaternions.

    >>> q = quaternion_multiply([4, 1, -2, 3], [8, -5, 6, 7])
    >>> np.allclose(q, [28, -44, -14, 48])
    True

    r1   r   rI   r7   )
quaternion1quaternion0w0x0y0z0w1x1y1z1s
             r   quaternion_multiplyr"    s     !NBB NBB88C"HrBwb(272Gb2gR'"r'1C"HrBwb(272Gb2gR'"r'1		
 jj r   c                     t        j                  | t         j                        }t        j                  |dd |dd        |S )zReturn conjugate of quaternion.

    >>> q0 = random_quaternion()
    >>> q1 = quaternion_conjugate(q0)
    >>> q1[0] == q0[0] and all(q1[1:] == -q0[1:])
    True

    r1   r   N)r   rI   r7   r   r   r   s     r   quaternion_conjugater%    s7     	2::.AKK!"quHr   c                     t        j                  | t         j                        }t        j                  |dd |dd        |t        j                  ||      z  S )zReturn inverse of quaternion.

    >>> q0 = random_quaternion()
    >>> q1 = quaternion_inverse(q0)
    >>> np.allclose(quaternion_multiply(q0, q1), [1, 0, 0, 0])
    True

    r1   r   N)r   rI   r7   r   r,   r$  s     r   quaternion_inverser'    sG     	2::.AKK!"qurvva|r   c                     t        | d         S )zTReturn real part of quaternion.

    >>> quaternion_real([3, 0, 1, 2])
    3.0

    r   )floatr   s    r   quaternion_realr+    s     Ar   c                 R    t        j                  | dd t         j                        S )ziReturn imaginary part of quaternion.

    >>> quaternion_imag([3, 0, 1, 2])
    array([0., 1., 2.])

    r   r	   r1   r  r*  s    r   quaternion_imagr-    s     88JqO2::66r   c                 8   t        | dd       }t        |dd       }|dk(  r|S |dk(  r|S t        j                  ||      }t        t        |      dz
        t        k  r|S |r|dk  r| }t        j
                  ||       t        j                  |      |t        j                  z  z   }t        |      t        k  r|S dt        j                  |      z  }	|t        j                  d|z
  |z        |	z  z  }|t        j                  ||z        |	z  z  }||z  }|S )a  Return spherical linear interpolation between two quaternions.

    >>> q0 = random_quaternion()
    >>> q1 = random_quaternion()
    >>> q = quaternion_slerp(q0, q1, 0)
    >>> np.allclose(q, q0)
    True
    >>> q = quaternion_slerp(q0, q1, 1, 1)
    >>> np.allclose(q, q1)
    True
    >>> q = quaternion_slerp(q0, q1, 0.5)
    >>> angle = np.arccos(np.dot(q0, q))
    >>> np.allclose(2, np.arccos(np.dot(q0, q1)) / angle) or         np.allclose(2, np.arccos(-np.dot(q0, q1)) / angle)
    True

    Nr	   rD   r3   )	r*   r   r,   r;   rv   r   arccospirF   )
quat0quat1fractionspinshortestpathq0q1drK   isins
             r   quaternion_slerpr:    s   $ 
U2AY	B	U2AY	B3		S	
r2A
3q6C<4	CB
BIIaL4"%%<'E
5zD	D"&&#.E)
*T
11B"&&E!
"T
))B"HBIr   c                 P   | 2t         j                  j                  d|z        j                  d      } n| j                  d   dk(  sJ t        j
                  d| d   z
        }t        j
                  | d         }t         j                  dz  }|| d   z  }|| d   z  }t        j                  t        j                  |      |z  t        j                  |      |z  t        j                  |      |z  t        j                  |      |z  g      j                  j                         S )a  Return uniform random unit quaternion.

    rand: array like or None
        Three independent random variables that are uniformly distributed
        between 0 and 1.

    >>> q = random_quaternion()
    >>> np.allclose(1, vector_norm(q))
    True
    >>> q = random_quaternion(num=10)
    >>> np.allclose(1, vector_norm(q, axis=1))
    True
    >>> q = random_quaternion(np.random.random(3))
    >>> len(q.shape), q.shape[0]==4
    (1, True)

    r"   )r"   r6   r   r3   r)   r   rE   )r   randomrandr   r   r   r0  rI   rG   rF   rU   r>   )r=  numr1r2pi2r   t2s          r   random_quaternionrC     s    $ |yy~~a#g&..w7zz!}!!!	tAw	B	a	B
%%#+C	tAwB	tAwB88	b"&&*r/266":?BFF2JOLa	r   r=  r>  r   c                     t        t        | |            }|r5t        j                  j                  d      dz
  t	        |      z  |dddf<   |S )a  
    Return uniform random rotation matrix.

    Parameters
    ------------
    rand : (3,)
      Three independent random variables that are uniformly distributed
      between 0 and 1 for each returned quaternion.
    num
      Number of matrices to return.
    translate
      If passed the rotation matrix will include translation
      that is random and between positive and negative half this value.

    >>> R = random_rotation_matrix()
    >>> np.allclose(np.dot(R.T, R), np.identity(4))
    True
    >>> R = random_rotation_matrix(num=10)
    >>> np.allclose(np.einsum('...ji,...jk->...ik', R, R), np.identity(4))
    True

    )r=  r>  r"   r	  N)r   rC  r   r<  r)  )r=  r>  r   r&   s       r   random_rotation_matrixrE  @  sM    2 0dDEF))!,s2eI6FFrr1uMr   c                   r    e Zd ZdZddZd Zd Zed        Zej                  d        Zd Z
d	 Zdd
Zd Zy)ArcballaO  Virtual Trackball Control.

    >>> ball = Arcball()
    >>> ball = Arcball(initial=np.identity(4))
    >>> ball.place([320, 320], 320)
    >>> ball.down([500, 250])
    >>> ball.drag([475, 275])
    >>> R = ball.matrix()
    >>> np.allclose(np.sum(R), 3.90583455)
    True
    >>> ball = Arcball(initial=[1, 0, 0, 0])
    >>> ball.place([320, 320], 320)
    >>> ball.setaxes([1, 1, 0], [-1, 1, 0])
    >>> ball.constrain = True
    >>> ball.down([400, 200])
    >>> ball.drag([200, 400])
    >>> R = ball.matrix()
    >>> np.allclose(np.sum(R), 0.2055924)
    True
    >>> ball.next()

    Nc                    d| _         d| _        d| _        ddg| _        t	        j
                  g d      | _        d| _        |t	        j
                  g d      | _        nut	        j
                  |t        j                        }|j                  dk(  rt        |      | _        n0|j                  d	k(  r|t        |      z  }|| _        nt        d
      | j                  x| _        | _        y)z`Initialize virtual trackball control.

        initial : quaternion or rotation matrix

        Nr3   rD   )rD   rD   r3   F)r3   rD   rD   rD   r1   r	   r	   r   z"initial not a quaternion or matrix)_axis_axes_radius_centerr   rI   _vdown
_constrain_qdownr7   r   r  rd   r=   _qnow_qpre)selfinitials     r   __init__zArcball.__init__y  s     

Szhh/?((#78DKhhwbjj9G}}&4W=$&;w//% !EFF"&++-
TZr   c                 l    t        |      | _        |d   | j                  d<   |d   | j                  d<   y)zPlace Arcball, e.g. when window size changes.

        center : sequence[2]
            Window coordinates of trackball center.
        radius : float
            Radius of trackball in window coordinates.

        r   r   N)r)  rL  rM  )rS  centerradiuss      r   placezArcball.place  s1     V} )Q )Qr   c                 ^    |d| _         y|D cg c]  }t        |       c}| _         yc c}w )z Set axes to constrain rotations.N)rK  r*   )rS  r   r   s      r   setaxeszArcball.setaxes  s(    <DJ8<=+d+=DJ=s   *c                     | j                   S )z'Return state of constrain to axis mode.)rO  rS  s    r   	constrainzArcball.constrain  s     r   c                 $    t        |      | _        y)z$Set state of constrain to axis mode.N)boolrO  )rS  values     r   r^  zArcball.constrain  s     u+r   c                 T   t        || j                  | j                        | _        | j                  x| _        | _        | j                  rW| j                  Kt        | j                  | j                        | _
        t        | j                  | j                        | _        yd| _
        y)z>Set initial cursor window coordinates and pick constrain-axis.N)arcball_map_to_sphererM  rL  rN  rQ  rP  rR  rO  rK  arcball_nearest_axisrJ  arcball_constrain_to_axis)rS  r-   s     r   downzArcball.down  so    +E4<<N#'::-dj??tzz5-dkk4::FDJ3DKKLDKDJr   c                    t        || j                  | j                        }| j                  t	        || j                        }| j
                  | _        t        j                  | j                  |      }t        j                  ||      t        k  r| j                  | _        yt        j                  | j                  |      |d   |d   |d   g}t        || j                        | _        y)z)Update current cursor window coordinates.Nr   r   rE   )rc  rM  rL  rJ  re  rQ  rR  r   r   rN  r,   rv   rP  r"  )rS  r-   vnowr}   r   s        r   dragzArcball.drag  s    $UDLL$,,G::!,T4::>DZZ
HHT[[$'66!Q<$DJT*AaD!A$!=A,Q<DJr   c                     t        | j                  | j                  d|z   d      }| j                  |c| _        | _        y)z,Continue rotation in direction of last drag.r)   FN)r:  rR  rQ  )rS  accelerationr   s      r   nextzArcball.next  s3    TZZS<5GO!%Q
DJr   c                 ,    t        | j                        S )z#Return homogeneous rotation matrix.)r   rQ  r]  s    r   r&   zArcball.matrix  s     ,,r   Nr   )__name__
__module____qualname____doc__rU  rY  r[  propertyr^  setterrf  ri  rl  r&   r   r   r   rG  rG  a  sX    ..2$>   & &=/
-r   rG  c                    | d   |d   z
  |z  }|d   | d   z
  |z  }||z  ||z  z   }|dkD  r3t        j                  |      }t        j                  ||z  ||z  dg      S t        j                  ||t        j                  d|z
        g      S )z7Return unit sphere coordinates from window coordinates.r   r   r3   rD   )r   r   rI   )r-   rW  rX  r   r   r   s         r   rc  rc    s    
(VAY
&	(B
)eAh
&	(B
R"r'A3wGGAJxxaa-..xxRq!1233r   c                    t        j                  | t         j                        }t        j                  |t         j                        }||t        j                  ||      z  z  }t	        |      }|t
        kD  r%|d   dk  rt        j                  ||       ||z  }|S |d   dk(  rt        j                  g d      S t        |d    |d   dg      S )z*Return sphere point perpendicular to axis.r1   rE   rD   r3   )r3   rD   rD   r   r   )r   rI   r7   r,   rd   rv   r   r*   )r-   r   r   r   r   s        r   re  re    s    
bjj)A
RZZ(ARVVAq\	AAA4xQ4#:KK1	Qts{xx((1qtS)**r   c                     t        j                  | t         j                        } d}d}|D ],  }t        j                  t	        | |      |       }||kD  s)|}|}. |S )z+Return axis, which arc is nearest to point.r1   Nrt   )r   r#   r7   r,   re  )r-   r   nearestmxr   r}   s         r   rd  rd    s_    JJuBJJ/EG	B FF,UD95Ar6GB	
 Nr   g      @)r   rE   r   r   )r   r   r   r   sxyx)r   r   r   r   sxzy)r   r   r   r   sxzx)r   r   r   r   syzx)r   r   r   r   syzy)r   r   r   r   syxz)r   r   r   r   syxy)r   r   r   r   szxy)rE   r   r   r   szxz)rE   r   r   r   szyx)rE   r   r   r   szyz)rE   r   r   r   rzyxr   r   r   r   rxyx)r   r   r   r   ryzx)r   r   r   r   rxzx)r   r   r   r   rxzy)r   r   r   r   )r   r   r   r   )r   r   r   r   )r   r   r   r   )rE   r   r   r   )rE   r   r   r   )rE   r   r   r   )rE   r   r   r   )ryzyrzxyryxyryxzrzxzrxyzrzyzc                    t        j                  | t         j                        } || j                  dk(  r)t        j                  t        j
                  | |             S | | z  } t        j                  t        j                  | |            }t        j                  ||       |S | | z  } t        j                  | ||       t        j                  ||       y)a  Return length, i.e. Euclidean norm, of ndarray along axis.

    >>> v = np.random.random(3)
    >>> n = vector_norm(v)
    >>> np.allclose(n, np.linalg.norm(v))
    True
    >>> v = np.random.rand(6, 5, 3)
    >>> n = vector_norm(v, axis=-1)
    >>> np.allclose(n, np.sqrt(np.sum(v*v, axis=2)))
    True
    >>> n = vector_norm(v, axis=1)
    >>> np.allclose(n, np.sqrt(np.sum(v*v, axis=1)))
    True
    >>> v = np.random.rand(5, 4, 3)
    >>> n = np.zeros((5, 3))
    >>> vector_norm(v, axis=1, out=n)
    >>> np.allclose(n, np.sqrt(np.sum(v*v, axis=1)))
    True
    >>> float(vector_norm([]))
    0.0
    >>> float(vector_norm([1]))
    1.0

    r1   Nr   r   )r   out)r   rI   r7   ndimr   r,   
atleast_1dr   )datar   r  s      r   rd   rd      s    2 88D

+D
{99>77266$-..mmBFF4d34
S

t$C(
Sr   c                    |bt        j                  | t         j                        } | j                  dk(  rL| t        j                  t        j
                  | |             z  } | S || urt        j                  |       |dd |} t        j                  t        j                  | | z  |            }t        j                  ||       |t        j                  ||      }| |z  } || S y)a  Return ndarray normalized by length, i.e. Euclidean norm, along axis.

    >>> v0 = np.random.random(3)
    >>> v1 = unit_vector(v0)
    >>> np.allclose(v1, v0 / np.linalg.norm(v0))
    True
    >>> v0 = np.random.rand(5, 4, 3)
    >>> v1 = unit_vector(v0, axis=-1)
    >>> v2 = v0 / np.expand_dims(np.sqrt(np.sum(v0*v0, axis=2)), 2)
    >>> np.allclose(v1, v2)
    True
    >>> v1 = unit_vector(v0, axis=1)
    >>> v2 = v0 / np.expand_dims(np.sqrt(np.sum(v0*v0, axis=1)), 1)
    >>> np.allclose(v1, v2)
    True
    >>> v1 = np.zeros((5, 4, 3))
    >>> unit_vector(v0, axis=1, out=v1)
    >>> np.allclose(v1, v2)
    True
    >>> list(unit_vector([]))
    []
    >>> [float(i) for i in unit_vector([1])]
    [1.0]

    Nr1   r   )
r   rI   r7   r  r   r,   r#   r  r   expand_dims)r  r   r  lengths       r   r*   r*   G  s    4 {xxBJJ/99>BGGBFF4.//DKd?ZZ%CF]]266$+t45FGGFF-FND
{ r   c                 @    t         j                  j                  |       S )a  Return array of random doubles in the half-open interval [0.0, 1.0).

    >>> v = random_vector(10000)
    >>> bool(np.all(v >= 0) and np.all(v < 1))
    True
    >>> v0 = random_vector(10)
    >>> v1 = random_vector(10)
    >>> bool(np.any(v0 == v1))
    False

    )r   r<  )sizes    r   random_vectorr  s  s     99D!!r   c                 2    t        j                  | ||      S )a?  Return vector perpendicular to vectors.

    >>> v = vector_product([2, 0, 0], [0, 3, 0])
    >>> np.allclose(v, [0, 0, 6])
    True
    >>> v0 = [[2, 0, 0, 2], [0, 2, 0, 2], [0, 0, 2, 2]]
    >>> v1 = [[3], [0], [0]]
    >>> v = vector_product(v0, v1)
    >>> np.allclose(v, [[0, 0, 0, 0], [0, 0, 6, 6], [0, -6, 0, -6]])
    True
    >>> v0 = [[2, 0, 0], [2, 0, 0], [0, 2, 0], [2, 0, 0]]
    >>> v1 = [[0, 3, 0], [0, 0, 3], [0, 0, 3], [3, 3, 3]]
    >>> v = vector_product(v0, v1, axis=1)
    >>> np.allclose(v, [[0, 0, 6], [0, -6, 0], [6, 0, 0], [0, -6, 6]])
    True

    r   )r   r   )r   r   r   s      r   vector_productr    s    $ 88B&&r   c                    t        j                  | t         j                        } t        j                  |t         j                        }t        j                  | |z  |      }|t	        | |      t	        ||      z  z  }t        j
                  |dd      }t        j                  |r|      S t        j                  |            S )a  Return angle between vectors.

    If directed is False, the input vectors are interpreted as undirected axes,
    i.e. the maximum angle is pi/2.

    >>> a = angle_between_vectors([1, -2, 3], [-1, 2, -3])
    >>> np.allclose(a, np.pi)
    True
    >>> a = angle_between_vectors([1, -2, 3], [-1, 2, -3], directed=False)
    >>> np.allclose(a, 0)
    True
    >>> v0 = [[2, 0, 0, 2], [0, 2, 0, 2], [0, 0, 2, 2]]
    >>> v1 = [[3], [0], [0]]
    >>> a = angle_between_vectors(v0, v1)
    >>> np.allclose(a, [0, 1.5708, 1.5708, 0.95532])
    True
    >>> v0 = [[2, 0, 0], [2, 0, 0], [0, 2, 0], [2, 0, 0]]
    >>> v1 = [[0, 3, 0], [0, 0, 3], [0, 0, 3], [3, 3, 3]]
    >>> a = angle_between_vectors(v0, v1, axis=1)
    >>> np.allclose(a, [1.5708, 1.5708, 1.5708, 0.95532])
    True

    r1   r   rt   r3   )r   r#   r7   r   rd   clipr/  fabs)r   r   directedr   r,   s        r   angle_between_vectorsr    s    0 
Bbjj	)B	Bbjj	)B
&&bt
$C;r%BT(BBBC ''#tS
!C99HS77"''#,77r   c                 @    t         j                  j                  |       S )ah  Return inverse of square transformation matrix.

    >>> M0 = random_rotation_matrix()
    >>> M1 = inverse_matrix(M0.T)
    >>> np.allclose(M1, np.linalg.inv(M0.T))
    True
    >>> for size in range(1, 7):
    ...     M0 = np.random.rand(size, size)
    ...     M1 = inverse_matrix(M0)
    ...     if not np.allclose(M1, np.linalg.inv(M0)): print(size)

    )r   r8   r   r%   s    r   inverse_matrixr    s     99==  r   c                  j    t        j                  d      }| D ]  }t        j                  ||      } |S )zReturn concatenation of series of transformation matrices.

    >>> M = np.random.rand(16).reshape((4, 4)) - 0.5
    >>> np.allclose(M, concatenate_matrices(M))
    True
    >>> np.allclose(np.dot(M, M.T), concatenate_matrices(M, M.T))
    True

    r	   )r   r   r,   )matricesr   rA   s      r   concatenate_matricesr    s4     	AA FF1aLHr   c                     t        j                  | t         j                        } | | d   z  } t        j                  |t         j                        }||d   z  }t        j                  | |      S )zReturn True if two matrices perform same transformation.

    >>> is_same_transform(np.identity(4), np.identity(4))
    True
    >>> is_same_transform(np.identity(4), random_rotation_matrix())
    False

    r1   rl   )r   rI   r7   allclose)matrix0matrix1s     r   is_same_transformr    sY     hhwbjj1Gwt}Ghhwbjj1Gwt}G;;w((r   c                     t        j                  |       } t        j                  |      }t        j                  | |      xs t        j                  | |       S )z)Return True if two quaternions are equal.)r   rI   r  )r6  r7  s     r   is_same_quaternionr    s?    	"B	"B;;r26"++b2#"66r   c                 b   t        j                  |      }t        j                  |       } t        |      }| j                  |dz   |dz   fk7  rt	        d      t        j
                  |dz         }| |d||f<   t        j                  | |      }||d||f<   t        j                  ||      }|S )a#  
    Given a transformation matrix, apply its rotation
    around a point in space.

    Parameters
    ----------
    matrix: (4,4) or (3, 3) float, transformation matrix
    point:  (3,) or (2,)  float, point in space

    Returns
    ---------
    result: (4,4) transformation matrix
    r   zmatrix must be (d+1, d+1)N)r   
asanyarrayr   r   r=   r   r,   )r&   r-   r   r   results        r   transform_aroundr    s     MM% E]]6"F
e*C||aq))455sQwI!6IdsdCiVVFI&F IdsdCiVVIv&FMr   c                 j   | ddg} |d}t        j                  | t         j                        } t        |      }t        j                  |      st        d      | j                  dk7  rt        d      t        j                  dt         j                        }t        j                  |      }t        j                  |      }||g|ddd	f<   | |g|d
dd	f<   | |dd	d	f<   |t        ||      }|>t        j                  d      }|dd	dd	fxx   |z  cc<   t        j                  ||      }|S )au  
    2D homogeonous transformation matrix.

    Parameters
    ----------
    offset : (2,) float
      XY offset
    theta : float
      Rotation around Z in radians
    point :  (2, ) float
      Point to rotate around
    scale : (2,) float or None
      Scale to apply

    Returns
    ----------
    matrix : (3, 3) flat
      Homogeneous 2D transformation matrix
    NrD   r1   ztheta must be finite angle!)rE   zoffset must be length 2!r"   r   rE   r   )r&   r-   )r   r  r7   r)  isfiniter=   r   r   rF   rG   r  r,   )offsetthetar-   ro   rU   r   r   r   s           r   planar_matrixr    s'   ( ~s}]]64F%LE;;u677||t344
q

#A
uA
uA1vAa!eHAwAa!eHAbqb!eHAU3FF1I	"1"bqb&	U	FF1aLHr   c                     t        j                  | t         j                        } | j                  dk7  rt	        d      t        j
                  d      }| dddf   |dddf<   | ddddf   |ddddf<   |S )a+  
    Given a 2D homogeneous rotation matrix convert it to a 3D rotation
    matrix that is rotating around the Z axis

    Parameters
    ----------
    matrix_2D: (3,3) float, homogeneous 2D rotation matrix

    Returns
    ----------
    matrix_3D: (4,4) float, homogeneous 3D rotation matrix
    r1   rl   z.Homogeneous 2D transformation matrix required!r	   NrE   r"   )r   r  r7   r   r=   r   )	matrix_2D	matrix_3Ds     r   planar_matrix_to_3Dr  ?  s     irzz:I& IJJq	I !Q'Ibqb!e!"1"bqb&)Ibqb"1"fr   c                 $    t        d|| |      }|S )a  
    Give a spherical coordinate vector, find the rotation that will
    transform a [0,0,1] vector to those coordinates

    Parameters
    -----------
    theta: float, rotation angle in radians
    phi:   float, rotation angle in radians

    Returns
    ----------
    matrix: (4,4) rotation matrix where the following will
             be a cartesian vector in the direction of the
             input spherical coordinates:
                np.dot(matrix, [0,0,1,0])

    rD   )r   )r   )r  phir   r  s       r   spherical_matrixr  Z  s    $ #sE5FMr   pointsr&   returnc                    t        j                  | t         j                        } t        |       dk(  s|| j	                         S t        j                  |t         j                        }| j
                  \  }}t        j                  |t        d|dz   d|dz   f   z
        j                         dk  r#t        j                  | j	                               S |r]t        j                  | t        j                  |      f      }t        j                  ||j                        j                  ddd|f   S t        j                  |d|d|f   | j                        j                  S )a  
    Returns points rotated by a homogeneous
    transformation matrix.

    If points are (n, 2) matrix must be (3, 3)
    If points are (n, 3) matrix must be (4, 4)

    Parameters
    ----------
    points : (n, dim) float
      Points where `dim` is 2 or 3.
    matrix : (3, 3) or (4, 4) float
      Homogeneous rotation matrix.
    translate : bool
      Apply translation from matrix or not.

    Returns
    ----------
    transformed : (n, dim) float
      Transformed points.
    r1   r   Nr   r4   )r   r  r7   r   r$   r   r;   	_IDENTITYmaxascontiguousarraycolumn_stackonesr,   rU   )r  r&   r   countr   stacks         r   transform_pointsr  p  s   0 ]]64F
6{a6>{{} ]]64FJE3 
vvfy37IcAgI!5667;;=D##FKKM22 89vvfegg&((DSD11 66&#tt$fhh/111r   c           	      "   | j                   d   dz
  }t        j                  t        j                  | d|d|f   | d|d|f   j                        t
        d|d|f   z
        j                         }|dkD  r||k  rt        j                  j                  | d|d|f         \  }}}t        j                  |dz         }t        j                  ||      |d|d|f<   | d||f   |d||f<   t        j                  || |      sJ |S | S )a  
    If a homogeneous transformation matrix is *almost* a rigid
    transform but many matrix-multiplies have accumulated some
    floating point error try to restore the matrix using SVD.

    Parameters
    -----------
    matrix : (4, 4) or (3, 3) float
      Homogeneous transformation matrix.
    max_deviance : float
      Do not alter the matrix if it is not rigid by more
      than this amount.

    Returns
    ----------
    repaired : (4, 4) or (3, 3) float
      Repaired homogeneous transformation matrix
    r   r   NgvIh%<=)atol)r   r   r;   r,   rU   r  r  r8   r   r   r  )r&   max_deviancer   checkUr   r@   repaireds           r   	fix_rigidr    s#   & ,,q/A
CFF
vdsdDSDj!6$3$*#5#7#789TcT4C4Z;PP	ce 

 u}-))--ttTcTz 231a66#'?!vva|#tt$TcT3Y/#s{{8V,???Mr   c                 b   t        j                  | t         j                        } | j                  dk7  ryt        j                  | d   g dz
        |kD  ryt        j
                  | ddddf   | ddddf   j                        t        ddddf   z
  }t        j                  |      |k  S )a7  
    Check to make sure a homogeonous transformation
    matrix is a rigid transform.

    Parameters
    -----------
    matrix : (4, 4) float
      A transformation matrix

    Returns
    -----------
    check : bool
      True if matrix is a a transform with
      only translation, scale, and rotation
    r1   rI  Fr6   r  Nr"   )r   r  r7   r   ptpr,   rU   r  )r&   epsilonr  s      r   is_rigidr    s    " ]]64F||v 
vvfRj<'(72 FF6"1"bqb&>6"1"bqb&>#3#34y!RaR7HHE66%=7""r   c                     t        j                  d      }t        j                  | dk7        r|ddddfxx   | z  cc<   |	||dddf<   |S )a  
    Optimized version of `compose_matrix` for just
    scaling then translating.

    Scalar args are broadcast to arrays of shape (3,)

    Parameters
    --------------
    scale : float or (3,) float
      Scale factor
    translate : float or (3,) float
      Translation
    r	   r   Nr"   )r   r   r   )ro   r   r   s      r   scale_and_translater    sW     	q	A	vveqj	"1"bqb&	U	"1"a%Hr   c                 &   t        j                  | t         j                        } d}t         j                  j                  |dz  df      }t        j                  | ddddf   |j
                        j
                  }t        j                  ||f      j                  d      }t        j                  |d      }t        j                  |dddf   |dddf         }t        j                  | ddddf   |d| j
                        j
                  |d| t        j                  t        j                  ||z  g d            j                  d	      }||z  }t        j                  |d| ||d z  d
gdz        }|j                         dk  }	|	S )a  
    Check to see if a matrix will invert triangles.

    Parameters
    -------------
    matrix : (4, 4) float
      Homogeneous transformation matrix

    Returns
    --------------
    flip : bool
      True if matrix will flip winding of triangles.
    r1   r"   N)r6   r"   r"   r   r   r   )r   r   r   )r6   r   r3   rD   )r   r  r7   r<  r,   rU   r   r   diffr   r   r   )
r&   r  trirot	trianglesvectorsr   norm
projectionflips
             r   flips_windingr    sX    ]]64FE
))

EAIq>
*C
&&BQB
'
)
)C 		3*%--j9Iggia(GHHWQT]GAqDM2EFF6"1"bqb&>5%=??;==E&5M77266%%-34<<WEDDLEfuef5uqyAJ ??s"DKr   rn  )NN)NNF)F)NNNNN)TTT)FT)r   )r   T)Nr   )Nr   N)r   )Tr   )NNNN)T)gh㈵>)r4   )Orr  numpyr   numpy.typingr   r   typedr   r   r   r   r  flagsr   r    r'   r/   rB   rP   r\   r`   rg   rp   rr   r~   r   r   r   r   r   r   r   r   r   r   r   r  r   r  r"  r%  r'  r+  r-  r:  rC  rE  rG  rc  re  rd  finfor)  epsrv   r   r   itemsr   rd   r*   r  r  r  r  r  r  r  r  r  r  r  r`  r7   r  r  r  r  r  )r   r   s   00r   <module>r     s  HaF  + , , BFF1I	$	 8	,4:Nb%#PD&%R9xE8P9x>,+^Q8h1h<hV/VdEP7tB6r ,^Vr* 7&RB W[
9
+2CKFCSBm- m-`
4+ 
 rxxS  

L
L L L	
 L L L L L L L L L L L  L!" L#$ 16 !, 1 1 341q!t4$N)X"'*8D!  ) 7:/d6. =A+2+2(+259+2RZZ+2\$N#@,'} 5s   F/