UTCScale.java

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

  18. import java.io.Serializable;
  19. import java.util.ArrayList;
  20. import java.util.Collection;
  21. import java.util.Comparator;
  22. import java.util.List;

  23. import org.hipparchus.CalculusFieldElement;
  24. import org.hipparchus.util.FastMath;
  25. import org.orekit.annotation.DefaultDataContext;
  26. import org.orekit.data.DataContext;
  27. import org.orekit.errors.OrekitException;
  28. import org.orekit.errors.OrekitInternalError;
  29. import org.orekit.utils.Constants;

  30. /** Coordinated Universal Time.
  31.  * <p>UTC is related to TAI using step adjustments from time to time
  32.  * according to IERS (International Earth Rotation Service) rules. Before 1972,
  33.  * these adjustments were piecewise linear offsets. Since 1972, these adjustments
  34.  * are piecewise constant offsets, which require introduction of leap seconds.</p>
  35.  * <p>Leap seconds are always inserted as additional seconds at the last minute
  36.  * of the day, pushing the next day forward. Such minutes are therefore more
  37.  * than 60 seconds long. In theory, there may be seconds removal instead of seconds
  38.  * insertion, but up to now (2010) it has never been used. As an example, when a
  39.  * one second leap was introduced at the end of 2005, the UTC time sequence was
  40.  * 2005-12-31T23:59:59 UTC, followed by 2005-12-31T23:59:60 UTC, followed by
  41.  * 2006-01-01T00:00:00 UTC.</p>
  42.  * <p>This is intended to be accessed thanks to {@link TimeScales},
  43.  * so there is no public constructor.</p>
  44.  * @author Luc Maisonobe
  45.  * @see AbsoluteDate
  46.  */
  47. public class UTCScale implements TimeScale {

  48.     /** Serializable UID. */
  49.     private static final long serialVersionUID = 20150402L;

  50.     /** UTC-TAI offsets. */
  51.     private UTCTAIOffset[] offsets;

  52.     /** Package private constructor for the factory.
  53.      * Used to create the prototype instance of this class that is used to
  54.      * clone all subsequent instances of {@link UTCScale}. Initializes the offset
  55.      * table that is shared among all instances.
  56.      * @param tai TAI time scale this UTC time scale references.
  57.      * @param offsets UTC-TAI offsets
  58.      */
  59.     UTCScale(final TimeScale tai, final Collection<? extends OffsetModel> offsets) {
  60.         // copy input so the original list is unmodified
  61.         final List<OffsetModel> offsetModels = new ArrayList<>(offsets);
  62.         offsetModels.sort(Comparator.comparing(OffsetModel::getStart));
  63.         if (offsetModels.get(0).getStart().getYear() > 1968) {
  64.             // the pre-1972 linear offsets are missing, add them manually
  65.             // excerpt from UTC-TAI.history file:
  66.             //  1961  Jan.  1 - 1961  Aug.  1     1.422 818 0s + (MJD - 37 300) x 0.001 296s
  67.             //        Aug.  1 - 1962  Jan.  1     1.372 818 0s +        ""
  68.             //  1962  Jan.  1 - 1963  Nov.  1     1.845 858 0s + (MJD - 37 665) x 0.001 123 2s
  69.             //  1963  Nov.  1 - 1964  Jan.  1     1.945 858 0s +        ""
  70.             //  1964  Jan.  1 -       April 1     3.240 130 0s + (MJD - 38 761) x 0.001 296s
  71.             //        April 1 -       Sept. 1     3.340 130 0s +        ""
  72.             //        Sept. 1 - 1965  Jan.  1     3.440 130 0s +        ""
  73.             //  1965  Jan.  1 -       March 1     3.540 130 0s +        ""
  74.             //        March 1 -       Jul.  1     3.640 130 0s +        ""
  75.             //        Jul.  1 -       Sept. 1     3.740 130 0s +        ""
  76.             //        Sept. 1 - 1966  Jan.  1     3.840 130 0s +        ""
  77.             //  1966  Jan.  1 - 1968  Feb.  1     4.313 170 0s + (MJD - 39 126) x 0.002 592s
  78.             //  1968  Feb.  1 - 1972  Jan.  1     4.213 170 0s +        ""
  79.             offsetModels.add( 0, new OffsetModel(new DateComponents(1961,  1, 1), 37300, 1.4228180, 0.0012960));
  80.             offsetModels.add( 1, new OffsetModel(new DateComponents(1961,  8, 1), 37300, 1.3728180, 0.0012960));
  81.             offsetModels.add( 2, new OffsetModel(new DateComponents(1962,  1, 1), 37665, 1.8458580, 0.0011232));
  82.             offsetModels.add( 3, new OffsetModel(new DateComponents(1963, 11, 1), 37665, 1.9458580, 0.0011232));
  83.             offsetModels.add( 4, new OffsetModel(new DateComponents(1964,  1, 1), 38761, 3.2401300, 0.0012960));
  84.             offsetModels.add( 5, new OffsetModel(new DateComponents(1964,  4, 1), 38761, 3.3401300, 0.0012960));
  85.             offsetModels.add( 6, new OffsetModel(new DateComponents(1964,  9, 1), 38761, 3.4401300, 0.0012960));
  86.             offsetModels.add( 7, new OffsetModel(new DateComponents(1965,  1, 1), 38761, 3.5401300, 0.0012960));
  87.             offsetModels.add( 8, new OffsetModel(new DateComponents(1965,  3, 1), 38761, 3.6401300, 0.0012960));
  88.             offsetModels.add( 9, new OffsetModel(new DateComponents(1965,  7, 1), 38761, 3.7401300, 0.0012960));
  89.             offsetModels.add(10, new OffsetModel(new DateComponents(1965,  9, 1), 38761, 3.8401300, 0.0012960));
  90.             offsetModels.add(11, new OffsetModel(new DateComponents(1966,  1, 1), 39126, 4.3131700, 0.0025920));
  91.             offsetModels.add(12, new OffsetModel(new DateComponents(1968,  2, 1), 39126, 4.2131700, 0.0025920));
  92.         }

  93.         // create cache
  94.         this.offsets = new UTCTAIOffset[offsetModels.size()];

  95.         UTCTAIOffset previous = null;

  96.         // link the offsets together
  97.         for (int i = 0; i < offsetModels.size(); ++i) {

  98.             final OffsetModel    o      = offsetModels.get(i);
  99.             final DateComponents date   = o.getStart();
  100.             final int            mjdRef = o.getMJDRef();
  101.             final double         offset = o.getOffset();
  102.             final double         slope  = o.getSlope();

  103.             // start of the leap
  104.             final double previousOffset    = (previous == null) ? 0.0 : previous.getOffset(date, TimeComponents.H00);
  105.             final AbsoluteDate leapStart   = new AbsoluteDate(date, tai).shiftedBy(previousOffset);

  106.             // end of the leap
  107.             final double startOffset       = offset + slope * (date.getMJD() - mjdRef);
  108.             final AbsoluteDate leapEnd     = new AbsoluteDate(date, tai).shiftedBy(startOffset);

  109.             // leap computed at leap start and in UTC scale
  110.             final double normalizedSlope   = slope / Constants.JULIAN_DAY;
  111.             final double leap              = leapEnd.durationFrom(leapStart) / (1 + normalizedSlope);

  112.             final AbsoluteDate reference = AbsoluteDate.createMJDDate(mjdRef, 0, tai)
  113.                     .shiftedBy(offset);
  114.             previous = new UTCTAIOffset(leapStart, date.getMJD(), leap, offset, mjdRef,
  115.                     normalizedSlope, reference);
  116.             this.offsets[i] = previous;

  117.         }

  118.     }

  119.     /**
  120.      * Returns the UTC-TAI offsets underlying this UTC scale.
  121.      * <p>
  122.      * Modifications to the returned list will not affect this UTC scale instance.
  123.      * @return new non-null modifiable list of UTC-TAI offsets time-sorted from
  124.      *         earliest to latest
  125.      */
  126.     public List<UTCTAIOffset> getUTCTAIOffsets() {
  127.         final List<UTCTAIOffset> offsetList = new ArrayList<>(offsets.length);
  128.         for (int i = 0; i < offsets.length; ++i) {
  129.             offsetList.add(offsets[i]);
  130.         }
  131.         return offsetList;
  132.     }

  133.     /** {@inheritDoc} */
  134.     @Override
  135.     public double offsetFromTAI(final AbsoluteDate date) {
  136.         final int offsetIndex = findOffsetIndex(date);
  137.         if (offsetIndex < 0) {
  138.             // the date is before the first known leap
  139.             return 0;
  140.         } else {
  141.             return -offsets[offsetIndex].getOffset(date);
  142.         }
  143.     }

  144.     /** {@inheritDoc} */
  145.     @Override
  146.     public <T extends CalculusFieldElement<T>> T offsetFromTAI(final FieldAbsoluteDate<T> date) {
  147.         final int offsetIndex = findOffsetIndex(date.toAbsoluteDate());
  148.         if (offsetIndex < 0) {
  149.             // the date is before the first known leap
  150.             return date.getField().getZero();
  151.         } else {
  152.             return offsets[offsetIndex].getOffset(date).negate();
  153.         }
  154.     }

  155.     /** {@inheritDoc} */
  156.     @Override
  157.     public double offsetToTAI(final DateComponents date,
  158.                               final TimeComponents time) {

  159.         // take offset from local time into account, but ignoring seconds,
  160.         // so when we parse an hour like 23:59:60.5 during leap seconds introduction,
  161.         // we do not jump to next day
  162.         final int minuteInDay = time.getHour() * 60 + time.getMinute() - time.getMinutesFromUTC();
  163.         final int correction  = minuteInDay < 0 ? (minuteInDay - 1439) / 1440 : minuteInDay / 1440;

  164.         // find close neighbors, assuming date in TAI, i.e a date earlier than real UTC date
  165.         final int mjd = date.getMJD() + correction;
  166.         final UTCTAIOffset offset = findOffset(mjd);
  167.         if (offset == null) {
  168.             // the date is before the first known leap
  169.             return 0;
  170.         } else {
  171.             return offset.getOffset(date, time);
  172.         }

  173.     }

  174.     /** {@inheritDoc} */
  175.     public String getName() {
  176.         return "UTC";
  177.     }

  178.     /** {@inheritDoc} */
  179.     public String toString() {
  180.         return getName();
  181.     }

  182.     /** Get the date of the first known leap second.
  183.      * @return date of the first known leap second
  184.      */
  185.     public AbsoluteDate getFirstKnownLeapSecond() {
  186.         return offsets[0].getDate();
  187.     }

  188.     /** Get the date of the last known leap second.
  189.      * @return date of the last known leap second
  190.      */
  191.     public AbsoluteDate getLastKnownLeapSecond() {
  192.         return offsets[offsets.length - 1].getDate();
  193.     }

  194.     /** {@inheritDoc} */
  195.     @Override
  196.     public boolean insideLeap(final AbsoluteDate date) {
  197.         final int offsetIndex = findOffsetIndex(date);
  198.         if (offsetIndex < 0) {
  199.             // the date is before the first known leap
  200.             return false;
  201.         } else {
  202.             return date.compareTo(offsets[offsetIndex].getValidityStart()) < 0;
  203.         }
  204.     }

  205.     /** {@inheritDoc} */
  206.     @Override
  207.     public <T extends CalculusFieldElement<T>> boolean insideLeap(final FieldAbsoluteDate<T> date) {
  208.         return insideLeap(date.toAbsoluteDate());
  209.     }

  210.     /** {@inheritDoc} */
  211.     @Override
  212.     public int minuteDuration(final AbsoluteDate date) {
  213.         final int offsetIndex = findOffsetIndex(date);
  214.         final UTCTAIOffset offset;
  215.         if (offsetIndex >= 0 &&
  216.                 date.compareTo(offsets[offsetIndex].getValidityStart()) < 0) {
  217.             // the date is during the leap itself
  218.             offset = offsets[offsetIndex];
  219.         } else if (offsetIndex + 1 < offsets.length &&
  220.             offsets[offsetIndex + 1].getDate().durationFrom(date) <= 60.0) {
  221.             // the date is after a leap, but it may be just before the next one
  222.             // the next leap will start in one minute, it will extend the current minute
  223.             offset = offsets[offsetIndex + 1];
  224.         } else {
  225.             offset = null;
  226.         }
  227.         if (offset != null) {
  228.             // since this method returns an int we can't return the precise duration in
  229.             // all cases, but we can bound it. Some leaps are more than 1s. See #694
  230.             return 60 + (int) FastMath.ceil(offset.getLeap());
  231.         }
  232.         // no leap is expected within the next minute
  233.         return 60;
  234.     }

  235.     /** {@inheritDoc} */
  236.     @Override
  237.     public <T extends CalculusFieldElement<T>> int minuteDuration(final FieldAbsoluteDate<T> date) {
  238.         return minuteDuration(date.toAbsoluteDate());
  239.     }

  240.     /** {@inheritDoc} */
  241.     @Override
  242.     public double getLeap(final AbsoluteDate date) {
  243.         final int offsetIndex = findOffsetIndex(date);
  244.         if (offsetIndex < 0) {
  245.             // the date is before the first known leap
  246.             return 0;
  247.         } else {
  248.             return offsets[offsetIndex].getLeap();
  249.         }
  250.     }

  251.     /** {@inheritDoc} */
  252.     @Override
  253.     public <T extends CalculusFieldElement<T>> T getLeap(final FieldAbsoluteDate<T> date) {
  254.         return date.getField().getZero().add(getLeap(date.toAbsoluteDate()));
  255.     }

  256.     /** Find the index of the offset valid at some date.
  257.      * @param date date at which offset is requested
  258.      * @return index of the offset valid at this date, or -1 if date is before first offset.
  259.      */
  260.     private int findOffsetIndex(final AbsoluteDate date) {
  261.         int inf = 0;
  262.         int sup = offsets.length;
  263.         while (sup - inf > 1) {
  264.             final int middle = (inf + sup) >>> 1;
  265.             if (date.compareTo(offsets[middle].getDate()) < 0) {
  266.                 sup = middle;
  267.             } else {
  268.                 inf = middle;
  269.             }
  270.         }
  271.         if (sup == offsets.length) {
  272.             // the date is after the last known leap second
  273.             return offsets.length - 1;
  274.         } else if (date.compareTo(offsets[inf].getDate()) < 0) {
  275.             // the date is before the first known leap
  276.             return -1;
  277.         } else {
  278.             return inf;
  279.         }
  280.     }

  281.     /** Find the offset valid at some date.
  282.      * @param mjd Modified Julian Day of the date at which offset is requested
  283.      * @return offset valid at this date, or null if date is before first offset.
  284.      */
  285.     private UTCTAIOffset findOffset(final int mjd) {
  286.         int inf = 0;
  287.         int sup = offsets.length;
  288.         while (sup - inf > 1) {
  289.             final int middle = (inf + sup) >>> 1;
  290.             if (mjd < offsets[middle].getMJD()) {
  291.                 sup = middle;
  292.             } else {
  293.                 inf = middle;
  294.             }
  295.         }
  296.         if (sup == offsets.length) {
  297.             // the date is after the last known leap second
  298.             return offsets[offsets.length - 1];
  299.         } else if (mjd < offsets[inf].getMJD()) {
  300.             // the date is before the first known leap
  301.             return null;
  302.         } else {
  303.             return offsets[inf];
  304.         }
  305.     }

  306.     /** Replace the instance with a data transfer object for serialization.
  307.      * @return data transfer object that will be serialized
  308.      */
  309.     @DefaultDataContext
  310.     private Object writeReplace() {
  311.         return new DataTransferObject();
  312.     }

  313.     /** Internal class used only for serialization. */
  314.     @DefaultDataContext
  315.     private static class DataTransferObject implements Serializable {

  316.         /** Serializable UID. */
  317.         private static final long serialVersionUID = 20131209L;

  318.         /** Replace the deserialized data transfer object with a {@link UTCScale}.
  319.          * @return replacement {@link UTCScale}
  320.          */
  321.         private Object readResolve() {
  322.             try {
  323.                 return DataContext.getDefault().getTimeScales().getUTC();
  324.             } catch (OrekitException oe) {
  325.                 throw new OrekitInternalError(oe);
  326.             }
  327.         }

  328.     }

  329. }