Debian Codegraph @

gavo/rscdef/coverage.py

raw
1 """
2 The coverage RD element.
3
4 Most code to obtain coverage information from actual resources is in
5 gavo.user.info.
6 """
7
8 #c Copyright 2008-2025, the GAVO project <[email protected]>
9 #c
10 #c This program is free software, covered by the GNU GPL. See the
11 #c COPYING file in the source distribution.
12
13 import re
14
15 from gavo import base
16 from gavo import stc
17 from gavo import utils
18 from gavo.rscdef import rdinj
19 from gavo.utils import pgsphere
20
21 class FloatInterval(base.AtomicAttribute):
22 """An attribute keeping a floating-point attribute.
23
24 The literal of these is as in VOTable: a whitespace-separated pair
25 for decimal floating-point literals.
26 """
27 typeDesc_ = "A float interval (i.e., a space-separated pair of floats)"
28
29 def parse(self, value):
30 try:
31 lower, upper = [float(f) for f in value.split()]
32 if lower>upper:
33 raise base.LiteralParseError(self.name_, value,
34 hint="In intervals, the lower value must be smaller or equal"
35 " to the upper one.")
36 return lower, upper
37 except (ValueError, TypeError):
38 raise base.LiteralParseError(self.name_, value,
39 hint="Intervals are represented as two floating-point literals"
40 " separated by whitespace.")
41
42 def unparse(self, value):
43 return "%.10g %.10g"%value
44
45
46 class FloatOrDateInterval(FloatInterval):
47 """An attribute keeping a temporal interval as MJD.
48
49 On literal input, we also allow ISO-like timestamps. You cannot
50 mix MJD and ISO, though.
51 """
52 typeDesc_ = "A float or ISO timestamp interval (values separated by space)"
53 def parse(self, value):
54 try:
55 return FloatInterval.parse(self, value)
56 except base.LiteralParseError:
57 try:
58 lower, upper = [stc.dateTimeToMJD(utils.parseISODT(f))
59 for f in value.split()]
60 if lower>upper:
61 raise base.LiteralParseError(self.name_, value,
62 hint="In intervals, the lower value must be smaller or equal"
63 " to the upper one.")
64 return lower, upper
65 except (ValueError, TypeError):
66 raise base.LiteralParseError(self.name_, value,
67 hint="Time intervals are represented as two floating-point or"
68 " ISO timestamp literals separated by whitespace.")
69
70
71 class SpectralInterval(FloatInterval):
72 """An attribute giving the spectral coverage.
73
74 On input, you can add unit tags in square brackets (``21[cm]``).
75 Without a unit, this is in Joules of energy.
76 """
77 typeDesc_ = ("A pair of floats with optional units in square brackets;"
78 " unitless is Joule. Lower/higher will be autoswapped.")
79
80 def _parseSingle(self, value):
81 mat = re.match(rf"\s*({utils.floatRE})\s*\[([^]]+)\]\s*$", value)
82 if not mat:
83 raise ValueError(f"{value} isn't val[unit]")
84
85 rawVal = float(mat.group(1))
86 return eval(base.getSpecExpr(mat.group(2), "J").format(rawVal))
87
88 def parse(self, value):
89 try:
90 low, high = FloatInterval.parse(self, value)
91 except base.LiteralParseError:
92 try:
93 lowS, highS = value.split()
94 low = self._parseSingle(lowS)
95 high = self._parseSingle(highS)
96 except Exception as ex:
97 raise base.LiteralParseError(self.name_, value,
98 hint="This is a pair of float/spectral unit in square brackets each"
99 f" ({ex})")
100 return min(low, high), max(low, high)
101
102
103 class Ranges(base.ListOfAtomsAttribute):
104 """An attribute definition for a list of intervals.
105 """
106 typeDesc_ = "A sequence of intervals (a space-separated pair of floats)"
107
108 def __init__(self, name, intervalAttr, default=[], **kwargs):
109 base.ListOfAtomsAttribute.__init__(
110 self, name, default, intervalAttr, **kwargs)
111
112 def feedFromArray(self, instance, arr):
113 """defines the intervals from a flat array by constructing
114 each interval from consecuive pairs.
115 """
116 self.feedObject(instance,
117 list(zip(arr[0::2], arr[1::2])))
118
119
120 class Updater(base.Structure):
121 """Information on where and how to update a piece of coverage information.
122 """
123 name_ = "updater"
124
125 # this stuff is interpreted by user.limits.iterCoverageItems
126 _sourceTable = base.ReferenceAttribute("sourceTable",
127 default=base.NotGiven,
128 description="A table from which to compute coverage by default.",
129 copyable=True)
130 _spaceTable = base.ReferenceAttribute("spaceTable",
131 default=base.NotGiven,
132 description="A table from which to compute spatial coverage (overrides"
133 " sourceTable).",
134 copyable=True)
135 _timeTable = base.ReferenceAttribute("timeTable",
136 default=base.NotGiven,
137 description="A table from which to compute temporal coverage (overrides"
138 " sourceTable)",
139 copyable=True)
140 _spectralTable = base.ReferenceAttribute("spectralTable",
141 default=base.NotGiven,
142 description="A table from which to compute spectral coverage (overrides"
143 " sourceTable)",
144 copyable=True)
145 _mocOrder = base.IntAttribute("mocOrder",
146 default=6,
147 description="Maximal HEALpix order to use in coverage MOCs (6 is about"
148 " a degree resolution, each additional point doubles resolution).",
149 copyable=True)
150
151
152 class Coverage(base.Structure):
153 """The coverage of a resource.
154
155 For now, this is attached to the complete resource rather than the table,
156 since this is where it sits in VOResource. DaCHS *could* be a bit
157 more flexible, allowing different coverages per publish element. It
158 is not right now, though.
159
160 Note: Technically, this will introduce or amend the coverage meta
161 element. The information given here will be masked if you define
162 a coverage meta on the service or table level. Just do not do that.
163 """
164 name_ = "coverage"
165
166 _updater = base.StructAttribute("updater",
167 childFactory=Updater,
168 description="Rules for automatic computation or updating of"
169 " coverage information.",
170 default=base.NotGiven)
171 _spectral = Ranges("spectral",
172 SpectralInterval(
173 "spectral", description="A wavelength interval"),
174 description="Interval(s) of spectral coverage, in Joules of"
175 " BARYCENTER vacuum messenger particle energy; add '[unit]' to"
176 " specify in other units (wavelength, frequency, and energy in VOUnit"
177 " are supported).")
178 _temporal = Ranges("temporal",
179 FloatOrDateInterval(
180 "temporal", description="A time interval"),
181 description="Interval(s) of temporal coverage, in MJD"
182 " (for TT BARYCENTER).")
183 _spatial = base.UnicodeAttribute("spatial",
184 default=base.NotGiven,
185 description="A MOC in ASCII representation giving the ICRS coverage"
186 " of the resource",
187 expand=True)
188 _fallbackTo = base.UnicodeAttribute("fallbackTo",
189 default=base.NotGiven,
190 description="Take coverage information from this RD in case"
191 " none is given locally. It is not an error if no such"
192 " coverage information exists either. Use this when a service"
193 " re-exposes data from another RD, as in sitewide siap2 and obscore,"
194 " so you only have to compute the coverage once.",
195 copyable=True)
196
197 def expand(self, value):
198 return self.parent.expand(value)
199
200 def completeElement(self, ctx):
201 super().completeElement(ctx)
202
203 fallbackRecords = {}
204 if self.fallbackTo:
205 with base.getTableConn() as conn:
206 try:
207 fallbackRecords = rdinj._getRecordsFor(
208 self.fallbackTo, "dc.rdmeta", conn)[0]
209 except IndexError:
210 # no coverage from fallbackTo, either; keep the empty dict.
211 pass
212
213 if self.spatial is base.NotGiven:
214 inj = ctx.getInjected("spatial_coverage",
215 fallbackRecords.get("spatial"))
216 if inj:
217 self.feed("spatial", inj)
218
219 if not self.spectral:
220 inj = ctx.getInjected("spectral_coverage",
221 fallbackRecords.get("spectral"))
222 if inj:
223 self._spectral.feedFromArray(self, inj)
224
225 if not self.temporal:
226 inj = ctx.getInjected("temporal_coverage",
227 fallbackRecords.get("temporal"))
228 if inj:
229 self._temporal.feedFromArray(self, inj)
230
231 if self.spatial is base.NotGiven:
232 self.parsedMOC = None
233 else:
234 self.parsedMOC = pgsphere.SMoc.fromASCII(self.spatial)
235
236 def onParentComplete(self):
237 if self.spatial is not base.NotGiven:
238 self.parent.addMeta("coverage.spatial", self.spatial)
239
240 for interval in self.temporal:
241 self.parent.addMeta("coverage.temporal",
242 self._temporal.itemAttD.unparse(interval))
243
244 for interval in self.spectral:
245 self.parent.addMeta("coverage.spectral",
246 self._spectral.itemAttD.unparse(interval))