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.  *      http://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. package org.apache.commons.math3.complex;

  18. import java.io.Serializable;
  19. import org.apache.commons.math3.util.FastMath;
  20. import org.apache.commons.math3.util.MathUtils;
  21. import org.apache.commons.math3.util.Precision;
  22. import org.apache.commons.math3.exception.DimensionMismatchException;
  23. import org.apache.commons.math3.exception.ZeroException;
  24. import org.apache.commons.math3.exception.util.LocalizedFormats;

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

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

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

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

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

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

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

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

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

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

  130.         return new Quaternion(w, x, y, z);
  131.     }

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

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

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

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

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

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

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

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

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

  230.         if (norm < Precision.SAFE_MIN) {
  231.             throw new ZeroException(LocalizedFormats.NORM, norm);
  232.         }

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

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

  253.         return false;
  254.     }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  420.         return s.toString();
  421.     }
  422. }