AngularCoordinates.java

  1. /* Copyright 2002-2013 CS Systèmes d'Information
  2.  * Licensed to CS Systèmes d'Information (CS) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * CS licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *   http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.orekit.utils;

  18. import java.io.Serializable;
  19. import java.util.Collection;

  20. import org.apache.commons.math3.analysis.differentiation.DerivativeStructure;
  21. import org.apache.commons.math3.analysis.interpolation.HermiteInterpolator;
  22. import org.apache.commons.math3.geometry.euclidean.threed.Rotation;
  23. import org.apache.commons.math3.geometry.euclidean.threed.Vector3D;
  24. import org.apache.commons.math3.util.FastMath;
  25. import org.apache.commons.math3.util.MathArrays;
  26. import org.apache.commons.math3.util.Pair;
  27. import org.orekit.errors.OrekitException;
  28. import org.orekit.time.AbsoluteDate;
  29. import org.orekit.time.TimeShiftable;

  30. /** Simple container for rotation/rotation rate pairs.
  31.  * <p>
  32.  * The state can be slightly shifted to close dates. This shift is based on
  33.  * a simple linear model. It is <em>not</em> intended as a replacement for
  34.  * proper attitude propagation but should be sufficient for either small
  35.  * time shifts or coarse accuracy.
  36.  * </p>
  37.  * <p>
  38.  * This class is the angular counterpart to {@link PVCoordinates}.
  39.  * </p>
  40.  * <p>Instances of this class are guaranteed to be immutable.</p>
  41.  * @author Luc Maisonobe
  42.  */
  43. public class AngularCoordinates implements TimeShiftable<AngularCoordinates>, Serializable {

  44.     /** Fixed orientation parallel with reference frame (identity rotation and zero rotation rate). */
  45.     public static final AngularCoordinates IDENTITY =
  46.             new AngularCoordinates(Rotation.IDENTITY, Vector3D.ZERO);

  47.     /** Serializable UID. */
  48.     private static final long serialVersionUID = 3750363056414336775L;

  49.     /** Rotation. */
  50.     private final Rotation rotation;

  51.     /** Rotation rate. */
  52.     private final Vector3D rotationRate;

  53.     /** Simple constructor.
  54.      * <p> Sets the Coordinates to default : Identity (0 0 0).</p>
  55.      */
  56.     public AngularCoordinates() {
  57.         rotation     = Rotation.IDENTITY;
  58.         rotationRate = Vector3D.ZERO;
  59.     }

  60.     /** Builds a rotation/rotation rate pair.
  61.      * @param rotation rotation
  62.      * @param rotationRate rotation rate (rad/s)
  63.      */
  64.     public AngularCoordinates(final Rotation rotation, final Vector3D rotationRate) {
  65.         this.rotation     = rotation;
  66.         this.rotationRate = rotationRate;
  67.     }

  68.     /** Estimate rotation rate between two orientations.
  69.      * <p>Estimation is based on a simple fixed rate rotation
  70.      * during the time interval between the two orientations.</p>
  71.      * @param start start orientation
  72.      * @param end end orientation
  73.      * @param dt time elapsed between the dates of the two orientations
  74.      * @return rotation rate allowing to go from start to end orientations
  75.      */
  76.     public static Vector3D estimateRate(final Rotation start, final Rotation end, final double dt) {
  77.         final Rotation evolution = start.applyTo(end.revert());
  78.         return new Vector3D(evolution.getAngle() / dt, evolution.getAxis());
  79.     }

  80.     /** Revert a rotation/rotation rate pair.
  81.      * Build a pair which reverse the effect of another pair.
  82.      * @return a new pair whose effect is the reverse of the effect
  83.      * of the instance
  84.      */
  85.     public AngularCoordinates revert() {
  86.         return new AngularCoordinates(rotation.revert(), rotation.applyInverseTo(rotationRate.negate()));
  87.     }

  88.     /** Get a time-shifted state.
  89.      * <p>
  90.      * The state can be slightly shifted to close dates. This shift is based on
  91.      * a simple linear model. It is <em>not</em> intended as a replacement for
  92.      * proper attitude propagation but should be sufficient for either small
  93.      * time shifts or coarse accuracy.
  94.      * </p>
  95.      * @param dt time shift in seconds
  96.      * @return a new state, shifted with respect to the instance (which is immutable)
  97.      */
  98.     public AngularCoordinates shiftedBy(final double dt) {
  99.         final double rate = rotationRate.getNorm();
  100.         if (rate == 0.0) {
  101.             // special case for fixed rotations
  102.             return this;
  103.         }

  104.         // BEWARE: there is really a minus sign here, because if
  105.         // the target frame rotates in one direction, the vectors in the origin
  106.         // frame seem to rotate in the opposite direction
  107.         final Rotation evolution = new Rotation(rotationRate, -rate * dt);

  108.         return new AngularCoordinates(evolution.applyTo(rotation), rotationRate);

  109.     }

  110.     /** Get the rotation.
  111.      * @return the rotation.
  112.      */
  113.     public Rotation getRotation() {
  114.         return rotation;
  115.     }

  116.     /** Get the rotation rate.
  117.      * @return the rotation rate vector (rad/s).
  118.      */
  119.     public Vector3D getRotationRate() {
  120.         return rotationRate;
  121.     }

  122.     /** Add an offset from the instance.
  123.      * <p>
  124.      * We consider here that the offset rotation is applied first and the
  125.      * instance is applied afterward. Note that angular coordinates do <em>not</em>
  126.      * commute under this operation, i.e. {@code a.addOffset(b)} and {@code
  127.      * b.addOffset(a)} lead to <em>different</em> results in most cases.
  128.      * </p>
  129.      * <p>
  130.      * The two methods {@link #addOffset(AngularCoordinates) addOffset} and
  131.      * {@link #subtractOffset(AngularCoordinates) subtractOffset} are designed
  132.      * so that round trip applications are possible. This means that both {@code
  133.      * ac1.subtractOffset(ac2).addOffset(ac2)} and {@code
  134.      * ac1.addOffset(ac2).subtractOffset(ac2)} return angular coordinates equal to ac1.
  135.      * </p>
  136.      * @param offset offset to subtract
  137.      * @return new instance, with offset subtracted
  138.      * @see #subtractOffset(AngularCoordinates)
  139.      */
  140.     public AngularCoordinates addOffset(final AngularCoordinates offset) {
  141.         return new AngularCoordinates(rotation.applyTo(offset.rotation),
  142.                                       rotationRate.add(rotation.applyTo(offset.rotationRate)));
  143.     }

  144.     /** Subtract an offset from the instance.
  145.      * <p>
  146.      * We consider here that the offset rotation is applied first and the
  147.      * instance is applied afterward. Note that angular coordinates do <em>not</em>
  148.      * commute under this operation, i.e. {@code a.subtractOffset(b)} and {@code
  149.      * b.subtractOffset(a)} lead to <em>different</em> results in most cases.
  150.      * </p>
  151.      * <p>
  152.      * The two methods {@link #addOffset(AngularCoordinates) addOffset} and
  153.      * {@link #subtractOffset(AngularCoordinates) subtractOffset} are designed
  154.      * so that round trip applications are possible. This means that both {@code
  155.      * ac1.subtractOffset(ac2).addOffset(ac2)} and {@code
  156.      * ac1.addOffset(ac2).subtractOffset(ac2)} return angular coordinates equal to ac1.
  157.      * </p>
  158.      * @param offset offset to subtract
  159.      * @return new instance, with offset subtracted
  160.      * @see #addOffset(AngularCoordinates)
  161.      */
  162.     public AngularCoordinates subtractOffset(final AngularCoordinates offset) {
  163.         return addOffset(offset.revert());
  164.     }

  165.     /** Interpolate angular coordinates.
  166.      * <p>
  167.      * The interpolated instance is created by polynomial Hermite interpolation
  168.      * on Rodrigues vector ensuring rotation rate remains the exact derivative of rotation.
  169.      * </p>
  170.      * <p>
  171.      * This method is based on Sergei Tanygin's paper <a
  172.      * href="http://www.agi.com/downloads/resources/white-papers/Attitude-interpolation.pdf">Attitude
  173.      * Interpolation</a>, changing the norm of the vector to match the modified Rodrigues
  174.      * vector as described in Malcolm D. Shuster's paper <a
  175.      * href="http://www.ladispe.polito.it/corsi/Meccatronica/02JHCOR/2011-12/Slides/Shuster_Pub_1993h_J_Repsurv_scan.pdf">A
  176.      * Survey of Attitude Representations</a>. This change avoids the singularity at &pi;.
  177.      * There is still a singularity at 2&pi;, which is handled by slightly offsetting all rotations
  178.      * when this singularity is detected.
  179.      * </p>
  180.      * <p>
  181.      * Note that even if first time derivatives (rotation rates)
  182.      * from sample can be ignored, the interpolated instance always includes
  183.      * interpolated derivatives. This feature can be used explicitly to
  184.      * compute these derivatives when it would be too complex to compute them
  185.      * from an analytical formula: just compute a few sample points from the
  186.      * explicit formula and set the derivatives to zero in these sample points,
  187.      * then use interpolation to add derivatives consistent with the rotations.
  188.      * </p>
  189.      * @param date interpolation date
  190.      * @param useRotationRates if true, use sample points rotation rates,
  191.      * otherwise ignore them and use only rotations
  192.      * @param sample sample points on which interpolation should be done
  193.      * @return a new position-velocity, interpolated at specified date
  194.      */
  195.     public static AngularCoordinates interpolate(final AbsoluteDate date, final boolean useRotationRates,
  196.                                                  final Collection<Pair<AbsoluteDate, AngularCoordinates>> sample) {

  197.         // set up safety elements for 2PI singularity avoidance
  198.         final double epsilon   = 2 * FastMath.PI / sample.size();
  199.         final double threshold = FastMath.min(-(1.0 - 1.0e-4), -FastMath.cos(epsilon / 4));

  200.         // set up a linear offset model canceling mean rotation rate
  201.         final Vector3D meanRate;
  202.         if (useRotationRates) {
  203.             Vector3D sum = Vector3D.ZERO;
  204.             for (final Pair<AbsoluteDate, AngularCoordinates> datedAC : sample) {
  205.                 sum = sum.add(datedAC.getValue().getRotationRate());
  206.             }
  207.             meanRate = new Vector3D(1.0 / sample.size(), sum);
  208.         } else {
  209.             Vector3D sum = Vector3D.ZERO;
  210.             Pair<AbsoluteDate, AngularCoordinates> previous = null;
  211.             for (final Pair<AbsoluteDate, AngularCoordinates> datedAC : sample) {
  212.                 if (previous != null) {
  213.                     sum = sum.add(estimateRate(previous.getValue().getRotation(),
  214.                                                          datedAC.getValue().getRotation(),
  215.                                                          datedAC.getKey().durationFrom(previous.getKey().getDate())));
  216.                 }
  217.                 previous = datedAC;
  218.             }
  219.             meanRate = new Vector3D(1.0 / (sample.size() - 1), sum);
  220.         }
  221.         AngularCoordinates offset = new AngularCoordinates(Rotation.IDENTITY, meanRate);

  222.         boolean restart = true;
  223.         for (int i = 0; restart && i < sample.size() + 2; ++i) {

  224.             // offset adaptation parameters
  225.             restart = false;

  226.             // set up an interpolator taking derivatives into account
  227.             final HermiteInterpolator interpolator = new HermiteInterpolator();

  228.             // add sample points
  229.             if (useRotationRates) {
  230.                 // populate sample with rotation and rotation rate data
  231.                 for (final Pair<AbsoluteDate, AngularCoordinates> datedAC : sample) {
  232.                     final double[] rodrigues = getModifiedRodrigues(datedAC.getKey(), datedAC.getValue(),
  233.                                                                     date, offset, threshold);
  234.                     if (rodrigues == null) {
  235.                         // the sample point is close to a modified Rodrigues vector singularity
  236.                         // we need to change the linear offset model to avoid this
  237.                         restart = true;
  238.                         break;
  239.                     }
  240.                     interpolator.addSamplePoint(datedAC.getKey().getDate().durationFrom(date),
  241.                                                 new double[] {
  242.                                                     rodrigues[0],
  243.                                                     rodrigues[1],
  244.                                                     rodrigues[2]
  245.                                                 },
  246.                                                 new double[] {
  247.                                                     rodrigues[3],
  248.                                                     rodrigues[4],
  249.                                                     rodrigues[5]
  250.                                                 });
  251.                 }
  252.             } else {
  253.                 // populate sample with rotation data only, ignoring rotation rate
  254.                 for (final Pair<AbsoluteDate, AngularCoordinates> datedAC : sample) {
  255.                     final double[] rodrigues = getModifiedRodrigues(datedAC.getKey(), datedAC.getValue(),
  256.                                                                     date, offset, threshold);
  257.                     if (rodrigues == null) {
  258.                         // the sample point is close to a modified Rodrigues vector singularity
  259.                         // we need to change the linear offset model to avoid this
  260.                         restart = true;
  261.                         break;
  262.                     }
  263.                     interpolator.addSamplePoint(datedAC.getKey().getDate().durationFrom(date),
  264.                                                 new double[] {
  265.                                                     rodrigues[0],
  266.                                                     rodrigues[1],
  267.                                                     rodrigues[2]
  268.                                                 });
  269.                 }
  270.             }

  271.             if (restart) {
  272.                 // interpolation failed, some intermediate rotation was too close to 2PI
  273.                 // we need to offset all rotations to avoid the singularity
  274.                 offset = offset.addOffset(new AngularCoordinates(new Rotation(Vector3D.PLUS_I, epsilon),
  275.                                                                  Vector3D.ZERO));
  276.             } else {
  277.                 // interpolation succeeded with the current offset
  278.                 final DerivativeStructure zero = new DerivativeStructure(1, 1, 0, 0.0);
  279.                 final DerivativeStructure[] p = interpolator.value(zero);
  280.                 return createFromModifiedRodrigues(new double[] {
  281.                     p[0].getValue(), p[1].getValue(), p[2].getValue(),
  282.                     p[0].getPartialDerivative(1), p[1].getPartialDerivative(1), p[2].getPartialDerivative(1)
  283.                 }, offset);
  284.             }

  285.         }

  286.         // this should never happen
  287.         throw OrekitException.createInternalError(null);

  288.     }

  289.     /** Convert rotation and rate to modified Rodrigues vector and derivative.
  290.      * <p>
  291.      * The modified Rodrigues vector is tan(&theta;/4) u where &theta; and u are the
  292.      * rotation angle and axis respectively.
  293.      * </p>
  294.      * @param date date of the angular coordinates
  295.      * @param ac coordinates to convert
  296.      * @param offsetDate date of the linear offset model to remove
  297.      * @param offset linear offset model to remove
  298.      * @param threshold threshold for rotations too close to 2&pi;
  299.      * @return modified Rodrigues vector and derivative, or null if rotation is too close to 2&pi;
  300.      */
  301.     private static double[] getModifiedRodrigues(final AbsoluteDate date, final AngularCoordinates ac,
  302.                                                  final AbsoluteDate offsetDate, final AngularCoordinates offset,
  303.                                                  final double threshold) {

  304.         // remove linear offset from the current coordinates
  305.         final double dt = date.durationFrom(offsetDate);
  306.         final AngularCoordinates fixed = ac.subtractOffset(offset.shiftedBy(dt));

  307.         // check modified Rodrigues vector singularity
  308.         double q0 = fixed.getRotation().getQ0();
  309.         double q1 = fixed.getRotation().getQ1();
  310.         double q2 = fixed.getRotation().getQ2();
  311.         double q3 = fixed.getRotation().getQ3();
  312.         if (q0 < threshold && FastMath.abs(dt) * fixed.getRotationRate().getNorm() > 1.0e-3) {
  313.             // this is an intermediate point that happens to be 2PI away from reference
  314.             // we need to change the linear offset model to avoid this point
  315.             return null;
  316.         }

  317.         // make sure all interpolated points will be on the same branch
  318.         if (q0 < 0) {
  319.             q0 = -q0;
  320.             q1 = -q1;
  321.             q2 = -q2;
  322.             q3 = -q3;
  323.         }

  324.         final double x  = fixed.getRotationRate().getX();
  325.         final double y  = fixed.getRotationRate().getY();
  326.         final double z  = fixed.getRotationRate().getZ();

  327.         // derivatives of the quaternion
  328.         final double q0Dot = -0.5 * MathArrays.linearCombination(q1, x, q2, y,  q3, z);
  329.         final double q1Dot =  0.5 * MathArrays.linearCombination(q0, x, q2, z, -q3, y);
  330.         final double q2Dot =  0.5 * MathArrays.linearCombination(q0, y, q3, x, -q1, z);
  331.         final double q3Dot =  0.5 * MathArrays.linearCombination(q0, z, q1, y, -q2, x);

  332.         final double inv = 1.0 / (1.0 + q0);
  333.         return new double[] {
  334.             inv * q1,
  335.             inv * q2,
  336.             inv * q3,
  337.             inv * (q1Dot - inv * q1 * q0Dot),
  338.             inv * (q2Dot - inv * q2 * q0Dot),
  339.             inv * (q3Dot - inv * q3 * q0Dot)
  340.         };

  341.     }

  342.     /** Convert a modified Rodrigues vector and derivative to angular coordinates.
  343.      * @param r modified Rodrigues vector (with first derivatives)
  344.      * @param offset linear offset model to add (its date must be consistent with the modified Rodrigues vector)
  345.      * @return angular coordinates
  346.      */
  347.     private static AngularCoordinates createFromModifiedRodrigues(final double[] r,
  348.                                                                   final AngularCoordinates offset) {

  349.         // rotation
  350.         final double rSquared = r[0] * r[0] + r[1] * r[1] + r[2] * r[2];
  351.         final double inv      = 1.0 / (1 + rSquared);
  352.         final double ratio    = inv * (1 - rSquared);
  353.         final Rotation rotation =
  354.                 new Rotation(ratio, 2 * inv * r[0], 2 * inv * r[1], 2 * inv * r[2], false);

  355.         // rotation rate
  356.         final Vector3D p    = new Vector3D(r[0], r[1], r[2]);
  357.         final Vector3D pDot = new Vector3D(r[3], r[4], r[5]);
  358.         final Vector3D rate = new Vector3D( 4 * ratio * inv, pDot,
  359.                                            -8 * inv * inv, p.crossProduct(pDot),
  360.                                             8 * inv * inv * p.dotProduct(pDot), p);

  361.         return new AngularCoordinates(rotation, rate).addOffset(offset);

  362.     }

  363. }