1   /* Copyright 2002-2026 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.frames;
18  
19  import java.io.BufferedReader;
20  import java.io.IOException;
21  import java.util.ArrayList;
22  import java.util.Collection;
23  import java.util.List;
24  import java.util.function.Supplier;
25  import java.util.regex.Matcher;
26  import java.util.regex.Pattern;
27  
28  import org.orekit.data.DataProvidersManager;
29  import org.orekit.data.DataSource;
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.TimeComponents;
35  import org.orekit.time.TimeScale;
36  import org.orekit.utils.Constants;
37  import org.orekit.utils.IERSConventions;
38  import org.orekit.utils.IERSConventions.NutationCorrectionConverter;
39  
40  /** Loader for EOP C04 files.
41   * <p>EOP C04 files contain {@link EOPEntry
42   * Earth Orientation Parameters} consistent with ITRF20xx for one year periods, with various
43   * xx (05, 08, 14, 20) depending on the data source.</p>
44   * <p>The EOP C04 files retrieved from the old ftp site
45   * <a href="ftp://ftp.iers.org/products/eop/long-term/">ftp://ftp.iers.org/products/eop/long-term/</a>
46   * were recognized thanks to their base names, which must match one of the patterns
47   * {@code eopc04_##_IAU2000.##} or {@code eopc04_##.##} (or the same ending with <code>.gz</code> for
48   * gzip-compressed files) where # stands for a digit character. As of early 2023, this ftp site
49   * seems not to be accessible anymore.</p>
50   * <p>
51   * The official source for these files is now the web site
52   * <a href="https://hpiers.obspm.fr/eoppc/eop/">https://hpiers.obspm.fr/eoppc/eop/</a>. These
53   * files do <em>not</em> follow the old naming convention that was used in the older ftp site.
54   * They lack the _05, _08 or _14 markers in the file names. The ITRF year appears only in the URL
55   * (with directories eopc04_05, eop04_c08…). The directory for the current data is named eopc04
56   * without any suffix. So before 2023-02-14 the eopc04 directory would contain files compatible with
57   * ITRF2014 and after 2023-02-14 it would contain files compatible with ITRF2020. In each directory,
58   * the files don't have any marker, hence users downloading eopc04.99 file from eopc04_05 would get
59   * a file compatible with ITRF2005 whereas users downloading a file with the exact same name eopc04.99
60   * but from eop04_c08 would get a file compatible with ITRF2008.
61   * </p>
62   * <p>
63   * Starting with Orekit version 12.0, the ITRF year is retrieved by analyzing the file header, it is
64   * not linked to file name anymore, hence it is compatible with any IERS site layout.
65   * </p>
66   * <p>
67   * This class is immutable and hence thread-safe
68   * </p>
69   * @author Luc Maisonobe
70   */
71  class EopC04FilesLoader extends AbstractEopLoader implements EopHistoryLoader {
72  
73      /** Build a loader for IERS EOP C04 files.
74       * @param supportedNames regular expression for supported files names
75       * @param manager provides access to the EOP C04 files.
76       * @param utcSupplier UTC time scale.
77       */
78      EopC04FilesLoader(final String supportedNames,
79                        final DataProvidersManager manager,
80                        final Supplier<TimeScale> utcSupplier) {
81          super(supportedNames, manager, utcSupplier);
82      }
83  
84      /** {@inheritDoc} */
85      public void fillHistory(final IERSConventions.NutationCorrectionConverter converter,
86                              final Collection<EOPEntry> history) {
87          final Parser parser = new Parser(converter, getUtc());
88          final EopParserLoader loader = new EopParserLoader(parser);
89          this.feed(loader);
90          history.addAll(loader.getEop());
91      }
92  
93      /** Internal class performing the parsing. */
94      static class Parser extends AbstractEopParser {
95  
96          /** Simple constructor.
97           * @param converter converter to use
98           * @param utc       time scale for parsing dates.
99           */
100         Parser(final NutationCorrectionConverter converter,
101                final TimeScale utc) {
102             super(converter, null, utc);
103         }
104 
105         /** {@inheritDoc} */
106         public Collection<EOPEntry> parse(final DataSource source)
107             throws IOException, OrekitException {
108 
109             final List<EOPEntry> history = new ArrayList<>();
110 
111             // set up a reader for line-oriented EOP C04 files
112             try (BufferedReader reader = new BufferedReader(source.getOpener().openReaderOnce())) {
113                 // reset parse info to start new file (do not clear history!)
114                 int lineNumber   = 0;
115                 boolean inHeader = true;
116                 final LineParser[] tentativeParsers = new LineParser[] {
117                     new LineWithoutRatesParser(source.getName()),
118                     new LineWithRatesParser(source.getName())
119                 };
120                 LineParser selectedParser = null;
121 
122                 // read all file
123                 for (String line = reader.readLine(); line != null; line = reader.readLine()) {
124                     ++lineNumber;
125                     boolean parsed = false;
126 
127                     if (inHeader) {
128                         // maybe it's an header line
129                         for (final LineParser parser : tentativeParsers) {
130                             if (parser.parseHeaderLine(line)) {
131                                 // we recognized one EOP C04 format
132                                 selectedParser = parser;
133                                 break;
134                             }
135                         }
136                     }
137 
138                     if (selectedParser != null) {
139                         // maybe it's a data line
140                         final EOPEntry entry = selectedParser.parseDataLine(line);
141                         if (entry != null) {
142 
143                             // this is a data line, build an entry from the extracted fields
144                             history.add(entry);
145                             parsed = true;
146 
147                             // we know we have already finished header
148                             inHeader = false;
149 
150                         }
151                     }
152 
153                     if (!(inHeader || parsed)) {
154                         throw new OrekitException(OrekitMessages.UNABLE_TO_PARSE_LINE_IN_FILE,
155                                 lineNumber, source.getName(), line);
156                     }
157                 }
158 
159                 // check if we have read something
160                 if (inHeader) {
161                     throw new OrekitException(OrekitMessages.NOT_A_SUPPORTED_IERS_DATA_FILE, source.getName());
162                 }
163             }
164 
165             return history;
166         }
167 
168         /** Base parser for EOP C04 lines.
169          * @since 12.0
170          */
171         private abstract static class LineParser {
172 
173             /** Pattern for ITRF version. */
174             private final Pattern itrfVersionPattern;
175 
176             /** Pattern for columns header. */
177             private final Pattern columnHeaderPattern;
178 
179             /** Pattern for data lines. */
180             private final Pattern dataPattern;
181 
182             /** Year group. */
183             private final int yearGroup;
184 
185             /** Month group. */
186             private final int monthGroup;
187 
188             /** Day group. */
189             private final int dayGroup;
190 
191             /** MJD group. */
192             private final int mjdGroup;
193 
194             /** Name of the stream for error messages. */
195             private final String name;
196 
197             /** ITRF version. */
198             private ITRFVersion itrfVersion;
199 
200             /** Simple constructor.
201              * @param itrfVersionRegexp regular expression for ITRF version
202              * @param columnsHeaderRegexp regular expression for columns header
203              * @param dataRegexp regular expression for data lines
204              * @param yearGroup year group
205              * @param monthGroup month group
206              * @param dayGroup day group
207              * @param mjdGroup MJD group
208              * @param name  of the stream for error messages.
209              */
210             protected LineParser(final String itrfVersionRegexp, final String columnsHeaderRegexp,
211                                  final String dataRegexp,
212                                  final int yearGroup, final int monthGroup, final int dayGroup,
213                                  final int mjdGroup, final String name) {
214                 this.itrfVersionPattern  = Pattern.compile(itrfVersionRegexp);
215                 this.columnHeaderPattern = Pattern.compile(columnsHeaderRegexp);
216                 this.dataPattern         = Pattern.compile(dataRegexp);
217                 this.yearGroup           = yearGroup;
218                 this.monthGroup          = monthGroup;
219                 this.dayGroup            = dayGroup;
220                 this.mjdGroup            = mjdGroup;
221                 this.name                = name;
222             }
223 
224             /** Get the ITRF version for this EOP C04 file.
225              * @return ITRF version
226              */
227             protected ITRFVersion getItrfVersion() {
228                 return itrfVersion;
229             }
230 
231             /** Parse a header line.
232              * @param line line to parse
233              * @return true if line was recognized (either ITRF version or columns header)
234              */
235             public boolean parseHeaderLine(final String line) {
236                 final Matcher itrfVersionMatcher = itrfVersionPattern.matcher(line);
237                 if (itrfVersionMatcher.matches()) {
238                     switch (Integer.parseInt(itrfVersionMatcher.group(1))) {
239                         case 5 :
240                             itrfVersion = ITRFVersion.ITRF_2005;
241                             break;
242                         case 8 :
243                             itrfVersion = ITRFVersion.ITRF_2008;
244                             break;
245                         case 14 :
246                             itrfVersion = ITRFVersion.ITRF_2014;
247                             break;
248                         case 20 :
249                             itrfVersion = ITRFVersion.ITRF_2020;
250                             break;
251                         default :
252                             throw new OrekitException(OrekitMessages.NO_SUCH_ITRF_FRAME, itrfVersionMatcher.group(1));
253                     }
254                     return true;
255                 } else {
256                     final Matcher columnHeaderMatcher = columnHeaderPattern.matcher(line);
257                     if (columnHeaderMatcher.matches()) {
258                         parseColumnsHeaderLine(columnHeaderMatcher);
259                         return true;
260                     }
261                     return false;
262                 }
263             }
264 
265             /** Parse a data line.
266              * @param line line to parse
267              * @return EOP entry for the line, or null if line does not match expected regular expression
268              */
269             public EOPEntry parseDataLine(final String line) {
270 
271                 final Matcher matcher = dataPattern.matcher(line);
272                 if (!matcher.matches()) {
273                     // this is not a data line
274                     return null;
275                 }
276 
277                 // check date
278                 final DateComponents dc = new DateComponents(Integer.parseInt(matcher.group(yearGroup)),
279                                                              Integer.parseInt(matcher.group(monthGroup)),
280                                                              Integer.parseInt(matcher.group(dayGroup)));
281                 final int    mjd   = Integer.parseInt(matcher.group(mjdGroup));
282                 if (dc.getMJD() != mjd) {
283                     throw new OrekitException(OrekitMessages.INCONSISTENT_DATES_IN_IERS_FILE,
284                                               name, dc.getYear(), dc.getMonth(), dc.getDay(), mjd);
285                 }
286 
287                 return parseDataLine(matcher, dc);
288 
289             }
290 
291             /** Parse a columns header line.
292              * @param matcher matcher for line
293              */
294             protected abstract void parseColumnsHeaderLine(Matcher matcher);
295 
296             /** Parse a data line.
297              * @param matcher matcher for line
298              * @param dc date components already extracted from the line
299              * @return EOP entry for the line
300              */
301             protected abstract EOPEntry parseDataLine(Matcher matcher, DateComponents dc);
302 
303         }
304 
305         /** Parser for data lines without pole rates.
306          * <p>
307          * ITRF markers have either the following form:
308          * </p>
309          * <pre>
310          *                           EOP (IERS) 05 C04
311          * </pre>
312          * <p>
313          * or the following form:
314          * </p>
315          * <pre>
316          *                           EOP (IERS) 14 C04 TIME SERIES
317          * </pre>
318          * <p>
319          * Header have either the following form:
320          * </p>
321          * <pre>
322          *       Date      MJD      x          y        UT1-UTC       LOD         dPsi      dEps       x Err     y Err   UT1-UTC Err  LOD Err    dPsi Err   dEpsilon Err
323          *                          "          "           s           s            "         "        "          "          s           s            "         "
324          *      (0h UTC)
325          * </pre>
326          * <p>
327          * or the following form:
328          * </p>
329          * <pre>
330          *       Date      MJD      x          y        UT1-UTC       LOD         dX        dY        x Err     y Err   UT1-UTC Err  LOD Err     dX Err       dY Err
331          *                          "          "           s           s          "         "           "          "          s         s            "           "
332          *      (0h UTC)
333          * </pre>
334          * <p>
335          * The data lines in the EOP C04 yearly data files have either the following fixed form:
336          * </p>
337          * <pre>
338          * year month day MJD …12 floating values fields in decimal format...
339          * 2000   1   1  51544   0.043242   0.377915   0.3554777   …
340          * 2000   1   2  51545   0.043515   0.377753   0.3546065   …
341          * 2000   1   3  51546   0.043623   0.377452   0.3538444   …
342          * </pre>
343          * @since 12.0
344          */
345         private class LineWithoutRatesParser extends LineParser {
346 
347             /** Nutation header group. */
348             private static final int NUTATION_HEADER_GROUP = 1;
349 
350             /** Year group. */
351             private static final int YEAR_GROUP = 1;
352 
353             /** Month group. */
354             private static final int MONTH_GROUP = 2;
355 
356             /** Day group. */
357             private static final int DAY_GROUP = 3;
358 
359             /** MJD group. */
360             private static final int MJD_GROUP = 4;
361 
362             /** X component of pole motion group. */
363             private static final int POLE_X_GROUP = 5;
364 
365             /** Y component of pole motion group. */
366             private static final int POLE_Y_GROUP = 6;
367 
368             /** UT1-UTC group. */
369             private static final int UT1_UTC_GROUP = 7;
370 
371             /** LoD group. */
372             private static final int LOD_GROUP = 8;
373 
374             /** Correction for nutation first field (either dX or dPsi). */
375             private static final int NUT_0_GROUP = 9;
376 
377             /** Correction for nutation second field (either dY or dEps). */
378             private static final int NUT_1_GROUP = 10;
379 
380             /** Indicator for non-rotating origin. */
381             private boolean isNonRotatingOrigin;
382 
383             /** Simple constructor.
384              * @param name  of the stream for error messages.
385              */
386             LineWithoutRatesParser(final String name) {
387                 super("^ +EOP +\\(IERS\\) +([0-9][0-9]) +C04.*",
388                       "^ *Date +MJD +x +y +UT1-UTC +LOD +((?:dPsi +dEps)|(?:dX +dY)) .*",
389                       "^(\\d+) +(\\d+) +(\\d+) +(\\d+) +(-?\\d+\\.\\d+) +(-?\\d+\\.\\d+) +(-?\\d+\\.\\d+) +(-?\\d+\\.\\d+) +(-?\\d+\\.\\d+) +(-?\\d+\\.\\d+)(?: +(-?\\d+\\.\\d+)){6}$",
390                       YEAR_GROUP, MONTH_GROUP, DAY_GROUP, MJD_GROUP,
391                       name);
392             }
393 
394             /** {@inheritDoc} */
395             @Override
396             protected void parseColumnsHeaderLine(final Matcher matcher) {
397                 isNonRotatingOrigin = matcher.group(NUTATION_HEADER_GROUP).startsWith("dX");
398             }
399 
400             /** {@inheritDoc} */
401             @Override
402             protected EOPEntry parseDataLine(final Matcher matcher, final DateComponents dc) {
403 
404                 final AbsoluteDate date = new AbsoluteDate(dc, getUtc());
405 
406                 final double x     = Double.parseDouble(matcher.group(POLE_X_GROUP)) * Constants.ARC_SECONDS_TO_RADIANS;
407                 final double y     = Double.parseDouble(matcher.group(POLE_Y_GROUP)) * Constants.ARC_SECONDS_TO_RADIANS;
408                 final double dtu1  = Double.parseDouble(matcher.group(UT1_UTC_GROUP));
409                 final double lod   = Double.parseDouble(matcher.group(LOD_GROUP));
410                 final double[] equinox;
411                 final double[] nro;
412                 if (isNonRotatingOrigin) {
413                     nro = new double[] {
414                         Double.parseDouble(matcher.group(NUT_0_GROUP)) * Constants.ARC_SECONDS_TO_RADIANS,
415                         Double.parseDouble(matcher.group(NUT_1_GROUP)) * Constants.ARC_SECONDS_TO_RADIANS
416                     };
417                     equinox = getConverter().toEquinox(date, nro[0], nro[1]);
418                 } else {
419                     equinox = new double[] {
420                         Double.parseDouble(matcher.group(NUT_0_GROUP)) * Constants.ARC_SECONDS_TO_RADIANS,
421                         Double.parseDouble(matcher.group(NUT_1_GROUP)) * Constants.ARC_SECONDS_TO_RADIANS
422                     };
423                     nro = getConverter().toNonRotating(date, equinox[0], equinox[1]);
424                 }
425 
426                 return new EOPEntry(dc.getMJD(), dtu1, lod, x, y, Double.NaN, Double.NaN,
427                                     equinox[0], equinox[1], nro[0], nro[1],
428                                     getItrfVersion(), date, EopDataType.FINAL);
429 
430             }
431         }
432 
433         /** Parser for data lines with pole rates.
434          * <p>
435          * ITRF markers have either the following form:
436          * </p>
437          * <pre>
438          * # EOP (IERS) 20 C04 TIME SERIES  consistent with ITRF 2020 - sampled at 0h UTC
439          * </pre>
440          * <p>
441          * Header have either the following form:
442          * </p>
443          * <pre>
444          * # YR  MM  DD  HH       MJD        x(")        y(")  UT1-UTC(s)       dX(")      dY(")       xrt(")      yrt(")      LOD(s)        x Er        y Er  UT1-UTC Er      dX Er       dY Er       xrt Er      yrt Er      LOD Er
445          * </pre>
446          * <p>
447          * The data lines in the EOP C04 yearly data files have either the following fixed form:
448          * </p>
449          * <pre>
450          * year month day hour MJD (in floating format) …16 floating values fields in decimal format...
451          * 2015   1   1  12  57023.50    0.030148    0.281014   …
452          * 2015   1   2  12  57024.50    0.029219    0.281441   …
453          * 2015   1   3  12  57025.50    0.028777    0.281824   …
454          * </pre>
455          * @since 12.0
456          */
457         private class LineWithRatesParser extends LineParser {
458 
459             /** Year group. */
460             private static final int YEAR_GROUP = 1;
461 
462             /** Month group. */
463             private static final int MONTH_GROUP = 2;
464 
465             /** Day group. */
466             private static final int DAY_GROUP = 3;
467 
468             /** Hour group. */
469             private static final int HOUR_GROUP = 4;
470 
471             /** MJD group. */
472             private static final int MJD_GROUP = 5;
473 
474             /** X component of pole motion group. */
475             private static final int POLE_X_GROUP = 6;
476 
477             /** Y component of pole motion group. */
478             private static final int POLE_Y_GROUP = 7;
479 
480             /** UT1-UTC group. */
481             private static final int UT1_UTC_GROUP = 8;
482 
483             /** Correction for nutation first field. */
484             private static final int NUT_DX_GROUP = 9;
485 
486             /** Correction for nutation second field. */
487             private static final int NUT_DY_GROUP = 10;
488 
489             /** X rate component of pole motion group.
490              * @since 12.0
491              */
492             private static final int POLE_X_RATE_GROUP = 11;
493 
494             /** Y rate component of pole motion group.
495              * @since 12.0
496              */
497             private static final int POLE_Y_RATE_GROUP = 12;
498 
499             /** LoD group. */
500             private static final int LOD_GROUP = 13;
501 
502             /** Simple constructor.
503              * @param name  of the stream for error messages.
504              */
505             LineWithRatesParser(final String name) {
506                 super("^# +EOP +\\(IERS\\) +([0-9][0-9]) +C04.*",
507                       "^# +YR +MM +DD +H +MJD +x\\(\"\\) +y\\(\"\\) +UT1-UTC\\(s\\) +dX\\(\"\\) +dY\\(\"\\) +xrt\\(\"\\) +yrt\\'\"\\) +.*",
508                       "^(\\d+) +(\\d+) +(\\d+) +(\\d+) +(\\d+)\\.\\d+ +(-?\\d+\\.\\d+) +(-?\\d+\\.\\d+) +(-?\\d+\\.\\d+) +(-?\\d+\\.\\d+) +(-?\\d+\\.\\d+) +(-?\\d+\\.\\d+) +(-?\\d+\\.\\d+) +(-?\\d+\\.\\d+)(?: +(-?\\d+\\.\\d+)){8}$", // we intentionally ignore MJD fractional part
509                       YEAR_GROUP, MONTH_GROUP, DAY_GROUP, MJD_GROUP,
510                       name);
511             }
512 
513             /** {@inheritDoc} */
514             @Override
515             protected void parseColumnsHeaderLine(final Matcher matcher) {
516                 // nothing to do here
517             }
518 
519             /** {@inheritDoc} */
520             @Override
521             protected EOPEntry parseDataLine(final Matcher matcher, final DateComponents dc) {
522 
523                 final TimeComponents tc = new TimeComponents(Integer.parseInt(matcher.group(HOUR_GROUP)), 0, 0.0);
524                 final AbsoluteDate date = new AbsoluteDate(dc, tc, getUtc());
525 
526                 final double x     = Double.parseDouble(matcher.group(POLE_X_GROUP)) * Constants.ARC_SECONDS_TO_RADIANS;
527                 final double y     = Double.parseDouble(matcher.group(POLE_Y_GROUP)) * Constants.ARC_SECONDS_TO_RADIANS;
528                 final double xRate = Double.parseDouble(matcher.group(POLE_X_RATE_GROUP)) *
529                                      Constants.ARC_SECONDS_TO_RADIANS / Constants.JULIAN_DAY;
530                 final double yRate = Double.parseDouble(matcher.group(POLE_Y_RATE_GROUP)) *
531                                      Constants.ARC_SECONDS_TO_RADIANS / Constants.JULIAN_DAY;
532                 final double dtu1  = Double.parseDouble(matcher.group(UT1_UTC_GROUP));
533                 final double lod   = Double.parseDouble(matcher.group(LOD_GROUP));
534                 final double[] nro = new double[] {
535                     Double.parseDouble(matcher.group(NUT_DX_GROUP)) * Constants.ARC_SECONDS_TO_RADIANS,
536                     Double.parseDouble(matcher.group(NUT_DY_GROUP)) * Constants.ARC_SECONDS_TO_RADIANS
537                 };
538                 final double[] equinox = getConverter().toEquinox(date, nro[0], nro[1]);
539 
540                 return new EOPEntry(dc.getMJD(), dtu1, lod, x, y, xRate, yRate,
541                                     equinox[0], equinox[1], nro[0], nro[1],
542                                     getItrfVersion(), date, EopDataType.FINAL);
543 
544             }
545         }
546 
547     }
548 
549 }