Пример #1
0
def validate_sentence_by_rules(rules, architecture):
    env = clips.Environment()
    for cnt, i in enumerate(rules):
        rule = '''
        (defrule rule%s
            (sentence %s)
            =>
            (printout t "The sentence is correct." crlf))
        ''' % (str(cnt), i)
        env.build(rule)
    rule = '''
    (defrule wrong
        =>
        (printout t "The sentence is wrong." crlf))
    '''
    env.build(rule)

    sentence = ''
    for i in architecture:
        sentence = sentence + i + ' '
    sentence = sentence[:-1]

    # print(sentence)

    fact_string = f'(sentence {sentence})'
    fact = env.assert_string(fact_string)
    template = fact.template

    assert template.implied == True

    validation_result = env.run()
    return validation_result
Пример #2
0
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     self.cell_mode = CellMode.CLIPS
     self.clips_output = OutputRouter()
     self.environment = clips.Environment()
     self.environment.add_router(self.clips_output)
     global_environment(self.environment)
Пример #3
0
def runButtonButtonFunction():
    global environment, guessOK, guessFAIL, fireOK, fireFAIL, kCell
    if not mapPath:
        msgBox = QMessageBox()
        msgBox.setWindowTitle("Error!")
        msgBox.setText("Load a map!")
        msgBox.exec()
    else:
        writeDat()
        environment = clips.Environment()
        environment.clear()
        environment.batch_star('go.bat')
        environment.run()
        for fact in environment.facts():
            analyze_fact(fact)
        win.textEdit.append(
            'Guess: ' + str(round((guessOK /
                                   (guessOK + guessFAIL) * 100), 1)) + '% ' +
            ' (' + str(guessOK) + ' su ' + str(guessOK + guessFAIL) + ')')
        win.textEdit.append('Fire: ' +
                            str(round((fireOK /
                                       (fireOK + fireFAIL) * 100), 1)) + '% ' +
                            ' (' + str(fireOK) + ' su ' +
                            str(fireOK + fireFAIL) + ')')
        win.textEdit.append(
            'Found: ' + str(round(((guessOK + fireOK) /
                                   (20 - kCell) * 100), 1)) + '% ' + ' (' +
            str(guessOK + fireOK) + ' su ' + str(20 - kCell) + ')')
        win.textEdit.append('Precision: ' + calculate_precision() +
                            '          ' + 'Recall: ' + calculate_recall())
Пример #4
0
    def __init__(self, custom_bridges=[]):
        """ EnvProvider constructor method

        Create new CLIPS environment
        """

        # Define holders for data_providers, bridges, functions,
        # built-it funcs, return func data
        self.data_providers = []
        self.bridges = {}
        self.functions = {}
        self.built_in_functions = ["not", "count", "str"]
        self.return_data = []

        # Create new empty CLIPS environment
        self.env = clips.Environment()

        # Prepare DSD meta-model and fill RULE meta model
        self.dsd_mm = DSD_META_MODEL
        mm_fill = self.import_custom_bridges(custom_bridges)
        self.rule_mm = self.fill_rule_meta_model(*mm_fill)

        # Build system data providers and define it's tempaltes
        self.data_providers = self.build_system_data_providers()
        self.define_templates_of_dsds(self.data_providers)

        # Insert system bridges
        self.insert_system_bridges()

        # Insert system rules
        self.insert_system_rules()
Пример #5
0
def clip_s(factList):
	env = clips.Environment()
	env.define_function(addLocation)
	env.define_function(stackExchange)
	env.define_function(associateConflictTop)
	env.define_function(addConflictsStack)
	env.define_function(conflictAddStack)
	env.define_function(addLocationWithAssociation)
	env.define_function(addLocationWithoutAssociation)
	env.load('rules.clp')
	
	aux = ''
	for a in factList:
		aux += a + '\n'

	env.load_facts(aux)
	
	for fact in env.facts():
		print(fact)
	for act in env.activations():
		print(act)
	print("##########################")
	env.run()
	#print(x)
	env.reset()
Пример #6
0
 def __init__(self):
     self.environment = clips.Environment()
     self.logger = logger.getChild(type(self).__name__)
     self.clips_types = {}
     self.preprocess_funcs = []
     self.postprocess_funcs = []
     RuleFunc._register_engine(self)
