1   /* Copyright 2002-2026 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  
19  import org.hipparchus.analysis.differentiation.Gradient;
20  import org.hipparchus.geometry.euclidean.threed.FieldVector3D;
21  import org.hipparchus.linear.Array2DRowRealMatrix;
22  import org.hipparchus.linear.DecompositionSolver;
23  import org.hipparchus.linear.MatrixUtils;
24  import org.hipparchus.linear.QRDecomposition;
25  import org.hipparchus.linear.RealMatrix;
26  import org.orekit.errors.OrekitException;
27  import org.orekit.errors.OrekitMessages;
28  import org.orekit.forces.ForceModel;
29  import org.orekit.forces.gravity.ThirdBodyAttractionEpoch;
30  import org.orekit.propagation.FieldSpacecraftState;
31  import org.orekit.propagation.SpacecraftState;
32  import org.orekit.propagation.integration.AdditionalDerivativesProvider;
33  import org.orekit.propagation.integration.CombinedDerivatives;
34  import org.orekit.utils.drivers.ParameterDriver;
35  import org.orekit.utils.drivers.ParameterDriversList;
36  
37  import java.util.IdentityHashMap;
38  import java.util.Map;
39  
40  /** Computes derivatives of the acceleration, including ThirdBodyAttraction.
41   * <p>
42   * {@link AdditionalDerivativesProvider Provider} computing the partial derivatives
43   * of the state (orbit) with respect to initial state and force models parameters.
44   * </p>
45   * <p>
46   * This set of equations are automatically added to a {@link NumericalPropagator numerical propagator}
47   * in order to compute partial derivatives of the orbit along with the orbit itself. This is
48   * useful for example in orbit determination applications.
49   * </p>
50   * <p>
51   * The partial derivatives with respect to initial state can be either dimension 6
52   * (orbit only) or 7 (orbit and mass).
53   * </p>
54   * <p>
55   * The partial derivatives with respect to force models parameters has a dimension
56   * equal to the number of selected parameters. Parameters selection is implemented at
57   * {@link ForceModel force models} level. Users must retrieve a {@link ParameterDriver
58   * parameter driver} using {@link ForceModel#getParameterDriver(String)} and then
59   * select it by calling {@link ParameterDriver#setSelected(boolean) setSelected(true)}.
60   * </p>
61   * <p>
62   * If several force models provide different {@link ParameterDriver drivers} for the
63   * same parameter name, selecting any of these drivers has the side effect of
64   * selecting all the drivers for this shared parameter. In this case, the partial
65   * derivatives will be the sum of the partial derivatives contributed by the
66   * corresponding force models. This case typically arises for central attraction
67   * coefficient, which has an influence on {@link org.orekit.forces.gravity.NewtonianAttraction
68   * Newtonian attraction}, {@link org.orekit.forces.gravity.HolmesFeatherstoneAttractionModel
69   * gravity field}, and {@link org.orekit.forces.gravity.Relativity relativity}.
70   * </p>
71   * @author V&eacute;ronique Pommier-Maurussane
72   * @author Luc Maisonobe
73   * @since 10.2
74   */
75  public class EpochDerivativesEquations
76      implements AdditionalDerivativesProvider  {
77  
78      /** State dimension, fixed to 6. */
79      public static final int STATE_DIMENSION = 6;
80  
81      /** Propagator computing state evolution. */
82      private final NumericalPropagator propagator;
83  
84      /** Selected parameters for Jacobian computation. */
85      private ParameterDriversList selected;
86  
87      /** Parameters map. */
88      private Map<String, Integer> map;
89  
90      /** Name. */
91      private final String name;
92  
93      /** Simple constructor.
94       * <p>
95       * Upon construction, this set of equations is <em>automatically</em> added to
96       * the propagator by calling its {@link
97       * NumericalPropagator#addAdditionalDerivativesProvider(AdditionalDerivativesProvider)} method. So
98       * there is no need to call this method explicitly for these equations.
99       * </p>
100      * @param name name of the partial derivatives equations
101      * @param propagator the propagator that will handle the orbit propagation
102      */
103     public EpochDerivativesEquations(final String name, final NumericalPropagator propagator) {
104         this.name                   = name;
105         this.selected               = null;
106         this.map                    = null;
107         this.propagator             = propagator;
108         propagator.addAdditionalDerivativesProvider(this);
109     }
110 
111     /** {@inheritDoc} */
112     public String getName() {
113         return name;
114     }
115 
116     /** {@inheritDoc} */
117     @Override
118     public int getDimension() {
119         freezeParametersSelection();
120         return 6 * (6 + selected.getNbParams() + 1);
121     }
122 
123     /** Freeze the selected parameters from the force models.
124      */
125     private void freezeParametersSelection() {
126         if (selected == null) {
127 
128             // first pass: gather all parameters, binding similar names together
129             selected = new ParameterDriversList();
130             for (final ForceModel provider : propagator.getAllForceModels()) {
131                 for (final ParameterDriver driver : provider.getParametersDrivers()) {
132                     selected.add(driver);
133                 }
134             }
135 
136             // second pass: now that shared parameter names are bound together,
137             // their selections status have been synchronized, we can filter them
138             selected.filter(true);
139 
140             // third pass: sort parameters lexicographically
141             selected.sort();
142 
143             // fourth pass: set up a map between parameters drivers and matrices columns
144             map = new IdentityHashMap<>();
145             int parameterIndex = 0;
146             int previousParameterIndex = 0;
147             for (final ParameterDriver selectedDriver : selected.getDrivers()) {
148                 for (final ForceModel provider : propagator.getAllForceModels()) {
149                     for (final ParameterDriver driver : provider.getParametersDrivers()) {
150                         if (driver.getName().equals(selectedDriver.getName())) {
151                             previousParameterIndex = parameterIndex;
152                             map.put(driver.getName(), previousParameterIndex++);
153                         }
154                     }
155                 }
156                 parameterIndex = previousParameterIndex;
157             }
158 
159         }
160     }
161 
162     /** Set the initial value of the Jacobian with respect to state and parameter.
163      * <p>
164      * This method is equivalent to call {@link #setInitialJacobians(SpacecraftState,
165      * double[][], double[][])} with dYdY0 set to the identity matrix and dYdP set
166      * to a zero matrix.
167      * </p>
168      * <p>
169      * The force models parameters for which partial derivatives are desired,
170      * <em>must</em> have been {@link ParameterDriver#setSelected(boolean) selected}
171      * before this method is called, so proper matrices dimensions are used.
172      * </p>
173      * @param s0 initial state
174      * @return state with initial Jacobians added
175      */
176     public SpacecraftState setInitialJacobians(final SpacecraftState s0) {
177         freezeParametersSelection();
178         final int epochStateDimension = 6;
179         final double[][] dYdY0 = new double[epochStateDimension][epochStateDimension];
180         final double[][] dYdP  = new double[epochStateDimension][selected.getNbParams() + 6];
181         for (int i = 0; i < epochStateDimension; ++i) {
182             dYdY0[i][i] = 1.0;
183         }
184         return setInitialJacobians(s0, dYdY0, dYdP);
185     }
186 
187     /** Set the initial value of the Jacobian with respect to state and parameter.
188      * <p>
189      * The returned state must be added to the propagator (it is not done
190      * automatically, as the user may need to add more states to it).
191      * </p>
192      * <p>
193      * The force models parameters for which partial derivatives are desired,
194      * <em>must</em> have been {@link ParameterDriver#setSelected(boolean) selected}
195      * before this method is called, and the {@code dY1dP} matrix dimension <em>must</em>
196      * be consistent with the selection.
197      * </p>
198      * @param s1 current state
199      * @param dY1dY0 Jacobian of current state at time t₁ with respect
200      * to state at some previous time t₀ (must be 6x6)
201      * @param dY1dP Jacobian of current state at time t₁ with respect
202      * to parameters (may be null if no parameters are selected)
203      * @return state with initial Jacobians added
204      */
205     public SpacecraftState setInitialJacobians(final SpacecraftState s1,
206                                                final double[][] dY1dY0, final double[][] dY1dP) {
207 
208         freezeParametersSelection();
209 
210         // Check dimensions
211         final int stateDimEpoch = dY1dY0.length;
212         if (stateDimEpoch != 6 || stateDimEpoch != dY1dY0[0].length) {
213             throw new OrekitException(OrekitMessages.STATE_JACOBIAN_NOT_6X6,
214                                       stateDimEpoch, dY1dY0[0].length);
215         }
216         if (dY1dP != null && stateDimEpoch != dY1dP.length) {
217             throw new OrekitException(OrekitMessages.STATE_AND_PARAMETERS_JACOBIANS_ROWS_MISMATCH,
218                                       stateDimEpoch, dY1dP.length);
219         }
220 
221         // store the matrices as a single dimension array
222         final double[] p = new double[STATE_DIMENSION * (STATE_DIMENSION + selected.getNbParams()) + 6];
223         setInitialJacobians(s1, dY1dY0, dY1dP, p);
224 
225         // set value in propagator
226         return s1.addAdditionalData(name, p);
227 
228     }
229 
230     /** Set the Jacobian with respect to state into a one-dimensional additional state array.
231      * <p>
232      * This method converts the Jacobians to Cartesian parameters and put the converted data
233      * in the one-dimensional {@code p} array.
234      * </p>
235      * @param state spacecraft state
236      * @param dY1dY0 Jacobian of current state at time t₁
237      * with respect to state at some previous time t₀
238      * @param dY1dP Jacobian of current state at time t₁
239      * with respect to parameters (may be null if there are no parameters)
240      * @param p placeholder where to put the one-dimensional additional state
241      */
242     public void setInitialJacobians(final SpacecraftState state, final double[][] dY1dY0,
243                                     final double[][] dY1dP, final double[] p) {
244 
245         // set up a converter
246         final RealMatrix dY1dC1 = MatrixUtils.createRealIdentityMatrix(STATE_DIMENSION);
247         final DecompositionSolver solver = new QRDecomposition(dY1dC1).getSolver();
248 
249         // convert the provided state Jacobian
250         final RealMatrix dC1dY0 = solver.solve(new Array2DRowRealMatrix(dY1dY0, false));
251 
252         // map the converted state Jacobian to one-dimensional array
253         int index = 0;
254         for (int i = 0; i < STATE_DIMENSION; ++i) {
255             for (int j = 0; j < STATE_DIMENSION; ++j) {
256                 p[index++] = dC1dY0.getEntry(i, j);
257             }
258         }
259 
260         if (selected.getNbParams() != 0) {
261             // convert the provided state Jacobian
262             final RealMatrix dC1dP = solver.solve(new Array2DRowRealMatrix(dY1dP, false));
263 
264             // map the converted parameters Jacobian to one-dimensional array
265             for (int i = 0; i < STATE_DIMENSION; ++i) {
266                 for (int j = 0; j < selected.getNbParams(); ++j) {
267                     p[index++] = dC1dP.getEntry(i, j);
268                 }
269             }
270         }
271 
272     }
273 
274     /** {@inheritDoc} */
275     public CombinedDerivatives combinedDerivatives(final SpacecraftState s) {
276 
277         // initialize acceleration Jacobians to zero
278         final int paramDimEpoch = selected.getNbParams() + 1; // added epoch
279         final int dimEpoch      = 3;
280         final double[][] dAccdParam = new double[dimEpoch][paramDimEpoch];
281         final double[][] dAccdPos   = new double[dimEpoch][dimEpoch];
282         final double[][] dAccdVel   = new double[dimEpoch][dimEpoch];
283 
284         final NumericalGradientConverter fullConverter    = new NumericalGradientConverter(s, 6, propagator.getAttitudeProvider());
285         final NumericalGradientConverter posOnlyConverter = new NumericalGradientConverter(s, 3, propagator.getAttitudeProvider());
286 
287         // compute acceleration Jacobians, finishing with the largest force: Newtonian attraction
288         for (final ForceModel forceModel : propagator.getAllForceModels()) {
289             final NumericalGradientConverter converter = forceModel.dependsOnPositionOnly() ? posOnlyConverter : fullConverter;
290             final FieldSpacecraftState<Gradient> dsState = converter.getState(forceModel);
291             final Gradient[] parameters = converter.getParametersAtStateDate(dsState, forceModel);
292 
293             final FieldVector3D<Gradient> acceleration = forceModel.acceleration(dsState, parameters);
294             final double[] derivativesX = acceleration.getX().getGradient();
295             final double[] derivativesY = acceleration.getY().getGradient();
296             final double[] derivativesZ = acceleration.getZ().getGradient();
297 
298             // update Jacobians with respect to state
299             addToRow(derivativesX, 0, converter.getFreeStateParameters(), dAccdPos, dAccdVel);
300             addToRow(derivativesY, 1, converter.getFreeStateParameters(), dAccdPos, dAccdVel);
301             addToRow(derivativesZ, 2, converter.getFreeStateParameters(), dAccdPos, dAccdVel);
302 
303             int index = converter.getFreeStateParameters();
304             for (ParameterDriver driver : forceModel.getParametersDrivers()) {
305                 if (driver.isSelected()) {
306                     final int parameterIndex = map.get(driver.getName());
307                     dAccdParam[0][parameterIndex] += derivativesX[index];
308                     dAccdParam[1][parameterIndex] += derivativesY[index];
309                     dAccdParam[2][parameterIndex] += derivativesZ[index];
310                     ++index;
311                 }
312             }
313 
314             // Add the derivatives of the acceleration w.r.t. the Epoch
315             if (forceModel instanceof ThirdBodyAttractionEpoch epoch) {
316                 final double[] parametersValues = new double[] {parameters[0].getValue()};
317                 final double[] derivatives = epoch.getDerivativesToEpoch(s, parametersValues);
318                 dAccdParam[0][paramDimEpoch - 1] += derivatives[0];
319                 dAccdParam[1][paramDimEpoch - 1] += derivatives[1];
320                 dAccdParam[2][paramDimEpoch - 1] += derivatives[2];
321             }
322 
323         }
324 
325         // the variational equations of the complete state Jacobian matrix have the following form:
326 
327         // [        |        ]   [                 |                  ]   [     |     ]
328         // [  Adot  |  Bdot  ]   [  dVel/dPos = 0  |  dVel/dVel = Id  ]   [  A  |  B  ]
329         // [        |        ]   [                 |                  ]   [     |     ]
330         // ---------+---------   ------------------+------------------- * ------+------
331         // [        |        ]   [                 |                  ]   [     |     ]
332         // [  Cdot  |  Ddot  ] = [    dAcc/dPos    |     dAcc/dVel    ]   [  C  |  D  ]
333         // [        |        ]   [                 |                  ]   [     |     ]
334 
335         // The A, B, C and D sub-matrices and their derivatives (Adot ...) are 3x3 matrices
336 
337         // The expanded multiplication above can be rewritten to take into account
338         // the fixed values found in the sub-matrices in the left factor. This leads to:
339 
340         //     [ Adot ] = [ C ]
341         //     [ Bdot ] = [ D ]
342         //     [ Cdot ] = [ dAcc/dPos ] * [ A ] + [ dAcc/dVel ] * [ C ]
343         //     [ Ddot ] = [ dAcc/dPos ] * [ B ] + [ dAcc/dVel ] * [ D ]
344 
345         // The following loops compute these expressions taking care of the mapping of the
346         // (A, B, C, D) matrices into the single dimension array p and of the mapping of the
347         // (Adot, Bdot, Cdot, Ddot) matrices into the single dimension array pDot.
348 
349         // copy C and E into Adot and Bdot
350         final int stateDim = 6;
351         final double[] p = s.getAdditionalState(getName());
352         final double[] pDot = new double[p.length];
353         System.arraycopy(p, dimEpoch * stateDim, pDot, 0, dimEpoch * stateDim);
354 
355         // compute Cdot and Ddot
356         for (int i = 0; i < dimEpoch; ++i) {
357             final double[] dAdPi = dAccdPos[i];
358             final double[] dAdVi = dAccdVel[i];
359             for (int j = 0; j < stateDim; ++j) {
360                 pDot[(dimEpoch + i) * stateDim + j] =
361                     dAdPi[0] * p[j]                + dAdPi[1] * p[j +     stateDim] + dAdPi[2] * p[j + 2 * stateDim] +
362                     dAdVi[0] * p[j + 3 * stateDim] + dAdVi[1] * p[j + 4 * stateDim] + dAdVi[2] * p[j + 5 * stateDim];
363             }
364         }
365 
366         for (int k = 0; k < paramDimEpoch; ++k) {
367             // the variational equations of the parameters Jacobian matrix are computed
368             // one column at a time, they have the following form:
369             // [      ]   [                 |                  ]   [   ]   [                  ]
370             // [ Edot ]   [  dVel/dPos = 0  |  dVel/dVel = Id  ]   [ E ]   [  dVel/dParam = 0 ]
371             // [      ]   [                 |                  ]   [   ]   [                  ]
372             // --------   ------------------+------------------- * ----- + --------------------
373             // [      ]   [                 |                  ]   [   ]   [                  ]
374             // [ Fdot ] = [    dAcc/dPos    |     dAcc/dVel    ]   [ F ]   [    dAcc/dParam   ]
375             // [      ]   [                 |                  ]   [   ]   [                  ]
376 
377             // The E and F sub-columns and their derivatives (Edot, Fdot) are 3 elements columns.
378 
379             // The expanded multiplication and addition above can be rewritten to take into
380             // account the fixed values found in the sub-matrices in the left factor. This leads to:
381 
382             //     [ Edot ] = [ F ]
383             //     [ Fdot ] = [ dAcc/dPos ] * [ E ] + [ dAcc/dVel ] * [ F ] + [ dAcc/dParam ]
384 
385             // The following loops compute these expressions taking care of the mapping of the
386             // (E, F) columns into the single dimension array p and of the mapping of the
387             // (Edot, Fdot) columns into the single dimension array pDot.
388 
389             // copy F into Edot
390             final int columnTop = stateDim * stateDim + k;
391             pDot[columnTop]                     = p[columnTop + 3 * paramDimEpoch];
392             pDot[columnTop +     paramDimEpoch] = p[columnTop + 4 * paramDimEpoch];
393             pDot[columnTop + 2 * paramDimEpoch] = p[columnTop + 5 * paramDimEpoch];
394 
395             // compute Fdot
396             for (int i = 0; i < dimEpoch; ++i) {
397                 final double[] dAdP = dAccdPos[i];
398                 final double[] dAdV = dAccdVel[i];
399                 pDot[columnTop + (dimEpoch + i) * paramDimEpoch] =
400                     dAccdParam[i][k] +
401                     dAdP[0] * p[columnTop]                     + dAdP[1] * p[columnTop +     paramDimEpoch] + dAdP[2] * p[columnTop + 2 * paramDimEpoch] +
402                     dAdV[0] * p[columnTop + 3 * paramDimEpoch] + dAdV[1] * p[columnTop + 4 * paramDimEpoch] + dAdV[2] * p[columnTop + 5 * paramDimEpoch];
403             }
404 
405         }
406 
407         return new CombinedDerivatives(pDot, null);
408 
409     }
410 
411     /** Fill Jacobians rows.
412      * @param derivatives derivatives of a component of acceleration (along either x, y or z)
413      * @param index component index (0 for x, 1 for y, 2 for z)
414      * @param freeStateParameters number of free parameters, either 3 (position),
415      * 6 (position-velocity) or 7 (position-velocity-mass)
416      * @param dAccdPos Jacobian of acceleration with respect to spacecraft position
417      * @param dAccdVel Jacobian of acceleration with respect to spacecraft velocity
418      */
419     private void addToRow(final double[] derivatives, final int index, final int freeStateParameters,
420                           final double[][] dAccdPos, final double[][] dAccdVel) {
421 
422         for (int i = 0; i < 3; ++i) {
423             dAccdPos[index][i] += derivatives[i];
424         }
425         if (freeStateParameters > 3) {
426             for (int i = 0; i < 3; ++i) {
427                 dAccdVel[index][i] += derivatives[i + 3];
428             }
429         }
430 
431     }
432 
433 }
434