FieldDSSTPropagator.java

  1. /* Copyright 2002-2022 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 java.util.ArrayList;
  19. import java.util.Arrays;
  20. import java.util.Collection;
  21. import java.util.Collections;
  22. import java.util.HashSet;
  23. import java.util.List;
  24. import java.util.Set;

  25. import org.hipparchus.CalculusFieldElement;
  26. import org.hipparchus.Field;
  27. import org.hipparchus.ode.FieldODEIntegrator;
  28. import org.hipparchus.ode.FieldODEStateAndDerivative;
  29. import org.hipparchus.ode.sampling.FieldODEStateInterpolator;
  30. import org.hipparchus.ode.sampling.FieldODEStepHandler;
  31. import org.hipparchus.util.FastMath;
  32. import org.hipparchus.util.MathArrays;
  33. import org.hipparchus.util.MathUtils;
  34. import org.orekit.annotation.DefaultDataContext;
  35. import org.orekit.attitudes.AttitudeProvider;
  36. import org.orekit.attitudes.FieldAttitude;
  37. import org.orekit.data.DataContext;
  38. import org.orekit.errors.OrekitException;
  39. import org.orekit.errors.OrekitInternalError;
  40. import org.orekit.errors.OrekitMessages;
  41. import org.orekit.frames.Frame;
  42. import org.orekit.orbits.FieldEquinoctialOrbit;
  43. import org.orekit.orbits.FieldOrbit;
  44. import org.orekit.orbits.OrbitType;
  45. import org.orekit.orbits.PositionAngle;
  46. import org.orekit.propagation.FieldSpacecraftState;
  47. import org.orekit.propagation.PropagationType;
  48. import org.orekit.propagation.Propagator;
  49. import org.orekit.propagation.SpacecraftState;
  50. import org.orekit.propagation.events.FieldEventDetector;
  51. import org.orekit.propagation.integration.FieldAbstractIntegratedPropagator;
  52. import org.orekit.propagation.integration.FieldStateMapper;
  53. import org.orekit.propagation.numerical.FieldNumericalPropagator;
  54. import org.orekit.propagation.semianalytical.dsst.forces.DSSTForceModel;
  55. import org.orekit.propagation.semianalytical.dsst.forces.DSSTNewtonianAttraction;
  56. import org.orekit.propagation.semianalytical.dsst.forces.FieldShortPeriodTerms;
  57. import org.orekit.propagation.semianalytical.dsst.utilities.FieldAuxiliaryElements;
  58. import org.orekit.propagation.semianalytical.dsst.utilities.FieldFixedNumberInterpolationGrid;
  59. import org.orekit.propagation.semianalytical.dsst.utilities.FieldInterpolationGrid;
  60. import org.orekit.propagation.semianalytical.dsst.utilities.FieldMaxGapInterpolationGrid;
  61. import org.orekit.time.FieldAbsoluteDate;
  62. import org.orekit.utils.FieldArrayDictionary;
  63. import org.orekit.utils.ParameterDriver;
  64. import org.orekit.utils.ParameterObserver;

  65. /**
  66.  * This class propagates {@link org.orekit.orbits.FieldOrbit orbits} using the DSST theory.
  67.  * <p>
  68.  * Whereas analytical propagators are configured only thanks to their various
  69.  * constructors and can be used immediately after construction, such a semianalytical
  70.  * propagator configuration involves setting several parameters between construction
  71.  * time and propagation time, just as numerical propagators.
  72.  * </p>
  73.  * <p>
  74.  * The configuration parameters that can be set are:
  75.  * </p>
  76.  * <ul>
  77.  * <li>the initial spacecraft state ({@link #setInitialState(FieldSpacecraftState)})</li>
  78.  * <li>the various force models ({@link #addForceModel(DSSTForceModel)},
  79.  * {@link #removeForceModels()})</li>
  80.  * <li>the discrete events that should be triggered during propagation (
  81.  * {@link #addEventDetector(org.orekit.propagation.events.FieldEventDetector)},
  82.  * {@link #clearEventsDetectors()})</li>
  83.  * <li>the binding logic with the rest of the application ({@link #getMultiplexer()})</li>
  84.  * </ul>
  85.  * <p>
  86.  * From these configuration parameters, only the initial state is mandatory.
  87.  * The default propagation settings are in {@link OrbitType#EQUINOCTIAL equinoctial}
  88.  * parameters with {@link PositionAngle#TRUE true} longitude argument.
  89.  * The central attraction coefficient used to define the initial orbit will be used.
  90.  * However, specifying only the initial state would mean the propagator would use
  91.  * only Keplerian forces. In this case, the simpler
  92.  * {@link org.orekit.propagation.analytical.KeplerianPropagator KeplerianPropagator}
  93.  * class would be more effective.
  94.  * </p>
  95.  * <p>
  96.  * The underlying numerical integrator set up in the constructor may also have
  97.  * its own configuration parameters. Typical configuration parameters for adaptive
  98.  * stepsize integrators are the min, max and perhaps start step size as well as
  99.  * the absolute and/or relative errors thresholds.
  100.  * </p>
  101.  * <p>
  102.  * The state that is seen by the integrator is a simple six elements double array.
  103.  * These six elements are:
  104.  * <ul>
  105.  * <li>the {@link org.orekit.orbits.FieldEquinoctialOrbit equinoctial orbit parameters}
  106.  * (a, e<sub>x</sub>, e<sub>y</sub>, h<sub>x</sub>, h<sub>y</sub>, λ<sub>m</sub>)
  107.  * in meters and radians,</li>
  108.  * </ul>
  109.  *
  110.  * <p>By default, at the end of the propagation, the propagator resets the initial state to the final state,
  111.  * thus allowing a new propagation to be started from there without recomputing the part already performed.
  112.  * This behaviour can be chenged by calling {@link #setResetAtEnd(boolean)}.
  113.  * </p>
  114.  * <p>Beware the same instance cannot be used simultaneously by different threads, the class is <em>not</em>
  115.  * thread-safe.</p>
  116.  *
  117.  * @see FieldSpacecraftState
  118.  * @see DSSTForceModel
  119.  * @author Romain Di Costanzo
  120.  * @author Pascal Parraud
  121.  * @since 10.0
  122.  */
  123. public class FieldDSSTPropagator<T extends CalculusFieldElement<T>> extends FieldAbstractIntegratedPropagator<T>  {

  124.     /** Retrograde factor I.
  125.      *  <p>
  126.      *  DSST model needs equinoctial orbit as internal representation.
  127.      *  Classical equinoctial elements have discontinuities when inclination
  128.      *  is close to zero. In this representation, I = +1. <br>
  129.      *  To avoid this discontinuity, another representation exists and equinoctial
  130.      *  elements can be expressed in a different way, called "retrograde" orbit.
  131.      *  This implies I = -1. <br>
  132.      *  As Orekit doesn't implement the retrograde orbit, I is always set to +1.
  133.      *  But for the sake of consistency with the theory, the retrograde factor
  134.      *  has been kept in the formulas.
  135.      *  </p>
  136.      */
  137.     private static final int I = 1;

  138.     /** Number of grid points per integration step to be used in interpolation of short periodics coefficients.*/
  139.     private static final int INTERPOLATION_POINTS_PER_STEP = 3;

  140.     /** Default value for epsilon. */
  141.     private static final double EPSILON_DEFAULT = 1.0e-13;

  142.     /** Default value for maxIterations. */
  143.     private static final int MAX_ITERATIONS_DEFAULT = 200;

  144.     /** Flag specifying whether the initial orbital state is given with osculating elements. */
  145.     private boolean initialIsOsculating;

  146.     /** Field used by this class.*/
  147.     private final Field<T> field;

  148.     /** Force models used to compute short periodic terms. */
  149.     private final transient List<DSSTForceModel> forceModels;

  150.     /** State mapper holding the force models. */
  151.     private FieldMeanPlusShortPeriodicMapper mapper;

  152.     /** Generator for the interpolation grid. */
  153.     private FieldInterpolationGrid<T> interpolationgrid;

  154.     /** Create a new instance of DSSTPropagator.
  155.      *  <p>
  156.      *  After creation, there are no perturbing forces at all.
  157.      *  This means that if {@link #addForceModel addForceModel}
  158.      *  is not called after creation, the integrated orbit will
  159.      *  follow a Keplerian evolution only.
  160.      *  </p>
  161.      *
  162.      * <p>This constructor uses the {@link DataContext#getDefault() default data context}.
  163.      *
  164.      *  @param field field used by default
  165.      *  @param integrator numerical integrator to use for propagation.
  166.      *  @param propagationType type of orbit to output (mean or osculating).
  167.      * @see #FieldDSSTPropagator(Field, FieldODEIntegrator, PropagationType,
  168.      * AttitudeProvider)
  169.      */
  170.     @DefaultDataContext
  171.     public FieldDSSTPropagator(final Field<T> field, final FieldODEIntegrator<T> integrator, final PropagationType propagationType) {
  172.         this(field, integrator, propagationType,
  173.                 Propagator.getDefaultLaw(DataContext.getDefault().getFrames()));
  174.     }

  175.     /** Create a new instance of DSSTPropagator.
  176.      *  <p>
  177.      *  After creation, there are no perturbing forces at all.
  178.      *  This means that if {@link #addForceModel addForceModel}
  179.      *  is not called after creation, the integrated orbit will
  180.      *  follow a Keplerian evolution only.
  181.      *  </p>
  182.      * @param field field used by default
  183.      *  @param integrator numerical integrator to use for propagation.
  184.      * @param propagationType type of orbit to output (mean or osculating).
  185.      * @param attitudeProvider attitude law to use.
  186.      * @since 10.1
  187.      */
  188.     public FieldDSSTPropagator(final Field<T> field,
  189.                                final FieldODEIntegrator<T> integrator,
  190.                                final PropagationType propagationType,
  191.                                final AttitudeProvider attitudeProvider) {
  192.         super(field, integrator, propagationType);
  193.         this.field  = field;
  194.         forceModels = new ArrayList<DSSTForceModel>();
  195.         initMapper(field);
  196.         // DSST uses only equinoctial orbits and mean longitude argument
  197.         setOrbitType(OrbitType.EQUINOCTIAL);
  198.         setPositionAngleType(PositionAngle.MEAN);
  199.         setAttitudeProvider(attitudeProvider);
  200.         setInterpolationGridToFixedNumberOfPoints(INTERPOLATION_POINTS_PER_STEP);
  201.     }

  202.     /** Create a new instance of DSSTPropagator.
  203.      *  <p>
  204.      *  After creation, there are no perturbing forces at all.
  205.      *  This means that if {@link #addForceModel addForceModel}
  206.      *  is not called after creation, the integrated orbit will
  207.      *  follow a Keplerian evolution only. Only the mean orbits
  208.      *  will be generated.
  209.      *  </p>
  210.      *
  211.      * <p>This constructor uses the {@link DataContext#getDefault() default data context}.
  212.      *
  213.      *  @param field fied used by default
  214.      *  @param integrator numerical integrator to use for propagation.
  215.      * @see #FieldDSSTPropagator(Field, FieldODEIntegrator, AttitudeProvider)
  216.      */
  217.     @DefaultDataContext
  218.     public FieldDSSTPropagator(final Field<T> field, final FieldODEIntegrator<T> integrator) {
  219.         this(field, integrator,
  220.                 Propagator.getDefaultLaw(DataContext.getDefault().getFrames()));
  221.     }

  222.     /** Create a new instance of DSSTPropagator.
  223.      *  <p>
  224.      *  After creation, there are no perturbing forces at all.
  225.      *  This means that if {@link #addForceModel addForceModel}
  226.      *  is not called after creation, the integrated orbit will
  227.      *  follow a Keplerian evolution only. Only the mean orbits
  228.      *  will be generated.
  229.      *  </p>
  230.      * @param field fied used by default
  231.      *  @param integrator numerical integrator to use for propagation.
  232.      * @param attitudeProvider attitude law to use.
  233.      * @since 10.1
  234.      */
  235.     public FieldDSSTPropagator(final Field<T> field,
  236.                                final FieldODEIntegrator<T> integrator,
  237.                                final AttitudeProvider attitudeProvider) {
  238.         super(field, integrator, PropagationType.MEAN);
  239.         this.field  = field;
  240.         forceModels = new ArrayList<DSSTForceModel>();
  241.         initMapper(field);
  242.         // DSST uses only equinoctial orbits and mean longitude argument
  243.         setOrbitType(OrbitType.EQUINOCTIAL);
  244.         setPositionAngleType(PositionAngle.MEAN);
  245.         setAttitudeProvider(attitudeProvider);
  246.         setInterpolationGridToFixedNumberOfPoints(INTERPOLATION_POINTS_PER_STEP);
  247.     }

  248.     /** Set the central attraction coefficient μ.
  249.      * <p>
  250.      * Setting the central attraction coefficient is
  251.      * equivalent to {@link #addForceModel(DSSTForceModel) add}
  252.      * a {@link DSSTNewtonianAttraction} force model.
  253.      * </p>
  254.     * @param mu central attraction coefficient (m³/s²)
  255.     * @see #addForceModel(DSSTForceModel)
  256.     * @see #getAllForceModels()
  257.     */
  258.     public void setMu(final T mu) {
  259.         addForceModel(new DSSTNewtonianAttraction(mu.getReal()));
  260.     }

  261.     /** Set the central attraction coefficient μ only in upper class.
  262.      * @param mu central attraction coefficient (m³/s²)
  263.      */
  264.     private void superSetMu(final T mu) {
  265.         super.setMu(mu);
  266.     }

  267.     /** Check if Newtonian attraction force model is available.
  268.      * <p>
  269.      * Newtonian attraction is always the last force model in the list.
  270.      * </p>
  271.      * @return true if Newtonian attraction force model is available
  272.      */
  273.     private boolean hasNewtonianAttraction() {
  274.         final int last = forceModels.size() - 1;
  275.         return last >= 0 && forceModels.get(last) instanceof DSSTNewtonianAttraction;
  276.     }

  277.     /** Set the initial state with osculating orbital elements.
  278.      *  @param initialState initial state (defined with osculating elements)
  279.      */
  280.     public void setInitialState(final FieldSpacecraftState<T> initialState) {
  281.         setInitialState(initialState, PropagationType.OSCULATING);
  282.     }

  283.     /** Set the initial state.
  284.      *  @param initialState initial state
  285.      *  @param stateType defined if the orbital state is defined with osculating or mean elements
  286.      */
  287.     public void setInitialState(final FieldSpacecraftState<T> initialState,
  288.                                 final PropagationType stateType) {
  289.         switch (stateType) {
  290.             case MEAN:
  291.                 initialIsOsculating = false;
  292.                 break;
  293.             case OSCULATING:
  294.                 initialIsOsculating = true;
  295.                 break;
  296.             default:
  297.                 throw new OrekitInternalError(null);
  298.         }
  299.         resetInitialState(initialState);
  300.     }

  301.     /** Reset the initial state.
  302.      *
  303.      *  @param state new initial state
  304.      */
  305.     @Override
  306.     public void resetInitialState(final FieldSpacecraftState<T> state) {
  307.         super.resetInitialState(state);
  308.         if (!hasNewtonianAttraction()) {
  309.             // use the state to define central attraction
  310.             setMu(state.getMu());
  311.         }
  312.         super.setStartDate(state.getDate());
  313.     }

  314.     /** Set the selected short periodic coefficients that must be stored as additional states.
  315.      * @param selectedCoefficients short periodic coefficients that must be stored as additional states
  316.      * (null means no coefficients are selected, empty set means all coefficients are selected)
  317.      */
  318.     public void setSelectedCoefficients(final Set<String> selectedCoefficients) {
  319.         mapper.setSelectedCoefficients(selectedCoefficients == null ?
  320.                                        null : new HashSet<String>(selectedCoefficients));
  321.     }

  322.     /** Get the selected short periodic coefficients that must be stored as additional states.
  323.      * @return short periodic coefficients that must be stored as additional states
  324.      * (null means no coefficients are selected, empty set means all coefficients are selected)
  325.      */
  326.     public Set<String> getSelectedCoefficients() {
  327.         final Set<String> set = mapper.getSelectedCoefficients();
  328.         return set == null ? null : Collections.unmodifiableSet(set);
  329.     }

  330.     /** Check if the initial state is provided in osculating elements.
  331.      * @return true if initial state is provided in osculating elements
  332.      */
  333.     public boolean initialIsOsculating() {
  334.         return initialIsOsculating;
  335.     }

  336.     /** Set the interpolation grid generator.
  337.      * <p>
  338.      * The generator will create an interpolation grid with a fixed
  339.      * number of points for each mean element integration step.
  340.      * </p>
  341.      * <p>
  342.      * If neither {@link #setInterpolationGridToFixedNumberOfPoints(int)}
  343.      * nor {@link #setInterpolationGridToMaxTimeGap(CalculusFieldElement)} has been called,
  344.      * by default the propagator is set as to 3 interpolations points per step.
  345.      * </p>
  346.      * @param interpolationPoints number of interpolation points at
  347.      * each integration step
  348.      * @see #setInterpolationGridToMaxTimeGap(CalculusFieldElement)
  349.      * @since 7.1
  350.      */
  351.     public void setInterpolationGridToFixedNumberOfPoints(final int interpolationPoints) {
  352.         interpolationgrid = new FieldFixedNumberInterpolationGrid<>(field, interpolationPoints);
  353.     }

  354.     /** Set the interpolation grid generator.
  355.      * <p>
  356.      * The generator will create an interpolation grid with a maximum
  357.      * time gap between interpolation points.
  358.      * </p>
  359.      * <p>
  360.      * If neither {@link #setInterpolationGridToFixedNumberOfPoints(int)}
  361.      * nor {@link #setInterpolationGridToMaxTimeGap(CalculusFieldElement)} has been called,
  362.      * by default the propagator is set as to 3 interpolations points per step.
  363.      * </p>
  364.      * @param maxGap maximum time gap between interpolation points (seconds)
  365.      * @see #setInterpolationGridToFixedNumberOfPoints(int)
  366.      * @since 7.1
  367.      */
  368.     public void setInterpolationGridToMaxTimeGap(final T maxGap) {
  369.         interpolationgrid = new FieldMaxGapInterpolationGrid<>(field, maxGap);
  370.     }

  371.     /** Add a force model to the global perturbation model.
  372.      *  <p>
  373.      *  If this method is not called at all,
  374.      *  the integrated orbit will follow a Keplerian evolution only.
  375.      *  </p>
  376.      *  @param force perturbing {@link DSSTForceModel force} to add
  377.      *  @see #removeForceModels()
  378.      *  @see #setMu(CalculusFieldElement)
  379.      */
  380.     public void addForceModel(final DSSTForceModel force) {

  381.         if (force instanceof DSSTNewtonianAttraction) {
  382.             // we want to add the central attraction force model

  383.             try {
  384.                 // ensure we are notified of any mu change
  385.                 force.getParametersDrivers().get(0).addObserver(new ParameterObserver() {
  386.                     /** {@inheritDoc} */
  387.                     @Override
  388.                     public void valueChanged(final double previousValue, final ParameterDriver driver) {
  389.                         superSetMu(field.getZero().add(driver.getValue()));
  390.                     }
  391.                 });
  392.             } catch (OrekitException oe) {
  393.                 // this should never happen
  394.                 throw new OrekitInternalError(oe);
  395.             }

  396.             if (hasNewtonianAttraction()) {
  397.                 // there is already a central attraction model, replace it
  398.                 forceModels.set(forceModels.size() - 1, force);
  399.             } else {
  400.                 // there are no central attraction model yet, add it at the end of the list
  401.                 forceModels.add(force);
  402.             }
  403.         } else {
  404.             // we want to add a perturbing force model
  405.             if (hasNewtonianAttraction()) {
  406.                 // insert the new force model before Newtonian attraction,
  407.                 // which should always be the last one in the list
  408.                 forceModels.add(forceModels.size() - 1, force);
  409.             } else {
  410.                 // we only have perturbing force models up to now, just append at the end of the list
  411.                 forceModels.add(force);
  412.             }
  413.         }

  414.         force.registerAttitudeProvider(getAttitudeProvider());

  415.     }

  416.     /** Remove all perturbing force models from the global perturbation model
  417.      *  (except central attraction).
  418.      *  <p>
  419.      *  Once all perturbing forces have been removed (and as long as no new force model is added),
  420.      *  the integrated orbit will follow a Keplerian evolution only.
  421.      *  </p>
  422.      *  @see #addForceModel(DSSTForceModel)
  423.      */
  424.     public void removeForceModels() {
  425.         final int last = forceModels.size() - 1;
  426.         if (hasNewtonianAttraction()) {
  427.             // preserve the Newtonian attraction model at the end
  428.             final DSSTForceModel newton = forceModels.get(last);
  429.             forceModels.clear();
  430.             forceModels.add(newton);
  431.         } else {
  432.             forceModels.clear();
  433.         }
  434.     }

  435.     /** Get all the force models, perturbing forces and Newtonian attraction included.
  436.      * @return list of perturbing force models, with Newtonian attraction being the
  437.      * last one
  438.      * @see #addForceModel(DSSTForceModel)
  439.      * @see #setMu(CalculusFieldElement)
  440.      */
  441.     public List<DSSTForceModel> getAllForceModels() {
  442.         return Collections.unmodifiableList(forceModels);
  443.     }

  444.     /** Get propagation parameter type.
  445.      * @return orbit type used for propagation
  446.      */
  447.     public OrbitType getOrbitType() {
  448.         return super.getOrbitType();
  449.     }

  450.     /** Get propagation parameter type.
  451.      * @return angle type to use for propagation
  452.      */
  453.     public PositionAngle getPositionAngleType() {
  454.         return super.getPositionAngleType();
  455.     }

  456.     /** Conversion from mean to osculating orbit.
  457.      * <p>
  458.      * Compute osculating state <b>in a DSST sense</b>, corresponding to the
  459.      * mean SpacecraftState in input, and according to the Force models taken
  460.      * into account.
  461.      * </p><p>
  462.      * Since the osculating state is obtained by adding short-periodic variation
  463.      * of each force model, the resulting output will depend on the
  464.      * force models parameterized in input.
  465.      * </p>
  466.      * @param mean Mean state to convert
  467.      * @param forces Forces to take into account
  468.      * @param attitudeProvider attitude provider (may be null if there are no Gaussian force models
  469.      * like atmospheric drag, radiation pressure or specific user-defined models)
  470.      * @param <T> type of the elements
  471.      * @return osculating state in a DSST sense
  472.      */
  473.     @SuppressWarnings("unchecked")
  474.     public static <T extends CalculusFieldElement<T>> FieldSpacecraftState<T> computeOsculatingState(final FieldSpacecraftState<T> mean,
  475.                                                                                                  final AttitudeProvider attitudeProvider,
  476.                                                                                                  final Collection<DSSTForceModel> forces) {

  477.         //Create the auxiliary object
  478.         final FieldAuxiliaryElements<T> aux = new FieldAuxiliaryElements<>(mean.getOrbit(), I);

  479.         // Set the force models
  480.         final List<FieldShortPeriodTerms<T>> shortPeriodTerms = new ArrayList<FieldShortPeriodTerms<T>>();
  481.         for (final DSSTForceModel force : forces) {
  482.             final T[] parameters = force.getParameters(mean.getDate().getField());
  483.             force.registerAttitudeProvider(attitudeProvider);
  484.             shortPeriodTerms.addAll(force.initializeShortPeriodTerms(aux, PropagationType.OSCULATING, parameters));
  485.             force.updateShortPeriodTerms(parameters, mean);
  486.         }

  487.         final FieldEquinoctialOrbit<T> osculatingOrbit = computeOsculatingOrbit(mean, shortPeriodTerms);

  488.         return new FieldSpacecraftState<>(osculatingOrbit, mean.getAttitude(), mean.getMass(),
  489.                                           mean.getAdditionalStatesValues());

  490.     }

  491.     /** Conversion from osculating to mean orbit.
  492.      * <p>
  493.      * Compute mean state <b>in a DSST sense</b>, corresponding to the
  494.      * osculating SpacecraftState in input, and according to the Force models
  495.      * taken into account.
  496.      * </p><p>
  497.      * Since the osculating state is obtained with the computation of
  498.      * short-periodic variation of each force model, the resulting output will
  499.      * depend on the force models parameterized in input.
  500.      * </p><p>
  501.      * The computation is done through a fixed-point iteration process.
  502.      * </p>
  503.      * @param osculating Osculating state to convert
  504.      * @param attitudeProvider attitude provider (may be null if there are no Gaussian force models
  505.      * like atmospheric drag, radiation pressure or specific user-defined models)
  506.      * @param forceModel Forces to take into account
  507.      * @param <T> type of the elements
  508.      * @return mean state in a DSST sense
  509.      */
  510.     public static <T extends CalculusFieldElement<T>> FieldSpacecraftState<T> computeMeanState(final FieldSpacecraftState<T> osculating,
  511.                                                                                            final AttitudeProvider attitudeProvider,
  512.                                                                                            final Collection<DSSTForceModel> forceModel) {
  513.         return computeMeanState(osculating, attitudeProvider, forceModel, EPSILON_DEFAULT, MAX_ITERATIONS_DEFAULT);
  514.     }

  515.     /** Conversion from osculating to mean orbit.
  516.      * <p>
  517.      * Compute mean state <b>in a DSST sense</b>, corresponding to the
  518.      * osculating SpacecraftState in input, and according to the Force models
  519.      * taken into account.
  520.      * </p><p>
  521.      * Since the osculating state is obtained with the computation of
  522.      * short-periodic variation of each force model, the resulting output will
  523.      * depend on the force models parameterized in input.
  524.      * </p><p>
  525.      * The computation is done through a fixed-point iteration process.
  526.      * </p>
  527.      * @param osculating Osculating state to convert
  528.      * @param attitudeProvider attitude provider (may be null if there are no Gaussian force models
  529.      * like atmospheric drag, radiation pressure or specific user-defined models)
  530.      * @param forceModel Forces to take into account
  531.      * @param epsilon convergence threshold for mean parameters conversion
  532.      * @param maxIterations maximum iterations for mean parameters conversion
  533.      * @return mean state in a DSST sense
  534.      * @param <T> type of the elements
  535.      * @since 10.1
  536.      */
  537.     public static <T extends CalculusFieldElement<T>> FieldSpacecraftState<T> computeMeanState(final FieldSpacecraftState<T> osculating,
  538.                                                                                            final AttitudeProvider attitudeProvider,
  539.                                                                                            final Collection<DSSTForceModel> forceModel,
  540.                                                                                            final double epsilon,
  541.                                                                                            final int maxIterations) {
  542.         final FieldOrbit<T> meanOrbit = computeMeanOrbit(osculating, attitudeProvider, forceModel, epsilon, maxIterations);
  543.         return new FieldSpacecraftState<>(meanOrbit, osculating.getAttitude(), osculating.getMass(),
  544.                                           osculating.getAdditionalStatesValues());
  545.     }

  546.     /** Override the default value of the parameter.
  547.     *  <p>
  548.     *  By default, if the initial orbit is defined as osculating,
  549.     *  it will be averaged over 2 satellite revolutions.
  550.     *  This can be changed by using this method.
  551.     *  </p>
  552.     *  @param satelliteRevolution number of satellite revolutions to use for converting osculating to mean
  553.     *                             elements
  554.     */
  555.     public void setSatelliteRevolution(final int satelliteRevolution) {
  556.         mapper.setSatelliteRevolution(satelliteRevolution);
  557.     }

  558.    /** Get the number of satellite revolutions to use for converting osculating to mean elements.
  559.     *  @return number of satellite revolutions to use for converting osculating to mean elements
  560.     */
  561.     public int getSatelliteRevolution() {
  562.         return mapper.getSatelliteRevolution();
  563.     }

  564.    /** {@inheritDoc} */
  565.     @Override
  566.     public void setAttitudeProvider(final AttitudeProvider attitudeProvider) {
  567.         super.setAttitudeProvider(attitudeProvider);

  568.         //Register the attitude provider for each force model
  569.         for (final DSSTForceModel force : forceModels) {
  570.             force.registerAttitudeProvider(attitudeProvider);
  571.         }
  572.     }

  573.     /** Method called just before integration.
  574.      * <p>
  575.      * The default implementation does nothing, it may be specialized in subclasses.
  576.      * </p>
  577.      * @param initialState initial state
  578.      * @param tEnd target date at which state should be propagated
  579.      */
  580.     @SuppressWarnings("unchecked")
  581.     @Override
  582.     protected void beforeIntegration(final FieldSpacecraftState<T> initialState,
  583.                                      final FieldAbsoluteDate<T> tEnd) {

  584.         // check if only mean elements must be used
  585.         final PropagationType type = isMeanOrbit();

  586.         // compute common auxiliary elements
  587.         final FieldAuxiliaryElements<T> aux = new FieldAuxiliaryElements<>(initialState.getOrbit(), I);

  588.         // initialize all perturbing forces
  589.         final List<FieldShortPeriodTerms<T>> shortPeriodTerms = new ArrayList<FieldShortPeriodTerms<T>>();
  590.         for (final DSSTForceModel force : forceModels) {
  591.             shortPeriodTerms.addAll(force.initializeShortPeriodTerms(aux, type, force.getParameters(field)));
  592.         }
  593.         mapper.setShortPeriodTerms(shortPeriodTerms);

  594.         // if required, insert the special short periodics step handler
  595.         if (type == PropagationType.OSCULATING) {
  596.             final FieldShortPeriodicsHandler spHandler = new FieldShortPeriodicsHandler(forceModels);
  597.             // Compute short periodic coefficients for this point
  598.             for (DSSTForceModel forceModel : forceModels) {
  599.                 forceModel.updateShortPeriodTerms(forceModel.getParameters(field), initialState);

  600.             }
  601.             final Collection<FieldODEStepHandler<T>> stepHandlers = new ArrayList<FieldODEStepHandler<T>>();
  602.             stepHandlers.add(spHandler);
  603.             final FieldODEIntegrator<T> integrator = getIntegrator();
  604.             final Collection<FieldODEStepHandler<T>> existing = integrator.getStepHandlers();
  605.             stepHandlers.addAll(existing);

  606.             integrator.clearStepHandlers();

  607.             // add back the existing handlers after the short periodics one
  608.             for (final FieldODEStepHandler<T> sp : stepHandlers) {
  609.                 integrator.addStepHandler(sp);
  610.             }
  611.         }
  612.     }

  613.     /** {@inheritDoc} */
  614.     @Override
  615.     protected void afterIntegration() {
  616.         // remove the special short periodics step handler if added before
  617.         if (isMeanOrbit() ==  PropagationType.OSCULATING) {
  618.             final List<FieldODEStepHandler<T>> preserved = new ArrayList<FieldODEStepHandler<T>>();
  619.             final FieldODEIntegrator<T> integrator = getIntegrator();

  620.             // clear the list
  621.             integrator.clearStepHandlers();

  622.             // add back the step handlers that were important for the user
  623.             for (final FieldODEStepHandler<T> sp : preserved) {
  624.                 integrator.addStepHandler(sp);
  625.             }
  626.         }
  627.     }

  628.     /** Compute mean state from osculating state.
  629.      * <p>
  630.      * Compute in a DSST sense the mean state corresponding to the input osculating state.
  631.      * </p><p>
  632.      * The computing is done through a fixed-point iteration process.
  633.      * </p>
  634.      * @param osculating initial osculating state
  635.      * @param attitudeProvider attitude provider (may be null if there are no Gaussian force models
  636.      * like atmospheric drag, radiation pressure or specific user-defined models)
  637.      * @param forceModel force models
  638.      * @param epsilon convergence threshold for mean parameters conversion
  639.      * @param maxIterations maximum iterations for mean parameters conversion
  640.      * @param <T> type of the elements
  641.      * @return mean state
  642.      * @since 10.1
  643.      */
  644.     @SuppressWarnings("unchecked")
  645.     private static <T extends CalculusFieldElement<T>> FieldOrbit<T> computeMeanOrbit(final FieldSpacecraftState<T> osculating, final AttitudeProvider attitudeProvider, final Collection<DSSTForceModel> forceModel,
  646.                                                                                   final double epsilon, final int maxIterations) {

  647.         // zero
  648.         final T zero = osculating.getDate().getField().getZero();

  649.         // rough initialization of the mean parameters
  650.         FieldEquinoctialOrbit<T> meanOrbit = (FieldEquinoctialOrbit<T>) OrbitType.EQUINOCTIAL.convertType(osculating.getOrbit());

  651.         // threshold for each parameter
  652.         final T epsilonT   = zero.add(epsilon);
  653.         final T thresholdA = epsilonT.multiply(FastMath.abs(meanOrbit.getA()).add(1.));
  654.         final T thresholdE = epsilonT.multiply(meanOrbit.getE().add(1.));
  655.         final T thresholdI = epsilonT.multiply(meanOrbit.getI().add(1.));
  656.         final T thresholdL = epsilonT.multiply(zero.getPi());

  657.         // ensure all Gaussian force models can rely on attitude
  658.         for (final DSSTForceModel force : forceModel) {
  659.             force.registerAttitudeProvider(attitudeProvider);
  660.         }

  661.         int i = 0;
  662.         while (i++ < maxIterations) {

  663.             final FieldSpacecraftState<T> meanState = new FieldSpacecraftState<>(meanOrbit, osculating.getAttitude(), osculating.getMass());

  664.             //Create the auxiliary object
  665.             final FieldAuxiliaryElements<T> aux = new FieldAuxiliaryElements<>(meanOrbit, I);

  666.             // Set the force models
  667.             final List<FieldShortPeriodTerms<T>> shortPeriodTerms = new ArrayList<FieldShortPeriodTerms<T>>();
  668.             for (final DSSTForceModel force : forceModel) {
  669.                 final T[] parameters = force.getParameters(osculating.getDate().getField());
  670.                 shortPeriodTerms.addAll(force.initializeShortPeriodTerms(aux, PropagationType.OSCULATING, parameters));
  671.                 force.updateShortPeriodTerms(parameters, meanState);
  672.             }

  673.             // recompute the osculating parameters from the current mean parameters
  674.             final FieldEquinoctialOrbit<T> rebuilt = computeOsculatingOrbit(meanState, shortPeriodTerms);

  675.             // adapted parameters residuals
  676.             final T deltaA  = osculating.getA().subtract(rebuilt.getA());
  677.             final T deltaEx = osculating.getEquinoctialEx().subtract(rebuilt.getEquinoctialEx());
  678.             final T deltaEy = osculating.getEquinoctialEy().subtract(rebuilt.getEquinoctialEy());
  679.             final T deltaHx = osculating.getHx().subtract(rebuilt.getHx());
  680.             final T deltaHy = osculating.getHy().subtract(rebuilt.getHy());
  681.             final T deltaLv = MathUtils.normalizeAngle(osculating.getLv().subtract(rebuilt.getLv()), zero);

  682.             // check convergence
  683.             if (FastMath.abs(deltaA).getReal()  < thresholdA.getReal() &&
  684.                 FastMath.abs(deltaEx).getReal() < thresholdE.getReal() &&
  685.                 FastMath.abs(deltaEy).getReal() < thresholdE.getReal() &&
  686.                 FastMath.abs(deltaHx).getReal() < thresholdI.getReal() &&
  687.                 FastMath.abs(deltaHy).getReal() < thresholdI.getReal() &&
  688.                 FastMath.abs(deltaLv).getReal() < thresholdL.getReal()) {
  689.                 return meanOrbit;
  690.             }

  691.             // update mean parameters
  692.             meanOrbit = new FieldEquinoctialOrbit<>(meanOrbit.getA().add(deltaA),
  693.                                                     meanOrbit.getEquinoctialEx().add(deltaEx),
  694.                                                     meanOrbit.getEquinoctialEy().add(deltaEy),
  695.                                                     meanOrbit.getHx().add(deltaHx),
  696.                                                     meanOrbit.getHy().add(deltaHy),
  697.                                                     meanOrbit.getLv().add(deltaLv),
  698.                                                     PositionAngle.TRUE, meanOrbit.getFrame(),
  699.                                                     meanOrbit.getDate(), meanOrbit.getMu());
  700.         }

  701.         throw new OrekitException(OrekitMessages.UNABLE_TO_COMPUTE_DSST_MEAN_PARAMETERS, i);
  702.     }

  703.     /** Compute osculating state from mean state.
  704.      * <p>
  705.      * Compute and add the short periodic variation to the mean {@link SpacecraftState}.
  706.      * </p>
  707.      * @param meanState initial mean state
  708.      * @param shortPeriodTerms short period terms
  709.      * @param <T> type of the elements
  710.      * @return osculating state
  711.      */
  712.     private static <T extends CalculusFieldElement<T>> FieldEquinoctialOrbit<T> computeOsculatingOrbit(final FieldSpacecraftState<T> meanState,
  713.                                                                                                    final List<FieldShortPeriodTerms<T>> shortPeriodTerms) {

  714.         final T[] mean = MathArrays.buildArray(meanState.getDate().getField(), 6);
  715.         final T[] meanDot = MathArrays.buildArray(meanState.getDate().getField(), 6);
  716.         OrbitType.EQUINOCTIAL.mapOrbitToArray(meanState.getOrbit(), PositionAngle.MEAN, mean, meanDot);
  717.         final T[] y = mean.clone();
  718.         for (final FieldShortPeriodTerms<T> spt : shortPeriodTerms) {
  719.             final T[] shortPeriodic = spt.value(meanState.getOrbit());
  720.             for (int i = 0; i < shortPeriodic.length; i++) {
  721.                 y[i] = y[i].add(shortPeriodic[i]);
  722.             }
  723.         }
  724.         return (FieldEquinoctialOrbit<T>) OrbitType.EQUINOCTIAL.mapArrayToOrbit(y, meanDot,
  725.                                                                                 PositionAngle.MEAN, meanState.getDate(),
  726.                                                                                 meanState.getMu(), meanState.getFrame());
  727.     }

  728.     /** {@inheritDoc} */
  729.     @Override
  730.     protected FieldSpacecraftState<T> getInitialIntegrationState() {
  731.         if (initialIsOsculating) {
  732.             // the initial state is an osculating state,
  733.             // it must be converted to mean state
  734.             return computeMeanState(getInitialState(), getAttitudeProvider(), forceModels);
  735.         } else {
  736.             // the initial state is already a mean state
  737.             return getInitialState();
  738.         }
  739.     }

  740.     /** {@inheritDoc}
  741.      * <p>
  742.      * Note that for DSST, orbit type is hardcoded to {@link OrbitType#EQUINOCTIAL}
  743.      * and position angle type is hardcoded to {@link PositionAngle#MEAN}, so
  744.      * the corresponding parameters are ignored.
  745.      * </p>
  746.      */
  747.     @Override
  748.     protected FieldStateMapper<T> createMapper(final FieldAbsoluteDate<T> referenceDate, final T mu,
  749.                                                final OrbitType ignoredOrbitType, final PositionAngle ignoredPositionAngleType,
  750.                                                final AttitudeProvider attitudeProvider, final Frame frame) {

  751.         // create a mapper with the common settings provided as arguments
  752.         final FieldMeanPlusShortPeriodicMapper newMapper =
  753.                 new FieldMeanPlusShortPeriodicMapper(referenceDate, mu, attitudeProvider, frame);

  754.         // copy the specific settings from the existing mapper
  755.         if (mapper != null) {
  756.             newMapper.setSatelliteRevolution(mapper.getSatelliteRevolution());
  757.             newMapper.setSelectedCoefficients(mapper.getSelectedCoefficients());
  758.             newMapper.setShortPeriodTerms(mapper.getShortPeriodTerms());
  759.         }

  760.         mapper = newMapper;
  761.         return mapper;

  762.     }

  763.     /** Internal mapper using mean parameters plus short periodic terms. */
  764.     private class FieldMeanPlusShortPeriodicMapper extends FieldStateMapper<T> {

  765.         /** Short periodic coefficients that must be stored as additional states. */
  766.         private Set<String>                selectedCoefficients;

  767.         /** Number of satellite revolutions in the averaging interval. */
  768.         private int                        satelliteRevolution;

  769.         /** Short period terms. */
  770.         private List<FieldShortPeriodTerms<T>>     shortPeriodTerms;

  771.         /** Simple constructor.
  772.          * @param referenceDate reference date
  773.          * @param mu central attraction coefficient (m³/s²)
  774.          * @param attitudeProvider attitude provider
  775.          * @param frame inertial frame
  776.          */
  777.         FieldMeanPlusShortPeriodicMapper(final FieldAbsoluteDate<T> referenceDate, final T mu,
  778.                                          final AttitudeProvider attitudeProvider, final Frame frame) {

  779.             super(referenceDate, mu, OrbitType.EQUINOCTIAL, PositionAngle.MEAN, attitudeProvider, frame);

  780.             this.selectedCoefficients = null;

  781.             // Default averaging period for conversion from osculating to mean elements
  782.             this.satelliteRevolution = 2;

  783.             this.shortPeriodTerms    = Collections.emptyList();

  784.         }

  785.         /** {@inheritDoc} */
  786.         @Override
  787.         public FieldSpacecraftState<T> mapArrayToState(final FieldAbsoluteDate<T> date,
  788.                                                        final T[] y, final T[] yDot,
  789.                                                        final PropagationType type) {

  790.             // add short periodic variations to mean elements to get osculating elements
  791.             // (the loop may not be performed if there are no force models and in the
  792.             //  case we want to remain in mean parameters only)
  793.             final T[] elements = y.clone();
  794.             final FieldArrayDictionary<T> coefficients;
  795.             switch (type) {
  796.                 case MEAN:
  797.                     coefficients = null;
  798.                     break;
  799.                 case OSCULATING:
  800.                     final FieldOrbit<T> meanOrbit = OrbitType.EQUINOCTIAL.mapArrayToOrbit(elements, yDot, PositionAngle.MEAN, date, getMu(), getFrame());
  801.                     coefficients = selectedCoefficients == null ? null : new FieldArrayDictionary<>(date.getField());
  802.                     for (final FieldShortPeriodTerms<T> spt : shortPeriodTerms) {
  803.                         final T[] shortPeriodic = spt.value(meanOrbit);
  804.                         for (int i = 0; i < shortPeriodic.length; i++) {
  805.                             elements[i] = elements[i].add(shortPeriodic[i]);
  806.                         }
  807.                         if (selectedCoefficients != null) {
  808.                             coefficients.putAll(spt.getCoefficients(date, selectedCoefficients));
  809.                         }
  810.                     }
  811.                     break;
  812.                 default:
  813.                     throw new OrekitInternalError(null);
  814.             }

  815.             final T mass = elements[6];
  816.             if (mass.getReal() <= 0.0) {
  817.                 throw new OrekitException(OrekitMessages.SPACECRAFT_MASS_BECOMES_NEGATIVE, mass);
  818.             }

  819.             final FieldOrbit<T> orbit       = OrbitType.EQUINOCTIAL.mapArrayToOrbit(elements, yDot, PositionAngle.MEAN, date, getMu(), getFrame());
  820.             final FieldAttitude<T> attitude = getAttitudeProvider().getAttitude(orbit, date, getFrame());

  821.             if (coefficients == null) {
  822.                 return new FieldSpacecraftState<>(orbit, attitude, mass);
  823.             } else {
  824.                 return new FieldSpacecraftState<>(orbit, attitude, mass, coefficients);
  825.             }

  826.         }

  827.         /** {@inheritDoc} */
  828.         @Override
  829.         public void mapStateToArray(final FieldSpacecraftState<T> state, final T[] y, final T[] yDot) {

  830.             OrbitType.EQUINOCTIAL.mapOrbitToArray(state.getOrbit(), PositionAngle.MEAN, y, yDot);
  831.             y[6] = state.getMass();

  832.         }

  833.         /** Set the number of satellite revolutions to use for converting osculating to mean elements.
  834.          *  <p>
  835.          *  By default, if the initial orbit is defined as osculating,
  836.          *  it will be averaged over 2 satellite revolutions.
  837.          *  This can be changed by using this method.
  838.          *  </p>
  839.          *  @param satelliteRevolution number of satellite revolutions to use for converting osculating to mean
  840.          *                             elements
  841.          */
  842.         public void setSatelliteRevolution(final int satelliteRevolution) {
  843.             this.satelliteRevolution = satelliteRevolution;
  844.         }

  845.         /** Get the number of satellite revolutions to use for converting osculating to mean elements.
  846.          *  @return number of satellite revolutions to use for converting osculating to mean elements
  847.          */
  848.         public int getSatelliteRevolution() {
  849.             return satelliteRevolution;
  850.         }

  851.         /** Set the selected short periodic coefficients that must be stored as additional states.
  852.          * @param selectedCoefficients short periodic coefficients that must be stored as additional states
  853.          * (null means no coefficients are selected, empty set means all coefficients are selected)
  854.          */
  855.         public void setSelectedCoefficients(final Set<String> selectedCoefficients) {
  856.             this.selectedCoefficients = selectedCoefficients;
  857.         }

  858.         /** Get the selected short periodic coefficients that must be stored as additional states.
  859.          * @return short periodic coefficients that must be stored as additional states
  860.          * (null means no coefficients are selected, empty set means all coefficients are selected)
  861.          */
  862.         public Set<String> getSelectedCoefficients() {
  863.             return selectedCoefficients;
  864.         }

  865.         /** Set the short period terms.
  866.          * @param shortPeriodTerms short period terms
  867.          * @since 7.1
  868.          */
  869.         public void setShortPeriodTerms(final List<FieldShortPeriodTerms<T>> shortPeriodTerms) {
  870.             this.shortPeriodTerms = shortPeriodTerms;
  871.         }

  872.         /** Get the short period terms.
  873.          * @return shortPeriodTerms short period terms
  874.          * @since 7.1
  875.          */
  876.         public List<FieldShortPeriodTerms<T>> getShortPeriodTerms() {
  877.             return shortPeriodTerms;
  878.         }

  879.     }

  880.     /** {@inheritDoc} */
  881.     @Override
  882.     protected MainStateEquations<T> getMainStateEquations(final FieldODEIntegrator<T> integrator) {
  883.         return new Main(integrator);
  884.     }

  885.     /** Internal class for mean parameters integration. */
  886.     private class Main implements MainStateEquations<T> {

  887.         /** Derivatives array. */
  888.         private final T[] yDot;

  889.         /** Simple constructor.
  890.          * @param integrator numerical integrator to use for propagation.
  891.          */
  892.         Main(final FieldODEIntegrator<T> integrator) {
  893.             yDot = MathArrays.buildArray(field, 7);

  894.             for (final DSSTForceModel forceModel : forceModels) {
  895.                 final FieldEventDetector<T>[] modelDetectors = forceModel.getFieldEventsDetectors(field);
  896.                 if (modelDetectors != null) {
  897.                     for (final FieldEventDetector<T> detector : modelDetectors) {
  898.                         setUpEventDetector(integrator, detector);
  899.                     }
  900.                 }
  901.             }

  902.         }

  903.         /** {@inheritDoc} */
  904.         @Override
  905.         public void init(final FieldSpacecraftState<T> initialState, final FieldAbsoluteDate<T> target) {
  906.             forceModels.forEach(fm -> fm.init(initialState, target));
  907.         }

  908.         /** {@inheritDoc} */
  909.         @Override
  910.         public T[] computeDerivatives(final FieldSpacecraftState<T> state) {

  911.             final T zero = state.getDate().getField().getZero();
  912.             Arrays.fill(yDot, zero);

  913.             // compute common auxiliary elements
  914.             final FieldAuxiliaryElements<T> auxiliaryElements = new FieldAuxiliaryElements<>(state.getOrbit(), I);

  915.             // compute the contributions of all perturbing forces
  916.             for (final DSSTForceModel forceModel : forceModels) {
  917.                 final T[] daidt = elementRates(forceModel, state, auxiliaryElements, forceModel.getParameters(field));
  918.                 for (int i = 0; i < daidt.length; i++) {
  919.                     yDot[i] = yDot[i].add(daidt[i]);
  920.                 }
  921.             }

  922.             return yDot.clone();
  923.         }

  924.         /** This method allows to compute the mean equinoctial elements rates da<sub>i</sub> / dt
  925.          *  for a specific force model.
  926.          *  @param forceModel force to take into account
  927.          *  @param state current state
  928.          *  @param auxiliaryElements auxiliary elements related to the current orbit
  929.          *  @param parameters force model parameters
  930.          *  @return the mean equinoctial elements rates da<sub>i</sub> / dt
  931.          */
  932.         private T[] elementRates(final DSSTForceModel forceModel,
  933.                                  final FieldSpacecraftState<T> state,
  934.                                  final FieldAuxiliaryElements<T> auxiliaryElements,
  935.                                  final T[] parameters) {
  936.             return forceModel.getMeanElementRate(state, auxiliaryElements, parameters);
  937.         }

  938.     }

  939.     /** Estimate tolerance vectors for an AdaptativeStepsizeIntegrator.
  940.      *  <p>
  941.      *  The errors are estimated from partial derivatives properties of orbits,
  942.      *  starting from a scalar position error specified by the user.
  943.      *  Considering the energy conservation equation V = sqrt(mu (2/r - 1/a)),
  944.      *  we get at constant energy (i.e. on a Keplerian trajectory):
  945.      *
  946.      *  <pre>
  947.      *  V² r |dV| = mu |dr|
  948.      *  </pre>
  949.      *
  950.      *  <p> So we deduce a scalar velocity error consistent with the position error. From here, we apply
  951.      *  orbits Jacobians matrices to get consistent errors on orbital parameters.
  952.      *
  953.      *  <p>
  954.      *  The tolerances are only <em>orders of magnitude</em>, and integrator tolerances are only
  955.      *  local estimates, not global ones. So some care must be taken when using these tolerances.
  956.      *  Setting 1mm as a position error does NOT mean the tolerances will guarantee a 1mm error
  957.      *  position after several orbits integration.
  958.      *  </p>
  959.      * @param <T> elements type
  960.      * @param dP user specified position error (m)
  961.      * @param orbit reference orbit
  962.      * @return a two rows array, row 0 being the absolute tolerance error
  963.      *                       and row 1 being the relative tolerance error
  964.      */
  965.     public static <T extends CalculusFieldElement<T>> double[][] tolerances(final T dP, final FieldOrbit<T> orbit) {
  966.         return FieldNumericalPropagator.tolerances(dP, orbit, OrbitType.EQUINOCTIAL);
  967.     }

  968.     /** Estimate tolerance vectors for an AdaptativeStepsizeIntegrator.
  969.      *  <p>
  970.      *  The errors are estimated from partial derivatives properties of orbits,
  971.      *  starting from scalar position and velocity errors specified by the user.
  972.      *  <p>
  973.      *  The tolerances are only <em>orders of magnitude</em>, and integrator tolerances are only
  974.      *  local estimates, not global ones. So some care must be taken when using these tolerances.
  975.      *  Setting 1mm as a position error does NOT mean the tolerances will guarantee a 1mm error
  976.      *  position after several orbits integration.
  977.      *  </p>
  978.      *
  979.      * @param <T> elements type
  980.      * @param dP user specified position error (m)
  981.      * @param dV user specified velocity error (m/s)
  982.      * @param orbit reference orbit
  983.      * @return a two rows array, row 0 being the absolute tolerance error
  984.      *                       and row 1 being the relative tolerance error
  985.      * @since 10.3
  986.      */
  987.     public static <T extends CalculusFieldElement<T>> double[][] tolerances(final T dP, final T dV,
  988.                                                                         final FieldOrbit<T> orbit) {
  989.         return FieldNumericalPropagator.tolerances(dP, dV, orbit, OrbitType.EQUINOCTIAL);
  990.     }

  991.     /** Step handler used to compute the parameters for the short periodic contributions.
  992.      * @author Lucian Barbulescu
  993.      */
  994.     private class FieldShortPeriodicsHandler implements FieldODEStepHandler<T> {

  995.         /** Force models used to compute short periodic terms. */
  996.         private final List<DSSTForceModel> forceModels;

  997.         /** Constructor.
  998.          * @param forceModels force models
  999.          */
  1000.         FieldShortPeriodicsHandler(final List<DSSTForceModel> forceModels) {
  1001.             this.forceModels = forceModels;
  1002.         }

  1003.         /** {@inheritDoc} */
  1004.         @SuppressWarnings("unchecked")
  1005.         @Override
  1006.         public void handleStep(final FieldODEStateInterpolator<T> interpolator) {

  1007.             // Get the grid points to compute
  1008.             final T[] interpolationPoints =
  1009.                             interpolationgrid.getGridPoints(interpolator.getPreviousState().getTime(),
  1010.                                                             interpolator.getCurrentState().getTime());

  1011.             final FieldSpacecraftState<T>[] meanStates = new FieldSpacecraftState[interpolationPoints.length];
  1012.             for (int i = 0; i < interpolationPoints.length; ++i) {

  1013.                 // Build the mean state interpolated at grid point
  1014.                 final T time = interpolationPoints[i];
  1015.                 final FieldODEStateAndDerivative<T> sd = interpolator.getInterpolatedState(time);
  1016.                 meanStates[i] = mapper.mapArrayToState(time,
  1017.                                                        sd.getPrimaryState(),
  1018.                                                        sd.getPrimaryDerivative(),
  1019.                                                        PropagationType.MEAN);

  1020.             }

  1021.             // Compute short periodic coefficients for this step
  1022.             for (DSSTForceModel forceModel : forceModels) {
  1023.                 forceModel.updateShortPeriodTerms(forceModel.getParameters(field), meanStates);
  1024.             }

  1025.         }
  1026.     }

  1027. }