Пример #7
0
def run_CLIPS(input):
    premise_types = nlp.get_premise_types(input)

    nlp.check_S_M_P(nlp.preprocess(input))

    env = clips.Environment()
    env.clear()

    rule = f"""
    (defrule my-rule
      =>
        (assert (premisa1 {premise_types[0]}))
        (assert (premisa2 {premise_types[1]}))
        (assert (concluzia {premise_types[2]}))
        (assert (Running))
      )
    """
    env.build(rule)

    env.batch_star("Proiect.clp")
    env.reset()
    env.run()
    #
    # for fact in env.facts():
    #     print(fact)

    # for rule in env.rules():
    #     print(rule)


#
#
# run_CLIPS(example)
Пример #8
0
 def __init__(self, size):
     self.size = size
     # Initialize tiles
     self.matrix = [[MinesweeperTile() for i in range(size)]
                    for j in range(size)]
     self.game = INIT
     self.env = clips.Environment()  # Connect CLIPS environment to the game
     self.recent_act = (-1, -1)  # Recent tile to be acted upon
Пример #9
0
def main():
    window = Tk()
    env = clips.Environment()
    env.load('es_rules.CLP')
    env.run(limit=None)
    app = Application(window, env)
    window.geometry('800x700')
    window.mainloop()
Пример #10
0
 def setUp(self):
     """sets up the environment to work with."""
     id = 'tenantId'
     self.json_fact = '{"serverId": "serverId", "cpu": 90, "mem": 30, "hdd":70, "net":90}'
     clips.Reset()
     self.e1 = clips.Environment()
     eid = clips.Symbol(id)
     self.e1.Identifier = eid
def printRules():
    env = clips.Environment()
    env.load("shape_rule.clp")

    rules = list(env.rules())
    f = open("rules.txt", "w")
    for rule in rules:
        f.write(str(rule) + "\n")
    f.close()
Пример #12
0
 def setUp(self):
     """set up testing environment"""
     e1 = clips.Environment()
     self.envdict = {
         'clips': clips,
         'env': e1,
     }
     clips.DebugConfig.WatchAll()
     e1.DebugConfig.WatchAll()
Пример #13
0
    def __init__(self):
        self.smartphones = None
        with open(path_to_data_clean_pickle, 'rb') as handle:
            self.smartphones = pickle.load(handle)  # pandas DataFrame

        self.columns = self.smartphones.columns
        self.env = clips.Environment()
        self.env.load(path_to_smartphones_clp)
        self.env.reset()
        self.fill_database()
Пример #14
0
    def __load_clp(self):
        try:
            os.remove("fiesire.dat")
        except OSError:
            pass

        env = clips.Environment()
        env.load("sudokuv3.clp")

        env.reset()
        env.run()
Пример #15
0
    def __init__(self, mlObject):
        self.env = clips.Environment()
        self.mlObject = mlObject
        self.fact_type = "input ui"
        self.clips_type = "symbol"
        self.set_of_functions = dictionary

        #NLP components
        self.nlp = eric_nlp.Eric_nlp()
        self.nlp.load_model(self.nlp.nlp_model_file)
        self.nlp.init_depparsing("en")
Пример #16
0
    def __init__(self):

        self.rules = []
        self.inp_template = None
        self.out_template = None

        self.clips_sinp_template = None
        self.clips_out_template = None

        self.env = clips.Environment()
        #env.build
        return None
Пример #17
0
 def __init__(self, config_path):
     self.env = clips.Environment()
     print("strategy used: {}".format(self.env.strategy))
     print("config_path: ", config_path)
     self.game_config = load_game(config_path)
     self.rem_bombs = self.game_config["num_bombs"]
     self.b = self.game_config["board_size"]
     self.board = [['*' for i in range(self.b)] for i in range(self.b)]
     self.board[0][0] = 0
     self.opened = [[0 for i in range(self.b)] for i in range(self.b)]
     self.opened[0][0] = 1
     self.E = generate_e(self.game_config)
     self.init_facts()
