EcksteinHechlerPropagator.java

/* Copyright 2002-2016 CS Systèmes d'Information
 * Licensed to CS Systèmes d'Information (CS) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * CS licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.orekit.propagation.analytical;

import java.io.NotSerializableException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.SortedSet;

import org.apache.commons.math3.analysis.differentiation.DerivativeStructure;
import org.apache.commons.math3.geometry.euclidean.threed.FieldVector3D;
import org.apache.commons.math3.geometry.euclidean.threed.Vector3D;
import org.apache.commons.math3.util.FastMath;
import org.apache.commons.math3.util.MathUtils;
import org.orekit.attitudes.AttitudeProvider;
import org.orekit.errors.OrekitException;
import org.orekit.errors.OrekitInternalError;
import org.orekit.errors.OrekitMessages;
import org.orekit.errors.PropagationException;
import org.orekit.forces.gravity.potential.UnnormalizedSphericalHarmonicsProvider;
import org.orekit.forces.gravity.potential.UnnormalizedSphericalHarmonicsProvider.UnnormalizedSphericalHarmonics;
import org.orekit.orbits.CartesianOrbit;
import org.orekit.orbits.CircularOrbit;
import org.orekit.orbits.Orbit;
import org.orekit.orbits.OrbitType;
import org.orekit.orbits.PositionAngle;
import org.orekit.propagation.AdditionalStateProvider;
import org.orekit.propagation.SpacecraftState;
import org.orekit.time.AbsoluteDate;
import org.orekit.utils.TimeSpanMap;
import org.orekit.utils.TimeStampedPVCoordinates;

/** This class propagates a {@link org.orekit.propagation.SpacecraftState}
 *  using the analytical Eckstein-Hechler model.
 * <p>The Eckstein-Hechler model is suited for near circular orbits
 * (e < 0.1, with poor accuracy between 0.005 and 0.1) and inclination
 * neither equatorial (direct or retrograde) nor critical (direct or
 * retrograde).</p>
 * <p>
 * Note that before version 7.0, there was a large inconsistency in the generated
 * orbits, and it was fixed as of version 7.0 of Orekit, with a visible side effect.
 * The problems is that if the circular parameters produced by the Eckstein-Hechler
 * model are used to build an orbit considered to be osculating, the velocity deduced
 * from this orbit was <em>inconsistent with the position evolution</em>! The reason is
 * that the model includes non-Keplerian effects but it does not include a corresponding
 * circular/Cartesian conversion. As a consequence, all subsequent computation involving
 * velocity were wrong. This includes attitude modes like yaw compensation and Doppler
 * effect. As this effect was considered serious enough and as accurate velocities were
 * considered important, the propagator now generates {@link CartesianOrbit Cartesian
 * orbits} which are built in a special way to ensure consistency throughout propagation.
 * A side effect is that if circular parameters are rebuilt by user from these propagated
 * Cartesian orbit, the circular parameters will generally <em>not</em> match the initial
 * orbit (differences in semi-major axis can exceed 120 m). The position however <em>will</em>
 * match to sub-micrometer level, and this position will be identical to the positions
 * that were generated by previous versions (in other words, the internals of the models
 * have not been changed, only the output parameters have been changed). The correctness
 * of the initialization has been assessed and is good, as it allows the subsequent orbit
 * to remain close to a numerical reference orbit.
 * </p>
 * <p>
 * If users need a more definitive initialization of an Eckstein-Hechler propagator, they
 * should consider using a {@link org.orekit.propagation.conversion.PropagatorConverter
 * propagator converter} to initialize their Eckstein-Hechler propagator using a complete
 * sample instead of just a single initial orbit.
 * </p>
 * @see Orbit
 * @author Guylaine Prat
 */
public class EcksteinHechlerPropagator extends AbstractAnalyticalPropagator implements Serializable {

    /** Serializable UID. */
    private static final long serialVersionUID = 20151202L;

    /** Initial Eckstein-Hechler model. */
    private EHModel initialModel;

    /** All models. */
    private transient TimeSpanMap<EHModel> models;

    /** Reference radius of the central body attraction model (m). */
    private double referenceRadius;

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

    /** Un-normalized zonal coefficients. */
    private double[] ck0;

    /** Build a propagator from orbit and potential provider.
     * <p>Mass and attitude provider are set to unspecified non-null arbitrary values.</p>
     * @param initialOrbit initial orbit
     * @param provider for un-normalized zonal coefficients
     * @exception OrekitException if the zonal coefficients cannot be retrieved
     * @exception PropagationException if the mean parameters cannot be computed
     */
    public EcksteinHechlerPropagator(final Orbit initialOrbit,
                                     final UnnormalizedSphericalHarmonicsProvider provider)
        throws PropagationException, OrekitException {
        this(initialOrbit, DEFAULT_LAW, DEFAULT_MASS, provider,
             provider.onDate(initialOrbit.getDate()));
    }

    /**
     * Private helper constructor.
     * @param initialOrbit initial orbit
     * @param attitude attitude provider
     * @param mass spacecraft mass
     * @param provider for un-normalized zonal coefficients
     * @param harmonics {@code provider.onDate(initialOrbit.getDate())}
     * @exception OrekitException if the zonal coefficients cannot be retrieved
     */
    public EcksteinHechlerPropagator(final Orbit initialOrbit,
                                     final AttitudeProvider attitude,
                                     final double mass,
                                     final UnnormalizedSphericalHarmonicsProvider provider,
                                     final UnnormalizedSphericalHarmonics harmonics)
        throws OrekitException {
        this(initialOrbit, attitude, mass, provider.getAe(), provider.getMu(),
             harmonics.getUnnormalizedCnm(2, 0),
             harmonics.getUnnormalizedCnm(3, 0),
             harmonics.getUnnormalizedCnm(4, 0),
             harmonics.getUnnormalizedCnm(5, 0),
             harmonics.getUnnormalizedCnm(6, 0));
    }

