RapidDataAndPredictionXMLLoader.java

  1. /* Copyright 2002-2022 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. import java.io.IOException;
  19. import java.io.InputStream;
  20. import java.io.InputStreamReader;
  21. import java.nio.charset.StandardCharsets;
  22. import java.util.ArrayList;
  23. import java.util.Collection;
  24. import java.util.List;
  25. import java.util.SortedSet;
  26. import java.util.function.Supplier;

  27. import javax.xml.parsers.ParserConfigurationException;
  28. import javax.xml.parsers.SAXParser;
  29. import javax.xml.parsers.SAXParserFactory;

  30. import org.hipparchus.exception.LocalizedCoreFormats;
  31. import org.orekit.data.DataProvidersManager;
  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.IERSConventions;
  38. import org.orekit.utils.units.Unit;
  39. import org.xml.sax.Attributes;
  40. import org.xml.sax.InputSource;
  41. import org.xml.sax.SAXException;
  42. import org.xml.sax.helpers.DefaultHandler;

  43. /** Loader for IERS rapid data and prediction file in XML format (finals file).
  44.  * <p>Rapid data and prediction file contain {@link EOPEntry
  45.  * Earth Orientation Parameters} for several years periods, in one file
  46.  * only that is updated regularly.</p>
  47.  * <p>The XML EOP files are recognized thanks to their base names, which
  48.  * must match one of the the patterns <code>finals.2000A.*.xml</code> or
  49.  * <code>finals.*.xml</code> (or the same ending with <code>.gz</code> for
  50.  * gzip-compressed files) where * stands for a word like "all", "daily",
  51.  * or "data".</p>
  52.  * <p>Files containing data (back to 1973) are available at IERS web site: <a
  53.  * href="http://www.iers.org/IERS/EN/DataProducts/EarthOrientationData/eop.html">Earth orientation data</a>.</p>
  54.  * <p>
  55.  * This class is immutable and hence thread-safe
  56.  * </p>
  57.  * @author Luc Maisonobe
  58.  */
  59. class RapidDataAndPredictionXMLLoader extends AbstractEopLoader
  60.         implements EOPHistoryLoader {

  61.     /** Millisecond unit. */
  62.     private static final Unit MILLI_SECOND = Unit.parse("ms");

  63.     /** Milli arcsecond unit. */
  64.     private static final Unit MILLI_ARC_SECOND = Unit.parse("mas");

  65.     /**
  66.      * Build a loader for IERS XML EOP files.
  67.      *
  68.      * @param supportedNames regular expression for supported files names
  69.      * @param manager        provides access to the XML EOP files.
  70.      * @param utcSupplier    UTC time scale.
  71.      */
  72.     RapidDataAndPredictionXMLLoader(final String supportedNames,
  73.                                     final DataProvidersManager manager,
  74.                                     final Supplier<TimeScale> utcSupplier) {
  75.         super(supportedNames, manager, utcSupplier);
  76.     }

  77.     /** {@inheritDoc} */
  78.     public void fillHistory(final IERSConventions.NutationCorrectionConverter converter,
  79.                             final SortedSet<EOPEntry> history) {
  80.         final ItrfVersionProvider itrfVersionProvider = new ITRFVersionLoader(
  81.                 ITRFVersionLoader.SUPPORTED_NAMES,
  82.                 getDataProvidersManager());
  83.         final Parser parser = new Parser(converter, itrfVersionProvider, getUtc());
  84.         final EopParserLoader loader = new EopParserLoader(parser);
  85.         this.feed(loader);
  86.         history.addAll(loader.getEop());
  87.     }

  88.     /** Internal class performing the parsing. */
  89.     static class Parser extends AbstractEopParser {

  90.         /** History entries. */
  91.         private List<EOPEntry> history;

  92.         /**
  93.          * Simple constructor.
  94.          *
  95.          * @param converter           converter to use
  96.          * @param itrfVersionProvider to use for determining the ITRF version of the EOP.
  97.          * @param utc                 time scale for parsing dates.
  98.          */
  99.         Parser(final IERSConventions.NutationCorrectionConverter converter,
  100.                final ItrfVersionProvider itrfVersionProvider,
  101.                final TimeScale utc) {
  102.             super(converter, itrfVersionProvider, utc);
  103.         }

  104.         /** {@inheritDoc} */
  105.         @Override
  106.         public Collection<EOPEntry> parse(final InputStream input, final String name)
  107.             throws IOException, OrekitException {
  108.             try {
  109.                 this.history = new ArrayList<>();
  110.                 // set up a parser for line-oriented bulletin B files
  111.                 final SAXParser parser = SAXParserFactory.newInstance().newSAXParser();

  112.                 // read all file, ignoring header
  113.                 parser.parse(new InputSource(new InputStreamReader(input, StandardCharsets.UTF_8)),
  114.                              new EOPContentHandler(name));

  115.                 return history;

  116.             } catch (SAXException | ParserConfigurationException e) {
  117.                 throw new OrekitException(e, LocalizedCoreFormats.SIMPLE_MESSAGE, e.getMessage());
  118.             }
  119.         }

  120.         /** Local content handler for XML EOP files. */
  121.         private class EOPContentHandler extends DefaultHandler {

  122.             // CHECKSTYLE: stop JavadocVariable check

  123.             // elements and attributes used in both daily and finals data files
  124.             private static final String MJD_ELT           = "MJD";
  125.             private static final String LOD_ELT           = "LOD";
  126.             private static final String X_ELT             = "X";
  127.             private static final String Y_ELT             = "Y";
  128.             private static final String DPSI_ELT          = "dPsi";
  129.             private static final String DEPSILON_ELT      = "dEpsilon";
  130.             private static final String DX_ELT            = "dX";
  131.             private static final String DY_ELT            = "dY";

  132.             // elements and attributes specific to daily data files
  133.             private static final String DATA_EOP_ELT      = "dataEOP";
  134.             private static final String TIME_SERIES_ELT   = "timeSeries";
  135.             private static final String DATE_YEAR_ELT     = "dateYear";
  136.             private static final String DATE_MONTH_ELT    = "dateMonth";
  137.             private static final String DATE_DAY_ELT      = "dateDay";
  138.             private static final String POLE_ELT          = "pole";
  139.             private static final String UT_ELT            = "UT";
  140.             private static final String UT1_U_UTC_ELT     = "UT1_UTC";
  141.             private static final String NUTATION_ELT      = "nutation";
  142.             private static final String SOURCE_ATTR       = "source";
  143.             private static final String BULLETIN_A_SOURCE = "BulletinA";

  144.             // elements and attributes specific to finals data files
  145.             private static final String FINALS_ELT        = "Finals";
  146.             private static final String DATE_ELT          = "date";
  147.             private static final String EOP_SET_ELT       = "EOPSet";
  148.             private static final String BULLETIN_A_ELT    = "bulletinA";
  149.             private static final String UT1_M_UTC_ELT     = "UT1-UTC";

  150.             private boolean inBulletinA;
  151.             private int     year;
  152.             private int     month;
  153.             private int     day;
  154.             private int     mjd;
  155.             private AbsoluteDate mjdDate;
  156.             private double  dtu1;
  157.             private double  lod;
  158.             private double  x;
  159.             private double  y;
  160.             private double  dpsi;
  161.             private double  deps;
  162.             private double  dx;
  163.             private double  dy;

  164.             // CHECKSTYLE: resume JavadocVariable check

  165.             /** File name. */
  166.             private final String name;

  167.             /** Buffer for read characters. */
  168.             private final StringBuilder buffer;

  169.             /** Indicator for daily data XML format or final data XML format. */
  170.             private DataFileContent content;

  171.             /** ITRF version configuration. */
  172.             private ITRFVersionLoader.ITRFVersionConfiguration configuration;

  173.             /** Simple constructor.
  174.              * @param name file name
  175.              */
  176.             EOPContentHandler(final String name) {
  177.                 this.name   = name;
  178.                 this.buffer = new StringBuilder();
  179.             }

  180.             /** {@inheritDoc} */
  181.             @Override
  182.             public void startDocument() {
  183.                 content       = DataFileContent.UNKNOWN;
  184.                 configuration = null;
  185.             }

  186.             /** {@inheritDoc} */
  187.             @Override
  188.             public void characters(final char[] ch, final int start, final int length) {
  189.                 buffer.append(ch, start, length);
  190.             }

  191.             /** {@inheritDoc} */
  192.             @Override
  193.             public void startElement(final String uri, final String localName,
  194.                                      final String qName, final Attributes atts) {

  195.                 // reset the buffer to empty
  196.                 buffer.delete(0, buffer.length());

  197.                 if (content == DataFileContent.UNKNOWN) {
  198.                     // try to identify file content
  199.                     if (qName.equals(TIME_SERIES_ELT)) {
  200.                         // the file contains final data
  201.                         content = DataFileContent.DAILY;
  202.                     } else if (qName.equals(FINALS_ELT)) {
  203.                         // the file contains final data
  204.                         content = DataFileContent.FINAL;
  205.                     }
  206.                 }

  207.                 if (content == DataFileContent.DAILY) {
  208.                     startDailyElement(qName, atts);
  209.                 } else if (content == DataFileContent.FINAL) {
  210.                     startFinalElement(qName);
  211.                 }

  212.             }

  213.             /** Handle end of an element in a daily data file.
  214.              * @param qName name of the element
  215.              * @param atts element attributes
  216.              */
  217.             private void startDailyElement(final String qName, final Attributes atts) {
  218.                 if (qName.equals(TIME_SERIES_ELT)) {
  219.                     // reset EOP data
  220.                     resetEOPData();
  221.                 } else if (qName.equals(POLE_ELT) || qName.equals(UT_ELT) || qName.equals(NUTATION_ELT)) {
  222.                     final String source = atts.getValue(SOURCE_ATTR);
  223.                     if (source != null) {
  224.                         inBulletinA = source.equals(BULLETIN_A_SOURCE);
  225.                     }
  226.                 }
  227.             }

  228.             /** Handle end of an element in a final data file.
  229.              * @param qName name of the element
  230.              */
  231.             private void startFinalElement(final String qName) {
  232.                 if (qName.equals(EOP_SET_ELT)) {
  233.                     // reset EOP data
  234.                     resetEOPData();
  235.                 } else if (qName.equals(BULLETIN_A_ELT)) {
  236.                     inBulletinA = true;
  237.                 }
  238.             }

  239.             /** Reset EOP data.
  240.              */
  241.             private void resetEOPData() {
  242.                 inBulletinA = false;
  243.                 year        = -1;
  244.                 month       = -1;
  245.                 day         = -1;
  246.                 mjd         = -1;
  247.                 mjdDate     = null;
  248.                 dtu1        = Double.NaN;
  249.                 lod         = Double.NaN;
  250.                 x           = Double.NaN;
  251.                 y           = Double.NaN;
  252.                 dpsi        = Double.NaN;
  253.                 deps        = Double.NaN;
  254.                 dx          = Double.NaN;
  255.                 dy          = Double.NaN;
  256.             }

  257.             /** {@inheritDoc} */
  258.             @Override
  259.             public void endElement(final String uri, final String localName, final String qName) {
  260.                 if (content == DataFileContent.DAILY) {
  261.                     endDailyElement(qName);
  262.                 } else if (content == DataFileContent.FINAL) {
  263.                     endFinalElement(qName);
  264.                 }
  265.             }

  266.             /** Handle end of an element in a daily data file.
  267.              * @param qName name of the element
  268.              */
  269.             private void endDailyElement(final String qName) {
  270.                 if (qName.equals(DATE_YEAR_ELT) && buffer.length() > 0) {
  271.                     year = Integer.parseInt(buffer.toString());
  272.                 } else if (qName.equals(DATE_MONTH_ELT) && buffer.length() > 0) {
  273.                     month = Integer.parseInt(buffer.toString());
  274.                 } else if (qName.equals(DATE_DAY_ELT) && buffer.length() > 0) {
  275.                     day = Integer.parseInt(buffer.toString());
  276.                 } else if (qName.equals(MJD_ELT) && buffer.length() > 0) {
  277.                     mjd     = Integer.parseInt(buffer.toString());
  278.                     mjdDate = new AbsoluteDate(new DateComponents(DateComponents.MODIFIED_JULIAN_EPOCH, mjd),
  279.                                                getUtc());
  280.                 } else if (qName.equals(UT1_M_UTC_ELT)) {
  281.                     dtu1 = overwrite(dtu1, Unit.SECOND);
  282.                 } else if (qName.equals(LOD_ELT)) {
  283.                     lod = overwrite(lod, MILLI_SECOND);
  284.                 } else if (qName.equals(X_ELT)) {
  285.                     x = overwrite(x, Unit.ARC_SECOND);
  286.                 } else if (qName.equals(Y_ELT)) {
  287.                     y = overwrite(y, Unit.ARC_SECOND);
  288.                 } else if (qName.equals(DPSI_ELT)) {
  289.                     dpsi = overwrite(dpsi, MILLI_ARC_SECOND);
  290.                 } else if (qName.equals(DEPSILON_ELT)) {
  291.                     deps = overwrite(deps, MILLI_ARC_SECOND);
  292.                 } else if (qName.equals(DX_ELT)) {
  293.                     dx   = overwrite(dx, MILLI_ARC_SECOND);
  294.                 } else if (qName.equals(DY_ELT)) {
  295.                     dy   = overwrite(dy, MILLI_ARC_SECOND);
  296.                 } else if (qName.equals(POLE_ELT) || qName.equals(UT_ELT) || qName.equals(NUTATION_ELT)) {
  297.                     inBulletinA = false;
  298.                 } else if (qName.equals(DATA_EOP_ELT)) {
  299.                     checkDates();
  300.                     if (!Double.isNaN(dtu1) && !Double.isNaN(lod) && !Double.isNaN(x) && !Double.isNaN(y)) {
  301.                         final double[] equinox;
  302.                         final double[] nro;
  303.                         if (Double.isNaN(dpsi)) {
  304.                             nro = new double[] {
  305.                                 dx, dy
  306.                             };
  307.                             equinox = getConverter().toEquinox(mjdDate, nro[0], nro[1]);
  308.                         } else {
  309.                             equinox = new double[] {
  310.                                 dpsi, deps
  311.                             };
  312.                             nro = getConverter().toNonRotating(mjdDate, equinox[0], equinox[1]);
  313.                         }
  314.                         if (configuration == null || !configuration.isValid(mjd)) {
  315.                             // get a configuration for current name and date range
  316.                             configuration = getItrfVersionProvider().getConfiguration(name, mjd);
  317.                         }
  318.                         history.add(new EOPEntry(mjd, dtu1, lod, x, y, equinox[0], equinox[1], nro[0], nro[1],
  319.                                                  configuration.getVersion(), mjdDate));
  320.                     }
  321.                 }
  322.             }

  323.             /** Handle end of an element in a final data file.
  324.              * @param qName name of the element
  325.              */
  326.             private void endFinalElement(final String qName) {
  327.                 if (qName.equals(DATE_ELT) && buffer.length() > 0) {
  328.                     final String[] fields = buffer.toString().split("-");
  329.                     if (fields.length == 3) {
  330.                         year  = Integer.parseInt(fields[0]);
  331.                         month = Integer.parseInt(fields[1]);
  332.                         day   = Integer.parseInt(fields[2]);
  333.                     }
  334.                 } else if (qName.equals(MJD_ELT) && buffer.length() > 0) {
  335.                     mjd     = Integer.parseInt(buffer.toString());
  336.                     mjdDate = new AbsoluteDate(new DateComponents(DateComponents.MODIFIED_JULIAN_EPOCH, mjd),
  337.                                                getUtc());
  338.                 } else if (qName.equals(UT1_U_UTC_ELT)) {
  339.                     dtu1 = overwrite(dtu1, Unit.SECOND);
  340.                 } else if (qName.equals(LOD_ELT)) {
  341.                     lod = overwrite(lod, MILLI_SECOND);
  342.                 } else if (qName.equals(X_ELT)) {
  343.                     x = overwrite(x, Unit.ARC_SECOND);
  344.                 } else if (qName.equals(Y_ELT)) {
  345.                     y = overwrite(y, Unit.ARC_SECOND);
  346.                 } else if (qName.equals(DPSI_ELT)) {
  347.                     dpsi = overwrite(dpsi, MILLI_ARC_SECOND);
  348.                 } else if (qName.equals(DEPSILON_ELT)) {
  349.                     deps = overwrite(deps, MILLI_ARC_SECOND);
  350.                 } else if (qName.equals(DX_ELT)) {
  351.                     dx   = overwrite(dx, MILLI_ARC_SECOND);
  352.                 } else if (qName.equals(DY_ELT)) {
  353.                     dy   = overwrite(dy, MILLI_ARC_SECOND);
  354.                 } else if (qName.equals(BULLETIN_A_ELT)) {
  355.                     inBulletinA = false;
  356.                 } else if (qName.equals(EOP_SET_ELT)) {
  357.                     checkDates();
  358.                     if (!Double.isNaN(dtu1) && !Double.isNaN(lod) && !Double.isNaN(x) && !Double.isNaN(y)) {
  359.                         final double[] equinox;
  360.                         final double[] nro;
  361.                         if (Double.isNaN(dpsi)) {
  362.                             nro = new double[] {
  363.                                 dx, dy
  364.                             };
  365.                             equinox = getConverter().toEquinox(mjdDate, nro[0], nro[1]);
  366.                         } else {
  367.                             equinox = new double[] {
  368.                                 dpsi, deps
  369.                             };
  370.                             nro = getConverter().toNonRotating(mjdDate, equinox[0], equinox[1]);
  371.                         }
  372.                         if (configuration == null || !configuration.isValid(mjd)) {
  373.                             // get a configuration for current name and date range
  374.                             configuration = getItrfVersionProvider().getConfiguration(name, mjd);
  375.                         }
  376.                         history.add(new EOPEntry(mjd, dtu1, lod, x, y, equinox[0], equinox[1], nro[0], nro[1],
  377.                                                  configuration.getVersion(), mjdDate));
  378.                     }
  379.                 }
  380.             }

  381.             /** Overwrite a value if it is not set or if we are in a bulletinB.
  382.              * @param oldValue old value to overwrite (may be NaN)
  383.              * @param units units of raw data
  384.              * @return a new value
  385.              */
  386.             private double overwrite(final double oldValue, final Unit units) {
  387.                 if (buffer.length() == 0) {
  388.                     // there is nothing to overwrite with
  389.                     return oldValue;
  390.                 } else if (inBulletinA && !Double.isNaN(oldValue)) {
  391.                     // the value is already set and bulletin A values have a low priority
  392.                     return oldValue;
  393.                 } else {
  394.                     // either the value is not set or it is a high priority bulletin B value
  395.                     return units.toSI(Double.parseDouble(buffer.toString()));
  396.                 }
  397.             }

  398.             /** Check if the year, month, day date and MJD date are consistent.
  399.              */
  400.             private void checkDates() {
  401.                 if (new DateComponents(year, month, day).getMJD() != mjd) {
  402.                     throw new OrekitException(OrekitMessages.INCONSISTENT_DATES_IN_IERS_FILE,
  403.                                               name, year, month, day, mjd);
  404.                 }
  405.             }

  406.             /** {@inheritDoc} */
  407.             @Override
  408.             public InputSource resolveEntity(final String publicId, final String systemId) {
  409.                 // disable external entities
  410.                 return new InputSource();
  411.             }

  412.         }

  413.     }

  414.     /** Enumerate for data file content. */
  415.     private enum DataFileContent {

  416.         /** Unknown content. */
  417.         UNKNOWN,

  418.         /** Daily data. */
  419.         DAILY,

  420.         /** Final data. */
  421.         FINAL

  422.     }

  423. }