OEMParser.java

  1. /* Copyright 2002-2016 CS Systèmes d'Information
  2.  * Licensed to CS Systèmes d'Information (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.util.ArrayList;
  23. import java.util.List;
  24. import java.util.Scanner;

  25. import org.apache.commons.math3.exception.util.DummyLocalizable;
  26. import org.apache.commons.math3.geometry.euclidean.threed.Vector3D;
  27. import org.apache.commons.math3.linear.MatrixUtils;
  28. import org.apache.commons.math3.linear.RealMatrix;
  29. import org.orekit.errors.OrekitException;
  30. import org.orekit.errors.OrekitMessages;
  31. import org.orekit.files.general.OrbitFileParser;
  32. import org.orekit.frames.Frame;
  33. import org.orekit.frames.LOFType;
  34. import org.orekit.orbits.CartesianOrbit;
  35. import org.orekit.time.AbsoluteDate;
  36. import org.orekit.utils.IERSConventions;
  37. import org.orekit.utils.PVCoordinates;

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

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

  74.     /** Complete constructor.
  75.      * @param missionReferenceDate reference date for Mission Elapsed Time or Mission Relative Time time systems
  76.      * @param mu gravitational coefficient
  77.      * @param conventions IERS Conventions
  78.      * @param simpleEOP if true, tidal effects are ignored when interpolating EOP
  79.      * @param launchYear launch year for TLEs
  80.      * @param launchNumber launch number for TLEs
  81.      * @param launchPiece piece of launch (from "A" to "ZZZ") for TLEs
  82.      */
  83.     private OEMParser(final AbsoluteDate missionReferenceDate, final double mu,
  84.                       final IERSConventions conventions, final boolean simpleEOP,
  85.                       final int launchYear, final int launchNumber, final String launchPiece) {
  86.         super(missionReferenceDate, mu, conventions, simpleEOP, launchYear, launchNumber, launchPiece);
  87.     }

  88.     /** {@inheritDoc} */
  89.     public OEMParser withMissionReferenceDate(final AbsoluteDate newMissionReferenceDate) {
  90.         return new OEMParser(newMissionReferenceDate, getMu(), getConventions(), isSimpleEOP(),
  91.                              getLaunchYear(), getLaunchNumber(), getLaunchPiece());
  92.     }

  93.     /** {@inheritDoc} */
  94.     public OEMParser withMu(final double newMu) {
  95.         return new OEMParser(getMissionReferenceDate(), newMu, getConventions(), isSimpleEOP(),
  96.                              getLaunchYear(), getLaunchNumber(), getLaunchPiece());
  97.     }

  98.     /** {@inheritDoc} */
  99.     public OEMParser withConventions(final IERSConventions newConventions) {
  100.         return new OEMParser(getMissionReferenceDate(), getMu(), newConventions, isSimpleEOP(),
  101.                              getLaunchYear(), getLaunchNumber(), getLaunchPiece());
  102.     }

  103.     /** {@inheritDoc} */
  104.     public OEMParser withSimpleEOP(final boolean newSimpleEOP) {
  105.         return new OEMParser(getMissionReferenceDate(), getMu(), getConventions(), newSimpleEOP,
  106.                              getLaunchYear(), getLaunchNumber(), getLaunchPiece());
  107.     }

  108.     /** {@inheritDoc} */
  109.     public OEMParser withInternationalDesignator(final int newLaunchYear,
  110.                                                  final int newLaunchNumber,
  111.                                                  final String newLaunchPiece) {
  112.         return new OEMParser(getMissionReferenceDate(), getMu(), getConventions(), isSimpleEOP(),
  113.                              newLaunchYear, newLaunchNumber, newLaunchPiece);
  114.     }

  115.     /** {@inheritDoc} */
  116.     @Override
  117.     public OEMFile parse(final String fileName) throws OrekitException {
  118.         return (OEMFile) super.parse(fileName);
  119.     }

  120.     /** {@inheritDoc} */
  121.     @Override
  122.     public OEMFile parse(final InputStream stream) throws OrekitException {
  123.         return (OEMFile) super.parse(stream);
  124.     }

  125.     /** {@inheritDoc} */
  126.     public OEMFile parse(final InputStream stream, final String fileName) throws OrekitException {

  127.         try {

  128.             final BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
  129.             // initialize internal data structures
  130.             final ParseInfo pi = new ParseInfo();
  131.             pi.fileName = fileName;
  132.             final OEMFile file = pi.file;

  133.             // set the additional data that has been configured prior the parsing by the user.
  134.             pi.file.setMissionReferenceDate(getMissionReferenceDate());
  135.             pi.file.setMuSet(getMu());
  136.             pi.file.setConventions(getConventions());

  137.             for (String line = reader.readLine(); line != null; line = reader.readLine()) {
  138.                 ++pi.lineNumber;
  139.                 if (line.trim().length() == 0) {
  140.                     continue;
  141.                 }
  142.                 pi.keyValue = new KeyValue(line, pi.lineNumber, pi.fileName);
  143.                 if (pi.keyValue.getKeyword() == null) {
  144.                     throw new OrekitException(OrekitMessages.CCSDS_UNEXPECTED_KEYWORD, pi.lineNumber, pi.fileName, line);
  145.                 }
  146.                 switch (pi.keyValue.getKeyword()) {
  147.                     case CCSDS_OEM_VERS:
  148.                         file.setFormatVersion(pi.keyValue.getDoubleValue());
  149.                         break;

  150.                     case META_START:
  151.                         file.addEphemeridesBlock();
  152.                         pi.lastEphemeridesBlock = file.getEphemeridesBlocks().get(file.getEphemeridesBlocks().size() - 1);
  153.                         pi.lastEphemeridesBlock.getMetaData().setLaunchYear(getLaunchYear());
  154.                         pi.lastEphemeridesBlock.getMetaData().setLaunchNumber(getLaunchNumber());
  155.                         pi.lastEphemeridesBlock.getMetaData().setLaunchPiece(getLaunchPiece());
  156.                         break;

  157.                     case START_TIME:
  158.                         pi.lastEphemeridesBlock.setStartTime(parseDate(pi.keyValue.getValue(),
  159.                                                                        pi.lastEphemeridesBlock.getMetaData().getTimeSystem()));
  160.                         break;

  161.                     case USEABLE_START_TIME:
  162.                         pi.lastEphemeridesBlock.setUseableStartTime(parseDate(pi.keyValue.getValue(),
  163.                                                                               pi.lastEphemeridesBlock.getMetaData().getTimeSystem()));
  164.                         break;

  165.                     case USEABLE_STOP_TIME:
  166.                         pi.lastEphemeridesBlock.setUseableStopTime(parseDate(pi.keyValue.getValue(), pi.lastEphemeridesBlock.getMetaData().getTimeSystem()));
  167.                         break;

  168.                     case STOP_TIME:
  169.                         pi.lastEphemeridesBlock.setStopTime(parseDate(pi.keyValue.getValue(), pi.lastEphemeridesBlock.getMetaData().getTimeSystem()));
  170.                         break;

  171.                     case INTERPOLATION:
  172.                         pi.lastEphemeridesBlock.setInterpolationMethod(pi.keyValue.getValue());
  173.                         break;

  174.                     case INTERPOLATION_DEGREE:
  175.                         pi.lastEphemeridesBlock.setInterpolationDegree(Integer .parseInt(pi.keyValue.getValue()));
  176.                         break;

  177.                     case META_STOP:
  178.                         file.setMuUsed();
  179.                         parseEphemeridesDataLines(reader, pi);
  180.                         break;

  181.                     case COVARIANCE_START:
  182.                         parseCovarianceDataLines(reader, pi);
  183.                         break;

  184.                     default:
  185.                         boolean parsed = false;
  186.                         parsed = parsed || parseComment(pi.keyValue, pi.commentTmp);
  187.                         parsed = parsed || parseHeaderEntry(pi.keyValue, file, pi.commentTmp);
  188.                         if (pi.lastEphemeridesBlock != null) {
  189.                             parsed = parsed || parseMetaDataEntry(pi.keyValue,
  190.                                                                   pi.lastEphemeridesBlock.getMetaData(), pi.commentTmp);
  191.                             if (parsed && pi.keyValue.getKeyword() == Keyword.REF_FRAME_EPOCH) {
  192.                                 pi.lastEphemeridesBlock.setHasRefFrameEpoch(true);
  193.                             }
  194.                         }
  195.                         if (!parsed) {
  196.                             throw new OrekitException(OrekitMessages.CCSDS_UNEXPECTED_KEYWORD, pi.lineNumber, pi.fileName, line);
  197.                         }
  198.                 }
  199.             }
  200.             file.checkTimeSystems();
  201.             return file;
  202.         } catch (IOException ioe) {
  203.             throw new OrekitException(ioe, new DummyLocalizable(ioe.getMessage()));
  204.         }
  205.     }

  206.     /**
  207.      * Parse an ephemeris data line and add its content to the ephemerides
  208.      * block.
  209.      *
  210.      * @param reader the reader
  211.      * @param pi the parser info
  212.      * @exception IOException if an error occurs while reading from the stream
  213.      * @exception OrekitException if a date cannot be parsed
  214.      */
  215.     private void parseEphemeridesDataLines(final BufferedReader reader,  final ParseInfo pi)
  216.         throws OrekitException, IOException {

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

  218.             ++pi.lineNumber;
  219.             if (line.trim().length() > 0) {
  220.                 pi.keyValue = new KeyValue(line, pi.lineNumber, pi.fileName);
  221.                 if (pi.keyValue.getKeyword() == null) {
  222.                     Scanner sc = null;
  223.                     try {
  224.                         sc = new Scanner(line);
  225.                         final AbsoluteDate date = parseDate(sc.next(), pi.lastEphemeridesBlock.getMetaData().getTimeSystem());
  226.                         final Vector3D position = new Vector3D(Double.parseDouble(sc.next()) * 1000,
  227.                                                                Double.parseDouble(sc.next()) * 1000,
  228.                                                                Double.parseDouble(sc.next()) * 1000);
  229.                         final Vector3D velocity = new Vector3D(Double.parseDouble(sc.next()) * 1000,
  230.                                                                Double.parseDouble(sc.next()) * 1000,
  231.                                                                Double.parseDouble(sc.next()) * 1000);
  232.                         final CartesianOrbit orbit =
  233.                                 new CartesianOrbit(new PVCoordinates(position, velocity),
  234.                                                    pi.lastEphemeridesBlock.getMetaData().getFrame(),
  235.                                                    date, pi.file.getMuUsed());
  236.                         Vector3D acceleration = null;
  237.                         if (sc.hasNext()) {
  238.                             acceleration = new Vector3D(Double.parseDouble(sc.next()) * 1000,
  239.                                                         Double.parseDouble(sc.next()) * 1000,
  240.                                                         Double.parseDouble(sc.next()) * 1000);
  241.                         }
  242.                         final OEMFile.EphemeridesDataLine epDataLine =
  243.                                 new OEMFile.EphemeridesDataLine(orbit, acceleration);
  244.                         pi.lastEphemeridesBlock.getEphemeridesDataLines().add(epDataLine);
  245.                     } catch (NumberFormatException nfe) {
  246.                         throw new OrekitException(OrekitMessages.UNABLE_TO_PARSE_LINE_IN_FILE,
  247.                                                   pi.lineNumber, pi.fileName, line);
  248.                     } finally {
  249.                         if (sc != null) {
  250.                             sc.close();
  251.                         }
  252.                     }
  253.                 } else {
  254.                     switch (pi.keyValue.getKeyword()) {
  255.                         case META_START:
  256.                             pi.lastEphemeridesBlock.setEphemeridesDataLinesComment(pi.commentTmp);
  257.                             pi.commentTmp.clear();
  258.                             pi.lineNumber--;
  259.                             reader.reset();
  260.                             return;
  261.                         case COVARIANCE_START:
  262.                             pi.lastEphemeridesBlock.setEphemeridesDataLinesComment(pi.commentTmp);
  263.                             pi.commentTmp.clear();
  264.                             pi.lineNumber--;
  265.                             reader.reset();
  266.                             return;
  267.                         case COMMENT:
  268.                             pi.commentTmp.add(pi.keyValue.getValue());
  269.                             break;
  270.                         default :
  271.                             throw new OrekitException(OrekitMessages.CCSDS_UNEXPECTED_KEYWORD, pi.lineNumber, pi.fileName, line);
  272.                     }
  273.                 }
  274.             }
  275.             reader.mark(300);

  276.         }
  277.     }

  278.     /**
  279.      * Parse the covariance data lines, create a set of CovarianceMatrix objects
  280.      * and add them in the covarianceMatrices list of the ephemerides block.
  281.      *
  282.      * @param reader the reader
  283.      * @param pi the parser info
  284.      * @throws IOException if an error occurs while reading from the stream
  285.      * @throws OrekitException if the frame cannot be retrieved
  286.      */
  287.     private void parseCovarianceDataLines(final BufferedReader reader, final ParseInfo pi)
  288.         throws IOException, OrekitException  {
  289.         int i = 0;
  290.         for (String line = reader.readLine(); line != null; line = reader.readLine()) {

  291.             ++pi.lineNumber;
  292.             if (line.trim().length() == 0) {
  293.                 continue;
  294.             }
  295.             pi.keyValue = new KeyValue(line, pi.lineNumber, pi.fileName);
  296.             if (pi.keyValue.getKeyword() == null) {
  297.                 final Scanner sc = new Scanner(line);
  298.                 for (int j = 0; j < i + 1; j++) {
  299.                     try {
  300.                         pi.lastMatrix.addToEntry(i, j, Double.parseDouble(sc.next()));
  301.                     } catch (NumberFormatException nfe) {
  302.                         sc.close();
  303.                         throw new OrekitException(OrekitMessages.UNABLE_TO_PARSE_LINE_IN_FILE,
  304.                                                   pi.lineNumber, pi.fileName, line);
  305.                     }
  306.                     if (j != i) {
  307.                         pi.lastMatrix.addToEntry(j, i, pi.lastMatrix.getEntry(i, j));
  308.                     }
  309.                 }
  310.                 if (i == 5) {
  311.                     final OEMFile.CovarianceMatrix cm =
  312.                             new OEMFile.CovarianceMatrix(pi.epoch, pi.covRefLofType, pi.covRefFrame, pi.lastMatrix);
  313.                     pi.lastEphemeridesBlock.getCovarianceMatrices().add(cm);
  314.                 }
  315.                 i++;
  316.                 if (sc != null) {
  317.                     sc.close();
  318.                 }
  319.             } else {
  320.                 switch (pi.keyValue.getKeyword()) {
  321.                     case EPOCH :
  322.                         i                = 0;
  323.                         pi.covRefLofType = null;
  324.                         pi.covRefFrame   = null;
  325.                         pi.lastMatrix    = MatrixUtils.createRealMatrix(6, 6);
  326.                         pi.epoch         = parseDate(pi.keyValue.getValue(), pi.lastEphemeridesBlock.getMetaData().getTimeSystem());
  327.                         break;
  328.                     case COV_REF_FRAME :
  329.                         final CCSDSFrame frame = parseCCSDSFrame(pi.keyValue.getValue());
  330.                         if (frame.isLof()) {
  331.                             pi.covRefLofType = frame.getLofType();
  332.                             pi.covRefFrame   = null;
  333.                         } else {
  334.                             pi.covRefLofType = null;
  335.                             pi.covRefFrame   = frame.getFrame(getConventions(), isSimpleEOP());
  336.                         }
  337.                         break;
  338.                     case COVARIANCE_STOP :
  339.                         return;
  340.                     default :
  341.                         throw new OrekitException(OrekitMessages.CCSDS_UNEXPECTED_KEYWORD, pi.lineNumber, pi.fileName, line);
  342.                 }
  343.             }
  344.         }
  345.     }

  346.     /** Private class used to stock OEM parsing info.
  347.      * @author sports
  348.      */
  349.     private static class ParseInfo {

  350.         /** Ephemerides block being parsed. */
  351.         private OEMFile.EphemeridesBlock lastEphemeridesBlock;

  352.         /** Name of the file. */
  353.         private String fileName;

  354.         /** Current line number. */
  355.         private int lineNumber;

  356.         /** OEM file being read. */
  357.         private OEMFile file;

  358.         /** Key value of the line being read. */
  359.         private KeyValue keyValue;

  360.         /** Stored epoch. */
  361.         private AbsoluteDate epoch;

  362.         /** Covariance reference type of Local Orbital Frame. */
  363.         private LOFType covRefLofType;

  364.         /** Covariance reference frame. */
  365.         private Frame covRefFrame;
  366.         /** Stored matrix. */
  367.         private RealMatrix lastMatrix;

  368.         /** Stored comments. */
  369.         private List<String> commentTmp;

  370.         /** Create a new {@link ParseInfo} object. */
  371.         protected ParseInfo() {
  372.             lineNumber = 0;
  373.             file = new OEMFile();
  374.             commentTmp = new ArrayList<String>();
  375.         }
  376.     }
  377. }