| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
import logging |
| 21 |
|
| 22 |
import pyfactxx |
| 23 |
import rdflib |
| 24 |
|
| 25 |
from .parser import parse |
| 26 |
from .query import QueryStore |
| 27 |
|
| 28 |
logger = logging.getLogger(__name__) |
| 29 |
|
| 30 |
class Coras: |
| 31 |
def __init__(self): |
| 32 |
self._reasoner = pyfactxx.Reasoner() |
| 33 |
self._graph = rdflib.ConjunctiveGraph() |
| 34 |
|
| 35 |
store = QueryStore(self._graph, self._reasoner) |
| 36 |
self._query_graph = rdflib.ConjunctiveGraph(store=store) |
| 37 |
|
| 38 |
@property |
| 39 |
def reasoner(self): |
| 40 |
return self._reasoner |
| 41 |
|
| 42 |
def load(self, f, format='xml'): |
| 43 |
""" |
| 44 |
Load an ontology from a file. |
| 45 |
|
| 46 |
:param f: File object with an ontology data. |
| 47 |
:param format: Format of the data. |
| 48 |
""" |
| 49 |
self._graph.parse(f, format=format) |
| 50 |
|
| 51 |
def query(self, *args, **kw): |
| 52 |
processed = set() |
| 53 |
|
| 54 |
need_asserted = 'scope' not in kw or kw['scope'] in ('asserted', 'both') |
| 55 |
need_inferred = 'scope' not in kw or kw['scope'] in ('inferred', 'both') |
| 56 |
|
| 57 |
if 'scope' in kw: |
| 58 |
del kw['scope'] |
| 59 |
|
| 60 |
for item in self._graph.query(*args, **kw): |
| 61 |
processed.add(item) |
| 62 |
if need_asserted: |
| 63 |
yield item |
| 64 |
|
| 65 |
if need_inferred and self._reasoner.is_realised(): |
| 66 |
for item in self._query_graph.query(*args, **kw): |
| 67 |
if item not in processed: |
| 68 |
yield item |
| 69 |
|
| 70 |
def parse(self): |
| 71 |
logger.debug('parse graph') |
| 72 |
parse(self._graph, self._reasoner) |
| 73 |
|
| 74 |
def realise(self): |
| 75 |
logger.debug('reasoner classification') |
| 76 |
self._reasoner.classify() |
| 77 |
logger.debug('reasoner realisation') |
| 78 |
self._reasoner.realise() |
| 79 |
logger.debug('reasoner realisation done') |
| 80 |
|
| 81 |
def as_labels(graph, items): |
| 82 |
""" |
| 83 |
Replace URI values in a query result with RDF labels. |
| 84 |
|
| 85 |
:param graph: RDFLib graph having label information. |
| 86 |
:param items: Query results to be processed. |
| 87 |
""" |
| 88 |
items = (tuple(as_label(graph, v) for v in row) for row in items) |
| 89 |
yield from items |
| 90 |
|
| 91 |
def as_label(graph, value): |
| 92 |
""" |
| 93 |
Replace URI value with a RDF label. |
| 94 |
|
| 95 |
:param graph: RDFLib graph having label information. |
| 96 |
:param value: URI value to be replaced. |
| 97 |
""" |
| 98 |
if isinstance(value, rdflib.Literal): |
| 99 |
label = value |
| 100 |
else: |
| 101 |
labels = graph.objects(rdflib.URIRef(value), rdflib.RDFS.label) |
| 102 |
label = next(labels, value) |
| 103 |
return label |
| 104 |
|
| 105 |
|
| 106 |
|