def __init__(self, rules_files: List[Text], functions_package_name: Text = None): """ :param rules_files: List of files containing the Clips definition of the rules. Files are provided following their intended loading order. For instance, if file_2 uses constructs defined in file_1 then the following list must be provided [file_1, file_2]. :param functions_package_name: The name of the package containing the functions that will be used in the rules. """ super().__init__() self._tic("__init__") self.rules_files = rules_files self.env = Environment() if functions_package_name is not None: self.functions_package_name = functions_package_name for f in get_functions_from_module_name(functions_package_name): logger.info("Defining function {}".format(f.__name__)) self.env.define_function(f) for rf in rules_files: self.env.load(rf) # This is the total number of rules fired during the execution of the reason() method. self.num_fires = 0 self._toc("__init__") logger.info("Rules engine created in {0:.3f} ms".format( self._tictoc("__init__") * 1000))
def home(): res = {} if 'file' not in request.files: res['status'] = 'ERROR' res['msg'] = 'No file submitted' return cors((jsonify(res))) file = request.files['file'] # if user does not select file, browser also # submit an empty part without filename if not allowed_file(file.filename): res['status'] = 'ERROR' res['msg'] = 'Only png, jpg, and jpeg format allowed' return cors(jsonify(res)) else: filename = secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) results = detection.detectImage('uploads/' + filename) env = Environment() env.load('backend/shape.clp') shape.insert_angle(env, results) res['activations'] = shape.get_activations(env) env.run() res['rules'] = shape.get_rules(env) res['facts'] = shape.get_facts(env) return cors(jsonify(res))
def setUp(self): self.env = Environment() self.env.build(DEFMETHOD) self.env.build(DEFGENERIC1) self.env.build(DEFGENERIC2) self.env.build(DEFFUNCTION1) self.env.build(DEFFUNCTION2)
def run(clp_file: str, facts, board_size): env = Environment() env.batch_star(clp_file) for fact in facts: env.assert_string(fact) env.run() print("Run clips done") history = [generate_init_state(board_size)] logs = [] log = [] state = generate_init_state(board_size) for fact in env.facts(): log.append(str(fact)) if "bomb" in str(fact) and check(fact, BOMBPATTERN): row, col = parse(fact, BOMBPATTERN) state = generate_history_state(state, row, col, 1) logs.append(log) history.append(state) log = [] if "not_bomb" in str(fact) and check(fact, NOTBOMBPATTERN): row, col = parse(fact, NOTBOMBPATTERN) state = generate_history_state(state, row, col, 0) return history, logs
def __init__(self, config: Dict) -> None: self.config = config self.is_shape_init = False self.static_env = Environment() self.env = [] self.shape_fact = '' self.run_result = [] logging.getLogger('clips/load').info('Loading clips file {}'.format(config['kbs_file'])) self.static_env.load(config['kbs_file'])
def run(config_file): config = toml.loads(config_file) # initialize sensors; # - temperature/humidity # - soil moisture # - RTC clock # - LCD display # - Buzzer # TODO env = Environment() env.load(config['clips_file']) starttime = time() while True: # reset CLIPS. Set the fact base to its initial state env.reset() # TODO: read data from sensors and assert facts env.assert_string(f'(humidity-is {humidity})') env.assert_string(f'(temperature-is {temperature})') env.assert_string(f'(time-of-day-is {time_of_day})') env.assert_string(f'(soil-has-moisture {has_moisture})') # run clips env.run() # get output. should we water plant or not? water_plant = None for fact in env.facts(): if fact.template.name == 'water-plant': water_plant = fact[0] == 'yes' if water_plant is None: print("Something wrong in CLIPS rules") else: # TODO: display on LCD and sound buzzer # execute above code every x seconds sleep(config['run_every'] - ((time() - starttime) % config['run_every'])) if __name__ == "__main__": try: config_file = sys.argv[1] except IndexError: print("Need to pass config file") exit(1) try: run(config_file) except KeyboardInterrupt: print("Terminating...")
def setShape(self, shape_list: List[ShapeData]) -> None: self.is_shape_init = False self.shape_list = shape_list self.env = [Environment() for _ in range(len(shape_list))] for idx, shape in enumerate(shape_list): logging.getLogger('clips/load').debug('Init new shape') self.env[idx].load(self.config['kbs_file']) self.env[idx].reset() self.initShapeFact(shape, self.env[idx]) self.is_shape_init = True self.shape_fact = self.genFacts()
def setUp(self): self.value = None self.env = Environment() router = LoggingRouter() router.add_to_environment(self.env) self.env.build(DEFCLASS) self.env.build(DEFFUNCTION) self.env.build(DEFRULE_FACT) self.env.build(DEFRULE_INSTANCE) self.env.define_function(python_function) self.env.define_function(self.python_method) self.env.define_function(self.python_fact_method)
def callCLIPS(list_facts): env = Environment() #rule env.define_function(callRule) env.define_function(callFact) env.load('rule.txt') print(list_facts) #fact for fact in list_facts : env.assert_string(fact) env.run()
def setUp(self): self.values = [] self.env = Environment() self.router = LoggingRouter() self.router.add_to_environment(self.env) self.env.define_function(python_function) self.env.define_function(python_function, name='python-function-renamed') self.env.define_function(python_types) self.env.define_function(self.python_method) self.env.define_function(self.python_fact_method) self.env.build(DEFCLASS) self.env.build(DEFFUNCTION) self.env.build(DEFRULE_FACT) self.env.build(DEFRULE_INSTANCE)
from clips import Environment, Symbol environment = Environment() # assert a fact as string environment.assert_string('(a-fact)') # retrieve a fact template template = environment.find_template('a-fact') # create a new fact from the template fact = template.new_fact() # implied (ordered) facts are accessed as lists fact.extend((7, 2)) # assert the fact within the environment fact.assertit() # execute the activations in the agenda environment.run() for fact in environment.facts(): print(fact)
def __init__(self, clp_file_name): self.environment = Environment() self.get_result = [] self.facts = [] #ini array2D of string self.environment.load(clp_file_name) self.environment.reset()
def setUp(self): self.env = Environment() self.env.build(DEFTEMPLATE)
from flask import Flask, render_template, jsonify, url_for, request from clips import Environment # Define the clips environment clips = Environment() # Load the Project Expert System clips.load("project.clp") # Define the app of web server app = Flask(__name__) boolAnswer = False def changeUIState(): # Get the state-list. factlist = clips.eval("(find-all-facts ((?f state-list)) TRUE)") if len(factlist) == 0: return jsonify(question="Error in the website and we don't know why") currentID = factlist[0]["current"] print("currentID1 :", currentID) # Get the current UI state. factlist = clips.eval("(find-all-facts ((?f UI-state)) (eq ?f:id %s))" % currentID) if len(factlist) == 0: return jsonify(question="Error in the website and we don't know why") # Determine the Next/Prev button states. state = factlist[0]["state"] if state == "final":
def setUp(self): self.env = Environment() router = LoggingRouter() router.add_to_environment(self.env) for defclass in DEFCLASSES: self.env.build(defclass)
def detection(file_name): e = Environment() # Pilih rule e.load('geometri.clp') # Load image img = cv2.imread(file_name, cv2.IMREAD_GRAYSCALE) _, threshold = cv2.threshold(img, 240, 255, cv2.THRESH_BINARY) # Buat contours contours, _ = cv2.findContours(threshold, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # Pilih font font = cv2.FONT_HERSHEY_COMPLEX for cnt in contours[1:]: # Aproksimasi sisi polygon approx = cv2.approxPolyDP(cnt, 0.01 * cv2.arcLength(cnt, True), True) # Gambar contour cv2.drawContours(img, [approx], 0, (0), 5) #cv2.imshow("contours", img) cv2.imwrite("result.jpg", img) # Get x, y untuk text x = approx.ravel()[0] y = approx.ravel()[1] # print(cv2.arcLength(cnt, True)) for a in approx: print("(titik " + str(a[0][0]) + " " + str(a[0][1]) + ")") for i in getSisi(approx): print(i) for i in getSudut(approx): print(i) # Klasifikasi berdasarkan jumlah sisi print(len(approx)) if len(approx) == 3: # Assert fakta berupa titik shape e.assert_string(getEdgeFact(getSisi(approx))) e.assert_string(getAngleFact(getSudut(approx))) e.assert_string('(titik 3)') cv2.putText(img, "Segitiga", (x, y), font, 1, (0)) elif len(approx) == 4: e.assert_string(getEdgeFact(getSisi(approx))) e.assert_string(getAngleFact(getSudut(approx))) e.assert_string('(titik 4)') cv2.putText(img, "Persegi", (x, y), font, 1, (0)) elif len(approx) == 5: e.assert_string(getEdgeFact(getSisi(approx))) e.assert_string('(titik 5)') cv2.putText(img, "Segi Lima", (x, y), font, 1, (0)) elif len(approx) == 6: e.assert_string(getEdgeFact(getSisi(approx))) e.assert_string('(titik 6)') cv2.putText(img, "Segi Enam", (x, y), font, 1, (0)) # Print initial facts print("\nInitial Facts :") list_fact = '' for fact in e.facts(): list_fact += str(fact) + '\n' print(fact) outputFile = open("fakta.txt", "w") outputFile.write(list_fact) outputFile.close() print("\nAgenda :") list_agenda = '' for agenda in e.activations(): list_agenda += str(agenda) + '\n' print(agenda) outputFile = open("hit_rules.txt", "w") outputFile.write(list_agenda) outputFile.close() # Kalo mau run sekali, pake e.run(1) # Kalo mau run sampai habis, pake e.run() e.run() # Print all facts at the end print("\n\nFinal Facts :") list_fact = '' for fact in e.facts(): list_fact += str(fact) + '\n' print(fact) outputFile = open("matched_facts.txt", "w") outputFile.write(list_fact) outputFile.close()
def __init__(self): self.environment = Environment() # load constructs into the environment self.environment.load('minesweeper.clp') self.environment.reset()
def __init__(self, clps=[]): self.env = Environment() for clp in clps: self.env.load(clp)
def initialize_env(self, clp_file_name): self.environment = Environment() self.environment.load(clp_file_name)
def __init__(self, configuration): self.environment = Environment() self.configuration = configuration
def setup(clp_file, input_file): list_bomb = [] with open(input_file, "r") as f: board_size = int(f.readline()) n_bombs = int(f.readline()) for i in range(n_bombs): x, y = map(int, f.readline().split(",")) list_bomb.append((x, y)) list_facts = generate_facts(board_size, list_bomb) print("board size:", board_size) print("total bombs:", n_bombs) print() env = Environment() env.batch_star(clp_file) for fact in list_facts: env.assert_string(fact) env.run() print("Run clips done") print() list_fact_bomb = [] for bomb in list_bomb: list_fact_bomb.append(f"(row {bomb[0]}) (col {bomb[1]})") correct_bomb = [] false_bomb = [] not_bomb_count = 0 total_count = -2 facts_list = [] print("List fakta : ") for fact in env.facts(): facts_list.append(fact) if "bomb" in str(fact): if "not" not in str(fact): print("fakta :", fact) tmp = str(fact).split("(bomb ") if len(tmp) > 1: if tmp[1][:-1] in list_fact_bomb: correct_bomb.append(tmp[1][:-1]) else: false_bomb.append(tmp[1][:-1]) total_count += 1 if "not_bomb" in str(fact): not_bomb_count += 1 # TODO move to minesweeper clp if total_count + not_bomb_count != board_size * board_size: for bomb in list_fact_bomb: if bomb not in correct_bomb: row_col = f"(row {bomb.split(')')[0][-1]}) (col {bomb.split(')')[1][-1]})" env.assert_string(f"(bomb {row_col})") correct_bomb.append(row_col) total_count += 1 print("not bomb count:", not_bomb_count) print("bomb count:", total_count - not_bomb_count) print("correct bomb:", len(correct_bomb)) for bomb in correct_bomb: print(bomb) print("false bomb:", len(false_bomb)) for bomb in false_bomb: print(bomb) print("missed bomb:") for bomb in list_fact_bomb: if bomb not in correct_bomb: print(bomb)
def setUp(self): self.env = Environment() self.env.add_router(LoggingRouter()) for defclass in DEFCLASSES: self.env.build(defclass)
def setUp(self): self.env = Environment() self.env.build(DEFGLOBAL)
def __init__(self): self.env = Environment()
self.board_open_asserted[i][j] = True if __name__ == "__main__": size = int(input()) list_bomb = [] list_flag = [] for i in range(int(input())): coor = tuple(map(int, input().split(', '))) list_bomb.append(coor) list_flag.append(coor) board = Board(size, list_bomb) env = Environment() board.env = env env.load('minesweeper.clp') env.define_function(board.click_tile_env, 'click_tile') rule = """ (defrule open-tile-program (aman ?x ?y) (not (siku ?x ?y)) (not (open ?x ?y)) (size ?n) (test (>= ?x 0)) (test (< ?x ?n)) (test (>= ?y 0)) (test (< ?y ?n)) (using-program)
def init(): global env env = Environment() env.load('miner.clp')