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.semianalytical.dsst;
18  
19  import java.util.ArrayList;
20  import java.util.Arrays;
21  import java.util.IdentityHashMap;
22  import java.util.List;
23  import java.util.Map;
24  
25  import org.hipparchus.analysis.differentiation.Gradient;
26  import org.hipparchus.linear.MatrixUtils;
27  import org.hipparchus.linear.RealMatrix;
28  import org.orekit.orbits.OrbitParamsType;
29  import org.orekit.orbits.PositionAngleType;
30  import org.orekit.propagation.AbstractMatricesHarvester;
31  import org.orekit.propagation.FieldSpacecraftState;
32  import org.orekit.propagation.PropagationType;
33  import org.orekit.propagation.SpacecraftState;
34  import org.orekit.propagation.semianalytical.dsst.forces.DSSTForceModel;
35  import org.orekit.propagation.semianalytical.dsst.forces.FieldShortPeriodTerms;
36  import org.orekit.propagation.semianalytical.dsst.utilities.FieldAuxiliaryElements;
37  import org.orekit.utils.DoubleArrayDictionary;
38  import org.orekit.utils.drivers.ParameterDriver;
39  
40  /** Harvester between two-dimensional Jacobian matrices and one-dimensional {@link
41   * SpacecraftState#getAdditionalState(String) additional state arrays}.
42   * @author Luc Maisonobe
43   * @author Bryan Cazabonne
44   * @since 11.1
45   */
46  public class DSSTHarvester extends AbstractMatricesHarvester {
47  
48      /** Retrograde factor I.
49       *  <p>
50       *  DSST model needs equinoctial orbit as internal representation.
51       *  Classical equinoctial elements have discontinuities when inclination
52       *  is close to zero. In this representation, I = +1. <br>
53       *  To avoid this discontinuity, another representation exists and equinoctial
54       *  elements can be expressed in a different way, called "retrograde" orbit.
55       *  This implies I = -1. <br>
56       *  As Orekit doesn't implement the retrograde orbit, I is always set to +1.
57       *  But for the sake of consistency with the theory, the retrograde factor
58       *  has been kept in the formulas.
59       *  </p>
60       */
61      private static final int I = 1;
62  
63      /** Propagator bound to this harvester. */
64      private final DSSTPropagator propagator;
65  
66      /** Derivatives of the short period terms that apply to State Transition Matrix.*/
67      private final double[][] shortPeriodDerivativesStm;
68  
69      /** Derivatives of the short period terms that apply to Jacobians columns. */
70      private final DoubleArrayDictionary shortPeriodDerivativesJacobianColumns;
71  
72      /** Columns names for parameters. */
73      private List<String> columnsNames;
74  
75      /**
76       * Field short periodic terms. Key is the force model to which they pertain. Value is
77       * the terms. They need to be stored in a map because the DsstForceModel interface
78       * does not have a getter for the terms.
79       */
80      private final Map<DSSTForceModel, List<FieldShortPeriodTerms<Gradient>>>
81              fieldShortPeriodTerms;
82  
83      /** Simple constructor.
84       * <p>
85       * The arguments for initial matrices <em>must</em> be compatible with the
86       * {@link OrbitParamsType#EQUINOCTIAL equinoctial orbit type}
87       * and {@link PositionAngleType position angle} that will be used by propagator
88       * </p>
89       * @param propagator propagator bound to this harvester
90       * @param stmName State Transition Matrix state name
91       * @param initialStm initial State Transition Matrix ∂Y/∂Y₀,
92       * if null (which is the most frequent case), assumed to be 6x6 identity
93       * @param initialJacobianColumns initial columns of the Jacobians matrix with respect to parameters,
94       * if null or if some selected parameters are missing from the dictionary, the corresponding
95       * initial column is assumed to be 0
96       */
97      DSSTHarvester(final DSSTPropagator propagator, final String stmName,
98                    final RealMatrix initialStm, final DoubleArrayDictionary initialJacobianColumns) {
99          setInitialStm(stmName, initialStm);
100         setInitialJacobianColumns(initialJacobianColumns);
101         this.propagator                            = propagator;
102         this.shortPeriodDerivativesStm             = new double[getStateDimension()][getStateDimension()];
103         this.shortPeriodDerivativesJacobianColumns = new DoubleArrayDictionary();
104         // Use identity hash map to have the same behavior as a getter on the force model
105         this.fieldShortPeriodTerms                 = new IdentityHashMap<>();
106     }
107 
108     /** {@inheritDoc} */
109     @Override
110     public RealMatrix getStateTransitionMatrix(final SpacecraftState state) {
111 
112         final RealMatrix stm = getB2(state);
113 
114         final int stateDimension = getStateDimension();
115         if (propagator.getPropagationType() == PropagationType.OSCULATING) {
116             // add the short period terms
117             for (int i = 0; i < stateDimension; i++) {
118                 for (int j = 0; j < stateDimension; j++) {
119                     stm.addToEntry(i, j, shortPeriodDerivativesStm[i][j]);
120                 }
121             }
122         }
123 
124         return stm;
125 
126     }
127 
128     /** {@inheritDoc} */
129     @Override
130     public RealMatrix getParametersJacobian(final SpacecraftState state) {
131 
132         final RealMatrix jacobian = getB3(state);
133         if (jacobian != null && propagator.getPropagationType() == PropagationType.OSCULATING) {
134 
135             // add the short period terms
136             final List<String> names = getJacobiansColumnsNames();
137             for (int j = 0; j < names.size(); ++j) {
138                 final double[] column = shortPeriodDerivativesJacobianColumns.get(names.get(j));
139                 for (int i = 0; i < getStateDimension(); i++) {
140                     jacobian.addToEntry(i, j, column[i]);
141                 }
142             }
143 
144         }
145 
146         return jacobian;
147 
148     }
149 
150     /** Get the Jacobian matrix B1 (B1 = ∂εη/∂Y).
151      * <p>
152      * B1 represents the partial derivatives of the short period motion
153      * with respect to the mean equinoctial elements.
154      * </p>
155      * @return the B1 jacobian matrix
156      */
157     public RealMatrix getB1() {
158 
159         // Initialize B1
160         final int stateDimension = getStateDimension();
161         final RealMatrix B1 = MatrixUtils.createRealMatrix(stateDimension, stateDimension);
162 
163         // add the short period terms
164         for (int i = 0; i < stateDimension; i++) {
165             for (int j = 0; j < stateDimension; j++) {
166                 B1.addToEntry(i, j, shortPeriodDerivativesStm[i][j]);
167             }
168         }
169 
170         // Return B1
171         return B1;
172 
173     }
174 
175     /** Get the Jacobian matrix B2 (B2 = ∂Y/∂Y₀).
176      * <p>
177      * B2 represents the partial derivatives of the mean equinoctial elements
178      * with respect to the initial ones.
179      * </p>
180      * @param state spacecraft state
181      * @return the B2 jacobian matrix
182      */
183     public RealMatrix getB2(final SpacecraftState state) {
184         if (!state.hasAdditionalData(getStmName())) {
185             return null;
186         }
187         return toSquareMatrix(state.getAdditionalState(getStmName()));
188     }
189 
190     /** Get the Jacobian matrix B3 (B3 = ∂Y/∂P).
191      * <p>
192      * B3 represents the partial derivatives of the mean equinoctial elements
193      * with respect to the estimated propagation parameters.
194      * </p>
195      * @param state spacecraft state
196      * @return the B3 jacobian matrix
197      */
198     public RealMatrix getB3(final SpacecraftState state) {
199 
200         final List<String> names = getJacobiansColumnsNames();
201 
202         if (names == null || names.isEmpty()) {
203             return null;
204         }
205 
206         final RealMatrix dYdP = MatrixUtils.createRealMatrix(getStateDimension(), names.size());
207         for (int j = 0; j < names.size(); j++) {
208             dYdP.setColumn(j, state.getAdditionalState(names.get(j)));
209         }
210 
211         return dYdP;
212 
213     }
214 
215     /** Get the Jacobian matrix B4 (B4 = ∂εη/∂c).
216      * <p>
217      * B4 represents the partial derivatives of the short period motion
218      * with respect to the estimated propagation parameters.
219      * </p>
220      * @return the B4 jacobian matrix
221      */
222     public RealMatrix getB4() {
223 
224         // Initialize B4
225         final List<String> names = getJacobiansColumnsNames();
226         final RealMatrix B4 = MatrixUtils.createRealMatrix(getStateDimension(), names.size());
227 
228         // add the short period terms
229         for (int j = 0; j < names.size(); ++j) {
230             final double[] column = shortPeriodDerivativesJacobianColumns.get(names.get(j));
231             for (int i = 0; i < getStateDimension(); i++) {
232                 B4.addToEntry(i, j, column[i]);
233             }
234         }
235 
236         // Return B4
237         return B4;
238 
239     }
240 
241     /** Freeze the names of the Jacobian columns.
242      * <p>
243      * This method is called when proagation starts, i.e. when configuration is completed
244      * </p>
245      */
246     public void freezeColumnsNames() {
247         columnsNames = getJacobiansColumnsNames();
248     }
249 
250     /** {@inheritDoc} */
251     @Override
252     public List<String> getJacobiansColumnsNames() {
253         return columnsNames == null ? propagator.getJacobiansColumnsNames() : columnsNames;
254     }
255 
256     /** Initialize the short periodic terms for the "field" elements.
257      * @param reference current mean spacecraft state
258      */
259     public void initializeFieldShortPeriodTerms(final SpacecraftState reference) {
260         initializeFieldShortPeriodTerms(reference, propagator.getPropagationType());
261     }
262 
263     /**
264      * Initialize the short periodic terms for the "field" elements.
265      *
266      * @param reference current mean spacecraft state
267      * @param type      MEAN or OSCULATING
268      */
269     public void initializeFieldShortPeriodTerms(final SpacecraftState reference,
270                                                 final PropagationType type) {
271 
272         // Converter
273         final DSSTGradientConverter converter = new DSSTGradientConverter(reference, propagator.getAttitudeProvider());
274 
275         // clear old values
276         // prevents duplicates or stale values when reusing a DSSTPropagator
277         fieldShortPeriodTerms.clear();
278 
279         // Loop on force models
280         for (final DSSTForceModel forceModel : propagator.getAllForceModels()) {
281 
282             // Convert to Gradient
283             final FieldSpacecraftState<Gradient> dsState = converter.getState(forceModel);
284             final Gradient[] dsParameters = converter.getParametersAtStateDate(dsState, forceModel);
285             final FieldAuxiliaryElements<Gradient> auxiliaryElements = new FieldAuxiliaryElements<>(dsState.getOrbit(), I);
286 
287             // Initialize the "Field" short periodic terms, same mode as the propagator
288             final List<FieldShortPeriodTerms<Gradient>> terms =
289                     forceModel.initializeShortPeriodTerms(
290                             auxiliaryElements,
291                             type,
292                             dsParameters);
293             // create a copy of the list to protect against inadvertent modification
294             final List<FieldShortPeriodTerms<Gradient>> list;
295             synchronized (fieldShortPeriodTerms) {
296                 list = fieldShortPeriodTerms.computeIfAbsent(forceModel, x -> new ArrayList<>());
297             }
298             list.addAll(terms);
299 
300         }
301 
302     }
303 
304     /** Update the short periodic terms for the "field" elements.
305      * @param reference current mean spacecraft state
306      */
307     @SuppressWarnings("unchecked")
308     public void updateFieldShortPeriodTerms(final SpacecraftState reference) {
309 
310         // Converter
311         final DSSTGradientConverter converter = new DSSTGradientConverter(reference, propagator.getAttitudeProvider());
312 
313         // Loop on force models
314         for (final DSSTForceModel forceModel : propagator.getAllForceModels()) {
315 
316             // Convert to Gradient
317             final FieldSpacecraftState<Gradient> dsState = converter.getState(forceModel);
318             final Gradient[] dsParameters = converter.getParameters(dsState, forceModel);
319 
320             // Update the short periodic terms for the current force model
321             forceModel.updateShortPeriodTerms(dsParameters, dsState);
322 
323         }
324 
325     }
326 
327     /** {@inheritDoc} */
328     @Override
329     public void setReferenceState(final SpacecraftState reference) {
330 
331         // reset derivatives to zero
332         for (final double[] row : shortPeriodDerivativesStm) {
333             Arrays.fill(row, 0.0);
334         }
335 
336         shortPeriodDerivativesJacobianColumns.clear();
337 
338         final DSSTGradientConverter converter = new DSSTGradientConverter(reference, propagator.getAttitudeProvider());
339 
340         // Compute Jacobian
341         for (final DSSTForceModel forceModel : propagator.getAllForceModels()) {
342 
343             final FieldSpacecraftState<Gradient> dsState = converter.getState(forceModel);
344             final Gradient zero = dsState.getDate().getField().getZero();
345             final Gradient[] shortPeriod = new Gradient[6];
346             Arrays.fill(shortPeriod, zero);
347             final List<FieldShortPeriodTerms<Gradient>> terms;
348             synchronized (fieldShortPeriodTerms) {
349                 terms = fieldShortPeriodTerms.computeIfAbsent(forceModel, x -> new ArrayList<>(0));
350             }
351             for (final FieldShortPeriodTerms<Gradient> spt : terms) {
352                 final Gradient[] spVariation = spt.value(dsState.getOrbit());
353                 for (int i = 0; i < spVariation .length; i++) {
354                     shortPeriod[i] = shortPeriod[i].add(spVariation[i]);
355                 }
356             }
357 
358             final double[] derivativesASP  = shortPeriod[0].getGradient();
359             final double[] derivativesExSP = shortPeriod[1].getGradient();
360             final double[] derivativesEySP = shortPeriod[2].getGradient();
361             final double[] derivativesHxSP = shortPeriod[3].getGradient();
362             final double[] derivativesHySP = shortPeriod[4].getGradient();
363             final double[] derivativesLSP  = shortPeriod[5].getGradient();
364 
365             // update Jacobian with respect to state
366             addToRow(derivativesASP,  0);
367             addToRow(derivativesExSP, 1);
368             addToRow(derivativesEySP, 2);
369             addToRow(derivativesHxSP, 3);
370             addToRow(derivativesHySP, 4);
371             addToRow(derivativesLSP,  5);
372 
373             int paramsIndex = converter.getFreeStateParameters();
374             for (ParameterDriver driver : forceModel.getParametersDrivers()) {
375                 if (driver.isSelected()) {
376 
377                     // get the partials derivatives for this driver
378                     DoubleArrayDictionary.Entry entry = shortPeriodDerivativesJacobianColumns.getEntry(driver.getName());
379                     if (entry == null) {
380                         // create an entry filled with zeroes
381                         shortPeriodDerivativesJacobianColumns.put(driver.getName(), new double[getStateDimension()]);
382                         entry = shortPeriodDerivativesJacobianColumns.getEntry(driver.getName());
383                     }
384 
385                     // add the contribution of the current force model
386                     entry.increment(new double[] {
387                         derivativesASP[paramsIndex], derivativesExSP[paramsIndex], derivativesEySP[paramsIndex],
388                         derivativesHxSP[paramsIndex], derivativesHySP[paramsIndex], derivativesLSP[paramsIndex]
389                     });
390                     ++paramsIndex;
391                 }
392             }
393         }
394 
395     }
396 
397     /** Fill State Transition Matrix rows.
398      * @param derivatives derivatives of a component
399      * @param index component index (0 for a, 1 for ex, 2 for ey, 3 for hx, 4 for hy, 5 for l)
400      */
401     private void addToRow(final double[] derivatives, final int index) {
402         for (int i = 0; i < 6; i++) {
403             shortPeriodDerivativesStm[index][i] += derivatives[i];
404         }
405     }
406 
407     /** {@inheritDoc} */
408     @Override
409     public OrbitParamsType getOrbitParamsType() {
410         return propagator.getOrbitParamsType();
411     }
412 
413     /** {@inheritDoc} */
414     @Override
415     public PositionAngleType getPositionAngleType() {
416         return propagator.getPositionAngleType();
417     }
418 
419 }