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.time;
18  
19  import java.io.Serializable;
20  import java.util.ArrayList;
21  import java.util.List;
22  
23  import org.orekit.errors.OrekitException;
24  import org.orekit.errors.OrekitInternalError;
25  import org.orekit.errors.TimeStampedCacheException;
26  import org.orekit.utils.Constants;
27  import org.orekit.utils.ImmutableTimeStampedCache;
28  import org.orekit.utils.TimeStampedCache;
29  
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 the {@link TimeScalesFactory} class,
43   * so there is no public constructor.</p>
44   * @author Luc Maisonobe
45   * @see AbsoluteDate
46   */
47  public class UTCScale implements TimeScale {
48  
49      /** Serializable UID. */
50      private static final long serialVersionUID = 20150402L;
51  
52      /** Time steps. */
53      private transient TimeStampedCache<UTCTAIOffset> cache;
54  
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 offsets UTC-TAI offsets
60       * @exception OrekitException if cache cannot be set up
61       */
62      UTCScale(final List<OffsetModel> offsets) throws OrekitException {
63  
64          // create cache
65          final List<UTCTAIOffset> data = new ArrayList<UTCTAIOffset>(offsets.size());
66  
67          if (offsets.get(0).getStart().getYear() > 1968) {
68              // the pre-1972 linear offsets are missing, add them manually
69              // excerpt from UTC-TAI.history file:
70              //  1961  Jan.  1 - 1961  Aug.  1     1.422 818 0s + (MJD - 37 300) x 0.001 296s
71              //        Aug.  1 - 1962  Jan.  1     1.372 818 0s +        ""
72              //  1962  Jan.  1 - 1963  Nov.  1     1.845 858 0s + (MJD - 37 665) x 0.001 123 2s
73              //  1963  Nov.  1 - 1964  Jan.  1     1.945 858 0s +        ""
74              //  1964  Jan.  1 -       April 1     3.240 130 0s + (MJD - 38 761) x 0.001 296s
75              //        April 1 -       Sept. 1     3.340 130 0s +        ""
76              //        Sept. 1 - 1965  Jan.  1     3.440 130 0s +        ""
77              //  1965  Jan.  1 -       March 1     3.540 130 0s +        ""
78              //        March 1 -       Jul.  1     3.640 130 0s +        ""
79              //        Jul.  1 -       Sept. 1     3.740 130 0s +        ""
80              //        Sept. 1 - 1966  Jan.  1     3.840 130 0s +        ""
81              //  1966  Jan.  1 - 1968  Feb.  1     4.313 170 0s + (MJD - 39 126) x 0.002 592s
82              //  1968  Feb.  1 - 1972  Jan.  1     4.213 170 0s +        ""
83              offsets.add( 0, new OffsetModel(new DateComponents(1961,  1, 1), 37300, 1.4228180, 0.0012960));
84              offsets.add( 1, new OffsetModel(new DateComponents(1961,  8, 1), 37300, 1.3728180, 0.0012960));
85              offsets.add( 2, new OffsetModel(new DateComponents(1962,  1, 1), 37665, 1.8458580, 0.0011232));
86              offsets.add( 3, new OffsetModel(new DateComponents(1963, 11, 1), 37665, 1.9458580, 0.0011232));
87              offsets.add( 4, new OffsetModel(new DateComponents(1964,  1, 1), 38761, 3.2401300, 0.0012960));
88              offsets.add( 5, new OffsetModel(new DateComponents(1964,  4, 1), 38761, 3.3401300, 0.0012960));
89              offsets.add( 6, new OffsetModel(new DateComponents(1964,  9, 1), 38761, 3.4401300, 0.0012960));
90              offsets.add( 7, new OffsetModel(new DateComponents(1965,  1, 1), 38761, 3.5401300, 0.0012960));
91              offsets.add( 8, new OffsetModel(new DateComponents(1965,  3, 1), 38761, 3.6401300, 0.0012960));
92              offsets.add( 9, new OffsetModel(new DateComponents(1965,  7, 1), 38761, 3.7401300, 0.0012960));
93              offsets.add(10, new OffsetModel(new DateComponents(1965,  9, 1), 38761, 3.8401300, 0.0012960));
94              offsets.add(11, new OffsetModel(new DateComponents(1966,  1, 1), 39126, 4.3131700, 0.0025920));
95              offsets.add(12, new OffsetModel(new DateComponents(1968,  2, 1), 39126, 4.2131700, 0.0025920));
96          }
97  
98          UTCTAIOffset previous = null;
99  
100         // link the offsets together
101         final TimeScale tai = TimeScalesFactory.getTAI();
102         for (final OffsetModel o : offsets) {
103 
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 
109             // start of the leap
110             final double previousOffset    = (previous == null) ? 0.0 : previous.getOffset(date, TimeComponents.H00);
111             final AbsoluteDate leapStart   = new AbsoluteDate(date, tai).shiftedBy(previousOffset);
112 
113             // end of the leap
114             final double startOffset       = offset + slope * (date.getMJD() - mjdRef);
115             final AbsoluteDate leapEnd     = new AbsoluteDate(date, tai).shiftedBy(startOffset);
116 
117             // leap computed at leap start and in UTC scale
118             final double normalizedSlope   = slope / Constants.JULIAN_DAY;
119             final double leap              = leapEnd.durationFrom(leapStart) / (1 + normalizedSlope);
120 
121             previous = new UTCTAIOffset(leapStart, date.getMJD(), leap, offset, mjdRef, normalizedSlope);
122             data.add(previous);
123 
124         }
125 
126         cache = new ImmutableTimeStampedCache<UTCTAIOffset>(2, data);
127 
128     }
129 
130     /** {@inheritDoc} */
131     public double offsetFromTAI(final AbsoluteDate date) {
132         if (cache.getEarliest().getDate().compareTo(date) > 0) {
133             // the date is before the first known leap
134             return 0;
135         } else if (cache.getLatest().getDate().compareTo(date) < 0) {
136             // the date is after the last known leap
137             return -cache.getLatest().getOffset(date);
138         } else {
139             // the date is nominally bracketed by two leaps
140             try {
141                 return -cache.getNeighbors(date).get(0).getOffset(date);
142             } catch (TimeStampedCacheException tce) {
143                 // this should never happen as boundaries have been handled in the previous statements
144                 throw new OrekitInternalError(tce);
145             }
146         }
147     }
148 
149     /** {@inheritDoc} */
150     public double offsetToTAI(final DateComponents date,
151                               final TimeComponents time) {
152 
153         if (cache.getEarliest().getMJD() > date.getMJD()) {
154             // the date is before the first known leap
155             return 0;
156         } else if (cache.getLatest().getMJD() <= date.getMJD()) {
157             // the date is after the last known leap
158             return cache.getLatest().getOffset(date, time);
159         } else {
160             // the date is nominally bracketed by two leaps
161             try {
162                 // find close neighbors, assuming date in TAI, i.e a date earlier than real UTC date
163                 final List<UTCTAIOffset> neighbors =
164                         cache.getNeighbors(new AbsoluteDate(date, time, TimeScalesFactory.getTAI()));
165                 if (neighbors.get(1).getMJD() <= date.getMJD()) {
166                     // the date is in fact just after a leap second!
167                     return neighbors.get(1).getOffset(date, time);
168                 } else {
169                     return neighbors.get(0).getOffset(date, time);
170                 }
171             } catch (TimeStampedCacheException tce) {
172                 // this should never happen as boundaries have been handled in the previous statements
173                 throw new OrekitInternalError(tce);
174             }
175         }
176 
177     }
178 
179     /** {@inheritDoc} */
180     public String getName() {
181         return "UTC";
182     }
183 
184     /** {@inheritDoc} */
185     public String toString() {
186         return getName();
187     }
188 
189     /** Get the date of the first known leap second.
190      * @return date of the first known leap second
191      */
192     public AbsoluteDate getFirstKnownLeapSecond() {
193         return cache.getEarliest().getDate();
194     }
195 
196     /** Get the date of the last known leap second.
197      * @return date of the last known leap second
198      */
199     public AbsoluteDate getLastKnownLeapSecond() {
200         return cache.getLatest().getDate();
201     }
202 
203     /** Check if date is within a leap second introduction.
204      * @param date date to check
205      * @return true if time is within a leap second introduction
206      */
207     public boolean insideLeap(final AbsoluteDate date) {
208         if (cache.getEarliest().getDate().compareTo(date) > 0) {
209             // the date is before the first known leap
210             return false;
211         } else if (cache.getLatest().getDate().compareTo(date) < 0) {
212             // the date is after the last known leap
213             return date.compareTo(cache.getLatest().getValidityStart()) < 0;
214         } else {
215             // the date is nominally bracketed by two leaps
216             try {
217                 return date.compareTo(cache.getNeighbors(date).get(0).getValidityStart()) < 0;
218             } catch (TimeStampedCacheException tce) {
219                 // this should never happen as boundaries have been handled in the previous statements
220                 throw new OrekitInternalError(tce);
221             }
222         }
223     }
224 
225     /** Get the value of the previous leap.
226      * @param date date to check
227      * @return value of the previous leap
228      */
229     public double getLeap(final AbsoluteDate date) {
230         if (cache.getEarliest().getDate().compareTo(date) > 0) {
231             return 0;
232         } else if (cache.getLatest().getDate().compareTo(date) < 0) {
233             // the date is after the last known leap
234             return cache.getLatest().getLeap();
235         } else {
236             // the date is nominally bracketed by two leaps
237             try {
238                 return cache.getNeighbors(date).get(0).getLeap();
239             } catch (TimeStampedCacheException tce) {
240                 // this should never happen as boundaries have been handled in the previous statements
241                 throw new OrekitInternalError(tce);
242             }
243         }
244     }
245 
246     /** Replace the instance with a data transfer object for serialization.
247      * <p>
248      * This intermediate class serializes only the frame key.
249      * </p>
250      * @return data transfer object that will be serialized
251      */
252     private Object writeReplace() {
253         return new DataTransferObject();
254     }
255 
256     /** Internal class used only for serialization. */
257     private static class DataTransferObject implements Serializable {
258 
259         /** Serializable UID. */
260         private static final long serialVersionUID = 20131209L;
261 
262         /** Replace the deserialized data transfer object with a {@link UTCScale}.
263          * @return replacement {@link UTCScale}
264          */
265         private Object readResolve() {
266             try {
267                 return TimeScalesFactory.getUTC();
268             } catch (OrekitException oe) {
269                 throw new OrekitInternalError(oe);
270             }
271         }
272 
273     }
274 
275 }