Пример #18
0
 def reset(self):
     """
     reset
     :return:
     """
     self.file_pointers = 1  # sim.data file read position
     self.m_nCount = 0
     self.clips_env = clips.Environment()
     self.engine = clips
     self.filemodel.reset()
     self.filemodel.load_data(self.fact_filename)
     self.data = np.array([])
     self.data_header = np.array([])
Пример #19
0
 def __enter__(self):
     self.semaphore.acquire()
     with self.lock:
         if self.free_envs:
             # Free environments are available
             self.env_id, env = self.free_envs.popitem()
             logger.debug("Reusing CLIPS environment #%d", self.env_id)
         else:
             # Create new environment
             self.env_id = self.env_seq.next()
             logger.debug("Creating new CLIPS environment #%d", self.env_id)
             env = clips.Environment()
         self.used_envs[self.env_id] = env
     return env
Пример #20
0
    def __init__(self):
        ##CONST CODE AREA
        self.CLIPS_FILE_LOAD_FAILED_CODE = 404
        self.CLIPS_FILE_LOAD_SUCCESS_CODE = 200

        ##GLOBAL_AREA
        self.file_pointers = 1  # sim.data file read position
        self.m_nCount = 0
        self.data_file_name = TEMP_FILE_PREFIX + 'test_flight_facts.dat'
        self.clips_dribble_filename = TEMP_FILE_PREFIX + 'record.dat'
        self.clips_env = clips.Environment()
        self.engine = clips
        ## fact dataframe
        self.dataframe = pd.DataFrame
        ## mapper
        self.mapper_list = []
        self.record_name = ''  #Reasoning result record file name
Пример #21
0
    def test_clips(self):
        env = clips.Environment()
        env.Reset()

        rule_lhs_index = {}

        r1_lhs = "(duck ?name)"
        r1 = env.BuildRule("duck-rule", r1_lhs, "", "The Duck rule")
        rule_lhs_index[r1.Name] = r1_lhs

        r2_lhs = "(cat-name ?name)(cat-has ?name ?thing)"
        r2 = env.BuildRule("cat-rule", r2_lhs, "", "The Cat rule")
        rule_lhs_index[r2.Name] = r2_lhs

        fact_index = {}

        f1 = env.Assert("(duck daffy)")
        fact_index[f1.Index] = f1
        self.assertEqual(f1.Index, 1)

        f2 = env.Assert("(duck waldo)")
        fact_index[f2.Index] = f2
        self.assertEqual(f2.Index, 2)

        f3 = env.Assert("(cat-name mittens)")
        fact_index[f3.Index] = f3
        self.assertEqual(f3.Index, 3)

        f4 = env.Assert("(cat-has mittens paws)")
        fact_index[f4.Index] = f4

        out = planner._get_clips_output(env, 'PrintAgenda')
        match_sets = planner._get_clips_match_sets(out, env, fact_index,
                                                   rule_lhs_index)
        d = {
            'duck-rule': [{
                'name': 'waldo'
            }, {
                'name': 'daffy'
            }],
            'cat-rule': [{
                'thing': 'paws',
                'name': 'mittens'
            }]
        }
        self.assertEqual(match_sets, d)
    def clip_s(self, factList):
        env = clips.Environment()
        env.define_function(self.addLocation)
        env.define_function(self.stackExchange)
        env.define_function(self.associateConflictTop)
        env.define_function(self.addConflictsStack)
        env.define_function(self.conflictAddStack)
        env.define_function(self.addLocationWithAssociation)
        env.define_function(self.addLocationWithoutAssociation)
        env.load('rules.clp')
        aux = ''
        for a in factList:
            aux += a + '\n'

        env.load_facts(aux)
        env.run()
        env.reset()
Пример #23
0
 def __init__(self, *args, **kw):
     graphs = [x.ns.value for x in args]
     self.ns = Namespace(*graphs)
     IMP.__init__(self)
     TPL.__init__(self)
     for k in kw:
         self.ns.set(f"/etc/{k}", kw[k])
     self.get = self.ns.get
     self.set = self.ns.set
     self.mkdir = self.ns.mkdir
     self.rm = self.ns.rm
     self.o = self.ns.object
     self.ls = self.ns.ls
     self.Set("id", str(uuid.uuid4()))
     self.Set("faker", faker.Faker())
     self.Set("env", clips.Environment())
     self.Reload()
     self.Run = self.env.run
