SHMFormatReader.java

  1. /* Copyright 2002-2025 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.Locale;
  25. import java.util.regex.Pattern;

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

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

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

  53.     /** First field labels. */
  54.     private static final String GRCOEF = "GRCOEF";

  55.     /** Second field labels. */
  56.     private static final String GRCOF2 = "GRCOF2";

  57.     /** Drift coefficients labels. */
  58.     private static final String GRDOTA = "GRDOTA";

  59.     /** Flag for Earth data. */
  60.     private static final int EARTH = 0x1;

  61.     /** Flag for degree/order. */
  62.     private static final int LIMITS = 0x2;

  63.     /** Flag for coefficients. */
  64.     private static final int COEFFS = 0x4;

  65.     /** Reference date. */
  66.     private AbsoluteDate referenceDate;

  67.     /** Converter from triangular to flat form. */
  68.     private Flattener dotFlattener;

  69.     /** Secular drift of the cosine coefficients. */
  70.     private double[] cDot;

  71.     /** Secular drift of the sine coefficients. */
  72.     private double[] sDot;

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

  86.     /** Simple constructor.
  87.      * @param supportedNames regular expression for supported files names
  88.      * @param missingCoefficientsAllowed if true, allows missing coefficients in the input data
  89.      * @param timeScale for parsing dates.
  90.      * @since 10.1
  91.      */
  92.     public SHMFormatReader(final String supportedNames,
  93.                            final boolean missingCoefficientsAllowed,
  94.                            final TimeScale timeScale) {
  95.         super(supportedNames, missingCoefficientsAllowed, timeScale);
  96.         reset();
  97.     }

  98.     /** {@inheritDoc} */
  99.     public void loadData(final InputStream input, final String name)
  100.         throws IOException, ParseException, OrekitException {

  101.         // reset the indicator before loading any data
  102.         reset();

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

  105.         Flattener flattener  = null;
  106.         int       dotDegree  = -1;
  107.         int       dotOrder   = -1;
  108.         int       flags      = 0;
  109.         double[]  c0         = null;
  110.         double[]  s0         = null;
  111.         double[]  c1         = null;
  112.         double[]  s1         = null;
  113.         String    line       = null;
  114.         int       lineNumber = 1;
  115.         try (BufferedReader r = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8))) {
  116.             line = r.readLine();
  117.             if (line != null &&
  118.                 "FIRST ".equals(line.substring(0, 6)) &&
  119.                 "SHM    ".equals(line.substring(49, 56))) {
  120.                 for (line = r.readLine(); line != null; line = r.readLine()) {
  121.                     lineNumber++;
  122.                     if (line.length() >= 6) {
  123.                         final String[] tab = SEPARATOR.split(line);

  124.                         // read the earth values
  125.                         if ("EARTH".equals(tab[0])) {
  126.                             setMu(parseDouble(tab[1]));
  127.                             setAe(parseDouble(tab[2]));
  128.                             flags |= EARTH;
  129.                         }

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

  132.                             final int degree = FastMath.min(getMaxParseDegree(), Integer.parseInt(tab[1]));
  133.                             final int order  = FastMath.min(getMaxParseOrder(), degree);
  134.                             flattener = new Flattener(degree, order);
  135.                             c0 = buildFlatArray(flattener, missingCoefficientsAllowed() ? 0.0 : Double.NaN);
  136.                             s0 = buildFlatArray(flattener, missingCoefficientsAllowed() ? 0.0 : Double.NaN);
  137.                             c1 = buildFlatArray(flattener, 0.0);
  138.                             s1 = buildFlatArray(flattener, 0.0);
  139.                             final String lowerCaseLine = line.toLowerCase(Locale.US);
  140.                             normalized = lowerCaseLine.contains("fully normalized");
  141.                             if (lowerCaseLine.contains("exclusive permanent tide")) {
  142.                                 tideSystem = TideSystem.TIDE_FREE;
  143.                             } else {
  144.                                 tideSystem = TideSystem.UNKNOWN;
  145.                             }
  146.                             flags |= LIMITS;
  147.                         }

  148.                         // fill the arrays
  149.                         if (GRCOEF.equals(line.substring(0, 6)) || GRCOF2.equals(tab[0]) || GRDOTA.equals(tab[0])) {
  150.                             final int i = Integer.parseInt(tab[1]);
  151.                             final int j = Integer.parseInt(tab[2]);
  152.                             if (flattener.withinRange(i, j)) {
  153.                                 if (GRDOTA.equals(tab[0])) {

  154.                                     // store the secular drift coefficients
  155.                                     parseCoefficient(tab[3], flattener, c1, i, j, "Cdot", name);
  156.                                     parseCoefficient(tab[4], flattener, s1, i, j, "Sdot", name);
  157.                                     dotDegree = FastMath.max(dotDegree, i);
  158.                                     dotOrder  = FastMath.max(dotOrder,  j);

  159.                                     // check the reference date (format yyyymmdd)
  160.                                     final DateComponents localRef = new DateComponents(Integer.parseInt(tab[7].substring(0, 4)),
  161.                                                                                        Integer.parseInt(tab[7].substring(4, 6)),
  162.                                                                                        Integer.parseInt(tab[7].substring(6, 8)));
  163.                                     if (referenceDate == null) {
  164.                                         // first reference found, store it
  165.                                         referenceDate = toDate(localRef);
  166.                                     } else if (!referenceDate.equals(toDate(localRef))) {
  167.                                         final AbsoluteDate localDate = toDate(localRef);
  168.                                         throw new OrekitException(OrekitMessages.SEVERAL_REFERENCE_DATES_IN_GRAVITY_FIELD,
  169.                                                                   referenceDate, localDate, name,
  170.                                                                   localDate.durationFrom(referenceDate));
  171.                                     }

  172.                                 } else {

  173.                                     // store the constant coefficients
  174.                                     parseCoefficient(tab[3], flattener, c0, i, j, "C", name);
  175.                                     parseCoefficient(tab[4], flattener, s0, i, j, "S", name);

  176.                                 }
  177.                             }
  178.                             flags |= COEFFS;
  179.                         }

  180.                     }
  181.                 }
  182.             }
  183.         } catch (NumberFormatException nfe) {
  184.             throw new OrekitException(OrekitMessages.UNABLE_TO_PARSE_LINE_IN_FILE,
  185.                                       lineNumber, name, line);
  186.         }

  187.         if (flags != (EARTH | LIMITS | COEFFS)) {
  188.             String loaderName = getClass().getName();
  189.             loaderName = loaderName.substring(loaderName.lastIndexOf('.') + 1);
  190.             throw new OrekitException(OrekitMessages.UNEXPECTED_FILE_FORMAT_ERROR_FOR_LOADER,
  191.                                       name, loaderName);
  192.         }

  193.         if (missingCoefficientsAllowed()) {
  194.             // ensure at least the (0, 0) element is properly set
  195.             if (Precision.equals(c0[flattener.index(0, 0)], 0.0, 0)) {
  196.                 c0[flattener.index(0, 0)] = 1.0;
  197.             }
  198.         }

  199.         // resize secular drift arrays
  200.         if (dotDegree >= 0) {
  201.             dotFlattener = new Flattener(dotDegree, dotOrder);
  202.             cDot         = new double[dotFlattener.arraySize()];
  203.             sDot         = new double[dotFlattener.arraySize()];
  204.             for (int n = 0; n <= dotDegree; ++n) {
  205.                 for (int m = 0; m <= FastMath.min(n, dotOrder); ++m) {
  206.                     cDot[dotFlattener.index(n, m)] = c1[flattener.index(n, m)];
  207.                     sDot[dotFlattener.index(n, m)] = s1[flattener.index(n, m)];
  208.                 }
  209.             }
  210.         }

  211.         setRawCoefficients(normalized, flattener, c0, s0, name);
  212.         setTideSystem(tideSystem);
  213.         setReadComplete(true);

  214.     }

  215.     /** Reset instance before read.
  216.      * @since 11.1
  217.      */
  218.     private void reset() {
  219.         setReadComplete(false);
  220.         referenceDate = null;
  221.         dotFlattener  = null;
  222.         cDot          = null;
  223.         sDot          = null;
  224.     }

  225.     /** Get a provider for read spherical harmonics coefficients.
  226.      * <p>
  227.      * SHM fields do include time-dependent parts which are taken into account
  228.      * in the returned provider.
  229.      * </p>
  230.      * @param wantNormalized if true, the provider will provide normalized coefficients,
  231.      * otherwise it will provide un-normalized coefficients
  232.      * @param degree maximal degree
  233.      * @param order maximal order
  234.      * @return a new provider
  235.      * @since 6.0
  236.      */
  237.     public RawSphericalHarmonicsProvider getProvider(final boolean wantNormalized,
  238.                                                      final int degree, final int order) {

  239.         // get the constant part
  240.         RawSphericalHarmonicsProvider provider = getBaseProvider(wantNormalized, degree, order);

  241.         if (dotFlattener != null) {

  242.             // add the secular trend layer
  243.             final double scale = 1.0 / Constants.JULIAN_YEAR;
  244.             final Flattener rescaledFlattener = new Flattener(FastMath.min(degree, dotFlattener.getDegree()),
  245.                                                               FastMath.min(order, dotFlattener.getOrder()));
  246.             provider = new SecularTrendSphericalHarmonics(provider, referenceDate, rescaledFlattener,
  247.                                                           rescale(scale, wantNormalized, rescaledFlattener, dotFlattener, cDot),
  248.                                                           rescale(scale, wantNormalized, rescaledFlattener, dotFlattener, sDot));

  249.         }

  250.         return provider;

  251.     }

  252. }