Quaternion.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      https://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */

  17. /*
  18.  * This is not the original file distributed by the Apache Software Foundation
  19.  * It has been modified by the Hipparchus project
  20.  */

  21. package org.hipparchus.complex;

  22. import java.io.Serializable;

  23. import org.hipparchus.exception.LocalizedCoreFormats;
  24. import org.hipparchus.exception.MathIllegalArgumentException;
  25. import org.hipparchus.util.FastMath;
  26. import org.hipparchus.util.MathUtils;
  27. import org.hipparchus.util.Precision;

  28. /**
  29.  * This class implements <a href="http://mathworld.wolfram.com/Quaternion.html">
  30.  * quaternions</a> (Hamilton's hypercomplex numbers).
  31.  * <p>
  32.  * Instance of this class are guaranteed to be immutable.
  33.  */
  34. public final class Quaternion implements Serializable {
  35.     /** Identity quaternion. */
  36.     public static final Quaternion IDENTITY = new Quaternion(1, 0, 0, 0);
  37.     /** Zero quaternion. */
  38.     public static final Quaternion ZERO = new Quaternion(0, 0, 0, 0);
  39.     /** i */
  40.     public static final Quaternion I = new Quaternion(0, 1, 0, 0);
  41.     /** j */
  42.     public static final Quaternion J = new Quaternion(0, 0, 1, 0);
  43.     /** k */
  44.     public static final Quaternion K = new Quaternion(0, 0, 0, 1);

  45.     /** Serializable version identifier. */
  46.     private static final long serialVersionUID = 20092012L;

  47.     /** First component (scalar part). */
  48.     private final double q0;
  49.     /** Second component (first vector part). */
  50.     private final double q1;
  51.     /** Third component (second vector part). */
  52.     private final double q2;
  53.     /** Fourth component (third vector part). */
  54.     private final double q3;

  55.     /**
  56.      * Builds a quaternion from its components.
  57.      *
  58.      * @param a Scalar component.
  59.      * @param b First vector component.
  60.      * @param c Second vector component.
  61.      * @param d Third vector component.
  62.      */
  63.     public Quaternion(final double a,
  64.                       final double b,
  65.                       final double c,
  66.                       final double d) {
  67.         this.q0 = a;
  68.         this.q1 = b;
  69.         this.q2 = c;
  70.         this.q3 = d;
  71.     }

  72.     /**
  73.      * Builds a quaternion from scalar and vector parts.
  74.      *
  75.      * @param scalar Scalar part of the quaternion.
  76.      * @param v Components of the vector part of the quaternion.
  77.      *
  78.      * @throws MathIllegalArgumentException if the array length is not 3.
  79.      */
  80.     public Quaternion(final double scalar, final double[] v)
  81.         throws MathIllegalArgumentException {
  82.         MathUtils.checkDimension(v.length, 3);
  83.         this.q0 = scalar;
  84.         this.q1 = v[0];
  85.         this.q2 = v[1];
  86.         this.q3 = v[2];
  87.     }

  88.     /**
  89.      * Builds a pure quaternion from a vector (assuming that the scalar
  90.      * part is zero).
  91.      *
  92.      * @param v Components of the vector part of the pure quaternion.
  93.      */
  94.     public Quaternion(final double[] v) {
  95.         this(0, v);
  96.     }

  97.     /**
  98.      * Returns the conjugate quaternion of the instance.
  99.      *
  100.      * @return the conjugate quaternion
  101.      */
  102.     public Quaternion getConjugate() {
  103.         return new Quaternion(q0, -q1, -q2, -q3);
  104.     }

  105.     /**
  106.      * Returns the Hamilton product of two quaternions.
  107.      *
  108.      * @param q1 First quaternion.
  109.      * @param q2 Second quaternion.
  110.      * @return the product {@code q1} and {@code q2}, in that order.
  111.      */
  112.     public static Quaternion multiply(final Quaternion q1, final Quaternion q2) {
  113.         // Components of the first quaternion.
  114.         final double q1a = q1.getQ0();
  115.         final double q1b = q1.getQ1();
  116.         final double q1c = q1.getQ2();
  117.         final double q1d = q1.getQ3();

  118.         // Components of the second quaternion.
  119.         final double q2a = q2.getQ0();
  120.         final double q2b = q2.getQ1();
  121.         final double q2c = q2.getQ2();
  122.         final double q2d = q2.getQ3();

  123.         // Components of the product.
  124.         final double w = q1a * q2a - q1b * q2b - q1c * q2c - q1d * q2d;
  125.         final double x = q1a * q2b + q1b * q2a + q1c * q2d - q1d * q2c;
  126.         final double y = q1a * q2c - q1b * q2d + q1c * q2a + q1d * q2b;
  127.         final double z = q1a * q2d + q1b * q2c - q1c * q2b + q1d * q2a;

  128.         return new Quaternion(w, x, y, z);
  129.     }

  130.     /**
  131.      * Returns the Hamilton product of the instance by a quaternion.
  132.      *
  133.      * @param q Quaternion.
  134.      * @return the product of this instance with {@code q}, in that order.
  135.      */
  136.     public Quaternion multiply(final Quaternion q) {
  137.         return multiply(this, q);
  138.     }

  139.     /**
  140.      * Computes the sum of two quaternions.
  141.      *
  142.      * @param q1 Quaternion.
  143.      * @param q2 Quaternion.
  144.      * @return the sum of {@code q1} and {@code q2}.
  145.      */
  146.     public static Quaternion add(final Quaternion q1,
  147.                                  final Quaternion q2) {
  148.         return new Quaternion(q1.getQ0() + q2.getQ0(),
  149.                               q1.getQ1() + q2.getQ1(),
  150.                               q1.getQ2() + q2.getQ2(),
  151.                               q1.getQ3() + q2.getQ3());
  152.     }

  153.     /**
  154.      * Computes the sum of the instance and another quaternion.
  155.      *
  156.      * @param q Quaternion.
  157.      * @return the sum of this instance and {@code q}
  158.      */
  159.     public Quaternion add(final Quaternion q) {
  160.         return add(this, q);
  161.     }

  162.     /**
  163.      * Subtracts two quaternions.
  164.      *
  165.      * @param q1 First Quaternion.
  166.      * @param q2 Second quaternion.
  167.      * @return the difference between {@code q1} and {@code q2}.
  168.      */
  169.     public static Quaternion subtract(final Quaternion q1,
  170.                                       final Quaternion q2) {
  171.         return new Quaternion(q1.getQ0() - q2.getQ0(),
  172.                               q1.getQ1() - q2.getQ1(),
  173.                               q1.getQ2() - q2.getQ2(),
  174.                               q1.getQ3() - q2.getQ3());
  175.     }

  176.     /**
  177.      * Subtracts a quaternion from the instance.
  178.      *
  179.      * @param q Quaternion.
  180.      * @return the difference between this instance and {@code q}.
  181.      */
  182.     public Quaternion subtract(final Quaternion q) {
  183.         return subtract(this, q);
  184.     }

  185.     /**
  186.      * Computes the dot-product of two quaternions.
  187.      *
  188.      * @param q1 Quaternion.
  189.      * @param q2 Quaternion.
  190.      * @return the dot product of {@code q1} and {@code q2}.
  191.      */
  192.     public static double dotProduct(final Quaternion q1,
  193.                                     final Quaternion q2) {
  194.         return q1.getQ0() * q2.getQ0() +
  195.             q1.getQ1() * q2.getQ1() +
  196.             q1.getQ2() * q2.getQ2() +
  197.             q1.getQ3() * q2.getQ3();
  198.     }

  199.     /**
  200.      * Computes the dot-product of the instance by a quaternion.
  201.      *
  202.      * @param q Quaternion.
  203.      * @return the dot product of this instance and {@code q}.
  204.      */
  205.     public double dotProduct(final Quaternion q) {
  206.         return dotProduct(this, q);
  207.     }

  208.     /**
  209.      * Computes the norm of the quaternion.
  210.      *
  211.      * @return the norm.
  212.      */
  213.     public double getNorm() {
  214.         return FastMath.sqrt(q0 * q0 +
  215.                              q1 * q1 +
  216.                              q2 * q2 +
  217.                              q3 * q3);
  218.     }

  219.     /**
  220.      * Computes the normalized quaternion (the versor of the instance).
  221.      * The norm of the quaternion must not be zero.
  222.      *
  223.      * @return a normalized quaternion.
  224.      * @throws MathIllegalArgumentException if the norm of the quaternion is zero.
  225.      */
  226.     public Quaternion normalize() {
  227.         final double norm = getNorm();

  228.         if (norm < Precision.SAFE_MIN) {
  229.             throw new MathIllegalArgumentException(LocalizedCoreFormats.NORM, norm);
  230.         }

  231.         return new Quaternion(q0 / norm,
  232.                               q1 / norm,
  233.                               q2 / norm,
  234.                               q3 / norm);
  235.     }

  236.     /**
  237.      * {@inheritDoc}
  238.      */
  239.     @Override
  240.     public boolean equals(Object other) {
  241.         if (this == other) {
  242.             return true;
  243.         }
  244.         if (other instanceof Quaternion) {
  245.             final Quaternion q = (Quaternion) other;
  246.             return q0 == q.getQ0() &&
  247.                 q1 == q.getQ1() &&
  248.                 q2 == q.getQ2() &&
  249.                 q3 == q.getQ3();
  250.         }

  251.         return false;
  252.     }

  253.     /**
  254.      * {@inheritDoc}
  255.      */
  256.     @Override
  257.     public int hashCode() {
  258.         // "Effective Java" (second edition, p. 47).
  259.         int result = 17;
  260.         for (double comp : new double[] { q0, q1, q2, q3 }) {
  261.             final int c = MathUtils.hash(comp);
  262.             result = 31 * result + c;
  263.         }
  264.         return result;
  265.     }

  266.     /**
  267.      * Checks whether this instance is equal to another quaternion
  268.      * within a given tolerance.
  269.      *
  270.      * @param q Quaternion with which to compare the current quaternion.
  271.      * @param eps Tolerance.
  272.      * @return {@code true} if the each of the components are equal
  273.      * within the allowed absolute error.
  274.      */
  275.     public boolean equals(final Quaternion q,
  276.                           final double eps) {
  277.         return Precision.equals(q0, q.getQ0(), eps) &&
  278.             Precision.equals(q1, q.getQ1(), eps) &&
  279.             Precision.equals(q2, q.getQ2(), eps) &&
  280.             Precision.equals(q3, q.getQ3(), eps);
  281.     }

  282.     /**
  283.      * Checks whether the instance is a unit quaternion within a given
  284.      * tolerance.
  285.      *
  286.      * @param eps Tolerance (absolute error).
  287.      * @return {@code true} if the norm is 1 within the given tolerance,
  288.      * {@code false} otherwise
  289.      */
  290.     public boolean isUnitQuaternion(double eps) {
  291.         return Precision.equals(getNorm(), 1d, eps);
  292.     }

  293.     /**
  294.      * Checks whether the instance is a pure quaternion within a given
  295.      * tolerance.
  296.      *
  297.      * @param eps Tolerance (absolute error).
  298.      * @return {@code true} if the scalar part of the quaternion is zero.
  299.      */
  300.     public boolean isPureQuaternion(double eps) {
  301.         return FastMath.abs(getQ0()) <= eps;
  302.     }

  303.     /**
  304.      * Returns the polar form of the quaternion.
  305.      *
  306.      * @return the unit quaternion with positive scalar part.
  307.      */
  308.     public Quaternion getPositivePolarForm() {
  309.         if (getQ0() < 0) {
  310.             final Quaternion unitQ = normalize();
  311.             // The quaternion of rotation (normalized quaternion) q and -q
  312.             // are equivalent (i.e. represent the same rotation).
  313.             return new Quaternion(-unitQ.getQ0(),
  314.                                   -unitQ.getQ1(),
  315.                                   -unitQ.getQ2(),
  316.                                   -unitQ.getQ3());
  317.         } else {
  318.             return this.normalize();
  319.         }
  320.     }

  321.     /**
  322.      * Returns the inverse of this instance.
  323.      * The norm of the quaternion must not be zero.
  324.      *
  325.      * @return the inverse.
  326.      * @throws MathIllegalArgumentException if the norm (squared) of the quaternion is zero.
  327.      */
  328.     public Quaternion getInverse() {
  329.         final double squareNorm = q0 * q0 + q1 * q1 + q2 * q2 + q3 * q3;
  330.         if (squareNorm < Precision.SAFE_MIN) {
  331.             throw new MathIllegalArgumentException(LocalizedCoreFormats.NORM, squareNorm);
  332.         }

  333.         return new Quaternion(q0 / squareNorm,
  334.                               -q1 / squareNorm,
  335.                               -q2 / squareNorm,
  336.                               -q3 / squareNorm);
  337.     }

  338.     /**
  339.      * Gets the first component of the quaternion (scalar part).
  340.      *
  341.      * @return the scalar part.
  342.      */
  343.     public double getQ0() {
  344.         return q0;
  345.     }

  346.     /**
  347.      * Gets the second component of the quaternion (first component
  348.      * of the vector part).
  349.      *
  350.      * @return the first component of the vector part.
  351.      */
  352.     public double getQ1() {
  353.         return q1;
  354.     }

  355.     /**
  356.      * Gets the third component of the quaternion (second component
  357.      * of the vector part).
  358.      *
  359.      * @return the second component of the vector part.
  360.      */
  361.     public double getQ2() {
  362.         return q2;
  363.     }

  364.     /**
  365.      * Gets the fourth component of the quaternion (third component
  366.      * of the vector part).
  367.      *
  368.      * @return the third component of the vector part.
  369.      */
  370.     public double getQ3() {
  371.         return q3;
  372.     }

  373.     /**
  374.      * Gets the scalar part of the quaternion.
  375.      *
  376.      * @return the scalar part.
  377.      * @see #getQ0()
  378.      */
  379.     public double getScalarPart() {
  380.         return getQ0();
  381.     }

  382.     /**
  383.      * Gets the three components of the vector part of the quaternion.
  384.      *
  385.      * @return the vector part.
  386.      * @see #getQ1()
  387.      * @see #getQ2()
  388.      * @see #getQ3()
  389.      */
  390.     public double[] getVectorPart() {
  391.         return new double[] { getQ1(), getQ2(), getQ3() };
  392.     }

  393.     /**
  394.      * Multiplies the instance by a scalar.
  395.      *
  396.      * @param alpha Scalar factor.
  397.      * @return a scaled quaternion.
  398.      */
  399.     public Quaternion multiply(final double alpha) {
  400.         return new Quaternion(alpha * q0,
  401.                               alpha * q1,
  402.                               alpha * q2,
  403.                               alpha * q3);
  404.     }

  405.     /**
  406.      * {@inheritDoc}
  407.      */
  408.     @Override
  409.     public String toString() {
  410.         final String sp = " ";
  411.         final StringBuilder s = new StringBuilder();
  412.         s.append('[')
  413.             .append(q0).append(sp)
  414.             .append(q1).append(sp)
  415.             .append(q2).append(sp)
  416.             .append(q3)
  417.             .append(']');

  418.         return s.toString();
  419.     }
  420. }