我目前正在探索 Owlready 库的所有可能性。 现在我正在尝试处理一些 SWRL 规则,到目前为止一切进展顺利,但我陷入了困境。
我已经在本体中定义了一些规则,现在我想查看所有结果(因此,从规则推断出的所有内容)。
例如,如果我有一条规则
has_brother(David, ?b) ^ has_child(?b, ?s) -> has_uncle(?s, David)
大卫有两个兄弟,约翰和皮特,约翰的孩子是安娜,皮特的孩子是西蒙,我也想看到类似的东西:
has_brother(David, John) ^ has_child(John, Anna) -> has_uncle(Anna, David)
has_brother(David, Pete) ^ has_child(Pete, Simon) -> has_uncle(Simon, David)
这有可能吗? 我想也许如果我运行推理机,我可以在其输出中看到它,但我在任何地方都找不到它。
我感谢任何可能的帮助!
这是我的解决方案:
import owlready2 as owl
onto = owl.get_ontology("http://test.org/onto.owl")
with onto:
class Person(owl.Thing):
pass
class has_brother(owl.ObjectProperty, owl.SymmetricProperty, owl.IrreflexiveProperty):
domain = [Person]
range = [Person]
class has_child(Person >> Person):
pass
class has_uncle(Person >> Person):
pass
rule1 = owl.Imp()
rule1.set_as_rule(
"has_brother(?p, ?b), has_child(?p, ?c) -> has_uncle(?c, ?b)"
)
# This rule gives "irreflexive transitivity",
# i.e. transitivity, as long it does not lead to has_brother(?a, ?a)"
rule2 = owl.Imp()
rule2.set_as_rule(
"has_brother(?a, ?b), has_brother(?b, ?c), differentFrom(?a, ?c) -> has_brother(?a, ?c)"
)
david = Person("David")
john = Person("John")
pete = Person("Pete")
anna = Person("Anna")
simon = Person("Simon")
owl.AllDifferent([david, john, pete, anna, simon])
david.has_brother.extend([john, pete])
john.has_child.append(anna)
pete.has_child.append(simon)
print("Uncles of Anna:", anna.has_uncle) # -> []
print("Uncles of Simon:", simon.has_uncle) # -> []
owl.sync_reasoner(infer_property_values=True)
print("Uncles of Anna:", anna.has_uncle) # -> [onto.Pete, onto.David]
print("Uncles of Simon:", simon.has_uncle) # -> [onto.John, onto.David]
备注:
有人可能认为
has_brother
是
has_brother(A, B)
⇒ has_brother(B, A)
has_brother(A, B) + has_brother(B, C) ⇒ has_brother(A, C)
但是,只有当“唯一名称假设”成立时,传递性才成立。否则 A
可能与
C
是同一个人,这与非自反性相冲突。因此我使用了这种“弱传递性”的规则。一旦,has_brother
按预期工作,叔叔规则也一样。当然,推理机必须先运行。
更新我已了解并测试过。
我在 owlready2 中不明白的是为什么我不能在现有本体(加载的 rdfxml 文件)上“应用”swrl 规则
我尝试在工作目录中添加一个
onto.owl
(并添加一个
owl.onto_path.append("./")
),这个onto.owl
包含更多“人”和更多关系,但没有办法让它工作。如果有人发布一个示例,阅读本体文件,然后对其应用规则,我会很高兴。
再见