def prepare(cls): """ Prepare CLIPS """ logger.debug("Prepare CLIPS") # Install python functions logger.debug("Register python function py-match-re") clips.RegisterPythonFunction(clips_match_re, "py-match-re")
def __call__(self, *args, **kwargs): """ Return an expression that indicates an invocation of this function with given arguments. """ wrapper = self._wrapper_by_engine.get(self._cur_engine) if wrapper is None: wrapper = self._create_wrapper(self._cur_engine) clips.RegisterPythonFunction(wrapper) return PythonFuncExpr(wrapper.__name__, self.type, *args)
def posiblesEnfermedades(request): if request.method == 'POST': sintomas_id = ast.literal_eval( request.POST.get("sintomas")) print sintomas_id signos_car = {} respuesta = {} preguntas = {} e = Enfermedades() clips.RegisterPythonFunction(e.add_enfermedad) clips.Load("posibles-enfermedades.clp") clips.Reset() for sintoma_id in sintomas_id: try: sintoma = SignoGeneral.objects.get(pk=sintoma_id) print sintoma.identificador clips.Assert("(signo "+sintoma.identificador+")") except Exception as e: print e return HttpResponse(0) clips.Run() print e.lista for key in e.lista: try: enfermedad = Enfermedad.objects.filter(pk=key) print enfermedad if len(enfermedad): enfermedad = enfermedad[0] p = PreguntaEnfermedad.objects.filter(enfermedad=enfermedad) array_preguntas = [] array_preguntas.append(enfermedad.nombre) for pregunta in p: array_preguntas.append(pregunta.pregunta) preguntas[key] = array_preguntas except Exception as ex: print ex return HttpResponse(0) # Las preguntas se pasan por un dict que contiene como key el id de las enfermedades y en cada value # un arreglo con el nombre y las preguntas respuesta = {"lista":e.lista,"preguntas":preguntas} if len(e.lista): return HttpResponse(json.dumps(respuesta),content_type='application/json') else: return HttpResponse(0)
def load_module(self, name): import fnmatch mod = self.find_the_mod(name) if mod == None: raise ValueError c = 0 for e in dir(mod): if fnmatch.fnmatch(e, "*_clips"): fun_name = rchop(e, "_clips") try: fun = getattr(mod, fun_name) except: continue clips.RegisterPythonFunction(fun) clips.Build(getattr(mod, e)) c += 1 return c
def load_pyclp_module(self, name): import fnmatch from USS.DATA.MISC.STR import rchop mod = self.find_the_mod(name) if mod == None: raise ValueError, "PYCLP modulе %s not found" % name c = 0 for e in dir(mod): if fnmatch.fnmatch(e, "*_clips"): fun_name = rchop(e, "_clips") try: fun = getattr(mod, fun_name) except: continue clips.RegisterPythonFunction(fun) #print getattr(mod, e) self.clips.Build(getattr(mod, e)) c += 1 return c
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])
new_args = [to_native(arg) for arg in matchargs] func(*new_args) except: #traceback.print_last() print "Exception in user code:" print '-' * 60 traceback.print_exc(file=sys.stdout) print '-' * 60 pass #print rule print rule_callback clips.RegisterPythonFunction(rule_callback, 'rule_callback') def connect_rules(inst): global _rules_dict rule_funcs = filter(lambda attr: attr.startswith('rule_'), dir(inst)) class_name = inst.__class__.__name__ maprule = dict([(class_name + '-' + func[5:], getattr(inst, func)) for func in rule_funcs]) _rules_dict.update(maprule) class BaseRules: 'Base Rules for ' def __init__(self):
#!/usr/bin/env python import eventlet as eventlib eventlib.monkey_patch() import clips namespace = "/" ENV_SPECIFIC_FUNCTIONS = {} def envCallSpecificFunction(e_id, funcname, *args): f = ENV_SPECIFIC_FUNCTIONS[e_id][funcname] return f(*args) clips.RegisterPythonFunction(envCallSpecificFunction, 'env-call-specific-func') def PrepareEnvironment(e, sid): eid = clips.Symbol("eid-" + sid) ENV_SPECIFIC_FUNCTIONS[eid] = {} e.Identifier = eid def DestroyEnvironment(e): del ENV_SPECIFIC_FUNCTIONS[e.Identifier] def AddSpecificFunction(e, func, funcname=None): try: eid = e.Identifier
def addf(a, b): return a + b print addf("egg", "spam") print addf(2, 4) import clips clips.RegisterPythonFunction(addf) print clips.Eval('(python-call addf "egg" "spam")') print clips.Eval('(python-call addf 2 4)')
def define_IO_Routines(): clips.RegisterPythonFunction(pyprintout) clips.RegisterPythonFunction(pyreadline) clips.RegisterPythonFunction(pyread) clips.RegisterPythonFunction(capture_error) clips.Load("IO.clp")
import time import clips import sys def msg(s): print "M> %s" % s clips.RegisterPythonFunction(msg) def load_facts(facts_file): clips.LoadFacts(facts_file) def load_rules(rules_file): clips.Load(rules_file) def repeat(interval, func, *args, **kwargs): try: while True: func(*args, **kwargs) time.sleep(interval) except KeyboardInterrupt: msg("exiting ...") def run_checks(facts_file, rules_file): clips.Reset() load_rules(rules_file) load_facts(facts_file) clips.Run()
def registerPythonFunction(self, function): clips.RegisterPythonFunction(function)
import clips import subprocess import sys from capturer import CaptureOutput from cStringIO import StringIO clips.Reset() #sys.stdout = open("logfile", "w") """ user = True def py_getvar(k): return (clips.Symbol('TRUE') if globals().get(k) else clips.Symbol('FALSE')) clips.RegisterPythonFunction(py_getvar) # if globals().get('user') is not None: assert something clips.BuildRule("user-rule", "(test (eq (python-call py_getvar user) TRUE))", '(assert (user-present))', "the user rule") clips.BuildRule("do-stuff-rule", "(we-should-do-stuff)", '(python-call py_dostuff)', "the do stuff rule") clips.BuildRule("do-stuff-rule2", "(we-should-do-stuff2)", '(python-call py_dostuff2)', "the do stuff rule2") clips.BuildRule("user-rule2", "(test (eq (python-call py_getvar user2) TRUE))", '(assert (user-present2))', "the user rule2") def addf(a, b): return a + b clips.RegisterPythonFunction(addf) """ #clips.Build("""(defrule duck (animal-is duck) => (assert (sound-is quack)) (printout t \"it's a duck\" crlf) (bind ?tot (python-call addf 40 2 )) (printout t ?tot crlf))""") #clips.Assert("(animal-is duck)") #clips.Run()
def system_run(input_ set): if 'hazard' in input_set: clips.Clear() clips.Reset() eng_var[:]=[] eng_var.append(input_set['lat']) eng_var.append(input_set['long']) eng_var.append(clips.BuildTemplate("entity", """ (slot aid (type STRING)) (slot latitude (type NUMBER)) (slot longitude (type NUMBER)) (slot quantity (type NUMBER)) """, "template for a entity")) eng_var.append(clips.BuildTemplate("allies", """ (slot username (type STRING)) (slot foraid (type STRING)) (slot action (type STRING)) (slot quantity (type NUMBER)) """, "template for a allies")) eng_var.append(input_set['control']) eng_var.append(clips.BuildTemplate("disaster", """ (slot hazard (type STRING)) (slot latitude (type NUMBER)) (slot longitude (type NUMBER)) (slot span (type NUMBER)) """, "template for a disaster")) d=clips.Fact(eng_var[5]) d.Slots['hazard'] = input_set['hazard'] d.Slots['latitude'] = input_set['lat'] d.Slots['longitude'] = input_set['long'] d.Slots['span'] = input_set['span'] d.Assert() facts[:] = [] fields[:] = [] list_map[:] = [] clips.RegisterPythonFunction(invoke_pronearea) clips.RegisterPythonFunction(display_disaster) clips.RegisterPythonFunction(invoke_entity) clips.RegisterPythonFunction(invoke_useralert) clips.RegisterPythonFunction(invoke_user_allocate ) clips.RegisterPythonFunction(invoke_user_deallocate) clips.RegisterPythonFunction(invoke_message) clips.RegisterPythonFunction(invoke_alert_area) clips.BatchStar("/home/jishnu/PycharmProjects/dmis/controlunit/expertsystem/inference.clp") clips.Run() if 'refresh' in input_set: if len(eng_var)==0: return {'fact': facts, 'field': fields,'map_data':list_map} message_dealer(input_set['control'],eng_var[0],eng_var[1],eng_var[2]) user_status_checking() clips.Run() if 'send' in input_set: if len(eng_var)==0: return {'fact': facts, 'field': fields,'map_data':list_map} message_handler(input_set['control'],input_set['selectaid'],input_set['parameter']) if 'deallocate' in input_set: try: clips.Assert("(DeallocateAll)") except clips.ClipsError: print("Error in Deallocation") clips.Run() facts[:] = [] fields[:] = [] list_map[:] = [] clips.SendCommand("run") print (clips.PrintFacts()) list_temp=list(facts) list_temp.reverse() return {'fact':list_temp,'field':list(set(fields)),'map_data':list_map}
import clips def py_square(x): return x * x clips.RegisterPythonFunction(py_square) print clips.Eval("(python-call py_square 7)") print clips.Eval("(python-call py_square 0.7)")
#interaction_object.update_games() val = interaction_object.get_identifier_last_move() return clips.Integer(val) def clips_move_input(): #get the value someway val = interaction_object.get_movement_last_move() return clips.Integer(val) clips.RegisterPythonFunction(clips_piece_input, "piece-input") clips.RegisterPythonFunction(clips_move_input, "move-input") def LoadFunctions(clips, team): # Generates the CLIPS module mod_name = "EQUIPO-" + team # Module body mod_body = "(import MAIN deftemplate initial-fact ficha dimension "\ "tiempo mueve tiempo-inicial obstaculo)" mod_body += "(import MAIN deffunction ?ALL)" mod_equipo = clips.BuildModule(mod_name, mod_body) # Function that reads the movement fun_name = 'read-mov' fun_para = '?n ?t'