OWL2中的SWRL规则

2024-05-18 17:51:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在探索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)

这有可能吗? 我想如果我运行reasoner,我可以在它的输出中看到它,但是我在任何地方都找不到它

我感谢任何可能的帮助


Tags: child规则本体孩子可能性johnhasdavid
1条回答
网友
1楼 · 发布于 2024-05-18 17:51:51

这是我的解决方案:



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按预期工作,叔叔规则也会这样做。当然,推理者必须先运行

更新:我在this Jupyter notebook中发布了解决方案(其中还包含执行的输出)

相关问题 更多 >

    热门问题