{ "cells": [ { "cell_type": "markdown", "id": "6bcf8e50", "metadata": {}, "source": [ "# Examples\n", "\n", "Let's start by importing the {py:class}`quatorch.Quaternion` class:" ] }, { "cell_type": "code", "execution_count": null, "id": "3a61013c", "metadata": { "tags": [ "remove-output" ] }, "outputs": [], "source": [ "from quatorch import Quaternion" ] }, { "cell_type": "markdown", "id": "2806da51", "metadata": {}, "source": [ "There are two main ways to initialize a quaternion: \n", "- from four scalars representing WXYZ components\n", "- from a tensor that has shape $(..., 4)$\n", "\n", "Here are two ways to define a $45$-degree rotation around the X axis:" ] }, { "cell_type": "code", "execution_count": null, "id": "c85ece73", "metadata": {}, "outputs": [], "source": [ "import torch\n", "\n", "\n", "# Create a quaternion from four scalars (W, X, Y, Z)\n", "q = Quaternion(0.9239, 0.3827, 0.0, 0.0)\n", "\n", "# Or from a tensor of shape (..., 4)\n", "q2 = Quaternion(torch.tensor([0.9239, 0.3827, 0.0, 0.0]))\n", "\n", "print(f\"{(q == q2) = }\")" ] }, { "cell_type": "markdown", "id": "447056ef", "metadata": {}, "source": [ "Both methods create the same quaternion. Notice that element-wise comparison was performed, as a quaternion is still a subclass of `torch.Tensor`. Let's inspect some quaternion operations as multiplication and exponentiation:" ] }, { "cell_type": "code", "execution_count": null, "id": "f0d9c5e1", "metadata": {}, "outputs": [], "source": [ "q = q.normalize()\n", "\n", "print(f\"{q*q*q*q = }\")\n", "print(f\"{q**4 = }\")\n", "print(f\"{(4 * q.log()).exp() = }\")\n", "print(f\"{-q**(-4) = }\")" ] }, { "cell_type": "markdown", "id": "b086eb3d", "metadata": {}, "source": [ "As expected, all the above returned the same result, which represents a 180 degrees rotation around the X axis. We can verify that by converting it to an axis-angle representation:" ] }, { "cell_type": "code", "execution_count": null, "id": "4b84596b", "metadata": {}, "outputs": [], "source": [ "axis, angle = (q**4).to_axis_angle()\n", "print(f\"Axis: {axis}, Angle (degrees): {angle.rad2deg()}\")" ] }, { "cell_type": "markdown", "id": "2e8f3e99", "metadata": {}, "source": [ "Or a rotation matrix:" ] }, { "cell_type": "code", "execution_count": null, "id": "397b9997", "metadata": {}, "outputs": [], "source": [ "q.to_rotation_matrix()" ] }, { "cell_type": "markdown", "id": "f8b886a3", "metadata": {}, "source": [ "
You may also construct quaternions from rotation matrices or an axis-angle representation using the methods {any}`quatorch.Quaternion.from_rotation_matrix` and {any}`quatorch.Quaternion.from_axis_angle`
\n", "