FieldNumericalPropagator.java

  1. /* Copyright 2002-2025 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.CalculusFieldElement;
  23. import org.hipparchus.Field;
  24. import org.hipparchus.geometry.euclidean.threed.FieldVector3D;
  25. import org.hipparchus.ode.FieldODEIntegrator;
  26. import org.hipparchus.util.MathArrays;
  27. import org.orekit.annotation.DefaultDataContext;
  28. import org.orekit.attitudes.AttitudeProvider;
  29. import org.orekit.attitudes.FieldAttitude;
  30. import org.orekit.data.DataContext;
  31. import org.orekit.errors.OrekitException;
  32. import org.orekit.errors.OrekitIllegalArgumentException;
  33. import org.orekit.errors.OrekitInternalError;
  34. import org.orekit.errors.OrekitMessages;
  35. import org.orekit.forces.ForceModel;
  36. import org.orekit.forces.gravity.NewtonianAttraction;
  37. import org.orekit.frames.Frame;
  38. import org.orekit.orbits.FieldOrbit;
  39. import org.orekit.orbits.OrbitType;
  40. import org.orekit.orbits.PositionAngleType;
  41. import org.orekit.propagation.CartesianToleranceProvider;
  42. import org.orekit.propagation.FieldSpacecraftState;
  43. import org.orekit.propagation.PropagationType;
  44. import org.orekit.propagation.Propagator;
  45. import org.orekit.propagation.ToleranceProvider;
  46. import org.orekit.propagation.events.FieldEventDetector;
  47. import org.orekit.propagation.integration.FieldAbstractIntegratedPropagator;
  48. import org.orekit.propagation.integration.FieldStateMapper;
  49. import org.orekit.time.AbsoluteDate;
  50. import org.orekit.time.FieldAbsoluteDate;
  51. import org.orekit.utils.FieldAbsolutePVCoordinates;
  52. import org.orekit.utils.ParameterDriver;
  53. import org.orekit.utils.ParameterObserver;
  54. import org.orekit.utils.TimeSpanMap;
  55. import org.orekit.utils.TimeStampedFieldPVCoordinates;

  56. /** This class propagates {@link org.orekit.orbits.FieldOrbit orbits} using
  57.  * numerical integration.
  58.  * <p>Numerical propagation is much more accurate than analytical propagation
  59.  * like for example {@link org.orekit.propagation.analytical.KeplerianPropagator
  60.  * Keplerian} or {@link org.orekit.propagation.analytical.EcksteinHechlerPropagator
  61.  * Eckstein-Hechler}, but requires a few more steps to set up to be used properly.
  62.  * Whereas analytical propagators are configured only thanks to their various
  63.  * constructors and can be used immediately after construction, numerical propagators
  64.  * configuration involve setting several parameters between construction time
  65.  * and propagation time.</p>
  66.  * <p>The configuration parameters that can be set are:</p>
  67.  * <ul>
  68.  *   <li>the initial spacecraft state ({@link #setInitialState(FieldSpacecraftState)})</li>
  69.  *   <li>the central attraction coefficient ({@link #setMu(CalculusFieldElement)})</li>
  70.  *   <li>the various force models ({@link #addForceModel(ForceModel)},
  71.  *   {@link #removeForceModels()})</li>
  72.  *   <li>the {@link OrbitType type} of orbital parameters to be used for propagation
  73.  *   ({@link #setOrbitType(OrbitType)}),
  74.  *   <li>the {@link PositionAngleType type} of position angle to be used in orbital parameters
  75.  *   to be used for propagation where it is relevant ({@link
  76.  *   #setPositionAngleType(PositionAngleType)}),
  77.  *   <li>whether {@link org.orekit.propagation.integration.FieldAdditionalDerivativesProvider additional derivatives providers}
  78.  *   should be propagated along with orbital state
  79.  *   ({@link #addAdditionalDerivativesProvider(org.orekit.propagation.integration.FieldAdditionalDerivativesProvider)}),
  80.  *   <li>the discrete events that should be triggered during propagation
  81.  *   ({@link #addEventDetector(FieldEventDetector)},
  82.  *   {@link #clearEventsDetectors()})</li>
  83.  *   <li>the binding logic with the rest of the application ({@link #getMultiplexer()})</li>
  84.  * </ul>
  85.  * <p>From these configuration parameters, only the initial state is mandatory. The default
  86.  * propagation settings are in {@link OrbitType#EQUINOCTIAL equinoctial} parameters with
  87.  * {@link PositionAngleType#ECCENTRIC} longitude argument. If the central attraction coefficient
  88.  * is not explicitly specified, the one used to define the initial orbit will be used.
  89.  * However, specifying only the initial state and perhaps the central attraction coefficient
  90.  * would mean the propagator would use only Keplerian forces. In this case, the simpler {@link
  91.  * org.orekit.propagation.analytical.KeplerianPropagator KeplerianPropagator} class would
  92.  * perhaps be more effective.</p>
  93.  * <p>The underlying numerical integrator set up in the constructor may also have its own
  94.  * configuration parameters. Typical configuration parameters for adaptive stepsize integrators
  95.  * are the min, max and perhaps start step size as well as the absolute and/or relative errors
  96.  * thresholds.</p>
  97.  * <p>The state that is seen by the integrator is a simple seven elements double array.
  98.  * The six first elements are either:
  99.  * <ul>
  100.  *   <li>the {@link org.orekit.orbits.FieldEquinoctialOrbit equinoctial orbit parameters} (a, e<sub>x</sub>,
  101.  *   e<sub>y</sub>, h<sub>x</sub>, h<sub>y</sub>, λ<sub>M</sub> or λ<sub>E</sub>
  102.  *   or λ<sub>v</sub>) in meters and radians,</li>
  103.  *   <li>the {@link org.orekit.orbits.FieldKeplerianOrbit Keplerian orbit parameters} (a, e, i, ω, Ω,
  104.  *   M or E or v) in meters and radians,</li>
  105.  *   <li>the {@link org.orekit.orbits.FieldCircularOrbit circular orbit parameters} (a, e<sub>x</sub>, e<sub>y</sub>, i,
  106.  *   Ω, α<sub>M</sub> or α<sub>E</sub> or α<sub>v</sub>) in meters
  107.  *   and radians,</li>
  108.  *   <li>the {@link org.orekit.orbits.FieldCartesianOrbit Cartesian orbit parameters} (x, y, z, v<sub>x</sub>,
  109.  *   v<sub>y</sub>, v<sub>z</sub>) in meters and meters per seconds.
  110.  * </ul>
  111.  * The last element is the mass in kilograms.
  112.  * <p>The following code snippet shows a typical setting for Low Earth Orbit propagation in
  113.  * equinoctial parameters and true longitude argument:</p>
  114.  * <pre>
  115.  * final T          zero      = field.getZero();
  116.  * final T          dP        = zero.add(0.001);
  117.  * final T          minStep   = zero.add(0.001);
  118.  * final T          maxStep   = zero.add(500);
  119.  * final T          initStep  = zero.add(60);
  120.  * final double[][] tolerance = ToleranceProvider.getDefaultToleranceProvider(dP).getTolerances(orbit, OrbitType.EQUINOCTIAL);
  121.  * AdaptiveStepsizeFieldIntegrator&lt;T&gt; integrator = new DormandPrince853FieldIntegrator&lt;&gt;(field, minStep, maxStep, tolerance[0], tolerance[1]);
  122.  * integrator.setInitialStepSize(initStep);
  123.  * propagator = new FieldNumericalPropagator&lt;&gt;(field, integrator);
  124.  * </pre>
  125.  * <p>By default, at the end of the propagation, the propagator resets the initial state to the final state,
  126.  * thus allowing a new propagation to be started from there without recomputing the part already performed.
  127.  * This behaviour can be changed by calling {@link #setResetAtEnd(boolean)}.
  128.  * </p>
  129.  * <p>Beware the same instance cannot be used simultaneously by different threads, the class is <em>not</em>
  130.  * thread-safe.</p>

  131.  * @see FieldSpacecraftState
  132.  * @see ForceModel
  133.  * @see org.orekit.propagation.sampling.FieldOrekitStepHandler
  134.  * @see org.orekit.propagation.sampling.FieldOrekitFixedStepHandler
  135.  * @see org.orekit.propagation.integration.FieldIntegratedEphemeris
  136.  * @see FieldTimeDerivativesEquations
  137.  *
  138.  * @author Mathieu Rom&eacute;ro
  139.  * @author Luc Maisonobe
  140.  * @author Guylaine Prat
  141.  * @author Fabien Maussion
  142.  * @author V&eacute;ronique Pommier-Maurussane
  143.  * @param <T> type of the field elements
  144.  */
  145. public class FieldNumericalPropagator<T extends CalculusFieldElement<T>> extends FieldAbstractIntegratedPropagator<T> {

  146.     /** Force models used during the extrapolation of the FieldOrbit<T>, without Jacobians. */
  147.     private final List<ForceModel> forceModels;

  148.     /** Field used by this class.*/
  149.     private final Field<T> field;

  150.     /** boolean to ignore or not the creation of a NewtonianAttraction. */
  151.     private boolean ignoreCentralAttraction = false;

  152.     /**
  153.      * boolean to know if a full attitude (with rates) is needed when computing derivatives for the ODE.
  154.      */
  155.     private boolean needFullAttitudeForDerivatives = true;

  156.     /** Create a new instance of NumericalPropagator, based on orbit definition mu.
  157.      * After creation, the instance is empty, i.e. the attitude provider is set to an
  158.      * unspecified default law and there are no perturbing forces at all.
  159.      * This means that if {@link #addForceModel addForceModel} is not
  160.      * called after creation, the integrated orbit will follow a Keplerian
  161.      * evolution only. The defaults are {@link OrbitType#EQUINOCTIAL}
  162.      * for {@link #setOrbitType(OrbitType) propagation
  163.      * orbit type} and {@link PositionAngleType#ECCENTRIC} for {@link
  164.      * #setPositionAngleType(PositionAngleType) position angle type}.
  165.      *
  166.      * <p>This constructor uses the {@link DataContext#getDefault() default data context}.
  167.      *
  168.      * @param integrator numerical integrator to use for propagation.
  169.      * @param field Field used by default
  170.      * @see #FieldNumericalPropagator(Field, FieldODEIntegrator, AttitudeProvider)
  171.      */
  172.     @DefaultDataContext
  173.     public FieldNumericalPropagator(final Field<T> field, final FieldODEIntegrator<T> integrator) {
  174.         this(field, integrator, Propagator.getDefaultLaw(DataContext.getDefault().getFrames()));
  175.     }

  176.     /** Create a new instance of NumericalPropagator, based on orbit definition mu.
  177.      * After creation, the instance is empty, i.e. the attitude provider is set to an
  178.      * unspecified default law and there are no perturbing forces at all.
  179.      * This means that if {@link #addForceModel addForceModel} is not
  180.      * called after creation, the integrated orbit will follow a Keplerian
  181.      * evolution only. The defaults are {@link OrbitType#EQUINOCTIAL}
  182.      * for {@link #setOrbitType(OrbitType) propagation
  183.      * orbit type} and {@link PositionAngleType#ECCENTRIC} for {@link
  184.      * #setPositionAngleType(PositionAngleType) position angle type}.
  185.      * @param field Field used by default
  186.      * @param integrator numerical integrator to use for propagation.
  187.      * @param attitudeProvider attitude law to use.
  188.      * @since 10.1
  189.      */
  190.     public FieldNumericalPropagator(final Field<T> field,
  191.                                     final FieldODEIntegrator<T> integrator,
  192.                                     final AttitudeProvider attitudeProvider) {
  193.         super(field, integrator, PropagationType.OSCULATING);
  194.         this.field = field;
  195.         forceModels = new ArrayList<>();
  196.         initMapper(field);
  197.         setAttitudeProvider(attitudeProvider);
  198.         setMu(field.getZero().add(Double.NaN));
  199.         clearStepHandlers();
  200.         setOrbitType(NumericalPropagator.DEFAULT_ORBIT_TYPE);
  201.         setPositionAngleType(NumericalPropagator.DEFAULT_POSITION_ANGLE_TYPE);
  202.     }

  203.     /** Set the flag to ignore or not the creation of a {@link NewtonianAttraction}.
  204.      * @param ignoreCentralAttraction if true, {@link NewtonianAttraction} is <em>not</em>
  205.      * added automatically if missing
  206.      */
  207.     public void setIgnoreCentralAttraction(final boolean ignoreCentralAttraction) {
  208.         this.ignoreCentralAttraction = ignoreCentralAttraction;
  209.     }

  210.     /** Set the central attraction coefficient μ.
  211.      * <p>
  212.      * Setting the central attraction coefficient is
  213.      * equivalent to {@link #addForceModel(ForceModel) add}
  214.      * a {@link NewtonianAttraction} force model.
  215.      * </p>
  216.      * @param mu central attraction coefficient (m³/s²)
  217.      * @see #addForceModel(ForceModel)
  218.      * @see #getAllForceModels()
  219.      */
  220.     @Override
  221.     public void setMu(final T mu) {
  222.         if (ignoreCentralAttraction) {
  223.             superSetMu(mu);
  224.         } else {
  225.             addForceModel(new NewtonianAttraction(mu.getReal()));
  226.         }
  227.     }

  228.     /** Set the central attraction coefficient μ only in upper class.
  229.      * @param mu central attraction coefficient (m³/s²)
  230.      */
  231.     private void superSetMu(final T mu) {
  232.         super.setMu(mu);
  233.     }

  234.     /** Check if Newtonian attraction force model is available.
  235.      * <p>
  236.      * Newtonian attraction is always the last force model in the list.
  237.      * </p>
  238.      * @return true if Newtonian attraction force model is available
  239.      */
  240.     private boolean hasNewtonianAttraction() {
  241.         final int last = forceModels.size() - 1;
  242.         return last >= 0 && forceModels.get(last) instanceof NewtonianAttraction;
  243.     }

  244.     /** Add a force model to the global perturbation model.
  245.      * <p>If this method is not called at all, the integrated orbit will follow
  246.      * a Keplerian evolution only.</p>
  247.      * @param model perturbing {@link ForceModel} to add
  248.      * @see #removeForceModels()
  249.      * @see #setMu(CalculusFieldElement)
  250.      */
  251.     public void addForceModel(final ForceModel model) {

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

  254.             try {
  255.                 // ensure we are notified of any mu change
  256.                 model.getParametersDrivers().get(0).addObserver(new ParameterObserver() {
  257.                     /** {@inheritDoc} */
  258.                     @Override
  259.                     public void valueChanged(final double previousValue, final ParameterDriver driver, final AbsoluteDate date) {
  260.                         // mu PDriver should have only 1 span
  261.                         superSetMu(field.getZero().newInstance(driver.getValue(date)));
  262.                     }
  263.                     /** {@inheritDoc} */
  264.                     @Override
  265.                     public void valueSpanMapChanged(final TimeSpanMap<Double> previousValue, final ParameterDriver driver) {
  266.                         // mu PDriver should have only 1 span
  267.                         superSetMu(field.getZero().newInstance(driver.getValue()));
  268.                     }
  269.                 });
  270.             } catch (OrekitException oe) {
  271.                 // this should never happen
  272.                 throw new OrekitInternalError(oe);
  273.             }

  274.             if (hasNewtonianAttraction()) {
  275.                 // there is already a central attraction model, replace it
  276.                 forceModels.set(forceModels.size() - 1, model);
  277.             } else {
  278.                 // there are no central attraction model yet, add it at the end of the list
  279.                 forceModels.add(model);
  280.             }
  281.         } else {
  282.             // we want to add a perturbing force model
  283.             if (hasNewtonianAttraction()) {
  284.                 // insert the new force model before Newtonian attraction,
  285.                 // which should always be the last one in the list
  286.                 forceModels.add(forceModels.size() - 1, model);
  287.             } else {
  288.                 // we only have perturbing force models up to now, just append at the end of the list
  289.                 forceModels.add(model);
  290.             }
  291.         }

  292.     }

  293.     /** Remove all perturbing force models from the global perturbation model.
  294.      * <p>Once all perturbing forces have been removed (and as long as no new force
  295.      * model is added), the integrated orbit will follow a Keplerian evolution
  296.      * only.</p>
  297.      * @see #addForceModel(ForceModel)
  298.      */
  299.     public void removeForceModels() {
  300.         forceModels.clear();
  301.     }

  302.     /** Get all the force models, perturbing forces and Newtonian attraction included.
  303.      * @return list of perturbing force models, with Newtonian attraction being the
  304.      * last one
  305.      * @see #addForceModel(ForceModel)
  306.      * @see #setMu(CalculusFieldElement)
  307.      * @since 9.1
  308.      */
  309.     public List<ForceModel> getAllForceModels() {
  310.         return Collections.unmodifiableList(forceModels);
  311.     }

  312.     /** Set propagation orbit type.
  313.      * @param orbitType orbit type to use for propagation
  314.      */
  315.     @Override
  316.     public void setOrbitType(final OrbitType orbitType) {
  317.         super.setOrbitType(orbitType);
  318.     }

  319.     /** Get propagation parameter type.
  320.      * @return orbit type used for propagation
  321.      */
  322.     @Override
  323.     public OrbitType getOrbitType() {
  324.         return superGetOrbitType();
  325.     }

  326.     /** Get propagation parameter type.
  327.      * @return orbit type used for propagation
  328.      */
  329.     private OrbitType superGetOrbitType() {
  330.         return super.getOrbitType();
  331.     }

  332.     /** Set position angle type.
  333.      * <p>
  334.      * The position parameter type is meaningful only if {@link
  335.      * #getOrbitType() propagation orbit type}
  336.      * support it. As an example, it is not meaningful for propagation
  337.      * in {@link OrbitType#CARTESIAN Cartesian} parameters.
  338.      * </p>
  339.      * @param positionAngleType angle type to use for propagation
  340.      */
  341.     @Override
  342.     public void setPositionAngleType(final PositionAngleType positionAngleType) {
  343.         super.setPositionAngleType(positionAngleType);
  344.     }

  345.     /** Get propagation parameter type.
  346.      * @return angle type to use for propagation
  347.      */
  348.     @Override
  349.     public PositionAngleType getPositionAngleType() {
  350.         return super.getPositionAngleType();
  351.     }

  352.     /** Set the initial state.
  353.      * @param initialState initial state
  354.      */
  355.     public void setInitialState(final FieldSpacecraftState<T> initialState) {
  356.         resetInitialState(initialState);
  357.     }

  358.     /** {@inheritDoc} */
  359.     @Override
  360.     public void resetInitialState(final FieldSpacecraftState<T> state) {
  361.         super.resetInitialState(state);
  362.         if (!hasNewtonianAttraction()) {
  363.             setMu(state.getOrbit().getMu());
  364.         }
  365.         setStartDate(state.getDate());
  366.     }

  367.     /** {@inheritDoc} */
  368.     @Override
  369.     protected AttitudeProvider initializeAttitudeProviderForDerivatives() {
  370.         return needFullAttitudeForDerivatives ? getAttitudeProvider() : getFrozenAttitudeProvider();
  371.     }

  372.     /** {@inheritDoc} */
  373.     protected FieldStateMapper<T> createMapper(final FieldAbsoluteDate<T> referenceDate, final T mu,
  374.                                        final OrbitType orbitType, final PositionAngleType positionAngleType,
  375.                                        final AttitudeProvider attitudeProvider, final Frame frame) {
  376.         return new FieldOsculatingMapper(referenceDate, mu, orbitType, positionAngleType, attitudeProvider, frame);
  377.     }

  378.     /** Internal mapper using directly osculating parameters. */
  379.     private class FieldOsculatingMapper extends FieldStateMapper<T> {

  380.         /** Simple constructor.
  381.          * <p>
  382.          * The position parameter type is meaningful only if {@link
  383.          * #getOrbitType() propagation orbit type}
  384.          * support it. As an example, it is not meaningful for propagation
  385.          * in {@link OrbitType#CARTESIAN Cartesian} parameters.
  386.          * </p>
  387.          * @param referenceDate reference date
  388.          * @param mu central attraction coefficient (m³/s²)
  389.          * @param orbitType orbit type to use for mapping
  390.          * @param positionAngleType angle type to use for propagation
  391.          * @param attitudeProvider attitude provider
  392.          * @param frame inertial frame
  393.          */
  394.         FieldOsculatingMapper(final FieldAbsoluteDate<T> referenceDate, final T mu,
  395.                               final OrbitType orbitType, final PositionAngleType positionAngleType,
  396.                               final AttitudeProvider attitudeProvider, final Frame frame) {
  397.             super(referenceDate, mu, orbitType, positionAngleType, attitudeProvider, frame);
  398.         }

  399.         /** {@inheritDoc} */
  400.         public FieldSpacecraftState<T> mapArrayToState(final FieldAbsoluteDate<T> date, final T[] y, final T[] yDot,
  401.                                                        final PropagationType type) {
  402.             // the parameter type is ignored for the Numerical Propagator

  403.             final T mass = y[6];
  404.             if (mass.getReal() <= 0.0) {
  405.                 throw new OrekitException(OrekitMessages.NOT_POSITIVE_SPACECRAFT_MASS, mass);
  406.             }

  407.             if (superGetOrbitType() == null) {
  408.                 // propagation uses absolute position-velocity-acceleration
  409.                 final FieldVector3D<T> p = new FieldVector3D<>(y[0],    y[1],    y[2]);
  410.                 final FieldVector3D<T> v = new FieldVector3D<>(y[3],    y[4],    y[5]);
  411.                 final FieldVector3D<T> a;
  412.                 final FieldAbsolutePVCoordinates<T> absPva;
  413.                 if (yDot == null) {
  414.                     absPva = new FieldAbsolutePVCoordinates<>(getFrame(), new TimeStampedFieldPVCoordinates<>(date, p, v, FieldVector3D.getZero(date.getField())));
  415.                 } else {
  416.                     a = new FieldVector3D<>(yDot[3], yDot[4], yDot[5]);
  417.                     absPva = new FieldAbsolutePVCoordinates<>(getFrame(), new TimeStampedFieldPVCoordinates<>(date, p, v, a));
  418.                 }

  419.                 final FieldAttitude<T> attitude = getAttitudeProvider().getAttitude(absPva, date, getFrame());
  420.                 return new FieldSpacecraftState<>(absPva, attitude).withMass(mass);
  421.             } else {
  422.                 // propagation uses regular orbits
  423.                 final FieldOrbit<T> orbit       = superGetOrbitType().mapArrayToOrbit(y, yDot, super.getPositionAngleType(), date, getMu(), getFrame());
  424.                 final FieldAttitude<T> attitude = getAttitudeProvider().getAttitude(orbit, date, getFrame());
  425.                 return new FieldSpacecraftState<>(orbit, attitude).withMass(mass);
  426.             }
  427.         }

  428.         /** {@inheritDoc} */
  429.         public void mapStateToArray(final FieldSpacecraftState<T> state, final T[] y, final T[] yDot) {
  430.             if (superGetOrbitType() == null) {
  431.                 // propagation uses absolute position-velocity-acceleration
  432.                 final FieldVector3D<T> p = state.getAbsPVA().getPosition();
  433.                 final FieldVector3D<T> v = state.getAbsPVA().getVelocity();
  434.                 y[0] = p.getX();
  435.                 y[1] = p.getY();
  436.                 y[2] = p.getZ();
  437.                 y[3] = v.getX();
  438.                 y[4] = v.getY();
  439.                 y[5] = v.getZ();
  440.                 y[6] = state.getMass();
  441.             }
  442.             else {
  443.                 superGetOrbitType().mapOrbitToArray(state.getOrbit(), super.getPositionAngleType(), y, yDot);
  444.                 y[6] = state.getMass();
  445.             }
  446.         }

  447.     }

  448.     /** {@inheritDoc} */
  449.     protected MainStateEquations<T> getMainStateEquations(final FieldODEIntegrator<T> integrator) {
  450.         return new Main(integrator);
  451.     }

  452.     /** Internal class for osculating parameters integration. */
  453.     private class Main implements MainStateEquations<T>, FieldTimeDerivativesEquations<T> {

  454.         /** Derivatives array. */
  455.         private final T[] yDot;

  456.         /** Current state. */
  457.         private FieldSpacecraftState<T> currentState;

  458.         /** Jacobian of the orbital parameters with respect to the Cartesian parameters. */
  459.         private final T[][] jacobian;

  460.         /** Flag keeping track whether Jacobian matrix needs to be recomputed or not. */
  461.         private boolean recomputingJacobian;

  462.         /** Simple constructor.
  463.          * @param integrator numerical integrator to use for propagation.
  464.          */
  465.         Main(final FieldODEIntegrator<T> integrator) {

  466.             this.yDot     = MathArrays.buildArray(getField(),  7);
  467.             this.jacobian = MathArrays.buildArray(getField(),  6, 6);
  468.             this.recomputingJacobian = true;

  469.             // feed internal event detectors
  470.             for (final ForceModel forceModel : forceModels) {
  471.                 forceModel.getFieldEventDetectors(getField()).forEach(detector -> setUpEventDetector(integrator, detector));
  472.             }
  473.             getAttitudeProvider().getFieldEventDetectors(getField()).forEach(detector -> setUpEventDetector(integrator, detector));

  474.             // default value for Jacobian is identity
  475.             for (int i = 0; i < jacobian.length; ++i) {
  476.                 Arrays.fill(jacobian[i], getField().getZero());
  477.                 jacobian[i][i] = getField().getOne();
  478.             }

  479.         }

  480.         /** {@inheritDoc} */
  481.         @Override
  482.         public void init(final FieldSpacecraftState<T> initialState, final FieldAbsoluteDate<T> target) {
  483.             needFullAttitudeForDerivatives = forceModels.stream().anyMatch(ForceModel::dependsOnAttitudeRate);

  484.             forceModels.forEach(fm -> fm.init(initialState, target));

  485.             final int numberOfForces = forceModels.size();
  486.             final OrbitType orbitType = superGetOrbitType();
  487.             if (orbitType != null && orbitType != OrbitType.CARTESIAN && numberOfForces > 0) {
  488.                 if (numberOfForces > 1) {
  489.                     recomputingJacobian = true;
  490.                 } else {
  491.                     recomputingJacobian = !(forceModels.get(0) instanceof NewtonianAttraction);
  492.                 }
  493.             } else {
  494.                 recomputingJacobian = false;
  495.             }
  496.         }

  497.         /** {@inheritDoc} */
  498.         @Override
  499.         public T[] computeDerivatives(final FieldSpacecraftState<T> state) {
  500.             final T zero = state.getMass().getField().getZero();
  501.             currentState = state;
  502.             Arrays.fill(yDot, zero);
  503.             if (recomputingJacobian) {
  504.                 // propagation uses Jacobian matrix of orbital parameters w.r.t. Cartesian ones
  505.                 currentState.getOrbit().getJacobianWrtCartesian(getPositionAngleType(), jacobian);
  506.             }

  507.             // compute the contributions of all perturbing forces,
  508.             // using the Kepler contribution at the end since
  509.             // NewtonianAttraction is always the last instance in the list
  510.             for (final ForceModel forceModel : forceModels) {
  511.                 forceModel.addContribution(state, this);
  512.             }

  513.             if (superGetOrbitType() == null) {
  514.                 // position derivative is velocity, and was not added above in the force models
  515.                 // (it is added when orbit type is non-null because NewtonianAttraction considers it)
  516.                 final FieldVector3D<T> velocity = currentState.getPVCoordinates().getVelocity();
  517.                 yDot[0] = yDot[0].add(velocity.getX());
  518.                 yDot[1] = yDot[1].add(velocity.getY());
  519.                 yDot[2] = yDot[2].add(velocity.getZ());
  520.             }

  521.             return yDot.clone();

  522.         }

  523.         /** {@inheritDoc} */
  524.         @Override
  525.         public void addKeplerContribution(final T mu) {
  526.             if (superGetOrbitType() == null) {

  527.                 // if mu is neither 0 nor NaN, we want to include Newtonian acceleration
  528.                 if (mu.getReal() > 0) {
  529.                     // velocity derivative is Newtonian acceleration
  530.                     final FieldVector3D<T> position = currentState.getPosition();
  531.                     final T r2         = position.getNormSq();
  532.                     final T coeff      = r2.multiply(r2.sqrt()).reciprocal().negate().multiply(mu);
  533.                     yDot[3] = yDot[3].add(coeff.multiply(position.getX()));
  534.                     yDot[4] = yDot[4].add(coeff.multiply(position.getY()));
  535.                     yDot[5] = yDot[5].add(coeff.multiply(position.getZ()));
  536.                 }

  537.             } else {
  538.                 // propagation uses regular orbits
  539.                 currentState.getOrbit().addKeplerContribution(getPositionAngleType(), mu, yDot);
  540.             }
  541.         }

  542.         /** {@inheritDoc} */
  543.         @Override
  544.         public void addNonKeplerianAcceleration(final FieldVector3D<T> gamma) {
  545.             for (int i = 0; i < 6; ++i) {
  546.                 final T[] jRow = jacobian[i];
  547.                 yDot[i] = yDot[i].add(jRow[3].linearCombination(jRow[3], gamma.getX(),
  548.                                                                 jRow[4], gamma.getY(),
  549.                                                                 jRow[5], gamma.getZ()));
  550.             }
  551.         }

  552.         /** {@inheritDoc} */
  553.         @Override
  554.         public void addMassDerivative(final T q) {
  555.             if (q.getReal() > 0) {
  556.                 throw new OrekitIllegalArgumentException(OrekitMessages.POSITIVE_FLOW_RATE, q);
  557.             }
  558.             yDot[6] = yDot[6].add(q);
  559.         }

  560.     }

  561.     /** Estimate tolerance vectors for integrators.
  562.      * <p>
  563.      * The errors are estimated from partial derivatives properties of orbits,
  564.      * starting from a scalar position error specified by the user.
  565.      * Considering the energy conservation equation V = sqrt(mu (2/r - 1/a)),
  566.      * we get at constant energy (i.e. on a Keplerian trajectory):
  567.      * <pre>
  568.      * V r² |dV| = mu |dr|
  569.      * </pre>
  570.      * So we deduce a scalar velocity error consistent with the position error.
  571.      * From here, we apply orbits Jacobians matrices to get consistent errors
  572.      * on orbital parameters.
  573.      * <p>
  574.      * The tolerances are only <em>orders of magnitude</em>, and integrator tolerances
  575.      * are only local estimates, not global ones. So some care must be taken when using
  576.      * these tolerances. Setting 1mm as a position error does NOT mean the tolerances
  577.      * will guarantee a 1mm error position after several orbits integration.
  578.      * </p>
  579.      * @param dP user specified position error
  580.      * @param orbit reference orbit
  581.      * @param type propagation type for the meaning of the tolerance vectors elements
  582.      * (it may be different from {@code orbit.getType()})
  583.      * @return a two rows array, row 0 being the absolute tolerance error and row 1
  584.      * being the relative tolerance error
  585.      * @param <T> elements type
  586.      * @deprecated since 13.0. Use {@link ToleranceProvider} for default and custom tolerances.
  587.      */
  588.     @Deprecated
  589.     public static <T extends CalculusFieldElement<T>> double[][] tolerances(final T dP, final FieldOrbit<T> orbit,
  590.                                                                             final OrbitType type) {

  591.         return ToleranceProvider.getDefaultToleranceProvider(dP.getReal()).getTolerances(orbit, type, PositionAngleType.TRUE);
  592.     }

  593.     /** Estimate tolerance vectors for integrators when propagating in orbits.
  594.      * <p>
  595.      * The errors are estimated from partial derivatives properties of orbits,
  596.      * starting from scalar position and velocity errors specified by the user.
  597.      * <p>
  598.      * The tolerances are only <em>orders of magnitude</em>, and integrator tolerances
  599.      * are only local estimates, not global ones. So some care must be taken when using
  600.      * these tolerances. Setting 1mm as a position error does NOT mean the tolerances
  601.      * will guarantee a 1mm error position after several orbits integration.
  602.      * </p>
  603.      * @param <T> elements type
  604.      * @param dP user specified position error
  605.      * @param dV user specified velocity error
  606.      * @param orbit reference orbit
  607.      * @param type propagation type for the meaning of the tolerance vectors elements
  608.      * (it may be different from {@code orbit.getType()})
  609.      * @return a two rows array, row 0 being the absolute tolerance error and row 1
  610.      * being the relative tolerance error
  611.      * @since 10.3
  612.      * @deprecated since 13.0. Use {@link ToleranceProvider} for default and custom tolerances.
  613.      */
  614.     @Deprecated
  615.     public static <T extends CalculusFieldElement<T>> double[][] tolerances(final T dP, final T dV,
  616.                                                                             final FieldOrbit<T> orbit,
  617.                                                                             final OrbitType type) {

  618.         return ToleranceProvider.of(CartesianToleranceProvider.of(dP.getReal(), dV.getReal(),
  619.                 CartesianToleranceProvider.DEFAULT_ABSOLUTE_MASS_TOLERANCE)).getTolerances(orbit, type, PositionAngleType.TRUE);
  620.     }

  621. }