StateTransitionMatrixGenerator.java

  1. /* Copyright 2002-2024 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.attitudes.AttitudeProviderModifier;
  30. import org.orekit.errors.OrekitException;
  31. import org.orekit.forces.ForceModel;
  32. import org.orekit.orbits.OrbitType;
  33. import org.orekit.orbits.PositionAngleType;
  34. import org.orekit.propagation.FieldSpacecraftState;
  35. import org.orekit.propagation.SpacecraftState;
  36. import org.orekit.propagation.integration.AdditionalDerivativesProvider;
  37. import org.orekit.propagation.integration.CombinedDerivatives;
  38. import org.orekit.utils.DoubleArrayDictionary;
  39. import org.orekit.utils.ParameterDriver;
  40. import org.orekit.utils.TimeSpanMap.Span;

  41. /** Generator for State Transition Matrix.
  42.  * @author Luc Maisonobe
  43.  * @author Melina Vanel
  44.  * @since 11.1
  45.  */
  46. class StateTransitionMatrixGenerator implements AdditionalDerivativesProvider {

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

  49.     /** Space dimension. */
  50.     private static final int SPACE_DIMENSION = 3;

  51.     /** State dimension. */
  52.     public static final int STATE_DIMENSION = 2 * SPACE_DIMENSION;

  53.     /** Name of the Cartesian STM additional state. */
  54.     private final String stmName;

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

  57.     /** Attitude provider used in propagation. */
  58.     private final AttitudeProvider attitudeProvider;

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

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

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

  85.     /** {@inheritDoc} */
  86.     @Override
  87.     public String getName() {
  88.         return stmName;
  89.     }

  90.     /** {@inheritDoc} */
  91.     @Override
  92.     public int getDimension() {
  93.         return STATE_DIMENSION * STATE_DIMENSION;
  94.     }

  95.     /** {@inheritDoc} */
  96.     @Override
  97.     public boolean yields(final SpacecraftState state) {
  98.         return !state.hasAdditionalState(getName());
  99.     }

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

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

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

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

  144.         // set additional state
  145.         return state.addAdditionalState(stmName, flat);

  146.     }

  147.     /** {@inheritDoc} */
  148.     public CombinedDerivatives combinedDerivatives(final SpacecraftState state) {

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

  162.         // retrieve current State Transition Matrix
  163.         final double[] p    = state.getAdditionalState(getName());
  164.         final double[] pDot = new double[p.length];

  165.         // perform multiplication
  166.         multiplyMatrix(factor, p, pDot, STATE_DIMENSION);

  167.         return new CombinedDerivatives(pDot, null);

  168.     }

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

  187.         final int n = SPACE_DIMENSION * columns;

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

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

  199.     }

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

  205.         // set up containers for partial derivatives
  206.         final double[]              factor               = new double[SPACE_DIMENSION * STATE_DIMENSION];
  207.         final DoubleArrayDictionary accelerationPartials = new DoubleArrayDictionary();

  208.         // evaluate contribution of all force models
  209.         final AttitudeProvider equivalentAttitudeProvider = wrapAttitudeProviderIfPossible(forceModels, attitudeProvider);
  210.         final boolean isThereAnyForceNotDependingOnlyOnPosition = forceModels.stream().anyMatch(force -> !force.dependsOnPositionOnly());
  211.         final NumericalGradientConverter posOnlyConverter = new NumericalGradientConverter(state, SPACE_DIMENSION, equivalentAttitudeProvider);
  212.         final NumericalGradientConverter fullConverter = isThereAnyForceNotDependingOnlyOnPosition ?
  213.             new NumericalGradientConverter(state, STATE_DIMENSION, equivalentAttitudeProvider) : posOnlyConverter;

  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.getParametersAtStateDate(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.                     // for each span (for each estimated value) corresponding name is added
  249.                     for (Span<String> span = driver.getNamesSpanMap().getFirstSpan(); span != null; span = span.next()) {

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

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

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

  270.         }

  271.         return factor;

  272.     }

  273.     /**
  274.      * Method that first checks if it is possible to replace the attitude provider with a computationally cheaper one
  275.      * to evaluate. If applicable, the new provider only computes the rotation and uses dummy rate and acceleration,
  276.      * since they should not be used later on.
  277.      * @param forceModels list of forces
  278.      * @param attitudeProvider original attitude provider
  279.      * @return same provider if at least one forces used attitude derivatives, otherwise one wrapping the old one for
  280.      * the rotation
  281.      */
  282.     private static AttitudeProvider wrapAttitudeProviderIfPossible(final List<ForceModel> forceModels,
  283.                                                                    final AttitudeProvider attitudeProvider) {
  284.         if (forceModels.stream().anyMatch(ForceModel::dependsOnAttitudeRate)) {
  285.             // at least one force uses an attitude rate, need to keep the original provider
  286.             return attitudeProvider;
  287.         } else {
  288.             // the original provider can be replaced by a lighter one for performance
  289.             return AttitudeProviderModifier.getFrozenAttitudeProvider(attitudeProvider);
  290.         }
  291.     }

  292.     /** Interface for observing partials derivatives. */
  293.     public interface PartialsObserver {

  294.         /** Callback called when partial derivatives have been computed.
  295.          * <p>
  296.          * The factor matrix is:
  297.          * \[F = \begin{matrix}
  298.          *               0         &             0         &             0         &             1         &             0         &             0        \\
  299.          *               0         &             0         &             0         &             0         &             1         &             0        \\
  300.          *               0         &             0         &             0         &             0         &             0         &             1        \\
  301.          *  \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}\\
  302.          *  \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}\\
  303.          *  \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}
  304.          * \end{matrix}\]
  305.          * </p>
  306.          * @param state current spacecraft state
  307.          * @param factor factor matrix, flattened along rows
  308.          * @param accelerationPartials partials derivatives of acceleration with respect to the parameter driver
  309.          * that was registered (zero if no parameters were not selected or parameter is unknown)
  310.          */
  311.         void partialsComputed(SpacecraftState state, double[] factor, double[] accelerationPartials);

  312.     }

  313. }