AbsoluteDate.java

  1. /* Copyright 2002-2013 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.time;

  18. import java.io.Serializable;
  19. import java.util.Date;

  20. import org.apache.commons.math3.util.FastMath;
  21. import org.apache.commons.math3.util.MathArrays;
  22. import org.orekit.errors.OrekitException;
  23. import org.orekit.errors.OrekitMessages;
  24. import org.orekit.utils.Constants;


  25. /** This class represents a specific instant in time.

  26.  * <p>Instances of this class are considered to be absolute in the sense
  27.  * that each one represent the occurrence of some event and can be compared
  28.  * to other instances or located in <em>any</em> {@link TimeScale time scale}. In
  29.  * other words the different locations of an event with respect to two different
  30.  * time scales (say {@link TAIScale TAI} and {@link UTCScale UTC} for example) are
  31.  * simply different perspective related to a single object. Only one
  32.  * <code>AbsoluteDate</code> instance is needed, both representations being available
  33.  * from this single instance by specifying the time scales as parameter when calling
  34.  * the ad-hoc methods.</p>
  35.  *
  36.  * <p>Since an instance is not bound to a specific time-scale, all methods related
  37.  * to the location of the date within some time scale require to provide the time
  38.  * scale as an argument. It is therefore possible to define a date in one time scale
  39.  * and to use it in another one. An example of such use is to read a date from a file
  40.  * in UTC and write it in another file in TAI. This can be done as follows:</p>
  41.  * <pre>
  42.  *   DateTimeComponents utcComponents = readNextDate();
  43.  *   AbsoluteDate date = new AbsoluteDate(utcComponents, TimeScalesFactory.getUTC());
  44.  *   writeNextDate(date.getComponents(TimeScalesFactory.getTAI()));
  45.  * </pre>
  46.  *
  47.  * <p>Two complementary views are available:</p>
  48.  * <ul>
  49.  *   <li><p>location view (mainly for input/output or conversions)</p>
  50.  *   <p>locations represent the coordinate of one event with respect to a
  51.  *   {@link TimeScale time scale}. The related methods are {@link
  52.  *   #AbsoluteDate(DateComponents, TimeComponents, TimeScale)}, {@link
  53.  *   #AbsoluteDate(int, int, int, int, int, double, TimeScale)}, {@link
  54.  *   #AbsoluteDate(int, int, int, TimeScale)}, {@link #AbsoluteDate(Date,
  55.  *   TimeScale)}, {@link #createGPSDate(int, double)}, {@link
  56.  *   #parseCCSDSCalendarSegmentedTimeCode(byte, byte[])}, toString(){@link
  57.  *   #toDate(TimeScale)}, {@link #toString(TimeScale) toString(timeScale)},
  58.  *   {@link #toString()}, and {@link #timeScalesOffset}.</p>
  59.  *   </li>
  60.  *   <li><p>offset view (mainly for physical computation)</p>
  61.  *   <p>offsets represent either the flow of time between two events
  62.  *   (two instances of the class) or durations. They are counted in seconds,
  63.  *   are continuous and could be measured using only a virtually perfect stopwatch.
  64.  *   The related methods are {@link #AbsoluteDate(AbsoluteDate, double)},
  65.  *   {@link #parseCCSDSUnsegmentedTimeCode(byte, byte, byte[], AbsoluteDate)},
  66.  *   {@link #parseCCSDSDaySegmentedTimeCode(byte, byte[], DateComponents)},
  67.  *   {@link #durationFrom(AbsoluteDate)}, {@link #compareTo(AbsoluteDate)}, {@link #equals(Object)}
  68.  *   and {@link #hashCode()}.</p>
  69.  *   </li>
  70.  * </ul>
  71.  * <p>
  72.  * A few reference epochs which are commonly used in space systems have been defined. These
  73.  * epochs can be used as the basis for offset computation. The supported epochs are:
  74.  * {@link #JULIAN_EPOCH}, {@link #MODIFIED_JULIAN_EPOCH}, {@link #FIFTIES_EPOCH},
  75.  * {@link #CCSDS_EPOCH}, {@link #GALILEO_EPOCH}, {@link #GPS_EPOCH}, {@link #J2000_EPOCH},
  76.  * {@link #JAVA_EPOCH}. There are also two factory methods {@link #createJulianEpoch(double)}
  77.  * and {@link #createBesselianEpoch(double)} that can be used to compute other reference
  78.  * epochs like J1900.0 or B1950.0.
  79.  * In addition to these reference epochs, two other constants are defined for convenience:
  80.  * {@link #PAST_INFINITY} and {@link #FUTURE_INFINITY}, which can be used either as dummy
  81.  * dates when a date is not yet initialized, or for initialization of loops searching for
  82.  * a min or max date.
  83.  * </p>
  84.  * <p>
  85.  * Instances of the <code>AbsoluteDate</code> class are guaranteed to be immutable.
  86.  * </p>
  87.  * @author Luc Maisonobe
  88.  * @see TimeScale
  89.  * @see TimeStamped
  90.  * @see ChronologicalComparator
  91.  */
  92. public class AbsoluteDate
  93.     implements TimeStamped, TimeShiftable<AbsoluteDate>, Comparable<AbsoluteDate>, Serializable {

  94.     /** Reference epoch for julian dates: -4712-01-01T12:00:00 Terrestrial Time.
  95.      * <p>Both <code>java.util.Date</code> and {@link DateComponents} classes
  96.      * follow the astronomical conventions and consider a year 0 between
  97.      * years -1 and +1, hence this reference date lies in year -4712 and not
  98.      * in year -4713 as can be seen in other documents or programs that obey
  99.      * a different convention (for example the <code>convcal</code> utility).</p>
  100.      */
  101.     public static final AbsoluteDate JULIAN_EPOCH =
  102.         new AbsoluteDate(DateComponents.JULIAN_EPOCH, TimeComponents.H12, TimeScalesFactory.getTT());

  103.     /** Reference epoch for modified julian dates: 1858-11-17T00:00:00 Terrestrial Time. */
  104.     public static final AbsoluteDate MODIFIED_JULIAN_EPOCH =
  105.         new AbsoluteDate(DateComponents.MODIFIED_JULIAN_EPOCH, TimeComponents.H00, TimeScalesFactory.getTT());

  106.     /** Reference epoch for 1950 dates: 1950-01-01T00:00:00 Terrestrial Time. */
  107.     public static final AbsoluteDate FIFTIES_EPOCH =
  108.         new AbsoluteDate(DateComponents.FIFTIES_EPOCH, TimeComponents.H00, TimeScalesFactory.getTT());

  109.     /** Reference epoch for CCSDS Time Code Format (CCSDS 301.0-B-4):
  110.      * 1958-01-01T00:00:00 International Atomic Time (<em>not</em> UTC). */
  111.     public static final AbsoluteDate CCSDS_EPOCH =
  112.         new AbsoluteDate(DateComponents.CCSDS_EPOCH, TimeComponents.H00, TimeScalesFactory.getTAI());

  113.     /** Reference epoch for Galileo System Time: 1999-08-22T00:00:00 UTC. */
  114.     public static final AbsoluteDate GALILEO_EPOCH =
  115.         new AbsoluteDate(DateComponents.GALILEO_EPOCH, new TimeComponents(0, 0, 32),
  116.                          TimeScalesFactory.getTAI());

  117.     /** Reference epoch for GPS weeks: 1980-01-06T00:00:00 GPS time. */
  118.     public static final AbsoluteDate GPS_EPOCH =
  119.         new AbsoluteDate(DateComponents.GPS_EPOCH, TimeComponents.H00, TimeScalesFactory.getGPS());

  120.     /** J2000.0 Reference epoch: 2000-01-01T12:00:00 Terrestrial Time (<em>not</em> UTC).
  121.      * @see #createJulianEpoch(double)
  122.      * @see #createBesselianEpoch(double)
  123.      */
  124.     public static final AbsoluteDate J2000_EPOCH =
  125.         new AbsoluteDate(DateComponents.J2000_EPOCH, TimeComponents.H12, TimeScalesFactory.getTT());

  126.     /** Java Reference epoch: 1970-01-01T00:00:00 Universal Time Coordinate.
  127.      * <p>
  128.      * Between 1968-02-01 and 1972-01-01, UTC-TAI = 4.213 170 0s + (MJD - 39 126) x 0.002 592s.
  129.      * As on 1970-01-01 MJD = 40587, UTC-TAI = 8.000082s
  130.      * </p>
  131.      */
  132.     public static final AbsoluteDate JAVA_EPOCH =
  133.         new AbsoluteDate(DateComponents.JAVA_EPOCH, TimeScalesFactory.getTAI()).shiftedBy(8.000082);

  134.     /** Dummy date at infinity in the past direction. */
  135.     public static final AbsoluteDate PAST_INFINITY = JAVA_EPOCH.shiftedBy(Double.NEGATIVE_INFINITY);

  136.     /** Dummy date at infinity in the future direction. */
  137.     public static final AbsoluteDate FUTURE_INFINITY = JAVA_EPOCH.shiftedBy(Double.POSITIVE_INFINITY);

  138.     /** Serializable UID. */
  139.     private static final long serialVersionUID = 617061803741806846L;

  140.     /** Reference epoch in seconds from 2000-01-01T12:00:00 TAI.
  141.      * <p>Beware, it is not {@link #J2000_EPOCH} since it is in TAI and not in TT.</p> */
  142.     private final long epoch;

  143.     /** Offset from the reference epoch in seconds. */
  144.     private final double offset;

  145.     /** Create an instance with a default value ({@link #J2000_EPOCH}).
  146.      */
  147.     public AbsoluteDate() {
  148.         epoch  = J2000_EPOCH.epoch;
  149.         offset = J2000_EPOCH.offset;
  150.     }

  151.     /** Build an instance from a location (parsed from a string) in a {@link TimeScale time scale}.
  152.      * <p>
  153.      * The supported formats for location are mainly the ones defined in ISO-8601 standard,
  154.      * the exact subset is explained in {@link DateTimeComponents#parseDateTime(String)},
  155.      * {@link DateComponents#parseDate(String)} and {@link TimeComponents#parseTime(String)}.
  156.      * </p>
  157.      * <p>
  158.      * As CCSDS ASCII calendar segmented time code is a trimmed down version of ISO-8601,
  159.      * it is also supported by this constructor.
  160.      * </p>
  161.      * @param location location in the time scale, must be in a supported format
  162.      * @param timeScale time scale
  163.      * @exception IllegalArgumentException if location string is not in a supported format
  164.      */
  165.     public AbsoluteDate(final String location, final TimeScale timeScale) {
  166.         this(DateTimeComponents.parseDateTime(location), timeScale);
  167.     }

  168.     /** Build an instance from a location in a {@link TimeScale time scale}.
  169.      * @param location location in the time scale
  170.      * @param timeScale time scale
  171.      */
  172.     public AbsoluteDate(final DateTimeComponents location, final TimeScale timeScale) {
  173.         this(location.getDate(), location.getTime(), timeScale);
  174.     }

  175.     /** Build an instance from a location in a {@link TimeScale time scale}.
  176.      * @param date date location in the time scale
  177.      * @param time time location in the time scale
  178.      * @param timeScale time scale
  179.      */
  180.     public AbsoluteDate(final DateComponents date, final TimeComponents time,
  181.                         final TimeScale timeScale) {

  182.         final double seconds  = time.getSecond();
  183.         final double tsOffset = timeScale.offsetToTAI(date, time);

  184.         // compute sum exactly, using Møller-Knuth TwoSum algorithm without branching
  185.         // the following statements must NOT be simplified, they rely on floating point
  186.         // arithmetic properties (rounding and representable numbers)
  187.         // at the end, the EXACT result of addition seconds + tsOffset
  188.         // is sum + residual, where sum is the closest representable number to the exact
  189.         // result and residual is the missing part that does not fit in the first number
  190.         final double sum      = seconds + tsOffset;
  191.         final double sPrime   = sum - tsOffset;
  192.         final double tPrime   = sum - sPrime;
  193.         final double deltaS   = seconds  - sPrime;
  194.         final double deltaT   = tsOffset - tPrime;
  195.         final double residual = deltaS   + deltaT;
  196.         final long   dl       = (long) FastMath.floor(sum);

  197.         offset = (sum - dl) + residual;
  198.         epoch  = 60l * ((date.getJ2000Day() * 24l + time.getHour()) * 60l + time.getMinute() - 720l) + dl;

  199.     }

  200.     /** Build an instance from a location in a {@link TimeScale time scale}.
  201.      * @param year year number (may be 0 or negative for BC years)
  202.      * @param month month number from 1 to 12
  203.      * @param day day number from 1 to 31
  204.      * @param hour hour number from 0 to 23
  205.      * @param minute minute number from 0 to 59
  206.      * @param second second number from 0.0 to 60.0 (excluded)
  207.      * @param timeScale time scale
  208.      * @exception IllegalArgumentException if inconsistent arguments
  209.      * are given (parameters out of range)
  210.      */
  211.     public AbsoluteDate(final int year, final int month, final int day,
  212.                         final int hour, final int minute, final double second,
  213.                         final TimeScale timeScale) throws IllegalArgumentException {
  214.         this(new DateComponents(year, month, day), new TimeComponents(hour, minute, second), timeScale);
  215.     }

  216.     /** Build an instance from a location in a {@link TimeScale time scale}.
  217.      * @param year year number (may be 0 or negative for BC years)
  218.      * @param month month enumerate
  219.      * @param day day number from 1 to 31
  220.      * @param hour hour number from 0 to 23
  221.      * @param minute minute number from 0 to 59
  222.      * @param second second number from 0.0 to 60.0 (excluded)
  223.      * @param timeScale time scale
  224.      * @exception IllegalArgumentException if inconsistent arguments
  225.      * are given (parameters out of range)
  226.      */
  227.     public AbsoluteDate(final int year, final Month month, final int day,
  228.                         final int hour, final int minute, final double second,
  229.                         final TimeScale timeScale) throws IllegalArgumentException {
  230.         this(new DateComponents(year, month, day), new TimeComponents(hour, minute, second), timeScale);
  231.     }

  232.     /** Build an instance from a location in a {@link TimeScale time scale}.
  233.      * <p>The hour is set to 00:00:00.000.</p>
  234.      * @param date date location in the time scale
  235.      * @param timeScale time scale
  236.      * @exception IllegalArgumentException if inconsistent arguments
  237.      * are given (parameters out of range)
  238.      */
  239.     public AbsoluteDate(final DateComponents date, final TimeScale timeScale)
  240.         throws IllegalArgumentException {
  241.         this(date, TimeComponents.H00, timeScale);
  242.     }

  243.     /** Build an instance from a location in a {@link TimeScale time scale}.
  244.      * <p>The hour is set to 00:00:00.000.</p>
  245.      * @param year year number (may be 0 or negative for BC years)
  246.      * @param month month number from 1 to 12
  247.      * @param day day number from 1 to 31
  248.      * @param timeScale time scale
  249.      * @exception IllegalArgumentException if inconsistent arguments
  250.      * are given (parameters out of range)
  251.      */
  252.     public AbsoluteDate(final int year, final int month, final int day,
  253.                         final TimeScale timeScale) throws IllegalArgumentException {
  254.         this(new DateComponents(year, month, day), TimeComponents.H00, timeScale);
  255.     }

  256.     /** Build an instance from a location in a {@link TimeScale time scale}.
  257.      * <p>The hour is set to 00:00:00.000.</p>
  258.      * @param year year number (may be 0 or negative for BC years)
  259.      * @param month month enumerate
  260.      * @param day day number from 1 to 31
  261.      * @param timeScale time scale
  262.      * @exception IllegalArgumentException if inconsistent arguments
  263.      * are given (parameters out of range)
  264.      */
  265.     public AbsoluteDate(final int year, final Month month, final int day,
  266.                         final TimeScale timeScale) throws IllegalArgumentException {
  267.         this(new DateComponents(year, month, day), TimeComponents.H00, timeScale);
  268.     }

  269.     /** Build an instance from a location in a {@link TimeScale time scale}.
  270.      * @param location location in the time scale
  271.      * @param timeScale time scale
  272.      */
  273.     public AbsoluteDate(final Date location, final TimeScale timeScale) {
  274.         this(new DateComponents(DateComponents.JAVA_EPOCH,
  275.                                 (int) (location.getTime() / 86400000l)),
  276.                                 new TimeComponents(0.001 * (location.getTime() % 86400000l)),
  277.              timeScale);
  278.     }

  279.     /** Build an instance from an elapsed duration since to another instant.
  280.      * <p>It is important to note that the elapsed duration is <em>not</em>
  281.      * the difference between two readings on a time scale. As an example,
  282.      * the duration between the two instants leading to the readings
  283.      * 2005-12-31T23:59:59 and 2006-01-01T00:00:00 in the {@link UTCScale UTC}
  284.      * time scale is <em>not</em> 1 second, but a stop watch would have measured
  285.      * an elapsed duration of 2 seconds between these two instances because a leap
  286.      * second was introduced at the end of 2005 in this time scale.</p>
  287.      * <p>This constructor is the reverse of the {@link #durationFrom(AbsoluteDate)}
  288.      * method.</p>
  289.      * @param since start instant of the measured duration
  290.      * @param elapsedDuration physically elapsed duration from the <code>since</code>
  291.      * instant, as measured in a regular time scale
  292.      * @see #durationFrom(AbsoluteDate)
  293.      */
  294.     public AbsoluteDate(final AbsoluteDate since, final double elapsedDuration) {

  295.         final double sum = since.offset + elapsedDuration;
  296.         if (Double.isInfinite(sum)) {
  297.             offset = sum;
  298.             epoch  = (sum < 0) ? Long.MIN_VALUE : Long.MAX_VALUE;
  299.         } else {
  300.             // compute sum exactly, using Møller-Knuth TwoSum algorithm without branching
  301.             // the following statements must NOT be simplified, they rely on floating point
  302.             // arithmetic properties (rounding and representable numbers)
  303.             // at the end, the EXACT result of addition since.offset + elapsedDuration
  304.             // is sum + residual, where sum is the closest representable number to the exact
  305.             // result and residual is the missing part that does not fit in the first number
  306.             final double oPrime   = sum - elapsedDuration;
  307.             final double dPrime   = sum - oPrime;
  308.             final double deltaO   = since.offset - oPrime;
  309.             final double deltaD   = elapsedDuration - dPrime;
  310.             final double residual = deltaO + deltaD;
  311.             final long   dl       = (long) FastMath.floor(sum);
  312.             offset = (sum - dl) + residual;
  313.             epoch  = since.epoch  + dl;
  314.         }
  315.     }

  316.     /** Build an instance from an apparent clock offset with respect to another
  317.      * instant <em>in the perspective of a specific {@link TimeScale time scale}</em>.
  318.      * <p>It is important to note that the apparent clock offset <em>is</em> the
  319.      * difference between two readings on a time scale and <em>not</em> an elapsed
  320.      * duration. As an example, the apparent clock offset between the two instants
  321.      * leading to the readings 2005-12-31T23:59:59 and 2006-01-01T00:00:00 in the
  322.      * {@link UTCScale UTC} time scale is 1 second, but the elapsed duration is 2
  323.      * seconds because a leap second has been introduced at the end of 2005 in this
  324.      * time scale.</p>
  325.      * <p>This constructor is the reverse of the {@link #offsetFrom(AbsoluteDate,
  326.      * TimeScale)} method.</p>
  327.      * @param reference reference instant
  328.      * @param apparentOffset apparent clock offset from the reference instant
  329.      * (difference between two readings in the specified time scale)
  330.      * @param timeScale time scale with respect to which the offset is defined
  331.      * @see #offsetFrom(AbsoluteDate, TimeScale)
  332.      */
  333.     public AbsoluteDate(final AbsoluteDate reference, final double apparentOffset,
  334.                         final TimeScale timeScale) {
  335.         this(new DateTimeComponents(reference.getComponents(timeScale), apparentOffset),
  336.              timeScale);
  337.     }

  338.     /** Build an instance from a CCSDS Unsegmented Time Code (CUC).
  339.      * <p>
  340.      * CCSDS Unsegmented Time Code is defined in the blue book:
  341.      * CCSDS Time Code Format (CCSDS 301.0-B-4) published in November 2010
  342.      * </p>
  343.      * <p>
  344.      * If the date to be parsed is formatted using version 3 of the standard
  345.      * (CCSDS 301.0-B-3 published in 2002) or if the extension of the preamble
  346.      * field introduced in version 4 of the standard is not used, then the
  347.      * {@code preambleField2} parameter can be set to 0.
  348.      * </p>
  349.      * @param preambleField1 first byte of the field specifying the format, often
  350.      * not transmitted in data interfaces, as it is constant for a given data interface
  351.      * @param preambleField2 second byte of the field specifying the format
  352.      * (added in revision 4 of the CCSDS standard in 2010), often not transmitted in data
  353.      * interfaces, as it is constant for a given data interface (value ignored if presence
  354.      * not signaled in {@code preambleField1})
  355.      * @param timeField byte array containing the time code
  356.      * @param agencyDefinedEpoch reference epoch, ignored if the preamble field
  357.      * specifies the {@link #CCSDS_EPOCH CCSDS reference epoch} is used (and hence
  358.      * may be null in this case)
  359.      * @return an instance corresponding to the specified date
  360.      * @throws OrekitException if preamble is inconsistent with Unsegmented Time Code,
  361.      * or if it is inconsistent with time field, or if agency epoch is needed but not provided
  362.      */
  363.     public static AbsoluteDate parseCCSDSUnsegmentedTimeCode(final byte preambleField1,
  364.                                                              final byte preambleField2,
  365.                                                              final byte[] timeField,
  366.                                                              final AbsoluteDate agencyDefinedEpoch)
  367.         throws OrekitException {

  368.         // time code identification and reference epoch
  369.         final AbsoluteDate epoch;
  370.         switch (preambleField1 & 0x70) {
  371.         case 0x10:
  372.             // the reference epoch is CCSDS epoch 1958-01-01T00:00:00 TAI
  373.             epoch = CCSDS_EPOCH;
  374.             break;
  375.         case 0x20:
  376.             // the reference epoch is agency defined
  377.             if (agencyDefinedEpoch == null) {
  378.                 throw new OrekitException(OrekitMessages.CCSDS_DATE_MISSING_AGENCY_EPOCH);
  379.             }
  380.             epoch = agencyDefinedEpoch;
  381.             break;
  382.         default :
  383.             throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_PREAMBLE_FIELD,
  384.                                       formatByte(preambleField1));
  385.         }

  386.         // time field lengths
  387.         int coarseTimeLength = 1 + ((preambleField1 & 0x0C) >>> 2);
  388.         int fineTimeLength   = preambleField1 & 0x03;

  389.         if ((preambleField1 & 0x80) != 0x0) {
  390.             // there is an additional octet in preamble field
  391.             coarseTimeLength += (preambleField2 & 0x60) >>> 5;
  392.             fineTimeLength   += (preambleField2 & 0x1C) >>> 2;
  393.         }

  394.         if (timeField.length != coarseTimeLength + fineTimeLength) {
  395.             throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_LENGTH_TIME_FIELD,
  396.                                       timeField.length, coarseTimeLength + fineTimeLength);
  397.         }

  398.         double seconds = 0;
  399.         for (int i = 0; i < coarseTimeLength; ++i) {
  400.             seconds = seconds * 256 + toUnsigned(timeField[i]);
  401.         }
  402.         double subseconds = 0;
  403.         for (int i = timeField.length - 1; i >= coarseTimeLength; --i) {
  404.             subseconds = (subseconds + toUnsigned(timeField[i])) / 256;
  405.         }

  406.         return new AbsoluteDate(epoch, seconds).shiftedBy(subseconds);

  407.     }

  408.     /** Build an instance from a CCSDS Day Segmented Time Code (CDS).
  409.      * <p>
  410.      * CCSDS Day Segmented Time Code is defined in the blue book:
  411.      * CCSDS Time Code Format (CCSDS 301.0-B-4) published in November 2010
  412.      * </p>
  413.      * @param preambleField field specifying the format, often not transmitted in
  414.      * data interfaces, as it is constant for a given data interface
  415.      * @param timeField byte array containing the time code
  416.      * @param agencyDefinedEpoch reference epoch, ignored if the preamble field
  417.      * specifies the {@link #CCSDS_EPOCH CCSDS reference epoch} is used (and hence
  418.      * may be null in this case)
  419.      * @return an instance corresponding to the specified date
  420.      * @throws OrekitException if preamble is inconsistent with Day Segmented Time Code,
  421.      * or if it is inconsistent with time field, or if agency epoch is needed but not provided,
  422.      * or it UTC time scale cannot be retrieved
  423.      */
  424.     public static AbsoluteDate parseCCSDSDaySegmentedTimeCode(final byte preambleField, final byte[] timeField,
  425.                                                               final DateComponents agencyDefinedEpoch)
  426.         throws OrekitException {

  427.         // time code identification
  428.         if ((preambleField & 0xF0) != 0x40) {
  429.             throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_PREAMBLE_FIELD,
  430.                                       formatByte(preambleField));
  431.         }

  432.         // reference epoch
  433.         final DateComponents epoch;
  434.         if ((preambleField & 0x08) == 0x00) {
  435.             // the reference epoch is CCSDS epoch 1958-01-01T00:00:00 TAI
  436.             epoch = DateComponents.CCSDS_EPOCH;
  437.         } else {
  438.             // the reference epoch is agency defined
  439.             if (agencyDefinedEpoch == null) {
  440.                 throw new OrekitException(OrekitMessages.CCSDS_DATE_MISSING_AGENCY_EPOCH);
  441.             }
  442.             epoch = agencyDefinedEpoch;
  443.         }

  444.         // time field lengths
  445.         final int daySegmentLength = ((preambleField & 0x04) == 0x0) ? 2 : 3;
  446.         final int subMillisecondLength = (preambleField & 0x03) << 1;
  447.         if (subMillisecondLength == 6) {
  448.             throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_PREAMBLE_FIELD,
  449.                                       formatByte(preambleField));
  450.         }
  451.         if (timeField.length != daySegmentLength + 4 + subMillisecondLength) {
  452.             throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_LENGTH_TIME_FIELD,
  453.                                       timeField.length, daySegmentLength + 4 + subMillisecondLength);
  454.         }


  455.         int i   = 0;
  456.         int day = 0;
  457.         while (i < daySegmentLength) {
  458.             day = day * 256 + toUnsigned(timeField[i++]);
  459.         }

  460.         long milliInDay = 0l;
  461.         while (i < daySegmentLength + 4) {
  462.             milliInDay = milliInDay * 256 + toUnsigned(timeField[i++]);
  463.         }
  464.         final int milli   = (int) (milliInDay % 1000l);
  465.         final int seconds = (int) ((milliInDay - milli) / 1000l);

  466.         double subMilli = 0;
  467.         double divisor  = 1;
  468.         while (i < timeField.length) {
  469.             subMilli = subMilli * 256 + toUnsigned(timeField[i++]);
  470.             divisor *= 1000;
  471.         }

  472.         final DateComponents date = new DateComponents(epoch, day);
  473.         final TimeComponents time = new TimeComponents(seconds);
  474.         return new AbsoluteDate(date, time, TimeScalesFactory.getUTC()).shiftedBy(milli * 1.0e-3 + subMilli / divisor);

  475.     }

  476.     /** Build an instance from a CCSDS Calendar Segmented Time Code (CCS).
  477.      * <p>
  478.      * CCSDS Calendar Segmented Time Code is defined in the blue book:
  479.      * CCSDS Time Code Format (CCSDS 301.0-B-4) published in November 2010
  480.      * </p>
  481.      * @param preambleField field specifying the format, often not transmitted in
  482.      * data interfaces, as it is constant for a given data interface
  483.      * @param timeField byte array containing the time code
  484.      * @return an instance corresponding to the specified date
  485.      * @throws OrekitException if preamble is inconsistent with Calendar Segmented Time Code,
  486.      * or if it is inconsistent with time field, or it UTC time scale cannot be retrieved
  487.      */
  488.     public static AbsoluteDate parseCCSDSCalendarSegmentedTimeCode(final byte preambleField, final byte[] timeField)
  489.         throws OrekitException {

  490.         // time code identification
  491.         if ((preambleField & 0xF0) != 0x50) {
  492.             throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_PREAMBLE_FIELD,
  493.                                       formatByte(preambleField));
  494.         }

  495.         // time field length
  496.         final int length = 7 + (preambleField & 0x07);
  497.         if (length == 14) {
  498.             throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_PREAMBLE_FIELD,
  499.                                       formatByte(preambleField));
  500.         }
  501.         if (timeField.length != length) {
  502.             throw new OrekitException(OrekitMessages.CCSDS_DATE_INVALID_LENGTH_TIME_FIELD,
  503.                                       timeField.length, length);
  504.         }

  505.         // date part in the first four bytes
  506.         final DateComponents date;
  507.         if ((preambleField & 0x08) == 0x00) {
  508.             // month of year and day of month variation
  509.             date = new DateComponents(toUnsigned(timeField[0]) * 256 + toUnsigned(timeField[1]),
  510.                                       toUnsigned(timeField[2]),
  511.                                       toUnsigned(timeField[3]));
  512.         } else {
  513.             // day of year variation
  514.             date = new DateComponents(toUnsigned(timeField[0]) * 256 + toUnsigned(timeField[1]),
  515.                                       toUnsigned(timeField[2]) * 256 + toUnsigned(timeField[3]));
  516.         }

  517.         // time part from bytes 5 to last (between 7 and 13 depending on precision)
  518.         final TimeComponents time = new TimeComponents(toUnsigned(timeField[4]),
  519.                                                        toUnsigned(timeField[5]),
  520.                                                        toUnsigned(timeField[6]));
  521.         double subSecond = 0;
  522.         double divisor   = 1;
  523.         for (int i = 7; i < length; ++i) {
  524.             subSecond = subSecond * 100 + toUnsigned(timeField[i]);
  525.             divisor *= 100;
  526.         }

  527.         return new AbsoluteDate(date, time, TimeScalesFactory.getUTC()).shiftedBy(subSecond / divisor);

  528.     }

  529.     /** Decode a signed byte as an unsigned int value.
  530.      * @param b byte to decode
  531.      * @return an unsigned int value
  532.      */
  533.     private static int toUnsigned(final byte b) {
  534.         final int i = (int) b;
  535.         return (i < 0) ? 256 + i : i;
  536.     }

  537.     /** Format a byte as an hex string for error messages.
  538.      * @param data byte to format
  539.      * @return a formatted string
  540.      */
  541.     private static String formatByte(final byte data) {
  542.         return "0x" + Integer.toHexString(data).toUpperCase();
  543.     }

  544.     /** Build an instance corresponding to a GPS date.
  545.      * <p>GPS dates are provided as a week number starting at
  546.      * {@link #GPS_EPOCH GPS epoch} and as a number of milliseconds
  547.      * since week start.</p>
  548.      * @param weekNumber week number since {@link #GPS_EPOCH GPS epoch}
  549.      * @param milliInWeek number of milliseconds since week start
  550.      * @return a new instant
  551.      */
  552.     public static AbsoluteDate createGPSDate(final int weekNumber,
  553.                                              final double milliInWeek) {
  554.         final int day = (int) FastMath.floor(milliInWeek / (1000.0 * Constants.JULIAN_DAY));
  555.         final double secondsInDay = milliInWeek / 1000.0 - day * Constants.JULIAN_DAY;
  556.         return new AbsoluteDate(new DateComponents(DateComponents.GPS_EPOCH, weekNumber * 7 + day),
  557.                                 new TimeComponents(secondsInDay),
  558.                                 TimeScalesFactory.getGPS());
  559.     }

  560.     /** Build an instance corresponding to a Julian Epoch (JE).
  561.      * <p>According to Lieske paper: <a
  562.      * href="http://articles.adsabs.harvard.edu/cgi-bin/nph-iarticle_query?1979A%26A....73..282L&defaultprint=YES&filetype=.pdf.">
  563.      * Precession Matrix Based on IAU (1976) System of Astronomical Constants</a>, Astronomy and Astrophysics,
  564.      * vol. 73, no. 3, Mar. 1979, p. 282-284, Julian Epoch is related to Julian Ephemeris Date as:</p>
  565.      * <pre>
  566.      * JE = 2000.0 + (JED - 2451545.0) / 365.25
  567.      * </pre>
  568.      * <p>
  569.      * This method reverts the formula above and computes an {@code AbsoluteDate} from the Julian Epoch.
  570.      * </p>
  571.      * @param julianEpoch Julian epoch, like 2000.0 for defining the classical reference J2000.0
  572.      * @return a new instant
  573.      * @see #J2000_EPOCH
  574.      * @see #createBesselianEpoch(double)
  575.      */
  576.     public static AbsoluteDate createJulianEpoch(final double julianEpoch) {
  577.         return new AbsoluteDate(J2000_EPOCH,
  578.                                 Constants.JULIAN_YEAR * (julianEpoch - 2000.0));
  579.     }

  580.     /** Build an instance corresponding to a Besselian Epoch (BE).
  581.      * <p>According to Lieske paper: <a
  582.      * href="http://articles.adsabs.harvard.edu/cgi-bin/nph-iarticle_query?1979A%26A....73..282L&defaultprint=YES&filetype=.pdf.">
  583.      * Precession Matrix Based on IAU (1976) System of Astronomical Constants</a>, Astronomy and Astrophysics,
  584.      * vol. 73, no. 3, Mar. 1979, p. 282-284, Besselian Epoch is related to Julian Ephemeris Date as:</p>
  585.      * <pre>
  586.      * BE = 1900.0 + (JED - 2415020.31352) / 365.242198781
  587.      * </pre>
  588.      * <p>
  589.      * This method reverts the formula above and computes an {@code AbsoluteDate} from the Besselian Epoch.
  590.      * </p>
  591.      * @param besselianEpoch Besselian epoch, like 1950 for defining the classical reference B1950.0
  592.      * @return a new instant
  593.      * @see #createJulianEpoch(double)
  594.      */
  595.     public static AbsoluteDate createBesselianEpoch(final double besselianEpoch) {
  596.         return new AbsoluteDate(J2000_EPOCH,
  597.                                 MathArrays.linearCombination(Constants.BESSELIAN_YEAR, besselianEpoch - 1900,
  598.                                                              Constants.JULIAN_DAY, -36525,
  599.                                                              Constants.JULIAN_DAY, 0.31352));
  600.     }

  601.     /** Get a time-shifted date.
  602.      * <p>
  603.      * Calling this method is equivalent to call <code>new AbsoluteDate(this, dt)</code>.
  604.      * </p>
  605.      * @param dt time shift in seconds
  606.      * @return a new date, shifted with respect to instance (which is immutable)
  607.      * @see org.orekit.utils.PVCoordinates#shiftedBy(double)
  608.      * @see org.orekit.attitudes.Attitude#shiftedBy(double)
  609.      * @see org.orekit.orbits.Orbit#shiftedBy(double)
  610.      * @see org.orekit.propagation.SpacecraftState#shiftedBy(double)
  611.      */
  612.     public AbsoluteDate shiftedBy(final double dt) {
  613.         return new AbsoluteDate(this, dt);
  614.     }

  615.     /** Compute the physically elapsed duration between two instants.
  616.      * <p>The returned duration is the number of seconds physically
  617.      * elapsed between the two instants, measured in a regular time
  618.      * scale with respect to surface of the Earth (i.e either the {@link
  619.      * TAIScale TAI scale}, the {@link TTScale TT scale} or the {@link
  620.      * GPSScale GPS scale}). It is the only method that gives a
  621.      * duration with a physical meaning.</p>
  622.      * <p>This method gives the same result (with less computation)
  623.      * as calling {@link #offsetFrom(AbsoluteDate, TimeScale)}
  624.      * with a second argument set to one of the regular scales cited
  625.      * above.</p>
  626.      * <p>This method is the reverse of the {@link #AbsoluteDate(AbsoluteDate,
  627.      * double)} constructor.</p>
  628.      * @param instant instant to subtract from the instance
  629.      * @return offset in seconds between the two instants (positive
  630.      * if the instance is posterior to the argument)
  631.      * @see #offsetFrom(AbsoluteDate, TimeScale)
  632.      * @see #AbsoluteDate(AbsoluteDate, double)
  633.      */
  634.     public double durationFrom(final AbsoluteDate instant) {
  635.         return (epoch - instant.epoch) + (offset - instant.offset);
  636.     }

  637.     /** Compute the apparent clock offset between two instant <em>in the
  638.      * perspective of a specific {@link TimeScale time scale}</em>.
  639.      * <p>The offset is the number of seconds counted in the given
  640.      * time scale between the locations of the two instants, with
  641.      * all time scale irregularities removed (i.e. considering all
  642.      * days are exactly 86400 seconds long). This method will give
  643.      * a result that may not have a physical meaning if the time scale
  644.      * is irregular. For example since a leap second was introduced at
  645.      * the end of 2005, the apparent offset between 2005-12-31T23:59:59
  646.      * and 2006-01-01T00:00:00 is 1 second, but the physical duration
  647.      * of the corresponding time interval as returned by the {@link
  648.      * #durationFrom(AbsoluteDate)} method is 2 seconds.</p>
  649.      * <p>This method is the reverse of the {@link #AbsoluteDate(AbsoluteDate,
  650.      * double, TimeScale)} constructor.</p>
  651.      * @param instant instant to subtract from the instance
  652.      * @param timeScale time scale with respect to which the offset should
  653.      * be computed
  654.      * @return apparent clock offset in seconds between the two instants
  655.      * (positive if the instance is posterior to the argument)
  656.      * @see #durationFrom(AbsoluteDate)
  657.      * @see #AbsoluteDate(AbsoluteDate, double, TimeScale)
  658.      */
  659.     public double offsetFrom(final AbsoluteDate instant, final TimeScale timeScale) {
  660.         final long   elapsedDurationA = epoch - instant.epoch;
  661.         final double elapsedDurationB = (offset         + timeScale.offsetFromTAI(this)) -
  662.                                         (instant.offset + timeScale.offsetFromTAI(instant));
  663.         return  elapsedDurationA + elapsedDurationB;
  664.     }

  665.     /** Compute the offset between two time scales at the current instant.
  666.      * <p>The offset is defined as <i>l<sub>1</sub>-l<sub>2</sub></i>
  667.      * where <i>l<sub>1</sub></i> is the location of the instant in
  668.      * the <code>scale1</code> time scale and <i>l<sub>2</sub></i> is the
  669.      * location of the instant in the <code>scale2</code> time scale.</p>
  670.      * @param scale1 first time scale
  671.      * @param scale2 second time scale
  672.      * @return offset in seconds between the two time scales at the
  673.      * current instant
  674.      */
  675.     public double timeScalesOffset(final TimeScale scale1, final TimeScale scale2) {
  676.         return scale1.offsetFromTAI(this) - scale2.offsetFromTAI(this);
  677.     }

  678.     /** Convert the instance to a Java {@link java.util.Date Date}.
  679.      * <p>Conversion to the Date class induces a loss of precision because
  680.      * the Date class does not provide sub-millisecond information. Java Dates
  681.      * are considered to be locations in some times scales.</p>
  682.      * @param timeScale time scale to use
  683.      * @return a {@link java.util.Date Date} instance representing the location
  684.      * of the instant in the time scale
  685.      */
  686.     public Date toDate(final TimeScale timeScale) {
  687.         final double time = epoch + (offset + timeScale.offsetFromTAI(this));
  688.         return new Date(FastMath.round((time + 10957.5 * 86400.0) * 1000));
  689.     }

  690.     /** Split the instance into date/time components.
  691.      * @param timeScale time scale to use
  692.      * @return date/time components
  693.      */
  694.     public DateTimeComponents getComponents(final TimeScale timeScale) {

  695.         // compute offset from 2000-01-01T00:00:00 in specified time scale exactly,
  696.         // using Møller-Knuth TwoSum algorithm without branching
  697.         // the following statements must NOT be simplified, they rely on floating point
  698.         // arithmetic properties (rounding and representable numbers)
  699.         // at the end, the EXACT result of addition offset + timeScale.offsetFromTAI(this)
  700.         // is sum + residual, where sum is the closest representable number to the exact
  701.         // result and residual is the missing part that does not fit in the first number
  702.         final double taiOffset = timeScale.offsetFromTAI(this);
  703.         final double sum       = offset + taiOffset;
  704.         final double oPrime    = sum - taiOffset;
  705.         final double dPrime    = sum - oPrime;
  706.         final double deltaO    = offset - oPrime;
  707.         final double deltaD    = taiOffset - dPrime;
  708.         final double residual  = deltaO + deltaD;

  709.         // split date and time
  710.         final long   carry = (long) FastMath.floor(sum);
  711.         double offset2000B = (sum - carry) + residual;
  712.         long   offset2000A = epoch + carry + 43200l;
  713.         if (offset2000B < 0) {
  714.             offset2000A -= 1;
  715.             offset2000B += 1;
  716.         }
  717.         long time = offset2000A % 86400l;
  718.         if (time < 0l) {
  719.             time += 86400l;
  720.         }
  721.         final int date = (int) ((offset2000A - time) / 86400l);

  722.         // extract calendar elements
  723.         final DateComponents dateComponents = new DateComponents(DateComponents.J2000_EPOCH, date);
  724.         TimeComponents timeComponents = new TimeComponents((int) time, offset2000B);

  725.         if (timeScale instanceof UTCScale) {
  726.             final UTCScale utc = (UTCScale) timeScale;
  727.             if (utc.insideLeap(this)) {
  728.                 // fix the seconds number to take the leap into account
  729.                 timeComponents = new TimeComponents(timeComponents.getHour(), timeComponents.getMinute(),
  730.                                                     timeComponents.getSecond() + utc.getLeap(this));
  731.             }
  732.         }

  733.         // build the components
  734.         return new DateTimeComponents(dateComponents, timeComponents);

  735.     }

  736.     /** Compare the instance with another date.
  737.      * @param date other date to compare the instance to
  738.      * @return a negative integer, zero, or a positive integer as this date
  739.      * is before, simultaneous, or after the specified date.
  740.      */
  741.     public int compareTo(final AbsoluteDate date) {
  742.         final double delta = durationFrom(date);
  743.         if (delta < 0) {
  744.             return -1;
  745.         } else if (delta > 0) {
  746.             return +1;
  747.         }
  748.         return 0;
  749.     }

  750.     /** {@inheritDoc} */
  751.     public AbsoluteDate getDate() {
  752.         return this;
  753.     }

  754.     /** Check if the instance represent the same time as another instance.
  755.      * @param date other date
  756.      * @return true if the instance and the other date refer to the same instant
  757.      */
  758.     public boolean equals(final Object date) {

  759.         if (date == this) {
  760.             // first fast check
  761.             return true;
  762.         }

  763.         if ((date != null) && (date instanceof AbsoluteDate)) {
  764.             return durationFrom((AbsoluteDate) date) == 0;
  765.         }

  766.         return false;

  767.     }

  768.     /** Get a hashcode for this date.
  769.      * @return hashcode
  770.      */
  771.     public int hashCode() {
  772.         final long l = Double.doubleToLongBits(durationFrom(J2000_EPOCH));
  773.         return (int) (l ^ (l >>> 32));
  774.     }

  775.     /** Get a String representation of the instant location in UTC time scale.
  776.      * @return a string representation of the instance,
  777.      * in ISO-8601 format with milliseconds accuracy
  778.      */
  779.     public String toString() {
  780.         try {
  781.             return toString(TimeScalesFactory.getUTC());
  782.         } catch (OrekitException oe) {
  783.             throw new RuntimeException(oe);
  784.         }
  785.     }

  786.     /** Get a String representation of the instant location.
  787.      * @param timeScale time scale to use
  788.      * @return a string representation of the instance,
  789.      * in ISO-8601 format with milliseconds accuracy
  790.      */
  791.     public String toString(final TimeScale timeScale) {
  792.         return getComponents(timeScale).toString();
  793.     }

  794. }