Debian Codegraph @

gavo/rscdef/rmkfuncs.py

raw
1 """
2 Functions available to rowmaker procs.
3
4 Rowmaker procs are compiled in the namespace defined by this module.
5 """
6
7 #c Copyright 2008-2025, the GAVO project <[email protected]>
8 #c
9 #c This program is free software, covered by the GNU GPL. See the
10 #c COPYING file in the source distribution.
11
12
13 import base64
14 import datetime
15 import linecache
16 import math
17 import os
18 import pprint #noflake: exported name
19 import re #noflake: exported name
20 import sys #noflake: exported name
21 import time
22 import traceback #noflake: exported name
23 import urllib.request, urllib.parse, urllib.error #noflake: exported name
24
25 import numpy #noflake: exported name
26
27 from gavo import base
28 from gavo import stc
29 from gavo import utils
30 from gavo.base import ( #noflake: exported names
31 coords, parseBooleanLiteral, parseInt, sqlmunge,
32 makeSitePath, makeAbsoluteURL, SkipThis)
33 from gavo.base.literals import (identity, #noflake:exported names
34 parseInt, parseFloat, parseBooleanLiteral, parseUnicode,
35 parseDefaultDate, parseDefaultDatetime, parseDefaultTime, parseCooPair,
36 parseSPoint, getDefaultValueParsers, originalOrIdentity, parseBytes,
37 parseJSON)
38
39 from gavo.base.unitconv import ( #noflake: exported names
40 PLANCK_H, LIGHT_C, BOLTZMANN_K)
41 from gavo.rscdef.common import ( #noflake: exported names
42 getStandardPubDID, getAccrefFromStandardPubDID,
43 getDatalinkMetaLink,
44 getInputsRelativePath)
45 from gavo.stc import parseSimpleSTCS #noflake: exported name
46 from gavo.stc.times import ( #noflake: exported names
47 dateTimeToJdn, dateTimeToMJD, dateTimeToJYear,
48 bYearToDateTime, jdnToDateTime, mjdToDateTime, TTtoTAI, TAItoTT,
49 JD_MJD)
50 from gavo.utils import codetricks
51 from gavo.utils import ( #noflake: exported names
52 dmsToDeg, hmsToDeg, degToDms, degToHms, hoursToHms, makeIAUId,
53 DEG, parseISODT, iterSimpleText, getFileStem,
54 getWCSAxis, getRelativePath, loadPythonModule)
55 from gavo.utils import pgsphere #noflake: exported names
56
57
58 # degrees per mas
59 DEG_MAS = 1/3600000.
60 # degrees per arcsec
61 DEG_ARCSEC = 1/3600.
62
63 NaN = float('nan')
64
65 MS = base.makeStruct
66
67
68 class IgnoreThisRow(base.ExecutiveAction):
69 """can be raised by user code to indicate that a row should be
70 skipped when building a table.
71
72 Note: To skip an entire source, raise SkipThis (usually in a rowfilter
73 or so).
74
75 Also note that the non-code way to skip things, `Triggers`_, is
76 preferred when you don't already use code.
77 """
78
79
80 def addCartesian(result, alpha, delta):
81 """inserts c_x, c_y, and c_z for the equatorial position alpha, delta
82 into result.
83
84 c_x, c_y, and c_z are the cartesian coordinates of the intersection
85 point of the radius vector of alpha, delta with the unit sphere.
86
87 alpha and delta already have to be floats, so you probably want
88 to use variables here.
89
90 >>> r = {}; addCartesian(r, 25, 30); "%.7f %.7f"%(r["c_x"], r["c_y"])
91 '0.7848856 0.3659982'
92 """
93 result["c_x"], result["c_y"], result["c_z"] = utils.spherToCart(
94 alpha*DEG, delta*DEG)
95
96
97 def combinePMs(result, pma, pmd):
98 """inserts pm_total (in degs/yr) and pm_posang (in degs, east over north)
99 into result.
100
101 pma and pmd have to be in degs/yr, with cos(delta) applied to pma.
102 """
103 if pma is None or pmd is None:
104 tpm = pmpa = None
105 else:
106 tpm = math.sqrt(pma**2+pmd**2)
107 pmpa = math.atan2(pma, pmd)*360/2/math.pi
108 result["pm_total"] = tpm
109 result["pm_posang"] = pmpa
110
111
112 @utils.document
113 def getQueryMeta():
114 """returns a query meta object from somewhere up the stack.
115
116 This is for row makers running within a service. This can be used
117 to, e.g., enforce match limits by writing getQueryMeta()["dbLimit"].
118 """
119 return codetricks.stealVar("queryMeta")
120
121 @utils.document
122 def parseTime(literal, format="%H:%M:%S"):
123 """returns a ``datetime.timedelta`` object for literal parsed according
124 to format.
125
126 For format, you can the magic values ``!!secondsSinceMidnight``,
127 ``!!decimalHours`` or a strptime-like spec using the H, M, and S codes.
128
129 >>> parseTime("89930", "!!secondsSinceMidnight")
130 datetime.timedelta(days=1, seconds=3530)
131 >>> parseTime("23.4", "!!decimalHours")
132 datetime.timedelta(seconds=84240)
133 >>> parseTime("3.4:5", "%H.%M:%S")
134 datetime.timedelta(seconds=11045)
135 >>> parseTime("20:04", "%H:%M")
136 datetime.timedelta(seconds=72240)
137 """
138 if format=="!!secondsSinceMidnight":
139 return datetime.timedelta(seconds=float(literal))
140 elif format=="!!decimalHours":
141 return datetime.timedelta(hours=float(literal))
142 else:
143 # We can't really use prebuilt strptimes since times like 25:21:22.445
144 # are perfectly ok in astronomy.
145 partDict = utils.parsePercentExpression(literal, format)
146 return datetime.timedelta(0, hours=float(partDict.get("H", 0)),
147 minutes=float(partDict.get("M", 0)), seconds=float(partDict.get("S", 0)))
148
149
150 @utils.document
151 def parseDate(literal, format="%Y-%m-%d"):
152 """returns a ``datetime.date`` object of literal parsed according to the
153 strptime-similar format.
154
155 The function understands the special ``dateFormat`` ``!!jYear``
156 (stuff like 1980.89).
157 """
158 if format in ("!!julianEp", "!!jYear"):
159 return stc.jYearToDateTime(float(literal))
160 return datetime.datetime(*time.strptime(literal, format)[:3])
161
162
163 @utils.document
164 def parseTimestamp(literal, format="%Y-%m-%dT%H:%M:%S"):
165 """returns a ``datetime.datetime`` object from a literal parsed according
166 to the strptime-similar format.
167
168 A ``ValueError`` is raised if literal doesn't match format (actually,
169 a parse with essentially DALI-standard ISO representation is always tried)
170 """
171 try:
172 return datetime.datetime(*time.strptime(literal, format)[:6])
173 except ValueError:
174 # always try ISO format
175 return parseISODT(literal)
176
177
178 @utils.document
179 def toMJD(literal):
180 """returns a modified julian date made from some datetime representation.
181
182 Valid representations include:
183
184 * MJD (a float smaller than 1e6)
185 * JD (a float larger than 1e6)
186 * datetime.datetime instances
187 * ISO time strings.
188 """
189 if literal is None:
190 return None
191 elif isinstance(literal, str):
192 return stc.dateTimeToMJD(parseTimestamp(literal))
193 elif isinstance(literal, datetime.datetime):
194 return stc.dateTimeToMJD(literal)
195 elif literal>1e6:
196 return literal-stc.JD_MJD
197 else:
198 return literal
199
200
201 @utils.document
202 def makeTimestamp(date, time):
203 """makes a datetime instance from a date and a time.
204 """
205 return datetime.datetime(date.year, date.month, date.day)+time
206
207
208 @utils.document
209 def parseAngle(literal, format, sepChar=None):
210 """converts the various forms angles might be encountered to degrees.
211
212 format is one of hms, dms, fracHour. For sexagesimal/time angles,
213 you can pass a sepChar (default: split at blanks) that lets you
214 specify what separates hours/degrees, minutes, and seconds.
215
216 >>> "%.8f"%(parseAngle("23 59 59.95", "hms"))
217 '359.99979167'
218 >>> "%10.5f"%parseAngle("-20:31:05.12", "dms", sepChar=":")
219 ' -20.51809'
220 >>> "%010.6f"%parseAngle("21.0209556", "fracHour")
221 '315.314334'
222 """
223 if format=="dms":
224 return utils.dmsToDeg(literal, sepChar=sepChar)
225 elif format=="hms":
226 return utils.hmsToDeg(literal, sepChar=sepChar)
227 elif format=="fracHour":
228 return utils.fracHoursToDeg(literal)
229 else:
230 raise base.Error("Invalid format: %s"%format)
231
232
233 @utils.document
234 def computeMean(val1, val2):
235 """returns the mean value between two values.
236
237 Beware: Integer division done here for the benefit of datetime calculations.
238
239 >>> computeMean(1.,3)
240 2.0
241 >>> computeMean(datetime.datetime(2000, 10, 13),
242 ... datetime.datetime(2000, 10, 12))
243 datetime.datetime(2000, 10, 12, 12, 0)
244 """
245 return val1+(val2-val1)/2
246
247
248 @utils.document
249 def killBlanks(literal):
250 """returns the string literal with all blanks removed.
251
252 This is useful when numbers are formatted with blanks thrown in.
253
254 Nones are passed through.
255 """
256 if literal is None:
257 return None
258 else:
259 return literal.replace(" ", "")
260
261
262 @utils.document
263 def lastSourceElements(path, numElements):
264 """returns a path made up from the last ``numElements`` items in ``path``.
265 """
266 newPath = []
267 for i in range(int(numElements)):
268 path, part = os.path.split(path)
269 newPath.append(part)
270 newPath.reverse()
271 return os.path.join(*newPath)
272
273
274 @utils.document
275 def scale(val, factor, offset=0):
276 """returns val*factor+offset if val is not None, None otherwise.
277
278 This is when you want to manipulate a numeric value that may be NULL.
279 It is a somewhat safer alternative to using nullExcs with scaled values.
280 """
281 if val is None:
282 return None
283 return factor*val+offset
284
285
286 @utils.document
287 def parseWithNull(literal, baseParser, nullLiteral=base.Undefined,
288 default=None, checker=None):
289 """returns default if literal is ``nullLiteral``, else
290 ``baseParser(literal)``.
291
292 If ``checker`` is non-None, it must be a callable returning ``True`` if its
293 argument is a null value.
294
295 ``nullLiteral`` is compared against the unprocessed literal (usually, a
296 string). The intended use is like this (but note that often, a
297 ``nullExcs`` attribute on a rowmaker ``map`` element is the more
298 elegant way:
299
300 >>> parseWithNull("8888.0", float, "8888")
301 8888.0
302 >>> print(parseWithNull("8888", float, "8888"))
303 None
304 >>> print(parseWithNull("N/A", int, "N/A"))
305 None
306 """
307 if (nullLiteral is not base.Undefined and literal==nullLiteral
308 ) or literal is None:
309 return default
310 if checker is not None:
311 if checker(literal):
312 return default
313 res = baseParser(literal)
314 if res is None:
315 return default
316 return res
317
318
319 @utils.document
320 def requireValue(val, fieldName):
321 """returns ``val`` unless it is ``None``, in which case a ``ValidationError``
322 for ``fieldName`` will be raised.
323 """
324 if val is None:
325 raise base.ValidationError("Value is required but was not provided",
326 fieldName)
327 return val
328
329
330 def genLimitKeys(inputKey):
331 """yields _MAX and _MIN inputKeys from a single input key.
332
333 This also tries to sensibly fix descriptions and ucds.
334 This is mainly for datalink metaMakers; condDescs may use a
335 similar thing, but that's not exposed to RDs.
336
337 Don't use this function any more. It will go away soon.
338 """
339 name = inputKey.name
340 ucd = inputKey.ucd or None
341 description = inputKey.description
342 base.ui.notifyWarning("Deprecated genLimitKeys function used."
343 " Fix your RD to use proper DALI-intervals (ask dachs-support"
344 " if you don't know what to do.)")
345
346 yield inputKey.change(name=name+"_MIN",
347 ucd=ucd and "par.min;"+ucd,
348 description=description.rstrip(".")+", lower limit")
349 yield inputKey.change(name=name+"_MAX",
350 ucd=ucd and "par.max;"+ucd,
351 description=description.rstrip(".")+", upper limit")
352
353
354 @utils.document
355 def getFlatName(accref):
356 """returns a unix-compatible file name for an access reference.
357
358 The file name will not contain terrible characters, let alone
359 slashes. This is used to, e.g., keep all previews in one directory.
360 """
361 # just in case someone passes in a full file path, strip it
362 if accref.startswith("/"):
363 accref = utils.getRelativePath(accref,
364 base.getConfig("inputsDir"), liberalChars=True)
365
366 return base64.b64encode(accref.encode("utf-8"), b"$!").decode("ascii")
367
368
369 def addProcDefObject(name, func):
370 globals()[name] = func
371
372
373 def makeProc(funcName, code, setupCode, parent, srcPos, **moreNames):
374 """compiles a function in the rmkfunc's namespace.
375
376 code is a complete function source. setupCode is executed right away
377 in this namespace to add globals.
378 """
379 funcNs = globals().copy()
380 funcNs["parent"] = parent
381 funcNs.update(moreNames)
382 if setupCode.strip():
383 src = setupCode.rstrip()
384 try:
385 uniqueName = "<setup code in {}>".format(srcPos)
386 compiled = compile(src, uniqueName, 'exec')
387 linecache.cache[uniqueName] = (
388 len(src), None, src.split("\n"), uniqueName)
389 exec(compiled, funcNs)
390 except (SyntaxError, TypeError) as ex:
391 raise base.ui.logOldExc(
392 base.BadCode(setupCode, "setup code", ex,
393 pos=srcPos))
394 except NameError as ex:
395 raise base.ui.logOldExc(
396 base.BadCode(setupCode, "setup code", ex,
397 hint="This typically happens when you forget to put"
398 " quotes around string values.",
399 pos=srcPos))
400
401 uniqueName = None
402 if parent and getattr(parent, "name_", None):
403 uniqueName = "<{} at {}>".format(parent.name_, srcPos)
404 return utils.compileFunction(
405 code.rstrip(),
406 funcName,
407 funcNs,
408 debug=base.DEBUG,
409 uniqueName=uniqueName)
410
411
412 def _test(): # pragma: no cover
413 import doctest
414 doctest.testmod()
415
416
417 if __name__=="__main__":
418 _test()