gpt4 book ai didi

python - OWL 2 中的 SWRL 规则

转载 作者:行者123 更新时间:2023-12-04 17:12:12 30 4
gpt4 key购买 nike

我目前正在发现 Owlready 库的所有可能性。
现在我正在尝试处理一些 SWRL 规则,到目前为止一切顺利,但我有一点被卡住了。
我已经在我的本体中定义了一些规则,现在我想查看所有结果(因此,一切都是从规则中推断出来的)。
例如,如果我有一个规则has_brother(David, ?b) ^ has_child(?b, ?s) -> has_uncle(?s, David)大卫有两个兄弟,约翰和皮特,约翰的 child 是安娜,皮特的 child 是西蒙,我也想看到类似的东西: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像预期的那样工作,叔叔规则也一样。当然,reasoner 必须先运行。
    更新 : 我在 this Jupyter notebook 中发布了解决方案(其中还包含执行的输出)。

    关于python - OWL 2 中的 SWRL 规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69224096/

    30 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com