001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017
018package org.apache.commons.math3.geometry.euclidean.threed;
019
020import java.io.Serializable;
021
022import org.apache.commons.math3.exception.MathArithmeticException;
023import org.apache.commons.math3.exception.MathIllegalArgumentException;
024import org.apache.commons.math3.exception.util.LocalizedFormats;
025import org.apache.commons.math3.util.FastMath;
026import org.apache.commons.math3.util.MathArrays;
027
028/**
029 * This class implements rotations in a three-dimensional space.
030 *
031 * <p>Rotations can be represented by several different mathematical
032 * entities (matrices, axe and angle, Cardan or Euler angles,
033 * quaternions). This class presents an higher level abstraction, more
034 * user-oriented and hiding this implementation details. Well, for the
035 * curious, we use quaternions for the internal representation. The
036 * user can build a rotation from any of these representations, and
037 * any of these representations can be retrieved from a
038 * <code>Rotation</code> instance (see the various constructors and
039 * getters). In addition, a rotation can also be built implicitly
040 * from a set of vectors and their image.</p>
041 * <p>This implies that this class can be used to convert from one
042 * representation to another one. For example, converting a rotation
043 * matrix into a set of Cardan angles from can be done using the
044 * following single line of code:</p>
045 * <pre>
046 * double[] angles = new Rotation(matrix, 1.0e-10).getAngles(RotationOrder.XYZ);
047 * </pre>
048 * <p>Focus is oriented on what a rotation <em>do</em> rather than on its
049 * underlying representation. Once it has been built, and regardless of its
050 * internal representation, a rotation is an <em>operator</em> which basically
051 * transforms three dimensional {@link Vector3D vectors} into other three
052 * dimensional {@link Vector3D vectors}. Depending on the application, the
053 * meaning of these vectors may vary and the semantics of the rotation also.</p>
054 * <p>For example in an spacecraft attitude simulation tool, users will often
055 * consider the vectors are fixed (say the Earth direction for example) and the
056 * frames change. The rotation transforms the coordinates of the vector in inertial
057 * frame into the coordinates of the same vector in satellite frame. In this
058 * case, the rotation implicitly defines the relation between the two frames.</p>
059 * <p>Another example could be a telescope control application, where the rotation
060 * would transform the sighting direction at rest into the desired observing
061 * direction when the telescope is pointed towards an object of interest. In this
062 * case the rotation transforms the direction at rest in a topocentric frame
063 * into the sighting direction in the same topocentric frame. This implies in this
064 * case the frame is fixed and the vector moves.</p>
065 * <p>In many case, both approaches will be combined. In our telescope example,
066 * we will probably also need to transform the observing direction in the topocentric
067 * frame into the observing direction in inertial frame taking into account the observatory
068 * location and the Earth rotation, which would essentially be an application of the
069 * first approach.</p>
070 *
071 * <p>These examples show that a rotation is what the user wants it to be. This
072 * class does not push the user towards one specific definition and hence does not
073 * provide methods like <code>projectVectorIntoDestinationFrame</code> or
074 * <code>computeTransformedDirection</code>. It provides simpler and more generic
075 * methods: {@link #applyTo(Vector3D) applyTo(Vector3D)} and {@link
076 * #applyInverseTo(Vector3D) applyInverseTo(Vector3D)}.</p>
077 *
078 * <p>Since a rotation is basically a vectorial operator, several rotations can be
079 * composed together and the composite operation <code>r = r<sub>1</sub> o
080 * r<sub>2</sub></code> (which means that for each vector <code>u</code>,
081 * <code>r(u) = r<sub>1</sub>(r<sub>2</sub>(u))</code>) is also a rotation. Hence
082 * we can consider that in addition to vectors, a rotation can be applied to other
083 * rotations as well (or to itself). With our previous notations, we would say we
084 * can apply <code>r<sub>1</sub></code> to <code>r<sub>2</sub></code> and the result
085 * we get is <code>r = r<sub>1</sub> o r<sub>2</sub></code>. For this purpose, the
086 * class provides the methods: {@link #applyTo(Rotation) applyTo(Rotation)} and
087 * {@link #applyInverseTo(Rotation) applyInverseTo(Rotation)}.</p>
088 *
089 * <p>Rotations are guaranteed to be immutable objects.</p>
090 *
091 * @see Vector3D
092 * @see RotationOrder
093 * @since 1.2
094 */
095
096public class Rotation implements Serializable {
097
098  /** Identity rotation. */
099  public static final Rotation IDENTITY = new Rotation(1.0, 0.0, 0.0, 0.0, false);
100
101  /** Serializable version identifier */
102  private static final long serialVersionUID = -2153622329907944313L;
103
104  /** Scalar coordinate of the quaternion. */
105  private final double q0;
106
107  /** First coordinate of the vectorial part of the quaternion. */
108  private final double q1;
109
110  /** Second coordinate of the vectorial part of the quaternion. */
111  private final double q2;
112
113  /** Third coordinate of the vectorial part of the quaternion. */
114  private final double q3;
115
116  /** Build a rotation from the quaternion coordinates.
117   * <p>A rotation can be built from a <em>normalized</em> quaternion,
118   * i.e. a quaternion for which q<sub>0</sub><sup>2</sup> +
119   * q<sub>1</sub><sup>2</sup> + q<sub>2</sub><sup>2</sup> +
120   * q<sub>3</sub><sup>2</sup> = 1. If the quaternion is not normalized,
121   * the constructor can normalize it in a preprocessing step.</p>
122   * <p>Note that some conventions put the scalar part of the quaternion
123   * as the 4<sup>th</sup> component and the vector part as the first three
124   * components. This is <em>not</em> our convention. We put the scalar part
125   * as the first component.</p>
126   * @param q0 scalar part of the quaternion
127   * @param q1 first coordinate of the vectorial part of the quaternion
128   * @param q2 second coordinate of the vectorial part of the quaternion
129   * @param q3 third coordinate of the vectorial part of the quaternion
130   * @param needsNormalization if true, the coordinates are considered
131   * not to be normalized, a normalization preprocessing step is performed
132   * before using them
133   */
134  public Rotation(double q0, double q1, double q2, double q3,
135                  boolean needsNormalization) {
136
137    if (needsNormalization) {
138      // normalization preprocessing
139      double inv = 1.0 / FastMath.sqrt(q0 * q0 + q1 * q1 + q2 * q2 + q3 * q3);
140      q0 *= inv;
141      q1 *= inv;
142      q2 *= inv;
143      q3 *= inv;
144    }
145
146    this.q0 = q0;
147    this.q1 = q1;
148    this.q2 = q2;
149    this.q3 = q3;
150
151  }
152
153  /** Build a rotation from an axis and an angle.
154   * <p>We use the convention that angles are oriented according to
155   * the effect of the rotation on vectors around the axis. That means
156   * that if (i, j, k) is a direct frame and if we first provide +k as
157   * the axis and &pi;/2 as the angle to this constructor, and then
158   * {@link #applyTo(Vector3D) apply} the instance to +i, we will get
159   * +j.</p>
160   * <p>Another way to represent our convention is to say that a rotation
161   * of angle &theta; about the unit vector (x, y, z) is the same as the
162   * rotation build from quaternion components { cos(-&theta;/2),
163   * x * sin(-&theta;/2), y * sin(-&theta;/2), z * sin(-&theta;/2) }.
164   * Note the minus sign on the angle!</p>
165   * <p>On the one hand this convention is consistent with a vectorial
166   * perspective (moving vectors in fixed frames), on the other hand it
167   * is different from conventions with a frame perspective (fixed vectors
168   * viewed from different frames) like the ones used for example in spacecraft
169   * attitude community or in the graphics community.</p>
170   * @param axis axis around which to rotate
171   * @param angle rotation angle.
172   * @exception MathIllegalArgumentException if the axis norm is zero
173   */
174  public Rotation(Vector3D axis, double angle) throws MathIllegalArgumentException {
175
176    double norm = axis.getNorm();
177    if (norm == 0) {
178      throw new MathIllegalArgumentException(LocalizedFormats.ZERO_NORM_FOR_ROTATION_AXIS);
179    }
180
181    double halfAngle = -0.5 * angle;
182    double coeff = FastMath.sin(halfAngle) / norm;
183
184    q0 = FastMath.cos (halfAngle);
185    q1 = coeff * axis.getX();
186    q2 = coeff * axis.getY();
187    q3 = coeff * axis.getZ();
188
189  }
190
191  /** Build a rotation from a 3X3 matrix.
192
193   * <p>Rotation matrices are orthogonal matrices, i.e. unit matrices
194   * (which are matrices for which m.m<sup>T</sup> = I) with real
195   * coefficients. The module of the determinant of unit matrices is
196   * 1, among the orthogonal 3X3 matrices, only the ones having a
197   * positive determinant (+1) are rotation matrices.</p>
198
199   * <p>When a rotation is defined by a matrix with truncated values
200   * (typically when it is extracted from a technical sheet where only
201   * four to five significant digits are available), the matrix is not
202   * orthogonal anymore. This constructor handles this case
203   * transparently by using a copy of the given matrix and applying a
204   * correction to the copy in order to perfect its orthogonality. If
205   * the Frobenius norm of the correction needed is above the given
206   * threshold, then the matrix is considered to be too far from a
207   * true rotation matrix and an exception is thrown.<p>
208
209   * @param m rotation matrix
210   * @param threshold convergence threshold for the iterative
211   * orthogonality correction (convergence is reached when the
212   * difference between two steps of the Frobenius norm of the
213   * correction is below this threshold)
214
215   * @exception NotARotationMatrixException if the matrix is not a 3X3
216   * matrix, or if it cannot be transformed into an orthogonal matrix
217   * with the given threshold, or if the determinant of the resulting
218   * orthogonal matrix is negative
219
220   */
221  public Rotation(double[][] m, double threshold)
222    throws NotARotationMatrixException {
223
224    // dimension check
225    if ((m.length != 3) || (m[0].length != 3) ||
226        (m[1].length != 3) || (m[2].length != 3)) {
227      throw new NotARotationMatrixException(
228              LocalizedFormats.ROTATION_MATRIX_DIMENSIONS,
229              m.length, m[0].length);
230    }
231
232    // compute a "close" orthogonal matrix
233    double[][] ort = orthogonalizeMatrix(m, threshold);
234
235    // check the sign of the determinant
236    double det = ort[0][0] * (ort[1][1] * ort[2][2] - ort[2][1] * ort[1][2]) -
237                 ort[1][0] * (ort[0][1] * ort[2][2] - ort[2][1] * ort[0][2]) +
238                 ort[2][0] * (ort[0][1] * ort[1][2] - ort[1][1] * ort[0][2]);
239    if (det < 0.0) {
240      throw new NotARotationMatrixException(
241              LocalizedFormats.CLOSEST_ORTHOGONAL_MATRIX_HAS_NEGATIVE_DETERMINANT,
242              det);
243    }
244
245    double[] quat = mat2quat(ort);
246    q0 = quat[0];
247    q1 = quat[1];
248    q2 = quat[2];
249    q3 = quat[3];
250
251  }
252
253  /** Build the rotation that transforms a pair of vector into another pair.
254
255   * <p>Except for possible scale factors, if the instance were applied to
256   * the pair (u<sub>1</sub>, u<sub>2</sub>) it will produce the pair
257   * (v<sub>1</sub>, v<sub>2</sub>).</p>
258
259   * <p>If the angular separation between u<sub>1</sub> and u<sub>2</sub> is
260   * not the same as the angular separation between v<sub>1</sub> and
261   * v<sub>2</sub>, then a corrected v'<sub>2</sub> will be used rather than
262   * v<sub>2</sub>, the corrected vector will be in the (v<sub>1</sub>,
263   * v<sub>2</sub>) plane.</p>
264
265   * @param u1 first vector of the origin pair
266   * @param u2 second vector of the origin pair
267   * @param v1 desired image of u1 by the rotation
268   * @param v2 desired image of u2 by the rotation
269   * @exception MathArithmeticException if the norm of one of the vectors is zero,
270   * or if one of the pair is degenerated (i.e. the vectors of the pair are colinear)
271   */
272  public Rotation(Vector3D u1, Vector3D u2, Vector3D v1, Vector3D v2)
273      throws MathArithmeticException {
274
275      // build orthonormalized base from u1, u2
276      // this fails when vectors are null or colinear, which is forbidden to define a rotation
277      final Vector3D u3 = u1.crossProduct(u2).normalize();
278      u2 = u3.crossProduct(u1).normalize();
279      u1 = u1.normalize();
280
281      // build an orthonormalized base from v1, v2
282      // this fails when vectors are null or colinear, which is forbidden to define a rotation
283      final Vector3D v3 = v1.crossProduct(v2).normalize();
284      v2 = v3.crossProduct(v1).normalize();
285      v1 = v1.normalize();
286
287      // buid a matrix transforming the first base into the second one
288      final double[][] m = new double[][] {
289          {
290              MathArrays.linearCombination(u1.getX(), v1.getX(), u2.getX(), v2.getX(), u3.getX(), v3.getX()),
291              MathArrays.linearCombination(u1.getY(), v1.getX(), u2.getY(), v2.getX(), u3.getY(), v3.getX()),
292              MathArrays.linearCombination(u1.getZ(), v1.getX(), u2.getZ(), v2.getX(), u3.getZ(), v3.getX())
293          },
294          {
295              MathArrays.linearCombination(u1.getX(), v1.getY(), u2.getX(), v2.getY(), u3.getX(), v3.getY()),
296              MathArrays.linearCombination(u1.getY(), v1.getY(), u2.getY(), v2.getY(), u3.getY(), v3.getY()),
297              MathArrays.linearCombination(u1.getZ(), v1.getY(), u2.getZ(), v2.getY(), u3.getZ(), v3.getY())
298          },
299          {
300              MathArrays.linearCombination(u1.getX(), v1.getZ(), u2.getX(), v2.getZ(), u3.getX(), v3.getZ()),
301              MathArrays.linearCombination(u1.getY(), v1.getZ(), u2.getY(), v2.getZ(), u3.getY(), v3.getZ()),
302              MathArrays.linearCombination(u1.getZ(), v1.getZ(), u2.getZ(), v2.getZ(), u3.getZ(), v3.getZ())
303          }
304      };
305
306      double[] quat = mat2quat(m);
307      q0 = quat[0];
308      q1 = quat[1];
309      q2 = quat[2];
310      q3 = quat[3];
311
312  }
313
314  /** Build one of the rotations that transform one vector into another one.
315
316   * <p>Except for a possible scale factor, if the instance were
317   * applied to the vector u it will produce the vector v. There is an
318   * infinite number of such rotations, this constructor choose the
319   * one with the smallest associated angle (i.e. the one whose axis
320   * is orthogonal to the (u, v) plane). If u and v are colinear, an
321   * arbitrary rotation axis is chosen.</p>
322
323   * @param u origin vector
324   * @param v desired image of u by the rotation
325   * @exception MathArithmeticException if the norm of one of the vectors is zero
326   */
327  public Rotation(Vector3D u, Vector3D v) throws MathArithmeticException {
328
329    double normProduct = u.getNorm() * v.getNorm();
330    if (normProduct == 0) {
331        throw new MathArithmeticException(LocalizedFormats.ZERO_NORM_FOR_ROTATION_DEFINING_VECTOR);
332    }
333
334    double dot = u.dotProduct(v);
335
336    if (dot < ((2.0e-15 - 1.0) * normProduct)) {
337      // special case u = -v: we select a PI angle rotation around
338      // an arbitrary vector orthogonal to u
339      Vector3D w = u.orthogonal();
340      q0 = 0.0;
341      q1 = -w.getX();
342      q2 = -w.getY();
343      q3 = -w.getZ();
344    } else {
345      // general case: (u, v) defines a plane, we select
346      // the shortest possible rotation: axis orthogonal to this plane
347      q0 = FastMath.sqrt(0.5 * (1.0 + dot / normProduct));
348      double coeff = 1.0 / (2.0 * q0 * normProduct);
349      Vector3D q = v.crossProduct(u);
350      q1 = coeff * q.getX();
351      q2 = coeff * q.getY();
352      q3 = coeff * q.getZ();
353    }
354
355  }
356
357  /** Build a rotation from three Cardan or Euler elementary rotations.
358
359   * <p>Cardan rotations are three successive rotations around the
360   * canonical axes X, Y and Z, each axis being used once. There are
361   * 6 such sets of rotations (XYZ, XZY, YXZ, YZX, ZXY and ZYX). Euler
362   * rotations are three successive rotations around the canonical
363   * axes X, Y and Z, the first and last rotations being around the
364   * same axis. There are 6 such sets of rotations (XYX, XZX, YXY,
365   * YZY, ZXZ and ZYZ), the most popular one being ZXZ.</p>
366   * <p>Beware that many people routinely use the term Euler angles even
367   * for what really are Cardan angles (this confusion is especially
368   * widespread in the aerospace business where Roll, Pitch and Yaw angles
369   * are often wrongly tagged as Euler angles).</p>
370
371   * @param order order of rotations to use
372   * @param alpha1 angle of the first elementary rotation
373   * @param alpha2 angle of the second elementary rotation
374   * @param alpha3 angle of the third elementary rotation
375   */
376  public Rotation(RotationOrder order,
377                  double alpha1, double alpha2, double alpha3) {
378      Rotation r1 = new Rotation(order.getA1(), alpha1);
379      Rotation r2 = new Rotation(order.getA2(), alpha2);
380      Rotation r3 = new Rotation(order.getA3(), alpha3);
381      Rotation composed = r1.applyTo(r2.applyTo(r3));
382      q0 = composed.q0;
383      q1 = composed.q1;
384      q2 = composed.q2;
385      q3 = composed.q3;
386  }
387
388  /** Convert an orthogonal rotation matrix to a quaternion.
389   * @param ort orthogonal rotation matrix
390   * @return quaternion corresponding to the matrix
391   */
392  private static double[] mat2quat(final double[][] ort) {
393
394      final double[] quat = new double[4];
395
396      // There are different ways to compute the quaternions elements
397      // from the matrix. They all involve computing one element from
398      // the diagonal of the matrix, and computing the three other ones
399      // using a formula involving a division by the first element,
400      // which unfortunately can be zero. Since the norm of the
401      // quaternion is 1, we know at least one element has an absolute
402      // value greater or equal to 0.5, so it is always possible to
403      // select the right formula and avoid division by zero and even
404      // numerical inaccuracy. Checking the elements in turn and using
405      // the first one greater than 0.45 is safe (this leads to a simple
406      // test since qi = 0.45 implies 4 qi^2 - 1 = -0.19)
407      double s = ort[0][0] + ort[1][1] + ort[2][2];
408      if (s > -0.19) {
409          // compute q0 and deduce q1, q2 and q3
410          quat[0] = 0.5 * FastMath.sqrt(s + 1.0);
411          double inv = 0.25 / quat[0];
412          quat[1] = inv * (ort[1][2] - ort[2][1]);
413          quat[2] = inv * (ort[2][0] - ort[0][2]);
414          quat[3] = inv * (ort[0][1] - ort[1][0]);
415      } else {
416          s = ort[0][0] - ort[1][1] - ort[2][2];
417          if (s > -0.19) {
418              // compute q1 and deduce q0, q2 and q3
419              quat[1] = 0.5 * FastMath.sqrt(s + 1.0);
420              double inv = 0.25 / quat[1];
421              quat[0] = inv * (ort[1][2] - ort[2][1]);
422              quat[2] = inv * (ort[0][1] + ort[1][0]);
423              quat[3] = inv * (ort[0][2] + ort[2][0]);
424          } else {
425              s = ort[1][1] - ort[0][0] - ort[2][2];
426              if (s > -0.19) {
427                  // compute q2 and deduce q0, q1 and q3
428                  quat[2] = 0.5 * FastMath.sqrt(s + 1.0);
429                  double inv = 0.25 / quat[2];
430                  quat[0] = inv * (ort[2][0] - ort[0][2]);
431                  quat[1] = inv * (ort[0][1] + ort[1][0]);
432                  quat[3] = inv * (ort[2][1] + ort[1][2]);
433              } else {
434                  // compute q3 and deduce q0, q1 and q2
435                  s = ort[2][2] - ort[0][0] - ort[1][1];
436                  quat[3] = 0.5 * FastMath.sqrt(s + 1.0);
437                  double inv = 0.25 / quat[3];
438                  quat[0] = inv * (ort[0][1] - ort[1][0]);
439                  quat[1] = inv * (ort[0][2] + ort[2][0]);
440                  quat[2] = inv * (ort[2][1] + ort[1][2]);
441              }
442          }
443      }
444
445      return quat;
446
447  }
448
449  /** Revert a rotation.
450   * Build a rotation which reverse the effect of another
451   * rotation. This means that if r(u) = v, then r.revert(v) = u. The
452   * instance is not changed.
453   * @return a new rotation whose effect is the reverse of the effect
454   * of the instance
455   */
456  public Rotation revert() {
457    return new Rotation(-q0, q1, q2, q3, false);
458  }
459
460  /** Get the scalar coordinate of the quaternion.
461   * @return scalar coordinate of the quaternion
462   */
463  public double getQ0() {
464    return q0;
465  }
466
467  /** Get the first coordinate of the vectorial part of the quaternion.
468   * @return first coordinate of the vectorial part of the quaternion
469   */
470  public double getQ1() {
471    return q1;
472  }
473
474  /** Get the second coordinate of the vectorial part of the quaternion.
475   * @return second coordinate of the vectorial part of the quaternion
476   */
477  public double getQ2() {
478    return q2;
479  }
480
481  /** Get the third coordinate of the vectorial part of the quaternion.
482   * @return third coordinate of the vectorial part of the quaternion
483   */
484  public double getQ3() {
485    return q3;
486  }
487
488  /** Get the normalized axis of the rotation.
489   * @return normalized axis of the rotation
490   * @see #Rotation(Vector3D, double)
491   */
492  public Vector3D getAxis() {
493    double squaredSine = q1 * q1 + q2 * q2 + q3 * q3;
494    if (squaredSine == 0) {
495      return new Vector3D(1, 0, 0);
496    } else if (q0 < 0) {
497      double inverse = 1 / FastMath.sqrt(squaredSine);
498      return new Vector3D(q1 * inverse, q2 * inverse, q3 * inverse);
499    }
500    double inverse = -1 / FastMath.sqrt(squaredSine);
501    return new Vector3D(q1 * inverse, q2 * inverse, q3 * inverse);
502  }
503
504  /** Get the angle of the rotation.
505   * @return angle of the rotation (between 0 and &pi;)
506   * @see #Rotation(Vector3D, double)
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   * @return an array of three angles, in the order specified by the set
549   * @exception CardanEulerSingularityException if the rotation is
550   * singular with respect to the angles set specified
551   */
552  public double[] getAngles(RotationOrder order)
553    throws CardanEulerSingularityException {
554
555    if (order == RotationOrder.XYZ) {
556
557      // r (Vector3D.plusK) coordinates are :
558      //  sin (theta), -cos (theta) sin (phi), cos (theta) cos (phi)
559      // (-r) (Vector3D.plusI) coordinates are :
560      // cos (psi) cos (theta), -sin (psi) cos (theta), sin (theta)
561      // and we can choose to have theta in the interval [-PI/2 ; +PI/2]
562      Vector3D v1 = applyTo(Vector3D.PLUS_K);
563      Vector3D v2 = applyInverseTo(Vector3D.PLUS_I);
564      if  ((v2.getZ() < -0.9999999999) || (v2.getZ() > 0.9999999999)) {
565        throw new CardanEulerSingularityException(true);
566      }
567      return new double[] {
568        FastMath.atan2(-(v1.getY()), v1.getZ()),
569        FastMath.asin(v2.getZ()),
570        FastMath.atan2(-(v2.getY()), v2.getX())
571      };
572
573    } else if (order == RotationOrder.XZY) {
574
575      // r (Vector3D.plusJ) coordinates are :
576      // -sin (psi), cos (psi) cos (phi), cos (psi) sin (phi)
577      // (-r) (Vector3D.plusI) coordinates are :
578      // cos (theta) cos (psi), -sin (psi), sin (theta) cos (psi)
579      // and we can choose to have psi in the interval [-PI/2 ; +PI/2]
580      Vector3D v1 = applyTo(Vector3D.PLUS_J);
581      Vector3D v2 = applyInverseTo(Vector3D.PLUS_I);
582      if ((v2.getY() < -0.9999999999) || (v2.getY() > 0.9999999999)) {
583        throw new CardanEulerSingularityException(true);
584      }
585      return new double[] {
586        FastMath.atan2(v1.getZ(), v1.getY()),
587       -FastMath.asin(v2.getY()),
588        FastMath.atan2(v2.getZ(), v2.getX())
589      };
590
591    } else if (order == RotationOrder.YXZ) {
592
593      // r (Vector3D.plusK) coordinates are :
594      //  cos (phi) sin (theta), -sin (phi), cos (phi) cos (theta)
595      // (-r) (Vector3D.plusJ) coordinates are :
596      // sin (psi) cos (phi), cos (psi) cos (phi), -sin (phi)
597      // and we can choose to have phi in the interval [-PI/2 ; +PI/2]
598      Vector3D v1 = applyTo(Vector3D.PLUS_K);
599      Vector3D v2 = applyInverseTo(Vector3D.PLUS_J);
600      if ((v2.getZ() < -0.9999999999) || (v2.getZ() > 0.9999999999)) {
601        throw new CardanEulerSingularityException(true);
602      }
603      return new double[] {
604        FastMath.atan2(v1.getX(), v1.getZ()),
605       -FastMath.asin(v2.getZ()),
606        FastMath.atan2(v2.getX(), v2.getY())
607      };
608
609    } else if (order == RotationOrder.YZX) {
610
611      // r (Vector3D.plusI) coordinates are :
612      // cos (psi) cos (theta), sin (psi), -cos (psi) sin (theta)
613      // (-r) (Vector3D.plusJ) coordinates are :
614      // sin (psi), cos (phi) cos (psi), -sin (phi) cos (psi)
615      // and we can choose to have psi in the interval [-PI/2 ; +PI/2]
616      Vector3D v1 = applyTo(Vector3D.PLUS_I);
617      Vector3D v2 = applyInverseTo(Vector3D.PLUS_J);
618      if ((v2.getX() < -0.9999999999) || (v2.getX() > 0.9999999999)) {
619        throw new CardanEulerSingularityException(true);
620      }
621      return new double[] {
622        FastMath.atan2(-(v1.getZ()), v1.getX()),
623        FastMath.asin(v2.getX()),
624        FastMath.atan2(-(v2.getZ()), v2.getY())
625      };
626
627    } else if (order == RotationOrder.ZXY) {
628
629      // r (Vector3D.plusJ) coordinates are :
630      // -cos (phi) sin (psi), cos (phi) cos (psi), sin (phi)
631      // (-r) (Vector3D.plusK) coordinates are :
632      // -sin (theta) cos (phi), sin (phi), cos (theta) cos (phi)
633      // and we can choose to have phi in the interval [-PI/2 ; +PI/2]
634      Vector3D v1 = applyTo(Vector3D.PLUS_J);
635      Vector3D v2 = applyInverseTo(Vector3D.PLUS_K);
636      if ((v2.getY() < -0.9999999999) || (v2.getY() > 0.9999999999)) {
637        throw new CardanEulerSingularityException(true);
638      }
639      return new double[] {
640        FastMath.atan2(-(v1.getX()), v1.getY()),
641        FastMath.asin(v2.getY()),
642        FastMath.atan2(-(v2.getX()), v2.getZ())
643      };
644
645    } else if (order == RotationOrder.ZYX) {
646
647      // r (Vector3D.plusI) coordinates are :
648      //  cos (theta) cos (psi), cos (theta) sin (psi), -sin (theta)
649      // (-r) (Vector3D.plusK) coordinates are :
650      // -sin (theta), sin (phi) cos (theta), cos (phi) cos (theta)
651      // and we can choose to have theta in the interval [-PI/2 ; +PI/2]
652      Vector3D v1 = applyTo(Vector3D.PLUS_I);
653      Vector3D v2 = applyInverseTo(Vector3D.PLUS_K);
654      if ((v2.getX() < -0.9999999999) || (v2.getX() > 0.9999999999)) {
655        throw new CardanEulerSingularityException(true);
656      }
657      return new double[] {
658        FastMath.atan2(v1.getY(), v1.getX()),
659       -FastMath.asin(v2.getX()),
660        FastMath.atan2(v2.getY(), v2.getZ())
661      };
662
663    } else if (order == RotationOrder.XYX) {
664
665      // r (Vector3D.plusI) coordinates are :
666      //  cos (theta), sin (phi1) sin (theta), -cos (phi1) sin (theta)
667      // (-r) (Vector3D.plusI) coordinates are :
668      // cos (theta), sin (theta) sin (phi2), sin (theta) cos (phi2)
669      // and we can choose to have theta in the interval [0 ; PI]
670      Vector3D v1 = applyTo(Vector3D.PLUS_I);
671      Vector3D v2 = applyInverseTo(Vector3D.PLUS_I);
672      if ((v2.getX() < -0.9999999999) || (v2.getX() > 0.9999999999)) {
673        throw new CardanEulerSingularityException(false);
674      }
675      return new double[] {
676        FastMath.atan2(v1.getY(), -v1.getZ()),
677        FastMath.acos(v2.getX()),
678        FastMath.atan2(v2.getY(), v2.getZ())
679      };
680
681    } else if (order == RotationOrder.XZX) {
682
683      // r (Vector3D.plusI) coordinates are :
684      //  cos (psi), cos (phi1) sin (psi), sin (phi1) sin (psi)
685      // (-r) (Vector3D.plusI) coordinates are :
686      // cos (psi), -sin (psi) cos (phi2), sin (psi) sin (phi2)
687      // and we can choose to have psi in the interval [0 ; PI]
688      Vector3D v1 = applyTo(Vector3D.PLUS_I);
689      Vector3D v2 = applyInverseTo(Vector3D.PLUS_I);
690      if ((v2.getX() < -0.9999999999) || (v2.getX() > 0.9999999999)) {
691        throw new CardanEulerSingularityException(false);
692      }
693      return new double[] {
694        FastMath.atan2(v1.getZ(), v1.getY()),
695        FastMath.acos(v2.getX()),
696        FastMath.atan2(v2.getZ(), -v2.getY())
697      };
698
699    } else if (order == RotationOrder.YXY) {
700
701      // r (Vector3D.plusJ) coordinates are :
702      //  sin (theta1) sin (phi), cos (phi), cos (theta1) sin (phi)
703      // (-r) (Vector3D.plusJ) coordinates are :
704      // sin (phi) sin (theta2), cos (phi), -sin (phi) cos (theta2)
705      // and we can choose to have phi in the interval [0 ; PI]
706      Vector3D v1 = applyTo(Vector3D.PLUS_J);
707      Vector3D v2 = applyInverseTo(Vector3D.PLUS_J);
708      if ((v2.getY() < -0.9999999999) || (v2.getY() > 0.9999999999)) {
709        throw new CardanEulerSingularityException(false);
710      }
711      return new double[] {
712        FastMath.atan2(v1.getX(), v1.getZ()),
713        FastMath.acos(v2.getY()),
714        FastMath.atan2(v2.getX(), -v2.getZ())
715      };
716
717    } else if (order == RotationOrder.YZY) {
718
719      // r (Vector3D.plusJ) coordinates are :
720      //  -cos (theta1) sin (psi), cos (psi), sin (theta1) sin (psi)
721      // (-r) (Vector3D.plusJ) coordinates are :
722      // sin (psi) cos (theta2), cos (psi), sin (psi) sin (theta2)
723      // and we can choose to have psi in the interval [0 ; PI]
724      Vector3D v1 = applyTo(Vector3D.PLUS_J);
725      Vector3D v2 = applyInverseTo(Vector3D.PLUS_J);
726      if ((v2.getY() < -0.9999999999) || (v2.getY() > 0.9999999999)) {
727        throw new CardanEulerSingularityException(false);
728      }
729      return new double[] {
730        FastMath.atan2(v1.getZ(), -v1.getX()),
731        FastMath.acos(v2.getY()),
732        FastMath.atan2(v2.getZ(), v2.getX())
733      };
734
735    } else if (order == RotationOrder.ZXZ) {
736
737      // r (Vector3D.plusK) coordinates are :
738      //  sin (psi1) sin (phi), -cos (psi1) sin (phi), cos (phi)
739      // (-r) (Vector3D.plusK) coordinates are :
740      // sin (phi) sin (psi2), sin (phi) cos (psi2), cos (phi)
741      // and we can choose to have phi in the interval [0 ; PI]
742      Vector3D v1 = applyTo(Vector3D.PLUS_K);
743      Vector3D v2 = applyInverseTo(Vector3D.PLUS_K);
744      if ((v2.getZ() < -0.9999999999) || (v2.getZ() > 0.9999999999)) {
745        throw new CardanEulerSingularityException(false);
746      }
747      return new double[] {
748        FastMath.atan2(v1.getX(), -v1.getY()),
749        FastMath.acos(v2.getZ()),
750        FastMath.atan2(v2.getX(), v2.getY())
751      };
752
753    } else { // last possibility is ZYZ
754
755      // r (Vector3D.plusK) coordinates are :
756      //  cos (psi1) sin (theta), sin (psi1) sin (theta), cos (theta)
757      // (-r) (Vector3D.plusK) coordinates are :
758      // -sin (theta) cos (psi2), sin (theta) sin (psi2), cos (theta)
759      // and we can choose to have theta in the interval [0 ; PI]
760      Vector3D v1 = applyTo(Vector3D.PLUS_K);
761      Vector3D v2 = applyInverseTo(Vector3D.PLUS_K);
762      if ((v2.getZ() < -0.9999999999) || (v2.getZ() > 0.9999999999)) {
763        throw new CardanEulerSingularityException(false);
764      }
765      return new double[] {
766        FastMath.atan2(v1.getY(), v1.getX()),
767        FastMath.acos(v2.getZ()),
768        FastMath.atan2(v2.getY(), -v2.getX())
769      };
770
771    }
772
773  }
774
775  /** Get the 3X3 matrix corresponding to the instance
776   * @return the matrix corresponding to the instance
777   */
778  public double[][] getMatrix() {
779
780    // products
781    double q0q0  = q0 * q0;
782    double q0q1  = q0 * q1;
783    double q0q2  = q0 * q2;
784    double q0q3  = q0 * q3;
785    double q1q1  = q1 * q1;
786    double q1q2  = q1 * q2;
787    double q1q3  = q1 * q3;
788    double q2q2  = q2 * q2;
789    double q2q3  = q2 * q3;
790    double q3q3  = q3 * q3;
791
792    // create the matrix
793    double[][] m = new double[3][];
794    m[0] = new double[3];
795    m[1] = new double[3];
796    m[2] = new double[3];
797
798    m [0][0] = 2.0 * (q0q0 + q1q1) - 1.0;
799    m [1][0] = 2.0 * (q1q2 - q0q3);
800    m [2][0] = 2.0 * (q1q3 + q0q2);
801
802    m [0][1] = 2.0 * (q1q2 + q0q3);
803    m [1][1] = 2.0 * (q0q0 + q2q2) - 1.0;
804    m [2][1] = 2.0 * (q2q3 - q0q1);
805
806    m [0][2] = 2.0 * (q1q3 - q0q2);
807    m [1][2] = 2.0 * (q2q3 + q0q1);
808    m [2][2] = 2.0 * (q0q0 + q3q3) - 1.0;
809
810    return m;
811
812  }
813
814  /** Apply the rotation to a vector.
815   * @param u vector to apply the rotation to
816   * @return a new vector which is the image of u by the rotation
817   */
818  public Vector3D applyTo(Vector3D u) {
819
820    double x = u.getX();
821    double y = u.getY();
822    double z = u.getZ();
823
824    double s = q1 * x + q2 * y + q3 * z;
825
826    return new Vector3D(2 * (q0 * (x * q0 - (q2 * z - q3 * y)) + s * q1) - x,
827                        2 * (q0 * (y * q0 - (q3 * x - q1 * z)) + s * q2) - y,
828                        2 * (q0 * (z * q0 - (q1 * y - q2 * x)) + s * q3) - z);
829
830  }
831
832  /** Apply the rotation to a vector stored in an array.
833   * @param in an array with three items which stores vector to rotate
834   * @param out an array with three items to put result to (it can be the same
835   * array as in)
836   */
837  public void applyTo(final double[] in, final double[] out) {
838
839      final double x = in[0];
840      final double y = in[1];
841      final double z = in[2];
842
843      final double s = q1 * x + q2 * y + q3 * z;
844
845      out[0] = 2 * (q0 * (x * q0 - (q2 * z - q3 * y)) + s * q1) - x;
846      out[1] = 2 * (q0 * (y * q0 - (q3 * x - q1 * z)) + s * q2) - y;
847      out[2] = 2 * (q0 * (z * q0 - (q1 * y - q2 * x)) + s * q3) - z;
848
849  }
850
851  /** Apply the inverse of the rotation to a vector.
852   * @param u vector to apply the inverse of the rotation to
853   * @return a new vector which such that u is its image by the rotation
854   */
855  public Vector3D applyInverseTo(Vector3D u) {
856
857    double x = u.getX();
858    double y = u.getY();
859    double z = u.getZ();
860
861    double s = q1 * x + q2 * y + q3 * z;
862    double m0 = -q0;
863
864    return new Vector3D(2 * (m0 * (x * m0 - (q2 * z - q3 * y)) + s * q1) - x,
865                        2 * (m0 * (y * m0 - (q3 * x - q1 * z)) + s * q2) - y,
866                        2 * (m0 * (z * m0 - (q1 * y - q2 * x)) + s * q3) - z);
867
868  }
869
870  /** Apply the inverse of the rotation to a vector stored in an array.
871   * @param in an array with three items which stores vector to rotate
872   * @param out an array with three items to put result to (it can be the same
873   * array as in)
874   */
875  public void applyInverseTo(final double[] in, final double[] out) {
876
877      final double x = in[0];
878      final double y = in[1];
879      final double z = in[2];
880
881      final double s = q1 * x + q2 * y + q3 * z;
882      final double m0 = -q0;
883
884      out[0] = 2 * (m0 * (x * m0 - (q2 * z - q3 * y)) + s * q1) - x;
885      out[1] = 2 * (m0 * (y * m0 - (q3 * x - q1 * z)) + s * q2) - y;
886      out[2] = 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 (FastMath.abs(fn1 - fn) <= threshold) {
1002          return o;
1003      }
1004
1005      // prepare next iteration
1006      x00 = o0[0];
1007      x01 = o0[1];
1008      x02 = o0[2];
1009      x10 = o1[0];
1010      x11 = o1[1];
1011      x12 = o1[2];
1012      x20 = o2[0];
1013      x21 = o2[1];
1014      x22 = o2[2];
1015      fn  = fn1;
1016
1017    }
1018
1019    // the algorithm did not converge after 10 iterations
1020    throw new NotARotationMatrixException(
1021            LocalizedFormats.UNABLE_TO_ORTHOGONOLIZE_MATRIX,
1022            i - 1);
1023  }
1024
1025  /** Compute the <i>distance</i> between two rotations.
1026   * <p>The <i>distance</i> is intended here as a way to check if two
1027   * rotations are almost similar (i.e. they transform vectors the same way)
1028   * or very different. It is mathematically defined as the angle of
1029   * the rotation r that prepended to one of the rotations gives the other
1030   * one:</p>
1031   * <pre>
1032   *        r<sub>1</sub>(r) = r<sub>2</sub>
1033   * </pre>
1034   * <p>This distance is an angle between 0 and &pi;. Its value is the smallest
1035   * possible upper bound of the angle in radians between r<sub>1</sub>(v)
1036   * and r<sub>2</sub>(v) for all possible vectors v. This upper bound is
1037   * reached for some v. The distance is equal to 0 if and only if the two
1038   * rotations are identical.</p>
1039   * <p>Comparing two rotations should always be done using this value rather
1040   * than for example comparing the components of the quaternions. It is much
1041   * more stable, and has a geometric meaning. Also comparing quaternions
1042   * components is error prone since for example quaternions (0.36, 0.48, -0.48, -0.64)
1043   * and (-0.36, -0.48, 0.48, 0.64) represent exactly the same rotation despite
1044   * their components are different (they are exact opposites).</p>
1045   * @param r1 first rotation
1046   * @param r2 second rotation
1047   * @return <i>distance</i> between r1 and r2
1048   */
1049  public static double distance(Rotation r1, Rotation r2) {
1050      return r1.applyInverseTo(r2).getAngle();
1051  }
1052
1053}