PotentialCoefficientsReader.java

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

  18. import java.io.IOException;
  19. import java.io.InputStream;
  20. import java.text.ParseException;
  21. import java.util.ArrayList;
  22. import java.util.Arrays;
  23. import java.util.List;

  24. import org.apache.commons.math3.util.FastMath;
  25. import org.apache.commons.math3.util.Precision;
  26. import org.orekit.data.DataLoader;
  27. import org.orekit.errors.OrekitException;
  28. import org.orekit.errors.OrekitMessages;

  29. /**This abstract class represents a Gravitational Potential Coefficients file reader.
  30.  *
  31.  * <p> As it exits many different coefficients models and containers this
  32.  *  interface represents all the methods that should be implemented by a reader.
  33.  *  The proper way to use this interface is to call the {@link GravityFieldFactory}
  34.  *  which will determine which reader to use with the selected potential
  35.  *  coefficients file.<p>
  36.  *
  37.  * @see GravityFieldFactory
  38.  * @author Fabien Maussion
  39.  */
  40. public abstract class PotentialCoefficientsReader implements DataLoader {

  41.     /** Maximal degree to parse. */
  42.     private int maxParseDegree;

  43.     /** Maximal order to parse. */
  44.     private int maxParseOrder;

  45.     /** Regular expression for supported files names. */
  46.     private final String supportedNames;

  47.     /** Allow missing coefficients in the input data. */
  48.     private final boolean missingCoefficientsAllowed;

  49.     /** Indicator for complete read. */
  50.     private boolean readComplete;

  51.     /** Central body reference radius. */
  52.     private double ae;

  53.     /** Central body attraction coefficient. */
  54.     private double mu;

  55.     /** Raw tesseral-sectorial coefficients matrix. */
  56.     private double[][] rawC;

  57.     /** Raw tesseral-sectorial coefficients matrix. */
  58.     private double[][] rawS;

  59.     /** Indicator for normalized raw coefficients. */
  60.     private boolean normalized;

  61.     /** Tide system. */
  62.     private TideSystem tideSystem;

  63.     /** Simple constructor.
  64.      * <p>Build an uninitialized reader.</p>
  65.      * @param supportedNames regular expression for supported files names
  66.      * @param missingCoefficientsAllowed allow missing coefficients in the input data
  67.      */
  68.     protected PotentialCoefficientsReader(final String supportedNames,
  69.                                           final boolean missingCoefficientsAllowed) {
  70.         this.supportedNames             = supportedNames;
  71.         this.missingCoefficientsAllowed = missingCoefficientsAllowed;
  72.         this.maxParseDegree             = Integer.MAX_VALUE;
  73.         this.maxParseOrder              = Integer.MAX_VALUE;
  74.         this.readComplete               = false;
  75.         this.ae                         = Double.NaN;
  76.         this.mu                         = Double.NaN;
  77.         this.rawC                       = null;
  78.         this.rawS                       = null;
  79.         this.normalized                 = false;
  80.         this.tideSystem                 = TideSystem.UNKNOWN;
  81.     }

  82.     /** Get the regular expression for supported files names.
  83.      * @return regular expression for supported files names
  84.      */
  85.     public String getSupportedNames() {
  86.         return supportedNames;
  87.     }

  88.     /** Check if missing coefficients are allowed in the input data.
  89.      * @return true if missing coefficients are allowed in the input data
  90.      */
  91.     public boolean missingCoefficientsAllowed() {
  92.         return missingCoefficientsAllowed;
  93.     }

  94.     /** Set the degree limit for the next file parsing.
  95.      * @param maxParseDegree maximal degree to parse (may be safely
  96.      * set to {@link Integer#MAX_VALUE} to parse all available coefficients)
  97.      * @since 6.0
  98.      */
  99.     public void setMaxParseDegree(final int maxParseDegree) {
  100.         this.maxParseDegree = maxParseDegree;
  101.     }

  102.     /** Get the degree limit for the next file parsing.
  103.      * @return degree limit for the next file parsing
  104.      * @since 6.0
  105.      */
  106.     public int getMaxParseDegree() {
  107.         return maxParseDegree;
  108.     }

  109.     /** Set the order limit for the next file parsing.
  110.      * @param maxParseOrder maximal order to parse (may be safely
  111.      * set to {@link Integer#MAX_VALUE} to parse all available coefficients)
  112.      * @since 6.0
  113.      */
  114.     public void setMaxParseOrder(final int maxParseOrder) {
  115.         this.maxParseOrder = maxParseOrder;
  116.     }

  117.     /** Get the order limit for the next file parsing.
  118.      * @return order limit for the next file parsing
  119.      * @since 6.0
  120.      */
  121.     public int getMaxParseOrder() {
  122.         return maxParseOrder;
  123.     }

  124.     /** {@inheritDoc} */
  125.     public boolean stillAcceptsData() {
  126.         return !(readComplete &&
  127.                  getMaxAvailableDegree() >= getMaxParseDegree() &&
  128.                  getMaxAvailableOrder()  >= getMaxParseOrder());
  129.     }

  130.     /** Set the indicator for completed read.
  131.      * @param readComplete if true, a gravity field has been completely read
  132.      */
  133.     protected void setReadComplete(final boolean readComplete) {
  134.         this.readComplete = readComplete;
  135.     }

  136.     /** Set the central body reference radius.
  137.      * @param ae central body reference radius
  138.      */
  139.     protected void setAe(final double ae) {
  140.         this.ae = ae;
  141.     }

  142.     /** Get the central body reference radius.
  143.      * @return central body reference radius
  144.      */
  145.     protected double getAe() {
  146.         return ae;
  147.     }

  148.     /** Set the central body attraction coefficient.
  149.      * @param mu central body attraction coefficient
  150.      */
  151.     protected void setMu(final double mu) {
  152.         this.mu = mu;
  153.     }

  154.     /** Get the central body attraction coefficient.
  155.      * @return central body attraction coefficient
  156.      */
  157.     protected double getMu() {
  158.         return mu;
  159.     }

  160.     /** Set the {@link TideSystem} used in the gravity field.
  161.      * @param tideSystem tide system used in the gravity field
  162.      */
  163.     protected void setTideSystem(final TideSystem tideSystem) {
  164.         this.tideSystem = tideSystem;
  165.     }

  166.     /** Get the {@link TideSystem} used in the gravity field.
  167.      * @return tide system used in the gravity field
  168.      */
  169.     protected TideSystem getTideSystem() {
  170.         return tideSystem;
  171.     }

  172.     /** Set the tesseral-sectorial coefficients matrix.
  173.      * @param rawNormalized if true, raw coefficients are normalized
  174.      * @param c raw tesseral-sectorial coefficients matrix
  175.      * (a reference to the array will be stored)
  176.      * @param s raw tesseral-sectorial coefficients matrix
  177.      * (a reference to the array will be stored)
  178.      * @param name name of the file (or zip entry)
  179.      * @exception OrekitException if a coefficient is missing
  180.      */
  181.     protected void setRawCoefficients(final boolean rawNormalized,
  182.                                       final double[][] c, final double[][] s,
  183.                                       final String name)
  184.         throws OrekitException {

  185.         // normalization indicator
  186.         normalized = rawNormalized;

  187.         // cosine part
  188.         for (int i = 0; i < c.length; ++i) {
  189.             for (int j = 0; j < c[i].length; ++j) {
  190.                 if (Double.isNaN(c[i][j])) {
  191.                     throw new OrekitException(OrekitMessages.MISSING_GRAVITY_FIELD_COEFFICIENT_IN_FILE,
  192.                                               'C', i, j, name);
  193.                 }
  194.             }
  195.         }
  196.         rawC = c;

  197.         // sine part
  198.         for (int i = 0; i < s.length; ++i) {
  199.             for (int j = 0; j < s[i].length; ++j) {
  200.                 if (Double.isNaN(s[i][j])) {
  201.                     throw new OrekitException(OrekitMessages.MISSING_GRAVITY_FIELD_COEFFICIENT_IN_FILE,
  202.                                               'S', i, j, name);
  203.                 }
  204.             }
  205.         }
  206.         rawS = s;

  207.     }

  208.     /** Set the normalized tesseral-sectorial coefficients matrix.
  209.      * @param normalizedS tesseral-sectorial coefficients matrix
  210.      * (a reference to the array will be stored, <em>and</em>
  211.      * the elements will be un-normalized in-place)
  212.      * @param name name of the file (or zip entry)
  213.      * @exception OrekitException if a coefficient is missing
  214.      */
  215.     protected void setNormalizedS(final double[][] normalizedS, final String name)
  216.         throws OrekitException {
  217.         final int degree = normalizedS.length - 1;
  218.         final int order  = normalizedS[degree].length - 1;
  219.         final double[][] factors = GravityFieldFactory.getUnnormalizationFactors(degree, order);
  220.         for (int i = 0; i < normalizedS.length; ++i) {
  221.             for (int j = 0; j < normalizedS[i].length; ++j) {
  222.                 normalizedS[i][j] *= factors[i][j];
  223.             }
  224.         }
  225.         setUnNormalizedS(normalizedS, name);
  226.     }

  227.     /** Set the un-normalized tesseral-sectorial coefficients matrix.
  228.      * @param unNormalizedS un-normalized tesseral-sectorial coefficients matrix
  229.      * (a reference to the array will be stored)
  230.      * @param name name of the file (or zip entry)
  231.      * @exception OrekitException if a coefficient is missing
  232.      */
  233.     protected void setUnNormalizedS(final double[][] unNormalizedS, final String name)
  234.         throws OrekitException {

  235.         for (int i = 0; i < unNormalizedS.length; ++i) {
  236.             for (int j = 0; j < unNormalizedS[i].length; ++j) {
  237.                 if (Double.isNaN(unNormalizedS[i][j])) {
  238.                     throw new OrekitException(OrekitMessages.MISSING_GRAVITY_FIELD_COEFFICIENT_IN_FILE,
  239.                                               'S', i, j, name);
  240.                 }
  241.             }
  242.         }

  243.         this.rawS = unNormalizedS;

  244.     }

  245.     /** Get the maximal degree available in the last file parsed.
  246.      * @return maximal degree available in the last file parsed
  247.      * @since 6.0
  248.      */
  249.     public int getMaxAvailableDegree() {
  250.         return rawC.length - 1;
  251.     }

  252.     /** Get the maximal order available in the last file parsed.
  253.      * @return maximal order available in the last file parsed
  254.      * @since 6.0
  255.      */
  256.     public int getMaxAvailableOrder() {
  257.         return rawC[rawC.length - 1].length - 1;
  258.     }

  259.     /** {@inheritDoc} */
  260.     public abstract void loadData(InputStream input, String name)
  261.         throws IOException, ParseException, OrekitException;

  262.     /** Get a provider for read spherical harmonics coefficients.
  263.      * @param wantNormalized if true, the provider will provide normalized coefficients,
  264.      * otherwise it will provide un-normalized coefficients
  265.      * @param degree maximal degree
  266.      * @param order maximal order
  267.      * @return a new provider
  268.      * @exception OrekitException if the requested maximal degree or order exceeds the
  269.      * available degree or order or if no gravity field has read yet
  270.      * @see #getConstantProvider(boolean, int, int)
  271.      * @since 6.0
  272.      */
  273.     public abstract RawSphericalHarmonicsProvider getProvider(boolean wantNormalized, int degree, int order)
  274.         throws OrekitException;

  275.     /** Get a time-independent provider for read spherical harmonics coefficients.
  276.      * @param wantNormalized if true, the raw provider must provide normalized coefficients,
  277.      * otherwise it will provide un-normalized coefficients
  278.      * @param degree maximal degree
  279.      * @param order maximal order
  280.      * @return a new provider, with no time-dependent parts
  281.      * @exception OrekitException if the requested maximal degree or order exceeds the
  282.      * available degree or order or if no gravity field has read yet
  283.      * @see #getProvider(boolean, int, int)
  284.      * @since 6.0
  285.      */
  286.     protected ConstantSphericalHarmonics getConstantProvider(final boolean wantNormalized,
  287.                                                              final int degree, final int order)
  288.         throws OrekitException {

  289.         if (!readComplete) {
  290.             throw new OrekitException(OrekitMessages.NO_GRAVITY_FIELD_DATA_LOADED);
  291.         }

  292.         if (degree >= rawC.length) {
  293.             throw new OrekitException(OrekitMessages.TOO_LARGE_DEGREE_FOR_GRAVITY_FIELD,
  294.                                       degree, rawC.length - 1);
  295.         }

  296.         if (order >= rawC[rawC.length - 1].length) {
  297.             throw new OrekitException(OrekitMessages.TOO_LARGE_ORDER_FOR_GRAVITY_FIELD,
  298.                                       order, rawC[rawC.length - 1].length);
  299.         }

  300.         // fix normalization
  301.         final double[][] truncatedC = buildTriangularArray(degree, order, 0.0);
  302.         final double[][] truncatedS = buildTriangularArray(degree, order, 0.0);
  303.         rescale(1.0, normalized, rawC, rawS, wantNormalized, truncatedC, truncatedS);

  304.         return new ConstantSphericalHarmonics(ae, mu, tideSystem, truncatedC, truncatedS);

  305.     }

  306.     /** Build a coefficients triangular array.
  307.      * @param degree array degree
  308.      * @param order array order
  309.      * @param value initial value to put in array elements
  310.      * @return built array
  311.      */
  312.     protected static double[][] buildTriangularArray(final int degree, final int order, final double value) {
  313.         final double[][] array = new double[degree + 1][];
  314.         for (int k = 0; k < array.length; ++k) {
  315.             array[k] = buildRow(k, order, value);
  316.         }
  317.         return array;
  318.     }

  319.     /** Build a coefficients row.
  320.      * @param degree row degree
  321.      * @param order row order
  322.      * @param value initial value to put in array elements
  323.      * @return built row
  324.      */
  325.     protected static double[] buildRow(final int degree, final int order, final double value) {
  326.         final double[] row = new double[FastMath.min(order, degree) + 1];
  327.         Arrays.fill(row, value);
  328.         return row;
  329.     }

  330.     /** Extend a list of lists of coefficients if needed.
  331.      * @param list list of lists of coefficients
  332.      * @param degree degree required to be present
  333.      * @param order order required to be present
  334.      * @param value initial value to put in list elements
  335.      */
  336.     protected void extendListOfLists(final List<List<Double>> list, final int degree, final int order,
  337.                                      final double value) {
  338.         for (int i = list.size(); i <= degree; ++i) {
  339.             list.add(new ArrayList<Double>());
  340.         }
  341.         final List<Double> listN = list.get(degree);
  342.         final Double v = Double.valueOf(value);
  343.         for (int j = listN.size(); j <= order; ++j) {
  344.             listN.add(v);
  345.         }
  346.     }

  347.     /** Convert a list of list into an array.
  348.      * @param list list of lists of coefficients
  349.      * @return a new array
  350.      */
  351.     protected double[][] toArray(final List<List<Double>> list) {
  352.         final double[][] array = new double[list.size()][];
  353.         for (int i = 0; i < array.length; ++i) {
  354.             array[i] = new double[list.get(i).size()];
  355.             for (int j = 0; j < array[i].length; ++j) {
  356.                 array[i][j] = list.get(i).get(j);
  357.             }
  358.         }
  359.         return array;
  360.     }

  361.     /** Parse a coefficient.
  362.      * @param field text field to parse
  363.      * @param list list where to put the coefficient
  364.      * @param i first index in the list
  365.      * @param j second index in the list
  366.      * @param cName name of the coefficient
  367.      * @param name name of the file
  368.      * @exception OrekitException if the coefficient is already set
  369.      */
  370.     protected void parseCoefficient(final String field, final List<List<Double>> list,
  371.                                     final int i, final int j,
  372.                                     final String cName, final String name)
  373.         throws OrekitException {
  374.         final double value    = Double.parseDouble(field.replace('D', 'E'));
  375.         final double oldValue = list.get(i).get(j);
  376.         if (Double.isNaN(oldValue) || Precision.equals(oldValue, 0.0, 1)) {
  377.             // the coefficient was not already initialized
  378.             list.get(i).set(j, value);
  379.         } else {
  380.             throw new OrekitException(OrekitMessages.DUPLICATED_GRAVITY_FIELD_COEFFICIENT_IN_FILE,
  381.                                       name, i, j, name);
  382.         }
  383.     }

  384.     /** Parse a coefficient.
  385.      * @param field text field to parse
  386.      * @param array array where to put the coefficient
  387.      * @param i first index in the list
  388.      * @param j second index in the list
  389.      * @param cName name of the coefficient
  390.      * @param name name of the file
  391.      * @exception OrekitException if the coefficient is already set
  392.      */
  393.     protected void parseCoefficient(final String field, final double[][] array,
  394.                                     final int i, final int j,
  395.                                     final String cName, final String name)
  396.         throws OrekitException {
  397.         final double value    = Double.parseDouble(field.replace('D', 'E'));
  398.         final double oldValue = array[i][j];
  399.         if (Double.isNaN(oldValue) || Precision.equals(oldValue, 0.0, 1)) {
  400.             // the coefficient was not already initialized
  401.             array[i][j] = value;
  402.         } else {
  403.             throw new OrekitException(OrekitMessages.DUPLICATED_GRAVITY_FIELD_COEFFICIENT_IN_FILE,
  404.                                       name, i, j, name);
  405.         }
  406.     }

  407.     /** Rescale coefficients arrays.
  408.      * @param scale general scaling factor to apply to all elements
  409.      * @param normalizedOrigin if true, the origin coefficients are normalized
  410.      * @param originC cosine part of the origina coefficients
  411.      * @param originS sine part of the origin coefficients
  412.      * @param wantNormalized if true, the rescaled coefficients must be normalized
  413.      * @param rescaledC cosine part of the rescaled coefficients to fill in (may be the originC array)
  414.      * @param rescaledS sine part of the rescaled coefficients to fill in (may be the originS array)
  415.      * @exception OrekitException if normalization/unnormalization fails because of an underflow
  416.      * due to too high degree/order
  417.      */
  418.     protected static void rescale(final double scale,
  419.                                   final boolean normalizedOrigin, final double[][] originC,
  420.                                   final double[][] originS, final boolean wantNormalized,
  421.                                   final double[][] rescaledC, final double[][] rescaledS)
  422.         throws OrekitException {

  423.         if (wantNormalized == normalizedOrigin) {
  424.             // apply only the general scaling factor
  425.             for (int i = 0; i < rescaledC.length; ++i) {
  426.                 final double[] rCi = rescaledC[i];
  427.                 final double[] rSi = rescaledS[i];
  428.                 final double[] oCi = originC[i];
  429.                 final double[] oSi = originS[i];
  430.                 for (int j = 0; j < rCi.length; ++j) {
  431.                     rCi[j] = oCi[j] * scale;
  432.                     rSi[j] = oSi[j] * scale;
  433.                 }
  434.             }
  435.         } else {

  436.             // we have to re-scale the coefficients
  437.             // (we use rescaledC.length - 1 for the order instead of rescaledC[rescaledC.length - 1].length - 1
  438.             //  because typically trend or pulsation arrays are irregular, some test cases have
  439.             //  order 2 elements at degree 2, but only order 1 elements for higher degrees for example)
  440.             final double[][] factors = GravityFieldFactory.getUnnormalizationFactors(rescaledC.length - 1,
  441.                                                                                      rescaledC.length - 1);

  442.             if (wantNormalized) {
  443.                 // normalize the coefficients
  444.                 for (int i = 0; i < rescaledC.length; ++i) {
  445.                     final double[] rCi = rescaledC[i];
  446.                     final double[] rSi = rescaledS[i];
  447.                     final double[] oCi = originC[i];
  448.                     final double[] oSi = originS[i];
  449.                     final double[] fi  = factors[i];
  450.                     for (int j = 0; j < rCi.length; ++j) {
  451.                         final double factor = scale / fi[j];
  452.                         rCi[j] = oCi[j] * factor;
  453.                         rSi[j] = oSi[j] * factor;
  454.                     }
  455.                 }
  456.             } else {
  457.                 // un-normalize the coefficients
  458.                 for (int i = 0; i < rescaledC.length; ++i) {
  459.                     final double[] rCi = rescaledC[i];
  460.                     final double[] rSi = rescaledS[i];
  461.                     final double[] oCi = originC[i];
  462.                     final double[] oSi = originS[i];
  463.                     final double[] fi  = factors[i];
  464.                     for (int j = 0; j < rCi.length; ++j) {
  465.                         final double factor = scale * fi[j];
  466.                         rCi[j] = oCi[j] * factor;
  467.                         rSi[j] = oSi[j] * factor;
  468.                     }
  469.                 }
  470.             }

  471.         }
  472.     }

  473. }