SHMFormatReader.java

  1. /* Copyright 2002-2020 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.forces.gravity.potential;

  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.text.ParseException;
  24. import java.util.ArrayList;
  25. import java.util.List;
  26. import java.util.Locale;
  27. import java.util.regex.Pattern;

  28. import org.hipparchus.util.FastMath;
  29. import org.hipparchus.util.Precision;
  30. import org.orekit.annotation.DefaultDataContext;
  31. import org.orekit.data.DataContext;
  32. import org.orekit.errors.OrekitException;
  33. import org.orekit.errors.OrekitMessages;
  34. import org.orekit.time.AbsoluteDate;
  35. import org.orekit.time.DateComponents;
  36. import org.orekit.time.TimeScale;
  37. import org.orekit.utils.Constants;

  38. /** Reader for the SHM gravity field format.
  39.  *
  40.  * <p> This format was used to describe the gravity field of EIGEN models
  41.  * published by the GFZ Potsdam up to 2003. It was then replaced by
  42.  * {@link ICGEMFormatReader ICGEM format}. The SHM format is described in
  43.  * <a href="http://op.gfz-potsdam.de/champ/docs_CHAMP/CH-FORMAT-REFLINKS.html"> Potsdam university
  44.  * website</a>.
  45.  *
  46.  * <p> The proper way to use this class is to call the {@link GravityFieldFactory}
  47.  *  which will determine which reader to use with the selected gravity field file.</p>
  48.  *
  49.  * @see GravityFields
  50.  * @author Fabien Maussion
  51.  */
  52. public class SHMFormatReader extends PotentialCoefficientsReader {

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

  55.     /** First field labels. */
  56.     private static final String GRCOEF = "GRCOEF";

  57.     /** Second field labels. */
  58.     private static final String GRCOF2 = "GRCOF2";

  59.     /** Drift coefficients labels. */
  60.     private static final String GRDOTA = "GRDOTA";

  61.     /** Reference date. */
  62.     private AbsoluteDate referenceDate;

  63.     /** Secular drift of the cosine coefficients. */
  64.     private final List<List<Double>> cDot;

  65.     /** Secular drift of the sine coefficients. */
  66.     private final List<List<Double>> sDot;

  67.     /** Simple constructor.
  68.      *
  69.      * <p>This constructor uses the {@link DataContext#getDefault() default data context}.
  70.      *
  71.      * @param supportedNames regular expression for supported files names
  72.      * @param missingCoefficientsAllowed if true, allows missing coefficients in the input data
  73.      * @see #SHMFormatReader(String, boolean, TimeScale)
  74.      */
  75.     @DefaultDataContext
  76.     public SHMFormatReader(final String supportedNames, final boolean missingCoefficientsAllowed) {
  77.         this(supportedNames, missingCoefficientsAllowed,
  78.                 DataContext.getDefault().getTimeScales().getTT());
  79.     }

  80.     /** Simple constructor.
  81.      * @param supportedNames regular expression for supported files names
  82.      * @param missingCoefficientsAllowed if true, allows missing coefficients in the input data
  83.      * @param timeScale for parsing dates.
  84.      * @since 10.1
  85.      */
  86.     public SHMFormatReader(final String supportedNames,
  87.                            final boolean missingCoefficientsAllowed,
  88.                            final TimeScale timeScale) {
  89.         super(supportedNames, missingCoefficientsAllowed, timeScale);
  90.         referenceDate = null;
  91.         cDot = new ArrayList<>();
  92.         sDot = new ArrayList<>();
  93.     }

  94.     /** {@inheritDoc} */
  95.     public void loadData(final InputStream input, final String name)
  96.         throws IOException, ParseException, OrekitException {

  97.         // reset the indicator before loading any data
  98.         setReadComplete(false);
  99.         referenceDate = null;
  100.         cDot.clear();
  101.         sDot.clear();

  102.         boolean    normalized = false;
  103.         TideSystem tideSystem = TideSystem.UNKNOWN;

  104.         boolean okEarth  = false;
  105.         boolean okSHM    = false;
  106.         boolean okCoeffs = false;
  107.         double[][] c     = null;
  108.         double[][] s     = null;
  109.         String line      = null;
  110.         int lineNumber   = 1;
  111.         try (BufferedReader r = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8))) {
  112.             line = r.readLine();
  113.             if ((line != null) &&
  114.                 "FIRST ".equals(line.substring(0, 6)) &&
  115.                 "SHM    ".equals(line.substring(49, 56))) {
  116.                 for (line = r.readLine(); line != null; line = r.readLine()) {
  117.                     lineNumber++;
  118.                     if (line.length() >= 6) {
  119.                         final String[] tab = SEPARATOR.split(line);

  120.                         // read the earth values
  121.                         if ("EARTH".equals(tab[0])) {
  122.                             setMu(parseDouble(tab[1]));
  123.                             setAe(parseDouble(tab[2]));
  124.                             okEarth = true;
  125.                         }

  126.                         // initialize the arrays
  127.                         if ("SHM".equals(tab[0])) {

  128.                             final int degree = FastMath.min(getMaxParseDegree(), Integer.parseInt(tab[1]));
  129.                             final int order  = FastMath.min(getMaxParseOrder(), degree);
  130.                             c = buildTriangularArray(degree, order, missingCoefficientsAllowed() ? 0.0 : Double.NaN);
  131.                             s = buildTriangularArray(degree, order, missingCoefficientsAllowed() ? 0.0 : Double.NaN);
  132.                             final String lowerCaseLine = line.toLowerCase(Locale.US);
  133.                             normalized = lowerCaseLine.contains("fully normalized");
  134.                             if (lowerCaseLine.contains("exclusive permanent tide")) {
  135.                                 tideSystem = TideSystem.TIDE_FREE;
  136.                             } else {
  137.                                 tideSystem = TideSystem.UNKNOWN;
  138.                             }
  139.                             okSHM = true;
  140.                         }

  141.                         // fill the arrays
  142.                         if (GRCOEF.equals(line.substring(0, 6)) || GRCOF2.equals(tab[0]) || GRDOTA.equals(tab[0])) {
  143.                             final int i = Integer.parseInt(tab[1]);
  144.                             final int j = Integer.parseInt(tab[2]);
  145.                             if (i < c.length && j < c[i].length) {
  146.                                 if (GRDOTA.equals(tab[0])) {

  147.                                     // store the secular drift coefficients
  148.                                     extendListOfLists(cDot, i, j, 0.0);
  149.                                     extendListOfLists(sDot, i, j, 0.0);
  150.                                     parseCoefficient(tab[3], cDot, i, j, "Cdot", name);
  151.                                     parseCoefficient(tab[4], sDot, i, j, "Sdot", name);

  152.                                     // check the reference date (format yyyymmdd)
  153.                                     final DateComponents localRef = new DateComponents(Integer.parseInt(tab[7].substring(0, 4)),
  154.                                                                                        Integer.parseInt(tab[7].substring(4, 6)),
  155.                                                                                        Integer.parseInt(tab[7].substring(6, 8)));
  156.                                     if (referenceDate == null) {
  157.                                         // first reference found, store it
  158.                                         referenceDate = toDate(localRef);
  159.                                     } else if (!referenceDate.equals(toDate(localRef))) {
  160.                                         throw new OrekitException(OrekitMessages.SEVERAL_REFERENCE_DATES_IN_GRAVITY_FIELD,
  161.                                                                   referenceDate, toDate(localRef), name);
  162.                                     }

  163.                                 } else {

  164.                                     // store the constant coefficients
  165.                                     parseCoefficient(tab[3], c, i, j, "C", name);
  166.                                     parseCoefficient(tab[4], s, i, j, "S", name);
  167.                                     okCoeffs = true;

  168.                                 }
  169.                             }
  170.                         }

  171.                     }
  172.                 }
  173.             }
  174.         } catch (NumberFormatException nfe) {
  175.             throw new OrekitException(OrekitMessages.UNABLE_TO_PARSE_LINE_IN_FILE,
  176.                                       lineNumber, name, line);
  177.         }

  178.         if (missingCoefficientsAllowed() && c.length > 0 && c[0].length > 0) {
  179.             // ensure at least the (0, 0) element is properly set
  180.             if (Precision.equals(c[0][0], 0.0, 0)) {
  181.                 c[0][0] = 1.0;
  182.             }
  183.         }

  184.         if (!(okEarth && okSHM && okCoeffs)) {
  185.             String loaderName = getClass().getName();
  186.             loaderName = loaderName.substring(loaderName.lastIndexOf('.') + 1);
  187.             throw new OrekitException(OrekitMessages.UNEXPECTED_FILE_FORMAT_ERROR_FOR_LOADER,
  188.                                       name, loaderName);
  189.         }

  190.         setRawCoefficients(normalized, c, s, name);
  191.         setTideSystem(tideSystem);
  192.         setReadComplete(true);

  193.     }

  194.     /** Get a provider for read spherical harmonics coefficients.
  195.      * <p>
  196.      * SHM fields do include time-dependent parts which are taken into account
  197.      * in the returned provider.
  198.      * </p>
  199.      * @param wantNormalized if true, the provider will provide normalized coefficients,
  200.      * otherwise it will provide un-normalized coefficients
  201.      * @param degree maximal degree
  202.      * @param order maximal order
  203.      * @return a new provider
  204.      * @since 6.0
  205.      */
  206.     public RawSphericalHarmonicsProvider getProvider(final boolean wantNormalized,
  207.                                                      final int degree, final int order) {

  208.         // get the constant part
  209.         RawSphericalHarmonicsProvider provider = getConstantProvider(wantNormalized, degree, order);

  210.         if (!cDot.isEmpty()) {

  211.             // add the secular trend layer
  212.             final double[][] cArray = toArray(cDot);
  213.             final double[][] sArray = toArray(sDot);
  214.             rescale(1.0 / Constants.JULIAN_YEAR, true, cArray, sArray, wantNormalized, cArray, sArray);
  215.             provider = new SecularTrendSphericalHarmonics(provider, referenceDate, cArray, sArray);

  216.         }

  217.         return provider;

  218.     }

  219. }