OneAxisEllipsoid.java

  1. /* Copyright 2002-2018 CS Systèmes d'Information
  2.  * Licensed to CS Systèmes d'Information (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.RealFieldElement;
  20. import org.hipparchus.analysis.differentiation.DerivativeStructure;
  21. import org.hipparchus.geometry.euclidean.threed.FieldLine;
  22. import org.hipparchus.geometry.euclidean.threed.FieldVector3D;
  23. import org.hipparchus.geometry.euclidean.threed.Line;
  24. import org.hipparchus.geometry.euclidean.threed.Vector3D;
  25. import org.hipparchus.geometry.euclidean.twod.Vector2D;
  26. import org.hipparchus.util.FastMath;
  27. import org.hipparchus.util.MathArrays;
  28. import org.orekit.errors.OrekitException;
  29. import org.orekit.frames.FieldTransform;
  30. import org.orekit.frames.Frame;
  31. import org.orekit.frames.Transform;
  32. import org.orekit.time.AbsoluteDate;
  33. import org.orekit.time.FieldAbsoluteDate;
  34. import org.orekit.utils.PVCoordinates;
  35. import org.orekit.utils.TimeStampedPVCoordinates;


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

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

  41.  * @author Luc Maisonobe
  42.  */
  43. public class OneAxisEllipsoid extends Ellipsoid implements BodyShape {

  44.     /** Serializable UID. */
  45.     private static final long serialVersionUID = 20130518L;

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

  48.     /** Body frame related to body shape. */
  49.     private final Frame bodyFrame;

  50.     /** Equatorial radius power 2. */
  51.     private final double ae2;

  52.     /** Polar radius power 2. */
  53.     private final double ap2;

  54.     /** Flattening. */
  55.     private final double f;

  56.     /** Eccentricity power 2. */
  57.     private final double e2;

  58.     /** 1 minus flatness. */
  59.     private final double g;

  60.     /** g * g. */
  61.     private final double g2;

  62.     /** Convergence limit. */
  63.     private double angularThreshold;

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

  93.     /** Set the angular convergence threshold.
  94.      * <p>The angular threshold is used both to identify points close to
  95.      * the ellipse axes and as the convergence threshold used to
  96.      * stop the iterations in the {@link #transform(Vector3D, Frame,
  97.      * AbsoluteDate)} method.</p>
  98.      * <p>If this method is not called, the default value is set to
  99.      * 10<sup>-12</sup>.</p>
  100.      * @param angularThreshold angular convergence threshold (rad)
  101.      */
  102.     public void setAngularThreshold(final double angularThreshold) {
  103.         this.angularThreshold = angularThreshold;
  104.     }

  105.     /** Get the equatorial radius of the body.
  106.      * @return equatorial radius of the body (m)
  107.      */
  108.     public double getEquatorialRadius() {
  109.         return getA();
  110.     }

  111.     /** Get the flattening of the body: f = (a-b)/a.
  112.      * @return the flattening
  113.      */
  114.     public double getFlattening() {
  115.         return f;
  116.     }

  117.     /** {@inheritDoc} */
  118.     public Frame getBodyFrame() {
  119.         return bodyFrame;
  120.     }

  121.     /** {@inheritDoc} */
  122.     public GeodeticPoint getIntersectionPoint(final Line line, final Vector3D close,
  123.                                               final Frame frame, final AbsoluteDate date)
  124.         throws OrekitException {

  125.         // transform line and close to body frame
  126.         final Transform frameToBodyFrame = frame.getTransformTo(bodyFrame, date);
  127.         final Line lineInBodyFrame = frameToBodyFrame.transformLine(line);
  128.         final Vector3D closeInBodyFrame = frameToBodyFrame.transformPosition(close);
  129.         final double closeAbscissa = lineInBodyFrame.getAbscissa(closeInBodyFrame);

  130.         // compute some miscellaneous variables outside of the loop
  131.         final Vector3D point    = lineInBodyFrame.getOrigin();
  132.         final double x          = point.getX();
  133.         final double y          = point.getY();
  134.         final double z          = point.getZ();
  135.         final double z2         = z * z;
  136.         final double r2         = x * x + y * y;

  137.         final Vector3D direction = lineInBodyFrame.getDirection();
  138.         final double dx         = direction.getX();
  139.         final double dy         = direction.getY();
  140.         final double dz         = direction.getZ();
  141.         final double cz2        = dx * dx + dy * dy;

  142.         // abscissa of the intersection as a root of a 2nd degree polynomial :
  143.         // a k^2 - 2 b k + c = 0
  144.         final double a  = 1.0 - e2 * cz2;
  145.         final double b  = -(g2 * (x * dx + y * dy) + z * dz);
  146.         final double c  = g2 * (r2 - ae2) + z2;
  147.         final double b2 = b * b;
  148.         final double ac = a * c;
  149.         if (b2 < ac) {
  150.             return null;
  151.         }
  152.         final double s  = FastMath.sqrt(b2 - ac);
  153.         final double k1 = (b < 0) ? (b - s) / a : c / (b + s);
  154.         final double k2 = c / (a * k1);

  155.         // select the right point
  156.         final double k =
  157.             (FastMath.abs(k1 - closeAbscissa) < FastMath.abs(k2 - closeAbscissa)) ? k1 : k2;
  158.         final Vector3D intersection = lineInBodyFrame.pointAt(k);
  159.         final double ix = intersection.getX();
  160.         final double iy = intersection.getY();
  161.         final double iz = intersection.getZ();

  162.         final double lambda = FastMath.atan2(iy, ix);
  163.         final double phi    = FastMath.atan2(iz, g2 * FastMath.sqrt(ix * ix + iy * iy));
  164.         return new GeodeticPoint(phi, lambda, 0.0);

  165.     }

  166.     /** {@inheritDoc} */
  167.     public <T extends RealFieldElement<T>> FieldGeodeticPoint<T> getIntersectionPoint(final FieldLine<T> line,
  168.                                                                                       final FieldVector3D<T> close,
  169.                                                                                       final Frame frame,
  170.                                                                                       final FieldAbsoluteDate<T> date)
  171.         throws OrekitException {

  172.         // transform line and close to body frame
  173.         final FieldTransform<T> frameToBodyFrame = frame.getTransformTo(bodyFrame, date);
  174.         final FieldLine<T>      lineInBodyFrame  = frameToBodyFrame.transformLine(line);
  175.         final FieldVector3D<T>  closeInBodyFrame = frameToBodyFrame.transformPosition(close);
  176.         final T                 closeAbscissa    = lineInBodyFrame.getAbscissa(closeInBodyFrame);

  177.         // compute some miscellaneous variables outside of the loop
  178.         final FieldVector3D<T> point = lineInBodyFrame.getOrigin();
  179.         final T x  = point.getX();
  180.         final T y  = point.getY();
  181.         final T z  = point.getZ();
  182.         final T z2 = z.multiply(z);
  183.         final T r2 = x.multiply(x).add(y.multiply(y));

  184.         final FieldVector3D<T> direction = lineInBodyFrame.getDirection();
  185.         final T dx  = direction.getX();
  186.         final T dy  = direction.getY();
  187.         final T dz  = direction.getZ();
  188.         final T cz2 = dx.multiply(dx).add(dy.multiply(dy));

  189.         // abscissa of the intersection as a root of a 2nd degree polynomial :
  190.         // a k^2 - 2 b k + c = 0
  191.         final T a  = cz2.multiply(e2).subtract(1.0).negate();
  192.         final T b  = x.multiply(dx).add(y.multiply(dy)).multiply(g2).add(z.multiply(dz)).negate();
  193.         final T c  = r2.subtract(ae2).multiply(g2).add(z2);
  194.         final T b2 = b.multiply(b);
  195.         final T ac = a.multiply(c);
  196.         if (b2.getReal() < ac.getReal()) {
  197.             return null;
  198.         }
  199.         final T s  = b2.subtract(ac).sqrt();
  200.         final T k1 = (b.getReal() < 0) ? b.subtract(s).divide(a) : c.divide(b.add(s));
  201.         final T k2 = c.divide(a.multiply(k1));

  202.         // select the right point
  203.         final T k = (FastMath.abs(k1.getReal() - closeAbscissa.getReal()) < FastMath.abs(k2.getReal() - closeAbscissa.getReal())) ?
  204.                     k1 : k2;
  205.         final FieldVector3D<T> intersection = lineInBodyFrame.pointAt(k);
  206.         final T ix = intersection.getX();
  207.         final T iy = intersection.getY();
  208.         final T iz = intersection.getZ();

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

  212.     }

  213.     /** {@inheritDoc} */
  214.     public Vector3D transform(final GeodeticPoint point) {
  215.         final double longitude = point.getLongitude();
  216.         final double cLambda   = FastMath.cos(longitude);
  217.         final double sLambda   = FastMath.sin(longitude);
  218.         final double latitude  = point.getLatitude();
  219.         final double cPhi      = FastMath.cos(latitude);
  220.         final double sPhi      = FastMath.sin(latitude);
  221.         final double h         = point.getAltitude();
  222.         final double n         = getA() / FastMath.sqrt(1.0 - e2 * sPhi * sPhi);
  223.         final double r         = (n + h) * cPhi;
  224.         return new Vector3D(r * cLambda, r * sLambda, (g2 * n + h) * sPhi);
  225.     }

  226.     /** {@inheritDoc} */
  227.     public <T extends RealFieldElement<T>> FieldVector3D<T> transform(final FieldGeodeticPoint<T> point) {

  228.         final T latitude  = point.getLatitude();
  229.         final T longitude = point.getLongitude();
  230.         final T altitude  = point.getAltitude();

  231.         final T cLambda = longitude.cos();
  232.         final T sLambda = longitude.sin();
  233.         final T cPhi    = latitude.cos();
  234.         final T sPhi    = latitude.sin();
  235.         final T n       = sPhi.multiply(sPhi).multiply(e2).subtract(1.0).negate().sqrt().reciprocal().multiply(getA());
  236.         final T r       = n.add(altitude).multiply(cPhi);

  237.         return new FieldVector3D<>(r.multiply(cLambda),
  238.                                    r.multiply(sLambda),
  239.                                    sPhi.multiply(altitude.add(n.multiply(g2))));
  240.     }

  241.     /** {@inheritDoc} */
  242.     public Vector3D projectToGround(final Vector3D point, final AbsoluteDate date, final Frame frame)
  243.         throws OrekitException {

  244.         // transform point to body frame
  245.         final Transform  toBody    = frame.getTransformTo(bodyFrame, date);
  246.         final Vector3D   p         = toBody.transformPosition(point);
  247.         final double     z         = p.getZ();
  248.         final double     r         = FastMath.hypot(p.getX(), p.getY());

  249.         // set up the 2D meridian ellipse
  250.         final Ellipse meridian = new Ellipse(Vector3D.ZERO,
  251.                                              new Vector3D(p.getX() / r, p.getY() / r, 0),
  252.                                              Vector3D.PLUS_K,
  253.                                              getA(), getC(), bodyFrame);

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

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

  258.     }

  259.     /** {@inheritDoc} */
  260.     public TimeStampedPVCoordinates projectToGround(final TimeStampedPVCoordinates pv, final Frame frame)
  261.         throws OrekitException {

  262.         // transform point to body frame
  263.         final Transform                toBody        = frame.getTransformTo(bodyFrame, pv.getDate());
  264.         final TimeStampedPVCoordinates pvInBodyFrame = toBody.transformPVCoordinates(pv);
  265.         final Vector3D                 p             = pvInBodyFrame.getPosition();
  266.         final double                   r             = FastMath.hypot(p.getX(), p.getY());

  267.         // set up the 2D ellipse corresponding to first principal curvature along meridian
  268.         final Vector3D meridian = new Vector3D(p.getX() / r, p.getY() / r, 0);
  269.         final Ellipse firstPrincipalCurvature =
  270.                 new Ellipse(Vector3D.ZERO, meridian, Vector3D.PLUS_K, getA(), getC(), bodyFrame);

  271.         // project coordinates in the meridian plane
  272.         final TimeStampedPVCoordinates gpFirst = firstPrincipalCurvature.projectToEllipse(pvInBodyFrame);
  273.         final Vector3D                 gpP     = gpFirst.getPosition();
  274.         final double                   gr      = MathArrays.linearCombination(gpP.getX(), meridian.getX(),
  275.                                                                               gpP.getY(), meridian.getY());
  276.         final double                   gz      = gpP.getZ();

  277.         // topocentric frame
  278.         final Vector3D east   = new Vector3D(-meridian.getY(), meridian.getX(), 0);
  279.         final Vector3D zenith = new Vector3D(gr * getC() / getA(), meridian, gz * getA() / getC(), Vector3D.PLUS_K).normalize();
  280.         final Vector3D north  = Vector3D.crossProduct(zenith, east);

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

  284.         final Vector3D gpV = gpFirst.getVelocity().add(gpSecond.getVelocity());
  285.         final Vector3D gpA = gpFirst.getAcceleration().add(gpSecond.getAcceleration());

  286.         // moving projected point
  287.         final TimeStampedPVCoordinates groundPV =
  288.                 new TimeStampedPVCoordinates(pv.getDate(), gpP, gpV, gpA);

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

  291.     }

  292.     /** {@inheritDoc}
  293.      * <p>
  294.      * This method is based on Toshio Fukushima's algorithm which uses Halley's method.
  295.      * <a href="https://www.researchgate.net/publication/227215135_Transformation_from_Cartesian_to_Geodetic_Coordinates_Accelerated_by_Halley's_Method">
  296.      * transformation from Cartesian to Geodetic Coordinates Accelerated by Halley's Method</a>,
  297.      * Toshio Fukushima, Journal of Geodesy 9(12):689-693, February 2006
  298.      * </p>
  299.      * <p>
  300.      * Some changes have been added to the original method:
  301.      * <ul>
  302.      *   <li>in order to handle more accurately corner cases near the pole</li>
  303.      *   <li>in order to handle properly corner cases near the equatorial plane, even far inside the ellipsoid</li>
  304.      *   <li>in order to handle very flat ellipsoids</li>
  305.      * </ul>
  306.      * </p>
  307.      */
  308.     public GeodeticPoint transform(final Vector3D point, final Frame frame, final AbsoluteDate date)
  309.         throws OrekitException {

  310.         // transform point to body frame
  311.         final Vector3D pointInBodyFrame = frame.getTransformTo(bodyFrame, date).transformPosition(point);
  312.         final double   r2               = pointInBodyFrame.getX() * pointInBodyFrame.getX() +
  313.                                           pointInBodyFrame.getY() * pointInBodyFrame.getY();
  314.         final double   r                = FastMath.sqrt(r2);
  315.         final double   z                = pointInBodyFrame.getZ();

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

  317.         double h;
  318.         double phi;
  319.         if (r <= ANGULAR_THRESHOLD * FastMath.abs(z)) {
  320.             // the point is almost on the polar axis, approximate the ellipsoid with
  321.             // the osculating sphere whose center is at evolute cusp along polar axis
  322.             final double osculatingRadius = ae2 / getC();
  323.             final double evoluteCuspZ     = FastMath.copySign(getA() * e2 / g, -z);
  324.             final double deltaZ           = z - evoluteCuspZ;
  325.             // we use π/2 - atan(r/Δz) instead of atan(Δz/r) for accuracy purposes, as r is much smaller than Δz
  326.             phi = FastMath.copySign(0.5 * FastMath.PI - FastMath.atan(r / FastMath.abs(deltaZ)), deltaZ);
  327.             h   = FastMath.hypot(deltaZ, r) - osculatingRadius;
  328.         } else if (FastMath.abs(z) <= ANGULAR_THRESHOLD * r) {
  329.             // the point is almost on the major axis

  330.             final double osculatingRadius = ap2 / getA();
  331.             final double evoluteCuspR     = getA() * e2;
  332.             final double deltaR           = r - evoluteCuspR;
  333.             if (deltaR >= 0) {
  334.                 // the point is outside of the ellipse evolute, approximate the ellipse
  335.                 // with the osculating circle whose center is at evolute cusp along major axis
  336.                 phi = (deltaR == 0) ? 0.0 : FastMath.atan(z / deltaR);
  337.                 h   = FastMath.hypot(deltaR, z) - osculatingRadius;
  338.             } else {
  339.                 // the point is on the part of the major axis within ellipse evolute
  340.                 // we can compute the closest ellipse point analytically, and it is NOT near the equator
  341.                 final double rClose = r / e2;
  342.                 final double zClose = FastMath.copySign(g * FastMath.sqrt(ae2 - rClose * rClose), z);
  343.                 phi = FastMath.atan((zClose - z) / (rClose - r));
  344.                 h   = -FastMath.hypot(r - rClose, z - zClose);
  345.             }

  346.         } else {
  347.             // use Toshio Fukushima method, with several iterations
  348.             final double epsPhi = 1.0e-15;
  349.             final double epsH   = 1.0e-14 * FastMath.max(getA(), FastMath.sqrt(r2 + z * z));
  350.             final double c     = getA() * e2;
  351.             final double absZ  = FastMath.abs(z);
  352.             final double zc    = g * absZ;
  353.             double sn  = absZ;
  354.             double sn2 = sn * sn;
  355.             double cn  = g * r;
  356.             double cn2 = cn * cn;
  357.             double an2 = cn2 + sn2;
  358.             double an  = FastMath.sqrt(an2);
  359.             double bn  = 0;
  360.             phi = Double.POSITIVE_INFINITY;
  361.             h   = Double.POSITIVE_INFINITY;
  362.             for (int i = 0; i < 10; ++i) { // this usually converges in 2 iterations
  363.                 final double oldSn  = sn;
  364.                 final double oldCn  = cn;
  365.                 final double oldPhi = phi;
  366.                 final double oldH   = h;
  367.                 final double an3    = an2 * an;
  368.                 final double csncn  = c * sn * cn;
  369.                 bn    = 1.5 * csncn * ((r * sn - zc * cn) * an - csncn);
  370.                 sn    = (zc * an3 + c * sn2 * sn) * an3 - bn * sn;
  371.                 cn    = (r  * an3 - c * cn2 * cn) * an3 - bn * cn;
  372.                 if (sn * oldSn < 0 || cn < 0) {
  373.                     // the Halley iteration went too far, we restrict it and iterate again
  374.                     while (sn * oldSn < 0 || cn < 0) {
  375.                         sn = (sn + oldSn) / 2;
  376.                         cn = (cn + oldCn) / 2;
  377.                     }
  378.                 } else {

  379.                     // rescale components to avoid overflow when several iterations are used
  380.                     final int exp = (FastMath.getExponent(sn) + FastMath.getExponent(cn)) / 2;
  381.                     sn = FastMath.scalb(sn, -exp);
  382.                     cn = FastMath.scalb(cn, -exp);

  383.                     sn2 = sn * sn;
  384.                     cn2 = cn * cn;
  385.                     an2 = cn2 + sn2;
  386.                     an  = FastMath.sqrt(an2);

  387.                     final double cc = g * cn;
  388.                     h = (r * cc + absZ * sn - getA() * g * an) / FastMath.sqrt(an2 - e2 * cn2);
  389.                     if (FastMath.abs(oldH   - h)   < epsH) {
  390.                         phi = FastMath.copySign(FastMath.atan(sn / cc), z);
  391.                         if (FastMath.abs(oldPhi - phi) < epsPhi) {
  392.                             break;
  393.                         }
  394.                     }

  395.                 }

  396.             }
  397.         }

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

  399.     }

  400.     /** {@inheritDoc}
  401.      * <p>
  402.      * This method is based on Toshio Fukushima's algorithm which uses Halley's method.
  403.      * <a href="https://www.researchgate.net/publication/227215135_Transformation_from_Cartesian_to_Geodetic_Coordinates_Accelerated_by_Halley's_Method">
  404.      * transformation from Cartesian to Geodetic Coordinates Accelerated by Halley's Method</a>,
  405.      * Toshio Fukushima, Journal of Geodesy 9(12):689-693, February 2006
  406.      * </p>
  407.      * <p>
  408.      * Some changes have been added to the original method:
  409.      * <ul>
  410.      *   <li>in order to handle more accurately corner cases near the pole</li>
  411.      *   <li>in order to handle properly corner cases near the equatorial plane, even far inside the ellipsoid</li>
  412.      *   <li>in order to handle very flat ellipsoids</li>
  413.      * </ul>
  414.      * </p>
  415.      */
  416.     public <T extends RealFieldElement<T>> FieldGeodeticPoint<T> transform(final FieldVector3D<T> point,
  417.                                                                            final Frame frame,
  418.                                                                            final FieldAbsoluteDate<T> date)
  419.         throws OrekitException {

  420.         // transform point to body frame
  421.         final FieldVector3D<T> pointInBodyFrame = frame.getTransformTo(bodyFrame, date).transformPosition(point);
  422.         final T   r2                            = pointInBodyFrame.getX().multiply(pointInBodyFrame.getX()).
  423.                                               add(pointInBodyFrame.getY().multiply(pointInBodyFrame.getY()));
  424.         final T   r                             = r2.sqrt();
  425.         final T   z                             = pointInBodyFrame.getZ();

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

  427.         T h;
  428.         T phi;
  429.         if (r.getReal() <= ANGULAR_THRESHOLD * FastMath.abs(z.getReal())) {
  430.             // the point is almost on the polar axis, approximate the ellipsoid with
  431.             // the osculating sphere whose center is at evolute cusp along polar axis
  432.             final double osculatingRadius = ae2 / getC();
  433.             final double evoluteCuspZ     = FastMath.copySign(getA() * e2 / g, -z.getReal());
  434.             final T      deltaZ           = z.subtract(evoluteCuspZ);
  435.             // we use π/2 - atan(r/Δz) instead of atan(Δz/r) for accuracy purposes, as r is much smaller than Δz
  436.             phi = r.divide(deltaZ.abs()).atan().negate().add(0.5 * FastMath.PI).copySign(deltaZ);
  437.             h   = deltaZ.hypot(r).subtract(osculatingRadius);
  438.         } else if (FastMath.abs(z.getReal()) <= ANGULAR_THRESHOLD * r.getReal()) {
  439.             // the point is almost on the major axis

  440.             final double osculatingRadius = ap2 / getA();
  441.             final double evoluteCuspR     = getA() * e2;
  442.             final T      deltaR           = r.subtract(evoluteCuspR);
  443.             if (deltaR.getReal() >= 0) {
  444.                 // the point is outside of the ellipse evolute, approximate the ellipse
  445.                 // with the osculating circle whose center is at evolute cusp along major axis
  446.                 phi = (deltaR.getReal() == 0) ? z.getField().getZero() : z.divide(deltaR).atan();
  447.                 h   = deltaR.hypot(z).subtract(osculatingRadius);
  448.             } else {
  449.                 // the point is on the part of the major axis within ellipse evolute
  450.                 // we can compute the closest ellipse point analytically, and it is NOT near the equator
  451.                 final T rClose = r.divide(e2);
  452.                 final T zClose = rClose.multiply(rClose).negate().add(ae2).sqrt().multiply(g).copySign(z);
  453.                 phi = zClose.subtract(z).divide(rClose.subtract(r)).atan();
  454.                 h   = r.subtract(rClose).hypot(z.subtract(zClose)).negate();
  455.             }

  456.         } else {
  457.             // use Toshio Fukushima method, with several iterations
  458.             final double epsPhi = 1.0e-15;
  459.             final double epsH   = 1.0e-14 * getA();
  460.             final double c      = getA() * e2;
  461.             final T      absZ   = z.abs();
  462.             final T      zc     = absZ.multiply(g);
  463.             T            sn     = absZ;
  464.             T            sn2    = sn.multiply(sn);
  465.             T            cn     = r.multiply(g);
  466.             T            cn2    = cn.multiply(cn);
  467.             T            an2    = cn2.add(sn2);
  468.             T            an     = an2.sqrt();
  469.             T            bn     = an.getField().getZero();
  470.             phi = an.getField().getZero().add(Double.POSITIVE_INFINITY);
  471.             h   = an.getField().getZero().add(Double.POSITIVE_INFINITY);
  472.             for (int i = 0; i < 10; ++i) { // this usually converges in 2 iterations
  473.                 final T oldSn  = sn;
  474.                 final T oldCn  = cn;
  475.                 final T oldPhi = phi;
  476.                 final T oldH   = h;
  477.                 final T an3    = an2.multiply(an);
  478.                 final T csncn  = sn.multiply(cn).multiply(c);
  479.                 bn    = csncn.multiply(1.5).multiply((r.multiply(sn).subtract(zc.multiply(cn))).multiply(an).subtract(csncn));
  480.                 sn    = zc.multiply(an3).add(sn2.multiply(sn).multiply(c)).multiply(an3).subtract(bn.multiply(sn));
  481.                 cn    = r.multiply(an3).subtract(cn2.multiply(cn).multiply(c)).multiply(an3).subtract(bn.multiply(cn));
  482.                 if (sn.getReal() * oldSn.getReal() < 0 || cn.getReal() < 0) {
  483.                     // the Halley iteration went too far, we restrict it and iterate again
  484.                     while (sn.getReal() * oldSn.getReal() < 0 || cn.getReal() < 0) {
  485.                         sn = sn.add(oldSn).multiply(0.5);
  486.                         cn = cn.add(oldCn).multiply(0.5);
  487.                     }
  488.                 } else {

  489.                     // rescale components to avoid overflow when several iterations are used
  490.                     final int exp = (FastMath.getExponent(sn.getReal()) + FastMath.getExponent(cn.getReal())) / 2;
  491.                     sn = sn.scalb(-exp);
  492.                     cn = cn.scalb(-exp);

  493.                     sn2 = sn.multiply(sn);
  494.                     cn2 = cn.multiply(cn);
  495.                     an2 = cn2.add(sn2);
  496.                     an  = an2.sqrt();

  497.                     final T cc = cn.multiply(g);
  498.                     h = r.multiply(cc).add(absZ.multiply(sn)).subtract(an.multiply(getA() * g)).divide(an2.subtract(cn2.multiply(e2)).sqrt());
  499.                     if (FastMath.abs(oldH.getReal()  - h.getReal())   < epsH) {
  500.                         phi = sn.divide(cc).atan().copySign(z);
  501.                         if (FastMath.abs(oldPhi.getReal() - phi.getReal()) < epsPhi) {
  502.                             break;
  503.                         }
  504.                     }

  505.                 }

  506.             }
  507.         }

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

  509.     }

  510.     /** Transform a Cartesian point to a surface-relative point.
  511.      * @param point Cartesian point
  512.      * @param frame frame in which Cartesian point is expressed
  513.      * @param date date of the computation (used for frames conversions)
  514.      * @return point at the same location but as a surface-relative point,
  515.      * using time as the single derivation parameter
  516.      * @exception OrekitException if point cannot be converted to body frame
  517.      */
  518.     public FieldGeodeticPoint<DerivativeStructure> transform(final PVCoordinates point,
  519.                                                              final Frame frame, final AbsoluteDate date)
  520.         throws OrekitException {

  521.         // transform point to body frame
  522.         final Transform toBody = frame.getTransformTo(bodyFrame, date);
  523.         final PVCoordinates pointInBodyFrame = toBody.transformPVCoordinates(point);
  524.         final FieldVector3D<DerivativeStructure> p = pointInBodyFrame.toDerivativeStructureVector(2);
  525.         final DerivativeStructure   pr2 = p.getX().multiply(p.getX()).add(p.getY().multiply(p.getY()));
  526.         final DerivativeStructure   pr  = pr2.sqrt();
  527.         final DerivativeStructure   pz  = p.getZ();

  528.         // project point on the ellipsoid surface
  529.         final TimeStampedPVCoordinates groundPoint = projectToGround(new TimeStampedPVCoordinates(date, pointInBodyFrame),
  530.                                                                      bodyFrame);
  531.         final FieldVector3D<DerivativeStructure> gp = groundPoint.toDerivativeStructureVector(2);
  532.         final DerivativeStructure   gpr2 = gp.getX().multiply(gp.getX()).add(gp.getY().multiply(gp.getY()));
  533.         final DerivativeStructure   gpr  = gpr2.sqrt();
  534.         final DerivativeStructure   gpz  = gp.getZ();

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

  539.         return new FieldGeodeticPoint<>(DerivativeStructure.atan2(gpz, gpr.multiply(g2)),
  540.                                                                   DerivativeStructure.atan2(p.getY(), p.getX()),
  541.                                                                   DerivativeStructure.hypot(dr, dz).copySign(insideIfNegative));
  542.     }

  543.     /** Replace the instance with a data transfer object for serialization.
  544.      * <p>
  545.      * This intermediate class serializes the files supported names, the
  546.      * ephemeris type and the body name.
  547.      * </p>
  548.      * @return data transfer object that will be serialized
  549.      */
  550.     private Object writeReplace() {
  551.         return new DataTransferObject(getA(), f, bodyFrame, angularThreshold);
  552.     }

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

  555.         /** Serializable UID. */
  556.         private static final long serialVersionUID = 20130518L;

  557.         /** Equatorial radius. */
  558.         private final double ae;

  559.         /** Flattening. */
  560.         private final double f;

  561.         /** Body frame related to body shape. */
  562.         private final Frame bodyFrame;

  563.         /** Convergence limit. */
  564.         private final double angularThreshold;

  565.         /** Simple constructor.
  566.          * @param ae equatorial radius
  567.          * @param f the flattening (f = (a-b)/a)
  568.          * @param bodyFrame body frame related to body shape
  569.          * @param angularThreshold convergence limit
  570.          */
  571.         DataTransferObject(final double ae, final double f,
  572.                                   final Frame bodyFrame, final double angularThreshold) {
  573.             this.ae               = ae;
  574.             this.f                = f;
  575.             this.bodyFrame        = bodyFrame;
  576.             this.angularThreshold = angularThreshold;
  577.         }

  578.         /** Replace the deserialized data transfer object with a
  579.          * {@link JPLCelestialBody}.
  580.          * @return replacement {@link JPLCelestialBody}
  581.          */
  582.         private Object readResolve() {
  583.             final OneAxisEllipsoid ellipsoid = new OneAxisEllipsoid(ae, f, bodyFrame);
  584.             ellipsoid.setAngularThreshold(angularThreshold);
  585.             return ellipsoid;
  586.         }

  587.     }

  588. }