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.exception.MathIllegalArgumentException;
28  import org.hipparchus.exception.MathRuntimeException;
29  import org.hipparchus.geometry.LocalizedGeometryFormats;
30  import org.hipparchus.util.FastMath;
31  import org.hipparchus.util.MathArrays;
32  import org.hipparchus.util.SinCos;
33  
34  /**
35   * This class implements rotations in a three-dimensional space.
36   *
37   * <p>Rotations can be represented by several different mathematical
38   * entities (matrices, axe and angle, Cardan or Euler angles,
39   * quaternions). This class presents an higher level abstraction, more
40   * user-oriented and hiding this implementation details. Well, for the
41   * curious, we use quaternions for the internal representation. The
42   * user can build a rotation from any of these representations, and
43   * any of these representations can be retrieved from a
44   * <code>Rotation</code> instance (see the various constructors and
45   * getters). In addition, a rotation can also be built implicitly
46   * from a set of vectors and their image.</p>
47   * <p>This implies that this class can be used to convert from one
48   * representation to another one. For example, converting a rotation
49   * matrix into a set of Cardan angles from can be done using the
50   * following single line of code:</p>
51   * <pre>
52   * double[] angles = new Rotation(matrix, 1.0e-10).getAngles(RotationOrder.XYZ);
53   * </pre>
54   * <p>Focus is oriented on what a rotation <em>do</em> rather than on its
55   * underlying representation. Once it has been built, and regardless of its
56   * internal representation, a rotation is an <em>operator</em> which basically
57   * transforms three dimensional {@link Vector3D vectors} into other three
58   * dimensional {@link Vector3D vectors}. Depending on the application, the
59   * meaning of these vectors may vary and the semantics of the rotation also.</p>
60   * <p>For example in an spacecraft attitude simulation tool, users will often
61   * consider the vectors are fixed (say the Earth direction for example) and the
62   * frames change. The rotation transforms the coordinates of the vector in inertial
63   * frame into the coordinates of the same vector in satellite frame. In this
64   * case, the rotation implicitly defines the relation between the two frames.</p>
65   * <p>Another example could be a telescope control application, where the rotation
66   * would transform the sighting direction at rest into the desired observing
67   * direction when the telescope is pointed towards an object of interest. In this
68   * case the rotation transforms the direction at rest in a topocentric frame
69   * into the sighting direction in the same topocentric frame. This implies in this
70   * case the frame is fixed and the vector moves.</p>
71   * <p>In many case, both approaches will be combined. In our telescope example,
72   * we will probably also need to transform the observing direction in the topocentric
73   * frame into the observing direction in inertial frame taking into account the observatory
74   * location and the Earth rotation, which would essentially be an application of the
75   * first approach.</p>
76   *
77   * <p>These examples show that a rotation is what the user wants it to be. This
78   * class does not push the user towards one specific definition and hence does not
79   * provide methods like <code>projectVectorIntoDestinationFrame</code> or
80   * <code>computeTransformedDirection</code>. It provides simpler and more generic
81   * methods: {@link #applyTo(Vector3D) applyTo(Vector3D)} and {@link
82   * #applyInverseTo(Vector3D) applyInverseTo(Vector3D)}.</p>
83   *
84   * <p>Since a rotation is basically a vectorial operator, several rotations can be
85   * composed together and the composite operation <code>r = r<sub>1</sub> o
86   * r<sub>2</sub></code> (which means that for each vector <code>u</code>,
87   * <code>r(u) = r<sub>1</sub>(r<sub>2</sub>(u))</code>) is also a rotation. Hence
88   * we can consider that in addition to vectors, a rotation can be applied to other
89   * rotations as well (or to itself). With our previous notations, we would say we
90   * can apply <code>r<sub>1</sub></code> to <code>r<sub>2</sub></code> and the result
91   * we get is <code>r = r<sub>1</sub> o r<sub>2</sub></code>. For this purpose, the
92   * class provides the methods: {@link #applyTo(Rotation) applyTo(Rotation)} and
93   * {@link #applyInverseTo(Rotation) applyInverseTo(Rotation)}.</p>
94   *
95   * <p>Rotations are guaranteed to be immutable objects.</p>
96   *
97   * @see Vector3D
98   * @see RotationOrder
99   */
100 
101 public class Rotation implements Serializable {
102 
103   /** Identity rotation. */
104   public static final Rotation IDENTITY = new Rotation(1.0, 0.0, 0.0, 0.0, false);
105 
106   /** Serializable version identifier */
107   private static final long serialVersionUID = -2153622329907944313L;
108 
109   /** Scalar coordinate of the quaternion. */
110   private final double q0;
111 
112   /** First coordinate of the vectorial part of the quaternion. */
113   private final double q1;
114 
115   /** Second coordinate of the vectorial part of the quaternion. */
116   private final double q2;
117 
118   /** Third coordinate of the vectorial part of the quaternion. */
119   private final double q3;
120 
121   /** Build a rotation from the quaternion coordinates.
122    * <p>A rotation can be built from a <em>normalized</em> quaternion,
123    * i.e. a quaternion for which q<sub>0</sub><sup>2</sup> +
124    * q<sub>1</sub><sup>2</sup> + q<sub>2</sub><sup>2</sup> +
125    * q<sub>3</sub><sup>2</sup> = 1. If the quaternion is not normalized,
126    * the constructor can normalize it in a preprocessing step.</p>
127    * <p>Note that some conventions put the scalar part of the quaternion
128    * as the 4<sup>th</sup> component and the vector part as the first three
129    * components. This is <em>not</em> our convention. We put the scalar part
130    * as the first component.</p>
131    * @param q0 scalar part of the quaternion
132    * @param q1 first coordinate of the vectorial part of the quaternion
133    * @param q2 second coordinate of the vectorial part of the quaternion
134    * @param q3 third coordinate of the vectorial part of the quaternion
135    * @param needsNormalization if true, the coordinates are considered
136    * not to be normalized, a normalization preprocessing step is performed
137    * before using them
138    */
139   public Rotation(double q0, double q1, double q2, double q3,
140                   boolean needsNormalization) {
141 
142     if (needsNormalization) {
143       // normalization preprocessing
144       double inv = 1.0 / FastMath.sqrt(q0 * q0 + q1 * q1 + q2 * q2 + q3 * q3);
145       q0 *= inv;
146       q1 *= inv;
147       q2 *= inv;
148       q3 *= inv;
149     }
150 
151     this.q0 = q0;
152     this.q1 = q1;
153     this.q2 = q2;
154     this.q3 = q3;
155 
156   }
157 
158   /** Build a rotation from an axis and an angle.
159    * @param axis axis around which to rotate
160    * @param angle rotation angle
161    * @param convention convention to use for the semantics of the angle
162    * @exception MathIllegalArgumentException if the axis norm is zero
163    */
164   public Rotation(final Vector3D axis, final double angle, final RotationConvention convention)
165       throws MathIllegalArgumentException {
166 
167     double norm = axis.getNorm();
168     if (norm == 0) {
169       throw new MathIllegalArgumentException(LocalizedGeometryFormats.ZERO_NORM_FOR_ROTATION_AXIS);
170     }
171 
172     double halfAngle = convention == RotationConvention.VECTOR_OPERATOR ? -0.5 * angle : 0.5 * angle;
173     SinCos sinCos = FastMath.sinCos(halfAngle);
174     double coeff = sinCos.sin() / norm;
175 
176     q0 = sinCos.cos();
177     q1 = coeff * axis.getX();
178     q2 = coeff * axis.getY();
179     q3 = coeff * axis.getZ();
180 
181   }
182 
183   /** Build a rotation from a 3X3 matrix.
184 
185    * <p>Rotation matrices are orthogonal matrices, i.e. unit matrices
186    * (which are matrices for which m.m<sup>T</sup> = I) with real
187    * coefficients. The module of the determinant of unit matrices is
188    * 1, among the orthogonal 3X3 matrices, only the ones having a
189    * positive determinant (+1) are rotation matrices.</p>
190 
191    * <p>When a rotation is defined by a matrix with truncated values
192    * (typically when it is extracted from a technical sheet where only
193    * four to five significant digits are available), the matrix is not
194    * orthogonal anymore. This constructor handles this case
195    * transparently by using a copy of the given matrix and applying a
196    * correction to the copy in order to perfect its orthogonality. If
197    * the Frobenius norm of the correction needed is above the given
198    * threshold, then the matrix is considered to be too far from a
199    * true rotation matrix and an exception is thrown.</p>
200 
201    * @param m rotation matrix
202    * @param threshold convergence threshold for the iterative
203    * orthogonality correction (convergence is reached when the
204    * difference between two steps of the Frobenius norm of the
205    * correction is below this threshold)
206 
207    * @exception MathIllegalArgumentException if the matrix is not a 3X3
208    * matrix, or if it cannot be transformed into an orthogonal matrix
209    * with the given threshold, or if the determinant of the resulting
210    * orthogonal matrix is negative
211 
212    */
213   public Rotation(double[][] m, double threshold)
214     throws MathIllegalArgumentException {
215 
216     // dimension check
217     if ((m.length != 3) || (m[0].length != 3) ||
218         (m[1].length != 3) || (m[2].length != 3)) {
219       throw new MathIllegalArgumentException(LocalizedGeometryFormats.ROTATION_MATRIX_DIMENSIONS,
220                                              m.length, m[0].length);
221     }
222 
223     // compute a "close" orthogonal matrix
224     double[][] ort = orthogonalizeMatrix(m, threshold);
225 
226     // check the sign of the determinant
227     double det = ort[0][0] * (ort[1][1] * ort[2][2] - ort[2][1] * ort[1][2]) -
228                  ort[1][0] * (ort[0][1] * ort[2][2] - ort[2][1] * ort[0][2]) +
229                  ort[2][0] * (ort[0][1] * ort[1][2] - ort[1][1] * ort[0][2]);
230     if (det < 0.0) {
231       throw new MathIllegalArgumentException(LocalizedGeometryFormats.CLOSEST_ORTHOGONAL_MATRIX_HAS_NEGATIVE_DETERMINANT,
232                                              det);
233     }
234 
235     double[] quat = mat2quat(ort);
236     q0 = quat[0];
237     q1 = quat[1];
238     q2 = quat[2];
239     q3 = quat[3];
240 
241   }
242 
243   /** Build the rotation that transforms a pair of vectors into another pair.
244 
245    * <p>Except for possible scale factors, if the instance were applied to
246    * the pair (u<sub>1</sub>, u<sub>2</sub>) it will produce the pair
247    * (v<sub>1</sub>, v<sub>2</sub>).</p>
248 
249    * <p>If the angular separation between u<sub>1</sub> and u<sub>2</sub> is
250    * not the same as the angular separation between v<sub>1</sub> and
251    * v<sub>2</sub>, then a corrected v'<sub>2</sub> will be used rather than
252    * v<sub>2</sub>, the corrected vector will be in the (±v<sub>1</sub>,
253    * +v<sub>2</sub>) half-plane.</p>
254    * @param u1 first vector of the origin pair
255    * @param u2 second vector of the origin pair
256    * @param v1 desired image of u1 by the rotation
257    * @param v2 desired image of u2 by the rotation
258    * @exception MathRuntimeException if the norm of one of the vectors is zero,
259    * or if one of the pair is degenerated (i.e. the vectors of the pair are collinear)
260    */
261   public Rotation(Vector3D u1, Vector3D u2, Vector3D v1, Vector3D v2)
262       throws MathRuntimeException {
263 
264       // build orthonormalized base from u1, u2
265       // this fails when vectors are null or collinear, which is forbidden to define a rotation
266       final Vector3D u3 = u1.crossProduct(u2).normalize();
267       u2 = u3.crossProduct(u1).normalize();
268       u1 = u1.normalize();
269 
270       // build an orthonormalized base from v1, v2
271       // this fails when vectors are null or collinear, which is forbidden to define a rotation
272       final Vector3D v3 = v1.crossProduct(v2).normalize();
273       v2 = v3.crossProduct(v1).normalize();
274       v1 = v1.normalize();
275 
276       // buid a matrix transforming the first base into the second one
277       final double[][] m = {
278           {
279               MathArrays.linearCombination(u1.getX(), v1.getX(), u2.getX(), v2.getX(), u3.getX(), v3.getX()),
280               MathArrays.linearCombination(u1.getY(), v1.getX(), u2.getY(), v2.getX(), u3.getY(), v3.getX()),
281               MathArrays.linearCombination(u1.getZ(), v1.getX(), u2.getZ(), v2.getX(), u3.getZ(), v3.getX())
282           },
283           {
284               MathArrays.linearCombination(u1.getX(), v1.getY(), u2.getX(), v2.getY(), u3.getX(), v3.getY()),
285               MathArrays.linearCombination(u1.getY(), v1.getY(), u2.getY(), v2.getY(), u3.getY(), v3.getY()),
286               MathArrays.linearCombination(u1.getZ(), v1.getY(), u2.getZ(), v2.getY(), u3.getZ(), v3.getY())
287           },
288           {
289               MathArrays.linearCombination(u1.getX(), v1.getZ(), u2.getX(), v2.getZ(), u3.getX(), v3.getZ()),
290               MathArrays.linearCombination(u1.getY(), v1.getZ(), u2.getY(), v2.getZ(), u3.getY(), v3.getZ()),
291               MathArrays.linearCombination(u1.getZ(), v1.getZ(), u2.getZ(), v2.getZ(), u3.getZ(), v3.getZ())
292           }
293       };
294 
295       double[] quat = mat2quat(m);
296       q0 = quat[0];
297       q1 = quat[1];
298       q2 = quat[2];
299       q3 = quat[3];
300 
301   }
302 
303   /** Build one of the rotations that transform one vector into another one.
304 
305    * <p>Except for a possible scale factor, if the instance were
306    * applied to the vector u it will produce the vector v. There is an
307    * infinite number of such rotations, this constructor choose the
308    * one with the smallest associated angle (i.e. the one whose axis
309    * is orthogonal to the (u, v) plane). If u and v are collinear, an
310    * arbitrary rotation axis is chosen.</p>
311 
312    * @param u origin vector
313    * @param v desired image of u by the rotation
314    * @exception MathRuntimeException if the norm of one of the vectors is zero
315    */
316   public Rotation(Vector3D u, Vector3D v) throws MathRuntimeException {
317 
318     double normProduct = u.getNorm() * v.getNorm();
319     if (normProduct == 0) {
320         throw new MathRuntimeException(LocalizedGeometryFormats.ZERO_NORM_FOR_ROTATION_DEFINING_VECTOR);
321     }
322 
323     double dot = u.dotProduct(v);
324 
325     if (dot < ((2.0e-15 - 1.0) * normProduct)) {
326       // special case u = -v: we select a PI angle rotation around
327       // an arbitrary vector orthogonal to u
328       Vector3D w = u.orthogonal();
329       q0 = 0.0;
330       q1 = -w.getX();
331       q2 = -w.getY();
332       q3 = -w.getZ();
333     } else {
334       // general case: (u, v) defines a plane, we select
335       // the shortest possible rotation: axis orthogonal to this plane
336       q0 = FastMath.sqrt(0.5 * (1.0 + dot / normProduct));
337       double coeff = 1.0 / (2.0 * q0 * normProduct);
338       Vector3D q = v.crossProduct(u);
339       q1 = coeff * q.getX();
340       q2 = coeff * q.getY();
341       q3 = coeff * q.getZ();
342     }
343 
344   }
345 
346   /** Build a rotation from three Cardan or Euler elementary rotations.
347 
348    * <p>Cardan rotations are three successive rotations around the
349    * canonical axes X, Y and Z, each axis being used once. There are
350    * 6 such sets of rotations (XYZ, XZY, YXZ, YZX, ZXY and ZYX). Euler
351    * rotations are three successive rotations around the canonical
352    * axes X, Y and Z, the first and last rotations being around the
353    * same axis. There are 6 such sets of rotations (XYX, XZX, YXY,
354    * YZY, ZXZ and ZYZ), the most popular one being ZXZ.</p>
355    * <p>Beware that many people routinely use the term Euler angles even
356    * for what really are Cardan angles (this confusion is especially
357    * widespread in the aerospace business where Roll, Pitch and Yaw angles
358    * are often wrongly tagged as Euler angles).</p>
359 
360    * @param order order of rotations to compose, from left to right
361    * (i.e. we will use {@code r1.compose(r2.compose(r3, convention), convention)})
362    * @param convention convention to use for the semantics of the angle
363    * @param alpha1 angle of the first elementary rotation
364    * @param alpha2 angle of the second elementary rotation
365    * @param alpha3 angle of the third elementary rotation
366    */
367   public Rotation(RotationOrder order, RotationConvention convention,
368                   double alpha1, double alpha2, double alpha3) {
369       Rotation r1 = new Rotation(order.getA1(), alpha1, convention);
370       Rotation r2 = new Rotation(order.getA2(), alpha2, convention);
371       Rotation r3 = new Rotation(order.getA3(), alpha3, convention);
372       Rotation composed = r1.compose(r2.compose(r3, convention), convention);
373       q0 = composed.q0;
374       q1 = composed.q1;
375       q2 = composed.q2;
376       q3 = composed.q3;
377   }
378 
379   /** Convert an orthogonal rotation matrix to a quaternion.
380    * @param ort orthogonal rotation matrix
381    * @return quaternion corresponding to the matrix
382    */
383   private static double[] mat2quat(final double[][] ort) {
384 
385       final double[] quat = new double[4];
386 
387       // There are different ways to compute the quaternions elements
388       // from the matrix. They all involve computing one element from
389       // the diagonal of the matrix, and computing the three other ones
390       // using a formula involving a division by the first element,
391       // which unfortunately can be zero. Since the norm of the
392       // quaternion is 1, we know at least one element has an absolute
393       // value greater or equal to 0.5, so it is always possible to
394       // select the right formula and avoid division by zero and even
395       // numerical inaccuracy. Checking the elements in turn and using
396       // the first one greater than 0.45 is safe (this leads to a simple
397       // test since qi = 0.45 implies 4 qi^2 - 1 = -0.19)
398       double s = ort[0][0] + ort[1][1] + ort[2][2];
399       if (s > -0.19) {
400           // compute q0 and deduce q1, q2 and q3
401           quat[0] = 0.5 * FastMath.sqrt(s + 1.0);
402           double inv = 0.25 / quat[0];
403           quat[1] = inv * (ort[1][2] - ort[2][1]);
404           quat[2] = inv * (ort[2][0] - ort[0][2]);
405           quat[3] = inv * (ort[0][1] - ort[1][0]);
406       } else {
407           s = ort[0][0] - ort[1][1] - ort[2][2];
408           if (s > -0.19) {
409               // compute q1 and deduce q0, q2 and q3
410               quat[1] = 0.5 * FastMath.sqrt(s + 1.0);
411               double inv = 0.25 / quat[1];
412               quat[0] = inv * (ort[1][2] - ort[2][1]);
413               quat[2] = inv * (ort[0][1] + ort[1][0]);
414               quat[3] = inv * (ort[0][2] + ort[2][0]);
415           } else {
416               s = ort[1][1] - ort[0][0] - ort[2][2];
417               if (s > -0.19) {
418                   // compute q2 and deduce q0, q1 and q3
419                   quat[2] = 0.5 * FastMath.sqrt(s + 1.0);
420                   double inv = 0.25 / quat[2];
421                   quat[0] = inv * (ort[2][0] - ort[0][2]);
422                   quat[1] = inv * (ort[0][1] + ort[1][0]);
423                   quat[3] = inv * (ort[2][1] + ort[1][2]);
424               } else {
425                   // compute q3 and deduce q0, q1 and q2
426                   s = ort[2][2] - ort[0][0] - ort[1][1];
427                   quat[3] = 0.5 * FastMath.sqrt(s + 1.0);
428                   double inv = 0.25 / quat[3];
429                   quat[0] = inv * (ort[0][1] - ort[1][0]);
430                   quat[1] = inv * (ort[0][2] + ort[2][0]);
431                   quat[2] = inv * (ort[2][1] + ort[1][2]);
432               }
433           }
434       }
435 
436       return quat;
437 
438   }
439 
440   /** Revert a rotation.
441    * Build a rotation which reverse the effect of another
442    * rotation. This means that if r(u) = v, then r.revert(v) = u. The
443    * instance is not changed.
444    * @return a new rotation whose effect is the reverse of the effect
445    * of the instance
446    */
447   public Rotation revert() {
448     return new Rotation(-q0, q1, q2, q3, false);
449   }
450 
451   /** Get the scalar coordinate of the quaternion.
452    * @return scalar coordinate of the quaternion
453    */
454   public double getQ0() {
455     return q0;
456   }
457 
458   /** Get the first coordinate of the vectorial part of the quaternion.
459    * @return first coordinate of the vectorial part of the quaternion
460    */
461   public double getQ1() {
462     return q1;
463   }
464 
465   /** Get the second coordinate of the vectorial part of the quaternion.
466    * @return second coordinate of the vectorial part of the quaternion
467    */
468   public double getQ2() {
469     return q2;
470   }
471 
472   /** Get the third coordinate of the vectorial part of the quaternion.
473    * @return third coordinate of the vectorial part of the quaternion
474    */
475   public double getQ3() {
476     return q3;
477   }
478 
479   /** Get the normalized axis of the rotation.
480    * <p>
481    * Note that as {@link #getAngle()} always returns an angle
482    * between 0 and &pi;, changing the convention changes the
483    * direction of the axis, not the sign of the angle.
484    * </p>
485    * @param convention convention to use for the semantics of the angle
486    * @return normalized axis of the rotation
487    * @see #Rotation(Vector3D, double, RotationConvention)
488    */
489   public Vector3D getAxis(final RotationConvention convention) {
490     final double squaredSine = q1 * q1 + q2 * q2 + q3 * q3;
491     if (squaredSine == 0) {
492       return convention == RotationConvention.VECTOR_OPERATOR ? Vector3D.PLUS_I : Vector3D.MINUS_I;
493     } else {
494         final double sgn = convention == RotationConvention.VECTOR_OPERATOR ? +1 : -1;
495         if (q0 < 0) {
496             final double inverse = sgn / FastMath.sqrt(squaredSine);
497             return new Vector3D(q1 * inverse, q2 * inverse, q3 * inverse);
498         }
499         final double inverse = -sgn / FastMath.sqrt(squaredSine);
500         return new Vector3D(q1 * inverse, q2 * inverse, q3 * inverse);
501     }
502   }
503 
504   /** Get the angle of the rotation.
505    * @return angle of the rotation (between 0 and &pi;)
506    * @see #Rotation(Vector3D, double, RotationConvention)
507    */
508   public double getAngle() {
509     if ((q0 < -0.1) || (q0 > 0.1)) {
510       return 2 * FastMath.asin(FastMath.sqrt(q1 * q1 + q2 * q2 + q3 * q3));
511     } else if (q0 < 0) {
512       return 2 * FastMath.acos(-q0);
513     }
514     return 2 * FastMath.acos(q0);
515   }
516 
517   /** Get the Cardan or Euler angles corresponding to the instance.
518 
519    * <p>The equations show that each rotation can be defined by two
520    * different values of the Cardan or Euler angles set. For example
521    * if Cardan angles are used, the rotation defined by the angles
522    * a<sub>1</sub>, a<sub>2</sub> and a<sub>3</sub> is the same as
523    * the rotation defined by the angles &pi; + a<sub>1</sub>, &pi;
524    * - a<sub>2</sub> and &pi; + a<sub>3</sub>. This method implements
525    * the following arbitrary choices:</p>
526    * <ul>
527    *   <li>for Cardan angles, the chosen set is the one for which the
528    *   second angle is between -&pi;/2 and &pi;/2 (i.e its cosine is
529    *   positive),</li>
530    *   <li>for Euler angles, the chosen set is the one for which the
531    *   second angle is between 0 and &pi; (i.e its sine is positive).</li>
532    * </ul>
533 
534    * <p>Cardan and Euler angle have a very disappointing drawback: all
535    * of them have singularities. This means that if the instance is
536    * too close to the singularities corresponding to the given
537    * rotation order, it will be impossible to retrieve the angles. For
538    * Cardan angles, this is often called gimbal lock. There is
539    * <em>nothing</em> to do to prevent this, it is an intrinsic problem
540    * with Cardan and Euler representation (but not a problem with the
541    * rotation itself, which is perfectly well defined). For Cardan
542    * angles, singularities occur when the second angle is close to
543    * -&pi;/2 or +&pi;/2, for Euler angle singularities occur when the
544    * second angle is close to 0 or &pi;, this implies that the identity
545    * rotation is always singular for Euler angles!</p>
546 
547    * @param order rotation order to use
548    * @param convention convention to use for the semantics of the angle
549    * @return an array of three angles, in the order specified by the set
550    */
551   public double[] getAngles(RotationOrder order, RotationConvention convention) {
552       return order.getAngles(this, convention);
553   }
554 
555   /** Get the 3X3 matrix corresponding to the instance
556    * @return the matrix corresponding to the instance
557    */
558   public double[][] getMatrix() {
559 
560     // products
561     double q0q0  = q0 * q0;
562     double q0q1  = q0 * q1;
563     double q0q2  = q0 * q2;
564     double q0q3  = q0 * q3;
565     double q1q1  = q1 * q1;
566     double q1q2  = q1 * q2;
567     double q1q3  = q1 * q3;
568     double q2q2  = q2 * q2;
569     double q2q3  = q2 * q3;
570     double q3q3  = q3 * q3;
571 
572     // create the matrix
573     double[][] m = new double[3][];
574     m[0] = new double[3];
575     m[1] = new double[3];
576     m[2] = new double[3];
577 
578     m [0][0] = 2.0 * (q0q0 + q1q1) - 1.0;
579     m [1][0] = 2.0 * (q1q2 - q0q3);
580     m [2][0] = 2.0 * (q1q3 + q0q2);
581 
582     m [0][1] = 2.0 * (q1q2 + q0q3);
583     m [1][1] = 2.0 * (q0q0 + q2q2) - 1.0;
584     m [2][1] = 2.0 * (q2q3 - q0q1);
585 
586     m [0][2] = 2.0 * (q1q3 - q0q2);
587     m [1][2] = 2.0 * (q2q3 + q0q1);
588     m [2][2] = 2.0 * (q0q0 + q3q3) - 1.0;
589 
590     return m;
591 
592   }
593 
594   /** Apply the rotation to a vector.
595    * @param u vector to apply the rotation to
596    * @return a new vector which is the image of u by the rotation
597    */
598   public Vector3D applyTo(Vector3D u) {
599 
600     double x = u.getX();
601     double y = u.getY();
602     double z = u.getZ();
603 
604     double s = q1 * x + q2 * y + q3 * z;
605 
606     return new Vector3D(2 * (q0 * (x * q0 - (q2 * z - q3 * y)) + s * q1) - x,
607                         2 * (q0 * (y * q0 - (q3 * x - q1 * z)) + s * q2) - y,
608                         2 * (q0 * (z * q0 - (q1 * y - q2 * x)) + s * q3) - z);
609 
610   }
611 
612   /** Apply the rotation to a vector stored in an array.
613    * @param in an array with three items which stores vector to rotate
614    * @param out an array with three items to put result to (it can be the same
615    * array as in)
616    */
617   public void applyTo(final double[] in, final double[] out) {
618 
619       final double x = in[0];
620       final double y = in[1];
621       final double z = in[2];
622 
623       final double s = q1 * x + q2 * y + q3 * z;
624 
625       out[0] = 2 * (q0 * (x * q0 - (q2 * z - q3 * y)) + s * q1) - x;
626       out[1] = 2 * (q0 * (y * q0 - (q3 * x - q1 * z)) + s * q2) - y;
627       out[2] = 2 * (q0 * (z * q0 - (q1 * y - q2 * x)) + s * q3) - z;
628 
629   }
630 
631   /** Apply the inverse of the rotation to a vector.
632    * @param u vector to apply the inverse of the rotation to
633    * @return a new vector which such that u is its image by the rotation
634    */
635   public Vector3D applyInverseTo(Vector3D u) {
636 
637     double x = u.getX();
638     double y = u.getY();
639     double z = u.getZ();
640 
641     double s = q1 * x + q2 * y + q3 * z;
642     double m0 = -q0;
643 
644     return new Vector3D(2 * (m0 * (x * m0 - (q2 * z - q3 * y)) + s * q1) - x,
645                         2 * (m0 * (y * m0 - (q3 * x - q1 * z)) + s * q2) - y,
646                         2 * (m0 * (z * m0 - (q1 * y - q2 * x)) + s * q3) - z);
647 
648   }
649 
650   /** Apply the inverse of the rotation to a vector stored in an array.
651    * @param in an array with three items which stores vector to rotate
652    * @param out an array with three items to put result to (it can be the same
653    * array as in)
654    */
655   public void applyInverseTo(final double[] in, final double[] out) {
656 
657       final double x = in[0];
658       final double y = in[1];
659       final double z = in[2];
660 
661       final double s = q1 * x + q2 * y + q3 * z;
662       final double m0 = -q0;
663 
664       out[0] = 2 * (m0 * (x * m0 - (q2 * z - q3 * y)) + s * q1) - x;
665       out[1] = 2 * (m0 * (y * m0 - (q3 * x - q1 * z)) + s * q2) - y;
666       out[2] = 2 * (m0 * (z * m0 - (q1 * y - q2 * x)) + s * q3) - z;
667 
668   }
669 
670   /** Apply the instance to another rotation.
671    * <p>
672    * Calling this method is equivalent to call
673    * {@link #compose(Rotation, RotationConvention)
674    * compose(r, RotationConvention.VECTOR_OPERATOR)}.
675    * </p>
676    * @param r rotation to apply the rotation to
677    * @return a new rotation which is the composition of r by the instance
678    */
679   public Rotation applyTo(Rotation r) {
680     return compose(r, RotationConvention.VECTOR_OPERATOR);
681   }
682 
683   /** Compose the instance with another rotation.
684    * <p>
685    * If the semantics of the rotations composition corresponds to a
686    * {@link RotationConvention#VECTOR_OPERATOR vector operator} convention,
687    * applying the instance to a rotation is computing the composition
688    * in an order compliant with the following rule : let {@code u} be any
689    * vector and {@code v} its image by {@code r1} (i.e.
690    * {@code r1.applyTo(u) = v}). Let {@code w} be the image of {@code v} by
691    * rotation {@code r2} (i.e. {@code r2.applyTo(v) = w}). Then
692    * {@code w = comp.applyTo(u)}, where
693    * {@code comp = r2.compose(r1, RotationConvention.VECTOR_OPERATOR)}.
694    * </p>
695    * <p>
696    * If the semantics of the rotations composition corresponds to a
697    * {@link RotationConvention#FRAME_TRANSFORM frame transform} convention,
698    * the application order will be reversed. So keeping the exact same
699    * meaning of all {@code r1}, {@code r2}, {@code u}, {@code v}, {@code w}
700    * and  {@code comp} as above, {@code comp} could also be computed as
701    * {@code comp = r1.compose(r2, RotationConvention.FRAME_TRANSFORM)}.
702    * </p>
703    * @param r rotation to apply the rotation to
704    * @param convention convention to use for the semantics of the angle
705    * @return a new rotation which is the composition of r by the instance
706    */
707   public Rotation compose(final Rotation r, final RotationConvention convention) {
708     return convention == RotationConvention.VECTOR_OPERATOR ?
709            composeInternal(r) : r.composeInternal(this);
710   }
711 
712   /** Compose the instance with another rotation using vector operator convention.
713    * @param r rotation to apply the rotation to
714    * @return a new rotation which is the composition of r by the instance
715    * using vector operator convention
716    */
717   private Rotation composeInternal(final Rotation r) {
718     return new Rotation(r.q0 * q0 - (r.q1 * q1 + r.q2 * q2 + r.q3 * q3),
719                         r.q1 * q0 + r.q0 * q1 + (r.q2 * q3 - r.q3 * q2),
720                         r.q2 * q0 + r.q0 * q2 + (r.q3 * q1 - r.q1 * q3),
721                         r.q3 * q0 + r.q0 * q3 + (r.q1 * q2 - r.q2 * q1),
722                         false);
723   }
724 
725   /** Apply the inverse of the instance to another rotation.
726    * <p>
727    * Calling this method is equivalent to call
728    * {@link #composeInverse(Rotation, RotationConvention)
729    * composeInverse(r, RotationConvention.VECTOR_OPERATOR)}.
730    * </p>
731    * @param r rotation to apply the rotation to
732    * @return a new rotation which is the composition of r by the inverse
733    * of the instance
734    */
735   public Rotation applyInverseTo(Rotation r) {
736     return composeInverse(r, RotationConvention.VECTOR_OPERATOR);
737   }
738 
739   /** Compose the inverse of the instance with another rotation.
740    * <p>
741    * If the semantics of the rotations composition corresponds to a
742    * {@link RotationConvention#VECTOR_OPERATOR vector operator} convention,
743    * applying the inverse of the instance to a rotation is computing
744    * the composition in an order compliant with the following rule :
745    * let {@code u} be any vector and {@code v} its image by {@code r1}
746    * (i.e. {@code r1.applyTo(u) = v}). Let {@code w} be the inverse image
747    * of {@code v} by {@code r2} (i.e. {@code r2.applyInverseTo(v) = w}).
748    * Then {@code w = comp.applyTo(u)}, where
749    * {@code comp = r2.composeInverse(r1)}.
750    * </p>
751    * <p>
752    * If the semantics of the rotations composition corresponds to a
753    * {@link RotationConvention#FRAME_TRANSFORM frame transform} convention,
754    * the application order will be reversed, which means it is the
755    * <em>innermost</em> rotation that will be reversed. So keeping the exact same
756    * meaning of all {@code r1}, {@code r2}, {@code u}, {@code v}, {@code w}
757    * and  {@code comp} as above, {@code comp} could also be computed as
758    * {@code comp = r1.revert().composeInverse(r2.revert(), RotationConvention.FRAME_TRANSFORM)}.
759    * </p>
760    * @param r rotation to apply the rotation to
761    * @param convention convention to use for the semantics of the angle
762    * @return a new rotation which is the composition of r by the inverse
763    * of the instance
764    */
765   public Rotation composeInverse(final Rotation r, final RotationConvention convention) {
766     return convention == RotationConvention.VECTOR_OPERATOR ?
767            composeInverseInternal(r) : r.composeInternal(revert());
768   }
769 
770   /** Compose the inverse of the instance with another rotation
771    * using vector operator convention.
772    * @param r rotation to apply the rotation to
773    * @return a new rotation which is the composition of r by the inverse
774    * of the instance using vector operator convention
775    */
776   private Rotation composeInverseInternal(Rotation r) {
777     return new Rotation(-r.q0 * q0 - (r.q1 * q1 + r.q2 * q2 + r.q3 * q3),
778                         -r.q1 * q0 + r.q0 * q1 + (r.q2 * q3 - r.q3 * q2),
779                         -r.q2 * q0 + r.q0 * q2 + (r.q3 * q1 - r.q1 * q3),
780                         -r.q3 * q0 + r.q0 * q3 + (r.q1 * q2 - r.q2 * q1),
781                         false);
782   }
783 
784   /** Perfect orthogonality on a 3X3 matrix.
785    * @param m initial matrix (not exactly orthogonal)
786    * @param threshold convergence threshold for the iterative
787    * orthogonality correction (convergence is reached when the
788    * difference between two steps of the Frobenius norm of the
789    * correction is below this threshold)
790    * @return an orthogonal matrix close to m
791    * @exception MathIllegalArgumentException if the matrix cannot be
792    * orthogonalized with the given threshold after 10 iterations
793    */
794   private double[][] orthogonalizeMatrix(double[][] m, double threshold)
795     throws MathIllegalArgumentException {
796     double[] m0 = m[0];
797     double[] m1 = m[1];
798     double[] m2 = m[2];
799     double x00 = m0[0];
800     double x01 = m0[1];
801     double x02 = m0[2];
802     double x10 = m1[0];
803     double x11 = m1[1];
804     double x12 = m1[2];
805     double x20 = m2[0];
806     double x21 = m2[1];
807     double x22 = m2[2];
808     double fn = 0;
809     double fn1;
810 
811     double[][] o = new double[3][3];
812     double[] o0 = o[0];
813     double[] o1 = o[1];
814     double[] o2 = o[2];
815 
816     // iterative correction: Xn+1 = Xn - 0.5 * (Xn.Mt.Xn - M)
817     int i;
818     for (i = 0; i < 11; ++i) {
819 
820       // Mt.Xn
821       double mx00 = m0[0] * x00 + m1[0] * x10 + m2[0] * x20;
822       double mx10 = m0[1] * x00 + m1[1] * x10 + m2[1] * x20;
823       double mx20 = m0[2] * x00 + m1[2] * x10 + m2[2] * x20;
824       double mx01 = m0[0] * x01 + m1[0] * x11 + m2[0] * x21;
825       double mx11 = m0[1] * x01 + m1[1] * x11 + m2[1] * x21;
826       double mx21 = m0[2] * x01 + m1[2] * x11 + m2[2] * x21;
827       double mx02 = m0[0] * x02 + m1[0] * x12 + m2[0] * x22;
828       double mx12 = m0[1] * x02 + m1[1] * x12 + m2[1] * x22;
829       double mx22 = m0[2] * x02 + m1[2] * x12 + m2[2] * x22;
830 
831       // Xn+1
832       o0[0] = x00 - 0.5 * (x00 * mx00 + x01 * mx10 + x02 * mx20 - m0[0]);
833       o0[1] = x01 - 0.5 * (x00 * mx01 + x01 * mx11 + x02 * mx21 - m0[1]);
834       o0[2] = x02 - 0.5 * (x00 * mx02 + x01 * mx12 + x02 * mx22 - m0[2]);
835       o1[0] = x10 - 0.5 * (x10 * mx00 + x11 * mx10 + x12 * mx20 - m1[0]);
836       o1[1] = x11 - 0.5 * (x10 * mx01 + x11 * mx11 + x12 * mx21 - m1[1]);
837       o1[2] = x12 - 0.5 * (x10 * mx02 + x11 * mx12 + x12 * mx22 - m1[2]);
838       o2[0] = x20 - 0.5 * (x20 * mx00 + x21 * mx10 + x22 * mx20 - m2[0]);
839       o2[1] = x21 - 0.5 * (x20 * mx01 + x21 * mx11 + x22 * mx21 - m2[1]);
840       o2[2] = x22 - 0.5 * (x20 * mx02 + x21 * mx12 + x22 * mx22 - m2[2]);
841 
842       // correction on each elements
843       double corr00 = o0[0] - m0[0];
844       double corr01 = o0[1] - m0[1];
845       double corr02 = o0[2] - m0[2];
846       double corr10 = o1[0] - m1[0];
847       double corr11 = o1[1] - m1[1];
848       double corr12 = o1[2] - m1[2];
849       double corr20 = o2[0] - m2[0];
850       double corr21 = o2[1] - m2[1];
851       double corr22 = o2[2] - m2[2];
852 
853       // Frobenius norm of the correction
854       fn1 = corr00 * corr00 + corr01 * corr01 + corr02 * corr02 +
855             corr10 * corr10 + corr11 * corr11 + corr12 * corr12 +
856             corr20 * corr20 + corr21 * corr21 + corr22 * corr22;
857 
858       // convergence test
859       if (FastMath.abs(fn1 - fn) <= threshold) {
860           return o;
861       }
862 
863       // prepare next iteration
864       x00 = o0[0];
865       x01 = o0[1];
866       x02 = o0[2];
867       x10 = o1[0];
868       x11 = o1[1];
869       x12 = o1[2];
870       x20 = o2[0];
871       x21 = o2[1];
872       x22 = o2[2];
873       fn  = fn1;
874 
875     }
876 
877     // the algorithm did not converge after 10 iterations
878     throw new MathIllegalArgumentException(LocalizedGeometryFormats.UNABLE_TO_ORTHOGONOLIZE_MATRIX,
879                                            i - 1);
880   }
881 
882   /** Compute the <i>distance</i> between two rotations.
883    * <p>The <i>distance</i> is intended here as a way to check if two
884    * rotations are almost similar (i.e. they transform vectors the same way)
885    * or very different. It is mathematically defined as the angle of
886    * the rotation r that prepended to one of the rotations gives the other
887    * one: \(r_1(r) = r_2\)
888    * </p>
889    * <p>This distance is an angle between 0 and &pi;. Its value is the smallest
890    * possible upper bound of the angle in radians between r<sub>1</sub>(v)
891    * and r<sub>2</sub>(v) for all possible vectors v. This upper bound is
892    * reached for some v. The distance is equal to 0 if and only if the two
893    * rotations are identical.</p>
894    * <p>Comparing two rotations should always be done using this value rather
895    * than for example comparing the components of the quaternions. It is much
896    * more stable, and has a geometric meaning. Also comparing quaternions
897    * components is error prone since for example quaternions (0.36, 0.48, -0.48, -0.64)
898    * and (-0.36, -0.48, 0.48, 0.64) represent exactly the same rotation despite
899    * their components are different (they are exact opposites).</p>
900    * @param r1 first rotation
901    * @param r2 second rotation
902    * @return <i>distance</i> between r1 and r2
903    */
904   public static double distance(Rotation r1, Rotation r2) {
905       return r1.composeInverseInternal(r2).getAngle();
906   }
907 
908 }