ontolutils 0.2.18__tar.gz → 0.2.20__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. {ontolutils-0.2.18 → ontolutils-0.2.20}/PKG-INFO +1 -1
  2. {ontolutils-0.2.18 → ontolutils-0.2.20}/ontolutils/classes/query_util.py +13 -13
  3. {ontolutils-0.2.18 → ontolutils-0.2.20}/ontolutils/classes/thing.py +14 -10
  4. {ontolutils-0.2.18 → ontolutils-0.2.20}/ontolutils/namespacelib/__init__.py +6 -1
  5. {ontolutils-0.2.18 → ontolutils-0.2.20}/ontolutils.egg-info/PKG-INFO +1 -1
  6. {ontolutils-0.2.18 → ontolutils-0.2.20}/setup.cfg +1 -1
  7. {ontolutils-0.2.18 → ontolutils-0.2.20}/tests/test_classes.py +20 -2
  8. {ontolutils-0.2.18 → ontolutils-0.2.20}/tests/test_query.py +50 -0
  9. {ontolutils-0.2.18 → ontolutils-0.2.20}/LICENSE +0 -0
  10. {ontolutils-0.2.18 → ontolutils-0.2.20}/README.md +0 -0
  11. {ontolutils-0.2.18 → ontolutils-0.2.20}/ontolutils/__init__.py +0 -0
  12. {ontolutils-0.2.18 → ontolutils-0.2.20}/ontolutils/_version.py +0 -0
  13. {ontolutils-0.2.18 → ontolutils-0.2.20}/ontolutils/cache.py +0 -0
  14. {ontolutils-0.2.18 → ontolutils-0.2.20}/ontolutils/classes/__init__.py +0 -0
  15. {ontolutils-0.2.18 → ontolutils-0.2.20}/ontolutils/classes/decorator.py +0 -0
  16. {ontolutils-0.2.18 → ontolutils-0.2.20}/ontolutils/classes/typing.py +0 -0
  17. {ontolutils-0.2.18 → ontolutils-0.2.20}/ontolutils/classes/utils.py +0 -0
  18. {ontolutils-0.2.18 → ontolutils-0.2.20}/ontolutils/namespacelib/__dev.py +0 -0
  19. {ontolutils-0.2.18 → ontolutils-0.2.20}/ontolutils/namespacelib/_iana_utils.py +0 -0
  20. {ontolutils-0.2.18 → ontolutils-0.2.20}/ontolutils/namespacelib/codemeta.py +0 -0
  21. {ontolutils-0.2.18 → ontolutils-0.2.20}/ontolutils/namespacelib/m4i.py +0 -0
  22. {ontolutils-0.2.18 → ontolutils-0.2.20}/ontolutils/namespacelib/obo.py +0 -0
  23. {ontolutils-0.2.18 → ontolutils-0.2.20}/ontolutils/namespacelib/qudt_kind.py +0 -0
  24. {ontolutils-0.2.18 → ontolutils-0.2.20}/ontolutils/namespacelib/qudt_unit.py +0 -0
  25. {ontolutils-0.2.18 → ontolutils-0.2.20}/ontolutils/namespacelib/schema.py +0 -0
  26. {ontolutils-0.2.18 → ontolutils-0.2.20}/ontolutils/namespacelib/ssno.py +0 -0
  27. {ontolutils-0.2.18 → ontolutils-0.2.20}/ontolutils.egg-info/SOURCES.txt +0 -0
  28. {ontolutils-0.2.18 → ontolutils-0.2.20}/ontolutils.egg-info/dependency_links.txt +0 -0
  29. {ontolutils-0.2.18 → ontolutils-0.2.20}/ontolutils.egg-info/requires.txt +0 -0
  30. {ontolutils-0.2.18 → ontolutils-0.2.20}/ontolutils.egg-info/top_level.txt +0 -0
  31. {ontolutils-0.2.18 → ontolutils-0.2.20}/pyproject.toml +0 -0
  32. {ontolutils-0.2.18 → ontolutils-0.2.20}/setup.py +0 -0
  33. {ontolutils-0.2.18 → ontolutils-0.2.20}/tests/test_decorator.py +0 -0
  34. {ontolutils-0.2.18 → ontolutils-0.2.20}/tests/test_namespaces.py +0 -0
  35. {ontolutils-0.2.18 → ontolutils-0.2.20}/tests/test_readme.py +0 -0
  36. {ontolutils-0.2.18 → ontolutils-0.2.20}/tests/test_typing.py +0 -0
  37. {ontolutils-0.2.18 → ontolutils-0.2.20}/tests/test_utils.py +0 -0
  38. {ontolutils-0.2.18 → ontolutils-0.2.20}/tests/test_version.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: ontolutils
