Here is a small ontology,称为wildlife.owl
,由Protégé创建,其中我具有类animal
,carnivore
,herbivore
,lion
,giraffe
和个人Léo
(lion
) ,Gigi
(giraffe
)和Giginou
(也是giraffe
)。在本体中,我仅声明lion ⊏ carnivore ⊏ animal
。
[当我在Protégé的DL查询选项卡中询问animal
的实例时,除其他外,我得到Léo
(这是lion
,因此是carnivore
,因此是animal
)。
但是当我编写以下SPARQ查询时:
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX owl: <http://www.w3.org/2002/07/owl#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
PREFIX me: <file:wildlife.owl#>
SELECT ?b
WHERE { ?b rdf:type me:animal }
我没有任何实例。当我用me:animal
替换me:carnivore
时,结果相同。只有当我用me:lion
替换它时,才得到所需的结果Léo
。
为什么DL Query进行推理(允许我获得Léo
作为animal
类的实例)而不是SPARQL查询?
我该怎么做才能在SPARQL查询中获得相同的结果?
我的下一个问题与Python有关:当我使用Owlreader2和RDFlib发送SPARQL查询时,仍然没有结果:
from owlready2 import *
from rdflib import *
onto = get_ontology("wildlife.owl").load()
sync_reasoner([onto])
graph = default_world.as_rdflib_graph()
print(list(graph.query_owlready("""
PREFIX rdf-syntax: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX me: <file:wildlife.owl#>
SELECT ?b WHERE {
?b rdf-syntax:type me:animal .
}""")))
如何使用OWL Reasoner获得此查询?
[在调用推理机时,Owlready不会保留琐事推理,例如is-可及性(例如,狮子是动物的事实。]]
对于简单的推论,您应该使用SPARQL,如下面的示例所示。感谢SubclassOf * SPARQL语法(*表示可传递性),?any_animal变量包含所有动物子类(包括动物本身)。然后,我们采用?any_animal类的任何实例。
from owlready2 import *
from rdflib import *
onto = get_ontology("http://test.org/wildlife.owl")
with onto:
class animal(Thing): pass
class carnivore(animal): pass
class lion(carnivore): pass
lion()
default_world.graph.dump()
graph = default_world.as_rdflib_graph()
print(list(graph.query_owlready("""
PREFIX rdf-syntax: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX me: <http://test.org/wildlife.owl#>
SELECT ?b WHERE {
?any_animal <http://www.w3.org/2000/01/rdf-schema#subClassOf>* me:animal .
?b rdf-syntax:type ?any_animal .
}""")))