FieldNumericalPropagator.java

  1. /* Copyright 2002-2018 CS Systèmes d'Information
  2.  * Licensed to CS Systèmes d'Information (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.MathArrays;
  27. import org.orekit.attitudes.AttitudeProvider;
  28. import org.orekit.attitudes.FieldAttitude;
  29. import org.orekit.errors.OrekitException;
  30. import org.orekit.errors.OrekitIllegalArgumentException;
  31. import org.orekit.errors.OrekitInternalError;
  32. import org.orekit.errors.OrekitMessages;
  33. import org.orekit.forces.ForceModel;
  34. import org.orekit.forces.gravity.NewtonianAttraction;
  35. import org.orekit.frames.Frame;
  36. import org.orekit.orbits.FieldOrbit;
  37. import org.orekit.orbits.OrbitType;
  38. import org.orekit.orbits.PositionAngle;
  39. import org.orekit.propagation.FieldSpacecraftState;
  40. import org.orekit.propagation.SpacecraftState;
  41. import org.orekit.propagation.events.FieldEventDetector;
  42. import org.orekit.propagation.integration.FieldAbstractIntegratedPropagator;
  43. import org.orekit.propagation.integration.FieldStateMapper;
  44. import org.orekit.time.AbsoluteDate;
  45. import org.orekit.time.FieldAbsoluteDate;
  46. import org.orekit.utils.FieldPVCoordinates;
  47. import org.orekit.utils.ParameterDriver;
  48. import org.orekit.utils.ParameterObserver;
  49. import org.orekit.utils.TimeStampedFieldPVCoordinates;

  50. /** This class propagates {@link org.orekit.orbits.FieldOrbit orbits} using
  51.  * numerical integration.
  52.  * <p>Numerical propagation is much more accurate than analytical propagation
  53.  * like for example {@link org.orekit.propagation.analytical.KeplerianPropagator
  54.  * Keplerian} or {@link org.orekit.propagation.analytical.EcksteinHechlerPropagator
  55.  * Eckstein-Hechler}, but requires a few more steps to set up to be used properly.
  56.  * Whereas analytical propagators are configured only thanks to their various
  57.  * constructors and can be used immediately after construction, numerical propagators
  58.  * configuration involve setting several parameters between construction time
  59.  * and propagation time.</p>
  60.  * <p>The configuration parameters that can be set are:</p>
  61.  * <ul>
  62.  *   <li>the initial spacecraft state ({@link #setInitialState(FieldSpacecraftState)})</li>
  63.  *   <li>the central attraction coefficient ({@link #setMu(double)})</li>
  64.  *   <li>the various force models ({@link #addForceModel(ForceModel)},
  65.  *   {@link #removeForceModels()})</li>
  66.  *   <li>the {@link OrbitType type} of orbital parameters to be used for propagation
  67.  *   ({@link #setOrbitType(OrbitType)}),
  68.  *   <li>the {@link PositionAngle type} of position angle to be used in orbital parameters
  69.  *   to be used for propagation where it is relevant ({@link
  70.  *   #setPositionAngleType(PositionAngle)}),
  71.  *   <li>whether {@link org.orekit.propagation.integration.FieldAdditionalEquations additional equations}
  72.  *   should be propagated along with orbital state
  73.  *   ({@link #addAdditionalEquations(org.orekit.propagation.integration.FieldAdditionalEquations)}),
  74.  *   <li>the discrete events that should be triggered during propagation
  75.  *   ({@link #addEventDetector(FieldEventDetector)},
  76.  *   {@link #clearEventsDetectors()})</li>
  77.  *   <li>the binding logic with the rest of the application ({@link #setSlaveMode()},
  78.  *   {@link #setMasterMode(RealFieldElement, org.orekit.propagation.sampling.FieldOrekitFixedStepHandler)},
  79.  *   {@link #setMasterMode(org.orekit.propagation.sampling.FieldOrekitStepHandler)},
  80.  *   {@link #setEphemerisMode()}, {@link #getGeneratedEphemeris()})</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>
  110.  * <p>The following code snippet shows a typical setting for Low Earth Orbit propagation in
  111.  * equinoctial parameters and true longitude argument:</p>
  112.  * <pre>
  113.  * final T          zero      = field.getZero();
  114.  * final T          dP        = zero.add(0.001);
  115.  * final T          minStep   = zero.add(0.001);
  116.  * final T          maxStep   = zero.add(500);
  117.  * final T          initStep  = zero.add(60);
  118.  * final double[][] tolerance = FieldNumericalPropagator.tolerances(dP, orbit, OrbitType.EQUINOCTIAL);
  119.  * AdaptiveStepsizeFieldIntegrator<T> integrator = new DormandPrince853FieldIntegrator<>(field, minStep, maxStep, tolerance[0], tolerance[1]);
  120.  * integrator.setInitialStepSize(initStep);
  121.  * propagator = new FieldNumericalPropagator<>(field, integrator);
  122.  * </pre>
  123.  * <p>By default, at the end of the propagation, the propagator resets the initial state to the final state,
  124.  * thus allowing a new propagation to be started from there without recomputing the part already performed.
  125.  * This behaviour can be chenged by calling {@link #setResetAtEnd(boolean)}.
  126.  * </p>
  127.  * <p>Beware the same instance cannot be used simultaneously by different threads, the class is <em>not</em>
  128.  * thread-safe.</p>

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

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

  145.     /** Create a new instance of NumericalPropagator, based on orbit definition mu.
  146.      * After creation, the instance is empty, i.e. the attitude provider is set to an
  147.      * unspecified default law and there are no perturbing forces at all.
  148.      * This means that if {@link #addForceModel addForceModel} is not
  149.      * called after creation, the integrated orbit will follow a Keplerian
  150.      * evolution only. The defaults are {@link OrbitType#EQUINOCTIAL}
  151.      * for {@link #setOrbitType(OrbitType) propagation
  152.      * orbit type} and {@link PositionAngle#TRUE} for {@link
  153.      * #setPositionAngleType(PositionAngle) position angle type}.
  154.      * @param integrator numerical integrator to use for propagation.
  155.      * @param field Field used by default
  156.      */
  157.     public FieldNumericalPropagator(final Field<T> field, final FieldODEIntegrator<T> integrator) {
  158.         super(field, integrator, true);
  159.         forceModels = new ArrayList<ForceModel>();
  160.         initMapper();
  161.         setAttitudeProvider(DEFAULT_LAW);
  162.         setMu(Double.NaN);
  163.         setSlaveMode();
  164.         setOrbitType(OrbitType.EQUINOCTIAL);
  165.         setPositionAngleType(PositionAngle.TRUE);
  166.     }

  167.      /** Set the central attraction coefficient μ.
  168.      * @param mu central attraction coefficient (m³/s²)
  169.      * @see #addForceModel(ForceModel)
  170.      */
  171.     public void setMu(final double mu) {
  172.         addForceModel(new NewtonianAttraction(mu));
  173.     }

  174.     /** Set the central attraction coefficient μ only in upper class.
  175.      * @param mu central attraction coefficient (m³/s²)
  176.      */
  177.     private void superSetMu(final double mu) {
  178.         super.setMu(mu);
  179.     }

  180.     /** Check if Newtonian attraction force model is available.
  181.      * <p>
  182.      * Newtonian attraction is always the last force model in the list.
  183.      * </p>
  184.      * @return true if Newtonian attraction force model is available
  185.      */
  186.     private boolean hasNewtonianAttraction() {
  187.         final int last = forceModels.size() - 1;
  188.         return last >= 0 && forceModels.get(last) instanceof NewtonianAttraction;
  189.     }

  190.     /** Add a force model to the global perturbation model.
  191.      * <p>If this method is not called at all, the integrated orbit will follow
  192.      * a Keplerian evolution only.</p>
  193.      * @param model perturbing {@link ForceModel} to add
  194.      * @see #removeForceModels()
  195.      * @see #setMu(double)
  196.      */
  197.     public void addForceModel(final ForceModel model) {

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

  200.             try {
  201.                 // ensure we are notified of any mu change
  202.                 model.getParametersDrivers()[0].addObserver(new ParameterObserver() {
  203.                     /** {@inheritDoc} */
  204.                     @Override
  205.                     public void valueChanged(final double previousValue, final ParameterDriver driver) {
  206.                         superSetMu(driver.getValue());
  207.                     }
  208.                 });
  209.             } catch (OrekitException oe) {
  210.                 // this should never happen
  211.                 throw new OrekitInternalError(oe);
  212.             }

  213.             if (hasNewtonianAttraction()) {
  214.                 // there is already a central attraction model, replace it
  215.                 forceModels.set(forceModels.size() - 1, model);
  216.             } else {
  217.                 // there are no central attraction model yet, add it at the end of the list
  218.                 forceModels.add(model);
  219.             }
  220.         } else {
  221.             // we want to add a perturbing force model
  222.             if (hasNewtonianAttraction()) {
  223.                 // insert the new force model before Newtonian attraction,
  224.                 // which should always be the last one in the list
  225.                 forceModels.add(forceModels.size() - 1, model);
  226.             } else {
  227.                 // we only have perturbing force models up to now, just append at the end of the list
  228.                 forceModels.add(model);
  229.             }
  230.         }

  231.     }

  232.     /** Remove all perturbing force models from the global perturbation model.
  233.      * <p>Once all perturbing forces have been removed (and as long as no new force
  234.      * model is added), the integrated orbit will follow a Keplerian evolution
  235.      * only.</p>
  236.      * @see #addForceModel(ForceModel)
  237.      */
  238.     public void removeForceModels() {
  239.         forceModels.clear();
  240.     }

  241.     /** Get all the force models, perturbing forces and Newtonian attraction included.
  242.      * @return list of perturbing force models, with Newtonian attraction being the
  243.      * last one
  244.      * @see #addForceModel(ForceModel)
  245.      * @see #setMu(double)
  246.      * @since 9.1
  247.      */
  248.     public List<ForceModel> getAllForceModels() {
  249.         return Collections.unmodifiableList(forceModels);
  250.     }

  251.     /** Get perturbing force models list.
  252.      * @return list of perturbing force models
  253.      * @deprecated as of 9.1, this method is deprecated, the perturbing
  254.      * force models are retrieved together with the Newtonian attraction
  255.      * by calling {@link #getAllForceModels()}
  256.      */
  257.     @Deprecated
  258.     public List<ForceModel> getForceModels() {
  259.         return hasNewtonianAttraction() ? forceModels.subList(0, forceModels.size() - 1) : forceModels;
  260.     }

  261.     /** Get the Newtonian attraction from the central body force model.
  262.      * @return Newtonian attraction force model
  263.      * @deprecated as of 9.1, this method is deprecated, the Newtonian
  264.      * attraction force model (if any) is the last in the {@link #getAllForceModels()}
  265.      */
  266.     @Deprecated
  267.     public NewtonianAttraction getNewtonianAttractionForceModel() {
  268.         final int last = forceModels.size() - 1;
  269.         if (last >= 0 && forceModels.get(last) instanceof NewtonianAttraction) {
  270.             return (NewtonianAttraction) forceModels.get(last);
  271.         } else {
  272.             return null;
  273.         }
  274.     }

  275.     /** Set propagation orbit type.
  276.      * @param orbitType orbit type to use for propagation
  277.      */
  278.     public void setOrbitType(final OrbitType orbitType) {
  279.         super.setOrbitType(orbitType);
  280.     }

  281.     /** Get propagation parameter type.
  282.      * @return orbit type used for propagation
  283.      */
  284.     public OrbitType getOrbitType() {
  285.         return super.getOrbitType();
  286.     }

  287.     /** Set position angle type.
  288.      * <p>
  289.      * The position parameter type is meaningful only if {@link
  290.      * #getOrbitType() propagation orbit type}
  291.      * support it. As an example, it is not meaningful for propagation
  292.      * in {@link OrbitType#CARTESIAN Cartesian} parameters.
  293.      * </p>
  294.      * @param positionAngleType angle type to use for propagation
  295.      */
  296.     public void setPositionAngleType(final PositionAngle positionAngleType) {
  297.         super.setPositionAngleType(positionAngleType);
  298.     }

  299.     /** Get propagation parameter type.
  300.      * @return angle type to use for propagation
  301.      */
  302.     public PositionAngle getPositionAngleType() {
  303.         return super.getPositionAngleType();
  304.     }

  305.     /** Set the initial state.
  306.      * @param initialState initial state
  307.      * @exception OrekitException if initial state cannot be set
  308.      */
  309.     public void setInitialState(final FieldSpacecraftState<T> initialState) throws OrekitException {
  310.         resetInitialState(initialState);
  311.     }

  312.     /** {@inheritDoc} */
  313.     public void resetInitialState(final FieldSpacecraftState<T> state) throws OrekitException {
  314.         super.resetInitialState(state);
  315.         if (!hasNewtonianAttraction()) {
  316.             setMu(state.getMu());
  317.         }
  318.         setStartDate(state.getDate());
  319.     }

  320.     /** {@inheritDoc} */
  321.     public TimeStampedFieldPVCoordinates<T> getPVCoordinates(final FieldAbsoluteDate<T> date, final Frame frame)
  322.         throws OrekitException {
  323.         return propagate(date).getPVCoordinates(frame);
  324.     }

  325.     /** {@inheritDoc} */
  326.     protected FieldStateMapper<T> createMapper(final FieldAbsoluteDate<T> referenceDate, final double mu,
  327.                                        final OrbitType orbitType, final PositionAngle positionAngleType,
  328.                                        final AttitudeProvider attitudeProvider, final Frame frame) {
  329.         return new FieldOsculatingMapper(referenceDate, mu, orbitType, positionAngleType, attitudeProvider, frame);
  330.     }

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

  333.         /** Simple constructor.
  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 referenceDate reference date
  341.          * @param mu central attraction coefficient (m³/s²)
  342.          * @param orbitType orbit type to use for mapping
  343.          * @param positionAngleType angle type to use for propagation
  344.          * @param attitudeProvider attitude provider
  345.          * @param frame inertial frame
  346.          */
  347.         FieldOsculatingMapper(final FieldAbsoluteDate<T> referenceDate, final double mu,
  348.                               final OrbitType orbitType, final PositionAngle positionAngleType,
  349.                               final AttitudeProvider attitudeProvider, final Frame frame) {
  350.             super(referenceDate, mu, orbitType, positionAngleType, attitudeProvider, frame);
  351.         }

  352.         /** {@inheritDoc} */
  353.         public FieldSpacecraftState<T> mapArrayToState(final FieldAbsoluteDate<T> date, final T[] y, final T[] yDot,
  354.                                                        final boolean meanOnly)
  355.             throws OrekitException {
  356.             // the parameter meanOnly is ignored for the Numerical Propagator

  357.             final T mass = y[6];
  358.             if (mass.getReal() <= 0.0) {
  359.                 throw new OrekitException(OrekitMessages.SPACECRAFT_MASS_BECOMES_NEGATIVE, mass);
  360.             }
  361.             final FieldOrbit<T> orbit       = super.getOrbitType().mapArrayToOrbit(y, yDot, super.getPositionAngleType(), date, getMu(), getFrame());
  362.             final FieldAttitude<T> attitude = getAttitudeProvider().getAttitude(orbit, date, getFrame());
  363.             return new FieldSpacecraftState<>(orbit, attitude, mass);
  364.         }

  365.         /** {@inheritDoc} */
  366.         public void mapStateToArray(final FieldSpacecraftState<T> state, final T[] y, final T[] yDot) {
  367.             super.getOrbitType().mapOrbitToArray(state.getOrbit(), super.getPositionAngleType(), y, yDot);
  368.             y[6] = state.getMass();
  369.         }

  370.     }

  371.     /** {@inheritDoc} */
  372.     protected MainStateEquations<T> getMainStateEquations(final FieldODEIntegrator<T> integrator) {
  373.         return new Main(integrator);
  374.     }

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

  377.         /** Derivatives array. */
  378.         private final T[] yDot;

  379.         /** Current orbit. */
  380.         private FieldOrbit<T> orbit;

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

  383.         /** Simple constructor.
  384.          * @param integrator numerical integrator to use for propagation.
  385.          */
  386.         Main(final FieldODEIntegrator<T> integrator) {

  387.             this.yDot     = MathArrays.buildArray(getField(),  7);
  388.             this.jacobian = MathArrays.buildArray(getField(),  6, 6);
  389.             for (final ForceModel forceModel : forceModels) {
  390.                 forceModel.getFieldEventsDetectors(getField()).forEach(detector -> setUpEventDetector(integrator, detector));
  391.             }

  392.         }

  393.         /** {@inheritDoc} */
  394.         @Override
  395.         public void init(final FieldSpacecraftState<T> initialState, final FieldAbsoluteDate<T> target)
  396.             throws OrekitException {
  397.             final SpacecraftState stateD  = initialState.toSpacecraftState();
  398.             final AbsoluteDate    targetD = target.toAbsoluteDate();
  399.             for (final ForceModel forceModel : forceModels) {
  400.                 forceModel.init(stateD, targetD);
  401.             }
  402.         }

  403.         /** {@inheritDoc} */
  404.         @Override
  405.         public T[] computeDerivatives(final FieldSpacecraftState<T> state) throws OrekitException {
  406.             final T zero = state.getA().getField().getZero();
  407.             orbit = state.getOrbit();
  408.             Arrays.fill(yDot, zero);
  409.             orbit.getJacobianWrtCartesian(getPositionAngleType(), jacobian);

  410.             // compute the contributions of all perturbing forces,
  411.             // using the Kepler contribution at the end since
  412.             // NewtonianAttraction is always the last instance in the list
  413.             for (final ForceModel forceModel : forceModels) {
  414.                 forceModel.addContribution(state, this);
  415.             }

  416.             return yDot.clone();

  417.         }

  418.         /** {@inheritDoc} */
  419.         @Override
  420.         public void addKeplerContribution(final double mu) {
  421.             orbit.addKeplerContribution(getPositionAngleType(), mu, yDot);
  422.         }

  423.         /** {@inheritDoc} */
  424.         @Override
  425.         public void addNonKeplerianAcceleration(final FieldVector3D<T> gamma)
  426.             throws OrekitException {
  427.             for (int i = 0; i < 6; ++i) {
  428.                 final T[] jRow = jacobian[i];
  429.                 yDot[i] = yDot[i].add(jRow[3].linearCombination(jRow[3], gamma.getX(),
  430.                                                                 jRow[4], gamma.getY(),
  431.                                                                 jRow[5], gamma.getZ()));
  432.             }
  433.         }

  434.         /** {@inheritDoc} */
  435.         @Override
  436.         public void addMassDerivative(final T q) {
  437.             if (q.getReal() > 0) {
  438.                 throw new OrekitIllegalArgumentException(OrekitMessages.POSITIVE_FLOW_RATE, q);
  439.             }
  440.             yDot[6] = yDot[6].add(q);
  441.         }

  442.     }

  443.     /** Estimate tolerance vectors for integrators.
  444.      * <p>
  445.      * The errors are estimated from partial derivatives properties of orbits,
  446.      * starting from a scalar position error specified by the user.
  447.      * Considering the energy conservation equation V = sqrt(mu (2/r - 1/a)),
  448.      * we get at constant energy (i.e. on a Keplerian trajectory):
  449.      * <pre>
  450.      * V² r |dV| = mu |dr|
  451.      * </pre>
  452.      * So we deduce a scalar velocity error consistent with the position error.
  453.      * From here, we apply orbits Jacobians matrices to get consistent errors
  454.      * on orbital parameters.
  455.      * </p>
  456.      * <p>
  457.      * The tolerances are only <em>orders of magnitude</em>, and integrator tolerances
  458.      * are only local estimates, not global ones. So some care must be taken when using
  459.      * these tolerances. Setting 1mm as a position error does NOT mean the tolerances
  460.      * will guarantee a 1mm error position after several orbits integration.
  461.      * </p>
  462.      * @param dP user specified position error
  463.      * @param orbit reference orbit
  464.      * @param type propagation type for the meaning of the tolerance vectors elements
  465.      * (it may be different from {@code orbit.getType()})
  466.      * @return a two rows array, row 0 being the absolute tolerance error and row 1
  467.      * being the relative tolerance error
  468.      * @exception OrekitException if Jacobian is singular
  469.      * @param <T> elements type
  470.      */
  471.     public static <T extends RealFieldElement<T>> double[][] tolerances(final T dP, final FieldOrbit<T> orbit, final OrbitType type)
  472.         throws OrekitException {

  473.         // estimate the scalar velocity error
  474.         final FieldPVCoordinates<T> pv = orbit.getPVCoordinates();
  475.         final T r2 = pv.getPosition().getNormSq();
  476.         final T v  = pv.getVelocity().getNorm();
  477.         final T dV = dP.multiply(orbit.getMu()).divide(v.multiply(r2));

  478.         final double[] absTol = new double[7];
  479.         final double[] relTol = new double[7];

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

  483.         if (type == OrbitType.CARTESIAN) {
  484.             absTol[0] = dP.getReal();
  485.             absTol[1] = dP.getReal();
  486.             absTol[2] = dP.getReal();
  487.             absTol[3] = dV.getReal();
  488.             absTol[4] = dV.getReal();
  489.             absTol[5] = dV.getReal();
  490.         } else {

  491.             // convert the orbit to the desired type
  492.             final T[][] jacobian = MathArrays.buildArray(dP.getField(), 6, 6);
  493.             final FieldOrbit<T> converted = type.convertType(orbit);
  494.             converted.getJacobianWrtCartesian(PositionAngle.TRUE, jacobian);

  495.             for (int i = 0; i < 6; ++i) {
  496.                 final  T[] row = jacobian[i];
  497.                 absTol[i] =     row[0].abs().multiply(dP).
  498.                             add(row[1].abs().multiply(dP)).
  499.                             add(row[2].abs().multiply(dP)).
  500.                             add(row[3].abs().multiply(dV)).
  501.                             add(row[4].abs().multiply(dV)).
  502.                             add(row[5].abs().multiply(dV)).
  503.                             getReal();
  504.                 if (Double.isNaN(absTol[i])) {
  505.                     throw new OrekitException(OrekitMessages.SINGULAR_JACOBIAN_FOR_ORBIT_TYPE, type);
  506.                 }
  507.             }

  508.         }

  509.         Arrays.fill(relTol, dP.divide(r2.sqrt()).getReal());

  510.         return new double[][]{
  511.             absTol, relTol
  512.         };

  513.     }

  514. }