Пример #24
0
 def __init__(self, socket, sid, source):
     # clips.RegisterPythonFunction(self.clips_debug, "debug")
     # clips.RegisterPythonFunction(self.clips_alert, "print")
     # clips.RegisterPythonFunction(self.clips_prompt, "ask")
     clipsEnv = clips.Environment()
     PrepareEnvironment(clipsEnv, sid)
     AddSpecificFunction(clipsEnv, self.clips_debug, "debug")
     AddSpecificFunction(clipsEnv, self.clips_alert, "alert")
     AddSpecificFunction(clipsEnv, self.clips_prompt, "prompt")
     AddSpecificFunction(clipsEnv, self.clips_prompt2, "prompt2")
     AddSpecificFunction(clipsEnv, self.clips_final, "final")
     # clipsEnv.Load("header_python.clp")
     clipsEnv.Load("{}.clp".format(source))
     self.ta = TempAns()
     self.socket = socket
     self.sid = sid
     self.clips = clips
     self.clipsEnv = clipsEnv
     self.final = None
Пример #25
0
 def __init__(self):
     ##CONST CODE AREA
     self.CLIPS_FILE_LOAD_FAILED_CODE = 404
     self.CLIPS_FILE_LOAD_SUCCESS_CODE = 200
     self.codetype = sys.getfilesystemencoding()
     ##GLOBAL_AREA
     self.file_pointers = 1  # sim.data file read position
     self.m_nCount = 0
     self.data_file_name = TEMP_FILE_PREFIX + 'test_flight_facts.dat'
     self.clips_dribble_filename = TEMP_FILE_PREFIX + 'record.dat'
     self.clips_env = clips.Environment()
     self.engine = clips
     self.filemodel = FileModel()
     self.fact_filename = ''
     ## fact dataframe
     self.data = np.array([])
     self.data_header = np.array([])
     # self.dataframe = pd.DataFrame
     ## mapper
     self.mapper_list = []  # Template and slot mapping pair list
     self.record_name = ''  # Reasoning result record file name
Пример #26
0
def result():
    bb = int(request.form['bb'])
    tb = int(request.form['tb'])
    usia = int(request.form['usia'])
    jk = request.form['jk']
    aktivitas = request.form['aktivitas']
    penyakit = request.form['penyakit']
    env = clips.Environment()
    env.Load("CLIPS/templates.clp")
    env.Load("CLIPS/functions.clp")
    env.Load("CLIPS/rules.clp")
    env.Load("CLIPS/skeletal-kontrol.clp")
    env.BuildDeffacts(
        "pasien", "(pasien (berat-badan " + str(bb) + ") (tinggi-badan " +
        str(tb) + ") (usia " + str(usia) + ") (jenis-kelamin " + jk +
        ") (aktivitas \"" + aktivitas + "\") (penyakit \"" + penyakit + "\"))")
    env.Reset()
    env.Assert("(mulai)")
    env.Run()
    env.SaveFacts("a.txt")
    t = clips.StdoutStream.Read()
    return render_template("result.html", t=Markup(t))
Пример #27
0
 def __enter__(self):
     self.cond.acquire()
     env = None
     while not env:
         if self.free_envs:
             # Reuse free environment
             self.env_id, env = self.free_envs.popitem()
             logger.debug("Reusing CLIPS environment #%d", self.env_id)
             self.used_envs[self.env_id] = env
             break
         elif self.env_seq < self.max_environments:
             # Create new environment
             self.env_id = self.env_seq
             self.env_seq += 1
             logger.debug("Creating new CLIPS environment #%d", self.env_id)
             env = clips.Environment()
             self.used_envs[self.env_id] = env
             break
         else:
             logging.debug("No free CLIPS environment available. Waiting")
             self.cond.wait()
     self.cond.release()
     return env
