Debian Codegraph @

gavo/dm/dmrd.py

raw
1 """
2 Writing annotations in RDs.
3
4 This module provides the glue between annotations (typically in SIL)
5 and the rest of the RDs. It provides the ResAnnotation struct, which
6 contains the SIL, and the makeAttributeAnnotation function that is a factory
7 for attribute annotations.
8 """
9
10 #c Copyright 2008-2025, the GAVO project <[email protected]>
11 #c
12 #c This program is free software, covered by the GNU GPL. See the
13 #c COPYING file in the source distribution.
14
15
16 import functools
17 import itertools
18
19 from gavo import base
20 from gavo.dm import annotations
21 from gavo.dm import common
22 from gavo.dm import sil
23 from gavo.utils import stanxml
24 from gavo.utils import algotricks
25
26
27 stanxml.registerPrefix("vo-dml", "http://www.ivoa.net/xml/VODML/v1",
28 stanxml.schemaURL("vo-dml.xsd"))
29
30
31 class SynthesizedRoles(base.Structure):
32 """DM annotation copied and adapted to a new table.
33
34 This is a stand-in for DataModelRoles in tables not parsed from
35 XMLs. Their DM structure is defined through references the columns and
36 params make to the annotations their originals had.
37
38 These have no attributes but just arrange for the new annotations
39 to be generated.
40 """
41 name_ = "_synthesizedRoles"
42
43 def synthesizeAnnotations(self, rd, ctx):
44 # don't overwrite existing annotations (usually, they
45 # will be the result of a previous run when multiple
46 # annotations are present).
47 if self.parent.annotations:
48 return
49
50 annotationMap = {}
51
52 # First, construct a map from column/param annotations in
53 # the old annotations to new columns and params. As a
54 # side effect, the dmRoles of the new items are cleared.
55 for item in itertools.chain(self.parent.params, self.parent.columns):
56 if item.parent!=self.parent:
57 # Don't annotate things that don't belong to us. We need to
58 # be careful there because in the current architecture, we
59 # would be changing dmRoles
60 continue
61
62 if isinstance(item.dmRoles, list):
63 # item has been processed before, probably as part of another
64 # DM declaration. No need to repeat that.
65 continue
66
67 for annotation in item.dmRoles.oldRoles:
68 # annotation is a weakref here; skip the annotation if the
69 # referenced thing has gone away
70 resolved = annotation()
71 if resolved is not None:
72 annotationMap[resolved] = item
73 item.dmRoles = []
74
75 # Then, collect the annotations we have to copy
76 oldInstances = set(ann.instance() for ann in annotationMap)
77
78 # tell the instances to copy themselves, replacing references
79 # accordingly.
80 newInstances = []
81 for oldInstance in oldInstances:
82 newInstances.append(
83 oldInstance.copyWithAnnotationMap(
84 annotationMap, self.parent, None))
85 self.parent.annotations = newInstances
86
87 def completeElement(self, ctx):
88 ctx.addExitFunc(self.synthesizeAnnotations)
89 super().completeElement(ctx)
90
91
92 class DataModelRoles(base.Structure):
93 """an annotation of a table in terms of data models.
94
95 The content of this element is a Simple Instance Language clause.
96 """
97
98 # We used to defer the SIL parsing until the end of the XML parse
99 # in order to be relaxed about forward references. That, however,
100 # is not a good idea because later elements in the RD may copy the table,
101 # and its annotations will be incomplete then. Instead, we're now
102 # building the annotation when the element is complete and worry
103 # about cross-table forward references when they turn up.
104 #
105 # There's an additional complication in that we may want to
106 # access parsed annotations while parsing other annotations
107 # (e.g., when processing foreign keys).
108 # To allow the thing to "parse itself" in such situations, we do
109 # all the crazy magic with the _buildAnnotation function.
110 name_ = "dm"
111
112 _sil = base.DataContent(description="SIL (simple instance language)"
113 " annotation.", copyable=True)
114
115 def getAnnotation(self, roleName, container, instance):
116 return annotations.GroupRefAnnotation(roleName, self.parse(), instance)
117
118 def onParentComplete(self):
119 self.parent.annotations.append(self.parse())
120
121 def parse(self):
122 """returns a parsed version of the embedded annotation.
123
124 The parse really is only run once, but you should only call it once
125 the embedding table is complete, because this needs to resolve table
126 params and columns (and possibly other dm elements).
127 """
128 if hasattr(self, "_parsedAnnotation"):
129 return self._parsedAnnotation
130
131 try:
132 self._parsedAnnotation = sil.getAnnotation(
133 self.content_, getAnnotationMaker(self.parent))
134 except Exception as ex:
135 base.ui.notifyInfo("While parsing the SIL below: %s"%str(ex))
136 base.ui.notifyInfo(self.content_)
137 raise base.ui.logOldExc(base.StructureError(str(ex),
138 pos=self.getSourcePosition()))
139 return self._parsedAnnotation
140
141
142 def copy(self, newParent, ctx):
143 # we use the general mechanism used for recovering annotations from
144 # columns and params in tables here so we're independent of
145 # changes in columns.
146 return SynthesizedRoles(newParent).finishElement(ctx)
147
148
149 class DataModelRolesAttribute(base.StructListAttribute):
150 """an attribute allowing data model annotation using SIL.
151
152 It will also give an annotations attribute on the instance, and a
153 getAnnotationsOfType method letting you pull out a specific annotation.
154
155 For situation where an existing annotation should be copied from
156 annotations coming in through columns and/or params, the attribute
157 also gives an updateAnnotationFromChildren method. It will do
158 nothing if some annotation already exists.
159 """
160 def __init__(self):
161 base.StructListAttribute.__init__(self,
162 "dm",
163 childFactory=DataModelRoles,
164 description="Annotations for data models.",
165 copyable=True)
166
167 def iterParentMethods(self):
168 def iterAnnotationsOfType(instance, typeName):
169 """returns the first annotation of the type passed.
170 """
171 for ann in instance.annotations:
172 if ann.type==typeName:
173 yield ann
174
175 yield ("iterAnnotationsOfType", iterAnnotationsOfType)
176
177 def updateAnnotationFromChildren(instance):
178 roleSynthesizer = SynthesizedRoles(instance)
179 roleSynthesizer.synthesizeAnnotations(None, None)
180 yield ("updateAnnotationFromChildren", updateAnnotationFromChildren)
181
182
183 def makeAttributeAnnotation(container, instance, attName, attValue):
184 """returns a typed annotation for attValue within container.
185
186 When attValue is a literal, this is largely trivial. If it's a reference,
187 this figures out what it points to and creates an annotation of
188 the appropriate type (e.g., ColumnAnnotation, ParamAnnotation, etc).
189
190 container in current DaCHS should be a TableDef or something similar;
191 this function expects at least a getByName function and an rd attribute.
192
193 instance is the root of the current annotation. Complex objects should
194 keep a (weak) reference to that. We don't have parent links in
195 our dm trees, and without a reference to the root there's no
196 way we can go "up".
197
198 This is usually used as a callback from within sil.getAnnotation and
199 expects Atom and Reference instances as used there.
200 """
201 if isinstance(attValue, sil.Atom):
202 return common.AtomicAnnotation(attName, attValue, instance=instance)
203
204 elif isinstance(attValue, sil.Reference):
205 # try name-resolving first (resolveId only does id resolving on
206 # unadorned strings)
207 try:
208 res = container.getByName(attValue)
209 except base.NotFoundError:
210 if container.rd:
211 res = base.resolveId(container.rd, attValue, instance=container)
212 else:
213 raise
214
215 if not hasattr(res, "getAnnotation"):
216 raise base.StructureError("Element %s cannot be referenced"
217 " within a data model."%repr(res))
218
219 return res.getAnnotation(attName, container, instance)
220
221 else:
222 assert False
223
224
225 def getAnnotationMaker(container):
226 """wraps makeAttributeAnnotationMaker such that names are resolved
227 within container.
228 """
229 return functools.partial(makeAttributeAnnotation, container)
230
231
232 def _splitPath(path:str):
233 """returns a pair of (prefix)/(stuff-without-slash) for path.
234 """
235 splitpoint = path.rfind("/")
236 if splitpoint==-1:
237 return "", path
238 else:
239 return path[:splitpoint], path[splitpoint+1:]
240
241
242 def _makeDMVal(stcObj):
243 """returns a value palatable to makeAttributeAnnotation from stcObj
244
245 (which essentially will be an set.ColRef or some literal).
246 """
247 if hasattr(stcObj, "dest"):
248 return sil.Reference(stcObj.dest)
249
250 else:
251 return sil.Atom(stcObj)
252
253
254 def buildAdhocSTC(table, vals):
255 """builds a modern adhoc STC annotation in table based on a mapping
256 of attribute paths to annotation targets in vals.
257
258 This is only necessary as long as we want to support <stc> specs. The
259 keys here are, in effect defined in rscdef.tabledef; see _utypeToModern.
260 """
261 if vals.pop("!!!flavor!!!", None)!="SPHERICAL":
262 # anything else would need a lot more thought, and that's certainly not
263 # worth it. STC-S should die.
264 return
265
266 # Sigh. STC1 split off the J/B from the epoch value. Let's cope in
267 # some way.
268 if vals.pop("!!!yearDef!!!", "J")!="J":
269 raise NotImplementedError("We can only deal with Julian epochs")
270 if "/space/frame/epoch" in vals:
271 if isinstance(vals["/space/frame/epoch"], str):
272 vals["/space/frame/epoch"] = "J"+vals["/space/frame/epoch"]
273
274 annMaker = getAnnotationMaker(table)
275 # astid is the id of the STC1 AST that has produced the original utypes.
276 # We want to record this because in votablewrite we want to re-use the
277 # COOSYS that already exists when there is an STC1 annotation.
278 astid = None
279 objs = {}
280
281 for path in algotricks.pathSort(vals.keys()):
282 prefix, attname = _splitPath(path)
283 parent = objs[prefix] if path else None
284
285 if path in buildAdhocSTC.typesForPaths:
286 # it's an intermediate object: create it
287 objs[path] = common.ObjectAnnotation(
288 attname, buildAdhocSTC.typesForPaths[path], objs.get(""))
289 if parent is not None:
290 parent.add(objs[path])
291
292 else:
293 # it's an attribute; translate stc's references and literals
294 parent.add(annMaker(objs[""], attname, _makeDMVal(vals[path])))
295 if astid is None:
296 # if value is a ColRef, whatever it refers to will define our
297 # STC1 AST
298 try:
299 destCol = table.getElementForName(vals[path].dest)
300 astid = str(id(destCol.stc))
301 objs[""].add(annMaker(objs[""], "astid", sil.Atom(astid)))
302 except (base.NotFoundError, AttributeError):
303 # not a ColRef, apparently, try next val
304 pass
305
306 table.annotations.append(objs[""])
307
308
309 buildAdhocSTC.typesForPaths = {
310 "": "votable:Coords",
311 "/space": "votable:SphericalCoordinate",
312 "/space/frame": "votable:SpaceFrame",
313 "/time": "votable:TimeCoordinate",
314 "/time/frame": "votable:TimeFrame",
315 }