OneAxisEllipsoid.java

  1. /* Copyright 2002-2025 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.util.function.DoubleFunction;

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


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

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

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

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

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

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

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

  58.     /** Eccentricity. */
  59.     private final double e;

  60.     /** Eccentricity squared. */
  61.     private final double e2;

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

  64.     /** g squared. */
  65.     private final double g2;

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

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

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

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

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

  130.     /** Get the first eccentricity squared of the ellipsoid: e^2 = f * (2.0 - f).
  131.      * @return the eccentricity squared
  132.      */
  133.     public double getEccentricitySquared() {
  134.         return e2;
  135.     }

  136.     /** Get the first eccentricity of the ellipsoid: e = sqrt(f * (2.0 - f)).
  137.      * @return the eccentricity
  138.      */
  139.     public double getEccentricity() {
  140.         return e;
  141.     }

  142.     /** Get body frame related to body shape.
  143.      * <p>Be mindful that the OneAxisEllipsoid.getBodyFrame() and
  144.      * the OneAxisEllipsoid.getFrame() methods return the same object.</p>
  145.      * @return body frame related to body shape
  146.      */
  147.     public Frame getBodyFrame() {
  148.         return getFrame();
  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(getFrame(), 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 FieldStaticTransform<T> frameToBodyFrame = frame.getStaticTransformTo(getFrame(), 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.square();
  244.         final T r2 = x.square().add(y.square());

  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.square().add(dy.square());

  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.square();
  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(getFrame(), 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(), getFrame());

  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(getFrame(), 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(), getFrame());

  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.      * </p>
  373.      * <ul>
  374.      *   <li>in order to handle more accurately corner cases near the pole</li>
  375.      *   <li>in order to handle properly corner cases near the equatorial plane, even far inside the ellipsoid</li>
  376.      *   <li>in order to handle very flat ellipsoids</li>
  377.      * </ul>
  378.      * <p>
  379.      * In some rare cases (for example very flat ellipsoid, or points close to ellipsoid center), the loop
  380.      * may fail to converge. As this seems to happen only in degenerate cases, a design choice was to return
  381.      * an approximate point corresponding to last iteration. This point may be incorrect and fail to give the
  382.      * initial point back if doing roundtrip by calling {@link #transform(GeodeticPoint)}. This design choice
  383.      * was made to avoid NaNs appearing for example in inter-satellites visibility checks when two satellites
  384.      * are almost on opposite sides of Earth. The intermediate points far within the Earth should not prevent
  385.      * the detection algorithm to find visibility start/end.
  386.      * </p>
  387.      */
  388.     public GeodeticPoint transform(final Vector3D point, final Frame frame, final AbsoluteDate date) {

  389.         // transform point to body frame
  390.         final Vector3D pointInBodyFrame = frame.getStaticTransformTo(getFrame(), date)
  391.                 .transformPosition(point);
  392.         final double   r2               = pointInBodyFrame.getX() * pointInBodyFrame.getX() +
  393.                                           pointInBodyFrame.getY() * pointInBodyFrame.getY();
  394.         final double   r                = FastMath.sqrt(r2);
  395.         final double   z                = pointInBodyFrame.getZ();

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

  397.         double h;
  398.         double phi;
  399.         if (r <= ANGULAR_THRESHOLD * FastMath.abs(z)) {
  400.             // the point is almost on the polar axis, approximate the ellipsoid with
  401.             // the osculating sphere whose center is at evolute cusp along polar axis
  402.             final double osculatingRadius = ae2 / getC();
  403.             final double evoluteCuspZ     = FastMath.copySign(getA() * e2 / g, -z);
  404.             final double deltaZ           = z - evoluteCuspZ;
  405.             // we use Ï€/2 - atan(r/Δz) instead of atan(Δz/r) for accuracy purposes, as r is much smaller than Δz
  406.             phi = FastMath.copySign(0.5 * FastMath.PI - FastMath.atan(r / FastMath.abs(deltaZ)), deltaZ);
  407.             h   = FastMath.hypot(deltaZ, r) - osculatingRadius;
  408.         } else if (FastMath.abs(z) <= ANGULAR_THRESHOLD * r) {
  409.             // the point is almost on the major axis

  410.             final double osculatingRadius = ap2 / getA();
  411.             final double evoluteCuspR     = getA() * e2;
  412.             final double deltaR           = r - evoluteCuspR;
  413.             if (deltaR >= 0) {
  414.                 // the point is outside of the ellipse evolute, approximate the ellipse
  415.                 // with the osculating circle whose center is at evolute cusp along major axis
  416.                 phi = (deltaR == 0) ? 0.0 : FastMath.atan(z / deltaR);
  417.                 h   = FastMath.hypot(deltaR, z) - osculatingRadius;
  418.             } else {
  419.                 // the point is on the part of the major axis within ellipse evolute
  420.                 // we can compute the closest ellipse point analytically, and it is NOT near the equator
  421.                 final double rClose = r / e2;
  422.                 final double zClose = FastMath.copySign(g * FastMath.sqrt(ae2 - rClose * rClose), z);
  423.                 phi = FastMath.atan((zClose - z) / (rClose - r));
  424.                 h   = -FastMath.hypot(r - rClose, z - zClose);
  425.             }

  426.         } else {
  427.             // use Toshio Fukushima method, with several iterations
  428.             final double epsPhi = 1.0e-15;
  429.             final double epsH   = 1.0e-14 * FastMath.max(getA(), FastMath.sqrt(r2 + z * z));
  430.             final double c     = getA() * e2;
  431.             final double absZ  = FastMath.abs(z);
  432.             final double zc    = g * absZ;
  433.             double sn  = absZ;
  434.             double sn2 = sn * sn;
  435.             double cn  = g * r;
  436.             double cn2 = cn * cn;
  437.             double an2 = cn2 + sn2;
  438.             double an  = FastMath.sqrt(an2);
  439.             double bn  = 0;
  440.             phi = Double.POSITIVE_INFINITY;
  441.             h   = Double.POSITIVE_INFINITY;
  442.             for (int i = 0; i < 1000; ++i) {
  443.                 // this usually converges in 2 iterations, but in rare cases it can take much more
  444.                 // see https://gitlab.orekit.org/orekit/orekit/-/issues/1224 for examples
  445.                 // with points near Earth center which need 137 iterations for the first example
  446.                 // and 1150 iterations for the second example
  447.                 final double oldSn  = sn;
  448.                 final double oldCn  = cn;
  449.                 final double oldPhi = phi;
  450.                 final double oldH   = h;
  451.                 final double an3    = an2 * an;
  452.                 final double csncn  = c * sn * cn;
  453.                 bn    = 1.5 * csncn * ((r * sn - zc * cn) * an - csncn);
  454.                 sn    = (zc * an3 + c * sn2 * sn) * an3 - bn * sn;
  455.                 cn    = (r  * an3 - c * cn2 * cn) * an3 - bn * cn;
  456.                 if (sn * oldSn < 0 || cn < 0) {
  457.                     // the Halley iteration went too far, we restrict it and iterate again
  458.                     while (sn * oldSn < 0 || cn < 0) {
  459.                         sn = (sn + oldSn) / 2;
  460.                         cn = (cn + oldCn) / 2;
  461.                     }
  462.                 } else {

  463.                     // rescale components to avoid overflow when several iterations are used
  464.                     final int exp = (FastMath.getExponent(sn) + FastMath.getExponent(cn)) / 2;
  465.                     sn = FastMath.scalb(sn, -exp);
  466.                     cn = FastMath.scalb(cn, -exp);

  467.                     sn2 = sn * sn;
  468.                     cn2 = cn * cn;
  469.                     an2 = cn2 + sn2;
  470.                     an  = FastMath.sqrt(an2);

  471.                     final double cc = g * cn;
  472.                     h = (r * cc + absZ * sn - getA() * g * an) / FastMath.sqrt(an2 - e2 * cn2);
  473.                     if (FastMath.abs(oldH   - h)   < epsH) {
  474.                         phi = FastMath.copySign(FastMath.atan(sn / cc), z);
  475.                         if (FastMath.abs(oldPhi - phi) < epsPhi) {
  476.                             break;
  477.                         }
  478.                     }

  479.                 }

  480.             }

  481.             if (Double.isInfinite(phi)) {
  482.                 // we did not converge, the point is probably within the ellipsoid
  483.                 // we just compute the "best" phi we can to avoid NaN
  484.                 phi = FastMath.copySign(FastMath.atan(sn / (g * cn)), z);
  485.             }

  486.         }

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

  488.     }

  489.     /** {@inheritDoc}
  490.      * <p>
  491.      * This method is based on Toshio Fukushima's algorithm which uses Halley's method.
  492.      * <a href="https://www.researchgate.net/publication/227215135_Transformation_from_Cartesian_to_Geodetic_Coordinates_Accelerated_by_Halley's_Method">
  493.      * transformation from Cartesian to Geodetic Coordinates Accelerated by Halley's Method</a>,
  494.      * Toshio Fukushima, Journal of Geodesy 9(12):689-693, February 2006
  495.      * </p>
  496.      * <p>
  497.      * Some changes have been added to the original method:
  498.      * <ul>
  499.      *   <li>in order to handle more accurately corner cases near the pole</li>
  500.      *   <li>in order to handle properly corner cases near the equatorial plane, even far inside the ellipsoid</li>
  501.      *   <li>in order to handle very flat ellipsoids</li>
  502.      * </ul>
  503.      * <p>
  504.      * In some rare cases (for example very flat ellipsoid, or points close to ellipsoid center), the loop
  505.      * may fail to converge. As this seems to happen only in degenerate cases, a design choice was to return
  506.      * an approximate point corresponding to last iteration. This point may be incorrect and fail to give the
  507.      * initial point back if doing roundtrip by calling {@link #transform(GeodeticPoint)}. This design choice
  508.      * was made to avoid NaNs appearing for example in inter-satellites visibility checks when two satellites
  509.      * are almost on opposite sides of Earth. The intermediate points far within the Earth should not prevent
  510.      * the detection algorithm to find visibility start/end.
  511.      * </p>
  512.      */
  513.     public <T extends CalculusFieldElement<T>> FieldGeodeticPoint<T> transform(final FieldVector3D<T> point,
  514.                                                                            final Frame frame,
  515.                                                                            final FieldAbsoluteDate<T> date) {

  516.         // transform point to body frame
  517.         final FieldVector3D<T> pointInBodyFrame = (frame == getFrame()) ?
  518.                                                   point :
  519.                                                   frame.getStaticTransformTo(getFrame(), date).transformPosition(point);
  520.         final T   r2                            = pointInBodyFrame.getX().multiply(pointInBodyFrame.getX()).
  521.                                                   add(pointInBodyFrame.getY().multiply(pointInBodyFrame.getY()));
  522.         final T   r                             = r2.sqrt();
  523.         final T   z                             = pointInBodyFrame.getZ();

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

  525.         T h;
  526.         T phi;
  527.         if (r.getReal() <= ANGULAR_THRESHOLD * FastMath.abs(z.getReal())) {
  528.             // the point is almost on the polar axis, approximate the ellipsoid with
  529.             // the osculating sphere whose center is at evolute cusp along polar axis
  530.             final double osculatingRadius = ae2 / getC();
  531.             final double evoluteCuspZ     = FastMath.copySign(getA() * e2 / g, -z.getReal());
  532.             final T      deltaZ           = z.subtract(evoluteCuspZ);
  533.             // we use Ï€/2 - atan(r/Δz) instead of atan(Δz/r) for accuracy purposes, as r is much smaller than Δz
  534.             phi = r.divide(deltaZ.abs()).atan().negate().add(r.getPi().multiply(0.5)).copySign(deltaZ);
  535.             h   = deltaZ.hypot(r).subtract(osculatingRadius);
  536.         } else if (FastMath.abs(z.getReal()) <= ANGULAR_THRESHOLD * r.getReal()) {
  537.             // the point is almost on the major axis

  538.             final double osculatingRadius = ap2 / getA();
  539.             final double evoluteCuspR     = getA() * e2;
  540.             final T      deltaR           = r.subtract(evoluteCuspR);
  541.             if (deltaR.getReal() >= 0) {
  542.                 // the point is outside of the ellipse evolute, approximate the ellipse
  543.                 // with the osculating circle whose center is at evolute cusp along major axis
  544.                 phi = (deltaR.getReal() == 0) ? z.getField().getZero() : z.divide(deltaR).atan();
  545.                 h   = deltaR.hypot(z).subtract(osculatingRadius);
  546.             } else {
  547.                 // the point is on the part of the major axis within ellipse evolute
  548.                 // we can compute the closest ellipse point analytically, and it is NOT near the equator
  549.                 final T rClose = r.divide(e2);
  550.                 final T zClose = rClose.multiply(rClose).negate().add(ae2).sqrt().multiply(g).copySign(z);
  551.                 phi = zClose.subtract(z).divide(rClose.subtract(r)).atan();
  552.                 h   = r.subtract(rClose).hypot(z.subtract(zClose)).negate();
  553.             }

  554.         } else {
  555.             // use Toshio Fukushima method, with several iterations
  556.             final double epsPhi = 1.0e-15;
  557.             final double epsH   = 1.0e-14 * getA();
  558.             final double c      = getA() * e2;
  559.             final T      absZ   = z.abs();
  560.             final T      zc     = absZ.multiply(g);
  561.             T            sn     = absZ;
  562.             T            sn2    = sn.multiply(sn);
  563.             T            cn     = r.multiply(g);
  564.             T            cn2    = cn.multiply(cn);
  565.             T            an2    = cn2.add(sn2);
  566.             T            an     = an2.sqrt();
  567.             T            bn     = an.getField().getZero();
  568.             phi = an.getField().getZero().add(Double.POSITIVE_INFINITY);
  569.             h   = an.getField().getZero().add(Double.POSITIVE_INFINITY);
  570.             for (int i = 0; i < 1000; ++i) {
  571.                 // this usually converges in 2 iterations, but in rare cases it can take much more
  572.                 // see https://gitlab.orekit.org/orekit/orekit/-/issues/1224 for examples
  573.                 // with points near Earth center which need 137 iterations for the first example
  574.                 // and 1150 iterations for the second example
  575.                 final T oldSn  = sn;
  576.                 final T oldCn  = cn;
  577.                 final T oldPhi = phi;
  578.                 final T oldH   = h;
  579.                 final T an3    = an2.multiply(an);
  580.                 final T csncn  = sn.multiply(cn).multiply(c);
  581.                 bn    = csncn.multiply(1.5).multiply((r.multiply(sn).subtract(zc.multiply(cn))).multiply(an).subtract(csncn));
  582.                 sn    = zc.multiply(an3).add(sn2.multiply(sn).multiply(c)).multiply(an3).subtract(bn.multiply(sn));
  583.                 cn    = r.multiply(an3).subtract(cn2.multiply(cn).multiply(c)).multiply(an3).subtract(bn.multiply(cn));
  584.                 if (sn.getReal() * oldSn.getReal() < 0 || cn.getReal() < 0) {
  585.                     // the Halley iteration went too far, we restrict it and iterate again
  586.                     while (sn.getReal() * oldSn.getReal() < 0 || cn.getReal() < 0) {
  587.                         sn = sn.add(oldSn).multiply(0.5);
  588.                         cn = cn.add(oldCn).multiply(0.5);
  589.                     }
  590.                 } else {

  591.                     // rescale components to avoid overflow when several iterations are used
  592.                     final int exp = (FastMath.getExponent(sn.getReal()) + FastMath.getExponent(cn.getReal())) / 2;
  593.                     sn = sn.scalb(-exp);
  594.                     cn = cn.scalb(-exp);

  595.                     sn2 = sn.square();
  596.                     cn2 = cn.square();
  597.                     an2 = cn2.add(sn2);
  598.                     an  = an2.sqrt();

  599.                     final T cc = cn.multiply(g);
  600.                     h = r.multiply(cc).add(absZ.multiply(sn)).subtract(an.multiply(getA() * g)).divide(an2.subtract(cn2.multiply(e2)).sqrt());
  601.                     if (FastMath.abs(oldH.getReal()  - h.getReal())   < epsH) {
  602.                         phi = sn.divide(cc).atan().copySign(z);
  603.                         if (FastMath.abs(oldPhi.getReal() - phi.getReal()) < epsPhi) {
  604.                             break;
  605.                         }
  606.                     }

  607.                 }

  608.             }

  609.             if (Double.isInfinite(phi.getReal())) {
  610.                 // we did not converge, the point is probably within the ellipsoid
  611.                 // we just compute the "best" phi we can to avoid NaN
  612.                 phi = sn.divide(cn.multiply(g)).atan().copySign(z);
  613.             }

  614.         }

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

  616.     }

  617.     /** Transform a Cartesian point to a surface-relative point.
  618.      * @param point Cartesian point
  619.      * @param frame frame in which Cartesian point is expressed
  620.      * @param date date of the computation (used for frames conversions)
  621.      * @return point at the same location but as a surface-relative point,
  622.      * using time as the single derivation parameter
  623.      */
  624.     public FieldGeodeticPoint<UnivariateDerivative2> transform(final PVCoordinates point,
  625.                                                                final Frame frame, final AbsoluteDate date) {

  626.         // transform point to body frame
  627.         final Transform toBody = frame.getTransformTo(getFrame(), date);
  628.         final PVCoordinates pointInBodyFrame = toBody.transformPVCoordinates(point);
  629.         final FieldVector3D<UnivariateDerivative2> p = pointInBodyFrame.toUnivariateDerivative2Vector();
  630.         final UnivariateDerivative2   pr2 = p.getX().square().add(p.getY().square());
  631.         final UnivariateDerivative2   pr  = pr2.sqrt();
  632.         final UnivariateDerivative2   pz  = p.getZ();

  633.         // project point on the ellipsoid surface
  634.         final TimeStampedPVCoordinates groundPoint = projectToGround(new TimeStampedPVCoordinates(date, pointInBodyFrame),
  635.                                                                      getFrame());
  636.         final FieldVector3D<UnivariateDerivative2> gp = groundPoint.toUnivariateDerivative2Vector();
  637.         final UnivariateDerivative2   gpr2 = gp.getX().square().add(gp.getY().square());
  638.         final UnivariateDerivative2   gpr  = gpr2.sqrt();
  639.         final UnivariateDerivative2   gpz  = gp.getZ();

  640.         // relative position of test point with respect to its ellipse sub-point
  641.         final UnivariateDerivative2 dr  = pr.subtract(gpr);
  642.         final UnivariateDerivative2 dz  = pz.subtract(gpz);
  643.         final double insideIfNegative = g2 * (pr2.getReal() - ae2) + pz.getReal() * pz.getReal();

  644.         return new FieldGeodeticPoint<>(FastMath.atan2(gpz, gpr.multiply(g2)), FastMath.atan2(p.getY(), p.getX()),
  645.             FastMath.hypot(dr, dz).copySign(insideIfNegative));
  646.     }

  647.     /** Compute the azimuth angle from local north between the two points.
  648.      * The angle is calculated clockwise from local north at the origin point
  649.      * and follows the rhumb line to the destination point.
  650.      *
  651.      * @param origin the origin point, at which the azimuth angle will be computed (non-{@code null})
  652.      * @param destination the destination point, to which the angle is defined (non-{@code null})
  653.      * @return the resulting azimuth angle (radians, {@code [0-2pi)})
  654.      * @since 11.3
  655.      */
  656.     public double azimuthBetweenPoints(final GeodeticPoint origin, final GeodeticPoint destination) {
  657.         final double dLon = MathUtils.normalizeAngle(destination.getLongitude(), origin.getLongitude()) - origin.getLongitude();
  658.         final double originIsoLat = geodeticToIsometricLatitude(origin.getLatitude());
  659.         final double destIsoLat = geodeticToIsometricLatitude(destination.getLatitude());

  660.         final double az = FastMath.atan2(dLon, destIsoLat - originIsoLat);
  661.         if (az < 0.) {
  662.             return az + MathUtils.TWO_PI;
  663.         }
  664.         return az;
  665.     }

  666.     /** Compute the azimuth angle from local north between the two points.
  667.      *
  668.      * The angle is calculated clockwise from local north at the origin point
  669.      * and follows the rhumb line to the destination point.
  670.      *
  671.      * @param origin the origin point, at which the azimuth angle will be computed (non-{@code null})
  672.      * @param destination the destination point, to which the angle is defined (non-{@code null})
  673.      * @param <T> the type of field elements
  674.      * @return the resulting azimuth angle (radians, {@code [0-2pi)})
  675.      * @since 11.3
  676.      */
  677.     public <T extends CalculusFieldElement<T>> T azimuthBetweenPoints(final FieldGeodeticPoint<T> origin, final FieldGeodeticPoint<T> destination) {
  678.         final T dLon = MathUtils.normalizeAngle(destination.getLongitude().subtract(origin.getLongitude()), origin.getLongitude().getField().getZero());
  679.         final T originIsoLat = geodeticToIsometricLatitude(origin.getLatitude());
  680.         final T destIsoLat = geodeticToIsometricLatitude(destination.getLatitude());

  681.         final T az = FastMath.atan2(dLon, destIsoLat.subtract(originIsoLat));
  682.         if (az.getReal() < 0.) {
  683.             return az.add(az.getPi().multiply(2));
  684.         }
  685.         return az;
  686.     }

  687.     /** Compute the <a href="https://mathworld.wolfram.com/IsometricLatitude.html">isometric latitude</a>
  688.      *  corresponding to the provided latitude.
  689.      *
  690.      * @param geodeticLatitude the latitude (radians, within interval {@code [-pi/2, +pi/2]})
  691.      * @return the isometric latitude (radians)
  692.      * @since 11.3
  693.      */
  694.     public double geodeticToIsometricLatitude(final double geodeticLatitude) {
  695.         if (FastMath.abs(geodeticLatitude) <= angularThreshold) {
  696.             return 0.;
  697.         }

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

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

  703.         return a + b;
  704.     }

  705.     /** Compute the <a href="https://mathworld.wolfram.com/IsometricLatitude.html">isometric latitude</a>
  706.      *  corresponding to the provided latitude.
  707.      *
  708.      * @param geodeticLatitude the latitude (radians, within interval {@code [-pi/2, +pi/2]})
  709.      * @param <T> the type of field elements
  710.      * @return the isometric latitude (radians)
  711.      * @since 11.3
  712.      */
  713.     public <T extends CalculusFieldElement<T>> T geodeticToIsometricLatitude(final T geodeticLatitude) {
  714.         if (geodeticLatitude.abs().getReal() <= angularThreshold) {
  715.             return geodeticLatitude.getField().getZero();
  716.         }
  717.         final Field<T> field = geodeticLatitude.getField();
  718.         final T ecc = geodeticLatitude.newInstance(e);
  719.         final T eSinLat = ecc.multiply(geodeticLatitude.sin());

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

  724.         return a.add(b);
  725.     }

  726.     /** Find intermediate point of lowest altitude along a line between two endpoints.
  727.      * @param endpoint1 first endpoint, in body frame
  728.      * @param endpoint2 second endpoint, in body frame
  729.      * @return point with lowest altitude between {@code endpoint1} and {@code endpoint2}.
  730.      * @since 12.0
  731.      */
  732.     public GeodeticPoint lowestAltitudeIntermediate(final Vector3D endpoint1, final Vector3D endpoint2) {

  733.         final Vector3D delta = endpoint2.subtract(endpoint1);

  734.         // function computing intermediate point above ellipsoid (lambda varying between 0 and 1)
  735.         final DoubleFunction<GeodeticPoint> intermediate =
  736.                         lambda -> transform(new Vector3D(1 - lambda, endpoint1, lambda, endpoint2),
  737.                                             getFrame(), null);

  738.         // first endpoint
  739.         final GeodeticPoint gp1 = intermediate.apply(0.0);

  740.         if (Vector3D.dotProduct(delta, gp1.getZenith()) >= 0) {
  741.             // the line from first endpoint to second endpoint is going away from central body
  742.             // the minimum altitude is reached at first endpoint
  743.             return gp1;
  744.         } else {
  745.             // the line from first endpoint to second endpoint is closing the central body

  746.             // second endpoint
  747.             final GeodeticPoint gp2 = intermediate.apply(1.0);

  748.             if (Vector3D.dotProduct(delta, gp2.getZenith()) <= 0) {
  749.                 // the line from first endpoint to second endpoint is still decreasing when reaching second endpoint,
  750.                 // the minimum altitude is reached at second endpoint
  751.                 return gp2;
  752.             } else {
  753.                 // the line from first endpoint to second endpoint reaches a minimum between first and second endpoints
  754.                 final double lambdaMin = new BracketingNthOrderBrentSolver(1.0e-14, 5).
  755.                                          solve(1000,
  756.                                                lambda -> Vector3D.dotProduct(delta, intermediate.apply(lambda).getZenith()),
  757.                                                0.0, 1.0);
  758.                 return intermediate.apply(lambdaMin);
  759.             }
  760.         }

  761.     }

  762.     /** Find intermediate point of lowest altitude along a line between two endpoints.
  763.      * @param endpoint1 first endpoint, in body frame
  764.      * @param endpoint2 second endpoint, in body frame
  765.      * @param <T> type of the field elements
  766.      * @return point with lowest altitude between {@code endpoint1} and {@code endpoint2}.
  767.      * @since 12.0
  768.      */
  769.     public <T extends CalculusFieldElement<T>> FieldGeodeticPoint<T> lowestAltitudeIntermediate(final FieldVector3D<T> endpoint1,
  770.                                                                                                 final FieldVector3D<T> endpoint2) {

  771.         final FieldVector3D<T> delta = endpoint2.subtract(endpoint1);

  772.         // function computing intermediate point above ellipsoid (lambda varying between 0 and 1)
  773.         final DoubleFunction<FieldGeodeticPoint<T>> intermediate =
  774.                         lambda -> transform(new FieldVector3D<>(1 - lambda, endpoint1, lambda, endpoint2),
  775.                                             getFrame(), null);

  776.         // first endpoint
  777.         final FieldGeodeticPoint<T> gp1 = intermediate.apply(0.0);

  778.         if (FieldVector3D.dotProduct(delta, gp1.getZenith()).getReal() >= 0) {
  779.             // the line from first endpoint to second endpoint is going away from central body
  780.             // the minimum altitude is reached at first endpoint
  781.             return gp1;
  782.         } else {
  783.             // the line from first endpoint to second endpoint is closing the central body

  784.             // second endpoint
  785.             final FieldGeodeticPoint<T> gp2 = intermediate.apply(1.0);

  786.             if (FieldVector3D.dotProduct(delta, gp2.getZenith()).getReal() <= 0) {
  787.                 // the line from first endpoint to second endpoint is still decreasing when reaching second endpoint,
  788.                 // the minimum altitude is reached at second endpoint
  789.                 return gp2;
  790.             } else {
  791.                 // the line from first endpoint to second endpoint reaches a minimum between first and second endpoints
  792.                 final double lambdaMin = new BracketingNthOrderBrentSolver(1.0e-14, 5).
  793.                                          solve(1000,
  794.                                                lambda -> FieldVector3D.dotProduct(delta, intermediate.apply(lambda).getZenith()).getReal(),
  795.                                                0.0, 1.0);
  796.                 return intermediate.apply(lambdaMin);
  797.             }
  798.         }

  799.     }

  800. }