Rotation.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.geometry.euclidean.threed;

  22. import java.io.Serializable;

  23. import org.hipparchus.exception.MathIllegalArgumentException;
  24. import org.hipparchus.exception.MathRuntimeException;
  25. import org.hipparchus.geometry.LocalizedGeometryFormats;
  26. import org.hipparchus.util.FastMath;
  27. import org.hipparchus.util.MathArrays;
  28. import org.hipparchus.util.SinCos;

  29. /**
  30.  * This class implements rotations in a three-dimensional space.
  31.  *
  32.  * <p>Rotations can be represented by several different mathematical
  33.  * entities (matrices, axe and angle, Cardan or Euler angles,
  34.  * quaternions). This class presents an higher level abstraction, more
  35.  * user-oriented and hiding this implementation details. Well, for the
  36.  * curious, we use quaternions for the internal representation. The
  37.  * user can build a rotation from any of these representations, and
  38.  * any of these representations can be retrieved from a
  39.  * <code>Rotation</code> instance (see the various constructors and
  40.  * getters). In addition, a rotation can also be built implicitly
  41.  * from a set of vectors and their image.</p>
  42.  * <p>This implies that this class can be used to convert from one
  43.  * representation to another one. For example, converting a rotation
  44.  * matrix into a set of Cardan angles from can be done using the
  45.  * following single line of code:</p>
  46.  * <pre>
  47.  * double[] angles = new Rotation(matrix, 1.0e-10).getAngles(RotationOrder.XYZ);
  48.  * </pre>
  49.  * <p>Focus is oriented on what a rotation <em>do</em> rather than on its
  50.  * underlying representation. Once it has been built, and regardless of its
  51.  * internal representation, a rotation is an <em>operator</em> which basically
  52.  * transforms three dimensional {@link Vector3D vectors} into other three
  53.  * dimensional {@link Vector3D vectors}. Depending on the application, the
  54.  * meaning of these vectors may vary and the semantics of the rotation also.</p>
  55.  * <p>For example in an spacecraft attitude simulation tool, users will often
  56.  * consider the vectors are fixed (say the Earth direction for example) and the
  57.  * frames change. The rotation transforms the coordinates of the vector in inertial
  58.  * frame into the coordinates of the same vector in satellite frame. In this
  59.  * case, the rotation implicitly defines the relation between the two frames.</p>
  60.  * <p>Another example could be a telescope control application, where the rotation
  61.  * would transform the sighting direction at rest into the desired observing
  62.  * direction when the telescope is pointed towards an object of interest. In this
  63.  * case the rotation transforms the direction at rest in a topocentric frame
  64.  * into the sighting direction in the same topocentric frame. This implies in this
  65.  * case the frame is fixed and the vector moves.</p>
  66.  * <p>In many case, both approaches will be combined. In our telescope example,
  67.  * we will probably also need to transform the observing direction in the topocentric
  68.  * frame into the observing direction in inertial frame taking into account the observatory
  69.  * location and the Earth rotation, which would essentially be an application of the
  70.  * first approach.</p>
  71.  *
  72.  * <p>These examples show that a rotation is what the user wants it to be. This
  73.  * class does not push the user towards one specific definition and hence does not
  74.  * provide methods like <code>projectVectorIntoDestinationFrame</code> or
  75.  * <code>computeTransformedDirection</code>. It provides simpler and more generic
  76.  * methods: {@link #applyTo(Vector3D) applyTo(Vector3D)} and {@link
  77.  * #applyInverseTo(Vector3D) applyInverseTo(Vector3D)}.</p>
  78.  *
  79.  * <p>Since a rotation is basically a vectorial operator, several rotations can be
  80.  * composed together and the composite operation <code>r = r<sub>1</sub> o
  81.  * r<sub>2</sub></code> (which means that for each vector <code>u</code>,
  82.  * <code>r(u) = r<sub>1</sub>(r<sub>2</sub>(u))</code>) is also a rotation. Hence
  83.  * we can consider that in addition to vectors, a rotation can be applied to other
  84.  * rotations as well (or to itself). With our previous notations, we would say we
  85.  * can apply <code>r<sub>1</sub></code> to <code>r<sub>2</sub></code> and the result
  86.  * we get is <code>r = r<sub>1</sub> o r<sub>2</sub></code>. For this purpose, the
  87.  * class provides the methods: {@link #applyTo(Rotation) applyTo(Rotation)} and
  88.  * {@link #applyInverseTo(Rotation) applyInverseTo(Rotation)}.</p>
  89.  *
  90.  * <p>Rotations are guaranteed to be immutable objects.</p>
  91.  *
  92.  * @see Vector3D
  93.  * @see RotationOrder
  94.  */

  95. public class Rotation implements Serializable {

  96.   /** Identity rotation. */
  97.   public static final Rotation IDENTITY = new Rotation(1.0, 0.0, 0.0, 0.0, false);

  98.   /** Serializable version identifier */
  99.   private static final long serialVersionUID = -2153622329907944313L;

  100.   /** Scalar coordinate of the quaternion. */
  101.   private final double q0;

  102.   /** First coordinate of the vectorial part of the quaternion. */
  103.   private final double q1;

  104.   /** Second coordinate of the vectorial part of the quaternion. */
  105.   private final double q2;

  106.   /** Third coordinate of the vectorial part of the quaternion. */
  107.   private final double q3;

  108.   /** Build a rotation from the quaternion coordinates.
  109.    * <p>A rotation can be built from a <em>normalized</em> quaternion,
  110.    * i.e. a quaternion for which q<sub>0</sub><sup>2</sup> +
  111.    * q<sub>1</sub><sup>2</sup> + q<sub>2</sub><sup>2</sup> +
  112.    * q<sub>3</sub><sup>2</sup> = 1. If the quaternion is not normalized,
  113.    * the constructor can normalize it in a preprocessing step.</p>
  114.    * <p>Note that some conventions put the scalar part of the quaternion
  115.    * as the 4<sup>th</sup> component and the vector part as the first three
  116.    * components. This is <em>not</em> our convention. We put the scalar part
  117.    * as the first component.</p>
  118.    * @param q0 scalar part of the quaternion
  119.    * @param q1 first coordinate of the vectorial part of the quaternion
  120.    * @param q2 second coordinate of the vectorial part of the quaternion
  121.    * @param q3 third coordinate of the vectorial part of the quaternion
  122.    * @param needsNormalization if true, the coordinates are considered
  123.    * not to be normalized, a normalization preprocessing step is performed
  124.    * before using them
  125.    */
  126.   public Rotation(double q0, double q1, double q2, double q3,
  127.                   boolean needsNormalization) {

  128.     if (needsNormalization) {
  129.       // normalization preprocessing
  130.       double inv = 1.0 / FastMath.sqrt(q0 * q0 + q1 * q1 + q2 * q2 + q3 * q3);
  131.       q0 *= inv;
  132.       q1 *= inv;
  133.       q2 *= inv;
  134.       q3 *= inv;
  135.     }

  136.     this.q0 = q0;
  137.     this.q1 = q1;
  138.     this.q2 = q2;
  139.     this.q3 = q3;

  140.   }

  141.   /** Build a rotation from an axis and an angle.
  142.    * @param axis axis around which to rotate
  143.    * @param angle rotation angle
  144.    * @param convention convention to use for the semantics of the angle
  145.    * @exception MathIllegalArgumentException if the axis norm is zero
  146.    */
  147.   public Rotation(final Vector3D axis, final double angle, final RotationConvention convention)
  148.       throws MathIllegalArgumentException {

  149.     double norm = axis.getNorm();
  150.     if (norm == 0) {
  151.       throw new MathIllegalArgumentException(LocalizedGeometryFormats.ZERO_NORM_FOR_ROTATION_AXIS);
  152.     }

  153.     double halfAngle = convention == RotationConvention.VECTOR_OPERATOR ? -0.5 * angle : 0.5 * angle;
  154.     SinCos sinCos = FastMath.sinCos(halfAngle);
  155.     double coeff = sinCos.sin() / norm;

  156.     q0 = sinCos.cos();
  157.     q1 = coeff * axis.getX();
  158.     q2 = coeff * axis.getY();
  159.     q3 = coeff * axis.getZ();

  160.   }

  161.   /** Build a rotation from a 3X3 matrix.

  162.    * <p>Rotation matrices are orthogonal matrices, i.e. unit matrices
  163.    * (which are matrices for which m.m<sup>T</sup> = I) with real
  164.    * coefficients. The module of the determinant of unit matrices is
  165.    * 1, among the orthogonal 3X3 matrices, only the ones having a
  166.    * positive determinant (+1) are rotation matrices.</p>

  167.    * <p>When a rotation is defined by a matrix with truncated values
  168.    * (typically when it is extracted from a technical sheet where only
  169.    * four to five significant digits are available), the matrix is not
  170.    * orthogonal anymore. This constructor handles this case
  171.    * transparently by using a copy of the given matrix and applying a
  172.    * correction to the copy in order to perfect its orthogonality. If
  173.    * the Frobenius norm of the correction needed is above the given
  174.    * threshold, then the matrix is considered to be too far from a
  175.    * true rotation matrix and an exception is thrown.</p>

  176.    * @param m rotation matrix
  177.    * @param threshold convergence threshold for the iterative
  178.    * orthogonality correction (convergence is reached when the
  179.    * difference between two steps of the Frobenius norm of the
  180.    * correction is below this threshold)

  181.    * @exception MathIllegalArgumentException if the matrix is not a 3X3
  182.    * matrix, or if it cannot be transformed into an orthogonal matrix
  183.    * with the given threshold, or if the determinant of the resulting
  184.    * orthogonal matrix is negative

  185.    */
  186.   public Rotation(double[][] m, double threshold)
  187.     throws MathIllegalArgumentException {

  188.     // dimension check
  189.     if ((m.length != 3) || (m[0].length != 3) ||
  190.         (m[1].length != 3) || (m[2].length != 3)) {
  191.       throw new MathIllegalArgumentException(LocalizedGeometryFormats.ROTATION_MATRIX_DIMENSIONS,
  192.                                              m.length, m[0].length);
  193.     }

  194.     // compute a "close" orthogonal matrix
  195.     double[][] ort = orthogonalizeMatrix(m, threshold);

  196.     // check the sign of the determinant
  197.     double det = ort[0][0] * (ort[1][1] * ort[2][2] - ort[2][1] * ort[1][2]) -
  198.                  ort[1][0] * (ort[0][1] * ort[2][2] - ort[2][1] * ort[0][2]) +
  199.                  ort[2][0] * (ort[0][1] * ort[1][2] - ort[1][1] * ort[0][2]);
  200.     if (det < 0.0) {
  201.       throw new MathIllegalArgumentException(LocalizedGeometryFormats.CLOSEST_ORTHOGONAL_MATRIX_HAS_NEGATIVE_DETERMINANT,
  202.                                              det);
  203.     }

  204.     double[] quat = mat2quat(ort);
  205.     q0 = quat[0];
  206.     q1 = quat[1];
  207.     q2 = quat[2];
  208.     q3 = quat[3];

  209.   }

  210.   /** Build the rotation that transforms a pair of vectors into another pair.

  211.    * <p>Except for possible scale factors, if the instance were applied to
  212.    * the pair (u<sub>1</sub>, u<sub>2</sub>) it will produce the pair
  213.    * (v<sub>1</sub>, v<sub>2</sub>).</p>

  214.    * <p>If the angular separation between u<sub>1</sub> and u<sub>2</sub> is
  215.    * not the same as the angular separation between v<sub>1</sub> and
  216.    * v<sub>2</sub>, then a corrected v'<sub>2</sub> will be used rather than
  217.    * v<sub>2</sub>, the corrected vector will be in the (±v<sub>1</sub>,
  218.    * +v<sub>2</sub>) half-plane.</p>
  219.    * @param u1 first vector of the origin pair
  220.    * @param u2 second vector of the origin pair
  221.    * @param v1 desired image of u1 by the rotation
  222.    * @param v2 desired image of u2 by the rotation
  223.    * @exception MathRuntimeException if the norm of one of the vectors is zero,
  224.    * or if one of the pair is degenerated (i.e. the vectors of the pair are collinear)
  225.    */
  226.   public Rotation(Vector3D u1, Vector3D u2, Vector3D v1, Vector3D v2)
  227.       throws MathRuntimeException {

  228.       // build orthonormalized base from u1, u2
  229.       // this fails when vectors are null or collinear, which is forbidden to define a rotation
  230.       final Vector3D u3 = u1.crossProduct(u2).normalize();
  231.       u2 = u3.crossProduct(u1).normalize();
  232.       u1 = u1.normalize();

  233.       // build an orthonormalized base from v1, v2
  234.       // this fails when vectors are null or collinear, which is forbidden to define a rotation
  235.       final Vector3D v3 = v1.crossProduct(v2).normalize();
  236.       v2 = v3.crossProduct(v1).normalize();
  237.       v1 = v1.normalize();

  238.       // buid a matrix transforming the first base into the second one
  239.       final double[][] m = {
  240.           {
  241.               MathArrays.linearCombination(u1.getX(), v1.getX(), u2.getX(), v2.getX(), u3.getX(), v3.getX()),
  242.               MathArrays.linearCombination(u1.getY(), v1.getX(), u2.getY(), v2.getX(), u3.getY(), v3.getX()),
  243.               MathArrays.linearCombination(u1.getZ(), v1.getX(), u2.getZ(), v2.getX(), u3.getZ(), v3.getX())
  244.           },
  245.           {
  246.               MathArrays.linearCombination(u1.getX(), v1.getY(), u2.getX(), v2.getY(), u3.getX(), v3.getY()),
  247.               MathArrays.linearCombination(u1.getY(), v1.getY(), u2.getY(), v2.getY(), u3.getY(), v3.getY()),
  248.               MathArrays.linearCombination(u1.getZ(), v1.getY(), u2.getZ(), v2.getY(), u3.getZ(), v3.getY())
  249.           },
  250.           {
  251.               MathArrays.linearCombination(u1.getX(), v1.getZ(), u2.getX(), v2.getZ(), u3.getX(), v3.getZ()),
  252.               MathArrays.linearCombination(u1.getY(), v1.getZ(), u2.getY(), v2.getZ(), u3.getY(), v3.getZ()),
  253.               MathArrays.linearCombination(u1.getZ(), v1.getZ(), u2.getZ(), v2.getZ(), u3.getZ(), v3.getZ())
  254.           }
  255.       };

  256.       double[] quat = mat2quat(m);
  257.       q0 = quat[0];
  258.       q1 = quat[1];
  259.       q2 = quat[2];
  260.       q3 = quat[3];

  261.   }

  262.   /** Build one of the rotations that transform one vector into another one.

  263.    * <p>Except for a possible scale factor, if the instance were
  264.    * applied to the vector u it will produce the vector v. There is an
  265.    * infinite number of such rotations, this constructor choose the
  266.    * one with the smallest associated angle (i.e. the one whose axis
  267.    * is orthogonal to the (u, v) plane). If u and v are collinear, an
  268.    * arbitrary rotation axis is chosen.</p>

  269.    * @param u origin vector
  270.    * @param v desired image of u by the rotation
  271.    * @exception MathRuntimeException if the norm of one of the vectors is zero
  272.    */
  273.   public Rotation(Vector3D u, Vector3D v) throws MathRuntimeException {

  274.     double normProduct = u.getNorm() * v.getNorm();
  275.     if (normProduct == 0) {
  276.         throw new MathRuntimeException(LocalizedGeometryFormats.ZERO_NORM_FOR_ROTATION_DEFINING_VECTOR);
  277.     }

  278.     double dot = u.dotProduct(v);

  279.     if (dot < ((2.0e-15 - 1.0) * normProduct)) {
  280.       // special case u = -v: we select a PI angle rotation around
  281.       // an arbitrary vector orthogonal to u
  282.       Vector3D w = u.orthogonal();
  283.       q0 = 0.0;
  284.       q1 = -w.getX();
  285.       q2 = -w.getY();
  286.       q3 = -w.getZ();
  287.     } else {
  288.       // general case: (u, v) defines a plane, we select
  289.       // the shortest possible rotation: axis orthogonal to this plane
  290.       q0 = FastMath.sqrt(0.5 * (1.0 + dot / normProduct));
  291.       double coeff = 1.0 / (2.0 * q0 * normProduct);
  292.       Vector3D q = v.crossProduct(u);
  293.       q1 = coeff * q.getX();
  294.       q2 = coeff * q.getY();
  295.       q3 = coeff * q.getZ();
  296.     }

  297.   }

  298.   /** Build a rotation from three Cardan or Euler elementary rotations.

  299.    * <p>Cardan rotations are three successive rotations around the
  300.    * canonical axes X, Y and Z, each axis being used once. There are
  301.    * 6 such sets of rotations (XYZ, XZY, YXZ, YZX, ZXY and ZYX). Euler
  302.    * rotations are three successive rotations around the canonical
  303.    * axes X, Y and Z, the first and last rotations being around the
  304.    * same axis. There are 6 such sets of rotations (XYX, XZX, YXY,
  305.    * YZY, ZXZ and ZYZ), the most popular one being ZXZ.</p>
  306.    * <p>Beware that many people routinely use the term Euler angles even
  307.    * for what really are Cardan angles (this confusion is especially
  308.    * widespread in the aerospace business where Roll, Pitch and Yaw angles
  309.    * are often wrongly tagged as Euler angles).</p>

  310.    * @param order order of rotations to compose, from left to right
  311.    * (i.e. we will use {@code r1.compose(r2.compose(r3, convention), convention)})
  312.    * @param convention convention to use for the semantics of the angle
  313.    * @param alpha1 angle of the first elementary rotation
  314.    * @param alpha2 angle of the second elementary rotation
  315.    * @param alpha3 angle of the third elementary rotation
  316.    */
  317.   public Rotation(RotationOrder order, RotationConvention convention,
  318.                   double alpha1, double alpha2, double alpha3) {
  319.       Rotation r1 = new Rotation(order.getA1(), alpha1, convention);
  320.       Rotation r2 = new Rotation(order.getA2(), alpha2, convention);
  321.       Rotation r3 = new Rotation(order.getA3(), alpha3, convention);
  322.       Rotation composed = r1.compose(r2.compose(r3, convention), convention);
  323.       q0 = composed.q0;
  324.       q1 = composed.q1;
  325.       q2 = composed.q2;
  326.       q3 = composed.q3;
  327.   }

  328.   /** Convert an orthogonal rotation matrix to a quaternion.
  329.    * @param ort orthogonal rotation matrix
  330.    * @return quaternion corresponding to the matrix
  331.    */
  332.   private static double[] mat2quat(final double[][] ort) {

  333.       final double[] quat = new double[4];

  334.       // There are different ways to compute the quaternions elements
  335.       // from the matrix. They all involve computing one element from
  336.       // the diagonal of the matrix, and computing the three other ones
  337.       // using a formula involving a division by the first element,
  338.       // which unfortunately can be zero. Since the norm of the
  339.       // quaternion is 1, we know at least one element has an absolute
  340.       // value greater or equal to 0.5, so it is always possible to
  341.       // select the right formula and avoid division by zero and even
  342.       // numerical inaccuracy. Checking the elements in turn and using
  343.       // the first one greater than 0.45 is safe (this leads to a simple
  344.       // test since qi = 0.45 implies 4 qi^2 - 1 = -0.19)
  345.       double s = ort[0][0] + ort[1][1] + ort[2][2];
  346.       if (s > -0.19) {
  347.           // compute q0 and deduce q1, q2 and q3
  348.           quat[0] = 0.5 * FastMath.sqrt(s + 1.0);
  349.           double inv = 0.25 / quat[0];
  350.           quat[1] = inv * (ort[1][2] - ort[2][1]);
  351.           quat[2] = inv * (ort[2][0] - ort[0][2]);
  352.           quat[3] = inv * (ort[0][1] - ort[1][0]);
  353.       } else {
  354.           s = ort[0][0] - ort[1][1] - ort[2][2];
  355.           if (s > -0.19) {
  356.               // compute q1 and deduce q0, q2 and q3
  357.               quat[1] = 0.5 * FastMath.sqrt(s + 1.0);
  358.               double inv = 0.25 / quat[1];
  359.               quat[0] = inv * (ort[1][2] - ort[2][1]);
  360.               quat[2] = inv * (ort[0][1] + ort[1][0]);
  361.               quat[3] = inv * (ort[0][2] + ort[2][0]);
  362.           } else {
  363.               s = ort[1][1] - ort[0][0] - ort[2][2];
  364.               if (s > -0.19) {
  365.                   // compute q2 and deduce q0, q1 and q3
  366.                   quat[2] = 0.5 * FastMath.sqrt(s + 1.0);
  367.                   double inv = 0.25 / quat[2];
  368.                   quat[0] = inv * (ort[2][0] - ort[0][2]);
  369.                   quat[1] = inv * (ort[0][1] + ort[1][0]);
  370.                   quat[3] = inv * (ort[2][1] + ort[1][2]);
  371.               } else {
  372.                   // compute q3 and deduce q0, q1 and q2
  373.                   s = ort[2][2] - ort[0][0] - ort[1][1];
  374.                   quat[3] = 0.5 * FastMath.sqrt(s + 1.0);
  375.                   double inv = 0.25 / quat[3];
  376.                   quat[0] = inv * (ort[0][1] - ort[1][0]);
  377.                   quat[1] = inv * (ort[0][2] + ort[2][0]);
  378.                   quat[2] = inv * (ort[2][1] + ort[1][2]);
  379.               }
  380.           }
  381.       }

  382.       return quat;

  383.   }

  384.   /** Revert a rotation.
  385.    * Build a rotation which reverse the effect of another
  386.    * rotation. This means that if r(u) = v, then r.revert(v) = u. The
  387.    * instance is not changed.
  388.    * @return a new rotation whose effect is the reverse of the effect
  389.    * of the instance
  390.    */
  391.   public Rotation revert() {
  392.     return new Rotation(-q0, q1, q2, q3, false);
  393.   }

  394.   /** Get the scalar coordinate of the quaternion.
  395.    * @return scalar coordinate of the quaternion
  396.    */
  397.   public double getQ0() {
  398.     return q0;
  399.   }

  400.   /** Get the first coordinate of the vectorial part of the quaternion.
  401.    * @return first coordinate of the vectorial part of the quaternion
  402.    */
  403.   public double getQ1() {
  404.     return q1;
  405.   }

  406.   /** Get the second coordinate of the vectorial part of the quaternion.
  407.    * @return second coordinate of the vectorial part of the quaternion
  408.    */
  409.   public double getQ2() {
  410.     return q2;
  411.   }

  412.   /** Get the third coordinate of the vectorial part of the quaternion.
  413.    * @return third coordinate of the vectorial part of the quaternion
  414.    */
  415.   public double getQ3() {
  416.     return q3;
  417.   }

  418.   /** Get the normalized axis of the rotation.
  419.    * <p>
  420.    * Note that as {@link #getAngle()} always returns an angle
  421.    * between 0 and &pi;, changing the convention changes the
  422.    * direction of the axis, not the sign of the angle.
  423.    * </p>
  424.    * @param convention convention to use for the semantics of the angle
  425.    * @return normalized axis of the rotation
  426.    * @see #Rotation(Vector3D, double, RotationConvention)
  427.    */
  428.   public Vector3D getAxis(final RotationConvention convention) {
  429.     final double squaredSine = q1 * q1 + q2 * q2 + q3 * q3;
  430.     if (squaredSine == 0) {
  431.       return convention == RotationConvention.VECTOR_OPERATOR ? Vector3D.PLUS_I : Vector3D.MINUS_I;
  432.     } else {
  433.         final double sgn = convention == RotationConvention.VECTOR_OPERATOR ? +1 : -1;
  434.         if (q0 < 0) {
  435.             final double inverse = sgn / FastMath.sqrt(squaredSine);
  436.             return new Vector3D(q1 * inverse, q2 * inverse, q3 * inverse);
  437.         }
  438.         final double inverse = -sgn / FastMath.sqrt(squaredSine);
  439.         return new Vector3D(q1 * inverse, q2 * inverse, q3 * inverse);
  440.     }
  441.   }

  442.   /** Get the angle of the rotation.
  443.    * @return angle of the rotation (between 0 and &pi;)
  444.    * @see #Rotation(Vector3D, double, RotationConvention)
  445.    */
  446.   public double getAngle() {
  447.     if ((q0 < -0.1) || (q0 > 0.1)) {
  448.       return 2 * FastMath.asin(FastMath.sqrt(q1 * q1 + q2 * q2 + q3 * q3));
  449.     } else if (q0 < 0) {
  450.       return 2 * FastMath.acos(-q0);
  451.     }
  452.     return 2 * FastMath.acos(q0);
  453.   }

  454.   /** Get the Cardan or Euler angles corresponding to the instance.

  455.    * <p>The equations show that each rotation can be defined by two
  456.    * different values of the Cardan or Euler angles set. For example
  457.    * if Cardan angles are used, the rotation defined by the angles
  458.    * a<sub>1</sub>, a<sub>2</sub> and a<sub>3</sub> is the same as
  459.    * the rotation defined by the angles &pi; + a<sub>1</sub>, &pi;
  460.    * - a<sub>2</sub> and &pi; + a<sub>3</sub>. This method implements
  461.    * the following arbitrary choices:</p>
  462.    * <ul>
  463.    *   <li>for Cardan angles, the chosen set is the one for which the
  464.    *   second angle is between -&pi;/2 and &pi;/2 (i.e its cosine is
  465.    *   positive),</li>
  466.    *   <li>for Euler angles, the chosen set is the one for which the
  467.    *   second angle is between 0 and &pi; (i.e its sine is positive).</li>
  468.    * </ul>

  469.    * <p>
  470.    * The algorithm used here works even when the rotation is exactly at the
  471.    * the singularity of the rotation order and convention. In this case, one of
  472.    * the angles in the singular pair is arbitrarily set to exactly 0 and the
  473.    * second angle is computed. The angle set to 0 in the singular case is the
  474.    * angle of the first rotation in the case of Cardan orders, and it is the angle
  475.    * of the last rotation in the case of Euler orders. This implies that extracting
  476.    * the angles of a rotation never fails (it used to trigger an exception in singular
  477.    * cases up to Hipparchus 3.0).
  478.    * </p>

  479.    * @param order rotation order to use
  480.    * @param convention convention to use for the semantics of the angle
  481.    * @return an array of three angles, in the order specified by the set
  482.    */
  483.   public double[] getAngles(RotationOrder order, RotationConvention convention) {
  484.       return order.getAngles(this, convention);
  485.   }

  486.   /** Get the 3X3 matrix corresponding to the instance
  487.    * @return the matrix corresponding to the instance
  488.    */
  489.   public double[][] getMatrix() {

  490.     // products
  491.     double q0q0  = q0 * q0;
  492.     double q0q1  = q0 * q1;
  493.     double q0q2  = q0 * q2;
  494.     double q0q3  = q0 * q3;
  495.     double q1q1  = q1 * q1;
  496.     double q1q2  = q1 * q2;
  497.     double q1q3  = q1 * q3;
  498.     double q2q2  = q2 * q2;
  499.     double q2q3  = q2 * q3;
  500.     double q3q3  = q3 * q3;

  501.     // create the matrix
  502.     double[][] m = new double[3][];
  503.     m[0] = new double[3];
  504.     m[1] = new double[3];
  505.     m[2] = new double[3];

  506.     m [0][0] = 2.0 * (q0q0 + q1q1) - 1.0;
  507.     m [1][0] = 2.0 * (q1q2 - q0q3);
  508.     m [2][0] = 2.0 * (q1q3 + q0q2);

  509.     m [0][1] = 2.0 * (q1q2 + q0q3);
  510.     m [1][1] = 2.0 * (q0q0 + q2q2) - 1.0;
  511.     m [2][1] = 2.0 * (q2q3 - q0q1);

  512.     m [0][2] = 2.0 * (q1q3 - q0q2);
  513.     m [1][2] = 2.0 * (q2q3 + q0q1);
  514.     m [2][2] = 2.0 * (q0q0 + q3q3) - 1.0;

  515.     return m;

  516.   }

  517.   /** Apply the rotation to a vector.
  518.    * @param u vector to apply the rotation to
  519.    * @return a new vector which is the image of u by the rotation
  520.    */
  521.   public Vector3D applyTo(Vector3D u) {

  522.     double x = u.getX();
  523.     double y = u.getY();
  524.     double z = u.getZ();

  525.     double s = q1 * x + q2 * y + q3 * z;

  526.     return new Vector3D(2 * (q0 * (x * q0 - (q2 * z - q3 * y)) + s * q1) - x,
  527.                         2 * (q0 * (y * q0 - (q3 * x - q1 * z)) + s * q2) - y,
  528.                         2 * (q0 * (z * q0 - (q1 * y - q2 * x)) + s * q3) - z);

  529.   }

  530.   /** Apply the rotation to a vector stored in an array.
  531.    * @param in an array with three items which stores vector to rotate
  532.    * @param out an array with three items to put result to (it can be the same
  533.    * array as in)
  534.    */
  535.   public void applyTo(final double[] in, final double[] out) {

  536.       final double x = in[0];
  537.       final double y = in[1];
  538.       final double z = in[2];

  539.       final double s = q1 * x + q2 * y + q3 * z;

  540.       out[0] = 2 * (q0 * (x * q0 - (q2 * z - q3 * y)) + s * q1) - x;
  541.       out[1] = 2 * (q0 * (y * q0 - (q3 * x - q1 * z)) + s * q2) - y;
  542.       out[2] = 2 * (q0 * (z * q0 - (q1 * y - q2 * x)) + s * q3) - z;

  543.   }

  544.   /** Apply the inverse of the rotation to a vector.
  545.    * @param u vector to apply the inverse of the rotation to
  546.    * @return a new vector which such that u is its image by the rotation
  547.    */
  548.   public Vector3D applyInverseTo(Vector3D u) {

  549.     double x = u.getX();
  550.     double y = u.getY();
  551.     double z = u.getZ();

  552.     double s = q1 * x + q2 * y + q3 * z;
  553.     double m0 = -q0;

  554.     return new Vector3D(2 * (m0 * (x * m0 - (q2 * z - q3 * y)) + s * q1) - x,
  555.                         2 * (m0 * (y * m0 - (q3 * x - q1 * z)) + s * q2) - y,
  556.                         2 * (m0 * (z * m0 - (q1 * y - q2 * x)) + s * q3) - z);

  557.   }

  558.   /** Apply the inverse of the rotation to a vector stored in an array.
  559.    * @param in an array with three items which stores vector to rotate
  560.    * @param out an array with three items to put result to (it can be the same
  561.    * array as in)
  562.    */
  563.   public void applyInverseTo(final double[] in, final double[] out) {

  564.       final double x = in[0];
  565.       final double y = in[1];
  566.       final double z = in[2];

  567.       final double s = q1 * x + q2 * y + q3 * z;
  568.       final double m0 = -q0;

  569.       out[0] = 2 * (m0 * (x * m0 - (q2 * z - q3 * y)) + s * q1) - x;
  570.       out[1] = 2 * (m0 * (y * m0 - (q3 * x - q1 * z)) + s * q2) - y;
  571.       out[2] = 2 * (m0 * (z * m0 - (q1 * y - q2 * x)) + s * q3) - z;

  572.   }

  573.   /** Apply the instance to another rotation.
  574.    * <p>
  575.    * Calling this method is equivalent to call
  576.    * {@link #compose(Rotation, RotationConvention)
  577.    * compose(r, RotationConvention.VECTOR_OPERATOR)}.
  578.    * </p>
  579.    * @param r rotation to apply the rotation to
  580.    * @return a new rotation which is the composition of r by the instance
  581.    */
  582.   public Rotation applyTo(Rotation r) {
  583.     return compose(r, RotationConvention.VECTOR_OPERATOR);
  584.   }

  585.   /** Compose the instance with another rotation.
  586.    * <p>
  587.    * If the semantics of the rotations composition corresponds to a
  588.    * {@link RotationConvention#VECTOR_OPERATOR vector operator} convention,
  589.    * applying the instance to a rotation is computing the composition
  590.    * in an order compliant with the following rule : let {@code u} be any
  591.    * vector and {@code v} its image by {@code r1} (i.e.
  592.    * {@code r1.applyTo(u) = v}). Let {@code w} be the image of {@code v} by
  593.    * rotation {@code r2} (i.e. {@code r2.applyTo(v) = w}). Then
  594.    * {@code w = comp.applyTo(u)}, where
  595.    * {@code comp = r2.compose(r1, RotationConvention.VECTOR_OPERATOR)}.
  596.    * </p>
  597.    * <p>
  598.    * If the semantics of the rotations composition corresponds to a
  599.    * {@link RotationConvention#FRAME_TRANSFORM frame transform} convention,
  600.    * the application order will be reversed. So keeping the exact same
  601.    * meaning of all {@code r1}, {@code r2}, {@code u}, {@code v}, {@code w}
  602.    * and  {@code comp} as above, {@code comp} could also be computed as
  603.    * {@code comp = r1.compose(r2, RotationConvention.FRAME_TRANSFORM)}.
  604.    * </p>
  605.    * @param r rotation to apply the rotation to
  606.    * @param convention convention to use for the semantics of the angle
  607.    * @return a new rotation which is the composition of r by the instance
  608.    */
  609.   public Rotation compose(final Rotation r, final RotationConvention convention) {
  610.     return convention == RotationConvention.VECTOR_OPERATOR ?
  611.            composeInternal(r) : r.composeInternal(this);
  612.   }

  613.   /** Compose the instance with another rotation using vector operator convention.
  614.    * @param r rotation to apply the rotation to
  615.    * @return a new rotation which is the composition of r by the instance
  616.    * using vector operator convention
  617.    */
  618.   private Rotation composeInternal(final Rotation r) {
  619.     return new Rotation(r.q0 * q0 - (r.q1 * q1 + r.q2 * q2 + r.q3 * q3),
  620.                         r.q1 * q0 + r.q0 * q1 + (r.q2 * q3 - r.q3 * q2),
  621.                         r.q2 * q0 + r.q0 * q2 + (r.q3 * q1 - r.q1 * q3),
  622.                         r.q3 * q0 + r.q0 * q3 + (r.q1 * q2 - r.q2 * q1),
  623.                         false);
  624.   }

  625.   /** Apply the inverse of the instance to another rotation.
  626.    * <p>
  627.    * Calling this method is equivalent to call
  628.    * {@link #composeInverse(Rotation, RotationConvention)
  629.    * composeInverse(r, RotationConvention.VECTOR_OPERATOR)}.
  630.    * </p>
  631.    * @param r rotation to apply the rotation to
  632.    * @return a new rotation which is the composition of r by the inverse
  633.    * of the instance
  634.    */
  635.   public Rotation applyInverseTo(Rotation r) {
  636.     return composeInverse(r, RotationConvention.VECTOR_OPERATOR);
  637.   }

  638.   /** Compose the inverse of the instance with another rotation.
  639.    * <p>
  640.    * If the semantics of the rotations composition corresponds to a
  641.    * {@link RotationConvention#VECTOR_OPERATOR vector operator} convention,
  642.    * applying the inverse of the instance to a rotation is computing
  643.    * the composition in an order compliant with the following rule :
  644.    * let {@code u} be any vector and {@code v} its image by {@code r1}
  645.    * (i.e. {@code r1.applyTo(u) = v}). Let {@code w} be the inverse image
  646.    * of {@code v} by {@code r2} (i.e. {@code r2.applyInverseTo(v) = w}).
  647.    * Then {@code w = comp.applyTo(u)}, where
  648.    * {@code comp = r2.composeInverse(r1)}.
  649.    * </p>
  650.    * <p>
  651.    * If the semantics of the rotations composition corresponds to a
  652.    * {@link RotationConvention#FRAME_TRANSFORM frame transform} convention,
  653.    * the application order will be reversed, which means it is the
  654.    * <em>innermost</em> rotation that will be reversed. So keeping the exact same
  655.    * meaning of all {@code r1}, {@code r2}, {@code u}, {@code v}, {@code w}
  656.    * and  {@code comp} as above, {@code comp} could also be computed as
  657.    * {@code comp = r1.revert().composeInverse(r2.revert(), RotationConvention.FRAME_TRANSFORM)}.
  658.    * </p>
  659.    * @param r rotation to apply the rotation to
  660.    * @param convention convention to use for the semantics of the angle
  661.    * @return a new rotation which is the composition of r by the inverse
  662.    * of the instance
  663.    */
  664.   public Rotation composeInverse(final Rotation r, final RotationConvention convention) {
  665.     return convention == RotationConvention.VECTOR_OPERATOR ?
  666.            composeInverseInternal(r) : r.composeInternal(revert());
  667.   }

  668.   /** Compose the inverse of the instance with another rotation
  669.    * using vector operator convention.
  670.    * @param r rotation to apply the rotation to
  671.    * @return a new rotation which is the composition of r by the inverse
  672.    * of the instance using vector operator convention
  673.    */
  674.   private Rotation composeInverseInternal(Rotation r) {
  675.     return new Rotation(-r.q0 * q0 - (r.q1 * q1 + r.q2 * q2 + r.q3 * q3),
  676.                         -r.q1 * q0 + r.q0 * q1 + (r.q2 * q3 - r.q3 * q2),
  677.                         -r.q2 * q0 + r.q0 * q2 + (r.q3 * q1 - r.q1 * q3),
  678.                         -r.q3 * q0 + r.q0 * q3 + (r.q1 * q2 - r.q2 * q1),
  679.                         false);
  680.   }

  681.   /** Perfect orthogonality on a 3X3 matrix.
  682.    * @param m initial matrix (not exactly orthogonal)
  683.    * @param threshold convergence threshold for the iterative
  684.    * orthogonality correction (convergence is reached when the
  685.    * difference between two steps of the Frobenius norm of the
  686.    * correction is below this threshold)
  687.    * @return an orthogonal matrix close to m
  688.    * @exception MathIllegalArgumentException if the matrix cannot be
  689.    * orthogonalized with the given threshold after 10 iterations
  690.    */
  691.   private double[][] orthogonalizeMatrix(double[][] m, double threshold)
  692.     throws MathIllegalArgumentException {
  693.     double[] m0 = m[0];
  694.     double[] m1 = m[1];
  695.     double[] m2 = m[2];
  696.     double x00 = m0[0];
  697.     double x01 = m0[1];
  698.     double x02 = m0[2];
  699.     double x10 = m1[0];
  700.     double x11 = m1[1];
  701.     double x12 = m1[2];
  702.     double x20 = m2[0];
  703.     double x21 = m2[1];
  704.     double x22 = m2[2];
  705.     double fn = 0;
  706.     double fn1;

  707.     double[][] o = new double[3][3];
  708.     double[] o0 = o[0];
  709.     double[] o1 = o[1];
  710.     double[] o2 = o[2];

  711.     // iterative correction: Xn+1 = Xn - 0.5 * (Xn.Mt.Xn - M)
  712.     int i;
  713.     for (i = 0; i < 11; ++i) {

  714.       // Mt.Xn
  715.       double mx00 = m0[0] * x00 + m1[0] * x10 + m2[0] * x20;
  716.       double mx10 = m0[1] * x00 + m1[1] * x10 + m2[1] * x20;
  717.       double mx20 = m0[2] * x00 + m1[2] * x10 + m2[2] * x20;
  718.       double mx01 = m0[0] * x01 + m1[0] * x11 + m2[0] * x21;
  719.       double mx11 = m0[1] * x01 + m1[1] * x11 + m2[1] * x21;
  720.       double mx21 = m0[2] * x01 + m1[2] * x11 + m2[2] * x21;
  721.       double mx02 = m0[0] * x02 + m1[0] * x12 + m2[0] * x22;
  722.       double mx12 = m0[1] * x02 + m1[1] * x12 + m2[1] * x22;
  723.       double mx22 = m0[2] * x02 + m1[2] * x12 + m2[2] * x22;

  724.       // Xn+1
  725.       o0[0] = x00 - 0.5 * (x00 * mx00 + x01 * mx10 + x02 * mx20 - m0[0]);
  726.       o0[1] = x01 - 0.5 * (x00 * mx01 + x01 * mx11 + x02 * mx21 - m0[1]);
  727.       o0[2] = x02 - 0.5 * (x00 * mx02 + x01 * mx12 + x02 * mx22 - m0[2]);
  728.       o1[0] = x10 - 0.5 * (x10 * mx00 + x11 * mx10 + x12 * mx20 - m1[0]);
  729.       o1[1] = x11 - 0.5 * (x10 * mx01 + x11 * mx11 + x12 * mx21 - m1[1]);
  730.       o1[2] = x12 - 0.5 * (x10 * mx02 + x11 * mx12 + x12 * mx22 - m1[2]);
  731.       o2[0] = x20 - 0.5 * (x20 * mx00 + x21 * mx10 + x22 * mx20 - m2[0]);
  732.       o2[1] = x21 - 0.5 * (x20 * mx01 + x21 * mx11 + x22 * mx21 - m2[1]);
  733.       o2[2] = x22 - 0.5 * (x20 * mx02 + x21 * mx12 + x22 * mx22 - m2[2]);

  734.       // correction on each elements
  735.       double corr00 = o0[0] - m0[0];
  736.       double corr01 = o0[1] - m0[1];
  737.       double corr02 = o0[2] - m0[2];
  738.       double corr10 = o1[0] - m1[0];
  739.       double corr11 = o1[1] - m1[1];
  740.       double corr12 = o1[2] - m1[2];
  741.       double corr20 = o2[0] - m2[0];
  742.       double corr21 = o2[1] - m2[1];
  743.       double corr22 = o2[2] - m2[2];

  744.       // Frobenius norm of the correction
  745.       fn1 = corr00 * corr00 + corr01 * corr01 + corr02 * corr02 +
  746.             corr10 * corr10 + corr11 * corr11 + corr12 * corr12 +
  747.             corr20 * corr20 + corr21 * corr21 + corr22 * corr22;

  748.       // convergence test
  749.       if (FastMath.abs(fn1 - fn) <= threshold) {
  750.           return o;
  751.       }

  752.       // prepare next iteration
  753.       x00 = o0[0];
  754.       x01 = o0[1];
  755.       x02 = o0[2];
  756.       x10 = o1[0];
  757.       x11 = o1[1];
  758.       x12 = o1[2];
  759.       x20 = o2[0];
  760.       x21 = o2[1];
  761.       x22 = o2[2];
  762.       fn  = fn1;

  763.     }

  764.     // the algorithm did not converge after 10 iterations
  765.     throw new MathIllegalArgumentException(LocalizedGeometryFormats.UNABLE_TO_ORTHOGONOLIZE_MATRIX,
  766.                                            i - 1);
  767.   }

  768.   /** Compute the <i>distance</i> between two rotations.
  769.    * <p>The <i>distance</i> is intended here as a way to check if two
  770.    * rotations are almost similar (i.e. they transform vectors the same way)
  771.    * or very different. It is mathematically defined as the angle of
  772.    * the rotation r that prepended to one of the rotations gives the other
  773.    * one: \(r_1(r) = r_2\)
  774.    * </p>
  775.    * <p>This distance is an angle between 0 and &pi;. Its value is the smallest
  776.    * possible upper bound of the angle in radians between r<sub>1</sub>(v)
  777.    * and r<sub>2</sub>(v) for all possible vectors v. This upper bound is
  778.    * reached for some v. The distance is equal to 0 if and only if the two
  779.    * rotations are identical.</p>
  780.    * <p>Comparing two rotations should always be done using this value rather
  781.    * than for example comparing the components of the quaternions. It is much
  782.    * more stable, and has a geometric meaning. Also comparing quaternions
  783.    * components is error prone since for example quaternions (0.36, 0.48, -0.48, -0.64)
  784.    * and (-0.36, -0.48, 0.48, 0.64) represent exactly the same rotation despite
  785.    * their components are different (they are exact opposites).</p>
  786.    * @param r1 first rotation
  787.    * @param r2 second rotation
  788.    * @return <i>distance</i> between r1 and r2
  789.    */
  790.   public static double distance(Rotation r1, Rotation r2) {
  791.       return r1.composeInverseInternal(r2).getAngle();
  792.   }

  793. }