OneAxisEllipsoid.java

  1. /* Copyright 2002-2022 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.bodies;

  18. import java.io.Serializable;

  19. import org.hipparchus.CalculusFieldElement;
  20. import org.hipparchus.analysis.differentiation.DerivativeStructure;
  21. import org.hipparchus.geometry.euclidean.threed.FieldLine;
  22. import org.hipparchus.geometry.euclidean.threed.FieldVector3D;
  23. import org.hipparchus.geometry.euclidean.threed.Line;
  24. import org.hipparchus.geometry.euclidean.threed.Vector3D;
  25. import org.hipparchus.geometry.euclidean.twod.Vector2D;
  26. import org.hipparchus.util.FastMath;
  27. import org.hipparchus.util.FieldSinCos;
  28. import org.hipparchus.util.MathArrays;
  29. import org.hipparchus.util.SinCos;
  30. import org.orekit.frames.FieldTransform;
  31. import org.orekit.frames.Frame;
  32. import org.orekit.frames.StaticTransform;
  33. import org.orekit.frames.Transform;
  34. import org.orekit.time.AbsoluteDate;
  35. import org.orekit.time.FieldAbsoluteDate;
  36. import org.orekit.utils.PVCoordinates;
  37. import org.orekit.utils.TimeStampedPVCoordinates;


  38. /** Modeling of a one-axis ellipsoid.

  39.  * <p>One-axis ellipsoids is a good approximate model for most planet-size
  40.  * and larger natural bodies. It is the equilibrium shape reached by
  41.  * a fluid body under its own gravity field when it rotates. The symmetry
  42.  * axis is the rotation or polar axis.</p>

  43.  * @author Luc Maisonobe
  44.  * @author Guylaine Prat
  45.  */
  46. public class OneAxisEllipsoid extends Ellipsoid implements BodyShape {

  47.     /** Serializable UID. */
  48.     private static final long serialVersionUID = 20130518L;

  49.     /** Threshold for polar and equatorial points detection. */
  50.     private static final double ANGULAR_THRESHOLD = 1.0e-4;

  51.     /** Body frame related to body shape. */
  52.     private final Frame bodyFrame;

  53.     /** Equatorial radius power 2. */
  54.     private final double ae2;

  55.     /** Polar radius power 2. */
  56.     private final double ap2;

  57.     /** Flattening. */
  58.     private final double f;

  59.     /** Eccentricity power 2. */
  60.     private final double e2;

  61.     /** 1 minus flatness. */
  62.     private final double g;

  63.     /** g * g. */
  64.     private final double g2;

  65.     /** Convergence limit. */
  66.     private double angularThreshold;

  67.     /** Simple constructor.
  68.      * <p>Standard values for Earth models can be found in the {@link org.orekit.utils.Constants Constants} class:</p>
  69.      * <table border="1" style="background-color:#f5f5dc;">
  70.      * <caption>Ellipsoid Models</caption>
  71.      * <tr style="background-color:#c9d5c9;"><th>model</th><th>a<sub>e</sub> (m)</th> <th>f</th></tr>
  72.      * <tr><td style="background-color:#c9d5c9; padding:5px">GRS 80</td>
  73.      *     <td>{@link org.orekit.utils.Constants#GRS80_EARTH_EQUATORIAL_RADIUS Constants.GRS80_EARTH_EQUATORIAL_RADIUS}</td>
  74.      *     <td>{@link org.orekit.utils.Constants#GRS80_EARTH_FLATTENING Constants.GRS80_EARTH_FLATTENING}</td></tr>
  75.      * <tr><td style="background-color:#c9d5c9; padding:5px">WGS84</td>
  76.      *     <td>{@link org.orekit.utils.Constants#WGS84_EARTH_EQUATORIAL_RADIUS Constants.WGS84_EARTH_EQUATORIAL_RADIUS}</td>
  77.      *     <td>{@link org.orekit.utils.Constants#WGS84_EARTH_FLATTENING Constants.WGS84_EARTH_FLATTENING}</td></tr>
  78.      * <tr><td style="background-color:#c9d5c9; padding:5px">IERS96</td>
  79.      *     <td>{@link org.orekit.utils.Constants#IERS96_EARTH_EQUATORIAL_RADIUS Constants.IERS96_EARTH_EQUATORIAL_RADIUS}</td>
  80.      *     <td>{@link org.orekit.utils.Constants#IERS96_EARTH_FLATTENING Constants.IERS96_EARTH_FLATTENING}</td></tr>
  81.      * <tr><td style="background-color:#c9d5c9; padding:5px">IERS2003</td>
  82.      *     <td>{@link org.orekit.utils.Constants#IERS2003_EARTH_EQUATORIAL_RADIUS Constants.IERS2003_EARTH_EQUATORIAL_RADIUS}</td>
  83.      *     <td>{@link org.orekit.utils.Constants#IERS2003_EARTH_FLATTENING Constants.IERS2003_EARTH_FLATTENING}</td></tr>
  84.      * <tr><td style="background-color:#c9d5c9; padding:5px">IERS2010</td>
  85.      *     <td>{@link org.orekit.utils.Constants#IERS2010_EARTH_EQUATORIAL_RADIUS Constants.IERS2010_EARTH_EQUATORIAL_RADIUS}</td>
  86.      *     <td>{@link org.orekit.utils.Constants#IERS2010_EARTH_FLATTENING Constants.IERS2010_EARTH_FLATTENING}</td></tr>
  87.      * </table>
  88.      * @param ae equatorial radius
  89.      * @param f the flattening (f = (a-b)/a)
  90.      * @param bodyFrame body frame related to body shape
  91.      * @see org.orekit.frames.FramesFactory#getITRF(org.orekit.utils.IERSConventions, boolean)
  92.      */
  93.     public OneAxisEllipsoid(final double ae, final double f,
  94.                             final Frame bodyFrame) {
  95.         super(bodyFrame, ae, ae, ae * (1.0 - f));
  96.         this.f    = f;
  97.         this.ae2  = ae * ae;
  98.         this.e2   = f * (2.0 - f);
  99.         this.g    = 1.0 - f;
  100.         this.g2   = g * g;
  101.         this.ap2  = ae2 * g2;
  102.         setAngularThreshold(1.0e-12);
  103.         this.bodyFrame = bodyFrame;
  104.     }

  105.     /** Set the angular convergence threshold.
  106.      * <p>The angular threshold is used both to identify points close to
  107.      * the ellipse axes and as the convergence threshold used to
  108.      * stop the iterations in the {@link #transform(Vector3D, Frame,
  109.      * AbsoluteDate)} method.</p>
  110.      * <p>If this method is not called, the default value is set to
  111.      * 10<sup>-12</sup>.</p>
  112.      * @param angularThreshold angular convergence threshold (rad)
  113.      */
  114.     public void setAngularThreshold(final double angularThreshold) {
  115.         this.angularThreshold = angularThreshold;
  116.     }

  117.     /** Get the equatorial radius of the body.
  118.      * @return equatorial radius of the body (m)
  119.      */
  120.     public double getEquatorialRadius() {
  121.         return getA();
  122.     }

  123.     /** Get the flattening of the body: f = (a-b)/a.
  124.      * @return the flattening
  125.      */
  126.     public double getFlattening() {
  127.         return f;
  128.     }

  129.     /** {@inheritDoc} */
  130.     public Frame getBodyFrame() {
  131.         return bodyFrame;
  132.     }

  133.     /** Get the intersection point of a line with the surface of the body.
  134.      * <p>A line may have several intersection points with a closed
  135.      * surface (we consider the one point case as a degenerated two
  136.      * points case). The close parameter is used to select which of
  137.      * these points should be returned. The selected point is the one
  138.      * that is closest to the close point.</p>
  139.      * @param line test line (may intersect the body or not)
  140.      * @param close point used for intersections selection
  141.      * @param frame frame in which line is expressed
  142.      * @param date date of the line in given frame
  143.      * @return intersection point at altitude zero or null if the line does
  144.      * not intersect the surface
  145.      * @since 9.3
  146.      */
  147.     public Vector3D getCartesianIntersectionPoint(final Line line, final Vector3D close,
  148.                                                   final Frame frame, final AbsoluteDate date) {

  149.         // transform line and close to body frame
  150.         final StaticTransform frameToBodyFrame =
  151.                 frame.getStaticTransformTo(bodyFrame, date);
  152.         final Line lineInBodyFrame = frameToBodyFrame.transformLine(line);

  153.         // compute some miscellaneous variables
  154.         final Vector3D point    = lineInBodyFrame.getOrigin();
  155.         final double x          = point.getX();
  156.         final double y          = point.getY();
  157.         final double z          = point.getZ();
  158.         final double z2         = z * z;
  159.         final double r2         = x * x + y * y;

  160.         final Vector3D direction = lineInBodyFrame.getDirection();
  161.         final double dx         = direction.getX();
  162.         final double dy         = direction.getY();
  163.         final double dz         = direction.getZ();
  164.         final double cz2        = dx * dx + dy * dy;

  165.         // abscissa of the intersection as a root of a 2nd degree polynomial :
  166.         // a k^2 - 2 b k + c = 0
  167.         final double a  = 1.0 - e2 * cz2;
  168.         final double b  = -(g2 * (x * dx + y * dy) + z * dz);
  169.         final double c  = g2 * (r2 - ae2) + z2;
  170.         final double b2 = b * b;
  171.         final double ac = a * c;
  172.         if (b2 < ac) {
  173.             return null;
  174.         }
  175.         final double s  = FastMath.sqrt(b2 - ac);
  176.         final double k1 = (b < 0) ? (b - s) / a : c / (b + s);
  177.         final double k2 = c / (a * k1);

  178.         // select the right point
  179.         final Vector3D closeInBodyFrame = frameToBodyFrame.transformPosition(close);
  180.         final double   closeAbscissa    = lineInBodyFrame.getAbscissa(closeInBodyFrame);
  181.         final double k =
  182.             (FastMath.abs(k1 - closeAbscissa) < FastMath.abs(k2 - closeAbscissa)) ? k1 : k2;
  183.         return lineInBodyFrame.pointAt(k);

  184.     }

  185.     /** {@inheritDoc} */
  186.     public GeodeticPoint getIntersectionPoint(final Line line, final Vector3D close,
  187.                                               final Frame frame, final AbsoluteDate date) {

  188.         final Vector3D intersection = getCartesianIntersectionPoint(line, close, frame, date);
  189.         if (intersection == null) {
  190.             return null;
  191.         }
  192.         final double ix = intersection.getX();
  193.         final double iy = intersection.getY();
  194.         final double iz = intersection.getZ();

  195.         final double lambda = FastMath.atan2(iy, ix);
  196.         final double phi    = FastMath.atan2(iz, g2 * FastMath.sqrt(ix * ix + iy * iy));
  197.         return new GeodeticPoint(phi, lambda, 0.0);

  198.     }

  199.     /** Get the intersection point of a line with the surface of the body.
  200.      * <p>A line may have several intersection points with a closed
  201.      * surface (we consider the one point case as a degenerated two
  202.      * points case). The close parameter is used to select which of
  203.      * these points should be returned. The selected point is the one
  204.      * that is closest to the close point.</p>
  205.      * @param line test line (may intersect the body or not)
  206.      * @param close point used for intersections selection
  207.      * @param frame frame in which line is expressed
  208.      * @param date date of the line in given frame
  209.      * @param <T> type of the field elements
  210.      * @return intersection point at altitude zero or null if the line does
  211.      * not intersect the surface
  212.      * @since 9.3
  213.      */
  214.     public <T extends CalculusFieldElement<T>> FieldVector3D<T> getCartesianIntersectionPoint(final FieldLine<T> line,
  215.                                                                                           final FieldVector3D<T> close,
  216.                                                                                           final Frame frame,
  217.                                                                                           final FieldAbsoluteDate<T> date) {

  218.         // transform line and close to body frame
  219.         final FieldTransform<T> frameToBodyFrame = frame.getTransformTo(bodyFrame, date);
  220.         final FieldLine<T>      lineInBodyFrame  = frameToBodyFrame.transformLine(line);

  221.         // compute some miscellaneous variables
  222.         final FieldVector3D<T> point = lineInBodyFrame.getOrigin();
  223.         final T x  = point.getX();
  224.         final T y  = point.getY();
  225.         final T z  = point.getZ();
  226.         final T z2 = z.multiply(z);
  227.         final T r2 = x.multiply(x).add(y.multiply(y));

  228.         final FieldVector3D<T> direction = lineInBodyFrame.getDirection();
  229.         final T dx  = direction.getX();
  230.         final T dy  = direction.getY();
  231.         final T dz  = direction.getZ();
  232.         final T cz2 = dx.multiply(dx).add(dy.multiply(dy));

  233.         // abscissa of the intersection as a root of a 2nd degree polynomial :
  234.         // a k^2 - 2 b k + c = 0
  235.         final T a  = cz2.multiply(e2).subtract(1.0).negate();
  236.         final T b  = x.multiply(dx).add(y.multiply(dy)).multiply(g2).add(z.multiply(dz)).negate();
  237.         final T c  = r2.subtract(ae2).multiply(g2).add(z2);
  238.         final T b2 = b.multiply(b);
  239.         final T ac = a.multiply(c);
  240.         if (b2.getReal() < ac.getReal()) {
  241.             return null;
  242.         }
  243.         final T s  = b2.subtract(ac).sqrt();
  244.         final T k1 = (b.getReal() < 0) ? b.subtract(s).divide(a) : c.divide(b.add(s));
  245.         final T k2 = c.divide(a.multiply(k1));

  246.         // select the right point
  247.         final FieldVector3D<T>  closeInBodyFrame = frameToBodyFrame.transformPosition(close);
  248.         final T                 closeAbscissa    = lineInBodyFrame.getAbscissa(closeInBodyFrame);
  249.         final T k = (FastMath.abs(k1.getReal() - closeAbscissa.getReal()) < FastMath.abs(k2.getReal() - closeAbscissa.getReal())) ?
  250.                     k1 : k2;
  251.         return lineInBodyFrame.pointAt(k);
  252.     }

  253.     /** {@inheritDoc} */
  254.     public <T extends CalculusFieldElement<T>> FieldGeodeticPoint<T> getIntersectionPoint(final FieldLine<T> line,
  255.                                                                                       final FieldVector3D<T> close,
  256.                                                                                       final Frame frame,
  257.                                                                                       final FieldAbsoluteDate<T> date) {

  258.         final FieldVector3D<T> intersection = getCartesianIntersectionPoint(line, close, frame, date);
  259.         if (intersection == null) {
  260.             return null;
  261.         }
  262.         final T ix = intersection.getX();
  263.         final T iy = intersection.getY();
  264.         final T iz = intersection.getZ();

  265.         final T lambda = iy.atan2(ix);
  266.         final T phi    = iz.atan2(ix.multiply(ix).add(iy.multiply(iy)).sqrt().multiply(g2));
  267.         return new FieldGeodeticPoint<>(phi, lambda, phi.getField().getZero());

  268.     }

  269.     /** {@inheritDoc} */
  270.     public Vector3D transform(final GeodeticPoint point) {
  271.         final double longitude = point.getLongitude();
  272.         final SinCos scLambda  = FastMath.sinCos(longitude);
  273.         final double latitude  = point.getLatitude();
  274.         final SinCos scPhi     = FastMath.sinCos(latitude);
  275.         final double h         = point.getAltitude();
  276.         final double n         = getA() / FastMath.sqrt(1.0 - e2 * scPhi.sin() * scPhi.sin());
  277.         final double r         = (n + h) * scPhi.cos();
  278.         return new Vector3D(r * scLambda.cos(), r * scLambda.sin(), (g2 * n + h) * scPhi.sin());
  279.     }

  280.     /** {@inheritDoc} */
  281.     public <T extends CalculusFieldElement<T>> FieldVector3D<T> transform(final FieldGeodeticPoint<T> point) {

  282.         final T latitude  = point.getLatitude();
  283.         final T longitude = point.getLongitude();
  284.         final T altitude  = point.getAltitude();

  285.         final FieldSinCos<T> scLambda = FastMath.sinCos(longitude);
  286.         final FieldSinCos<T> scPhi    = FastMath.sinCos(latitude);
  287.         final T cLambda = scLambda.cos();
  288.         final T sLambda = scLambda.sin();
  289.         final T cPhi    = scPhi.cos();
  290.         final T sPhi    = scPhi.sin();
  291.         final T n       = sPhi.multiply(sPhi).multiply(e2).subtract(1.0).negate().sqrt().reciprocal().multiply(getA());
  292.         final T r       = n.add(altitude).multiply(cPhi);

  293.         return new FieldVector3D<>(r.multiply(cLambda),
  294.                                    r.multiply(sLambda),
  295.                                    sPhi.multiply(altitude.add(n.multiply(g2))));
  296.     }

  297.     /** {@inheritDoc} */
  298.     public Vector3D projectToGround(final Vector3D point, final AbsoluteDate date, final Frame frame) {

  299.         // transform point to body frame
  300.         final StaticTransform toBody = frame.getStaticTransformTo(bodyFrame, date);
  301.         final Vector3D   p         = toBody.transformPosition(point);
  302.         final double     z         = p.getZ();
  303.         final double     r         = FastMath.hypot(p.getX(), p.getY());

  304.         // set up the 2D meridian ellipse
  305.         final Ellipse meridian = new Ellipse(Vector3D.ZERO,
  306.                                              r == 0 ? Vector3D.PLUS_I : new Vector3D(p.getX() / r, p.getY() / r, 0),
  307.                                              Vector3D.PLUS_K,
  308.                                              getA(), getC(), bodyFrame);

  309.         // find the closest point in the meridian plane
  310.         final Vector3D groundPoint = meridian.toSpace(meridian.projectToEllipse(new Vector2D(r, z)));

  311.         // transform point back to initial frame
  312.         return toBody.getInverse().transformPosition(groundPoint);

  313.     }

  314.     /** {@inheritDoc} */
  315.     public TimeStampedPVCoordinates projectToGround(final TimeStampedPVCoordinates pv, final Frame frame) {

  316.         // transform point to body frame
  317.         final Transform                toBody        = frame.getTransformTo(bodyFrame, pv.getDate());
  318.         final TimeStampedPVCoordinates pvInBodyFrame = toBody.transformPVCoordinates(pv);
  319.         final Vector3D                 p             = pvInBodyFrame.getPosition();
  320.         final double                   r             = FastMath.hypot(p.getX(), p.getY());

  321.         // set up the 2D ellipse corresponding to first principal curvature along meridian
  322.         final Vector3D meridian = r == 0 ? Vector3D.PLUS_I : new Vector3D(p.getX() / r, p.getY() / r, 0);
  323.         final Ellipse firstPrincipalCurvature =
  324.                 new Ellipse(Vector3D.ZERO, meridian, Vector3D.PLUS_K, getA(), getC(), bodyFrame);

  325.         // project coordinates in the meridian plane
  326.         final TimeStampedPVCoordinates gpFirst = firstPrincipalCurvature.projectToEllipse(pvInBodyFrame);
  327.         final Vector3D                 gpP     = gpFirst.getPosition();
  328.         final double                   gr      = MathArrays.linearCombination(gpP.getX(), meridian.getX(),
  329.                                                                               gpP.getY(), meridian.getY());
  330.         final double                   gz      = gpP.getZ();

  331.         // topocentric frame
  332.         final Vector3D east   = new Vector3D(-meridian.getY(), meridian.getX(), 0);
  333.         final Vector3D zenith = new Vector3D(gr * getC() / getA(), meridian, gz * getA() / getC(), Vector3D.PLUS_K).normalize();
  334.         final Vector3D north  = Vector3D.crossProduct(zenith, east);

  335.         // set up the ellipse corresponding to second principal curvature in the zenith/east plane
  336.         final Ellipse secondPrincipalCurvature  = getPlaneSection(gpP, north);
  337.         final TimeStampedPVCoordinates gpSecond = secondPrincipalCurvature.projectToEllipse(pvInBodyFrame);

  338.         final Vector3D gpV = gpFirst.getVelocity().add(gpSecond.getVelocity());
  339.         final Vector3D gpA = gpFirst.getAcceleration().add(gpSecond.getAcceleration());

  340.         // moving projected point
  341.         final TimeStampedPVCoordinates groundPV =
  342.                 new TimeStampedPVCoordinates(pv.getDate(), gpP, gpV, gpA);

  343.         // transform moving projected point back to initial frame
  344.         return toBody.getInverse().transformPVCoordinates(groundPV);

  345.     }

  346.     /** {@inheritDoc}
  347.      * <p>
  348.      * This method is based on Toshio Fukushima's algorithm which uses Halley's method.
  349.      * <a href="https://www.researchgate.net/publication/227215135_Transformation_from_Cartesian_to_Geodetic_Coordinates_Accelerated_by_Halley's_Method">
  350.      * transformation from Cartesian to Geodetic Coordinates Accelerated by Halley's Method</a>,
  351.      * Toshio Fukushima, Journal of Geodesy 9(12):689-693, February 2006
  352.      * </p>
  353.      * <p>
  354.      * Some changes have been added to the original method:
  355.      * <ul>
  356.      *   <li>in order to handle more accurately corner cases near the pole</li>
  357.      *   <li>in order to handle properly corner cases near the equatorial plane, even far inside the ellipsoid</li>
  358.      *   <li>in order to handle very flat ellipsoids</li>
  359.      * </ul>
  360.      */
  361.     public GeodeticPoint transform(final Vector3D point, final Frame frame, final AbsoluteDate date) {

  362.         // transform point to body frame
  363.         final Vector3D pointInBodyFrame = frame.getStaticTransformTo(bodyFrame, date)
  364.                 .transformPosition(point);
  365.         final double   r2               = pointInBodyFrame.getX() * pointInBodyFrame.getX() +
  366.                                           pointInBodyFrame.getY() * pointInBodyFrame.getY();
  367.         final double   r                = FastMath.sqrt(r2);
  368.         final double   z                = pointInBodyFrame.getZ();

  369.         final double   lambda           = FastMath.atan2(pointInBodyFrame.getY(), pointInBodyFrame.getX());

  370.         double h;
  371.         double phi;
  372.         if (r <= ANGULAR_THRESHOLD * FastMath.abs(z)) {
  373.             // the point is almost on the polar axis, approximate the ellipsoid with
  374.             // the osculating sphere whose center is at evolute cusp along polar axis
  375.             final double osculatingRadius = ae2 / getC();
  376.             final double evoluteCuspZ     = FastMath.copySign(getA() * e2 / g, -z);
  377.             final double deltaZ           = z - evoluteCuspZ;
  378.             // we use π/2 - atan(r/Δz) instead of atan(Δz/r) for accuracy purposes, as r is much smaller than Δz
  379.             phi = FastMath.copySign(0.5 * FastMath.PI - FastMath.atan(r / FastMath.abs(deltaZ)), deltaZ);
  380.             h   = FastMath.hypot(deltaZ, r) - osculatingRadius;
  381.         } else if (FastMath.abs(z) <= ANGULAR_THRESHOLD * r) {
  382.             // the point is almost on the major axis

  383.             final double osculatingRadius = ap2 / getA();
  384.             final double evoluteCuspR     = getA() * e2;
  385.             final double deltaR           = r - evoluteCuspR;
  386.             if (deltaR >= 0) {
  387.                 // the point is outside of the ellipse evolute, approximate the ellipse
  388.                 // with the osculating circle whose center is at evolute cusp along major axis
  389.                 phi = (deltaR == 0) ? 0.0 : FastMath.atan(z / deltaR);
  390.                 h   = FastMath.hypot(deltaR, z) - osculatingRadius;
  391.             } else {
  392.                 // the point is on the part of the major axis within ellipse evolute
  393.                 // we can compute the closest ellipse point analytically, and it is NOT near the equator
  394.                 final double rClose = r / e2;
  395.                 final double zClose = FastMath.copySign(g * FastMath.sqrt(ae2 - rClose * rClose), z);
  396.                 phi = FastMath.atan((zClose - z) / (rClose - r));
  397.                 h   = -FastMath.hypot(r - rClose, z - zClose);
  398.             }

  399.         } else {
  400.             // use Toshio Fukushima method, with several iterations
  401.             final double epsPhi = 1.0e-15;
  402.             final double epsH   = 1.0e-14 * FastMath.max(getA(), FastMath.sqrt(r2 + z * z));
  403.             final double c     = getA() * e2;
  404.             final double absZ  = FastMath.abs(z);
  405.             final double zc    = g * absZ;
  406.             double sn  = absZ;
  407.             double sn2 = sn * sn;
  408.             double cn  = g * r;
  409.             double cn2 = cn * cn;
  410.             double an2 = cn2 + sn2;
  411.             double an  = FastMath.sqrt(an2);
  412.             double bn  = 0;
  413.             phi = Double.POSITIVE_INFINITY;
  414.             h   = Double.POSITIVE_INFINITY;
  415.             for (int i = 0; i < 10; ++i) { // this usually converges in 2 iterations
  416.                 final double oldSn  = sn;
  417.                 final double oldCn  = cn;
  418.                 final double oldPhi = phi;
  419.                 final double oldH   = h;
  420.                 final double an3    = an2 * an;
  421.                 final double csncn  = c * sn * cn;
  422.                 bn    = 1.5 * csncn * ((r * sn - zc * cn) * an - csncn);
  423.                 sn    = (zc * an3 + c * sn2 * sn) * an3 - bn * sn;
  424.                 cn    = (r  * an3 - c * cn2 * cn) * an3 - bn * cn;
  425.                 if (sn * oldSn < 0 || cn < 0) {
  426.                     // the Halley iteration went too far, we restrict it and iterate again
  427.                     while (sn * oldSn < 0 || cn < 0) {
  428.                         sn = (sn + oldSn) / 2;
  429.                         cn = (cn + oldCn) / 2;
  430.                     }
  431.                 } else {

  432.                     // rescale components to avoid overflow when several iterations are used
  433.                     final int exp = (FastMath.getExponent(sn) + FastMath.getExponent(cn)) / 2;
  434.                     sn = FastMath.scalb(sn, -exp);
  435.                     cn = FastMath.scalb(cn, -exp);

  436.                     sn2 = sn * sn;
  437.                     cn2 = cn * cn;
  438.                     an2 = cn2 + sn2;
  439.                     an  = FastMath.sqrt(an2);

  440.                     final double cc = g * cn;
  441.                     h = (r * cc + absZ * sn - getA() * g * an) / FastMath.sqrt(an2 - e2 * cn2);
  442.                     if (FastMath.abs(oldH   - h)   < epsH) {
  443.                         phi = FastMath.copySign(FastMath.atan(sn / cc), z);
  444.                         if (FastMath.abs(oldPhi - phi) < epsPhi) {
  445.                             break;
  446.                         }
  447.                     }

  448.                 }

  449.             }
  450.         }

  451.         return new GeodeticPoint(phi, lambda, h);

  452.     }

  453.     /** {@inheritDoc}
  454.      * <p>
  455.      * This method is based on Toshio Fukushima's algorithm which uses Halley's method.
  456.      * <a href="https://www.researchgate.net/publication/227215135_Transformation_from_Cartesian_to_Geodetic_Coordinates_Accelerated_by_Halley's_Method">
  457.      * transformation from Cartesian to Geodetic Coordinates Accelerated by Halley's Method</a>,
  458.      * Toshio Fukushima, Journal of Geodesy 9(12):689-693, February 2006
  459.      * </p>
  460.      * <p>
  461.      * Some changes have been added to the original method:
  462.      * <ul>
  463.      *   <li>in order to handle more accurately corner cases near the pole</li>
  464.      *   <li>in order to handle properly corner cases near the equatorial plane, even far inside the ellipsoid</li>
  465.      *   <li>in order to handle very flat ellipsoids</li>
  466.      * </ul>
  467.      */
  468.     public <T extends CalculusFieldElement<T>> FieldGeodeticPoint<T> transform(final FieldVector3D<T> point,
  469.                                                                            final Frame frame,
  470.                                                                            final FieldAbsoluteDate<T> date) {

  471.         // transform point to body frame
  472.         final FieldVector3D<T> pointInBodyFrame = frame.getTransformTo(bodyFrame, date).transformPosition(point);
  473.         final T   r2                            = pointInBodyFrame.getX().multiply(pointInBodyFrame.getX()).
  474.                                               add(pointInBodyFrame.getY().multiply(pointInBodyFrame.getY()));
  475.         final T   r                             = r2.sqrt();
  476.         final T   z                             = pointInBodyFrame.getZ();

  477.         final T   lambda                        = pointInBodyFrame.getY().atan2(pointInBodyFrame.getX());

  478.         T h;
  479.         T phi;
  480.         if (r.getReal() <= ANGULAR_THRESHOLD * FastMath.abs(z.getReal())) {
  481.             // the point is almost on the polar axis, approximate the ellipsoid with
  482.             // the osculating sphere whose center is at evolute cusp along polar axis
  483.             final double osculatingRadius = ae2 / getC();
  484.             final double evoluteCuspZ     = FastMath.copySign(getA() * e2 / g, -z.getReal());
  485.             final T      deltaZ           = z.subtract(evoluteCuspZ);
  486.             // we use π/2 - atan(r/Δz) instead of atan(Δz/r) for accuracy purposes, as r is much smaller than Δz
  487.             phi = r.divide(deltaZ.abs()).atan().negate().add(r.getPi().multiply(0.5)).copySign(deltaZ);
  488.             h   = deltaZ.hypot(r).subtract(osculatingRadius);
  489.         } else if (FastMath.abs(z.getReal()) <= ANGULAR_THRESHOLD * r.getReal()) {
  490.             // the point is almost on the major axis

  491.             final double osculatingRadius = ap2 / getA();
  492.             final double evoluteCuspR     = getA() * e2;
  493.             final T      deltaR           = r.subtract(evoluteCuspR);
  494.             if (deltaR.getReal() >= 0) {
  495.                 // the point is outside of the ellipse evolute, approximate the ellipse
  496.                 // with the osculating circle whose center is at evolute cusp along major axis
  497.                 phi = (deltaR.getReal() == 0) ? z.getField().getZero() : z.divide(deltaR).atan();
  498.                 h   = deltaR.hypot(z).subtract(osculatingRadius);
  499.             } else {
  500.                 // the point is on the part of the major axis within ellipse evolute
  501.                 // we can compute the closest ellipse point analytically, and it is NOT near the equator
  502.                 final T rClose = r.divide(e2);
  503.                 final T zClose = rClose.multiply(rClose).negate().add(ae2).sqrt().multiply(g).copySign(z);
  504.                 phi = zClose.subtract(z).divide(rClose.subtract(r)).atan();
  505.                 h   = r.subtract(rClose).hypot(z.subtract(zClose)).negate();
  506.             }

  507.         } else {
  508.             // use Toshio Fukushima method, with several iterations
  509.             final double epsPhi = 1.0e-15;
  510.             final double epsH   = 1.0e-14 * getA();
  511.             final double c      = getA() * e2;
  512.             final T      absZ   = z.abs();
  513.             final T      zc     = absZ.multiply(g);
  514.             T            sn     = absZ;
  515.             T            sn2    = sn.multiply(sn);
  516.             T            cn     = r.multiply(g);
  517.             T            cn2    = cn.multiply(cn);
  518.             T            an2    = cn2.add(sn2);
  519.             T            an     = an2.sqrt();
  520.             T            bn     = an.getField().getZero();
  521.             phi = an.getField().getZero().add(Double.POSITIVE_INFINITY);
  522.             h   = an.getField().getZero().add(Double.POSITIVE_INFINITY);
  523.             for (int i = 0; i < 10; ++i) { // this usually converges in 2 iterations
  524.                 final T oldSn  = sn;
  525.                 final T oldCn  = cn;
  526.                 final T oldPhi = phi;
  527.                 final T oldH   = h;
  528.                 final T an3    = an2.multiply(an);
  529.                 final T csncn  = sn.multiply(cn).multiply(c);
  530.                 bn    = csncn.multiply(1.5).multiply((r.multiply(sn).subtract(zc.multiply(cn))).multiply(an).subtract(csncn));
  531.                 sn    = zc.multiply(an3).add(sn2.multiply(sn).multiply(c)).multiply(an3).subtract(bn.multiply(sn));
  532.                 cn    = r.multiply(an3).subtract(cn2.multiply(cn).multiply(c)).multiply(an3).subtract(bn.multiply(cn));
  533.                 if (sn.getReal() * oldSn.getReal() < 0 || cn.getReal() < 0) {
  534.                     // the Halley iteration went too far, we restrict it and iterate again
  535.                     while (sn.getReal() * oldSn.getReal() < 0 || cn.getReal() < 0) {
  536.                         sn = sn.add(oldSn).multiply(0.5);
  537.                         cn = cn.add(oldCn).multiply(0.5);
  538.                     }
  539.                 } else {

  540.                     // rescale components to avoid overflow when several iterations are used
  541.                     final int exp = (FastMath.getExponent(sn.getReal()) + FastMath.getExponent(cn.getReal())) / 2;
  542.                     sn = sn.scalb(-exp);
  543.                     cn = cn.scalb(-exp);

  544.                     sn2 = sn.multiply(sn);
  545.                     cn2 = cn.multiply(cn);
  546.                     an2 = cn2.add(sn2);
  547.                     an  = an2.sqrt();

  548.                     final T cc = cn.multiply(g);
  549.                     h = r.multiply(cc).add(absZ.multiply(sn)).subtract(an.multiply(getA() * g)).divide(an2.subtract(cn2.multiply(e2)).sqrt());
  550.                     if (FastMath.abs(oldH.getReal()  - h.getReal())   < epsH) {
  551.                         phi = sn.divide(cc).atan().copySign(z);
  552.                         if (FastMath.abs(oldPhi.getReal() - phi.getReal()) < epsPhi) {
  553.                             break;
  554.                         }
  555.                     }

  556.                 }

  557.             }
  558.         }

  559.         return new FieldGeodeticPoint<>(phi, lambda, h);

  560.     }

  561.     /** Transform a Cartesian point to a surface-relative point.
  562.      * @param point Cartesian point
  563.      * @param frame frame in which Cartesian point is expressed
  564.      * @param date date of the computation (used for frames conversions)
  565.      * @return point at the same location but as a surface-relative point,
  566.      * using time as the single derivation parameter
  567.      */
  568.     public FieldGeodeticPoint<DerivativeStructure> transform(final PVCoordinates point,
  569.                                                              final Frame frame, final AbsoluteDate date) {

  570.         // transform point to body frame
  571.         final Transform toBody = frame.getTransformTo(bodyFrame, date);
  572.         final PVCoordinates pointInBodyFrame = toBody.transformPVCoordinates(point);
  573.         final FieldVector3D<DerivativeStructure> p = pointInBodyFrame.toDerivativeStructureVector(2);
  574.         final DerivativeStructure   pr2 = p.getX().multiply(p.getX()).add(p.getY().multiply(p.getY()));
  575.         final DerivativeStructure   pr  = pr2.sqrt();
  576.         final DerivativeStructure   pz  = p.getZ();

  577.         // project point on the ellipsoid surface
  578.         final TimeStampedPVCoordinates groundPoint = projectToGround(new TimeStampedPVCoordinates(date, pointInBodyFrame),
  579.                                                                      bodyFrame);
  580.         final FieldVector3D<DerivativeStructure> gp = groundPoint.toDerivativeStructureVector(2);
  581.         final DerivativeStructure   gpr2 = gp.getX().multiply(gp.getX()).add(gp.getY().multiply(gp.getY()));
  582.         final DerivativeStructure   gpr  = gpr2.sqrt();
  583.         final DerivativeStructure   gpz  = gp.getZ();

  584.         // relative position of test point with respect to its ellipse sub-point
  585.         final DerivativeStructure dr  = pr.subtract(gpr);
  586.         final DerivativeStructure dz  = pz.subtract(gpz);
  587.         final double insideIfNegative = g2 * (pr2.getReal() - ae2) + pz.getReal() * pz.getReal();

  588.         return new FieldGeodeticPoint<>(DerivativeStructure.atan2(gpz, gpr.multiply(g2)),
  589.                                                                   DerivativeStructure.atan2(p.getY(), p.getX()),
  590.                                                                   DerivativeStructure.hypot(dr, dz).copySign(insideIfNegative));
  591.     }

  592.     /** Replace the instance with a data transfer object for serialization.
  593.      * <p>
  594.      * This intermediate class serializes the files supported names, the
  595.      * ephemeris type and the body name.
  596.      * </p>
  597.      * @return data transfer object that will be serialized
  598.      */
  599.     private Object writeReplace() {
  600.         return new DataTransferObject(getA(), f, bodyFrame, angularThreshold);
  601.     }

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

  604.         /** Serializable UID. */
  605.         private static final long serialVersionUID = 20130518L;

  606.         /** Equatorial radius. */
  607.         private final double ae;

  608.         /** Flattening. */
  609.         private final double f;

  610.         /** Body frame related to body shape. */
  611.         private final Frame bodyFrame;

  612.         /** Convergence limit. */
  613.         private final double angularThreshold;

  614.         /** Simple constructor.
  615.          * @param ae equatorial radius
  616.          * @param f the flattening (f = (a-b)/a)
  617.          * @param bodyFrame body frame related to body shape
  618.          * @param angularThreshold convergence limit
  619.          */
  620.         DataTransferObject(final double ae, final double f,
  621.                                   final Frame bodyFrame, final double angularThreshold) {
  622.             this.ae               = ae;
  623.             this.f                = f;
  624.             this.bodyFrame        = bodyFrame;
  625.             this.angularThreshold = angularThreshold;
  626.         }

  627.         /** Replace the deserialized data transfer object with a
  628.          * {@link JPLCelestialBody}.
  629.          * @return replacement {@link JPLCelestialBody}
  630.          */
  631.         private Object readResolve() {
  632.             final OneAxisEllipsoid ellipsoid = new OneAxisEllipsoid(ae, f, bodyFrame);
  633.             ellipsoid.setAngularThreshold(angularThreshold);
  634.             return ellipsoid;
  635.         }

  636.     }

  637. }