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