Debian Codegraph @

gavo/stc/times.py

raw
1 """
2 Helpers for time parsing and conversion.
3 """
4
5 #c Copyright 2008-2025, the GAVO project <[email protected]>
6 #c
7 #c This program is free software, covered by the GNU GPL. See the
8 #c COPYING file in the source distribution.
9
10
11 import bisect
12 import datetime
13 import math
14
15 from gavo import utils
16 from gavo.stc import common
17
18
19 JD_MJD = 2400000.5
20
21 def parseISODT(value):
22 try:
23 return utils.parseISODT(value)
24 except ValueError as ex:
25 raise common.STCLiteralError(str(ex), value)
26
27
28 @utils.document
29 def jdnToJYear(jd):
30 """returns a julian year from a julian day number.
31 """
32 return (jd-2451545.0)/365.25+2000.0
33
34
35 @utils.document
36 def jdnToDateTime(jd):
37 """returns a ``datetime.datetime`` instance for a julian day number.
38 """
39 return jYearToDateTime(jdnToJYear(jd))
40
41
42 @utils.document
43 def mjdToDateTime(mjd):
44 """returns a ``datetime.datetime`` instance for a modified julian day number.
45
46 Beware: This loses a couple of significant digits due to transformation
47 to jd.
48 """
49 return jdnToDateTime(mjd+JD_MJD)
50
51
52 @utils.document
53 def bYearToDateTime(bYear):
54 """returns a datetime.datetime instance for a fractional Besselian year.
55
56 This uses the formula given by Lieske, J.H., A&A 73, 282 (1979).
57 """
58 jdn = (bYear-1900.0)*common.tropicalYear+2415020.31352
59 return jdnToDateTime(jdn)
60
61
62 @utils.document
63 def jYearToDateTime(jYear):
64 """returns a datetime.datetime instance for a fractional (julian) year.
65
66 This refers to time specifications like J2001.32.
67 """
68 return datetime.datetime(2000, 1, 1, 12)+datetime.timedelta(
69 days=(jYear-2000.0)*365.25)
70
71
72 dtJ2000 = jYearToDateTime(2000.0)
73 dtB1950 = bYearToDateTime(1950.0)
74
75 @utils.document
76 def dateTimeToJdn(dt):
77 """returns a julian day number (including fractionals) from a datetime
78 instance.
79 """
80 a = (14-dt.month)//12
81 y = dt.year+4800-a
82 m = dt.month+12*a-3
83 jdn = dt.day+(153*m+2)//5+365*y+y//4-y//100+y//400-32045
84 try:
85 secsOnDay = dt.hour*3600+dt.minute*60+dt.second+dt.microsecond/1e6
86 except AttributeError:
87 secsOnDay = 0
88 return jdn+(secsOnDay-43200)/86400.
89
90 @utils.document
91 def dateTimeToMJD(dt):
92 """returns a modified julian date for a datetime instance.
93 """
94 return dateTimeToJdn(dt)-JD_MJD
95
96 def dateTimeToBYear(dt):
97 return (dateTimeToJdn(dt)-2415020.31352)/common.tropicalYear+1900.0
98
99
100 @utils.document
101 def dateTimeToJYear(dt):
102 """returns a fractional (julian) year for a datetime.datetime instance.
103 """
104 return (dateTimeToJdn(dt)-2451545)/365.25+2000
105
106
107 def getSeconds(td):
108 """returns the number of seconds corresponding to a timedelta object.
109 """
110 return td.days*86400+td.seconds+td.microseconds*1e-6
111
112
113 ############ Time scale conversions
114 # All these convert to/from TT.
115
116 _TDTminusTAI = datetime.timedelta(seconds=32.184)
117
118 @utils.document
119 def TTtoTAI(tdt):
120 """returns TAI for a (datetime.datetime) TDT.
121 """
122 return tdt+_TDTminusTAI
123
124 @utils.document
125 def TAItoTT(tai):
126 """returns TDT for a (datetime.datetime) TAI.
127 """
128 return tai-_TDTminusTAI
129
130
131 def _getTDBOffset(tdb):
132 """returns the TDB-TDT according to [EXS] 2.222-1.
133 """
134 g = (357.53+0.9856003*(dateTimeToJdn(tdb)-2451545.0))/180*math.pi
135 return datetime.timedelta(0.001658*math.sin(g)+0.000014*math.sin(2*g))
136
137 def TDBtoTT(tdb):
138 """returns an approximate TT from a TDB.
139
140 The simplified formula 2.222-1 from [EXS] is used.
141 """
142 return tdb-_getTDBOffset(tdb)
143
144 def TTtoTDB(tt):
145 """returns approximate TDB from TT.
146
147 The simplified formula 2.222-1 from [EXS] is used.
148 """
149 return tt+_getTDBOffset(tt)
150
151
152 _L_G = 6.969291e-10 # [EXS], p. 47
153
154 def _getTCGminusTT(dt): # [EXS], 2.223-5
155 return datetime.timedelta(seconds=
156 _L_G*(dateTimeToJdn(dt)-2443144.5)*86400)
157
158 def TTtoTCG(tt):
159 """returns TT from TCG.
160
161 This uses 2.223-5 from [EXS].
162 """
163 return tt+_getTCGminusTT(tt)
164
165 def TCGtoTT(tcg):
166 """returns TT from TCG.
167
168 This uses 2.223-5 from [EXS].
169 """
170 return tcg+_getTCGminusTT(tcg)
171
172
173 _L_B = 1.550505e-8
174
175 def _getTCBminusTDB(dt): # [EXS], 2.223-2
176 return datetime.timedelta(
177 seconds=_L_B*(dateTimeToJdn(dt)-2443144.5)*86400)
178
179 def TCBtoTT(tcb):
180 """returns an approximate TCB from a TT.
181
182 This uses [EXS] 2.223-2 and the approximate conversion from TDB to TT.
183 """
184 return TDBtoTT(tcb+_getTCBminusTDB(tcb))
185
186 def TTtoTCB(tt):
187 """returns an approximate TT from a TCB.
188
189 This uses [EXS] 2.223-2 and the approximate conversion from TT to TDB.
190 """
191 return TTtoTDB(tt)-_getTCBminusTDB(tt)
192
193
194 def _makeLeapSecondTable():
195 lsTable = []
196 for lsCount, lsMoment in enumerate([ # from Lenny tzinfo
197 datetime.datetime(1971, 12, 31, 23, 59, 59),
198 datetime.datetime(1972, 0o6, 30, 23, 59, 59),
199 datetime.datetime(1972, 12, 31, 23, 59, 59),
200 datetime.datetime(1973, 12, 31, 23, 59, 59),
201 datetime.datetime(1974, 12, 31, 23, 59, 59),
202 datetime.datetime(1975, 12, 31, 23, 59, 59),
203 datetime.datetime(1976, 12, 31, 23, 59, 59),
204 datetime.datetime(1977, 12, 31, 23, 59, 59),
205 datetime.datetime(1978, 12, 31, 23, 59, 59),
206 datetime.datetime(1979, 12, 31, 23, 59, 59),
207 datetime.datetime(1981, 0o6, 30, 23, 59, 59),
208 datetime.datetime(1982, 0o6, 30, 23, 59, 59),
209 datetime.datetime(1983, 0o6, 30, 23, 59, 59),
210 datetime.datetime(1985, 0o6, 30, 23, 59, 59),
211 datetime.datetime(1987, 12, 31, 23, 59, 59),
212 datetime.datetime(1989, 12, 31, 23, 59, 59),
213 datetime.datetime(1990, 12, 31, 23, 59, 59),
214 datetime.datetime(1992, 0o6, 30, 23, 59, 59),
215 datetime.datetime(1993, 0o6, 30, 23, 59, 59),
216 datetime.datetime(1994, 0o6, 30, 23, 59, 59),
217 datetime.datetime(1995, 12, 31, 23, 59, 59),
218 datetime.datetime(1997, 0o6, 30, 23, 59, 59),
219 datetime.datetime(1998, 12, 31, 23, 59, 59),
220 datetime.datetime(2005, 12, 31, 23, 59, 59),
221 datetime.datetime(2008, 12, 31, 23, 59, 59),
222 ]):
223 lsTable.append((lsMoment, datetime.timedelta(seconds=lsCount+10)))
224 return lsTable
225
226 # A table of TAI-UTC, indexed by UTC
227 leapSecondTable = _makeLeapSecondTable()
228 del _makeLeapSecondTable
229 _sentinelTD = datetime.timedelta(seconds=0)
230
231 def getLeapSeconds(dt, table=leapSecondTable):
232 """returns TAI-UTC for the datetime dt.
233 """
234 ind = bisect.bisect_left(leapSecondTable, (dt, _sentinelTD))
235 if ind==0:
236 return datetime.timedelta(seconds=9.)
237 return table[ind-1][1]
238
239
240 def UTCtoTT(utc):
241 """returns TT from UTC.
242
243 The leap second table is complete through 2009-5.
244
245 >>> getLeapSeconds(datetime.datetime(1998,12,31,23,59,58))
246 datetime.timedelta(seconds=31)
247 >>> TTtoTAI(UTCtoTT(datetime.datetime(1998,12,31,23,59,59)))
248 datetime.datetime(1999, 1, 1, 0, 0, 30)
249 >>> TTtoTAI(UTCtoTT(datetime.datetime(1999,1,1,0,0,0)))
250 datetime.datetime(1999, 1, 1, 0, 0, 32)
251 """
252 return TAItoTT(utc+getLeapSeconds(utc))
253
254
255 # A table of TAI-UTC, indexed by TT
256 ttLeapSecondTable = [(UTCtoTT(t), dt)
257 for t, dt in leapSecondTable]
258
259
260 def TTtoUTC(tt):
261 """returns UTC from TT.
262
263 The leap second table is complete through 2009-5.
264
265 >>> TTtoUTC(UTCtoTT(datetime.datetime(1998,12,31,23,59,59)))
266 datetime.datetime(1998, 12, 31, 23, 59, 59)
267 >>> TTtoUTC(UTCtoTT(datetime.datetime(1999,1,1,0,0,0)))
268 datetime.datetime(1999, 1, 1, 0, 0)
269 """
270 # XXX TODO: leap seconds need to be computed from UTC, so this will
271 # be one second off in the immediate vicinity of a leap second.
272 return TTtoTAI(tt)-getLeapSeconds(tt, ttLeapSecondTable)
273
274
275 # A dict mapping timescales to conversions to/from TT.
276 timeConversions = {
277 "UTC": (UTCtoTT, TTtoUTC),
278 "TCB": (TCBtoTT, TTtoTCB),
279 "TCG": (TCGtoTT, TTtoTCG),
280 "TDB": (TDBtoTT, TTtoTDB),
281 "TAI": (TAItoTT, TTtoTAI),
282 "TT": (utils.identity, utils.identity),
283 }
284
285
286 def getTransformFromScales(fromScale, toScale):
287 if not fromScale or not toScale:
288 return utils.identity
289
290 try:
291 toTT = timeConversions[fromScale][0]
292 toTarget = timeConversions[toScale][1]
293 except KeyError as key:
294 raise common.STCValueError("Unknown timescale for transform: %s"%key)
295
296 def transform(val):
297 return toTarget(toTT(val))
298
299 return transform
300
301
302 def getTransformFromSTC(fromSTC, toSTC):
303 fromScale, toScale = fromSTC.time.frame.timeScale, toSTC.time.frame.timeScale
304 if fromScale!=toSTC and toSTC is not None:
305 return getTransformFromScales(fromScale, toScale)
306
307
308 @ utils.document
309 def isMJD(col):
310 """returns True if the rscdef.Column instance col likely contains MJD values.
311
312 This has a long and winding history in DaCHS, and so this is a disaster
313 of heuristics.
314 """
315 if col.unit!="d":
316 return False
317
318 # classic DaCHS: have a name with mjd in it
319 if "mjd" in col.name:
320 return True
321
322 # SIAP: a stupid uype
323 if col.ucd and "MJD" in col.ucd.upper():
324 return True
325
326 # xtype abuse: just here for backward compatibility; this is pain because
327 # something else will have to kill the xtype.
328 if col.xtype=="mjd":
329 return True
330
331 # the current recommended way to declare MJD: use an appropriate time0
332 # in a votable:Coords annotation
333 for role in col.dmRoles:
334 # resolve weakref
335 ann = role()
336 if ann.name!="location":
337 # it's not the annotation of a time part of votable:Coords
338 continue
339 try:
340 time0 = ann.instance()["time"]["frame"]["time0"]
341 if time0=="MJD-origin":
342 return True
343 elif time0=="JD-origin":
344 return False
345 else:
346 return float(time0)==JD_MJD
347 except KeyError:
348 # no proper frame annotation in this role; keep on trying
349 pass
350
351 # I could inspect column statistics (JD 50000 would be extremely unlikely),
352 # but there's an overdose of heuristics here as is.
353 return False
354
355
356 def datetimeMapperFactory(colDesc):
357 import time
358 # TODO: take a long, hard look at this. I *think* essentially all of
359 # this should be replaced by displayHint-s, if only because neither
360 # timestamp nor date should have a unit. However, this stuff is executed.
361 # We need to work out where...
362 if (colDesc["dbtype"]=="timestamp"
363 or colDesc["dbtype"]=="date"
364 # must look in original, as the one in colDesc comes from typesystems
365 or colDesc.original.xtype=="adql:TIMESTAMP" # legacy, delete ~2020
366 or colDesc.original.xtype=="timestamp"):
367 unit = colDesc["unit"]
368 if (colDesc["displayHint"].get("format")=="humanDate"
369 or colDesc.original.xtype=="adql:TIMESTAMP" # legacy, delete ~2020
370 or colDesc.original.xtype=="timestamp"):
371 fun = lambda val: (val and val.isoformat()) or None
372 destType = ("char", "*")
373 colDesc["nullvalue"] = ""
374
375 elif (colDesc["ucd"] and "MJD" in colDesc["ucd"].upper()
376 or colDesc["xtype"]=="mjd"
377 or "mjd" in colDesc["name"]):
378 colDesc["unit"] = "d"
379 fun = lambda val: (val and dateTimeToMJD(val))
380 destType = ("double", '1')
381 colDesc["nullvalue"] = "NaN"
382 colDesc["xtype"] = None
383
384 elif unit=="yr" or unit=="a":
385 def fun(val):
386 return (val and dateTimeToJYear(val))
387 destType = ("double", '1')
388 colDesc["nullvalue"] = "NaN"
389 colDesc["xtype"] = None
390
391 elif unit=="d":
392 fun = lambda val: (val and dateTimeToJdn(val))
393 destType = ("double", '1')
394 colDesc["nullvalue"] = "NaN"
395 colDesc["xtype"] = None
396
397 elif unit=="s":
398 fun = lambda val: (val and time.mktime(val.timetuple()))
399 destType = ("double", '1')
400 colDesc["nullvalue"] = "NaN"
401 colDesc["xtype"] = None
402
403 else:
404 # default for datetime column: serialise to timestamp
405 fun = lambda val: (val and val.isoformat()) or None
406 destType = ("char", "*")
407 colDesc["nullvalue"] = ""
408 colDesc["xtype"] = "timestamp"
409
410 colDesc["datatype"], colDesc["arraysize"] = destType
411 return fun
412 utils.registerDefaultMF(datetimeMapperFactory)
413
414
415 def _test():
416 import doctest
417 doctest.testmod()
418
419 if __name__=="__main__":
420 _test()