StateTransitionMatrixGenerator.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.propagation.numerical;

  18. import java.util.HashMap;
  19. import java.util.List;
  20. import java.util.Map;

  21. import org.hipparchus.analysis.differentiation.Gradient;
  22. import org.hipparchus.exception.LocalizedCoreFormats;
  23. import org.hipparchus.geometry.euclidean.threed.FieldVector3D;
  24. import org.hipparchus.linear.MatrixUtils;
  25. import org.hipparchus.linear.QRDecomposition;
  26. import org.hipparchus.linear.RealMatrix;
  27. import org.hipparchus.util.Precision;
  28. import org.orekit.attitudes.AttitudeProvider;
  29. import org.orekit.errors.OrekitException;
  30. import org.orekit.forces.ForceModel;
  31. import org.orekit.orbits.OrbitType;
  32. import org.orekit.orbits.PositionAngle;
  33. import org.orekit.propagation.FieldSpacecraftState;
  34. import org.orekit.propagation.SpacecraftState;
  35. import org.orekit.propagation.integration.AdditionalDerivativesProvider;
  36. import org.orekit.utils.DoubleArrayDictionary;
  37. import org.orekit.utils.ParameterDriver;

  38. /** Generator for State Transition Matrix.
  39.  * @author Luc Maisonobe
  40.  * @since 11.1
  41.  */
  42. class StateTransitionMatrixGenerator implements AdditionalDerivativesProvider {

  43.     /** Threshold for matrix solving. */
  44.     private static final double THRESHOLD = Precision.SAFE_MIN;

  45.     /** Space dimension. */
  46.     private static final int SPACE_DIMENSION = 3;

  47.     /** State dimension. */
  48.     public static final int STATE_DIMENSION = 2 * SPACE_DIMENSION;

  49.     /** Name of the Cartesian STM additional state. */
  50.     private final String stmName;

  51.     /** Force models used in propagation. */
  52.     private final List<ForceModel> forceModels;

  53.     /** Attitude provider used in propagation. */
  54.     private final AttitudeProvider attitudeProvider;

  55.     /** Observers for partial derivatives. */
  56.     private final Map<String, PartialsObserver> partialsObservers;

  57.     /** Simple constructor.
  58.      * @param stmName name of the Cartesian STM additional state
  59.      * @param forceModels force models used in propagation
  60.      * @param attitudeProvider attitude provider used in propagation
  61.      */
  62.     StateTransitionMatrixGenerator(final String stmName, final List<ForceModel> forceModels,
  63.                                    final AttitudeProvider attitudeProvider) {
  64.         this.stmName           = stmName;
  65.         this.forceModels       = forceModels;
  66.         this.attitudeProvider  = attitudeProvider;
  67.         this.partialsObservers = new HashMap<>();
  68.     }

  69.     /** Register an observer for partial derivatives.
  70.      * <p>
  71.      * The observer {@link PartialsObserver#partialsComputed(double[], double[]) partialsComputed}
  72.      * method will be called when partial derivatives are computed, as a side effect of
  73.      * calling {@link #generate(SpacecraftState)}
  74.      * </p>
  75.      * @param name name of the parameter driver this observer is interested in (may be null)
  76.      * @param observer observer to register
  77.      */
  78.     void addObserver(final String name, final PartialsObserver observer) {
  79.         partialsObservers.put(name, observer);
  80.     }

  81.     /** {@inheritDoc} */
  82.     @Override
  83.     public String getName() {
  84.         return stmName;
  85.     }

  86.     /** {@inheritDoc} */
  87.     @Override
  88.     public int getDimension() {
  89.         return STATE_DIMENSION * STATE_DIMENSION;
  90.     }

  91.     /** {@inheritDoc} */
  92.     @Override
  93.     public boolean yield(final SpacecraftState state) {
  94.         return !state.hasAdditionalState(getName());
  95.     }

  96.     /** Set the initial value of the State Transition Matrix.
  97.      * <p>
  98.      * The returned state must be added to the propagator.
  99.      * </p>
  100.      * @param state initial state
  101.      * @param dYdY0 initial State Transition Matrix ∂Y/∂Y₀,
  102.      * if null (which is the most frequent case), assumed to be 6x6 identity
  103.      * @param orbitType orbit type used for states Y and Y₀ in {@code dYdY0}
  104.      * @param positionAngle position angle used states Y and Y₀ in {@code dYdY0}
  105.      * @return state with initial STM (converted to Cartesian ∂C/∂Y₀) added
  106.      */
  107.     SpacecraftState setInitialStateTransitionMatrix(final SpacecraftState state,
  108.                                                     final RealMatrix dYdY0,
  109.                                                     final OrbitType orbitType,
  110.                                                     final PositionAngle positionAngle) {

  111.         final RealMatrix nonNullDYdY0;
  112.         if (dYdY0 == null) {
  113.             nonNullDYdY0 = MatrixUtils.createRealIdentityMatrix(STATE_DIMENSION);
  114.         } else {
  115.             if (dYdY0.getRowDimension() != STATE_DIMENSION ||
  116.                             dYdY0.getColumnDimension() != STATE_DIMENSION) {
  117.                 throw new OrekitException(LocalizedCoreFormats.DIMENSIONS_MISMATCH_2x2,
  118.                                           dYdY0.getRowDimension(), dYdY0.getColumnDimension(),
  119.                                           STATE_DIMENSION, STATE_DIMENSION);
  120.             }
  121.             nonNullDYdY0 = dYdY0;
  122.         }

  123.         // convert to Cartesian STM
  124.         final RealMatrix dCdY0;
  125.         if (state.isOrbitDefined()) {
  126.             final double[][] dYdC = new double[STATE_DIMENSION][STATE_DIMENSION];
  127.             orbitType.convertType(state.getOrbit()).getJacobianWrtCartesian(positionAngle, dYdC);
  128.             dCdY0 = new QRDecomposition(MatrixUtils.createRealMatrix(dYdC), THRESHOLD).getSolver().solve(nonNullDYdY0);
  129.         } else {
  130.             dCdY0 = nonNullDYdY0;
  131.         }

  132.         // flatten matrix
  133.         final double[] flat = new double[STATE_DIMENSION * STATE_DIMENSION];
  134.         int k = 0;
  135.         for (int i = 0; i < STATE_DIMENSION; ++i) {
  136.             for (int j = 0; j < STATE_DIMENSION; ++j) {
  137.                 flat[k++] = dCdY0.getEntry(i, j);
  138.             }
  139.         }

  140.         // set additional state
  141.         return state.addAdditionalState(stmName, flat);

  142.     }

  143.     /** {@inheritDoc} */
  144.     public double[] derivatives(final SpacecraftState state) {

  145.         // Assuming position is (px, py, pz), velocity is (vx, vy, vz) and the acceleration
  146.         // due to the force models is (Σ ax, Σ ay, Σ az), the differential equation for
  147.         // Cartesian State Transition Matrix ∂C/∂Y₀ for the contribution of all force models is:
  148.         //                   [     0          0          0            1          0          0   ]
  149.         //                   [     0          0          0            0          1          0   ]
  150.         //  d(∂C/∂Y₀)/dt  =  [     0          0          0            1          0          1   ] ⨯ ∂C/∂Y₀
  151.         //                   [Σ dax/dpx  Σ dax/dpy  Σ dax/dpz    Σ dax/dvx  Σ dax/dvy  Σ dax/dvz]
  152.         //                   [Σ day/dpx  Σ day/dpy  Σ dax/dpz    Σ day/dvx  Σ day/dvy  Σ dax/dvz]
  153.         //                   [Σ daz/dpx  Σ daz/dpy  Σ dax/dpz    Σ daz/dvx  Σ daz/dvy  Σ dax/dvz]
  154.         // some force models depend on velocity (either directly or through attitude),
  155.         // whereas some other force models depend only on position.
  156.         // For the latter, the lower right part of the matrix is zero
  157.         final double[] factor = computePartials(state);

  158.         // retrieve current State Transition Matrix
  159.         final double[] p    = state.getAdditionalState(getName());
  160.         final double[] pDot = new double[p.length];

  161.         // perform multiplication
  162.         multiplyMatrix(factor, p, pDot, STATE_DIMENSION);

  163.         return pDot;

  164.     }

  165.     /** Compute evolution matrix product.
  166.      * <p>
  167.      * This method computes \(Y = F \times X\) where the factor matrix is:
  168.      * \[F = \begin{matrix}
  169.      *               0         &             0         &             0         &             1         &             0         &             0        \\
  170.      *               0         &             0         &             0         &             0         &             1         &             0        \\
  171.      *               0         &             0         &             0         &             0         &             0         &             1        \\
  172.      *  \sum \frac{da_x}{dp_x} & \sum\frac{da_x}{dp_y} & \sum\frac{da_x}{dp_z} & \sum\frac{da_x}{dv_x} & \sum\frac{da_x}{dv_y} & \sum\frac{da_x}{dv_z}\\
  173.      *  \sum \frac{da_y}{dp_x} & \sum\frac{da_y}{dp_y} & \sum\frac{da_y}{dp_z} & \sum\frac{da_y}{dv_x} & \sum\frac{da_y}{dv_y} & \sum\frac{da_y}{dv_z}\\
  174.      *  \sum \frac{da_z}{dp_x} & \sum\frac{da_z}{dp_y} & \sum\frac{da_z}{dp_z} & \sum\frac{da_z}{dv_x} & \sum\frac{da_z}{dv_y} & \sum\frac{da_z}{dv_z}
  175.      * \end{matrix}\]
  176.      * </p>
  177.      * @param factor factor matrix
  178.      * @param x right factor of the multiplication, as a flatten array in row major order
  179.      * @param y placeholder where to put the result, as a flatten array in row major order
  180.      * @param columns number of columns of both x and y (so their dimensions are 6 x columns)
  181.      */
  182.     static void multiplyMatrix(final double[] factor, final double[] x, final double[] y, final int columns) {

  183.         final int n = SPACE_DIMENSION * columns;

  184.         // handle first three rows by a simple copy
  185.         System.arraycopy(x, n, y, 0, n);

  186.         // regular multiplication for the last three rows
  187.         for (int j = 0; j < columns; ++j) {
  188.             y[n + j              ] = factor[ 0] * x[j              ] + factor[ 1] * x[j +     columns] + factor[ 2] * x[j + 2 * columns] +
  189.                                      factor[ 3] * x[j + 3 * columns] + factor[ 4] * x[j + 4 * columns] + factor[ 5] * x[j + 5 * columns];
  190.             y[n + j +     columns] = factor[ 6] * x[j              ] + factor[ 7] * x[j +     columns] + factor[ 8] * x[j + 2 * columns] +
  191.                                      factor[ 9] * x[j + 3 * columns] + factor[10] * x[j + 4 * columns] + factor[11] * x[j + 5 * columns];
  192.             y[n + j + 2 * columns] = factor[12] * x[j              ] + factor[13] * x[j +     columns] + factor[14] * x[j + 2 * columns] +
  193.                                      factor[15] * x[j + 3 * columns] + factor[16] * x[j + 4 * columns] + factor[17] * x[j + 5 * columns];
  194.         }

  195.     }

  196.     /** Compute the various partial derivatives.
  197.      * @param state current spacecraft state
  198.      * @return factor matrix
  199.      */
  200.     private double[] computePartials(final SpacecraftState state) {

  201.         // set up containers for partial derivatives
  202.         final double[]              factor               = new double[SPACE_DIMENSION * STATE_DIMENSION];
  203.         final DoubleArrayDictionary accelerationPartials = new DoubleArrayDictionary();

  204.         // evaluate contribution of all force models
  205.         final NumericalGradientConverter fullConverter    = new NumericalGradientConverter(state, STATE_DIMENSION, attitudeProvider);
  206.         final NumericalGradientConverter posOnlyConverter = new NumericalGradientConverter(state, SPACE_DIMENSION, attitudeProvider);
  207.         for (final ForceModel forceModel : forceModels) {

  208.             final NumericalGradientConverter     converter    = forceModel.dependsOnPositionOnly() ? posOnlyConverter : fullConverter;
  209.             final FieldSpacecraftState<Gradient> dsState      = converter.getState(forceModel);
  210.             final Gradient[]                     parameters   = converter.getParameters(dsState, forceModel);
  211.             final FieldVector3D<Gradient>        acceleration = forceModel.acceleration(dsState, parameters);
  212.             final double[]                       gradX        = acceleration.getX().getGradient();
  213.             final double[]                       gradY        = acceleration.getY().getGradient();
  214.             final double[]                       gradZ        = acceleration.getZ().getGradient();

  215.             // lower left part of the factor matrix
  216.             factor[ 0] += gradX[0];
  217.             factor[ 1] += gradX[1];
  218.             factor[ 2] += gradX[2];
  219.             factor[ 6] += gradY[0];
  220.             factor[ 7] += gradY[1];
  221.             factor[ 8] += gradY[2];
  222.             factor[12] += gradZ[0];
  223.             factor[13] += gradZ[1];
  224.             factor[14] += gradZ[2];

  225.             if (!forceModel.dependsOnPositionOnly()) {
  226.                 // lower right part of the factor matrix
  227.                 factor[ 3] += gradX[3];
  228.                 factor[ 4] += gradX[4];
  229.                 factor[ 5] += gradX[5];
  230.                 factor[ 9] += gradY[3];
  231.                 factor[10] += gradY[4];
  232.                 factor[11] += gradY[5];
  233.                 factor[15] += gradZ[3];
  234.                 factor[16] += gradZ[4];
  235.                 factor[17] += gradZ[5];
  236.             }

  237.             // partials derivatives with respect to parameters
  238.             int paramsIndex = converter.getFreeStateParameters();
  239.             for (ParameterDriver driver : forceModel.getParametersDrivers()) {
  240.                 if (driver.isSelected()) {

  241.                     // get the partials derivatives for this driver
  242.                     DoubleArrayDictionary.Entry entry = accelerationPartials.getEntry(driver.getName());
  243.                     if (entry == null) {
  244.                         // create an entry filled with zeroes
  245.                         accelerationPartials.put(driver.getName(), new double[SPACE_DIMENSION]);
  246.                         entry = accelerationPartials.getEntry(driver.getName());
  247.                     }

  248.                     // add the contribution of the current force model
  249.                     entry.increment(new double[] {
  250.                         gradX[paramsIndex], gradY[paramsIndex], gradZ[paramsIndex]
  251.                     });
  252.                     ++paramsIndex;

  253.                 }
  254.             }

  255.             // notify observers
  256.             for (Map.Entry<String, PartialsObserver> observersEntry : partialsObservers.entrySet()) {
  257.                 final DoubleArrayDictionary.Entry entry = accelerationPartials.getEntry(observersEntry.getKey());
  258.                 observersEntry.getValue().partialsComputed(state, factor, entry == null ? new double[SPACE_DIMENSION] : entry.getValue());
  259.             }

  260.         }

  261.         return factor;

  262.     }

  263.     /** Interface for observing partials derivatives. */
  264.     public interface PartialsObserver {

  265.         /** Callback called when partial derivatives have been computed.
  266.          * <p>
  267.          * The factor matrix is:
  268.          * \[F = \begin{matrix}
  269.          *               0         &             0         &             0         &             1         &             0         &             0        \\
  270.          *               0         &             0         &             0         &             0         &             1         &             0        \\
  271.          *               0         &             0         &             0         &             0         &             0         &             1        \\
  272.          *  \sum \frac{da_x}{dp_x} & \sum\frac{da_x}{dp_y} & \sum\frac{da_x}{dp_z} & \sum\frac{da_x}{dv_x} & \sum\frac{da_x}{dv_y} & \sum\frac{da_x}{dv_z}\\
  273.          *  \sum \frac{da_y}{dp_x} & \sum\frac{da_y}{dp_y} & \sum\frac{da_y}{dp_z} & \sum\frac{da_y}{dv_x} & \sum\frac{da_y}{dv_y} & \sum\frac{da_y}{dv_z}\\
  274.          *  \sum \frac{da_z}{dp_x} & \sum\frac{da_z}{dp_y} & \sum\frac{da_z}{dp_z} & \sum\frac{da_z}{dv_x} & \sum\frac{da_z}{dv_y} & \sum\frac{da_z}{dv_z}
  275.          * \end{matrix}\]
  276.          * </p>
  277.          * @param state current spacecraft state
  278.          * @param factor factor matrix, flattened along rows
  279.          * @param accelerationPartials partials derivatives of acceleration with respect to the parameter driver
  280.          * that was registered (zero if no parameters were not selected or parameter is unknown)
  281.          */
  282.         void partialsComputed(SpacecraftState state, double[] factor, double[] accelerationPartials);

  283.     }

  284. }