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  
19  import java.io.BufferedReader;
20  import java.io.IOException;
21  import java.io.InputStream;
22  import java.io.InputStreamReader;
23  import java.nio.charset.StandardCharsets;
24  import java.text.ParseException;
25  import java.util.ArrayList;
26  import java.util.List;
27  import java.util.Locale;
28  import java.util.regex.Pattern;
29  
30  import org.hipparchus.util.FastMath;
31  import org.hipparchus.util.Precision;
32  import org.orekit.errors.OrekitException;
33  import org.orekit.errors.OrekitMessages;
34  import org.orekit.utils.Constants;
35  
36  /**This reader is adapted to the EGM Format.
37   *
38   * <p> The proper way to use this class is to call the {@link GravityFieldFactory}
39   *  which will determine which reader to use with the selected gravity field file.</p>
40   *
41   * @see GravityFields
42   * @author Fabien Maussion
43   */
44  public class EGMFormatReader extends PotentialCoefficientsReader {
45  
46      /** Pattern for delimiting regular expressions. */
47      private static final Pattern SEPARATOR = Pattern.compile("\\s+");
48  
49      /** Flag for using WGS84 values for equatorial radius and central attraction coefficient. */
50      private final boolean useWgs84Coefficients;
51  
52      /** Simple constructor.
53       * @param supportedNames regular expression for supported files names
54       * @param missingCoefficientsAllowed if true, allows missing coefficients in the input data
55       */
56      public EGMFormatReader(final String supportedNames, final boolean missingCoefficientsAllowed) {
57          this(supportedNames, missingCoefficientsAllowed, false);
58      }
59  
60      /**
61       * Simple constructor that allows overriding 'standard' EGM96 ae and mu with
62       * WGS84 variants.
63       *
64       * @param supportedNames regular expression for supported files names
65       * @param missingCoefficientsAllowed if true, allows missing coefficients in the input data
66       * @param useWgs84Coefficients if true, the WGS84 values will be used for equatorial radius
67       * and central attraction coefficient
68       */
69      public EGMFormatReader(final String supportedNames, final boolean missingCoefficientsAllowed,
70                             final boolean useWgs84Coefficients) {
71          super(supportedNames, missingCoefficientsAllowed, null);
72          this.useWgs84Coefficients = useWgs84Coefficients;
73      }
74  
75  
76      /** {@inheritDoc} */
77      public void loadData(final InputStream input, final String name)
78          throws IOException, ParseException, OrekitException {
79  
80          // reset the indicator before loading any data
81          setReadComplete(false);
82  
83          // both EGM96 and EGM2008 use the same values for ae and mu
84          // if a new EGM model changes them, we should have some selection logic
85          // based on file name (a better way would be to have the data in the
86          // file...)
87          if (this.useWgs84Coefficients) {
88              setAe(Constants.WGS84_EARTH_EQUATORIAL_RADIUS);
89              setMu(Constants.WGS84_EARTH_MU);
90          } else {
91              setAe(Constants.EGM96_EARTH_EQUATORIAL_RADIUS);
92              setMu(Constants.EGM96_EARTH_MU);
93          }
94  
95          final String lowerCaseName = name.toLowerCase(Locale.US);
96          if (lowerCaseName.contains("2008") || lowerCaseName.contains("zerotide")) {
97              setTideSystem(TideSystem.ZERO_TIDE);
98          } else {
99              setTideSystem(TideSystem.TIDE_FREE);
100         }
101 
102         final List<List<Double>> c = new ArrayList<>();
103         final List<List<Double>> s = new ArrayList<>();
104         boolean okFields = true;
105         int lineNumber = 0;
106         String line = null;
107         try (BufferedReader r = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8))) {
108             for (line = r.readLine(); okFields && line != null; line = r.readLine()) {
109                 lineNumber++;
110                 if (line.length() >= 15) {
111 
112                     // get the fields defining the current the potential terms
113                     final String[] tab = SEPARATOR.split(line.trim());
114                     if (tab.length != 6) {
115                         okFields = false;
116                     }
117 
118                     final int i = Integer.parseInt(tab[0]);
119                     final int j = Integer.parseInt(tab[1]);
120                     if (i <= getMaxParseDegree() && j <= getMaxParseOrder()) {
121                         for (int k = 0; k <= i; ++k) {
122                             extendListOfLists(c, k, FastMath.min(k, getMaxParseOrder()),
123                                               missingCoefficientsAllowed() ? 0.0 : Double.NaN);
124                             extendListOfLists(s, k, FastMath.min(k, getMaxParseOrder()),
125                                               missingCoefficientsAllowed() ? 0.0 : Double.NaN);
126                         }
127                         parseCoefficient(tab[2], c, i, j, "C", name);
128                         parseCoefficient(tab[3], s, i, j, "S", name);
129                     }
130 
131                 }
132             }
133         } catch (NumberFormatException nfe) {
134             throw new OrekitException(OrekitMessages.UNABLE_TO_PARSE_LINE_IN_FILE,
135                                       lineNumber, name, line);
136         }
137 
138         if (missingCoefficientsAllowed() && getMaxParseDegree() > 0 && getMaxParseOrder() > 0) {
139             // ensure at least the (0, 0) element is properly set
140             extendListOfLists(c, 0, 0, 0.0);
141             extendListOfLists(s, 0, 0, 0.0);
142             if (Precision.equals(c.get(0).get(0), 0.0, 0)) {
143                 c.get(0).set(0, 1.0);
144             }
145         }
146 
147         if ((!okFields) || (c.size() < 1)) {
148             String loaderName = getClass().getName();
149             loaderName = loaderName.substring(loaderName.lastIndexOf('.') + 1);
150             throw new OrekitException(OrekitMessages.UNEXPECTED_FILE_FORMAT_ERROR_FOR_LOADER,
151                                       name, loaderName);
152         }
153 
154         setRawCoefficients(true, toArray(c), toArray(s), name);
155         setReadComplete(true);
156 
157     }
158 
159     /** Get a provider for read spherical harmonics coefficients.
160      * <p>
161      * EGM fields don't include time-dependent parts, so this method returns
162      * directly a constant provider.
163      * </p>
164      * @param wantNormalized if true, the provider will provide normalized coefficients,
165      * otherwise it will provide un-normalized coefficients
166      * @param degree maximal degree
167      * @param order maximal order
168      * @return a new provider
169      * @since 6.0
170      */
171     public RawSphericalHarmonicsProvider getProvider(final boolean wantNormalized,
172                                                      final int degree, final int order) {
173         return getConstantProvider(wantNormalized, degree, order);
174     }
175 
176 }