bilal.murat
bilal.murat

Reputation: 13

In clipspy, how can I get asserted fact from a python class or def function?

I want to create an expert system program to do risk analysis in occupational safety. I code this program in CLIPS. To create GUI and to add new attribute it, I want to recode in Python with clipspy and tkinter libraries. In this program, according to answer which gotten from user next question will decide and ask. because of having a lot of questions, I need more function to be defined to assert facts which can be used in other defrule functions. But, when I use assert_fact" function in a class or def function, my next defrule function cannot get it to be invoked. In this context, I need your help about how to use assert_fact function in Python class or def function. you can see one example below:

olasılık = """ (deftemplate olasılık
        (slot ad (type SYMBOL))
        (slot deger (type NUMBER)))"""
env.build(olasılık)
def sonuç():
   print("değer 1 dopru")
   sr.assert_fact(ad=clips.Symbol("olasılık1"), deger=10)
   
def rule():

    rule = """(defrule rule
        (olasılık 
             (ad ?ad)(deger ?deger))
        =>
        (printout t " deneme yapıyorum.     " ?ad "   adıdır   " (* 10 ?deger) crlf))"""
    env.build(rule)

In this code I hope to work defrule function. But it does not.

To make it more understandable, I put whole code below:

import clips
import tkinter as tk



master = tk.Tk()
master.title("KTD Risk Analizi")
master.geometry("500x300")
frame1 = tk.Frame(master, bd="20", bg="lightblue", width="600", height="600")
frame1.pack(fill="both", expand=True)
frame2 = tk.Frame(master, bd="20", bg="lightblue", width="600", height="600")
frame2.pack(fill="both", expand=True)
frame3 = tk.Frame(master, bd="20", bg="lightblue", width="600", height="600")
frame3.pack(fill="both", expand=True)

env = clips.Environment()

def severity():
    severity = """(deftemplate severity
                (slot name (type SYMBOL))
                (slot number (type NUMBER)))"""
    env.build(severity)

def probolity():
    probolity = """(deftemplate probolity
                (slot name (type SYMBOL))
                (slot number (type NUMBER)))"""
    env.build(probolity)
def find_template1():
        siddet = env.find_template("severity")
        return siddet
def find_template2():
        olasilik = env.find_template("probolity")
        return olasilik

var = tk.IntVar()

class Qustion4():
    sonuc = 0
    def __init__(self):
        self.L1 = tk.Label(frame1, text="Araç trafik yolları belirlenmiş mi?", justify=tk.LEFT, padx=20)
        self.L1.grid(row=0, column=0)
        self.evet = tk.Button(frame1, text="evet", command=self.answer_yes)
        self.evet.grid(row=0, column=1)
        self.hayir = tk.Button(frame1, text="hayır", command=self.answer_no)
        self.hayir.grid(row=0, column=2)


    def click(self):
        Calculation4()
        self.sonuc = var.get()
        return self.sonuc

    def answer_yes(self):
        self.L1["state"] = "disable"
        self.evet["state"] = "disable"
        self.hayir["state"] = "disable"
        self.etiket2 = tk.Label(frame2, text="Ne sıklıkla kullanılıyor?", justify=tk.CENTER, padx=40)
        self.etiket2.grid(row=1, column=0)
        self.az = tk.Radiobutton(frame2, text="Az", variable=var, value=1)
        self.az.grid(row=1, column=1)
        self.orta = tk.Radiobutton(frame2, text="Orta", variable=var, value=2)
        self.orta.grid(row=1, column=2)
        self.cok = tk.Radiobutton(frame2, text="Çok", variable=var, value=3)
        self.cok.grid(row=1, column=3)
        self.SSoru = tk.Button(frame2, text=" Sonraki Soru", state="active", command=self.click)
        self.SSoru.grid(row=1, column=4)

    def answer_no(self):
        self.evet["state"] = "disable"
        self.hayir["state"] = "disable"
        self.SSoru = tk.Button(frame1, text=" Sonraki Soru", state="active", command=self.click)
        self.SSoru.grid(row=0, column=3)


    def result_deploy (self):
        if self.sonuc == 0:
            print("check Radiobutton function", self.sonuc)

        elif self.sonuc == 1:
            print("değer bir olduğunda çalışacak", self.sonuc)
            r1 =self.siddet.assert_fact(name=clips.Symbol("risk1"), number=3)
            o1 = self.olasilik.assert_fact(name=clips.Symbol("olasılık1"), number=4)

        elif self.sonuc == 2:
            print(" değer iki olduğunda çalışacak", self.sonuc)
            r1 =self.siddet.assert_fact(name=clips.Symbol("risk1"), number=3)
            o1 = self.olasilik.assert_fact(name=clips.Symbol("olasılık1"), number=3.5)

        elif self.sonuc == 3:
            print("değer üç olduğunda çalışacak", self.sonuc)
            r1 = self.siddet.assert_fact(name=clips.Symbol("risk1"), number=3)
            o1 = self.olasilik.assert_fact(name=clips.Symbol("olasılık1"), number=2)
        else:
            print("code does not work, check system")