    /** Build a propagator from orbit and potential.
     * <p>Mass and attitude provider are set to unspecified non-null arbitrary values.</p>
     * <p>The C<sub>n,0</sub> coefficients are the denormalized zonal coefficients, they
     * are related to both the normalized coefficients
     * <span style="text-decoration: overline">C</span><sub>n,0</sub>
     *  and the J<sub>n</sub> one as follows:</p>
     * <pre>
     *   C<sub>n,0</sub> = [(2-δ<sub>0,m</sub>)(2n+1)(n-m)!/(n+m)!]<sup>½</sup>
     *                      <span style="text-decoration: overline">C</span><sub>n,0</sub>
     *   C<sub>n,0</sub> = -J<sub>n</sub>
     * </pre>
     * @param initialOrbit initial orbit
     * @param referenceRadius reference radius of the Earth for the potential model (m)
     * @param mu central attraction coefficient (m³/s²)
     * @param c20 un-normalized zonal coefficient (about -1.08e-3 for Earth)
     * @param c30 un-normalized zonal coefficient (about +2.53e-6 for Earth)
     * @param c40 un-normalized zonal coefficient (about +1.62e-6 for Earth)
     * @param c50 un-normalized zonal coefficient (about +2.28e-7 for Earth)
     * @param c60 un-normalized zonal coefficient (about -5.41e-7 for Earth)
     * @exception PropagationException if the mean parameters cannot be computed
     * @see org.orekit.utils.Constants
     */
    public EcksteinHechlerPropagator(final Orbit initialOrbit,
                                     final double referenceRadius, final double mu,
                                     final double c20, final double c30, final double c40,
                                     final double c50, final double c60)
        throws PropagationException {
        this(initialOrbit, DEFAULT_LAW, DEFAULT_MASS, referenceRadius, mu, c20, c30, c40, c50, c60);
    }

    /** Build a propagator from orbit, mass and potential provider.
     * <p>Attitude law is set to an unspecified non-null arbitrary value.</p>
     * @param initialOrbit initial orbit
     * @param mass spacecraft mass
     * @param provider for un-normalized zonal coefficients
     * @exception OrekitException if the zonal coefficients cannot be retrieved
     * @exception PropagationException if the mean parameters cannot be computed
     */
    public EcksteinHechlerPropagator(final Orbit initialOrbit, final double mass,
                                     final UnnormalizedSphericalHarmonicsProvider provider)
        throws PropagationException, OrekitException {
        this(initialOrbit, DEFAULT_LAW, mass, provider, provider.onDate(initialOrbit.getDate()));
    }

    /** Build a propagator from orbit, mass and potential.
     * <p>Attitude law is set to an unspecified non-null arbitrary value.</p>
     * <p>The C<sub>n,0</sub> coefficients are the denormalized zonal coefficients, they
     * are related to both the normalized coefficients
     * <span style="text-decoration: overline">C</span><sub>n,0</sub>
     *  and the J<sub>n</sub> one as follows:</p>
     * <pre>
     *   C<sub>n,0</sub> = [(2-δ<sub>0,m</sub>)(2n+1)(n-m)!/(n+m)!]<sup>½</sup>
     *                      <span style="text-decoration: overline">C</span><sub>n,0</sub>
     *   C<sub>n,0</sub> = -J<sub>n</sub>
     * </pre>
     * @param initialOrbit initial orbit
     * @param mass spacecraft mass
     * @param referenceRadius reference radius of the Earth for the potential model (m)
     * @param mu central attraction coefficient (m³/s²)
     * @param c20 un-normalized zonal coefficient (about -1.08e-3 for Earth)
     * @param c30 un-normalized zonal coefficient (about +2.53e-6 for Earth)
     * @param c40 un-normalized zonal coefficient (about +1.62e-6 for Earth)
     * @param c50 un-normalized zonal coefficient (about +2.28e-7 for Earth)
     * @param c60 un-normalized zonal coefficient (about -5.41e-7 for Earth)
     * @exception PropagationException if the mean parameters cannot be computed
     */
    public EcksteinHechlerPropagator(final Orbit initialOrbit, final double mass,
                                     final double referenceRadius, final double mu,
                                     final double c20, final double c30, final double c40,
                                     final double c50, final double c60)
        throws PropagationException {
        this(initialOrbit, DEFAULT_LAW, mass, referenceRadius, mu, c20, c30, c40, c50, c60);
    }

    /** Build a propagator from orbit, attitude provider and potential provider.
     * <p>Mass is set to an unspecified non-null arbitrary value.</p>
     * @param initialOrbit initial orbit
     * @param attitudeProv attitude provider
     * @param provider for un-normalized zonal coefficients
     * @exception OrekitException if the zonal coefficients cannot be retrieved
     * @exception PropagationException if the mean parameters cannot be computed
     */
    public EcksteinHechlerPropagator(final Orbit initialOrbit,
                                     final AttitudeProvider attitudeProv,
                                     final UnnormalizedSphericalHarmonicsProvider provider)
        throws PropagationException, OrekitException {
        this(initialOrbit, attitudeProv, DEFAULT_MASS, provider, provider.onDate(initialOrbit.getDate()));
    }

