FieldRotation.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.CalculusFieldElement;
  24. import org.hipparchus.Field;
  25. import org.hipparchus.exception.MathIllegalArgumentException;
  26. import org.hipparchus.exception.MathRuntimeException;
  27. import org.hipparchus.geometry.LocalizedGeometryFormats;
  28. import org.hipparchus.util.FastMath;
  29. import org.hipparchus.util.FieldSinCos;
  30. import org.hipparchus.util.MathArrays;

  31. /**
  32.  * This class is a re-implementation of {@link Rotation} using {@link CalculusFieldElement}.
  33.  * <p>Instance of this class are guaranteed to be immutable.</p>
  34.  *
  35.  * @param <T> the type of the field elements
  36.  * @see FieldVector3D
  37.  * @see RotationOrder
  38.  */

  39. public class FieldRotation<T extends CalculusFieldElement<T>> implements Serializable {

  40.     /** Serializable version identifier */
  41.     private static final long serialVersionUID = 20130224L;

  42.     /** Scalar coordinate of the quaternion. */
  43.     private final T q0;

  44.     /** First coordinate of the vectorial part of the quaternion. */
  45.     private final T q1;

  46.     /** Second coordinate of the vectorial part of the quaternion. */
  47.     private final T q2;

  48.     /** Third coordinate of the vectorial part of the quaternion. */
  49.     private final T q3;

  50.     /** Build a rotation from the quaternion coordinates.
  51.      * <p>A rotation can be built from a <em>normalized</em> quaternion,
  52.      * i.e. a quaternion for which q<sub>0</sub><sup>2</sup> +
  53.      * q<sub>1</sub><sup>2</sup> + q<sub>2</sub><sup>2</sup> +
  54.      * q<sub>3</sub><sup>2</sup> = 1. If the quaternion is not normalized,
  55.      * the constructor can normalize it in a preprocessing step.</p>
  56.      * <p>Note that some conventions put the scalar part of the quaternion
  57.      * as the 4<sup>th</sup> component and the vector part as the first three
  58.      * components. This is <em>not</em> our convention. We put the scalar part
  59.      * as the first component.</p>
  60.      * @param q0 scalar part of the quaternion
  61.      * @param q1 first coordinate of the vectorial part of the quaternion
  62.      * @param q2 second coordinate of the vectorial part of the quaternion
  63.      * @param q3 third coordinate of the vectorial part of the quaternion
  64.      * @param needsNormalization if true, the coordinates are considered
  65.      * not to be normalized, a normalization preprocessing step is performed
  66.      * before using them
  67.      */
  68.     public FieldRotation(final T q0, final T q1, final T q2, final T q3, final boolean needsNormalization) {

  69.         if (needsNormalization) {
  70.             // normalization preprocessing
  71.             final T inv =
  72.                     q0.square().add(q1.square()).add(q2.square()).add(q3.square()).sqrt().reciprocal();
  73.             this.q0 = inv.multiply(q0);
  74.             this.q1 = inv.multiply(q1);
  75.             this.q2 = inv.multiply(q2);
  76.             this.q3 = inv.multiply(q3);
  77.         } else {
  78.             this.q0 = q0;
  79.             this.q1 = q1;
  80.             this.q2 = q2;
  81.             this.q3 = q3;
  82.         }

  83.     }

  84.     /** Build a rotation from an axis and an angle.
  85.      * <p>We use the convention that angles are oriented according to
  86.      * the effect of the rotation on vectors around the axis. That means
  87.      * that if (i, j, k) is a direct frame and if we first provide +k as
  88.      * the axis and &pi;/2 as the angle to this constructor, and then
  89.      * {@link #applyTo(FieldVector3D) apply} the instance to +i, we will get
  90.      * +j.</p>
  91.      * <p>Another way to represent our convention is to say that a rotation
  92.      * of angle &theta; about the unit vector (x, y, z) is the same as the
  93.      * rotation build from quaternion components { cos(-&theta;/2),
  94.      * x * sin(-&theta;/2), y * sin(-&theta;/2), z * sin(-&theta;/2) }.
  95.      * Note the minus sign on the angle!</p>
  96.      * <p>On the one hand this convention is consistent with a vectorial
  97.      * perspective (moving vectors in fixed frames), on the other hand it
  98.      * is different from conventions with a frame perspective (fixed vectors
  99.      * viewed from different frames) like the ones used for example in spacecraft
  100.      * attitude community or in the graphics community.</p>
  101.      * @param axis axis around which to rotate
  102.      * @param angle rotation angle.
  103.      * @param convention convention to use for the semantics of the angle
  104.      * @exception MathIllegalArgumentException if the axis norm is zero
  105.      */
  106.     public FieldRotation(final FieldVector3D<T> axis, final T angle, final RotationConvention convention)
  107.         throws MathIllegalArgumentException {

  108.         final T norm = axis.getNorm();
  109.         if (norm.getReal() == 0) {
  110.             throw new MathIllegalArgumentException(LocalizedGeometryFormats.ZERO_NORM_FOR_ROTATION_AXIS);
  111.         }

  112.         final T halfAngle = angle.multiply(convention == RotationConvention.VECTOR_OPERATOR ? -0.5 : 0.5);
  113.         final FieldSinCos<T> sinCos = FastMath.sinCos(halfAngle);
  114.         final T coeff = sinCos.sin().divide(norm);

  115.         q0 = sinCos.cos();
  116.         q1 = coeff.multiply(axis.getX());
  117.         q2 = coeff.multiply(axis.getY());
  118.         q3 = coeff.multiply(axis.getZ());

  119.     }

  120.     /** Build a {@link FieldRotation} from a {@link Rotation}.
  121.      * @param field field for the components
  122.      * @param r rotation to convert
  123.      */
  124.     public FieldRotation(final Field<T> field, final Rotation r) {
  125.         this.q0 = field.getZero().add(r.getQ0());
  126.         this.q1 = field.getZero().add(r.getQ1());
  127.         this.q2 = field.getZero().add(r.getQ2());
  128.         this.q3 = field.getZero().add(r.getQ3());
  129.     }

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

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

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

  145.      * @param m rotation matrix
  146.      * @param threshold convergence threshold for the iterative
  147.      * orthogonality correction (convergence is reached when the
  148.      * difference between two steps of the Frobenius norm of the
  149.      * correction is below this threshold)

  150.      * @exception MathIllegalArgumentException if the matrix is not a 3X3
  151.      * matrix, or if it cannot be transformed into an orthogonal matrix
  152.      * with the given threshold, or if the determinant of the resulting
  153.      * orthogonal matrix is negative

  154.      */
  155.     public FieldRotation(final T[][] m, final double threshold)
  156.         throws MathIllegalArgumentException {

  157.         // dimension check
  158.         if ((m.length != 3) || (m[0].length != 3) ||
  159.                 (m[1].length != 3) || (m[2].length != 3)) {
  160.             throw new MathIllegalArgumentException(LocalizedGeometryFormats.ROTATION_MATRIX_DIMENSIONS,
  161.                                                    m.length, m[0].length);
  162.         }

  163.         // compute a "close" orthogonal matrix
  164.         final T[][] ort = orthogonalizeMatrix(m, threshold);

  165.         // check the sign of the determinant
  166.         final T d0 = ort[1][1].multiply(ort[2][2]).subtract(ort[2][1].multiply(ort[1][2]));
  167.         final T d1 = ort[0][1].multiply(ort[2][2]).subtract(ort[2][1].multiply(ort[0][2]));
  168.         final T d2 = ort[0][1].multiply(ort[1][2]).subtract(ort[1][1].multiply(ort[0][2]));
  169.         final T det =
  170.                 ort[0][0].multiply(d0).subtract(ort[1][0].multiply(d1)).add(ort[2][0].multiply(d2));
  171.         if (det.getReal() < 0.0) {
  172.             throw new MathIllegalArgumentException(LocalizedGeometryFormats.CLOSEST_ORTHOGONAL_MATRIX_HAS_NEGATIVE_DETERMINANT,
  173.                                                    det);
  174.         }

  175.         final T[] quat = mat2quat(ort);
  176.         q0 = quat[0];
  177.         q1 = quat[1];
  178.         q2 = quat[2];
  179.         q3 = quat[3];

  180.     }

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

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

  185.      * <p>If the angular separation between u<sub>1</sub> and u<sub>2</sub> is
  186.      * not the same as the angular separation between v<sub>1</sub> and
  187.      * v<sub>2</sub>, then a corrected v'<sub>2</sub> will be used rather than
  188.      * v<sub>2</sub>, the corrected vector will be in the (±v<sub>1</sub>,
  189.      * +v<sub>2</sub>) half-plane.</p>
  190.      * @param u1 first vector of the origin pair
  191.      * @param u2 second vector of the origin pair
  192.      * @param v1 desired image of u1 by the rotation
  193.      * @param v2 desired image of u2 by the rotation
  194.      * @exception MathRuntimeException if the norm of one of the vectors is zero,
  195.      * or if one of the pair is degenerated (i.e. the vectors of the pair are collinear)
  196.      */
  197.     public FieldRotation(FieldVector3D<T> u1, FieldVector3D<T> u2, FieldVector3D<T> v1, FieldVector3D<T> v2)
  198.         throws MathRuntimeException {

  199.         // build orthonormalized base from u1, u2
  200.         // this fails when vectors are null or collinear, which is forbidden to define a rotation
  201.         final FieldVector3D<T> u3 = FieldVector3D.crossProduct(u1, u2).normalize();
  202.         u2 = FieldVector3D.crossProduct(u3, u1).normalize();
  203.         u1 = u1.normalize();

  204.         // build an orthonormalized base from v1, v2
  205.         // this fails when vectors are null or collinear, which is forbidden to define a rotation
  206.         final FieldVector3D<T> v3 = FieldVector3D.crossProduct(v1, v2).normalize();
  207.         v2 = FieldVector3D.crossProduct(v3, v1).normalize();
  208.         v1 = v1.normalize();

  209.         // buid a matrix transforming the first base into the second one
  210.         final T[][] array = MathArrays.buildArray(u1.getX().getField(), 3, 3);
  211.         array[0][0] = u1.getX().multiply(v1.getX()).add(u2.getX().multiply(v2.getX())).add(u3.getX().multiply(v3.getX()));
  212.         array[0][1] = u1.getY().multiply(v1.getX()).add(u2.getY().multiply(v2.getX())).add(u3.getY().multiply(v3.getX()));
  213.         array[0][2] = u1.getZ().multiply(v1.getX()).add(u2.getZ().multiply(v2.getX())).add(u3.getZ().multiply(v3.getX()));
  214.         array[1][0] = u1.getX().multiply(v1.getY()).add(u2.getX().multiply(v2.getY())).add(u3.getX().multiply(v3.getY()));
  215.         array[1][1] = u1.getY().multiply(v1.getY()).add(u2.getY().multiply(v2.getY())).add(u3.getY().multiply(v3.getY()));
  216.         array[1][2] = u1.getZ().multiply(v1.getY()).add(u2.getZ().multiply(v2.getY())).add(u3.getZ().multiply(v3.getY()));
  217.         array[2][0] = u1.getX().multiply(v1.getZ()).add(u2.getX().multiply(v2.getZ())).add(u3.getX().multiply(v3.getZ()));
  218.         array[2][1] = u1.getY().multiply(v1.getZ()).add(u2.getY().multiply(v2.getZ())).add(u3.getY().multiply(v3.getZ()));
  219.         array[2][2] = u1.getZ().multiply(v1.getZ()).add(u2.getZ().multiply(v2.getZ())).add(u3.getZ().multiply(v3.getZ()));

  220.         T[] quat = mat2quat(array);
  221.         q0 = quat[0];
  222.         q1 = quat[1];
  223.         q2 = quat[2];
  224.         q3 = quat[3];

  225.     }

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

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

  233.      * @param u origin vector
  234.      * @param v desired image of u by the rotation
  235.      * @exception MathRuntimeException if the norm of one of the vectors is zero
  236.      */
  237.     public FieldRotation(final FieldVector3D<T> u, final FieldVector3D<T> v) throws MathRuntimeException {

  238.         final T normProduct = u.getNorm().multiply(v.getNorm());
  239.         if (normProduct.getReal() == 0) {
  240.             throw new MathRuntimeException(LocalizedGeometryFormats.ZERO_NORM_FOR_ROTATION_DEFINING_VECTOR);
  241.         }

  242.         final T dot = FieldVector3D.dotProduct(u, v);

  243.         if (dot.getReal() < ((2.0e-15 - 1.0) * normProduct.getReal())) {
  244.             // special case u = -v: we select a PI angle rotation around
  245.             // an arbitrary vector orthogonal to u
  246.             final FieldVector3D<T> w = u.orthogonal();
  247.             q0 = normProduct.getField().getZero();
  248.             q1 = w.getX().negate();
  249.             q2 = w.getY().negate();
  250.             q3 = w.getZ().negate();
  251.         } else {
  252.             // general case: (u, v) defines a plane, we select
  253.             // the shortest possible rotation: axis orthogonal to this plane
  254.             q0 = dot.divide(normProduct).add(1.0).multiply(0.5).sqrt();
  255.             final T coeff = q0.multiply(normProduct).multiply(2.0).reciprocal();
  256.             final FieldVector3D<T> q = FieldVector3D.crossProduct(v, u);
  257.             q1 = coeff.multiply(q.getX());
  258.             q2 = coeff.multiply(q.getY());
  259.             q3 = coeff.multiply(q.getZ());
  260.         }

  261.     }

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

  263.      * <p>Cardan rotations are three successive rotations around the
  264.      * canonical axes X, Y and Z, each axis being used once. There are
  265.      * 6 such sets of rotations (XYZ, XZY, YXZ, YZX, ZXY and ZYX). Euler
  266.      * rotations are three successive rotations around the canonical
  267.      * axes X, Y and Z, the first and last rotations being around the
  268.      * same axis. There are 6 such sets of rotations (XYX, XZX, YXY,
  269.      * YZY, ZXZ and ZYZ), the most popular one being ZXZ.</p>
  270.      * <p>Beware that many people routinely use the term Euler angles even
  271.      * for what really are Cardan angles (this confusion is especially
  272.      * widespread in the aerospace business where Roll, Pitch and Yaw angles
  273.      * are often wrongly tagged as Euler angles).</p>

  274.      * @param order order of rotations to compose, from left to right
  275.      * (i.e. we will use {@code r1.compose(r2.compose(r3, convention), convention)})
  276.      * @param convention convention to use for the semantics of the angle
  277.      * @param alpha1 angle of the first elementary rotation
  278.      * @param alpha2 angle of the second elementary rotation
  279.      * @param alpha3 angle of the third elementary rotation
  280.      */
  281.     public FieldRotation(final RotationOrder order, final RotationConvention convention,
  282.                          final T alpha1, final T alpha2, final T alpha3) {
  283.         final Field<T> field = alpha1.getField();
  284.         final FieldRotation<T> r1 = new FieldRotation<>(new FieldVector3D<>(field, order.getA1()), alpha1, convention);
  285.         final FieldRotation<T> r2 = new FieldRotation<>(new FieldVector3D<>(field, order.getA2()), alpha2, convention);
  286.         final FieldRotation<T> r3 = new FieldRotation<>(new FieldVector3D<>(field, order.getA3()), alpha3, convention);
  287.         final FieldRotation<T> composed = r1.compose(r2.compose(r3, convention), convention);
  288.         q0 = composed.q0;
  289.         q1 = composed.q1;
  290.         q2 = composed.q2;
  291.         q3 = composed.q3;
  292.     }

  293.     /** Get identity rotation.
  294.      * @param field field for the components
  295.      * @return a new rotation
  296.      * @param <T> the type of the field elements
  297.      */
  298.     public static <T extends CalculusFieldElement<T>> FieldRotation<T> getIdentity(final Field<T> field) {
  299.         return new FieldRotation<>(field, Rotation.IDENTITY);
  300.     }

  301.     /** Convert an orthogonal rotation matrix to a quaternion.
  302.      * @param ort orthogonal rotation matrix
  303.      * @return quaternion corresponding to the matrix
  304.      */
  305.     private T[] mat2quat(final T[][] ort) {

  306.         final T[] quat = MathArrays.buildArray(ort[0][0].getField(), 4);

  307.         // There are different ways to compute the quaternions elements
  308.         // from the matrix. They all involve computing one element from
  309.         // the diagonal of the matrix, and computing the three other ones
  310.         // using a formula involving a division by the first element,
  311.         // which unfortunately can be zero. Since the norm of the
  312.         // quaternion is 1, we know at least one element has an absolute
  313.         // value greater or equal to 0.5, so it is always possible to
  314.         // select the right formula and avoid division by zero and even
  315.         // numerical inaccuracy. Checking the elements in turn and using
  316.         // the first one greater than 0.45 is safe (this leads to a simple
  317.         // test since qi = 0.45 implies 4 qi^2 - 1 = -0.19)
  318.         T s = ort[0][0].add(ort[1][1]).add(ort[2][2]);
  319.         if (s.getReal() > -0.19) {
  320.             // compute q0 and deduce q1, q2 and q3
  321.             quat[0] = s.add(1.0).sqrt().multiply(0.5);
  322.             T inv = quat[0].reciprocal().multiply(0.25);
  323.             quat[1] = inv.multiply(ort[1][2].subtract(ort[2][1]));
  324.             quat[2] = inv.multiply(ort[2][0].subtract(ort[0][2]));
  325.             quat[3] = inv.multiply(ort[0][1].subtract(ort[1][0]));
  326.         } else {
  327.             s = ort[0][0].subtract(ort[1][1]).subtract(ort[2][2]);
  328.             if (s.getReal() > -0.19) {
  329.                 // compute q1 and deduce q0, q2 and q3
  330.                 quat[1] = s.add(1.0).sqrt().multiply(0.5);
  331.                 T inv = quat[1].reciprocal().multiply(0.25);
  332.                 quat[0] = inv.multiply(ort[1][2].subtract(ort[2][1]));
  333.                 quat[2] = inv.multiply(ort[0][1].add(ort[1][0]));
  334.                 quat[3] = inv.multiply(ort[0][2].add(ort[2][0]));
  335.             } else {
  336.                 s = ort[1][1].subtract(ort[0][0]).subtract(ort[2][2]);
  337.                 if (s.getReal() > -0.19) {
  338.                     // compute q2 and deduce q0, q1 and q3
  339.                     quat[2] = s.add(1.0).sqrt().multiply(0.5);
  340.                     T inv = quat[2].reciprocal().multiply(0.25);
  341.                     quat[0] = inv.multiply(ort[2][0].subtract(ort[0][2]));
  342.                     quat[1] = inv.multiply(ort[0][1].add(ort[1][0]));
  343.                     quat[3] = inv.multiply(ort[2][1].add(ort[1][2]));
  344.                 } else {
  345.                     // compute q3 and deduce q0, q1 and q2
  346.                     s = ort[2][2].subtract(ort[0][0]).subtract(ort[1][1]);
  347.                     quat[3] = s.add(1.0).sqrt().multiply(0.5);
  348.                     T inv = quat[3].reciprocal().multiply(0.25);
  349.                     quat[0] = inv.multiply(ort[0][1].subtract(ort[1][0]));
  350.                     quat[1] = inv.multiply(ort[0][2].add(ort[2][0]));
  351.                     quat[2] = inv.multiply(ort[2][1].add(ort[1][2]));
  352.                 }
  353.             }
  354.         }

  355.         return quat;

  356.     }

  357.     /** Revert a rotation.
  358.      * Build a rotation which reverse the effect of another
  359.      * rotation. This means that if r(u) = v, then r.revert(v) = u. The
  360.      * instance is not changed.
  361.      * @return a new rotation whose effect is the reverse of the effect
  362.      * of the instance
  363.      */
  364.     public FieldRotation<T> revert() {
  365.         return new FieldRotation<>(q0.negate(), q1, q2, q3, false);
  366.     }

  367.     /** Get the scalar coordinate of the quaternion.
  368.      * @return scalar coordinate of the quaternion
  369.      */
  370.     public T getQ0() {
  371.         return q0;
  372.     }

  373.     /** Get the first coordinate of the vectorial part of the quaternion.
  374.      * @return first coordinate of the vectorial part of the quaternion
  375.      */
  376.     public T getQ1() {
  377.         return q1;
  378.     }

  379.     /** Get the second coordinate of the vectorial part of the quaternion.
  380.      * @return second coordinate of the vectorial part of the quaternion
  381.      */
  382.     public T getQ2() {
  383.         return q2;
  384.     }

  385.     /** Get the third coordinate of the vectorial part of the quaternion.
  386.      * @return third coordinate of the vectorial part of the quaternion
  387.      */
  388.     public T getQ3() {
  389.         return q3;
  390.     }

  391.     /** Get the normalized axis of the rotation.
  392.      * <p>
  393.      * Note that as {@link #getAngle()} always returns an angle
  394.      * between 0 and &pi;, changing the convention changes the
  395.      * direction of the axis, not the sign of the angle.
  396.      * </p>
  397.      * @param convention convention to use for the semantics of the angle
  398.      * @return normalized axis of the rotation
  399.      * @see #FieldRotation(FieldVector3D, CalculusFieldElement, RotationConvention)
  400.      */
  401.     public FieldVector3D<T> getAxis(final RotationConvention convention) {
  402.         final T squaredSine = q1.square().add(q2.square()).add(q3.square());
  403.         if (squaredSine.getReal() == 0) {
  404.             final Field<T> field = squaredSine.getField();
  405.             return new FieldVector3D<>(convention == RotationConvention.VECTOR_OPERATOR ? field.getOne(): field.getOne().negate(),
  406.                                        field.getZero(),
  407.                                        field.getZero());
  408.         } else {
  409.             final double sgn = convention == RotationConvention.VECTOR_OPERATOR ? +1 : -1;
  410.             if (q0.getReal() < 0) {
  411.                 T inverse = squaredSine.sqrt().reciprocal().multiply(sgn);
  412.                 return new FieldVector3D<>(q1.multiply(inverse), q2.multiply(inverse), q3.multiply(inverse));
  413.             }
  414.             final T inverse = squaredSine.sqrt().reciprocal().negate().multiply(sgn);
  415.             return new FieldVector3D<>(q1.multiply(inverse), q2.multiply(inverse), q3.multiply(inverse));
  416.         }
  417.     }

  418.     /** Get the angle of the rotation.
  419.      * @return angle of the rotation (between 0 and &pi;)
  420.      * @see #FieldRotation(FieldVector3D, CalculusFieldElement, RotationConvention)
  421.      */
  422.     public T getAngle() {
  423.         if ((q0.getReal() < -0.1) || (q0.getReal() > 0.1)) {
  424.             return q1.square().add(q2.square()).add(q3.square()).sqrt().asin().multiply(2);
  425.         } else if (q0.getReal() < 0) {
  426.             return q0.negate().acos().multiply(2);
  427.         }
  428.         return q0.acos().multiply(2);
  429.     }

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

  431.      * <p>The equations show that each rotation can be defined by two
  432.      * different values of the Cardan or Euler angles set. For example
  433.      * if Cardan angles are used, the rotation defined by the angles
  434.      * a<sub>1</sub>, a<sub>2</sub> and a<sub>3</sub> is the same as
  435.      * the rotation defined by the angles &pi; + a<sub>1</sub>, &pi;
  436.      * - a<sub>2</sub> and &pi; + a<sub>3</sub>. This method implements
  437.      * the following arbitrary choices:</p>
  438.      * <ul>
  439.      *   <li>for Cardan angles, the chosen set is the one for which the
  440.      *   second angle is between -&pi;/2 and &pi;/2 (i.e its cosine is
  441.      *   positive),</li>
  442.      *   <li>for Euler angles, the chosen set is the one for which the
  443.      *   second angle is between 0 and &pi; (i.e its sine is positive).</li>
  444.      * </ul>

  445.      * <p>
  446.      * The algorithm used here works even when the rotation is exactly at the
  447.      * the singularity of the rotation order and convention. In this case, one of
  448.      * the angles in the singular pair is arbitrarily set to exactly 0 and the
  449.      * second angle is computed. The angle set to 0 in the singular case is the
  450.      * angle of the first rotation in the case of Cardan orders, and it is the angle
  451.      * of the last rotation in the case of Euler orders. This implies that extracting
  452.      * the angles of a rotation never fails (it used to trigger an exception in singular
  453.      * cases up to Hipparchus 3.0).
  454.      * </p>

  455.      * @param order rotation order to use
  456.      * @param convention convention to use for the semantics of the angle
  457.      * @return an array of three angles, in the order specified by the set
  458.      */
  459.     public T[] getAngles(final RotationOrder order, RotationConvention convention) {
  460.         return order.getAngles(this, convention);
  461.     }

  462.     /** Get the 3X3 matrix corresponding to the instance
  463.      * @return the matrix corresponding to the instance
  464.      */
  465.     public T[][] getMatrix() {

  466.         // products
  467.         final T q0q0  = q0.square();
  468.         final T q0q1  = q0.multiply(q1);
  469.         final T q0q2  = q0.multiply(q2);
  470.         final T q0q3  = q0.multiply(q3);
  471.         final T q1q1  = q1.square();
  472.         final T q1q2  = q1.multiply(q2);
  473.         final T q1q3  = q1.multiply(q3);
  474.         final T q2q2  = q2.square();
  475.         final T q2q3  = q2.multiply(q3);
  476.         final T q3q3  = q3.square();

  477.         // create the matrix
  478.         final T[][] m = MathArrays.buildArray(q0.getField(), 3, 3);

  479.         m [0][0] = q0q0.add(q1q1).multiply(2).subtract(1);
  480.         m [1][0] = q1q2.subtract(q0q3).multiply(2);
  481.         m [2][0] = q1q3.add(q0q2).multiply(2);

  482.         m [0][1] = q1q2.add(q0q3).multiply(2);
  483.         m [1][1] = q0q0.add(q2q2).multiply(2).subtract(1);
  484.         m [2][1] = q2q3.subtract(q0q1).multiply(2);

  485.         m [0][2] = q1q3.subtract(q0q2).multiply(2);
  486.         m [1][2] = q2q3.add(q0q1).multiply(2);
  487.         m [2][2] = q0q0.add(q3q3).multiply(2).subtract(1);

  488.         return m;

  489.     }

  490.     /** Convert to a constant vector without derivatives.
  491.      * @return a constant vector
  492.      */
  493.     public Rotation toRotation() {
  494.         return new Rotation(q0.getReal(), q1.getReal(), q2.getReal(), q3.getReal(), false);
  495.     }

  496.     /** Apply the rotation to a vector.
  497.      * @param u vector to apply the rotation to
  498.      * @return a new vector which is the image of u by the rotation
  499.      */
  500.     public FieldVector3D<T> applyTo(final FieldVector3D<T> u) {

  501.         final T x = u.getX();
  502.         final T y = u.getY();
  503.         final T z = u.getZ();

  504.         final T s = q1.multiply(x).add(q2.multiply(y)).add(q3.multiply(z));

  505.         return new FieldVector3D<>(q0.multiply(x.multiply(q0).subtract(q2.multiply(z).subtract(q3.multiply(y)))).add(s.multiply(q1)).multiply(2).subtract(x),
  506.                                    q0.multiply(y.multiply(q0).subtract(q3.multiply(x).subtract(q1.multiply(z)))).add(s.multiply(q2)).multiply(2).subtract(y),
  507.                                    q0.multiply(z.multiply(q0).subtract(q1.multiply(y).subtract(q2.multiply(x)))).add(s.multiply(q3)).multiply(2).subtract(z));

  508.     }

  509.     /** Apply the rotation to a vector.
  510.      * @param u vector to apply the rotation to
  511.      * @return a new vector which is the image of u by the rotation
  512.      */
  513.     public FieldVector3D<T> applyTo(final Vector3D u) {

  514.         final double x = u.getX();
  515.         final double y = u.getY();
  516.         final double z = u.getZ();

  517.         final T s = q1.multiply(x).add(q2.multiply(y)).add(q3.multiply(z));

  518.         return new FieldVector3D<>(q0.multiply(q0.multiply(x).subtract(q2.multiply(z).subtract(q3.multiply(y)))).add(s.multiply(q1)).multiply(2).subtract(x),
  519.                                    q0.multiply(q0.multiply(y).subtract(q3.multiply(x).subtract(q1.multiply(z)))).add(s.multiply(q2)).multiply(2).subtract(y),
  520.                                    q0.multiply(q0.multiply(z).subtract(q1.multiply(y).subtract(q2.multiply(x)))).add(s.multiply(q3)).multiply(2).subtract(z));

  521.     }

  522.     /** Apply the rotation to a vector stored in an array.
  523.      * @param in an array with three items which stores vector to rotate
  524.      * @param out an array with three items to put result to (it can be the same
  525.      * array as in)
  526.      */
  527.     public void applyTo(final T[] in, final T[] out) {

  528.         final T x = in[0];
  529.         final T y = in[1];
  530.         final T z = in[2];

  531.         final T s = q1.multiply(x).add(q2.multiply(y)).add(q3.multiply(z));

  532.         out[0] = q0.multiply(x.multiply(q0).subtract(q2.multiply(z).subtract(q3.multiply(y)))).add(s.multiply(q1)).multiply(2).subtract(x);
  533.         out[1] = q0.multiply(y.multiply(q0).subtract(q3.multiply(x).subtract(q1.multiply(z)))).add(s.multiply(q2)).multiply(2).subtract(y);
  534.         out[2] = q0.multiply(z.multiply(q0).subtract(q1.multiply(y).subtract(q2.multiply(x)))).add(s.multiply(q3)).multiply(2).subtract(z);

  535.     }

  536.     /** Apply the rotation to a vector stored in an array.
  537.      * @param in an array with three items which stores vector to rotate
  538.      * @param out an array with three items to put result to
  539.      */
  540.     public void applyTo(final double[] in, final T[] out) {

  541.         final double x = in[0];
  542.         final double y = in[1];
  543.         final double z = in[2];

  544.         final T s = q1.multiply(x).add(q2.multiply(y)).add(q3.multiply(z));

  545.         out[0] = q0.multiply(q0.multiply(x).subtract(q2.multiply(z).subtract(q3.multiply(y)))).add(s.multiply(q1)).multiply(2).subtract(x);
  546.         out[1] = q0.multiply(q0.multiply(y).subtract(q3.multiply(x).subtract(q1.multiply(z)))).add(s.multiply(q2)).multiply(2).subtract(y);
  547.         out[2] = q0.multiply(q0.multiply(z).subtract(q1.multiply(y).subtract(q2.multiply(x)))).add(s.multiply(q3)).multiply(2).subtract(z);

  548.     }

  549.     /** Apply a rotation to a vector.
  550.      * @param r rotation to apply
  551.      * @param u vector to apply the rotation to
  552.      * @param <T> the type of the field elements
  553.      * @return a new vector which is the image of u by the rotation
  554.      */
  555.     public static <T extends CalculusFieldElement<T>> FieldVector3D<T> applyTo(final Rotation r, final FieldVector3D<T> u) {

  556.         final T x = u.getX();
  557.         final T y = u.getY();
  558.         final T z = u.getZ();

  559.         final T s = x.multiply(r.getQ1()).add(y.multiply(r.getQ2())).add(z.multiply(r.getQ3()));

  560.         return new FieldVector3D<>(x.multiply(r.getQ0()).subtract(z.multiply(r.getQ2()).subtract(y.multiply(r.getQ3()))).multiply(r.getQ0()).add(s.multiply(r.getQ1())).multiply(2).subtract(x),
  561.                                    y.multiply(r.getQ0()).subtract(x.multiply(r.getQ3()).subtract(z.multiply(r.getQ1()))).multiply(r.getQ0()).add(s.multiply(r.getQ2())).multiply(2).subtract(y),
  562.                                    z.multiply(r.getQ0()).subtract(y.multiply(r.getQ1()).subtract(x.multiply(r.getQ2()))).multiply(r.getQ0()).add(s.multiply(r.getQ3())).multiply(2).subtract(z));

  563.     }

  564.     /** Apply the inverse of the rotation to a vector.
  565.      * @param u vector to apply the inverse of the rotation to
  566.      * @return a new vector which such that u is its image by the rotation
  567.      */
  568.     public FieldVector3D<T> applyInverseTo(final FieldVector3D<T> u) {

  569.         final T x = u.getX();
  570.         final T y = u.getY();
  571.         final T z = u.getZ();

  572.         final T s  = q1.multiply(x).add(q2.multiply(y)).add(q3.multiply(z));
  573.         final T m0 = q0.negate();

  574.         return new FieldVector3D<>(m0.multiply(x.multiply(m0).subtract(q2.multiply(z).subtract(q3.multiply(y)))).add(s.multiply(q1)).multiply(2).subtract(x),
  575.                                    m0.multiply(y.multiply(m0).subtract(q3.multiply(x).subtract(q1.multiply(z)))).add(s.multiply(q2)).multiply(2).subtract(y),
  576.                                    m0.multiply(z.multiply(m0).subtract(q1.multiply(y).subtract(q2.multiply(x)))).add(s.multiply(q3)).multiply(2).subtract(z));

  577.     }

  578.     /** Apply the inverse of the rotation to a vector.
  579.      * @param u vector to apply the inverse of the rotation to
  580.      * @return a new vector which such that u is its image by the rotation
  581.      */
  582.     public FieldVector3D<T> applyInverseTo(final Vector3D u) {

  583.         final double x = u.getX();
  584.         final double y = u.getY();
  585.         final double z = u.getZ();

  586.         final T s  = q1.multiply(x).add(q2.multiply(y)).add(q3.multiply(z));
  587.         final T m0 = q0.negate();

  588.         return new FieldVector3D<>(m0.multiply(m0.multiply(x).subtract(q2.multiply(z).subtract(q3.multiply(y)))).add(s.multiply(q1)).multiply(2).subtract(x),
  589.                                    m0.multiply(m0.multiply(y).subtract(q3.multiply(x).subtract(q1.multiply(z)))).add(s.multiply(q2)).multiply(2).subtract(y),
  590.                                    m0.multiply(m0.multiply(z).subtract(q1.multiply(y).subtract(q2.multiply(x)))).add(s.multiply(q3)).multiply(2).subtract(z));

  591.     }

  592.     /** Apply the inverse of the rotation to a vector stored in an array.
  593.      * @param in an array with three items which stores vector to rotate
  594.      * @param out an array with three items to put result to (it can be the same
  595.      * array as in)
  596.      */
  597.     public void applyInverseTo(final T[] in, final T[] out) {

  598.         final T x = in[0];
  599.         final T y = in[1];
  600.         final T z = in[2];

  601.         final T s = q1.multiply(x).add(q2.multiply(y)).add(q3.multiply(z));
  602.         final T m0 = q0.negate();

  603.         out[0] = m0.multiply(x.multiply(m0).subtract(q2.multiply(z).subtract(q3.multiply(y)))).add(s.multiply(q1)).multiply(2).subtract(x);
  604.         out[1] = m0.multiply(y.multiply(m0).subtract(q3.multiply(x).subtract(q1.multiply(z)))).add(s.multiply(q2)).multiply(2).subtract(y);
  605.         out[2] = m0.multiply(z.multiply(m0).subtract(q1.multiply(y).subtract(q2.multiply(x)))).add(s.multiply(q3)).multiply(2).subtract(z);

  606.     }

  607.     /** Apply the inverse of the rotation to a vector stored in an array.
  608.      * @param in an array with three items which stores vector to rotate
  609.      * @param out an array with three items to put result to
  610.      */
  611.     public void applyInverseTo(final double[] in, final T[] out) {

  612.         final double x = in[0];
  613.         final double y = in[1];
  614.         final double z = in[2];

  615.         final T s = q1.multiply(x).add(q2.multiply(y)).add(q3.multiply(z));
  616.         final T m0 = q0.negate();

  617.         out[0] = m0.multiply(m0.multiply(x).subtract(q2.multiply(z).subtract(q3.multiply(y)))).add(s.multiply(q1)).multiply(2).subtract(x);
  618.         out[1] = m0.multiply(m0.multiply(y).subtract(q3.multiply(x).subtract(q1.multiply(z)))).add(s.multiply(q2)).multiply(2).subtract(y);
  619.         out[2] = m0.multiply(m0.multiply(z).subtract(q1.multiply(y).subtract(q2.multiply(x)))).add(s.multiply(q3)).multiply(2).subtract(z);

  620.     }

  621.     /** Apply the inverse of a rotation to a vector.
  622.      * @param r rotation to apply
  623.      * @param u vector to apply the inverse of the rotation to
  624.      * @param <T> the type of the field elements
  625.      * @return a new vector which such that u is its image by the rotation
  626.      */
  627.     public static <T extends CalculusFieldElement<T>> FieldVector3D<T> applyInverseTo(final Rotation r, final FieldVector3D<T> u) {

  628.         final T x = u.getX();
  629.         final T y = u.getY();
  630.         final T z = u.getZ();

  631.         final T s  = x.multiply(r.getQ1()).add(y.multiply(r.getQ2())).add(z.multiply(r.getQ3()));
  632.         final double m0 = -r.getQ0();

  633.         return new FieldVector3D<>(x.multiply(m0).subtract(z.multiply(r.getQ2()).subtract(y.multiply(r.getQ3()))).multiply(m0).add(s.multiply(r.getQ1())).multiply(2).subtract(x),
  634.                                    y.multiply(m0).subtract(x.multiply(r.getQ3()).subtract(z.multiply(r.getQ1()))).multiply(m0).add(s.multiply(r.getQ2())).multiply(2).subtract(y),
  635.                                    z.multiply(m0).subtract(y.multiply(r.getQ1()).subtract(x.multiply(r.getQ2()))).multiply(m0).add(s.multiply(r.getQ3())).multiply(2).subtract(z));

  636.     }

  637.     /** Apply the instance to another rotation.
  638.      * <p>
  639.      * Calling this method is equivalent to call
  640.      * {@link #compose(FieldRotation, RotationConvention)
  641.      * compose(r, RotationConvention.VECTOR_OPERATOR)}.
  642.      * </p>
  643.      * @param r rotation to apply the rotation to
  644.      * @return a new rotation which is the composition of r by the instance
  645.      */
  646.     public FieldRotation<T> applyTo(final FieldRotation<T> r) {
  647.         return compose(r, RotationConvention.VECTOR_OPERATOR);
  648.     }

  649.     /** Compose the instance with another rotation.
  650.      * <p>
  651.      * If the semantics of the rotations composition corresponds to a
  652.      * {@link RotationConvention#VECTOR_OPERATOR vector operator} convention,
  653.      * applying the instance to a rotation is computing the composition
  654.      * in an order compliant with the following rule : let {@code u} be any
  655.      * vector and {@code v} its image by {@code r1} (i.e.
  656.      * {@code r1.applyTo(u) = v}). Let {@code w} be the image of {@code v} by
  657.      * rotation {@code r2} (i.e. {@code r2.applyTo(v) = w}). Then
  658.      * {@code w = comp.applyTo(u)}, where
  659.      * {@code comp = r2.compose(r1, RotationConvention.VECTOR_OPERATOR)}.
  660.      * </p>
  661.      * <p>
  662.      * If the semantics of the rotations composition corresponds to a
  663.      * {@link RotationConvention#FRAME_TRANSFORM frame transform} convention,
  664.      * the application order will be reversed. So keeping the exact same
  665.      * meaning of all {@code r1}, {@code r2}, {@code u}, {@code v}, {@code w}
  666.      * and  {@code comp} as above, {@code comp} could also be computed as
  667.      * {@code comp = r1.compose(r2, RotationConvention.FRAME_TRANSFORM)}.
  668.      * </p>
  669.      * @param r rotation to apply the rotation to
  670.      * @param convention convention to use for the semantics of the angle
  671.      * @return a new rotation which is the composition of r by the instance
  672.      */
  673.     public FieldRotation<T> compose(final FieldRotation<T> r, final RotationConvention convention) {
  674.         return convention == RotationConvention.VECTOR_OPERATOR ?
  675.                              composeInternal(r) : r.composeInternal(this);
  676.     }

  677.     /** Compose the instance with another rotation using vector operator convention.
  678.      * @param r rotation to apply the rotation to
  679.      * @return a new rotation which is the composition of r by the instance
  680.      * using vector operator convention
  681.      */
  682.     private FieldRotation<T> composeInternal(final FieldRotation<T> r) {
  683.         return new FieldRotation<>(r.q0.multiply(q0).subtract(r.q1.multiply(q1).add(r.q2.multiply(q2)).add(r.q3.multiply(q3))),
  684.                                    r.q1.multiply(q0).add(r.q0.multiply(q1)).add(r.q2.multiply(q3).subtract(r.q3.multiply(q2))),
  685.                                    r.q2.multiply(q0).add(r.q0.multiply(q2)).add(r.q3.multiply(q1).subtract(r.q1.multiply(q3))),
  686.                                    r.q3.multiply(q0).add(r.q0.multiply(q3)).add(r.q1.multiply(q2).subtract(r.q2.multiply(q1))),
  687.                                    false);
  688.     }

  689.     /** Apply the instance to another rotation.
  690.      * <p>
  691.      * Calling this method is equivalent to call
  692.      * {@link #compose(Rotation, RotationConvention)
  693.      * compose(r, RotationConvention.VECTOR_OPERATOR)}.
  694.      * </p>
  695.      * @param r rotation to apply the rotation to
  696.      * @return a new rotation which is the composition of r by the instance
  697.      */
  698.     public FieldRotation<T> applyTo(final Rotation r) {
  699.         return compose(r, RotationConvention.VECTOR_OPERATOR);
  700.     }

  701.     /** Compose the instance with another rotation.
  702.      * <p>
  703.      * If the semantics of the rotations composition corresponds to a
  704.      * {@link RotationConvention#VECTOR_OPERATOR vector operator} convention,
  705.      * applying the instance to a rotation is computing the composition
  706.      * in an order compliant with the following rule : let {@code u} be any
  707.      * vector and {@code v} its image by {@code r1} (i.e.
  708.      * {@code r1.applyTo(u) = v}). Let {@code w} be the image of {@code v} by
  709.      * rotation {@code r2} (i.e. {@code r2.applyTo(v) = w}). Then
  710.      * {@code w = comp.applyTo(u)}, where
  711.      * {@code comp = r2.compose(r1, RotationConvention.VECTOR_OPERATOR)}.
  712.      * </p>
  713.      * <p>
  714.      * If the semantics of the rotations composition corresponds to a
  715.      * {@link RotationConvention#FRAME_TRANSFORM frame transform} convention,
  716.      * the application order will be reversed. So keeping the exact same
  717.      * meaning of all {@code r1}, {@code r2}, {@code u}, {@code v}, {@code w}
  718.      * and  {@code comp} as above, {@code comp} could also be computed as
  719.      * {@code comp = r1.compose(r2, RotationConvention.FRAME_TRANSFORM)}.
  720.      * </p>
  721.      * @param r rotation to apply the rotation to
  722.      * @param convention convention to use for the semantics of the angle
  723.      * @return a new rotation which is the composition of r by the instance
  724.      */
  725.     public FieldRotation<T> compose(final Rotation r, final RotationConvention convention) {
  726.         return convention == RotationConvention.VECTOR_OPERATOR ?
  727.                              composeInternal(r) : applyTo(r, this);
  728.     }

  729.     /** Compose the instance with another rotation using vector operator convention.
  730.      * @param r rotation to apply the rotation to
  731.      * @return a new rotation which is the composition of r by the instance
  732.      * using vector operator convention
  733.      */
  734.     private FieldRotation<T> composeInternal(final Rotation r) {
  735.         return new FieldRotation<>(q0.multiply(r.getQ0()).subtract(q1.multiply(r.getQ1()).add(q2.multiply(r.getQ2())).add(q3.multiply(r.getQ3()))),
  736.                                    q0.multiply(r.getQ1()).add(q1.multiply(r.getQ0())).add(q3.multiply(r.getQ2()).subtract(q2.multiply(r.getQ3()))),
  737.                                    q0.multiply(r.getQ2()).add(q2.multiply(r.getQ0())).add(q1.multiply(r.getQ3()).subtract(q3.multiply(r.getQ1()))),
  738.                                    q0.multiply(r.getQ3()).add(q3.multiply(r.getQ0())).add(q2.multiply(r.getQ1()).subtract(q1.multiply(r.getQ2()))),
  739.                                    false);
  740.     }

  741.     /** Apply a rotation to another rotation.
  742.      * Applying a rotation to another rotation is computing the composition
  743.      * in an order compliant with the following rule : let u be any
  744.      * vector and v its image by rInner (i.e. rInner.applyTo(u) = v), let w be the image
  745.      * of v by rOuter (i.e. rOuter.applyTo(v) = w), then w = comp.applyTo(u),
  746.      * where comp = applyTo(rOuter, rInner).
  747.      * @param r1 rotation to apply
  748.      * @param rInner rotation to apply the rotation to
  749.      * @param <T> the type of the field elements
  750.      * @return a new rotation which is the composition of r by the instance
  751.      */
  752.     public static <T extends CalculusFieldElement<T>> FieldRotation<T> applyTo(final Rotation r1, final FieldRotation<T> rInner) {
  753.         return new FieldRotation<>(rInner.q0.multiply(r1.getQ0()).subtract(rInner.q1.multiply(r1.getQ1()).add(rInner.q2.multiply(r1.getQ2())).add(rInner.q3.multiply(r1.getQ3()))),
  754.                                    rInner.q1.multiply(r1.getQ0()).add(rInner.q0.multiply(r1.getQ1())).add(rInner.q2.multiply(r1.getQ3()).subtract(rInner.q3.multiply(r1.getQ2()))),
  755.                                    rInner.q2.multiply(r1.getQ0()).add(rInner.q0.multiply(r1.getQ2())).add(rInner.q3.multiply(r1.getQ1()).subtract(rInner.q1.multiply(r1.getQ3()))),
  756.                                    rInner.q3.multiply(r1.getQ0()).add(rInner.q0.multiply(r1.getQ3())).add(rInner.q1.multiply(r1.getQ2()).subtract(rInner.q2.multiply(r1.getQ1()))),
  757.                                    false);
  758.     }

  759.     /** Apply the inverse of the instance to another rotation.
  760.      * <p>
  761.      * Calling this method is equivalent to call
  762.      * {@link #composeInverse(FieldRotation, RotationConvention)
  763.      * composeInverse(r, RotationConvention.VECTOR_OPERATOR)}.
  764.      * </p>
  765.      * @param r rotation to apply the rotation to
  766.      * @return a new rotation which is the composition of r by the inverse
  767.      * of the instance
  768.      */
  769.     public FieldRotation<T> applyInverseTo(final FieldRotation<T> r) {
  770.         return composeInverse(r, RotationConvention.VECTOR_OPERATOR);
  771.     }

  772.     /** Compose the inverse of the instance with another rotation.
  773.      * <p>
  774.      * If the semantics of the rotations composition corresponds to a
  775.      * {@link RotationConvention#VECTOR_OPERATOR vector operator} convention,
  776.      * applying the inverse of the instance to a rotation is computing
  777.      * the composition in an order compliant with the following rule :
  778.      * let {@code u} be any vector and {@code v} its image by {@code r1}
  779.      * (i.e. {@code r1.applyTo(u) = v}). Let {@code w} be the inverse image
  780.      * of {@code v} by {@code r2} (i.e. {@code r2.applyInverseTo(v) = w}).
  781.      * Then {@code w = comp.applyTo(u)}, where
  782.      * {@code comp = r2.composeInverse(r1)}.
  783.      * </p>
  784.      * <p>
  785.      * If the semantics of the rotations composition corresponds to a
  786.      * {@link RotationConvention#FRAME_TRANSFORM frame transform} convention,
  787.      * the application order will be reversed, which means it is the
  788.      * <em>innermost</em> rotation that will be reversed. So keeping the exact same
  789.      * meaning of all {@code r1}, {@code r2}, {@code u}, {@code v}, {@code w}
  790.      * and  {@code comp} as above, {@code comp} could also be computed as
  791.      * {@code comp = r1.revert().composeInverse(r2.revert(), RotationConvention.FRAME_TRANSFORM)}.
  792.      * </p>
  793.      * @param r rotation to apply the rotation to
  794.      * @param convention convention to use for the semantics of the angle
  795.      * @return a new rotation which is the composition of r by the inverse
  796.      * of the instance
  797.      */
  798.     public FieldRotation<T> composeInverse(final FieldRotation<T> r, final RotationConvention convention) {
  799.         return convention == RotationConvention.VECTOR_OPERATOR ?
  800.                              composeInverseInternal(r) : r.composeInternal(revert());
  801.     }

  802.     /** Compose the inverse of the instance with another rotation
  803.      * using vector operator convention.
  804.      * @param r rotation to apply the rotation to
  805.      * @return a new rotation which is the composition of r by the inverse
  806.      * of the instance using vector operator convention
  807.      */
  808.     private FieldRotation<T> composeInverseInternal(FieldRotation<T> r) {
  809.         return new FieldRotation<>(r.q0.multiply(q0).add(r.q1.multiply(q1)).add(r.q2.multiply(q2)).add(r.q3.multiply(q3)).negate(),
  810.                                    r.q0.multiply(q1).add(r.q2.multiply(q3).subtract(r.q3.multiply(q2))).subtract(r.q1.multiply(q0)),
  811.                                    r.q0.multiply(q2).add(r.q3.multiply(q1).subtract(r.q1.multiply(q3))).subtract(r.q2.multiply(q0)),
  812.                                    r.q0.multiply(q3).add(r.q1.multiply(q2).subtract(r.q2.multiply(q1))).subtract(r.q3.multiply(q0)),
  813.                                    false);
  814.     }

  815.     /** Apply the inverse of the instance to another rotation.
  816.      * <p>
  817.      * Calling this method is equivalent to call
  818.      * {@link #composeInverse(Rotation, RotationConvention)
  819.      * composeInverse(r, RotationConvention.VECTOR_OPERATOR)}.
  820.      * </p>
  821.      * @param r rotation to apply the rotation to
  822.      * @return a new rotation which is the composition of r by the inverse
  823.      * of the instance
  824.      */
  825.     public FieldRotation<T> applyInverseTo(final Rotation r) {
  826.         return composeInverse(r, RotationConvention.VECTOR_OPERATOR);
  827.     }

  828.     /** Compose the inverse of the instance with another rotation.
  829.      * <p>
  830.      * If the semantics of the rotations composition corresponds to a
  831.      * {@link RotationConvention#VECTOR_OPERATOR vector operator} convention,
  832.      * applying the inverse of the instance to a rotation is computing
  833.      * the composition in an order compliant with the following rule :
  834.      * let {@code u} be any vector and {@code v} its image by {@code r1}
  835.      * (i.e. {@code r1.applyTo(u) = v}). Let {@code w} be the inverse image
  836.      * of {@code v} by {@code r2} (i.e. {@code r2.applyInverseTo(v) = w}).
  837.      * Then {@code w = comp.applyTo(u)}, where
  838.      * {@code comp = r2.composeInverse(r1)}.
  839.      * </p>
  840.      * <p>
  841.      * If the semantics of the rotations composition corresponds to a
  842.      * {@link RotationConvention#FRAME_TRANSFORM frame transform} convention,
  843.      * the application order will be reversed, which means it is the
  844.      * <em>innermost</em> rotation that will be reversed. So keeping the exact same
  845.      * meaning of all {@code r1}, {@code r2}, {@code u}, {@code v}, {@code w}
  846.      * and  {@code comp} as above, {@code comp} could also be computed as
  847.      * {@code comp = r1.revert().composeInverse(r2.revert(), RotationConvention.FRAME_TRANSFORM)}.
  848.      * </p>
  849.      * @param r rotation to apply the rotation to
  850.      * @param convention convention to use for the semantics of the angle
  851.      * @return a new rotation which is the composition of r by the inverse
  852.      * of the instance
  853.      */
  854.     public FieldRotation<T> composeInverse(final Rotation r, final RotationConvention convention) {
  855.         return convention == RotationConvention.VECTOR_OPERATOR ?
  856.                              composeInverseInternal(r) : applyTo(r, revert());
  857.     }

  858.     /** Compose the inverse of the instance with another rotation
  859.      * using vector operator convention.
  860.      * @param r rotation to apply the rotation to
  861.      * @return a new rotation which is the composition of r by the inverse
  862.      * of the instance using vector operator convention
  863.      */
  864.     private FieldRotation<T> composeInverseInternal(Rotation r) {
  865.         return new FieldRotation<>(q0.multiply(r.getQ0()).add(q1.multiply(r.getQ1()).add(q2.multiply(r.getQ2())).add(q3.multiply(r.getQ3()))).negate(),
  866.                                    q1.multiply(r.getQ0()).add(q3.multiply(r.getQ2()).subtract(q2.multiply(r.getQ3()))).subtract(q0.multiply(r.getQ1())),
  867.                                    q2.multiply(r.getQ0()).add(q1.multiply(r.getQ3()).subtract(q3.multiply(r.getQ1()))).subtract(q0.multiply(r.getQ2())),
  868.                                    q3.multiply(r.getQ0()).add(q2.multiply(r.getQ1()).subtract(q1.multiply(r.getQ2()))).subtract(q0.multiply(r.getQ3())),
  869.                                    false);
  870.     }

  871.     /** Apply the inverse of a rotation to another rotation.
  872.      * Applying the inverse of a rotation to another rotation is computing
  873.      * the composition in an order compliant with the following rule :
  874.      * let u be any vector and v its image by rInner (i.e. rInner.applyTo(u) = v),
  875.      * let w be the inverse image of v by rOuter
  876.      * (i.e. rOuter.applyInverseTo(v) = w), then w = comp.applyTo(u), where
  877.      * comp = applyInverseTo(rOuter, rInner).
  878.      * @param rOuter rotation to apply the rotation to
  879.      * @param rInner rotation to apply the rotation to
  880.      * @param <T> the type of the field elements
  881.      * @return a new rotation which is the composition of r by the inverse
  882.      * of the instance
  883.      */
  884.     public static <T extends CalculusFieldElement<T>> FieldRotation<T> applyInverseTo(final Rotation rOuter, final FieldRotation<T> rInner) {
  885.         return new FieldRotation<>(rInner.q0.multiply(rOuter.getQ0()).add(rInner.q1.multiply(rOuter.getQ1()).add(rInner.q2.multiply(rOuter.getQ2())).add(rInner.q3.multiply(rOuter.getQ3()))).negate(),
  886.                                    rInner.q0.multiply(rOuter.getQ1()).add(rInner.q2.multiply(rOuter.getQ3()).subtract(rInner.q3.multiply(rOuter.getQ2()))).subtract(rInner.q1.multiply(rOuter.getQ0())),
  887.                                    rInner.q0.multiply(rOuter.getQ2()).add(rInner.q3.multiply(rOuter.getQ1()).subtract(rInner.q1.multiply(rOuter.getQ3()))).subtract(rInner.q2.multiply(rOuter.getQ0())),
  888.                                    rInner.q0.multiply(rOuter.getQ3()).add(rInner.q1.multiply(rOuter.getQ2()).subtract(rInner.q2.multiply(rOuter.getQ1()))).subtract(rInner.q3.multiply(rOuter.getQ0())),
  889.                                    false);
  890.     }

  891.     /** Perfect orthogonality on a 3X3 matrix.
  892.      * @param m initial matrix (not exactly orthogonal)
  893.      * @param threshold convergence threshold for the iterative
  894.      * orthogonality correction (convergence is reached when the
  895.      * difference between two steps of the Frobenius norm of the
  896.      * correction is below this threshold)
  897.      * @return an orthogonal matrix close to m
  898.      * @exception MathIllegalArgumentException if the matrix cannot be
  899.      * orthogonalized with the given threshold after 10 iterations
  900.      */
  901.     private T[][] orthogonalizeMatrix(final T[][] m, final double threshold)
  902.         throws MathIllegalArgumentException {

  903.         T x00 = m[0][0];
  904.         T x01 = m[0][1];
  905.         T x02 = m[0][2];
  906.         T x10 = m[1][0];
  907.         T x11 = m[1][1];
  908.         T x12 = m[1][2];
  909.         T x20 = m[2][0];
  910.         T x21 = m[2][1];
  911.         T x22 = m[2][2];
  912.         double fn = 0;
  913.         double fn1;

  914.         final T[][] o = MathArrays.buildArray(m[0][0].getField(), 3, 3);

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

  918.             // Mt.Xn
  919.             final T mx00 = m[0][0].multiply(x00).add(m[1][0].multiply(x10)).add(m[2][0].multiply(x20));
  920.             final T mx10 = m[0][1].multiply(x00).add(m[1][1].multiply(x10)).add(m[2][1].multiply(x20));
  921.             final T mx20 = m[0][2].multiply(x00).add(m[1][2].multiply(x10)).add(m[2][2].multiply(x20));
  922.             final T mx01 = m[0][0].multiply(x01).add(m[1][0].multiply(x11)).add(m[2][0].multiply(x21));
  923.             final T mx11 = m[0][1].multiply(x01).add(m[1][1].multiply(x11)).add(m[2][1].multiply(x21));
  924.             final T mx21 = m[0][2].multiply(x01).add(m[1][2].multiply(x11)).add(m[2][2].multiply(x21));
  925.             final T mx02 = m[0][0].multiply(x02).add(m[1][0].multiply(x12)).add(m[2][0].multiply(x22));
  926.             final T mx12 = m[0][1].multiply(x02).add(m[1][1].multiply(x12)).add(m[2][1].multiply(x22));
  927.             final T mx22 = m[0][2].multiply(x02).add(m[1][2].multiply(x12)).add(m[2][2].multiply(x22));

  928.             // Xn+1
  929.             o[0][0] = x00.subtract(x00.multiply(mx00).add(x01.multiply(mx10)).add(x02.multiply(mx20)).subtract(m[0][0]).multiply(0.5));
  930.             o[0][1] = x01.subtract(x00.multiply(mx01).add(x01.multiply(mx11)).add(x02.multiply(mx21)).subtract(m[0][1]).multiply(0.5));
  931.             o[0][2] = x02.subtract(x00.multiply(mx02).add(x01.multiply(mx12)).add(x02.multiply(mx22)).subtract(m[0][2]).multiply(0.5));
  932.             o[1][0] = x10.subtract(x10.multiply(mx00).add(x11.multiply(mx10)).add(x12.multiply(mx20)).subtract(m[1][0]).multiply(0.5));
  933.             o[1][1] = x11.subtract(x10.multiply(mx01).add(x11.multiply(mx11)).add(x12.multiply(mx21)).subtract(m[1][1]).multiply(0.5));
  934.             o[1][2] = x12.subtract(x10.multiply(mx02).add(x11.multiply(mx12)).add(x12.multiply(mx22)).subtract(m[1][2]).multiply(0.5));
  935.             o[2][0] = x20.subtract(x20.multiply(mx00).add(x21.multiply(mx10)).add(x22.multiply(mx20)).subtract(m[2][0]).multiply(0.5));
  936.             o[2][1] = x21.subtract(x20.multiply(mx01).add(x21.multiply(mx11)).add(x22.multiply(mx21)).subtract(m[2][1]).multiply(0.5));
  937.             o[2][2] = x22.subtract(x20.multiply(mx02).add(x21.multiply(mx12)).add(x22.multiply(mx22)).subtract(m[2][2]).multiply(0.5));

  938.             // correction on each elements
  939.             final double corr00 = o[0][0].getReal() - m[0][0].getReal();
  940.             final double corr01 = o[0][1].getReal() - m[0][1].getReal();
  941.             final double corr02 = o[0][2].getReal() - m[0][2].getReal();
  942.             final double corr10 = o[1][0].getReal() - m[1][0].getReal();
  943.             final double corr11 = o[1][1].getReal() - m[1][1].getReal();
  944.             final double corr12 = o[1][2].getReal() - m[1][2].getReal();
  945.             final double corr20 = o[2][0].getReal() - m[2][0].getReal();
  946.             final double corr21 = o[2][1].getReal() - m[2][1].getReal();
  947.             final double corr22 = o[2][2].getReal() - m[2][2].getReal();

  948.             // Frobenius norm of the correction
  949.             fn1 = corr00 * corr00 + corr01 * corr01 + corr02 * corr02 +
  950.                   corr10 * corr10 + corr11 * corr11 + corr12 * corr12 +
  951.                   corr20 * corr20 + corr21 * corr21 + corr22 * corr22;

  952.             // convergence test
  953.             if (FastMath.abs(fn1 - fn) <= threshold) {
  954.                 return o;
  955.             }

  956.             // prepare next iteration
  957.             x00 = o[0][0];
  958.             x01 = o[0][1];
  959.             x02 = o[0][2];
  960.             x10 = o[1][0];
  961.             x11 = o[1][1];
  962.             x12 = o[1][2];
  963.             x20 = o[2][0];
  964.             x21 = o[2][1];
  965.             x22 = o[2][2];
  966.             fn  = fn1;

  967.         }

  968.         // the algorithm did not converge after 10 iterations
  969.         throw new MathIllegalArgumentException(LocalizedGeometryFormats.UNABLE_TO_ORTHOGONOLIZE_MATRIX,
  970.                                                i - 1);

  971.     }

  972.     /** Compute the <i>distance</i> between two rotations.
  973.      * <p>The <i>distance</i> is intended here as a way to check if two
  974.      * rotations are almost similar (i.e. they transform vectors the same way)
  975.      * or very different. It is mathematically defined as the angle of
  976.      * the rotation r that prepended to one of the rotations gives the other
  977.      * one: \(r_1(r) = r_2\)
  978.      * </p>
  979.      * <p>This distance is an angle between 0 and &pi;. Its value is the smallest
  980.      * possible upper bound of the angle in radians between r<sub>1</sub>(v)
  981.      * and r<sub>2</sub>(v) for all possible vectors v. This upper bound is
  982.      * reached for some v. The distance is equal to 0 if and only if the two
  983.      * rotations are identical.</p>
  984.      * <p>Comparing two rotations should always be done using this value rather
  985.      * than for example comparing the components of the quaternions. It is much
  986.      * more stable, and has a geometric meaning. Also comparing quaternions
  987.      * components is error prone since for example quaternions (0.36, 0.48, -0.48, -0.64)
  988.      * and (-0.36, -0.48, 0.48, 0.64) represent exactly the same rotation despite
  989.      * their components are different (they are exact opposites).</p>
  990.      * @param r1 first rotation
  991.      * @param r2 second rotation
  992.      * @param <T> the type of the field elements
  993.      * @return <i>distance</i> between r1 and r2
  994.      */
  995.     public static <T extends CalculusFieldElement<T>> T distance(final FieldRotation<T> r1, final FieldRotation<T> r2) {
  996.         return r1.composeInverseInternal(r2).getAngle();
  997.     }

  998. }