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