Mixing Python, OWL, SWRL and Reasoning

Posted by cknoll on
URL: http://owlready.306.s1.nabble.com/Mixing-Python-OWL-SWRL-and-Reasoning-tp2653.html

Hello,

on [1] https://owlready2.readthedocs.io/en/latest/mixing_python_owl.html it is documented how to mix Python and OWL.

I think this is already very useful, but I want to to a step further: I want to reason over SWRL rules which evaluate data_properties which are defined by (simple) Python methods.


To demonstrate what I want I adapted the example from [1]: I added a class "ExpensiveDrug" and a SWRL rule which should classify a Drug as expensive depending on the return value of get_per_tablet_cost.


However I cannot construct the rule that way. I get  ValueError: Cannot find entity 'get_per_tablet_cost'!

Is it even possible to do what I want (i.e. software defined data properties)?


from owlready2 import *
onto = get_ontology("http://test.org/onto.owl")


with onto:
    class Drug(Thing):
        def get_per_tablet_cost(self):
            return self.cost / self.number_of_tablets

    class has_for_cost(Drug >> float, FunctionalProperty):
        python_name = "cost"

    class has_for_number_of_tablets(Drug >> int, FunctionalProperty):
        python_name = "number_of_tablets"
       
    class ExpensiveDrug(Drug):
        pass

my_drug1 = Drug(cost=10.0, number_of_tablets=5)
my_drug2 = Drug(cost=500.0, number_of_tablets=5)
print(my_drug1.get_per_tablet_cost()) # -> 2
print(my_drug2.get_per_tablet_cost()) # -> 100

with onto:
    rule = Imp()
    rule.set_as_rule(
        "Drug(?d), get_per_tablet_cost(?d, ?c), greaterThanOrEqual(?c, 10) -> ExpensiveDrug(?d)"
    )


Best,
Carsten