    /** Build a propagator from orbit, attitude provider and potential.
     * <p>Mass is set to an unspecified non-null arbitrary value.</p>
     * <p>The C<sub>n,0</sub> coefficients are the denormalized zonal coefficients, they
     * are related to both the normalized coefficients
     * <span style="text-decoration: overline">C</span><sub>n,0</sub>
     *  and the J<sub>n</sub> one as follows:</p>
     * <pre>
     *   C<sub>n,0</sub> = [(2-δ<sub>0,m</sub>)(2n+1)(n-m)!/(n+m)!]<sup>½</sup>
     *                     <span style="text-decoration: overline">C</span><sub>n,0</sub>
     *   C<sub>n,0</sub> = -J<sub>n</sub>
     * </pre>
     * @param initialOrbit initial orbit
     * @param attitudeProv attitude provider
     * @param referenceRadius reference radius of the Earth for the potential model (m)
     * @param mu central attraction coefficient (m³/s²)
     * @param c20 un-normalized zonal coefficient (about -1.08e-3 for Earth)
     * @param c30 un-normalized zonal coefficient (about +2.53e-6 for Earth)
     * @param c40 un-normalized zonal coefficient (about +1.62e-6 for Earth)
     * @param c50 un-normalized zonal coefficient (about +2.28e-7 for Earth)
     * @param c60 un-normalized zonal coefficient (about -5.41e-7 for Earth)
     * @exception PropagationException if the mean parameters cannot be computed
     */
    public EcksteinHechlerPropagator(final Orbit initialOrbit,
                                     final AttitudeProvider attitudeProv,
                                     final double referenceRadius, final double mu,
                                     final double c20, final double c30, final double c40,
                                     final double c50, final double c60)
        throws PropagationException {
        this(initialOrbit, attitudeProv, DEFAULT_MASS, referenceRadius, mu, c20, c30, c40, c50, c60);
    }

    /** Build a propagator from orbit, attitude provider, mass and potential provider.
     * @param initialOrbit initial orbit
     * @param attitudeProv attitude provider
     * @param mass spacecraft mass
     * @param provider for un-normalized zonal coefficients
     * @exception OrekitException if the zonal coefficients cannot be retrieved
     * @exception PropagationException if the mean parameters cannot be computed
     */
    public EcksteinHechlerPropagator(final Orbit initialOrbit,
                                     final AttitudeProvider attitudeProv,
                                     final double mass,
                                     final UnnormalizedSphericalHarmonicsProvider provider)
        throws PropagationException, OrekitException {
        this(initialOrbit, attitudeProv, mass, provider, provider.onDate(initialOrbit.getDate()));
    }

    /** Build a propagator from orbit, attitude provider, mass and potential.
     * <p>The C<sub>n,0</sub> coefficients are the denormalized zonal coefficients, they
     * are related to both the normalized coefficients
     * <span style="text-decoration: overline">C</span><sub>n,0</sub>
     *  and the J<sub>n</sub> one as follows:</p>
     * <pre>
     *   C<sub>n,0</sub> = [(2-δ<sub>0,m</sub>)(2n+1)(n-m)!/(n+m)!]<sup>½</sup>
     *                      <span style="text-decoration: overline">C</span><sub>n,0</sub>
     *   C<sub>n,0</sub> = -J<sub>n</sub>
     * </pre>
     * @param initialOrbit initial orbit
     * @param attitudeProv attitude provider
     * @param mass spacecraft mass
     * @param referenceRadius reference radius of the Earth for the potential model (m)
     * @param mu central attraction coefficient (m³/s²)
     * @param c20 un-normalized zonal coefficient (about -1.08e-3 for Earth)
     * @param c30 un-normalized zonal coefficient (about +2.53e-6 for Earth)
     * @param c40 un-normalized zonal coefficient (about +1.62e-6 for Earth)
     * @param c50 un-normalized zonal coefficient (about +2.28e-7 for Earth)
     * @param c60 un-normalized zonal coefficient (about -5.41e-7 for Earth)
     * @exception PropagationException if the mean parameters cannot be computed
     */
    public EcksteinHechlerPropagator(final Orbit initialOrbit,
                                     final AttitudeProvider attitudeProv,
                                     final double mass,
                                     final double referenceRadius, final double mu,
                                     final double c20, final double c30, final double c40,
                                     final double c50, final double c60)
        throws PropagationException {

        super(attitudeProv);

        try {

            // store model coefficients
            this.referenceRadius = referenceRadius;
            this.mu  = mu;
            this.ck0 = new double[] {
                0.0, 0.0, c20, c30, c40, c50, c60
            };

            // compute mean parameters
            // transform into circular adapted parameters used by the Eckstein-Hechler model
            resetInitialState(new SpacecraftState(initialOrbit,
                                                  attitudeProv.getAttitude(initialOrbit,
                                                                           initialOrbit.getDate(),
                                                                           initialOrbit.getFrame()),
                                                  mass));

        } catch (OrekitException oe) {
            throw new PropagationException(oe);
        }
    }

    /** {@inheritDoc} */
    public void resetInitialState(final SpacecraftState state)
        throws PropagationException {
        super.resetInitialState(state);
        this.initialModel = computeMeanParameters((CircularOrbit) OrbitType.CIRCULAR.convertType(state.getOrbit()),
                                                  state.getMass());
        this.models       = new TimeSpanMap<EHModel>(initialModel);
    }

    /** {@inheritDoc} */
    protected void resetIntermediateState(final SpacecraftState state, final boolean forward)
        throws PropagationException {
        super.resetIntermediateState(state, forward);
        final EHModel newModel = computeMeanParameters((CircularOrbit) OrbitType.CIRCULAR.convertType(state.getOrbit()),
                                                       state.getMass());
        if (forward) {
            models.addValidAfter(newModel, state.getDate());
        } else {
            models.addValidBefore(newModel, state.getDate());
        }
    }