Пример #28
0
def parse_input(sentence):
    sentence_post_tagged = pos_tagg(sentence)
    env = clips.Environment()
    env.clear()
    env.load('LAL.clp')
    env.reset()
    ''' Facts - Base parsing rules '''

    fact = env.assert_string('(text S ' + sentence_post_tagged + ')')
    fact = env.assert_string('(answer)')
    fact = env.assert_string('(rule G1  S NN A)')
    fact = env.assert_string('(rule G2  A NN B)')
    fact = env.assert_string('(rule G3  B , C)')
    fact = env.assert_string('(rule G4  C NNP D)')
    fact = env.assert_string('(rule G5  D VBD E)')
    fact = env.assert_string('(rule G6  E RB F)')
    fact = env.assert_string('(rule G7  F JJ H)')
    fact = env.assert_string('(rule G8  H . EPS)')

    print("Input received: " + sentence)
    print("POS Tagged version: " + sentence_post_tagged)
    print("Result from CLIPS code: ")

    env.run()
        x, y = tuple(map(int, line.split(',')))
        arBombX.append(x)
        arBombY.append(y)

    arBomb = list(zip(arBombX, arBombY))
    print(arBomb)

    f.close()

    print("input file success!")
    print()
    print()

    game = papan(size, arBomb)

    env = clips.Environment()
    env.load('minesweeper6.clp')

    for i in range(size):
        for k in range(size):
            result_facts.append(add_val(i, k, game.isi[i][k].status))
            if ((i == 0) and (k == 0)):
                result_facts.append(add_tile(i, k, 3, 0, 0))
            elif (((i == size - 1) and (k == size - 1))
                  or ((i == 0) and (k == size - 1))
                  or ((i == size - 1) and (k == 0))):
                result_facts.append(add_tile(i, k, 3, 0, -1))
            elif ((i == 0) or (k == 0) or (i == size - 1) or (k == size - 1)):
                result_facts.append(add_tile(i, k, 5, 0, -1))
            else:
                result_facts.append(add_tile(i, k, 8, 0, -1))
