OEMParser.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.ccsds;

  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.util.ArrayList;
  24. import java.util.List;
  25. import java.util.Scanner;

  26. import org.hipparchus.exception.DummyLocalizable;
  27. import org.hipparchus.geometry.euclidean.threed.Vector3D;
  28. import org.hipparchus.linear.MatrixUtils;
  29. import org.hipparchus.linear.RealMatrix;
  30. import org.orekit.annotation.DefaultDataContext;
  31. import org.orekit.data.DataContext;
  32. import org.orekit.errors.OrekitException;
  33. import org.orekit.errors.OrekitMessages;
  34. import org.orekit.files.general.EphemerisFileParser;
  35. import org.orekit.frames.Frame;
  36. import org.orekit.frames.LOFType;
  37. import org.orekit.time.AbsoluteDate;
  38. import org.orekit.utils.IERSConventions;
  39. import org.orekit.utils.TimeStampedPVCoordinates;

  40. /**
  41.  * A parser for the CCSDS OEM (Orbit Ephemeris Message).
  42.  * @author sports
  43.  * @since 6.1
  44.  */
  45. public class OEMParser extends ODMParser implements EphemerisFileParser {

  46.     /** Simple constructor.
  47.      * <p>
  48.      * This class is immutable, and hence thread safe. When parts
  49.      * must be changed, such as reference date for Mission Elapsed Time or
  50.      * Mission Relative Time time systems, or the gravitational coefficient or
  51.      * the IERS conventions, the various {@code withXxx} methods must be called,
  52.      * which create a new immutable instance with the new parameters. This
  53.      * is a combination of the
  54.      * <a href="https://en.wikipedia.org/wiki/Builder_pattern">builder design
  55.      * pattern</a> and a
  56.      * <a href="http://en.wikipedia.org/wiki/Fluent_interface">fluent
  57.      * interface</a>.
  58.      * </p>
  59.      * <p>
  60.      * The initial date for Mission Elapsed Time and Mission Relative Time time systems is not set here.
  61.      * If such time systems are used, it must be initialized before parsing by calling {@link
  62.      * #withMissionReferenceDate(AbsoluteDate)}.
  63.      * </p>
  64.      * <p>
  65.      * The gravitational coefficient is not set here. If it is needed in order
  66.      * to parse Cartesian orbits where the value is not set in the CCSDS file, it must
  67.      * be initialized before parsing by calling {@link #withMu(double)}.
  68.      * </p>
  69.      * <p>
  70.      * The IERS conventions to use is not set here. If it is needed in order to
  71.      * parse some reference frames or UT1 time scale, it must be initialized before
  72.      * parsing by calling {@link #withConventions(IERSConventions)}.
  73.      * </p>
  74.      *
  75.      * <p>This method uses the {@link DataContext#getDefault() default data context}. See
  76.      * {@link #withDataContext(DataContext)}.
  77.      */
  78.     @DefaultDataContext
  79.     public OEMParser() {
  80.         this(DataContext.getDefault());
  81.     }

  82.     /** Constructor with data context.
  83.      * <p>
  84.      * This class is immutable, and hence thread safe. When parts
  85.      * must be changed, such as reference date for Mission Elapsed Time or
  86.      * Mission Relative Time time systems, or the gravitational coefficient or
  87.      * the IERS conventions, the various {@code withXxx} methods must be called,
  88.      * which create a new immutable instance with the new parameters. This
  89.      * is a combination of the
  90.      * <a href="https://en.wikipedia.org/wiki/Builder_pattern">builder design
  91.      * pattern</a> and a
  92.      * <a href="http://en.wikipedia.org/wiki/Fluent_interface">fluent
  93.      * interface</a>.
  94.      * </p>
  95.      * <p>
  96.      * The initial date for Mission Elapsed Time and Mission Relative Time time systems is not set here.
  97.      * If such time systems are used, it must be initialized before parsing by calling {@link
  98.      * #withMissionReferenceDate(AbsoluteDate)}.
  99.      * </p>
  100.      * <p>
  101.      * The gravitational coefficient is not set here. If it is needed in order
  102.      * to parse Cartesian orbits where the value is not set in the CCSDS file, it must
  103.      * be initialized before parsing by calling {@link #withMu(double)}.
  104.      * </p>
  105.      * <p>
  106.      * The IERS conventions to use is not set here. If it is needed in order to
  107.      * parse some reference frames or UT1 time scale, it must be initialized before
  108.      * parsing by calling {@link #withConventions(IERSConventions)}.
  109.      * </p>
  110.      *
  111.      * @param dataContext used by the parser.
  112.      *
  113.      * @see #OEMParser()
  114.      * @see #withDataContext(DataContext)
  115.      * @since 10.1
  116.      */
  117.     public OEMParser(final DataContext dataContext) {
  118.         this(AbsoluteDate.FUTURE_INFINITY, Double.NaN, null, true, 0, 0, "", dataContext);
  119.     }

  120.     /** Complete constructor.
  121.      * @param missionReferenceDate reference date for Mission Elapsed Time or Mission Relative Time time systems
  122.      * @param mu gravitational coefficient
  123.      * @param conventions IERS Conventions
  124.      * @param simpleEOP if true, tidal effects are ignored when interpolating EOP
  125.      * @param launchYear launch year for TLEs
  126.      * @param launchNumber launch number for TLEs
  127.      * @param launchPiece piece of launch (from "A" to "ZZZ") for TLEs
  128.      * @param dataContext used to retrieve frames, time scales, etc.
  129.      */
  130.     private OEMParser(final AbsoluteDate missionReferenceDate, final double mu,
  131.                       final IERSConventions conventions, final boolean simpleEOP,
  132.                       final int launchYear, final int launchNumber,
  133.                       final String launchPiece, final DataContext dataContext) {
  134.         super(missionReferenceDate, mu, conventions, simpleEOP, launchYear, launchNumber,
  135.                 launchPiece, dataContext);
  136.     }

  137.     /** {@inheritDoc} */
  138.     public OEMParser withMissionReferenceDate(final AbsoluteDate newMissionReferenceDate) {
  139.         return new OEMParser(newMissionReferenceDate, getMu(), getConventions(), isSimpleEOP(),
  140.                              getLaunchYear(), getLaunchNumber(), getLaunchPiece(),
  141.                              getDataContext());
  142.     }

  143.     /** {@inheritDoc} */
  144.     public OEMParser withMu(final double newMu) {
  145.         return new OEMParser(getMissionReferenceDate(), newMu, getConventions(), isSimpleEOP(),
  146.                              getLaunchYear(), getLaunchNumber(), getLaunchPiece(),
  147.                              getDataContext());
  148.     }

  149.     /** {@inheritDoc} */
  150.     public OEMParser withConventions(final IERSConventions newConventions) {
  151.         return new OEMParser(getMissionReferenceDate(), getMu(), newConventions, isSimpleEOP(),
  152.                              getLaunchYear(), getLaunchNumber(), getLaunchPiece(),
  153.                              getDataContext());
  154.     }

  155.     /** {@inheritDoc} */
  156.     public OEMParser withSimpleEOP(final boolean newSimpleEOP) {
  157.         return new OEMParser(getMissionReferenceDate(), getMu(), getConventions(), newSimpleEOP,
  158.                              getLaunchYear(), getLaunchNumber(), getLaunchPiece(),
  159.                              getDataContext());
  160.     }

  161.     /** {@inheritDoc} */
  162.     public OEMParser withInternationalDesignator(final int newLaunchYear,
  163.                                                  final int newLaunchNumber,
  164.                                                  final String newLaunchPiece) {
  165.         return new OEMParser(getMissionReferenceDate(), getMu(), getConventions(), isSimpleEOP(),
  166.                              newLaunchYear, newLaunchNumber, newLaunchPiece,
  167.                              getDataContext());
  168.     }

  169.     @Override
  170.     public OEMParser withDataContext(final DataContext dataContext) {
  171.         return new OEMParser(getMissionReferenceDate(), getMu(), getConventions(), isSimpleEOP(),
  172.                 getLaunchYear(), getLaunchNumber(), getLaunchPiece(),
  173.                 dataContext);
  174.     }

  175.     /** {@inheritDoc} */
  176.     @Override
  177.     public OEMFile parse(final String fileName) {
  178.         return (OEMFile) super.parse(fileName);
  179.     }

  180.     /** {@inheritDoc} */
  181.     @Override
  182.     public OEMFile parse(final InputStream stream) {
  183.         return (OEMFile) super.parse(stream);
  184.     }

  185.     /** {@inheritDoc} */
  186.     public OEMFile parse(final InputStream stream, final String fileName) {
  187.         try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8))) {
  188.             return parse(reader, fileName);
  189.         } catch (IOException ioe) {
  190.             throw new OrekitException(ioe, new DummyLocalizable(ioe.getMessage()));
  191.         }
  192.     }

  193.     @Override
  194.     public OEMFile parse(final BufferedReader reader, final String fileName) {

  195.         try {

  196.             // initialize internal data structures
  197.             final ParseInfo pi = new ParseInfo();
  198.             pi.fileName = fileName;
  199.             final OEMFile file = pi.file;

  200.             // set the additional data that has been configured prior the parsing by the user.
  201.             pi.file.setMissionReferenceDate(getMissionReferenceDate());
  202.             pi.file.setMuSet(getMu());
  203.             pi.file.setConventions(getConventions());
  204.             pi.file.setDataContext(getDataContext());

  205.             for (String line = reader.readLine(); line != null; line = reader.readLine()) {
  206.                 ++pi.lineNumber;
  207.                 if (line.trim().length() == 0) {
  208.                     continue;
  209.                 }
  210.                 pi.keyValue = new KeyValue(line, pi.lineNumber, pi.fileName);
  211.                 if (pi.keyValue.getKeyword() == null) {
  212.                     throw new OrekitException(OrekitMessages.CCSDS_UNEXPECTED_KEYWORD, pi.lineNumber, pi.fileName, line);
  213.                 }
  214.                 switch (pi.keyValue.getKeyword()) {
  215.                     case CCSDS_OEM_VERS:
  216.                         file.setFormatVersion(pi.keyValue.getDoubleValue());
  217.                         break;

  218.                     case META_START:
  219.                         file.addEphemeridesBlock();
  220.                         pi.lastEphemeridesBlock = file.getEphemeridesBlocks().get(file.getEphemeridesBlocks().size() - 1);
  221.                         pi.lastEphemeridesBlock.getMetaData().setLaunchYear(getLaunchYear());
  222.                         pi.lastEphemeridesBlock.getMetaData().setLaunchNumber(getLaunchNumber());
  223.                         pi.lastEphemeridesBlock.getMetaData().setLaunchPiece(getLaunchPiece());
  224.                         break;

  225.                     case START_TIME:
  226.                         pi.lastEphemeridesBlock.setStartTime(parseDate(pi.keyValue.getValue(),
  227.                                                                        pi.lastEphemeridesBlock.getMetaData().getTimeSystem()));
  228.                         break;

  229.                     case USEABLE_START_TIME:
  230.                         pi.lastEphemeridesBlock.setUseableStartTime(parseDate(pi.keyValue.getValue(),
  231.                                                                               pi.lastEphemeridesBlock.getMetaData().getTimeSystem()));
  232.                         break;

  233.                     case USEABLE_STOP_TIME:
  234.                         pi.lastEphemeridesBlock.setUseableStopTime(parseDate(pi.keyValue.getValue(), pi.lastEphemeridesBlock.getMetaData().getTimeSystem()));
  235.                         break;

  236.                     case STOP_TIME:
  237.                         pi.lastEphemeridesBlock.setStopTime(parseDate(pi.keyValue.getValue(), pi.lastEphemeridesBlock.getMetaData().getTimeSystem()));
  238.                         break;

  239.                     case INTERPOLATION:
  240.                         pi.lastEphemeridesBlock.setInterpolationMethod(pi.keyValue.getValue());
  241.                         break;

  242.                     case INTERPOLATION_DEGREE:
  243.                         pi.lastEphemeridesBlock.setInterpolationDegree(Integer .parseInt(pi.keyValue.getValue()));
  244.                         break;

  245.                     case META_STOP:
  246.                         file.setMuUsed();
  247.                         parseEphemeridesDataLines(reader, pi);
  248.                         break;

  249.                     case COVARIANCE_START:
  250.                         parseCovarianceDataLines(reader, pi);
  251.                         break;

  252.                     default:
  253.                         boolean parsed = false;
  254.                         parsed = parsed || parseComment(pi.keyValue, pi.commentTmp);
  255.                         parsed = parsed || parseHeaderEntry(pi.keyValue, file, pi.commentTmp);
  256.                         if (pi.lastEphemeridesBlock != null) {
  257.                             parsed = parsed || parseMetaDataEntry(pi.keyValue,
  258.                                                                   pi.lastEphemeridesBlock.getMetaData(), pi.commentTmp);
  259.                             if (parsed && pi.keyValue.getKeyword() == Keyword.REF_FRAME_EPOCH) {
  260.                                 pi.lastEphemeridesBlock.setHasRefFrameEpoch(true);
  261.                             }
  262.                         }
  263.                         if (!parsed) {
  264.                             throw new OrekitException(OrekitMessages.CCSDS_UNEXPECTED_KEYWORD, pi.lineNumber, pi.fileName, line);
  265.                         }
  266.                 }
  267.             }
  268.             file.checkTimeSystems();
  269.             return file;
  270.         } catch (IOException ioe) {
  271.             throw new OrekitException(ioe, new DummyLocalizable(ioe.getMessage()));
  272.         }
  273.     }

  274.     /**
  275.      * Parse an ephemeris data line and add its content to the ephemerides
  276.      * block.
  277.      *
  278.      * @param reader the reader
  279.      * @param pi the parser info
  280.      * @exception IOException if an error occurs while reading from the stream
  281.      */
  282.     private void parseEphemeridesDataLines(final BufferedReader reader,  final ParseInfo pi)
  283.         throws IOException {

  284.         for (String line = reader.readLine(); line != null; line = reader.readLine()) {

  285.             ++pi.lineNumber;
  286.             if (line.trim().length() > 0) {
  287.                 pi.keyValue = new KeyValue(line, pi.lineNumber, pi.fileName);
  288.                 if (pi.keyValue.getKeyword() == null) {
  289.                     Scanner sc = null;
  290.                     try {
  291.                         sc = new Scanner(line);
  292.                         final AbsoluteDate date = parseDate(sc.next(), pi.lastEphemeridesBlock.getMetaData().getTimeSystem());
  293.                         final Vector3D position = new Vector3D(Double.parseDouble(sc.next()) * 1000,
  294.                                                                Double.parseDouble(sc.next()) * 1000,
  295.                                                                Double.parseDouble(sc.next()) * 1000);
  296.                         final Vector3D velocity = new Vector3D(Double.parseDouble(sc.next()) * 1000,
  297.                                                                Double.parseDouble(sc.next()) * 1000,
  298.                                                                Double.parseDouble(sc.next()) * 1000);
  299.                         Vector3D acceleration = Vector3D.NaN;
  300.                         boolean hasAcceleration = false;
  301.                         if (sc.hasNext()) {
  302.                             acceleration = new Vector3D(Double.parseDouble(sc.next()) * 1000,
  303.                                                         Double.parseDouble(sc.next()) * 1000,
  304.                                                         Double.parseDouble(sc.next()) * 1000);
  305.                             hasAcceleration = true;
  306.                         }
  307.                         final TimeStampedPVCoordinates epDataLine;
  308.                         if (hasAcceleration) {
  309.                             epDataLine = new TimeStampedPVCoordinates(date, position, velocity, acceleration);
  310.                         } else {
  311.                             epDataLine = new TimeStampedPVCoordinates(date, position, velocity);
  312.                         }
  313.                         pi.lastEphemeridesBlock.getEphemeridesDataLines().add(epDataLine);
  314.                         pi.lastEphemeridesBlock.updateHasAcceleration(hasAcceleration);
  315.                     } catch (NumberFormatException nfe) {
  316.                         throw new OrekitException(OrekitMessages.UNABLE_TO_PARSE_LINE_IN_FILE,
  317.                                                   pi.lineNumber, pi.fileName, line);
  318.                     } finally {
  319.                         if (sc != null) {
  320.                             sc.close();
  321.                         }
  322.                     }
  323.                 } else {
  324.                     switch (pi.keyValue.getKeyword()) {
  325.                         case META_START:
  326.                             pi.lastEphemeridesBlock.setEphemeridesDataLinesComment(pi.commentTmp);
  327.                             pi.commentTmp.clear();
  328.                             pi.lineNumber--;
  329.                             reader.reset();
  330.                             return;
  331.                         case COVARIANCE_START:
  332.                             pi.lastEphemeridesBlock.setEphemeridesDataLinesComment(pi.commentTmp);
  333.                             pi.commentTmp.clear();
  334.                             pi.lineNumber--;
  335.                             reader.reset();
  336.                             return;
  337.                         case COMMENT:
  338.                             pi.commentTmp.add(pi.keyValue.getValue());
  339.                             break;
  340.                         default :
  341.                             throw new OrekitException(OrekitMessages.CCSDS_UNEXPECTED_KEYWORD, pi.lineNumber, pi.fileName, line);
  342.                     }
  343.                 }
  344.             }
  345.             reader.mark(300);

  346.         }
  347.     }

  348.     /**
  349.      * Parse the covariance data lines, create a set of CovarianceMatrix objects
  350.      * and add them in the covarianceMatrices list of the ephemerides block.
  351.      *
  352.      * @param reader the reader
  353.      * @param pi the parser info
  354.      * @throws IOException if an error occurs while reading from the stream
  355.      */
  356.     private void parseCovarianceDataLines(final BufferedReader reader, final ParseInfo pi)
  357.         throws IOException {
  358.         int i = 0;
  359.         for (String line = reader.readLine(); line != null; line = reader.readLine()) {

  360.             ++pi.lineNumber;
  361.             if (line.trim().length() == 0) {
  362.                 continue;
  363.             }
  364.             pi.keyValue = new KeyValue(line, pi.lineNumber, pi.fileName);
  365.             if (pi.keyValue.getKeyword() == null) {
  366.                 final Scanner sc = new Scanner(line);
  367.                 for (int j = 0; j < i + 1; j++) {
  368.                     try {
  369.                         pi.lastMatrix.addToEntry(i, j, Double.parseDouble(sc.next()));
  370.                     } catch (NumberFormatException nfe) {
  371.                         sc.close();
  372.                         throw new OrekitException(OrekitMessages.UNABLE_TO_PARSE_LINE_IN_FILE,
  373.                                                   pi.lineNumber, pi.fileName, line);
  374.                     }
  375.                     if (j != i) {
  376.                         pi.lastMatrix.addToEntry(j, i, pi.lastMatrix.getEntry(i, j));
  377.                     }
  378.                 }
  379.                 if (i == 5) {
  380.                     final OEMFile.CovarianceMatrix cm =
  381.                             new OEMFile.CovarianceMatrix(pi.epoch, pi.covRefLofType, pi.covRefFrame, pi.lastMatrix);
  382.                     pi.lastEphemeridesBlock.getCovarianceMatrices().add(cm);
  383.                 }
  384.                 i++;
  385.                 if (sc != null) {
  386.                     sc.close();
  387.                 }
  388.             } else {
  389.                 switch (pi.keyValue.getKeyword()) {
  390.                     case EPOCH :
  391.                         i                = 0;
  392.                         pi.covRefLofType = null;
  393.                         pi.covRefFrame   = null;
  394.                         pi.lastMatrix    = MatrixUtils.createRealMatrix(6, 6);
  395.                         pi.epoch         = parseDate(pi.keyValue.getValue(), pi.lastEphemeridesBlock.getMetaData().getTimeSystem());
  396.                         break;
  397.                     case COV_REF_FRAME :
  398.                         final CCSDSFrame frame = parseCCSDSFrame(pi.keyValue.getValue());
  399.                         if (frame.isLof()) {
  400.                             pi.covRefLofType = frame.getLofType();
  401.                             pi.covRefFrame   = null;
  402.                         } else {
  403.                             pi.covRefLofType = null;
  404.                             pi.covRefFrame   = frame.getFrame(getConventions(), isSimpleEOP(), getDataContext());
  405.                         }
  406.                         break;
  407.                     case COVARIANCE_STOP :
  408.                         return;
  409.                     default :
  410.                         throw new OrekitException(OrekitMessages.CCSDS_UNEXPECTED_KEYWORD, pi.lineNumber, pi.fileName, line);
  411.                 }
  412.             }
  413.         }
  414.     }

  415.     /** Private class used to stock OEM parsing info.
  416.      * @author sports
  417.      */
  418.     private static class ParseInfo {

  419.         /** Ephemerides block being parsed. */
  420.         private OEMFile.EphemeridesBlock lastEphemeridesBlock;

  421.         /** Name of the file. */
  422.         private String fileName;

  423.         /** Current line number. */
  424.         private int lineNumber;

  425.         /** OEM file being read. */
  426.         private OEMFile file;

  427.         /** Key value of the line being read. */
  428.         private KeyValue keyValue;

  429.         /** Stored epoch. */
  430.         private AbsoluteDate epoch;

  431.         /** Covariance reference type of Local Orbital Frame. */
  432.         private LOFType covRefLofType;

  433.         /** Covariance reference frame. */
  434.         private Frame covRefFrame;
  435.         /** Stored matrix. */
  436.         private RealMatrix lastMatrix;

  437.         /** Stored comments. */
  438.         private List<String> commentTmp;

  439.         /** Create a new {@link ParseInfo} object. */
  440.         protected ParseInfo() {
  441.             lineNumber = 0;
  442.             file = new OEMFile();
  443.             commentTmp = new ArrayList<String>();
  444.         }
  445.     }
  446. }