AngularCoordinates.java

  1. /* Copyright 2002-2022 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.CalculusFieldElement;
  20. import org.hipparchus.analysis.differentiation.DSFactory;
  21. import org.hipparchus.analysis.differentiation.Derivative;
  22. import org.hipparchus.analysis.differentiation.DerivativeStructure;
  23. import org.hipparchus.analysis.differentiation.UnivariateDerivative1;
  24. import org.hipparchus.analysis.differentiation.UnivariateDerivative2;
  25. import org.hipparchus.exception.LocalizedCoreFormats;
  26. import org.hipparchus.exception.MathIllegalArgumentException;
  27. import org.hipparchus.exception.MathRuntimeException;
  28. import org.hipparchus.geometry.euclidean.threed.FieldRotation;
  29. import org.hipparchus.geometry.euclidean.threed.FieldVector3D;
  30. import org.hipparchus.geometry.euclidean.threed.Rotation;
  31. import org.hipparchus.geometry.euclidean.threed.RotationConvention;
  32. import org.hipparchus.geometry.euclidean.threed.Vector3D;
  33. import org.hipparchus.linear.DecompositionSolver;
  34. import org.hipparchus.linear.MatrixUtils;
  35. import org.hipparchus.linear.QRDecomposition;
  36. import org.hipparchus.linear.RealMatrix;
  37. import org.hipparchus.linear.RealVector;
  38. import org.hipparchus.util.FastMath;
  39. import org.hipparchus.util.MathArrays;
  40. import org.orekit.errors.OrekitException;
  41. import org.orekit.errors.OrekitMessages;
  42. import org.orekit.time.TimeShiftable;

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

  57.     /** Fixed orientation parallel with reference frame
  58.      * (identity rotation, zero rotation rate and acceleration).
  59.      */
  60.     public static final AngularCoordinates IDENTITY =
  61.             new AngularCoordinates(Rotation.IDENTITY, Vector3D.ZERO, Vector3D.ZERO);

  62.     /** Serializable UID. */
  63.     private static final long serialVersionUID = 20140414L;

  64.     /** Rotation. */
  65.     private final Rotation rotation;

  66.     /** Rotation rate. */
  67.     private final Vector3D rotationRate;

  68.     /** Rotation acceleration. */
  69.     private final Vector3D rotationAcceleration;

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

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

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

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

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

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

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

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

  140.         } catch (MathRuntimeException mrte) {
  141.             throw new OrekitException(mrte);
  142.         }

  143.     }

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

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

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

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

  167.         final double q0       = r.getQ0().getReal();
  168.         final double q1       = r.getQ1().getReal();
  169.         final double q2       = r.getQ2().getReal();
  170.         final double q3       = r.getQ3().getReal();

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

  197.     }

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

  219.         final double v12 = v1.getNormSq();
  220.         final double v1n = FastMath.sqrt(v12);
  221.         final double v22 = v2.getNormSq();
  222.         final double v2n = FastMath.sqrt(v22);
  223.         final double threshold = tolerance * FastMath.max(v1n, v2n);

  224.         Vector3D omega;

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

  240.             final RealVector rhs = MatrixUtils.createRealVector(new double[] {
  241.                 c1.getX(), c1.getY(), c1.getZ(),
  242.                 c2.getX(), c2.getY(), c2.getZ()
  243.             });

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

  248.         } catch (MathIllegalArgumentException miae) {
  249.             if (miae.getSpecifier() == LocalizedCoreFormats.SINGULAR_MATRIX) {

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

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

  274.         }

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

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

  284.         return omega;

  285.     }

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

  295.         // quaternion components
  296.         final double q0 = rotation.getQ0();
  297.         final double q1 = rotation.getQ1();
  298.         final double q2 = rotation.getQ2();
  299.         final double q3 = rotation.getQ3();

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

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

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

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

  363.     }

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

  372.         // quaternion components
  373.         final double q0 = rotation.getQ0();
  374.         final double q1 = rotation.getQ1();
  375.         final double q2 = rotation.getQ2();
  376.         final double q3 = rotation.getQ3();

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

  385.         final UnivariateDerivative1 q0UD = new UnivariateDerivative1(q0, q0Dot);
  386.         final UnivariateDerivative1 q1UD = new UnivariateDerivative1(q1, q1Dot);
  387.         final UnivariateDerivative1 q2UD = new UnivariateDerivative1(q2, q2Dot);
  388.         final UnivariateDerivative1 q3UD = new UnivariateDerivative1(q3, q3Dot);

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

  390.     }

  391.     /** Transform the instance to a {@link FieldRotation}&lt;{@link UnivariateDerivative2}&gt;.
  392.      * <p>
  393.      * The {@link UnivariateDerivative2} coordinates correspond to time-derivatives up
  394.      * to the order 2.
  395.      * </p>
  396.      * @return rotation with time-derivatives embedded within the coordinates
  397.      */
  398.     public FieldRotation<UnivariateDerivative2> toUnivariateDerivative2Rotation() {

  399.         // quaternion components
  400.         final double q0 = rotation.getQ0();
  401.         final double q1 = rotation.getQ1();
  402.         final double q2 = rotation.getQ2();
  403.         final double q3 = rotation.getQ3();

  404.         // first time-derivatives of the quaternion
  405.         final double oX    = rotationRate.getX();
  406.         final double oY    = rotationRate.getY();
  407.         final double oZ    = rotationRate.getZ();
  408.         final double q0Dot = 0.5 * MathArrays.linearCombination(-q1, oX, -q2, oY, -q3, oZ);
  409.         final double q1Dot = 0.5 * MathArrays.linearCombination( q0, oX, -q3, oY,  q2, oZ);
  410.         final double q2Dot = 0.5 * MathArrays.linearCombination( q3, oX,  q0, oY, -q1, oZ);
  411.         final double q3Dot = 0.5 * MathArrays.linearCombination(-q2, oX,  q1, oY,  q0, oZ);

  412.         // second time-derivatives of the quaternion
  413.         final double oXDot = rotationAcceleration.getX();
  414.         final double oYDot = rotationAcceleration.getY();
  415.         final double oZDot = rotationAcceleration.getZ();
  416.         final double q0DotDot = -0.5 * MathArrays.linearCombination(new double[] {
  417.             q1, q2,  q3, q1Dot, q2Dot,  q3Dot
  418.         }, new double[] {
  419.             oXDot, oYDot, oZDot, oX, oY, oZ
  420.         });
  421.         final double q1DotDot =  0.5 * MathArrays.linearCombination(new double[] {
  422.             q0, q2, -q3, q0Dot, q2Dot, -q3Dot
  423.         }, new double[] {
  424.             oXDot, oZDot, oYDot, oX, oZ, oY
  425.         });
  426.         final double q2DotDot =  0.5 * MathArrays.linearCombination(new double[] {
  427.             q0, q3, -q1, q0Dot, q3Dot, -q1Dot
  428.         }, new double[] {
  429.             oYDot, oXDot, oZDot, oY, oX, oZ
  430.         });
  431.         final double q3DotDot =  0.5 * MathArrays.linearCombination(new double[] {
  432.             q0, q1, -q2, q0Dot, q1Dot, -q2Dot
  433.         }, new double[] {
  434.             oZDot, oYDot, oXDot, oZ, oY, oX
  435.         });

  436.         final UnivariateDerivative2 q0UD = new UnivariateDerivative2(q0, q0Dot, q0DotDot);
  437.         final UnivariateDerivative2 q1UD = new UnivariateDerivative2(q1, q1Dot, q1DotDot);
  438.         final UnivariateDerivative2 q2UD = new UnivariateDerivative2(q2, q2Dot, q2DotDot);
  439.         final UnivariateDerivative2 q3UD = new UnivariateDerivative2(q3, q3Dot, q3DotDot);

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

  441.     }

  442.     /** Estimate rotation rate between two orientations.
  443.      * <p>Estimation is based on a simple fixed rate rotation
  444.      * during the time interval between the two orientations.</p>
  445.      * @param start start orientation
  446.      * @param end end orientation
  447.      * @param dt time elapsed between the dates of the two orientations
  448.      * @return rotation rate allowing to go from start to end orientations
  449.      */
  450.     public static Vector3D estimateRate(final Rotation start, final Rotation end, final double dt) {
  451.         final Rotation evolution = start.compose(end.revert(), RotationConvention.VECTOR_OPERATOR);
  452.         return new Vector3D(evolution.getAngle() / dt, evolution.getAxis(RotationConvention.VECTOR_OPERATOR));
  453.     }

  454.     /** Revert a rotation/rotation rate/ rotation acceleration triplet.
  455.      * Build a triplet which reverse the effect of another triplet.
  456.      * @return a new triplet whose effect is the reverse of the effect
  457.      * of the instance
  458.      */
  459.     public AngularCoordinates revert() {
  460.         return new AngularCoordinates(rotation.revert(),
  461.                                       rotation.applyInverseTo(rotationRate).negate(),
  462.                                       rotation.applyInverseTo(rotationAcceleration).negate());
  463.     }

  464.     /** Get a time-shifted state.
  465.      * <p>
  466.      * The state can be slightly shifted to close dates. This shift is based on
  467.      * an approximate solution of the fixed acceleration motion. It is <em>not</em>
  468.      * intended as a replacement for proper attitude propagation but should be
  469.      * sufficient for either small time shifts or coarse accuracy.
  470.      * </p>
  471.      * @param dt time shift in seconds
  472.      * @return a new state, shifted with respect to the instance (which is immutable)
  473.      */
  474.     public AngularCoordinates shiftedBy(final double dt) {

  475.         // the shiftedBy method is based on a local approximation.
  476.         // It considers separately the contribution of the constant
  477.         // rotation, the linear contribution or the rate and the
  478.         // quadratic contribution of the acceleration. The rate
  479.         // and acceleration contributions are small rotations as long
  480.         // as the time shift is small, which is the crux of the algorithm.
  481.         // Small rotations are almost commutative, so we append these small
  482.         // contributions one after the other, as if they really occurred
  483.         // successively, despite this is not what really happens.

  484.         // compute the linear contribution first, ignoring acceleration
  485.         // BEWARE: there is really a minus sign here, because if
  486.         // the target frame rotates in one direction, the vectors in the origin
  487.         // frame seem to rotate in the opposite direction
  488.         final double rate = rotationRate.getNorm();
  489.         final Rotation rateContribution = (rate == 0.0) ?
  490.                                           Rotation.IDENTITY :
  491.                                           new Rotation(rotationRate, rate * dt, RotationConvention.FRAME_TRANSFORM);

  492.         // append rotation and rate contribution
  493.         final AngularCoordinates linearPart =
  494.                 new AngularCoordinates(rateContribution.compose(rotation, RotationConvention.VECTOR_OPERATOR), rotationRate);

  495.         final double acc  = rotationAcceleration.getNorm();
  496.         if (acc == 0.0) {
  497.             // no acceleration, the linear part is sufficient
  498.             return linearPart;
  499.         }

  500.         // compute the quadratic contribution, ignoring initial rotation and rotation rate
  501.         // BEWARE: there is really a minus sign here, because if
  502.         // the target frame rotates in one direction, the vectors in the origin
  503.         // frame seem to rotate in the opposite direction
  504.         final AngularCoordinates quadraticContribution =
  505.                 new AngularCoordinates(new Rotation(rotationAcceleration,
  506.                                                     0.5 * acc * dt * dt,
  507.                                                     RotationConvention.FRAME_TRANSFORM),
  508.                                        new Vector3D(dt, rotationAcceleration),
  509.                                        rotationAcceleration);

  510.         // the quadratic contribution is a small rotation:
  511.         // its initial angle and angular rate are both zero.
  512.         // small rotations are almost commutative, so we append the small
  513.         // quadratic part after the linear part as a simple offset
  514.         return quadraticContribution.addOffset(linearPart);

  515.     }

  516.     /** Get the rotation.
  517.      * @return the rotation.
  518.      */
  519.     public Rotation getRotation() {
  520.         return rotation;
  521.     }

  522.     /** Get the rotation rate.
  523.      * @return the rotation rate vector Ω (rad/s).
  524.      */
  525.     public Vector3D getRotationRate() {
  526.         return rotationRate;
  527.     }

  528.     /** Get the rotation acceleration.
  529.      * @return the rotation acceleration vector dΩ/dt (rad/s²).
  530.      */
  531.     public Vector3D getRotationAcceleration() {
  532.         return rotationAcceleration;
  533.     }

  534.     /** Add an offset from the instance.
  535.      * <p>
  536.      * We consider here that the offset rotation is applied first and the
  537.      * instance is applied afterward. Note that angular coordinates do <em>not</em>
  538.      * commute under this operation, i.e. {@code a.addOffset(b)} and {@code
  539.      * b.addOffset(a)} lead to <em>different</em> results in most cases.
  540.      * </p>
  541.      * <p>
  542.      * The two methods {@link #addOffset(AngularCoordinates) addOffset} and
  543.      * {@link #subtractOffset(AngularCoordinates) subtractOffset} are designed
  544.      * so that round trip applications are possible. This means that both {@code
  545.      * ac1.subtractOffset(ac2).addOffset(ac2)} and {@code
  546.      * ac1.addOffset(ac2).subtractOffset(ac2)} return angular coordinates equal to ac1.
  547.      * </p>
  548.      * @param offset offset to subtract
  549.      * @return new instance, with offset subtracted
  550.      * @see #subtractOffset(AngularCoordinates)
  551.      */
  552.     public AngularCoordinates addOffset(final AngularCoordinates offset) {
  553.         final Vector3D rOmega    = rotation.applyTo(offset.rotationRate);
  554.         final Vector3D rOmegaDot = rotation.applyTo(offset.rotationAcceleration);
  555.         return new AngularCoordinates(rotation.compose(offset.rotation, RotationConvention.VECTOR_OPERATOR),
  556.                                       rotationRate.add(rOmega),
  557.                                       new Vector3D( 1.0, rotationAcceleration,
  558.                                                     1.0, rOmegaDot,
  559.                                                    -1.0, Vector3D.crossProduct(rotationRate, rOmega)));
  560.     }

  561.     /** Subtract an offset from the instance.
  562.      * <p>
  563.      * We consider here that the offset rotation is applied first and the
  564.      * instance is applied afterward. Note that angular coordinates do <em>not</em>
  565.      * commute under this operation, i.e. {@code a.subtractOffset(b)} and {@code
  566.      * b.subtractOffset(a)} lead to <em>different</em> results in most cases.
  567.      * </p>
  568.      * <p>
  569.      * The two methods {@link #addOffset(AngularCoordinates) addOffset} and
  570.      * {@link #subtractOffset(AngularCoordinates) subtractOffset} are designed
  571.      * so that round trip applications are possible. This means that both {@code
  572.      * ac1.subtractOffset(ac2).addOffset(ac2)} and {@code
  573.      * ac1.addOffset(ac2).subtractOffset(ac2)} return angular coordinates equal to ac1.
  574.      * </p>
  575.      * @param offset offset to subtract
  576.      * @return new instance, with offset subtracted
  577.      * @see #addOffset(AngularCoordinates)
  578.      */
  579.     public AngularCoordinates subtractOffset(final AngularCoordinates offset) {
  580.         return addOffset(offset.revert());
  581.     }

  582.     /** Apply the rotation to a pv coordinates.
  583.      * @param pv vector to apply the rotation to
  584.      * @return a new pv coordinates which is the image of u by the rotation
  585.      */
  586.     public PVCoordinates applyTo(final PVCoordinates pv) {

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

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

  598.     }

  599.     /** Apply the rotation to a pv coordinates.
  600.      * @param pv vector to apply the rotation to
  601.      * @return a new pv coordinates which is the image of u by the rotation
  602.      */
  603.     public TimeStampedPVCoordinates applyTo(final TimeStampedPVCoordinates pv) {

  604.         final Vector3D transformedP = getRotation().applyTo(pv.getPosition());
  605.         final Vector3D crossP       = Vector3D.crossProduct(getRotationRate(), transformedP);
  606.         final Vector3D transformedV = getRotation().applyTo(pv.getVelocity()).subtract(crossP);
  607.         final Vector3D crossV       = Vector3D.crossProduct(getRotationRate(), transformedV);
  608.         final Vector3D crossCrossP  = Vector3D.crossProduct(getRotationRate(), crossP);
  609.         final Vector3D crossDotP    = Vector3D.crossProduct(getRotationAcceleration(), transformedP);
  610.         final Vector3D transformedA = new Vector3D( 1, getRotation().applyTo(pv.getAcceleration()),
  611.                                                    -2, crossV,
  612.                                                    -1, crossCrossP,
  613.                                                    -1, crossDotP);

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

  615.     }

  616.     /** Apply the rotation to a pv coordinates.
  617.      * @param pv vector to apply the rotation to
  618.      * @param <T> type of the field elements
  619.      * @return a new pv coordinates which is the image of u by the rotation
  620.      * @since 9.0
  621.      */
  622.     public <T extends CalculusFieldElement<T>> FieldPVCoordinates<T> applyTo(final FieldPVCoordinates<T> pv) {

  623.         final FieldVector3D<T> transformedP = FieldRotation.applyTo(rotation, pv.getPosition());
  624.         final FieldVector3D<T> crossP       = FieldVector3D.crossProduct(rotationRate, transformedP);
  625.         final FieldVector3D<T> transformedV = FieldRotation.applyTo(rotation, pv.getVelocity()).subtract(crossP);
  626.         final FieldVector3D<T> crossV       = FieldVector3D.crossProduct(rotationRate, transformedV);
  627.         final FieldVector3D<T> crossCrossP  = FieldVector3D.crossProduct(rotationRate, crossP);
  628.         final FieldVector3D<T> crossDotP    = FieldVector3D.crossProduct(rotationAcceleration, transformedP);
  629.         final FieldVector3D<T> transformedA = new FieldVector3D<>( 1, FieldRotation.applyTo(rotation, pv.getAcceleration()),
  630.                                                                   -2, crossV,
  631.                                                                   -1, crossCrossP,
  632.                                                                   -1, crossDotP);

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

  634.     }

  635.     /** Apply the rotation to a pv coordinates.
  636.      * @param pv vector to apply the rotation to
  637.      * @param <T> type of the field elements
  638.      * @return a new pv coordinates which is the image of u by the rotation
  639.      * @since 9.0
  640.      */
  641.     public <T extends CalculusFieldElement<T>> TimeStampedFieldPVCoordinates<T> applyTo(final TimeStampedFieldPVCoordinates<T> pv) {

  642.         final FieldVector3D<T> transformedP = FieldRotation.applyTo(rotation, pv.getPosition());
  643.         final FieldVector3D<T> crossP       = FieldVector3D.crossProduct(rotationRate, transformedP);
  644.         final FieldVector3D<T> transformedV = FieldRotation.applyTo(rotation, pv.getVelocity()).subtract(crossP);
  645.         final FieldVector3D<T> crossV       = FieldVector3D.crossProduct(rotationRate, transformedV);
  646.         final FieldVector3D<T> crossCrossP  = FieldVector3D.crossProduct(rotationRate, crossP);
  647.         final FieldVector3D<T> crossDotP    = FieldVector3D.crossProduct(rotationAcceleration, transformedP);
  648.         final FieldVector3D<T> transformedA = new FieldVector3D<>( 1, FieldRotation.applyTo(rotation, pv.getAcceleration()),
  649.                                                                   -2, crossV,
  650.                                                                   -1, crossCrossP,
  651.                                                                   -1, crossDotP);

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

  653.     }

  654.     /** Convert rotation, rate and acceleration to modified Rodrigues vector and derivatives.
  655.      * <p>
  656.      * The modified Rodrigues vector is tan(θ/4) u where θ and u are the
  657.      * rotation angle and axis respectively.
  658.      * </p>
  659.      * @param sign multiplicative sign for quaternion components
  660.      * @return modified Rodrigues vector and derivatives (vector on row 0, first derivative
  661.      * on row 1, second derivative on row 2)
  662.      * @see #createFromModifiedRodrigues(double[][])
  663.      */
  664.     public double[][] getModifiedRodrigues(final double sign) {

  665.         final double q0    = sign * getRotation().getQ0();
  666.         final double q1    = sign * getRotation().getQ1();
  667.         final double q2    = sign * getRotation().getQ2();
  668.         final double q3    = sign * getRotation().getQ3();
  669.         final double oX    = getRotationRate().getX();
  670.         final double oY    = getRotationRate().getY();
  671.         final double oZ    = getRotationRate().getZ();
  672.         final double oXDot = getRotationAcceleration().getX();
  673.         final double oYDot = getRotationAcceleration().getY();
  674.         final double oZDot = getRotationAcceleration().getZ();

  675.         // first time-derivatives of the quaternion
  676.         final double q0Dot = 0.5 * MathArrays.linearCombination(-q1, oX, -q2, oY, -q3, oZ);
  677.         final double q1Dot = 0.5 * MathArrays.linearCombination( q0, oX, -q3, oY,  q2, oZ);
  678.         final double q2Dot = 0.5 * MathArrays.linearCombination( q3, oX,  q0, oY, -q1, oZ);
  679.         final double q3Dot = 0.5 * MathArrays.linearCombination(-q2, oX,  q1, oY,  q0, oZ);

  680.         // second time-derivatives of the quaternion
  681.         final double q0DotDot = -0.5 * MathArrays.linearCombination(new double[] {
  682.             q1, q2,  q3, q1Dot, q2Dot,  q3Dot
  683.         }, new double[] {
  684.             oXDot, oYDot, oZDot, oX, oY, oZ
  685.         });
  686.         final double q1DotDot =  0.5 * MathArrays.linearCombination(new double[] {
  687.             q0, q2, -q3, q0Dot, q2Dot, -q3Dot
  688.         }, new double[] {
  689.             oXDot, oZDot, oYDot, oX, oZ, oY
  690.         });
  691.         final double q2DotDot =  0.5 * MathArrays.linearCombination(new double[] {
  692.             q0, q3, -q1, q0Dot, q3Dot, -q1Dot
  693.         }, new double[] {
  694.             oYDot, oXDot, oZDot, oY, oX, oZ
  695.         });
  696.         final double q3DotDot =  0.5 * MathArrays.linearCombination(new double[] {
  697.             q0, q1, -q2, q0Dot, q1Dot, -q2Dot
  698.         }, new double[] {
  699.             oZDot, oYDot, oXDot, oZ, oY, oX
  700.         });

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

  707.         final double r1       = inv * q1;
  708.         final double r2       = inv * q2;
  709.         final double r3       = inv * q3;

  710.         final double mInvR1   = -inv * r1;
  711.         final double mInvR2   = -inv * r2;
  712.         final double mInvR3   = -inv * r3;

  713.         final double r1Dot    = MathArrays.linearCombination(inv, q1Dot, mInvR1, q0Dot);
  714.         final double r2Dot    = MathArrays.linearCombination(inv, q2Dot, mInvR2, q0Dot);
  715.         final double r3Dot    = MathArrays.linearCombination(inv, q3Dot, mInvR3, q0Dot);

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

  719.         return new double[][] {
  720.             {
  721.                 r1,       r2,       r3
  722.             }, {
  723.                 r1Dot,    r2Dot,    r3Dot
  724.             }, {
  725.                 r1DotDot, r2DotDot, r3DotDot
  726.             }
  727.         };

  728.     }

  729.     /** Convert a modified Rodrigues vector and derivatives to angular coordinates.
  730.      * @param r modified Rodrigues vector (with first and second times derivatives)
  731.      * @return angular coordinates
  732.      * @see #getModifiedRodrigues(double)
  733.      */
  734.     public static AngularCoordinates createFromModifiedRodrigues(final double[][] r) {

  735.         // rotation
  736.         final double rSquared = r[0][0] * r[0][0] + r[0][1] * r[0][1] + r[0][2] * r[0][2];
  737.         final double oPQ0     = 2 / (1 + rSquared);
  738.         final double q0       = oPQ0 - 1;
  739.         final double q1       = oPQ0 * r[0][0];
  740.         final double q2       = oPQ0 * r[0][1];
  741.         final double q3       = oPQ0 * r[0][2];

  742.         // rotation rate
  743.         final double oPQ02    = oPQ0 * oPQ0;
  744.         final double q0Dot    = -oPQ02 * MathArrays.linearCombination(r[0][0], r[1][0], r[0][1], r[1][1],  r[0][2], r[1][2]);
  745.         final double q1Dot    = oPQ0 * r[1][0] + r[0][0] * q0Dot;
  746.         final double q2Dot    = oPQ0 * r[1][1] + r[0][1] * q0Dot;
  747.         final double q3Dot    = oPQ0 * r[1][2] + r[0][2] * q0Dot;
  748.         final double oX       = 2 * MathArrays.linearCombination(-q1, q0Dot,  q0, q1Dot,  q3, q2Dot, -q2, q3Dot);
  749.         final double oY       = 2 * MathArrays.linearCombination(-q2, q0Dot, -q3, q1Dot,  q0, q2Dot,  q1, q3Dot);
  750.         final double oZ       = 2 * MathArrays.linearCombination(-q3, q0Dot,  q2, q1Dot, -q1, q2Dot,  q0, q3Dot);

  751.         // rotation acceleration
  752.         final double q0DotDot = (1 - q0) / oPQ0 * q0Dot * q0Dot -
  753.                                 oPQ02 * MathArrays.linearCombination(r[0][0], r[2][0], r[0][1], r[2][1], r[0][2], r[2][2]) -
  754.                                 (q1Dot * q1Dot + q2Dot * q2Dot + q3Dot * q3Dot);
  755.         final double q1DotDot = MathArrays.linearCombination(oPQ0, r[2][0], 2 * r[1][0], q0Dot, r[0][0], q0DotDot);
  756.         final double q2DotDot = MathArrays.linearCombination(oPQ0, r[2][1], 2 * r[1][1], q0Dot, r[0][1], q0DotDot);
  757.         final double q3DotDot = MathArrays.linearCombination(oPQ0, r[2][2], 2 * r[1][2], q0Dot, r[0][2], q0DotDot);
  758.         final double oXDot    = 2 * MathArrays.linearCombination(-q1, q0DotDot,  q0, q1DotDot,  q3, q2DotDot, -q2, q3DotDot);
  759.         final double oYDot    = 2 * MathArrays.linearCombination(-q2, q0DotDot, -q3, q1DotDot,  q0, q2DotDot,  q1, q3DotDot);
  760.         final double oZDot    = 2 * MathArrays.linearCombination(-q3, q0DotDot,  q2, q1DotDot, -q1, q2DotDot,  q0, q3DotDot);

  761.         return new AngularCoordinates(new Rotation(q0, q1, q2, q3, false),
  762.                                       new Vector3D(oX, oY, oZ),
  763.                                       new Vector3D(oXDot, oYDot, oZDot));

  764.     }

  765. }