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