FieldNumericalPropagator.java

  1. /* Copyright 2002-2022 CS GROUP
  2.  * Licensed to CS GROUP (CS) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * CS licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *   http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.orekit.propagation.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.PositionAngle;
  41. import org.orekit.propagation.FieldSpacecraftState;
  42. import org.orekit.propagation.PropagationType;
  43. import org.orekit.propagation.Propagator;
  44. import org.orekit.propagation.events.FieldEventDetector;
  45. import org.orekit.propagation.integration.FieldAbstractIntegratedPropagator;
  46. import org.orekit.propagation.integration.FieldStateMapper;
  47. import org.orekit.time.FieldAbsoluteDate;
  48. import org.orekit.utils.FieldAbsolutePVCoordinates;
  49. import org.orekit.utils.FieldPVCoordinates;
  50. import org.orekit.utils.ParameterDriver;
  51. import org.orekit.utils.ParameterObserver;
  52. import org.orekit.utils.TimeStampedFieldPVCoordinates;

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

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

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

  144.     /** Field used by this class.*/
  145.     private final Field<T> field;

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

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

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

  195.     /** Set the flag to ignore or not the creation of a {@link NewtonianAttraction}.
  196.      * @param ignoreCentralAttraction if true, {@link NewtonianAttraction} is <em>not</em>
  197.      * added automatically if missing
  198.      */
  199.     public void setIgnoreCentralAttraction(final boolean ignoreCentralAttraction) {
  200.         this.ignoreCentralAttraction = ignoreCentralAttraction;
  201.     }

  202.      /** Set the central attraction coefficient μ.
  203.       * <p>
  204.       * Setting the central attraction coefficient is
  205.       * equivalent to {@link #addForceModel(ForceModel) add}
  206.       * a {@link NewtonianAttraction} force model.
  207.       * </p>
  208.      * @param mu central attraction coefficient (m³/s²)
  209.      * @see #addForceModel(ForceModel)
  210.      * @see #getAllForceModels()
  211.      */
  212.     public void setMu(final T mu) {
  213.         if (ignoreCentralAttraction) {
  214.             superSetMu(mu);
  215.         } else {
  216.             addForceModel(new NewtonianAttraction(mu.getReal()));
  217.         }
  218.     }

  219.     /** Set the central attraction coefficient μ only in upper class.
  220.      * @param mu central attraction coefficient (m³/s²)
  221.      */
  222.     private void superSetMu(final T mu) {
  223.         super.setMu(mu);
  224.     }

  225.     /** Check if Newtonian attraction force model is available.
  226.      * <p>
  227.      * Newtonian attraction is always the last force model in the list.
  228.      * </p>
  229.      * @return true if Newtonian attraction force model is available
  230.      */
  231.     private boolean hasNewtonianAttraction() {
  232.         final int last = forceModels.size() - 1;
  233.         return last >= 0 && forceModels.get(last) instanceof NewtonianAttraction;
  234.     }

  235.     /** Add a force model to the global perturbation model.
  236.      * <p>If this method is not called at all, the integrated orbit will follow
  237.      * a Keplerian evolution only.</p>
  238.      * @param model perturbing {@link ForceModel} to add
  239.      * @see #removeForceModels()
  240.      * @see #setMu(CalculusFieldElement)
  241.      */
  242.     public void addForceModel(final ForceModel model) {

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

  245.             try {
  246.                 // ensure we are notified of any mu change
  247.                 model.getParametersDrivers().get(0).addObserver(new ParameterObserver() {
  248.                     /** {@inheritDoc} */
  249.                     @Override
  250.                     public void valueChanged(final double previousValue, final ParameterDriver driver) {
  251.                         superSetMu(field.getZero().add(driver.getValue()));
  252.                     }
  253.                 });
  254.             } catch (OrekitException oe) {
  255.                 // this should never happen
  256.                 throw new OrekitInternalError(oe);
  257.             }

  258.             if (hasNewtonianAttraction()) {
  259.                 // there is already a central attraction model, replace it
  260.                 forceModels.set(forceModels.size() - 1, model);
  261.             } else {
  262.                 // there are no central attraction model yet, add it at the end of the list
  263.                 forceModels.add(model);
  264.             }
  265.         } else {
  266.             // we want to add a perturbing force model
  267.             if (hasNewtonianAttraction()) {
  268.                 // insert the new force model before Newtonian attraction,
  269.                 // which should always be the last one in the list
  270.                 forceModels.add(forceModels.size() - 1, model);
  271.             } else {
  272.                 // we only have perturbing force models up to now, just append at the end of the list
  273.                 forceModels.add(model);
  274.             }
  275.         }

  276.     }

  277.     /** Remove all perturbing force models from the global perturbation model.
  278.      * <p>Once all perturbing forces have been removed (and as long as no new force
  279.      * model is added), the integrated orbit will follow a Keplerian evolution
  280.      * only.</p>
  281.      * @see #addForceModel(ForceModel)
  282.      */
  283.     public void removeForceModels() {
  284.         forceModels.clear();
  285.     }

  286.     /** Get all the force models, perturbing forces and Newtonian attraction included.
  287.      * @return list of perturbing force models, with Newtonian attraction being the
  288.      * last one
  289.      * @see #addForceModel(ForceModel)
  290.      * @see #setMu(CalculusFieldElement)
  291.      * @since 9.1
  292.      */
  293.     public List<ForceModel> getAllForceModels() {
  294.         return Collections.unmodifiableList(forceModels);
  295.     }

  296.     /** Set propagation orbit type.
  297.      * @param orbitType orbit type to use for propagation
  298.      */
  299.     public void setOrbitType(final OrbitType orbitType) {
  300.         super.setOrbitType(orbitType);
  301.     }

  302.     /** Get propagation parameter type.
  303.      * @return orbit type used for propagation
  304.      */
  305.     public OrbitType getOrbitType() {
  306.         return superGetOrbitType();
  307.     }

  308.     /** Get propagation parameter type.
  309.      * @return orbit type used for propagation
  310.      */
  311.     private OrbitType superGetOrbitType() {
  312.         return super.getOrbitType();
  313.     }

  314.     /** Set position angle type.
  315.      * <p>
  316.      * The position parameter type is meaningful only if {@link
  317.      * #getOrbitType() propagation orbit type}
  318.      * support it. As an example, it is not meaningful for propagation
  319.      * in {@link OrbitType#CARTESIAN Cartesian} parameters.
  320.      * </p>
  321.      * @param positionAngleType angle type to use for propagation
  322.      */
  323.     public void setPositionAngleType(final PositionAngle positionAngleType) {
  324.         super.setPositionAngleType(positionAngleType);
  325.     }

  326.     /** Get propagation parameter type.
  327.      * @return angle type to use for propagation
  328.      */
  329.     public PositionAngle getPositionAngleType() {
  330.         return super.getPositionAngleType();
  331.     }

  332.     /** Set the initial state.
  333.      * @param initialState initial state
  334.      */
  335.     public void setInitialState(final FieldSpacecraftState<T> initialState) {
  336.         resetInitialState(initialState);
  337.     }

  338.     /** {@inheritDoc} */
  339.     public void resetInitialState(final FieldSpacecraftState<T> state) {
  340.         super.resetInitialState(state);
  341.         if (!hasNewtonianAttraction()) {
  342.             setMu(state.getMu());
  343.         }
  344.         setStartDate(state.getDate());
  345.     }

  346.     /** {@inheritDoc} */
  347.     public TimeStampedFieldPVCoordinates<T> getPVCoordinates(final FieldAbsoluteDate<T> date, final Frame frame) {
  348.         return propagate(date).getPVCoordinates(frame);
  349.     }

  350.     /** {@inheritDoc} */
  351.     protected FieldStateMapper<T> createMapper(final FieldAbsoluteDate<T> referenceDate, final T mu,
  352.                                        final OrbitType orbitType, final PositionAngle positionAngleType,
  353.                                        final AttitudeProvider attitudeProvider, final Frame frame) {
  354.         return new FieldOsculatingMapper(referenceDate, mu, orbitType, positionAngleType, attitudeProvider, frame);
  355.     }

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

  358.         /** Simple constructor.
  359.          * <p>
  360.          * The position parameter type is meaningful only if {@link
  361.          * #getOrbitType() propagation orbit type}
  362.          * support it. As an example, it is not meaningful for propagation
  363.          * in {@link OrbitType#CARTESIAN Cartesian} parameters.
  364.          * </p>
  365.          * @param referenceDate reference date
  366.          * @param mu central attraction coefficient (m³/s²)
  367.          * @param orbitType orbit type to use for mapping
  368.          * @param positionAngleType angle type to use for propagation
  369.          * @param attitudeProvider attitude provider
  370.          * @param frame inertial frame
  371.          */
  372.         FieldOsculatingMapper(final FieldAbsoluteDate<T> referenceDate, final T mu,
  373.                               final OrbitType orbitType, final PositionAngle positionAngleType,
  374.                               final AttitudeProvider attitudeProvider, final Frame frame) {
  375.             super(referenceDate, mu, orbitType, positionAngleType, attitudeProvider, frame);
  376.         }

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

  381.             final T mass = y[6];
  382.             if (mass.getReal() <= 0.0) {
  383.                 throw new OrekitException(OrekitMessages.SPACECRAFT_MASS_BECOMES_NEGATIVE, mass);
  384.             }

  385.             if (superGetOrbitType() == null) {
  386.                 // propagation uses absolute position-velocity-acceleration
  387.                 final FieldVector3D<T> p = new FieldVector3D<>(y[0],    y[1],    y[2]);
  388.                 final FieldVector3D<T> v = new FieldVector3D<>(y[3],    y[4],    y[5]);
  389.                 final FieldVector3D<T> a;
  390.                 final FieldAbsolutePVCoordinates<T> absPva;
  391.                 if (yDot == null) {
  392.                     absPva = new FieldAbsolutePVCoordinates<>(getFrame(), new TimeStampedFieldPVCoordinates<>(date, p, v, FieldVector3D.getZero(date.getField())));
  393.                 } else {
  394.                     a = new FieldVector3D<>(yDot[3], yDot[4], yDot[5]);
  395.                     absPva = new FieldAbsolutePVCoordinates<>(getFrame(), new TimeStampedFieldPVCoordinates<>(date, p, v, a));
  396.                 }

  397.                 final FieldAttitude<T> attitude = getAttitudeProvider().getAttitude(absPva, date, getFrame());
  398.                 return new FieldSpacecraftState<>(absPva, attitude, mass);
  399.             } else {
  400.                 // propagation uses regular orbits
  401.                 final FieldOrbit<T> orbit       = superGetOrbitType().mapArrayToOrbit(y, yDot, super.getPositionAngleType(), date, getMu(), getFrame());
  402.                 final FieldAttitude<T> attitude = getAttitudeProvider().getAttitude(orbit, date, getFrame());
  403.                 return new FieldSpacecraftState<>(orbit, attitude, mass);
  404.             }
  405.         }

  406.         /** {@inheritDoc} */
  407.         public void mapStateToArray(final FieldSpacecraftState<T> state, final T[] y, final T[] yDot) {
  408.             if (superGetOrbitType() == null) {
  409.                 // propagation uses absolute position-velocity-acceleration
  410.                 final FieldVector3D<T> p = state.getAbsPVA().getPosition();
  411.                 final FieldVector3D<T> v = state.getAbsPVA().getVelocity();
  412.                 y[0] = p.getX();
  413.                 y[1] = p.getY();
  414.                 y[2] = p.getZ();
  415.                 y[3] = v.getX();
  416.                 y[4] = v.getY();
  417.                 y[5] = v.getZ();
  418.                 y[6] = state.getMass();
  419.             }
  420.             else {
  421.                 superGetOrbitType().mapOrbitToArray(state.getOrbit(), super.getPositionAngleType(), y, yDot);
  422.                 y[6] = state.getMass();
  423.             }
  424.         }

  425.     }

  426.     /** {@inheritDoc} */
  427.     protected MainStateEquations<T> getMainStateEquations(final FieldODEIntegrator<T> integrator) {
  428.         return new Main(integrator);
  429.     }

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

  432.         /** Derivatives array. */
  433.         private final T[] yDot;

  434.         /** Current state. */
  435.         private FieldSpacecraftState<T> currentState;

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

  438.         /** Simple constructor.
  439.          * @param integrator numerical integrator to use for propagation.
  440.          */
  441.         Main(final FieldODEIntegrator<T> integrator) {

  442.             this.yDot     = MathArrays.buildArray(getField(),  7);
  443.             this.jacobian = MathArrays.buildArray(getField(),  6, 6);
  444.             for (final ForceModel forceModel : forceModels) {
  445.                 forceModel.getFieldEventsDetectors(getField()).forEach(detector -> setUpEventDetector(integrator, detector));
  446.             }

  447.             if (superGetOrbitType() == null) {
  448.                 // propagation uses absolute position-velocity-acceleration
  449.                 // we can set Jacobian once and for all
  450.                 for (int i = 0; i < jacobian.length; ++i) {
  451.                     Arrays.fill(jacobian[i], getField().getZero());
  452.                     jacobian[i][i] = getField().getOne();
  453.                 }
  454.             }

  455.         }

  456.         /** {@inheritDoc} */
  457.         @Override
  458.         public void init(final FieldSpacecraftState<T> initialState, final FieldAbsoluteDate<T> target) {
  459.             forceModels.forEach(fm -> fm.init(initialState, target));
  460.         }

  461.         /** {@inheritDoc} */
  462.         @Override
  463.         public T[] computeDerivatives(final FieldSpacecraftState<T> state) {
  464.             final T zero = state.getA().getField().getZero();
  465.             currentState = state;
  466.             Arrays.fill(yDot, zero);
  467.             if (superGetOrbitType() != null) {
  468.                 // propagation uses regular orbits
  469.                 currentState.getOrbit().getJacobianWrtCartesian(getPositionAngleType(), jacobian);
  470.             }

  471.             // compute the contributions of all perturbing forces,
  472.             // using the Kepler contribution at the end since
  473.             // NewtonianAttraction is always the last instance in the list
  474.             for (final ForceModel forceModel : forceModels) {
  475.                 forceModel.addContribution(state, this);
  476.             }

  477.             if (superGetOrbitType() == null) {
  478.                 // position derivative is velocity, and was not added above in the force models
  479.                 // (it is added when orbit type is non-null because NewtonianAttraction considers it)
  480.                 final FieldVector3D<T> velocity = currentState.getPVCoordinates().getVelocity();
  481.                 yDot[0] = yDot[0].add(velocity.getX());
  482.                 yDot[1] = yDot[1].add(velocity.getY());
  483.                 yDot[2] = yDot[2].add(velocity.getZ());
  484.             }

  485.             return yDot.clone();

  486.         }

  487.         /** {@inheritDoc} */
  488.         @Override
  489.         public void addKeplerContribution(final T mu) {
  490.             if (superGetOrbitType() == null) {

  491.                 // if mu is neither 0 nor NaN, we want to include Newtonian acceleration
  492.                 if (mu.getReal() > 0) {
  493.                     // velocity derivative is Newtonian acceleration
  494.                     final FieldVector3D<T> position = currentState.getPVCoordinates().getPosition();
  495.                     final T r2         = position.getNormSq();
  496.                     final T coeff      = r2.multiply(r2.sqrt()).reciprocal().negate().multiply(mu);
  497.                     yDot[3] = yDot[3].add(coeff.multiply(position.getX()));
  498.                     yDot[4] = yDot[4].add(coeff.multiply(position.getY()));
  499.                     yDot[5] = yDot[5].add(coeff.multiply(position.getZ()));
  500.                 }

  501.             } else {
  502.                 // propagation uses regular orbits
  503.                 currentState.getOrbit().addKeplerContribution(getPositionAngleType(), mu, yDot);
  504.             }
  505.         }

  506.         /** {@inheritDoc} */
  507.         @Override
  508.         public void addNonKeplerianAcceleration(final FieldVector3D<T> gamma) {
  509.             for (int i = 0; i < 6; ++i) {
  510.                 final T[] jRow = jacobian[i];
  511.                 yDot[i] = yDot[i].add(jRow[3].linearCombination(jRow[3], gamma.getX(),
  512.                                                                 jRow[4], gamma.getY(),
  513.                                                                 jRow[5], gamma.getZ()));
  514.             }
  515.         }

  516.         /** {@inheritDoc} */
  517.         @Override
  518.         public void addMassDerivative(final T q) {
  519.             if (q.getReal() > 0) {
  520.                 throw new OrekitIllegalArgumentException(OrekitMessages.POSITIVE_FLOW_RATE, q);
  521.             }
  522.             yDot[6] = yDot[6].add(q);
  523.         }

  524.     }

  525.     /** Estimate tolerance vectors for integrators.
  526.      * <p>
  527.      * The errors are estimated from partial derivatives properties of orbits,
  528.      * starting from a scalar position error specified by the user.
  529.      * Considering the energy conservation equation V = sqrt(mu (2/r - 1/a)),
  530.      * we get at constant energy (i.e. on a Keplerian trajectory):
  531.      * <pre>
  532.      * V² r |dV| = mu |dr|
  533.      * </pre>
  534.      * So we deduce a scalar velocity error consistent with the position error.
  535.      * From here, we apply orbits Jacobians matrices to get consistent errors
  536.      * on orbital parameters.
  537.      * <p>
  538.      * The tolerances are only <em>orders of magnitude</em>, and integrator tolerances
  539.      * are only local estimates, not global ones. So some care must be taken when using
  540.      * these tolerances. Setting 1mm as a position error does NOT mean the tolerances
  541.      * will guarantee a 1mm error position after several orbits integration.
  542.      * </p>
  543.      * @param dP user specified position error
  544.      * @param orbit reference orbit
  545.      * @param type propagation type for the meaning of the tolerance vectors elements
  546.      * (it may be different from {@code orbit.getType()})
  547.      * @return a two rows array, row 0 being the absolute tolerance error and row 1
  548.      * being the relative tolerance error
  549.      * @param <T> elements type
  550.      */
  551.     public static <T extends CalculusFieldElement<T>> double[][] tolerances(final T dP, final FieldOrbit<T> orbit, final OrbitType type) {

  552.         // estimate the scalar velocity error
  553.         final FieldPVCoordinates<T> pv = orbit.getPVCoordinates();
  554.         final T r2 = pv.getPosition().getNormSq();
  555.         final T v  = pv.getVelocity().getNorm();
  556.         final T dV = dP.multiply(orbit.getMu()).divide(v.multiply(r2));

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

  558.     }

  559.     /** Estimate tolerance vectors for integrators when propagating in orbits.
  560.      * <p>
  561.      * The errors are estimated from partial derivatives properties of orbits,
  562.      * starting from scalar position and velocity errors specified by the user.
  563.      * <p>
  564.      * The tolerances are only <em>orders of magnitude</em>, and integrator tolerances
  565.      * are only local estimates, not global ones. So some care must be taken when using
  566.      * these tolerances. Setting 1mm as a position error does NOT mean the tolerances
  567.      * will guarantee a 1mm error position after several orbits integration.
  568.      * </p>
  569.      * @param <T> elements type
  570.      * @param dP user specified position error
  571.      * @param dV user specified velocity error
  572.      * @param orbit reference orbit
  573.      * @param type propagation type for the meaning of the tolerance vectors elements
  574.      * (it may be different from {@code orbit.getType()})
  575.      * @return a two rows array, row 0 being the absolute tolerance error and row 1
  576.      * being the relative tolerance error
  577.      * @since 10.3
  578.      */
  579.     public static <T extends CalculusFieldElement<T>> double[][] tolerances(final T dP, final T dV,
  580.                                                                         final FieldOrbit<T> orbit, final OrbitType type) {

  581.         final double[] absTol = new double[7];
  582.         final double[] relTol = new double[7];

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

  586.         if (type == OrbitType.CARTESIAN) {
  587.             absTol[0] = dP.getReal();
  588.             absTol[1] = dP.getReal();
  589.             absTol[2] = dP.getReal();
  590.             absTol[3] = dV.getReal();
  591.             absTol[4] = dV.getReal();
  592.             absTol[5] = dV.getReal();
  593.         } else {

  594.             // convert the orbit to the desired type
  595.             final T[][] jacobian = MathArrays.buildArray(dP.getField(), 6, 6);
  596.             final FieldOrbit<T> converted = type.convertType(orbit);
  597.             converted.getJacobianWrtCartesian(PositionAngle.TRUE, jacobian);

  598.             for (int i = 0; i < 6; ++i) {
  599.                 final  T[] row = jacobian[i];
  600.                 absTol[i] =     row[0].abs().multiply(dP).
  601.                             add(row[1].abs().multiply(dP)).
  602.                             add(row[2].abs().multiply(dP)).
  603.                             add(row[3].abs().multiply(dV)).
  604.                             add(row[4].abs().multiply(dV)).
  605.                             add(row[5].abs().multiply(dV)).
  606.                             getReal();
  607.                 if (Double.isNaN(absTol[i])) {
  608.                     throw new OrekitException(OrekitMessages.SINGULAR_JACOBIAN_FOR_ORBIT_TYPE, type);
  609.                 }
  610.             }

  611.         }

  612.         Arrays.fill(relTol, dP.divide(orbit.getPVCoordinates().getPosition().getNormSq().sqrt()).getReal());

  613.         return new double[][] { absTol, relTol };

  614.     }

  615. }