NeQuickModel.java

  1. /* Copyright 2002-2022 CS GROUP
  2.  * Licensed to CS GROUP (CS) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * CS licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *   http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.orekit.models.earth.ionosphere;

  18. import java.io.BufferedReader;
  19. import java.io.IOException;
  20. import java.io.InputStream;
  21. import java.io.InputStreamReader;
  22. import java.nio.charset.StandardCharsets;
  23. import java.util.Collections;
  24. import java.util.List;
  25. import java.util.regex.Pattern;

  26. import org.hipparchus.Field;
  27. import org.hipparchus.CalculusFieldElement;
  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.annotation.DefaultDataContext;
  33. import org.orekit.bodies.BodyShape;
  34. import org.orekit.bodies.FieldGeodeticPoint;
  35. import org.orekit.bodies.GeodeticPoint;
  36. import org.orekit.data.DataContext;
  37. import org.orekit.errors.OrekitException;
  38. import org.orekit.errors.OrekitMessages;
  39. import org.orekit.frames.TopocentricFrame;
  40. import org.orekit.propagation.FieldSpacecraftState;
  41. import org.orekit.propagation.SpacecraftState;
  42. import org.orekit.time.AbsoluteDate;
  43. import org.orekit.time.DateComponents;
  44. import org.orekit.time.DateTimeComponents;
  45. import org.orekit.time.FieldAbsoluteDate;
  46. import org.orekit.time.TimeScale;
  47. import org.orekit.utils.ParameterDriver;
  48. import org.orekit.utils.TimeStampedFieldPVCoordinates;
  49. import org.orekit.utils.TimeStampedPVCoordinates;

  50. /**
  51.  * NeQuick ionospheric delay model.
  52.  *
  53.  * @author Bryan Cazabonne
  54.  *
  55.  * @see "European Union (2016). European GNSS (Galileo) Open Service-Ionospheric Correction
  56.  *       Algorithm for Galileo Single Frequency Users. 1.2."
  57.  *
  58.  * @since 10.1
  59.  */
  60. public class NeQuickModel implements IonosphericModel {

  61.     /** NeQuick resources base directory. */
  62.     private static final String NEQUICK_BASE = "/assets/org/orekit/nequick/";

  63.     /** Serializable UID. */
  64.     private static final long serialVersionUID = 201928051L;

  65.     /** Pattern for delimiting regular expressions. */
  66.     private static final Pattern SEPARATOR = Pattern.compile("\\s+");

  67.     /** Mean Earth radius in m (Ref Table 2.5.2). */
  68.     private static final double RE = 6371200.0;

  69.     /** Meters to kilometers converter. */
  70.     private static final double M_TO_KM = 0.001;

  71.     /** Factor for the electron density computation. */
  72.     private static final double DENSITY_FACTOR = 1.0e11;

  73.     /** Factor for the path delay computation. */
  74.     private static final double DELAY_FACTOR = 40.3e16;

  75.     /** The three ionospheric coefficients broadcast in the Galileo navigation message. */
  76.     private final double[] alpha;

  77.     /** MODIP grid. */
  78.     private final double[][] stModip;

  79.     /** Month used for loading CCIR coefficients. */
  80.     private int month;

  81.     /** F2 coefficients used by the F2 layer. */
  82.     private double[][][] f2;

  83.     /** Fm3 coefficients used by the F2 layer. */
  84.     private double[][][] fm3;

  85.     /** UTC time scale. */
  86.     private final TimeScale utc;

  87.     /**
  88.      * Build a new instance.
  89.      *
  90.      * <p>This constructor uses the {@link DataContext#getDefault() default data context}.
  91.      *
  92.      * @param alpha effective ionisation level coefficients
  93.      * @see #NeQuickModel(double[], TimeScale)
  94.      */
  95.     @DefaultDataContext
  96.     public NeQuickModel(final double[] alpha) {
  97.         this(alpha, DataContext.getDefault().getTimeScales().getUTC());
  98.     }

  99.     /**
  100.      * Build a new instance.
  101.      * @param alpha effective ionisation level coefficients
  102.      * @param utc UTC time scale.
  103.      * @since 10.1
  104.      */
  105.     public NeQuickModel(final double[] alpha,
  106.                         final TimeScale utc) {
  107.         // F2 layer values
  108.         this.month = 0;
  109.         this.f2    = null;
  110.         this.fm3   = null;
  111.         // Read modip grid
  112.         final MODIPLoader parser = new MODIPLoader();
  113.         parser.loadMODIPGrid();
  114.         this.stModip = parser.getMODIPGrid();
  115.         // Ionisation level coefficients
  116.         this.alpha = alpha.clone();
  117.         this.utc = utc;
  118.     }

  119.     @Override
  120.     public double pathDelay(final SpacecraftState state, final TopocentricFrame baseFrame,
  121.                             final double frequency, final double[] parameters) {
  122.         // Point
  123.         final GeodeticPoint recPoint = baseFrame.getPoint();
  124.         // Date
  125.         final AbsoluteDate date = state.getDate();

  126.         // Reference body shape
  127.         final BodyShape ellipsoid = baseFrame.getParentShape();
  128.         // Satellite geodetic coordinates
  129.         final TimeStampedPVCoordinates pv = state.getPVCoordinates(ellipsoid.getBodyFrame());
  130.         final GeodeticPoint satPoint = ellipsoid.transform(pv.getPosition(), ellipsoid.getBodyFrame(), state.getDate());

  131.         // Total Electron Content
  132.         final double tec = stec(date, recPoint, satPoint);

  133.         // Ionospheric delay
  134.         final double factor = DELAY_FACTOR / (frequency * frequency);
  135.         return factor * tec;
  136.     }

  137.     @Override
  138.     public <T extends CalculusFieldElement<T>> T pathDelay(final FieldSpacecraftState<T> state, final TopocentricFrame baseFrame,
  139.                                                        final double frequency, final T[] parameters) {
  140.         // Date
  141.         final FieldAbsoluteDate<T> date = state.getDate();
  142.         // Point
  143.         final FieldGeodeticPoint<T> recPoint = baseFrame.getPoint(date.getField());


  144.         // Reference body shape
  145.         final BodyShape ellipsoid = baseFrame.getParentShape();
  146.         // Satellite geodetic coordinates
  147.         final TimeStampedFieldPVCoordinates<T> pv = state.getPVCoordinates(ellipsoid.getBodyFrame());
  148.         final FieldGeodeticPoint<T> satPoint = ellipsoid.transform(pv.getPosition(), ellipsoid.getBodyFrame(), state.getDate());

  149.         // Total Electron Content
  150.         final T tec = stec(date, recPoint, satPoint);

  151.         // Ionospheric delay
  152.         final double factor = DELAY_FACTOR / (frequency * frequency);
  153.         return tec.multiply(factor);
  154.     }

  155.     @Override
  156.     public List<ParameterDriver> getParametersDrivers() {
  157.         return Collections.emptyList();
  158.     }

  159.     /**
  160.      * This method allows the computation of the Stant Total Electron Content (STEC).
  161.      * <p>
  162.      * This method follows the Gauss algorithm exposed in section 2.5.8.2.8 of
  163.      * the reference document.
  164.      * </p>
  165.      * @param date current date
  166.      * @param recP receiver position
  167.      * @param satP satellite position
  168.      * @return the STEC in TECUnits
  169.      */
  170.     public double stec(final AbsoluteDate date, final GeodeticPoint recP, final GeodeticPoint satP) {

  171.         // Ray-perigee parameters
  172.         final Ray ray = new Ray(recP, satP);

  173.         // Load the correct CCIR file
  174.         final DateTimeComponents dateTime = date.getComponents(utc);
  175.         loadsIfNeeded(dateTime.getDate());

  176.         // Tolerance for the integration accuracy. Defined inside the reference document, section 2.5.8.1.
  177.         final double h1 = recP.getAltitude();
  178.         final double tolerance;
  179.         if (h1 < 1000000.0) {
  180.             tolerance = 0.001;
  181.         } else {
  182.             tolerance = 0.01;
  183.         }

  184.         // Integration
  185.         int n = 8;
  186.         final Segment seg1 = new Segment(n, ray);
  187.         double gn1 = stecIntegration(seg1, dateTime);
  188.         n *= 2;
  189.         final Segment seg2 = new Segment(n, ray);
  190.         double gn2 = stecIntegration(seg2, dateTime);

  191.         int count = 1;
  192.         while (FastMath.abs(gn2 - gn1) > tolerance * FastMath.abs(gn1) && count < 20) {
  193.             gn1 = gn2;
  194.             n *= 2;
  195.             final Segment seg = new Segment(n, ray);
  196.             gn2 = stecIntegration(seg, dateTime);
  197.             count += 1;
  198.         }

  199.         // If count > 20 the integration did not converge
  200.         if (count == 20) {
  201.             throw new OrekitException(OrekitMessages.STEC_INTEGRATION_DID_NOT_CONVERGE);
  202.         }

  203.         // Eq. 202
  204.         return (gn2 + ((gn2 - gn1) / 15.0)) * 1.0e-16;
  205.     }

  206.     /**
  207.      * This method allows the computation of the Stant Total Electron Content (STEC).
  208.      * <p>
  209.      * This method follows the Gauss algorithm exposed in section 2.5.8.2.8 of
  210.      * the reference document.
  211.      * </p>
  212.      * @param <T> type of the elements
  213.      * @param date current date
  214.      * @param recP receiver position
  215.      * @param satP satellite position
  216.      * @return the STEC in TECUnits
  217.      */
  218.     public <T extends CalculusFieldElement<T>> T stec(final FieldAbsoluteDate<T> date,
  219.                                                   final FieldGeodeticPoint<T> recP,
  220.                                                   final FieldGeodeticPoint<T> satP) {

  221.         // Field
  222.         final Field<T> field = date.getField();

  223.         // Ray-perigee parameters
  224.         final FieldRay<T> ray = new FieldRay<>(field, recP, satP);

  225.         // Load the correct CCIR file
  226.         final DateTimeComponents dateTime = date.getComponents(utc);
  227.         loadsIfNeeded(dateTime.getDate());

  228.         // Tolerance for the integration accuracy. Defined inside the reference document, section 2.5.8.1.
  229.         final T h1 = recP.getAltitude();
  230.         final double tolerance;
  231.         if (h1.getReal() < 1000000.0) {
  232.             tolerance = 0.001;
  233.         } else {
  234.             tolerance = 0.01;
  235.         }

  236.         // Integration
  237.         int n = 8;
  238.         final FieldSegment<T> seg1 = new FieldSegment<>(field, n, ray);
  239.         T gn1 = stecIntegration(field, seg1, dateTime);
  240.         n *= 2;
  241.         final FieldSegment<T> seg2 = new FieldSegment<>(field, n, ray);
  242.         T gn2 = stecIntegration(field, seg2, dateTime);

  243.         int count = 1;
  244.         while (FastMath.abs(gn2.subtract(gn1)).getReal() > FastMath.abs(gn1).multiply(tolerance).getReal() && count < 20) {
  245.             gn1 = gn2;
  246.             n *= 2;
  247.             final FieldSegment<T> seg = new FieldSegment<>(field, n, ray);
  248.             gn2 = stecIntegration(field, seg, dateTime);
  249.             count += 1;
  250.         }

  251.         // If count > 20 the integration did not converge
  252.         if (count == 20) {
  253.             throw new OrekitException(OrekitMessages.STEC_INTEGRATION_DID_NOT_CONVERGE);
  254.         }

  255.         // Eq. 202
  256.         return gn2.add(gn2.subtract(gn1).divide(15.0)).multiply(1.0e-16);
  257.     }

  258.     /**
  259.      * This method perfoms the STEC integration.
  260.      * @param seg coordinates along the integration path
  261.      * @param dateTime current date and time componentns
  262.      * @return result of the integration
  263.      */
  264.     private double stecIntegration(final Segment seg, final DateTimeComponents dateTime) {
  265.         // Integration points
  266.         final double[] heightS    = seg.getHeights();
  267.         final double[] latitudeS  = seg.getLatitudes();
  268.         final double[] longitudeS = seg.getLongitudes();

  269.         // Compute electron density
  270.         double density = 0.0;
  271.         for (int i = 0; i < heightS.length; i++) {
  272.             final NeQuickParameters parameters = new NeQuickParameters(dateTime, f2, fm3,
  273.                                                                        latitudeS[i], longitudeS[i],
  274.                                                                        alpha, stModip);
  275.             density += electronDensity(heightS[i], parameters);
  276.         }

  277.         return 0.5 * seg.getInterval() * density;
  278.     }

  279.     /**
  280.      * This method perfoms the STEC integration.
  281.      * @param <T> type of the elements
  282.      * @param field field of the elements
  283.      * @param seg coordinates along the integration path
  284.      * @param dateTime current date and time componentns
  285.      * @return result of the integration
  286.      */
  287.     private <T extends CalculusFieldElement<T>> T stecIntegration(final Field<T> field,
  288.                                                               final FieldSegment<T> seg,
  289.                                                               final DateTimeComponents dateTime) {
  290.         // Integration points
  291.         final T[] heightS    = seg.getHeights();
  292.         final T[] latitudeS  = seg.getLatitudes();
  293.         final T[] longitudeS = seg.getLongitudes();

  294.         // Compute electron density
  295.         T density = field.getZero();
  296.         for (int i = 0; i < heightS.length; i++) {
  297.             final FieldNeQuickParameters<T> parameters = new FieldNeQuickParameters<>(field, dateTime, f2, fm3,
  298.                                                                                       latitudeS[i], longitudeS[i],
  299.                                                                                       alpha, stModip);
  300.             density = density.add(electronDensity(field, heightS[i], parameters));
  301.         }

  302.         return seg.getInterval().multiply(density).multiply(0.5);
  303.     }

  304.     /**
  305.      * Computes the electron density at a given height.
  306.      * @param h height in m
  307.      * @param parameters NeQuick model parameters
  308.      * @return electron density [m^-3]
  309.      */
  310.     private double electronDensity(final double h, final NeQuickParameters parameters) {
  311.         // Convert height in kilometers
  312.         final double hInKm = h * M_TO_KM;
  313.         // Electron density
  314.         final double n;
  315.         if (hInKm <= parameters.getHmF2()) {
  316.             n = bottomElectronDensity(hInKm, parameters);
  317.         } else {
  318.             n = topElectronDensity(hInKm, parameters);
  319.         }
  320.         return n;
  321.     }

  322.     /**
  323.      * Computes the electron density at a given height.
  324.      * @param <T> type of the elements
  325.      * @param field field of the elements
  326.      * @param h height in m
  327.      * @param parameters NeQuick model parameters
  328.      * @return electron density [m^-3]
  329.      */
  330.     private <T extends CalculusFieldElement<T>> T electronDensity(final Field<T> field,
  331.                                                               final T h,
  332.                                                               final FieldNeQuickParameters<T> parameters) {
  333.         // Convert height in kilometers
  334.         final T hInKm = h.multiply(M_TO_KM);
  335.         // Electron density
  336.         final T n;
  337.         if (hInKm.getReal() <= parameters.getHmF2().getReal()) {
  338.             n = bottomElectronDensity(field, hInKm, parameters);
  339.         } else {
  340.             n = topElectronDensity(field, hInKm, parameters);
  341.         }
  342.         return n;
  343.     }

  344.     /**
  345.      * Computes the electron density of the bottomside.
  346.      * @param h height in km
  347.      * @param parameters NeQuick model parameters
  348.      * @return the electron density N in m-3
  349.      */
  350.     private double bottomElectronDensity(final double h, final NeQuickParameters parameters) {

  351.         // Select the relevant B parameter for the current height (Eq. 109 and 110)
  352.         final double be;
  353.         if (h > parameters.getHmE()) {
  354.             be = parameters.getBETop();
  355.         } else {
  356.             be = parameters.getBEBot();
  357.         }
  358.         final double bf1;
  359.         if (h > parameters.getHmF1()) {
  360.             bf1 = parameters.getB1Top();
  361.         } else {
  362.             bf1 = parameters.getB1Bot();
  363.         }
  364.         final double bf2 = parameters.getB2Bot();

  365.         // Useful array of constants
  366.         final double[] ct = new double[] {
  367.             1.0 / bf2, 1.0 / bf1, 1.0 / be
  368.         };

  369.         // Compute the exponential argument for each layer (Eq. 111 to 113)
  370.         // If h < 100km we use h = 100km as recommended in the reference document
  371.         final double   hTemp = FastMath.max(100.0, h);
  372.         final double   exp   = clipExp(10.0 / (1.0 + FastMath.abs(hTemp - parameters.getHmF2())));
  373.         final double[] arguments = new double[3];
  374.         arguments[0] = (hTemp - parameters.getHmF2()) / bf2;
  375.         arguments[1] = ((hTemp - parameters.getHmF1()) / bf1) * exp;
  376.         arguments[2] = ((hTemp - parameters.getHmE()) / be) * exp;

  377.         // S coefficients
  378.         final double[] s = new double[3];
  379.         // Array of corrective terms
  380.         final double[] ds = new double[3];

  381.         // Layer amplitudes
  382.         final double[] amplitudes = parameters.getLayerAmplitudes();

  383.         // Fill arrays (Eq. 114 to 118)
  384.         for (int i = 0; i < 3; i++) {
  385.             if (FastMath.abs(arguments[i]) > 25.0) {
  386.                 s[i]  = 0.0;
  387.                 ds[i] = 0.0;
  388.             } else {
  389.                 final double expA   = clipExp(arguments[i]);
  390.                 final double opExpA = 1.0 + expA;
  391.                 s[i]  = amplitudes[i] * (expA / (opExpA * opExpA));
  392.                 ds[i] = ct[i] * ((1.0 - expA) / (1.0 + expA));
  393.             }
  394.         }

  395.         // Electron density
  396.         final double aNo = MathArrays.linearCombination(s[0], 1.0, s[1], 1.0, s[2], 1.0);
  397.         if (h >= 100) {
  398.             return aNo * DENSITY_FACTOR;
  399.         } else {
  400.             // Chapman parameters (Eq. 119 and 120)
  401.             final double bc = 1.0 - 10.0 * (MathArrays.linearCombination(s[0], ds[0], s[1], ds[1], s[2], ds[2]) / aNo);
  402.             final double z  = 0.1 * (h - 100.0);
  403.             // Electron density (Eq. 121)
  404.             return aNo * clipExp(1.0 - bc * z - clipExp(-z)) * DENSITY_FACTOR;
  405.         }
  406.     }

  407.     /**
  408.      * Computes the electron density of the bottomside.
  409.      * @param <T> type of the elements
  410.      * @param field field of the elements
  411.      * @param h height in km
  412.      * @param parameters NeQuick model parameters
  413.      * @return the electron density N in m-3
  414.      */
  415.     private <T extends CalculusFieldElement<T>> T bottomElectronDensity(final Field<T> field,
  416.                                                                     final T h,
  417.                                                                     final FieldNeQuickParameters<T> parameters) {

  418.         // Zero and One
  419.         final T zero = field.getZero();
  420.         final T one  = field.getOne();

  421.         // Select the relevant B parameter for the current height (Eq. 109 and 110)
  422.         final T be;
  423.         if (h.getReal() > parameters.getHmE().getReal()) {
  424.             be = parameters.getBETop();
  425.         } else {
  426.             be = parameters.getBEBot();
  427.         }
  428.         final T bf1;
  429.         if (h.getReal() > parameters.getHmF1().getReal()) {
  430.             bf1 = parameters.getB1Top();
  431.         } else {
  432.             bf1 = parameters.getB1Bot();
  433.         }
  434.         final T bf2 = parameters.getB2Bot();

  435.         // Useful array of constants
  436.         final T[] ct = MathArrays.buildArray(field, 3);
  437.         ct[0] = bf2.reciprocal();
  438.         ct[1] = bf1.reciprocal();
  439.         ct[2] = be.reciprocal();

  440.         // Compute the exponential argument for each layer (Eq. 111 to 113)
  441.         // If h < 100km we use h = 100km as recommended in the reference document
  442.         final T   hTemp = FastMath.max(zero.add(100.0), h);
  443.         final T   exp   = clipExp(field, FastMath.abs(hTemp.subtract(parameters.getHmF2())).add(1.0).divide(10.0).reciprocal());
  444.         final T[] arguments = MathArrays.buildArray(field, 3);
  445.         arguments[0] = hTemp.subtract(parameters.getHmF2()).divide(bf2);
  446.         arguments[1] = hTemp.subtract(parameters.getHmF1()).divide(bf1).multiply(exp);
  447.         arguments[2] = hTemp.subtract(parameters.getHmE()).divide(be).multiply(exp);

  448.         // S coefficients
  449.         final T[] s = MathArrays.buildArray(field, 3);
  450.         // Array of corrective terms
  451.         final T[] ds = MathArrays.buildArray(field, 3);

  452.         // Layer amplitudes
  453.         final T[] amplitudes = parameters.getLayerAmplitudes();

  454.         // Fill arrays (Eq. 114 to 118)
  455.         for (int i = 0; i < 3; i++) {
  456.             if (FastMath.abs(arguments[i]).getReal() > 25.0) {
  457.                 s[i]  = zero;
  458.                 ds[i] = zero;
  459.             } else {
  460.                 final T expA   = clipExp(field, arguments[i]);
  461.                 final T opExpA = expA.add(1.0);
  462.                 s[i]  = amplitudes[i].multiply(expA.divide(opExpA.multiply(opExpA)));
  463.                 ds[i] = ct[i].multiply(expA.negate().add(1.0).divide(expA.add(1.0)));
  464.             }
  465.         }

  466.         // Electron density
  467.         final T aNo = one.linearCombination(s[0], one, s[1], one, s[2], one);
  468.         if (h.getReal() >= 100) {
  469.             return aNo.multiply(DENSITY_FACTOR);
  470.         } else {
  471.             // Chapman parameters (Eq. 119 and 120)
  472.             final T bc = s[0].multiply(ds[0]).add(one.linearCombination(s[0], ds[0], s[1], ds[1], s[2], ds[2])).divide(aNo).multiply(10.0).negate().add(1.0);
  473.             final T z  = h.subtract(100.0).multiply(0.1);
  474.             // Electron density (Eq. 121)
  475.             return aNo.multiply(clipExp(field, bc.multiply(z).add(clipExp(field, z.negate())).negate().add(1.0))).multiply(DENSITY_FACTOR);
  476.         }
  477.     }

  478.     /**
  479.      * Computes the electron density of the topside.
  480.      * @param h height in km
  481.      * @param parameters NeQuick model parameters
  482.      * @return the electron density N in m-3
  483.      */
  484.     private double topElectronDensity(final double h, final NeQuickParameters parameters) {

  485.         // Constant parameters (Eq. 122 and 123)
  486.         final double g = 0.125;
  487.         final double r = 100.0;

  488.         // Arguments deltaH and z (Eq. 124 and 125)
  489.         final double deltaH = h - parameters.getHmF2();
  490.         final double z      = deltaH / (parameters.getH0() * (1.0 + (r * g * deltaH) / (r * parameters.getH0() + g * deltaH)));

  491.         // Exponential (Eq. 126)
  492.         final double ee = clipExp(z);

  493.         // Electron density (Eq. 127)
  494.         if (ee > 1.0e11) {
  495.             return (4.0 * parameters.getNmF2() / ee) * DENSITY_FACTOR;
  496.         } else {
  497.             final double opExpZ = 1.0 + ee;
  498.             return ((4.0 * parameters.getNmF2() * ee) / (opExpZ * opExpZ)) * DENSITY_FACTOR;
  499.         }
  500.     }

  501.     /**
  502.      * Computes the electron density of the topside.
  503.      * @param <T> type of the elements
  504.      * @param field field of the elements
  505.      * @param h height in km
  506.      * @param parameters NeQuick model parameters
  507.      * @return the electron density N in m-3
  508.      */
  509.     private <T extends CalculusFieldElement<T>> T topElectronDensity(final Field<T> field,
  510.                                                                  final T h,
  511.                                                                  final FieldNeQuickParameters<T> parameters) {

  512.         // Constant parameters (Eq. 122 and 123)
  513.         final double g = 0.125;
  514.         final double r = 100.0;

  515.         // Arguments deltaH and z (Eq. 124 and 125)
  516.         final T deltaH = h.subtract(parameters.getHmF2());
  517.         final T z      = deltaH.divide(parameters.getH0().multiply(deltaH.multiply(r).multiply(g).divide(parameters.getH0().multiply(r).add(deltaH.multiply(g))).add(1.0)));

  518.         // Exponential (Eq. 126)
  519.         final T ee = clipExp(field, z);

  520.         // Electron density (Eq. 127)
  521.         if (ee.getReal() > 1.0e11) {
  522.             return parameters.getNmF2().multiply(4.0).divide(ee).multiply(DENSITY_FACTOR);
  523.         } else {
  524.             final T opExpZ = ee.add(field.getOne());
  525.             return parameters.getNmF2().multiply(4.0).multiply(ee).divide(opExpZ.multiply(opExpZ)).multiply(DENSITY_FACTOR);
  526.         }
  527.     }

  528.     /**
  529.      * Lazy loading of CCIR data.
  530.      * @param date current date components
  531.      */
  532.     private void loadsIfNeeded(final DateComponents date) {

  533.         // Current month
  534.         final int currentMonth = date.getMonth();

  535.         // Check if date have changed or if f2 and fm3 arrays are null
  536.         if (currentMonth != month || f2 == null || fm3 == null) {
  537.             this.month = currentMonth;

  538.             // Read file
  539.             final CCIRLoader loader = new CCIRLoader();
  540.             loader.loadCCIRCoefficients(date);

  541.             // Update arrays
  542.             this.f2 = loader.getF2();
  543.             this.fm3 = loader.getFm3();
  544.         }
  545.     }

  546.     /**
  547.      * A clipped exponential function.
  548.      * <p>
  549.      * This function, describe in section F.2.12.2 of the reference document, is
  550.      * recommanded for the computation of exponential values.
  551.      * </p>
  552.      * @param power power for exponential function
  553.      * @return clipped exponential value
  554.      */
  555.     private double clipExp(final double power) {
  556.         if (power > 80.0) {
  557.             return 5.5406E34;
  558.         } else if (power < -80) {
  559.             return 1.8049E-35;
  560.         } else {
  561.             return FastMath.exp(power);
  562.         }
  563.     }

  564.     /**
  565.      * A clipped exponential function.
  566.      * <p>
  567.      * This function, describe in section F.2.12.2 of the reference document, is
  568.      * recommanded for the computation of exponential values.
  569.      * </p>
  570.      * @param <T> type of the elements
  571.      * @param field field of the elements
  572.      * @param power power for exponential function
  573.      * @return clipped exponential value
  574.      */
  575.     private <T extends CalculusFieldElement<T>> T clipExp(final Field<T> field, final T power) {
  576.         final T zero = field.getZero();
  577.         if (power.getReal() > 80.0) {
  578.             return zero.add(5.5406E34);
  579.         } else if (power.getReal() < -80) {
  580.             return zero.add(1.8049E-35);
  581.         } else {
  582.             return FastMath.exp(power);
  583.         }
  584.     }

  585.     /** Get a data stream.
  586.      * @param name file name of the resource stream
  587.      * @return stream
  588.      */
  589.     private static InputStream getStream(final String name) {
  590.         return NeQuickModel.class.getResourceAsStream(name);
  591.     }

  592.     /**
  593.      * Parser for Modified Dip Latitude (MODIP) grid file.
  594.      * <p>
  595.      * The MODIP grid allows to estimate MODIP μ [deg] at a given point (φ,λ)
  596.      * by interpolation of the relevant values contained in the support file.
  597.      * </p> <p>
  598.      * The file contains the values of MODIP (expressed in degrees) on a geocentric grid
  599.      * from 90°S to 90°N with a 5-degree step in latitude and from 180°W to 180°E with a
  600.      * 10-degree in longitude.
  601.      * </p>
  602.      */
  603.     private static class MODIPLoader {

  604.         /** Supported name for MODIP grid. */
  605.         private static final String SUPPORTED_NAME = NEQUICK_BASE + "modip.txt";

  606.         /** MODIP grid. */
  607.         private double[][] grid;

  608.         /**
  609.          * Build a new instance.
  610.          */
  611.         MODIPLoader() {
  612.             this.grid = null;
  613.         }

  614.         /** Returns the MODIP grid array.
  615.          * @return the MODIP grid array
  616.          */
  617.         public double[][] getMODIPGrid() {
  618.             return grid.clone();
  619.         }

  620.         /**
  621.          * Load the data using supported names.
  622.          */
  623.         public void loadMODIPGrid() {
  624.             try (InputStream in = getStream(SUPPORTED_NAME)) {
  625.                 loadData(in, SUPPORTED_NAME);
  626.             } catch (IOException e) {
  627.                 throw new OrekitException(OrekitMessages.INTERNAL_ERROR, e);
  628.             }

  629.             // Throw an exception if MODIP grid was not loaded properly
  630.             if (grid == null) {
  631.                 throw new OrekitException(OrekitMessages.MODIP_GRID_NOT_LOADED, SUPPORTED_NAME);
  632.             }
  633.         }

  634.         /**
  635.          * Load data from a stream.
  636.          * @param input input stream
  637.          * @param name name of the file
  638.          * @throws IOException if data can't be read
  639.          */
  640.         public void loadData(final InputStream input, final String name)
  641.             throws IOException {

  642.             // Grid size
  643.             final int size = 39;

  644.             // Initialize array
  645.             final double[][] array = new double[size][size];

  646.             // Open stream and parse data
  647.             int   lineNumber = 0;
  648.             String line      = null;
  649.             try (InputStreamReader isr = new InputStreamReader(input, StandardCharsets.UTF_8);
  650.                  BufferedReader    br = new BufferedReader(isr)) {

  651.                 for (line = br.readLine(); line != null; line = br.readLine()) {
  652.                     ++lineNumber;
  653.                     line = line.trim();

  654.                     // Read grid data
  655.                     if (line.length() > 0) {
  656.                         final String[] modip_line = SEPARATOR.split(line);
  657.                         for (int column = 0; column < modip_line.length; column++) {
  658.                             array[lineNumber - 1][column] = Double.valueOf(modip_line[column]);
  659.                         }
  660.                     }

  661.                 }

  662.             } catch (NumberFormatException nfe) {
  663.                 throw new OrekitException(OrekitMessages.UNABLE_TO_PARSE_LINE_IN_FILE,
  664.                                           lineNumber, name, line);
  665.             }

  666.             // Clone parsed grid
  667.             grid = array.clone();

  668.         }
  669.     }

  670.     /**
  671.      * Parser for CCIR files.
  672.      * <p>
  673.      * Numerical grid maps which describe the regular variation of the ionosphere.
  674.      * They are used to derive other variables such as critical frequencies and transmission factors.
  675.      * </p> <p>
  676.      * The coefficients correspond to low and high solar activity conditions.
  677.      * </p> <p>
  678.      * The CCIR file naming convention is ccirXX.asc where each XX means month + 10.
  679.      * </p> <p>
  680.      * Coefficients are store into tow arrays, F2 and Fm3. F2 coefficients are used for the computation
  681.      * of the F2 layer critical frequency. Fm3 for the computation of the F2 layer maximum usable frequency factor.
  682.      * The size of these two arrays is fixed and discussed into the section 2.5.3.2
  683.      * of the reference document.
  684.      * </p>
  685.      */
  686.     private static class CCIRLoader {

  687.         /** Default supported files name pattern. */
  688.         public static final String DEFAULT_SUPPORTED_NAME = "ccir**.asc";

  689.         /** Total number of F2 coefficients contained in the file. */
  690.         private static final int NUMBER_F2_COEFFICIENTS = 1976;

  691.         /** Rows number for F2 and Fm3 arrays. */
  692.         private static final int ROWS = 2;

  693.         /** Columns number for F2 array. */
  694.         private static final int TOTAL_COLUMNS_F2 = 76;

  695.         /** Columns number for Fm3 array. */
  696.         private static final int TOTAL_COLUMNS_FM3 = 49;

  697.         /** Depth of F2 array. */
  698.         private static final int DEPTH_F2 = 13;

  699.         /** Depth of Fm3 array. */
  700.         private static final int DEPTH_FM3 = 9;

  701.         /** Regular expression for supported file name. */
  702.         private String supportedName;

  703.         /** F2 coefficients used for the computation of the F2 layer critical frequency. */
  704.         private double[][][] f2Loader;

  705.         /** Fm3 coefficients used for the computation of the F2 layer maximum usable frequency factor. */
  706.         private double[][][] fm3Loader;

  707.         /**
  708.          * Build a new instance.
  709.          */
  710.         CCIRLoader() {
  711.             this.supportedName = DEFAULT_SUPPORTED_NAME;
  712.             this.f2Loader  = null;
  713.             this.fm3Loader = null;
  714.         }

  715.         /**
  716.          * Get the F2 coefficients used for the computation of the F2 layer critical frequency.
  717.          * @return the F2 coefficients
  718.          */
  719.         public double[][][] getF2() {
  720.             return f2Loader.clone();
  721.         }

  722.         /**
  723.          * Get the Fm3 coefficients used for the computation of the F2 layer maximum usable frequency factor.
  724.          * @return the F2 coefficients
  725.          */
  726.         public double[][][] getFm3() {
  727.             return fm3Loader.clone();
  728.         }

  729.         /** Load the data for a given month.
  730.          * @param dateComponents month given but its DateComponents
  731.          */
  732.         public void loadCCIRCoefficients(final DateComponents dateComponents) {

  733.             // The files are named ccirXX.asc where XX substitute the month of the year + 10
  734.             final int currentMonth = dateComponents.getMonth();
  735.             this.supportedName = NEQUICK_BASE + String.format("ccir%02d.asc", currentMonth + 10);
  736.             try (InputStream in = getStream(supportedName)) {
  737.                 loadData(in, supportedName);
  738.             } catch (IOException e) {
  739.                 throw new OrekitException(OrekitMessages.INTERNAL_ERROR, e);
  740.             }
  741.             // Throw an exception if F2 or Fm3 were not loaded properly
  742.             if (f2Loader == null || fm3Loader == null) {
  743.                 throw new OrekitException(OrekitMessages.NEQUICK_F2_FM3_NOT_LOADED, supportedName);
  744.             }

  745.         }

  746.         /**
  747.          * Load data from a stream.
  748.          * @param input input stream
  749.          * @param name name of the file
  750.          * @throws IOException if data can't be read
  751.          */
  752.         public void loadData(final InputStream input, final String name)
  753.             throws IOException {

  754.             // Initialize arrays
  755.             final double[][][] f2Temp  = new double[ROWS][TOTAL_COLUMNS_F2][DEPTH_F2];
  756.             final double[][][] fm3Temp = new double[ROWS][TOTAL_COLUMNS_FM3][DEPTH_FM3];

  757.             // Placeholders for parsed data
  758.             int    lineNumber       = 0;
  759.             int    index            = 0;
  760.             int    currentRowF2     = 0;
  761.             int    currentColumnF2  = 0;
  762.             int    currentDepthF2   = 0;
  763.             int    currentRowFm3    = 0;
  764.             int    currentColumnFm3 = 0;
  765.             int    currentDepthFm3  = 0;
  766.             String line             = null;

  767.             try (InputStreamReader isr = new InputStreamReader(input, StandardCharsets.UTF_8);
  768.                  BufferedReader    br = new BufferedReader(isr)) {

  769.                 for (line = br.readLine(); line != null; line = br.readLine()) {
  770.                     ++lineNumber;
  771.                     line = line.trim();

  772.                     // Read grid data
  773.                     if (line.length() > 0) {
  774.                         final String[] ccir_line = SEPARATOR.split(line);
  775.                         for (int i = 0; i < ccir_line.length; i++) {

  776.                             if (index < NUMBER_F2_COEFFICIENTS) {
  777.                                 // Parse F2 coefficients
  778.                                 if (currentDepthF2 >= DEPTH_F2 && currentColumnF2 < (TOTAL_COLUMNS_F2 - 1)) {
  779.                                     currentDepthF2 = 0;
  780.                                     currentColumnF2++;
  781.                                 } else if (currentDepthF2 >= DEPTH_F2 && currentColumnF2 >= (TOTAL_COLUMNS_F2 - 1)) {
  782.                                     currentDepthF2 = 0;
  783.                                     currentColumnF2 = 0;
  784.                                     currentRowF2++;
  785.                                 }
  786.                                 f2Temp[currentRowF2][currentColumnF2][currentDepthF2++] = Double.valueOf(ccir_line[i]);
  787.                                 index++;
  788.                             } else {
  789.                                 // Parse Fm3 coefficients
  790.                                 if (currentDepthFm3 >= DEPTH_FM3 && currentColumnFm3 < (TOTAL_COLUMNS_FM3 - 1)) {
  791.                                     currentDepthFm3 = 0;
  792.                                     currentColumnFm3++;
  793.                                 } else if (currentDepthFm3 >= DEPTH_FM3 && currentColumnFm3 >= (TOTAL_COLUMNS_FM3 - 1)) {
  794.                                     currentDepthFm3 = 0;
  795.                                     currentColumnFm3 = 0;
  796.                                     currentRowFm3++;
  797.                                 }
  798.                                 fm3Temp[currentRowFm3][currentColumnFm3][currentDepthFm3++] = Double.valueOf(ccir_line[i]);
  799.                                 index++;
  800.                             }

  801.                         }
  802.                     }

  803.                 }

  804.             } catch (NumberFormatException nfe) {
  805.                 throw new OrekitException(OrekitMessages.UNABLE_TO_PARSE_LINE_IN_FILE,
  806.                                           lineNumber, name, line);
  807.             }

  808.             f2Loader  = f2Temp.clone();
  809.             fm3Loader = fm3Temp.clone();

  810.         }

  811.     }

  812.     /**
  813.      * Container for ray-perigee parameters.
  814.      * By convention, point 1 is at lower height.
  815.      */
  816.     private static class Ray {

  817.         /** Threshold for ray-perigee parameters computation. */
  818.         private static final double THRESHOLD = 1.0e-10;

  819.         /** Distance of the first point from the ray perigee [m]. */
  820.         private final double s1;

  821.         /** Distance of the second point from the ray perigee [m]. */
  822.         private final double s2;

  823.         /** Ray-perigee radius [m]. */
  824.         private final double rp;

  825.         /** Ray-perigee latitude [rad]. */
  826.         private final double latP;

  827.         /** Ray-perigee longitude [rad]. */
  828.         private final double lonP;

  829.         /** Sine and cosine of ray-perigee latitude. */
  830.         private final SinCos scLatP;

  831.         /** Sine of azimuth of satellite as seen from ray-perigee. */
  832.         private final double sinAzP;

  833.         /** Cosine of azimuth of satellite as seen from ray-perigee. */
  834.         private final double cosAzP;

  835.         /**
  836.          * Constructor.
  837.          * @param recP receiver position
  838.          * @param satP satellite position
  839.          */
  840.         Ray(final GeodeticPoint recP, final GeodeticPoint satP) {

  841.             // Integration limits in meters (Eq. 140 and 141)
  842.             final double r1 = RE + recP.getAltitude();
  843.             final double r2 = RE + satP.getAltitude();

  844.             // Useful parameters
  845.             final double lat1     = recP.getLatitude();
  846.             final double lat2     = satP.getLatitude();
  847.             final double lon1     = recP.getLongitude();
  848.             final double lon2     = satP.getLongitude();
  849.             final SinCos scLatSat = FastMath.sinCos(lat2);
  850.             final SinCos scLatRec = FastMath.sinCos(lat1);
  851.             final SinCos scLon21  = FastMath.sinCos(lon2 - lon1);

  852.             // Zenith angle computation (Eq. 153 to 155)
  853.             final double cosD = scLatRec.sin() * scLatSat.sin() +
  854.                                 scLatRec.cos() * scLatSat.cos() * scLon21.cos();
  855.             final double sinD = FastMath.sqrt(1.0 - cosD * cosD);
  856.             final double z = FastMath.atan2(sinD, cosD - (r1 / r2));

  857.             // Ray-perigee computation in meters (Eq. 156)
  858.             this.rp = r1 * FastMath.sin(z);

  859.             // Ray-perigee latitude and longitude
  860.             if (FastMath.abs(FastMath.abs(lat1) - 0.5 * FastMath.PI) < THRESHOLD) {

  861.                 // Ray-perigee latitude (Eq. 157)
  862.                 if (lat1 < 0) {
  863.                     this.latP = -z;
  864.                 } else {
  865.                     this.latP = z;
  866.                 }

  867.                 // Ray-perigee longitude (Eq. 164)
  868.                 if (z < 0) {
  869.                     this.lonP = lon2;
  870.                 } else {
  871.                     this.lonP = lon2 + FastMath.PI;
  872.                 }

  873.             } else {

  874.                 // Ray-perigee latitude (Eq. 158 to 163)
  875.                 final double deltaP   = 0.5 * FastMath.PI - z;
  876.                 final SinCos scDeltaP = FastMath.sinCos(deltaP);
  877.                 final double sinAz    = scLon21.sin() * scLatSat.cos() / sinD;
  878.                 final double cosAz    = (scLatSat.sin() - cosD * scLatRec.sin()) / (sinD * scLatRec.cos());
  879.                 final double sinLatP  = scLatRec.sin() * scDeltaP.cos() - scLatRec.cos() * scDeltaP.sin() * cosAz;
  880.                 final double cosLatP  = FastMath.sqrt(1.0 - sinLatP * sinLatP);
  881.                 this.latP = FastMath.atan2(sinLatP, cosLatP);

  882.                 // Ray-perigee longitude (Eq. 165 to 167)
  883.                 final double sinLonP = -sinAz * scDeltaP.sin() / cosLatP;
  884.                 final double cosLonP = (scDeltaP.cos() - scLatRec.sin() * sinLatP) / (scLatRec.cos() * cosLatP);
  885.                 this.lonP = FastMath.atan2(sinLonP, cosLonP) + lon1;

  886.             }

  887.             // Sine and cosine of ray-perigee latitude
  888.             this.scLatP = FastMath.sinCos(latP);

  889.             final SinCos scLon = FastMath.sinCos(lon2 - lonP);
  890.             // Sine and cosine of azimuth of satellite as seen from ray-perigee
  891.             final double psi   = greatCircleAngle(scLatSat, scLon);
  892.             final SinCos scPsi = FastMath.sinCos(psi);
  893.             if (FastMath.abs(FastMath.abs(latP) - 0.5 * FastMath.PI) < THRESHOLD) {
  894.                 // Eq. 172 and 173
  895.                 this.sinAzP = 0.0;
  896.                 if (latP < 0.0) {
  897.                     this.cosAzP = 1;
  898.                 } else {
  899.                     this.cosAzP = -1;
  900.                 }
  901.             } else {
  902.                 // Eq. 174 and 175
  903.                 this.sinAzP =  scLatSat.cos() * scLon.sin()                 /  scPsi.sin();
  904.                 this.cosAzP = (scLatSat.sin() - scLatP.sin() * scPsi.cos()) / (scLatP.cos() * scPsi.sin());
  905.             }

  906.             // Integration en points s1 and s2 in meters (Eq. 176 and 177)
  907.             this.s1 = FastMath.sqrt(r1 * r1 - rp * rp);
  908.             this.s2 = FastMath.sqrt(r2 * r2 - rp * rp);
  909.         }

  910.         /**
  911.          * Get the distance of the first point from the ray perigee.
  912.          * @return s1 in meters
  913.          */
  914.         public double getS1() {
  915.             return s1;
  916.         }

  917.         /**
  918.          * Get the distance of the second point from the ray perigee.
  919.          * @return s2 in meters
  920.          */
  921.         public double getS2() {
  922.             return s2;
  923.         }

  924.         /**
  925.          * Get the ray-perigee radius.
  926.          * @return the ray-perigee radius in meters
  927.          */
  928.         public double getRadius() {
  929.             return rp;
  930.         }

  931.         /**
  932.          * Get the ray-perigee latitude.
  933.          * @return the ray-perigee latitude in radians
  934.          */
  935.         public double getLatitude() {
  936.             return latP;
  937.         }

  938.         /**
  939.          * Get the ray-perigee longitude.
  940.          * @return the ray-perigee longitude in radians
  941.          */
  942.         public double getLongitude() {
  943.             return lonP;
  944.         }

  945.         /**
  946.          * Get the sine of azimuth of satellite as seen from ray-perigee.
  947.          * @return the sine of azimuth
  948.          */
  949.         public double getSineAz() {
  950.             return sinAzP;
  951.         }

  952.         /**
  953.          * Get the cosine of azimuth of satellite as seen from ray-perigee.
  954.          * @return the cosine of azimuth
  955.          */
  956.         public double getCosineAz() {
  957.             return cosAzP;
  958.         }

  959.         /**
  960.          * Compute the great circle angle from ray-perigee to satellite.
  961.          * <p>
  962.          * This method used the equations 168 to 171 pf the reference document.
  963.          * </p>
  964.          * @param scLat sine and cosine of satellite latitude
  965.          * @param scLon sine and cosine of satellite longitude minus receiver longitude
  966.          * @return the great circle angle in radians
  967.          */
  968.         private double greatCircleAngle(final SinCos scLat, final SinCos scLon) {
  969.             if (FastMath.abs(FastMath.abs(latP) - 0.5 * FastMath.PI) < THRESHOLD) {
  970.                 return FastMath.abs(FastMath.asin(scLat.sin()) - latP);
  971.             } else {
  972.                 final double cosPhi = scLatP.sin() * scLat.sin() +
  973.                                       scLatP.cos() * scLat.cos() * scLon.cos();
  974.                 final double sinPhi = FastMath.sqrt(1.0 - cosPhi * cosPhi);
  975.                 return FastMath.atan2(sinPhi, cosPhi);
  976.             }
  977.         }
  978.     }

  979.     /**
  980.      * Container for ray-perigee parameters.
  981.      * By convention, point 1 is at lower height.
  982.      */
  983.     private static class FieldRay <T extends CalculusFieldElement<T>> {

  984.         /** Threshold for ray-perigee parameters computation. */
  985.         private static final double THRESHOLD = 1.0e-10;

  986.         /** Distance of the first point from the ray perigee [m]. */
  987.         private final T s1;

  988.         /** Distance of the second point from the ray perigee [m]. */
  989.         private final T s2;

  990.         /** Ray-perigee radius [m]. */
  991.         private final T rp;

  992.         /** Ray-perigee latitude [rad]. */
  993.         private final T latP;

  994.         /** Ray-perigee longitude [rad]. */
  995.         private final T lonP;

  996.         /** Sine and cosine of ray-perigee latitude. */
  997.         private final FieldSinCos<T> scLatP;

  998.         /** Sine of azimuth of satellite as seen from ray-perigee. */
  999.         private final T sinAzP;

  1000.         /** Cosine of azimuth of satellite as seen from ray-perigee. */
  1001.         private final T cosAzP;

  1002.         /**
  1003.          * Constructor.
  1004.          * @param field field of the elements
  1005.          * @param recP receiver position
  1006.          * @param satP satellite position
  1007.          */
  1008.         FieldRay(final Field<T> field, final FieldGeodeticPoint<T> recP, final FieldGeodeticPoint<T> satP) {

  1009.             // Integration limits in meters (Eq. 140 and 141)
  1010.             final T r1 = recP.getAltitude().add(RE);
  1011.             final T r2 = satP.getAltitude().add(RE);

  1012.             // Useful parameters
  1013.             final T pi   = r1.getPi();
  1014.             final T lat1 = recP.getLatitude();
  1015.             final T lat2 = satP.getLatitude();
  1016.             final T lon1 = recP.getLongitude();
  1017.             final T lon2 = satP.getLongitude();
  1018.             final FieldSinCos<T> scLatSat = FastMath.sinCos(lat2);
  1019.             final FieldSinCos<T> scLatRec = FastMath.sinCos(lat1);

  1020.             // Zenith angle computation (Eq. 153 to 155)
  1021.             final T cosD = scLatRec.sin().multiply(scLatSat.sin()).
  1022.                             add(scLatRec.cos().multiply(scLatSat.cos()).multiply(FastMath.cos(lon2.subtract(lon1))));
  1023.             final T sinD = FastMath.sqrt(cosD.multiply(cosD).negate().add(1.0));
  1024.             final T z = FastMath.atan2(sinD, cosD.subtract(r1.divide(r2)));

  1025.             // Ray-perigee computation in meters (Eq. 156)
  1026.             this.rp = r1.multiply(FastMath.sin(z));

  1027.             // Ray-perigee latitude and longitude
  1028.             if (FastMath.abs(FastMath.abs(lat1).subtract(pi.multiply(0.5)).getReal()) < THRESHOLD) {

  1029.                 // Ray-perigee latitude (Eq. 157)
  1030.                 if (lat1.getReal() < 0) {
  1031.                     this.latP = z.negate();
  1032.                 } else {
  1033.                     this.latP = z;
  1034.                 }

  1035.                 // Ray-perigee longitude (Eq. 164)
  1036.                 if (z.getReal() < 0) {
  1037.                     this.lonP = lon2;
  1038.                 } else {
  1039.                     this.lonP = lon2.add(pi);
  1040.                 }

  1041.             } else {

  1042.                 // Ray-perigee latitude (Eq. 158 to 163)
  1043.                 final T deltaP = z.negate().add(pi.multiply(0.5));
  1044.                 final FieldSinCos<T> scDeltaP = FastMath.sinCos(deltaP);
  1045.                 final T sinAz    = FastMath.sin(lon2.subtract(lon1)).multiply(scLatSat.cos()).divide(sinD);
  1046.                 final T cosAz    = scLatSat.sin().subtract(cosD.multiply(scLatRec.sin())).divide(sinD.multiply(scLatRec.cos()));
  1047.                 final T sinLatP  = scLatRec.sin().multiply(scDeltaP.cos()).subtract(scLatRec.cos().multiply(scDeltaP.sin()).multiply(cosAz));
  1048.                 final T cosLatP  = FastMath.sqrt(sinLatP.multiply(sinLatP).negate().add(1.0));
  1049.                 this.latP = FastMath.atan2(sinLatP, cosLatP);

  1050.                 // Ray-perigee longitude (Eq. 165 to 167)
  1051.                 final T sinLonP = sinAz.negate().multiply(scDeltaP.sin()).divide(cosLatP);
  1052.                 final T cosLonP = scDeltaP.cos().subtract(scLatRec.sin().multiply(sinLatP)).divide(scLatRec.cos().multiply(cosLatP));
  1053.                 this.lonP = FastMath.atan2(sinLonP, cosLonP).add(lon1);

  1054.             }

  1055.             // Sine and cosine of ray-perigee latitude
  1056.             this.scLatP = FastMath.sinCos(latP);

  1057.             final FieldSinCos<T> scLon = FastMath.sinCos(lon2.subtract(lonP));
  1058.             // Sine and cosie of azimuth of satellite as seen from ray-perigee
  1059.             final T psi = greatCircleAngle(scLatSat, scLon);
  1060.             final FieldSinCos<T> scPsi = FastMath.sinCos(psi);
  1061.             if (FastMath.abs(FastMath.abs(latP).subtract(pi.multiply(0.5)).getReal()) < THRESHOLD) {
  1062.                 // Eq. 172 and 173
  1063.                 this.sinAzP = field.getZero();
  1064.                 if (latP.getReal() < 0.0) {
  1065.                     this.cosAzP = field.getOne();
  1066.                 } else {
  1067.                     this.cosAzP = field.getOne().negate();
  1068.                 }
  1069.             } else {
  1070.                 // Eq. 174 and 175
  1071.                 this.sinAzP = scLatSat.cos().multiply(scLon.sin()).divide(scPsi.sin());
  1072.                 this.cosAzP = scLatSat.sin().subtract(scLatP.sin().multiply(scPsi.cos())).divide(scLatP.cos().multiply(scPsi.sin()));
  1073.             }

  1074.             // Integration en points s1 and s2 in meters (Eq. 176 and 177)
  1075.             this.s1 = FastMath.sqrt(r1.multiply(r1).subtract(rp.multiply(rp)));
  1076.             this.s2 = FastMath.sqrt(r2.multiply(r2).subtract(rp.multiply(rp)));
  1077.         }

  1078.         /**
  1079.          * Get the distance of the first point from the ray perigee.
  1080.          * @return s1 in meters
  1081.          */
  1082.         public T getS1() {
  1083.             return s1;
  1084.         }

  1085.         /**
  1086.          * Get the distance of the second point from the ray perigee.
  1087.          * @return s2 in meters
  1088.          */
  1089.         public T getS2() {
  1090.             return s2;
  1091.         }

  1092.         /**
  1093.          * Get the ray-perigee radius.
  1094.          * @return the ray-perigee radius in meters
  1095.          */
  1096.         public T getRadius() {
  1097.             return rp;
  1098.         }

  1099.         /**
  1100.          * Get the ray-perigee latitude.
  1101.          * @return the ray-perigee latitude in radians
  1102.          */
  1103.         public T getLatitude() {
  1104.             return latP;
  1105.         }

  1106.         /**
  1107.          * Get the ray-perigee longitude.
  1108.          * @return the ray-perigee longitude in radians
  1109.          */
  1110.         public T getLongitude() {
  1111.             return lonP;
  1112.         }

  1113.         /**
  1114.          * Get the sine of azimuth of satellite as seen from ray-perigee.
  1115.          * @return the sine of azimuth
  1116.          */
  1117.         public T getSineAz() {
  1118.             return sinAzP;
  1119.         }

  1120.         /**
  1121.          * Get the cosine of azimuth of satellite as seen from ray-perigee.
  1122.          * @return the cosine of azimuth
  1123.          */
  1124.         public T getCosineAz() {
  1125.             return cosAzP;
  1126.         }

  1127.         /**
  1128.          * Compute the great circle angle from ray-perigee to satellite.
  1129.          * <p>
  1130.          * This method used the equations 168 to 171 pf the reference document.
  1131.          * </p>
  1132.          * @param scLat sine and cosine of satellite latitude
  1133.          * @param scLon sine and cosine of satellite longitude minus receiver longitude
  1134.          * @return the great circle angle in radians
  1135.          */
  1136.         private T greatCircleAngle(final FieldSinCos<T> scLat, final FieldSinCos<T> scLon) {
  1137.             if (FastMath.abs(FastMath.abs(latP).getReal() - 0.5 * FastMath.PI) < THRESHOLD) {
  1138.                 return FastMath.abs(FastMath.asin(scLat.sin()).subtract(latP));
  1139.             } else {
  1140.                 final T cosPhi = scLatP.sin().multiply(scLat.sin()).add(
  1141.                                  scLatP.cos().multiply(scLat.cos()).multiply(scLon.cos()));
  1142.                 final T sinPhi = FastMath.sqrt(cosPhi.multiply(cosPhi).negate().add(1.0));
  1143.                 return FastMath.atan2(sinPhi, cosPhi);
  1144.             }
  1145.         }
  1146.     }

  1147.     /** Performs the computation of the coordinates along the integration path. */
  1148.     private static class Segment {

  1149.         /** Latitudes [rad]. */
  1150.         private final double[] latitudes;

  1151.         /** Longitudes [rad]. */
  1152.         private final double[] longitudes;

  1153.         /** Heights [m]. */
  1154.         private final double[] heights;

  1155.         /** Integration step [m]. */
  1156.         private final double deltaN;

  1157.         /**
  1158.          * Constructor.
  1159.          * @param n number of points used for the integration
  1160.          * @param ray ray-perigee parameters
  1161.          */
  1162.         Segment(final int n, final Ray ray) {
  1163.             // Integration en points
  1164.             final double s1 = ray.getS1();
  1165.             final double s2 = ray.getS2();

  1166.             // Integration step (Eq. 195)
  1167.             this.deltaN = (s2 - s1) / n;

  1168.             // Segments
  1169.             final double[] s = getSegments(n, s1, s2);

  1170.             // Useful parameters
  1171.             final double rp = ray.getRadius();
  1172.             final SinCos scLatP = FastMath.sinCos(ray.getLatitude());

  1173.             // Geodetic coordinates
  1174.             final int size = s.length;
  1175.             heights    = new double[size];
  1176.             latitudes  = new double[size];
  1177.             longitudes = new double[size];
  1178.             for (int i = 0; i < size; i++) {
  1179.                 // Heights (Eq. 178)
  1180.                 heights[i] = FastMath.sqrt(s[i] * s[i] + rp * rp) - RE;

  1181.                 // Great circle parameters (Eq. 179 to 181)
  1182.                 final double tanDs = s[i] / rp;
  1183.                 final double cosDs = 1.0 / FastMath.sqrt(1.0 + tanDs * tanDs);
  1184.                 final double sinDs = tanDs * cosDs;

  1185.                 // Latitude (Eq. 182 to 183)
  1186.                 final double sinLatS = scLatP.sin() * cosDs + scLatP.cos() * sinDs * ray.getCosineAz();
  1187.                 final double cosLatS = FastMath.sqrt(1.0 - sinLatS * sinLatS);
  1188.                 latitudes[i] = FastMath.atan2(sinLatS, cosLatS);

  1189.                 // Longitude (Eq. 184 to 187)
  1190.                 final double sinLonS = sinDs * ray.getSineAz() * scLatP.cos();
  1191.                 final double cosLonS = cosDs - scLatP.sin() * sinLatS;
  1192.                 longitudes[i] = FastMath.atan2(sinLonS, cosLonS) + ray.getLongitude();
  1193.             }
  1194.         }

  1195.         /**
  1196.          * Computes the distance of a point from the ray-perigee.
  1197.          * @param n number of points used for the integration
  1198.          * @param s1 lower boundary
  1199.          * @param s2 upper boundary
  1200.          * @return the distance of a point from the ray-perigee in km
  1201.          */
  1202.         private double[] getSegments(final int n, final double s1, final double s2) {
  1203.             // Eq. 196
  1204.             final double g = 0.5773502691896 * deltaN;
  1205.             // Eq. 197
  1206.             final double y = s1 + (deltaN - g) * 0.5;
  1207.             final double[] segments = new double[2 * n];
  1208.             int index = 0;
  1209.             for (int i = 0; i < n; i++) {
  1210.                 // Eq. 198
  1211.                 segments[index] = y + i * deltaN;
  1212.                 index++;
  1213.                 segments[index] = y + i * deltaN + g;
  1214.                 index++;
  1215.             }
  1216.             return segments;
  1217.         }

  1218.         /**
  1219.          * Get the latitudes of the coordinates along the integration path.
  1220.          * @return the latitudes in radians
  1221.          */
  1222.         public double[] getLatitudes() {
  1223.             return latitudes;
  1224.         }

  1225.         /**
  1226.          * Get the longitudes of the coordinates along the integration path.
  1227.          * @return the longitudes in radians
  1228.          */
  1229.         public double[] getLongitudes() {
  1230.             return longitudes;
  1231.         }

  1232.         /**
  1233.          * Get the heights of the coordinates along the integration path.
  1234.          * @return the heights in m
  1235.          */
  1236.         public double[] getHeights() {
  1237.             return heights;
  1238.         }

  1239.         /**
  1240.          * Get the integration step.
  1241.          * @return the integration step in meters
  1242.          */
  1243.         public double getInterval() {
  1244.             return deltaN;
  1245.         }
  1246.     }

  1247.     /** Performs the computation of the coordinates along the integration path. */
  1248.     private static class FieldSegment <T extends CalculusFieldElement<T>> {

  1249.         /** Latitudes [rad]. */
  1250.         private final T[] latitudes;

  1251.         /** Longitudes [rad]. */
  1252.         private final T[] longitudes;

  1253.         /** Heights [m]. */
  1254.         private final T[] heights;

  1255.         /** Integration step [m]. */
  1256.         private final T deltaN;

  1257.         /**
  1258.          * Constructor.
  1259.          * @param field field of the elements
  1260.          * @param n number of points used for the integration
  1261.          * @param ray ray-perigee parameters
  1262.          */
  1263.         FieldSegment(final Field<T> field, final int n, final FieldRay<T> ray) {
  1264.             // Integration en points
  1265.             final T s1 = ray.getS1();
  1266.             final T s2 = ray.getS2();

  1267.             // Integration step (Eq. 195)
  1268.             this.deltaN = s2.subtract(s1).divide(n);

  1269.             // Segments
  1270.             final T[] s = getSegments(field, n, s1, s2);

  1271.             // Useful parameters
  1272.             final T rp = ray.getRadius();
  1273.             final FieldSinCos<T> scLatP = FastMath.sinCos(ray.getLatitude());

  1274.             // Geodetic coordinates
  1275.             final int size = s.length;
  1276.             heights    = MathArrays.buildArray(field, size);
  1277.             latitudes  = MathArrays.buildArray(field, size);
  1278.             longitudes = MathArrays.buildArray(field, size);
  1279.             for (int i = 0; i < size; i++) {
  1280.                 // Heights (Eq. 178)
  1281.                 heights[i] = FastMath.sqrt(s[i].multiply(s[i]).add(rp.multiply(rp))).subtract(RE);

  1282.                 // Great circle parameters (Eq. 179 to 181)
  1283.                 final T tanDs = s[i].divide(rp);
  1284.                 final T cosDs = FastMath.sqrt(tanDs.multiply(tanDs).add(1.0)).reciprocal();
  1285.                 final T sinDs = tanDs.multiply(cosDs);

  1286.                 // Latitude (Eq. 182 to 183)
  1287.                 final T sinLatS = scLatP.sin().multiply(cosDs).add(scLatP.cos().multiply(sinDs).multiply(ray.getCosineAz()));
  1288.                 final T cosLatS = FastMath.sqrt(sinLatS.multiply(sinLatS).negate().add(1.0));
  1289.                 latitudes[i] = FastMath.atan2(sinLatS, cosLatS);

  1290.                 // Longitude (Eq. 184 to 187)
  1291.                 final T sinLonS = sinDs.multiply(ray.getSineAz()).multiply(scLatP.cos());
  1292.                 final T cosLonS = cosDs.subtract(scLatP.sin().multiply(sinLatS));
  1293.                 longitudes[i] = FastMath.atan2(sinLonS, cosLonS).add(ray.getLongitude());
  1294.             }
  1295.         }

  1296.         /**
  1297.          * Computes the distance of a point from the ray-perigee.
  1298.          * @param field field of the elements
  1299.          * @param n number of points used for the integration
  1300.          * @param s1 lower boundary
  1301.          * @param s2 upper boundary
  1302.          * @return the distance of a point from the ray-perigee in km
  1303.          */
  1304.         private T[] getSegments(final Field<T> field, final int n, final T s1, final T s2) {
  1305.             // Eq. 196
  1306.             final T g = deltaN.multiply(0.5773502691896);
  1307.             // Eq. 197
  1308.             final T y = s1.add(deltaN.subtract(g).multiply(0.5));
  1309.             final T[] segments = MathArrays.buildArray(field, 2 * n);
  1310.             int index = 0;
  1311.             for (int i = 0; i < n; i++) {
  1312.                 // Eq. 198
  1313.                 segments[index] = y.add(deltaN.multiply(i));
  1314.                 index++;
  1315.                 segments[index] = y.add(deltaN.multiply(i)).add(g);
  1316.                 index++;
  1317.             }
  1318.             return segments;
  1319.         }

  1320.         /**
  1321.          * Get the latitudes of the coordinates along the integration path.
  1322.          * @return the latitudes in radians
  1323.          */
  1324.         public T[] getLatitudes() {
  1325.             return latitudes;
  1326.         }

  1327.         /**
  1328.          * Get the longitudes of the coordinates along the integration path.
  1329.          * @return the longitudes in radians
  1330.          */
  1331.         public T[] getLongitudes() {
  1332.             return longitudes;
  1333.         }

  1334.         /**
  1335.          * Get the heights of the coordinates along the integration path.
  1336.          * @return the heights in m
  1337.          */
  1338.         public T[] getHeights() {
  1339.             return heights;
  1340.         }

  1341.         /**
  1342.          * Get the integration step.
  1343.          * @return the integration step in meters
  1344.          */
  1345.         public T getInterval() {
  1346.             return deltaN;
  1347.         }
  1348.     }

  1349. }