Debian Codegraph @

gavo/dm/vodml.py

raw
1 """
2 Parsing VO-DML files and (perhaps one day) validating against the
3 rules obtained in this way.
4
5 Validation is something we expect to do only fairly rarely, so none of
6 this code is expected to be efficient.
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 functools
16
17 from lxml import etree
18
19 from gavo import base
20 from gavo.votable import V
21
22
23 KNOWN_MODELS = {
24 # maps the canonical prefix to the file name within resources/dm
25 "ivoa": "IVOA.vo-dml.xml",
26 "meas": "meas.vo-dml.xml",
27 "coords": "coords.vo-dml.xml",
28 "dachstoy": "dachstoy.vo-dml.xml",
29 "geojson": "geojson.vo-dml.xml",
30 "phot": "phot.vo-dml.xml",
31 }
32
33
34 def openModelFile(prefix):
35 """returns an open file for the VO-DML file corresponding to prefix.
36
37 This will raise a NotFoundError for an unknown prefix.
38 """
39 try:
40 fName = KNOWN_MODELS[prefix]
41 except KeyError:
42 raise base.NotFoundError(prefix, "VO-DML file for prefix",
43 "data models known to DaCHS", hint="This can happen if there"
44 " are new data models around or if data providers have defined"
45 " custom data models. If this error was fatal during VOTable"
46 " processing, please report it as an error; bad data model"
47 " annotation should not be fatal in DaCHS.")
48 return base.openDistFile("dm/"+fName, "rb")
49
50
51 class Model(object):
52 """a vo-dml model.
53
54 These are usually constructed using the fromPrefix constructor,
55 which uses a built-in mapping from well-known prefix to VO-DML file
56 to populate the model.
57 """
58
59 # non-well-known models can be fed in through fromFile; they will
60 # be entered here and can then be obtained through fromPrefix
61 # as long as the don't clash with KNOWN_MODELS.
62
63 _modelsReadFromFile = {}
64
65 def __init__(self, prefix, dmlTree):
66 self.prefix = prefix
67 self.title = self.version = None
68 self.version = self.uri = None
69 self.description = None
70 self.dmlTree = dmlTree
71 self.__idIndex = None
72 self._getModelMeta()
73
74 @classmethod
75 def fromPrefix(cls, prefix):
76 """returns a VO-DML model for a well-known prefix.
77
78 User code should typically use the getModelFromPrefix function.
79 """
80 if prefix in cls._modelsReadFromFile:
81 return cls._modelsReadFromFile[prefix]
82
83 inF = openModelFile(prefix)
84 try:
85 try:
86 return cls(prefix, etree.parse(inF))
87 except Exception as ex:
88 raise base.ui.logOldExc(
89 base.StructureError("Failure to parse VO-DML for prefix %s: %s"%(
90 prefix, repr(ex))))
91 finally:
92 inF.close()
93
94 @classmethod
95 def fromFile(cls, src, srcURL="http //not.given/invalid"):
96 """returns a VO-DML model from src.
97
98 src can either be a file name (interpreted relative to the root
99 of DaCHS' VO-DML repository) or an open file (which will be closed
100 as a side effect of this function).
101
102 This is intended for documents using non-standard models with custom
103 prefixes (i.e., not known to DaCHS).
104 """
105 if hasattr(src, "read"):
106 inF = src
107 else:
108 inF = openModelFile(src)
109
110 try:
111 tree = etree.parse(inF)
112 prefix = tree.find("name").text
113 res = cls(prefix, tree)
114 res.uri = srcURL
115
116 if prefix not in KNOWN_MODELS:
117 cls._modelsReadFromFile[prefix] = res
118 return res
119 finally:
120 inF.close()
121
122 def _getModelMeta(self):
123 """sets some metadata on the model from the parsed VO-DML.
124
125 This will fail silently (i.e., the metadata will remain on its
126 default).
127
128 Metadata obtained so far includes: title, version, description,
129 """
130 try:
131 self.title = self.dmlTree.find("title").text
132 self.version = self.dmlTree.find("version").text
133 self.description = self.dmlTree.find("description").text
134 self.uri = self.dmlTree.find("uri").text
135 except AttributeError:
136 # probably the VO-DML file is bad; just fall through to
137 # non-validatable model.
138 pass
139
140 @functools.lru_cache(200)
141 def getByVODMLId(self, vodmlId):
142 """returns the element with vodmlId.
143
144 This raises a NotFoundError for elements that are not present.
145
146 This can be used with or without a prefix. The prefix is just
147 discarded, though.
148
149 Do not pass in unparsed ids; they are used in xpaths.
150 """
151 vodmlId = vodmlId.split(":")[-1]
152
153 res = self.dmlTree.xpath(f"//*[vodml-id='{vodmlId}']")
154 if res:
155 return res[0]
156 else:
157 raise base.NotFoundError(vodmlId, "data model element",
158 self.prefix+" data model")
159
160 def _resolveVODMLId(self, vodmlId):
161 """returns an etree element for vodmlId, which may include a prefix.
162
163 (in which case we'd probably be looking in a different DM).
164
165 This will raise a NotFoundError when the vodmlId points nowhere.
166 """
167 if ":" in vodmlId:
168 return resolveVODMLId(vodmlId)
169 else:
170 return self.getByVODMLElement(vodmlId)
171
172 def _makeAttrDict(self, attrNode):
173 """returns a dictionary of attribute metadata for an etree attrNode.
174 """
175 res = {}
176 for child in attrNode:
177 if child.tag=="vodml-id":
178 res["vodml-id"] = child.text.strip()
179 elif child.tag=="description":
180 res["description"] = child.text.strip()
181 elif child.tag=="datatype":
182 res["datatype"] = child[0].text
183 return res
184
185 @functools.lru_cache(100)
186 def getType(self, name):
187 """returns an etree for a data or object type with the *name* name
188 within this DM.
189
190 Any prefix on name will be discarded without further ado. Don't
191 pass in anythin unparsed here; we are using xpaths.
192 """
193 name = name.split(":")[-1]
194 type = self.dmlTree.xpath(f"dataType[name='{name}']")
195 if type:
196 return type[0]
197
198 type = self.dmlTree.xpath(f"objectType[name='{name}']")
199 if type:
200 return type[0]
201
202 raise base.NotFoundError(
203 name, "VO-DML type", self.prefix+" data model")
204
205 @functools.lru_cache(1000)
206 def getAttributeMeta(self, typeName, attrName):
207 """returns a metadata dictionary for a the attribute attrName of the
208 type referenced by type name.
209
210 attrName is the unqualified attribute name. typeName may be qualified,
211 but prefixes are ignored.
212
213 Do not pass in unparsed strings to typeName and attrName; they are
214 blindly used in xpath expressions.
215
216 The metadata returned includes datatype, description, and vodmlId.
217
218 If either the data model, or type, or the attribute cannot be
219 found a NotFoundError is raised.
220 """
221 type = self.getType(typeName)
222
223 while True:
224 attr = type.xpath(f"(attribute|composition)[name='{attrName}']")
225 if attr:
226 return self._makeAttrDict(attr[0])
227 extends = type.xpath("extends/vodml-ref")
228 if extends:
229 type = self._resolveVODMLId(extends[0].text)
230 else:
231 raise base.NotFoundError(
232 attrName, "attribute", f"VO-DML type {typeName}")
233
234 def getVOT(self, ctx, instance):
235 """returns xmlstan for a VOTable declaration of this DM.
236 """
237 return V.MODEL(name=self.prefix, url=self.uri)
238
239
240 @functools.lru_cache(30)
241 def getModelForPrefix(prefix):
242 """returns a vodml.Model instance for as well-known VODML prefix.
243
244 This caches models for prefixes and thus should usually be used
245 from user code.
246
247 Note that this currently will currently return some stand-in shim
248 for unknown prefixes. That behaviour will change to become a
249 NotFoundError exception when there's actually useful data models.
250 """
251 try:
252 return Model.fromPrefix(prefix)
253 except base.NotFoundError:
254 res = Model(prefix, etree.fromstring(
255 """<junk><title>DaCHS standin model</title>
256 <description>This is used by DaCHS during the old west
257 days of VO DM development. Any annotation using this will
258 not be interoperable.</description>
259 <version>invalid</version></junk>"""))
260 res.uri = "urn:dachsjunk:not-model:"+prefix
261 return res
262
263
264 def getAttributeDefinition(qualifiedType, attrName):
265 """returns attribute metadata for a type.
266
267 qualifiedType is a type name with a prefix, attrName is the attribute's
268 name (not vodml-id).
269 """
270 prefix, typeName = qualifiedType.split(":")
271 return getModelForPrefix(prefix).getAttributeMeta(typeName, attrName)
272
273
274 def resolveVODMLId(vodmlId):
275 """returns an etree element corresponding to the prefixed vodmlId.
276
277 Of course, this only works if vodmlId has a well-known prefix.
278 """
279 prefix, id = vodmlId.split(":", 1)
280 return getModelForPrefix(prefix).getByVODMLId(id)