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.AttitudeProviderModifier;
  30. import org.orekit.attitudes.FieldAttitude;
  31. import org.orekit.data.DataContext;
  32. import org.orekit.errors.OrekitException;
  33. import org.orekit.errors.OrekitIllegalArgumentException;
  34. import org.orekit.errors.OrekitInternalError;
  35. import org.orekit.errors.OrekitMessages;
  36. import org.orekit.forces.ForceModel;
  37. import org.orekit.forces.gravity.NewtonianAttraction;
  38. import org.orekit.frames.Frame;
  39. import org.orekit.orbits.FieldOrbit;
  40. import org.orekit.orbits.OrbitType;
  41. import org.orekit.orbits.PositionAngleType;
  42. import org.orekit.propagation.CartesianToleranceProvider;
  43. import org.orekit.propagation.FieldSpacecraftState;
  44. import org.orekit.propagation.PropagationType;
  45. import org.orekit.propagation.Propagator;
  46. import org.orekit.propagation.ToleranceProvider;
  47. import org.orekit.propagation.events.FieldEventDetector;
  48. import org.orekit.propagation.integration.FieldAbstractIntegratedPropagator;
  49. import org.orekit.propagation.integration.FieldStateMapper;
  50. import org.orekit.time.AbsoluteDate;
  51. import org.orekit.time.FieldAbsoluteDate;
  52. import org.orekit.utils.FieldAbsolutePVCoordinates;
  53. import org.orekit.utils.ParameterDriver;
  54. import org.orekit.utils.ParameterObserver;
  55. import org.orekit.utils.TimeSpanMap;
  56. import org.orekit.utils.TimeStampedFieldPVCoordinates;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  293.     }

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

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

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

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

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

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

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

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

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

  368.     /** {@inheritDoc} */
  369.     @Override
  370.     protected AttitudeProvider initializeAttitudeProviderForDerivatives() {
  371.         final AttitudeProvider attitudeProvider = getAttitudeProvider();
  372.         return needFullAttitudeForDerivatives ? attitudeProvider :
  373.             AttitudeProviderModifier.getFrozenAttitudeProvider(attitudeProvider);
  374.     }

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

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

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

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

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

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

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

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

  450.     }

  451.     /** {@inheritDoc} */
  452.     protected MainStateEquations<T> getMainStateEquations(final FieldODEIntegrator<T> integrator) {
  453.         return new Main(integrator);
  454.     }

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

  457.         /** Derivatives array. */
  458.         private final T[] yDot;

  459.         /** Current state. */
  460.         private FieldSpacecraftState<T> currentState;

  461.         /** Jacobian of the orbital parameters with respect to the Cartesian parameters. */
  462.         private T[][] jacobian;

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

  465.         /** Simple constructor.
  466.          * @param integrator numerical integrator to use for propagation.
  467.          */
  468.         Main(final FieldODEIntegrator<T> integrator) {

  469.             this.yDot     = MathArrays.buildArray(getField(),  7);
  470.             this.jacobian = MathArrays.buildArray(getField(),  6, 6);
  471.             this.recomputingJacobian = true;

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

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

  482.         }

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

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

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

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

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

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

  524.             return yDot.clone();

  525.         }

  526.         /** {@inheritDoc} */
  527.         @Override
  528.         public void addKeplerContribution(final T mu) {
  529.             if (superGetOrbitType() == null) {

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

  540.             } else {
  541.                 // propagation uses regular orbits
  542.                 currentState.getOrbit().addKeplerContribution(getPositionAngleType(), mu, yDot);
  543.             }
  544.         }

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

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

  563.     }

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

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

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

  621.         return ToleranceProvider.of(CartesianToleranceProvider.of(dP.getReal(), dV.getReal(),
  622.                 CartesianToleranceProvider.DEFAULT_ABSOLUTE_MASS_TOLERANCE)).getTolerances(orbit, type, PositionAngleType.TRUE);
  623.     }

  624. }