SINEXLoader.java

  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.files.sinex;

  18. import java.io.BufferedReader;
  19. import java.io.IOException;
  20. import java.io.InputStream;
  21. import java.io.InputStreamReader;
  22. import java.nio.charset.StandardCharsets;
  23. import java.text.ParseException;
  24. import java.util.Collections;
  25. import java.util.HashMap;
  26. import java.util.Map;
  27. import java.util.regex.Pattern;

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

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

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

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

  58.     /** UTC time scale. */
  59.     private final TimeScale utc;

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

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

  84.     /** Simple constructor. This constructor uses the {@link DataContext#getDefault()
  85.      * default data context}.
  86.      * @param input data input stream
  87.      * @param name name of the file (or zip entry)
  88.      * @see #SINEXLoader(InputStream, String, TimeScale)
  89.      */
  90.     @DefaultDataContext
  91.     public SINEXLoader(final InputStream input, final String name) {
  92.         this(input, name, DataContext.getDefault().getTimeScales().getUTC());
  93.     }

  94.     /**
  95.      * Loads SINEX from the given input stream using the specified auxiliary data.
  96.      * @param input data input stream
  97.      * @param name name of the file (or zip entry)
  98.      * @param utc UTC time scale
  99.      */
  100.     public SINEXLoader(final InputStream input,
  101.                        final String name,
  102.                        final TimeScale utc) {
  103.         try {
  104.             this.utc = utc;
  105.             stations = new HashMap<>();
  106.             new Parser().loadData(input, name);
  107.         } catch (IOException | ParseException ioe) {
  108.             throw new OrekitException(ioe, new DummyLocalizable(ioe.getMessage()));
  109.         }
  110.     }

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

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

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

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

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

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

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

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

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

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

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

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

  292.         }

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

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

  311.     }

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

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

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

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

  338. }