    /** Compute mean parameters according to the Eckstein-Hechler analytical model.
     * @param osculating osculating orbit
     * @param mass constant mass
     * @return Eckstein-Hechler mean model
     * @exception PropagationException if orbit goes outside of supported range
     * (trajectory inside the Brillouin sphere, too eccentric, equatorial, critical
     * inclination) or if convergence cannot be reached
     */
    private EHModel computeMeanParameters(final CircularOrbit osculating, final double mass)
        throws PropagationException {

        // sanity check
        if (osculating.getA() < referenceRadius) {
            throw new PropagationException(OrekitMessages.TRAJECTORY_INSIDE_BRILLOUIN_SPHERE,
                                           osculating.getA());
        }

        // rough initialization of the mean parameters
        EHModel current = new EHModel(osculating, mass, referenceRadius, mu, ck0);

        // threshold for each parameter
        final double epsilon         = 1.0e-13;
        final double thresholdA      = epsilon * (1 + FastMath.abs(current.mean.getA()));
        final double thresholdE      = epsilon * (1 + current.mean.getE());
        final double thresholdAngles = epsilon * FastMath.PI;

        int i = 0;
        while (i++ < 100) {

            // recompute the osculating parameters from the current mean parameters
            final DerivativeStructure[] parameters = current.propagateParameters(current.mean.getDate());

            // adapted parameters residuals
            final double deltaA      = osculating.getA()          - parameters[0].getValue();
            final double deltaEx     = osculating.getCircularEx() - parameters[1].getValue();
            final double deltaEy     = osculating.getCircularEy() - parameters[2].getValue();
            final double deltaI      = osculating.getI()          - parameters[3].getValue();
            final double deltaRAAN   = MathUtils.normalizeAngle(osculating.getRightAscensionOfAscendingNode() -
                                                                parameters[4].getValue(),
                                                                0.0);
            final double deltaAlphaM = MathUtils.normalizeAngle(osculating.getAlphaM() - parameters[5].getValue(), 0.0);

            // update mean parameters
            current = new EHModel(new CircularOrbit(current.mean.getA()          + deltaA,
                                                    current.mean.getCircularEx() + deltaEx,
                                                    current.mean.getCircularEy() + deltaEy,
                                                    current.mean.getI()          + deltaI,
                                                    current.mean.getRightAscensionOfAscendingNode() + deltaRAAN,
                                                    current.mean.getAlphaM()     + deltaAlphaM,
                                                    PositionAngle.MEAN,
                                                    current.mean.getFrame(),
                                                    current.mean.getDate(), mu),
                                  mass, referenceRadius, mu, ck0);

            // check convergence
            if ((FastMath.abs(deltaA)      < thresholdA) &&
                (FastMath.abs(deltaEx)     < thresholdE) &&
                (FastMath.abs(deltaEy)     < thresholdE) &&
                (FastMath.abs(deltaI)      < thresholdAngles) &&
                (FastMath.abs(deltaRAAN)   < thresholdAngles) &&
                (FastMath.abs(deltaAlphaM) < thresholdAngles)) {
                return current;
            }

        }

        throw new PropagationException(OrekitMessages.UNABLE_TO_COMPUTE_ECKSTEIN_HECHLER_MEAN_PARAMETERS, i);

    }

    /** {@inheritDoc} */
    public CartesianOrbit propagateOrbit(final AbsoluteDate date)
        throws PropagationException {
        // compute Cartesian parameters, taking derivatives into account
        // to make sure velocity and acceleration are consistent
        final EHModel current = models.get(date);
        return new CartesianOrbit(toCartesian(date, current.propagateParameters(date)),
                                  current.mean.getFrame(), mu);
    }

    /** Local class for Eckstein-Hechler model, with fixed mean parameters. */
    private static class EHModel implements Serializable {

        /** Serializable UID. */
        private static final long serialVersionUID = 20160115L;

        /** Mean orbit. */
        private final CircularOrbit mean;

        /** Constant mass. */
        private final double mass;

        // CHECKSTYLE: stop JavadocVariable check

        // preprocessed values
        private final double xnotDot;
        private final double rdpom;
        private final double rdpomp;
        private final double eps1;
        private final double eps2;
        private final double xim;
        private final double ommD;
        private final double rdl;
        private final double aMD;

        private final double kh;
        private final double kl;

        private final double ax1;
        private final double ay1;
        private final double as1;
        private final double ac2;
        private final double axy3;
        private final double as3;
        private final double ac4;
        private final double as5;
        private final double ac6;

        private final double ex1;
        private final double exx2;
        private final double exy2;
        private final double ex3;
        private final double ex4;

        private final double ey1;
        private final double eyx2;
        private final double eyy2;
        private final double ey3;
        private final double ey4;

        private final double rx1;
        private final double ry1;
        private final double r2;
        private final double r3;
        private final double rl;

        private final double iy1;
        private final double ix1;
        private final double i2;
        private final double i3;
        private final double ih;

        private final double lx1;
        private final double ly1;
        private final double l2;
        private final double l3;
        private final double ll;

        // CHECKSTYLE: resume JavadocVariable check

