NumericalPropagator.java

  1. /* Copyright 2002-2019 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.io.NotSerializableException;
  19. import java.io.Serializable;
  20. import java.util.ArrayList;
  21. import java.util.Arrays;
  22. import java.util.Collections;
  23. import java.util.List;

  24. import org.hipparchus.geometry.euclidean.threed.Vector3D;
  25. import org.hipparchus.ode.ODEIntegrator;
  26. import org.hipparchus.util.FastMath;
  27. import org.orekit.attitudes.Attitude;
  28. import org.orekit.attitudes.AttitudeProvider;
  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.Orbit;
  37. import org.orekit.orbits.OrbitType;
  38. import org.orekit.orbits.PositionAngle;
  39. import org.orekit.propagation.SpacecraftState;
  40. import org.orekit.propagation.events.EventDetector;
  41. import org.orekit.propagation.integration.AbstractIntegratedPropagator;
  42. import org.orekit.propagation.integration.StateMapper;
  43. import org.orekit.time.AbsoluteDate;
  44. import org.orekit.utils.PVCoordinates;
  45. import org.orekit.utils.ParameterDriver;
  46. import org.orekit.utils.ParameterObserver;
  47. import org.orekit.utils.TimeStampedPVCoordinates;

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

  141.     /** Force models used during the extrapolation of the orbit. */
  142.     private final List<ForceModel> forceModels;

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

  163.      /** Set the central attraction coefficient μ.
  164.       * <p>
  165.       * Setting the central attraction coefficient is
  166.       * equivalent to {@link #addForceModel(ForceModel) add}
  167.       * a {@link NewtonianAttraction} force model.
  168.       * </p>
  169.      * @param mu central attraction coefficient (m³/s²)
  170.      * @see #addForceModel(ForceModel)
  171.      * @see #getAllForceModels()
  172.      */
  173.     public void setMu(final double mu) {
  174.         addForceModel(new NewtonianAttraction(mu));
  175.     }

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

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

  192.     /** Add a force model.
  193.      * <p>If this method is not called at all, the integrated orbit will follow
  194.      * a Keplerian evolution only.</p>
  195.      * @param model {@link ForceModel} to add (it can be either a perturbing force
  196.      * model or an instance of {@link NewtonianAttraction})
  197.      * @see #removeForceModels()
  198.      * @see #setMu(double)
  199.      */
  200.     public void addForceModel(final ForceModel model) {

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

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

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

  234.     }

  235.     /** Remove all force models (except central attraction).
  236.      * <p>Once all perturbing forces have been removed (and as long as no new force
  237.      * model is added), the integrated orbit will follow a Keplerian evolution
  238.      * only.</p>
  239.      * @see #addForceModel(ForceModel)
  240.      */
  241.     public void removeForceModels() {
  242.         final int last = forceModels.size() - 1;
  243.         if (hasNewtonianAttraction()) {
  244.             // preserve the Newtonian attraction model at the end
  245.             final ForceModel newton = forceModels.get(last);
  246.             forceModels.clear();
  247.             forceModels.add(newton);
  248.         } else {
  249.             forceModels.clear();
  250.         }
  251.     }

  252.     /** Get all the force models, perturbing forces and Newtonian attraction included.
  253.      * @return list of perturbing force models, with Newtonian attraction being the
  254.      * last one
  255.      * @see #addForceModel(ForceModel)
  256.      * @see #setMu(double)
  257.      */
  258.     public List<ForceModel> getAllForceModels() {
  259.         return Collections.unmodifiableList(forceModels);
  260.     }

  261.     /** Set propagation orbit type.
  262.      * @param orbitType orbit type to use for propagation
  263.      */
  264.     public void setOrbitType(final OrbitType orbitType) {
  265.         super.setOrbitType(orbitType);
  266.     }

  267.     /** Get propagation parameter type.
  268.      * @return orbit type used for propagation
  269.      */
  270.     public OrbitType getOrbitType() {
  271.         return super.getOrbitType();
  272.     }

  273.     /** Set position angle type.
  274.      * <p>
  275.      * The position parameter type is meaningful only if {@link
  276.      * #getOrbitType() propagation orbit type}
  277.      * support it. As an example, it is not meaningful for propagation
  278.      * in {@link OrbitType#CARTESIAN Cartesian} parameters.
  279.      * </p>
  280.      * @param positionAngleType angle type to use for propagation
  281.      */
  282.     public void setPositionAngleType(final PositionAngle positionAngleType) {
  283.         super.setPositionAngleType(positionAngleType);
  284.     }

  285.     /** Get propagation parameter type.
  286.      * @return angle type to use for propagation
  287.      */
  288.     public PositionAngle getPositionAngleType() {
  289.         return super.getPositionAngleType();
  290.     }

  291.     /** Set the initial state.
  292.      * @param initialState initial state
  293.      */
  294.     public void setInitialState(final SpacecraftState initialState) {
  295.         resetInitialState(initialState);
  296.     }

  297.     /** {@inheritDoc} */
  298.     public void resetInitialState(final SpacecraftState state) {
  299.         super.resetInitialState(state);
  300.         if (!hasNewtonianAttraction()) {
  301.             // use the state to define central attraction
  302.             setMu(state.getMu());
  303.         }
  304.         setStartDate(state.getDate());
  305.     }

  306.     /** {@inheritDoc} */
  307.     public TimeStampedPVCoordinates getPVCoordinates(final AbsoluteDate date, final Frame frame) {
  308.         return propagate(date).getPVCoordinates(frame);
  309.     }

  310.     /** {@inheritDoc} */
  311.     protected StateMapper createMapper(final AbsoluteDate referenceDate, final double mu,
  312.                                        final OrbitType orbitType, final PositionAngle positionAngleType,
  313.                                        final AttitudeProvider attitudeProvider, final Frame frame) {
  314.         return new OsculatingMapper(referenceDate, mu, orbitType, positionAngleType, attitudeProvider, frame);
  315.     }

  316.     /** Internal mapper using directly osculating parameters. */
  317.     private static class OsculatingMapper extends StateMapper implements Serializable {

  318.         /** Serializable UID. */
  319.         private static final long serialVersionUID = 20130621L;

  320.         /** Simple constructor.
  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 referenceDate reference date
  328.          * @param mu central attraction coefficient (m³/s²)
  329.          * @param orbitType orbit type to use for mapping
  330.          * @param positionAngleType angle type to use for propagation
  331.          * @param attitudeProvider attitude provider
  332.          * @param frame inertial frame
  333.          */
  334.         OsculatingMapper(final AbsoluteDate referenceDate, final double mu,
  335.                          final OrbitType orbitType, final PositionAngle positionAngleType,
  336.                          final AttitudeProvider attitudeProvider, final Frame frame) {
  337.             super(referenceDate, mu, orbitType, positionAngleType, attitudeProvider, frame);
  338.         }

  339.         /** {@inheritDoc} */
  340.         public SpacecraftState mapArrayToState(final AbsoluteDate date, final double[] y, final double[] yDot,
  341.                                                final boolean meanOnly) {
  342.             // the parameter meanOnly is ignored for the Numerical Propagator

  343.             final double mass = y[6];
  344.             if (mass <= 0.0) {
  345.                 throw new OrekitException(OrekitMessages.SPACECRAFT_MASS_BECOMES_NEGATIVE, mass);
  346.             }

  347.             final Orbit orbit       = getOrbitType().mapArrayToOrbit(y, yDot, getPositionAngleType(), date, getMu(), getFrame());
  348.             final Attitude attitude = getAttitudeProvider().getAttitude(orbit, date, getFrame());

  349.             return new SpacecraftState(orbit, attitude, mass);

  350.         }

  351.         /** {@inheritDoc} */
  352.         public void mapStateToArray(final SpacecraftState state, final double[] y, final double[] yDot) {
  353.             getOrbitType().mapOrbitToArray(state.getOrbit(), getPositionAngleType(), y, yDot);
  354.             y[6] = state.getMass();
  355.         }

  356.         /** Replace the instance with a data transfer object for serialization.
  357.          * @return data transfer object that will be serialized
  358.          * @exception NotSerializableException if the state mapper cannot be serialized (typically for DSST propagator)
  359.          */
  360.         private Object writeReplace() throws NotSerializableException {
  361.             return new DataTransferObject(getReferenceDate(), getMu(), getOrbitType(),
  362.                                           getPositionAngleType(), getAttitudeProvider(), getFrame());
  363.         }

  364.         /** Internal class used only for serialization. */
  365.         private static class DataTransferObject implements Serializable {

  366.             /** Serializable UID. */
  367.             private static final long serialVersionUID = 20130621L;

  368.             /** Reference date. */
  369.             private final AbsoluteDate referenceDate;

  370.             /** Central attraction coefficient (m³/s²). */
  371.             private final double mu;

  372.             /** Orbit type to use for mapping. */
  373.             private final OrbitType orbitType;

  374.             /** Angle type to use for propagation. */
  375.             private final PositionAngle positionAngleType;

  376.             /** Attitude provider. */
  377.             private final AttitudeProvider attitudeProvider;

  378.             /** Inertial frame. */
  379.             private final Frame frame;

  380.             /** Simple constructor.
  381.              * @param referenceDate reference date
  382.              * @param mu central attraction coefficient (m³/s²)
  383.              * @param orbitType orbit type to use for mapping
  384.              * @param positionAngleType angle type to use for propagation
  385.              * @param attitudeProvider attitude provider
  386.              * @param frame inertial frame
  387.              */
  388.             DataTransferObject(final AbsoluteDate referenceDate, final double mu,
  389.                                       final OrbitType orbitType, final PositionAngle positionAngleType,
  390.                                       final AttitudeProvider attitudeProvider, final Frame frame) {
  391.                 this.referenceDate     = referenceDate;
  392.                 this.mu                = mu;
  393.                 this.orbitType         = orbitType;
  394.                 this.positionAngleType = positionAngleType;
  395.                 this.attitudeProvider  = attitudeProvider;
  396.                 this.frame             = frame;
  397.             }

  398.             /** Replace the deserialized data transfer object with a {@link OsculatingMapper}.
  399.              * @return replacement {@link OsculatingMapper}
  400.              */
  401.             private Object readResolve() {
  402.                 return new OsculatingMapper(referenceDate, mu, orbitType, positionAngleType, attitudeProvider, frame);
  403.             }
  404.         }

  405.     }

  406.     /** {@inheritDoc} */
  407.     protected MainStateEquations getMainStateEquations(final ODEIntegrator integrator) {
  408.         return new Main(integrator);
  409.     }

  410.     /** Internal class for osculating parameters integration. */
  411.     private class Main implements MainStateEquations, TimeDerivativesEquations {

  412.         /** Derivatives array. */
  413.         private final double[] yDot;

  414.         /** Current orbit. */
  415.         private Orbit orbit;

  416.         /** Jacobian of the orbital parameters with respect to the Cartesian parameters. */
  417.         private double[][] jacobian;

  418.         /** Simple constructor.
  419.          * @param integrator numerical integrator to use for propagation.
  420.          */
  421.         Main(final ODEIntegrator integrator) {

  422.             this.yDot     = new double[7];
  423.             this.jacobian = new double[6][6];

  424.             for (final ForceModel forceModel : forceModels) {
  425.                 forceModel.getEventsDetectors().forEach(detector -> setUpEventDetector(integrator, detector));
  426.             }

  427.         }

  428.         /** {@inheritDoc} */
  429.         @Override
  430.         public void init(final SpacecraftState initialState, final AbsoluteDate target) {
  431.             for (final ForceModel forceModel : forceModels) {
  432.                 forceModel.init(initialState, target);
  433.             }
  434.         }

  435.         /** {@inheritDoc} */
  436.         @Override
  437.         public double[] computeDerivatives(final SpacecraftState state) {

  438.             orbit = state.getOrbit();
  439.             Arrays.fill(yDot, 0.0);
  440.             orbit.getJacobianWrtCartesian(getPositionAngleType(), jacobian);

  441.             // compute the contributions of all perturbing forces,
  442.             // using the Kepler contribution at the end since
  443.             // NewtonianAttraction is always the last instance in the list
  444.             for (final ForceModel forceModel : forceModels) {
  445.                 forceModel.addContribution(state, this);
  446.             }

  447.             return yDot.clone();

  448.         }

  449.         /** {@inheritDoc} */
  450.         @Override
  451.         public void addKeplerContribution(final double mu) {
  452.             orbit.addKeplerContribution(getPositionAngleType(), mu, yDot);
  453.         }

  454.         /** {@inheritDoc} */
  455.         public void addNonKeplerianAcceleration(final Vector3D gamma) {
  456.             for (int i = 0; i < 6; ++i) {
  457.                 final double[] jRow = jacobian[i];
  458.                 yDot[i] += jRow[3] * gamma.getX() + jRow[4] * gamma.getY() + jRow[5] * gamma.getZ();
  459.             }
  460.         }

  461.         /** {@inheritDoc} */
  462.         @Override
  463.         public void addMassDerivative(final double q) {
  464.             if (q > 0) {
  465.                 throw new OrekitIllegalArgumentException(OrekitMessages.POSITIVE_FLOW_RATE, q);
  466.             }
  467.             yDot[6] += q;
  468.         }

  469.     }

  470.     /** Estimate tolerance vectors for integrators.
  471.      * <p>
  472.      * The errors are estimated from partial derivatives properties of orbits,
  473.      * starting from a scalar position error specified by the user.
  474.      * Considering the energy conservation equation V = sqrt(mu (2/r - 1/a)),
  475.      * we get at constant energy (i.e. on a Keplerian trajectory):
  476.      * <pre>
  477.      * V² r |dV| = mu |dr|
  478.      * </pre>
  479.      * <p> So we deduce a scalar velocity error consistent with the position error.
  480.      * From here, we apply orbits Jacobians matrices to get consistent errors
  481.      * on orbital parameters.
  482.      *
  483.      * <p>
  484.      * The tolerances are only <em>orders of magnitude</em>, and integrator tolerances
  485.      * are only local estimates, not global ones. So some care must be taken when using
  486.      * these tolerances. Setting 1mm as a position error does NOT mean the tolerances
  487.      * will guarantee a 1mm error position after several orbits integration.
  488.      * </p>
  489.      * @param dP user specified position error
  490.      * @param orbit reference orbit
  491.      * @param type propagation type for the meaning of the tolerance vectors elements
  492.      * (it may be different from {@code orbit.getType()})
  493.      * @return a two rows array, row 0 being the absolute tolerance error and row 1
  494.      * being the relative tolerance error
  495.      */
  496.     public static double[][] tolerances(final double dP, final Orbit orbit, final OrbitType type) {

  497.         // estimate the scalar velocity error
  498.         final PVCoordinates pv = orbit.getPVCoordinates();
  499.         final double r2 = pv.getPosition().getNormSq();
  500.         final double v  = pv.getVelocity().getNorm();
  501.         final double dV = orbit.getMu() * dP / (v * r2);

  502.         final double[] absTol = new double[7];
  503.         final double[] relTol = new double[7];

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

  507.         if (type == OrbitType.CARTESIAN) {
  508.             absTol[0] = dP;
  509.             absTol[1] = dP;
  510.             absTol[2] = dP;
  511.             absTol[3] = dV;
  512.             absTol[4] = dV;
  513.             absTol[5] = dV;
  514.         } else {

  515.             // convert the orbit to the desired type
  516.             final double[][] jacobian = new double[6][6];
  517.             final Orbit converted = type.convertType(orbit);
  518.             converted.getJacobianWrtCartesian(PositionAngle.TRUE, jacobian);

  519.             for (int i = 0; i < 6; ++i) {
  520.                 final double[] row = jacobian[i];
  521.                 absTol[i] = FastMath.abs(row[0]) * dP +
  522.                             FastMath.abs(row[1]) * dP +
  523.                             FastMath.abs(row[2]) * dP +
  524.                             FastMath.abs(row[3]) * dV +
  525.                             FastMath.abs(row[4]) * dV +
  526.                             FastMath.abs(row[5]) * dV;
  527.                 if (Double.isNaN(absTol[i])) {
  528.                     throw new OrekitException(OrekitMessages.SINGULAR_JACOBIAN_FOR_ORBIT_TYPE, type);
  529.                 }
  530.             }

  531.         }

  532.         Arrays.fill(relTol, dP / FastMath.sqrt(r2));

  533.         return new double[][] {
  534.             absTol, relTol
  535.         };

  536.     }

  537. }