这是我的解决方案:
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
果然大叔规矩也行。当然,推理器必须先运行。
更新:我在这个 Jupyter 笔记本中发布了解决方案(其中还包含执行的输出)。