class Calculation4():
    getattr(Qustion4, "r1", "o1")
    def hesap4(self):
        hesaplamaSoru4 = """(defrule hesaplamaSoru4

           (severity (name ?risk1)(number ?rdeger1)
           (probolity (name ?olasılık1)(number ?odeger1)

           =>
           (if (or (>= (* ?rdeger1 ?odeger1) 10)(> ?odeger1 3.5))
           then 
           (printout t "   **** ****************************************************    " crlf)
           (printout t "**** Araçlara takılma sonucu tökezleme kazaları için Risk Öncelik Skoru  : " (round (*  ?rdeger1 ?odeger1))
            "dur." crlf) 
           (printout t "**** Güvenli iş yeri ortamı sağlamak için aşağıda belirtilen tedbirleri alınız   : " crlf) 
           (printout t "**** Kullanılan araçların genişliğine uygun olarak sadece araçlar için kullanılacak yollar tespit 
           edilmeli" crlf)
           (printout t "**** Yükleme ekipmanlarının (forklift, transpalet, vb.) harekat alanlarına malzeme istiflenmemeli" crlf)
           (printout t "**** Araç yolları üzerinde çukur, çöküntü ve gevşek zemin olmamalı" crlf)
           (printout t "**** Yol üzerindeki muhtemel tehlikeler, rampa, kavşak, kör köşeler gibi, işaretler ile 
           belirginleştirilmelidir." crlf )
           (printout t "**** Araç yolları taşınamsı muhtemel yükleri taşıyabilecek zeminlerden geçmeli. "crlf)
           (printout t "   **** ****************************************************    " crlf)
           else 
           (printout t "   **** ****************************************************    " crlf)
           (printout t "**** Araçlara takılma sonucu tökezleme kazaları için Risk Öncelik Skoru  : 
           " (round (*  ?rdeger1 ?odeger1)) " 'dur." crlf)
           (printout t "**** Güvenli iş yeri için gerekli şartlar sağlanmış gözüküyor. Mevcut Durumu Koruyunuz." crlf )
           (printout t "   **** ****************************************************    " crlf)))
           """
        env.build(hesaplamaSoru4)

soru4 = Qustion4()

env.run()
master.mainloop()

Upvotes: 1

Views: 233

Answers (1)

noxdafox
noxdafox

Reputation: 15060

It is not fully clear to me what the question is and you are not providing a full working example so I hope this will answer the question.

Your main handler is the clips.Environment class. Objects from this class represent a CLIPS engine instance and allow to define or load constructs.

env = clips.Environment()

# Define a Fact Template
env.build("""
(deftemplate example_fact
  (slot example_slot))
""")

# Define a Rule
env.build("""
(defrule example_rule
  (example_fact (example_slot ?value))
  =>
  (println t ?v))
""")

A fact is defined by its template which acts as factory object.

Therefore in order to assert a fact, you need to retrieve its template object and use it to assert a new fact.

# Retrieve the template of the fact you want to assert
template = env.find_template('example_fact')

# Assert 3 different `example_fact`
template.assert_fact(example_slot="foo")
template.assert_fact(example_slot="bar")
template.assert_fact(example_slot="baz")

If you want to wrap the logic of asserting facts within a Python function, you can do the following.

def assert_example_fact(slot_value):
    template = env.find_template('example_fact')
    template.assert_fact(example_slot=slot_value)

assert_example_fact("foo")
assert_example_fact("bar")
assert_example_fact("baz")

If you want to generalize the above function:

def assert_fact(template_name, **slots):
    template = env.find_template(template_name)
    template.assert_fact(**slots)

assert_fact('example_fact', example_slot="foo")
assert_fact('different_fact', different_slot="bar", another_slot="baz")

EDIT: your rule is incorrect.

(defrule hesaplamaSoru4
  (severity (name ?risk1)(number ?rdeger1)       ; <--- Missing closing parentheses
  (probolity (name ?olasılık1)(number ?odeger1)  ; <--- Missing closing parentheses

I would recommend to test your CLIPS logic separately using the CLIPS REPL or iCLIPS before bundling it into your program.

Upvotes: 1

Related Questions