Debian Codegraph @

gavo/dm/common.py

raw
1 """
2 Common code for new-style Data Model support.
3
4 In particular, this defines a hierarchy of Annotation objects. The annotation
5 of DaCHS tables is an ObjectAnnotation, the other Annotation classes
6 (conceptually, all are key-value pairs) make up their inner structure.
7 """
8
9 #c Copyright 2008-2025, the GAVO project <[email protected]>
10 #c
11 #c This program is free software, covered by the GNU GPL. See the
12 #c COPYING file in the source distribution.
13
14
15 import contextlib
16 import re
17 import weakref
18
19 from gavo import utils
20 from gavo import votable
21 from gavo.votable import V
22
23
24 VODML_NAME = "vo-dml"
25
26
27 @contextlib.contextmanager
28 def containerTypeSet(ctx, typeName):
29 """a context manager to control the type currently serialised in a VOTable.
30
31 ctx is a VOTable serialisation context (that we liberally hack into).
32 """
33 if not hasattr(ctx, "_dml_typestack"):
34 ctx._dml_typestack = []
35 ctx._dml_typestack.append(typeName)
36 try:
37 yield
38 finally:
39 ctx._dml_typestack.pop()
40
41
42 def completeVODMLId(ctx, roleName):
43 """completes roleName to a full (standard) vo-dml id.
44
45 This is based on what the containerTypeSet context manager leaves
46 in the VOTable serialisation context ctx.
47 """
48 return roleName
49
50 # current spec wants hierarchical strings here. Let's not.
51 if ":" in roleName:
52 # we allow the use of fully qualified role names and don't touch them
53 return roleName
54 return "%s.%s"%(ctx._dml_typestack[-1], roleName)
55
56
57 def parseTypeName(typename):
58 """returns modelname, package (None for the empty package), name
59 for a VO-DML type name.
60
61 Malformed names raise a ValueError.
62
63 >>> parseTypeName("dm:type")
64 ('dm', None, 'type')
65 >>> parseTypeName("dm:pck.type")
66 ('dm', 'pck', 'type')
67 >>> parseTypeName(":malformed.typeid")
68 Traceback (most recent call last):
69 ValueError: ':malformed.typeid' is not a valid VO-DML type name
70 """
71 mat = re.match(r"([\w_-]+):(?:([\w_-]+)\.)?([\w_-]+)", typename)
72 if not mat:
73 raise ValueError("'%s' is not a valid VO-DML type name"%typename)
74 return mat.groups()
75
76
77 class AnnotationBase(object):
78 """A base class for of structs.
79
80 Basically, these are pairs of a role name and something else, which
81 depends on the actual subclass (e.g., an atomic value, a reference,
82 a sequence of key-value pairs, a sequence of other objects, ...).
83
84 They have a method getVOT(ctx, instance) -> xmlstan, which, using a
85 votablewrite.Context ctx, will return mapping-document conformant VOTable
86 xmlstan; instance is the rsc/rscdef structure the annotation is produced
87 for.
88
89 Use asSIL() to retrieve a simple string representation.
90
91 Compound annotations (sequences, key-value pairs) should use
92 add(thing) to build themselves up.
93
94 AnnotationBase is abstract and doesn't implement some of these methods.
95 """
96 def __init__(self, name, instance):
97 self.name = name
98 if instance is None: # should only be true for the root
99 self.instance = instance
100 else:
101 self.instance = weakref.ref(instance)
102
103 def getVOT(self, ctx, instance):
104 raise NotImplementedError("%s cannot be serialised (override getVOT)."%
105 self.__class__.__name__)
106
107 def asSIL(self):
108 raise NotImplementedError("%s cannot be serialised (override asSIL)."%
109 self.__class__.__name__)
110
111 def add(self, thing):
112 raise ValueError(
113 "%s is not a compound annotation."%self.__class__.__name__)
114
115 def iterNodes(self):
116 yield self
117
118
119 class TableRelativeAnnotation(AnnotationBase):
120 """A base class for annotations that must be adapted or discarded when
121 an annotation is copied.
122 """
123 # This currently is only used as a sentinel for such annotations.
124 # Perhaps we should modify copy here?
125
126
127 class AtomicAnnotation(AnnotationBase):
128 """An annotation of an atomic value, i.e., a key-value pair.
129
130 These can take optional metadata.
131 """
132 def __init__(self, name=None, value=None, unit=None,
133 ucd=None, instance=None):
134 AnnotationBase.__init__(self, name, instance)
135 self.value, self.unit, self.ucd = value, unit, ucd
136
137 def copy(self, newInstance):
138 return self.__class__(
139 self.name, self.value, self.unit, self.ucd,
140 newInstance)
141
142 def getVOT(self, ctx, instance):
143 # if we have additional metadata, serialise this using a param
144 if self.unit or self.ucd:
145 attrs = votable.guessParamAttrsForValue(self.value)
146 attrs.update({
147 "unit": self.unit,
148 "ucd": self.ucd})
149
150 param = V.PARAM(name=self.name,
151 id=ctx.getOrMakeIdFor(self.value),
152 dmrole=completeVODMLId(ctx, self.name),
153 **attrs)
154 ctx.getEnclosingContainer()[
155 votable.serializeToParam(param, self.value)]
156 ctx.curDMAttr(ref=param.id)
157 return None
158
159 else:
160 # no additional metadata, just dump a literal string
161 # (technically, we should use ivoa: types. Oh, bother, another
162 # type system, just what we need).
163 ctx.curDMAttr(
164 dmtype="ivoa:string",
165 value=utils.safe_str(self.value))
166 return None
167
168
169 def asSIL(self, suppressType=False):
170 if suppressType:
171 return self.value.asSIL()
172 else:
173 return "%s: %s"%(self.name, self.value.asSIL())
174
175
176 class _WithMapCopyMixin(object):
177 """A mixin furnishing a class with a copyWithAnnotationMap method.
178
179 The class mixing this in must provide an iterator iterChildRoles
180 yielding child annotations one by one.
181
182 Every compound annotation must mix this in in order to provide
183 halfway sane copying semantics when columns get re-mixed in new
184 tables (which we do all the time).
185
186 We also expect a method copyEmpty(i) that returns an instance of the
187 Annotation but without any child annotations.
188
189 In return, this will furnish a copy(i) method based on copyEmpty
190 and iterChildRoles.
191 """
192 def copyWithAnnotationMap(self, annotationMap, container, instance):
193 """returns a copy of this annotation, with annotations mentioned
194 in annotationMap replaced.
195
196 Table-related annotations (currently, Param- and ColumnAnnotations)
197 not mentioned in annotationMap) will be discarded.
198
199 This is used when annotation tables with columns copied from
200 other tables. annotationMap, normally generated by
201 dmrd.SynthesizedRoles, then maps the old annotations to the elements
202 that should be annotated in the new table.
203 """
204 copy = self.copyEmpty(instance)
205 if instance is None: # I'm the new root
206 instance = copy
207
208 for role in self.iterChildRoles():
209
210 if role in annotationMap:
211 copy.add(
212 annotationMap[role].getAnnotation(
213 role.name, container, instance))
214
215 elif isinstance(role, TableRelativeAnnotation):
216 pass
217
218 elif hasattr(role, "copyWithAnnotationMap"):
219 copy.add(role.copyWithAnnotationMap(
220 annotationMap, container, instance))
221
222 else:
223 copy.add(role.copy(instance))
224
225 return copy
226
227 def copy(self, newInstance):
228 return self.copyWithAnnotationMap({}, None, newInstance)
229
230
231 class _AttributeGroupAnnotation(AnnotationBase, _WithMapCopyMixin):
232 """An internal base class for DatatypeAnnotation and ObjectAnnotation.
233 """
234 def __init__(self, name, type, instance):
235 AnnotationBase.__init__(self, name, instance)
236 self.type = type
237 if self.type is None:
238 # TODO: infer from parent? from DM?
239 self.modelPrefix = getattr(instance, "modelPrefix", "undefined")
240 else:
241 self.modelPrefix, _, _ = parseTypeName(self.type)
242
243 self.childRoles = {}
244
245 def __getitem__(self, key):
246 child = self.childRoles.__getitem__(key)
247 if isinstance(child, AtomicAnnotation):
248 return child.value
249 else:
250 return child
251
252 def get(self, key, default=None):
253 if key not in self:
254 return default
255 return self[key]
256
257 def __contains__(self, key):
258 return key in self.childRoles
259
260 def copyEmpty(self, newInstance):
261 return self.__class__(self.name, self.type, newInstance)
262
263 def iterChildRoles(self):
264 return iter(self.childRoles.values())
265
266 def add(self, role):
267 assert role.name not in self.childRoles
268 self.childRoles[role.name] = role
269
270 def asSIL(self, suppressType=False):
271 if suppressType or self.type is None:
272 typeAnn = ""
273 else:
274 typeAnn = "(%s) "%self.type
275
276 return "%s{\n %s}\n"%(typeAnn,
277 "\n ".join(r.asSIL() for r in list(self.childRoles.values())))
278
279 def getVOT(self, ctx, instance):
280 """inserts this annotation into a VOTable.
281
282 ctx is the votable serialisation context, instance is the annotated
283 DaCHS object.
284 """
285 ctx.addVODMLPrefix(self.modelPrefix)
286 ctx.groupIdsInTree.add(id(self))
287 res = V.INSTANCE(
288 dmtype=self.type,
289 ID=ctx.getOrMakeIdFor(self))
290
291 for role, ann in self.childRoles.items():
292 with ctx.settingAttribute(
293 V.ATTRIBUTE(dmrole=completeVODMLId(ctx, role))) as attr:
294 attr[ann.getVOT(ctx, instance)]
295 res[attr]
296
297 return res
298
299
300 class DatatypeAnnotation(_AttributeGroupAnnotation):
301 """An annotation for a datatype.
302
303 Datatypes are essentially simple groups of attributes; they are used
304 *within* objects (e.g., to group photometry points, or positions, or
305 the like.
306 """
307
308
309 class ObjectAnnotation(_AttributeGroupAnnotation):
310 """An annotation for an object.
311
312 Objects are used for actual DM instances. In particular,
313 every annotation of a DaCHS table is rooted in an object.
314 """
315 def __repr__(self):
316 return f"<ObjectAnnotation {self.type}>"
317
318
319 class CollectionAnnotation(AnnotationBase, _WithMapCopyMixin):
320 """A collection contains 0..n things of the same type.
321 """
322 def __init__(self, name, type, instance):
323 AnnotationBase.__init__(self, name, instance)
324 self.type = type
325 # these can have atomic children, in which case we don't manage types
326 if self.type is not None:
327 self.modelPrefix, _, _ = parseTypeName(type)
328 self.children = []
329
330 def __getitem__(self, index):
331 child = self.children[index]
332 if isinstance(child, AtomicAnnotation):
333 return child.value
334 else:
335 return child
336
337 def __len__(self):
338 return len(self.children)
339
340 def iterChildRoles(self):
341 return iter(self.children)
342
343 def copyEmpty(self, newInstance):
344 return self.__class__(self.name, self.type, newInstance)
345
346 def add(self, child):
347 self.children.append(child)
348
349 def asSIL(self):
350 if self.type is None:
351 opener = "["
352 else:
353 opener = "(%s) ["%(self.type,)
354
355 bodyItems = []
356 for r in self.children:
357 bodyItems.append(r.asSIL(suppressType="True"))
358
359 return "%s: \n %s%s]\n"%(
360 self.name,
361 opener,
362 "\n ".join(bodyItems))
363
364 def getVOT(self, ctx, instance):
365 if self.type:
366 ctx.addVODMLPrefix(self.modelPrefix)
367
368 res = V.COLLECTION()
369 for c in self.children:
370 with ctx.settingAttribute(
371 V.ATTRIBUTE()) as item:
372 item[c.getVOT(ctx, instance)]
373 res[item]
374
375 return res
376
377
378 def _test():
379 import doctest
380 doctest.testmod()
381
382
383 if __name__=="__main__":
384 _test()