1   /* Copyright 2002-2019 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  
19  import java.io.BufferedReader;
20  import java.io.IOException;
21  import java.io.InputStream;
22  import java.io.InputStreamReader;
23  import java.text.ParseException;
24  import java.util.ArrayList;
25  import java.util.List;
26  import java.util.regex.Matcher;
27  import java.util.regex.Pattern;
28  
29  import org.hipparchus.util.FastMath;
30  import org.hipparchus.util.Precision;
31  import org.orekit.errors.OrekitException;
32  import org.orekit.errors.OrekitMessages;
33  import org.orekit.errors.OrekitParseException;
34  import org.orekit.time.DateComponents;
35  import org.orekit.utils.Constants;
36  
37  /** Reader for the GRGS gravity field format.
38   *
39   * <p> This format was used to describe various gravity fields at GRGS (Toulouse).
40   *
41   * <p> The proper way to use this class is to call the {@link GravityFieldFactory}
42   *  which will determine which reader to use with the selected gravity field file.</p>
43   *
44   * @see GravityFieldFactory
45   * @author Luc Maisonobe
46   */
47  public class GRGSFormatReader extends PotentialCoefficientsReader {
48  
49      /** Patterns for lines (the last pattern is repeated for all data lines). */
50      private static final Pattern[] LINES;
51  
52      /** Reference date. */
53      private DateComponents referenceDate;
54  
55      /** Secular drift of the cosine coefficients. */
56      private final List<List<Double>> cDot;
57  
58      /** Secular drift of the sine coefficients. */
59      private final List<List<Double>> sDot;
60  
61      static {
62  
63          // sub-patterns
64          final String real = "[-+]?\\d?\\.\\d+[eEdD][-+]\\d\\d";
65          final String sep = ")\\s*(";
66  
67          // regular expression for header lines
68          final String[] header = {
69              "^\\s*FIELD - .*$",
70              "^\\s+AE\\s+1/F\\s+GM\\s+OMEGA\\s*$",
71              "^\\s*(" + real + sep + real + sep + real + sep + real + ")\\s*$",
72              "^\\s*REFERENCE\\s+DATE\\s+:\\s+(\\d+)\\.0+\\s*$",
73              "^\\s*MAXIMAL\\s+DEGREE\\s+:\\s+(\\d+)\\s.*$",
74              "^\\s*L\\s+M\\s+DOT\\s+CBAR\\s+SBAR\\s+SIGMA C\\s+SIGMA S(\\s+LIB)?\\s*$"
75          };
76  
77          // regular expression for data lines
78          final String data = "^([ 0-9]{3})([ 0-9]{3})(   |DOT)\\s*(" +
79                              real + sep + real + sep + real + sep + real +
80                              ")(\\s+[0-9]+)?\\s*$";
81  
82          // compile the regular expressions
83          LINES = new Pattern[header.length + 1];
84          for (int i = 0; i < header.length; ++i) {
85              LINES[i] = Pattern.compile(header[i]);
86          }
87          LINES[LINES.length - 1] = Pattern.compile(data);
88  
89      }
90  
91      /** Simple constructor.
92       * @param supportedNames regular expression for supported files names
93       * @param missingCoefficientsAllowed if true, allows missing coefficients in the input data
94       */
95      public GRGSFormatReader(final String supportedNames, final boolean missingCoefficientsAllowed) {
96          super(supportedNames, missingCoefficientsAllowed);
97          referenceDate = null;
98          cDot = new ArrayList<List<Double>>();
99          sDot = new ArrayList<List<Double>>();
100     }
101 
102     /** {@inheritDoc} */
103     public void loadData(final InputStream input, final String name)
104         throws IOException, ParseException, OrekitException {
105 
106         // reset the indicator before loading any data
107         setReadComplete(false);
108         referenceDate = null;
109         cDot.clear();
110         sDot.clear();
111 
112         //        FIELD - GRIM5, VERSION : C1, november 1999
113         //        AE                  1/F                 GM                 OMEGA
114         //0.63781364600000E+070.29825765000000E+030.39860044150000E+150.72921150000000E-04
115         //REFERENCE DATE : 1997.00
116         //MAXIMAL DEGREE : 120     Sigmas calibration factor : .5000E+01 (applied)
117         //L  M DOT         CBAR                SBAR             SIGMA C      SIGMA S
118         // 2  0DOT 0.13637590952454E-10 0.00000000000000E+00  .143968E-11  .000000E+00
119         // 3  0DOT 0.28175700027753E-11 0.00000000000000E+00  .496704E-12  .000000E+00
120         // 4  0DOT 0.12249148508277E-10 0.00000000000000E+00  .129977E-11  .000000E+00
121         // 0  0     .99999999988600E+00  .00000000000000E+00  .153900E-09  .000000E+00
122         // 2  0   -0.48416511550920E-03 0.00000000000000E+00  .204904E-10  .000000E+00
123 
124         final BufferedReader r = new BufferedReader(new InputStreamReader(input, "UTF-8"));
125         int lineNumber = 0;
126         double[][] c   = null;
127         double[][] s   = null;
128         for (String line = r.readLine(); line != null; line = r.readLine()) {
129 
130             ++lineNumber;
131 
132             // match current header or data line
133             final Matcher matcher = LINES[FastMath.min(LINES.length, lineNumber) - 1].matcher(line);
134             if (!matcher.matches()) {
135                 throw new OrekitParseException(OrekitMessages.UNABLE_TO_PARSE_LINE_IN_FILE,
136                                                lineNumber, name, line);
137             }
138 
139             if (lineNumber == 3) {
140                 // header line defining ae, 1/f, GM and Omega
141                 setAe(parseDouble(matcher.group(1)));
142                 setMu(parseDouble(matcher.group(3)));
143             } else if (lineNumber == 4) {
144                 // header line containing the reference date
145                 referenceDate  = new DateComponents(Integer.parseInt(matcher.group(1)), 1, 1);
146             } else if (lineNumber == 5) {
147                 // header line defining max degree
148                 final int degree = FastMath.min(getMaxParseDegree(), Integer.parseInt(matcher.group(1)));
149                 final int order  = FastMath.min(getMaxParseOrder(), degree);
150                 c = buildTriangularArray(degree, order, missingCoefficientsAllowed() ? 0.0 : Double.NaN);
151                 s = buildTriangularArray(degree, order, missingCoefficientsAllowed() ? 0.0 : Double.NaN);
152             } else if (lineNumber > 6) {
153                 // data line
154                 final int i = Integer.parseInt(matcher.group(1).trim());
155                 final int j = Integer.parseInt(matcher.group(2).trim());
156                 if (i < c.length && j < c[i].length) {
157                     if ("DOT".equals(matcher.group(3).trim())) {
158 
159                         // store the secular drift coefficients
160                         extendListOfLists(cDot, i, j, 0.0);
161                         extendListOfLists(sDot, i, j, 0.0);
162                         parseCoefficient(matcher.group(4), cDot, i, j, "Cdot", name);
163                         parseCoefficient(matcher.group(5), sDot, i, j, "Sdot", name);
164 
165                     } else {
166 
167                         // store the constant coefficients
168                         parseCoefficient(matcher.group(4), c, i, j, "C", name);
169                         parseCoefficient(matcher.group(5), s, i, j, "S", name);
170 
171                     }
172                 }
173             }
174 
175         }
176 
177         if (missingCoefficientsAllowed() && c.length > 0 && c[0].length > 0) {
178             // ensure at least the (0, 0) element is properly set
179             if (Precision.equals(c[0][0], 0.0, 0)) {
180                 c[0][0] = 1.0;
181             }
182         }
183 
184         setRawCoefficients(true, c, s, name);
185         setTideSystem(TideSystem.UNKNOWN);
186         setReadComplete(true);
187 
188     }
189 
190     /** Get a provider for read spherical harmonics coefficients.
191      * <p>
192      * GRGS fields may include time-dependent parts which are taken into account
193      * in the returned provider.
194      * </p>
195      * @param wantNormalized if true, the provider will provide normalized coefficients,
196      * otherwise it will provide un-normalized coefficients
197      * @param degree maximal degree
198      * @param order maximal order
199      * @return a new provider
200      * @since 6.0
201      */
202     public RawSphericalHarmonicsProvider getProvider(final boolean wantNormalized,
203                                                      final int degree, final int order) {
204 
205         // get the constant part
206         RawSphericalHarmonicsProvider provider = getConstantProvider(wantNormalized, degree, order);
207 
208         if (!cDot.isEmpty()) {
209 
210             // add the secular trend layer
211             final double[][] cArray = toArray(cDot);
212             final double[][] sArray = toArray(sDot);
213             rescale(1.0 / Constants.JULIAN_YEAR, true, cArray, sArray, wantNormalized, cArray, sArray);
214             provider = new SecularTrendSphericalHarmonics(provider, referenceDate, cArray, sArray);
215 
216         }
217 
218         return provider;
219 
220     }
221 
222 }