View Javadoc
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  /*
19   * This is not the original file distributed by the Apache Software Foundation
20   * It has been modified by the Hipparchus project
21   */
22  
23  package org.hipparchus.geometry.euclidean.threed;
24  
25  import java.io.Serializable;
26  
27  import org.hipparchus.CalculusFieldElement;
28  import org.hipparchus.Field;
29  import org.hipparchus.exception.MathIllegalArgumentException;
30  import org.hipparchus.exception.MathRuntimeException;
31  import org.hipparchus.geometry.LocalizedGeometryFormats;
32  import org.hipparchus.util.FastMath;
33  import org.hipparchus.util.FieldSinCos;
34  import org.hipparchus.util.MathArrays;
35  
36  /**
37   * This class is a re-implementation of {@link Rotation} using {@link CalculusFieldElement}.
38   * <p>Instance of this class are guaranteed to be immutable.</p>
39   *
40   * @param <T> the type of the field elements
41   * @see FieldVector3D
42   * @see RotationOrder
43   */
44  
45  public class FieldRotation<T extends CalculusFieldElement<T>> implements Serializable {
46  
47      /** Serializable version identifier */
48      private static final long serialVersionUID = 20130224L;
49  
50      /** Scalar coordinate of the quaternion. */
51      private final T q0;
52  
53      /** First coordinate of the vectorial part of the quaternion. */
54      private final T q1;
55  
56      /** Second coordinate of the vectorial part of the quaternion. */
57      private final T q2;
58  
59      /** Third coordinate of the vectorial part of the quaternion. */
60      private final T q3;
61  
62      /** Build a rotation from the quaternion coordinates.
63       * <p>A rotation can be built from a <em>normalized</em> quaternion,
64       * i.e. a quaternion for which q<sub>0</sub><sup>2</sup> +
65       * q<sub>1</sub><sup>2</sup> + q<sub>2</sub><sup>2</sup> +
66       * q<sub>3</sub><sup>2</sup> = 1. If the quaternion is not normalized,
67       * the constructor can normalize it in a preprocessing step.</p>
68       * <p>Note that some conventions put the scalar part of the quaternion
69       * as the 4<sup>th</sup> component and the vector part as the first three
70       * components. This is <em>not</em> our convention. We put the scalar part
71       * as the first component.</p>
72       * @param q0 scalar part of the quaternion
73       * @param q1 first coordinate of the vectorial part of the quaternion
74       * @param q2 second coordinate of the vectorial part of the quaternion
75       * @param q3 third coordinate of the vectorial part of the quaternion
76       * @param needsNormalization if true, the coordinates are considered
77       * not to be normalized, a normalization preprocessing step is performed
78       * before using them
79       */
80      public FieldRotation(final T q0, final T q1, final T q2, final T q3, final boolean needsNormalization) {
81  
82          if (needsNormalization) {
83              // normalization preprocessing
84              final T inv =
85                      q0.square().add(q1.square()).add(q2.square()).add(q3.square()).sqrt().reciprocal();
86              this.q0 = inv.multiply(q0);
87              this.q1 = inv.multiply(q1);
88              this.q2 = inv.multiply(q2);
89              this.q3 = inv.multiply(q3);
90          } else {
91              this.q0 = q0;
92              this.q1 = q1;
93              this.q2 = q2;
94              this.q3 = q3;
95          }
96  
97      }
98  
99      /** Build a rotation from an axis and an angle.
100      * <p>We use the convention that angles are oriented according to
101      * the effect of the rotation on vectors around the axis. That means
102      * that if (i, j, k) is a direct frame and if we first provide +k as
103      * the axis and &pi;/2 as the angle to this constructor, and then
104      * {@link #applyTo(FieldVector3D) apply} the instance to +i, we will get
105      * +j.</p>
106      * <p>Another way to represent our convention is to say that a rotation
107      * of angle &theta; about the unit vector (x, y, z) is the same as the
108      * rotation build from quaternion components { cos(-&theta;/2),
109      * x * sin(-&theta;/2), y * sin(-&theta;/2), z * sin(-&theta;/2) }.
110      * Note the minus sign on the angle!</p>
111      * <p>On the one hand this convention is consistent with a vectorial
112      * perspective (moving vectors in fixed frames), on the other hand it
113      * is different from conventions with a frame perspective (fixed vectors
114      * viewed from different frames) like the ones used for example in spacecraft
115      * attitude community or in the graphics community.</p>
116      * @param axis axis around which to rotate
117      * @param angle rotation angle.
118      * @param convention convention to use for the semantics of the angle
119      * @exception MathIllegalArgumentException if the axis norm is zero
120      */
121     public FieldRotation(final FieldVector3D<T> axis, final T angle, final RotationConvention convention)
122         throws MathIllegalArgumentException {
123 
124         final T norm = axis.getNorm();
125         if (norm.getReal() == 0) {
126             throw new MathIllegalArgumentException(LocalizedGeometryFormats.ZERO_NORM_FOR_ROTATION_AXIS);
127         }
128 
129         final T halfAngle = angle.multiply(convention == RotationConvention.VECTOR_OPERATOR ? -0.5 : 0.5);
130         final FieldSinCos<T> sinCos = FastMath.sinCos(halfAngle);
131         final T coeff = sinCos.sin().divide(norm);
132 
133         q0 = sinCos.cos();
134         q1 = coeff.multiply(axis.getX());
135         q2 = coeff.multiply(axis.getY());
136         q3 = coeff.multiply(axis.getZ());
137 
138     }
139 
140     /** Build a {@link FieldRotation} from a {@link Rotation}.
141      * @param field field for the components
142      * @param r rotation to convert
143      */
144     public FieldRotation(final Field<T> field, final Rotation r) {
145         this.q0 = field.getZero().add(r.getQ0());
146         this.q1 = field.getZero().add(r.getQ1());
147         this.q2 = field.getZero().add(r.getQ2());
148         this.q3 = field.getZero().add(r.getQ3());
149     }
150 
151     /** Build a rotation from a 3X3 matrix.
152 
153      * <p>Rotation matrices are orthogonal matrices, i.e. unit matrices
154      * (which are matrices for which m.m<sup>T</sup> = I) with real
155      * coefficients. The module of the determinant of unit matrices is
156      * 1, among the orthogonal 3X3 matrices, only the ones having a
157      * positive determinant (+1) are rotation matrices.</p>
158 
159      * <p>When a rotation is defined by a matrix with truncated values
160      * (typically when it is extracted from a technical sheet where only
161      * four to five significant digits are available), the matrix is not
162      * orthogonal anymore. This constructor handles this case
163      * transparently by using a copy of the given matrix and applying a
164      * correction to the copy in order to perfect its orthogonality. If
165      * the Frobenius norm of the correction needed is above the given
166      * threshold, then the matrix is considered to be too far from a
167      * true rotation matrix and an exception is thrown.</p>
168 
169      * @param m rotation matrix
170      * @param threshold convergence threshold for the iterative
171      * orthogonality correction (convergence is reached when the
172      * difference between two steps of the Frobenius norm of the
173      * correction is below this threshold)
174 
175      * @exception MathIllegalArgumentException if the matrix is not a 3X3
176      * matrix, or if it cannot be transformed into an orthogonal matrix
177      * with the given threshold, or if the determinant of the resulting
178      * orthogonal matrix is negative
179 
180      */
181     public FieldRotation(final T[][] m, final double threshold)
182         throws MathIllegalArgumentException {
183 
184         // dimension check
185         if ((m.length != 3) || (m[0].length != 3) ||
186                 (m[1].length != 3) || (m[2].length != 3)) {
187             throw new MathIllegalArgumentException(LocalizedGeometryFormats.ROTATION_MATRIX_DIMENSIONS,
188                                                    m.length, m[0].length);
189         }
190 
191         // compute a "close" orthogonal matrix
192         final T[][] ort = orthogonalizeMatrix(m, threshold);
193 
194         // check the sign of the determinant
195         final T d0 = ort[1][1].multiply(ort[2][2]).subtract(ort[2][1].multiply(ort[1][2]));
196         final T d1 = ort[0][1].multiply(ort[2][2]).subtract(ort[2][1].multiply(ort[0][2]));
197         final T d2 = ort[0][1].multiply(ort[1][2]).subtract(ort[1][1].multiply(ort[0][2]));
198         final T det =
199                 ort[0][0].multiply(d0).subtract(ort[1][0].multiply(d1)).add(ort[2][0].multiply(d2));
200         if (det.getReal() < 0.0) {
201             throw new MathIllegalArgumentException(LocalizedGeometryFormats.CLOSEST_ORTHOGONAL_MATRIX_HAS_NEGATIVE_DETERMINANT,
202                                                    det);
203         }
204 
205         final T[] quat = mat2quat(ort);
206         q0 = quat[0];
207         q1 = quat[1];
208         q2 = quat[2];
209         q3 = quat[3];
210 
211     }
212 
213     /** Build the rotation that transforms a pair of vectors into another pair.
214 
215      * <p>Except for possible scale factors, if the instance were applied to
216      * the pair (u<sub>1</sub>, u<sub>2</sub>) it will produce the pair
217      * (v<sub>1</sub>, v<sub>2</sub>).</p>
218 
219      * <p>If the angular separation between u<sub>1</sub> and u<sub>2</sub> is
220      * not the same as the angular separation between v<sub>1</sub> and
221      * v<sub>2</sub>, then a corrected v'<sub>2</sub> will be used rather than
222      * v<sub>2</sub>, the corrected vector will be in the (±v<sub>1</sub>,
223      * +v<sub>2</sub>) half-plane.</p>
224      * @param u1 first vector of the origin pair
225      * @param u2 second vector of the origin pair
226      * @param v1 desired image of u1 by the rotation
227      * @param v2 desired image of u2 by the rotation
228      * @exception MathRuntimeException if the norm of one of the vectors is zero,
229      * or if one of the pair is degenerated (i.e. the vectors of the pair are collinear)
230      */
231     public FieldRotation(FieldVector3D<T> u1, FieldVector3D<T> u2, FieldVector3D<T> v1, FieldVector3D<T> v2)
232         throws MathRuntimeException {
233 
234         // build orthonormalized base from u1, u2
235         // this fails when vectors are null or collinear, which is forbidden to define a rotation
236         final FieldVector3D<T> u3 = FieldVector3D.crossProduct(u1, u2).normalize();
237         u2 = FieldVector3D.crossProduct(u3, u1).normalize();
238         u1 = u1.normalize();
239 
240         // build an orthonormalized base from v1, v2
241         // this fails when vectors are null or collinear, which is forbidden to define a rotation
242         final FieldVector3D<T> v3 = FieldVector3D.crossProduct(v1, v2).normalize();
243         v2 = FieldVector3D.crossProduct(v3, v1).normalize();
244         v1 = v1.normalize();
245 
246         // buid a matrix transforming the first base into the second one
247         final T[][] array = MathArrays.buildArray(u1.getX().getField(), 3, 3);
248         array[0][0] = u1.getX().multiply(v1.getX()).add(u2.getX().multiply(v2.getX())).add(u3.getX().multiply(v3.getX()));
249         array[0][1] = u1.getY().multiply(v1.getX()).add(u2.getY().multiply(v2.getX())).add(u3.getY().multiply(v3.getX()));
250         array[0][2] = u1.getZ().multiply(v1.getX()).add(u2.getZ().multiply(v2.getX())).add(u3.getZ().multiply(v3.getX()));
251         array[1][0] = u1.getX().multiply(v1.getY()).add(u2.getX().multiply(v2.getY())).add(u3.getX().multiply(v3.getY()));
252         array[1][1] = u1.getY().multiply(v1.getY()).add(u2.getY().multiply(v2.getY())).add(u3.getY().multiply(v3.getY()));
253         array[1][2] = u1.getZ().multiply(v1.getY()).add(u2.getZ().multiply(v2.getY())).add(u3.getZ().multiply(v3.getY()));
254         array[2][0] = u1.getX().multiply(v1.getZ()).add(u2.getX().multiply(v2.getZ())).add(u3.getX().multiply(v3.getZ()));
255         array[2][1] = u1.getY().multiply(v1.getZ()).add(u2.getY().multiply(v2.getZ())).add(u3.getY().multiply(v3.getZ()));
256         array[2][2] = u1.getZ().multiply(v1.getZ()).add(u2.getZ().multiply(v2.getZ())).add(u3.getZ().multiply(v3.getZ()));
257 
258         T[] quat = mat2quat(array);
259         q0 = quat[0];
260         q1 = quat[1];
261         q2 = quat[2];
262         q3 = quat[3];
263 
264     }
265 
266     /** Build one of the rotations that transform one vector into another one.
267 
268      * <p>Except for a possible scale factor, if the instance were
269      * applied to the vector u it will produce the vector v. There is an
270      * infinite number of such rotations, this constructor choose the
271      * one with the smallest associated angle (i.e. the one whose axis
272      * is orthogonal to the (u, v) plane). If u and v are collinear, an
273      * arbitrary rotation axis is chosen.</p>
274 
275      * @param u origin vector
276      * @param v desired image of u by the rotation
277      * @exception MathRuntimeException if the norm of one of the vectors is zero
278      */
279     public FieldRotation(final FieldVector3D<T> u, final FieldVector3D<T> v) throws MathRuntimeException {
280 
281         final T normProduct = u.getNorm().multiply(v.getNorm());
282         if (normProduct.getReal() == 0) {
283             throw new MathRuntimeException(LocalizedGeometryFormats.ZERO_NORM_FOR_ROTATION_DEFINING_VECTOR);
284         }
285 
286         final T dot = FieldVector3D.dotProduct(u, v);
287 
288         if (dot.getReal() < ((2.0e-15 - 1.0) * normProduct.getReal())) {
289             // special case u = -v: we select a PI angle rotation around
290             // an arbitrary vector orthogonal to u
291             final FieldVector3D<T> w = u.orthogonal();
292             q0 = normProduct.getField().getZero();
293             q1 = w.getX().negate();
294             q2 = w.getY().negate();
295             q3 = w.getZ().negate();
296         } else {
297             // general case: (u, v) defines a plane, we select
298             // the shortest possible rotation: axis orthogonal to this plane
299             q0 = dot.divide(normProduct).add(1.0).multiply(0.5).sqrt();
300             final T coeff = q0.multiply(normProduct).multiply(2.0).reciprocal();
301             final FieldVector3D<T> q = FieldVector3D.crossProduct(v, u);
302             q1 = coeff.multiply(q.getX());
303             q2 = coeff.multiply(q.getY());
304             q3 = coeff.multiply(q.getZ());
305         }
306 
307     }
308 
309     /** Build a rotation from three Cardan or Euler elementary rotations.
310 
311      * <p>Cardan rotations are three successive rotations around the
312      * canonical axes X, Y and Z, each axis being used once. There are
313      * 6 such sets of rotations (XYZ, XZY, YXZ, YZX, ZXY and ZYX). Euler
314      * rotations are three successive rotations around the canonical
315      * axes X, Y and Z, the first and last rotations being around the
316      * same axis. There are 6 such sets of rotations (XYX, XZX, YXY,
317      * YZY, ZXZ and ZYZ), the most popular one being ZXZ.</p>
318      * <p>Beware that many people routinely use the term Euler angles even
319      * for what really are Cardan angles (this confusion is especially
320      * widespread in the aerospace business where Roll, Pitch and Yaw angles
321      * are often wrongly tagged as Euler angles).</p>
322 
323      * @param order order of rotations to compose, from left to right
324      * (i.e. we will use {@code r1.compose(r2.compose(r3, convention), convention)})
325      * @param convention convention to use for the semantics of the angle
326      * @param alpha1 angle of the first elementary rotation
327      * @param alpha2 angle of the second elementary rotation
328      * @param alpha3 angle of the third elementary rotation
329      */
330     public FieldRotation(final RotationOrder order, final RotationConvention convention,
331                          final T alpha1, final T alpha2, final T alpha3) {
332         final Field<T> field = alpha1.getField();
333         final FieldRotation<T> r1 = new FieldRotation<>(new FieldVector3D<>(field, order.getA1()), alpha1, convention);
334         final FieldRotation<T> r2 = new FieldRotation<>(new FieldVector3D<>(field, order.getA2()), alpha2, convention);
335         final FieldRotation<T> r3 = new FieldRotation<>(new FieldVector3D<>(field, order.getA3()), alpha3, convention);
336         final FieldRotation<T> composed = r1.compose(r2.compose(r3, convention), convention);
337         q0 = composed.q0;
338         q1 = composed.q1;
339         q2 = composed.q2;
340         q3 = composed.q3;
341     }
342 
343     /** Get identity rotation.
344      * @param field field for the components
345      * @return a new rotation
346      * @param <T> the type of the field elements
347      */
348     public static <T extends CalculusFieldElement<T>> FieldRotation<T> getIdentity(final Field<T> field) {
349         return new FieldRotation<>(field, Rotation.IDENTITY);
350     }
351 
352     /** Convert an orthogonal rotation matrix to a quaternion.
353      * @param ort orthogonal rotation matrix
354      * @return quaternion corresponding to the matrix
355      */
356     private T[] mat2quat(final T[][] ort) {
357 
358         final T[] quat = MathArrays.buildArray(ort[0][0].getField(), 4);
359 
360         // There are different ways to compute the quaternions elements
361         // from the matrix. They all involve computing one element from
362         // the diagonal of the matrix, and computing the three other ones
363         // using a formula involving a division by the first element,
364         // which unfortunately can be zero. Since the norm of the
365         // quaternion is 1, we know at least one element has an absolute
366         // value greater or equal to 0.5, so it is always possible to
367         // select the right formula and avoid division by zero and even
368         // numerical inaccuracy. Checking the elements in turn and using
369         // the first one greater than 0.45 is safe (this leads to a simple
370         // test since qi = 0.45 implies 4 qi^2 - 1 = -0.19)
371         T s = ort[0][0].add(ort[1][1]).add(ort[2][2]);
372         if (s.getReal() > -0.19) {
373             // compute q0 and deduce q1, q2 and q3
374             quat[0] = s.add(1.0).sqrt().multiply(0.5);
375             T inv = quat[0].reciprocal().multiply(0.25);
376             quat[1] = inv.multiply(ort[1][2].subtract(ort[2][1]));
377             quat[2] = inv.multiply(ort[2][0].subtract(ort[0][2]));
378             quat[3] = inv.multiply(ort[0][1].subtract(ort[1][0]));
379         } else {
380             s = ort[0][0].subtract(ort[1][1]).subtract(ort[2][2]);
381             if (s.getReal() > -0.19) {
382                 // compute q1 and deduce q0, q2 and q3
383                 quat[1] = s.add(1.0).sqrt().multiply(0.5);
384                 T inv = quat[1].reciprocal().multiply(0.25);
385                 quat[0] = inv.multiply(ort[1][2].subtract(ort[2][1]));
386                 quat[2] = inv.multiply(ort[0][1].add(ort[1][0]));
387                 quat[3] = inv.multiply(ort[0][2].add(ort[2][0]));
388             } else {
389                 s = ort[1][1].subtract(ort[0][0]).subtract(ort[2][2]);
390                 if (s.getReal() > -0.19) {
391                     // compute q2 and deduce q0, q1 and q3
392                     quat[2] = s.add(1.0).sqrt().multiply(0.5);
393                     T inv = quat[2].reciprocal().multiply(0.25);
394                     quat[0] = inv.multiply(ort[2][0].subtract(ort[0][2]));
395                     quat[1] = inv.multiply(ort[0][1].add(ort[1][0]));
396                     quat[3] = inv.multiply(ort[2][1].add(ort[1][2]));
397                 } else {
398                     // compute q3 and deduce q0, q1 and q2
399                     s = ort[2][2].subtract(ort[0][0]).subtract(ort[1][1]);
400                     quat[3] = s.add(1.0).sqrt().multiply(0.5);
401                     T inv = quat[3].reciprocal().multiply(0.25);
402                     quat[0] = inv.multiply(ort[0][1].subtract(ort[1][0]));
403                     quat[1] = inv.multiply(ort[0][2].add(ort[2][0]));
404                     quat[2] = inv.multiply(ort[2][1].add(ort[1][2]));
405                 }
406             }
407         }
408 
409         return quat;
410 
411     }
412 
413     /** Revert a rotation.
414      * Build a rotation which reverse the effect of another
415      * rotation. This means that if r(u) = v, then r.revert(v) = u. The
416      * instance is not changed.
417      * @return a new rotation whose effect is the reverse of the effect
418      * of the instance
419      */
420     public FieldRotation<T> revert() {
421         return new FieldRotation<>(q0.negate(), q1, q2, q3, false);
422     }
423 
424     /** Get the scalar coordinate of the quaternion.
425      * @return scalar coordinate of the quaternion
426      */
427     public T getQ0() {
428         return q0;
429     }
430 
431     /** Get the first coordinate of the vectorial part of the quaternion.
432      * @return first coordinate of the vectorial part of the quaternion
433      */
434     public T getQ1() {
435         return q1;
436     }
437 
438     /** Get the second coordinate of the vectorial part of the quaternion.
439      * @return second coordinate of the vectorial part of the quaternion
440      */
441     public T getQ2() {
442         return q2;
443     }
444 
445     /** Get the third coordinate of the vectorial part of the quaternion.
446      * @return third coordinate of the vectorial part of the quaternion
447      */
448     public T getQ3() {
449         return q3;
450     }
451 
452     /** Get the normalized axis of the rotation.
453      * <p>
454      * Note that as {@link #getAngle()} always returns an angle
455      * between 0 and &pi;, changing the convention changes the
456      * direction of the axis, not the sign of the angle.
457      * </p>
458      * @param convention convention to use for the semantics of the angle
459      * @return normalized axis of the rotation
460      * @see #FieldRotation(FieldVector3D, CalculusFieldElement, RotationConvention)
461      */
462     public FieldVector3D<T> getAxis(final RotationConvention convention) {
463         final T squaredSine = q1.square().add(q2.square()).add(q3.square());
464         if (squaredSine.getReal() == 0) {
465             final Field<T> field = squaredSine.getField();
466             return new FieldVector3D<>(convention == RotationConvention.VECTOR_OPERATOR ? field.getOne(): field.getOne().negate(),
467                                        field.getZero(),
468                                        field.getZero());
469         } else {
470             final double sgn = convention == RotationConvention.VECTOR_OPERATOR ? +1 : -1;
471             if (q0.getReal() < 0) {
472                 T inverse = squaredSine.sqrt().reciprocal().multiply(sgn);
473                 return new FieldVector3D<>(q1.multiply(inverse), q2.multiply(inverse), q3.multiply(inverse));
474             }
475             final T inverse = squaredSine.sqrt().reciprocal().negate().multiply(sgn);
476             return new FieldVector3D<>(q1.multiply(inverse), q2.multiply(inverse), q3.multiply(inverse));
477         }
478     }
479 
480     /** Get the angle of the rotation.
481      * @return angle of the rotation (between 0 and &pi;)
482      * @see #FieldRotation(FieldVector3D, CalculusFieldElement, RotationConvention)
483      */
484     public T getAngle() {
485         if ((q0.getReal() < -0.1) || (q0.getReal() > 0.1)) {
486             return q1.square().add(q2.square()).add(q3.square()).sqrt().asin().multiply(2);
487         } else if (q0.getReal() < 0) {
488             return q0.negate().acos().multiply(2);
489         }
490         return q0.acos().multiply(2);
491     }
492 
493     /** Get the Cardan or Euler angles corresponding to the instance.
494 
495      * <p>The equations show that each rotation can be defined by two
496      * different values of the Cardan or Euler angles set. For example
497      * if Cardan angles are used, the rotation defined by the angles
498      * a<sub>1</sub>, a<sub>2</sub> and a<sub>3</sub> is the same as
499      * the rotation defined by the angles &pi; + a<sub>1</sub>, &pi;
500      * - a<sub>2</sub> and &pi; + a<sub>3</sub>. This method implements
501      * the following arbitrary choices:</p>
502      * <ul>
503      *   <li>for Cardan angles, the chosen set is the one for which the
504      *   second angle is between -&pi;/2 and &pi;/2 (i.e its cosine is
505      *   positive),</li>
506      *   <li>for Euler angles, the chosen set is the one for which the
507      *   second angle is between 0 and &pi; (i.e its sine is positive).</li>
508      * </ul>
509 
510      * <p>Cardan and Euler angle have a very disappointing drawback: all
511      * of them have singularities. This means that if the instance is
512      * too close to the singularities corresponding to the given
513      * rotation order, it will be impossible to retrieve the angles. For
514      * Cardan angles, this is often called gimbal lock. There is
515      * <em>nothing</em> to do to prevent this, it is an intrinsic problem
516      * with Cardan and Euler representation (but not a problem with the
517      * rotation itself, which is perfectly well defined). For Cardan
518      * angles, singularities occur when the second angle is close to
519      * -&pi;/2 or +&pi;/2, for Euler angle singularities occur when the
520      * second angle is close to 0 or &pi;, this implies that the identity
521      * rotation is always singular for Euler angles!</p>
522 
523      * @param order rotation order to use
524      * @param convention convention to use for the semantics of the angle
525      * @return an array of three angles, in the order specified by the set
526      */
527     public T[] getAngles(final RotationOrder order, RotationConvention convention) {
528         return order.getAngles(this, convention);
529     }
530 
531     /** Get the 3X3 matrix corresponding to the instance
532      * @return the matrix corresponding to the instance
533      */
534     public T[][] getMatrix() {
535 
536         // products
537         final T q0q0  = q0.square();
538         final T q0q1  = q0.multiply(q1);
539         final T q0q2  = q0.multiply(q2);
540         final T q0q3  = q0.multiply(q3);
541         final T q1q1  = q1.square();
542         final T q1q2  = q1.multiply(q2);
543         final T q1q3  = q1.multiply(q3);
544         final T q2q2  = q2.square();
545         final T q2q3  = q2.multiply(q3);
546         final T q3q3  = q3.square();
547 
548         // create the matrix
549         final T[][] m = MathArrays.buildArray(q0.getField(), 3, 3);
550 
551         m [0][0] = q0q0.add(q1q1).multiply(2).subtract(1);
552         m [1][0] = q1q2.subtract(q0q3).multiply(2);
553         m [2][0] = q1q3.add(q0q2).multiply(2);
554 
555         m [0][1] = q1q2.add(q0q3).multiply(2);
556         m [1][1] = q0q0.add(q2q2).multiply(2).subtract(1);
557         m [2][1] = q2q3.subtract(q0q1).multiply(2);
558 
559         m [0][2] = q1q3.subtract(q0q2).multiply(2);
560         m [1][2] = q2q3.add(q0q1).multiply(2);
561         m [2][2] = q0q0.add(q3q3).multiply(2).subtract(1);
562 
563         return m;
564 
565     }
566 
567     /** Convert to a constant vector without derivatives.
568      * @return a constant vector
569      */
570     public Rotation toRotation() {
571         return new Rotation(q0.getReal(), q1.getReal(), q2.getReal(), q3.getReal(), false);
572     }
573 
574     /** Apply the rotation to a vector.
575      * @param u vector to apply the rotation to
576      * @return a new vector which is the image of u by the rotation
577      */
578     public FieldVector3D<T> applyTo(final FieldVector3D<T> u) {
579 
580         final T x = u.getX();
581         final T y = u.getY();
582         final T z = u.getZ();
583 
584         final T s = q1.multiply(x).add(q2.multiply(y)).add(q3.multiply(z));
585 
586         return new FieldVector3D<>(q0.multiply(x.multiply(q0).subtract(q2.multiply(z).subtract(q3.multiply(y)))).add(s.multiply(q1)).multiply(2).subtract(x),
587                                    q0.multiply(y.multiply(q0).subtract(q3.multiply(x).subtract(q1.multiply(z)))).add(s.multiply(q2)).multiply(2).subtract(y),
588                                    q0.multiply(z.multiply(q0).subtract(q1.multiply(y).subtract(q2.multiply(x)))).add(s.multiply(q3)).multiply(2).subtract(z));
589 
590     }
591 
592     /** Apply the rotation to a vector.
593      * @param u vector to apply the rotation to
594      * @return a new vector which is the image of u by the rotation
595      */
596     public FieldVector3D<T> applyTo(final Vector3D u) {
597 
598         final double x = u.getX();
599         final double y = u.getY();
600         final double z = u.getZ();
601 
602         final T s = q1.multiply(x).add(q2.multiply(y)).add(q3.multiply(z));
603 
604         return new FieldVector3D<>(q0.multiply(q0.multiply(x).subtract(q2.multiply(z).subtract(q3.multiply(y)))).add(s.multiply(q1)).multiply(2).subtract(x),
605                                    q0.multiply(q0.multiply(y).subtract(q3.multiply(x).subtract(q1.multiply(z)))).add(s.multiply(q2)).multiply(2).subtract(y),
606                                    q0.multiply(q0.multiply(z).subtract(q1.multiply(y).subtract(q2.multiply(x)))).add(s.multiply(q3)).multiply(2).subtract(z));
607 
608     }
609 
610     /** Apply the rotation to a vector stored in an array.
611      * @param in an array with three items which stores vector to rotate
612      * @param out an array with three items to put result to (it can be the same
613      * array as in)
614      */
615     public void applyTo(final T[] in, final T[] out) {
616 
617         final T x = in[0];
618         final T y = in[1];
619         final T z = in[2];
620 
621         final T s = q1.multiply(x).add(q2.multiply(y)).add(q3.multiply(z));
622 
623         out[0] = q0.multiply(x.multiply(q0).subtract(q2.multiply(z).subtract(q3.multiply(y)))).add(s.multiply(q1)).multiply(2).subtract(x);
624         out[1] = q0.multiply(y.multiply(q0).subtract(q3.multiply(x).subtract(q1.multiply(z)))).add(s.multiply(q2)).multiply(2).subtract(y);
625         out[2] = q0.multiply(z.multiply(q0).subtract(q1.multiply(y).subtract(q2.multiply(x)))).add(s.multiply(q3)).multiply(2).subtract(z);
626 
627     }
628 
629     /** Apply the rotation to a vector stored in an array.
630      * @param in an array with three items which stores vector to rotate
631      * @param out an array with three items to put result to
632      */
633     public void applyTo(final double[] in, final T[] out) {
634 
635         final double x = in[0];
636         final double y = in[1];
637         final double z = in[2];
638 
639         final T s = q1.multiply(x).add(q2.multiply(y)).add(q3.multiply(z));
640 
641         out[0] = q0.multiply(q0.multiply(x).subtract(q2.multiply(z).subtract(q3.multiply(y)))).add(s.multiply(q1)).multiply(2).subtract(x);
642         out[1] = q0.multiply(q0.multiply(y).subtract(q3.multiply(x).subtract(q1.multiply(z)))).add(s.multiply(q2)).multiply(2).subtract(y);
643         out[2] = q0.multiply(q0.multiply(z).subtract(q1.multiply(y).subtract(q2.multiply(x)))).add(s.multiply(q3)).multiply(2).subtract(z);
644 
645     }
646 
647     /** Apply a rotation to a vector.
648      * @param r rotation to apply
649      * @param u vector to apply the rotation to
650      * @param <T> the type of the field elements
651      * @return a new vector which is the image of u by the rotation
652      */
653     public static <T extends CalculusFieldElement<T>> FieldVector3D<T> applyTo(final Rotation r, final FieldVector3D<T> u) {
654 
655         final T x = u.getX();
656         final T y = u.getY();
657         final T z = u.getZ();
658 
659         final T s = x.multiply(r.getQ1()).add(y.multiply(r.getQ2())).add(z.multiply(r.getQ3()));
660 
661         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),
662                                    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),
663                                    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));
664 
665     }
666 
667     /** Apply the inverse of the rotation to a vector.
668      * @param u vector to apply the inverse of the rotation to
669      * @return a new vector which such that u is its image by the rotation
670      */
671     public FieldVector3D<T> applyInverseTo(final FieldVector3D<T> u) {
672 
673         final T x = u.getX();
674         final T y = u.getY();
675         final T z = u.getZ();
676 
677         final T s  = q1.multiply(x).add(q2.multiply(y)).add(q3.multiply(z));
678         final T m0 = q0.negate();
679 
680         return new FieldVector3D<>(m0.multiply(x.multiply(m0).subtract(q2.multiply(z).subtract(q3.multiply(y)))).add(s.multiply(q1)).multiply(2).subtract(x),
681                                    m0.multiply(y.multiply(m0).subtract(q3.multiply(x).subtract(q1.multiply(z)))).add(s.multiply(q2)).multiply(2).subtract(y),
682                                    m0.multiply(z.multiply(m0).subtract(q1.multiply(y).subtract(q2.multiply(x)))).add(s.multiply(q3)).multiply(2).subtract(z));
683 
684     }
685 
686     /** Apply the inverse of the rotation to a vector.
687      * @param u vector to apply the inverse of the rotation to
688      * @return a new vector which such that u is its image by the rotation
689      */
690     public FieldVector3D<T> applyInverseTo(final Vector3D u) {
691 
692         final double x = u.getX();
693         final double y = u.getY();
694         final double z = u.getZ();
695 
696         final T s  = q1.multiply(x).add(q2.multiply(y)).add(q3.multiply(z));
697         final T m0 = q0.negate();
698 
699         return new FieldVector3D<>(m0.multiply(m0.multiply(x).subtract(q2.multiply(z).subtract(q3.multiply(y)))).add(s.multiply(q1)).multiply(2).subtract(x),
700                                    m0.multiply(m0.multiply(y).subtract(q3.multiply(x).subtract(q1.multiply(z)))).add(s.multiply(q2)).multiply(2).subtract(y),
701                                    m0.multiply(m0.multiply(z).subtract(q1.multiply(y).subtract(q2.multiply(x)))).add(s.multiply(q3)).multiply(2).subtract(z));
702 
703     }
704 
705     /** Apply the inverse of the rotation to a vector stored in an array.
706      * @param in an array with three items which stores vector to rotate
707      * @param out an array with three items to put result to (it can be the same
708      * array as in)
709      */
710     public void applyInverseTo(final T[] in, final T[] out) {
711 
712         final T x = in[0];
713         final T y = in[1];
714         final T z = in[2];
715 
716         final T s = q1.multiply(x).add(q2.multiply(y)).add(q3.multiply(z));
717         final T m0 = q0.negate();
718 
719         out[0] = m0.multiply(x.multiply(m0).subtract(q2.multiply(z).subtract(q3.multiply(y)))).add(s.multiply(q1)).multiply(2).subtract(x);
720         out[1] = m0.multiply(y.multiply(m0).subtract(q3.multiply(x).subtract(q1.multiply(z)))).add(s.multiply(q2)).multiply(2).subtract(y);
721         out[2] = m0.multiply(z.multiply(m0).subtract(q1.multiply(y).subtract(q2.multiply(x)))).add(s.multiply(q3)).multiply(2).subtract(z);
722 
723     }
724 
725     /** Apply the inverse of the rotation to a vector stored in an array.
726      * @param in an array with three items which stores vector to rotate
727      * @param out an array with three items to put result to
728      */
729     public void applyInverseTo(final double[] in, final T[] out) {
730 
731         final double x = in[0];
732         final double y = in[1];
733         final double z = in[2];
734 
735         final T s = q1.multiply(x).add(q2.multiply(y)).add(q3.multiply(z));
736         final T m0 = q0.negate();
737 
738         out[0] = m0.multiply(m0.multiply(x).subtract(q2.multiply(z).subtract(q3.multiply(y)))).add(s.multiply(q1)).multiply(2).subtract(x);
739         out[1] = m0.multiply(m0.multiply(y).subtract(q3.multiply(x).subtract(q1.multiply(z)))).add(s.multiply(q2)).multiply(2).subtract(y);
740         out[2] = m0.multiply(m0.multiply(z).subtract(q1.multiply(y).subtract(q2.multiply(x)))).add(s.multiply(q3)).multiply(2).subtract(z);
741 
742     }
743 
744     /** Apply the inverse of a rotation to a vector.
745      * @param r rotation to apply
746      * @param u vector to apply the inverse of the rotation to
747      * @param <T> the type of the field elements
748      * @return a new vector which such that u is its image by the rotation
749      */
750     public static <T extends CalculusFieldElement<T>> FieldVector3D<T> applyInverseTo(final Rotation r, final FieldVector3D<T> u) {
751 
752         final T x = u.getX();
753         final T y = u.getY();
754         final T z = u.getZ();
755 
756         final T s  = x.multiply(r.getQ1()).add(y.multiply(r.getQ2())).add(z.multiply(r.getQ3()));
757         final double m0 = -r.getQ0();
758 
759         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),
760                                    y.multiply(m0).subtract(x.multiply(r.getQ3()).subtract(z.multiply(r.getQ1()))).multiply(m0).add(s.multiply(r.getQ2())).multiply(2).subtract(y),
761                                    z.multiply(m0).subtract(y.multiply(r.getQ1()).subtract(x.multiply(r.getQ2()))).multiply(m0).add(s.multiply(r.getQ3())).multiply(2).subtract(z));
762 
763     }
764 
765     /** Apply the instance to another rotation.
766      * <p>
767      * Calling this method is equivalent to call
768      * {@link #compose(FieldRotation, RotationConvention)
769      * compose(r, RotationConvention.VECTOR_OPERATOR)}.
770      * </p>
771      * @param r rotation to apply the rotation to
772      * @return a new rotation which is the composition of r by the instance
773      */
774     public FieldRotation<T> applyTo(final FieldRotation<T> r) {
775         return compose(r, RotationConvention.VECTOR_OPERATOR);
776     }
777 
778     /** Compose the instance with another rotation.
779      * <p>
780      * If the semantics of the rotations composition corresponds to a
781      * {@link RotationConvention#VECTOR_OPERATOR vector operator} convention,
782      * applying the instance to a rotation is computing the composition
783      * in an order compliant with the following rule : let {@code u} be any
784      * vector and {@code v} its image by {@code r1} (i.e.
785      * {@code r1.applyTo(u) = v}). Let {@code w} be the image of {@code v} by
786      * rotation {@code r2} (i.e. {@code r2.applyTo(v) = w}). Then
787      * {@code w = comp.applyTo(u)}, where
788      * {@code comp = r2.compose(r1, RotationConvention.VECTOR_OPERATOR)}.
789      * </p>
790      * <p>
791      * If the semantics of the rotations composition corresponds to a
792      * {@link RotationConvention#FRAME_TRANSFORM frame transform} convention,
793      * the application order will be reversed. So keeping the exact same
794      * meaning of all {@code r1}, {@code r2}, {@code u}, {@code v}, {@code w}
795      * and  {@code comp} as above, {@code comp} could also be computed as
796      * {@code comp = r1.compose(r2, RotationConvention.FRAME_TRANSFORM)}.
797      * </p>
798      * @param r rotation to apply the rotation to
799      * @param convention convention to use for the semantics of the angle
800      * @return a new rotation which is the composition of r by the instance
801      */
802     public FieldRotation<T> compose(final FieldRotation<T> r, final RotationConvention convention) {
803         return convention == RotationConvention.VECTOR_OPERATOR ?
804                              composeInternal(r) : r.composeInternal(this);
805     }
806 
807     /** Compose the instance with another rotation using vector operator convention.
808      * @param r rotation to apply the rotation to
809      * @return a new rotation which is the composition of r by the instance
810      * using vector operator convention
811      */
812     private FieldRotation<T> composeInternal(final FieldRotation<T> r) {
813         return new FieldRotation<>(r.q0.multiply(q0).subtract(r.q1.multiply(q1).add(r.q2.multiply(q2)).add(r.q3.multiply(q3))),
814                                    r.q1.multiply(q0).add(r.q0.multiply(q1)).add(r.q2.multiply(q3).subtract(r.q3.multiply(q2))),
815                                    r.q2.multiply(q0).add(r.q0.multiply(q2)).add(r.q3.multiply(q1).subtract(r.q1.multiply(q3))),
816                                    r.q3.multiply(q0).add(r.q0.multiply(q3)).add(r.q1.multiply(q2).subtract(r.q2.multiply(q1))),
817                                    false);
818     }
819 
820     /** Apply the instance to another rotation.
821      * <p>
822      * Calling this method is equivalent to call
823      * {@link #compose(Rotation, RotationConvention)
824      * compose(r, RotationConvention.VECTOR_OPERATOR)}.
825      * </p>
826      * @param r rotation to apply the rotation to
827      * @return a new rotation which is the composition of r by the instance
828      */
829     public FieldRotation<T> applyTo(final Rotation r) {
830         return compose(r, RotationConvention.VECTOR_OPERATOR);
831     }
832 
833     /** Compose the instance with another rotation.
834      * <p>
835      * If the semantics of the rotations composition corresponds to a
836      * {@link RotationConvention#VECTOR_OPERATOR vector operator} convention,
837      * applying the instance to a rotation is computing the composition
838      * in an order compliant with the following rule : let {@code u} be any
839      * vector and {@code v} its image by {@code r1} (i.e.
840      * {@code r1.applyTo(u) = v}). Let {@code w} be the image of {@code v} by
841      * rotation {@code r2} (i.e. {@code r2.applyTo(v) = w}). Then
842      * {@code w = comp.applyTo(u)}, where
843      * {@code comp = r2.compose(r1, RotationConvention.VECTOR_OPERATOR)}.
844      * </p>
845      * <p>
846      * If the semantics of the rotations composition corresponds to a
847      * {@link RotationConvention#FRAME_TRANSFORM frame transform} convention,
848      * the application order will be reversed. So keeping the exact same
849      * meaning of all {@code r1}, {@code r2}, {@code u}, {@code v}, {@code w}
850      * and  {@code comp} as above, {@code comp} could also be computed as
851      * {@code comp = r1.compose(r2, RotationConvention.FRAME_TRANSFORM)}.
852      * </p>
853      * @param r rotation to apply the rotation to
854      * @param convention convention to use for the semantics of the angle
855      * @return a new rotation which is the composition of r by the instance
856      */
857     public FieldRotation<T> compose(final Rotation r, final RotationConvention convention) {
858         return convention == RotationConvention.VECTOR_OPERATOR ?
859                              composeInternal(r) : applyTo(r, this);
860     }
861 
862     /** Compose the instance with another rotation using vector operator convention.
863      * @param r rotation to apply the rotation to
864      * @return a new rotation which is the composition of r by the instance
865      * using vector operator convention
866      */
867     private FieldRotation<T> composeInternal(final Rotation r) {
868         return new FieldRotation<>(q0.multiply(r.getQ0()).subtract(q1.multiply(r.getQ1()).add(q2.multiply(r.getQ2())).add(q3.multiply(r.getQ3()))),
869                                    q0.multiply(r.getQ1()).add(q1.multiply(r.getQ0())).add(q3.multiply(r.getQ2()).subtract(q2.multiply(r.getQ3()))),
870                                    q0.multiply(r.getQ2()).add(q2.multiply(r.getQ0())).add(q1.multiply(r.getQ3()).subtract(q3.multiply(r.getQ1()))),
871                                    q0.multiply(r.getQ3()).add(q3.multiply(r.getQ0())).add(q2.multiply(r.getQ1()).subtract(q1.multiply(r.getQ2()))),
872                                    false);
873     }
874 
875     /** Apply a rotation to another rotation.
876      * Applying a rotation to another rotation is computing the composition
877      * in an order compliant with the following rule : let u be any
878      * vector and v its image by rInner (i.e. rInner.applyTo(u) = v), let w be the image
879      * of v by rOuter (i.e. rOuter.applyTo(v) = w), then w = comp.applyTo(u),
880      * where comp = applyTo(rOuter, rInner).
881      * @param r1 rotation to apply
882      * @param rInner rotation to apply the rotation to
883      * @param <T> the type of the field elements
884      * @return a new rotation which is the composition of r by the instance
885      */
886     public static <T extends CalculusFieldElement<T>> FieldRotation<T> applyTo(final Rotation r1, final FieldRotation<T> rInner) {
887         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()))),
888                                    rInner.q1.multiply(r1.getQ0()).add(rInner.q0.multiply(r1.getQ1())).add(rInner.q2.multiply(r1.getQ3()).subtract(rInner.q3.multiply(r1.getQ2()))),
889                                    rInner.q2.multiply(r1.getQ0()).add(rInner.q0.multiply(r1.getQ2())).add(rInner.q3.multiply(r1.getQ1()).subtract(rInner.q1.multiply(r1.getQ3()))),
890                                    rInner.q3.multiply(r1.getQ0()).add(rInner.q0.multiply(r1.getQ3())).add(rInner.q1.multiply(r1.getQ2()).subtract(rInner.q2.multiply(r1.getQ1()))),
891                                    false);
892     }
893 
894     /** Apply the inverse of the instance to another rotation.
895      * <p>
896      * Calling this method is equivalent to call
897      * {@link #composeInverse(FieldRotation, RotationConvention)
898      * composeInverse(r, RotationConvention.VECTOR_OPERATOR)}.
899      * </p>
900      * @param r rotation to apply the rotation to
901      * @return a new rotation which is the composition of r by the inverse
902      * of the instance
903      */
904     public FieldRotation<T> applyInverseTo(final FieldRotation<T> r) {
905         return composeInverse(r, RotationConvention.VECTOR_OPERATOR);
906     }
907 
908     /** Compose the inverse of the instance with another rotation.
909      * <p>
910      * If the semantics of the rotations composition corresponds to a
911      * {@link RotationConvention#VECTOR_OPERATOR vector operator} convention,
912      * applying the inverse of the instance to a rotation is computing
913      * the composition in an order compliant with the following rule :
914      * let {@code u} be any vector and {@code v} its image by {@code r1}
915      * (i.e. {@code r1.applyTo(u) = v}). Let {@code w} be the inverse image
916      * of {@code v} by {@code r2} (i.e. {@code r2.applyInverseTo(v) = w}).
917      * Then {@code w = comp.applyTo(u)}, where
918      * {@code comp = r2.composeInverse(r1)}.
919      * </p>
920      * <p>
921      * If the semantics of the rotations composition corresponds to a
922      * {@link RotationConvention#FRAME_TRANSFORM frame transform} convention,
923      * the application order will be reversed, which means it is the
924      * <em>innermost</em> rotation that will be reversed. So keeping the exact same
925      * meaning of all {@code r1}, {@code r2}, {@code u}, {@code v}, {@code w}
926      * and  {@code comp} as above, {@code comp} could also be computed as
927      * {@code comp = r1.revert().composeInverse(r2.revert(), RotationConvention.FRAME_TRANSFORM)}.
928      * </p>
929      * @param r rotation to apply the rotation to
930      * @param convention convention to use for the semantics of the angle
931      * @return a new rotation which is the composition of r by the inverse
932      * of the instance
933      */
934     public FieldRotation<T> composeInverse(final FieldRotation<T> r, final RotationConvention convention) {
935         return convention == RotationConvention.VECTOR_OPERATOR ?
936                              composeInverseInternal(r) : r.composeInternal(revert());
937     }
938 
939     /** Compose the inverse of the instance with another rotation
940      * using vector operator convention.
941      * @param r rotation to apply the rotation to
942      * @return a new rotation which is the composition of r by the inverse
943      * of the instance using vector operator convention
944      */
945     private FieldRotation<T> composeInverseInternal(FieldRotation<T> r) {
946         return new FieldRotation<>(r.q0.multiply(q0).add(r.q1.multiply(q1)).add(r.q2.multiply(q2)).add(r.q3.multiply(q3)).negate(),
947                                    r.q0.multiply(q1).add(r.q2.multiply(q3).subtract(r.q3.multiply(q2))).subtract(r.q1.multiply(q0)),
948                                    r.q0.multiply(q2).add(r.q3.multiply(q1).subtract(r.q1.multiply(q3))).subtract(r.q2.multiply(q0)),
949                                    r.q0.multiply(q3).add(r.q1.multiply(q2).subtract(r.q2.multiply(q1))).subtract(r.q3.multiply(q0)),
950                                    false);
951     }
952 
953     /** Apply the inverse of the instance to another rotation.
954      * <p>
955      * Calling this method is equivalent to call
956      * {@link #composeInverse(Rotation, RotationConvention)
957      * composeInverse(r, RotationConvention.VECTOR_OPERATOR)}.
958      * </p>
959      * @param r rotation to apply the rotation to
960      * @return a new rotation which is the composition of r by the inverse
961      * of the instance
962      */
963     public FieldRotation<T> applyInverseTo(final Rotation r) {
964         return composeInverse(r, RotationConvention.VECTOR_OPERATOR);
965     }
966 
967     /** Compose the inverse of the instance with another rotation.
968      * <p>
969      * If the semantics of the rotations composition corresponds to a
970      * {@link RotationConvention#VECTOR_OPERATOR vector operator} convention,
971      * applying the inverse of the instance to a rotation is computing
972      * the composition in an order compliant with the following rule :
973      * let {@code u} be any vector and {@code v} its image by {@code r1}
974      * (i.e. {@code r1.applyTo(u) = v}). Let {@code w} be the inverse image
975      * of {@code v} by {@code r2} (i.e. {@code r2.applyInverseTo(v) = w}).
976      * Then {@code w = comp.applyTo(u)}, where
977      * {@code comp = r2.composeInverse(r1)}.
978      * </p>
979      * <p>
980      * If the semantics of the rotations composition corresponds to a
981      * {@link RotationConvention#FRAME_TRANSFORM frame transform} convention,
982      * the application order will be reversed, which means it is the
983      * <em>innermost</em> rotation that will be reversed. So keeping the exact same
984      * meaning of all {@code r1}, {@code r2}, {@code u}, {@code v}, {@code w}
985      * and  {@code comp} as above, {@code comp} could also be computed as
986      * {@code comp = r1.revert().composeInverse(r2.revert(), RotationConvention.FRAME_TRANSFORM)}.
987      * </p>
988      * @param r rotation to apply the rotation to
989      * @param convention convention to use for the semantics of the angle
990      * @return a new rotation which is the composition of r by the inverse
991      * of the instance
992      */
993     public FieldRotation<T> composeInverse(final Rotation r, final RotationConvention convention) {
994         return convention == RotationConvention.VECTOR_OPERATOR ?
995                              composeInverseInternal(r) : applyTo(r, revert());
996     }
997 
998     /** Compose the inverse of the instance with another rotation
999      * using vector operator convention.
1000      * @param r rotation to apply the rotation to
1001      * @return a new rotation which is the composition of r by the inverse
1002      * of the instance using vector operator convention
1003      */
1004     private FieldRotation<T> composeInverseInternal(Rotation r) {
1005         return new FieldRotation<>(q0.multiply(r.getQ0()).add(q1.multiply(r.getQ1()).add(q2.multiply(r.getQ2())).add(q3.multiply(r.getQ3()))).negate(),
1006                                    q1.multiply(r.getQ0()).add(q3.multiply(r.getQ2()).subtract(q2.multiply(r.getQ3()))).subtract(q0.multiply(r.getQ1())),
1007                                    q2.multiply(r.getQ0()).add(q1.multiply(r.getQ3()).subtract(q3.multiply(r.getQ1()))).subtract(q0.multiply(r.getQ2())),
1008                                    q3.multiply(r.getQ0()).add(q2.multiply(r.getQ1()).subtract(q1.multiply(r.getQ2()))).subtract(q0.multiply(r.getQ3())),
1009                                    false);
1010     }
1011 
1012     /** Apply the inverse of a rotation to another rotation.
1013      * Applying the inverse of a rotation to another rotation is computing
1014      * the composition in an order compliant with the following rule :
1015      * let u be any vector and v its image by rInner (i.e. rInner.applyTo(u) = v),
1016      * let w be the inverse image of v by rOuter
1017      * (i.e. rOuter.applyInverseTo(v) = w), then w = comp.applyTo(u), where
1018      * comp = applyInverseTo(rOuter, rInner).
1019      * @param rOuter rotation to apply the rotation to
1020      * @param rInner rotation to apply the rotation to
1021      * @param <T> the type of the field elements
1022      * @return a new rotation which is the composition of r by the inverse
1023      * of the instance
1024      */
1025     public static <T extends CalculusFieldElement<T>> FieldRotation<T> applyInverseTo(final Rotation rOuter, final FieldRotation<T> rInner) {
1026         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(),
1027                                    rInner.q0.multiply(rOuter.getQ1()).add(rInner.q2.multiply(rOuter.getQ3()).subtract(rInner.q3.multiply(rOuter.getQ2()))).subtract(rInner.q1.multiply(rOuter.getQ0())),
1028                                    rInner.q0.multiply(rOuter.getQ2()).add(rInner.q3.multiply(rOuter.getQ1()).subtract(rInner.q1.multiply(rOuter.getQ3()))).subtract(rInner.q2.multiply(rOuter.getQ0())),
1029                                    rInner.q0.multiply(rOuter.getQ3()).add(rInner.q1.multiply(rOuter.getQ2()).subtract(rInner.q2.multiply(rOuter.getQ1()))).subtract(rInner.q3.multiply(rOuter.getQ0())),
1030                                    false);
1031     }
1032 
1033     /** Perfect orthogonality on a 3X3 matrix.
1034      * @param m initial matrix (not exactly orthogonal)
1035      * @param threshold convergence threshold for the iterative
1036      * orthogonality correction (convergence is reached when the
1037      * difference between two steps of the Frobenius norm of the
1038      * correction is below this threshold)
1039      * @return an orthogonal matrix close to m
1040      * @exception MathIllegalArgumentException if the matrix cannot be
1041      * orthogonalized with the given threshold after 10 iterations
1042      */
1043     private T[][] orthogonalizeMatrix(final T[][] m, final double threshold)
1044         throws MathIllegalArgumentException {
1045 
1046         T x00 = m[0][0];
1047         T x01 = m[0][1];
1048         T x02 = m[0][2];
1049         T x10 = m[1][0];
1050         T x11 = m[1][1];
1051         T x12 = m[1][2];
1052         T x20 = m[2][0];
1053         T x21 = m[2][1];
1054         T x22 = m[2][2];
1055         double fn = 0;
1056         double fn1;
1057 
1058         final T[][] o = MathArrays.buildArray(m[0][0].getField(), 3, 3);
1059 
1060         // iterative correction: Xn+1 = Xn - 0.5 * (Xn.Mt.Xn - M)
1061         int i;
1062         for (i = 0; i < 11; ++i) {
1063 
1064             // Mt.Xn
1065             final T mx00 = m[0][0].multiply(x00).add(m[1][0].multiply(x10)).add(m[2][0].multiply(x20));
1066             final T mx10 = m[0][1].multiply(x00).add(m[1][1].multiply(x10)).add(m[2][1].multiply(x20));
1067             final T mx20 = m[0][2].multiply(x00).add(m[1][2].multiply(x10)).add(m[2][2].multiply(x20));
1068             final T mx01 = m[0][0].multiply(x01).add(m[1][0].multiply(x11)).add(m[2][0].multiply(x21));
1069             final T mx11 = m[0][1].multiply(x01).add(m[1][1].multiply(x11)).add(m[2][1].multiply(x21));
1070             final T mx21 = m[0][2].multiply(x01).add(m[1][2].multiply(x11)).add(m[2][2].multiply(x21));
1071             final T mx02 = m[0][0].multiply(x02).add(m[1][0].multiply(x12)).add(m[2][0].multiply(x22));
1072             final T mx12 = m[0][1].multiply(x02).add(m[1][1].multiply(x12)).add(m[2][1].multiply(x22));
1073             final T mx22 = m[0][2].multiply(x02).add(m[1][2].multiply(x12)).add(m[2][2].multiply(x22));
1074 
1075             // Xn+1
1076             o[0][0] = x00.subtract(x00.multiply(mx00).add(x01.multiply(mx10)).add(x02.multiply(mx20)).subtract(m[0][0]).multiply(0.5));
1077             o[0][1] = x01.subtract(x00.multiply(mx01).add(x01.multiply(mx11)).add(x02.multiply(mx21)).subtract(m[0][1]).multiply(0.5));
1078             o[0][2] = x02.subtract(x00.multiply(mx02).add(x01.multiply(mx12)).add(x02.multiply(mx22)).subtract(m[0][2]).multiply(0.5));
1079             o[1][0] = x10.subtract(x10.multiply(mx00).add(x11.multiply(mx10)).add(x12.multiply(mx20)).subtract(m[1][0]).multiply(0.5));
1080             o[1][1] = x11.subtract(x10.multiply(mx01).add(x11.multiply(mx11)).add(x12.multiply(mx21)).subtract(m[1][1]).multiply(0.5));
1081             o[1][2] = x12.subtract(x10.multiply(mx02).add(x11.multiply(mx12)).add(x12.multiply(mx22)).subtract(m[1][2]).multiply(0.5));
1082             o[2][0] = x20.subtract(x20.multiply(mx00).add(x21.multiply(mx10)).add(x22.multiply(mx20)).subtract(m[2][0]).multiply(0.5));
1083             o[2][1] = x21.subtract(x20.multiply(mx01).add(x21.multiply(mx11)).add(x22.multiply(mx21)).subtract(m[2][1]).multiply(0.5));
1084             o[2][2] = x22.subtract(x20.multiply(mx02).add(x21.multiply(mx12)).add(x22.multiply(mx22)).subtract(m[2][2]).multiply(0.5));
1085 
1086             // correction on each elements
1087             final double corr00 = o[0][0].getReal() - m[0][0].getReal();
1088             final double corr01 = o[0][1].getReal() - m[0][1].getReal();
1089             final double corr02 = o[0][2].getReal() - m[0][2].getReal();
1090             final double corr10 = o[1][0].getReal() - m[1][0].getReal();
1091             final double corr11 = o[1][1].getReal() - m[1][1].getReal();
1092             final double corr12 = o[1][2].getReal() - m[1][2].getReal();
1093             final double corr20 = o[2][0].getReal() - m[2][0].getReal();
1094             final double corr21 = o[2][1].getReal() - m[2][1].getReal();
1095             final double corr22 = o[2][2].getReal() - m[2][2].getReal();
1096 
1097             // Frobenius norm of the correction
1098             fn1 = corr00 * corr00 + corr01 * corr01 + corr02 * corr02 +
1099                   corr10 * corr10 + corr11 * corr11 + corr12 * corr12 +
1100                   corr20 * corr20 + corr21 * corr21 + corr22 * corr22;
1101 
1102             // convergence test
1103             if (FastMath.abs(fn1 - fn) <= threshold) {
1104                 return o;
1105             }
1106 
1107             // prepare next iteration
1108             x00 = o[0][0];
1109             x01 = o[0][1];
1110             x02 = o[0][2];
1111             x10 = o[1][0];
1112             x11 = o[1][1];
1113             x12 = o[1][2];
1114             x20 = o[2][0];
1115             x21 = o[2][1];
1116             x22 = o[2][2];
1117             fn  = fn1;
1118 
1119         }
1120 
1121         // the algorithm did not converge after 10 iterations
1122         throw new MathIllegalArgumentException(LocalizedGeometryFormats.UNABLE_TO_ORTHOGONOLIZE_MATRIX,
1123                                                i - 1);
1124 
1125     }
1126 
1127     /** Compute the <i>distance</i> between two rotations.
1128      * <p>The <i>distance</i> is intended here as a way to check if two
1129      * rotations are almost similar (i.e. they transform vectors the same way)
1130      * or very different. It is mathematically defined as the angle of
1131      * the rotation r that prepended to one of the rotations gives the other
1132      * one: \(r_1(r) = r_2\)
1133      * </p>
1134      * <p>This distance is an angle between 0 and &pi;. Its value is the smallest
1135      * possible upper bound of the angle in radians between r<sub>1</sub>(v)
1136      * and r<sub>2</sub>(v) for all possible vectors v. This upper bound is
1137      * reached for some v. The distance is equal to 0 if and only if the two
1138      * rotations are identical.</p>
1139      * <p>Comparing two rotations should always be done using this value rather
1140      * than for example comparing the components of the quaternions. It is much
1141      * more stable, and has a geometric meaning. Also comparing quaternions
1142      * components is error prone since for example quaternions (0.36, 0.48, -0.48, -0.64)
1143      * and (-0.36, -0.48, 0.48, 0.64) represent exactly the same rotation despite
1144      * their components are different (they are exact opposites).</p>
1145      * @param r1 first rotation
1146      * @param r2 second rotation
1147      * @param <T> the type of the field elements
1148      * @return <i>distance</i> between r1 and r2
1149      */
1150     public static <T extends CalculusFieldElement<T>> T distance(final FieldRotation<T> r1, final FieldRotation<T> r2) {
1151         return r1.composeInverseInternal(r2).getAngle();
1152     }
1153 
1154 }