        /** Create a model for specified mean orbit.
         * @param mean mean orbit
         * @param mass constant mass
         * @param referenceRadius reference radius of the central body attraction model (m)
         * @param mu central attraction coefficient (m³/s²)
         * @param ck0 un-normalized zonal coefficients
         * @exception PropagationException if mean orbit is not within model supported domain
         */
        EHModel(final CircularOrbit mean, final double mass,
                final double referenceRadius, final double mu, final double[] ck0)
            throws PropagationException {

            this.mean            = mean;
            this.mass            = mass;

            // preliminary processing
            double q = referenceRadius / mean.getA();
            double ql = q * q;
            final double g2 = ck0[2] * ql;
            ql *= q;
            final double g3 = ck0[3] * ql;
            ql *= q;
            final double g4 = ck0[4] * ql;
            ql *= q;
            final double g5 = ck0[5] * ql;
            ql *= q;
            final double g6 = ck0[6] * ql;

            final double cosI1 = FastMath.cos(mean.getI());
            final double sinI1 = FastMath.sin(mean.getI());
            final double sinI2 = sinI1 * sinI1;
            final double sinI4 = sinI2 * sinI2;
            final double sinI6 = sinI2 * sinI4;

            if (sinI2 < 1.0e-10) {
                throw new PropagationException(OrekitMessages.ALMOST_EQUATORIAL_ORBIT,
                                               FastMath.toDegrees(mean.getI()));
            }

            if (FastMath.abs(sinI2 - 4.0 / 5.0) < 1.0e-3) {
                throw new PropagationException(OrekitMessages.ALMOST_CRITICALLY_INCLINED_ORBIT,
                                               FastMath.toDegrees(mean.getI()));
            }

            if (mean.getE() > 0.1) {
                // if 0.005 < e < 0.1 no error is triggered, but accuracy is poor
                throw new PropagationException(OrekitMessages.TOO_LARGE_ECCENTRICITY_FOR_PROPAGATION_MODEL,
                                               mean.getE());
            }

            xnotDot = FastMath.sqrt(mu / mean.getA()) / mean.getA();

            rdpom = -0.75 * g2 * (4.0 - 5.0 * sinI2);
            rdpomp = 7.5 * g4 * (1.0 - 31.0 / 8.0 * sinI2 + 49.0 / 16.0 * sinI4) -
                    13.125 * g6 * (1.0 - 8.0 * sinI2 + 129.0 / 8.0 * sinI4 - 297.0 / 32.0 * sinI6);

            q = 3.0 / (32.0 * rdpom);
            eps1 = q * g4 * sinI2 * (30.0 - 35.0 * sinI2) -
                    175.0 * q * g6 * sinI2 * (1.0 - 3.0 * sinI2 + 2.0625 * sinI4);
            q = 3.0 * sinI1 / (8.0 * rdpom);
            eps2 = q * g3 * (4.0 - 5.0 * sinI2) - q * g5 * (10.0 - 35.0 * sinI2 + 26.25 * sinI4);

            xim = mean.getI();
            ommD = cosI1 * (1.50    * g2 - 2.25 * g2 * g2 * (2.5 - 19.0 / 6.0 * sinI2) +
                            0.9375  * g4 * (7.0 * sinI2 - 4.0) +
                            3.28125 * g6 * (2.0 - 9.0 * sinI2 + 8.25 * sinI4));

            rdl = 1.0 - 1.50 * g2 * (3.0 - 4.0 * sinI2);
            aMD = rdl +
                    2.25 * g2 * g2 * (9.0 - 263.0 / 12.0 * sinI2 + 341.0 / 24.0 * sinI4) +
                    15.0 / 16.0 * g4 * (8.0 - 31.0 * sinI2 + 24.5 * sinI4) +
                    105.0 / 32.0 * g6 * (-10.0 / 3.0 + 25.0 * sinI2 - 48.75 * sinI4 + 27.5 * sinI6);

            final double qq = -1.5 * g2 / rdl;
            final double qA   = 0.75 * g2 * g2 * sinI2;
            final double qB   = 0.25 * g4 * sinI2;
            final double qC   = 105.0 / 16.0 * g6 * sinI2;
            final double qD   = -0.75 * g3 * sinI1;
            final double qE   = 3.75 * g5 * sinI1;
            kh = 0.375 / rdpom;
            kl = kh / sinI1;

            ax1 = qq * (2.0 - 3.5 * sinI2);
            ay1 = qq * (2.0 - 2.5 * sinI2);
            as1 = qD * (4.0 - 5.0 * sinI2) +
                  qE * (2.625 * sinI4 - 3.5 * sinI2 + 1.0);
            ac2 = qq * sinI2 +
                  qA * 7.0 * (2.0 - 3.0 * sinI2) +
                  qB * (15.0 - 17.5 * sinI2) +
                  qC * (3.0 * sinI2 - 1.0 - 33.0 / 16.0 * sinI4);
            axy3 = qq * 3.5 * sinI2;
            as3 = qD * 5.0 / 3.0 * sinI2 +
                  qE * 7.0 / 6.0 * sinI2 * (1.0 - 1.125 * sinI2);
            ac4 = qA * sinI2 +
                  qB * 4.375 * sinI2 +
                  qC * 0.75 * (1.1 * sinI4 - sinI2);

            as5 = qE * 21.0 / 80.0 * sinI4;

            ac6 = qC * -11.0 / 80.0 * sinI4;

            ex1 = qq * (1.0 - 1.25 * sinI2);
            exx2 = qq * 0.5 * (3.0 - 5.0 * sinI2);
            exy2 = qq * (2.0 - 1.5 * sinI2);
            ex3 = qq * 7.0 / 12.0 * sinI2;
            ex4 = qq * 17.0 / 8.0 * sinI2;

            ey1 = qq * (1.0 - 1.75 * sinI2);
            eyx2 = qq * (1.0 - 3.0 * sinI2);
            eyy2 = qq * (2.0 * sinI2 - 1.5);
            ey3 = qq * 7.0 / 12.0 * sinI2;
            ey4 = qq * 17.0 / 8.0 * sinI2;

            q  = -qq * cosI1;
            rx1 =  3.5 * q;
            ry1 = -2.5 * q;
            r2 = -0.5 * q;
            r3 =  7.0 / 6.0 * q;
            rl = g3 * cosI1 * (4.0 - 15.0 * sinI2) -
                 2.5 * g5 * cosI1 * (4.0 - 42.0 * sinI2 + 52.5 * sinI4);

            q = 0.5 * qq * sinI1 * cosI1;
            iy1 =  q;
            ix1 = -q;
            i2 =  q;
            i3 =  q * 7.0 / 3.0;
            ih = -g3 * cosI1 * (4.0 - 5.0 * sinI2) +
                 2.5 * g5 * cosI1 * (4.0 - 14.0 * sinI2 + 10.5 * sinI4);

            lx1 = qq * (7.0 - 77.0 / 8.0 * sinI2);
            ly1 = qq * (55.0 / 8.0 * sinI2 - 7.50);
            l2 = qq * (1.25 * sinI2 - 0.5);
            l3 = qq * (77.0 / 24.0 * sinI2 - 7.0 / 6.0);
            ll = g3 * (53.0 * sinI2 - 4.0 - 57.5 * sinI4) +
                 2.5 * g5 * (4.0 - 96.0 * sinI2 + 269.5 * sinI4 - 183.75 * sinI6);

        }

