SinexLoader.java

  1. /* Copyright 2002-2021 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.files.sinex;

  18. import java.io.BufferedInputStream;
  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.Collections;
  26. import java.util.HashMap;
  27. import java.util.Map;
  28. import java.util.regex.Pattern;

  29. import org.hipparchus.exception.DummyLocalizable;
  30. import org.hipparchus.geometry.euclidean.threed.Vector3D;
  31. import org.hipparchus.util.FastMath;
  32. import org.orekit.annotation.DefaultDataContext;
  33. import org.orekit.data.DataContext;
  34. import org.orekit.data.DataLoader;
  35. import org.orekit.data.DataProvidersManager;
  36. import org.orekit.data.DataSource;
  37. import org.orekit.errors.OrekitException;
  38. import org.orekit.errors.OrekitMessages;
  39. import org.orekit.files.sinex.Station.ReferenceSystem;
  40. import org.orekit.time.AbsoluteDate;
  41. import org.orekit.time.DateComponents;
  42. import org.orekit.time.TimeScale;
  43. import org.orekit.utils.Constants;

  44. /**
  45.  * Loader for Solution INdependent EXchange (SINEX) files.
  46.  * <p>
  47.  * For now only few keys are supported: SITE/ID, SITE/ECCENTRICITY, SOLUTION/EPOCHS and SOLUTION/ESTIMATE.
  48.  * They represent the minimum set of parameters that are interesting to consider in a SINEX file.
  49.  * </p>
  50.  * @author Bryan Cazabonne
  51.  * @since 10.3
  52.  */
  53. public class SinexLoader {

  54.     /** Pattern for delimiting regular expressions. */
  55.     private static final Pattern SEPARATOR = Pattern.compile(":");

  56.     /** Station data.
  57.      * Key: Site code
  58.      */
  59.     private final Map<String, Station> stations;

  60.     /** UTC time scale. */
  61.     private final TimeScale utc;

  62.     /** Simple constructor. This constructor uses the {@link DataContext#getDefault()
  63.      * default data context}.
  64.      * @param supportedNames regular expression for supported files names
  65.      * @see #SinexLoader(String, DataProvidersManager, TimeScale)
  66.      */
  67.     @DefaultDataContext
  68.     public SinexLoader(final String supportedNames) {
  69.         this(supportedNames,
  70.              DataContext.getDefault().getDataProvidersManager(),
  71.              DataContext.getDefault().getTimeScales().getUTC());
  72.     }

  73.     /**
  74.      * Construct a loader by specifying the source of SINEX auxiliary data files.
  75.      * @param supportedNames regular expression for supported files names
  76.      * @param dataProvidersManager provides access to auxiliary data.
  77.      * @param utc UTC time scale
  78.      */
  79.     public SinexLoader(final String supportedNames,
  80.                        final DataProvidersManager dataProvidersManager,
  81.                        final TimeScale utc) {
  82.         this.utc = utc;
  83.         stations = new HashMap<>();
  84.         dataProvidersManager.feed(supportedNames, new Parser());
  85.     }

  86.     /** Simple constructor. This constructor uses the {@link DataContext#getDefault()
  87.      * default data context}.
  88.      * @param source source for the RINEX data
  89.      * @see #SinexLoader(String, DataProvidersManager, TimeScale)
  90.      */
  91.     @DefaultDataContext
  92.     public SinexLoader(final DataSource source) {
  93.         this(source, DataContext.getDefault().getTimeScales().getUTC());
  94.     }

  95.     /**
  96.      * Loads SINEX from the given input stream using the specified auxiliary data.
  97.      * @param source source for the RINEX data
  98.      * @param utc UTC time scale
  99.      */
  100.     public SinexLoader(final DataSource source, final TimeScale utc) {
  101.         try {
  102.             this.utc = utc;
  103.             stations = new HashMap<>();
  104.             try (InputStream         is  = source.getOpener().openStreamOnce();
  105.                  BufferedInputStream bis = new BufferedInputStream(is)) {
  106.                 new Parser().loadData(bis, source.getName());
  107.             }
  108.         } catch (IOException | ParseException ioe) {
  109.             throw new OrekitException(ioe, new DummyLocalizable(ioe.getMessage()));
  110.         }
  111.     }

  112.     /**
  113.      * Get the parsed station data.
  114.      * @return unmodifiable view of parsed station data
  115.      */
  116.     public Map<String, Station> getStations() {
  117.         return Collections.unmodifiableMap(stations);
  118.     }

  119.     /**
  120.      * Get the station corresponding to the given site code.
  121.      * @param siteCode site code
  122.      * @return the corresponding station
  123.      */
  124.     public Station getStation(final String siteCode) {
  125.         return stations.get(siteCode);
  126.     }

  127.     /**
  128.      * Add a new entry to the map of stations.
  129.      * @param station station entry to add
  130.      */
  131.     private void addStation(final Station station) {
  132.         // Check if station already exists
  133.         if (stations.get(station.getSiteCode()) == null) {
  134.             stations.put(station.getSiteCode(), station);
  135.         }
  136.     }

  137.     /** Parser for SINEX files. */
  138.     private class Parser implements DataLoader {

  139.         /** Start character of a comment line. */
  140.         private static final String COMMENT = "*";

  141.         /** {@inheritDoc} */
  142.         @Override
  143.         public boolean stillAcceptsData() {
  144.             // We load all SINEX files we can find
  145.             return true;
  146.         }

  147.         /** {@inheritDoc} */
  148.         @Override
  149.         public void loadData(final InputStream input, final String name)
  150.             throws IOException, ParseException {

  151.             // Useful parameters
  152.             int lineNumber     = 0;
  153.             String line        = null;
  154.             boolean inId       = false;
  155.             boolean inEcc      = false;
  156.             boolean inEpoch    = false;
  157.             boolean inEstimate = false;
  158.             Vector3D position  = Vector3D.ZERO;
  159.             Vector3D velocity  = Vector3D.ZERO;

  160.             try (BufferedReader reader = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8))) {

  161.                 // Loop on lines
  162.                 for (line = reader.readLine(); line != null; line = reader.readLine()) {
  163.                     ++lineNumber;
  164.                     // For now, only few keys are supported
  165.                     // They represent the minimum set of parameters that are interesting to consider in a SINEX file
  166.                     // Other keys can be added depending user needs
  167.                     switch(line.trim()) {
  168.                         case "+SITE/ID" :
  169.                             // Start of site id. data
  170.                             inId = true;
  171.                             break;
  172.                         case "-SITE/ID" :
  173.                             // End of site id. data
  174.                             inId = false;
  175.                             break;
  176.                         case "+SITE/ECCENTRICITY" :
  177.                             // Start of antenna eccentricities data
  178.                             inEcc = true;
  179.                             break;
  180.                         case "-SITE/ECCENTRICITY" :
  181.                             // End of antenna eccentricities data
  182.                             inEcc = false;
  183.                             break;
  184.                         case "+SOLUTION/EPOCHS" :
  185.                             // Start of epoch data
  186.                             inEpoch = true;
  187.                             break;
  188.                         case "-SOLUTION/EPOCHS" :
  189.                             // End of epoch data
  190.                             inEpoch = false;
  191.                             break;
  192.                         case "+SOLUTION/ESTIMATE" :
  193.                             // Start of coordinates data
  194.                             inEstimate = true;
  195.                             break;
  196.                         case "-SOLUTION/ESTIMATE" :
  197.                             // Start of coordinates data
  198.                             inEstimate = false;
  199.                             break;
  200.                         default:
  201.                             if (line.startsWith(COMMENT)) {
  202.                                 // ignore that line
  203.                             } else {
  204.                                 // parsing data
  205.                                 if (inId) {
  206.                                     // read site id. data
  207.                                     final Station station = new Station();
  208.                                     station.setSiteCode(parseString(line, 1, 4));
  209.                                     station.setDomes(parseString(line, 9, 9));
  210.                                     // add the station to the map
  211.                                     addStation(station);
  212.                                 } else if (inEcc) {
  213.                                     // read antenna eccentricities data
  214.                                     final Station station = getStation(parseString(line, 1, 4));
  215.                                     // check if start and end dates have been set
  216.                                     if (station.getValidFrom() == null) {
  217.                                         station.setValidFrom(stringEpochToAbsoluteDate(parseString(line, 16, 12)));
  218.                                         station.setValidUntil(stringEpochToAbsoluteDate(parseString(line, 29, 12)));
  219.                                     }
  220.                                     station.setEccRefSystem(ReferenceSystem.getEccRefSystem(parseString(line, 42, 3)));
  221.                                     station.setEccentricities(new Vector3D(parseDouble(line, 46, 8),
  222.                                                                            parseDouble(line, 55, 8),
  223.                                                                            parseDouble(line, 64, 8)));
  224.                                 } else if (inEpoch) {
  225.                                     // read epoch data
  226.                                     final Station station = getStation(parseString(line, 1, 4));
  227.                                     station.setValidFrom(stringEpochToAbsoluteDate(parseString(line, 16, 12)));
  228.                                     station.setValidUntil(stringEpochToAbsoluteDate(parseString(line, 29, 12)));
  229.                                 } else if (inEstimate) {
  230.                                     final Station station = getStation(parseString(line, 14, 4));
  231.                                     // check if this station exists
  232.                                     if (station != null) {
  233.                                         // switch on coordinates data
  234.                                         switch(parseString(line, 7, 6)) {
  235.                                             case "STAX":
  236.                                                 // station X coordinate
  237.                                                 final double x = parseDouble(line, 47, 22);
  238.                                                 position = new Vector3D(x, position.getY(), position.getZ());
  239.                                                 station.setPosition(position);
  240.                                                 break;
  241.                                             case "STAY":
  242.                                                 // station Y coordinate
  243.                                                 final double y = parseDouble(line, 47, 22);
  244.                                                 position = new Vector3D(position.getX(), y, position.getZ());
  245.                                                 station.setPosition(position);
  246.                                                 break;
  247.                                             case "STAZ":
  248.                                                 // station Z coordinate
  249.                                                 final double z = parseDouble(line, 47, 22);
  250.                                                 position = new Vector3D(position.getX(), position.getY(), z);
  251.                                                 station.setPosition(position);
  252.                                                 // set the reference epoch (identical for all coordinates)
  253.                                                 station.setEpoch(stringEpochToAbsoluteDate(parseString(line, 27, 12)));
  254.                                                 // reset position vector
  255.                                                 position = Vector3D.ZERO;
  256.                                                 break;
  257.                                             case "VELX":
  258.                                                 // station X velocity (value is in m/y)
  259.                                                 final double vx = parseDouble(line, 47, 22) / Constants.JULIAN_YEAR;
  260.                                                 velocity = new Vector3D(vx, velocity.getY(), velocity.getZ());
  261.                                                 station.setVelocity(velocity);
  262.                                                 break;
  263.                                             case "VELY":
  264.                                                 // station Y velocity (value is in m/y)
  265.                                                 final double vy = parseDouble(line, 47, 22) / Constants.JULIAN_YEAR;
  266.                                                 velocity = new Vector3D(velocity.getX(), vy, velocity.getZ());
  267.                                                 station.setVelocity(velocity);
  268.                                                 break;
  269.                                             case "VELZ":
  270.                                                 // station Z velocity (value is in m/y)
  271.                                                 final double vz = parseDouble(line, 47, 22) / Constants.JULIAN_YEAR;
  272.                                                 velocity = new Vector3D(velocity.getX(), velocity.getY(), vz);
  273.                                                 station.setVelocity(velocity);
  274.                                                 // reset position vector
  275.                                                 velocity = Vector3D.ZERO;
  276.                                                 break;
  277.                                             default:
  278.                                                 // ignore that field
  279.                                                 break;
  280.                                         }
  281.                                     }

  282.                                 } else {
  283.                                     // not supported line, ignore it
  284.                                 }
  285.                             }
  286.                             break;
  287.                     }
  288.                 }

  289.             } catch (NumberFormatException nfe) {
  290.                 throw new OrekitException(OrekitMessages.UNABLE_TO_PARSE_LINE_IN_FILE,
  291.                                           lineNumber, name, line);
  292.             }

  293.         }

  294.         /** Extract a string from a line.
  295.          * @param line to parse
  296.          * @param start start index of the string
  297.          * @param length length of the string
  298.          * @return parsed string
  299.          */
  300.         private String parseString(final String line, final int start, final int length) {
  301.             return line.substring(start, FastMath.min(line.length(), start + length)).trim();
  302.         }

  303.         /** Extract a double from a line.
  304.          * @param line to parse
  305.          * @param start start index of the real
  306.          * @param length length of the real
  307.          * @return parsed real
  308.          */
  309.         private double parseDouble(final String line, final int start, final int length) {
  310.             return Double.parseDouble(parseString(line, start, length));
  311.         }

  312.     }

  313.     /**
  314.      * Transform a String epoch to an AbsoluteDate.
  315.      * @param stringDate string epoch
  316.      * @return the corresponding AbsoluteDate
  317.      */
  318.     private AbsoluteDate stringEpochToAbsoluteDate(final String stringDate) {
  319.         // Date components
  320.         final String[] fields = SEPARATOR.split(stringDate);

  321.         // Read fields
  322.         final int twoDigitsYear = Integer.parseInt(fields[0]);
  323.         final int day           = Integer.parseInt(fields[1]);
  324.         final int secInDay      = Integer.parseInt(fields[2]);

  325.         // Data year
  326.         final int year;
  327.         if (twoDigitsYear > 50) {
  328.             year = 1900 + twoDigitsYear;
  329.         } else {
  330.             year = 2000 + twoDigitsYear;
  331.         }

  332.         // Return an absolute date.
  333.         // Initialize to 1st January of the given year because
  334.         // sometimes day in equal to 0 in the file.
  335.         return new AbsoluteDate(new DateComponents(year, 1, 1), utc).
  336.                         shiftedBy(Constants.JULIAN_DAY * (day - 1)).
  337.                         shiftedBy(secInDay);
  338.     }

  339. }