FieldAngularCoordinates.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.RealFieldElement;
  21. import org.apache.commons.math3.analysis.interpolation.FieldHermiteInterpolator;
  22. import org.apache.commons.math3.geometry.euclidean.threed.FieldRotation;
  23. import org.apache.commons.math3.geometry.euclidean.threed.FieldVector3D;
  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 FieldRotation<T>/FieldRotation<T> rate pairs, using {@link RealFieldElement}.
  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 FieldPVCoordinates}.
  39.  * </p>
  40.  * <p>Instances of this class are guaranteed to be immutable.</p>
  41.  * @param <T> the type of the field elements
  42.  * @author Luc Maisonobe
  43.  * @since 6.0
  44.  * @see AngularCoordinates
  45.  */
  46. public class FieldAngularCoordinates<T extends RealFieldElement<T>>
  47.      implements TimeShiftable<FieldAngularCoordinates<T>>, Serializable {

  48.     /** Serializable UID. */
  49.     private static final long serialVersionUID = 20130222L;

  50.     /** FieldRotation<T>. */
  51.     private final FieldRotation<T> rotation;

  52.     /** FieldRotation<T> rate. */
  53.     private final FieldVector3D<T> rotationRate;

  54.     /** Builds a FieldRotation<T>/FieldRotation<T> rate pair.
  55.      * @param rotation FieldRotation<T>
  56.      * @param rotationRate FieldRotation<T> rate (rad/s)
  57.      */
  58.     public FieldAngularCoordinates(final FieldRotation<T> rotation, final FieldVector3D<T> rotationRate) {
  59.         this.rotation     = rotation;
  60.         this.rotationRate = rotationRate;
  61.     }

  62.     /** Estimate FieldRotation<T> rate between two orientations.
  63.      * <p>Estimation is based on a simple fixed rate FieldRotation<T>
  64.      * during the time interval between the two orientations.</p>
  65.      * @param start start orientation
  66.      * @param end end orientation
  67.      * @param dt time elapsed between the dates of the two orientations
  68.      * @param <T> the type of the field elements
  69.      * @return FieldRotation<T> rate allowing to go from start to end orientations
  70.      */
  71.     public static <T extends RealFieldElement<T>> FieldVector3D<T> estimateRate(final FieldRotation<T> start, final FieldRotation<T> end, final double dt) {
  72.         final FieldRotation<T> evolution = start.applyTo(end.revert());
  73.         return new FieldVector3D<T>(evolution.getAngle().divide(dt), evolution.getAxis());
  74.     }

  75.     /** Revert a FieldRotation<T>/FieldRotation<T> rate pair.
  76.      * Build a pair which reverse the effect of another pair.
  77.      * @return a new pair whose effect is the reverse of the effect
  78.      * of the instance
  79.      */
  80.     public FieldAngularCoordinates<T> revert() {
  81.         return new FieldAngularCoordinates<T>(rotation.revert(), rotation.applyInverseTo(rotationRate.negate()));
  82.     }

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

  99.         // BEWARE: there is really a minus sign here, because if
  100.         // the target frame rotates in one direction, the vectors in the origin
  101.         // frame seem to rotate in the opposite direction
  102.         final FieldRotation<T> evolution = new FieldRotation<T>(rotationRate, rate.negate().multiply(dt));

  103.         return new FieldAngularCoordinates<T>(evolution.applyTo(rotation), rotationRate);

  104.     }

  105.     /** Get the FieldRotation<T>.
  106.      * @return the FieldRotation<T>.
  107.      */
  108.     public FieldRotation<T> getRotation() {
  109.         return rotation;
  110.     }

  111.     /** Get the FieldRotation<T> rate.
  112.      * @return the FieldRotation<T> rate vector (rad/s).
  113.      */
  114.     public FieldVector3D<T> getRotationRate() {
  115.         return rotationRate;
  116.     }

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

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

  160.     /** Convert to a constant angular coordinates without derivatives.
  161.      * @return a constant angular coordinates
  162.      */
  163.     public AngularCoordinates toAngularCoordinates() {
  164.         return new AngularCoordinates(rotation.toRotation(), rotationRate.toVector3D());
  165.     }

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

  200.         // get field properties
  201.         final T prototype = sample.iterator().next().getValue().getRotation().getQ0();
  202.         final T zero = prototype.getField().getZero();
  203.         final T one  = prototype.getField().getOne();

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

  207.         // set up a linear offset model canceling mean FieldRotation<T> rate
  208.         final FieldVector3D<T> meanRate;
  209.         if (useRotationRates) {
  210.             FieldVector3D<T> sum = new FieldVector3D<T>(zero, zero, zero);
  211.             for (final Pair<AbsoluteDate, FieldAngularCoordinates<T>> datedAC : sample) {
  212.                 sum = sum.add(datedAC.getValue().getRotationRate());
  213.             }
  214.             meanRate = new FieldVector3D<T>(1.0 / sample.size(), sum);
  215.         } else {
  216.             FieldVector3D<T> sum = new FieldVector3D<T>(zero, zero, zero);
  217.             Pair<AbsoluteDate, FieldAngularCoordinates<T>> previous = null;
  218.             for (final Pair<AbsoluteDate, FieldAngularCoordinates<T>> datedAC : sample) {
  219.                 if (previous != null) {
  220.                     sum = sum.add(estimateRate(previous.getValue().getRotation(),
  221.                                                          datedAC.getValue().getRotation(),
  222.                                                          datedAC.getKey().durationFrom(previous.getKey().getDate())));
  223.                 }
  224.                 previous = datedAC;
  225.             }
  226.             meanRate = new FieldVector3D<T>(1.0 / (sample.size() - 1), sum);
  227.         }
  228.         FieldAngularCoordinates<T> offset =
  229.                 new FieldAngularCoordinates<T>(new FieldRotation<T>(one, zero, zero, zero, false), meanRate);

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

  232.             // offset adaptation parameters
  233.             restart = false;

  234.             // set up an interpolator taking derivatives into account
  235.             final FieldHermiteInterpolator<T> interpolator = new FieldHermiteInterpolator<T>();

  236.             // add sample points
  237.             if (useRotationRates) {
  238.                 // populate sample with FieldRotation<T> and FieldRotation<T> rate data
  239.                 for (final Pair<AbsoluteDate, FieldAngularCoordinates<T>> datedAC : sample) {
  240.                     final T[][] rodrigues = getModifiedRodrigues(datedAC.getKey(), datedAC.getValue(),
  241.                                                                  date, offset, threshold);
  242.                     if (rodrigues == null) {
  243.                         // the sample point is close to a modified Rodrigues vector singularity
  244.                         // we need to change the linear offset model to avoid this
  245.                         restart = true;
  246.                         break;
  247.                     }
  248.                     interpolator.addSamplePoint(zero.add(datedAC.getKey().getDate().durationFrom(date)),
  249.                                                 rodrigues[0], rodrigues[1]);
  250.                 }
  251.             } else {
  252.                 // populate sample with FieldRotation<T> data only, ignoring FieldRotation<T> rate
  253.                 for (final Pair<AbsoluteDate, FieldAngularCoordinates<T>> datedAC : sample) {
  254.                     final T[][] rodrigues = getModifiedRodrigues(datedAC.getKey(), datedAC.getValue(),
  255.                                                                  date, offset, threshold);
  256.                     if (rodrigues == null) {
  257.                         // the sample point is close to a modified Rodrigues vector singularity
  258.                         // we need to change the linear offset model to avoid this
  259.                         restart = true;
  260.                         break;
  261.                     }
  262.                     interpolator.addSamplePoint(zero.add(datedAC.getKey().getDate().durationFrom(date)),
  263.                                                 rodrigues[0]);
  264.                 }
  265.             }

  266.             if (restart) {
  267.                 // interpolation failed, some intermediate FieldRotation<T> was too close to 2PI
  268.                 // we need to offset all FieldRotation<T>s to avoid the singularity
  269.                 offset = offset.addOffset(new FieldAngularCoordinates<T>(new FieldRotation<T>(new FieldVector3D<T>(one, zero, zero),
  270.                                                                                               zero.add(epsilon)),
  271.                                                                          new FieldVector3D<T>(one, zero, zero)));
  272.             } else {
  273.                 // interpolation succeeded with the current offset
  274.                 final T[][] p = interpolator.derivatives(zero, 1);
  275.                 return createFromModifiedRodrigues(p, offset);
  276.             }

  277.         }

  278.         // this should never happen
  279.         throw OrekitException.createInternalError(null);

  280.     }

  281.     /** Convert rotation and rate to modified Rodrigues vector and derivative.
  282.      * <p>
  283.      * The modified Rodrigues vector is tan(&theta;/4) u where &theta; and u are the
  284.      * rotation angle and axis respectively.
  285.      * </p>
  286.      * @param date date of the angular coordinates
  287.      * @param ac coordinates to convert
  288.      * @param offsetDate date of the linear offset model to remove
  289.      * @param offset linear offset model to remove
  290.      * @param threshold threshold for rotations too close to 2&pi;
  291.      * @param <T> the type of the field elements
  292.      * @return modified Rodrigues vector and derivative, or null if rotation is too close to 2&pi;
  293.      */
  294.     private static <T extends RealFieldElement<T>> T[][] getModifiedRodrigues(final AbsoluteDate date, final FieldAngularCoordinates<T> ac,
  295.                                                                               final AbsoluteDate offsetDate, final FieldAngularCoordinates<T> offset,
  296.                                                                               final double threshold) {

  297.         // remove linear offset from the current coordinates
  298.         final double dt = date.durationFrom(offsetDate);
  299.         final FieldAngularCoordinates<T> fixed = ac.subtractOffset(offset.shiftedBy(dt));

  300.         // check modified Rodrigues vector singularity
  301.         T q0 = fixed.getRotation().getQ0();
  302.         T q1 = fixed.getRotation().getQ1();
  303.         T q2 = fixed.getRotation().getQ2();
  304.         T q3 = fixed.getRotation().getQ3();
  305.         if (q0.getReal() < threshold && FastMath.abs(dt) * fixed.getRotationRate().getNorm().getReal() > 1.0e-3) {
  306.             // this is an intermediate point that happens to be 2PI away from reference
  307.             // we need to change the linear offset model to avoid this point
  308.             return null;
  309.         }

  310.         // make sure all interpolated points will be on the same branch
  311.         if (q0.getReal() < 0) {
  312.             q0 = q0.negate();
  313.             q1 = q1.negate();
  314.             q2 = q2.negate();
  315.             q3 = q3.negate();
  316.         }

  317.         final T x  = fixed.getRotationRate().getX();
  318.         final T y  = fixed.getRotationRate().getY();
  319.         final T z  = fixed.getRotationRate().getZ();

  320.         // derivatives of the quaternion
  321.         final T q0Dot = q0.linearCombination(q1, x, q2, y,  q3, z).multiply(-0.5);
  322.         final T q1Dot = q1.linearCombination(q0, x, q2, z, q3.negate(), y).multiply(0.5);
  323.         final T q2Dot = q2.linearCombination(q0, y, q3, x, q1.negate(), z).multiply(0.5);
  324.         final T q3Dot = q3.linearCombination(q0, z, q1, y, q2.negate(), x).multiply(0.5);

  325.         final T inv = q0.add(1).reciprocal();
  326.         final T[][] rodrigues = MathArrays.buildArray(q0.getField(), 2, 3);
  327.         rodrigues[0][0] = inv.multiply(q1);
  328.         rodrigues[0][1] = inv.multiply(q2);
  329.         rodrigues[0][2] = inv.multiply(q3);
  330.         rodrigues[1][0] = inv.multiply(q1Dot.subtract(inv.multiply(q1).multiply(q0Dot)));
  331.         rodrigues[1][1] = inv.multiply(q2Dot.subtract(inv.multiply(q2).multiply(q0Dot)));
  332.         rodrigues[1][2] = inv.multiply(q3Dot.subtract(inv.multiply(q3).multiply(q0Dot)));

  333.         return rodrigues;

  334.     }

  335.     /** Convert a modified Rodrigues vector and derivative to angular coordinates.
  336.      * @param r modified Rodrigues vector (with first derivatives)
  337.      * @param offset linear offset model to add (its date must be consistent with the modified Rodrigues vector)
  338.      * @param <T> the type of the field elements
  339.      * @return angular coordinates
  340.      */
  341.     private static <T extends RealFieldElement<T>> FieldAngularCoordinates<T> createFromModifiedRodrigues(final T[][] r,
  342.                                                                                                           final FieldAngularCoordinates<T> offset) {

  343.         // rotation
  344.         final T rSquared = r[0][0].multiply(r[0][0]).add(r[0][1].multiply(r[0][1])).add(r[0][2].multiply(r[0][2]));
  345.         final T inv      = rSquared.add(1).reciprocal();
  346.         final T ratio    = inv.multiply(rSquared.subtract(1).negate());
  347.         final FieldRotation<T> rotation          = new FieldRotation<T>(ratio,
  348.                                                             inv.multiply(2).multiply(r[0][0]),
  349.                                                             inv.multiply(2).multiply(r[0][1]),
  350.                                                             inv.multiply(2).multiply(r[0][2]),
  351.                                                             false);

  352.         // rotation rate
  353.         final FieldVector3D<T> p    = new FieldVector3D<T>(r[0]);
  354.         final FieldVector3D<T> pDot = new FieldVector3D<T>(r[1]);
  355.         final FieldVector3D<T> rate = new FieldVector3D<T>(inv.multiply(ratio).multiply(4), pDot,
  356.                                                            inv.multiply(inv).multiply(-8), FieldVector3D.crossProduct(p, pDot),
  357.                                                            inv.multiply(inv).multiply(8).multiply(FieldVector3D.dotProduct(p, pDot)), p);

  358.         return new FieldAngularCoordinates<T>(rotation, rate).addOffset(offset);

  359.     }

  360. }