-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathmetamodelcore.py
349 lines (288 loc) · 11.5 KB
/
metamodelcore.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
import builtins
import datetime
import re
from dataclasses import field
from decimal import Decimal
from typing import Union, Optional, Tuple
from urllib.parse import urlparse
from rdflib import Literal, BNode, URIRef
from rdflib.namespace import is_ncname
from rdflib.term import Identifier as rdflib_Identifier
from linkml_runtime.utils.namespaces import Namespaces
from linkml_runtime.utils.strictness import is_strict
from linkml_runtime.utils.uri_validator import validate_uri
from linkml_runtime.utils.uri_validator import validate_uri_reference
from linkml_runtime.utils.uri_validator import validate_curie
# Reference Decimal to make sure it stays in the imports
_z = Decimal(1)
# ===========================
# Fields for use in dataclass
# ===========================
from linkml_runtime.utils.yamlutils import TypedNode
def empty_list():
""" Return a field with a list factory """
return field(default_factory=list)
def empty_dict():
""" Return a field with a dictionary factory """
return field(default_factory=dict)
def addl_args():
rval = field(default_factory=dict)
rval.name = '**args'
return rval
def empty_set():
"""" Return a field with a set factory """
return field(default_factory=set)
def bnode():
""" Return a field with a BNode factory """
return field(default_factory=lambda: BNode().n3())
# List of builtins for mangling names
builtinnames = dir(builtins)
class NCName(str):
""" Wrapper for NCName class """
def __init__(self, v: str) -> None:
if is_strict() and not self.is_valid(v):
raise ValueError(f"{TypedNode.yaml_loc(v)}{v}: Not a valid NCName")
self.nsm: Optional[Namespaces] = None
super().__init__()
@classmethod
def is_valid(cls, v: str) -> bool:
return is_ncname(v) if v else True # Empty is default name
class Identifier(str, TypedNode):
""" A datatype that can be a URI, CURIE or a BNode """
def __init__(self, v: Union[str, URIRef, BNode, "URIorCURIE", "Identifier"]) -> None:
v = str(v) if not isinstance(v, str) else v
if is_strict() and not self.is_valid(v):
raise ValueError(f"{v}: is not a valid Identifier")
TypedNode.__init__(self, v)
@classmethod
def is_valid(cls, v: Union[str, URIRef, BNode, "URIorCURIE", "Identifier"]) -> bool:
if v is None:
return False
if v.startswith('_:'):
pfx, ln = v.split(':')
return len(ln) == 1 and bool(Curie.term_name.match(ln))
else:
return URIorCURIE.is_valid(v)
def as_identifier(self, nsm: Optional[Namespaces]) -> Optional[rdflib_Identifier]:
if self.startswith('_:'):
return BNode(self)
elif URIorCURIE.is_absolute(self):
return URIRef(self)
elif nsm:
return URIorCURIE(self).as_uri(nsm)
return None
class URIorCURIE(Identifier):
""" A datatype that can either be a URI or a CURIE """
def __init__(self, v: Union[str, URIRef, "Curie", "URIorCURIE"]) -> None:
if is_strict() and not URIorCURIE.is_valid(v):
raise ValueError(f"{v} is not a valid URI or CURIE")
super().__init__(v)
@classmethod
def is_valid(cls, v: Union[str, URIRef, "Curie", "URIorCURIE"]) -> bool:
if not isinstance(v, (str, URIRef, Curie, URIorCURIE)):
return False
v = str(v)
if validate_uri(v):
return True
elif validate_uri_reference(v):
return True
else:
return URIorCURIE.is_curie(v)
@staticmethod
def is_absolute(v: str) -> bool:
return bool(urlparse(v).netloc)
@staticmethod
def is_curie(v: str, nsm: Optional[Namespaces] = None) -> bool:
if not validate_curie(v):
return False
if ':' in v and '://' not in v:
ns, ln = v.split(':', 1)
return len(ns) == 0 or (NCName.is_valid(ns) and
(nsm is None or any(ns == nsns for nsns, _ in nsm.namespaces())))
return False
def as_uri(self, nsm: Namespaces) -> Optional[URIRef]:
if self.is_absolute(self):
return URIRef(self)
return Curie(self).as_uri(nsm)
class URI(URIorCURIE):
""" A relative absolute URI
"""
def __init__(self, v: str) -> None:
if is_strict() and not URI.is_valid(v):
raise ValueError(f"'{v}': is not a valid URI")
super().__init__(v)
@classmethod
def is_valid(cls, v: str) -> bool:
if validate_uri(v):
return True
elif validate_uri_reference(v):
return True
else:
return False
class Curie(URIorCURIE):
""" Wrapper for an element that MUST be represented as a CURIE """
def __init__(self, v: str) -> None:
if is_strict() and not self.is_valid(v):
raise ValueError(f"{v} is not a valid CURIE")
super().__init__(v)
# TODO: see whether we can leverage the rdflib RDFA termorcurie package
term_name = re.compile("^[A-Za-z]([A-Za-z0-9._-]|/)*$")
@classmethod
def ns_ln(cls, v: str) -> Optional[Tuple[str, str]]:
if not validate_curie(v):
return None
# assume the presence of a colon and try to split the CURIE
curie_split = v.split(':', 1)
if len(curie_split) == 1:
# there is no ':' character in the string, it's only a reference
return '', v
else:
prefix = curie_split[0].lower()
reference = curie_split[1]
return prefix, reference
@classmethod
def is_valid(cls, v: str) -> bool:
if not validate_curie(v):
return False
pnln = cls.ns_ln(v)
#return pnln is not None and (not pnln[0] or isinstance(pnln[0], PN_PREFIX))
return pnln is not None
# This code was extracted from the termorcurie package of the rdfa
def as_uri(self, nsm: Namespaces) -> Optional[URIRef]:
""" Return the URI for the CURIE if a mapping is available, otherwise return None """
try:
return nsm.uri_for(self)
except ValueError:
pass
return None
class Bool:
""" Wrapper for boolean datatype """
bool_true = re.compile(r'([Tt]rue)|(1)$')
bool_false = re.compile(r'([Ff]alse)|(0)$')
def __new__(cls, v: Union[str, bool, "Bool"]) -> bool:
if isinstance(v, bool):
return v
if cls.bool_true.match(str(v)):
return True
if cls.bool_false.match(str(v)):
return False
if is_strict():
raise ValueError(f"{v}: Must be a boolean value")
return bool(v)
@classmethod
def is_valid(cls, v: str) -> bool:
""" Determine whether the string v is a valid instance of bool """
return isinstance(v, bool) or cls.bool_true.match(str(v)) or cls.bool_false.match(str(v))
class XSDTime(str, TypedNode):
""" Wrapper for time datatype """
def __new__(cls, value: Union[str, datetime.time, datetime.datetime, Literal]) -> str:
if is_strict() and not cls.is_valid(value):
raise ValueError(f"{value} is not a valid time")
if isinstance(value, Literal):
value = value.value
try:
if not isinstance(value, datetime.time):
value = datetime.time.fromisoformat(value)
return datetime.time.fromisoformat(str(value)).isoformat()
except TypeError as e:
pass
except ValueError as e:
pass
if not is_strict():
return str(value)
raise e
@classmethod
def is_valid(cls, value: Union[str, datetime.time, datetime.datetime, Literal]) -> bool:
if isinstance(value, Literal):
value = value.value
if isinstance(value, (datetime.time, datetime.datetime)):
value = value.isoformat()
try:
datetime.time.fromisoformat(str(value))
except ValueError:
return False
return True
class XSDDate(str, TypedNode):
""" Wrapper for date datatype """
def __new__(cls, value: Union[str, datetime.date, Literal]) -> str:
if is_strict() and not cls.is_valid(value):
raise ValueError(f"{value} is not a valid date")
if isinstance(value, Literal):
value = value.value
try:
if not isinstance(value, datetime.date):
value = datetime.date.fromisoformat(str(value))
return value.isoformat()
except TypeError as e:
pass
except ValueError as e:
pass
if not is_strict():
return str(value)
raise e
@classmethod
def is_valid(cls, value: Union[str, datetime.date, Literal]) -> bool:
if isinstance(value, Literal):
value = value.value
if isinstance(value, datetime.date):
value = value.isoformat()
try:
datetime.date.fromisoformat(str(value))
except ValueError:
return False
return True
class XSDDateTime(str, TypedNode):
""" Wrapper for date time dataclass """
def __new__(cls, value: Union[str, datetime.datetime, Literal]) -> str:
if is_strict() and not cls.is_valid(value):
raise ValueError(f"{value} is not a valid datetime")
if isinstance(value, Literal):
value = value.value
try:
if not isinstance(value, datetime.datetime):
value = datetime.datetime.fromisoformat(value) # Note that this handles non 'T' format as well
return value.isoformat()
except TypeError as e:
pass
except ValueError as e:
pass
if not is_strict():
return str(value)
raise e
@classmethod
def is_valid(cls, value: Union[str, datetime.datetime, Literal]) -> bool:
if isinstance(value, Literal):
value = value.value
if isinstance(value, datetime.datetime):
value = value.isoformat()
try:
datetime.datetime.fromisoformat(value)
except ValueError:
return False
return True
class NodeIdentifier(Identifier):
""" A RDFLib Identifier that represents a URI, CURIE or BNode in a model """
def __new__(cls, v: Union[str, URIRef, URIorCURIE, "NodeIdentifier", BNode]) -> "NodeIdentifier":
if hasattr(v, 'id'): # Allows passing instances of identified objects
v = v.id
if isinstance(v, NodeIdentifier):
if is_strict() and not issubclass(type(v), cls):
raise ValueError(f"Invalid identifier type for {cls.__name__}: {v} ({type(v).__name__})")
else:
return super().__new__(cls, v)
elif type(v) in (str, URIRef, URIorCURIE, BNode) or not is_strict():
return super().__new__(cls, str(v))
else:
raise ValueError(f"Unknown identifier for {cls.__name__}: {v}")
def __post_init__(self):
pass
class ElementIdentifier(NodeIdentifier):
""" A URIorCURIE that represents an element in a model """
def __new__(cls, v: Union[str, URIRef, URIorCURIE, NodeIdentifier, "ElementIdentifier"]) -> "ElementIdentifier":
if hasattr(v, 'id'): # Allows passing instances of identified objects
v = v.id
if is_strict() and (type(v) is BNode or str(v).startswith('_:')):
raise ValueError(f"Invalid identifier type for {cls.__name__}: {v} ({type(v).__name__})")
return super().__new__(cls, v)
def __post_init__(self):
pass