HolmesFeatherstoneAttractionModel.java

  1. /* Copyright 2002-2024 CS GROUP
  2.  * Licensed to CS GROUP (CS) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * CS licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *   http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.orekit.forces.gravity;


  18. import java.util.Collections;
  19. import java.util.List;

  20. import org.hipparchus.CalculusFieldElement;
  21. import org.hipparchus.analysis.differentiation.DerivativeStructure;
  22. import org.hipparchus.analysis.differentiation.Gradient;
  23. import org.hipparchus.geometry.euclidean.threed.FieldVector3D;
  24. import org.hipparchus.geometry.euclidean.threed.SphericalCoordinates;
  25. import org.hipparchus.geometry.euclidean.threed.Vector3D;
  26. import org.hipparchus.linear.Array2DRowRealMatrix;
  27. import org.hipparchus.linear.RealMatrix;
  28. import org.hipparchus.util.FastMath;
  29. import org.hipparchus.util.MathArrays;
  30. import org.orekit.forces.ForceModel;
  31. import org.orekit.forces.gravity.potential.NormalizedSphericalHarmonicsProvider;
  32. import org.orekit.forces.gravity.potential.NormalizedSphericalHarmonicsProvider.NormalizedSphericalHarmonics;
  33. import org.orekit.forces.gravity.potential.TideSystem;
  34. import org.orekit.forces.gravity.potential.TideSystemProvider;
  35. import org.orekit.frames.FieldStaticTransform;
  36. import org.orekit.frames.Frame;
  37. import org.orekit.frames.StaticTransform;
  38. import org.orekit.propagation.FieldSpacecraftState;
  39. import org.orekit.propagation.SpacecraftState;
  40. import org.orekit.time.AbsoluteDate;
  41. import org.orekit.time.FieldAbsoluteDate;
  42. import org.orekit.utils.FieldPVCoordinates;
  43. import org.orekit.utils.ParameterDriver;

  44. /** This class represents the gravitational field of a celestial body.
  45.  * <p>
  46.  * The algorithm implemented in this class has been designed by S. A. Holmes
  47.  * and W. E. Featherstone from Department of Spatial Sciences, Curtin University
  48.  * of Technology, Perth, Australia. It is described in their 2002 paper: <a
  49.  * href="https://www.researchgate.net/publication/226460594_A_unified_approach_to_the_Clenshaw_summation_and_the_recursive_computation_of_very_high_degree_and_order_normalised_associated_Legendre_functions">
  50.  * A unified approach to he Clenshaw summation and the recursive computation of
  51.  * very high degree and order normalised associated Legendre functions</a>
  52.  * (Journal of Geodesy (2002) 76: 279–299).
  53.  * </p>
  54.  * <p>
  55.  * This model directly uses normalized coefficients and stable recursion algorithms
  56.  * so it is more suited to high degree gravity fields than the classical Cunningham
  57.  * Droziner models which use un-normalized coefficients.
  58.  * </p>
  59.  * <p>
  60.  * Among the different algorithms presented in Holmes and Featherstone paper, this
  61.  * class implements the <em>modified forward row method</em>. All recursion coefficients
  62.  * are precomputed and stored for greater performance. This caching was suggested in the
  63.  * paper but not used due to the large memory requirements. Since 2002, even low end
  64.  * computers and mobile devices do have sufficient memory so this caching has become
  65.  * feasible nowadays.
  66.  * </p>
  67.  * @author Luc Maisonobe
  68.  * @since 6.0
  69.  */

  70. public class HolmesFeatherstoneAttractionModel implements ForceModel, TideSystemProvider {

  71.     /** Exponent scaling to avoid floating point overflow.
  72.      * <p>The paper uses 10^280, we prefer a power of two to preserve accuracy thanks to
  73.      * {@link FastMath#scalb(double, int)}, so we use 2^930 which has the same order of magnitude.
  74.      */
  75.     private static final int SCALING = 930;

  76.     /** Central attraction scaling factor.
  77.      * <p>
  78.      * We use a power of 2 to avoid numeric noise introduction
  79.      * in the multiplications/divisions sequences.
  80.      * </p>
  81.      */
  82.     private static final double MU_SCALE = FastMath.scalb(1.0, 32);

  83.     /** Driver for gravitational parameter. */
  84.     private final ParameterDriver gmParameterDriver;

  85.     /** Provider for the spherical harmonics. */
  86.     private final NormalizedSphericalHarmonicsProvider provider;

  87.     /** Rotating body. */
  88.     private final Frame bodyFrame;

  89.     /** Recursion coefficients g<sub>n,m</sub>/√j. */
  90.     private final double[] gnmOj;

  91.     /** Recursion coefficients h<sub>n,m</sub>/√j. */
  92.     private final double[] hnmOj;

  93.     /** Recursion coefficients e<sub>n,m</sub>. */
  94.     private final double[] enm;

  95.     /** Scaled sectorial Pbar<sub>m,m</sub>/u<sup>m</sup> &times; 2<sup>-SCALING</sup>. */
  96.     private final double[] sectorial;

  97.     /** Creates a new instance.
  98.      * @param centralBodyFrame rotating body frame
  99.      * @param provider provider for spherical harmonics
  100.      * @since 6.0
  101.      */
  102.     public HolmesFeatherstoneAttractionModel(final Frame centralBodyFrame,
  103.                                              final NormalizedSphericalHarmonicsProvider provider) {

  104.         gmParameterDriver = new ParameterDriver(NewtonianAttraction.CENTRAL_ATTRACTION_COEFFICIENT,
  105.                                                 provider.getMu(), MU_SCALE, 0.0, Double.POSITIVE_INFINITY);

  106.         this.provider  = provider;
  107.         this.bodyFrame = centralBodyFrame;

  108.         // the pre-computed arrays hold coefficients from triangular arrays in a single
  109.         // storing neither diagonal elements (n = m) nor the non-diagonal element n=1, m=0
  110.         final int degree = provider.getMaxDegree();
  111.         final int size = FastMath.max(0, degree * (degree + 1) / 2 - 1);
  112.         gnmOj = new double[size];
  113.         hnmOj = new double[size];
  114.         enm   = new double[size];

  115.         // pre-compute the recursion coefficients corresponding to equations 19 and 22
  116.         // from Holmes and Featherstone paper
  117.         // for cache efficiency, elements are stored in the same order they will be used
  118.         // later on, i.e. from rightmost column to leftmost column
  119.         int index = 0;
  120.         for (int m = degree; m >= 0; --m) {
  121.             final int j = (m == 0) ? 2 : 1;
  122.             for (int n = FastMath.max(2, m + 1); n <= degree; ++n) {
  123.                 final double f = (n - m) * (n + m + 1);
  124.                 gnmOj[index] = 2 * (m + 1) / FastMath.sqrt(j * f);
  125.                 hnmOj[index] = FastMath.sqrt((n + m + 2) * (n - m - 1) / (j * f));
  126.                 enm[index]   = FastMath.sqrt(f / j);
  127.                 ++index;
  128.             }
  129.         }

  130.         // scaled sectorial terms corresponding to equation 28 in Holmes and Featherstone paper
  131.         sectorial    = new double[degree + 1];
  132.         sectorial[0] = FastMath.scalb(1.0, -SCALING);
  133.         if (degree > 0) {
  134.             sectorial[1] = FastMath.sqrt(3) * sectorial[0];
  135.         }
  136.         for (int m = 2; m < sectorial.length; ++m) {
  137.             sectorial[m] = FastMath.sqrt((2 * m + 1) / (2.0 * m)) * sectorial[m - 1];
  138.         }

  139.     }

  140.     /** {@inheritDoc} */
  141.     @Override
  142.     public boolean dependsOnPositionOnly() {
  143.         return true;
  144.     }

  145.     /** {@inheritDoc} */
  146.     public TideSystem getTideSystem() {
  147.         return provider.getTideSystem();
  148.     }

  149.     /** Get the central attraction coefficient μ.
  150.      * @return mu central attraction coefficient (m³/s²),
  151.      * will throw an exception if gm PDriver has several
  152.      * values driven (in this case the method
  153.      * {@link #getMu(AbsoluteDate)} must be used.
  154.      */
  155.     public double getMu() {
  156.         return gmParameterDriver.getValue();
  157.     }

  158.     /** Get the central attraction coefficient μ.
  159.      * @param date date at which mu wants to be known
  160.      * @return mu central attraction coefficient (m³/s²)
  161.      */
  162.     public double getMu(final AbsoluteDate date) {
  163.         return gmParameterDriver.getValue(date);
  164.     }

  165.     /** Compute the value of the gravity field.
  166.      * @param date current date
  167.      * @param position position at which gravity field is desired in body frame
  168.      * @param mu central attraction coefficient to use
  169.      * @return value of the gravity field (central and non-central parts summed together)
  170.      */
  171.     public double value(final AbsoluteDate date, final Vector3D position,
  172.                         final double mu) {
  173.         return mu / position.getNorm() + nonCentralPart(date, position, mu);
  174.     }

  175.     /** Compute the non-central part of the gravity field.
  176.      * @param date current date
  177.      * @param position position at which gravity field is desired in body frame
  178.      * @param mu central attraction coefficient to use
  179.      * @return value of the non-central part of the gravity field
  180.      */
  181.     public double nonCentralPart(final AbsoluteDate date, final Vector3D position, final double mu) {

  182.         final int degree = provider.getMaxDegree();
  183.         final int order  = provider.getMaxOrder();
  184.         final NormalizedSphericalHarmonics harmonics = provider.onDate(date);

  185.         // allocate the columns for recursion
  186.         double[] pnm0Plus2 = new double[degree + 1];
  187.         double[] pnm0Plus1 = new double[degree + 1];
  188.         double[] pnm0      = new double[degree + 1];

  189.         // compute polar coordinates
  190.         final double x    = position.getX();
  191.         final double y    = position.getY();
  192.         final double z    = position.getZ();
  193.         final double x2   = x * x;
  194.         final double y2   = y * y;
  195.         final double z2   = z * z;
  196.         final double rho2 = x2 + y2;
  197.         final double r2   = rho2 + z2;
  198.         final double r    = FastMath.sqrt(r2);
  199.         final double rho  = FastMath.sqrt(rho2);
  200.         final double t    = z / r;   // cos(theta), where theta is the polar angle
  201.         final double u    = rho / r; // sin(theta), where theta is the polar angle
  202.         final double tOu  = z / rho;

  203.         // compute distance powers
  204.         final double[] aOrN = createDistancePowersArray(provider.getAe() / r);

  205.         // compute longitude cosines/sines
  206.         final double[][] cosSinLambda = createCosSinArrays(x / rho, y / rho);

  207.         // outer summation over order
  208.         int    index = 0;
  209.         double value = 0;
  210.         for (int m = degree; m >= 0; --m) {

  211.             // compute tesseral terms without derivatives
  212.             index = computeTesseral(m, degree, index, t, u, tOu,
  213.                                     pnm0Plus2, pnm0Plus1, null, pnm0, null, null);

  214.             if (m <= order) {
  215.                 // compute contribution of current order to field (equation 5 of the paper)

  216.                 // inner summation over degree, for fixed order
  217.                 double sumDegreeS        = 0;
  218.                 double sumDegreeC        = 0;
  219.                 for (int n = FastMath.max(2, m); n <= degree; ++n) {
  220.                     sumDegreeS += pnm0[n] * aOrN[n] * harmonics.getNormalizedSnm(n, m);
  221.                     sumDegreeC += pnm0[n] * aOrN[n] * harmonics.getNormalizedCnm(n, m);
  222.                 }

  223.                 // contribution to outer summation over order
  224.                 value = value * u + cosSinLambda[1][m] * sumDegreeS + cosSinLambda[0][m] * sumDegreeC;

  225.             }

  226.             // rotate the recursion arrays
  227.             final double[] tmp = pnm0Plus2;
  228.             pnm0Plus2 = pnm0Plus1;
  229.             pnm0Plus1 = pnm0;
  230.             pnm0      = tmp;

  231.         }

  232.         // scale back
  233.         value = FastMath.scalb(value, SCALING);

  234.         // apply the global mu/r factor
  235.         return mu * value / r;

  236.     }

  237.     /** Compute the gradient of the non-central part of the gravity field.
  238.      * @param date current date
  239.      * @param position position at which gravity field is desired in body frame
  240.      * @param mu central attraction coefficient to use
  241.      * @return gradient of the non-central part of the gravity field
  242.      */
  243.     public double[] gradient(final AbsoluteDate date, final Vector3D position, final double mu) {

  244.         final int degree = provider.getMaxDegree();
  245.         final int order  = provider.getMaxOrder();
  246.         final NormalizedSphericalHarmonics harmonics = provider.onDate(date);

  247.         // allocate the columns for recursion
  248.         double[] pnm0Plus2  = new double[degree + 1];
  249.         double[] pnm0Plus1  = new double[degree + 1];
  250.         double[] pnm0       = new double[degree + 1];
  251.         final double[] pnm1 = new double[degree + 1];

  252.         // compute polar coordinates
  253.         final double x    = position.getX();
  254.         final double y    = position.getY();
  255.         final double z    = position.getZ();
  256.         final double x2   = x * x;
  257.         final double y2   = y * y;
  258.         final double z2   = z * z;
  259.         final double r2   = x2 + y2 + z2;
  260.         final double r    = FastMath.sqrt (r2);
  261.         final double rho2 = x2 + y2;
  262.         final double rho  = FastMath.sqrt(rho2);
  263.         final double t    = z / r;   // cos(theta), where theta is the polar angle
  264.         final double u    = rho / r; // sin(theta), where theta is the polar angle
  265.         final double tOu  = z / rho;

  266.         // compute distance powers
  267.         final double[] aOrN = createDistancePowersArray(provider.getAe() / r);

  268.         // compute longitude cosines/sines
  269.         final double[][] cosSinLambda = createCosSinArrays(x / rho, y / rho);

  270.         // outer summation over order
  271.         int    index = 0;
  272.         double value = 0;
  273.         final double[] gradient = new double[3];
  274.         for (int m = degree; m >= 0; --m) {

  275.             // compute tesseral terms with derivatives
  276.             index = computeTesseral(m, degree, index, t, u, tOu,
  277.                                     pnm0Plus2, pnm0Plus1, null, pnm0, pnm1, null);

  278.             if (m <= order) {
  279.                 // compute contribution of current order to field (equation 5 of the paper)

  280.                 // inner summation over degree, for fixed order
  281.                 double sumDegreeS        = 0;
  282.                 double sumDegreeC        = 0;
  283.                 double dSumDegreeSdR     = 0;
  284.                 double dSumDegreeCdR     = 0;
  285.                 double dSumDegreeSdTheta = 0;
  286.                 double dSumDegreeCdTheta = 0;
  287.                 for (int n = FastMath.max(2, m); n <= degree; ++n) {
  288.                     final double qSnm  = aOrN[n] * harmonics.getNormalizedSnm(n, m);
  289.                     final double qCnm  = aOrN[n] * harmonics.getNormalizedCnm(n, m);
  290.                     final double nOr   = n / r;
  291.                     final double s0    = pnm0[n] * qSnm;
  292.                     final double c0    = pnm0[n] * qCnm;
  293.                     final double s1    = pnm1[n] * qSnm;
  294.                     final double c1    = pnm1[n] * qCnm;
  295.                     sumDegreeS        += s0;
  296.                     sumDegreeC        += c0;
  297.                     dSumDegreeSdR     -= nOr * s0;
  298.                     dSumDegreeCdR     -= nOr * c0;
  299.                     dSumDegreeSdTheta += s1;
  300.                     dSumDegreeCdTheta += c1;
  301.                 }

  302.                 // contribution to outer summation over order
  303.                 // beware that we need to order gradient using the mathematical conventions
  304.                 // compliant with the SphericalCoordinates class, so our lambda is its theta
  305.                 // (and hence at index 1) and our theta is its phi (and hence at index 2)
  306.                 final double sML = cosSinLambda[1][m];
  307.                 final double cML = cosSinLambda[0][m];
  308.                 value            = value       * u + sML * sumDegreeS        + cML * sumDegreeC;
  309.                 gradient[0]      = gradient[0] * u + sML * dSumDegreeSdR     + cML * dSumDegreeCdR;
  310.                 gradient[1]      = gradient[1] * u + m * (cML * sumDegreeS - sML * sumDegreeC);
  311.                 gradient[2]      = gradient[2] * u + sML * dSumDegreeSdTheta + cML * dSumDegreeCdTheta;

  312.             }

  313.             // rotate the recursion arrays
  314.             final double[] tmp = pnm0Plus2;
  315.             pnm0Plus2 = pnm0Plus1;
  316.             pnm0Plus1 = pnm0;
  317.             pnm0      = tmp;

  318.         }

  319.         // scale back
  320.         value       = FastMath.scalb(value,       SCALING);
  321.         gradient[0] = FastMath.scalb(gradient[0], SCALING);
  322.         gradient[1] = FastMath.scalb(gradient[1], SCALING);
  323.         gradient[2] = FastMath.scalb(gradient[2], SCALING);

  324.         // apply the global mu/r factor
  325.         final double muOr = mu / r;
  326.         value            *= muOr;
  327.         gradient[0]       = muOr * gradient[0] - value / r;
  328.         gradient[1]      *= muOr;
  329.         gradient[2]      *= muOr;

  330.         // convert gradient from spherical to Cartesian
  331.         return new SphericalCoordinates(position).toCartesianGradient(gradient);

  332.     }

  333.     /** Compute the gradient of the non-central part of the gravity field.
  334.      * @param date current date
  335.      * @param position position at which gravity field is desired in body frame
  336.      * @param mu central attraction coefficient to use
  337.      * @param <T> type of field used
  338.      * @return gradient of the non-central part of the gravity field
  339.      */
  340.     public <T extends CalculusFieldElement<T>> T[] gradient(final FieldAbsoluteDate<T> date, final FieldVector3D<T> position,
  341.                                                         final T mu) {

  342.         final int degree = provider.getMaxDegree();
  343.         final int order  = provider.getMaxOrder();
  344.         final NormalizedSphericalHarmonics harmonics = provider.onDate(date.toAbsoluteDate());
  345.         final T zero = date.getField().getZero();
  346.         // allocate the columns for recursion
  347.         T[] pnm0Plus2  = MathArrays.buildArray(date.getField(), degree + 1);
  348.         T[] pnm0Plus1  = MathArrays.buildArray(date.getField(), degree + 1);
  349.         T[] pnm0       = MathArrays.buildArray(date.getField(), degree + 1);
  350.         final T[] pnm1 = MathArrays.buildArray(date.getField(), degree + 1);

  351.         // compute polar coordinates
  352.         final T x    = position.getX();
  353.         final T y    = position.getY();
  354.         final T z    = position.getZ();
  355.         final T x2   = x.square();
  356.         final T y2   = y.square();
  357.         final T rho2 = x2.add(y2);
  358.         final T rho  = rho2.sqrt();
  359.         final T z2   = z.square();
  360.         final T r2   = rho2.add(z2);
  361.         final T r    = r2.sqrt();
  362.         final T t    = z.divide(r);   // cos(theta), where theta is the polar angle
  363.         final T u    = rho.divide(r); // sin(theta), where theta is the polar angle
  364.         final T tOu  = z.divide(rho);

  365.         // compute distance powers
  366.         final T[] aOrN = createDistancePowersArray(r.reciprocal().multiply(provider.getAe()));

  367.         // compute longitude cosines/sines
  368.         final T[][] cosSinLambda = createCosSinArrays(x.divide(rho), y.divide(rho));
  369.         // outer summation over order
  370.         int    index = 0;
  371.         T value = zero;
  372.         final T[] gradient = MathArrays.buildArray(zero.getField(), 3);
  373.         for (int m = degree; m >= 0; --m) {

  374.             // compute tesseral terms with derivatives
  375.             index = computeTesseral(m, degree, index, t, u, tOu,
  376.                                     pnm0Plus2, pnm0Plus1, null, pnm0, pnm1, null);
  377.             if (m <= order) {
  378.                 // compute contribution of current order to field (equation 5 of the paper)

  379.                 // inner summation over degree, for fixed order
  380.                 T sumDegreeS        = zero;
  381.                 T sumDegreeC        = zero;
  382.                 T dSumDegreeSdR     = zero;
  383.                 T dSumDegreeCdR     = zero;
  384.                 T dSumDegreeSdTheta = zero;
  385.                 T dSumDegreeCdTheta = zero;
  386.                 for (int n = FastMath.max(2, m); n <= degree; ++n) {
  387.                     final T qSnm  = aOrN[n].multiply(harmonics.getNormalizedSnm(n, m));
  388.                     final T qCnm  = aOrN[n].multiply(harmonics.getNormalizedCnm(n, m));
  389.                     final T nOr   = r.reciprocal().multiply(n);
  390.                     final T s0    = pnm0[n].multiply(qSnm);
  391.                     final T c0    = pnm0[n].multiply(qCnm);
  392.                     final T s1    = pnm1[n].multiply(qSnm);
  393.                     final T c1    = pnm1[n].multiply(qCnm);
  394.                     sumDegreeS        = sumDegreeS       .add(s0);
  395.                     sumDegreeC        = sumDegreeC       .add(c0);
  396.                     dSumDegreeSdR     = dSumDegreeSdR    .subtract(nOr.multiply(s0));
  397.                     dSumDegreeCdR     = dSumDegreeCdR    .subtract(nOr.multiply(c0));
  398.                     dSumDegreeSdTheta = dSumDegreeSdTheta.add(s1);
  399.                     dSumDegreeCdTheta = dSumDegreeCdTheta.add(c1);
  400.                 }

  401.                 // contribution to outer summation over order
  402.                 // beware that we need to order gradient using the mathematical conventions
  403.                 // compliant with the SphericalCoordinates class, so our lambda is its theta
  404.                 // (and hence at index 1) and our theta is its phi (and hence at index 2)
  405.                 final T sML = cosSinLambda[1][m];
  406.                 final T cML = cosSinLambda[0][m];
  407.                 value            = value      .multiply(u).add(sML.multiply(sumDegreeS   )).add(cML.multiply(sumDegreeC));
  408.                 gradient[0]      = gradient[0].multiply(u).add(sML.multiply(dSumDegreeSdR)).add(cML.multiply(dSumDegreeCdR));
  409.                 gradient[1]      = gradient[1].multiply(u).add(cML.multiply(sumDegreeS).subtract(sML.multiply(sumDegreeC)).multiply(m));
  410.                 gradient[2]      = gradient[2].multiply(u).add(sML.multiply(dSumDegreeSdTheta)).add(cML.multiply(dSumDegreeCdTheta));
  411.             }
  412.             // rotate the recursion arrays
  413.             final T[] tmp = pnm0Plus2;
  414.             pnm0Plus2 = pnm0Plus1;
  415.             pnm0Plus1 = pnm0;
  416.             pnm0      = tmp;

  417.         }
  418.         // scale back
  419.         value       = value.scalb(SCALING);
  420.         gradient[0] = gradient[0].scalb(SCALING);
  421.         gradient[1] = gradient[1].scalb(SCALING);
  422.         gradient[2] = gradient[2].scalb(SCALING);

  423.         // apply the global mu/r factor
  424.         final T muOr = r.reciprocal().multiply(mu);
  425.         value            = value.multiply(muOr);
  426.         gradient[0]      = muOr.multiply(gradient[0]).subtract(value.divide(r));
  427.         gradient[1]      = gradient[1].multiply(muOr);
  428.         gradient[2]      = gradient[2].multiply(muOr);

  429.         // convert gradient from spherical to Cartesian
  430.         // Cartesian coordinates
  431.         // remaining spherical coordinates

  432.         // intermediate variables
  433.         final T xPos    = position.getX();
  434.         final T yPos    = position.getY();
  435.         final T zPos    = position.getZ();
  436.         final T rho2Pos = x.square().add(y.square());
  437.         final T rhoPos  = rho2.sqrt();
  438.         final T r2Pos   = rho2.add(z.square());
  439.         final T rPos    = r2Pos.sqrt();

  440.         final T[][] jacobianPos = MathArrays.buildArray(zero.getField(), 3, 3);

  441.         // row representing the gradient of r
  442.         jacobianPos[0][0] = xPos.divide(rPos);
  443.         jacobianPos[0][1] = yPos.divide(rPos);
  444.         jacobianPos[0][2] = zPos.divide(rPos);

  445.         // row representing the gradient of theta
  446.         jacobianPos[1][0] =  yPos.negate().divide(rho2Pos);
  447.         jacobianPos[1][1] =  xPos.divide(rho2Pos);
  448.         // jacobian[1][2] is already set to 0 at allocation time

  449.         // row representing the gradient of phi
  450.         final T rhoPosTimesR2Pos = rhoPos.multiply(r2Pos);
  451.         jacobianPos[2][0] = xPos.multiply(zPos).divide(rhoPosTimesR2Pos);
  452.         jacobianPos[2][1] = yPos.multiply(zPos).divide(rhoPosTimesR2Pos);
  453.         jacobianPos[2][2] = rhoPos.negate().divide(r2Pos);
  454.         final T[] cartGradPos = MathArrays.buildArray(zero.getField(), 3);
  455.         cartGradPos[0] = gradient[0].multiply(jacobianPos[0][0]).add(gradient[1].multiply(jacobianPos[1][0])).add(gradient[2].multiply(jacobianPos[2][0]));
  456.         cartGradPos[1] = gradient[0].multiply(jacobianPos[0][1]).add(gradient[1].multiply(jacobianPos[1][1])).add(gradient[2].multiply(jacobianPos[2][1]));
  457.         cartGradPos[2] = gradient[0].multiply(jacobianPos[0][2])                                      .add(gradient[2].multiply(jacobianPos[2][2]));
  458.         return cartGradPos;

  459.     }

  460.     /** Compute both the gradient and the hessian of the non-central part of the gravity field.
  461.      * @param date current date
  462.      * @param position position at which gravity field is desired in body frame
  463.      * @param mu central attraction coefficient to use
  464.      * @return gradient and hessian of the non-central part of the gravity field
  465.      */
  466.     private GradientHessian gradientHessian(final AbsoluteDate date, final Vector3D position, final double mu) {

  467.         final int degree = provider.getMaxDegree();
  468.         final int order  = provider.getMaxOrder();
  469.         final NormalizedSphericalHarmonics harmonics = provider.onDate(date);

  470.         // allocate the columns for recursion
  471.         double[] pnm0Plus2  = new double[degree + 1];
  472.         double[] pnm0Plus1  = new double[degree + 1];
  473.         double[] pnm0       = new double[degree + 1];
  474.         double[] pnm1Plus1  = new double[degree + 1];
  475.         double[] pnm1       = new double[degree + 1];
  476.         final double[] pnm2 = new double[degree + 1];

  477.         // compute polar coordinates
  478.         final double x    = position.getX();
  479.         final double y    = position.getY();
  480.         final double z    = position.getZ();
  481.         final double x2   = x * x;
  482.         final double y2   = y * y;
  483.         final double z2   = z * z;
  484.         final double rho2 = x2 + y2;
  485.         final double rho  = FastMath.sqrt(rho2);
  486.         final double r2   = rho2 + z2;
  487.         final double r    = FastMath.sqrt(r2);
  488.         final double t    = z / r;   // cos(theta), where theta is the polar angle
  489.         final double u    = rho / r; // sin(theta), where theta is the polar angle
  490.         final double tOu  = z / rho;

  491.         // compute distance powers
  492.         final double[] aOrN = createDistancePowersArray(provider.getAe() / r);

  493.         // compute longitude cosines/sines
  494.         final double[][] cosSinLambda = createCosSinArrays(x / rho, y / rho);

  495.         // outer summation over order
  496.         int    index = 0;
  497.         double value = 0;
  498.         final double[]   gradient = new double[3];
  499.         final double[][] hessian  = new double[3][3];
  500.         for (int m = degree; m >= 0; --m) {

  501.             // compute tesseral terms
  502.             index = computeTesseral(m, degree, index, t, u, tOu,
  503.                                     pnm0Plus2, pnm0Plus1, pnm1Plus1, pnm0, pnm1, pnm2);

  504.             if (m <= order) {
  505.                 // compute contribution of current order to field (equation 5 of the paper)

  506.                 // inner summation over degree, for fixed order
  507.                 double sumDegreeS               = 0;
  508.                 double sumDegreeC               = 0;
  509.                 double dSumDegreeSdR            = 0;
  510.                 double dSumDegreeCdR            = 0;
  511.                 double dSumDegreeSdTheta        = 0;
  512.                 double dSumDegreeCdTheta        = 0;
  513.                 double d2SumDegreeSdRdR         = 0;
  514.                 double d2SumDegreeSdRdTheta     = 0;
  515.                 double d2SumDegreeSdThetadTheta = 0;
  516.                 double d2SumDegreeCdRdR         = 0;
  517.                 double d2SumDegreeCdRdTheta     = 0;
  518.                 double d2SumDegreeCdThetadTheta = 0;
  519.                 for (int n = FastMath.max(2, m); n <= degree; ++n) {
  520.                     final double qSnm         = aOrN[n] * harmonics.getNormalizedSnm(n, m);
  521.                     final double qCnm         = aOrN[n] * harmonics.getNormalizedCnm(n, m);
  522.                     final double nOr          = n / r;
  523.                     final double nnP1Or2      = nOr * (n + 1) / r;
  524.                     final double s0           = pnm0[n] * qSnm;
  525.                     final double c0           = pnm0[n] * qCnm;
  526.                     final double s1           = pnm1[n] * qSnm;
  527.                     final double c1           = pnm1[n] * qCnm;
  528.                     final double s2           = pnm2[n] * qSnm;
  529.                     final double c2           = pnm2[n] * qCnm;
  530.                     sumDegreeS               += s0;
  531.                     sumDegreeC               += c0;
  532.                     dSumDegreeSdR            -= nOr * s0;
  533.                     dSumDegreeCdR            -= nOr * c0;
  534.                     dSumDegreeSdTheta        += s1;
  535.                     dSumDegreeCdTheta        += c1;
  536.                     d2SumDegreeSdRdR         += nnP1Or2 * s0;
  537.                     d2SumDegreeSdRdTheta     -= nOr * s1;
  538.                     d2SumDegreeSdThetadTheta += s2;
  539.                     d2SumDegreeCdRdR         += nnP1Or2 * c0;
  540.                     d2SumDegreeCdRdTheta     -= nOr * c1;
  541.                     d2SumDegreeCdThetadTheta += c2;
  542.                 }

  543.                 // contribution to outer summation over order
  544.                 final double sML = cosSinLambda[1][m];
  545.                 final double cML = cosSinLambda[0][m];
  546.                 value            = value         * u + sML * sumDegreeS + cML * sumDegreeC;
  547.                 gradient[0]      = gradient[0]   * u + sML * dSumDegreeSdR + cML * dSumDegreeCdR;
  548.                 gradient[1]      = gradient[1]   * u + m * (cML * sumDegreeS - sML * sumDegreeC);
  549.                 gradient[2]      = gradient[2]   * u + sML * dSumDegreeSdTheta + cML * dSumDegreeCdTheta;
  550.                 hessian[0][0]    = hessian[0][0] * u + sML * d2SumDegreeSdRdR + cML * d2SumDegreeCdRdR;
  551.                 hessian[1][0]    = hessian[1][0] * u + m * (cML * dSumDegreeSdR - sML * dSumDegreeCdR);
  552.                 hessian[2][0]    = hessian[2][0] * u + sML * d2SumDegreeSdRdTheta + cML * d2SumDegreeCdRdTheta;
  553.                 hessian[1][1]    = hessian[1][1] * u - m * m * (sML * sumDegreeS + cML * sumDegreeC);
  554.                 hessian[2][1]    = hessian[2][1] * u + m * (cML * dSumDegreeSdTheta - sML * dSumDegreeCdTheta);
  555.                 hessian[2][2]    = hessian[2][2] * u + sML * d2SumDegreeSdThetadTheta + cML * d2SumDegreeCdThetadTheta;

  556.             }

  557.             // rotate the recursion arrays
  558.             final double[] tmp0 = pnm0Plus2;
  559.             pnm0Plus2 = pnm0Plus1;
  560.             pnm0Plus1 = pnm0;
  561.             pnm0      = tmp0;
  562.             final double[] tmp1 = pnm1Plus1;
  563.             pnm1Plus1 = pnm1;
  564.             pnm1      = tmp1;

  565.         }

  566.         // scale back
  567.         value = FastMath.scalb(value, SCALING);
  568.         for (int i = 0; i < 3; ++i) {
  569.             gradient[i] = FastMath.scalb(gradient[i], SCALING);
  570.             for (int j = 0; j <= i; ++j) {
  571.                 hessian[i][j] = FastMath.scalb(hessian[i][j], SCALING);
  572.             }
  573.         }


  574.         // apply the global mu/r factor
  575.         final double muOr = mu / r;
  576.         value         *= muOr;
  577.         gradient[0]    = muOr * gradient[0] - value / r;
  578.         gradient[1]   *= muOr;
  579.         gradient[2]   *= muOr;
  580.         hessian[0][0]  = muOr * hessian[0][0] - 2 * gradient[0] / r;
  581.         hessian[1][0]  = muOr * hessian[1][0] -     gradient[1] / r;
  582.         hessian[2][0]  = muOr * hessian[2][0] -     gradient[2] / r;
  583.         hessian[1][1] *= muOr;
  584.         hessian[2][1] *= muOr;
  585.         hessian[2][2] *= muOr;

  586.         // convert gradient and Hessian from spherical to Cartesian
  587.         final SphericalCoordinates sc = new SphericalCoordinates(position);
  588.         return new GradientHessian(sc.toCartesianGradient(gradient),
  589.                                    sc.toCartesianHessian(hessian, gradient));


  590.     }

  591.     /** Container for gradient and Hessian. */
  592.     private static class GradientHessian {

  593.         /** Gradient. */
  594.         private final double[] gradient;

  595.         /** Hessian. */
  596.         private final double[][] hessian;

  597.         /** Simple constructor.
  598.          * <p>
  599.          * A reference to the arrays is stored, they are <strong>not</strong> cloned.
  600.          * </p>
  601.          * @param gradient gradient
  602.          * @param hessian hessian
  603.          */
  604.         GradientHessian(final double[] gradient, final double[][] hessian) {
  605.             this.gradient = gradient;
  606.             this.hessian  = hessian;
  607.         }

  608.         /** Get a reference to the gradient.
  609.          * @return gradient (a reference to the internal array is returned)
  610.          */
  611.         public double[] getGradient() {
  612.             return gradient;
  613.         }

  614.         /** Get a reference to the Hessian.
  615.          * @return Hessian (a reference to the internal array is returned)
  616.          */
  617.         public double[][] getHessian() {
  618.             return hessian;
  619.         }

  620.     }

  621.     /** Compute a/r powers array.
  622.      * @param aOr a/r
  623.      * @return array containing (a/r)<sup>n</sup>
  624.      */
  625.     private double[] createDistancePowersArray(final double aOr) {

  626.         // initialize array
  627.         final double[] aOrN = new double[provider.getMaxDegree() + 1];
  628.         aOrN[0] = 1;
  629.         if (provider.getMaxDegree() > 0) {
  630.             aOrN[1] = aOr;
  631.         }

  632.         // fill up array
  633.         for (int n = 2; n < aOrN.length; ++n) {
  634.             final int p = n / 2;
  635.             final int q = n - p;
  636.             aOrN[n] = aOrN[p] * aOrN[q];
  637.         }

  638.         return aOrN;

  639.     }
  640.     /** Compute a/r powers array.
  641.      * @param aOr a/r
  642.      * @param <T> type of field used
  643.      * @return array containing (a/r)<sup>n</sup>
  644.      */
  645.     private <T extends CalculusFieldElement<T>> T[] createDistancePowersArray(final T aOr) {

  646.         // initialize array
  647.         final T[] aOrN = MathArrays.buildArray(aOr.getField(), provider.getMaxDegree() + 1);
  648.         aOrN[0] = aOr.getField().getOne();
  649.         if (provider.getMaxDegree() > 0) {
  650.             aOrN[1] = aOr;
  651.         }

  652.         // fill up array
  653.         for (int n = 2; n < aOrN.length; ++n) {
  654.             final int p = n / 2;
  655.             final int q = n - p;
  656.             aOrN[n] = aOrN[p].multiply(aOrN[q]);
  657.         }

  658.         return aOrN;

  659.     }

  660.     /** Compute longitude cosines and sines.
  661.      * @param cosLambda cos(λ)
  662.      * @param sinLambda sin(λ)
  663.      * @return array containing cos(m &times; λ) in row 0
  664.      * and sin(m &times; λ) in row 1
  665.      */
  666.     private double[][] createCosSinArrays(final double cosLambda, final double sinLambda) {

  667.         // initialize arrays
  668.         final double[][] cosSin = new double[2][provider.getMaxOrder() + 1];
  669.         cosSin[0][0] = 1;
  670.         cosSin[1][0] = 0;
  671.         if (provider.getMaxOrder() > 0) {
  672.             cosSin[0][1] = cosLambda;
  673.             cosSin[1][1] = sinLambda;

  674.             // fill up array
  675.             for (int m = 2; m < cosSin[0].length; ++m) {

  676.                 // m * lambda is split as p * lambda + q * lambda, trying to avoid
  677.                 // p or q being much larger than the other. This reduces the number of
  678.                 // intermediate results reused to compute each value, and hence should limit
  679.                 // as much as possible roundoff error accumulation
  680.                 // (this does not change the number of floating point operations)
  681.                 final int p = m / 2;
  682.                 final int q = m - p;

  683.                 cosSin[0][m] = cosSin[0][p] * cosSin[0][q] - cosSin[1][p] * cosSin[1][q];
  684.                 cosSin[1][m] = cosSin[1][p] * cosSin[0][q] + cosSin[0][p] * cosSin[1][q];
  685.             }
  686.         }

  687.         return cosSin;

  688.     }

  689.     /** Compute longitude cosines and sines.
  690.      * @param cosLambda cos(λ)
  691.      * @param sinLambda sin(λ)
  692.      * @param <T> type of field used
  693.      * @return array containing cos(m &times; λ) in row 0
  694.      * and sin(m &times; λ) in row 1
  695.      */
  696.     private <T extends CalculusFieldElement<T>> T[][] createCosSinArrays(final T cosLambda, final T sinLambda) {

  697.         final T one = cosLambda.getField().getOne();
  698.         final T zero = cosLambda.getField().getZero();
  699.         // initialize arrays
  700.         final T[][] cosSin = MathArrays.buildArray(one.getField(), 2, provider.getMaxOrder() + 1);
  701.         cosSin[0][0] = one;
  702.         cosSin[1][0] = zero;
  703.         if (provider.getMaxOrder() > 0) {
  704.             cosSin[0][1] = cosLambda;
  705.             cosSin[1][1] = sinLambda;

  706.             // fill up array
  707.             for (int m = 2; m < cosSin[0].length; ++m) {

  708.                 // m * lambda is split as p * lambda + q * lambda, trying to avoid
  709.                 // p or q being much larger than the other. This reduces the number of
  710.                 // intermediate results reused to compute each value, and hence should limit
  711.                 // as much as possible roundoff error accumulation
  712.                 // (this does not change the number of floating point operations)
  713.                 final int p = m / 2;
  714.                 final int q = m - p;

  715.                 cosSin[0][m] = cosSin[0][p].multiply(cosSin[0][q]).subtract(cosSin[1][p].multiply(cosSin[1][q]));
  716.                 cosSin[1][m] = cosSin[1][p].multiply(cosSin[0][q]).add(cosSin[0][p].multiply(cosSin[1][q]));

  717.             }
  718.         }

  719.         return cosSin;

  720.     }

  721.     /** Compute one order of tesseral terms.
  722.      * <p>
  723.      * This corresponds to equations 27 and 30 of the paper.
  724.      * </p>
  725.      * @param m current order
  726.      * @param degree max degree
  727.      * @param index index in the flattened array
  728.      * @param t cos(θ), where θ is the polar angle
  729.      * @param u sin(θ), where θ is the polar angle
  730.      * @param tOu t/u
  731.      * @param pnm0Plus2 array containing scaled P<sub>n,m+2</sub>/u<sup>m+2</sup>
  732.      * @param pnm0Plus1 array containing scaled P<sub>n,m+1</sub>/u<sup>m+1</sup>
  733.      * @param pnm1Plus1 array containing scaled dP<sub>n,m+1</sub>/u<sup>m+1</sup>
  734.      * (may be null if second derivatives are not needed)
  735.      * @param pnm0 array to fill with scaled P<sub>n,m</sub>/u<sup>m</sup>
  736.      * @param pnm1 array to fill with scaled dP<sub>n,m</sub>/u<sup>m</sup>
  737.      * (may be null if first derivatives are not needed)
  738.      * @param pnm2 array to fill with scaled d²P<sub>n,m</sub>/u<sup>m</sup>
  739.      * (may be null if second derivatives are not needed)
  740.      * @return new value for index
  741.      */
  742.     private int computeTesseral(final int m, final int degree, final int index,
  743.                                 final double t, final double u, final double tOu,
  744.                                 final double[] pnm0Plus2, final double[] pnm0Plus1, final double[] pnm1Plus1,
  745.                                 final double[] pnm0, final double[] pnm1, final double[] pnm2) {

  746.         final double u2 = u * u;

  747.         // initialize recursion from sectorial terms
  748.         int n = FastMath.max(2, m);
  749.         if (n == m) {
  750.             pnm0[n] = sectorial[n];
  751.             ++n;
  752.         }

  753.         // compute tesseral values
  754.         int localIndex = index;
  755.         while (n <= degree) {

  756.             // value (equation 27 of the paper)
  757.             pnm0[n] = gnmOj[localIndex] * t * pnm0Plus1[n] - hnmOj[localIndex] * u2 * pnm0Plus2[n];

  758.             ++localIndex;
  759.             ++n;

  760.         }

  761.         if (pnm1 != null) {

  762.             // initialize recursion from sectorial terms
  763.             n = FastMath.max(2, m);
  764.             if (n == m) {
  765.                 pnm1[n] = m * tOu * pnm0[n];
  766.                 ++n;
  767.             }

  768.             // compute tesseral values and derivatives with respect to polar angle
  769.             localIndex = index;
  770.             while (n <= degree) {

  771.                 // first derivative (equation 30 of the paper)
  772.                 pnm1[n] = m * tOu * pnm0[n] - enm[localIndex] * u * pnm0Plus1[n];

  773.                 ++localIndex;
  774.                 ++n;

  775.             }

  776.             if (pnm2 != null) {

  777.                 // initialize recursion from sectorial terms
  778.                 n = FastMath.max(2, m);
  779.                 if (n == m) {
  780.                     pnm2[n] = m * (tOu * pnm1[n] - pnm0[n] / u2);
  781.                     ++n;
  782.                 }

  783.                 // compute tesseral values and derivatives with respect to polar angle
  784.                 localIndex = index;
  785.                 while (n <= degree) {

  786.                     // second derivative (differential of equation 30 with respect to theta)
  787.                     pnm2[n] = m * (tOu * pnm1[n] - pnm0[n] / u2) - enm[localIndex] * u * pnm1Plus1[n];

  788.                     ++localIndex;
  789.                     ++n;

  790.                 }

  791.             }

  792.         }

  793.         return localIndex;

  794.     }

  795.     /** Compute one order of tesseral terms.
  796.      * <p>
  797.      * This corresponds to equations 27 and 30 of the paper.
  798.      * </p>
  799.      * @param m current order
  800.      * @param degree max degree
  801.      * @param index index in the flattened array
  802.      * @param t cos(θ), where θ is the polar angle
  803.      * @param u sin(θ), where θ is the polar angle
  804.      * @param tOu t/u
  805.      * @param pnm0Plus2 array containing scaled P<sub>n,m+2</sub>/u<sup>m+2</sup>
  806.      * @param pnm0Plus1 array containing scaled P<sub>n,m+1</sub>/u<sup>m+1</sup>
  807.      * @param pnm1Plus1 array containing scaled dP<sub>n,m+1</sub>/u<sup>m+1</sup>
  808.      * (may be null if second derivatives are not needed)
  809.      * @param pnm0 array to fill with scaled P<sub>n,m</sub>/u<sup>m</sup>
  810.      * @param pnm1 array to fill with scaled dP<sub>n,m</sub>/u<sup>m</sup>
  811.      * (may be null if first derivatives are not needed)
  812.      * @param pnm2 array to fill with scaled d²P<sub>n,m</sub>/u<sup>m</sup>
  813.      * (may be null if second derivatives are not needed)
  814.      * @param <T> instance of field element
  815.      * @return new value for index
  816.      */
  817.     private <T extends CalculusFieldElement<T>> int computeTesseral(final int m, final int degree, final int index,
  818.                                                                 final T t, final T u, final T tOu,
  819.                                                                 final T[] pnm0Plus2, final T[] pnm0Plus1, final T[] pnm1Plus1,
  820.                                                                 final T[] pnm0, final T[] pnm1, final T[] pnm2) {

  821.         final T u2 = u.square();
  822.         final T zero = u.getField().getZero();
  823.         // initialize recursion from sectorial terms
  824.         int n = FastMath.max(2, m);
  825.         if (n == m) {
  826.             pnm0[n] = zero.newInstance(sectorial[n]);
  827.             ++n;
  828.         }

  829.         // compute tesseral values
  830.         int localIndex = index;
  831.         while (n <= degree) {

  832.             // value (equation 27 of the paper)
  833.             pnm0[n] = t.multiply(gnmOj[localIndex]).multiply(pnm0Plus1[n]).subtract(u2.multiply(pnm0Plus2[n]).multiply(hnmOj[localIndex]));
  834.             ++localIndex;
  835.             ++n;

  836.         }
  837.         if (pnm1 != null) {

  838.             // initialize recursion from sectorial terms
  839.             n = FastMath.max(2, m);
  840.             if (n == m) {
  841.                 pnm1[n] = tOu.multiply(m).multiply(pnm0[n]);
  842.                 ++n;
  843.             }

  844.             // compute tesseral values and derivatives with respect to polar angle
  845.             localIndex = index;
  846.             while (n <= degree) {

  847.                 // first derivative (equation 30 of the paper)
  848.                 pnm1[n] = tOu.multiply(m).multiply(pnm0[n]).subtract(u.multiply(enm[localIndex]).multiply(pnm0Plus1[n]));

  849.                 ++localIndex;
  850.                 ++n;

  851.             }

  852.             if (pnm2 != null) {

  853.                 // initialize recursion from sectorial terms
  854.                 n = FastMath.max(2, m);
  855.                 if (n == m) {
  856.                     pnm2[n] =   tOu.multiply(pnm1[n]).subtract(pnm0[n].divide(u2)).multiply(m);
  857.                     ++n;
  858.                 }

  859.                 // compute tesseral values and derivatives with respect to polar angle
  860.                 localIndex = index;
  861.                 while (n <= degree) {

  862.                     // second derivative (differential of equation 30 with respect to theta)
  863.                     pnm2[n] = tOu.multiply(pnm1[n]).subtract(pnm0[n].divide(u2)).multiply(m).subtract(u.multiply(pnm1Plus1[n]).multiply(enm[localIndex]));
  864.                     ++localIndex;
  865.                     ++n;

  866.                 }

  867.             }

  868.         }
  869.         return localIndex;

  870.     }

  871.     /** {@inheritDoc} */
  872.     @Override
  873.     public Vector3D acceleration(final SpacecraftState s, final double[] parameters) {

  874.         final double mu = parameters[0];

  875.         // get the position in body frame
  876.         final AbsoluteDate date       = s.getDate();
  877.         final StaticTransform fromBodyFrame = bodyFrame.getStaticTransformTo(s.getFrame(), date);
  878.         final StaticTransform toBodyFrame   = fromBodyFrame.getInverse();
  879.         final Vector3D position       = toBodyFrame.transformPosition(s.getPosition());

  880.         // gradient of the non-central part of the gravity field
  881.         return fromBodyFrame.transformVector(new Vector3D(gradient(date, position, mu)));

  882.     }

  883.     /** {@inheritDoc} */
  884.     public <T extends CalculusFieldElement<T>> FieldVector3D<T> acceleration(final FieldSpacecraftState<T> s,
  885.                                                                          final T[] parameters) {

  886.         final T mu = parameters[0];

  887.         // check for faster computation dedicated to derivatives with respect to state
  888.         if (isGradientStateDerivative(s)) {
  889.             @SuppressWarnings("unchecked")
  890.             final FieldVector3D<Gradient> p = (FieldVector3D<Gradient>) s.getPosition();
  891.             @SuppressWarnings("unchecked")
  892.             final FieldVector3D<T> a = (FieldVector3D<T>) accelerationWrtState(s.getDate().toAbsoluteDate(),
  893.                                                                                s.getFrame(), p,
  894.                                                                                (Gradient) mu);
  895.             return a;
  896.         } else if (isDSStateDerivative(s)) {
  897.             @SuppressWarnings("unchecked")
  898.             final FieldVector3D<DerivativeStructure> p = (FieldVector3D<DerivativeStructure>) s.getPosition();
  899.             @SuppressWarnings("unchecked")
  900.             final FieldVector3D<T> a = (FieldVector3D<T>) accelerationWrtState(s.getDate().toAbsoluteDate(),
  901.                                                                                s.getFrame(), p,
  902.                                                                                (DerivativeStructure) mu);
  903.             return a;
  904.         }

  905.         // get the position in body frame
  906.         final FieldAbsoluteDate<T> date             = s.getDate();
  907.         final FieldStaticTransform<T> fromBodyFrame = bodyFrame.getStaticTransformTo(s.getFrame(), date);
  908.         final FieldStaticTransform<T> toBodyFrame   = fromBodyFrame.getInverse();
  909.         final FieldVector3D<T> position             = toBodyFrame.transformPosition(s.getPosition());

  910.         // gradient of the non-central part of the gravity field
  911.         return fromBodyFrame.transformVector(new FieldVector3D<>(gradient(date, position, mu)));

  912.     }

  913.     /** Check if a field state corresponds to derivatives with respect to state.
  914.      * @param state state to check
  915.      * @param <T> type of the filed elements
  916.      * @return true if state corresponds to derivatives with respect to state
  917.      * @since 9.0
  918.      */
  919.     private <T extends CalculusFieldElement<T>> boolean isDSStateDerivative(final FieldSpacecraftState<T> state) {
  920.         try {
  921.             final DerivativeStructure dsMass = (DerivativeStructure) state.getMass();
  922.             final int o = dsMass.getOrder();
  923.             final int p = dsMass.getFreeParameters();
  924.             if (o != 1 || p < 3) {
  925.                 return false;
  926.             }
  927.             @SuppressWarnings("unchecked")
  928.             final FieldPVCoordinates<DerivativeStructure> pv = (FieldPVCoordinates<DerivativeStructure>) state.getPVCoordinates();
  929.             return isVariable(pv.getPosition().getX(), 0) &&
  930.                    isVariable(pv.getPosition().getY(), 1) &&
  931.                    isVariable(pv.getPosition().getZ(), 2);
  932.         } catch (ClassCastException cce) {
  933.             return false;
  934.         }
  935.     }

  936.     /** Check if a field state corresponds to derivatives with respect to state.
  937.      * @param state state to check
  938.      * @param <T> type of the filed elements
  939.      * @return true if state corresponds to derivatives with respect to state
  940.      * @since 10.2
  941.      */
  942.     private <T extends CalculusFieldElement<T>> boolean isGradientStateDerivative(final FieldSpacecraftState<T> state) {
  943.         try {
  944.             final Gradient gMass = (Gradient) state.getMass();
  945.             final int p = gMass.getFreeParameters();
  946.             if (p < 3) {
  947.                 return false;
  948.             }
  949.             @SuppressWarnings("unchecked")
  950.             final FieldPVCoordinates<Gradient> pv = (FieldPVCoordinates<Gradient>) state.getPVCoordinates();
  951.             return isVariable(pv.getPosition().getX(), 0) &&
  952.                    isVariable(pv.getPosition().getY(), 1) &&
  953.                    isVariable(pv.getPosition().getZ(), 2);
  954.         } catch (ClassCastException cce) {
  955.             return false;
  956.         }
  957.     }

  958.     /** Check if a derivative represents a specified variable.
  959.      * @param ds derivative to check
  960.      * @param index index of the variable
  961.      * @return true if the derivative represents a specified variable
  962.      * @since 9.0
  963.      */
  964.     private boolean isVariable(final DerivativeStructure ds, final int index) {
  965.         final double[] derivatives = ds.getAllDerivatives();
  966.         boolean check = true;
  967.         for (int i = 1; i < derivatives.length; ++i) {
  968.             check &= derivatives[i] == ((index + 1 == i) ? 1.0 : 0.0);
  969.         }
  970.         return check;
  971.     }

  972.     /** Check if a derivative represents a specified variable.
  973.      * @param g derivative to check
  974.      * @param index index of the variable
  975.      * @return true if the derivative represents a specified variable
  976.      * @since 10.2
  977.      */
  978.     private boolean isVariable(final Gradient g, final int index) {
  979.         final double[] derivatives = g.getGradient();
  980.         boolean check = true;
  981.         for (int i = 0; i < derivatives.length; ++i) {
  982.             check &= derivatives[i] == ((index == i) ? 1.0 : 0.0);
  983.         }
  984.         return check;
  985.     }

  986.     /** Compute acceleration derivatives with respect to state parameters.
  987.      * <p>
  988.      * From a theoretical point of view, this method computes the same values
  989.      * as {@link #acceleration(FieldSpacecraftState, CalculusFieldElement[])} in the
  990.      * specific case of {@link DerivativeStructure} with respect to state, so
  991.      * it is less general. However, it is *much* faster in this important case.
  992.      * <p>
  993.      * <p>
  994.      * The derivatives should be computed with respect to position. The input
  995.      * parameters already take into account the free parameters (6 or 7 depending
  996.      * on derivation with respect to mass being considered or not) and order
  997.      * (always 1). Free parameters at indices 0, 1 and 2 correspond to derivatives
  998.      * with respect to position. Free parameters at indices 3, 4 and 5 correspond
  999.      * to derivatives with respect to velocity (these derivatives will remain zero
  1000.      * as acceleration due to gravity does not depend on velocity). Free parameter
  1001.      * at index 6 (if present) corresponds to to derivatives with respect to mass
  1002.      * (this derivative will remain zero as acceleration due to gravity does not
  1003.      * depend on mass).
  1004.      * </p>
  1005.      * @param date current date
  1006.      * @param frame inertial reference frame for state (both orbit and attitude)
  1007.      * @param position position of spacecraft in inertial frame
  1008.      * @param mu central attraction coefficient to use
  1009.      * @return acceleration with all derivatives specified by the input parameters
  1010.      * own derivatives
  1011.      * @since 6.0
  1012.      */
  1013.     private FieldVector3D<DerivativeStructure> accelerationWrtState(final AbsoluteDate date, final Frame frame,
  1014.                                                                     final FieldVector3D<DerivativeStructure> position,
  1015.                                                                     final DerivativeStructure mu) {

  1016.         // free parameters
  1017.         final int freeParameters = mu.getFreeParameters();

  1018.         // get the position in body frame
  1019.         final StaticTransform fromBodyFrame = bodyFrame.getStaticTransformTo(frame, date);
  1020.         final StaticTransform toBodyFrame   = fromBodyFrame.getInverse();
  1021.         final Vector3D positionBody   = toBodyFrame.transformPosition(position.toVector3D());

  1022.         // compute gradient and Hessian
  1023.         final GradientHessian gh   = gradientHessian(date, positionBody, mu.getReal());

  1024.         // gradient of the non-central part of the gravity field
  1025.         final double[] gInertial = fromBodyFrame.transformVector(new Vector3D(gh.getGradient())).toArray();

  1026.         // Hessian of the non-central part of the gravity field
  1027.         final RealMatrix hBody     = new Array2DRowRealMatrix(gh.getHessian(), false);
  1028.         final RealMatrix rot       = new Array2DRowRealMatrix(toBodyFrame.getRotation().getMatrix());
  1029.         final RealMatrix hInertial = rot.transposeMultiply(hBody).multiply(rot);

  1030.         // distribute all partial derivatives in a compact acceleration vector
  1031.         final double[] derivatives = new double[freeParameters + 1];
  1032.         final DerivativeStructure[] accDer = new DerivativeStructure[3];
  1033.         for (int i = 0; i < 3; ++i) {

  1034.             // first element is value of acceleration (i.e. gradient of field)
  1035.             derivatives[0] = gInertial[i];

  1036.             // Jacobian of acceleration (i.e. Hessian of field)
  1037.             derivatives[1] = hInertial.getEntry(i, 0);
  1038.             derivatives[2] = hInertial.getEntry(i, 1);
  1039.             derivatives[3] = hInertial.getEntry(i, 2);

  1040.             // next element is derivative with respect to parameter mu
  1041.             if (derivatives.length > 4 && isVariable(mu, 3)) {
  1042.                 derivatives[4] = gInertial[i] / mu.getReal();
  1043.             }

  1044.             accDer[i] = position.getX().getFactory().build(derivatives);

  1045.         }

  1046.         return new FieldVector3D<>(accDer);

  1047.     }

  1048.     /** Compute acceleration derivatives with respect to state parameters.
  1049.      * <p>
  1050.      * From a theoretical point of view, this method computes the same values
  1051.      * as {@link #acceleration(FieldSpacecraftState, CalculusFieldElement[])} in the
  1052.      * specific case of {@link DerivativeStructure} with respect to state, so
  1053.      * it is less general. However, it is *much* faster in this important case.
  1054.      * <p>
  1055.      * <p>
  1056.      * The derivatives should be computed with respect to position. The input
  1057.      * parameters already take into account the free parameters (6 or 7 depending
  1058.      * on derivation with respect to mass being considered or not) and order
  1059.      * (always 1). Free parameters at indices 0, 1 and 2 correspond to derivatives
  1060.      * with respect to position. Free parameters at indices 3, 4 and 5 correspond
  1061.      * to derivatives with respect to velocity (these derivatives will remain zero
  1062.      * as acceleration due to gravity does not depend on velocity). Free parameter
  1063.      * at index 6 (if present) corresponds to to derivatives with respect to mass
  1064.      * (this derivative will remain zero as acceleration due to gravity does not
  1065.      * depend on mass).
  1066.      * </p>
  1067.      * @param date current date
  1068.      * @param frame inertial reference frame for state (both orbit and attitude)
  1069.      * @param position position of spacecraft in inertial frame
  1070.      * @param mu central attraction coefficient to use
  1071.      * @return acceleration with all derivatives specified by the input parameters
  1072.      * own derivatives
  1073.      * @since 10.2
  1074.      */
  1075.     private FieldVector3D<Gradient> accelerationWrtState(final AbsoluteDate date, final Frame frame,
  1076.                                                          final FieldVector3D<Gradient> position,
  1077.                                                          final Gradient mu) {

  1078.         // free parameters
  1079.         final int freeParameters = mu.getFreeParameters();

  1080.         // get the position in body frame
  1081.         final StaticTransform fromBodyFrame = bodyFrame.getStaticTransformTo(frame, date);
  1082.         final StaticTransform toBodyFrame   = fromBodyFrame.getInverse();
  1083.         final Vector3D positionBody   = toBodyFrame.transformPosition(position.toVector3D());

  1084.         // compute gradient and Hessian
  1085.         final GradientHessian gh   = gradientHessian(date, positionBody, mu.getReal());

  1086.         // gradient of the non-central part of the gravity field
  1087.         final double[] gInertial = fromBodyFrame.transformVector(new Vector3D(gh.getGradient())).toArray();

  1088.         // Hessian of the non-central part of the gravity field
  1089.         final RealMatrix hBody     = new Array2DRowRealMatrix(gh.getHessian(), false);
  1090.         final RealMatrix rot       = new Array2DRowRealMatrix(toBodyFrame.getRotation().getMatrix());
  1091.         final RealMatrix hInertial = rot.transposeMultiply(hBody).multiply(rot);

  1092.         // distribute all partial derivatives in a compact acceleration vector
  1093.         final double[] derivatives = new double[freeParameters];
  1094.         final Gradient[] accDer = new Gradient[3];
  1095.         for (int i = 0; i < 3; ++i) {

  1096.             // Jacobian of acceleration (i.e. Hessian of field)
  1097.             derivatives[0] = hInertial.getEntry(i, 0);
  1098.             derivatives[1] = hInertial.getEntry(i, 1);
  1099.             derivatives[2] = hInertial.getEntry(i, 2);

  1100.             // next element is derivative with respect to parameter mu
  1101.             if (derivatives.length > 3 && isVariable(mu, 3)) {
  1102.                 derivatives[3] = gInertial[i] / mu.getReal();
  1103.             }

  1104.             accDer[i] = new Gradient(gInertial[i], derivatives);

  1105.         }

  1106.         return new FieldVector3D<>(accDer);

  1107.     }

  1108.     /** {@inheritDoc} */
  1109.     public List<ParameterDriver> getParametersDrivers() {
  1110.         return Collections.singletonList(gmParameterDriver);
  1111.     }

  1112. }