analitics

Pages

Thursday, January 12, 2023

Python 3.11.0 : The numpy-quaternion python package - part 001.

I write an article on my website about artificial intelligence and I used python to show a simple example with quaternions.
This Python module adds a quaternion dtype to NumPy and you can read about this on the official website.
I may have mistakenly installed a python packet with a similar name and I had to install it with the command:
python -m pip uninstall quaternion
the next step was to install this command
python -m pip install --upgrade --no-deps --force-reinstall numpy-quaternion
The source code I used defines two quaternions, one with real part a and imaginary parts, and one quaternion using Euler angles.
Then is perform the rotation uses quaternion multiplication.
Let's see the source code
import numpy as np
import quaternion

# define a quaternion with real part a and imaginary parts bi, cj, dk
a = 1
b = 2
c = 3
d = 4
q = np.quaternion(a, b, c, d)

# define a quaternion using euler angles
x = 1.0
y = 2.0
z = 3.0
q2 = quaternion.from_euler_angles(x, y, z)

# define a vector to rotate
v = [1, 0, 0]

# perform the rotation using quaternion multiplication

# quaternion multiplication is not commutative, the order matters
# because this line of source code will not work:  rotated_v = q2 * v * q2.conj()

rotated_v = (q2 * quaternion.quaternion(0, *v)) * q2.conj()

print(rotated_v)
This is the result:
quaternion(0, 0.103846565151668, 0.422918571742548, 0.900197629735517)