3
- Version: 0.2.18
3
+ Version: 0.2.20
4
4
  Summary: Utility library for the work with ontologies.
5
5
  Home-page: https://github.com/matthiasprobst/ontology-utils
6
6
  Author: Matthias Probst
@@ -79,7 +79,7 @@ WHERE {
79
79
  return str(obj)
80
80
 
81
81
 
82
- def get_query_string(cls, limit: int = None) -> str:
82
+ def get_query_string(cls) -> str:
83
83
  """Return the query string for the class."""
84
84
 
85
85
  def _get_namespace(key):
@@ -92,12 +92,8 @@ def get_query_string(cls, limit: int = None) -> str:
92
92
  SELECT *
93
93
  WHERE {{
94
94
  ?id a {_get_namespace(cls.__name__)} .
95
- ?id ?p ?o ."""
96
- if limit is not None:
97
- query_str += f"""
98
- }} LIMIT {limit}"""
99
- else:
100
- query_str += "\n}"
95
+ ?id ?p ?o .
96
+ }}"""
101
97
  return query_str
102
98
 
103
99
 
@@ -182,7 +178,7 @@ def expand_sparql_res(bindings,
182
178
  def dquery(subject: str,
183
179
  source: Optional[Union[str, pathlib.Path]] = None,
184
180
  data: Optional[Union[str, Dict]] = None,
185
- context: Optional[Dict] = None) -> Union[List[Dict], None]:
181
+ context: Optional[Dict] = None) -> List[Dict]:
186
182
  """Return a list of resutls. The entries are dictionaries.
187
183
 
188
184
  Example
@@ -196,9 +192,12 @@ def dquery(subject: str,
196
192
  data=data,
197
193
  format='json-ld',
198
194
  context=context)
199
-
195
+ if context is None:
196
+ context = {}
200
197
  prefixes = "".join([f"PREFIX {k}: <{p}>\n" for k, p in context.items() if not k.startswith('@')])
201
198
 
199
+ assert isinstance(subject, str), f"Subject must be a string, not {type(subject)}"
200
+
202
201
  query_str = f"""
203
202
  SELECT *
204
203
  WHERE {{
@@ -209,7 +208,7 @@ def dquery(subject: str,
209
208
  res = g.query(prefixes + query_str)
210
209
 
211
210
  if len(res) == 0:
212
- return None
211
+ return []
213
212
 
214
213
  logger.debug(f'Querying subject="{subject}" with query: "{prefixes + query_str}" and got {len(res)} results')
215
214
 
@@ -243,7 +242,8 @@ def query(cls: Thing,
243
242
  if cls == Thing:
244
243
  query_string = '\nSELECT *\nWHERE {\n ?id a ?type .\n ?id ?p ?o .\n}'
245
244
  else:
246
- query_string = get_query_string(cls)
245
+ query_string = get_query_string(
246
+ cls) # TODO: limit should be passed here, however the sparql query must be written yet
247
247
  g = rdflib.Graph()
248
248
 
249
249
  ns_keys = [_ns[0] for _ns in g.namespaces()]
@@ -282,7 +282,7 @@ def query(cls: Thing,
282
282
  logger.debug(f'Querying resulted in {len(res)} results')
283
283
 
284
284
  if len(res) == 0:
285
- return
285
+ return []
286
286
 
287
287
  logger.debug(f'Expanding SPARQL results...')
288
288
  kwargs: Dict = expand_sparql_res(res.bindings, g, False, False)
@@ -299,6 +299,6 @@ def query(cls: Thing,
299
299
  if limit == 1:
300
300
  return cls.model_validate({'id': k, **model_field_dict})
301
301
  out.append(cls.model_validate({'id': k, **model_field_dict}))
302
- if i == limit:
302
+ if i == limit - 1:
303
303
  return out
304
304
  return [cls.model_validate({'id': _id, **params}) for _id, params in kwargs.items()]
@@ -190,13 +190,13 @@ class Thing(ThingModel):
190
190
 
191
191
  at_context.update(**context)
192
192
 
193
- ctx = Context(source={**at_context, **URIRefManager.get(self.__class__)})
193
+ # ctx = Context(source={**at_context, **URIRefManager.get(self.__class__)})
194
194
 
195
195
  logger.debug(f'The context is "{at_context}".')
196
196
 
197
197
  def _serialize_fields(
198
198
  obj: Union[ThingModel, int, str, float, bool, datetime],
199
- exclude_none: bool
199
+ _exclude_none: bool
200
200
  ) -> Union[Dict, int, str, float, bool]:
201
201
  """Serializes the fields of a Thing object into a json-ld
202
202
  dictionary (without context!). Note, that IDs can automatically be
@@ -208,7 +208,7 @@ class Thing(ThingModel):
208
208
  The object to serialize (a subclass of ThingModel). All other types will
209
209
  be returned as is. One exception is datetime, which will be serialized
210
210
  to an ISO string.
211
- exclude_none: bool=True
211
+ _exclude_none: bool=True
212
212
  If True, fields with None values will be excluded from the
213
213
  serialization
214
214
 
@@ -225,12 +225,16 @@ class Thing(ThingModel):
225
225
  uri_ref_manager = URIRefManager.get(obj.__class__, None)
226
226
  at_context.update(NamespaceManager.get(obj.__class__, {}))
227
227
 
228
+ obj_ctx = Context(source={**context,
229
+ **NamespaceManager.get(obj.__class__, {}),
230
+ **URIRefManager.get(obj.__class__, {})})
231
+
228
232
  if uri_ref_manager is None:
229
233
  return str(obj)
230
234
 
231
235
  try:
232
236
  serialized_fields = {}
233
- for k in obj.model_dump(exclude_none=exclude_none):
237
+ for k in obj.model_dump(exclude_none=_exclude_none):
234
238
  value = getattr(obj, k)
235
239
  if value is not None and k not in ('id', '@id'):
236
240
  iri = uri_ref_manager.get(k, k)
@@ -240,9 +244,9 @@ class Thing(ThingModel):
240
244
  if resolve_keys:
241
245
  serialized_fields[iri] = value
242
246
  else:
243
- term = ctx.find_term(ctx.expand(iri))
247
+ term = obj_ctx.find_term(obj_ctx.expand(iri))
244
248
  if term:
245
- if ctx.shrink_iri(term.id).split(':')[1] != k:
249
+ if obj_ctx.shrink_iri(term.id).split(':')[1] != k:
246
250
  at_context[k] = term.id
247
251
  serialized_fields[k] = value
248
252
  else:
@@ -255,14 +259,14 @@ class Thing(ThingModel):
255
259
  _field = serialized_fields.pop(k)
256
260
  key = k
257
261
  if isinstance(v, Thing):
258
- serialized_fields[key] = _serialize_fields(v, exclude_none=exclude_none)
262
+ serialized_fields[key] = _serialize_fields(v, _exclude_none=_exclude_none)
259
263
  elif isinstance(v, list):
260
264
  serialized_fields[key] = [
261
- _serialize_fields(i, exclude_none=exclude_none) for i in v]
265
+ _serialize_fields(i, _exclude_none=_exclude_none) for i in v]
262
266
  elif isinstance(v, (int, float)):
263
267
  serialized_fields[key] = v
264
268
  else:
265
- serialized_fields[key] = _serialize_fields(v, exclude_none=exclude_none)
269
+ serialized_fields[key] = _serialize_fields(v, _exclude_none=_exclude_none)
266
270
 
267
271
  _type = URIRefManager[obj.__class__].get(obj.__class__.__name__, obj.__class__.__name__)
268
272
 
@@ -275,7 +279,7 @@ class Thing(ThingModel):
275
279
  out["@id"] = rdflib.BNode().n3()
276
280
  return out
277
281
 
278
- serialization = _serialize_fields(self, exclude_none=exclude_none)
282
+ serialization = _serialize_fields(self, _exclude_none=exclude_none)
279
283
 
280
284
  jsonld = {
281
285
  "@context": at_context,
@@ -1,6 +1,8 @@
1
1
  """Auto-generated file. Do not edit!"""
2
2
  import sys
3
3
 
4
+ import requests
5
+
4
6
  from . import __dev
5
7
  from ._iana_utils import IANA
6
8
  from .codemeta import CODEMETA
@@ -13,7 +15,10 @@ from .ssno import SSNO
13
15
  from ..cache import package_user_dir
14
16
 
15
17
  # create pivmeta module in local user directory
16
- __dev.pivmeta(filename=package_user_dir / 'pivmeta.py')
18
+ try:
19
+ __dev.pivmeta(filename=package_user_dir / 'pivmeta.py')
20
+ except requests.exceptions.ConnectionError:
21
+ pass # no internet connection, the pivmeta module may not be up to date
17
22
 
18
23
  sys.path.insert(0, str(package_user_dir))
19
24
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: ontolutils
3
- Version: 0.2.18
3
+ Version: 0.2.20
4
4
  Summary: Utility library for the work with ontologies.
5
5
  Home-page: https://github.com/matthiasprobst/ontology-utils
6
6
  Author: Matthias Probst
@@ -1,6 +1,6 @@
1
1
  [metadata]
2
2
  name = ontolutils
3
- version = 0.2.18
3
+ version = 0.2.20
4
4
  author = Matthias Probst
5
5
  author_email = matthias.probst@kit.edu
6
6
  description = Utility library for the work with ontologies.
@@ -93,6 +93,12 @@ class TestNamespaces(unittest.TestCase):
93
93
  def test_thing_custom_prop(self):
94
94
  """It is helpful to have the properties equal to the urirefs keys,
95
95
  however, this should not be required!"""
96
+ @namespaces(foaf='http://xmlns.com/foaf/0.1/',
97
+ schema='http://www.schema.org/')
98
+ @urirefs(Affiliation='prov:Affiliation',
99
+ name='schema:name')
100
+ class Affiliation(Thing):
101
+ name: str
96
102
 
97
103
  @namespaces(foaf='http://xmlns.com/foaf/0.1/',
98
104
  prov='http://www.w3.org/ns/prov#')
@@ -104,9 +110,14 @@ class TestNamespaces(unittest.TestCase):
104
110
  first_name: str = Field(default=None, alias='firstName')
105
111
  lastName: str
106
112
  age: int = None
113
+ affiliation: Affiliation=None
107
114
 
108
115
  p = Person(first_name='John', lastName='Doe', age=23)
109
- print(p.model_dump_jsonld(resolve_keys=True))
116
+ person_json = p.model_dump_jsonld(resolve_keys=False)
117
+ self.assertEqual(json.loads(person_json)['first_name'], 'John')
118
+ person_json = p.model_dump_jsonld(resolve_keys=True)
119
+ self.assertEqual(json.loads(person_json)['foaf:firstName'], 'John')
120
+
110
121
  p_from_jsonld = Person.from_jsonld(data=p.model_dump_jsonld(resolve_keys=True), limit=1)
111
122
  self.assertEqual(p_from_jsonld.first_name, 'John')
112
123
  self.assertEqual(p_from_jsonld.lastName, 'Doe')
@@ -322,7 +333,14 @@ class TestNamespaces(unittest.TestCase):
322
333
  label='Organization 1'
323
334
  ),
324
335
  )
325
- jsonld_str = person.model_dump_jsonld()
336
+ jsonld_str = person.model_dump_jsonld(resolve_keys=True)
337
+ jsonld_dict = json.loads(jsonld_str)
338
+
339
+ self.assertEqual(jsonld_dict['schema:affiliation']['@type'], 'prov:Organization')
340
+ self.assertEqual(jsonld_dict['schema:affiliation']['rdfs:label'], 'Organization 1')
341
+ self.assertEqual(jsonld_dict['rdfs:label'], 'Person 1')
342
+ self.assertEqual(jsonld_dict['@type'], 'foaf:Person')
343
+
326
344
 
327
345
  def test_prov(self):
328
346
  @namespaces(prov="https://www.w3.org/ns/prov#",
@@ -181,6 +181,56 @@ class TestQuery(unittest.TestCase):
181
181
  self.assertEqual(len(found_agents), 1)
182
182
  self.assertEqual(found_agents[0].mbox, 'e@mail.com')
183
183
 
184
+ with open(__this_dir__ / 'agent.jsonld', 'w') as f:
185
+ f.write(
186
+ """
187
+ {
188
+ "@context": {
189
+ "prov": "https://www.w3.org/ns/prov#",
190
+ "foaf": "http://xmlns.com/foaf/0.1/"
191
+ },
192
+ "@graph": [
193
+ {
194
+ "@id": "local:agent1",
195
+ "@type": "prov:Agent",
196
+ "foaf:mbox": "a@mail.com"
197
+ },
198
+ {
199
+ "@id": "local:agent2",
200
+ "@type": "prov:Agent",
201
+ "foaf:mbox": "b@mail.com"
202
+ },
203
+ {
204
+ "@id": "local:agent3",
205
+ "@type": "prov:Agent",
206
+ "foaf:mbox": "c@mail.com"
207
+ }
208
+ ]
209
+ }"""
210
+ )
211
+ found_agents = ontolutils.query(self.Agent, source=__this_dir__ / 'agent.jsonld',
212
+ limit=2)
213
+ self.assertEqual(len(found_agents), 2)
214
+ self.assertEqual(found_agents[0].mbox, 'a@mail.com')
215
+ self.assertEqual(found_agents[1].mbox, 'b@mail.com')
216
+
217
+ # find none:
218
+
219
+ @ontolutils.namespaces(prov="https://www.w3.org/ns/prov#",
220
+ foaf="http://xmlns.com/foaf/0.1/")
221
+ @ontolutils.urirefs(Mything='prov:Mything')
222
+ class Mything(ontolutils.Thing):
223
+ pass
224
+
225
+ found_Mything = ontolutils.query(Mything, source=__this_dir__ / 'agent.jsonld')
226
+ self.assertEqual(len(found_Mything), 0)
227
+
228
+ found_Mything = ontolutils.dquery(subject="prov:Mything",
229
+ source=__this_dir__ / 'agent.jsonld',
230
+ context=None
231
+ )
232
+ self.assertEqual(len(found_Mything), 0)
233
+
184
234
  def tearDown(self):
185
235
  pathlib.Path(__this_dir__ / 'agent.jsonld').unlink(missing_ok=True)
186
236
  pathlib.Path(__this_dir__ / 'agents.jsonld').unlink(missing_ok=True)
File without changes
File without changes
File without changes
File without changes