NeQuickModel.java

  1. /* Copyright 2002-2023 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.CalculusFieldElement;
  27. import org.hipparchus.Field;
  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. /**
  49.  * NeQuick ionospheric delay model.
  50.  *
  51.  * @author Bryan Cazabonne
  52.  *
  53.  * @see "European Union (2016). European GNSS (Galileo) Open Service-Ionospheric Correction
  54.  *       Algorithm for Galileo Single Frequency Users. 1.2."
  55.  *
  56.  * @since 10.1
  57.  */
  58. public class NeQuickModel implements IonosphericModel {

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

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

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

  65.     /** Meters to kilometers converter. */
  66.     private static final double M_TO_KM = 0.001;

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

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

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

  73.     /** MODIP grid. */
  74.     private final double[][] stModip;

  75.     /** Month used for loading CCIR coefficients. */
  76.     private int month;

  77.     /** F2 coefficients used by the F2 layer. */
  78.     private double[][][] f2;

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

  81.     /** UTC time scale. */
  82.     private final TimeScale utc;

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

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

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

  122.         // Reference body shape
  123.         final BodyShape ellipsoid = baseFrame.getParentShape();
  124.         // Satellite geodetic coordinates
  125.         final GeodeticPoint satPoint = ellipsoid.transform(state.getPosition(ellipsoid.getBodyFrame()), ellipsoid.getBodyFrame(), state.getDate());

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

  128.         // Ionospheric delay
  129.         final double factor = DELAY_FACTOR / (frequency * frequency);
  130.         return factor * tec;
  131.     }

  132.     @Override
  133.     public <T extends CalculusFieldElement<T>> T pathDelay(final FieldSpacecraftState<T> state, final TopocentricFrame baseFrame,
  134.                                                        final double frequency, final T[] parameters) {
  135.         // Date
  136.         final FieldAbsoluteDate<T> date = state.getDate();
  137.         // Point
  138.         final FieldGeodeticPoint<T> recPoint = baseFrame.getPoint(date.getField());


  139.         // Reference body shape
  140.         final BodyShape ellipsoid = baseFrame.getParentShape();
  141.         // Satellite geodetic coordinates
  142.         final FieldGeodeticPoint<T> satPoint = ellipsoid.transform(state.getPosition(ellipsoid.getBodyFrame()), ellipsoid.getBodyFrame(), state.getDate());

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

  145.         // Ionospheric delay
  146.         final double factor = DELAY_FACTOR / (frequency * frequency);
  147.         return tec.multiply(factor);
  148.     }

  149.     @Override
  150.     public List<ParameterDriver> getParametersDrivers() {
  151.         return Collections.emptyList();
  152.     }

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

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

  167.         // Load the correct CCIR file
  168.         final DateTimeComponents dateTime = date.getComponents(utc);
  169.         loadsIfNeeded(dateTime.getDate());

  170.         // Tolerance for the integration accuracy. Defined inside the reference document, section 2.5.8.1.
  171.         final double h1 = recP.getAltitude();
  172.         final double tolerance;
  173.         if (h1 < 1000000.0) {
  174.             tolerance = 0.001;
  175.         } else {
  176.             tolerance = 0.01;
  177.         }

  178.         // Integration
  179.         int n = 8;
  180.         final Segment seg1 = new Segment(n, ray);
  181.         double gn1 = stecIntegration(seg1, dateTime);
  182.         n *= 2;
  183.         final Segment seg2 = new Segment(n, ray);
  184.         double gn2 = stecIntegration(seg2, dateTime);

  185.         int count = 1;
  186.         while (FastMath.abs(gn2 - gn1) > tolerance * FastMath.abs(gn1) && count < 20) {
  187.             gn1 = gn2;
  188.             n *= 2;
  189.             final Segment seg = new Segment(n, ray);
  190.             gn2 = stecIntegration(seg, dateTime);
  191.             count += 1;
  192.         }

  193.         // If count > 20 the integration did not converge
  194.         if (count == 20) {
  195.             throw new OrekitException(OrekitMessages.STEC_INTEGRATION_DID_NOT_CONVERGE);
  196.         }

  197.         // Eq. 202
  198.         return (gn2 + ((gn2 - gn1) / 15.0)) * 1.0e-16;
  199.     }

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

  215.         // Field
  216.         final Field<T> field = date.getField();

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

  219.         // Load the correct CCIR file
  220.         final DateTimeComponents dateTime = date.getComponents(utc);
  221.         loadsIfNeeded(dateTime.getDate());

  222.         // Tolerance for the integration accuracy. Defined inside the reference document, section 2.5.8.1.
  223.         final T h1 = recP.getAltitude();
  224.         final double tolerance;
  225.         if (h1.getReal() < 1000000.0) {
  226.             tolerance = 0.001;
  227.         } else {
  228.             tolerance = 0.01;
  229.         }

  230.         // Integration
  231.         int n = 8;
  232.         final FieldSegment<T> seg1 = new FieldSegment<>(field, n, ray);
  233.         T gn1 = stecIntegration(field, seg1, dateTime);
  234.         n *= 2;
  235.         final FieldSegment<T> seg2 = new FieldSegment<>(field, n, ray);
  236.         T gn2 = stecIntegration(field, seg2, dateTime);

  237.         int count = 1;
  238.         while (FastMath.abs(gn2.subtract(gn1)).getReal() > FastMath.abs(gn1).multiply(tolerance).getReal() && count < 20) {
  239.             gn1 = gn2;
  240.             n *= 2;
  241.             final FieldSegment<T> seg = new FieldSegment<>(field, n, ray);
  242.             gn2 = stecIntegration(field, seg, dateTime);
  243.             count += 1;
  244.         }

  245.         // If count > 20 the integration did not converge
  246.         if (count == 20) {
  247.             throw new OrekitException(OrekitMessages.STEC_INTEGRATION_DID_NOT_CONVERGE);
  248.         }

  249.         // Eq. 202
  250.         return gn2.add(gn2.subtract(gn1).divide(15.0)).multiply(1.0e-16);
  251.     }

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

  263.         // Compute electron density
  264.         double density = 0.0;
  265.         for (int i = 0; i < heightS.length; i++) {
  266.             final NeQuickParameters parameters = new NeQuickParameters(dateTime, f2, fm3,
  267.                                                                        latitudeS[i], longitudeS[i],
  268.                                                                        alpha, stModip);
  269.             density += electronDensity(heightS[i], parameters);
  270.         }

  271.         return 0.5 * seg.getInterval() * density;
  272.     }

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

  288.         // Compute electron density
  289.         T density = field.getZero();
  290.         for (int i = 0; i < heightS.length; i++) {
  291.             final FieldNeQuickParameters<T> parameters = new FieldNeQuickParameters<>(field, dateTime, f2, fm3,
  292.                                                                                       latitudeS[i], longitudeS[i],
  293.                                                                                       alpha, stModip);
  294.             density = density.add(electronDensity(field, heightS[i], parameters));
  295.         }

  296.         return seg.getInterval().multiply(density).multiply(0.5);
  297.     }

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

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

  338.     /**
  339.      * Computes the electron density of the bottomside.
  340.      * @param h height in km
  341.      * @param parameters NeQuick model parameters
  342.      * @return the electron density N in m-3
  343.      */
  344.     private double bottomElectronDensity(final double h, final NeQuickParameters parameters) {

  345.         // Select the relevant B parameter for the current height (Eq. 109 and 110)
  346.         final double be;
  347.         if (h > parameters.getHmE()) {
  348.             be = parameters.getBETop();
  349.         } else {
  350.             be = parameters.getBEBot();
  351.         }
  352.         final double bf1;
  353.         if (h > parameters.getHmF1()) {
  354.             bf1 = parameters.getB1Top();
  355.         } else {
  356.             bf1 = parameters.getB1Bot();
  357.         }
  358.         final double bf2 = parameters.getB2Bot();

  359.         // Useful array of constants
  360.         final double[] ct = new double[] {
  361.             1.0 / bf2, 1.0 / bf1, 1.0 / be
  362.         };

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

  371.         // S coefficients
  372.         final double[] s = new double[3];
  373.         // Array of corrective terms
  374.         final double[] ds = new double[3];

  375.         // Layer amplitudes
  376.         final double[] amplitudes = parameters.getLayerAmplitudes();

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

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

  401.     /**
  402.      * Computes the electron density of the bottomside.
  403.      * @param <T> type of the elements
  404.      * @param field field of the elements
  405.      * @param h height in km
  406.      * @param parameters NeQuick model parameters
  407.      * @return the electron density N in m-3
  408.      */
  409.     private <T extends CalculusFieldElement<T>> T bottomElectronDensity(final Field<T> field,
  410.                                                                     final T h,
  411.                                                                     final FieldNeQuickParameters<T> parameters) {

  412.         // Zero and One
  413.         final T zero = field.getZero();
  414.         final T one  = field.getOne();

  415.         // Select the relevant B parameter for the current height (Eq. 109 and 110)
  416.         final T be;
  417.         if (h.getReal() > parameters.getHmE().getReal()) {
  418.             be = parameters.getBETop();
  419.         } else {
  420.             be = parameters.getBEBot();
  421.         }
  422.         final T bf1;
  423.         if (h.getReal() > parameters.getHmF1().getReal()) {
  424.             bf1 = parameters.getB1Top();
  425.         } else {
  426.             bf1 = parameters.getB1Bot();
  427.         }
  428.         final T bf2 = parameters.getB2Bot();

  429.         // Useful array of constants
  430.         final T[] ct = MathArrays.buildArray(field, 3);
  431.         ct[0] = bf2.reciprocal();
  432.         ct[1] = bf1.reciprocal();
  433.         ct[2] = be.reciprocal();

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

  442.         // S coefficients
  443.         final T[] s = MathArrays.buildArray(field, 3);
  444.         // Array of corrective terms
  445.         final T[] ds = MathArrays.buildArray(field, 3);

  446.         // Layer amplitudes
  447.         final T[] amplitudes = parameters.getLayerAmplitudes();

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

  460.         // Electron density
  461.         final T aNo = one.linearCombination(s[0], one, s[1], one, s[2], one);
  462.         if (h.getReal() >= 100) {
  463.             return aNo.multiply(DENSITY_FACTOR);
  464.         } else {
  465.             // Chapman parameters (Eq. 119 and 120)
  466.             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);
  467.             final T z  = h.subtract(100.0).multiply(0.1);
  468.             // Electron density (Eq. 121)
  469.             return aNo.multiply(clipExp(field, bc.multiply(z).add(clipExp(field, z.negate())).negate().add(1.0))).multiply(DENSITY_FACTOR);
  470.         }
  471.     }

  472.     /**
  473.      * Computes the electron density of the topside.
  474.      * @param h height in km
  475.      * @param parameters NeQuick model parameters
  476.      * @return the electron density N in m-3
  477.      */
  478.     private double topElectronDensity(final double h, final NeQuickParameters parameters) {

  479.         // Constant parameters (Eq. 122 and 123)
  480.         final double g = 0.125;
  481.         final double r = 100.0;

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

  485.         // Exponential (Eq. 126)
  486.         final double ee = clipExp(z);

  487.         // Electron density (Eq. 127)
  488.         if (ee > 1.0e11) {
  489.             return (4.0 * parameters.getNmF2() / ee) * DENSITY_FACTOR;
  490.         } else {
  491.             final double opExpZ = 1.0 + ee;
  492.             return ((4.0 * parameters.getNmF2() * ee) / (opExpZ * opExpZ)) * DENSITY_FACTOR;
  493.         }
  494.     }

  495.     /**
  496.      * Computes the electron density of the topside.
  497.      * @param <T> type of the elements
  498.      * @param field field of the elements
  499.      * @param h height in km
  500.      * @param parameters NeQuick model parameters
  501.      * @return the electron density N in m-3
  502.      */
  503.     private <T extends CalculusFieldElement<T>> T topElectronDensity(final Field<T> field,
  504.                                                                  final T h,
  505.                                                                  final FieldNeQuickParameters<T> parameters) {

  506.         // Constant parameters (Eq. 122 and 123)
  507.         final double g = 0.125;
  508.         final double r = 100.0;

  509.         // Arguments deltaH and z (Eq. 124 and 125)
  510.         final T deltaH = h.subtract(parameters.getHmF2());
  511.         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)));

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

  514.         // Electron density (Eq. 127)
  515.         if (ee.getReal() > 1.0e11) {
  516.             return parameters.getNmF2().multiply(4.0).divide(ee).multiply(DENSITY_FACTOR);
  517.         } else {
  518.             final T opExpZ = ee.add(field.getOne());
  519.             return parameters.getNmF2().multiply(4.0).multiply(ee).divide(opExpZ.multiply(opExpZ)).multiply(DENSITY_FACTOR);
  520.         }
  521.     }

  522.     /**
  523.      * Lazy loading of CCIR data.
  524.      * @param date current date components
  525.      */
  526.     private void loadsIfNeeded(final DateComponents date) {

  527.         // Current month
  528.         final int currentMonth = date.getMonth();

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

  532.             // Read file
  533.             final CCIRLoader loader = new CCIRLoader();
  534.             loader.loadCCIRCoefficients(date);

  535.             // Update arrays
  536.             this.f2 = loader.getF2();
  537.             this.fm3 = loader.getFm3();
  538.         }
  539.     }

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

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

  579.     /** Get a data stream.
  580.      * @param name file name of the resource stream
  581.      * @return stream
  582.      */
  583.     private static InputStream getStream(final String name) {
  584.         return NeQuickModel.class.getResourceAsStream(name);
  585.     }

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

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

  600.         /** MODIP grid. */
  601.         private double[][] grid;

  602.         /**
  603.          * Build a new instance.
  604.          */
  605.         MODIPLoader() {
  606.             this.grid = null;
  607.         }

  608.         /** Returns the MODIP grid array.
  609.          * @return the MODIP grid array
  610.          */
  611.         public double[][] getMODIPGrid() {
  612.             return grid.clone();
  613.         }

  614.         /**
  615.          * Load the data using supported names.
  616.          */
  617.         public void loadMODIPGrid() {
  618.             try (InputStream in = getStream(SUPPORTED_NAME)) {
  619.                 loadData(in, SUPPORTED_NAME);
  620.             } catch (IOException e) {
  621.                 throw new OrekitException(OrekitMessages.INTERNAL_ERROR, e);
  622.             }

  623.             // Throw an exception if MODIP grid was not loaded properly
  624.             if (grid == null) {
  625.                 throw new OrekitException(OrekitMessages.MODIP_GRID_NOT_LOADED, SUPPORTED_NAME);
  626.             }
  627.         }

  628.         /**
  629.          * Load data from a stream.
  630.          * @param input input stream
  631.          * @param name name of the file
  632.          * @throws IOException if data can't be read
  633.          */
  634.         public void loadData(final InputStream input, final String name)
  635.             throws IOException {

  636.             // Grid size
  637.             final int size = 39;

  638.             // Initialize array
  639.             final double[][] array = new double[size][size];

  640.             // Open stream and parse data
  641.             int   lineNumber = 0;
  642.             String line      = null;
  643.             try (InputStreamReader isr = new InputStreamReader(input, StandardCharsets.UTF_8);
  644.                  BufferedReader    br = new BufferedReader(isr)) {

  645.                 for (line = br.readLine(); line != null; line = br.readLine()) {
  646.                     ++lineNumber;
  647.                     line = line.trim();

  648.                     // Read grid data
  649.                     if (line.length() > 0) {
  650.                         final String[] modip_line = SEPARATOR.split(line);
  651.                         for (int column = 0; column < modip_line.length; column++) {
  652.                             array[lineNumber - 1][column] = Double.parseDouble(modip_line[column]);
  653.                         }
  654.                     }

  655.                 }

  656.             } catch (NumberFormatException nfe) {
  657.                 throw new OrekitException(OrekitMessages.UNABLE_TO_PARSE_LINE_IN_FILE,
  658.                                           lineNumber, name, line);
  659.             }

  660.             // Clone parsed grid
  661.             grid = array.clone();

  662.         }
  663.     }

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

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

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

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

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

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

  691.         /** Depth of F2 array. */
  692.         private static final int DEPTH_F2 = 13;

  693.         /** Depth of Fm3 array. */
  694.         private static final int DEPTH_FM3 = 9;

  695.         /** Regular expression for supported file name. */
  696.         private String supportedName;

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

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

  701.         /**
  702.          * Build a new instance.
  703.          */
  704.         CCIRLoader() {
  705.             this.supportedName = DEFAULT_SUPPORTED_NAME;
  706.             this.f2Loader  = null;
  707.             this.fm3Loader = null;
  708.         }

  709.         /**
  710.          * Get the F2 coefficients used for the computation of the F2 layer critical frequency.
  711.          * @return the F2 coefficients
  712.          */
  713.         public double[][][] getF2() {
  714.             return f2Loader.clone();
  715.         }

  716.         /**
  717.          * Get the Fm3 coefficients used for the computation of the F2 layer maximum usable frequency factor.
  718.          * @return the F2 coefficients
  719.          */
  720.         public double[][][] getFm3() {
  721.             return fm3Loader.clone();
  722.         }

  723.         /** Load the data for a given month.
  724.          * @param dateComponents month given but its DateComponents
  725.          */
  726.         public void loadCCIRCoefficients(final DateComponents dateComponents) {

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

  739.         }

  740.         /**
  741.          * Load data from a stream.
  742.          * @param input input stream
  743.          * @param name name of the file
  744.          * @throws IOException if data can't be read
  745.          */
  746.         public void loadData(final InputStream input, final String name)
  747.             throws IOException {

  748.             // Initialize arrays
  749.             final double[][][] f2Temp  = new double[ROWS][TOTAL_COLUMNS_F2][DEPTH_F2];
  750.             final double[][][] fm3Temp = new double[ROWS][TOTAL_COLUMNS_FM3][DEPTH_FM3];

  751.             // Placeholders for parsed data
  752.             int    lineNumber       = 0;
  753.             int    index            = 0;
  754.             int    currentRowF2     = 0;
  755.             int    currentColumnF2  = 0;
  756.             int    currentDepthF2   = 0;
  757.             int    currentRowFm3    = 0;
  758.             int    currentColumnFm3 = 0;
  759.             int    currentDepthFm3  = 0;
  760.             String line             = null;

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

  763.                 for (line = br.readLine(); line != null; line = br.readLine()) {
  764.                     ++lineNumber;
  765.                     line = line.trim();

  766.                     // Read grid data
  767.                     if (line.length() > 0) {
  768.                         final String[] ccir_line = SEPARATOR.split(line);
  769.                         for (int i = 0; i < ccir_line.length; i++) {

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

  795.                         }
  796.                     }

  797.                 }

  798.             } catch (NumberFormatException nfe) {
  799.                 throw new OrekitException(OrekitMessages.UNABLE_TO_PARSE_LINE_IN_FILE,
  800.                                           lineNumber, name, line);
  801.             }

  802.             f2Loader  = f2Temp.clone();
  803.             fm3Loader = fm3Temp.clone();

  804.         }

  805.     }

  806.     /**
  807.      * Container for ray-perigee parameters.
  808.      * By convention, point 1 is at lower height.
  809.      */
  810.     private static class Ray {

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

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

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

  817.         /** Ray-perigee radius [m]. */
  818.         private final double rp;

  819.         /** Ray-perigee latitude [rad]. */
  820.         private final double latP;

  821.         /** Ray-perigee longitude [rad]. */
  822.         private final double lonP;

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

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

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

  829.         /**
  830.          * Constructor.
  831.          * @param recP receiver position
  832.          * @param satP satellite position
  833.          */
  834.         Ray(final GeodeticPoint recP, final GeodeticPoint satP) {

  835.             // Integration limits in meters (Eq. 140 and 141)
  836.             final double r1 = RE + recP.getAltitude();
  837.             final double r2 = RE + satP.getAltitude();

  838.             // Useful parameters
  839.             final double lat1     = recP.getLatitude();
  840.             final double lat2     = satP.getLatitude();
  841.             final double lon1     = recP.getLongitude();
  842.             final double lon2     = satP.getLongitude();
  843.             final SinCos scLatSat = FastMath.sinCos(lat2);
  844.             final SinCos scLatRec = FastMath.sinCos(lat1);
  845.             final SinCos scLon21  = FastMath.sinCos(lon2 - lon1);

  846.             // Zenith angle computation (Eq. 153 to 155)
  847.             final double cosD = scLatRec.sin() * scLatSat.sin() +
  848.                                 scLatRec.cos() * scLatSat.cos() * scLon21.cos();
  849.             final double sinD = FastMath.sqrt(1.0 - cosD * cosD);
  850.             final double z = FastMath.atan2(sinD, cosD - (r1 / r2));

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

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

  855.                 // Ray-perigee latitude (Eq. 157)
  856.                 if (lat1 < 0) {
  857.                     this.latP = -z;
  858.                 } else {
  859.                     this.latP = z;
  860.                 }

  861.                 // Ray-perigee longitude (Eq. 164)
  862.                 if (z < 0) {
  863.                     this.lonP = lon2;
  864.                 } else {
  865.                     this.lonP = lon2 + FastMath.PI;
  866.                 }

  867.             } else {

  868.                 // Ray-perigee latitude (Eq. 158 to 163)
  869.                 final double deltaP   = 0.5 * FastMath.PI - z;
  870.                 final SinCos scDeltaP = FastMath.sinCos(deltaP);
  871.                 final double sinAz    = scLon21.sin() * scLatSat.cos() / sinD;
  872.                 final double cosAz    = (scLatSat.sin() - cosD * scLatRec.sin()) / (sinD * scLatRec.cos());
  873.                 final double sinLatP  = scLatRec.sin() * scDeltaP.cos() - scLatRec.cos() * scDeltaP.sin() * cosAz;
  874.                 final double cosLatP  = FastMath.sqrt(1.0 - sinLatP * sinLatP);
  875.                 this.latP = FastMath.atan2(sinLatP, cosLatP);

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

  880.             }

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

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

  900.             // Integration en points s1 and s2 in meters (Eq. 176 and 177)
  901.             this.s1 = FastMath.sqrt(r1 * r1 - rp * rp);
  902.             this.s2 = FastMath.sqrt(r2 * r2 - rp * rp);
  903.         }

  904.         /**
  905.          * Get the distance of the first point from the ray perigee.
  906.          * @return s1 in meters
  907.          */
  908.         public double getS1() {
  909.             return s1;
  910.         }

  911.         /**
  912.          * Get the distance of the second point from the ray perigee.
  913.          * @return s2 in meters
  914.          */
  915.         public double getS2() {
  916.             return s2;
  917.         }

  918.         /**
  919.          * Get the ray-perigee radius.
  920.          * @return the ray-perigee radius in meters
  921.          */
  922.         public double getRadius() {
  923.             return rp;
  924.         }

  925.         /**
  926.          * Get the ray-perigee latitude.
  927.          * @return the ray-perigee latitude in radians
  928.          */
  929.         public double getLatitude() {
  930.             return latP;
  931.         }

  932.         /**
  933.          * Get the ray-perigee longitude.
  934.          * @return the ray-perigee longitude in radians
  935.          */
  936.         public double getLongitude() {
  937.             return lonP;
  938.         }

  939.         /**
  940.          * Get the sine of azimuth of satellite as seen from ray-perigee.
  941.          * @return the sine of azimuth
  942.          */
  943.         public double getSineAz() {
  944.             return sinAzP;
  945.         }

  946.         /**
  947.          * Get the cosine of azimuth of satellite as seen from ray-perigee.
  948.          * @return the cosine of azimuth
  949.          */
  950.         public double getCosineAz() {
  951.             return cosAzP;
  952.         }

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

  973.     /**
  974.      * Container for ray-perigee parameters.
  975.      * By convention, point 1 is at lower height.
  976.      */
  977.     private static class FieldRay <T extends CalculusFieldElement<T>> {

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

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

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

  984.         /** Ray-perigee radius [m]. */
  985.         private final T rp;

  986.         /** Ray-perigee latitude [rad]. */
  987.         private final T latP;

  988.         /** Ray-perigee longitude [rad]. */
  989.         private final T lonP;

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

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

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

  996.         /**
  997.          * Constructor.
  998.          * @param field field of the elements
  999.          * @param recP receiver position
  1000.          * @param satP satellite position
  1001.          */
  1002.         FieldRay(final Field<T> field, final FieldGeodeticPoint<T> recP, final FieldGeodeticPoint<T> satP) {

  1003.             // Integration limits in meters (Eq. 140 and 141)
  1004.             final T r1 = recP.getAltitude().add(RE);
  1005.             final T r2 = satP.getAltitude().add(RE);

  1006.             // Useful parameters
  1007.             final T pi   = r1.getPi();
  1008.             final T lat1 = recP.getLatitude();
  1009.             final T lat2 = satP.getLatitude();
  1010.             final T lon1 = recP.getLongitude();
  1011.             final T lon2 = satP.getLongitude();
  1012.             final FieldSinCos<T> scLatSat = FastMath.sinCos(lat2);
  1013.             final FieldSinCos<T> scLatRec = FastMath.sinCos(lat1);

  1014.             // Zenith angle computation (Eq. 153 to 155)
  1015.             final T cosD = scLatRec.sin().multiply(scLatSat.sin()).
  1016.                             add(scLatRec.cos().multiply(scLatSat.cos()).multiply(FastMath.cos(lon2.subtract(lon1))));
  1017.             final T sinD = FastMath.sqrt(cosD.multiply(cosD).negate().add(1.0));
  1018.             final T z = FastMath.atan2(sinD, cosD.subtract(r1.divide(r2)));

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

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

  1023.                 // Ray-perigee latitude (Eq. 157)
  1024.                 if (lat1.getReal() < 0) {
  1025.                     this.latP = z.negate();
  1026.                 } else {
  1027.                     this.latP = z;
  1028.                 }

  1029.                 // Ray-perigee longitude (Eq. 164)
  1030.                 if (z.getReal() < 0) {
  1031.                     this.lonP = lon2;
  1032.                 } else {
  1033.                     this.lonP = lon2.add(pi);
  1034.                 }

  1035.             } else {

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

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

  1048.             }

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

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

  1068.             // Integration en points s1 and s2 in meters (Eq. 176 and 177)
  1069.             this.s1 = FastMath.sqrt(r1.multiply(r1).subtract(rp.multiply(rp)));
  1070.             this.s2 = FastMath.sqrt(r2.multiply(r2).subtract(rp.multiply(rp)));
  1071.         }

  1072.         /**
  1073.          * Get the distance of the first point from the ray perigee.
  1074.          * @return s1 in meters
  1075.          */
  1076.         public T getS1() {
  1077.             return s1;
  1078.         }

  1079.         /**
  1080.          * Get the distance of the second point from the ray perigee.
  1081.          * @return s2 in meters
  1082.          */
  1083.         public T getS2() {
  1084.             return s2;
  1085.         }

  1086.         /**
  1087.          * Get the ray-perigee radius.
  1088.          * @return the ray-perigee radius in meters
  1089.          */
  1090.         public T getRadius() {
  1091.             return rp;
  1092.         }

  1093.         /**
  1094.          * Get the ray-perigee latitude.
  1095.          * @return the ray-perigee latitude in radians
  1096.          */
  1097.         public T getLatitude() {
  1098.             return latP;
  1099.         }

  1100.         /**
  1101.          * Get the ray-perigee longitude.
  1102.          * @return the ray-perigee longitude in radians
  1103.          */
  1104.         public T getLongitude() {
  1105.             return lonP;
  1106.         }

  1107.         /**
  1108.          * Get the sine of azimuth of satellite as seen from ray-perigee.
  1109.          * @return the sine of azimuth
  1110.          */
  1111.         public T getSineAz() {
  1112.             return sinAzP;
  1113.         }

  1114.         /**
  1115.          * Get the cosine of azimuth of satellite as seen from ray-perigee.
  1116.          * @return the cosine of azimuth
  1117.          */
  1118.         public T getCosineAz() {
  1119.             return cosAzP;
  1120.         }

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

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

  1143.         /** Latitudes [rad]. */
  1144.         private final double[] latitudes;

  1145.         /** Longitudes [rad]. */
  1146.         private final double[] longitudes;

  1147.         /** Heights [m]. */
  1148.         private final double[] heights;

  1149.         /** Integration step [m]. */
  1150.         private final double deltaN;

  1151.         /**
  1152.          * Constructor.
  1153.          * @param n number of points used for the integration
  1154.          * @param ray ray-perigee parameters
  1155.          */
  1156.         Segment(final int n, final Ray ray) {
  1157.             // Integration en points
  1158.             final double s1 = ray.getS1();
  1159.             final double s2 = ray.getS2();

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

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

  1164.             // Useful parameters
  1165.             final double rp = ray.getRadius();
  1166.             final SinCos scLatP = FastMath.sinCos(ray.getLatitude());

  1167.             // Geodetic coordinates
  1168.             final int size = s.length;
  1169.             heights    = new double[size];
  1170.             latitudes  = new double[size];
  1171.             longitudes = new double[size];
  1172.             for (int i = 0; i < size; i++) {
  1173.                 // Heights (Eq. 178)
  1174.                 heights[i] = FastMath.sqrt(s[i] * s[i] + rp * rp) - RE;

  1175.                 // Great circle parameters (Eq. 179 to 181)
  1176.                 final double tanDs = s[i] / rp;
  1177.                 final double cosDs = 1.0 / FastMath.sqrt(1.0 + tanDs * tanDs);
  1178.                 final double sinDs = tanDs * cosDs;

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

  1183.                 // Longitude (Eq. 184 to 187)
  1184.                 final double sinLonS = sinDs * ray.getSineAz() * scLatP.cos();
  1185.                 final double cosLonS = cosDs - scLatP.sin() * sinLatS;
  1186.                 longitudes[i] = FastMath.atan2(sinLonS, cosLonS) + ray.getLongitude();
  1187.             }
  1188.         }

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

  1212.         /**
  1213.          * Get the latitudes of the coordinates along the integration path.
  1214.          * @return the latitudes in radians
  1215.          */
  1216.         public double[] getLatitudes() {
  1217.             return latitudes;
  1218.         }

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

  1226.         /**
  1227.          * Get the heights of the coordinates along the integration path.
  1228.          * @return the heights in m
  1229.          */
  1230.         public double[] getHeights() {
  1231.             return heights;
  1232.         }

  1233.         /**
  1234.          * Get the integration step.
  1235.          * @return the integration step in meters
  1236.          */
  1237.         public double getInterval() {
  1238.             return deltaN;
  1239.         }
  1240.     }

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

  1243.         /** Latitudes [rad]. */
  1244.         private final T[] latitudes;

  1245.         /** Longitudes [rad]. */
  1246.         private final T[] longitudes;

  1247.         /** Heights [m]. */
  1248.         private final T[] heights;

  1249.         /** Integration step [m]. */
  1250.         private final T deltaN;

  1251.         /**
  1252.          * Constructor.
  1253.          * @param field field of the elements
  1254.          * @param n number of points used for the integration
  1255.          * @param ray ray-perigee parameters
  1256.          */
  1257.         FieldSegment(final Field<T> field, final int n, final FieldRay<T> ray) {
  1258.             // Integration en points
  1259.             final T s1 = ray.getS1();
  1260.             final T s2 = ray.getS2();

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

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

  1265.             // Useful parameters
  1266.             final T rp = ray.getRadius();
  1267.             final FieldSinCos<T> scLatP = FastMath.sinCos(ray.getLatitude());

  1268.             // Geodetic coordinates
  1269.             final int size = s.length;
  1270.             heights    = MathArrays.buildArray(field, size);
  1271.             latitudes  = MathArrays.buildArray(field, size);
  1272.             longitudes = MathArrays.buildArray(field, size);
  1273.             for (int i = 0; i < size; i++) {
  1274.                 // Heights (Eq. 178)
  1275.                 heights[i] = FastMath.sqrt(s[i].multiply(s[i]).add(rp.multiply(rp))).subtract(RE);

  1276.                 // Great circle parameters (Eq. 179 to 181)
  1277.                 final T tanDs = s[i].divide(rp);
  1278.                 final T cosDs = FastMath.sqrt(tanDs.multiply(tanDs).add(1.0)).reciprocal();
  1279.                 final T sinDs = tanDs.multiply(cosDs);

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

  1284.                 // Longitude (Eq. 184 to 187)
  1285.                 final T sinLonS = sinDs.multiply(ray.getSineAz()).multiply(scLatP.cos());
  1286.                 final T cosLonS = cosDs.subtract(scLatP.sin().multiply(sinLatS));
  1287.                 longitudes[i] = FastMath.atan2(sinLonS, cosLonS).add(ray.getLongitude());
  1288.             }
  1289.         }

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

  1314.         /**
  1315.          * Get the latitudes of the coordinates along the integration path.
  1316.          * @return the latitudes in radians
  1317.          */
  1318.         public T[] getLatitudes() {
  1319.             return latitudes;
  1320.         }

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

  1328.         /**
  1329.          * Get the heights of the coordinates along the integration path.
  1330.          * @return the heights in m
  1331.          */
  1332.         public T[] getHeights() {
  1333.             return heights;
  1334.         }

  1335.         /**
  1336.          * Get the integration step.
  1337.          * @return the integration step in meters
  1338.          */
  1339.         public T getInterval() {
  1340.             return deltaN;
  1341.         }
  1342.     }

  1343. }