AngularCoordinates.java

  1. /* Copyright 2002-2020 CS GROUP
  2.  * Licensed to CS GROUP (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. import java.io.Serializable;

  19. import org.hipparchus.RealFieldElement;
  20. import org.hipparchus.analysis.differentiation.DSFactory;
  21. import org.hipparchus.analysis.differentiation.DerivativeStructure;
  22. import org.hipparchus.analysis.differentiation.UnivariateDerivative1;
  23. import org.hipparchus.exception.LocalizedCoreFormats;
  24. import org.hipparchus.exception.MathIllegalArgumentException;
  25. import org.hipparchus.exception.MathRuntimeException;
  26. import org.hipparchus.geometry.euclidean.threed.FieldRotation;
  27. import org.hipparchus.geometry.euclidean.threed.FieldVector3D;
  28. import org.hipparchus.geometry.euclidean.threed.Rotation;
  29. import org.hipparchus.geometry.euclidean.threed.RotationConvention;
  30. import org.hipparchus.geometry.euclidean.threed.Vector3D;
  31. import org.hipparchus.linear.DecompositionSolver;
  32. import org.hipparchus.linear.MatrixUtils;
  33. import org.hipparchus.linear.QRDecomposition;
  34. import org.hipparchus.linear.RealMatrix;
  35. import org.hipparchus.linear.RealVector;
  36. import org.hipparchus.util.FastMath;
  37. import org.hipparchus.util.MathArrays;
  38. import org.orekit.errors.OrekitException;
  39. import org.orekit.errors.OrekitMessages;
  40. import org.orekit.time.TimeShiftable;

  41. /** Simple container for rotation/rotation rate/rotation acceleration triplets.
  42.  * <p>
  43.  * The state can be slightly shifted to close dates. This shift is based on
  44.  * an approximate solution of the fixed acceleration motion. It is <em>not</em>
  45.  * intended as a replacement for proper attitude propagation but should be
  46.  * sufficient for either small time shifts or coarse accuracy.
  47.  * </p>
  48.  * <p>
  49.  * This class is the angular counterpart to {@link PVCoordinates}.
  50.  * </p>
  51.  * <p>Instances of this class are guaranteed to be immutable.</p>
  52.  * @author Luc Maisonobe
  53.  */
  54. public class AngularCoordinates implements TimeShiftable<AngularCoordinates>, Serializable {

  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.     /** Serializable UID. */
  61.     private static final long serialVersionUID = 20140414L;

  62.     /** Rotation. */
  63.     private final Rotation rotation;

  64.     /** Rotation rate. */
  65.     private final Vector3D rotationRate;

  66.     /** Rotation acceleration. */
  67.     private final Vector3D rotationAcceleration;

  68.     /** Simple constructor.
  69.      * <p> Sets the Coordinates to default : Identity, Ω = (0 0 0), dΩ/dt = (0 0 0).</p>
  70.      */
  71.     public AngularCoordinates() {
  72.         this(Rotation.IDENTITY, Vector3D.ZERO, Vector3D.ZERO);
  73.     }

  74.     /** Builds a rotation/rotation rate pair.
  75.      * @param rotation rotation
  76.      * @param rotationRate rotation rate Ω (rad/s)
  77.      */
  78.     public AngularCoordinates(final Rotation rotation, final Vector3D rotationRate) {
  79.         this(rotation, rotationRate, Vector3D.ZERO);
  80.     }

  81.     /** Builds a rotation/rotation rate/rotation acceleration triplet.
  82.      * @param rotation rotation
  83.      * @param rotationRate rotation rate Ω (rad/s)
  84.      * @param rotationAcceleration rotation acceleration dΩ/dt (rad²/s²)
  85.      */
  86.     public AngularCoordinates(final Rotation rotation,
  87.                               final Vector3D rotationRate, final Vector3D rotationAcceleration) {
  88.         this.rotation             = rotation;
  89.         this.rotationRate         = rotationRate;
  90.         this.rotationAcceleration = rotationAcceleration;
  91.     }

  92.     /** Build the rotation that transforms a pair of pv coordinates into another one.

  93.      * <p><em>WARNING</em>! This method requires much more stringent assumptions on
  94.      * its parameters than the similar {@link Rotation#Rotation(Vector3D, Vector3D,
  95.      * Vector3D, Vector3D) constructor} from the {@link Rotation Rotation} class.
  96.      * As far as the Rotation constructor is concerned, the {@code v₂} vector from
  97.      * the second pair can be slightly misaligned. The Rotation constructor will
  98.      * compensate for this misalignment and create a rotation that ensure {@code
  99.      * v₁ = r(u₁)} and {@code v₂ ∈ plane (r(u₁), r(u₂))}. <em>THIS IS NOT
  100.      * TRUE ANYMORE IN THIS CLASS</em>! As derivatives are involved and must be
  101.      * preserved, this constructor works <em>only</em> if the two pairs are fully
  102.      * consistent, i.e. if a rotation exists that fulfill all the requirements: {@code
  103.      * v₁ = r(u₁)}, {@code v₂ = r(u₂)}, {@code dv₁/dt = dr(u₁)/dt}, {@code dv₂/dt
  104.      * = dr(u₂)/dt}, {@code d²v₁/dt² = d²r(u₁)/dt²}, {@code d²v₂/dt² = d²r(u₂)/dt²}.</p>
  105.      * @param u1 first vector of the origin pair
  106.      * @param u2 second vector of the origin pair
  107.      * @param v1 desired image of u1 by the rotation
  108.      * @param v2 desired image of u2 by the rotation
  109.      * @param tolerance relative tolerance factor used to check singularities
  110.      */
  111.     public AngularCoordinates(final PVCoordinates u1, final PVCoordinates u2,
  112.                               final PVCoordinates v1, final PVCoordinates v2,
  113.                               final double tolerance) {

  114.         try {
  115.             // find the initial fixed rotation
  116.             rotation = new Rotation(u1.getPosition(), u2.getPosition(),
  117.                                     v1.getPosition(), v2.getPosition());

  118.             // find rotation rate Ω such that
  119.             //  Ω ⨯ v₁ = r(dot(u₁)) - dot(v₁)
  120.             //  Ω ⨯ v₂ = r(dot(u₂)) - dot(v₂)
  121.             final Vector3D ru1Dot = rotation.applyTo(u1.getVelocity());
  122.             final Vector3D ru2Dot = rotation.applyTo(u2.getVelocity());
  123.             rotationRate = inverseCrossProducts(v1.getPosition(), ru1Dot.subtract(v1.getVelocity()),
  124.                                                 v2.getPosition(), ru2Dot.subtract(v2.getVelocity()),
  125.                                                 tolerance);

  126.             // find rotation acceleration dot(Ω) such that
  127.             // dot(Ω) ⨯ v₁ = r(dotdot(u₁)) - 2 Ω ⨯ dot(v₁) - Ω ⨯  (Ω ⨯ v₁) - dotdot(v₁)
  128.             // dot(Ω) ⨯ v₂ = r(dotdot(u₂)) - 2 Ω ⨯ dot(v₂) - Ω ⨯  (Ω ⨯ v₂) - dotdot(v₂)
  129.             final Vector3D ru1DotDot = rotation.applyTo(u1.getAcceleration());
  130.             final Vector3D oDotv1    = Vector3D.crossProduct(rotationRate, v1.getVelocity());
  131.             final Vector3D oov1      = Vector3D.crossProduct(rotationRate, Vector3D.crossProduct(rotationRate, v1.getPosition()));
  132.             final Vector3D c1        = new Vector3D(1, ru1DotDot, -2, oDotv1, -1, oov1, -1, v1.getAcceleration());
  133.             final Vector3D ru2DotDot = rotation.applyTo(u2.getAcceleration());
  134.             final Vector3D oDotv2    = Vector3D.crossProduct(rotationRate, v2.getVelocity());
  135.             final Vector3D oov2      = Vector3D.crossProduct(rotationRate, Vector3D.crossProduct(rotationRate, v2.getPosition()));
  136.             final Vector3D c2        = new Vector3D(1, ru2DotDot, -2, oDotv2, -1, oov2, -1, v2.getAcceleration());
  137.             rotationAcceleration     = inverseCrossProducts(v1.getPosition(), c1, v2.getPosition(), c2, tolerance);

  138.         } catch (MathRuntimeException mrte) {
  139.             throw new OrekitException(mrte);
  140.         }

  141.     }

  142.     /** Build one of the rotations that transform one pv coordinates into another one.

  143.      * <p>Except for a possible scale factor, if the instance were
  144.      * applied to the vector u it will produce the vector v. There is an
  145.      * infinite number of such rotations, this constructor choose the
  146.      * one with the smallest associated angle (i.e. the one whose axis
  147.      * is orthogonal to the (u, v) plane). If u and v are collinear, an
  148.      * arbitrary rotation axis is chosen.</p>

  149.      * @param u origin vector
  150.      * @param v desired image of u by the rotation
  151.      */
  152.     public AngularCoordinates(final PVCoordinates u, final PVCoordinates v) {
  153.         this(new FieldRotation<>(u.toDerivativeStructureVector(2),
  154.                                  v.toDerivativeStructureVector(2)));
  155.     }

  156.     /** Builds a AngularCoordinates from  a {@link FieldRotation}&lt;{@link DerivativeStructure}&gt;.
  157.      * <p>
  158.      * The rotation components must have time as their only derivation parameter and
  159.      * have consistent derivation orders.
  160.      * </p>
  161.      * @param r rotation with time-derivatives embedded within the coordinates
  162.      */
  163.     public AngularCoordinates(final FieldRotation<DerivativeStructure> r) {

  164.         final double q0       = r.getQ0().getReal();
  165.         final double q1       = r.getQ1().getReal();
  166.         final double q2       = r.getQ2().getReal();
  167.         final double q3       = r.getQ3().getReal();

  168.         rotation     = new Rotation(q0, q1, q2, q3, false);
  169.         if (r.getQ0().getOrder() >= 1) {
  170.             final double q0Dot    = r.getQ0().getPartialDerivative(1);
  171.             final double q1Dot    = r.getQ1().getPartialDerivative(1);
  172.             final double q2Dot    = r.getQ2().getPartialDerivative(1);
  173.             final double q3Dot    = r.getQ3().getPartialDerivative(1);
  174.             rotationRate =
  175.                     new Vector3D(2 * MathArrays.linearCombination(-q1, q0Dot,  q0, q1Dot,  q3, q2Dot, -q2, q3Dot),
  176.                                  2 * MathArrays.linearCombination(-q2, q0Dot, -q3, q1Dot,  q0, q2Dot,  q1, q3Dot),
  177.                                  2 * MathArrays.linearCombination(-q3, q0Dot,  q2, q1Dot, -q1, q2Dot,  q0, q3Dot));
  178.             if (r.getQ0().getOrder() >= 2) {
  179.                 final double q0DotDot = r.getQ0().getPartialDerivative(2);
  180.                 final double q1DotDot = r.getQ1().getPartialDerivative(2);
  181.                 final double q2DotDot = r.getQ2().getPartialDerivative(2);
  182.                 final double q3DotDot = r.getQ3().getPartialDerivative(2);
  183.                 rotationAcceleration =
  184.                         new Vector3D(2 * MathArrays.linearCombination(-q1, q0DotDot,  q0, q1DotDot,  q3, q2DotDot, -q2, q3DotDot),
  185.                                      2 * MathArrays.linearCombination(-q2, q0DotDot, -q3, q1DotDot,  q0, q2DotDot,  q1, q3DotDot),
  186.                                      2 * MathArrays.linearCombination(-q3, q0DotDot,  q2, q1DotDot, -q1, q2DotDot,  q0, q3DotDot));
  187.             } else {
  188.                 rotationAcceleration = Vector3D.ZERO;
  189.             }
  190.         } else {
  191.             rotationRate         = Vector3D.ZERO;
  192.             rotationAcceleration = Vector3D.ZERO;
  193.         }

  194.     }

  195.     /** Find a vector from two known cross products.
  196.      * <p>
  197.      * We want to find Ω such that: Ω ⨯ v₁ = c₁ and Ω ⨯ v₂ = c₂
  198.      * </p>
  199.      * <p>
  200.      * The first equation (Ω ⨯ v₁ = c₁) will always be fulfilled exactly,
  201.      * and the second one will be fulfilled if possible.
  202.      * </p>
  203.      * @param v1 vector forming the first known cross product
  204.      * @param c1 know vector for cross product Ω ⨯ v₁
  205.      * @param v2 vector forming the second known cross product
  206.      * @param c2 know vector for cross product Ω ⨯ v₂
  207.      * @param tolerance relative tolerance factor used to check singularities
  208.      * @return vector Ω such that: Ω ⨯ v₁ = c₁ and Ω ⨯ v₂ = c₂
  209.      * @exception MathIllegalArgumentException if vectors are inconsistent and
  210.      * no solution can be found
  211.      */
  212.     private static Vector3D inverseCrossProducts(final Vector3D v1, final Vector3D c1,
  213.                                                  final Vector3D v2, final Vector3D c2,
  214.                                                  final double tolerance)
  215.         throws MathIllegalArgumentException {

  216.         final double v12 = v1.getNormSq();
  217.         final double v1n = FastMath.sqrt(v12);
  218.         final double v22 = v2.getNormSq();
  219.         final double v2n = FastMath.sqrt(v22);
  220.         final double threshold = tolerance * FastMath.max(v1n, v2n);

  221.         Vector3D omega;

  222.         try {
  223.             // create the over-determined linear system representing the two cross products
  224.             final RealMatrix m = MatrixUtils.createRealMatrix(6, 3);
  225.             m.setEntry(0, 1,  v1.getZ());
  226.             m.setEntry(0, 2, -v1.getY());
  227.             m.setEntry(1, 0, -v1.getZ());
  228.             m.setEntry(1, 2,  v1.getX());
  229.             m.setEntry(2, 0,  v1.getY());
  230.             m.setEntry(2, 1, -v1.getX());
  231.             m.setEntry(3, 1,  v2.getZ());
  232.             m.setEntry(3, 2, -v2.getY());
  233.             m.setEntry(4, 0, -v2.getZ());
  234.             m.setEntry(4, 2,  v2.getX());
  235.             m.setEntry(5, 0,  v2.getY());
  236.             m.setEntry(5, 1, -v2.getX());

  237.             final RealVector rhs = MatrixUtils.createRealVector(new double[] {
  238.                 c1.getX(), c1.getY(), c1.getZ(),
  239.                 c2.getX(), c2.getY(), c2.getZ()
  240.             });

  241.             // find the best solution we can
  242.             final DecompositionSolver solver = new QRDecomposition(m, threshold).getSolver();
  243.             final RealVector v = solver.solve(rhs);
  244.             omega = new Vector3D(v.getEntry(0), v.getEntry(1), v.getEntry(2));

  245.         } catch (MathIllegalArgumentException miae) {
  246.             if (miae.getSpecifier() == LocalizedCoreFormats.SINGULAR_MATRIX) {

  247.                 // handle some special cases for which we can compute a solution
  248.                 final double c12 = c1.getNormSq();
  249.                 final double c1n = FastMath.sqrt(c12);
  250.                 final double c22 = c2.getNormSq();
  251.                 final double c2n = FastMath.sqrt(c22);

  252.                 if (c1n <= threshold && c2n <= threshold) {
  253.                     // simple special case, velocities are cancelled
  254.                     return Vector3D.ZERO;
  255.                 } else if (v1n <= threshold && c1n >= threshold) {
  256.                     // this is inconsistent, if v₁ is zero, c₁ must be 0 too
  257.                     throw new MathIllegalArgumentException(LocalizedCoreFormats.NUMBER_TOO_LARGE, c1n, 0, true);
  258.                 } else if (v2n <= threshold && c2n >= threshold) {
  259.                     // this is inconsistent, if v₂ is zero, c₂ must be 0 too
  260.                     throw new MathIllegalArgumentException(LocalizedCoreFormats.NUMBER_TOO_LARGE, c2n, 0, true);
  261.                 } else if (Vector3D.crossProduct(v1, v2).getNorm() <= threshold && v12 > threshold) {
  262.                     // simple special case, v₂ is redundant with v₁, we just ignore it
  263.                     // use the simplest Ω: orthogonal to both v₁ and c₁
  264.                     omega = new Vector3D(1.0 / v12, Vector3D.crossProduct(v1, c1));
  265.                 } else {
  266.                     throw miae;
  267.                 }
  268.             } else {
  269.                 throw miae;
  270.             }

  271.         }

  272.         // check results
  273.         final double d1 = Vector3D.distance(Vector3D.crossProduct(omega, v1), c1);
  274.         if (d1 > threshold) {
  275.             throw new MathIllegalArgumentException(LocalizedCoreFormats.NUMBER_TOO_LARGE, d1, 0, true);
  276.         }

  277.         final double d2 = Vector3D.distance(Vector3D.crossProduct(omega, v2), c2);
  278.         if (d2 > threshold) {
  279.             throw new MathIllegalArgumentException(LocalizedCoreFormats.NUMBER_TOO_LARGE, d2, 0, true);
  280.         }

  281.         return omega;

  282.     }

  283.     /** Transform the instance to a {@link FieldRotation}&lt;{@link DerivativeStructure}&gt;.
  284.      * <p>
  285.      * The {@link DerivativeStructure} coordinates correspond to time-derivatives up
  286.      * to the user-specified order.
  287.      * </p>
  288.      * @param order derivation order for the vector components
  289.      * @return rotation with time-derivatives embedded within the coordinates
  290.      */
  291.     public FieldRotation<DerivativeStructure> toDerivativeStructureRotation(final int order) {

  292.         // quaternion components
  293.         final double q0 = rotation.getQ0();
  294.         final double q1 = rotation.getQ1();
  295.         final double q2 = rotation.getQ2();
  296.         final double q3 = rotation.getQ3();

  297.         // first time-derivatives of the quaternion
  298.         final double oX    = rotationRate.getX();
  299.         final double oY    = rotationRate.getY();
  300.         final double oZ    = rotationRate.getZ();
  301.         final double q0Dot = 0.5 * MathArrays.linearCombination(-q1, oX, -q2, oY, -q3, oZ);
  302.         final double q1Dot = 0.5 * MathArrays.linearCombination( q0, oX, -q3, oY,  q2, oZ);
  303.         final double q2Dot = 0.5 * MathArrays.linearCombination( q3, oX,  q0, oY, -q1, oZ);
  304.         final double q3Dot = 0.5 * MathArrays.linearCombination(-q2, oX,  q1, oY,  q0, oZ);

  305.         // second time-derivatives of the quaternion
  306.         final double oXDot = rotationAcceleration.getX();
  307.         final double oYDot = rotationAcceleration.getY();
  308.         final double oZDot = rotationAcceleration.getZ();
  309.         final double q0DotDot = -0.5 * MathArrays.linearCombination(new double[] {
  310.             q1, q2,  q3, q1Dot, q2Dot,  q3Dot
  311.         }, new double[] {
  312.             oXDot, oYDot, oZDot, oX, oY, oZ
  313.         });
  314.         final double q1DotDot =  0.5 * MathArrays.linearCombination(new double[] {
  315.             q0, q2, -q3, q0Dot, q2Dot, -q3Dot
  316.         }, new double[] {
  317.             oXDot, oZDot, oYDot, oX, oZ, oY
  318.         });
  319.         final double q2DotDot =  0.5 * MathArrays.linearCombination(new double[] {
  320.             q0, q3, -q1, q0Dot, q3Dot, -q1Dot
  321.         }, new double[] {
  322.             oYDot, oXDot, oZDot, oY, oX, oZ
  323.         });
  324.         final double q3DotDot =  0.5 * MathArrays.linearCombination(new double[] {
  325.             q0, q1, -q2, q0Dot, q1Dot, -q2Dot
  326.         }, new double[] {
  327.             oZDot, oYDot, oXDot, oZ, oY, oX
  328.         });

  329.         final DSFactory factory;
  330.         final DerivativeStructure q0DS;
  331.         final DerivativeStructure q1DS;
  332.         final DerivativeStructure q2DS;
  333.         final DerivativeStructure q3DS;
  334.         switch(order) {
  335.             case 0 :
  336.                 factory = new DSFactory(1, order);
  337.                 q0DS = factory.build(q0);
  338.                 q1DS = factory.build(q1);
  339.                 q2DS = factory.build(q2);
  340.                 q3DS = factory.build(q3);
  341.                 break;
  342.             case 1 :
  343.                 factory = new DSFactory(1, order);
  344.                 q0DS = factory.build(q0, q0Dot);
  345.                 q1DS = factory.build(q1, q1Dot);
  346.                 q2DS = factory.build(q2, q2Dot);
  347.                 q3DS = factory.build(q3, q3Dot);
  348.                 break;
  349.             case 2 :
  350.                 factory = new DSFactory(1, order);
  351.                 q0DS = factory.build(q0, q0Dot, q0DotDot);
  352.                 q1DS = factory.build(q1, q1Dot, q1DotDot);
  353.                 q2DS = factory.build(q2, q2Dot, q2DotDot);
  354.                 q3DS = factory.build(q3, q3Dot, q3DotDot);
  355.                 break;
  356.             default :
  357.                 throw new OrekitException(OrekitMessages.OUT_OF_RANGE_DERIVATION_ORDER, order);
  358.         }

  359.         return new FieldRotation<>(q0DS, q1DS, q2DS, q3DS, false);

  360.     }

  361.     /** Transform the instance to a {@link FieldRotation}&lt;{@link UnivariateDerivative1}&gt;.
  362.      * <p>
  363.      * The {@link UnivariateDerivative1} coordinates correspond to time-derivatives up
  364.      * to the order 1.
  365.      * </p>
  366.      * @return rotation with time-derivatives embedded within the coordinates
  367.      */
  368.     public FieldRotation<UnivariateDerivative1> toUnivariateDerivative1Rotation() {

  369.         // quaternion components
  370.         final double q0 = rotation.getQ0();
  371.         final double q1 = rotation.getQ1();
  372.         final double q2 = rotation.getQ2();
  373.         final double q3 = rotation.getQ3();

  374.         // first time-derivatives of the quaternion
  375.         final double oX    = rotationRate.getX();
  376.         final double oY    = rotationRate.getY();
  377.         final double oZ    = rotationRate.getZ();
  378.         final double q0Dot = 0.5 * MathArrays.linearCombination(-q1, oX, -q2, oY, -q3, oZ);
  379.         final double q1Dot = 0.5 * MathArrays.linearCombination( q0, oX, -q3, oY,  q2, oZ);
  380.         final double q2Dot = 0.5 * MathArrays.linearCombination( q3, oX,  q0, oY, -q1, oZ);
  381.         final double q3Dot = 0.5 * MathArrays.linearCombination(-q2, oX,  q1, oY,  q0, oZ);

  382.         final UnivariateDerivative1 q0UD = new UnivariateDerivative1(q0, q0Dot);
  383.         final UnivariateDerivative1 q1UD = new UnivariateDerivative1(q1, q1Dot);
  384.         final UnivariateDerivative1 q2UD = new UnivariateDerivative1(q2, q2Dot);
  385.         final UnivariateDerivative1 q3UD = new UnivariateDerivative1(q3, q3Dot);

  386.         return new FieldRotation<>(q0UD, q1UD, q2UD, q3UD, false);

  387.     }

  388.     /** Estimate rotation rate between two orientations.
  389.      * <p>Estimation is based on a simple fixed rate rotation
  390.      * during the time interval between the two orientations.</p>
  391.      * @param start start orientation
  392.      * @param end end orientation
  393.      * @param dt time elapsed between the dates of the two orientations
  394.      * @return rotation rate allowing to go from start to end orientations
  395.      */
  396.     public static Vector3D estimateRate(final Rotation start, final Rotation end, final double dt) {
  397.         final Rotation evolution = start.compose(end.revert(), RotationConvention.VECTOR_OPERATOR);
  398.         return new Vector3D(evolution.getAngle() / dt, evolution.getAxis(RotationConvention.VECTOR_OPERATOR));
  399.     }

  400.     /** Revert a rotation/rotation rate/ rotation acceleration triplet.
  401.      * Build a triplet which reverse the effect of another triplet.
  402.      * @return a new triplet whose effect is the reverse of the effect
  403.      * of the instance
  404.      */
  405.     public AngularCoordinates revert() {
  406.         return new AngularCoordinates(rotation.revert(),
  407.                                       rotation.applyInverseTo(rotationRate).negate(),
  408.                                       rotation.applyInverseTo(rotationAcceleration).negate());
  409.     }

  410.     /** Get a time-shifted state.
  411.      * <p>
  412.      * The state can be slightly shifted to close dates. This shift is based on
  413.      * an approximate solution of the fixed acceleration motion. It is <em>not</em>
  414.      * intended as a replacement for proper attitude propagation but should be
  415.      * sufficient for either small time shifts or coarse accuracy.
  416.      * </p>
  417.      * @param dt time shift in seconds
  418.      * @return a new state, shifted with respect to the instance (which is immutable)
  419.      */
  420.     public AngularCoordinates shiftedBy(final double dt) {

  421.         // the shiftedBy method is based on a local approximation.
  422.         // It considers separately the contribution of the constant
  423.         // rotation, the linear contribution or the rate and the
  424.         // quadratic contribution of the acceleration. The rate
  425.         // and acceleration contributions are small rotations as long
  426.         // as the time shift is small, which is the crux of the algorithm.
  427.         // Small rotations are almost commutative, so we append these small
  428.         // contributions one after the other, as if they really occurred
  429.         // successively, despite this is not what really happens.

  430.         // compute the linear contribution first, ignoring acceleration
  431.         // BEWARE: there is really a minus sign here, because if
  432.         // the target frame rotates in one direction, the vectors in the origin
  433.         // frame seem to rotate in the opposite direction
  434.         final double rate = rotationRate.getNorm();
  435.         final Rotation rateContribution = (rate == 0.0) ?
  436.                                           Rotation.IDENTITY :
  437.                                           new Rotation(rotationRate, rate * dt, RotationConvention.FRAME_TRANSFORM);

  438.         // append rotation and rate contribution
  439.         final AngularCoordinates linearPart =
  440.                 new AngularCoordinates(rateContribution.compose(rotation, RotationConvention.VECTOR_OPERATOR), rotationRate);

  441.         final double acc  = rotationAcceleration.getNorm();
  442.         if (acc == 0.0) {
  443.             // no acceleration, the linear part is sufficient
  444.             return linearPart;
  445.         }

  446.         // compute the quadratic contribution, ignoring initial rotation and rotation rate
  447.         // BEWARE: there is really a minus sign here, because if
  448.         // the target frame rotates in one direction, the vectors in the origin
  449.         // frame seem to rotate in the opposite direction
  450.         final AngularCoordinates quadraticContribution =
  451.                 new AngularCoordinates(new Rotation(rotationAcceleration,
  452.                                                     0.5 * acc * dt * dt,
  453.                                                     RotationConvention.FRAME_TRANSFORM),
  454.                                        new Vector3D(dt, rotationAcceleration),
  455.                                        rotationAcceleration);

  456.         // the quadratic contribution is a small rotation:
  457.         // its initial angle and angular rate are both zero.
  458.         // small rotations are almost commutative, so we append the small
  459.         // quadratic part after the linear part as a simple offset
  460.         return quadraticContribution.addOffset(linearPart);

  461.     }

  462.     /** Get the rotation.
  463.      * @return the rotation.
  464.      */
  465.     public Rotation getRotation() {
  466.         return rotation;
  467.     }

  468.     /** Get the rotation rate.
  469.      * @return the rotation rate vector Ω (rad/s).
  470.      */
  471.     public Vector3D getRotationRate() {
  472.         return rotationRate;
  473.     }

  474.     /** Get the rotation acceleration.
  475.      * @return the rotation acceleration vector dΩ/dt (rad²/s²).
  476.      */
  477.     public Vector3D getRotationAcceleration() {
  478.         return rotationAcceleration;
  479.     }

  480.     /** Add an offset from the instance.
  481.      * <p>
  482.      * We consider here that the offset rotation is applied first and the
  483.      * instance is applied afterward. Note that angular coordinates do <em>not</em>
  484.      * commute under this operation, i.e. {@code a.addOffset(b)} and {@code
  485.      * b.addOffset(a)} lead to <em>different</em> results in most cases.
  486.      * </p>
  487.      * <p>
  488.      * The two methods {@link #addOffset(AngularCoordinates) addOffset} and
  489.      * {@link #subtractOffset(AngularCoordinates) subtractOffset} are designed
  490.      * so that round trip applications are possible. This means that both {@code
  491.      * ac1.subtractOffset(ac2).addOffset(ac2)} and {@code
  492.      * ac1.addOffset(ac2).subtractOffset(ac2)} return angular coordinates equal to ac1.
  493.      * </p>
  494.      * @param offset offset to subtract
  495.      * @return new instance, with offset subtracted
  496.      * @see #subtractOffset(AngularCoordinates)
  497.      */
  498.     public AngularCoordinates addOffset(final AngularCoordinates offset) {
  499.         final Vector3D rOmega    = rotation.applyTo(offset.rotationRate);
  500.         final Vector3D rOmegaDot = rotation.applyTo(offset.rotationAcceleration);
  501.         return new AngularCoordinates(rotation.compose(offset.rotation, RotationConvention.VECTOR_OPERATOR),
  502.                                       rotationRate.add(rOmega),
  503.                                       new Vector3D( 1.0, rotationAcceleration,
  504.                                                     1.0, rOmegaDot,
  505.                                                    -1.0, Vector3D.crossProduct(rotationRate, rOmega)));
  506.     }

  507.     /** Subtract an offset from the instance.
  508.      * <p>
  509.      * We consider here that the offset rotation is applied first and the
  510.      * instance is applied afterward. Note that angular coordinates do <em>not</em>
  511.      * commute under this operation, i.e. {@code a.subtractOffset(b)} and {@code
  512.      * b.subtractOffset(a)} lead to <em>different</em> results in most cases.
  513.      * </p>
  514.      * <p>
  515.      * The two methods {@link #addOffset(AngularCoordinates) addOffset} and
  516.      * {@link #subtractOffset(AngularCoordinates) subtractOffset} are designed
  517.      * so that round trip applications are possible. This means that both {@code
  518.      * ac1.subtractOffset(ac2).addOffset(ac2)} and {@code
  519.      * ac1.addOffset(ac2).subtractOffset(ac2)} return angular coordinates equal to ac1.
  520.      * </p>
  521.      * @param offset offset to subtract
  522.      * @return new instance, with offset subtracted
  523.      * @see #addOffset(AngularCoordinates)
  524.      */
  525.     public AngularCoordinates subtractOffset(final AngularCoordinates offset) {
  526.         return addOffset(offset.revert());
  527.     }

  528.     /** Apply the rotation to a pv coordinates.
  529.      * @param pv vector to apply the rotation to
  530.      * @return a new pv coordinates which is the image of u by the rotation
  531.      */
  532.     public PVCoordinates applyTo(final PVCoordinates pv) {

  533.         final Vector3D transformedP = rotation.applyTo(pv.getPosition());
  534.         final Vector3D crossP       = Vector3D.crossProduct(rotationRate, transformedP);
  535.         final Vector3D transformedV = rotation.applyTo(pv.getVelocity()).subtract(crossP);
  536.         final Vector3D crossV       = Vector3D.crossProduct(rotationRate, transformedV);
  537.         final Vector3D crossCrossP  = Vector3D.crossProduct(rotationRate, crossP);
  538.         final Vector3D crossDotP    = Vector3D.crossProduct(rotationAcceleration, transformedP);
  539.         final Vector3D transformedA = new Vector3D( 1, rotation.applyTo(pv.getAcceleration()),
  540.                                                    -2, crossV,
  541.                                                    -1, crossCrossP,
  542.                                                    -1, crossDotP);

  543.         return new PVCoordinates(transformedP, transformedV, transformedA);

  544.     }

  545.     /** Apply the rotation to a pv coordinates.
  546.      * @param pv vector to apply the rotation to
  547.      * @return a new pv coordinates which is the image of u by the rotation
  548.      */
  549.     public TimeStampedPVCoordinates applyTo(final TimeStampedPVCoordinates pv) {

  550.         final Vector3D transformedP = getRotation().applyTo(pv.getPosition());
  551.         final Vector3D crossP       = Vector3D.crossProduct(getRotationRate(), transformedP);
  552.         final Vector3D transformedV = getRotation().applyTo(pv.getVelocity()).subtract(crossP);
  553.         final Vector3D crossV       = Vector3D.crossProduct(getRotationRate(), transformedV);
  554.         final Vector3D crossCrossP  = Vector3D.crossProduct(getRotationRate(), crossP);
  555.         final Vector3D crossDotP    = Vector3D.crossProduct(getRotationAcceleration(), transformedP);
  556.         final Vector3D transformedA = new Vector3D( 1, getRotation().applyTo(pv.getAcceleration()),
  557.                                                    -2, crossV,
  558.                                                    -1, crossCrossP,
  559.                                                    -1, crossDotP);

  560.         return new TimeStampedPVCoordinates(pv.getDate(), transformedP, transformedV, transformedA);

  561.     }

  562.     /** Apply the rotation to a pv coordinates.
  563.      * @param pv vector to apply the rotation to
  564.      * @param <T> type of the field elements
  565.      * @return a new pv coordinates which is the image of u by the rotation
  566.      * @since 9.0
  567.      */
  568.     public <T extends RealFieldElement<T>> FieldPVCoordinates<T> applyTo(final FieldPVCoordinates<T> pv) {

  569.         final FieldVector3D<T> transformedP = FieldRotation.applyTo(rotation, pv.getPosition());
  570.         final FieldVector3D<T> crossP       = FieldVector3D.crossProduct(rotationRate, transformedP);
  571.         final FieldVector3D<T> transformedV = FieldRotation.applyTo(rotation, pv.getVelocity()).subtract(crossP);
  572.         final FieldVector3D<T> crossV       = FieldVector3D.crossProduct(rotationRate, transformedV);
  573.         final FieldVector3D<T> crossCrossP  = FieldVector3D.crossProduct(rotationRate, crossP);
  574.         final FieldVector3D<T> crossDotP    = FieldVector3D.crossProduct(rotationAcceleration, transformedP);
  575.         final FieldVector3D<T> transformedA = new FieldVector3D<>( 1, FieldRotation.applyTo(rotation, pv.getAcceleration()),
  576.                                                                   -2, crossV,
  577.                                                                   -1, crossCrossP,
  578.                                                                   -1, crossDotP);

  579.         return new FieldPVCoordinates<>(transformedP, transformedV, transformedA);

  580.     }

  581.     /** Apply the rotation to a pv coordinates.
  582.      * @param pv vector to apply the rotation to
  583.      * @param <T> type of the field elements
  584.      * @return a new pv coordinates which is the image of u by the rotation
  585.      * @since 9.0
  586.      */
  587.     public <T extends RealFieldElement<T>> TimeStampedFieldPVCoordinates<T> applyTo(final TimeStampedFieldPVCoordinates<T> pv) {

  588.         final FieldVector3D<T> transformedP = FieldRotation.applyTo(rotation, pv.getPosition());
  589.         final FieldVector3D<T> crossP       = FieldVector3D.crossProduct(rotationRate, transformedP);
  590.         final FieldVector3D<T> transformedV = FieldRotation.applyTo(rotation, pv.getVelocity()).subtract(crossP);
  591.         final FieldVector3D<T> crossV       = FieldVector3D.crossProduct(rotationRate, transformedV);
  592.         final FieldVector3D<T> crossCrossP  = FieldVector3D.crossProduct(rotationRate, crossP);
  593.         final FieldVector3D<T> crossDotP    = FieldVector3D.crossProduct(rotationAcceleration, transformedP);
  594.         final FieldVector3D<T> transformedA = new FieldVector3D<>( 1, FieldRotation.applyTo(rotation, pv.getAcceleration()),
  595.                                                                   -2, crossV,
  596.                                                                   -1, crossCrossP,
  597.                                                                   -1, crossDotP);

  598.         return new TimeStampedFieldPVCoordinates<>(pv.getDate(), transformedP, transformedV, transformedA);

  599.     }

  600.     /** Convert rotation, rate and acceleration to modified Rodrigues vector and derivatives.
  601.      * <p>
  602.      * The modified Rodrigues vector is tan(θ/4) u where θ and u are the
  603.      * rotation angle and axis respectively.
  604.      * </p>
  605.      * @param sign multiplicative sign for quaternion components
  606.      * @return modified Rodrigues vector and derivatives (vector on row 0, first derivative
  607.      * on row 1, second derivative on row 2)
  608.      * @see #createFromModifiedRodrigues(double[][])
  609.      */
  610.     public double[][] getModifiedRodrigues(final double sign) {

  611.         final double q0    = sign * getRotation().getQ0();
  612.         final double q1    = sign * getRotation().getQ1();
  613.         final double q2    = sign * getRotation().getQ2();
  614.         final double q3    = sign * getRotation().getQ3();
  615.         final double oX    = getRotationRate().getX();
  616.         final double oY    = getRotationRate().getY();
  617.         final double oZ    = getRotationRate().getZ();
  618.         final double oXDot = getRotationAcceleration().getX();
  619.         final double oYDot = getRotationAcceleration().getY();
  620.         final double oZDot = getRotationAcceleration().getZ();

  621.         // first time-derivatives of the quaternion
  622.         final double q0Dot = 0.5 * MathArrays.linearCombination(-q1, oX, -q2, oY, -q3, oZ);
  623.         final double q1Dot = 0.5 * MathArrays.linearCombination( q0, oX, -q3, oY,  q2, oZ);
  624.         final double q2Dot = 0.5 * MathArrays.linearCombination( q3, oX,  q0, oY, -q1, oZ);
  625.         final double q3Dot = 0.5 * MathArrays.linearCombination(-q2, oX,  q1, oY,  q0, oZ);

  626.         // second time-derivatives of the quaternion
  627.         final double q0DotDot = -0.5 * MathArrays.linearCombination(new double[] {
  628.             q1, q2,  q3, q1Dot, q2Dot,  q3Dot
  629.         }, new double[] {
  630.             oXDot, oYDot, oZDot, oX, oY, oZ
  631.         });
  632.         final double q1DotDot =  0.5 * MathArrays.linearCombination(new double[] {
  633.             q0, q2, -q3, q0Dot, q2Dot, -q3Dot
  634.         }, new double[] {
  635.             oXDot, oZDot, oYDot, oX, oZ, oY
  636.         });
  637.         final double q2DotDot =  0.5 * MathArrays.linearCombination(new double[] {
  638.             q0, q3, -q1, q0Dot, q3Dot, -q1Dot
  639.         }, new double[] {
  640.             oYDot, oXDot, oZDot, oY, oX, oZ
  641.         });
  642.         final double q3DotDot =  0.5 * MathArrays.linearCombination(new double[] {
  643.             q0, q1, -q2, q0Dot, q1Dot, -q2Dot
  644.         }, new double[] {
  645.             oZDot, oYDot, oXDot, oZ, oY, oX
  646.         });

  647.         // the modified Rodrigues is tan(θ/4) u where θ and u are the rotation angle and axis respectively
  648.         // this can be rewritten using quaternion components:
  649.         //      r (q₁ / (1+q₀), q₂ / (1+q₀), q₃ / (1+q₀))
  650.         // applying the derivation chain rule to previous expression gives rDot and rDotDot
  651.         final double inv          = 1.0 / (1.0 + q0);
  652.         final double mTwoInvQ0Dot = -2 * inv * q0Dot;

  653.         final double r1       = inv * q1;
  654.         final double r2       = inv * q2;
  655.         final double r3       = inv * q3;

  656.         final double mInvR1   = -inv * r1;
  657.         final double mInvR2   = -inv * r2;
  658.         final double mInvR3   = -inv * r3;

  659.         final double r1Dot    = MathArrays.linearCombination(inv, q1Dot, mInvR1, q0Dot);
  660.         final double r2Dot    = MathArrays.linearCombination(inv, q2Dot, mInvR2, q0Dot);
  661.         final double r3Dot    = MathArrays.linearCombination(inv, q3Dot, mInvR3, q0Dot);

  662.         final double r1DotDot = MathArrays.linearCombination(inv, q1DotDot, mTwoInvQ0Dot, r1Dot, mInvR1, q0DotDot);
  663.         final double r2DotDot = MathArrays.linearCombination(inv, q2DotDot, mTwoInvQ0Dot, r2Dot, mInvR2, q0DotDot);
  664.         final double r3DotDot = MathArrays.linearCombination(inv, q3DotDot, mTwoInvQ0Dot, r3Dot, mInvR3, q0DotDot);

  665.         return new double[][] {
  666.             {
  667.                 r1,       r2,       r3
  668.             }, {
  669.                 r1Dot,    r2Dot,    r3Dot
  670.             }, {
  671.                 r1DotDot, r2DotDot, r3DotDot
  672.             }
  673.         };

  674.     }

  675.     /** Convert a modified Rodrigues vector and derivatives to angular coordinates.
  676.      * @param r modified Rodrigues vector (with first and second times derivatives)
  677.      * @return angular coordinates
  678.      * @see #getModifiedRodrigues(double)
  679.      */
  680.     public static AngularCoordinates createFromModifiedRodrigues(final double[][] r) {

  681.         // rotation
  682.         final double rSquared = r[0][0] * r[0][0] + r[0][1] * r[0][1] + r[0][2] * r[0][2];
  683.         final double oPQ0     = 2 / (1 + rSquared);
  684.         final double q0       = oPQ0 - 1;
  685.         final double q1       = oPQ0 * r[0][0];
  686.         final double q2       = oPQ0 * r[0][1];
  687.         final double q3       = oPQ0 * r[0][2];

  688.         // rotation rate
  689.         final double oPQ02    = oPQ0 * oPQ0;
  690.         final double q0Dot    = -oPQ02 * MathArrays.linearCombination(r[0][0], r[1][0], r[0][1], r[1][1],  r[0][2], r[1][2]);
  691.         final double q1Dot    = oPQ0 * r[1][0] + r[0][0] * q0Dot;
  692.         final double q2Dot    = oPQ0 * r[1][1] + r[0][1] * q0Dot;
  693.         final double q3Dot    = oPQ0 * r[1][2] + r[0][2] * q0Dot;
  694.         final double oX       = 2 * MathArrays.linearCombination(-q1, q0Dot,  q0, q1Dot,  q3, q2Dot, -q2, q3Dot);
  695.         final double oY       = 2 * MathArrays.linearCombination(-q2, q0Dot, -q3, q1Dot,  q0, q2Dot,  q1, q3Dot);
  696.         final double oZ       = 2 * MathArrays.linearCombination(-q3, q0Dot,  q2, q1Dot, -q1, q2Dot,  q0, q3Dot);

  697.         // rotation acceleration
  698.         final double q0DotDot = (1 - q0) / oPQ0 * q0Dot * q0Dot -
  699.                                 oPQ02 * MathArrays.linearCombination(r[0][0], r[2][0], r[0][1], r[2][1], r[0][2], r[2][2]) -
  700.                                 (q1Dot * q1Dot + q2Dot * q2Dot + q3Dot * q3Dot);
  701.         final double q1DotDot = MathArrays.linearCombination(oPQ0, r[2][0], 2 * r[1][0], q0Dot, r[0][0], q0DotDot);
  702.         final double q2DotDot = MathArrays.linearCombination(oPQ0, r[2][1], 2 * r[1][1], q0Dot, r[0][1], q0DotDot);
  703.         final double q3DotDot = MathArrays.linearCombination(oPQ0, r[2][2], 2 * r[1][2], q0Dot, r[0][2], q0DotDot);
  704.         final double oXDot    = 2 * MathArrays.linearCombination(-q1, q0DotDot,  q0, q1DotDot,  q3, q2DotDot, -q2, q3DotDot);
  705.         final double oYDot    = 2 * MathArrays.linearCombination(-q2, q0DotDot, -q3, q1DotDot,  q0, q2DotDot,  q1, q3DotDot);
  706.         final double oZDot    = 2 * MathArrays.linearCombination(-q3, q0DotDot,  q2, q1DotDot, -q1, q2DotDot,  q0, q3DotDot);

  707.         return new AngularCoordinates(new Rotation(q0, q1, q2, q3, false),
  708.                                       new Vector3D(oX, oY, oZ),
  709.                                       new Vector3D(oXDot, oYDot, oZDot));

  710.     }

  711. }