        /** Extrapolate an orbit up to a specific target date.
         * @param date target date for the orbit
         * @return propagated parameters
         * @exception PropagationException if some parameters are out of bounds
         */
        public DerivativeStructure[] propagateParameters(final AbsoluteDate date)
            throws PropagationException {

            // keplerian evolution
            final DerivativeStructure dt =
                    new DerivativeStructure(1, 2, 0, date.durationFrom(mean.getDate()));
            final DerivativeStructure xnot = dt.multiply(xnotDot);

            // secular effects

            // eccentricity
            final DerivativeStructure x   = xnot.multiply(rdpom + rdpomp);
            final DerivativeStructure cx  = x.cos();
            final DerivativeStructure sx  = x.sin();
            final DerivativeStructure exm = cx.multiply(mean.getCircularEx()).
                                            add(sx.multiply(eps2 - (1.0 - eps1) * mean.getCircularEy()));
            final DerivativeStructure eym = sx.multiply((1.0 + eps1) * mean.getCircularEx()).
                                            add(cx.multiply(mean.getCircularEy() - eps2)).
                                            add(eps2);

            // no secular effect on inclination

            // right ascension of ascending node
            final DerivativeStructure omm =
                    new DerivativeStructure(1, 2,
                                            MathUtils.normalizeAngle(mean.getRightAscensionOfAscendingNode() + ommD * xnot.getValue(),
                                                                     FastMath.PI),
                                            ommD * xnotDot,
                                            0.0);

            // latitude argument
            final DerivativeStructure xlm =
                    new DerivativeStructure(1, 2,
                                            MathUtils.normalizeAngle(mean.getAlphaM() + aMD * xnot.getValue(), FastMath.PI),
                                            aMD * xnotDot,
                                            0.0);

            // periodical terms
            final DerivativeStructure cl1 = xlm.cos();
            final DerivativeStructure sl1 = xlm.sin();
            final DerivativeStructure cl2 = cl1.multiply(cl1).subtract(sl1.multiply(sl1));
            final DerivativeStructure sl2 = cl1.multiply(sl1).add(sl1.multiply(cl1));
            final DerivativeStructure cl3 = cl2.multiply(cl1).subtract(sl2.multiply(sl1));
            final DerivativeStructure sl3 = cl2.multiply(sl1).add(sl2.multiply(cl1));
            final DerivativeStructure cl4 = cl3.multiply(cl1).subtract(sl3.multiply(sl1));
            final DerivativeStructure sl4 = cl3.multiply(sl1).add(sl3.multiply(cl1));
            final DerivativeStructure cl5 = cl4.multiply(cl1).subtract(sl4.multiply(sl1));
            final DerivativeStructure sl5 = cl4.multiply(sl1).add(sl4.multiply(cl1));
            final DerivativeStructure cl6 = cl5.multiply(cl1).subtract(sl5.multiply(sl1));

            final DerivativeStructure qh  = eym.subtract(eps2).multiply(kh);
            final DerivativeStructure ql  = exm.multiply(kl);

            final DerivativeStructure exmCl1 = exm.multiply(cl1);
            final DerivativeStructure exmSl1 = exm.multiply(sl1);
            final DerivativeStructure eymCl1 = eym.multiply(cl1);
            final DerivativeStructure eymSl1 = eym.multiply(sl1);
            final DerivativeStructure exmCl2 = exm.multiply(cl2);
            final DerivativeStructure exmSl2 = exm.multiply(sl2);
            final DerivativeStructure eymCl2 = eym.multiply(cl2);
            final DerivativeStructure eymSl2 = eym.multiply(sl2);
            final DerivativeStructure exmCl3 = exm.multiply(cl3);
            final DerivativeStructure exmSl3 = exm.multiply(sl3);
            final DerivativeStructure eymCl3 = eym.multiply(cl3);
            final DerivativeStructure eymSl3 = eym.multiply(sl3);
            final DerivativeStructure exmCl4 = exm.multiply(cl4);
            final DerivativeStructure exmSl4 = exm.multiply(sl4);
            final DerivativeStructure eymCl4 = eym.multiply(cl4);
            final DerivativeStructure eymSl4 = eym.multiply(sl4);

            // semi major axis
            final DerivativeStructure rda = exmCl1.multiply(ax1).
                                            add(eymSl1.multiply(ay1)).
                                            add(sl1.multiply(as1)).
                                            add(cl2.multiply(ac2)).
                                            add(exmCl3.add(eymSl3).multiply(axy3)).
                                            add(sl3.multiply(as3)).
                                            add(cl4.multiply(ac4)).
                                            add(sl5.multiply(as5)).
                                            add(cl6.multiply(ac6));

            // eccentricity
            final DerivativeStructure rdex = cl1.multiply(ex1).
                                             add(exmCl2.multiply(exx2)).
                                             add(eymSl2.multiply(exy2)).
                                             add(cl3.multiply(ex3)).
                                             add(exmCl4.add(eymSl4).multiply(ex4));
            final DerivativeStructure rdey = sl1.multiply(ey1).
                                             add(exmSl2.multiply(eyx2)).
                                             add(eymCl2.multiply(eyy2)).
                                             add(sl3.multiply(ey3)).
                                             add(exmSl4.subtract(eymCl4).multiply(ey4));

            // ascending node
            final DerivativeStructure rdom = exmSl1.multiply(rx1).
                                             add(eymCl1.multiply(ry1)).
                                             add(sl2.multiply(r2)).
                                             add(eymCl3.subtract(exmSl3).multiply(r3)).
                                             add(ql.multiply(rl));

            // inclination
            final DerivativeStructure rdxi = eymSl1.multiply(iy1).
                                             add(exmCl1.multiply(ix1)).
                                             add(cl2.multiply(i2)).
                                             add(exmCl3.add(eymSl3).multiply(i3)).
                                             add(qh.multiply(ih));

            // latitude argument
            final DerivativeStructure rdxl = exmSl1.multiply(lx1).
                                             add(eymCl1.multiply(ly1)).
                                             add(sl2.multiply(l2)).
                                             add(exmSl3.subtract(eymCl3).multiply(l3)).
                                             add(ql.multiply(ll));

            // osculating parameters
            return new DerivativeStructure[] {
                rda.add(1.0).multiply(mean.getA()),
                rdex.add(exm),
                rdey.add(eym),
                rdxi.add(xim),
                rdom.add(omm),
                rdxl.add(xlm)
            };

        }

    }

