DSSTStateTransitionMatrixGenerator.java

  1. /* Copyright 2002-2025 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.semianalytical.dsst;

  18. import org.hipparchus.analysis.differentiation.Gradient;
  19. import org.hipparchus.exception.LocalizedCoreFormats;
  20. import org.hipparchus.linear.MatrixUtils;
  21. import org.hipparchus.linear.RealMatrix;
  22. import org.orekit.attitudes.AttitudeProvider;
  23. import org.orekit.errors.OrekitException;
  24. import org.orekit.propagation.FieldSpacecraftState;
  25. import org.orekit.propagation.PropagationType;
  26. import org.orekit.propagation.SpacecraftState;
  27. import org.orekit.propagation.integration.AdditionalDerivativesProvider;
  28. import org.orekit.propagation.integration.CombinedDerivatives;
  29. import org.orekit.propagation.semianalytical.dsst.forces.DSSTForceModel;
  30. import org.orekit.propagation.semianalytical.dsst.utilities.FieldAuxiliaryElements;
  31. import org.orekit.time.AbsoluteDate;
  32. import org.orekit.utils.DoubleArrayDictionary;
  33. import org.orekit.utils.ParameterDriver;
  34. import org.orekit.utils.TimeSpanMap.Span;

  35. import java.util.HashMap;
  36. import java.util.List;
  37. import java.util.Map;

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

  43.     /** Space dimension. */
  44.     private static final int SPACE_DIMENSION = 3;

  45.     /** Retrograde factor I.
  46.      *  <p>
  47.      *  DSST model needs equinoctial orbit as internal representation.
  48.      *  Classical equinoctial elements have discontinuities when inclination
  49.      *  is close to zero. In this representation, I = +1. <br>
  50.      *  To avoid this discontinuity, another representation exists and equinoctial
  51.      *  elements can be expressed in a different way, called "retrograde" orbit.
  52.      *  This implies I = -1. <br>
  53.      *  As Orekit doesn't implement the retrograde orbit, I is always set to +1.
  54.      *  But for the sake of consistency with the theory, the retrograde factor
  55.      *  has been kept in the formulas.
  56.      *  </p>
  57.      */
  58.     private static final int I = 1;

  59.     /** State dimension. */
  60.     public static final int STATE_DIMENSION = 2 * SPACE_DIMENSION;

  61.     /** Name of the Cartesian STM additional state. */
  62.     private final String stmName;

  63.     /** Force models used in propagation. */
  64.     private final List<DSSTForceModel> forceModels;

  65.     /** Attitude provider used in propagation. */
  66.     private final AttitudeProvider attitudeProvider;

  67.     /** Observers for partial derivatives. */
  68.     private final Map<String, DSSTPartialsObserver> partialsObservers;

  69.     /** Mean or osculating. */
  70.     private final PropagationType propagationType;

  71.     /** Simple constructor.
  72.      * @param stmName name of the Cartesian STM additional state
  73.      * @param forceModels force models used in propagation
  74.      * @param attitudeProvider attitude provider used in propagation
  75.      * @param propagationType mean or osculating.
  76.      */
  77.     DSSTStateTransitionMatrixGenerator(final String stmName,
  78.                                        final List<DSSTForceModel> forceModels,
  79.                                        final AttitudeProvider attitudeProvider,
  80.                                        final PropagationType propagationType) {
  81.         this.stmName           = stmName;
  82.         this.forceModels       = forceModels;
  83.         this.attitudeProvider  = attitudeProvider;
  84.         this.propagationType   = propagationType;
  85.         this.partialsObservers = new HashMap<>();
  86.     }

  87.     /** Register an observer for partial derivatives.
  88.      * <p>
  89.      * The observer {@link DSSTPartialsObserver#partialsComputed(SpacecraftState, RealMatrix, double[])} partialsComputed}
  90.      * method will be called when partial derivatives are computed, as a side effect of
  91.      * calling {@link #computePartials(SpacecraftState)} (SpacecraftState)}
  92.      * </p>
  93.      * @param name name of the parameter driver this observer is interested in (may be null)
  94.      * @param observer observer to register
  95.      */
  96.     void addObserver(final String name, final DSSTPartialsObserver observer) {
  97.         partialsObservers.put(name, observer);
  98.     }

  99.     /** {@inheritDoc} */
  100.     @Override
  101.     public String getName() {
  102.         return stmName;
  103.     }

  104.     /** {@inheritDoc} */
  105.     @Override
  106.     public int getDimension() {
  107.         return STATE_DIMENSION * STATE_DIMENSION;
  108.     }

  109.     @Override
  110.     @SuppressWarnings("unchecked")
  111.     public void init(final SpacecraftState initialState, final AbsoluteDate target) {
  112.         // initialize short period terms.
  113.         // the propagator will have called the non-field method
  114.         // so just call the field method here
  115.         // This should be a Field copy of the code in DSSTPropagator.beforeIntegration(...)
  116.         // but with just the short period initialization calls
  117.         // See also how the field state is set up in computePartials(...)

  118.         final DSSTGradientConverter converter =
  119.                 new DSSTGradientConverter(initialState, attitudeProvider);

  120.         // check if only mean elements must be used
  121.         final PropagationType type = propagationType;

  122.         // initialize all perturbing forces
  123.         for (final DSSTForceModel forceModel : forceModels) {
  124.             final FieldSpacecraftState<Gradient> dsState = converter.getState(forceModel);
  125.             final Gradient[] parameters = converter.getParametersAtStateDate(dsState, forceModel);
  126.             final FieldAuxiliaryElements<Gradient> auxiliaryElements = new FieldAuxiliaryElements<>(dsState.getOrbit(), I);
  127.             forceModel.initializeShortPeriodTerms(auxiliaryElements, type, parameters);
  128.         }

  129.         // if required, insert the special short periodics step handler
  130.         if (type == PropagationType.OSCULATING) {
  131.             // Compute short periodic coefficients for this point
  132.             for (DSSTForceModel forceModel : forceModels) {
  133.                 final FieldSpacecraftState<Gradient> dsState = converter.getState(forceModel);
  134.                 final Gradient[] parameters = converter.getParametersAtStateDate(dsState, forceModel);
  135.                 forceModel.updateShortPeriodTerms(parameters, dsState);
  136.             }
  137.         }

  138.     }

  139.     /** {@inheritDoc} */
  140.     @Override
  141.     public boolean yields(final SpacecraftState state) {
  142.         return !state.hasAdditionalData(getName());
  143.     }

  144.     /** Set the initial value of the State Transition Matrix.
  145.      * <p>
  146.      * The returned state must be added to the propagator.
  147.      * </p>
  148.      * @param state initial state
  149.      * @param dYdY0 initial State Transition Matrix ∂Y/∂Y₀,
  150.      * if null (which is the most frequent case), assumed to be 6x6 identity
  151.      * @return state with initial STM (converted to Cartesian ∂C/∂Y₀) added
  152.      */
  153.     SpacecraftState setInitialStateTransitionMatrix(final SpacecraftState state, final RealMatrix dYdY0) {

  154.         if (dYdY0 != null) {
  155.             if (dYdY0.getRowDimension() != STATE_DIMENSION ||
  156.                             dYdY0.getColumnDimension() != STATE_DIMENSION) {
  157.                 throw new OrekitException(LocalizedCoreFormats.DIMENSIONS_MISMATCH_2x2,
  158.                                           dYdY0.getRowDimension(), dYdY0.getColumnDimension(),
  159.                                           STATE_DIMENSION, STATE_DIMENSION);
  160.             }
  161.         }

  162.         // flatten matrix
  163.         final double[] flat = new double[STATE_DIMENSION * STATE_DIMENSION];
  164.         int k = 0;
  165.         for (int i = 0; i < STATE_DIMENSION; ++i) {
  166.             for (int j = 0; j < STATE_DIMENSION; ++j) {
  167.                 flat[k++] = dYdY0.getEntry(i, j);
  168.             }
  169.         }

  170.         // set additional state
  171.         return state.addAdditionalData(stmName, flat);

  172.     }

  173.     /** {@inheritDoc} */
  174.     public CombinedDerivatives combinedDerivatives(final SpacecraftState state) {

  175.         final double[] p = state.getAdditionalState(getName());
  176.         final double[] res = new double[p.length];

  177.         // perform matrix multiplication with matrices flatten
  178.         final RealMatrix factor = computePartials(state);
  179.         int index = 0;
  180.         for (int i = 0; i < STATE_DIMENSION; ++i) {
  181.             for (int j = 0; j < STATE_DIMENSION; ++j) {
  182.                 double sum = 0;
  183.                 for (int k = 0; k < STATE_DIMENSION; ++k) {
  184.                     sum += factor.getEntry(i, k) * p[j + k * STATE_DIMENSION];
  185.                 }
  186.                 res[index++] = sum;
  187.             }
  188.         }

  189.         return new CombinedDerivatives(res, null);

  190.     }

  191.     /** Compute the various partial derivatives.
  192.      * @param state current spacecraft state
  193.      * @return factor matrix
  194.      */
  195.     private RealMatrix computePartials(final SpacecraftState state) {

  196.         // set up containers for partial derivatives
  197.         final RealMatrix            factor               = MatrixUtils.createRealMatrix(STATE_DIMENSION, STATE_DIMENSION);
  198.         final DoubleArrayDictionary meanElementsPartials = new DoubleArrayDictionary();
  199.         final DSSTGradientConverter converter            = new DSSTGradientConverter(state, attitudeProvider);

  200.         // Compute Jacobian
  201.         for (final DSSTForceModel forceModel : forceModels) {

  202.             final FieldSpacecraftState<Gradient> dsState = converter.getState(forceModel);
  203.             final Gradient[] parameters = converter.getParametersAtStateDate(dsState, forceModel);
  204.             final FieldAuxiliaryElements<Gradient> auxiliaryElements = new FieldAuxiliaryElements<>(dsState.getOrbit(), I);

  205.             final Gradient[] meanElementRate = forceModel.getMeanElementRate(dsState, auxiliaryElements, parameters);
  206.             final double[] derivativesA  = meanElementRate[0].getGradient();
  207.             final double[] derivativesEx = meanElementRate[1].getGradient();
  208.             final double[] derivativesEy = meanElementRate[2].getGradient();
  209.             final double[] derivativesHx = meanElementRate[3].getGradient();
  210.             final double[] derivativesHy = meanElementRate[4].getGradient();
  211.             final double[] derivativesL  = meanElementRate[5].getGradient();

  212.             // update Jacobian with respect to state
  213.             addToRow(derivativesA,  0, factor);
  214.             addToRow(derivativesEx, 1, factor);
  215.             addToRow(derivativesEy, 2, factor);
  216.             addToRow(derivativesHx, 3, factor);
  217.             addToRow(derivativesHy, 4, factor);
  218.             addToRow(derivativesL,  5, factor);

  219.             // partials derivatives with respect to parameters
  220.             int paramsIndex = converter.getFreeStateParameters();
  221.             for (ParameterDriver driver : forceModel.getParametersDrivers()) {
  222.                 if (driver.isSelected()) {
  223.                     // for each span (for each estimated value) corresponding name is added
  224.                     for (Span<String> span = driver.getNamesSpanMap().getFirstSpan(); span != null; span = span.next()) {

  225.                         // get the partials derivatives for this driver
  226.                         DoubleArrayDictionary.Entry entry = meanElementsPartials.getEntry(span.getData());
  227.                         if (entry == null) {
  228.                             // create an entry filled with zeroes
  229.                             meanElementsPartials.put(span.getData(), new double[STATE_DIMENSION]);
  230.                             entry = meanElementsPartials.getEntry(span.getData());
  231.                         }
  232.                         // add the contribution of the current force model
  233.                         entry.increment(new double[] {
  234.                             derivativesA[paramsIndex], derivativesEx[paramsIndex], derivativesEy[paramsIndex],
  235.                             derivativesHx[paramsIndex], derivativesHy[paramsIndex], derivativesL[paramsIndex]
  236.                         });
  237.                         ++paramsIndex;
  238.                     }

  239.                 }
  240.             }

  241.         }

  242.         // notify observers
  243.         for (Map.Entry<String, DSSTPartialsObserver> observersEntry : partialsObservers.entrySet()) {
  244.             final DoubleArrayDictionary.Entry entry = meanElementsPartials.getEntry(observersEntry.getKey());
  245.             observersEntry.getValue().partialsComputed(state, factor, entry == null ? new double[STATE_DIMENSION] : entry.getValue());
  246.         }

  247.         return factor;

  248.     }

  249.     /** Fill Jacobians rows.
  250.      * @param derivatives derivatives of a component
  251.      * @param index component index (0 for a, 1 for ex, 2 for ey, 3 for hx, 4 for hy, 5 for l)
  252.      * @param factor Jacobian of mean elements rate with respect to mean elements
  253.      */
  254.     private void addToRow(final double[] derivatives, final int index, final RealMatrix factor) {
  255.         for (int i = 0; i < 6; i++) {
  256.             factor.addToEntry(index, i, derivatives[i]);
  257.         }
  258.     }

  259.     /** Interface for observing partials derivatives. */
  260.     @FunctionalInterface
  261.     public interface DSSTPartialsObserver {

  262.         /** Callback called when partial derivatives have been computed.
  263.          * @param state current spacecraft state
  264.          * @param factor factor matrix
  265.          * @param meanElementsPartials partials derivatives of mean elements rates with respect to the parameter driver
  266.          * that was registered (zero if no parameters were not selected or parameter is unknown)
  267.          */
  268.         void partialsComputed(SpacecraftState state, RealMatrix factor, double[] meanElementsPartials);

  269.     }

  270. }