Пример #30
0
def main():
    tenantId = sys.argv[1]

    def env_id():
        return clips.Symbol(sys.argv[1])

    # the following dictionary will contain the environment specific functions
    ENV_SPECIFIC_FUNCTIONS = {}

    # ...and this wrapper calls in turn the functions associated with certain
    #  names for each environment
    def envCallSpecificFunction(e_id, funcname, *args):
        f = ENV_SPECIFIC_FUNCTIONS[e_id][funcname]
        return f(*args)

    clips.RegisterPythonFunction(envCallSpecificFunction,
                                 'env-call-specific-func')

    # now we need some helpers to make it easier to set up the environment and
    #  the map of environment specific functions
    def PrepareEnvironment(e):
        """Prepares environments to be defined.
        """
        eid = env_id()
        ENV_SPECIFIC_FUNCTIONS[eid] = {}  # a map of functions
        e.Identifier = eid  # so that we can always get it back
        return eid

    def GetNotificationUrl(ruleName, serverId):
        """Gets url from database where actions should be notified.
        """
        #conn = db.connect("cloto.db")
        conn = mysql.connect(charset=DB_CHARSET,
                             use_unicode=True,
                             host=DB_HOST,
                             user=DB_USER,
                             passwd=DB_PASSWD,
                             db=DB_NAME)
        #conn.row_factory = db.Row
        cur = conn.cursor()
        SQL = "SELECT url from cloto.cloto_subscription S join cloto.cloto_specificrule R " \
              "on S.ruleId=R.specificRule_Id " \
              "WHERE name='%s' AND S.serverId='%s';" \
              % (ruleName, serverId)
        cur.execute(SQL)
        while True:
            r = cur.fetchone()
            if not r:
                conn.close()
                break
            else:
                url = r[0]
                #url = r['url']
        return url

    def NotifyEmail(serverId, url, description, email):
        """Sends a notification to given url showing that service must send an email to an address.
        """
        try:
            headers = {'Content-Type': 'application/json'}
            data = '{"action": "notifyEmail", "serverId": "' + serverId\
                   + ', "email": "' + email + '", "description": "' + description + '"}'
            logger.info("Preparing eMail to %s: %s--- Response: " %
                        (url, data))

            r = requests.post(url, data=data, headers=headers)
            if r.status_code == 200:
                logger.info(
                    "mail sent to %s about server %s.--- Response: %d" %
                    (email, serverId, url, r.status_code))
            else:
                print(2)
                logger.info(
                    "ERROR Sending mail to %s about server %s.--- %s Response: %d"
                    % (email, serverId, url, r.status_code))
        except Exception as ex:
            logger.error(ex.message)

    def NotifyScale(serverId, url, action):
        """Sends a notification to given url showing that service must scale up or scale down a server.
        """
        try:
            headers = {'Content-Type': 'application/json'}
            data = '{"action": "' + action + '", "serverId": "' + serverId + '"}'
            logger.info(action + " message sent to %s : %s" % (url, data))
            r = requests.post(url, data=data, headers=headers)
            if r.status_code == 200:
                logger.info(
                    action +
                    " message sent to %s about server %s.--- Response: %d" %
                    (url, serverId, r.status_code))
            else:
                logger.error(
                    action +
                    " message sent to %s about server %s.--- Response: %d" %
                    (url, serverId, r.status_code))
        except Exception as ex:
            logger.error(ex.message)

    def get_rules_from_db(tenantId):
        """Gets all subscripted rules for a specified tenant and adds them to CLIPS environment to be checked.
        """
        import MySQLdb as mysql
        conn = mysql.connect(charset=DB_CHARSET,
                             use_unicode=True,
                             host=DB_HOST,
                             user=DB_USER,
                             passwd=DB_PASSWD,
                             db=DB_NAME)
        #conn = db.connect("cloto.db")
        #conn.row_factory = db.Row
        cur = conn.cursor()
        SQL = "SELECT * FROM cloto.cloto_specificrule WHERE specificRule_Id IN " \
              "(SELECT ruleId FROM cloto.cloto_subscription WHERE %s IN " \
              "(SELECT %s FROM cloto.cloto_entity WHERE tenantId='%s'))" % (SERVERID, SERVERID, tenantId)
        cur.execute(SQL)
        while True:
            r = cur.fetchone()
            if not r:
                conn.close()
                break
            else:
                rule_name = r[2]
                rule_cond = r[5]
                rule_action = r[6]
                #rule_name = r['name']
                #rule_cond = r['condition']
                #rule_action = r['action']
                e1.BuildRule(rule_name, rule_cond, rule_action)

    clips.Reset()
    e1 = clips.Environment()
    PrepareEnvironment(e1)
    clips.RegisterPythonFunction(NotifyEmail, "notify-email")
    clips.RegisterPythonFunction(NotifyScale, "notify-scale")
    clips.RegisterPythonFunction(GetNotificationUrl, "get-notification-url")
    e1.Assert("(initial-fact)")

    try:

        connection = pika.BlockingConnection(
            pika.ConnectionParameters(host=RABBITMQ_URL))
        channel = connection.channel()

        channel.exchange_declare(exchange="facts", exchange_type='direct')

        result = channel.queue_declare(exclusive=True)
        queue_name = result.method.queue

        channel.queue_bind(exchange="facts",
                           queue=queue_name,
                           routing_key=tenantId)

        logger.info('Environment started. Waiting for Facts')

        def callback(ch, method, properties, body):
            try:
                decoded = json.loads(body)
                f1 = e1.Assert("(ServerFact \"" + str(decoded[SERVERID]) +
                               "\" " + str(decoded['cpu']) + " " +
                               str(decoded['mem']) + ")")
                logger.info("received fact: %s" % body)
                get_rules_from_db(tenantId)
                saveout = sys.stdout
                fsock = open(LOGGING_PATH + '/CLIPSout.log', 'w')
                sys.stdout = fsock
                e1.PrintFacts()
                e1.PrintRules()
                e1.Run()
                sys.stdout = saveout
                fsock.close()
                f1.Retract()
            except ValueError:
                logger.error("receiving an invalid body: " + body)
            except clips.ClipsError:
                logger.error(clips.ErrorStream.Read())
            except Exception as ex:
                logger.warn("FACT: already exists or " + ex.message)

        channel.basic_consume(callback, queue=queue_name, no_ack=True)

        channel.start_consuming()
    except mysql.Error, e:
        logger.error("%s %s Error %s:" % LOGGER_COMPONENT, tenantId, e.args[0])