### Install pyquaternion Source: https://github.com/kieranwynn/pyquaternion/blob/master/README.md Install the pyquaternion library using pip. This command is for general installation. ```bash pip install pyquaternion ``` -------------------------------- ### Quaternion Division Example Source: https://github.com/kieranwynn/pyquaternion/blob/master/docs/index.md Demonstrates quaternion division using the `/` operator. The operation is equivalent to the Hamilton product of the dividend and the inverse of the divisor. Non-Quaternion objects are converted to Quaternions, potentially raising TypeErrors or ValueErrors. ```python >>> my_quaternion / my_quaternion == Quaternion(1.0) True ``` -------------------------------- ### Quaternion Exponentiation Example Source: https://github.com/kieranwynn/pyquaternion/blob/master/docs/index.md Illustrates quaternion exponentiation using the `**` operator for real number exponents. This operation is defined for real exponents `p`. The base must be a Quaternion object. A TypeError is raised if the exponent cannot be interpreted as a real number. ```python >>> one = Quaternion(1, 0, 0, 0) >>> i = Quaternion(0, 1, 0, 0) >>> j = Quaternion(0, 0, 1, 0) >>> k = Quaternion(0, 0, 0, 1) >>> (i ** 2) == (j ** 2) == (k ** 2) == -1 True ``` -------------------------------- ### Get Yaw, Pitch, and Roll (Euler Angles) Source: https://context7.com/kieranwynn/pyquaternion/llms.txt Obtain Tait-Bryan (z-y'-x'') Euler angles in radians from a unit quaternion. Useful for converting complex rotations into intuitive yaw, pitch, and roll components. ```python from pyquaternion import Quaternion import math # Pure yaw of 45 degrees q = Quaternion(axis=[0, 0, 1], degrees=45) yaw, pitch, roll = q.yaw_pitch_roll print(math.degrees(yaw)) # ~45.0 print(math.degrees(pitch)) # ~0.0 print(math.degrees(roll)) # ~0.0 # Combined rotation q2 = Quaternion(axis=[1, 1, 1], degrees=60) yaw2, pitch2, roll2 = q2.yaw_pitch_roll print([round(math.degrees(a), 2) for a in (yaw2, pitch2, roll2)]) ``` -------------------------------- ### Quaternion String Representation (__str__) Source: https://github.com/kieranwynn/pyquaternion/blob/master/docs/index.md Get an informal, nicely printable string representation of the Quaternion object. This is used by the `str()` function and `print()`. ```python >>> str(my_quaternion) '-0.810 +0.022i -0.563j -0.166k' >>> print(my_quaternion) -0.810 +0.022i -0.563j -0.166k ``` -------------------------------- ### Quaternion Interpolation Source: https://github.com/kieranwynn/pyquaternion/blob/master/docs/index.md Generate a sequence of Quaternion objects for smooth interpolation between two orientations. This is useful for animation. The `include_endpoints` argument ensures the start and end quaternions are included in the output. ```python import numpy numpy.set_printoptions(suppress=True) # Suppress insignificant values for clarity v = numpy.array([0., 0., 1.]) # Unit vector in the +z direction q0 = Quaternion(axis=[1, 1, 1], angle=0.0) # Rotate 0 about x=y=z q1 = Quaternion(axis=[1, 1, 1], angle=2 * 3.14159265 / 3) # Rotate 120 about x=y=z for q in Quaternion.intermediates(q0, q1, 8, include_endpoints=True): v_prime = q.rotate(v) print(v_prime) ``` -------------------------------- ### Quaternion Exponentiation and Inverse Source: https://context7.com/kieranwynn/pyquaternion/llms.txt Shows how to perform exponentiation (including fractional and negative powers) and verifies that raising a quaternion to the power of -1 is equivalent to its inverse. ```python from pyquaternion import Quaternion q = Quaternion(axis=[0, 0, 1], degrees=90) print((q ** 2).degrees) # ~180.0 print((q ** 0.5).degrees) # ~45.0 print(q ** -1 == q.inverse) # True ``` -------------------------------- ### Conjugate Source: https://context7.com/kieranwynn/pyquaternion/llms.txt Get the conjugate of a quaternion, which involves negating its vector part. ```APIDOC ## Conjugate ### Description Returns a new quaternion with its vector part negated. For unit quaternions, the conjugate is equivalent to the inverse. ### Attributes - **conjugate** (Quaternion): The conjugate of the quaternion. ``` -------------------------------- ### Basic Quaternion Rotation and Interpolation Source: https://github.com/kieranwynn/pyquaternion/blob/master/README.md Demonstrates creating a quaternion for a 90-degree rotation about the y-axis, rotating a vector, and interpolating between two quaternions. Ensure pyquaternion is imported before use. ```python import pyquaternion # Create a quaternion representing a rotation of +90 degrees about positive y axis. my_quaternion = pyquaternion.Quaternion(axis=[0, 1, 0], degrees=90) my_vector = [0, 0, 4] my_rotated_vector = my_quaternion.rotate(my_vector) print(' Basic Rotation') print('--------------') print('My Vector: {}'.format(my_vector)) print('Performing rotation of {angle} deg about {axis}'.format(angle=my_quaternion.degrees, axis=my_quaternion.axis)) print('My Rotated Vector: {}'.format(my_rotated_vector)) # Create another quaternion representing no rotation at all null_quaternion = pyquaternion.Quaternion(axis=[0, 1, 0], angle=0) print(' Interpolated Rotation') print('---------------------') # The following will create a sequence of 9 intermediate quaternion rotation objects for q in pyquaternion.Quaternion.intermediates(null_quaternion, my_quaternion, 9, include_endpoints=True): my_interpolated_point = q.rotate(my_vector) print('My Interpolated Point: {point} (after rotation of {angle} deg about {axis})'.format( point=my_interpolated_point, angle=round(q.degrees, 4), axis=q.axis )) print('Done!') ``` -------------------------------- ### Get Quaternion Conjugate Source: https://github.com/kieranwynn/pyquaternion/blob/master/docs/index.md Compute the conjugate of a quaternion. For a unit quaternion, this is identical to its inverse. ```python conj_quaternion = my_quaternion.conjugate ``` -------------------------------- ### Get Quaternion Inverse Source: https://github.com/kieranwynn/pyquaternion/blob/master/docs/index.md Compute the inverse of a quaternion. For a unit quaternion, this represents the inverse rotation. ```python inv_quaternion = my_quaternion.inverse ``` -------------------------------- ### Quaternion Norm (Magnitude) Source: https://github.com/kieranwynn/pyquaternion/blob/master/docs/index.md Get the L2 norm (magnitude) of the quaternion's 4-vector. For a unit quaternion, this value should be 1.0. ```APIDOC ## norm or magnitude ### Description L2 norm of the quaternion 4-vector. This should be 1.0 for a unit quaternion (versor). ### Returns a scalar real number representing the square root of the sum of the squares of the elements of the quaternion. ### Usage ```python my_quaternion.norm my_quaternion.magnitude ``` ``` -------------------------------- ### Copy Initialization Source: https://github.com/kieranwynn/pyquaternion/blob/master/docs/index.md Clones another existing Quaternion object. ```APIDOC ## Copy Initialization ### Description Clones another quaternion object. ### Method `Quaternion(other)` ### Parameters #### Path Parameters - **other** (Quaternion) - Required - Another Quaternion instance to be cloned. ### Code Example ```python q2 = Quaternion(q1) ``` ### Raises - `TypeError`: If the provided object is not an instance of Quaternion. ``` -------------------------------- ### str(), repr(), format() Source: https://context7.com/kieranwynn/pyquaternion/llms.txt Provides various methods for string representation of Quaternions, including human-readable, official, and custom formatted strings. ```APIDOC ## String Representation ### Description Quaternions can be represented as strings in multiple ways: - `str(q)`: Provides a human-readable string representation. - `repr(q)`: Provides an official string representation that can be used to recreate the object. - `format(q, format_spec)`: Allows for custom formatting using Python's format specifiers. ### Method `str(q: Quaternion) -> str` `repr(q: Quaternion) -> str` `format(q: Quaternion, format_spec: str) -> str` ### Parameters - **q** (Quaternion) - The quaternion to represent as a string. - **format_spec** (str, optional) - The format specifier string. ### Response - **str** - The string representation of the quaternion. ### Request Example ```python from pyquaternion import Quaternion q = Quaternion(axis=[0, 0, 1], degrees=90) print(str(q)) print(repr(q)) print("{:.6f}".format(q)) ``` ### Response Example ``` 0.707 +0.000i +0.000j +0.707k Quaternion(0.7071067811865476, 0.0, 0.0, 0.7071067811865476) +0.707107 +0.000000i +0.000000j +0.707107k ``` ``` -------------------------------- ### Get Quaternion Conjugate Source: https://context7.com/kieranwynn/pyquaternion/llms.txt Retrieve the conjugate of a quaternion, which has the vector part negated. For unit quaternions, the conjugate is equivalent to the inverse. ```python from pyquaternion import Quaternion q = Quaternion(1, 2, 3, 4) c = q.conjugate print(c) # 1.000 -2.000i -3.000j -4.000k # For unit quaternions, conjugate == inverse q_unit = q.normalised print(q_unit.conjugate == q_unit.inverse) # True ``` -------------------------------- ### Default Initialization Source: https://github.com/kieranwynn/pyquaternion/blob/master/docs/index.md Creates a unit quaternion (1 + 0i + 0j + 0k), representing a null rotation or a unit value for multiplication. ```APIDOC ## Default Initialization ### Description Creates a unit quaternion `1 + 0i + 0j + 0k`, which represents a null rotation and acts as a unit value in quaternion multiplication. ### Method `Quaternion()` ### Code Example ```python q1 = Quaternion() ``` ``` -------------------------------- ### Get Quaternion Norm or Magnitude Source: https://github.com/kieranwynn/pyquaternion/blob/master/docs/index.md Access the L2 norm (magnitude) of the quaternion's 4-element vector. For a unit quaternion, this value should be 1.0. ```python my_quaternion.norm ``` ```python my_quaternion.magnitude ``` -------------------------------- ### Sequence Initialization Source: https://github.com/kieranwynn/pyquaternion/blob/master/docs/index.md Creates a quaternion object from an ordered sequence containing 4 real valued scalar elements. ```APIDOC ## Sequence Initialization ### Description Creates a quaternion object from an ordered sequence containing 4 real valued scalar elements. The sequential elements `a, b, c, d` of the sequence correspond to the real, and each imaginary component respectively in the order `a + bi + cj + dk`. ### Method `Quaternion(seq)` ### Parameters #### Path Parameters - **seq** (list, tuple, generator, or iterable) - Required - An iterable sequence containing 4 values, each convertible to a real number. ### Code Example ```python q7 = Quaternion((a, b, c, d)) // from 4-tuple q7 = Quaternion([a, b, c, d]) // from list of 4 ``` ### Raises - `TypeError`: If any of the sequence contents cannot be converted to a real number. - `ValueError`: If the sequence contains less/more than 4 elements. ``` -------------------------------- ### Quaternion Exponential Map Source: https://github.com/kieranwynn/pyquaternion/blob/master/docs/index.md Computes the Quaternion exponential map on the Riemannian manifold. Finds the endpoint of a geodesic starting at q in the direction of eta. ```APIDOC ### `Quaternion.exp_map(q, eta)` - *class method* #### Description Quaternion exponential map. Find the exponential map on the Riemannian manifold described by the quaternion space. #### Params * `q` - the base point of the exponential map, i.e. a Quaternion object * `eta` - the argument of the exponential map, a tangent vector, i.e. a Quaternion object #### Returns A quaternion p such that p is the endpoint of the geodesic starting at q in the direction of eta, having the length equal to the magnitude of eta. #### Note The exponential map plays an important role in integrating orientation variations (e.g. angular velocities). This is done by projecting quaternion tangent vectors onto the quaternion manifold. ``` -------------------------------- ### Elements Initialization Source: https://github.com/kieranwynn/pyquaternion/blob/master/docs/index.md Creates a quaternion by specifying its four real-numbered scalar elements (w, x, y, z). ```APIDOC ## Elements Initialization ### Description Creates a quaternion by specifying 4 real-numbered scalar elements. ### Method `Quaternion(w, x, y, z)` ### Parameters #### Path Parameters - **w, x, y, z** (real number or string) - Required - Can be real numbers, strings representing real numbers, or a mixture of both. ### Code Example ```python q5 = Quaternion(1, 1, 0, 0) q5 = Quaternion("1.0", "0", ""0.347"", "0.0") q5 = Quaternion("1.76", 0, 0, 0) ``` ### Raises - `TypeError`: If any of the provided values cannot be converted to a real number. - `ValueError`: If any of the provided strings cannot be interpreted as a real number. ``` -------------------------------- ### Get Normalized Unit Quaternion Source: https://context7.com/kieranwynn/pyquaternion/llms.txt Obtain a new unit quaternion copy without altering the original quaternion. The `.unit` attribute is an alias for `.normalised`. ```python from pyquaternion import Quaternion q = Quaternion(0, 3, 0, 0) # not unit u = q.normalised print(u) # 0.000 +1.000i +0.000j +0.000k print(u.norm) # 1.0 print(q.norm) # 3.0 (original unchanged) # .unit is an alias print(q.unit == u) # True ``` -------------------------------- ### Accessing Individual Elements Source: https://github.com/kieranwynn/pyquaternion/blob/master/docs/index.md Demonstrates how to access individual elements (w, x, y, z) and all elements of a Quaternion object. ```APIDOC ## Accessing Individual Elements ### `w`, `x`, `y`, `z` **Description:** Access individual real-valued elements of the quaternion. **Returns:** A scalar, real-valued element corresponding to the accessed attribute. **Example:** ```python print(my_quaternion.w) print(my_quaternion.x) print(my_quaternion.y) print(my_quaternion.z) ``` ### `elements` **Description:** Retrieve all four elements of the quaternion as a numpy array. **Returns:** A numpy 4-array of real numbered coefficients. **Example:** ```python a = my_quaternion.elements print("{} + {}i + {}j + {}k".format(a[0], a[1], a[2], a[3])) ``` ### `__getitem__(index)` **Description:** Access a specific element of the quaternion using its index. **Parameters:** - `index` (integer): An integer in the range [-4:3] inclusive. **Raises:** - `IndexError`: If the index provided is invalid. - `TypeError` or `ValueError`: If the index cannot be interpreted as an integer. **Example:** ```python print("{} + {}i + {}j + {}k".format(my_quaternion[0], my_quaternion[1], my_quaternion[2], my_quaternion[3])) print("{} + {}i + {}j + {}k".format(my_quaternion[-4], my_quaternion[-3], my_quaternion[-2], my_quaternion[-1])) ``` ``` -------------------------------- ### Access Quaternion Rotation Angle Source: https://github.com/kieranwynn/pyquaternion/blob/master/docs/index.md Get the magnitude of the rotation in radians or degrees. The angle is in the range (-pi:pi). Note that 180-degree rotations can have equivalent representations. ```python theta = my_quaternion.angle # Magnitude of rotation about the prescribed axis, in radians theta = my_quaternion.radians # Equivalent, but explicit theta = my_quaternion.degrees # The same, but in degrees ``` -------------------------------- ### Initialize Quaternion from Rotation or Transformation Matrix Source: https://github.com/kieranwynn/pyquaternion/blob/master/docs/index.md Create a Quaternion object by specifying a 3x3 rotation matrix (R) or a 4x4 transformation matrix (T). Optional parameters for absolute (atol) and relative (rtol) tolerance can be provided for the orthogonality check. ```APIDOC ## Quaternion(matrix=R) or Quaternion(matrix=T) ### Description Specify the 3x3 rotation matrix (`R`) or 4x4 transformation matrix (`T`) from which the quaternion's rotation should be created. ### Parameters #### Path Parameters - `matrix=R` (numpy array or matrix) - Required - A 3x3 numpy array or matrix representing the rotation. - `matrix=T` (numpy array or matrix) - Required - A 4x4 numpy array or matrix representing the transformation. The translation part will be ignored. - `atol` (float) - Optional - The absolute tolerance parameter for orthogonality check. - `rtol` (float) - Optional - The relative tolerance parameter for orthogonality check. ### Request Example ```python import numpy rotation = numpy.eye(3) transformation = numpy.eye(4) q8d = Quaternion(matrix=rotation) # Using 3x3 rotation matrix q8d = Quaternion(matrix=transformation) # Using 4x4 transformation matrix # With custom tolerances q8d_custom_tol = Quaternion(matrix=rotation, atol=1e-07, rtol=1e-07) ``` ### Raises - `ValueError` if the matrix is not 3x3 or 4x4 or if the matrix is not special orthogonal. - `TypeError` if the matrix is of the wrong type. ``` -------------------------------- ### Initialize Quaternion from 3x3 or 4x4 Matrix Source: https://github.com/kieranwynn/pyquaternion/blob/master/docs/index.md Create a Quaternion object from a 3x3 rotation matrix or a 4x4 transformation matrix. The optional atol and rtol parameters can be used to adjust the tolerance for checking if the matrix is special orthogonal. ```python import numpy rotation = numpy.eye(3) transformation = numpy.eye(4) q8d = Quaternion(matrix=rotation) # Using 3x3 rotation matrix q8d = Quaternion(matrix=transformation) # Using 4x4 transformation matrix ``` ```python Quaternion(matrix=R, atol=atol, rtol=rtol) ``` ```python Quaternion(matrix=R, atol=1e-07, rtol=1e-07) ``` -------------------------------- ### Quaternion Official String Representation (__repr__) Source: https://github.com/kieranwynn/pyquaternion/blob/master/docs/index.md Get the official string representation of the Quaternion object, which is a valid Python expression to recreate the object. This is used by the `repr()` function and when inspecting objects. ```python >>> repr(my_quaternion) 'Quaternion(-0.80951530224438595, 0.022231097065902788, -0.56268832802625091,-0.16604999023923223)' >>> my_quaternion Quaternion(-0.80951530224438595, 0.022231097065902788, -0.56268832802625091,-0.16604999023923223) ``` -------------------------------- ### Create Quaternion from Scalar and Vector Parts Source: https://context7.com/kieranwynn/pyquaternion/llms.txt Initialize a Quaternion using its scalar (real) part and vector (imaginary) part. The vector part should be a 3-element sequence. Supports aliases 'real' and 'imaginary'. ```python from pyquaternion import Quaternion import numpy as np q = Quaternion(scalar=1.0, vector=[0.0, 0.0, 0.0]) # null rotation print(q) # 1.000 +0.000i +0.000j +0.000k # Pure imaginary quaternion (no scalar part) q_vec = Quaternion(scalar=None, vector=[0.0, 0.0, 1.0]) print(q_vec.scalar) # 0.0 print(q_vec.vector) # [0. 0. 1.] # Equivalently using real/imaginary aliases q2 = Quaternion(real=0.5, imaginary=np.array([0.5, 0.5, 0.5])) print(q2.norm) # 1.0 ``` -------------------------------- ### Get Unit Quaternion Copy Source: https://github.com/kieranwynn/pyquaternion/blob/master/docs/index.md Obtain a unit quaternion (versor) copy of a Quaternion object. A unit quaternion has a norm of 1.0. Note that a zero quaternion cannot be normalized and will remain zero. ```python unit_quaternion = my_quaternion.normalised ``` ```python unit_quaternion = my_quaternion.unit ``` -------------------------------- ### Comparison and Boolean Source: https://context7.com/kieranwynn/pyquaternion/llms.txt Compares quaternions using floating-point tolerance and checks for the zero quaternion. ```APIDOC ## `==`, `!=`, `bool()` — Comparison and boolean Equality uses floating-point tolerance; bool is `False` only for the zero quaternion. ```python from pyquaternion import Quaternion q1 = Quaternion(1, 0, 1, 1) q2 = Quaternion(scalar=1.0, vector=[0.0, 1.0, 1.0]) print(q1 == q2) # True print(q1 != q2) # False # Near-zero differences are considered equal q3 = Quaternion(1.0, 0.0, 0.0, 1e-15) print(q3 == Quaternion(1, 0, 0, 0)) # True (within tolerance) # Boolean print(bool(Quaternion())) # True (non-zero) print(bool(Quaternion(0, 0, 0, 0))) # False (zero quaternion) ``` ``` -------------------------------- ### Quaternion Exponential Map Class Method Source: https://github.com/kieranwynn/pyquaternion/blob/master/docs/index.md Calculates the exponential map on the quaternion Riemannian manifold. This finds the endpoint of a geodesic starting at 'q' in the direction of 'eta'. Useful for integrating orientation variations. ```python Quaternion.exp_map(q, eta) ``` -------------------------------- ### Numpy Array Initialization Source: https://github.com/kieranwynn/pyquaternion/blob/master/docs/index.md Creates a quaternion from the elements of a 4-element Numpy array. ```APIDOC ## Numpy Array Initialization ### Description Creates a quaternion from the elements of a 4-element Numpy array. The elements `[a, b, c, d]` of the array correspond to the real, and each imaginary component respectively in the order `a + bi + cj + dk`. ### Method `Quaternion(array)` ### Parameters #### Path Parameters - **array** (numpy.array) - Required - A 4-element numpy array containing real valued elements. ### Code Example ```python q6 = Quaternion(numpy.array([a, b, c, d])) ``` ### Raises - `TypeError`: If any of the array contents cannot be converted to a real number. - `ValueError`: If the array contains less/more than 4 elements. ``` -------------------------------- ### Calculate Quaternion Derivative Source: https://github.com/kieranwynn/pyquaternion/blob/master/docs/index.md Get the instantaneous quaternion derivative. The input `rate` is a 3-array describing rotation rates about the global x, y, and z axes. This method returns a unit quaternion representing the rotation rate. ```python q_dot = my_quaternion.derivative([0, 0, 3.14159]) # Rotate about z at 0.5 rotation per second ``` -------------------------------- ### Calculating Instantaneous Quaternion Derivative Source: https://context7.com/kieranwynn/pyquaternion/llms.txt Shows how to compute the instantaneous quaternion derivative using the `derivative` method, given a 3D angular rate vector. The result is a Quaternion object. ```python from pyquaternion import Quaternion import numpy as np q = Quaternion(axis=[0, 0, 1], degrees=45) # Angular velocity: rotating at 1 rad/s about Z rate = [0, 0, 1.0] q_dot = q.derivative(rate) print(q_dot) # The instantaneous rate of change quaternion print(type(q_dot)) # ``` -------------------------------- ### Explicit Element Initialization Source: https://github.com/kieranwynn/pyquaternion/blob/master/docs/index.md Specifies each quaternion element (w, x, y, z) using explicit labels. ```APIDOC ## Explicit Element Initialization ### Description Specify each element, using any sequence of ordered labels. ### Method `Quaternion(a=w, b=x, c=y, d=z)` ### Parameters #### Path Parameters - **a=w, b=x, c=y, d=z** (real number or string) - Required - Can be real numbers, strings representing real numbers, or a mixture of both. Accepts labels like `a`, `b`, `c`, `d` or `w`, `x`, `y`, `z` or `a`, `i`, `j`, `k` or `q1`, `q2`, `q3`, `q4`. ### Code Example ```python q8a = Quaternion(a=1.0, b=0.0, c=0.0, d=0.0) q8a = Quaternion(w=1.0, x=0.0, y=0.0, z=0.0) q8a = Quaternion(a=1.0, i=0.0, j=0.0, k=0.0) q8a = Quaternion(q1=1.0, q2=0.0, q3=0.0, q4=0.0) ``` ### Raises Exception behavior is the same as initialization by element. ``` -------------------------------- ### Convert Angle Units (Radians/Degrees) Source: https://context7.com/kieranwynn/pyquaternion/llms.txt Provides static methods for converting angles between radians and degrees. Includes safe handling of None input. ```python from pyquaternion import Quaternion import math print(Quaternion.to_degrees(math.pi)) # 180.0 print(Quaternion.to_degrees(math.pi / 2)) # 90.0 print(Quaternion.to_radians(180.0)) # 3.141592653589793 print(Quaternion.to_radians(45.0)) # 0.7853981633974483 print(Quaternion.to_degrees(None)) # None (safe for None input) ``` -------------------------------- ### Normalisation Source: https://github.com/kieranwynn/pyquaternion/blob/master/docs/index.md Get a unit quaternion (versor) copy of this Quaternion object. A unit quaternion has a norm of 1.0. Note: A Quaternion representing zero i.e. `Quaternion(0, 0, 0, 0)` cannot be normalised. In this case, the returned object will remain zero. ```APIDOC ## Normalisation ### Description Get a unit quaternion (versor) copy of this Quaternion object. A unit quaternion has a norm of 1.0. **Note:** A Quaternion representing zero i.e. `Quaternion(0, 0, 0, 0)` cannot be normalised. In this case, the returned object will remain zero. ### Returns A new Quaternion object clone that is guaranteed to be a unit quaternion *unless* the original object was zero, in which case the norm will remain zero. ### Usage ```python unit_quaternion = my_quaternion.normalised unit_quaternion = my_quaternion.unit ``` ``` -------------------------------- ### Random Initialization Source: https://github.com/kieranwynn/pyquaternion/blob/master/docs/index.md Creates a random quaternion representing a rotation chosen uniformly from the rotation space. ```APIDOC ## Random Initialization ### Description Creates a random quaternion that describes a rotation randomly chosen from a uniform distribution across the rotation space. ### Method `Quaternion.random()` ### Code Example ```python q3 = Quaternion.random() # Called as a class method ``` ``` -------------------------------- ### Simulate 360° Rotation in Steps Source: https://context7.com/kieranwynn/pyquaternion/llms.txt Simulates a full 360-degree rotation by integrating small angular steps. Useful for animations or gradual orientation changes. ```python from pyquaternion import Quaternion import math q2 = Quaternion() for _ in range(100): q2.integrate([0, 0, 2 * math.pi], 1.0 / 100) print(round(q2.degrees, 1)) # ~0.0 (full circle) ``` -------------------------------- ### Convert Quaternion to Rotation Matrix Source: https://github.com/kieranwynn/pyquaternion/blob/master/docs/index.md Get the 3x3 rotation matrix equivalent of the quaternion. This method implicitly normalizes the quaternion to a unit quaternion if it is not already one. Be aware that different quaternion values (e.g., q and -q) can represent the same rotation, which might cause issues in subsequent operations. ```python R = my_quaternion.rotation_matrix t # 3x3 rotation matrix ``` -------------------------------- ### Convert Quaternion to Transformation Matrix Source: https://github.com/kieranwynn/pyquaternion/blob/master/docs/index.md Get the 4x4 homogeneous transformation matrix equivalent of the quaternion. This method implicitly normalizes the quaternion to a unit quaternion if it is not already one. Be aware that different quaternion values (e.g., q and -q) can represent the same rotation, which might cause issues in subsequent operations. ```python T = my_quaternion.transformation_matrix # 4x4 transformation matrix ``` -------------------------------- ### Import Quaternion class Source: https://context7.com/kieranwynn/pyquaternion/llms.txt Import the core Quaternion class from the pyquaternion library. This is necessary to create and use quaternion objects. ```python from pyquaternion import Quaternion ``` -------------------------------- ### Compare Quaternions for Equality Source: https://github.com/kieranwynn/pyquaternion/blob/master/docs/index.md The `__eq__` method compares two Quaternion objects for equality. It returns `True` if all corresponding elements are equal within a small tolerance defined by numpy.allclose. Use `!=` for inequality checks. This does not directly evaluate the equality of quaternion rotations; for example, `q` and `-q` will be considered unequal. ```python >>> Quaternion(1, 0, 1, 1) == Quaternion(scalar=1.0, vector=[0.0, 1.0, 1.0]) True >>> Quaternion(1, 0, 1, 1) == Quaternion(scalar=1.0, vector=[0.1, 1.0, 1.0]) False >>> Quaternion() != Quaternion(scalar=2) True ``` -------------------------------- ### Create Quaternion by Scalar and Vector Source: https://github.com/kieranwynn/pyquaternion/blob/master/docs/index.md Initialize a Quaternion by specifying its scalar (real) and vector (imaginary) parts. The vector component must contain exactly 3 real numbers. Either component can be omitted and will default to zero. ```python q8b = Quaternion(scalar=1.0, vector=(0.0, 0.0, 0.0)) // Using 3-tuple ``` ```python q8b = Quaternion(scalar=None, vector=[1.0, 0.0, 0.0]) // Using list ``` ```python q8b = Quaternion(vector=numpy.array([1.0, 0.0, 0.0])) // Using Numpy 3-array ``` ```python q8b = Quaternion(real=1.0, imaginary=(0.0, 0.0, 0.0)) // Using 3-tuple ``` ```python q8b = Quaternion(real=None, imaginary=[1.0, 0.0, 0.0]) // Using list ``` ```python q8b = Quaternion(imaginary=numpy.array([1.0, 0.0, 0.0])) // Using Numpy 3-array ``` -------------------------------- ### Initialize Quaternion from a NumPy Array Source: https://github.com/kieranwynn/pyquaternion/blob/master/docs/index.md Create a Quaternion object directly from a 4-element NumPy array representing the quaternion elements [a, b, c, d]. ```APIDOC ## Quaternion(array=a) ### Description Specify a numpy 4-array of quaternion elements to be assigned directly to the internal vector representation of the quaternion object. ### Parameters #### Path Parameters - `array=a` (numpy array) - Required - A 4-element numpy array containing real valued elements [a, b, c, d]. ### Request Example ```python import numpy q8e = Quaternion(array=numpy.array([1.0, 0.0, 0.0, 0.0])) ``` ### Raises - `ValueError` if the array vector contains less/more than 4 elements. ``` -------------------------------- ### Create Quaternion by Rotation Axis and Angle Source: https://github.com/kieranwynn/pyquaternion/blob/master/docs/index.md Initialize a Quaternion by defining a rotation axis and an angle in radians or degrees. The axis must be a 3-element sequence or numpy array with a non-zero magnitude. The angle can be specified using radians, degrees, or a general angle (also in radians). ```python q8c = Quaternion(axis=(1.0, 0.0, 0.0), radians=math.pi/2) // Using radians asnd a 3-tuple ``` ```python q8c = Quaternion(axis=[1.0, 0.0, 0.0], degrees=90) // Using degrees and a list ``` ```python q8c = Quaternion(axis=numpy.array([1.0, 0.0, 0.0]), angle=math.pi/2) // Using radians and a Numpy 3-array ``` -------------------------------- ### Initialize Quaternion from NumPy Array Source: https://github.com/kieranwynn/pyquaternion/blob/master/docs/index.md Create a Quaternion object by directly assigning a 4-element NumPy array to its internal vector representation. This method is more direct and potentially faster than using a positional argument. ```python q8e = Quaternion(array=numpy.array([1.0, 0.0, 0.0, 0.0])) ``` -------------------------------- ### Spherical Linear Interpolation (SLERP) Source: https://context7.com/kieranwynn/pyquaternion/llms.txt Shows how to use `Quaternion.slerp` to find a quaternion at a fractional position along the great-circle arc between two other quaternions. The result is always a unit quaternion. ```python from pyquaternion import Quaternion q0 = Quaternion(axis=[1, 1, 1], angle=0.0) q1 = Quaternion(axis=[1, 1, 1], angle=3.141592) # Midpoint mid = Quaternion.slerp(q0, q1, 0.5) print(mid.degrees) # ~90.0 # 1/3 of the way third = Quaternion.slerp(q0, q1, 1.0/3.0) print(round(third.degrees, 1)) # ~60.0 # Result is always a unit quaternion print(mid.is_unit()) # True ``` -------------------------------- ### Generating Evenly Spaced Interpolation Steps Source: https://context7.com/kieranwynn/pyquaternion/llms.txt Demonstrates using `Quaternion.intermediates` to generate a sequence of quaternions evenly spaced along the SLERP path between two given quaternions. Can optionally include endpoints. ```python from pyquaternion import Quaternion import numpy as np q0 = Quaternion(axis=[0, 1, 0], degrees=0) q1 = Quaternion(axis=[0, 1, 0], degrees=90) v = np.array([0., 0., 1.]) # 9 steps, no endpoints → 9 intermediate quaternions for q in Quaternion.intermediates(q0, q1, 9): print(round(q.degrees, 1)) # 9.0, 18.0, 27.0, 36.0, 45.0, 54.0, 63.0, 72.0, 81.0 # Include endpoints → 11 values (9 + 2) steps = list(Quaternion.intermediates(q0, q1, 9, include_endpoints=True)) print(len(steps)) # 11 print(steps[0].degrees) # ~0.0 print(steps[-1].degrees)# ~90.0 # Animate a point along the interpolated path for q in Quaternion.intermediates(q0, q1, 4, include_endpoints=True): point = q.rotate(v) print(np.round(point, 3)) ``` -------------------------------- ### Quaternion Creation by Rotation Parameters Source: https://github.com/kieranwynn/pyquaternion/blob/master/docs/index.md Create a Quaternion object representing a rotation about an axis by a specified angle in radians or degrees. ```APIDOC ## Quaternion(axis=ax, radians=rad) or Quaternion(axis=ax, degrees=deg) or Quaternion(axis=ax, angle=theta) ### Description Specify the angle (qualified as radians or degrees) for a rotation about an axis vector [x, y, z] to be described by the quaternion object. ### Parameters * `axis=ax`: A sequence or numpy array containing 3 real numbers. It can have any magnitude except 0. * `radians=rad` [optional]: A real number or a string representing a real number in radians. * `degrees=deg` [optional]: A real number or a string representing a real number in degrees. * `angle=theta` [optional]: A real number or a string representing a real number in radians. The angle keyword may be absent, `None`, or empty, and will be assumed to be zero, but the `axis` keyword must be provided. ### Examples ```python import math import numpy from pyquaternion import Quaternion q8c = Quaternion(axis=(1.0, 0.0, 0.0), radians=math.pi/2) # Using radians and a 3-tuple q8c = Quaternion(axis=[1.0, 0.0, 0.0], degrees=90) # Using degrees and a list q8c = Quaternion(axis=numpy.array([1.0, 0.0, 0.0]), angle=math.pi/2) # Using radians and a Numpy 3-array ``` ### Raises * `ValueError`: If `axis` is missing. * `ValueError`: If `axis` contains less/more than 3 elements. * `TypeError`: If `radians/degrees/angle` cannot be interpreted as a real number. * `ZeroDivisionError`: If `axis` has 0 length. ``` -------------------------------- ### Scalar Initialization Source: https://github.com/kieranwynn/pyquaternion/blob/master/docs/index.md Creates a quaternion from a single real number (scalar). ```APIDOC ## Scalar Initialization ### Description Creates the quaternion representation of a scalar (single real number) value. The imaginary part of the resulting quaternion will always be `0i + 0j + 0k`. ### Method `Quaternion(scalar)` ### Parameters #### Path Parameters - **scalar** (real number or string) - Required - A real number or a string representing a real number. ### Code Example ```python q4 = Quaternion(4.7349) q4 = Quaternion(-3) q4 = Quaternion("4.7349") q4 = Quaternion("98") ``` ### Raises - `TypeError`: If the provided value cannot be converted to a real number. - `ValueError`: If a provided string cannot be interpreted as a real number. ``` -------------------------------- ### Time-Step Quaternion Integration Source: https://context7.com/kieranwynn/pyquaternion/llms.txt Demonstrates integrating a constant angular rate over a timestep using the `integrate` method. This method modifies the quaternion in place and guarantees the result is a unit quaternion. ```python from pyquaternion import Quaternion import numpy as np import math # Start at identity, rotate about Z at pi rad/s q = Quaternion() rate = [0, 0, math.pi] # rad/s about Z axis # After 0.5 seconds: should be ~90 degrees q.integrate(rate, 0.5) print(round(q.degrees, 1)) # ~90.0 print(q.is_unit()) # True (guaranteed) ``` -------------------------------- ### Create Quaternion Explicitly by Element Source: https://github.com/kieranwynn/pyquaternion/blob/master/docs/index.md Specifies each quaternion element (w, x, y, z) using named arguments. Accepts numbers or strings representing numbers. ```python q8a = Quaternion(a=1.0, b=0.0, c=0.0, d=0.0) ``` ```python q8a = Quaternion(w=1.0, x=0.0, y=0.0, z=0.0) ``` ```python q8a = Quaternion(a=1.0, i=0.0, j=0.0, k=0.0) ``` ```python q8a = Quaternion(q1=1.0, q2=0.0, q3=0.0, q4=0.0) ``` -------------------------------- ### Create a Default Quaternion Source: https://github.com/kieranwynn/pyquaternion/blob/master/docs/index.md Creates a unit quaternion representing the real number 1.0, which signifies a null rotation or a unit element for quaternion multiplication. ```python q1 = Quaternion() ``` -------------------------------- ### Quaternion Exponential and Logarithm Source: https://context7.com/kieranwynn/pyquaternion/llms.txt Computes the quaternion exponential and logarithm, which are fundamental for manifold operations. Demonstrates a round-trip conversion. ```python from pyquaternion import Quaternion import numpy as np q = Quaternion(axis=[0, 0, 1], degrees=90) log_q = Quaternion.log(q) print(log_q) # scalar=0.0, vector ~ [0, 0, pi/4] exp_log_q = Quaternion.exp(log_q) print(np.allclose(exp_log_q.elements, q.elements)) # True (round-trip) # log of the identity quaternion q_id = Quaternion() print(Quaternion.log(q_id)) # 0.000 +0.000i +0.000j +0.000k ``` -------------------------------- ### Quaternion(w, x, y, z) - From four scalar elements Source: https://context7.com/kieranwynn/pyquaternion/llms.txt Constructs a quaternion directly from four real-valued elements in w + xi + yj + zk form. ```APIDOC ## Quaternion(w, x, y, z) ### Description Constructs a quaternion directly from four real-valued elements in `w + xi + yj + zk` form. ### Method `Quaternion(w, x, y, z)` ### Parameters #### Path Parameters - **w** (float) - Required - The real part of the quaternion. - **x** (float) - Required - The i component of the quaternion. - **y** (float) - Required - The j component of the quaternion. - **z** (float) - Required - The k component of the quaternion. #### Request Example ```python from pyquaternion import Quaternion import numpy as np # From positional floats q = Quaternion(0.7071, 0.0, 0.7071, 0.0) print(repr(q)) # Quaternion(0.7071, 0.0, 0.7071, 0.0) print(q.norm) # ~1.0 (unit quaternion) # From a list or numpy array q2 = Quaternion([0.7071, 0.0, 0.7071, 0.0]) q3 = Quaternion(np.array([1.0, 0.0, 0.0, 0.0])) # From keyword elements (any 4-letter combination, sorted alphabetically) q4 = Quaternion(w=1.0, x=0.0, y=0.0, z=0.0) q5 = Quaternion(a=1.0, b=0.0, c=0.0, d=0.0) print(q4 == q5) # True ``` ``` -------------------------------- ### Create and Use Quaternion for Rotation Source: https://github.com/kieranwynn/pyquaternion/blob/master/docs/index.md Create a Quaternion object to represent a rotation and use it to rotate a 3D vector. Ensure numpy is imported and set to suppress insignificant values for clarity. ```python import numpy numpy.set_printoptions(suppress=True) # Suppress insignificant values for clarity v = numpy.array([0., 0., 1.]) # Unit vector in the +z direction my_quaternion = Quaternion(axis=[1, 0, 0], angle=3.14159265) v_prime = my_quaternion.rotate(v) v_prime ``` -------------------------------- ### Multiply Quaternions (Hamilton Product) Source: https://github.com/kieranwynn/pyquaternion/blob/master/docs/index.md The `__mul__` method computes the Hamilton product of two Quaternion objects. This operation is not commutative. If 'other' is not a Quaternion, it will be converted. If both multiplicands are unit quaternions, the product is guaranteed to be a unit quaternion. ```python >>> one = Quaternion(1, 0, 0, 0) >>> i = Quaternion(0, 1, 0, 0) >>> j = Quaternion(0, 0, 1, 0) >>> k = Quaternion(0, 0, 0, 1) >>> (i * i) == (j * j) == (k * k) == (i * j * k) == -1 True ``` -------------------------------- ### Quaternion String Representation and Type Conversion Source: https://context7.com/kieranwynn/pyquaternion/llms.txt Demonstrates various methods for converting Quaternions to strings and other numeric types. Note that type conversions primarily use the scalar (w) component. ```python from pyquaternion import Quaternion q = Quaternion(axis=[0, 0, 1], degrees=90) # Human-readable string print(str(q)) # 0.707 +0.000i +0.000j +0.707k # Official representation (can be eval'd) print(repr(q)) # Quaternion(0.7071..., 0.0, 0.0, 0.7071...) # Custom format spec (mirrors Python float formatting) print("{:.6f}".format(q)) # +0.707107 +0.000000i +0.000000j +0.707107k print("{:+.2e}".format(q)) # +7.07e-01 +0.00e+00i +0.00e+00j +7.07e-01k # Type conversion (uses real/scalar part only) q_real = Quaternion(3.7, 0, 0, 0) print(int(q_real)) # 3 print(float(q_real)) # 3.7 print(complex(q_real)) # (3.7+0j) # Complex uses w and x components q_cx = Quaternion(1.0, 2.0, 0.0, 0.0) print(complex(q_cx)) # (1+2j) ``` -------------------------------- ### Quaternion() - Default (identity/null rotation) Source: https://context7.com/kieranwynn/pyquaternion/llms.txt Creates a unit quaternion representing a null rotation (1 + 0i + 0j + 0k). ```APIDOC ## Quaternion() ### Description Creates a unit quaternion `1 + 0i + 0j + 0k` representing a null rotation. ### Method `Quaternion()` ### Request Example ```python from pyquaternion import Quaternion q = Quaternion() print(q) # 1.000 +0.000i +0.000j +0.000k print(q.norm) # 1.0 print(q.is_unit()) # True ``` ``` -------------------------------- ### Create Quaternion from Sequence Source: https://github.com/kieranwynn/pyquaternion/blob/master/docs/index.md Creates a quaternion from an ordered sequence (list, tuple, generator) containing 4 real-valued elements. ```python q7 = Quaternion((a, b, c, d)) // from 4-tuple ``` ```python q7 = Quaternion([a, b, c, d]) // from list of 4 ```