# source: https://owlready2.readthedocs.io/en/latest/intro.html#short-example-what-can-i-do-with-owlready
from owlready2 import Thing, FunctionalProperty, Imp, sync_reasoner_pellet, get_ontology, SymmetricProperty
import owlready2 as owl2
# the url currently has no meaning
onto = get_ontology("http://example.org/test.owl#")
# provide namespace for classes via `with` statement
with onto:
class Person(Thing):
pass
class Gender(Thing):
pass
class Woman(Person):
pass
class Man(Person):
pass
# syntax ‘domain >> range’ works by overloading the >> Operator to return an `ObjectProperty`
# A functional property is a property that has a single value for a given instance.
# Functional properties are created by inheriting the FunctionalProperty class.
class hasName(Person >> str, FunctionalProperty): pass
class hasGender(Person >> Gender, FunctionalProperty): pass
class hasChild(Person >> Person):
pass
class hasParent(Person >> Person):
pass
class hasFather(hasParent):
pass
class hasMother(hasParent):
pass
class isParentOf(Person >> Person):
pass
class isMotherOf(isParentOf):
inverse_property = hasMother
class isFartherOf(isParentOf):
inverse_property = hasFather
class hasSibling(Person >> Person, SymmetricProperty):
pass
# sub-properties
class hasBrother(hasSibling):
pass
class hasSister(hasSibling):
pass
class hasAunt(Person >> Person):
pass
class hasUncle(Person >> Person):
pass
male_g = Gender()
female_g = Gender()
rule = Imp()
rule.set_as_rule("""Person(?p), hasBrother(?p, ?b) -> Man(?b)""")
rule2 = Imp()
rule2.set_as_rule("""Person(?p), hasParent(?p, ?r), hasBrother(?r, ?b) -> hasUncle(?p, ?b)""")
fred = Person()
legolas = Person()
alice = Person(hasName="alice", hasBrother=[fred])
bob = Person(hasName="bob", )
bob.hasBrother.append(legolas)
susan = Person(hasMother=[alice], hasFather=[bob])
sync_reasoner_pellet(infer_property_values=True, infer_data_property_values=True)
fred.is_a # this is a consequence of rule1
legolas in susan.hasUncle # this is a consequence of rule2