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.propagation.integration.CombinedDerivatives;
  37. import org.orekit.utils.DoubleArrayDictionary;
  38. import org.orekit.utils.ParameterDriver;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  143.     }

  144.     /** {@inheritDoc} */
  145.     @Override
  146.     @Deprecated
  147.     public double[] derivatives(final SpacecraftState state) {
  148.         return combinedDerivatives(state).getAdditionalDerivatives();
  149.     }

  150.     /** {@inheritDoc} */
  151.     public CombinedDerivatives combinedDerivatives(final SpacecraftState state) {

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

  165.         // retrieve current State Transition Matrix
  166.         final double[] p    = state.getAdditionalState(getName());
  167.         final double[] pDot = new double[p.length];

  168.         // perform multiplication
  169.         multiplyMatrix(factor, p, pDot, STATE_DIMENSION);

  170.         return new CombinedDerivatives(pDot, null);

  171.     }

  172.     /** Compute evolution matrix product.
  173.      * <p>
  174.      * This method computes \(Y = F \times X\) where the factor matrix is:
  175.      * \[F = \begin{matrix}
  176.      *               0         &             0         &             0         &             1         &             0         &             0        \\
  177.      *               0         &             0         &             0         &             0         &             1         &             0        \\
  178.      *               0         &             0         &             0         &             0         &             0         &             1        \\
  179.      *  \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}\\
  180.      *  \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}\\
  181.      *  \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}
  182.      * \end{matrix}\]
  183.      * </p>
  184.      * @param factor factor matrix
  185.      * @param x right factor of the multiplication, as a flatten array in row major order
  186.      * @param y placeholder where to put the result, as a flatten array in row major order
  187.      * @param columns number of columns of both x and y (so their dimensions are 6 x columns)
  188.      */
  189.     static void multiplyMatrix(final double[] factor, final double[] x, final double[] y, final int columns) {

  190.         final int n = SPACE_DIMENSION * columns;

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

  193.         // regular multiplication for the last three rows
  194.         for (int j = 0; j < columns; ++j) {
  195.             y[n + j              ] = factor[ 0] * x[j              ] + factor[ 1] * x[j +     columns] + factor[ 2] * x[j + 2 * columns] +
  196.                                      factor[ 3] * x[j + 3 * columns] + factor[ 4] * x[j + 4 * columns] + factor[ 5] * x[j + 5 * columns];
  197.             y[n + j +     columns] = factor[ 6] * x[j              ] + factor[ 7] * x[j +     columns] + factor[ 8] * x[j + 2 * columns] +
  198.                                      factor[ 9] * x[j + 3 * columns] + factor[10] * x[j + 4 * columns] + factor[11] * x[j + 5 * columns];
  199.             y[n + j + 2 * columns] = factor[12] * x[j              ] + factor[13] * x[j +     columns] + factor[14] * x[j + 2 * columns] +
  200.                                      factor[15] * x[j + 3 * columns] + factor[16] * x[j + 4 * columns] + factor[17] * x[j + 5 * columns];
  201.         }

  202.     }

  203.     /** Compute the various partial derivatives.
  204.      * @param state current spacecraft state
  205.      * @return factor matrix
  206.      */
  207.     private double[] computePartials(final SpacecraftState state) {

  208.         // set up containers for partial derivatives
  209.         final double[]              factor               = new double[SPACE_DIMENSION * STATE_DIMENSION];
  210.         final DoubleArrayDictionary accelerationPartials = new DoubleArrayDictionary();

  211.         // evaluate contribution of all force models
  212.         final NumericalGradientConverter fullConverter    = new NumericalGradientConverter(state, STATE_DIMENSION, attitudeProvider);
  213.         final NumericalGradientConverter posOnlyConverter = new NumericalGradientConverter(state, SPACE_DIMENSION, attitudeProvider);
  214.         for (final ForceModel forceModel : forceModels) {

  215.             final NumericalGradientConverter     converter    = forceModel.dependsOnPositionOnly() ? posOnlyConverter : fullConverter;
  216.             final FieldSpacecraftState<Gradient> dsState      = converter.getState(forceModel);
  217.             final Gradient[]                     parameters   = converter.getParameters(dsState, forceModel);
  218.             final FieldVector3D<Gradient>        acceleration = forceModel.acceleration(dsState, parameters);
  219.             final double[]                       gradX        = acceleration.getX().getGradient();
  220.             final double[]                       gradY        = acceleration.getY().getGradient();
  221.             final double[]                       gradZ        = acceleration.getZ().getGradient();

  222.             // lower left part of the factor matrix
  223.             factor[ 0] += gradX[0];
  224.             factor[ 1] += gradX[1];
  225.             factor[ 2] += gradX[2];
  226.             factor[ 6] += gradY[0];
  227.             factor[ 7] += gradY[1];
  228.             factor[ 8] += gradY[2];
  229.             factor[12] += gradZ[0];
  230.             factor[13] += gradZ[1];
  231.             factor[14] += gradZ[2];

  232.             if (!forceModel.dependsOnPositionOnly()) {
  233.                 // lower right part of the factor matrix
  234.                 factor[ 3] += gradX[3];
  235.                 factor[ 4] += gradX[4];
  236.                 factor[ 5] += gradX[5];
  237.                 factor[ 9] += gradY[3];
  238.                 factor[10] += gradY[4];
  239.                 factor[11] += gradY[5];
  240.                 factor[15] += gradZ[3];
  241.                 factor[16] += gradZ[4];
  242.                 factor[17] += gradZ[5];
  243.             }

  244.             // partials derivatives with respect to parameters
  245.             int paramsIndex = converter.getFreeStateParameters();
  246.             for (ParameterDriver driver : forceModel.getParametersDrivers()) {
  247.                 if (driver.isSelected()) {

  248.                     // get the partials derivatives for this driver
  249.                     DoubleArrayDictionary.Entry entry = accelerationPartials.getEntry(driver.getName());
  250.                     if (entry == null) {
  251.                         // create an entry filled with zeroes
  252.                         accelerationPartials.put(driver.getName(), new double[SPACE_DIMENSION]);
  253.                         entry = accelerationPartials.getEntry(driver.getName());
  254.                     }

  255.                     // add the contribution of the current force model
  256.                     entry.increment(new double[] {
  257.                         gradX[paramsIndex], gradY[paramsIndex], gradZ[paramsIndex]
  258.                     });
  259.                     ++paramsIndex;

  260.                 }
  261.             }

  262.             // notify observers
  263.             for (Map.Entry<String, PartialsObserver> observersEntry : partialsObservers.entrySet()) {
  264.                 final DoubleArrayDictionary.Entry entry = accelerationPartials.getEntry(observersEntry.getKey());
  265.                 observersEntry.getValue().partialsComputed(state, factor, entry == null ? new double[SPACE_DIMENSION] : entry.getValue());
  266.             }

  267.         }

  268.         return factor;

  269.     }

  270.     /** Interface for observing partials derivatives. */
  271.     public interface PartialsObserver {

  272.         /** Callback called when partial derivatives have been computed.
  273.          * <p>
  274.          * The factor matrix is:
  275.          * \[F = \begin{matrix}
  276.          *               0         &             0         &             0         &             1         &             0         &             0        \\
  277.          *               0         &             0         &             0         &             0         &             1         &             0        \\
  278.          *               0         &             0         &             0         &             0         &             0         &             1        \\
  279.          *  \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}\\
  280.          *  \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}\\
  281.          *  \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}
  282.          * \end{matrix}\]
  283.          * </p>
  284.          * @param state current spacecraft state
  285.          * @param factor factor matrix, flattened along rows
  286.          * @param accelerationPartials partials derivatives of acceleration with respect to the parameter driver
  287.          * that was registered (zero if no parameters were not selected or parameter is unknown)
  288.          */
  289.         void partialsComputed(SpacecraftState state, double[] factor, double[] accelerationPartials);

  290.     }

  291. }