NumericalPropagator.java

  1. /* Copyright 2002-2024 CS GROUP
  2.  * Licensed to CS GROUP (CS) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * CS licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *   http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.orekit.propagation.numerical;

  18. import java.util.ArrayList;
  19. import java.util.Arrays;
  20. import java.util.Collections;
  21. import java.util.List;

  22. import org.hipparchus.exception.LocalizedCoreFormats;
  23. import org.hipparchus.geometry.euclidean.threed.Vector3D;
  24. import org.hipparchus.linear.MatrixUtils;
  25. import org.hipparchus.linear.QRDecomposition;
  26. import org.hipparchus.linear.RealMatrix;
  27. import org.hipparchus.ode.ODEIntegrator;
  28. import org.hipparchus.util.FastMath;
  29. import org.hipparchus.util.Precision;
  30. import org.orekit.annotation.DefaultDataContext;
  31. import org.orekit.attitudes.Attitude;
  32. import org.orekit.attitudes.AttitudeProvider;
  33. import org.orekit.data.DataContext;
  34. import org.orekit.errors.OrekitException;
  35. import org.orekit.errors.OrekitIllegalArgumentException;
  36. import org.orekit.errors.OrekitInternalError;
  37. import org.orekit.errors.OrekitMessages;
  38. import org.orekit.forces.ForceModel;
  39. import org.orekit.forces.gravity.NewtonianAttraction;
  40. import org.orekit.forces.inertia.InertialForces;
  41. import org.orekit.forces.maneuvers.Maneuver;
  42. import org.orekit.forces.maneuvers.jacobians.Duration;
  43. import org.orekit.forces.maneuvers.jacobians.MedianDate;
  44. import org.orekit.forces.maneuvers.jacobians.TriggerDate;
  45. import org.orekit.forces.maneuvers.trigger.ManeuverTriggers;
  46. import org.orekit.frames.Frame;
  47. import org.orekit.orbits.Orbit;
  48. import org.orekit.orbits.OrbitType;
  49. import org.orekit.orbits.PositionAngleType;
  50. import org.orekit.propagation.AbstractMatricesHarvester;
  51. import org.orekit.propagation.AdditionalStateProvider;
  52. import org.orekit.propagation.MatricesHarvester;
  53. import org.orekit.propagation.PropagationType;
  54. import org.orekit.propagation.Propagator;
  55. import org.orekit.propagation.SpacecraftState;
  56. import org.orekit.propagation.events.EventDetector;
  57. import org.orekit.propagation.events.ParameterDrivenDateIntervalDetector;
  58. import org.orekit.propagation.integration.AbstractIntegratedPropagator;
  59. import org.orekit.propagation.integration.AdditionalDerivativesProvider;
  60. import org.orekit.propagation.integration.StateMapper;
  61. import org.orekit.time.AbsoluteDate;
  62. import org.orekit.utils.AbsolutePVCoordinates;
  63. import org.orekit.utils.DoubleArrayDictionary;
  64. import org.orekit.utils.PVCoordinates;
  65. import org.orekit.utils.ParameterDriver;
  66. import org.orekit.utils.ParameterDriversList;
  67. import org.orekit.utils.ParameterDriversList.DelegatingDriver;
  68. import org.orekit.utils.TimeSpanMap.Span;
  69. import org.orekit.utils.ParameterObserver;
  70. import org.orekit.utils.TimeSpanMap;
  71. import org.orekit.utils.TimeStampedPVCoordinates;

  72. /** This class propagates {@link org.orekit.orbits.Orbit orbits} using
  73.  * numerical integration.
  74.  * <p>Numerical propagation is much more accurate than analytical propagation
  75.  * like for example {@link org.orekit.propagation.analytical.KeplerianPropagator
  76.  * Keplerian} or {@link org.orekit.propagation.analytical.EcksteinHechlerPropagator
  77.  * Eckstein-Hechler}, but requires a few more steps to set up to be used properly.
  78.  * Whereas analytical propagators are configured only thanks to their various
  79.  * constructors and can be used immediately after construction, numerical propagators
  80.  * configuration involve setting several parameters between construction time
  81.  * and propagation time.</p>
  82.  * <p>The configuration parameters that can be set are:</p>
  83.  * <ul>
  84.  *   <li>the initial spacecraft state ({@link #setInitialState(SpacecraftState)})</li>
  85.  *   <li>the central attraction coefficient ({@link #setMu(double)})</li>
  86.  *   <li>the various force models ({@link #addForceModel(ForceModel)},
  87.  *   {@link #removeForceModels()})</li>
  88.  *   <li>the {@link OrbitType type} of orbital parameters to be used for propagation
  89.  *   ({@link #setOrbitType(OrbitType)}),</li>
  90.  *   <li>the {@link PositionAngleType type} of position angle to be used in orbital parameters
  91.  *   to be used for propagation where it is relevant ({@link
  92.  *   #setPositionAngleType(PositionAngleType)}),</li>
  93.  *   <li>whether {@link MatricesHarvester state transition matrices and Jacobians matrices}
  94.  *   should be propagated along with orbital state ({@link
  95.  *   #setupMatricesComputation(String, RealMatrix, DoubleArrayDictionary)}),</li>
  96.  *   <li>whether {@link org.orekit.propagation.integration.AdditionalDerivativesProvider additional derivatives}
  97.  *   should be propagated along with orbital state ({@link
  98.  *   #addAdditionalDerivativesProvider(AdditionalDerivativesProvider)}),</li>
  99.  *   <li>the discrete events that should be triggered during propagation
  100.  *   ({@link #addEventDetector(EventDetector)},
  101.  *   {@link #clearEventsDetectors()})</li>
  102.  *   <li>the binding logic with the rest of the application ({@link #getMultiplexer()})</li>
  103.  * </ul>
  104.  * <p>From these configuration parameters, only the initial state is mandatory. The default
  105.  * propagation settings are in {@link OrbitType#EQUINOCTIAL equinoctial} parameters with
  106.  * {@link PositionAngleType#TRUE true} longitude argument. If the central attraction coefficient
  107.  * is not explicitly specified, the one used to define the initial orbit will be used.
  108.  * However, specifying only the initial state and perhaps the central attraction coefficient
  109.  * would mean the propagator would use only Keplerian forces. In this case, the simpler {@link
  110.  * org.orekit.propagation.analytical.KeplerianPropagator KeplerianPropagator} class would
  111.  * perhaps be more effective.</p>
  112.  * <p>The underlying numerical integrator set up in the constructor may also have its own
  113.  * configuration parameters. Typical configuration parameters for adaptive stepsize integrators
  114.  * are the min, max and perhaps start step size as well as the absolute and/or relative errors
  115.  * thresholds.</p>
  116.  * <p>The state that is seen by the integrator is a simple seven elements double array.
  117.  * The six first elements are either:
  118.  * <ul>
  119.  *   <li>the {@link org.orekit.orbits.EquinoctialOrbit equinoctial orbit parameters} (a, e<sub>x</sub>,
  120.  *   e<sub>y</sub>, h<sub>x</sub>, h<sub>y</sub>, λ<sub>M</sub> or λ<sub>E</sub>
  121.  *   or λ<sub>v</sub>) in meters and radians,</li>
  122.  *   <li>the {@link org.orekit.orbits.KeplerianOrbit Keplerian orbit parameters} (a, e, i, ω, Ω,
  123.  *   M or E or v) in meters and radians,</li>
  124.  *   <li>the {@link org.orekit.orbits.CircularOrbit circular orbit parameters} (a, e<sub>x</sub>, e<sub>y</sub>, i,
  125.  *   Ω, α<sub>M</sub> or α<sub>E</sub> or α<sub>v</sub>) in meters
  126.  *   and radians,</li>
  127.  *   <li>the {@link org.orekit.orbits.CartesianOrbit Cartesian orbit parameters} (x, y, z, v<sub>x</sub>,
  128.  *   v<sub>y</sub>, v<sub>z</sub>) in meters and meters per seconds.
  129.  * </ul>
  130.  * <p> The last element is the mass in kilograms and changes only during thrusters firings
  131.  *
  132.  * <p>The following code snippet shows a typical setting for Low Earth Orbit propagation in
  133.  * equinoctial parameters and true longitude argument:</p>
  134.  * <pre>
  135.  * final double dP       = 0.001;
  136.  * final double minStep  = 0.001;
  137.  * final double maxStep  = 500;
  138.  * final double initStep = 60;
  139.  * final double[][] tolerance = NumericalPropagator.tolerances(dP, orbit, OrbitType.EQUINOCTIAL);
  140.  * AdaptiveStepsizeIntegrator integrator = new DormandPrince853Integrator(minStep, maxStep, tolerance[0], tolerance[1]);
  141.  * integrator.setInitialStepSize(initStep);
  142.  * propagator = new NumericalPropagator(integrator);
  143.  * </pre>
  144.  * <p>By default, at the end of the propagation, the propagator resets the initial state to the final state,
  145.  * thus allowing a new propagation to be started from there without recomputing the part already performed.
  146.  * This behaviour can be chenged by calling {@link #setResetAtEnd(boolean)}.
  147.  * </p>
  148.  * <p>Beware the same instance cannot be used simultaneously by different threads, the class is <em>not</em>
  149.  * thread-safe.</p>
  150.  *
  151.  * @see SpacecraftState
  152.  * @see ForceModel
  153.  * @see org.orekit.propagation.sampling.OrekitStepHandler
  154.  * @see org.orekit.propagation.sampling.OrekitFixedStepHandler
  155.  * @see org.orekit.propagation.integration.IntegratedEphemeris
  156.  * @see TimeDerivativesEquations
  157.  *
  158.  * @author Mathieu Rom&eacute;ro
  159.  * @author Luc Maisonobe
  160.  * @author Guylaine Prat
  161.  * @author Fabien Maussion
  162.  * @author V&eacute;ronique Pommier-Maurussane
  163.  */
  164. public class NumericalPropagator extends AbstractIntegratedPropagator {

  165.     /** Space dimension. */
  166.     private static final int SPACE_DIMENSION = 3;

  167.     /** State dimension. */
  168.     private static final int STATE_DIMENSION = 2 * SPACE_DIMENSION;

  169.     /** Threshold for matrix solving. */
  170.     private static final double THRESHOLD = Precision.SAFE_MIN;

  171.     /** Force models used during the extrapolation of the orbit. */
  172.     private final List<ForceModel> forceModels;

  173.     /** boolean to ignore or not the creation of a NewtonianAttraction. */
  174.     private boolean ignoreCentralAttraction;

  175.     /** Create a new instance of NumericalPropagator, based on orbit definition mu.
  176.      * After creation, the instance is empty, i.e. the attitude provider is set to an
  177.      * unspecified default law and there are no perturbing forces at all.
  178.      * This means that if {@link #addForceModel addForceModel} is not
  179.      * called after creation, the integrated orbit will follow a Keplerian
  180.      * evolution only. The defaults are {@link OrbitType#EQUINOCTIAL}
  181.      * for {@link #setOrbitType(OrbitType) propagation
  182.      * orbit type} and {@link PositionAngleType#TRUE} for {@link
  183.      * #setPositionAngleType(PositionAngleType) position angle type}.
  184.      *
  185.      * <p>This constructor uses the {@link DataContext#getDefault() default data context}.
  186.      *
  187.      * @param integrator numerical integrator to use for propagation.
  188.      * @see #NumericalPropagator(ODEIntegrator, AttitudeProvider)
  189.      */
  190.     @DefaultDataContext
  191.     public NumericalPropagator(final ODEIntegrator integrator) {
  192.         this(integrator,
  193.                 Propagator.getDefaultLaw(DataContext.getDefault().getFrames()));
  194.     }

  195.     /** Create a new instance of NumericalPropagator, based on orbit definition mu.
  196.      * After creation, the instance is empty, i.e. the attitude provider is set to an
  197.      * unspecified default law and there are no perturbing forces at all.
  198.      * This means that if {@link #addForceModel addForceModel} is not
  199.      * called after creation, the integrated orbit will follow a Keplerian
  200.      * evolution only. The defaults are {@link OrbitType#EQUINOCTIAL}
  201.      * for {@link #setOrbitType(OrbitType) propagation
  202.      * orbit type} and {@link PositionAngleType#TRUE} for {@link
  203.      * #setPositionAngleType(PositionAngleType) position angle type}.
  204.      * @param integrator numerical integrator to use for propagation.
  205.      * @param attitudeProvider the attitude law.
  206.      * @since 10.1
  207.      */
  208.     public NumericalPropagator(final ODEIntegrator integrator,
  209.                                final AttitudeProvider attitudeProvider) {
  210.         super(integrator, PropagationType.OSCULATING);
  211.         forceModels             = new ArrayList<ForceModel>();
  212.         ignoreCentralAttraction = false;
  213.         initMapper();
  214.         setAttitudeProvider(attitudeProvider);
  215.         clearStepHandlers();
  216.         setOrbitType(OrbitType.EQUINOCTIAL);
  217.         setPositionAngleType(PositionAngleType.TRUE);
  218.     }

  219.     /** Set the flag to ignore or not the creation of a {@link NewtonianAttraction}.
  220.      * @param ignoreCentralAttraction if true, {@link NewtonianAttraction} is <em>not</em>
  221.      * added automatically if missing
  222.      */
  223.     public void setIgnoreCentralAttraction(final boolean ignoreCentralAttraction) {
  224.         this.ignoreCentralAttraction = ignoreCentralAttraction;
  225.     }

  226.      /** Set the central attraction coefficient μ.
  227.       * <p>
  228.       * Setting the central attraction coefficient is
  229.       * equivalent to {@link #addForceModel(ForceModel) add}
  230.       * a {@link NewtonianAttraction} force model.
  231.       * </p>
  232.      * @param mu central attraction coefficient (m³/s²)
  233.      * @see #addForceModel(ForceModel)
  234.      * @see #getAllForceModels()
  235.      */
  236.     public void setMu(final double mu) {
  237.         if (ignoreCentralAttraction) {
  238.             superSetMu(mu);
  239.         } else {
  240.             addForceModel(new NewtonianAttraction(mu));
  241.             superSetMu(mu);
  242.         }
  243.     }

  244.     /** Set the central attraction coefficient μ only in upper class.
  245.      * @param mu central attraction coefficient (m³/s²)
  246.      */
  247.     private void superSetMu(final double mu) {
  248.         super.setMu(mu);
  249.     }

  250.     /** Check if Newtonian attraction force model is available.
  251.      * <p>
  252.      * Newtonian attraction is always the last force model in the list.
  253.      * </p>
  254.      * @return true if Newtonian attraction force model is available
  255.      */
  256.     private boolean hasNewtonianAttraction() {
  257.         final int last = forceModels.size() - 1;
  258.         return last >= 0 && forceModels.get(last) instanceof NewtonianAttraction;
  259.     }

  260.     /** Add a force model.
  261.      * <p>If this method is not called at all, the integrated orbit will follow
  262.      * a Keplerian evolution only.</p>
  263.      * @param model {@link ForceModel} to add (it can be either a perturbing force
  264.      * model or an instance of {@link NewtonianAttraction})
  265.      * @see #removeForceModels()
  266.      * @see #setMu(double)
  267.      */
  268.     public void addForceModel(final ForceModel model) {

  269.         if (model instanceof NewtonianAttraction) {
  270.             // we want to add the central attraction force model

  271.             try {
  272.                 // ensure we are notified of any mu change
  273.                 model.getParametersDrivers().get(0).addObserver(new ParameterObserver() {
  274.                     /** {@inheritDoc} */
  275.                     @Override
  276.                     public void valueSpanMapChanged(final TimeSpanMap<Double> previousValue, final ParameterDriver driver) {
  277.                         superSetMu(driver.getValue());
  278.                     }
  279.                     /** {@inheritDoc} */
  280.                     @Override
  281.                     public void valueChanged(final double previousValue, final ParameterDriver driver, final AbsoluteDate date) {
  282.                         superSetMu(driver.getValue());
  283.                     }
  284.                 });
  285.             } catch (OrekitException oe) {
  286.                 // this should never happen
  287.                 throw new OrekitInternalError(oe);
  288.             }

  289.             if (hasNewtonianAttraction()) {
  290.                 // there is already a central attraction model, replace it
  291.                 forceModels.set(forceModels.size() - 1, model);
  292.             } else {
  293.                 // there are no central attraction model yet, add it at the end of the list
  294.                 forceModels.add(model);
  295.             }
  296.         } else {
  297.             // we want to add a perturbing force model
  298.             if (hasNewtonianAttraction()) {
  299.                 // insert the new force model before Newtonian attraction,
  300.                 // which should always be the last one in the list
  301.                 forceModels.add(forceModels.size() - 1, model);
  302.             } else {
  303.                 // we only have perturbing force models up to now, just append at the end of the list
  304.                 forceModels.add(model);
  305.             }
  306.         }

  307.     }

  308.     /** Remove all force models (except central attraction).
  309.      * <p>Once all perturbing forces have been removed (and as long as no new force
  310.      * model is added), the integrated orbit will follow a Keplerian evolution
  311.      * only.</p>
  312.      * @see #addForceModel(ForceModel)
  313.      */
  314.     public void removeForceModels() {
  315.         final int last = forceModels.size() - 1;
  316.         if (hasNewtonianAttraction()) {
  317.             // preserve the Newtonian attraction model at the end
  318.             final ForceModel newton = forceModels.get(last);
  319.             forceModels.clear();
  320.             forceModels.add(newton);
  321.         } else {
  322.             forceModels.clear();
  323.         }
  324.     }

  325.     /** Get all the force models, perturbing forces and Newtonian attraction included.
  326.      * @return list of perturbing force models, with Newtonian attraction being the
  327.      * last one
  328.      * @see #addForceModel(ForceModel)
  329.      * @see #setMu(double)
  330.      */
  331.     public List<ForceModel> getAllForceModels() {
  332.         return Collections.unmodifiableList(forceModels);
  333.     }

  334.     /** Set propagation orbit type.
  335.      * @param orbitType orbit type to use for propagation, null for
  336.      * propagating using {@link org.orekit.utils.AbsolutePVCoordinates} rather than {@link Orbit}
  337.      */
  338.     public void setOrbitType(final OrbitType orbitType) {
  339.         super.setOrbitType(orbitType);
  340.     }

  341.     /** Get propagation parameter type.
  342.      * @return orbit type used for propagation, null for
  343.      * propagating using {@link org.orekit.utils.AbsolutePVCoordinates} rather than {@link Orbit}
  344.      */
  345.     public OrbitType getOrbitType() {
  346.         return super.getOrbitType();
  347.     }

  348.     /** Set position angle type.
  349.      * <p>
  350.      * The position parameter type is meaningful only if {@link
  351.      * #getOrbitType() propagation orbit type}
  352.      * support it. As an example, it is not meaningful for propagation
  353.      * in {@link OrbitType#CARTESIAN Cartesian} parameters.
  354.      * </p>
  355.      * @param positionAngleType angle type to use for propagation
  356.      */
  357.     public void setPositionAngleType(final PositionAngleType positionAngleType) {
  358.         super.setPositionAngleType(positionAngleType);
  359.     }

  360.     /** Get propagation parameter type.
  361.      * @return angle type to use for propagation
  362.      */
  363.     public PositionAngleType getPositionAngleType() {
  364.         return super.getPositionAngleType();
  365.     }

  366.     /** Set the initial state.
  367.      * @param initialState initial state
  368.      */
  369.     public void setInitialState(final SpacecraftState initialState) {
  370.         resetInitialState(initialState);
  371.     }

  372.     /** {@inheritDoc} */
  373.     public void resetInitialState(final SpacecraftState state) {
  374.         super.resetInitialState(state);
  375.         if (!hasNewtonianAttraction()) {
  376.             // use the state to define central attraction
  377.             setMu(state.getMu());
  378.         }
  379.         setStartDate(state.getDate());
  380.     }

  381.     /** Get the names of the parameters in the matrix returned by {@link MatricesHarvester#getParametersJacobian}.
  382.      * @return names of the parameters (i.e. columns) of the Jacobian matrix
  383.      */
  384.     List<String> getJacobiansColumnsNames() {
  385.         final List<String> columnsNames = new ArrayList<>();
  386.         for (final ForceModel forceModel : getAllForceModels()) {
  387.             for (final ParameterDriver driver : forceModel.getParametersDrivers()) {
  388.                 if (driver.isSelected() && !columnsNames.contains(driver.getNamesSpanMap().getFirstSpan().getData())) {
  389.                     // As driver with same name should have same NamesSpanMap we only check if the first span is present,
  390.                     // if not we add all span names to columnsNames
  391.                     for (Span<String> span = driver.getNamesSpanMap().getFirstSpan(); span != null; span = span.next()) {
  392.                         columnsNames.add(span.getData());
  393.                     }
  394.                 }
  395.             }
  396.         }
  397.         Collections.sort(columnsNames);
  398.         return columnsNames;
  399.     }

  400.     /** {@inheritDoc} */
  401.     @Override
  402.     protected AbstractMatricesHarvester createHarvester(final String stmName, final RealMatrix initialStm,
  403.                                                         final DoubleArrayDictionary initialJacobianColumns) {
  404.         return new NumericalPropagationHarvester(this, stmName, initialStm, initialJacobianColumns);
  405.     }

  406.     /** {@inheritDoc} */
  407.     @Override
  408.     protected void setUpStmAndJacobianGenerators() {

  409.         final AbstractMatricesHarvester harvester = getHarvester();
  410.         if (harvester != null) {

  411.             // set up the additional equations and additional state providers
  412.             final StateTransitionMatrixGenerator stmGenerator = setUpStmGenerator();
  413.             final List<String> triggersDates = setUpTriggerDatesJacobiansColumns(stmGenerator.getName());
  414.             setUpRegularParametersJacobiansColumns(stmGenerator, triggersDates);

  415.             // as we are now starting the propagation, everything is configured
  416.             // we can freeze the names in the harvester
  417.             harvester.freezeColumnsNames();

  418.         }

  419.     }

  420.     /** Set up the State Transition Matrix Generator.
  421.      * @return State Transition Matrix Generator
  422.      * @since 11.1
  423.      */
  424.     private StateTransitionMatrixGenerator setUpStmGenerator() {

  425.         final AbstractMatricesHarvester harvester = getHarvester();

  426.         // add the STM generator corresponding to the current settings, and setup state accordingly
  427.         StateTransitionMatrixGenerator stmGenerator = null;
  428.         for (final AdditionalDerivativesProvider equations : getAdditionalDerivativesProviders()) {
  429.             if (equations instanceof StateTransitionMatrixGenerator &&
  430.                 equations.getName().equals(harvester.getStmName())) {
  431.                 // the STM generator has already been set up in a previous propagation
  432.                 stmGenerator = (StateTransitionMatrixGenerator) equations;
  433.                 break;
  434.             }
  435.         }
  436.         if (stmGenerator == null) {
  437.             // this is the first time we need the STM generate, create it
  438.             stmGenerator = new StateTransitionMatrixGenerator(harvester.getStmName(), getAllForceModels(), getAttitudeProvider());
  439.             addAdditionalDerivativesProvider(stmGenerator);
  440.         }

  441.         if (!getInitialIntegrationState().hasAdditionalState(harvester.getStmName())) {
  442.             // add the initial State Transition Matrix if it is not already there
  443.             // (perhaps due to a previous propagation)
  444.             setInitialState(stmGenerator.setInitialStateTransitionMatrix(getInitialState(),
  445.                                                                          harvester.getInitialStateTransitionMatrix(),
  446.                                                                          getOrbitType(),
  447.                                                                          getPositionAngleType()));
  448.         }

  449.         return stmGenerator;

  450.     }

  451.     /** Set up the Jacobians columns generator dedicated to trigger dates.
  452.      * @param stmName name of the State Transition Matrix state
  453.      * @return names of the columns corresponding to trigger dates
  454.      * @since 11.1
  455.      */
  456.     private List<String> setUpTriggerDatesJacobiansColumns(final String stmName) {

  457.         final List<String> names = new ArrayList<>();
  458.         for (final ForceModel forceModel : getAllForceModels()) {
  459.             if (forceModel instanceof Maneuver) {
  460.                 final Maneuver maneuver = (Maneuver) forceModel;
  461.                 final ManeuverTriggers maneuverTriggers = maneuver.getManeuverTriggers();

  462.                 maneuverTriggers.getEventDetectors().
  463.                         filter(d -> d instanceof ParameterDrivenDateIntervalDetector).
  464.                         map(d -> (ParameterDrivenDateIntervalDetector) d).
  465.                         forEach(d -> {
  466.                             TriggerDate start;
  467.                             TriggerDate stop;

  468.                             if (d.getStartDriver().isSelected() || d.getMedianDriver().isSelected() || d.getDurationDriver().isSelected()) {
  469.                                 // normally datedriver should have only 1 span but just in case the user defines several span, there will
  470.                                 // be no problem here
  471.                                 for (Span<String> span = d.getStartDriver().getNamesSpanMap().getFirstSpan(); span != null; span = span.next()) {
  472.                                     start = manageTriggerDate(stmName, maneuver, maneuverTriggers, span.getData(), true, d.getThreshold());
  473.                                     names.add(start.getName());
  474.                                     start = null;
  475.                                 }
  476.                             }
  477.                             if (d.getStopDriver().isSelected() || d.getMedianDriver().isSelected() || d.getDurationDriver().isSelected()) {
  478.                                 // normally datedriver should have only 1 span but just in case the user defines several span, there will
  479.                                 // be no problem here
  480.                                 for (Span<String> span = d.getStopDriver().getNamesSpanMap().getFirstSpan(); span != null; span = span.next()) {
  481.                                     stop = manageTriggerDate(stmName, maneuver, maneuverTriggers, span.getData(), false, d.getThreshold());
  482.                                     names.add(stop.getName());
  483.                                     stop = null;
  484.                                 }
  485.                             }
  486.                             if (d.getMedianDriver().isSelected()) {
  487.                                 // for first span
  488.                                 Span<String> currentMedianNameSpan = d.getMedianDriver().getNamesSpanMap().getFirstSpan();
  489.                                 MedianDate median =
  490.                                         manageMedianDate(d.getStartDriver().getNamesSpanMap().getFirstSpan().getData(),
  491.                                                 d.getStopDriver().getNamesSpanMap().getFirstSpan().getData(), currentMedianNameSpan.getData());
  492.                                 names.add(median.getName());
  493.                                 // for all span
  494.                                 // normally datedriver should have only 1 span but just in case the user defines several span, there will
  495.                                 // be no problem here. /!\ medianDate driver, startDate driver and stopDate driver must have same span number
  496.                                 for (int spanNumber = 1; spanNumber < d.getMedianDriver().getNamesSpanMap().getSpansNumber(); ++spanNumber) {
  497.                                     currentMedianNameSpan = d.getMedianDriver().getNamesSpanMap().getSpan(currentMedianNameSpan.getEnd());
  498.                                     median =
  499.                                             manageMedianDate(d.getStartDriver().getNamesSpanMap().getSpan(currentMedianNameSpan.getStart()).getData(),
  500.                                                     d.getStopDriver().getNamesSpanMap().getSpan(currentMedianNameSpan.getStart()).getData(),
  501.                                                     currentMedianNameSpan.getData());
  502.                                     names.add(median.getName());

  503.                                 }

  504.                             }
  505.                             if (d.getDurationDriver().isSelected()) {
  506.                                 // for first span
  507.                                 Span<String> currentDurationNameSpan = d.getDurationDriver().getNamesSpanMap().getFirstSpan();
  508.                                 Duration duration =
  509.                                         manageManeuverDuration(d.getStartDriver().getNamesSpanMap().getFirstSpan().getData(),
  510.                                                 d.getStopDriver().getNamesSpanMap().getFirstSpan().getData(), currentDurationNameSpan.getData());
  511.                                 names.add(duration.getName());
  512.                                 // for all span
  513.                                 for (int spanNumber = 1; spanNumber < d.getDurationDriver().getNamesSpanMap().getSpansNumber(); ++spanNumber) {
  514.                                     currentDurationNameSpan = d.getDurationDriver().getNamesSpanMap().getSpan(currentDurationNameSpan.getEnd());
  515.                                     duration =
  516.                                             manageManeuverDuration(d.getStartDriver().getNamesSpanMap().getSpan(currentDurationNameSpan.getStart()).getData(),
  517.                                                     d.getStopDriver().getNamesSpanMap().getSpan(currentDurationNameSpan.getStart()).getData(),
  518.                                                     currentDurationNameSpan.getData());
  519.                                     names.add(duration.getName());

  520.                                 }
  521.                             }
  522.                         });
  523.             }
  524.         }

  525.         return names;

  526.     }

  527.     /** Manage a maneuver trigger date.
  528.      * @param stmName name of the State Transition Matrix state
  529.      * @param maneuver maneuver force model
  530.      * @param mt trigger to which the driver is bound
  531.      * @param driverName name of the date driver
  532.      * @param start if true, the driver is a maneuver start
  533.      * @param threshold event detector threshold
  534.      * @return generator for the date driver
  535.      * @since 11.1
  536.      */
  537.     private TriggerDate manageTriggerDate(final String stmName,
  538.                                           final Maneuver maneuver,
  539.                                           final ManeuverTriggers mt,
  540.                                           final String driverName,
  541.                                           final boolean start,
  542.                                           final double threshold) {

  543.         TriggerDate triggerGenerator = null;

  544.         // check if we already have set up the provider
  545.         for (final AdditionalStateProvider provider : getAdditionalStateProviders()) {
  546.             if (provider instanceof TriggerDate &&
  547.                 provider.getName().equals(driverName)) {
  548.                 // the Jacobian column generator has already been set up in a previous propagation
  549.                 triggerGenerator = (TriggerDate) provider;
  550.                 break;
  551.             }
  552.         }

  553.         if (triggerGenerator == null) {
  554.             // this is the first time we need the Jacobian column generator, create it
  555.             triggerGenerator = new TriggerDate(stmName, driverName, start, maneuver, threshold);
  556.             mt.addResetter(triggerGenerator);
  557.             addAdditionalDerivativesProvider(triggerGenerator.getMassDepletionDelay());
  558.             addAdditionalStateProvider(triggerGenerator);
  559.         }

  560.         if (!getInitialIntegrationState().hasAdditionalState(driverName)) {
  561.             // add the initial Jacobian column if it is not already there
  562.             // (perhaps due to a previous propagation)
  563.             setInitialColumn(triggerGenerator.getMassDepletionDelay().getName(), new double[6]);
  564.             setInitialColumn(driverName, getHarvester().getInitialJacobianColumn(driverName));
  565.         }

  566.         return triggerGenerator;

  567.     }

  568.     /** Manage a maneuver median date.
  569.      * @param startName name of the start driver
  570.      * @param stopName name of the stop driver
  571.      * @param medianName name of the median driver
  572.      * @return generator for the median driver
  573.      * @since 11.1
  574.      */
  575.     private MedianDate manageMedianDate(final String startName, final String stopName, final String medianName) {

  576.         MedianDate medianGenerator = null;

  577.         // check if we already have set up the provider
  578.         for (final AdditionalStateProvider provider : getAdditionalStateProviders()) {
  579.             if (provider instanceof MedianDate &&
  580.                 provider.getName().equals(medianName)) {
  581.                 // the Jacobian column generator has already been set up in a previous propagation
  582.                 medianGenerator = (MedianDate) provider;
  583.                 break;
  584.             }
  585.         }

  586.         if (medianGenerator == null) {
  587.             // this is the first time we need the Jacobian column generator, create it
  588.             medianGenerator = new MedianDate(startName, stopName, medianName);
  589.             addAdditionalStateProvider(medianGenerator);
  590.         }

  591.         if (!getInitialIntegrationState().hasAdditionalState(medianName)) {
  592.             // add the initial Jacobian column if it is not already there
  593.             // (perhaps due to a previous propagation)
  594.             setInitialColumn(medianName, getHarvester().getInitialJacobianColumn(medianName));
  595.         }

  596.         return medianGenerator;

  597.     }

  598.     /** Manage a maneuver duration.
  599.      * @param startName name of the start driver
  600.      * @param stopName name of the stop driver
  601.      * @param durationName name of the duration driver
  602.      * @return generator for the median driver
  603.      * @since 11.1
  604.      */
  605.     private Duration manageManeuverDuration(final String startName, final String stopName, final String durationName) {

  606.         Duration durationGenerator = null;

  607.         // check if we already have set up the provider
  608.         for (final AdditionalStateProvider provider : getAdditionalStateProviders()) {
  609.             if (provider instanceof Duration &&
  610.                 provider.getName().equals(durationName)) {
  611.                 // the Jacobian column generator has already been set up in a previous propagation
  612.                 durationGenerator = (Duration) provider;
  613.                 break;
  614.             }
  615.         }

  616.         if (durationGenerator == null) {
  617.             // this is the first time we need the Jacobian column generator, create it
  618.             durationGenerator = new Duration(startName, stopName, durationName);
  619.             addAdditionalStateProvider(durationGenerator);
  620.         }

  621.         if (!getInitialIntegrationState().hasAdditionalState(durationName)) {
  622.             // add the initial Jacobian column if it is not already there
  623.             // (perhaps due to a previous propagation)
  624.             setInitialColumn(durationName, getHarvester().getInitialJacobianColumn(durationName));
  625.         }

  626.         return durationGenerator;

  627.     }

  628.     /** Set up the Jacobians columns generator for regular parameters.
  629.      * @param stmGenerator generator for the State Transition Matrix
  630.      * @param triggerDates names of the columns already managed as trigger dates
  631.      * @since 11.1
  632.      */
  633.     private void setUpRegularParametersJacobiansColumns(final StateTransitionMatrixGenerator stmGenerator,
  634.                                                         final List<String> triggerDates) {

  635.         // first pass: gather all parameters (excluding trigger dates), binding similar names together
  636.         final ParameterDriversList selected = new ParameterDriversList();
  637.         for (final ForceModel forceModel : getAllForceModels()) {
  638.             for (final ParameterDriver driver : forceModel.getParametersDrivers()) {
  639.                 if (!triggerDates.contains(driver.getNamesSpanMap().getFirstSpan().getData())) {
  640.                     // if the first span is not in triggerdate means that the driver is not a trigger
  641.                     // date and can be selected here
  642.                     selected.add(driver);
  643.                 }
  644.             }
  645.         }

  646.         // second pass: now that shared parameter names are bound together,
  647.         // their selections status have been synchronized, we can filter them
  648.         selected.filter(true);

  649.         // third pass: sort parameters lexicographically
  650.         selected.sort();

  651.         // add the Jacobians column generators corresponding to parameters, and setup state accordingly
  652.         // a new column is needed for each value estimated so for each span of the parameterDriver
  653.         for (final DelegatingDriver driver : selected.getDrivers()) {

  654.             for (Span<String> currentNameSpan = driver.getNamesSpanMap().getFirstSpan(); currentNameSpan != null; currentNameSpan = currentNameSpan.next()) {

  655.                 IntegrableJacobianColumnGenerator generator = null;
  656.                 // check if we already have set up the providers
  657.                 for (final AdditionalDerivativesProvider provider : getAdditionalDerivativesProviders()) {
  658.                     if (provider instanceof IntegrableJacobianColumnGenerator &&
  659.                         provider.getName().equals(currentNameSpan.getData())) {
  660.                         // the Jacobian column generator has already been set up in a previous propagation
  661.                         generator = (IntegrableJacobianColumnGenerator) provider;
  662.                         break;
  663.                     }

  664.                 }

  665.                 if (generator == null) {
  666.                     // this is the first time we need the Jacobian column generator, create it
  667.                     generator = new IntegrableJacobianColumnGenerator(stmGenerator, currentNameSpan.getData());
  668.                     addAdditionalDerivativesProvider(generator);
  669.                 }

  670.                 if (!getInitialIntegrationState().hasAdditionalState(currentNameSpan.getData())) {
  671.                     // add the initial Jacobian column if it is not already there
  672.                     // (perhaps due to a previous propagation)
  673.                     setInitialColumn(currentNameSpan.getData(), getHarvester().getInitialJacobianColumn(currentNameSpan.getData()));
  674.                 }

  675.             }

  676.         }

  677.     }

  678.     /** Add the initial value of the column to the initial state.
  679.      * <p>
  680.      * The initial state must already contain the Cartesian State Transition Matrix.
  681.      * </p>
  682.      * @param columnName name of the column
  683.      * @param dYdQ column of the Jacobian ∂Y/∂qₘ with respect to propagation type,
  684.      * if null (which is the most frequent case), assumed to be 0
  685.      * @since 11.1
  686.      */
  687.     private void setInitialColumn(final String columnName, final double[] dYdQ) {

  688.         final SpacecraftState state = getInitialState();

  689.         if (dYdQ.length != STATE_DIMENSION) {
  690.             throw new OrekitException(LocalizedCoreFormats.DIMENSIONS_MISMATCH,
  691.                                       dYdQ.length, STATE_DIMENSION);
  692.         }

  693.         // convert to Cartesian Jacobian
  694.         final double[][] dYdC = new double[STATE_DIMENSION][STATE_DIMENSION];
  695.         getOrbitType().convertType(state.getOrbit()).getJacobianWrtCartesian(getPositionAngleType(), dYdC);
  696.         final double[] column = new QRDecomposition(MatrixUtils.createRealMatrix(dYdC), THRESHOLD).
  697.                         getSolver().
  698.                         solve(MatrixUtils.createRealVector(dYdQ)).
  699.                         toArray();

  700.         // set additional state
  701.         setInitialState(state.addAdditionalState(columnName, column));

  702.     }

  703.     /** {@inheritDoc} */
  704.     @Override
  705.     public TimeStampedPVCoordinates getPVCoordinates(final AbsoluteDate date, final Frame frame) {
  706.         return propagate(date).getPVCoordinates(frame);
  707.     }

  708.     /** {@inheritDoc} */
  709.     @Override
  710.     protected StateMapper createMapper(final AbsoluteDate referenceDate, final double mu,
  711.                                        final OrbitType orbitType, final PositionAngleType positionAngleType,
  712.                                        final AttitudeProvider attitudeProvider, final Frame frame) {
  713.         return new OsculatingMapper(referenceDate, mu, orbitType, positionAngleType, attitudeProvider, frame);
  714.     }

  715.     /** Internal mapper using directly osculating parameters. */
  716.     private static class OsculatingMapper extends StateMapper {

  717.         /** Simple constructor.
  718.          * <p>
  719.          * The position parameter type is meaningful only if {@link
  720.          * #getOrbitType() propagation orbit type}
  721.          * support it. As an example, it is not meaningful for propagation
  722.          * in {@link OrbitType#CARTESIAN Cartesian} parameters.
  723.          * </p>
  724.          * @param referenceDate reference date
  725.          * @param mu central attraction coefficient (m³/s²)
  726.          * @param orbitType orbit type to use for mapping (can be null for {@link AbsolutePVCoordinates})
  727.          * @param positionAngleType angle type to use for propagation
  728.          * @param attitudeProvider attitude provider
  729.          * @param frame inertial frame
  730.          */
  731.         OsculatingMapper(final AbsoluteDate referenceDate, final double mu,
  732.                          final OrbitType orbitType, final PositionAngleType positionAngleType,
  733.                          final AttitudeProvider attitudeProvider, final Frame frame) {
  734.             super(referenceDate, mu, orbitType, positionAngleType, attitudeProvider, frame);
  735.         }

  736.         /** {@inheritDoc} */
  737.         public SpacecraftState mapArrayToState(final AbsoluteDate date, final double[] y, final double[] yDot,
  738.                                                final PropagationType type) {
  739.             // the parameter type is ignored for the Numerical Propagator

  740.             final double mass = y[6];
  741.             if (mass <= 0.0) {
  742.                 throw new OrekitException(OrekitMessages.NOT_POSITIVE_SPACECRAFT_MASS, mass);
  743.             }

  744.             if (getOrbitType() == null) {
  745.                 // propagation uses absolute position-velocity-acceleration
  746.                 final Vector3D p = new Vector3D(y[0],    y[1],    y[2]);
  747.                 final Vector3D v = new Vector3D(y[3],    y[4],    y[5]);
  748.                 final Vector3D a;
  749.                 final AbsolutePVCoordinates absPva;
  750.                 if (yDot == null) {
  751.                     absPva = new AbsolutePVCoordinates(getFrame(), new TimeStampedPVCoordinates(date, p, v));
  752.                 } else {
  753.                     a = new Vector3D(yDot[3], yDot[4], yDot[5]);
  754.                     absPva = new AbsolutePVCoordinates(getFrame(), new TimeStampedPVCoordinates(date, p, v, a));
  755.                 }

  756.                 final Attitude attitude = getAttitudeProvider().getAttitude(absPva, date, getFrame());
  757.                 return new SpacecraftState(absPva, attitude, mass);
  758.             } else {
  759.                 // propagation uses regular orbits
  760.                 final Orbit orbit       = getOrbitType().mapArrayToOrbit(y, yDot, getPositionAngleType(), date, getMu(), getFrame());
  761.                 final Attitude attitude = getAttitudeProvider().getAttitude(orbit, date, getFrame());

  762.                 return new SpacecraftState(orbit, attitude, mass);
  763.             }

  764.         }

  765.         /** {@inheritDoc} */
  766.         public void mapStateToArray(final SpacecraftState state, final double[] y, final double[] yDot) {
  767.             if (getOrbitType() == null) {
  768.                 // propagation uses absolute position-velocity-acceleration
  769.                 final Vector3D p = state.getAbsPVA().getPosition();
  770.                 final Vector3D v = state.getAbsPVA().getVelocity();
  771.                 y[0] = p.getX();
  772.                 y[1] = p.getY();
  773.                 y[2] = p.getZ();
  774.                 y[3] = v.getX();
  775.                 y[4] = v.getY();
  776.                 y[5] = v.getZ();
  777.                 y[6] = state.getMass();
  778.             }
  779.             else {
  780.                 getOrbitType().mapOrbitToArray(state.getOrbit(), getPositionAngleType(), y, yDot);
  781.                 y[6] = state.getMass();
  782.             }
  783.         }

  784.     }

  785.     /** {@inheritDoc} */
  786.     protected MainStateEquations getMainStateEquations(final ODEIntegrator integrator) {
  787.         return new Main(integrator);
  788.     }

  789.     /** Internal class for osculating parameters integration. */
  790.     private class Main implements MainStateEquations, TimeDerivativesEquations {

  791.         /** Derivatives array. */
  792.         private final double[] yDot;

  793.         /** Current state. */
  794.         private SpacecraftState currentState;

  795.         /** Jacobian of the orbital parameters with respect to the Cartesian parameters. */
  796.         private double[][] jacobian;

  797.         /** Simple constructor.
  798.          * @param integrator numerical integrator to use for propagation.
  799.          */
  800.         Main(final ODEIntegrator integrator) {

  801.             this.yDot     = new double[7];
  802.             this.jacobian = new double[6][6];

  803.             for (final ForceModel forceModel : forceModels) {
  804.                 forceModel.getEventDetectors().forEach(detector -> setUpEventDetector(integrator, detector));
  805.             }

  806.             if (getOrbitType() == null) {
  807.                 // propagation uses absolute position-velocity-acceleration
  808.                 // we can set Jacobian once and for all
  809.                 for (int i = 0; i < jacobian.length; ++i) {
  810.                     Arrays.fill(jacobian[i], 0.0);
  811.                     jacobian[i][i] = 1.0;
  812.                 }
  813.             }

  814.         }

  815.         /** {@inheritDoc} */
  816.         @Override
  817.         public void init(final SpacecraftState initialState, final AbsoluteDate target) {
  818.             forceModels.forEach(fm -> fm.init(initialState, target));
  819.         }

  820.         /** {@inheritDoc} */
  821.         @Override
  822.         public double[] computeDerivatives(final SpacecraftState state) {

  823.             currentState = state;
  824.             Arrays.fill(yDot, 0.0);
  825.             if (getOrbitType() != null) {
  826.                 // propagation uses regular orbits
  827.                 currentState.getOrbit().getJacobianWrtCartesian(getPositionAngleType(), jacobian);
  828.             }

  829.             // compute the contributions of all perturbing forces,
  830.             // using the Kepler contribution at the end since
  831.             // NewtonianAttraction is always the last instance in the list
  832.             for (final ForceModel forceModel : forceModels) {
  833.                 forceModel.addContribution(state, this);
  834.             }

  835.             if (getOrbitType() == null) {
  836.                 // position derivative is velocity, and was not added above in the force models
  837.                 // (it is added when orbit type is non-null because NewtonianAttraction considers it)
  838.                 final Vector3D velocity = currentState.getPVCoordinates().getVelocity();
  839.                 yDot[0] += velocity.getX();
  840.                 yDot[1] += velocity.getY();
  841.                 yDot[2] += velocity.getZ();
  842.             }


  843.             return yDot.clone();

  844.         }

  845.         /** {@inheritDoc} */
  846.         @Override
  847.         public void addKeplerContribution(final double mu) {
  848.             if (getOrbitType() == null) {
  849.                 // if mu is neither 0 nor NaN, we want to include Newtonian acceleration
  850.                 if (mu > 0) {
  851.                     // velocity derivative is Newtonian acceleration
  852.                     final Vector3D position = currentState.getPosition();
  853.                     final double r2         = position.getNormSq();
  854.                     final double coeff      = -mu / (r2 * FastMath.sqrt(r2));
  855.                     yDot[3] += coeff * position.getX();
  856.                     yDot[4] += coeff * position.getY();
  857.                     yDot[5] += coeff * position.getZ();
  858.                 }

  859.             } else {
  860.                 // propagation uses regular orbits
  861.                 currentState.getOrbit().addKeplerContribution(getPositionAngleType(), mu, yDot);
  862.             }
  863.         }

  864.         /** {@inheritDoc} */
  865.         public void addNonKeplerianAcceleration(final Vector3D gamma) {
  866.             for (int i = 0; i < 6; ++i) {
  867.                 final double[] jRow = jacobian[i];
  868.                 yDot[i] += jRow[3] * gamma.getX() + jRow[4] * gamma.getY() + jRow[5] * gamma.getZ();
  869.             }
  870.         }

  871.         /** {@inheritDoc} */
  872.         @Override
  873.         public void addMassDerivative(final double q) {
  874.             if (q > 0) {
  875.                 throw new OrekitIllegalArgumentException(OrekitMessages.POSITIVE_FLOW_RATE, q);
  876.             }
  877.             yDot[6] += q;
  878.         }

  879.     }

  880.     /** Estimate tolerance vectors for integrators when propagating in absolute position-velocity-acceleration.
  881.      * @param dP user specified position error
  882.      * @param absPva reference absolute position-velocity-acceleration
  883.      * @return a two rows array, row 0 being the absolute tolerance error and row 1
  884.      * being the relative tolerance error
  885.      * @see NumericalPropagator#tolerances(double, Orbit, OrbitType)
  886.      */
  887.     public static double[][] tolerances(final double dP, final AbsolutePVCoordinates absPva) {

  888.         final double relative = dP / absPva.getPosition().getNorm();
  889.         final double dV = relative * absPva.getVelocity().getNorm();

  890.         final double[] absTol = new double[7];
  891.         final double[] relTol = new double[7];

  892.         absTol[0] = dP;
  893.         absTol[1] = dP;
  894.         absTol[2] = dP;
  895.         absTol[3] = dV;
  896.         absTol[4] = dV;
  897.         absTol[5] = dV;

  898.         // we set the mass tolerance arbitrarily to 1.0e-6 kg, as mass evolves linearly
  899.         // with trust, this often has no influence at all on propagation
  900.         absTol[6] = 1.0e-6;

  901.         Arrays.fill(relTol, relative);

  902.         return new double[][] {
  903.             absTol, relTol
  904.         };

  905.     }

  906.     /** Estimate tolerance vectors for integrators when propagating in orbits.
  907.      * <p>
  908.      * The errors are estimated from partial derivatives properties of orbits,
  909.      * starting from a scalar position error specified by the user.
  910.      * Considering the energy conservation equation V = sqrt(mu (2/r - 1/a)),
  911.      * we get at constant energy (i.e. on a Keplerian trajectory):
  912.      * <pre>
  913.      * V r² |dV| = mu |dr|
  914.      * </pre>
  915.      * <p> So we deduce a scalar velocity error consistent with the position error.
  916.      * From here, we apply orbits Jacobians matrices to get consistent errors
  917.      * on orbital parameters.
  918.      *
  919.      * <p>
  920.      * The tolerances are only <em>orders of magnitude</em>, and integrator tolerances
  921.      * are only local estimates, not global ones. So some care must be taken when using
  922.      * these tolerances. Setting 1mm as a position error does NOT mean the tolerances
  923.      * will guarantee a 1mm error position after several orbits integration.
  924.      * </p>
  925.      * @param dP user specified position error
  926.      * @param orbit reference orbit
  927.      * @param type propagation type for the meaning of the tolerance vectors elements
  928.      * (it may be different from {@code orbit.getType()})
  929.      * @return a two rows array, row 0 being the absolute tolerance error and row 1
  930.      * being the relative tolerance error
  931.      */
  932.     public static double[][] tolerances(final double dP, final Orbit orbit, final OrbitType type) {

  933.         // estimate the scalar velocity error
  934.         final PVCoordinates pv = orbit.getPVCoordinates();
  935.         final double r2 = pv.getPosition().getNormSq();
  936.         final double v  = pv.getVelocity().getNorm();
  937.         final double dV = orbit.getMu() * dP / (v * r2);

  938.         return tolerances(dP, dV, orbit, type);

  939.     }

  940.     /** Estimate tolerance vectors for integrators when propagating in orbits.
  941.      * <p>
  942.      * The errors are estimated from partial derivatives properties of orbits,
  943.      * starting from scalar position and velocity errors specified by the user.
  944.      * <p>
  945.      * The tolerances are only <em>orders of magnitude</em>, and integrator tolerances
  946.      * are only local estimates, not global ones. So some care must be taken when using
  947.      * these tolerances. Setting 1mm as a position error does NOT mean the tolerances
  948.      * will guarantee a 1mm error position after several orbits integration.
  949.      * </p>
  950.      * @param dP user specified position error
  951.      * @param dV user specified velocity error
  952.      * @param orbit reference orbit
  953.      * @param type propagation type for the meaning of the tolerance vectors elements
  954.      * (it may be different from {@code orbit.getType()})
  955.      * @return a two rows array, row 0 being the absolute tolerance error and row 1
  956.      * being the relative tolerance error
  957.      * @since 10.3
  958.      */
  959.     public static double[][] tolerances(final double dP, final double dV,
  960.                                         final Orbit orbit, final OrbitType type) {

  961.         final double[] absTol = new double[7];
  962.         final double[] relTol = new double[7];

  963.         // we set the mass tolerance arbitrarily to 1.0e-6 kg, as mass evolves linearly
  964.         // with trust, this often has no influence at all on propagation
  965.         absTol[6] = 1.0e-6;

  966.         if (type == OrbitType.CARTESIAN) {
  967.             absTol[0] = dP;
  968.             absTol[1] = dP;
  969.             absTol[2] = dP;
  970.             absTol[3] = dV;
  971.             absTol[4] = dV;
  972.             absTol[5] = dV;
  973.         } else {

  974.             // convert the orbit to the desired type
  975.             final double[][] jacobian = new double[6][6];
  976.             final Orbit converted = type.convertType(orbit);
  977.             converted.getJacobianWrtCartesian(PositionAngleType.TRUE, jacobian);

  978.             for (int i = 0; i < 6; ++i) {
  979.                 final double[] row = jacobian[i];
  980.                 absTol[i] = FastMath.abs(row[0]) * dP +
  981.                             FastMath.abs(row[1]) * dP +
  982.                             FastMath.abs(row[2]) * dP +
  983.                             FastMath.abs(row[3]) * dV +
  984.                             FastMath.abs(row[4]) * dV +
  985.                             FastMath.abs(row[5]) * dV;
  986.                 if (Double.isNaN(absTol[i])) {
  987.                     throw new OrekitException(OrekitMessages.SINGULAR_JACOBIAN_FOR_ORBIT_TYPE, type);
  988.                 }
  989.             }

  990.         }

  991.         Arrays.fill(relTol, dP / FastMath.sqrt(orbit.getPosition().getNormSq()));

  992.         return new double[][] {
  993.             absTol, relTol
  994.         };

  995.     }

  996.     /** {@inheritDoc} */
  997.     @Override
  998.     protected void beforeIntegration(final SpacecraftState initialState, final AbsoluteDate tEnd) {

  999.         if (!getFrame().isPseudoInertial()) {

  1000.             // inspect all force models to find InertialForces
  1001.             for (ForceModel force : forceModels) {
  1002.                 if (force instanceof InertialForces) {
  1003.                     return;
  1004.                 }
  1005.             }

  1006.             // throw exception if no inertial forces found
  1007.             throw new OrekitException(OrekitMessages.INERTIAL_FORCE_MODEL_MISSING, getFrame().getName());

  1008.         }

  1009.     }

  1010. }