    /** Convert circular parameters <em>with derivatives</em> to Cartesian coordinates.
     * @param date date of the orbital parameters
     * @param parameters circular parameters (a, ex, ey, i, raan, alphaM)
     * @return Cartesian coordinates consistent with values and derivatives
     */
    private TimeStampedPVCoordinates toCartesian(final AbsoluteDate date, final DerivativeStructure[] parameters) {

        // evaluate coordinates in the orbit canonical reference frame
        final DerivativeStructure cosOmega = parameters[4].cos();
        final DerivativeStructure sinOmega = parameters[4].sin();
        final DerivativeStructure cosI     = parameters[3].cos();
        final DerivativeStructure sinI     = parameters[3].sin();
        final DerivativeStructure alphaE   = meanToEccentric(parameters[5], parameters[1], parameters[2]);
        final DerivativeStructure cosAE    = alphaE.cos();
        final DerivativeStructure sinAE    = alphaE.sin();
        final DerivativeStructure ex2      = parameters[1].multiply(parameters[1]);
        final DerivativeStructure ey2      = parameters[2].multiply(parameters[2]);
        final DerivativeStructure exy      = parameters[1].multiply(parameters[2]);
        final DerivativeStructure q        = ex2.add(ey2).subtract(1).negate().sqrt();
        final DerivativeStructure beta     = q.add(1).reciprocal();
        final DerivativeStructure bx2      = beta.multiply(ex2);
        final DerivativeStructure by2      = beta.multiply(ey2);
        final DerivativeStructure bxy      = beta.multiply(exy);
        final DerivativeStructure u        = bxy.multiply(sinAE).subtract(parameters[1].add(by2.subtract(1).multiply(cosAE)));
        final DerivativeStructure v        = bxy.multiply(cosAE).subtract(parameters[2].add(bx2.subtract(1).multiply(sinAE)));
        final DerivativeStructure x        = parameters[0].multiply(u);
        final DerivativeStructure y        = parameters[0].multiply(v);

        // canonical orbit reference frame
        final FieldVector3D<DerivativeStructure> p =
                new FieldVector3D<DerivativeStructure>(x.multiply(cosOmega).subtract(y.multiply(cosI.multiply(sinOmega))),
                                                       x.multiply(sinOmega).add(y.multiply(cosI.multiply(cosOmega))),
                                                       y.multiply(sinI));

        // dispatch derivatives
        final Vector3D p0 = new Vector3D(p.getX().getValue(),
                                         p.getY().getValue(),
                                         p.getZ().getValue());
        final Vector3D p1 = new Vector3D(p.getX().getPartialDerivative(1),
                                         p.getY().getPartialDerivative(1),
                                         p.getZ().getPartialDerivative(1));
        final Vector3D p2 = new Vector3D(p.getX().getPartialDerivative(2),
                                         p.getY().getPartialDerivative(2),
                                         p.getZ().getPartialDerivative(2));
        return new TimeStampedPVCoordinates(date, p0, p1, p2);

    }

    /** Computes the eccentric latitude argument from the mean latitude argument.
     * @param alphaM = M + Ω mean latitude argument (rad)
     * @param ex e cos(Ω), first component of circular eccentricity vector
     * @param ey e sin(Ω), second component of circular eccentricity vector
     * @return the eccentric latitude argument.
     */
    private DerivativeStructure meanToEccentric(final DerivativeStructure alphaM,
                                                final DerivativeStructure ex,
                                                final DerivativeStructure ey) {
        // Generalization of Kepler equation to circular parameters
        // with alphaE = PA + E and
        //      alphaM = PA + M = alphaE - ex.sin(alphaE) + ey.cos(alphaE)
        DerivativeStructure alphaE        = alphaM;
        DerivativeStructure shift         = alphaM.getField().getZero();
        DerivativeStructure alphaEMalphaM = alphaM.getField().getZero();
        DerivativeStructure cosAlphaE     = alphaE.cos();
        DerivativeStructure sinAlphaE     = alphaE.sin();
        int                 iter          = 0;
        do {
            final DerivativeStructure f2 = ex.multiply(sinAlphaE).subtract(ey.multiply(cosAlphaE));
            final DerivativeStructure f1 = alphaM.getField().getOne().subtract(ex.multiply(cosAlphaE)).subtract(ey.multiply(sinAlphaE));
            final DerivativeStructure f0 = alphaEMalphaM.subtract(f2);

            final DerivativeStructure f12 = f1.multiply(2);
            shift = f0.multiply(f12).divide(f1.multiply(f12).subtract(f0.multiply(f2)));

            alphaEMalphaM  = alphaEMalphaM.subtract(shift);
            alphaE         = alphaM.add(alphaEMalphaM);
            cosAlphaE      = alphaE.cos();
            sinAlphaE      = alphaE.sin();

        } while ((++iter < 50) && (FastMath.abs(shift.getValue()) > 1.0e-12));

        return alphaE;

    }

