1   /* Copyright 2002-2016 CS Systèmes d'Information
2    * Licensed to CS Systèmes d'Information (CS) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * CS 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  package org.orekit.utils;
18  
19  import java.io.Serializable;
20  
21  import org.hipparchus.analysis.differentiation.DerivativeStructure;
22  import org.hipparchus.exception.LocalizedCoreFormats;
23  import org.hipparchus.exception.MathIllegalArgumentException;
24  import org.hipparchus.exception.MathRuntimeException;
25  import org.hipparchus.geometry.euclidean.threed.FieldRotation;
26  import org.hipparchus.geometry.euclidean.threed.Rotation;
27  import org.hipparchus.geometry.euclidean.threed.RotationConvention;
28  import org.hipparchus.geometry.euclidean.threed.Vector3D;
29  import org.hipparchus.linear.DecompositionSolver;
30  import org.hipparchus.linear.MatrixUtils;
31  import org.hipparchus.linear.QRDecomposition;
32  import org.hipparchus.linear.RealMatrix;
33  import org.hipparchus.linear.RealVector;
34  import org.hipparchus.util.FastMath;
35  import org.hipparchus.util.MathArrays;
36  import org.orekit.errors.OrekitException;
37  import org.orekit.errors.OrekitMessages;
38  import org.orekit.time.TimeShiftable;
39  
40  /** Simple container for rotation/rotation rate/rotation acceleration triplets.
41   * <p>
42   * The state can be slightly shifted to close dates. This shift is based on
43   * an approximate solution of the fixed acceleration motion. It is <em>not</em>
44   * intended as a replacement for proper attitude propagation but should be
45   * sufficient for either small time shifts or coarse accuracy.
46   * </p>
47   * <p>
48   * This class is the angular counterpart to {@link PVCoordinates}.
49   * </p>
50   * <p>Instances of this class are guaranteed to be immutable.</p>
51   * @author Luc Maisonobe
52   */
53  public class AngularCoordinates implements TimeShiftable<AngularCoordinates>, Serializable {
54  
55      /** Fixed orientation parallel with reference frame
56       * (identity rotation, zero rotation rate and acceleration).
57       */
58      public static final AngularCoordinates IDENTITY =
59              new AngularCoordinates(Rotation.IDENTITY, Vector3D.ZERO, Vector3D.ZERO);
60  
61      /** Serializable UID. */
62      private static final long serialVersionUID = 20140414L;
63  
64      /** Rotation. */
65      private final Rotation rotation;
66  
67      /** Rotation rate. */
68      private final Vector3D rotationRate;
69  
70      /** Rotation acceleration. */
71      private final Vector3D rotationAcceleration;
72  
73      /** Simple constructor.
74       * <p> Sets the Coordinates to default : Identity, Ω = (0 0 0), dΩ/dt = (0 0 0).</p>
75       */
76      public AngularCoordinates() {
77          this(Rotation.IDENTITY, Vector3D.ZERO, Vector3D.ZERO);
78      }
79  
80      /** Builds a rotation/rotation rate pair.
81       * @param rotation rotation
82       * @param rotationRate rotation rate Ω (rad/s)
83       */
84      public AngularCoordinates(final Rotation rotation, final Vector3D rotationRate) {
85          this(rotation, rotationRate, Vector3D.ZERO);
86      }
87  
88      /** Builds a rotation/rotation rate/rotation acceleration triplet.
89       * @param rotation rotation
90       * @param rotationRate rotation rate Ω (rad/s)
91       * @param rotationAcceleration rotation acceleration dΩ/dt (rad²/s²)
92       */
93      public AngularCoordinates(final Rotation rotation,
94                                final Vector3D rotationRate, final Vector3D rotationAcceleration) {
95          this.rotation             = rotation;
96          this.rotationRate         = rotationRate;
97          this.rotationAcceleration = rotationAcceleration;
98      }
99  
100     /** Build the rotation that transforms a pair of pv coordinates into another one.
101 
102      * <p><em>WARNING</em>! This method requires much more stringent assumptions on
103      * its parameters than the similar {@link Rotation#Rotation(Vector3D, Vector3D,
104      * Vector3D, Vector3D) constructor} from the {@link Rotation Rotation} class.
105      * As far as the Rotation constructor is concerned, the {@code v₂} vector from
106      * the second pair can be slightly misaligned. The Rotation constructor will
107      * compensate for this misalignment and create a rotation that ensure {@code
108      * v₁ = r(u₁)} and {@code v₂ ∈ plane (r(u₁), r(u₂))}. <em>THIS IS NOT
109      * TRUE ANYMORE IN THIS CLASS</em>! As derivatives are involved and must be
110      * preserved, this constructor works <em>only</em> if the two pairs are fully
111      * consistent, i.e. if a rotation exists that fulfill all the requirements: {@code
112      * v₁ = r(u₁)}, {@code v₂ = r(u₂)}, {@code dv₁/dt = dr(u₁)/dt}, {@code dv₂/dt
113      * = dr(u₂)/dt}, {@code d²v₁/dt² = d²r(u₁)/dt²}, {@code d²v₂/dt² = d²r(u₂)/dt²}.</p>
114      * @param u1 first vector of the origin pair
115      * @param u2 second vector of the origin pair
116      * @param v1 desired image of u1 by the rotation
117      * @param v2 desired image of u2 by the rotation
118      * @param tolerance relative tolerance factor used to check singularities
119      * @exception OrekitException if the vectors are inconsistent for the
120      * rotation to be found (null, aligned, ...)
121      */
122     public AngularCoordinates(final PVCoordinates u1, final PVCoordinates u2,
123                               final PVCoordinates v1, final PVCoordinates v2,
124                               final double tolerance)
125         throws OrekitException {
126 
127         try {
128             // find the initial fixed rotation
129             rotation = new Rotation(u1.getPosition(), u2.getPosition(),
130                                     v1.getPosition(), v2.getPosition());
131 
132             // find rotation rate Ω such that
133             //  Ω ⨯ v₁ = r(dot(u₁)) - dot(v₁)
134             //  Ω ⨯ v₂ = r(dot(u₂)) - dot(v₂)
135             final Vector3D ru1Dot = rotation.applyTo(u1.getVelocity());
136             final Vector3D ru2Dot = rotation.applyTo(u2.getVelocity());
137             rotationRate = inverseCrossProducts(v1.getPosition(), ru1Dot.subtract(v1.getVelocity()),
138                                                 v2.getPosition(), ru2Dot.subtract(v2.getVelocity()),
139                                                 tolerance);
140 
141             // find rotation acceleration dot(Ω) such that
142             // dot(Ω) ⨯ v₁ = r(dotdot(u₁)) - 2 Ω ⨯ dot(v₁) - Ω ⨯  (Ω ⨯ v₁) - dotdot(v₁)
143             // dot(Ω) ⨯ v₂ = r(dotdot(u₂)) - 2 Ω ⨯ dot(v₂) - Ω ⨯  (Ω ⨯ v₂) - dotdot(v₂)
144             final Vector3D ru1DotDot = rotation.applyTo(u1.getAcceleration());
145             final Vector3D oDotv1    = Vector3D.crossProduct(rotationRate, v1.getVelocity());
146             final Vector3D oov1      = Vector3D.crossProduct(rotationRate, Vector3D.crossProduct(rotationRate, v1.getPosition()));
147             final Vector3D c1        = new Vector3D(1, ru1DotDot, -2, oDotv1, -1, oov1, -1, v1.getAcceleration());
148             final Vector3D ru2DotDot = rotation.applyTo(u2.getAcceleration());
149             final Vector3D oDotv2    = Vector3D.crossProduct(rotationRate, v2.getVelocity());
150             final Vector3D oov2      = Vector3D.crossProduct(rotationRate, Vector3D.crossProduct(rotationRate, v2.getPosition()));
151             final Vector3D c2        = new Vector3D(1, ru2DotDot, -2, oDotv2, -1, oov2, -1, v2.getAcceleration());
152             rotationAcceleration     = inverseCrossProducts(v1.getPosition(), c1, v2.getPosition(), c2, tolerance);
153 
154         } catch (MathRuntimeException mrte) {
155             throw new OrekitException(mrte);
156         }
157 
158     }
159 
160     /** Build one of the rotations that transform one pv coordinates into another one.
161 
162      * <p>Except for a possible scale factor, if the instance were
163      * applied to the vector u it will produce the vector v. There is an
164      * infinite number of such rotations, this constructor choose the
165      * one with the smallest associated angle (i.e. the one whose axis
166      * is orthogonal to the (u, v) plane). If u and v are collinear, an
167      * arbitrary rotation axis is chosen.</p>
168 
169      * @param u origin vector
170      * @param v desired image of u by the rotation
171      * @exception OrekitException if the vectors components cannot be converted to
172      * {@link DerivativeStructure} with proper order
173      */
174     public AngularCoordinates(final PVCoordinates u, final PVCoordinates v) throws OrekitException {
175         this(new FieldRotation<DerivativeStructure>(u.toDerivativeStructureVector(2),
176                                                     v.toDerivativeStructureVector(2)));
177     }
178 
179     /** Builds a AngularCoordinates from  a {@link FieldRotation}&lt;{@link DerivativeStructure}&gt;.
180      * <p>
181      * The rotation components must have time as their only derivation parameter and
182      * have consistent derivation orders.
183      * </p>
184      * @param r rotation with time-derivatives embedded within the coordinates
185      */
186     public AngularCoordinates(final FieldRotation<DerivativeStructure> r) {
187 
188         final double q0       = r.getQ0().getReal();
189         final double q1       = r.getQ1().getReal();
190         final double q2       = r.getQ2().getReal();
191         final double q3       = r.getQ3().getReal();
192 
193         rotation     = new Rotation(q0, q1, q2, q3, false);
194         if (r.getQ0().getOrder() >= 1) {
195             final double q0Dot    = r.getQ0().getPartialDerivative(1);
196             final double q1Dot    = r.getQ1().getPartialDerivative(1);
197             final double q2Dot    = r.getQ2().getPartialDerivative(1);
198             final double q3Dot    = r.getQ3().getPartialDerivative(1);
199             rotationRate =
200                     new Vector3D(2 * MathArrays.linearCombination(-q1, q0Dot,  q0, q1Dot,  q3, q2Dot, -q2, q3Dot),
201                                  2 * MathArrays.linearCombination(-q2, q0Dot, -q3, q1Dot,  q0, q2Dot,  q1, q3Dot),
202                                  2 * MathArrays.linearCombination(-q3, q0Dot,  q2, q1Dot, -q1, q2Dot,  q0, q3Dot));
203             if (r.getQ0().getOrder() >= 2) {
204                 final double q0DotDot = r.getQ0().getPartialDerivative(2);
205                 final double q1DotDot = r.getQ1().getPartialDerivative(2);
206                 final double q2DotDot = r.getQ2().getPartialDerivative(2);
207                 final double q3DotDot = r.getQ3().getPartialDerivative(2);
208                 rotationAcceleration =
209                         new Vector3D(2 * MathArrays.linearCombination(-q1, q0DotDot,  q0, q1DotDot,  q3, q2DotDot, -q2, q3DotDot),
210                                      2 * MathArrays.linearCombination(-q2, q0DotDot, -q3, q1DotDot,  q0, q2DotDot,  q1, q3DotDot),
211                                      2 * MathArrays.linearCombination(-q3, q0DotDot,  q2, q1DotDot, -q1, q2DotDot,  q0, q3DotDot));
212             } else {
213                 rotationAcceleration = Vector3D.ZERO;
214             }
215         } else {
216             rotationRate         = Vector3D.ZERO;
217             rotationAcceleration = Vector3D.ZERO;
218         }
219 
220     }
221 
222     /** Find a vector from two known cross products.
223      * <p>
224      * We want to find Ω such that: Ω ⨯ v₁ = c₁ and Ω ⨯ v₂ = c₂
225      * </p>
226      * <p>
227      * The first equation (Ω ⨯ v₁ = c₁) will always be fulfilled exactly,
228      * and the second one will be fulfilled if possible.
229      * </p>
230      * @param v1 vector forming the first known cross product
231      * @param c1 know vector for cross product Ω ⨯ v₁
232      * @param v2 vector forming the second known cross product
233      * @param c2 know vector for cross product Ω ⨯ v₂
234      * @param tolerance relative tolerance factor used to check singularities
235      * @return vector Ω such that: Ω ⨯ v₁ = c₁ and Ω ⨯ v₂ = c₂
236      * @exception MathIllegalArgumentException if vectors are inconsistent and
237      * no solution can be found
238      */
239     private static Vector3D inverseCrossProducts(final Vector3D v1, final Vector3D c1,
240                                                  final Vector3D v2, final Vector3D c2,
241                                                  final double tolerance)
242         throws MathIllegalArgumentException {
243 
244         final double v12 = v1.getNormSq();
245         final double v1n = FastMath.sqrt(v12);
246         final double v22 = v2.getNormSq();
247         final double v2n = FastMath.sqrt(v22);
248         final double threshold = tolerance * FastMath.max(v1n, v2n);
249 
250         Vector3D omega;
251 
252         try {
253             // create the over-determined linear system representing the two cross products
254             final RealMatrix m = MatrixUtils.createRealMatrix(6, 3);
255             m.setEntry(0, 1,  v1.getZ());
256             m.setEntry(0, 2, -v1.getY());
257             m.setEntry(1, 0, -v1.getZ());
258             m.setEntry(1, 2,  v1.getX());
259             m.setEntry(2, 0,  v1.getY());
260             m.setEntry(2, 1, -v1.getX());
261             m.setEntry(3, 1,  v2.getZ());
262             m.setEntry(3, 2, -v2.getY());
263             m.setEntry(4, 0, -v2.getZ());
264             m.setEntry(4, 2,  v2.getX());
265             m.setEntry(5, 0,  v2.getY());
266             m.setEntry(5, 1, -v2.getX());
267 
268             final RealVector rhs = MatrixUtils.createRealVector(new double[] {
269                 c1.getX(), c1.getY(), c1.getZ(),
270                 c2.getX(), c2.getY(), c2.getZ()
271             });
272 
273             // find the best solution we can
274             final DecompositionSolver solver = new QRDecomposition(m, threshold).getSolver();
275             final RealVector v = solver.solve(rhs);
276             omega = new Vector3D(v.getEntry(0), v.getEntry(1), v.getEntry(2));
277 
278         } catch (MathIllegalArgumentException miae) {
279             if (miae.getSpecifier() == LocalizedCoreFormats.SINGULAR_MATRIX) {
280 
281                 // handle some special cases for which we can compute a solution
282                 final double c12 = c1.getNormSq();
283                 final double c1n = FastMath.sqrt(c12);
284                 final double c22 = c2.getNormSq();
285                 final double c2n = FastMath.sqrt(c22);
286 
287                 if (c1n <= threshold && c2n <= threshold) {
288                     // simple special case, velocities are cancelled
289                     return Vector3D.ZERO;
290                 } else if (v1n <= threshold && c1n >= threshold) {
291                     // this is inconsistent, if v₁ is zero, c₁ must be 0 too
292                     throw new MathIllegalArgumentException(LocalizedCoreFormats.NUMBER_TOO_LARGE, c1n, 0, true);
293                 } else if (v2n <= threshold && c2n >= threshold) {
294                     // this is inconsistent, if v₂ is zero, c₂ must be 0 too
295                     throw new MathIllegalArgumentException(LocalizedCoreFormats.NUMBER_TOO_LARGE, c2n, 0, true);
296                 } else if (Vector3D.crossProduct(v1, v2).getNorm() <= threshold && v12 > threshold) {
297                     // simple special case, v₂ is redundant with v₁, we just ignore it
298                     // use the simplest Ω: orthogonal to both v₁ and c₁
299                     omega = new Vector3D(1.0 / v12, Vector3D.crossProduct(v1, c1));
300                 } else {
301                     throw miae;
302                 }
303             } else {
304                 throw miae;
305             }
306 
307         }
308 
309         // check results
310         final double d1 = Vector3D.distance(Vector3D.crossProduct(omega, v1), c1);
311         if (d1 > threshold) {
312             throw new MathIllegalArgumentException(LocalizedCoreFormats.NUMBER_TOO_LARGE, d1, 0, true);
313         }
314 
315         final double d2 = Vector3D.distance(Vector3D.crossProduct(omega, v2), c2);
316         if (d2 > threshold) {
317             throw new MathIllegalArgumentException(LocalizedCoreFormats.NUMBER_TOO_LARGE, d2, 0, true);
318         }
319 
320         return omega;
321 
322     }
323 
324     /** Transform the instance to a {@link FieldRotation}&lt;{@link DerivativeStructure}&gt;.
325      * <p>
326      * The {@link DerivativeStructure} coordinates correspond to time-derivatives up
327      * to the user-specified order.
328      * </p>
329      * @param order derivation order for the vector components
330      * @return rotation with time-derivatives embedded within the coordinates
331      * @exception OrekitException if the user specified order is too large
332      */
333     public FieldRotation<DerivativeStructure> toDerivativeStructureRotation(final int order)
334         throws OrekitException {
335 
336         // quaternion components
337         final double q0 = rotation.getQ0();
338         final double q1 = rotation.getQ1();
339         final double q2 = rotation.getQ2();
340         final double q3 = rotation.getQ3();
341 
342         // first time-derivatives of the quaternion
343         final double oX    = rotationRate.getX();
344         final double oY    = rotationRate.getY();
345         final double oZ    = rotationRate.getZ();
346         final double q0Dot = 0.5 * MathArrays.linearCombination(-q1, oX, -q2, oY, -q3, oZ);
347         final double q1Dot = 0.5 * MathArrays.linearCombination( q0, oX, -q3, oY,  q2, oZ);
348         final double q2Dot = 0.5 * MathArrays.linearCombination( q3, oX,  q0, oY, -q1, oZ);
349         final double q3Dot = 0.5 * MathArrays.linearCombination(-q2, oX,  q1, oY,  q0, oZ);
350 
351         // second time-derivatives of the quaternion
352         final double oXDot = rotationAcceleration.getX();
353         final double oYDot = rotationAcceleration.getY();
354         final double oZDot = rotationAcceleration.getZ();
355         final double q0DotDot = -0.5 * MathArrays.linearCombination(new double[] {
356             q1, q2,  q3, q1Dot, q2Dot,  q3Dot
357         }, new double[] {
358             oXDot, oYDot, oZDot, oX, oY, oZ
359         });
360         final double q1DotDot =  0.5 * MathArrays.linearCombination(new double[] {
361             q0, q2, -q3, q0Dot, q2Dot, -q3Dot
362         }, new double[] {
363             oXDot, oZDot, oYDot, oX, oZ, oY
364         });
365         final double q2DotDot =  0.5 * MathArrays.linearCombination(new double[] {
366             q0, q3, -q1, q0Dot, q3Dot, -q1Dot
367         }, new double[] {
368             oYDot, oXDot, oZDot, oY, oX, oZ
369         });
370         final double q3DotDot =  0.5 * MathArrays.linearCombination(new double[] {
371             q0, q1, -q2, q0Dot, q1Dot, -q2Dot
372         }, new double[] {
373             oZDot, oYDot, oXDot, oZ, oY, oX
374         });
375 
376         final DerivativeStructure q0DS;
377         final DerivativeStructure q1DS;
378         final DerivativeStructure q2DS;
379         final DerivativeStructure q3DS;
380         switch(order) {
381             case 0 :
382                 q0DS = new DerivativeStructure(1, 0, q0);
383                 q1DS = new DerivativeStructure(1, 0, q1);
384                 q2DS = new DerivativeStructure(1, 0, q2);
385                 q3DS = new DerivativeStructure(1, 0, q3);
386                 break;
387             case 1 :
388                 q0DS = new DerivativeStructure(1, 1, q0, q0Dot);
389                 q1DS = new DerivativeStructure(1, 1, q1, q1Dot);
390                 q2DS = new DerivativeStructure(1, 1, q2, q2Dot);
391                 q3DS = new DerivativeStructure(1, 1, q3, q3Dot);
392                 break;
393             case 2 :
394                 q0DS = new DerivativeStructure(1, 2, q0, q0Dot, q0DotDot);
395                 q1DS = new DerivativeStructure(1, 2, q1, q1Dot, q1DotDot);
396                 q2DS = new DerivativeStructure(1, 2, q2, q2Dot, q2DotDot);
397                 q3DS = new DerivativeStructure(1, 2, q3, q3Dot, q3DotDot);
398                 break;
399             default :
400                 throw new OrekitException(OrekitMessages.OUT_OF_RANGE_DERIVATION_ORDER, order);
401         }
402 
403         return new FieldRotation<DerivativeStructure>(q0DS, q1DS, q2DS, q3DS, false);
404 
405     }
406 
407     /** Estimate rotation rate between two orientations.
408      * <p>Estimation is based on a simple fixed rate rotation
409      * during the time interval between the two orientations.</p>
410      * @param start start orientation
411      * @param end end orientation
412      * @param dt time elapsed between the dates of the two orientations
413      * @return rotation rate allowing to go from start to end orientations
414      */
415     public static Vector3D estimateRate(final Rotation start, final Rotation end, final double dt) {
416         final Rotation evolution = start.compose(end.revert(), RotationConvention.VECTOR_OPERATOR);
417         return new Vector3D(evolution.getAngle() / dt, evolution.getAxis(RotationConvention.VECTOR_OPERATOR));
418     }
419 
420     /** Revert a rotation/rotation rate/ rotation acceleration triplet.
421      * Build a triplet which reverse the effect of another triplet.
422      * @return a new triplet whose effect is the reverse of the effect
423      * of the instance
424      */
425     public AngularCoordinates revert() {
426         return new AngularCoordinates(rotation.revert(),
427                                       rotation.applyInverseTo(rotationRate).negate(),
428                                       rotation.applyInverseTo(rotationAcceleration).negate());
429     }
430 
431     /** Get a time-shifted state.
432      * <p>
433      * The state can be slightly shifted to close dates. This shift is based on
434      * an approximate solution of the fixed acceleration motion. It is <em>not</em>
435      * intended as a replacement for proper attitude propagation but should be
436      * sufficient for either small time shifts or coarse accuracy.
437      * </p>
438      * @param dt time shift in seconds
439      * @return a new state, shifted with respect to the instance (which is immutable)
440      */
441     public AngularCoordinates shiftedBy(final double dt) {
442 
443         // the shiftedBy method is based on a local approximation.
444         // It considers separately the contribution of the constant
445         // rotation, the linear contribution or the rate and the
446         // quadratic contribution of the acceleration. The rate
447         // and acceleration contributions are small rotations as long
448         // as the time shift is small, which is the crux of the algorithm.
449         // Small rotations are almost commutative, so we append these small
450         // contributions one after the other, as if they really occurred
451         // successively, despite this is not what really happens.
452 
453         // compute the linear contribution first, ignoring acceleration
454         // BEWARE: there is really a minus sign here, because if
455         // the target frame rotates in one direction, the vectors in the origin
456         // frame seem to rotate in the opposite direction
457         final double rate = rotationRate.getNorm();
458         final Rotation rateContribution = (rate == 0.0) ?
459                                           Rotation.IDENTITY :
460                                           new Rotation(rotationRate, rate * dt, RotationConvention.FRAME_TRANSFORM);
461 
462         // append rotation and rate contribution
463         final AngularCoordinates linearPart =
464                 new AngularCoordinates(rateContribution.compose(rotation, RotationConvention.VECTOR_OPERATOR), rotationRate);
465 
466         final double acc  = rotationAcceleration.getNorm();
467         if (acc == 0.0) {
468             // no acceleration, the linear part is sufficient
469             return linearPart;
470         }
471 
472         // compute the quadratic contribution, ignoring initial rotation and rotation rate
473         // BEWARE: there is really a minus sign here, because if
474         // the target frame rotates in one direction, the vectors in the origin
475         // frame seem to rotate in the opposite direction
476         final AngularCoordinates quadraticContribution =
477                 new AngularCoordinates(new Rotation(rotationAcceleration,
478                                                     0.5 * acc * dt * dt,
479                                                     RotationConvention.FRAME_TRANSFORM),
480                                        new Vector3D(dt, rotationAcceleration),
481                                        rotationAcceleration);
482 
483         // the quadratic contribution is a small rotation:
484         // its initial angle and angular rate are both zero.
485         // small rotations are almost commutative, so we append the small
486         // quadratic part after the linear part as a simple offset
487         return quadraticContribution.addOffset(linearPart);
488 
489     }
490 
491     /** Get the rotation.
492      * @return the rotation.
493      */
494     public Rotation getRotation() {
495         return rotation;
496     }
497 
498     /** Get the rotation rate.
499      * @return the rotation rate vector Ω (rad/s).
500      */
501     public Vector3D getRotationRate() {
502         return rotationRate;
503     }
504 
505     /** Get the rotation acceleration.
506      * @return the rotation acceleration vector dΩ/dt (rad²/s²).
507      */
508     public Vector3D getRotationAcceleration() {
509         return rotationAcceleration;
510     }
511 
512     /** Add an offset from the instance.
513      * <p>
514      * We consider here that the offset rotation is applied first and the
515      * instance is applied afterward. Note that angular coordinates do <em>not</em>
516      * commute under this operation, i.e. {@code a.addOffset(b)} and {@code
517      * b.addOffset(a)} lead to <em>different</em> results in most cases.
518      * </p>
519      * <p>
520      * The two methods {@link #addOffset(AngularCoordinates) addOffset} and
521      * {@link #subtractOffset(AngularCoordinates) subtractOffset} are designed
522      * so that round trip applications are possible. This means that both {@code
523      * ac1.subtractOffset(ac2).addOffset(ac2)} and {@code
524      * ac1.addOffset(ac2).subtractOffset(ac2)} return angular coordinates equal to ac1.
525      * </p>
526      * @param offset offset to subtract
527      * @return new instance, with offset subtracted
528      * @see #subtractOffset(AngularCoordinates)
529      */
530     public AngularCoordinates addOffset(final AngularCoordinates offset) {
531         final Vector3D rOmega    = rotation.applyTo(offset.rotationRate);
532         final Vector3D rOmegaDot = rotation.applyTo(offset.rotationAcceleration);
533         return new AngularCoordinates(rotation.compose(offset.rotation, RotationConvention.VECTOR_OPERATOR),
534                                       rotationRate.add(rOmega),
535                                       new Vector3D( 1.0, rotationAcceleration,
536                                                     1.0, rOmegaDot,
537                                                    -1.0, Vector3D.crossProduct(rotationRate, rOmega)));
538     }
539 
540     /** Subtract an offset from the instance.
541      * <p>
542      * We consider here that the offset rotation is applied first and the
543      * instance is applied afterward. Note that angular coordinates do <em>not</em>
544      * commute under this operation, i.e. {@code a.subtractOffset(b)} and {@code
545      * b.subtractOffset(a)} lead to <em>different</em> results in most cases.
546      * </p>
547      * <p>
548      * The two methods {@link #addOffset(AngularCoordinates) addOffset} and
549      * {@link #subtractOffset(AngularCoordinates) subtractOffset} are designed
550      * so that round trip applications are possible. This means that both {@code
551      * ac1.subtractOffset(ac2).addOffset(ac2)} and {@code
552      * ac1.addOffset(ac2).subtractOffset(ac2)} return angular coordinates equal to ac1.
553      * </p>
554      * @param offset offset to subtract
555      * @return new instance, with offset subtracted
556      * @see #addOffset(AngularCoordinates)
557      */
558     public AngularCoordinates subtractOffset(final AngularCoordinates offset) {
559         return addOffset(offset.revert());
560     }
561 
562     /** Apply the rotation to a pv coordinates.
563      * @param pv vector to apply the rotation to
564      * @return a new pv coordinates which is the image of u by the rotation
565      */
566     public PVCoordinates applyTo(final PVCoordinates pv) {
567 
568         final Vector3D transformedP = rotation.applyTo(pv.getPosition());
569         final Vector3D crossP       = Vector3D.crossProduct(rotationRate, transformedP);
570         final Vector3D transformedV = rotation.applyTo(pv.getVelocity()).subtract(crossP);
571         final Vector3D crossV       = Vector3D.crossProduct(rotationRate, transformedV);
572         final Vector3D crossCrossP  = Vector3D.crossProduct(rotationRate, crossP);
573         final Vector3D crossDotP    = Vector3D.crossProduct(rotationAcceleration, transformedP);
574         final Vector3D transformedA = new Vector3D( 1, rotation.applyTo(pv.getAcceleration()),
575                                                    -2, crossV,
576                                                    -1, crossCrossP,
577                                                    -1, crossDotP);
578 
579         return new PVCoordinates(transformedP, transformedV, transformedA);
580 
581     }
582 
583     /** Apply the rotation to a pv coordinates.
584      * @param pv vector to apply the rotation to
585      * @return a new pv coordinates which is the image of u by the rotation
586      */
587     public TimeStampedPVCoordinates applyTo(final TimeStampedPVCoordinates pv) {
588 
589         final Vector3D transformedP = getRotation().applyTo(pv.getPosition());
590         final Vector3D crossP       = Vector3D.crossProduct(getRotationRate(), transformedP);
591         final Vector3D transformedV = getRotation().applyTo(pv.getVelocity()).subtract(crossP);
592         final Vector3D crossV       = Vector3D.crossProduct(getRotationRate(), transformedV);
593         final Vector3D crossCrossP  = Vector3D.crossProduct(getRotationRate(), crossP);
594         final Vector3D crossDotP    = Vector3D.crossProduct(getRotationAcceleration(), transformedP);
595         final Vector3D transformedA = new Vector3D( 1, getRotation().applyTo(pv.getAcceleration()),
596                                                    -2, crossV,
597                                                    -1, crossCrossP,
598                                                    -1, crossDotP);
599 
600         return new TimeStampedPVCoordinates(pv.getDate(), transformedP, transformedV, transformedA);
601 
602     }
603 
604     /** Convert rotation, rate and acceleration to modified Rodrigues vector and derivatives.
605      * <p>
606      * The modified Rodrigues vector is tan(θ/4) u where θ and u are the
607      * rotation angle and axis respectively.
608      * </p>
609      * @param sign multiplicative sign for quaternion components
610      * @return modified Rodrigues vector and derivatives (vector on row 0, first derivative
611      * on row 1, second derivative on row 2)
612      * @see #createFromModifiedRodrigues(double[][])
613      */
614     public double[][] getModifiedRodrigues(final double sign) {
615 
616         final double q0    = sign * getRotation().getQ0();
617         final double q1    = sign * getRotation().getQ1();
618         final double q2    = sign * getRotation().getQ2();
619         final double q3    = sign * getRotation().getQ3();
620         final double oX    = getRotationRate().getX();
621         final double oY    = getRotationRate().getY();
622         final double oZ    = getRotationRate().getZ();
623         final double oXDot = getRotationAcceleration().getX();
624         final double oYDot = getRotationAcceleration().getY();
625         final double oZDot = getRotationAcceleration().getZ();
626 
627         // first time-derivatives of the quaternion
628         final double q0Dot = 0.5 * MathArrays.linearCombination(-q1, oX, -q2, oY, -q3, oZ);
629         final double q1Dot = 0.5 * MathArrays.linearCombination( q0, oX, -q3, oY,  q2, oZ);
630         final double q2Dot = 0.5 * MathArrays.linearCombination( q3, oX,  q0, oY, -q1, oZ);
631         final double q3Dot = 0.5 * MathArrays.linearCombination(-q2, oX,  q1, oY,  q0, oZ);
632 
633         // second time-derivatives of the quaternion
634         final double q0DotDot = -0.5 * MathArrays.linearCombination(new double[] {
635             q1, q2,  q3, q1Dot, q2Dot,  q3Dot
636         }, new double[] {
637             oXDot, oYDot, oZDot, oX, oY, oZ
638         });
639         final double q1DotDot =  0.5 * MathArrays.linearCombination(new double[] {
640             q0, q2, -q3, q0Dot, q2Dot, -q3Dot
641         }, new double[] {
642             oXDot, oZDot, oYDot, oX, oZ, oY
643         });
644         final double q2DotDot =  0.5 * MathArrays.linearCombination(new double[] {
645             q0, q3, -q1, q0Dot, q3Dot, -q1Dot
646         }, new double[] {
647             oYDot, oXDot, oZDot, oY, oX, oZ
648         });
649         final double q3DotDot =  0.5 * MathArrays.linearCombination(new double[] {
650             q0, q1, -q2, q0Dot, q1Dot, -q2Dot
651         }, new double[] {
652             oZDot, oYDot, oXDot, oZ, oY, oX
653         });
654 
655         // the modified Rodrigues is tan(θ/4) u where θ and u are the rotation angle and axis respectively
656         // this can be rewritten using quaternion components:
657         //      r (q₁ / (1+q₀), q₂ / (1+q₀), q₃ / (1+q₀))
658         // applying the derivation chain rule to previous expression gives rDot and rDotDot
659         final double inv          = 1.0 / (1.0 + q0);
660         final double mTwoInvQ0Dot = -2 * inv * q0Dot;
661 
662         final double r1       = inv * q1;
663         final double r2       = inv * q2;
664         final double r3       = inv * q3;
665 
666         final double mInvR1   = -inv * r1;
667         final double mInvR2   = -inv * r2;
668         final double mInvR3   = -inv * r3;
669 
670         final double r1Dot    = MathArrays.linearCombination(inv, q1Dot, mInvR1, q0Dot);
671         final double r2Dot    = MathArrays.linearCombination(inv, q2Dot, mInvR2, q0Dot);
672         final double r3Dot    = MathArrays.linearCombination(inv, q3Dot, mInvR3, q0Dot);
673 
674         final double r1DotDot = MathArrays.linearCombination(inv, q1DotDot, mTwoInvQ0Dot, r1Dot, mInvR1, q0DotDot);
675         final double r2DotDot = MathArrays.linearCombination(inv, q2DotDot, mTwoInvQ0Dot, r2Dot, mInvR2, q0DotDot);
676         final double r3DotDot = MathArrays.linearCombination(inv, q3DotDot, mTwoInvQ0Dot, r3Dot, mInvR3, q0DotDot);
677 
678         return new double[][] {
679             {
680                 r1,       r2,       r3
681             }, {
682                 r1Dot,    r2Dot,    r3Dot
683             }, {
684                 r1DotDot, r2DotDot, r3DotDot
685             }
686         };
687 
688     }
689 
690     /** Convert a modified Rodrigues vector and derivatives to angular coordinates.
691      * @param r modified Rodrigues vector (with first and second times derivatives)
692      * @return angular coordinates
693      * @see #getModifiedRodrigues(double)
694      */
695     public static AngularCoordinates createFromModifiedRodrigues(final double[][] r) {
696 
697         // rotation
698         final double rSquared = r[0][0] * r[0][0] + r[0][1] * r[0][1] + r[0][2] * r[0][2];
699         final double oPQ0     = 2 / (1 + rSquared);
700         final double q0       = oPQ0 - 1;
701         final double q1       = oPQ0 * r[0][0];
702         final double q2       = oPQ0 * r[0][1];
703         final double q3       = oPQ0 * r[0][2];
704 
705         // rotation rate
706         final double oPQ02    = oPQ0 * oPQ0;
707         final double q0Dot    = -oPQ02 * MathArrays.linearCombination(r[0][0], r[1][0], r[0][1], r[1][1],  r[0][2], r[1][2]);
708         final double q1Dot    = oPQ0 * r[1][0] + r[0][0] * q0Dot;
709         final double q2Dot    = oPQ0 * r[1][1] + r[0][1] * q0Dot;
710         final double q3Dot    = oPQ0 * r[1][2] + r[0][2] * q0Dot;
711         final double oX       = 2 * MathArrays.linearCombination(-q1, q0Dot,  q0, q1Dot,  q3, q2Dot, -q2, q3Dot);
712         final double oY       = 2 * MathArrays.linearCombination(-q2, q0Dot, -q3, q1Dot,  q0, q2Dot,  q1, q3Dot);
713         final double oZ       = 2 * MathArrays.linearCombination(-q3, q0Dot,  q2, q1Dot, -q1, q2Dot,  q0, q3Dot);
714 
715         // rotation acceleration
716         final double q0DotDot = (1 - q0) / oPQ0 * q0Dot * q0Dot -
717                                 oPQ02 * MathArrays.linearCombination(r[0][0], r[2][0], r[0][1], r[2][1], r[0][2], r[2][2]) -
718                                 (q1Dot * q1Dot + q2Dot * q2Dot + q3Dot * q3Dot);
719         final double q1DotDot = MathArrays.linearCombination(oPQ0, r[2][0], 2 * r[1][0], q0Dot, r[0][0], q0DotDot);
720         final double q2DotDot = MathArrays.linearCombination(oPQ0, r[2][1], 2 * r[1][1], q0Dot, r[0][1], q0DotDot);
721         final double q3DotDot = MathArrays.linearCombination(oPQ0, r[2][2], 2 * r[1][2], q0Dot, r[0][2], q0DotDot);
722         final double oXDot    = 2 * MathArrays.linearCombination(-q1, q0DotDot,  q0, q1DotDot,  q3, q2DotDot, -q2, q3DotDot);
723         final double oYDot    = 2 * MathArrays.linearCombination(-q2, q0DotDot, -q3, q1DotDot,  q0, q2DotDot,  q1, q3DotDot);
724         final double oZDot    = 2 * MathArrays.linearCombination(-q3, q0DotDot,  q2, q1DotDot, -q1, q2DotDot,  q0, q3DotDot);
725 
726         return new AngularCoordinates(new Rotation(q0, q1, q2, q3, false),
727                                       new Vector3D(oX, oY, oZ),
728                                       new Vector3D(oXDot, oYDot, oZDot));
729 
730     }
731 
732 }