FieldNumericalPropagator.java

  1. /* Copyright 2002-2020 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.Field;
  23. import org.hipparchus.RealFieldElement;
  24. import org.hipparchus.geometry.euclidean.threed.FieldVector3D;
  25. import org.hipparchus.ode.FieldODEIntegrator;
  26. import org.hipparchus.util.FastMath;
  27. import org.hipparchus.util.MathArrays;
  28. import org.orekit.annotation.DefaultDataContext;
  29. import org.orekit.attitudes.AttitudeProvider;
  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.PositionAngle;
  42. import org.orekit.propagation.FieldSpacecraftState;
  43. import org.orekit.propagation.PropagationType;
  44. import org.orekit.propagation.Propagator;
  45. import org.orekit.propagation.SpacecraftState;
  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.FieldPVCoordinates;
  53. import org.orekit.utils.ParameterDriver;
  54. import org.orekit.utils.ParameterObserver;
  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(RealFieldElement)})</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 PositionAngle type} of position angle to be used in orbital parameters
  75.  *   to be used for propagation where it is relevant ({@link
  76.  *   #setPositionAngleType(PositionAngle)}),
  77.  *   <li>whether {@link org.orekit.propagation.integration.FieldAdditionalEquations additional equations}
  78.  *   should be propagated along with orbital state
  79.  *   ({@link #addAdditionalEquations(org.orekit.propagation.integration.FieldAdditionalEquations)}),
  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 #setSlaveMode()},
  84.  *   {@link #setMasterMode(RealFieldElement, org.orekit.propagation.sampling.FieldOrekitFixedStepHandler)},
  85.  *   {@link #setMasterMode(org.orekit.propagation.sampling.FieldOrekitStepHandler)},
  86.  *   {@link #setEphemerisMode()}, {@link #getGeneratedEphemeris()})</li>
  87.  * </ul>
  88.  * <p>From these configuration parameters, only the initial state is mandatory. The default
  89.  * propagation settings are in {@link OrbitType#EQUINOCTIAL equinoctial} parameters with
  90.  * {@link PositionAngle#TRUE true} longitude argument. If the central attraction coefficient
  91.  * is not explicitly specified, the one used to define the initial orbit will be used.
  92.  * However, specifying only the initial state and perhaps the central attraction coefficient
  93.  * would mean the propagator would use only Keplerian forces. In this case, the simpler {@link
  94.  * org.orekit.propagation.analytical.KeplerianPropagator KeplerianPropagator} class would
  95.  * perhaps be more effective.</p>
  96.  * <p>The underlying numerical integrator set up in the constructor may also have its own
  97.  * configuration parameters. Typical configuration parameters for adaptive stepsize integrators
  98.  * are the min, max and perhaps start step size as well as the absolute and/or relative errors
  99.  * thresholds.</p>
  100.  * <p>The state that is seen by the integrator is a simple seven elements double array.
  101.  * The six first elements are either:
  102.  * <ul>
  103.  *   <li>the {@link org.orekit.orbits.FieldEquinoctialOrbit equinoctial orbit parameters} (a, e<sub>x</sub>,
  104.  *   e<sub>y</sub>, h<sub>x</sub>, h<sub>y</sub>, λ<sub>M</sub> or λ<sub>E</sub>
  105.  *   or λ<sub>v</sub>) in meters and radians,</li>
  106.  *   <li>the {@link org.orekit.orbits.FieldKeplerianOrbit Keplerian orbit parameters} (a, e, i, ω, Ω,
  107.  *   M or E or v) in meters and radians,</li>
  108.  *   <li>the {@link org.orekit.orbits.FieldCircularOrbit circular orbit parameters} (a, e<sub>x</sub>, e<sub>y</sub>, i,
  109.  *   Ω, α<sub>M</sub> or α<sub>E</sub> or α<sub>v</sub>) in meters
  110.  *   and radians,</li>
  111.  *   <li>the {@link org.orekit.orbits.FieldCartesianOrbit Cartesian orbit parameters} (x, y, z, v<sub>x</sub>,
  112.  *   v<sub>y</sub>, v<sub>z</sub>) in meters and meters per seconds.
  113.  * </ul>
  114.  * The last element is the mass in kilograms.
  115.  * <p>The following code snippet shows a typical setting for Low Earth Orbit propagation in
  116.  * equinoctial parameters and true longitude argument:</p>
  117.  * <pre>
  118.  * final T          zero      = field.getZero();
  119.  * final T          dP        = zero.add(0.001);
  120.  * final T          minStep   = zero.add(0.001);
  121.  * final T          maxStep   = zero.add(500);
  122.  * final T          initStep  = zero.add(60);
  123.  * final double[][] tolerance = FieldNumericalPropagator.tolerances(dP, orbit, OrbitType.EQUINOCTIAL);
  124.  * AdaptiveStepsizeFieldIntegrator&lt;T&gt; integrator = new DormandPrince853FieldIntegrator&lt;&gt;(field, minStep, maxStep, tolerance[0], tolerance[1]);
  125.  * integrator.setInitialStepSize(initStep);
  126.  * propagator = new FieldNumericalPropagator&lt;&gt;(field, integrator);
  127.  * </pre>
  128.  * <p>By default, at the end of the propagation, the propagator resets the initial state to the final state,
  129.  * thus allowing a new propagation to be started from there without recomputing the part already performed.
  130.  * This behaviour can be chenged by calling {@link #setResetAtEnd(boolean)}.
  131.  * </p>
  132.  * <p>Beware the same instance cannot be used simultaneously by different threads, the class is <em>not</em>
  133.  * thread-safe.</p>

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

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

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

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

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

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

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

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

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

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

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

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

  251.             try {
  252.                 // ensure we are notified of any mu change
  253.                 model.getParametersDrivers()[0].addObserver(new ParameterObserver() {
  254.                     /** {@inheritDoc} */
  255.                     @Override
  256.                     public void valueChanged(final double previousValue, final ParameterDriver driver) {
  257.                         superSetMu(field.getZero().add(driver.getValue()));
  258.                     }
  259.                 });
  260.             } catch (OrekitException oe) {
  261.                 // this should never happen
  262.                 throw new OrekitInternalError(oe);
  263.             }

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

  282.     }

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

  292.     /** Get all the force models, perturbing forces and Newtonian attraction included.
  293.      * @return list of perturbing force models, with Newtonian attraction being the
  294.      * last one
  295.      * @see #addForceModel(ForceModel)
  296.      * @see #setMu(RealFieldElement)
  297.      * @since 9.1
  298.      */
  299.     public List<ForceModel> getAllForceModels() {
  300.         return Collections.unmodifiableList(forceModels);
  301.     }

  302.     /** Set propagation orbit type.
  303.      * @param orbitType orbit type to use for propagation
  304.      */
  305.     public void setOrbitType(final OrbitType orbitType) {
  306.         super.setOrbitType(orbitType);
  307.     }

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

  314.     /** Get propagation parameter type.
  315.      * @return orbit type used for propagation
  316.      */
  317.     private OrbitType superGetOrbitType() {
  318.         return super.getOrbitType();
  319.     }

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

  332.     /** Get propagation parameter type.
  333.      * @return angle type to use for propagation
  334.      */
  335.     public PositionAngle getPositionAngleType() {
  336.         return super.getPositionAngleType();
  337.     }

  338.     /** Set the initial state.
  339.      * @param initialState initial state
  340.      */
  341.     public void setInitialState(final FieldSpacecraftState<T> initialState) {
  342.         resetInitialState(initialState);
  343.     }

  344.     /** {@inheritDoc} */
  345.     public void resetInitialState(final FieldSpacecraftState<T> state) {
  346.         super.resetInitialState(state);
  347.         if (!hasNewtonianAttraction()) {
  348.             setMu(state.getMu());
  349.         }
  350.         setStartDate(state.getDate());
  351.     }

  352.     /** {@inheritDoc} */
  353.     public TimeStampedFieldPVCoordinates<T> getPVCoordinates(final FieldAbsoluteDate<T> date, final Frame frame) {
  354.         return propagate(date).getPVCoordinates(frame);
  355.     }

  356.     /** {@inheritDoc} */
  357.     protected FieldStateMapper<T> createMapper(final FieldAbsoluteDate<T> referenceDate, final T mu,
  358.                                        final OrbitType orbitType, final PositionAngle positionAngleType,
  359.                                        final AttitudeProvider attitudeProvider, final Frame frame) {
  360.         return new FieldOsculatingMapper(referenceDate, mu, orbitType, positionAngleType, attitudeProvider, frame);
  361.     }

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

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

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

  387.             final T mass = y[6];
  388.             if (mass.getReal() <= 0.0) {
  389.                 throw new OrekitException(OrekitMessages.SPACECRAFT_MASS_BECOMES_NEGATIVE, mass);
  390.             }

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

  403.                 final FieldAttitude<T> attitude = getAttitudeProvider().getAttitude(absPva, date, getFrame());
  404.                 return new FieldSpacecraftState<>(absPva, attitude, mass);
  405.             } else {
  406.                 // propagation uses regular orbits
  407.                 final FieldOrbit<T> orbit       = superGetOrbitType().mapArrayToOrbit(y, yDot, super.getPositionAngleType(), date, getMu(), getFrame());
  408.                 final FieldAttitude<T> attitude = getAttitudeProvider().getAttitude(orbit, date, getFrame());
  409.                 return new FieldSpacecraftState<>(orbit, attitude, mass);
  410.             }
  411.         }

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

  431.     }

  432.     /** {@inheritDoc} */
  433.     protected MainStateEquations<T> getMainStateEquations(final FieldODEIntegrator<T> integrator) {
  434.         return new Main(integrator);
  435.     }

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

  438.         /** Derivatives array. */
  439.         private final T[] yDot;

  440.         /** Current state. */
  441.         private FieldSpacecraftState<T> currentState;

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

  444.         /** Simple constructor.
  445.          * @param integrator numerical integrator to use for propagation.
  446.          */
  447.         Main(final FieldODEIntegrator<T> integrator) {

  448.             this.yDot     = MathArrays.buildArray(getField(),  7);
  449.             this.jacobian = MathArrays.buildArray(getField(),  6, 6);
  450.             for (final ForceModel forceModel : forceModels) {
  451.                 forceModel.getFieldEventsDetectors(getField()).forEach(detector -> setUpEventDetector(integrator, detector));
  452.             }

  453.             if (superGetOrbitType() == null) {
  454.                 // propagation uses absolute position-velocity-acceleration
  455.                 // we can set Jacobian once and for all
  456.                 for (int i = 0; i < jacobian.length; ++i) {
  457.                     Arrays.fill(jacobian[i], getField().getZero());
  458.                     jacobian[i][i] = getField().getOne();
  459.                 }
  460.             }

  461.         }

  462.         /** {@inheritDoc} */
  463.         @Override
  464.         public void init(final FieldSpacecraftState<T> initialState, final FieldAbsoluteDate<T> target) {
  465.             final SpacecraftState stateD  = initialState.toSpacecraftState();
  466.             final AbsoluteDate    targetD = target.toAbsoluteDate();
  467.             for (final ForceModel forceModel : forceModels) {
  468.                 forceModel.init(stateD, targetD);
  469.             }
  470.         }

  471.         /** {@inheritDoc} */
  472.         @Override
  473.         public T[] computeDerivatives(final FieldSpacecraftState<T> state) {
  474.             final T zero = state.getA().getField().getZero();
  475.             currentState = state;
  476.             Arrays.fill(yDot, zero);
  477.             if (superGetOrbitType() != null) {
  478.                 // propagation uses regular orbits
  479.                 currentState.getOrbit().getJacobianWrtCartesian(getPositionAngleType(), jacobian);
  480.             }

  481.             // compute the contributions of all perturbing forces,
  482.             // using the Kepler contribution at the end since
  483.             // NewtonianAttraction is always the last instance in the list
  484.             for (final ForceModel forceModel : forceModels) {
  485.                 forceModel.addContribution(state, this);
  486.             }

  487.             if (superGetOrbitType() == null) {
  488.                 // position derivative is velocity, and was not added above in the force models
  489.                 // (it is added when orbit type is non-null because NewtonianAttraction considers it)
  490.                 final FieldVector3D<T> velocity = currentState.getPVCoordinates().getVelocity();
  491.                 yDot[0] = yDot[0].add(velocity.getX());
  492.                 yDot[1] = yDot[1].add(velocity.getY());
  493.                 yDot[2] = yDot[2].add(velocity.getZ());
  494.             }

  495.             return yDot.clone();

  496.         }

  497.         /** {@inheritDoc} */
  498.         @Override
  499.         public void addKeplerContribution(final T mu) {
  500.             if (superGetOrbitType() == null) {

  501.                 // if mu is neither 0 nor NaN, we want to include Newtonian acceleration
  502.                 if (mu.getReal() > 0) {
  503.                     // velocity derivative is Newtonian acceleration
  504.                     final FieldVector3D<T> position = currentState.getPVCoordinates().getPosition();
  505.                     final double r2         = position.getNormSq().getReal();
  506.                     final double coeff      = -mu.getReal() / (r2 * FastMath.sqrt(r2));
  507.                     yDot[3] = yDot[3].add(coeff * position.getX().getReal());
  508.                     yDot[4] = yDot[4].add(coeff * position.getY().getReal());
  509.                     yDot[5] = yDot[5].add(coeff * position.getZ().getReal());
  510.                 }

  511.             } else {
  512.                 // propagation uses regular orbits
  513.                 currentState.getOrbit().addKeplerContribution(getPositionAngleType(), mu, yDot);
  514.             }
  515.         }

  516.         /** {@inheritDoc} */
  517.         @Override
  518.         public void addNonKeplerianAcceleration(final FieldVector3D<T> gamma) {
  519.             for (int i = 0; i < 6; ++i) {
  520.                 final T[] jRow = jacobian[i];
  521.                 yDot[i] = yDot[i].add(jRow[3].linearCombination(jRow[3], gamma.getX(),
  522.                                                                 jRow[4], gamma.getY(),
  523.                                                                 jRow[5], gamma.getZ()));
  524.             }
  525.         }

  526.         /** {@inheritDoc} */
  527.         @Override
  528.         public void addMassDerivative(final T q) {
  529.             if (q.getReal() > 0) {
  530.                 throw new OrekitIllegalArgumentException(OrekitMessages.POSITIVE_FLOW_RATE, q);
  531.             }
  532.             yDot[6] = yDot[6].add(q);
  533.         }

  534.     }

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

  562.         // estimate the scalar velocity error
  563.         final FieldPVCoordinates<T> pv = orbit.getPVCoordinates();
  564.         final T r2 = pv.getPosition().getNormSq();
  565.         final T v  = pv.getVelocity().getNorm();
  566.         final T dV = dP.multiply(orbit.getMu()).divide(v.multiply(r2));

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

  568.     }

  569.     /** Estimate tolerance vectors for integrators when propagating in orbits.
  570.      * <p>
  571.      * The errors are estimated from partial derivatives properties of orbits,
  572.      * starting from scalar position and velocity errors specified by the user.
  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 <T> elements type
  580.      * @param dP user specified position error
  581.      * @param dV user specified velocity error
  582.      * @param orbit reference orbit
  583.      * @param type propagation type for the meaning of the tolerance vectors elements
  584.      * (it may be different from {@code orbit.getType()})
  585.      * @return a two rows array, row 0 being the absolute tolerance error and row 1
  586.      * being the relative tolerance error
  587.      * @since 10.3
  588.      */
  589.     public static <T extends RealFieldElement<T>> double[][] tolerances(final T dP, final T dV,
  590.                                                                         final FieldOrbit<T> orbit, final OrbitType type) {

  591.         final double[] absTol = new double[7];
  592.         final double[] relTol = new double[7];

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

  596.         if (type == OrbitType.CARTESIAN) {
  597.             absTol[0] = dP.getReal();
  598.             absTol[1] = dP.getReal();
  599.             absTol[2] = dP.getReal();
  600.             absTol[3] = dV.getReal();
  601.             absTol[4] = dV.getReal();
  602.             absTol[5] = dV.getReal();
  603.         } else {

  604.             // convert the orbit to the desired type
  605.             final T[][] jacobian = MathArrays.buildArray(dP.getField(), 6, 6);
  606.             final FieldOrbit<T> converted = type.convertType(orbit);
  607.             converted.getJacobianWrtCartesian(PositionAngle.TRUE, jacobian);

  608.             for (int i = 0; i < 6; ++i) {
  609.                 final  T[] row = jacobian[i];
  610.                 absTol[i] =     row[0].abs().multiply(dP).
  611.                             add(row[1].abs().multiply(dP)).
  612.                             add(row[2].abs().multiply(dP)).
  613.                             add(row[3].abs().multiply(dV)).
  614.                             add(row[4].abs().multiply(dV)).
  615.                             add(row[5].abs().multiply(dV)).
  616.                             getReal();
  617.                 if (Double.isNaN(absTol[i])) {
  618.                     throw new OrekitException(OrekitMessages.SINGULAR_JACOBIAN_FOR_ORBIT_TYPE, type);
  619.                 }
  620.             }

  621.         }

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

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

  624.     }

  625. }