1   /* Copyright 2002-2021 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  
19  import java.io.Serializable;
20  
21  import org.hipparchus.CalculusFieldElement;
22  import org.hipparchus.analysis.differentiation.DerivativeStructure;
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.SinCos;
32  import org.orekit.frames.FieldTransform;
33  import org.orekit.frames.Frame;
34  import org.orekit.frames.Transform;
35  import org.orekit.time.AbsoluteDate;
36  import org.orekit.time.FieldAbsoluteDate;
37  import org.orekit.utils.PVCoordinates;
38  import org.orekit.utils.TimeStampedPVCoordinates;
39  
40  
41  /** Modeling of a one-axis ellipsoid.
42  
43   * <p>One-axis ellipsoids is a good approximate model for most planet-size
44   * and larger natural bodies. It is the equilibrium shape reached by
45   * a fluid body under its own gravity field when it rotates. The symmetry
46   * axis is the rotation or polar axis.</p>
47  
48   * @author Luc Maisonobe
49   * @author Guylaine Prat
50   */
51  public class OneAxisEllipsoid extends Ellipsoid implements BodyShape {
52  
53      /** Serializable UID. */
54      private static final long serialVersionUID = 20130518L;
55  
56      /** Threshold for polar and equatorial points detection. */
57      private static final double ANGULAR_THRESHOLD = 1.0e-4;
58  
59      /** Body frame related to body shape. */
60      private final Frame bodyFrame;
61  
62      /** Equatorial radius power 2. */
63      private final double ae2;
64  
65      /** Polar radius power 2. */
66      private final double ap2;
67  
68      /** Flattening. */
69      private final double f;
70  
71      /** Eccentricity power 2. */
72      private final double e2;
73  
74      /** 1 minus flatness. */
75      private final double g;
76  
77      /** g * g. */
78      private final double g2;
79  
80      /** Convergence limit. */
81      private double angularThreshold;
82  
83      /** Simple constructor.
84       * <p>Standard values for Earth models can be found in the {@link org.orekit.utils.Constants Constants} class:</p>
85       * <table border="1" style="background-color:#f5f5dc;">
86       * <caption>Ellipsoid Models</caption>
87       * <tr style="background-color:#c9d5c9;"><th>model</th><th>a<sub>e</sub> (m)</th> <th>f</th></tr>
88       * <tr><td style="background-color:#c9d5c9; padding:5px">GRS 80</td>
89       *     <td>{@link org.orekit.utils.Constants#GRS80_EARTH_EQUATORIAL_RADIUS Constants.GRS80_EARTH_EQUATORIAL_RADIUS}</td>
90       *     <td>{@link org.orekit.utils.Constants#GRS80_EARTH_FLATTENING Constants.GRS80_EARTH_FLATTENING}</td></tr>
91       * <tr><td style="background-color:#c9d5c9; padding:5px">WGS84</td>
92       *     <td>{@link org.orekit.utils.Constants#WGS84_EARTH_EQUATORIAL_RADIUS Constants.WGS84_EARTH_EQUATORIAL_RADIUS}</td>
93       *     <td>{@link org.orekit.utils.Constants#WGS84_EARTH_FLATTENING Constants.WGS84_EARTH_FLATTENING}</td></tr>
94       * <tr><td style="background-color:#c9d5c9; padding:5px">IERS96</td>
95       *     <td>{@link org.orekit.utils.Constants#IERS96_EARTH_EQUATORIAL_RADIUS Constants.IERS96_EARTH_EQUATORIAL_RADIUS}</td>
96       *     <td>{@link org.orekit.utils.Constants#IERS96_EARTH_FLATTENING Constants.IERS96_EARTH_FLATTENING}</td></tr>
97       * <tr><td style="background-color:#c9d5c9; padding:5px">IERS2003</td>
98       *     <td>{@link org.orekit.utils.Constants#IERS2003_EARTH_EQUATORIAL_RADIUS Constants.IERS2003_EARTH_EQUATORIAL_RADIUS}</td>
99       *     <td>{@link org.orekit.utils.Constants#IERS2003_EARTH_FLATTENING Constants.IERS2003_EARTH_FLATTENING}</td></tr>
100      * <tr><td style="background-color:#c9d5c9; padding:5px">IERS2010</td>
101      *     <td>{@link org.orekit.utils.Constants#IERS2010_EARTH_EQUATORIAL_RADIUS Constants.IERS2010_EARTH_EQUATORIAL_RADIUS}</td>
102      *     <td>{@link org.orekit.utils.Constants#IERS2010_EARTH_FLATTENING Constants.IERS2010_EARTH_FLATTENING}</td></tr>
103      * </table>
104      * @param ae equatorial radius
105      * @param f the flattening (f = (a-b)/a)
106      * @param bodyFrame body frame related to body shape
107      * @see org.orekit.frames.FramesFactory#getITRF(org.orekit.utils.IERSConventions, boolean)
108      */
109     public OneAxisEllipsoid(final double ae, final double f,
110                             final Frame bodyFrame) {
111         super(bodyFrame, ae, ae, ae * (1.0 - f));
112         this.f    = f;
113         this.ae2  = ae * ae;
114         this.e2   = f * (2.0 - f);
115         this.g    = 1.0 - f;
116         this.g2   = g * g;
117         this.ap2  = ae2 * g2;
118         setAngularThreshold(1.0e-12);
119         this.bodyFrame = bodyFrame;
120     }
121 
122     /** Set the angular convergence threshold.
123      * <p>The angular threshold is used both to identify points close to
124      * the ellipse axes and as the convergence threshold used to
125      * stop the iterations in the {@link #transform(Vector3D, Frame,
126      * AbsoluteDate)} method.</p>
127      * <p>If this method is not called, the default value is set to
128      * 10<sup>-12</sup>.</p>
129      * @param angularThreshold angular convergence threshold (rad)
130      */
131     public void setAngularThreshold(final double angularThreshold) {
132         this.angularThreshold = angularThreshold;
133     }
134 
135     /** Get the equatorial radius of the body.
136      * @return equatorial radius of the body (m)
137      */
138     public double getEquatorialRadius() {
139         return getA();
140     }
141 
142     /** Get the flattening of the body: f = (a-b)/a.
143      * @return the flattening
144      */
145     public double getFlattening() {
146         return f;
147     }
148 
149     /** {@inheritDoc} */
150     public Frame getBodyFrame() {
151         return bodyFrame;
152     }
153 
154     /** Get the intersection point of a line with the surface of the body.
155      * <p>A line may have several intersection points with a closed
156      * surface (we consider the one point case as a degenerated two
157      * points case). The close parameter is used to select which of
158      * these points should be returned. The selected point is the one
159      * that is closest to the close point.</p>
160      * @param line test line (may intersect the body or not)
161      * @param close point used for intersections selection
162      * @param frame frame in which line is expressed
163      * @param date date of the line in given frame
164      * @return intersection point at altitude zero or null if the line does
165      * not intersect the surface
166      * @since 9.3
167      */
168     public Vector3D getCartesianIntersectionPoint(final Line line, final Vector3D close,
169                                                   final Frame frame, final AbsoluteDate date) {
170 
171         // transform line and close to body frame
172         final Transform frameToBodyFrame = frame.getTransformTo(bodyFrame, date);
173         final Line lineInBodyFrame = frameToBodyFrame.transformLine(line);
174 
175         // compute some miscellaneous variables
176         final Vector3D point    = lineInBodyFrame.getOrigin();
177         final double x          = point.getX();
178         final double y          = point.getY();
179         final double z          = point.getZ();
180         final double z2         = z * z;
181         final double r2         = x * x + y * y;
182 
183         final Vector3D direction = lineInBodyFrame.getDirection();
184         final double dx         = direction.getX();
185         final double dy         = direction.getY();
186         final double dz         = direction.getZ();
187         final double cz2        = dx * dx + dy * dy;
188 
189         // abscissa of the intersection as a root of a 2nd degree polynomial :
190         // a k^2 - 2 b k + c = 0
191         final double a  = 1.0 - e2 * cz2;
192         final double b  = -(g2 * (x * dx + y * dy) + z * dz);
193         final double c  = g2 * (r2 - ae2) + z2;
194         final double b2 = b * b;
195         final double ac = a * c;
196         if (b2 < ac) {
197             return null;
198         }
199         final double s  = FastMath.sqrt(b2 - ac);
200         final double k1 = (b < 0) ? (b - s) / a : c / (b + s);
201         final double k2 = c / (a * k1);
202 
203         // select the right point
204         final Vector3D closeInBodyFrame = frameToBodyFrame.transformPosition(close);
205         final double   closeAbscissa    = lineInBodyFrame.getAbscissa(closeInBodyFrame);
206         final double k =
207             (FastMath.abs(k1 - closeAbscissa) < FastMath.abs(k2 - closeAbscissa)) ? k1 : k2;
208         return lineInBodyFrame.pointAt(k);
209 
210     }
211 
212     /** {@inheritDoc} */
213     public GeodeticPoint getIntersectionPoint(final Line line, final Vector3D close,
214                                               final Frame frame, final AbsoluteDate date) {
215 
216         final Vector3D intersection = getCartesianIntersectionPoint(line, close, frame, date);
217         if (intersection == null) {
218             return null;
219         }
220         final double ix = intersection.getX();
221         final double iy = intersection.getY();
222         final double iz = intersection.getZ();
223 
224         final double lambda = FastMath.atan2(iy, ix);
225         final double phi    = FastMath.atan2(iz, g2 * FastMath.sqrt(ix * ix + iy * iy));
226         return new GeodeticPoint(phi, lambda, 0.0);
227 
228     }
229 
230     /** Get the intersection point of a line with the surface of the body.
231      * <p>A line may have several intersection points with a closed
232      * surface (we consider the one point case as a degenerated two
233      * points case). The close parameter is used to select which of
234      * these points should be returned. The selected point is the one
235      * that is closest to the close point.</p>
236      * @param line test line (may intersect the body or not)
237      * @param close point used for intersections selection
238      * @param frame frame in which line is expressed
239      * @param date date of the line in given frame
240      * @param <T> type of the field elements
241      * @return intersection point at altitude zero or null if the line does
242      * not intersect the surface
243      * @since 9.3
244      */
245     public <T extends CalculusFieldElement<T>> FieldVector3D<T> getCartesianIntersectionPoint(final FieldLine<T> line,
246                                                                                           final FieldVector3D<T> close,
247                                                                                           final Frame frame,
248                                                                                           final FieldAbsoluteDate<T> date) {
249 
250         // transform line and close to body frame
251         final FieldTransform<T> frameToBodyFrame = frame.getTransformTo(bodyFrame, date);
252         final FieldLine<T>      lineInBodyFrame  = frameToBodyFrame.transformLine(line);
253 
254         // compute some miscellaneous variables
255         final FieldVector3D<T> point = lineInBodyFrame.getOrigin();
256         final T x  = point.getX();
257         final T y  = point.getY();
258         final T z  = point.getZ();
259         final T z2 = z.multiply(z);
260         final T r2 = x.multiply(x).add(y.multiply(y));
261 
262         final FieldVector3D<T> direction = lineInBodyFrame.getDirection();
263         final T dx  = direction.getX();
264         final T dy  = direction.getY();
265         final T dz  = direction.getZ();
266         final T cz2 = dx.multiply(dx).add(dy.multiply(dy));
267 
268         // abscissa of the intersection as a root of a 2nd degree polynomial :
269         // a k^2 - 2 b k + c = 0
270         final T a  = cz2.multiply(e2).subtract(1.0).negate();
271         final T b  = x.multiply(dx).add(y.multiply(dy)).multiply(g2).add(z.multiply(dz)).negate();
272         final T c  = r2.subtract(ae2).multiply(g2).add(z2);
273         final T b2 = b.multiply(b);
274         final T ac = a.multiply(c);
275         if (b2.getReal() < ac.getReal()) {
276             return null;
277         }
278         final T s  = b2.subtract(ac).sqrt();
279         final T k1 = (b.getReal() < 0) ? b.subtract(s).divide(a) : c.divide(b.add(s));
280         final T k2 = c.divide(a.multiply(k1));
281 
282         // select the right point
283         final FieldVector3D<T>  closeInBodyFrame = frameToBodyFrame.transformPosition(close);
284         final T                 closeAbscissa    = lineInBodyFrame.getAbscissa(closeInBodyFrame);
285         final T k = (FastMath.abs(k1.getReal() - closeAbscissa.getReal()) < FastMath.abs(k2.getReal() - closeAbscissa.getReal())) ?
286                     k1 : k2;
287         return lineInBodyFrame.pointAt(k);
288     }
289 
290     /** {@inheritDoc} */
291     public <T extends CalculusFieldElement<T>> FieldGeodeticPoint<T> getIntersectionPoint(final FieldLine<T> line,
292                                                                                       final FieldVector3D<T> close,
293                                                                                       final Frame frame,
294                                                                                       final FieldAbsoluteDate<T> date) {
295 
296         final FieldVector3D<T> intersection = getCartesianIntersectionPoint(line, close, frame, date);
297         if (intersection == null) {
298             return null;
299         }
300         final T ix = intersection.getX();
301         final T iy = intersection.getY();
302         final T iz = intersection.getZ();
303 
304         final T lambda = iy.atan2(ix);
305         final T phi    = iz.atan2(ix.multiply(ix).add(iy.multiply(iy)).sqrt().multiply(g2));
306         return new FieldGeodeticPoint<>(phi, lambda, phi.getField().getZero());
307 
308     }
309 
310     /** {@inheritDoc} */
311     public Vector3D transform(final GeodeticPoint point) {
312         final double longitude = point.getLongitude();
313         final SinCos scLambda  = FastMath.sinCos(longitude);
314         final double latitude  = point.getLatitude();
315         final SinCos scPhi     = FastMath.sinCos(latitude);
316         final double h         = point.getAltitude();
317         final double n         = getA() / FastMath.sqrt(1.0 - e2 * scPhi.sin() * scPhi.sin());
318         final double r         = (n + h) * scPhi.cos();
319         return new Vector3D(r * scLambda.cos(), r * scLambda.sin(), (g2 * n + h) * scPhi.sin());
320     }
321 
322     /** {@inheritDoc} */
323     public <T extends CalculusFieldElement<T>> FieldVector3D<T> transform(final FieldGeodeticPoint<T> point) {
324 
325         final T latitude  = point.getLatitude();
326         final T longitude = point.getLongitude();
327         final T altitude  = point.getAltitude();
328 
329         final FieldSinCos<T> scLambda = FastMath.sinCos(longitude);
330         final FieldSinCos<T> scPhi    = FastMath.sinCos(latitude);
331         final T cLambda = scLambda.cos();
332         final T sLambda = scLambda.sin();
333         final T cPhi    = scPhi.cos();
334         final T sPhi    = scPhi.sin();
335         final T n       = sPhi.multiply(sPhi).multiply(e2).subtract(1.0).negate().sqrt().reciprocal().multiply(getA());
336         final T r       = n.add(altitude).multiply(cPhi);
337 
338         return new FieldVector3D<>(r.multiply(cLambda),
339                                    r.multiply(sLambda),
340                                    sPhi.multiply(altitude.add(n.multiply(g2))));
341     }
342 
343     /** {@inheritDoc} */
344     public Vector3D projectToGround(final Vector3D point, final AbsoluteDate date, final Frame frame) {
345 
346         // transform point to body frame
347         final Transform  toBody    = frame.getTransformTo(bodyFrame, date);
348         final Vector3D   p         = toBody.transformPosition(point);
349         final double     z         = p.getZ();
350         final double     r         = FastMath.hypot(p.getX(), p.getY());
351 
352         // set up the 2D meridian ellipse
353         final Ellipse meridian = new Ellipse(Vector3D.ZERO,
354                                              r == 0 ? Vector3D.PLUS_I : new Vector3D(p.getX() / r, p.getY() / r, 0),
355                                              Vector3D.PLUS_K,
356                                              getA(), getC(), bodyFrame);
357 
358         // find the closest point in the meridian plane
359         final Vector3D groundPoint = meridian.toSpace(meridian.projectToEllipse(new Vector2D(r, z)));
360 
361         // transform point back to initial frame
362         return toBody.getInverse().transformPosition(groundPoint);
363 
364     }
365 
366     /** {@inheritDoc} */
367     public TimeStampedPVCoordinates projectToGround(final TimeStampedPVCoordinates pv, final Frame frame) {
368 
369         // transform point to body frame
370         final Transform                toBody        = frame.getTransformTo(bodyFrame, pv.getDate());
371         final TimeStampedPVCoordinates pvInBodyFrame = toBody.transformPVCoordinates(pv);
372         final Vector3D                 p             = pvInBodyFrame.getPosition();
373         final double                   r             = FastMath.hypot(p.getX(), p.getY());
374 
375         // set up the 2D ellipse corresponding to first principal curvature along meridian
376         final Vector3D meridian = r == 0 ? Vector3D.PLUS_I : new Vector3D(p.getX() / r, p.getY() / r, 0);
377         final Ellipse firstPrincipalCurvature =
378                 new Ellipse(Vector3D.ZERO, meridian, Vector3D.PLUS_K, getA(), getC(), bodyFrame);
379 
380         // project coordinates in the meridian plane
381         final TimeStampedPVCoordinates gpFirst = firstPrincipalCurvature.projectToEllipse(pvInBodyFrame);
382         final Vector3D                 gpP     = gpFirst.getPosition();
383         final double                   gr      = MathArrays.linearCombination(gpP.getX(), meridian.getX(),
384                                                                               gpP.getY(), meridian.getY());
385         final double                   gz      = gpP.getZ();
386 
387         // topocentric frame
388         final Vector3D east   = new Vector3D(-meridian.getY(), meridian.getX(), 0);
389         final Vector3D zenith = new Vector3D(gr * getC() / getA(), meridian, gz * getA() / getC(), Vector3D.PLUS_K).normalize();
390         final Vector3D north  = Vector3D.crossProduct(zenith, east);
391 
392         // set up the ellipse corresponding to second principal curvature in the zenith/east plane
393         final Ellipse secondPrincipalCurvature  = getPlaneSection(gpP, north);
394         final TimeStampedPVCoordinates gpSecond = secondPrincipalCurvature.projectToEllipse(pvInBodyFrame);
395 
396         final Vector3D gpV = gpFirst.getVelocity().add(gpSecond.getVelocity());
397         final Vector3D gpA = gpFirst.getAcceleration().add(gpSecond.getAcceleration());
398 
399         // moving projected point
400         final TimeStampedPVCoordinates groundPV =
401                 new TimeStampedPVCoordinates(pv.getDate(), gpP, gpV, gpA);
402 
403         // transform moving projected point back to initial frame
404         return toBody.getInverse().transformPVCoordinates(groundPV);
405 
406     }
407 
408     /** {@inheritDoc}
409      * <p>
410      * This method is based on Toshio Fukushima's algorithm which uses Halley's method.
411      * <a href="https://www.researchgate.net/publication/227215135_Transformation_from_Cartesian_to_Geodetic_Coordinates_Accelerated_by_Halley's_Method">
412      * transformation from Cartesian to Geodetic Coordinates Accelerated by Halley's Method</a>,
413      * Toshio Fukushima, Journal of Geodesy 9(12):689-693, February 2006
414      * </p>
415      * <p>
416      * Some changes have been added to the original method:
417      * <ul>
418      *   <li>in order to handle more accurately corner cases near the pole</li>
419      *   <li>in order to handle properly corner cases near the equatorial plane, even far inside the ellipsoid</li>
420      *   <li>in order to handle very flat ellipsoids</li>
421      * </ul>
422      */
423     public GeodeticPoint transform(final Vector3D point, final Frame frame, final AbsoluteDate date) {
424 
425         // transform point to body frame
426         final Vector3D pointInBodyFrame = frame.getTransformTo(bodyFrame, date).transformPosition(point);
427         final double   r2               = pointInBodyFrame.getX() * pointInBodyFrame.getX() +
428                                           pointInBodyFrame.getY() * pointInBodyFrame.getY();
429         final double   r                = FastMath.sqrt(r2);
430         final double   z                = pointInBodyFrame.getZ();
431 
432         final double   lambda           = FastMath.atan2(pointInBodyFrame.getY(), pointInBodyFrame.getX());
433 
434         double h;
435         double phi;
436         if (r <= ANGULAR_THRESHOLD * FastMath.abs(z)) {
437             // the point is almost on the polar axis, approximate the ellipsoid with
438             // the osculating sphere whose center is at evolute cusp along polar axis
439             final double osculatingRadius = ae2 / getC();
440             final double evoluteCuspZ     = FastMath.copySign(getA() * e2 / g, -z);
441             final double deltaZ           = z - evoluteCuspZ;
442             // we use π/2 - atan(r/Δz) instead of atan(Δz/r) for accuracy purposes, as r is much smaller than Δz
443             phi = FastMath.copySign(0.5 * FastMath.PI - FastMath.atan(r / FastMath.abs(deltaZ)), deltaZ);
444             h   = FastMath.hypot(deltaZ, r) - osculatingRadius;
445         } else if (FastMath.abs(z) <= ANGULAR_THRESHOLD * r) {
446             // the point is almost on the major axis
447 
448             final double osculatingRadius = ap2 / getA();
449             final double evoluteCuspR     = getA() * e2;
450             final double deltaR           = r - evoluteCuspR;
451             if (deltaR >= 0) {
452                 // the point is outside of the ellipse evolute, approximate the ellipse
453                 // with the osculating circle whose center is at evolute cusp along major axis
454                 phi = (deltaR == 0) ? 0.0 : FastMath.atan(z / deltaR);
455                 h   = FastMath.hypot(deltaR, z) - osculatingRadius;
456             } else {
457                 // the point is on the part of the major axis within ellipse evolute
458                 // we can compute the closest ellipse point analytically, and it is NOT near the equator
459                 final double rClose = r / e2;
460                 final double zClose = FastMath.copySign(g * FastMath.sqrt(ae2 - rClose * rClose), z);
461                 phi = FastMath.atan((zClose - z) / (rClose - r));
462                 h   = -FastMath.hypot(r - rClose, z - zClose);
463             }
464 
465         } else {
466             // use Toshio Fukushima method, with several iterations
467             final double epsPhi = 1.0e-15;
468             final double epsH   = 1.0e-14 * FastMath.max(getA(), FastMath.sqrt(r2 + z * z));
469             final double c     = getA() * e2;
470             final double absZ  = FastMath.abs(z);
471             final double zc    = g * absZ;
472             double sn  = absZ;
473             double sn2 = sn * sn;
474             double cn  = g * r;
475             double cn2 = cn * cn;
476             double an2 = cn2 + sn2;
477             double an  = FastMath.sqrt(an2);
478             double bn  = 0;
479             phi = Double.POSITIVE_INFINITY;
480             h   = Double.POSITIVE_INFINITY;
481             for (int i = 0; i < 10; ++i) { // this usually converges in 2 iterations
482                 final double oldSn  = sn;
483                 final double oldCn  = cn;
484                 final double oldPhi = phi;
485                 final double oldH   = h;
486                 final double an3    = an2 * an;
487                 final double csncn  = c * sn * cn;
488                 bn    = 1.5 * csncn * ((r * sn - zc * cn) * an - csncn);
489                 sn    = (zc * an3 + c * sn2 * sn) * an3 - bn * sn;
490                 cn    = (r  * an3 - c * cn2 * cn) * an3 - bn * cn;
491                 if (sn * oldSn < 0 || cn < 0) {
492                     // the Halley iteration went too far, we restrict it and iterate again
493                     while (sn * oldSn < 0 || cn < 0) {
494                         sn = (sn + oldSn) / 2;
495                         cn = (cn + oldCn) / 2;
496                     }
497                 } else {
498 
499                     // rescale components to avoid overflow when several iterations are used
500                     final int exp = (FastMath.getExponent(sn) + FastMath.getExponent(cn)) / 2;
501                     sn = FastMath.scalb(sn, -exp);
502                     cn = FastMath.scalb(cn, -exp);
503 
504                     sn2 = sn * sn;
505                     cn2 = cn * cn;
506                     an2 = cn2 + sn2;
507                     an  = FastMath.sqrt(an2);
508 
509                     final double cc = g * cn;
510                     h = (r * cc + absZ * sn - getA() * g * an) / FastMath.sqrt(an2 - e2 * cn2);
511                     if (FastMath.abs(oldH   - h)   < epsH) {
512                         phi = FastMath.copySign(FastMath.atan(sn / cc), z);
513                         if (FastMath.abs(oldPhi - phi) < epsPhi) {
514                             break;
515                         }
516                     }
517 
518                 }
519 
520             }
521         }
522 
523         return new GeodeticPoint(phi, lambda, h);
524 
525     }
526 
527     /** {@inheritDoc}
528      * <p>
529      * This method is based on Toshio Fukushima's algorithm which uses Halley's method.
530      * <a href="https://www.researchgate.net/publication/227215135_Transformation_from_Cartesian_to_Geodetic_Coordinates_Accelerated_by_Halley's_Method">
531      * transformation from Cartesian to Geodetic Coordinates Accelerated by Halley's Method</a>,
532      * Toshio Fukushima, Journal of Geodesy 9(12):689-693, February 2006
533      * </p>
534      * <p>
535      * Some changes have been added to the original method:
536      * <ul>
537      *   <li>in order to handle more accurately corner cases near the pole</li>
538      *   <li>in order to handle properly corner cases near the equatorial plane, even far inside the ellipsoid</li>
539      *   <li>in order to handle very flat ellipsoids</li>
540      * </ul>
541      */
542     public <T extends CalculusFieldElement<T>> FieldGeodeticPoint<T> transform(final FieldVector3D<T> point,
543                                                                            final Frame frame,
544                                                                            final FieldAbsoluteDate<T> date) {
545 
546         // transform point to body frame
547         final FieldVector3D<T> pointInBodyFrame = frame.getTransformTo(bodyFrame, date).transformPosition(point);
548         final T   r2                            = pointInBodyFrame.getX().multiply(pointInBodyFrame.getX()).
549                                               add(pointInBodyFrame.getY().multiply(pointInBodyFrame.getY()));
550         final T   r                             = r2.sqrt();
551         final T   z                             = pointInBodyFrame.getZ();
552 
553         final T   lambda                        = pointInBodyFrame.getY().atan2(pointInBodyFrame.getX());
554 
555         T h;
556         T phi;
557         if (r.getReal() <= ANGULAR_THRESHOLD * FastMath.abs(z.getReal())) {
558             // the point is almost on the polar axis, approximate the ellipsoid with
559             // the osculating sphere whose center is at evolute cusp along polar axis
560             final double osculatingRadius = ae2 / getC();
561             final double evoluteCuspZ     = FastMath.copySign(getA() * e2 / g, -z.getReal());
562             final T      deltaZ           = z.subtract(evoluteCuspZ);
563             // we use π/2 - atan(r/Δz) instead of atan(Δz/r) for accuracy purposes, as r is much smaller than Δz
564             phi = r.divide(deltaZ.abs()).atan().negate().add(r.getPi().multiply(0.5)).copySign(deltaZ);
565             h   = deltaZ.hypot(r).subtract(osculatingRadius);
566         } else if (FastMath.abs(z.getReal()) <= ANGULAR_THRESHOLD * r.getReal()) {
567             // the point is almost on the major axis
568 
569             final double osculatingRadius = ap2 / getA();
570             final double evoluteCuspR     = getA() * e2;
571             final T      deltaR           = r.subtract(evoluteCuspR);
572             if (deltaR.getReal() >= 0) {
573                 // the point is outside of the ellipse evolute, approximate the ellipse
574                 // with the osculating circle whose center is at evolute cusp along major axis
575                 phi = (deltaR.getReal() == 0) ? z.getField().getZero() : z.divide(deltaR).atan();
576                 h   = deltaR.hypot(z).subtract(osculatingRadius);
577             } else {
578                 // the point is on the part of the major axis within ellipse evolute
579                 // we can compute the closest ellipse point analytically, and it is NOT near the equator
580                 final T rClose = r.divide(e2);
581                 final T zClose = rClose.multiply(rClose).negate().add(ae2).sqrt().multiply(g).copySign(z);
582                 phi = zClose.subtract(z).divide(rClose.subtract(r)).atan();
583                 h   = r.subtract(rClose).hypot(z.subtract(zClose)).negate();
584             }
585 
586         } else {
587             // use Toshio Fukushima method, with several iterations
588             final double epsPhi = 1.0e-15;
589             final double epsH   = 1.0e-14 * getA();
590             final double c      = getA() * e2;
591             final T      absZ   = z.abs();
592             final T      zc     = absZ.multiply(g);
593             T            sn     = absZ;
594             T            sn2    = sn.multiply(sn);
595             T            cn     = r.multiply(g);
596             T            cn2    = cn.multiply(cn);
597             T            an2    = cn2.add(sn2);
598             T            an     = an2.sqrt();
599             T            bn     = an.getField().getZero();
600             phi = an.getField().getZero().add(Double.POSITIVE_INFINITY);
601             h   = an.getField().getZero().add(Double.POSITIVE_INFINITY);
602             for (int i = 0; i < 10; ++i) { // this usually converges in 2 iterations
603                 final T oldSn  = sn;
604                 final T oldCn  = cn;
605                 final T oldPhi = phi;
606                 final T oldH   = h;
607                 final T an3    = an2.multiply(an);
608                 final T csncn  = sn.multiply(cn).multiply(c);
609                 bn    = csncn.multiply(1.5).multiply((r.multiply(sn).subtract(zc.multiply(cn))).multiply(an).subtract(csncn));
610                 sn    = zc.multiply(an3).add(sn2.multiply(sn).multiply(c)).multiply(an3).subtract(bn.multiply(sn));
611                 cn    = r.multiply(an3).subtract(cn2.multiply(cn).multiply(c)).multiply(an3).subtract(bn.multiply(cn));
612                 if (sn.getReal() * oldSn.getReal() < 0 || cn.getReal() < 0) {
613                     // the Halley iteration went too far, we restrict it and iterate again
614                     while (sn.getReal() * oldSn.getReal() < 0 || cn.getReal() < 0) {
615                         sn = sn.add(oldSn).multiply(0.5);
616                         cn = cn.add(oldCn).multiply(0.5);
617                     }
618                 } else {
619 
620                     // rescale components to avoid overflow when several iterations are used
621                     final int exp = (FastMath.getExponent(sn.getReal()) + FastMath.getExponent(cn.getReal())) / 2;
622                     sn = sn.scalb(-exp);
623                     cn = cn.scalb(-exp);
624 
625                     sn2 = sn.multiply(sn);
626                     cn2 = cn.multiply(cn);
627                     an2 = cn2.add(sn2);
628                     an  = an2.sqrt();
629 
630                     final T cc = cn.multiply(g);
631                     h = r.multiply(cc).add(absZ.multiply(sn)).subtract(an.multiply(getA() * g)).divide(an2.subtract(cn2.multiply(e2)).sqrt());
632                     if (FastMath.abs(oldH.getReal()  - h.getReal())   < epsH) {
633                         phi = sn.divide(cc).atan().copySign(z);
634                         if (FastMath.abs(oldPhi.getReal() - phi.getReal()) < epsPhi) {
635                             break;
636                         }
637                     }
638 
639                 }
640 
641             }
642         }
643 
644         return new FieldGeodeticPoint<>(phi, lambda, h);
645 
646     }
647 
648     /** Transform a Cartesian point to a surface-relative point.
649      * @param point Cartesian point
650      * @param frame frame in which Cartesian point is expressed
651      * @param date date of the computation (used for frames conversions)
652      * @return point at the same location but as a surface-relative point,
653      * using time as the single derivation parameter
654      */
655     public FieldGeodeticPoint<DerivativeStructure> transform(final PVCoordinates point,
656                                                              final Frame frame, final AbsoluteDate date) {
657 
658         // transform point to body frame
659         final Transform toBody = frame.getTransformTo(bodyFrame, date);
660         final PVCoordinates pointInBodyFrame = toBody.transformPVCoordinates(point);
661         final FieldVector3D<DerivativeStructure> p = pointInBodyFrame.toDerivativeStructureVector(2);
662         final DerivativeStructure   pr2 = p.getX().multiply(p.getX()).add(p.getY().multiply(p.getY()));
663         final DerivativeStructure   pr  = pr2.sqrt();
664         final DerivativeStructure   pz  = p.getZ();
665 
666         // project point on the ellipsoid surface
667         final TimeStampedPVCoordinates groundPoint = projectToGround(new TimeStampedPVCoordinates(date, pointInBodyFrame),
668                                                                      bodyFrame);
669         final FieldVector3D<DerivativeStructure> gp = groundPoint.toDerivativeStructureVector(2);
670         final DerivativeStructure   gpr2 = gp.getX().multiply(gp.getX()).add(gp.getY().multiply(gp.getY()));
671         final DerivativeStructure   gpr  = gpr2.sqrt();
672         final DerivativeStructure   gpz  = gp.getZ();
673 
674         // relative position of test point with respect to its ellipse sub-point
675         final DerivativeStructure dr  = pr.subtract(gpr);
676         final DerivativeStructure dz  = pz.subtract(gpz);
677         final double insideIfNegative = g2 * (pr2.getReal() - ae2) + pz.getReal() * pz.getReal();
678 
679         return new FieldGeodeticPoint<>(DerivativeStructure.atan2(gpz, gpr.multiply(g2)),
680                                                                   DerivativeStructure.atan2(p.getY(), p.getX()),
681                                                                   DerivativeStructure.hypot(dr, dz).copySign(insideIfNegative));
682     }
683 
684     /** Replace the instance with a data transfer object for serialization.
685      * <p>
686      * This intermediate class serializes the files supported names, the
687      * ephemeris type and the body name.
688      * </p>
689      * @return data transfer object that will be serialized
690      */
691     private Object writeReplace() {
692         return new DataTransferObject(getA(), f, bodyFrame, angularThreshold);
693     }
694 
695     /** Internal class used only for serialization. */
696     private static class DataTransferObject implements Serializable {
697 
698         /** Serializable UID. */
699         private static final long serialVersionUID = 20130518L;
700 
701         /** Equatorial radius. */
702         private final double ae;
703 
704         /** Flattening. */
705         private final double f;
706 
707         /** Body frame related to body shape. */
708         private final Frame bodyFrame;
709 
710         /** Convergence limit. */
711         private final double angularThreshold;
712 
713         /** Simple constructor.
714          * @param ae equatorial radius
715          * @param f the flattening (f = (a-b)/a)
716          * @param bodyFrame body frame related to body shape
717          * @param angularThreshold convergence limit
718          */
719         DataTransferObject(final double ae, final double f,
720                                   final Frame bodyFrame, final double angularThreshold) {
721             this.ae               = ae;
722             this.f                = f;
723             this.bodyFrame        = bodyFrame;
724             this.angularThreshold = angularThreshold;
725         }
726 
727         /** Replace the deserialized data transfer object with a
728          * {@link JPLCelestialBody}.
729          * @return replacement {@link JPLCelestialBody}
730          */
731         private Object readResolve() {
732             final OneAxisEllipsoid ellipsoid = new OneAxisEllipsoid(ae, f, bodyFrame);
733             ellipsoid.setAngularThreshold(angularThreshold);
734             return ellipsoid;
735         }
736 
737     }
738 
739 }