pythonexpert-system

Expert system in Python with certain order of questions


I need to create expert system and I have one question. I'm using experta from Python and 3.8.0 is my version of Python interpreter in PyCharm. Here is my simple code:

from experta import *

class Greetings(KnowledgeEngine):
    @DefFacts()
    def _initial_action(self):
        yield Fact(action="greet")
        yield Fact(action="info")

    @Rule(Fact(action='greet'),
          NOT(Fact(name=W())))
    def ask_name(self):
        self.declare(Fact(name=input("What's your name? ")))

    @Rule(Fact(action='greet'),
          NOT(Fact(location=W())))
    def ask_location(self):
        self.declare(Fact(location=input("Where are you? ")))

    @Rule(Fact(action='greet'),
          Fact(name=MATCH.name),
          Fact(location=MATCH.location))
    def greet(self, name, location):
        print("Hi %s! How is the weather in %s?" % (name, location))

    @Rule(Fact(action='info'),
          NOT(Fact(number=W())))
    def ask_number(self):
        self.declare(Fact(number=input("What's your number? ")))

    @Rule(Fact(action='info'),
          NOT(Fact(height=W())))
    def ask_height(self):
        self.declare(Fact(height=input("Where are you? ")))

    @Rule(Fact(action='info'),
          Fact(number=MATCH.number),
          Fact(height=MATCH.height))
    def info(self, number, height):
        print("Your phone number is %s! Your basic height is %s." % (number, height))


if __name__ == "__main__":
    # start_analysis()
    system = Greetings()
    while 1:
        system.reset()
        system.run()
        print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
        print("Do you want to talk again?")
        if input() == 'no':
            exit()

I need some intermediate conclusions and then overall. It should be in certain order. So, at first I want to appear questions about name and location and then number and height. How can I modify my code to receive certain order? Do I need something like salience?


Solution

  • Salience allows to do this. This value, by default 0, determines the priority of the rule in relation to the others. Rules with a higher salience will be fired before rules with a lower one. That how we can order rules in our own way.