UTCScale.java

  1. /* Copyright 2002-2024 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.errors.OrekitException;
  27. import org.orekit.errors.OrekitInternalError;
  28. import org.orekit.utils.Constants;

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

  47.     /** Serializable UID. */
  48.     private static final long serialVersionUID = 20230302L;

  49.     /** International Atomic Scale. */
  50.     private final TimeScale tai;

  51.     /** base UTC-TAI offsets (may lack the pre-1975 offsets). */
  52.     private final Collection<? extends OffsetModel> baseOffsets;

  53.     /** UTC-TAI offsets. */
  54.     private final UTCTAIOffset[] offsets;

  55.     /** Package private constructor for the factory.
  56.      * Used to create the prototype instance of this class that is used to
  57.      * clone all subsequent instances of {@link UTCScale}. Initializes the offset
  58.      * table that is shared among all instances.
  59.      * @param tai TAI time scale this UTC time scale references.
  60.      * @param baseOffsets UTC-TAI base offsets (may lack the pre-1975 offsets)
  61.      */
  62.     UTCScale(final TimeScale tai, final Collection<? extends OffsetModel> baseOffsets) {

  63.         this.tai         = tai;
  64.         this.baseOffsets = baseOffsets;

  65.         // copy input so the original list is unmodified
  66.         final List<OffsetModel> offsetModels = new ArrayList<>(baseOffsets);
  67.         offsetModels.sort(Comparator.comparing(OffsetModel::getStart));
  68.         if (offsetModels.get(0).getStart().getYear() > 1968) {
  69.             // the pre-1972 linear offsets are missing, add them manually
  70.             // excerpt from UTC-TAI.history file:
  71.             //  1961  Jan.  1 - 1961  Aug.  1     1.422 818 0s + (MJD - 37 300) x 0.001 296s
  72.             //        Aug.  1 - 1962  Jan.  1     1.372 818 0s +        ""
  73.             //  1962  Jan.  1 - 1963  Nov.  1     1.845 858 0s + (MJD - 37 665) x 0.001 123 2s
  74.             //  1963  Nov.  1 - 1964  Jan.  1     1.945 858 0s +        ""
  75.             //  1964  Jan.  1 -       April 1     3.240 130 0s + (MJD - 38 761) x 0.001 296s
  76.             //        April 1 -       Sept. 1     3.340 130 0s +        ""
  77.             //        Sept. 1 - 1965  Jan.  1     3.440 130 0s +        ""
  78.             //  1965  Jan.  1 -       March 1     3.540 130 0s +        ""
  79.             //        March 1 -       Jul.  1     3.640 130 0s +        ""
  80.             //        Jul.  1 -       Sept. 1     3.740 130 0s +        ""
  81.             //        Sept. 1 - 1966  Jan.  1     3.840 130 0s +        ""
  82.             //  1966  Jan.  1 - 1968  Feb.  1     4.313 170 0s + (MJD - 39 126) x 0.002 592s
  83.             //  1968  Feb.  1 - 1972  Jan.  1     4.213 170 0s +        ""
  84.             offsetModels.add( 0, new OffsetModel(new DateComponents(1961,  1, 1), 37300, 1.4228180, 0.0012960));
  85.             offsetModels.add( 1, new OffsetModel(new DateComponents(1961,  8, 1), 37300, 1.3728180, 0.0012960));
  86.             offsetModels.add( 2, new OffsetModel(new DateComponents(1962,  1, 1), 37665, 1.8458580, 0.0011232));
  87.             offsetModels.add( 3, new OffsetModel(new DateComponents(1963, 11, 1), 37665, 1.9458580, 0.0011232));
  88.             offsetModels.add( 4, new OffsetModel(new DateComponents(1964,  1, 1), 38761, 3.2401300, 0.0012960));
  89.             offsetModels.add( 5, new OffsetModel(new DateComponents(1964,  4, 1), 38761, 3.3401300, 0.0012960));
  90.             offsetModels.add( 6, new OffsetModel(new DateComponents(1964,  9, 1), 38761, 3.4401300, 0.0012960));
  91.             offsetModels.add( 7, new OffsetModel(new DateComponents(1965,  1, 1), 38761, 3.5401300, 0.0012960));
  92.             offsetModels.add( 8, new OffsetModel(new DateComponents(1965,  3, 1), 38761, 3.6401300, 0.0012960));
  93.             offsetModels.add( 9, new OffsetModel(new DateComponents(1965,  7, 1), 38761, 3.7401300, 0.0012960));
  94.             offsetModels.add(10, new OffsetModel(new DateComponents(1965,  9, 1), 38761, 3.8401300, 0.0012960));
  95.             offsetModels.add(11, new OffsetModel(new DateComponents(1966,  1, 1), 39126, 4.3131700, 0.0025920));
  96.             offsetModels.add(12, new OffsetModel(new DateComponents(1968,  2, 1), 39126, 4.2131700, 0.0025920));
  97.         }

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

  100.         UTCTAIOffset previous = null;

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

  103.             final OffsetModel    o      = offsetModels.get(i);
  104.             final DateComponents date   = o.getStart();
  105.             final int            mjdRef = o.getMJDRef();
  106.             final double         offset = o.getOffset();
  107.             final double         slope  = o.getSlope();

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

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

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

  117.             final AbsoluteDate reference = AbsoluteDate.createMJDDate(mjdRef, 0, tai)
  118.                     .shiftedBy(offset);
  119.             previous = new UTCTAIOffset(leapStart, date.getMJD(), leap, offset, mjdRef,
  120.                     normalizedSlope, reference);
  121.             this.offsets[i] = previous;

  122.         }

  123.     }

  124.     /** Get the base offsets.
  125.      * @return base offsets (may lack the pre-1975 offsets)
  126.      * @since 12.0
  127.      */
  128.     public Collection<? extends OffsetModel> getBaseOffsets() {
  129.         return baseOffsets;
  130.     }

  131.     /**
  132.      * Returns the UTC-TAI offsets underlying this UTC scale.
  133.      * <p>
  134.      * Modifications to the returned list will not affect this UTC scale instance.
  135.      * @return new non-null modifiable list of UTC-TAI offsets time-sorted from
  136.      *         earliest to latest
  137.      */
  138.     public List<UTCTAIOffset> getUTCTAIOffsets() {
  139.         final List<UTCTAIOffset> offsetList = new ArrayList<>(offsets.length);
  140.         for (int i = 0; i < offsets.length; ++i) {
  141.             offsetList.add(offsets[i]);
  142.         }
  143.         return offsetList;
  144.     }

  145.     /** {@inheritDoc} */
  146.     @Override
  147.     public double offsetFromTAI(final AbsoluteDate date) {
  148.         final int offsetIndex = findOffsetIndex(date);
  149.         if (offsetIndex < 0) {
  150.             // the date is before the first known leap
  151.             return 0;
  152.         } else {
  153.             return -offsets[offsetIndex].getOffset(date);
  154.         }
  155.     }

  156.     /** {@inheritDoc} */
  157.     @Override
  158.     public <T extends CalculusFieldElement<T>> T offsetFromTAI(final FieldAbsoluteDate<T> date) {
  159.         final int offsetIndex = findOffsetIndex(date.toAbsoluteDate());
  160.         if (offsetIndex < 0) {
  161.             // the date is before the first known leap
  162.             return date.getField().getZero();
  163.         } else {
  164.             return offsets[offsetIndex].getOffset(date).negate();
  165.         }
  166.     }

  167.     /** {@inheritDoc} */
  168.     @Override
  169.     public double offsetToTAI(final DateComponents date,
  170.                               final TimeComponents time) {

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

  176.         // find close neighbors, assuming date in TAI, i.e a date earlier than real UTC date
  177.         final int mjd = date.getMJD() + correction;
  178.         final UTCTAIOffset offset = findOffset(mjd);
  179.         if (offset == null) {
  180.             // the date is before the first known leap
  181.             return 0;
  182.         } else {
  183.             return offset.getOffset(date, time);
  184.         }

  185.     }

  186.     /** {@inheritDoc} */
  187.     public String getName() {
  188.         return "UTC";
  189.     }

  190.     /** {@inheritDoc} */
  191.     public String toString() {
  192.         return getName();
  193.     }

  194.     /** Get the date of the first known leap second.
  195.      * @return date of the first known leap second
  196.      */
  197.     public AbsoluteDate getFirstKnownLeapSecond() {
  198.         return offsets[0].getDate();
  199.     }

  200.     /** Get the date of the last known leap second.
  201.      * @return date of the last known leap second
  202.      */
  203.     public AbsoluteDate getLastKnownLeapSecond() {
  204.         return offsets[offsets.length - 1].getDate();
  205.     }

  206.     /** {@inheritDoc} */
  207.     @Override
  208.     public boolean insideLeap(final AbsoluteDate date) {
  209.         final int offsetIndex = findOffsetIndex(date);
  210.         if (offsetIndex < 0) {
  211.             // the date is before the first known leap
  212.             return false;
  213.         } else {
  214.             return date.compareTo(offsets[offsetIndex].getValidityStart()) < 0;
  215.         }
  216.     }

  217.     /** {@inheritDoc} */
  218.     @Override
  219.     public <T extends CalculusFieldElement<T>> boolean insideLeap(final FieldAbsoluteDate<T> date) {
  220.         return insideLeap(date.toAbsoluteDate());
  221.     }

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

  247.     /** {@inheritDoc} */
  248.     @Override
  249.     public <T extends CalculusFieldElement<T>> int minuteDuration(final FieldAbsoluteDate<T> date) {
  250.         return minuteDuration(date.toAbsoluteDate());
  251.     }

  252.     /** {@inheritDoc} */
  253.     @Override
  254.     public double getLeap(final AbsoluteDate date) {
  255.         final int offsetIndex = findOffsetIndex(date);
  256.         if (offsetIndex < 0) {
  257.             // the date is before the first known leap
  258.             return 0;
  259.         } else {
  260.             return offsets[offsetIndex].getLeap();
  261.         }
  262.     }

  263.     /** {@inheritDoc} */
  264.     @Override
  265.     public <T extends CalculusFieldElement<T>> T getLeap(final FieldAbsoluteDate<T> date) {
  266.         return date.getField().getZero().add(getLeap(date.toAbsoluteDate()));
  267.     }

  268.     /** Find the index of the offset valid at some date.
  269.      * @param date date at which offset is requested
  270.      * @return index of the offset valid at this date, or -1 if date is before first offset.
  271.      */
  272.     private int findOffsetIndex(final AbsoluteDate date) {
  273.         int inf = 0;
  274.         int sup = offsets.length;
  275.         while (sup - inf > 1) {
  276.             final int middle = (inf + sup) >>> 1;
  277.             if (date.compareTo(offsets[middle].getDate()) < 0) {
  278.                 sup = middle;
  279.             } else {
  280.                 inf = middle;
  281.             }
  282.         }
  283.         if (sup == offsets.length) {
  284.             // the date is after the last known leap second
  285.             return offsets.length - 1;
  286.         } else if (date.compareTo(offsets[inf].getDate()) < 0) {
  287.             // the date is before the first known leap
  288.             return -1;
  289.         } else {
  290.             return inf;
  291.         }
  292.     }

  293.     /** Find the offset valid at some date.
  294.      * @param mjd Modified Julian Day of the date at which offset is requested
  295.      * @return offset valid at this date, or null if date is before first offset.
  296.      */
  297.     private UTCTAIOffset findOffset(final int mjd) {
  298.         int inf = 0;
  299.         int sup = offsets.length;
  300.         while (sup - inf > 1) {
  301.             final int middle = (inf + sup) >>> 1;
  302.             if (mjd < offsets[middle].getMJD()) {
  303.                 sup = middle;
  304.             } else {
  305.                 inf = middle;
  306.             }
  307.         }
  308.         if (sup == offsets.length) {
  309.             // the date is after the last known leap second
  310.             return offsets[offsets.length - 1];
  311.         } else if (mjd < offsets[inf].getMJD()) {
  312.             // the date is before the first known leap
  313.             return null;
  314.         } else {
  315.             return offsets[inf];
  316.         }
  317.     }

  318.     /** Replace the instance with a data transfer object for serialization.
  319.      * @return data transfer object that will be serialized
  320.      */
  321.     @DefaultDataContext
  322.     private Object writeReplace() {
  323.         return new DataTransferObject(tai, baseOffsets);
  324.     }

  325.     /** Internal class used only for serialization. */
  326.     @DefaultDataContext
  327.     private static class DataTransferObject implements Serializable {

  328.         /** Serializable UID. */
  329.         private static final long serialVersionUID = 20230302L;

  330.         /** International Atomic Scale. */
  331.         private final TimeScale tai;

  332.         /** base UTC-TAI offsets (may lack the pre-1975 offsets). */
  333.         private final Collection<? extends OffsetModel> baseOffsets;

  334.         /** Simple constructor.
  335.          * @param tai TAI time scale this UTC time scale references.
  336.          * @param baseOffsets UTC-TAI base offsets (may lack the pre-1975 offsets)
  337.          */
  338.         DataTransferObject(final TimeScale tai, final Collection<? extends OffsetModel> baseOffsets) {
  339.             this.tai         = tai;
  340.             this.baseOffsets = baseOffsets;
  341.         }

  342.         /** Replace the deserialized data transfer object with a {@link UTCScale}.
  343.          * @return replacement {@link UTCScale}
  344.          */
  345.         private Object readResolve() {
  346.             try {
  347.                 return new UTCScale(tai, baseOffsets);
  348.             } catch (OrekitException oe) {
  349.                 throw new OrekitInternalError(oe);
  350.             }
  351.         }

  352.     }

  353. }