SP3Parser.java

  1. /* Copyright 2002-2012 Space Applications Services
  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.sp3;

  18. import java.io.BufferedReader;
  19. import java.io.IOException;
  20. import java.io.Reader;
  21. import java.util.ArrayList;
  22. import java.util.List;
  23. import java.util.Locale;
  24. import java.util.Optional;
  25. import java.util.Scanner;
  26. import java.util.function.Function;
  27. import java.util.regex.Pattern;
  28. import java.util.stream.Stream;

  29. import org.hipparchus.exception.LocalizedCoreFormats;
  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.DataSource;
  35. import org.orekit.errors.OrekitException;
  36. import org.orekit.errors.OrekitIllegalArgumentException;
  37. import org.orekit.errors.OrekitMessages;
  38. import org.orekit.files.general.EphemerisFileParser;
  39. import org.orekit.files.sp3.SP3.SP3Coordinate;
  40. import org.orekit.files.sp3.SP3.SP3FileType;
  41. import org.orekit.frames.Frame;
  42. import org.orekit.gnss.TimeSystem;
  43. import org.orekit.time.AbsoluteDate;
  44. import org.orekit.time.DateComponents;
  45. import org.orekit.time.DateTimeComponents;
  46. import org.orekit.time.TimeComponents;
  47. import org.orekit.time.TimeScale;
  48. import org.orekit.time.TimeScales;
  49. import org.orekit.utils.CartesianDerivativesFilter;
  50. import org.orekit.utils.Constants;
  51. import org.orekit.utils.IERSConventions;

  52. /** A parser for the SP3 orbit file format. It supports all formats from sp3-a
  53.  * to sp3-d.
  54.  * <p>
  55.  * <b>Note:</b> this parser is thread-safe, so calling {@link #parse} from
  56.  * different threads is allowed.
  57.  * </p>
  58.  * @see <a href="ftp://igs.org/pub/data/format/sp3_docu.txt">SP3-a file format</a>
  59.  * @see <a href="ftp://igs.org/pub/data/format/sp3c.txt">SP3-c file format</a>
  60.  * @see <a href="ftp://igs.org/pub/data/format/sp3d.pdf">SP3-d file format</a>
  61.  * @author Thomas Neidhart
  62.  * @author Luc Maisonobe
  63.  */
  64. public class SP3Parser implements EphemerisFileParser<SP3> {

  65.     /** Bad or absent clock values are to be set to 999999.999999. */
  66.     public static final double DEFAULT_CLOCK_VALUE = 999999.999999;

  67.     /** Spaces delimiters. */
  68.     private static final String SPACES = "\\s+";

  69.     /** One millimeter, in meters. */
  70.     private static final double MILLIMETER = 1.0e-3;

  71.     /** Standard gravitational parameter in m^3 / s^2. */
  72.     private final double mu;
  73.     /** Number of data points to use in interpolation. */
  74.     private final int interpolationSamples;
  75.     /** Mapping from frame identifier in the file to a {@link Frame}. */
  76.     private final Function<? super String, ? extends Frame> frameBuilder;
  77.     /** Set of time scales. */
  78.     private final TimeScales timeScales;

  79.     /**
  80.      * Create an SP3 parser using default values.
  81.      *
  82.      * <p>This constructor uses the {@link DataContext#getDefault() default data context}.
  83.      *
  84.      * @see #SP3Parser(double, int, Function)
  85.      */
  86.     @DefaultDataContext
  87.     public SP3Parser() {
  88.         this(Constants.EIGEN5C_EARTH_MU, 7, SP3Parser::guessFrame);
  89.     }

  90.     /**
  91.      * Create an SP3 parser and specify the extra information needed to create a {@link
  92.      * org.orekit.propagation.Propagator Propagator} from the ephemeris data.
  93.      *
  94.      * <p>This constructor uses the {@link DataContext#getDefault() default data context}.
  95.      *
  96.      * @param mu                   is the standard gravitational parameter to use for
  97.      *                             creating {@link org.orekit.orbits.Orbit Orbits} from
  98.      *                             the ephemeris data. See {@link Constants}.
  99.      * @param interpolationSamples is the number of samples to use when interpolating.
  100.      * @param frameBuilder         is a function that can construct a frame from an SP3
  101.      *                             coordinate system string. The coordinate system can be
  102.      *                             any 5 character string e.g. ITR92, IGb08.
  103.      * @see #SP3Parser(double, int, Function, TimeScales)
  104.      */
  105.     @DefaultDataContext
  106.     public SP3Parser(final double mu,
  107.                      final int interpolationSamples,
  108.                      final Function<? super String, ? extends Frame> frameBuilder) {
  109.         this(mu, interpolationSamples, frameBuilder,
  110.                 DataContext.getDefault().getTimeScales());
  111.     }

  112.     /**
  113.      * Create an SP3 parser and specify the extra information needed to create a {@link
  114.      * org.orekit.propagation.Propagator Propagator} from the ephemeris data.
  115.      *
  116.      * @param mu                   is the standard gravitational parameter to use for
  117.      *                             creating {@link org.orekit.orbits.Orbit Orbits} from
  118.      *                             the ephemeris data. See {@link Constants}.
  119.      * @param interpolationSamples is the number of samples to use when interpolating.
  120.      * @param frameBuilder         is a function that can construct a frame from an SP3
  121.      *                             coordinate system string. The coordinate system can be
  122.      * @param timeScales           the set of time scales used for parsing dates.
  123.      * @since 10.1
  124.      */
  125.     public SP3Parser(final double mu,
  126.                      final int interpolationSamples,
  127.                      final Function<? super String, ? extends Frame> frameBuilder,
  128.                      final TimeScales timeScales) {
  129.         this.mu = mu;
  130.         this.interpolationSamples = interpolationSamples;
  131.         this.frameBuilder = frameBuilder;
  132.         this.timeScales = timeScales;
  133.     }

  134.     /**
  135.      * Default string to {@link Frame} conversion for {@link #SP3Parser()}.
  136.      *
  137.      * <p>This method uses the {@link DataContext#getDefault() default data context}.
  138.      *
  139.      * @param name of the frame.
  140.      * @return ITRF based on 2010 conventions,
  141.      * with tidal effects considered during EOP interpolation.
  142.      */
  143.     @DefaultDataContext
  144.     private static Frame guessFrame(final String name) {
  145.         return DataContext.getDefault().getFrames()
  146.                 .getITRF(IERSConventions.IERS_2010, false);
  147.     }

  148.     @Override
  149.     public SP3 parse(final DataSource source) {

  150.         try (Reader reader = source.getOpener().openReaderOnce();
  151.              BufferedReader br = (reader == null) ? null : new BufferedReader(reader)) {

  152.             if (br == null) {
  153.                 throw new OrekitException(OrekitMessages.UNABLE_TO_FIND_FILE, source.getName());
  154.             }

  155.             // initialize internal data structures
  156.             final ParseInfo pi = new ParseInfo();

  157.             int lineNumber = 0;
  158.             Stream<LineParser> candidateParsers = Stream.of(LineParser.HEADER_VERSION);
  159.             for (String line = br.readLine(); line != null; line = br.readLine()) {
  160.                 ++lineNumber;
  161.                 final String l = line;
  162.                 final Optional<LineParser> selected = candidateParsers.filter(p -> p.canHandle(l)).findFirst();
  163.                 if (selected.isPresent()) {
  164.                     try {
  165.                         selected.get().parse(line, pi);
  166.                     } catch (StringIndexOutOfBoundsException | NumberFormatException e) {
  167.                         throw new OrekitException(e,
  168.                                                   OrekitMessages.UNABLE_TO_PARSE_LINE_IN_FILE,
  169.                                                   lineNumber, source.getName(), line);
  170.                     }
  171.                     candidateParsers = selected.get().allowedNext();
  172.                 } else {
  173.                     throw new OrekitException(OrekitMessages.UNABLE_TO_PARSE_LINE_IN_FILE,
  174.                                               lineNumber, source.getName(), line);
  175.                 }
  176.                 if (pi.done) {
  177.                     if (pi.nbEpochs != pi.file.getNumberOfEpochs()) {
  178.                         throw new OrekitException(OrekitMessages.SP3_NUMBER_OF_EPOCH_MISMATCH,
  179.                                                   pi.nbEpochs, source.getName(), pi.file.getNumberOfEpochs());
  180.                     }
  181.                     return pi.file;
  182.                 }
  183.             }

  184.             // we never reached the EOF marker
  185.             throw new OrekitException(OrekitMessages.SP3_UNEXPECTED_END_OF_FILE, lineNumber);

  186.         } catch (IOException ioe) {
  187.             throw new OrekitException(ioe, LocalizedCoreFormats.SIMPLE_MESSAGE, ioe.getLocalizedMessage());
  188.         }

  189.     }

  190.     /** Returns the {@link SP3FileType} that corresponds to a given string in a SP3 file.
  191.      * @param fileType file type as string
  192.      * @return file type as enum
  193.      */
  194.     private static SP3FileType getFileType(final String fileType) {
  195.         SP3FileType type = SP3FileType.UNDEFINED;
  196.         if ("G".equalsIgnoreCase(fileType)) {
  197.             type = SP3FileType.GPS;
  198.         } else if ("M".equalsIgnoreCase(fileType)) {
  199.             type = SP3FileType.MIXED;
  200.         } else if ("R".equalsIgnoreCase(fileType)) {
  201.             type = SP3FileType.GLONASS;
  202.         } else if ("L".equalsIgnoreCase(fileType)) {
  203.             type = SP3FileType.LEO;
  204.         } else if ("S".equalsIgnoreCase(fileType)) {
  205.             type = SP3FileType.SBAS;
  206.         } else if ("I".equalsIgnoreCase(fileType)) {
  207.             type = SP3FileType.IRNSS;
  208.         } else if ("E".equalsIgnoreCase(fileType)) {
  209.             type = SP3FileType.GALILEO;
  210.         } else if ("C".equalsIgnoreCase(fileType)) {
  211.             type = SP3FileType.COMPASS;
  212.         } else if ("J".equalsIgnoreCase(fileType)) {
  213.             type = SP3FileType.QZSS;
  214.         }
  215.         return type;
  216.     }

  217.     /** Transient data used for parsing a sp3 file. The data is kept in a
  218.      * separate data structure to make the parser thread-safe.
  219.      * <p><b>Note</b>: The class intentionally does not provide accessor
  220.      * methods, as it is only used internally for parsing a SP3 file.</p>
  221.      */
  222.     private class ParseInfo {

  223.         /** Set of time scales for parsing dates. */
  224.         private final TimeScales timeScales;

  225.         /** The corresponding SP3File object. */
  226.         private SP3 file;

  227.         /** The latest epoch as read from the SP3 file. */
  228.         private AbsoluteDate latestEpoch;

  229.         /** The latest position as read from the SP3 file. */
  230.         private Vector3D latestPosition;

  231.         /** The latest clock value as read from the SP3 file. */
  232.         private double latestClock;

  233.         /** Indicates if the SP3 file has velocity entries. */
  234.         private boolean hasVelocityEntries;

  235.         /** The timescale used in the SP3 file. */
  236.         private TimeScale timeScale;

  237.         /** Date and time of the file. */
  238.         private DateTimeComponents epoch;

  239.         /** The number of satellites as contained in the SP3 file. */
  240.         private int maxSatellites;

  241.         /** The number of satellites accuracies already seen. */
  242.         private int nbAccuracies;

  243.         /** The number of epochs already seen. */
  244.         private int nbEpochs;

  245.         /** End Of File reached indicator. */
  246.         private boolean done;

  247.         /** The base for pos/vel. */
  248.         //private double posVelBase;

  249.         /** The base for clock/rate. */
  250.         //private double clockBase;

  251.         /** Create a new {@link ParseInfo} object. */
  252.         protected ParseInfo() {
  253.             this.timeScales = SP3Parser.this.timeScales;
  254.             file               = new SP3(mu, interpolationSamples, frameBuilder);
  255.             latestEpoch        = null;
  256.             latestPosition     = null;
  257.             latestClock        = 0.0;
  258.             hasVelocityEntries = false;
  259.             epoch              = DateTimeComponents.JULIAN_EPOCH;
  260.             timeScale          = timeScales.getGPS();
  261.             maxSatellites      = 0;
  262.             nbAccuracies       = 0;
  263.             nbEpochs           = 0;
  264.             done               = false;
  265.             //posVelBase = 2d;
  266.             //clockBase = 2d;
  267.         }
  268.     }

  269.     /** Parsers for specific lines. */
  270.     private enum LineParser {

  271.         /** Parser for version, epoch, data used and agency information. */
  272.         HEADER_VERSION("^#[a-z].*") {

  273.             /** {@inheritDoc} */
  274.             @Override
  275.             public void parse(final String line, final ParseInfo pi) {
  276.                 try (Scanner s1      = new Scanner(line);
  277.                      Scanner s2      = s1.useDelimiter(SPACES);
  278.                      Scanner scanner = s2.useLocale(Locale.US)) {
  279.                     scanner.skip("#");
  280.                     final String v = scanner.next();

  281.                     final char version = v.substring(0, 1).toLowerCase().charAt(0);
  282.                     if (version != 'a' && version != 'b' && version != 'c' && version != 'd') {
  283.                         throw new OrekitException(OrekitMessages.SP3_UNSUPPORTED_VERSION, version);
  284.                     }

  285.                     pi.hasVelocityEntries = "V".equals(v.substring(1, 2));
  286.                     pi.file.setFilter(pi.hasVelocityEntries ?
  287.                                       CartesianDerivativesFilter.USE_PV :
  288.                                       CartesianDerivativesFilter.USE_P);

  289.                     final int    year   = Integer.parseInt(v.substring(2));
  290.                     final int    month  = scanner.nextInt();
  291.                     final int    day    = scanner.nextInt();
  292.                     final int    hour   = scanner.nextInt();
  293.                     final int    minute = scanner.nextInt();
  294.                     final double second = scanner.nextDouble();

  295.                     pi.epoch = new DateTimeComponents(year, month, day,
  296.                                                       hour, minute, second);

  297.                     final int numEpochs = scanner.nextInt();
  298.                     pi.file.setNumberOfEpochs(numEpochs);

  299.                     // data used indicator
  300.                     pi.file.setDataUsed(scanner.next());

  301.                     pi.file.setCoordinateSystem(scanner.next());
  302.                     pi.file.setOrbitTypeKey(scanner.next());
  303.                     pi.file.setAgency(scanner.next());
  304.                 }
  305.             }

  306.             /** {@inheritDoc} */
  307.             @Override
  308.             public Stream<LineParser> allowedNext() {
  309.                 return Stream.of(HEADER_DATE_TIME_REFERENCE);
  310.             }

  311.         },

  312.         /** Parser for additional date/time references in gps/julian day notation. */
  313.         HEADER_DATE_TIME_REFERENCE("^##.*") {

  314.             /** {@inheritDoc} */
  315.             @Override
  316.             public void parse(final String line, final ParseInfo pi) {
  317.                 try (Scanner s1      = new Scanner(line);
  318.                      Scanner s2      = s1.useDelimiter(SPACES);
  319.                      Scanner scanner = s2.useLocale(Locale.US)) {
  320.                     scanner.skip("##");

  321.                     // gps week
  322.                     pi.file.setGpsWeek(scanner.nextInt());
  323.                     // seconds of week
  324.                     pi.file.setSecondsOfWeek(scanner.nextDouble());
  325.                     // epoch interval
  326.                     pi.file.setEpochInterval(scanner.nextDouble());
  327.                     // julian day
  328.                     pi.file.setJulianDay(scanner.nextInt());
  329.                     // day fraction
  330.                     pi.file.setDayFraction(scanner.nextDouble());
  331.                 }
  332.             }

  333.             /** {@inheritDoc} */
  334.             @Override
  335.             public Stream<LineParser> allowedNext() {
  336.                 return Stream.of(HEADER_SAT_IDS);
  337.             }

  338.         },

  339.         /** Parser for satellites identifiers. */
  340.         HEADER_SAT_IDS("^\\+ .*") {

  341.             /** {@inheritDoc} */
  342.             @Override
  343.             public void parse(final String line, final ParseInfo pi) {

  344.                 if (pi.maxSatellites == 0) {
  345.                     // this is the first ids line, it also contains the number of satellites
  346.                     pi.maxSatellites = Integer.parseInt(line.substring(3, 6).trim());
  347.                 }

  348.                 final int lineLength = line.length();
  349.                 int count = pi.file.getSatelliteCount();
  350.                 int startIdx = 9;
  351.                 while (count++ < pi.maxSatellites && (startIdx + 3) <= lineLength) {
  352.                     final String satId = line.substring(startIdx, startIdx + 3).trim();
  353.                     if (satId.length() > 0) {
  354.                         pi.file.addSatellite(satId);
  355.                     }
  356.                     startIdx += 3;
  357.                 }
  358.             }

  359.             /** {@inheritDoc} */
  360.             @Override
  361.             public Stream<LineParser> allowedNext() {
  362.                 return Stream.of(HEADER_SAT_IDS, HEADER_ACCURACY);
  363.             }

  364.         },

  365.         /** Parser for general accuracy information for each satellite. */
  366.         HEADER_ACCURACY("^\\+\\+.*") {

  367.             /** {@inheritDoc} */
  368.             @Override
  369.             public void parse(final String line, final ParseInfo pi) {
  370.                 final int lineLength = line.length();
  371.                 int startIdx = 9;
  372.                 while (pi.nbAccuracies < pi.maxSatellites && (startIdx + 3) <= lineLength) {
  373.                     final String sub = line.substring(startIdx, startIdx + 3).trim();
  374.                     if (sub.length() > 0) {
  375.                         final int exponent = Integer.parseInt(sub);
  376.                         // the accuracy is calculated as 2**exp (in mm)
  377.                         pi.file.setAccuracy(pi.nbAccuracies++, (2 << exponent) * MILLIMETER);
  378.                     }
  379.                     startIdx += 3;
  380.                 }
  381.             }

  382.             /** {@inheritDoc} */
  383.             @Override
  384.             public Stream<LineParser> allowedNext() {
  385.                 return Stream.of(HEADER_ACCURACY, HEADER_TIME_SYSTEM);
  386.             }

  387.         },

  388.         /** Parser for time system. */
  389.         HEADER_TIME_SYSTEM("^%c.*") {

  390.             /** {@inheritDoc} */
  391.             @Override
  392.             public void parse(final String line, final ParseInfo pi) {

  393.                 if (pi.file.getType() == null) {
  394.                     // this the first custom fields line, the only one really used
  395.                     pi.file.setType(getFileType(line.substring(3, 5).trim()));

  396.                     // now identify the time system in use
  397.                     final String tsStr = line.substring(9, 12).trim();
  398.                     final TimeSystem ts;
  399.                     if (tsStr.equalsIgnoreCase("ccc")) {
  400.                         ts = TimeSystem.GPS;
  401.                     } else {
  402.                         ts = TimeSystem.valueOf(tsStr);
  403.                     }
  404.                     pi.file.setTimeSystem(ts);
  405.                     pi.timeScale = ts.getTimeScale(pi.timeScales);

  406.                     // now we know the time scale used, we can set the file epoch
  407.                     pi.file.setEpoch(new AbsoluteDate(pi.epoch, pi.timeScale));
  408.                 }

  409.             }

  410.             /** {@inheritDoc} */
  411.             @Override
  412.             public Stream<LineParser> allowedNext() {
  413.                 return Stream.of(HEADER_TIME_SYSTEM, HEADER_STANDARD_DEVIATIONS);
  414.             }

  415.         },

  416.         /** Parser for standard deviations of position/velocity/clock components. */
  417.         HEADER_STANDARD_DEVIATIONS("^%f.*") {

  418.             /** {@inheritDoc} */
  419.             @Override
  420.             public void parse(final String line, final ParseInfo pi) {
  421.                 // String base = line.substring(3, 13).trim();
  422.                 // if (!base.equals("0.0000000")) {
  423.                 //    // (mm or 10**-4 mm/sec)
  424.                 //    pi.posVelBase = Double.valueOf(base);
  425.                 // }

  426.                 // base = line.substring(14, 26).trim();
  427.                 // if (!base.equals("0.000000000")) {
  428.                 //    // (psec or 10**-4 psec/sec)
  429.                 //    pi.clockBase = Double.valueOf(base);
  430.                 // }
  431.             }

  432.             /** {@inheritDoc} */
  433.             @Override
  434.             public Stream<LineParser> allowedNext() {
  435.                 return Stream.of(HEADER_STANDARD_DEVIATIONS, HEADER_CUSTOM_PARAMETERS);
  436.             }

  437.         },

  438.         /** Parser for custom parameters. */
  439.         HEADER_CUSTOM_PARAMETERS("^%i.*") {

  440.             /** {@inheritDoc} */
  441.             @Override
  442.             public void parse(final String line, final ParseInfo pi) {
  443.                 // ignore additional custom parameters
  444.             }

  445.             /** {@inheritDoc} */
  446.             @Override
  447.             public Stream<LineParser> allowedNext() {
  448.                 return Stream.of(HEADER_CUSTOM_PARAMETERS, HEADER_COMMENTS);
  449.             }

  450.         },

  451.         /** Parser for comments. */
  452.         HEADER_COMMENTS("^[%]?/\\*.*|") {

  453.             /** {@inheritDoc} */
  454.             @Override
  455.             public void parse(final String line, final ParseInfo pi) {
  456.                 // ignore comments
  457.             }

  458.             /** {@inheritDoc} */
  459.             @Override
  460.             public Stream<LineParser> allowedNext() {
  461.                 return Stream.of(HEADER_COMMENTS, DATA_EPOCH);
  462.             }

  463.         },

  464.         /** Parser for epoch. */
  465.         DATA_EPOCH("^\\* .*") {

  466.             /** {@inheritDoc} */
  467.             @Override
  468.             public void parse(final String line, final ParseInfo pi) {
  469.                 final int    year   = Integer.parseInt(line.substring(3, 7).trim());
  470.                 final int    month  = Integer.parseInt(line.substring(8, 10).trim());
  471.                 final int    day    = Integer.parseInt(line.substring(11, 13).trim());
  472.                 final int    hour   = Integer.parseInt(line.substring(14, 16).trim());
  473.                 final int    minute = Integer.parseInt(line.substring(17, 19).trim());
  474.                 final double second = Double.parseDouble(line.substring(20).trim());

  475.                 // some SP3 files have weird epochs as in the following two examples, where
  476.                 // the middle dates are wrong
  477.                 //
  478.                 // *  2016  7  6 16 58  0.00000000
  479.                 // PL51  11872.234459   3316.551981    101.400098 999999.999999
  480.                 // VL51   8054.606014 -27076.640110 -53372.762255 999999.999999
  481.                 // *  2016  7  6 16 60  0.00000000
  482.                 // PL51  11948.228978   2986.113872   -538.901114 999999.999999
  483.                 // VL51   4605.419303 -27972.588048 -53316.820671 999999.999999
  484.                 // *  2016  7  6 17  2  0.00000000
  485.                 // PL51  11982.652569   2645.786926  -1177.549463 999999.999999
  486.                 // VL51   1128.248622 -28724.293303 -53097.358387 999999.999999
  487.                 //
  488.                 // *  2016  7  6 23 58  0.00000000
  489.                 // PL51   3215.382310  -7958.586164   8812.395707
  490.                 // VL51 -18058.659942 -45834.335707 -34496.540437
  491.                 // *  2016  7  7 24  0  0.00000000
  492.                 // PL51   2989.229334  -8494.421415   8385.068555
  493.                 // VL51 -19617.027447 -43444.824985 -36706.159070
  494.                 // *  2016  7  7  0  2  0.00000000
  495.                 // PL51   2744.983592  -9000.639164   7931.904779
  496.                 // VL51 -21072.925764 -40899.633288 -38801.567078
  497.                 //
  498.                 // In the first case, the date should really be 2016  7  6 17  0  0.00000000,
  499.                 // i.e as the minutes field overflows, the hours field should be incremented
  500.                 // In the second case, the date should really be 2016  7  7  0  0  0.00000000,
  501.                 // i.e. as the hours field overflows, the day field should be kept as is
  502.                 // we cannot be sure how carry was managed when these bogus files were written
  503.                 // so we try different options, incrementing or not previous field, and selecting
  504.                 // the closest one to expected date
  505.                 DateComponents dc = new DateComponents(year, month, day);
  506.                 final List<AbsoluteDate> candidates = new ArrayList<>();
  507.                 int h = hour;
  508.                 int m = minute;
  509.                 double s = second;
  510.                 if (s >= 60.0) {
  511.                     s -= 60;
  512.                     addCandidate(candidates, dc, h, m, s, pi.timeScale);
  513.                     m++;
  514.                 }
  515.                 if (m > 59) {
  516.                     m = 0;
  517.                     addCandidate(candidates, dc, h, m, s, pi.timeScale);
  518.                     h++;
  519.                 }
  520.                 if (h > 23) {
  521.                     h = 0;
  522.                     addCandidate(candidates, dc, h, m, s, pi.timeScale);
  523.                     dc = new DateComponents(dc, 1);
  524.                 }
  525.                 addCandidate(candidates, dc, h, m, s, pi.timeScale);
  526.                 final AbsoluteDate expected = pi.latestEpoch == null ?
  527.                                               pi.file.getEpoch() :
  528.                                                   pi.latestEpoch.shiftedBy(pi.file.getEpochInterval());
  529.                 pi.latestEpoch = null;
  530.                 for (final AbsoluteDate candidate : candidates) {
  531.                     if (FastMath.abs(candidate.durationFrom(expected)) < 0.01 * pi.file.getEpochInterval()) {
  532.                         pi.latestEpoch = candidate;
  533.                     }
  534.                 }
  535.                 if (pi.latestEpoch == null) {
  536.                     // no date recognized, just parse again the initial fields
  537.                     // in order to generate again an exception
  538.                     pi.latestEpoch = new AbsoluteDate(year, month, day, hour, minute, second, pi.timeScale);
  539.                 }
  540.                 pi.nbEpochs++;
  541.             }

  542.             /** Add an epoch candidate to a list.
  543.              * @param candidates list of candidates
  544.              * @param dc date components
  545.              * @param hour hour number from 0 to 23
  546.              * @param minute minute number from 0 to 59
  547.              * @param second second number from 0.0 to 60.0 (excluded)
  548.              * @param timeScale time scale
  549.              * @since 11.1.1
  550.              */
  551.             private void addCandidate(final List<AbsoluteDate> candidates, final DateComponents dc,
  552.                                       final int hour, final int minute, final double second,
  553.                                       final TimeScale timeScale) {
  554.                 try {
  555.                     candidates.add(new AbsoluteDate(dc, new TimeComponents(hour, minute, second), timeScale));
  556.                 } catch (OrekitIllegalArgumentException oiae) {
  557.                     // ignored
  558.                 }
  559.             }

  560.             /** {@inheritDoc} */
  561.             @Override
  562.             public Stream<LineParser> allowedNext() {
  563.                 return Stream.of(DATA_POSITION);
  564.             }

  565.         },

  566.         /** Parser for position. */
  567.         DATA_POSITION("^P.*") {

  568.             /** {@inheritDoc} */
  569.             @Override
  570.             public void parse(final String line, final ParseInfo pi) {
  571.                 final String satelliteId = line.substring(1, 4).trim();

  572.                 if (!pi.file.containsSatellite(satelliteId)) {
  573.                     pi.latestPosition = null;
  574.                 } else {
  575.                     final double x = Double.parseDouble(line.substring(4, 18).trim());
  576.                     final double y = Double.parseDouble(line.substring(18, 32).trim());
  577.                     final double z = Double.parseDouble(line.substring(32, 46).trim());

  578.                     // the position values are in km and have to be converted to m
  579.                     pi.latestPosition = new Vector3D(x * 1000, y * 1000, z * 1000);

  580.                     // clock (microsec)
  581.                     pi.latestClock = line.trim().length() <= 46 ?
  582.                                                           DEFAULT_CLOCK_VALUE :
  583.                                                               Double.parseDouble(line.substring(46, 60).trim()) * 1e-6;

  584.                     // the additional items are optional and not read yet

  585.                     // if (line.length() >= 73) {
  586.                     // // x-sdev (b**n mm)
  587.                     // int xStdDevExp = Integer.valueOf(line.substring(61,
  588.                     // 63).trim());
  589.                     // // y-sdev (b**n mm)
  590.                     // int yStdDevExp = Integer.valueOf(line.substring(64,
  591.                     // 66).trim());
  592.                     // // z-sdev (b**n mm)
  593.                     // int zStdDevExp = Integer.valueOf(line.substring(67,
  594.                     // 69).trim());
  595.                     // // c-sdev (b**n psec)
  596.                     // int cStdDevExp = Integer.valueOf(line.substring(70,
  597.                     // 73).trim());
  598.                     //
  599.                     // pi.posStdDevRecord =
  600.                     // new PositionStdDevRecord(FastMath.pow(pi.posVelBase, xStdDevExp),
  601.                     // FastMath.pow(pi.posVelBase,
  602.                     // yStdDevExp), FastMath.pow(pi.posVelBase, zStdDevExp),
  603.                     // FastMath.pow(pi.clockBase, cStdDevExp));
  604.                     //
  605.                     // String clockEventFlag = line.substring(74, 75);
  606.                     // String clockPredFlag = line.substring(75, 76);
  607.                     // String maneuverFlag = line.substring(78, 79);
  608.                     // String orbitPredFlag = line.substring(79, 80);
  609.                     // }

  610.                     if (!pi.hasVelocityEntries) {
  611.                         final SP3Coordinate coord =
  612.                                 new SP3Coordinate(pi.latestEpoch,
  613.                                                   pi.latestPosition,
  614.                                                   pi.latestClock);
  615.                         pi.file.addSatelliteCoordinate(satelliteId, coord);
  616.                     }
  617.                 }
  618.             }

  619.             /** {@inheritDoc} */
  620.             @Override
  621.             public Stream<LineParser> allowedNext() {
  622.                 return Stream.of(DATA_EPOCH, DATA_POSITION, DATA_POSITION_CORRELATION, DATA_VELOCITY, EOF);
  623.             }

  624.         },

  625.         /** Parser for position correlation. */
  626.         DATA_POSITION_CORRELATION("^EP.*") {

  627.             /** {@inheritDoc} */
  628.             @Override
  629.             public void parse(final String line, final ParseInfo pi) {
  630.                 // ignored for now
  631.             }

  632.             /** {@inheritDoc} */
  633.             @Override
  634.             public Stream<LineParser> allowedNext() {
  635.                 return Stream.of(DATA_EPOCH, DATA_POSITION, DATA_VELOCITY, EOF);
  636.             }

  637.         },

  638.         /** Parser for velocity. */
  639.         DATA_VELOCITY("^V.*") {

  640.             /** {@inheritDoc} */
  641.             @Override
  642.             public void parse(final String line, final ParseInfo pi) {
  643.                 final String satelliteId = line.substring(1, 4).trim();

  644.                 if (pi.file.containsSatellite(satelliteId)) {
  645.                     final double xv = Double.parseDouble(line.substring(4, 18).trim());
  646.                     final double yv = Double.parseDouble(line.substring(18, 32).trim());
  647.                     final double zv = Double.parseDouble(line.substring(32, 46).trim());

  648.                     // the velocity values are in dm/s and have to be converted to m/s
  649.                     final Vector3D velocity = new Vector3D(xv / 10d, yv / 10d, zv / 10d);

  650.                     // clock rate in file is 1e-4 us / s
  651.                     final double clockRateChange = line.trim().length() <= 46 ?
  652.                                                                         DEFAULT_CLOCK_VALUE :
  653.                                                                             Double.parseDouble(line.substring(46, 60).trim()) * 1e-4;

  654.                     // the additional items are optional and not read yet

  655.                     // if (line.length() >= 73) {
  656.                     // // xvel-sdev (b**n 10**-4 mm/sec)
  657.                     // int xVstdDevExp = Integer.valueOf(line.substring(61,
  658.                     // 63).trim());
  659.                     // // yvel-sdev (b**n 10**-4 mm/sec)
  660.                     // int yVstdDevExp = Integer.valueOf(line.substring(64,
  661.                     // 66).trim());
  662.                     // // zvel-sdev (b**n 10**-4 mm/sec)
  663.                     // int zVstdDevExp = Integer.valueOf(line.substring(67,
  664.                     // 69).trim());
  665.                     // // clkrate-sdev (b**n 10**-4 psec/sec)
  666.                     // int clkStdDevExp = Integer.valueOf(line.substring(70,
  667.                     // 73).trim());
  668.                     // }

  669.                     final SP3Coordinate coord =
  670.                             new SP3Coordinate(pi.latestEpoch,
  671.                                               pi.latestPosition,
  672.                                               velocity,
  673.                                               pi.latestClock,
  674.                                               clockRateChange);
  675.                     pi.file.addSatelliteCoordinate(satelliteId, coord);
  676.                 }
  677.             }

  678.             /** {@inheritDoc} */
  679.             @Override
  680.             public Stream<LineParser> allowedNext() {
  681.                 return Stream.of(DATA_EPOCH, DATA_POSITION, DATA_VELOCITY_CORRELATION, EOF);
  682.             }

  683.         },

  684.         /** Parser for velocity correlation. */
  685.         DATA_VELOCITY_CORRELATION("^EV.*") {

  686.             /** {@inheritDoc} */
  687.             @Override
  688.             public void parse(final String line, final ParseInfo pi) {
  689.                 // ignored for now
  690.             }

  691.             /** {@inheritDoc} */
  692.             @Override
  693.             public Stream<LineParser> allowedNext() {
  694.                 return Stream.of(DATA_EPOCH, DATA_POSITION, EOF);
  695.             }

  696.         },

  697.         /** Parser for End Of File marker. */
  698.         EOF("^[eE][oO][fF]\\s*$") {

  699.             /** {@inheritDoc} */
  700.             @Override
  701.             public void parse(final String line, final ParseInfo pi) {
  702.                 pi.done = true;
  703.             }

  704.             /** {@inheritDoc} */
  705.             @Override
  706.             public Stream<LineParser> allowedNext() {
  707.                 return Stream.of(EOF);
  708.             }

  709.         };

  710.         /** Pattern for identifying line. */
  711.         private final Pattern pattern;

  712.         /** Simple constructor.
  713.          * @param lineRegexp regular expression for identifying line
  714.          */
  715.         LineParser(final String lineRegexp) {
  716.             pattern = Pattern.compile(lineRegexp);
  717.         }

  718.         /** Parse a line.
  719.          * @param line line to parse
  720.          * @param pi holder for transient data
  721.          */
  722.         public abstract void parse(String line, ParseInfo pi);

  723.         /** Get the allowed parsers for next line.
  724.          * @return allowed parsers for next line
  725.          */
  726.         public abstract Stream<LineParser> allowedNext();

  727.         /** Check if parser can handle line.
  728.          * @param line line to parse
  729.          * @return true if parser can handle the specified line
  730.          */
  731.         public boolean canHandle(final String line) {
  732.             return pattern.matcher(line).matches();
  733.         }

  734.     }

  735. }