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.Field;
  21. import org.hipparchus.analysis.differentiation.DerivativeStructure;
  22. import org.hipparchus.geometry.euclidean.threed.FieldLine;
  23. import org.hipparchus.geometry.euclidean.threed.FieldVector3D;
  24. import org.hipparchus.geometry.euclidean.threed.Line;
  25. import org.hipparchus.geometry.euclidean.threed.Vector3D;
  26. import org.hipparchus.geometry.euclidean.twod.Vector2D;
  27. import org.hipparchus.util.FastMath;
  28. import org.hipparchus.util.FieldSinCos;
  29. import org.hipparchus.util.MathArrays;
  30. import org.hipparchus.util.MathUtils;
  31. import org.hipparchus.util.SinCos;
  32. import org.orekit.frames.FieldTransform;
  33. import org.orekit.frames.Frame;
  34. import org.orekit.frames.StaticTransform;
  35. import org.orekit.frames.Transform;
  36. import org.orekit.time.AbsoluteDate;
  37. import org.orekit.time.FieldAbsoluteDate;
  38. import org.orekit.utils.PVCoordinates;
  39. import org.orekit.utils.TimeStampedPVCoordinates;


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

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

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

  49.     /** Serializable UID. */
  50.     private static final long serialVersionUID = 20130518L;

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

  53.     /** Body frame related to body shape. */
  54.     private final Frame bodyFrame;

  55.     /** Equatorial radius power 2. */
  56.     private final double ae2;

  57.     /** Polar radius power 2. */
  58.     private final double ap2;

  59.     /** Flattening. */
  60.     private final double f;

  61.     /** Eccentricity. */
  62.     private final double e;

  63.     /** Eccentricity squared. */
  64.     private final double e2;

  65.     /** 1 minus flatness. */
  66.     private final double g;

  67.     /** g squared. */
  68.     private final double g2;

  69.     /** Convergence limit. */
  70.     private double angularThreshold;

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

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

  122.     /** Get the equatorial radius of the body.
  123.      * @return equatorial radius of the body (m)
  124.      */
  125.     public double getEquatorialRadius() {
  126.         return getA();
  127.     }

  128.     /** Get the flattening of the body: f = (a-b)/a.
  129.      * @return the flattening
  130.      */
  131.     public double getFlattening() {
  132.         return f;
  133.     }

  134.     /** Get the first eccentricity squared of the ellipsoid: e^2 = f * (2.0 - f).
  135.      * @return the eccentricity squared
  136.      */
  137.     public double getEccentricitySquared() {
  138.         return e2;
  139.     }

  140.     /** Get the first eccentricity of the ellipsoid: e = sqrt(f * (2.0 - f)).
  141.      * @return the eccentricity
  142.      */
  143.     public double getEccentricity() {
  144.         return e;
  145.     }

  146.     /** {@inheritDoc} */
  147.     public Frame getBodyFrame() {
  148.         return bodyFrame;
  149.     }

  150.     /** Get the intersection point of a line with the surface of the body.
  151.      * <p>A line may have several intersection points with a closed
  152.      * surface (we consider the one point case as a degenerated two
  153.      * points case). The close parameter is used to select which of
  154.      * these points should be returned. The selected point is the one
  155.      * that is closest to the close point.</p>
  156.      * @param line test line (may intersect the body or not)
  157.      * @param close point used for intersections selection
  158.      * @param frame frame in which line is expressed
  159.      * @param date date of the line in given frame
  160.      * @return intersection point at altitude zero or null if the line does
  161.      * not intersect the surface
  162.      * @since 9.3
  163.      */
  164.     public Vector3D getCartesianIntersectionPoint(final Line line, final Vector3D close,
  165.                                                   final Frame frame, final AbsoluteDate date) {

  166.         // transform line and close to body frame
  167.         final StaticTransform frameToBodyFrame =
  168.                 frame.getStaticTransformTo(bodyFrame, date);
  169.         final Line lineInBodyFrame = frameToBodyFrame.transformLine(line);

  170.         // compute some miscellaneous variables
  171.         final Vector3D point    = lineInBodyFrame.getOrigin();
  172.         final double x          = point.getX();
  173.         final double y          = point.getY();
  174.         final double z          = point.getZ();
  175.         final double z2         = z * z;
  176.         final double r2         = x * x + y * y;

  177.         final Vector3D direction = lineInBodyFrame.getDirection();
  178.         final double dx         = direction.getX();
  179.         final double dy         = direction.getY();
  180.         final double dz         = direction.getZ();
  181.         final double cz2        = dx * dx + dy * dy;

  182.         // abscissa of the intersection as a root of a 2nd degree polynomial :
  183.         // a k^2 - 2 b k + c = 0
  184.         final double a  = 1.0 - e2 * cz2;
  185.         final double b  = -(g2 * (x * dx + y * dy) + z * dz);
  186.         final double c  = g2 * (r2 - ae2) + z2;
  187.         final double b2 = b * b;
  188.         final double ac = a * c;
  189.         if (b2 < ac) {
  190.             return null;
  191.         }
  192.         final double s  = FastMath.sqrt(b2 - ac);
  193.         final double k1 = (b < 0) ? (b - s) / a : c / (b + s);
  194.         final double k2 = c / (a * k1);

  195.         // select the right point
  196.         final Vector3D closeInBodyFrame = frameToBodyFrame.transformPosition(close);
  197.         final double   closeAbscissa    = lineInBodyFrame.getAbscissa(closeInBodyFrame);
  198.         final double k =
  199.             (FastMath.abs(k1 - closeAbscissa) < FastMath.abs(k2 - closeAbscissa)) ? k1 : k2;
  200.         return lineInBodyFrame.pointAt(k);

  201.     }

  202.     /** {@inheritDoc} */
  203.     public GeodeticPoint getIntersectionPoint(final Line line, final Vector3D close,
  204.                                               final Frame frame, final AbsoluteDate date) {

  205.         final Vector3D intersection = getCartesianIntersectionPoint(line, close, frame, date);
  206.         if (intersection == null) {
  207.             return null;
  208.         }
  209.         final double ix = intersection.getX();
  210.         final double iy = intersection.getY();
  211.         final double iz = intersection.getZ();

  212.         final double lambda = FastMath.atan2(iy, ix);
  213.         final double phi    = FastMath.atan2(iz, g2 * FastMath.sqrt(ix * ix + iy * iy));
  214.         return new GeodeticPoint(phi, lambda, 0.0);

  215.     }

  216.     /** Get the intersection point of a line with the surface of the body.
  217.      * <p>A line may have several intersection points with a closed
  218.      * surface (we consider the one point case as a degenerated two
  219.      * points case). The close parameter is used to select which of
  220.      * these points should be returned. The selected point is the one
  221.      * that is closest to the close point.</p>
  222.      * @param line test line (may intersect the body or not)
  223.      * @param close point used for intersections selection
  224.      * @param frame frame in which line is expressed
  225.      * @param date date of the line in given frame
  226.      * @param <T> type of the field elements
  227.      * @return intersection point at altitude zero or null if the line does
  228.      * not intersect the surface
  229.      * @since 9.3
  230.      */
  231.     public <T extends CalculusFieldElement<T>> FieldVector3D<T> getCartesianIntersectionPoint(final FieldLine<T> line,
  232.                                                                                           final FieldVector3D<T> close,
  233.                                                                                           final Frame frame,
  234.                                                                                           final FieldAbsoluteDate<T> date) {

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

  238.         // compute some miscellaneous variables
  239.         final FieldVector3D<T> point = lineInBodyFrame.getOrigin();
  240.         final T x  = point.getX();
  241.         final T y  = point.getY();
  242.         final T z  = point.getZ();
  243.         final T z2 = z.multiply(z);
  244.         final T r2 = x.multiply(x).add(y.multiply(y));

  245.         final FieldVector3D<T> direction = lineInBodyFrame.getDirection();
  246.         final T dx  = direction.getX();
  247.         final T dy  = direction.getY();
  248.         final T dz  = direction.getZ();
  249.         final T cz2 = dx.multiply(dx).add(dy.multiply(dy));

  250.         // abscissa of the intersection as a root of a 2nd degree polynomial :
  251.         // a k^2 - 2 b k + c = 0
  252.         final T a  = cz2.multiply(e2).subtract(1.0).negate();
  253.         final T b  = x.multiply(dx).add(y.multiply(dy)).multiply(g2).add(z.multiply(dz)).negate();
  254.         final T c  = r2.subtract(ae2).multiply(g2).add(z2);
  255.         final T b2 = b.multiply(b);
  256.         final T ac = a.multiply(c);
  257.         if (b2.getReal() < ac.getReal()) {
  258.             return null;
  259.         }
  260.         final T s  = b2.subtract(ac).sqrt();
  261.         final T k1 = (b.getReal() < 0) ? b.subtract(s).divide(a) : c.divide(b.add(s));
  262.         final T k2 = c.divide(a.multiply(k1));

  263.         // select the right point
  264.         final FieldVector3D<T>  closeInBodyFrame = frameToBodyFrame.transformPosition(close);
  265.         final T                 closeAbscissa    = lineInBodyFrame.getAbscissa(closeInBodyFrame);
  266.         final T k = (FastMath.abs(k1.getReal() - closeAbscissa.getReal()) < FastMath.abs(k2.getReal() - closeAbscissa.getReal())) ?
  267.                     k1 : k2;
  268.         return lineInBodyFrame.pointAt(k);
  269.     }

  270.     /** {@inheritDoc} */
  271.     public <T extends CalculusFieldElement<T>> FieldGeodeticPoint<T> getIntersectionPoint(final FieldLine<T> line,
  272.                                                                                       final FieldVector3D<T> close,
  273.                                                                                       final Frame frame,
  274.                                                                                       final FieldAbsoluteDate<T> date) {

  275.         final FieldVector3D<T> intersection = getCartesianIntersectionPoint(line, close, frame, date);
  276.         if (intersection == null) {
  277.             return null;
  278.         }
  279.         final T ix = intersection.getX();
  280.         final T iy = intersection.getY();
  281.         final T iz = intersection.getZ();

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

  285.     }

  286.     /** {@inheritDoc} */
  287.     public Vector3D transform(final GeodeticPoint point) {
  288.         final double longitude = point.getLongitude();
  289.         final SinCos scLambda  = FastMath.sinCos(longitude);
  290.         final double latitude  = point.getLatitude();
  291.         final SinCos scPhi     = FastMath.sinCos(latitude);
  292.         final double h         = point.getAltitude();
  293.         final double n         = getA() / FastMath.sqrt(1.0 - e2 * scPhi.sin() * scPhi.sin());
  294.         final double r         = (n + h) * scPhi.cos();
  295.         return new Vector3D(r * scLambda.cos(), r * scLambda.sin(), (g2 * n + h) * scPhi.sin());
  296.     }

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

  299.         final T latitude  = point.getLatitude();
  300.         final T longitude = point.getLongitude();
  301.         final T altitude  = point.getAltitude();

  302.         final FieldSinCos<T> scLambda = FastMath.sinCos(longitude);
  303.         final FieldSinCos<T> scPhi    = FastMath.sinCos(latitude);
  304.         final T cLambda = scLambda.cos();
  305.         final T sLambda = scLambda.sin();
  306.         final T cPhi    = scPhi.cos();
  307.         final T sPhi    = scPhi.sin();
  308.         final T n       = sPhi.multiply(sPhi).multiply(e2).subtract(1.0).negate().sqrt().reciprocal().multiply(getA());
  309.         final T r       = n.add(altitude).multiply(cPhi);

  310.         return new FieldVector3D<>(r.multiply(cLambda),
  311.                                    r.multiply(sLambda),
  312.                                    sPhi.multiply(altitude.add(n.multiply(g2))));
  313.     }

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

  316.         // transform point to body frame
  317.         final StaticTransform toBody = frame.getStaticTransformTo(bodyFrame, date);
  318.         final Vector3D   p         = toBody.transformPosition(point);
  319.         final double     z         = p.getZ();
  320.         final double     r         = FastMath.hypot(p.getX(), p.getY());

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

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

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

  330.     }

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

  333.         // transform point to body frame
  334.         final Transform                toBody        = frame.getTransformTo(bodyFrame, pv.getDate());
  335.         final TimeStampedPVCoordinates pvInBodyFrame = toBody.transformPVCoordinates(pv);
  336.         final Vector3D                 p             = pvInBodyFrame.getPosition();
  337.         final double                   r             = FastMath.hypot(p.getX(), p.getY());

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

  342.         // project coordinates in the meridian plane
  343.         final TimeStampedPVCoordinates gpFirst = firstPrincipalCurvature.projectToEllipse(pvInBodyFrame);
  344.         final Vector3D                 gpP     = gpFirst.getPosition();
  345.         final double                   gr      = MathArrays.linearCombination(gpP.getX(), meridian.getX(),
  346.                                                                               gpP.getY(), meridian.getY());
  347.         final double                   gz      = gpP.getZ();

  348.         // topocentric frame
  349.         final Vector3D east   = new Vector3D(-meridian.getY(), meridian.getX(), 0);
  350.         final Vector3D zenith = new Vector3D(gr * getC() / getA(), meridian, gz * getA() / getC(), Vector3D.PLUS_K).normalize();
  351.         final Vector3D north  = Vector3D.crossProduct(zenith, east);

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

  355.         final Vector3D gpV = gpFirst.getVelocity().add(gpSecond.getVelocity());
  356.         final Vector3D gpA = gpFirst.getAcceleration().add(gpSecond.getAcceleration());

  357.         // moving projected point
  358.         final TimeStampedPVCoordinates groundPV =
  359.                 new TimeStampedPVCoordinates(pv.getDate(), gpP, gpV, gpA);

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

  362.     }

  363.     /** {@inheritDoc}
  364.      * <p>
  365.      * This method is based on Toshio Fukushima's algorithm which uses Halley's method.
  366.      * <a href="https://www.researchgate.net/publication/227215135_Transformation_from_Cartesian_to_Geodetic_Coordinates_Accelerated_by_Halley's_Method">
  367.      * transformation from Cartesian to Geodetic Coordinates Accelerated by Halley's Method</a>,
  368.      * Toshio Fukushima, Journal of Geodesy 9(12):689-693, February 2006
  369.      * </p>
  370.      * <p>
  371.      * Some changes have been added to the original method:
  372.      * <ul>
  373.      *   <li>in order to handle more accurately corner cases near the pole</li>
  374.      *   <li>in order to handle properly corner cases near the equatorial plane, even far inside the ellipsoid</li>
  375.      *   <li>in order to handle very flat ellipsoids</li>
  376.      * </ul>
  377.      */
  378.     public GeodeticPoint transform(final Vector3D point, final Frame frame, final AbsoluteDate date) {

  379.         // transform point to body frame
  380.         final Vector3D pointInBodyFrame = frame.getStaticTransformTo(bodyFrame, date)
  381.                 .transformPosition(point);
  382.         final double   r2               = pointInBodyFrame.getX() * pointInBodyFrame.getX() +
  383.                                           pointInBodyFrame.getY() * pointInBodyFrame.getY();
  384.         final double   r                = FastMath.sqrt(r2);
  385.         final double   z                = pointInBodyFrame.getZ();

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

  387.         double h;
  388.         double phi;
  389.         if (r <= ANGULAR_THRESHOLD * FastMath.abs(z)) {
  390.             // the point is almost on the polar axis, approximate the ellipsoid with
  391.             // the osculating sphere whose center is at evolute cusp along polar axis
  392.             final double osculatingRadius = ae2 / getC();
  393.             final double evoluteCuspZ     = FastMath.copySign(getA() * e2 / g, -z);
  394.             final double deltaZ           = z - evoluteCuspZ;
  395.             // we use Ï€/2 - atan(r/Δz) instead of atan(Δz/r) for accuracy purposes, as r is much smaller than Δz
  396.             phi = FastMath.copySign(0.5 * FastMath.PI - FastMath.atan(r / FastMath.abs(deltaZ)), deltaZ);
  397.             h   = FastMath.hypot(deltaZ, r) - osculatingRadius;
  398.         } else if (FastMath.abs(z) <= ANGULAR_THRESHOLD * r) {
  399.             // the point is almost on the major axis

  400.             final double osculatingRadius = ap2 / getA();
  401.             final double evoluteCuspR     = getA() * e2;
  402.             final double deltaR           = r - evoluteCuspR;
  403.             if (deltaR >= 0) {
  404.                 // the point is outside of the ellipse evolute, approximate the ellipse
  405.                 // with the osculating circle whose center is at evolute cusp along major axis
  406.                 phi = (deltaR == 0) ? 0.0 : FastMath.atan(z / deltaR);
  407.                 h   = FastMath.hypot(deltaR, z) - osculatingRadius;
  408.             } else {
  409.                 // the point is on the part of the major axis within ellipse evolute
  410.                 // we can compute the closest ellipse point analytically, and it is NOT near the equator
  411.                 final double rClose = r / e2;
  412.                 final double zClose = FastMath.copySign(g * FastMath.sqrt(ae2 - rClose * rClose), z);
  413.                 phi = FastMath.atan((zClose - z) / (rClose - r));
  414.                 h   = -FastMath.hypot(r - rClose, z - zClose);
  415.             }

  416.         } else {
  417.             // use Toshio Fukushima method, with several iterations
  418.             final double epsPhi = 1.0e-15;
  419.             final double epsH   = 1.0e-14 * FastMath.max(getA(), FastMath.sqrt(r2 + z * z));
  420.             final double c     = getA() * e2;
  421.             final double absZ  = FastMath.abs(z);
  422.             final double zc    = g * absZ;
  423.             double sn  = absZ;
  424.             double sn2 = sn * sn;
  425.             double cn  = g * r;
  426.             double cn2 = cn * cn;
  427.             double an2 = cn2 + sn2;
  428.             double an  = FastMath.sqrt(an2);
  429.             double bn  = 0;
  430.             phi = Double.POSITIVE_INFINITY;
  431.             h   = Double.POSITIVE_INFINITY;
  432.             for (int i = 0; i < 10; ++i) { // this usually converges in 2 iterations
  433.                 final double oldSn  = sn;
  434.                 final double oldCn  = cn;
  435.                 final double oldPhi = phi;
  436.                 final double oldH   = h;
  437.                 final double an3    = an2 * an;
  438.                 final double csncn  = c * sn * cn;
  439.                 bn    = 1.5 * csncn * ((r * sn - zc * cn) * an - csncn);
  440.                 sn    = (zc * an3 + c * sn2 * sn) * an3 - bn * sn;
  441.                 cn    = (r  * an3 - c * cn2 * cn) * an3 - bn * cn;
  442.                 if (sn * oldSn < 0 || cn < 0) {
  443.                     // the Halley iteration went too far, we restrict it and iterate again
  444.                     while (sn * oldSn < 0 || cn < 0) {
  445.                         sn = (sn + oldSn) / 2;
  446.                         cn = (cn + oldCn) / 2;
  447.                     }
  448.                 } else {

  449.                     // rescale components to avoid overflow when several iterations are used
  450.                     final int exp = (FastMath.getExponent(sn) + FastMath.getExponent(cn)) / 2;
  451.                     sn = FastMath.scalb(sn, -exp);
  452.                     cn = FastMath.scalb(cn, -exp);

  453.                     sn2 = sn * sn;
  454.                     cn2 = cn * cn;
  455.                     an2 = cn2 + sn2;
  456.                     an  = FastMath.sqrt(an2);

  457.                     final double cc = g * cn;
  458.                     h = (r * cc + absZ * sn - getA() * g * an) / FastMath.sqrt(an2 - e2 * cn2);
  459.                     if (FastMath.abs(oldH   - h)   < epsH) {
  460.                         phi = FastMath.copySign(FastMath.atan(sn / cc), z);
  461.                         if (FastMath.abs(oldPhi - phi) < epsPhi) {
  462.                             break;
  463.                         }
  464.                     }

  465.                 }

  466.             }
  467.         }

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

  469.     }

  470.     /** {@inheritDoc}
  471.      * <p>
  472.      * This method is based on Toshio Fukushima's algorithm which uses Halley's method.
  473.      * <a href="https://www.researchgate.net/publication/227215135_Transformation_from_Cartesian_to_Geodetic_Coordinates_Accelerated_by_Halley's_Method">
  474.      * transformation from Cartesian to Geodetic Coordinates Accelerated by Halley's Method</a>,
  475.      * Toshio Fukushima, Journal of Geodesy 9(12):689-693, February 2006
  476.      * </p>
  477.      * <p>
  478.      * Some changes have been added to the original method:
  479.      * <ul>
  480.      *   <li>in order to handle more accurately corner cases near the pole</li>
  481.      *   <li>in order to handle properly corner cases near the equatorial plane, even far inside the ellipsoid</li>
  482.      *   <li>in order to handle very flat ellipsoids</li>
  483.      * </ul>
  484.      */
  485.     public <T extends CalculusFieldElement<T>> FieldGeodeticPoint<T> transform(final FieldVector3D<T> point,
  486.                                                                            final Frame frame,
  487.                                                                            final FieldAbsoluteDate<T> date) {

  488.         // transform point to body frame
  489.         final FieldVector3D<T> pointInBodyFrame = frame.getTransformTo(bodyFrame, date).transformPosition(point);
  490.         final T   r2                            = pointInBodyFrame.getX().multiply(pointInBodyFrame.getX()).
  491.                                               add(pointInBodyFrame.getY().multiply(pointInBodyFrame.getY()));
  492.         final T   r                             = r2.sqrt();
  493.         final T   z                             = pointInBodyFrame.getZ();

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

  495.         T h;
  496.         T phi;
  497.         if (r.getReal() <= ANGULAR_THRESHOLD * FastMath.abs(z.getReal())) {
  498.             // the point is almost on the polar axis, approximate the ellipsoid with
  499.             // the osculating sphere whose center is at evolute cusp along polar axis
  500.             final double osculatingRadius = ae2 / getC();
  501.             final double evoluteCuspZ     = FastMath.copySign(getA() * e2 / g, -z.getReal());
  502.             final T      deltaZ           = z.subtract(evoluteCuspZ);
  503.             // we use Ï€/2 - atan(r/Δz) instead of atan(Δz/r) for accuracy purposes, as r is much smaller than Δz
  504.             phi = r.divide(deltaZ.abs()).atan().negate().add(r.getPi().multiply(0.5)).copySign(deltaZ);
  505.             h   = deltaZ.hypot(r).subtract(osculatingRadius);
  506.         } else if (FastMath.abs(z.getReal()) <= ANGULAR_THRESHOLD * r.getReal()) {
  507.             // the point is almost on the major axis

  508.             final double osculatingRadius = ap2 / getA();
  509.             final double evoluteCuspR     = getA() * e2;
  510.             final T      deltaR           = r.subtract(evoluteCuspR);
  511.             if (deltaR.getReal() >= 0) {
  512.                 // the point is outside of the ellipse evolute, approximate the ellipse
  513.                 // with the osculating circle whose center is at evolute cusp along major axis
  514.                 phi = (deltaR.getReal() == 0) ? z.getField().getZero() : z.divide(deltaR).atan();
  515.                 h   = deltaR.hypot(z).subtract(osculatingRadius);
  516.             } else {
  517.                 // the point is on the part of the major axis within ellipse evolute
  518.                 // we can compute the closest ellipse point analytically, and it is NOT near the equator
  519.                 final T rClose = r.divide(e2);
  520.                 final T zClose = rClose.multiply(rClose).negate().add(ae2).sqrt().multiply(g).copySign(z);
  521.                 phi = zClose.subtract(z).divide(rClose.subtract(r)).atan();
  522.                 h   = r.subtract(rClose).hypot(z.subtract(zClose)).negate();
  523.             }

  524.         } else {
  525.             // use Toshio Fukushima method, with several iterations
  526.             final double epsPhi = 1.0e-15;
  527.             final double epsH   = 1.0e-14 * getA();
  528.             final double c      = getA() * e2;
  529.             final T      absZ   = z.abs();
  530.             final T      zc     = absZ.multiply(g);
  531.             T            sn     = absZ;
  532.             T            sn2    = sn.multiply(sn);
  533.             T            cn     = r.multiply(g);
  534.             T            cn2    = cn.multiply(cn);
  535.             T            an2    = cn2.add(sn2);
  536.             T            an     = an2.sqrt();
  537.             T            bn     = an.getField().getZero();
  538.             phi = an.getField().getZero().add(Double.POSITIVE_INFINITY);
  539.             h   = an.getField().getZero().add(Double.POSITIVE_INFINITY);
  540.             for (int i = 0; i < 10; ++i) { // this usually converges in 2 iterations
  541.                 final T oldSn  = sn;
  542.                 final T oldCn  = cn;
  543.                 final T oldPhi = phi;
  544.                 final T oldH   = h;
  545.                 final T an3    = an2.multiply(an);
  546.                 final T csncn  = sn.multiply(cn).multiply(c);
  547.                 bn    = csncn.multiply(1.5).multiply((r.multiply(sn).subtract(zc.multiply(cn))).multiply(an).subtract(csncn));
  548.                 sn    = zc.multiply(an3).add(sn2.multiply(sn).multiply(c)).multiply(an3).subtract(bn.multiply(sn));
  549.                 cn    = r.multiply(an3).subtract(cn2.multiply(cn).multiply(c)).multiply(an3).subtract(bn.multiply(cn));
  550.                 if (sn.getReal() * oldSn.getReal() < 0 || cn.getReal() < 0) {
  551.                     // the Halley iteration went too far, we restrict it and iterate again
  552.                     while (sn.getReal() * oldSn.getReal() < 0 || cn.getReal() < 0) {
  553.                         sn = sn.add(oldSn).multiply(0.5);
  554.                         cn = cn.add(oldCn).multiply(0.5);
  555.                     }
  556.                 } else {

  557.                     // rescale components to avoid overflow when several iterations are used
  558.                     final int exp = (FastMath.getExponent(sn.getReal()) + FastMath.getExponent(cn.getReal())) / 2;
  559.                     sn = sn.scalb(-exp);
  560.                     cn = cn.scalb(-exp);

  561.                     sn2 = sn.multiply(sn);
  562.                     cn2 = cn.multiply(cn);
  563.                     an2 = cn2.add(sn2);
  564.                     an  = an2.sqrt();

  565.                     final T cc = cn.multiply(g);
  566.                     h = r.multiply(cc).add(absZ.multiply(sn)).subtract(an.multiply(getA() * g)).divide(an2.subtract(cn2.multiply(e2)).sqrt());
  567.                     if (FastMath.abs(oldH.getReal()  - h.getReal())   < epsH) {
  568.                         phi = sn.divide(cc).atan().copySign(z);
  569.                         if (FastMath.abs(oldPhi.getReal() - phi.getReal()) < epsPhi) {
  570.                             break;
  571.                         }
  572.                     }

  573.                 }

  574.             }
  575.         }

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

  577.     }

  578.     /** Transform a Cartesian point to a surface-relative point.
  579.      * @param point Cartesian point
  580.      * @param frame frame in which Cartesian point is expressed
  581.      * @param date date of the computation (used for frames conversions)
  582.      * @return point at the same location but as a surface-relative point,
  583.      * using time as the single derivation parameter
  584.      */
  585.     public FieldGeodeticPoint<DerivativeStructure> transform(final PVCoordinates point,
  586.                                                              final Frame frame, final AbsoluteDate date) {

  587.         // transform point to body frame
  588.         final Transform toBody = frame.getTransformTo(bodyFrame, date);
  589.         final PVCoordinates pointInBodyFrame = toBody.transformPVCoordinates(point);
  590.         final FieldVector3D<DerivativeStructure> p = pointInBodyFrame.toDerivativeStructureVector(2);
  591.         final DerivativeStructure   pr2 = p.getX().multiply(p.getX()).add(p.getY().multiply(p.getY()));
  592.         final DerivativeStructure   pr  = pr2.sqrt();
  593.         final DerivativeStructure   pz  = p.getZ();

  594.         // project point on the ellipsoid surface
  595.         final TimeStampedPVCoordinates groundPoint = projectToGround(new TimeStampedPVCoordinates(date, pointInBodyFrame),
  596.                                                                      bodyFrame);
  597.         final FieldVector3D<DerivativeStructure> gp = groundPoint.toDerivativeStructureVector(2);
  598.         final DerivativeStructure   gpr2 = gp.getX().multiply(gp.getX()).add(gp.getY().multiply(gp.getY()));
  599.         final DerivativeStructure   gpr  = gpr2.sqrt();
  600.         final DerivativeStructure   gpz  = gp.getZ();

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

  605.         return new FieldGeodeticPoint<>(DerivativeStructure.atan2(gpz, gpr.multiply(g2)),
  606.                                                                   DerivativeStructure.atan2(p.getY(), p.getX()),
  607.                                                                   DerivativeStructure.hypot(dr, dz).copySign(insideIfNegative));
  608.     }

  609.     /** Compute the azimuth angle from local north between the two points.
  610.      *
  611.      * The angle is calculated clockwise from local north at the origin point
  612.      * and follows the rhumb line to the destination point.
  613.      *
  614.      * @param origin the origin point, at which the azimuth angle will be computed (non-{@code null})
  615.      * @param destination the destination point, to which the angle is defined (non-{@code null})
  616.      * @return the resulting azimuth angle (radians, {@code [0-2pi)})
  617.      * @since 11.3
  618.      */
  619.     public double azimuthBetweenPoints(final GeodeticPoint origin, final GeodeticPoint destination) {
  620.         final double dLon = MathUtils.normalizeAngle(destination.getLongitude(), origin.getLongitude()) - origin.getLongitude();
  621.         final double originIsoLat = geodeticToIsometricLatitude(origin.getLatitude());
  622.         final double destIsoLat = geodeticToIsometricLatitude(destination.getLatitude());

  623.         final double az = FastMath.atan2(dLon, destIsoLat - originIsoLat);
  624.         if (az < 0.) {
  625.             return az + MathUtils.TWO_PI;
  626.         }
  627.         return az;
  628.     }

  629.     /** Compute the azimuth angle from local north between the two points.
  630.      *
  631.      * The angle is calculated clockwise from local north at the origin point
  632.      * and follows the rhumb line to the destination point.
  633.      *
  634.      * @param origin the origin point, at which the azimuth angle will be computed (non-{@code null})
  635.      * @param destination the destination point, to which the angle is defined (non-{@code null})
  636.      * @param <T> the type of field elements
  637.      * @return the resulting azimuth angle (radians, {@code [0-2pi)})
  638.      * @since 11.3
  639.      */
  640.     public <T extends CalculusFieldElement<T>> T azimuthBetweenPoints(final FieldGeodeticPoint<T> origin, final FieldGeodeticPoint<T> destination) {
  641.         final T dLon = MathUtils.normalizeAngle(destination.getLongitude().subtract(origin.getLongitude()), origin.getLongitude().getField().getZero());
  642.         final T originIsoLat = geodeticToIsometricLatitude(origin.getLatitude());
  643.         final T destIsoLat = geodeticToIsometricLatitude(destination.getLatitude());

  644.         final T az = FastMath.atan2(dLon, destIsoLat.subtract(originIsoLat));
  645.         if (az.getReal() < 0.) {
  646.             return az.add(az.getPi().multiply(2));
  647.         }
  648.         return az;
  649.     }

  650.     /** Compute the <a href="https://mathworld.wolfram.com/IsometricLatitude.html">isometric latitude</a>
  651.      *  corresponding to the provided latitude.
  652.      *
  653.      * @param geodeticLatitude the latitude (radians, within interval {@code [-pi/2, +pi/2]})
  654.      * @return the isometric latitude (radians)
  655.      * @since 11.3
  656.      */
  657.     public double geodeticToIsometricLatitude(final double geodeticLatitude) {
  658.         if (FastMath.abs(geodeticLatitude) <= angularThreshold) {
  659.             return 0.;
  660.         }

  661.         final double eSinLat = e * FastMath.sin(geodeticLatitude);

  662.         // first term: ln(tan(pi/4 + lat/2))
  663.         final double a = FastMath.log(FastMath.tan(FastMath.PI / 4. + geodeticLatitude / 2.));
  664.         // second term: (ecc / 2) * ln((1 - ecc*sin(lat)) / (1 + ecc * sin(lat)))
  665.         final double b = (e / 2.) * FastMath.log((1. - eSinLat) / (1. + eSinLat));

  666.         return a + b;
  667.     }

  668.     /** Compute the <a href="https://mathworld.wolfram.com/IsometricLatitude.html">isometric latitude</a>
  669.      *  corresponding to the provided latitude.
  670.      *
  671.      * @param geodeticLatitude the latitude (radians, within interval {@code [-pi/2, +pi/2]})
  672.      * @param <T> the type of field elements
  673.      * @return the isometric latitude (radians)
  674.      * @since 11.3
  675.      */
  676.     public <T extends CalculusFieldElement<T>> T geodeticToIsometricLatitude(final T geodeticLatitude) {
  677.         if (geodeticLatitude.abs().getReal() <= angularThreshold) {
  678.             return geodeticLatitude.getField().getZero();
  679.         }
  680.         final Field<T> field = geodeticLatitude.getField();
  681.         final T ecc = geodeticLatitude.newInstance(e);
  682.         final T eSinLat = ecc.multiply(geodeticLatitude.sin());

  683.         // first term: ln(tan(pi/4 + lat/2))
  684.         final T a = FastMath.log(FastMath.tan(geodeticLatitude.getPi().divide(4.).add(geodeticLatitude.divide(2.))));
  685.         // second term: (ecc / 2) * ln((1 - ecc*sin(lat)) / (1 + ecc * sin(lat)))
  686.         final T b = ecc.divide(2.).multiply(FastMath.log(field.getOne().subtract(eSinLat).divide(field.getOne().add(eSinLat))));

  687.         return a.add(b);
  688.     }

  689.     /** Replace the instance with a data transfer object for serialization.
  690.      * <p>
  691.      * This intermediate class serializes the files supported names, the
  692.      * ephemeris type and the body name.
  693.      * </p>
  694.      * @return data transfer object that will be serialized
  695.      */
  696.     private Object writeReplace() {
  697.         return new DataTransferObject(getA(), f, bodyFrame, angularThreshold);
  698.     }

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

  701.         /** Serializable UID. */
  702.         private static final long serialVersionUID = 20130518L;

  703.         /** Equatorial radius. */
  704.         private final double ae;

  705.         /** Flattening. */
  706.         private final double f;

  707.         /** Body frame related to body shape. */
  708.         private final Frame bodyFrame;

  709.         /** Convergence limit. */
  710.         private final double angularThreshold;

  711.         /** Simple constructor.
  712.          * @param ae equatorial radius
  713.          * @param f the flattening (f = (a-b)/a)
  714.          * @param bodyFrame body frame related to body shape
  715.          * @param angularThreshold convergence limit
  716.          */
  717.         DataTransferObject(final double ae, final double f,
  718.                                   final Frame bodyFrame, final double angularThreshold) {
  719.             this.ae               = ae;
  720.             this.f                = f;
  721.             this.bodyFrame        = bodyFrame;
  722.             this.angularThreshold = angularThreshold;
  723.         }

  724.         /** Replace the deserialized data transfer object with a
  725.          * {@link JPLCelestialBody}.
  726.          * @return replacement {@link JPLCelestialBody}
  727.          */
  728.         private Object readResolve() {
  729.             final OneAxisEllipsoid ellipsoid = new OneAxisEllipsoid(ae, f, bodyFrame);
  730.             ellipsoid.setAngularThreshold(angularThreshold);
  731.             return ellipsoid;
  732.         }

  733.     }

  734. }