    /** {@inheritDoc} */
    protected double getMass(final AbsoluteDate date) {
        return models.get(date).mass;
    }

    /** Replace the instance with a data transfer object for serialization.
     * @return data transfer object that will be serialized
     * @exception NotSerializableException if an additional state provider is not serializable
     */
    private Object writeReplace() throws NotSerializableException {
        try {
            // managed states providers
            final List<AdditionalStateProvider> serializableProviders = new ArrayList<AdditionalStateProvider>();
            for (final AdditionalStateProvider provider : getAdditionalStateProviders()) {
                if (provider instanceof Serializable) {
                    serializableProviders.add(provider);
                } else {
                    throw new NotSerializableException(provider.getClass().getName());
                }
            }

            // states transitions
            final AbsoluteDate[]  transitionDates;
            final CircularOrbit[] allOrbits;
            final double[]        allMasses;
            final SortedSet<TimeSpanMap.Transition<EHModel>> transitions = models.getTransitions();
            if (transitions.size() == 1  && transitions.first().getBefore() == transitions.first().getAfter()) {
                // the single entry is a dummy one, without a real transition
                // we ignore it completely
                transitionDates = null;
                allOrbits       = null;
                allMasses       = null;
            } else {
                transitionDates = new AbsoluteDate[transitions.size()];
                allOrbits       = new CircularOrbit[transitions.size() + 1];
                allMasses       = new double[transitions.size() + 1];
                int i = 0;
                for (final TimeSpanMap.Transition<EHModel> transition : transitions) {
                    if (i == 0) {
                        // model before the first transition
                        allOrbits[i] = transition.getBefore().mean;
                        allMasses[i] = transition.getBefore().mass;
                    }
                    transitionDates[i] = transition.getDate();
                    allOrbits[++i]     = transition.getAfter().mean;
                    allMasses[i]       = transition.getAfter().mass;
                }
            }

            return new DataTransferObject(getInitialState().getOrbit(), initialModel.mass,
                                          referenceRadius, mu, ck0, getAttitudeProvider(),
                                          transitionDates, allOrbits, allMasses,
                                          serializableProviders.toArray(new AdditionalStateProvider[serializableProviders.size()]));
        } catch (OrekitException orekitException) {
            // this should never happen
            throw new OrekitInternalError(null);
        }

    }

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

        /** Serializable UID. */
        private static final long serialVersionUID = 20151202L;

        /** Initial orbit. */
        private final Orbit orbit;

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

        /** Mass and gravity field. */
        private double[] g;

        /** Transition dates (may be null). */
        private final AbsoluteDate[] transitionDates;

        /** Orbits before and after transitions (may be null). */
        private final CircularOrbit[] allOrbits;

        /** Masses before and after transitions (may be null). */
        private final double[] allMasses;

        /** Providers for additional states. */
        private final AdditionalStateProvider[] providers;

        /** Simple constructor.
         * @param orbit initial orbit
         * @param mass spacecraft mass
         * @param referenceRadius reference radius of the Earth for the potential model (m)
         * @param mu central attraction coefficient (m³/s²)
         * @param ck0 un-normalized zonal coefficients
         * @param attitudeProvider attitude provider
         * @param transitionDates transition dates (may be null)
         * @param allOrbits orbits before and after transitions (may be null)
         * @param allMasses masses before and after transitions (may be null)
         * @param providers providers for additional states
         */
        DataTransferObject(final Orbit orbit, final double mass,
                           final double referenceRadius, final double mu,
                           final double[] ck0,
                           final AttitudeProvider attitudeProvider,
                           final AbsoluteDate[] transitionDates,
                           final CircularOrbit[] allOrbits,
                           final double[] allMasses,
                           final AdditionalStateProvider[] providers) {
            this.orbit            = orbit;
            this.attitudeProvider = attitudeProvider;
            this.g = new double[] {
                mass, referenceRadius, mu,
                ck0[2], ck0[3], ck0[4], ck0[5], ck0[6] // ck0[0] and ck0[1] are both zero so not serialized
            };
            this.transitionDates  = transitionDates;
            this.allOrbits        = allOrbits;
            this.allMasses        = allMasses;
            this.providers        = providers;
        }

        /** Replace the deserialized data transfer object with a {@link EcksteinHechlerPropagator}.
         * @return replacement {@link EcksteinHechlerPropagator}
         */
        private Object readResolve() {
            try {
                final EcksteinHechlerPropagator propagator =
                                new EcksteinHechlerPropagator(orbit, attitudeProvider,
                                                              g[0], g[1], g[2],              // mass, referenceRadius, mu
                                                              g[3], g[4], g[5], g[6], g[7]); // c20, c30, c40, c50, c60
                for (final AdditionalStateProvider provider : providers) {
                    propagator.addAdditionalStateProvider(provider);

                }
                if (transitionDates != null) {
                    // override the state transitions
                    final double[] ck0 = new double[] {
                        0, 0, g[3], g[4], g[5], g[6], g[7]
                    };
                    propagator.models = new TimeSpanMap<EHModel>(new EHModel(allOrbits[0], allMasses[0],
                                                                             g[1], g[2], ck0));
                    for (int i = 0; i < transitionDates.length; ++i) {
                        propagator.models.addValidAfter(new EHModel(allOrbits[i + 1], allMasses[i + 1],
                                                                    g[1], g[2], ck0),
                                                        transitionDates[i]);
                    }
                }

                return propagator;
            } catch (OrekitException oe) {
                throw new OrekitInternalError(oe);
            }
        }

    }

}