def match_preference(data): preference = '(preference ' + \ '(sex "' + data['sex'] + '") ' + \ '(price-level "' + data['priceLevel'] + '") ' + \ '(age-level "' + data['ageLevel'] + '") ' + \ '(cat-fashion "' + data['catFashion'] + '") ' + \ '(cat-music "' + data['catMusic'] + '") ' + \ '(cat-book "' + data['catBook'] + '") ' + \ '(cat-games "' + data['catGames'] + '") ' + \ '(cat-movies "' + data['catMovies'] + '") ' + \ '(cat-gadgets "' + data['catGadgets'] + '") ' + \ '(cat-sport "' + data['catSport'] + '") ' + \ '(cat-cosmetics "' + data['catCosmetics'] + '") ' + \ '(cat-toy "' + data['catToy'] + '"))' print(preference) clips.Clear() clips.BatchStar(settings.CLIPS_DIR + "/templates.clp") clips.BatchStar(settings.CLIPS_DIR + "/gifts.clp") clips.BatchStar(settings.CLIPS_DIR + "/suggestions.clp") clips.BatchStar(settings.CLIPS_DIR + "/rules.clp") clips.Reset() clips.Assert(preference) clips.Run() return clips.StdoutStream.Read()
def get_all_games(): # Load template clips.Clear() clips.Load("clips/templates.clp") clips.Load("clips/games.clp") clips.Reset() # Run clips clips.Run() # load game from facts games = [] facts = clips.FactList() for fact in facts: if fact.Relation != 'game': continue game = { 'id': int(fact.Slots['id']), 'name': fact.Slots['name'], 'description': fact.Slots['description'], 'genre': list(fact.Slots['genre']), 'platform': list(fact.Slots['platform']), 'age-range': fact.Slots['age-range'], 'game-mode': fact.Slots['game-mode'], 'release-date': fact.Slots['release-date'], 'length': fact.Slots['length'], 'difficulty': fact.Slots['difficulty'], 'image': fact.Slots['image'] } games.append(game) # print fact.Slots['id'], list(fact.Slots['genre']) return games
def modulo2(opciones): #Reseteamos entorno clips.Reset() #Creamos contadores clips.Assert("(contador_mov_soprano 0)") clips.Assert("(contador_melodia_soprano 0)") clips.Assert("(contador_mov_contraalto 0)") clips.Assert("(contador_melodia_contraalto 0)") clips.Assert("(contador_mov_tenor 0)") clips.Assert("(contador_melodia_tenor 0)") clips.Assert("(contador_mov_bajo 0)") clips.Assert("(contador_melodia_bajo 0)") clips.Assert("(movContrariosExtremos 0)") clips.Assert("(movDirectosExtremos 0)") clips.Assert("(movOblicuosExtremos 0)") clips.Assert("(saltosGrandesSoprano 0)") clips.Assert("(saltosPequenosSoprano 0)") clips.Assert("(saltosGrandesContraalto 0)") clips.Assert("(saltosPequenosContraalto 0)") clips.Assert("(saltosGrandesTenor 0)") clips.Assert("(saltosPequenosTenor 0)") clips.Assert("(saltosGrandesBajo 0)") clips.Assert("(saltosPequenosBajo 0)") #Cargamos las reglas clips.Load('./tfg_web/reglas/reglas-modulo2.clp') #Ejecutamos clips.Run()
def clipsMatchPreference(data): # Preference preference = '(preference ' +\ '(cuisine "'+data['cuisine']+'") ' +\ '(is-vegetarian "'+data['isVegetarian']+'") ' +\ '(has-soup "'+data['hasSoup']+'") ' +\ '(fat-level "'+data['fatLevel']+'")' +\ '(calorie-level "'+data['calorieLevel']+'") ' +\ '(fiber-level "'+data['fiberLevel']+'") ' +\ '(carb-level "'+data['carbLevel']+'") ' +\ '(spicy-level "'+data['spicyLevel']+'") ' +\ '(sour-level "'+data['sourLevel']+'") ' +\ '(sweet-level "'+data['sweetLevel']+'") ' +\ '(salty-level "'+data['saltyLevel']+'"))' # CLIPS clips.Clear() clips.BatchStar(settings.CLIPS_DIR + "/templates.clp") if os.path.isfile(settings.CLIPS_DIR + "/dishes.clp"): clips.BatchStar(settings.CLIPS_DIR + "/dishes.clp") if os.path.isfile(settings.CLIPS_DIR + "/reviews.clp"): clips.BatchStar(settings.CLIPS_DIR + "/reviews.clp") if os.path.isfile(settings.CLIPS_DIR + "/suggestions.clp"): clips.BatchStar(settings.CLIPS_DIR + "/suggestions.clp") clips.BatchStar(settings.CLIPS_DIR + "/rules.clp") clips.Reset() clips.Assert(preference) clips.Run() return clips.StdoutStream.Read()
def new(bot, update): """ Starts a new chat with the beer expert when the command /new is issued. """ clips.Reset() clips.Run() nextUIState(bot, update)
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 __init__(self): connect_rules(self) #mod=self.new_module('MAIN') #print (eng.clips_init()) clips.Clear() clips.Load('astrules.clp') clips.Reset()
def loadCLIPS(): clips.Load(os.path.join('src', 'clips', 'peces.pont')) clips.Load(os.path.join('src', 'clips', 'peces.clp')) clips.Load(os.path.join('src', 'clips', 'peces.pins')) clips.Reset() clips.SendCommand('(set-salience-evaluation when-activated)') clips.SendCommand('(set-strategy depth)') printCLIPS() loadFishFromCLIPS(True)
def start(bot, update): """ Sends a welcome message when the command /start is issued. """ clips.Reset() clips.Run() update.message.reply_text(text='Hello %s! 🤖' % update.message.from_user.first_name, reply_markup=ReplyKeyboardRemove()) update.message.reply_text(clips.Eval('(find-fact ((?u UI-state)) (eq ?u:state initial))')[0].Slots['display'])
def clipsChoosePetrolBrand(data): # Preference #data = 'DBS-Esso' ccInput = '(form-input ' +\ '(Bankcard '+data+'))' # CLIPS clips.Clear() clips.Load(settings.CLIPS_DIR + "/init.clp") clips.Load(settings.CLIPS_DIR + "/card_clips.clp") clips.Reset() clips.Assert(ccInput) clips.Run() return clips.StdoutStream.Read()
def handleEvent(bot, update): """ Triggers the next state in working memory based on which button is pressed. """ current_id = clips.Eval( '(find-fact ((?s state-list)) TRUE)')[0].Slots['current'] current_ui = clips.Eval('(find-fact ((?u UI-state)) (eq ?u:id %s))' % current_id) response = update.message.text if response in current_ui[0].Slots['valid-answers']: if len(response.split(' ')) > 1: clips.Assert('(next %s "%s")' % (current_id, response)) else: clips.Assert('(next %s %s)' % (current_id, response)) clips.Run() nextUIState(bot, update) elif response == emojize(':sos: Help', use_aliases=True): help = current_ui[0].Slots['help'] if not re.findall('_.+?_\(.*?\)', help): update.message.reply_text(text=help, parse_mode=ParseMode.MARKDOWN) else: keyboard = list() for pattern in re.findall('_.+?_\(.*?\)', help): keyboard.append([ InlineKeyboardButton(text=re.findall('_(.+?)_', pattern)[0], callback_data=re.findall( '\((.*?)\)', pattern)[0]) ]) for link in re.findall('\(.*?\)', help): help = help.replace(link, '') update.message.reply_text( text=help, parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup(keyboard)) elif response == emojize(':question: Why', use_aliases=True): update.message.reply_text(text=current_ui[0].Slots['why'], parse_mode=ParseMode.MARKDOWN) elif response == emojize(':back: Previous', use_aliases=True): clips.Assert('(prev %s)' % current_id) clips.Run() nextUIState(bot, update) elif response == emojize(':repeat: Restart', use_aliases=True): new(bot, update) elif response == emojize(':x: Cancel', use_aliases=True): clips.Reset() update.message.reply_text( text='Bye! I hope we can talk again some day. 👋🏻', reply_markup=ReplyKeyboardRemove())
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 modulo3(opciones): #Creamos entorno clips.Reset() #Creamos contadores clips.Assert("(contador_soprano 0)") clips.Assert("(contador_contraalto 0)") clips.Assert("(contador_tenor 0)") clips.Assert("(contador_bajo 0)") #Cargamos las reglas clips.Load('./tfg_web/reglas/reglas-modulo3.clp') #Ejecutamos clips.Run()
def clips_search_matching(data): search = '(search ' +\ '(genre "'+data['genre']+'") ' +\ '(game-mode "'+data['game-mode']+'") ' +\ '(platform "'+data['platform']+'") ' +\ '(age-range "'+data['age-range']+'") ' +\ '(difficulty "'+data['difficulty']+'"))' #CLIPS print(search) clips.Clear() clips.Load(settings.CLIPS_DIR + "/templates.clp") clips.Load(settings.CLIPS_DIR + "/games.clp") clips.Load(settings.CLIPS_DIR + "/rules.clp") # clips.Load(settings.CLIPS_DIR + "/test-facts.clp") clips.Reset() clips.Assert(search) clips.Run() return parse_game_facts(clips.StdoutStream.Read())
def clipsChooseOEMR(data): # Preference psrprofile = '(form-input ' +\ '(aptType '+data['housetype']+') ' +\ '(income '+data['income']+') ' +\ '(tenancy-type '+data['residence']+') ' +\ '(is-risk-averse '+data['risk']+') ' +\ '(accept-direct-billing '+data['bill']+') ' +\ '(accept-sec-dep '+data['sd']+') ' +\ '(want-incentives '+data['incentive']+') ' +\ '(prefer-est-brand '+data['brand']+'))' # CLIPS clips.Clear() clips.Load(settings.CLIPS_DIR + "/psr_templates.clp") clips.Load(settings.CLIPS_DIR + "/psr_init_facts.clp") clips.Load(settings.CLIPS_DIR + "/psr_plans.CLP") clips.Load(settings.CLIPS_DIR + "/psr_rules.CLP") clips.Reset() clips.Assert(psrprofile) clips.Run() return clips.StdoutStream.Read()
def clipsMatchPreferencemaes(data): # Preference preference = '(preference ' +\ '(planta "'+data['planta']+'") ' +\ '(sintoma-aa "'+data['sintomaAA']+'") ' +\ '(sintoma-bb "'+data['sintomaBB']+'") ' +\ '(sintoma-cc "'+data['sintomaCC']+'"))' # CLIPS clips.Clear() clips.BatchStar(settings.CLIPS_DIR + "/templatesmaes.clp") if os.path.isfile(settings.CLIPS_DIR + "/dishesmaes.clp"): clips.BatchStar(settings.CLIPS_DIR + "/dishesmaes.clp") if os.path.isfile(settings.CLIPS_DIR + "/reviewsmaes.clp"): clips.BatchStar(settings.CLIPS_DIR + "/reviewsmaes.clp") if os.path.isfile(settings.CLIPS_DIR + "/suggestionsmaes.clp"): clips.BatchStar(settings.CLIPS_DIR + "/suggestionsmaes.clp") clips.BatchStar(settings.CLIPS_DIR + "/rulesmaes.clp") clips.Reset() clips.Assert(preference) clips.Run() return clips.StdoutStream.Read()
def OnOpen(self, event): dlg = wx.FileDialog(self, "Selecciona archivo", self.dirname, "", "*.clp", wx.FD_OPEN) if dlg.ShowModal() == wx.ID_OK: self.filename = dlg.GetFilename() self.dirname = dlg.GetDirectory() if (self.filename != ""): os.chdir(self.dirname) self.clipsFile = os.path.join(self.dirname, self.filename) self.simClipsFile = os.path.join(self.dirname, 'CicloControlado2.clp') self.timeClipsFile = os.path.join(self.dirname, 'simulacionoficinaalumnos.clp') clips.Clear() clips.BatchStar(self.simClipsFile) clips.BatchStar(self.clipsFile) clips.BatchStar(self.timeClipsFile) clips.Reset() clips.Run() # Modo de ejecucion for f in clips.FactList(): if "Preguntando" in f.PPForm(): self.nuevoCicloItem.Enable(True) break self.SetStatusText(self.clipsFile) self.office.updatePeopleLocation() self.Refresh() self.OutputFrame.box.Clear() self.OutputFrame.appendText("-> Iniciar simulacion " + time.strftime("%c")) dlg.Destroy()
def __init__(self, parent): clips.Load('try.clp') clips.Reset() clips.BuildGlobal('religion', parent.religion) clips.BuildGlobal('sex', parent.sex) clips.BuildGlobal('age', parent.age) self.parent = parent wx.Frame.__init__(self, parent, id=wx.ID_ANY, title=wx.EmptyString, pos=wx.DefaultPosition, size=wx.Size(600, 350), style=wx.DEFAULT_FRAME_STYLE | wx.TAB_TRAVERSAL) self.SetSizeHintsSz(wx.DefaultSize, wx.DefaultSize) self.status = customStatusBar(self) self.SetStatusBar(self.status) self.panelOne = Panel_YESorNO(self) bsizer = wx.BoxSizer(wx.VERTICAL) bsizer.Add(self.panelOne, 1, wx.EXPAND) self.SetSizer(bsizer) self.Layout() self.Centre(wx.BOTH)
def run_checks(facts_file, rules_file): clips.Reset() load_rules(rules_file) load_facts(facts_file) clips.Run()
def load_expert_shell(): clips.BatchStar("robot_planner.clp") clips.Reset()
import pandas as pd facts = pd.read_csv("facts.csv", sep=";", encoding='cp1252', squeeze=True, lineterminator="\n") defrules = pd.read_csv("defrules.csv", sep=";", encoding='cp1252', squeeze=True, lineterminator="\n") print(facts.shape) print(defrules.shape) clips.Reset() for x in facts[1:10]: print(x) clips.Assert(x) for x in defrules[1:5]: s = str(x) print(s) clips.Build(s) clips.PrintFacts() clips.PrintRules()
def define_init_rules(): clips.Load("rules.clp") clips.Reset()
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}
def init_human_game(player_formation, computer_team, player_as, number_turns, dont_save=False): """ Intialize the clips environment """ player_num = 0 team_a = None team_b = None name_team_a = '' name_team_b = '' team_a_piece = xdg.get_data_path('images/piece-orange.png') team_b_piece = xdg.get_data_path('images/piece-violete.png') default_piece = xdg.get_data_path('images/piece-default.png') formacion_temporal_player = None formacion_temporal_pc = None formacion_temporal_player = parsear_fichero_formacion(player_formation) player_formation = formacion_temporal_player formacion_temporal_pc = parsear_fichero_formacion(computer_team[1]) computer_team = (computer_team[0], formacion_temporal_pc) if player_as == 'A': player_num = 1 team_a = player_formation team_b = computer_team name_team_a = filenames.extract_simple_name_es((None, team_a)) name_team_b = filenames.extract_name_expert_system(team_b) else: player_num = -1 team_b = player_formation team_a = computer_team name_team_b = filenames.extract_simple_name_es((None, team_b)) name_team_a = filenames.extract_name_expert_system(team_a) aux_team_a = (name_team_a, team_a_piece) aux_team_b = (name_team_b, team_b_piece) clips.Eval('(reset)') clips.Eval('(clear)') clips.EngineConfig.Strategy = clips.RANDOM_STRATEGY random.seed() clips.Eval("(seed %d)" % random.randint(0, 9999)) funciones.LoadFunctions(clips) f1.init_world(clips, number_turns) try: f1.LoadFunctions(clips) except Exception: print clips.ErrorStream.Read() exit(-1) mover.LoadFunctions(clips) texto.LoadFunctions(clips) traducirF.LoadFunctions(clips) traducirM.LoadFunctions(clips) if player_num == 1: int_team = mirroring.interactive_formation(team_a) temp_team = mirroring.mirroring_team(team_b[1]) try: clips.Load(int_team) except clips.ClipsError: os.remove(int_team) raise FileError(_('Error parsing the file ') + team_a) try: clips.Load(temp_team) except clips.ClipsError: os.remove(temp_team) raise FileError(_('Error parsing the file ') + team_b[1]) os.remove(int_team) os.remove(temp_team) fB.LoadFunctions(clips) temp_rules = mirroring.mirroring_rules(team_b[0]) try: clips.Load(temp_rules) except clips.ClipsError: os.remove(temp_rules) raise FileError(_('Error parsing the file ') + team_b[0]) os.remove(temp_rules) else: try: clips.Load(team_a[1]) except clips.ClipsError: raise FileError(_('Error parsing the file ') + team_a[1]) int_team = mirroring.interactive_formation(team_b) temp_team = mirroring.mirroring_team(int_team) try: clips.Load(temp_team) except clips.ClipsError: os.remove(temp_team) raise FileError(_('Error parsing the file ') + team_a[1]) os.remove(temp_team) fA.LoadFunctions(clips) try: clips.Load(team_a[0]) except clips.ClipsError: raise FileError(_('Error parsing the file ') + team_a[0]) interaccion.LoadFunctions(clips, player_as) interaccion.interaction_object = r_intact.HumanInteraction( aux_team_a, aux_team_b, default_piece, player_num, number_turns) clips.Reset() # restart the environment clips.Run() # start the simulation interaccion.interaction_object.finish() _stream = clips.StdoutStream.Read() # print the output # print _stream # print interaccion.interaction_object.define_winner() if not dont_save: _rename_output_file(_generate_file_name(name_team_a, name_team_b)) if os.path.isfile("resultado.txt"): os.remove('resultado.txt') os.remove(formacion_temporal_pc) os.remove(formacion_temporal_player) clips.Eval('(reset)') clips.Eval('(clear)')
def Reset(): _clipsLock.acquire() clips.Reset() _clipsLock.release()
def globalCLEAR(self): clips.Reset() clips.Clear()
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])
def __startGame(self): """Intialize rules and facts of the main environment. This function loads differents modules and create an environment that provides the proper context where a game can be played. """ clips.Eval('(clear)') clips.EngineConfig.Strategy = clips.RANDOM_STRATEGY random.seed() clips.Eval("(seed " + str(random.randint(0, 9999)) + ")") try: # Se cargan una serie de funciones de utilidad, como "minimo" o "mov-valido" funciones.LoadFunctions(clips) # Se inicializan las opciones de juego (deffacts) f1.init_world(clips, self.number_turns) # Se cargan las plantillas ficha-r, ficha, mueve y obstaculo # además de las reglas para el control de los turnos f1.LoadFunctions(clips) mover.LoadFunctions(clips) texto.LoadFunctions(clips) traducirF.LoadFunctions(clips) traducirM.LoadFunctions(clips) nombreFicheroObstaculos = parsear_fichero_obstaculos.generar_reglas_obstaculos( ) if nombreFicheroObstaculos: clips.Load(nombreFicheroObstaculos) os.unlink(nombreFicheroObstaculos) except clips.ClipsError as e: logging.error("####################") logging.error("ERROR de clips: %s", e) logging.error("Mensaje: ") logging.error(clips.ErrorStream.Read()) logging.error("####################") raise FileError("W===============TTTT") logging.info("Parseando ficheros de formación...") temp_form_A = parsear_fichero_formacion.parsear_fichero_formacion( self.teamA[1], "A") temp_form_B = parsear_fichero_formacion.parsear_fichero_formacion( self.teamB[1], "B") self.teamA = (self.teamA[0], temp_form_A) self.teamB = (self.teamB[0], temp_form_B) temp_team = mirroring.mirroring_team(self.teamB[1]) logging.info('Cargando %s', self.teamA[1]) #create a temporally file that mirror the formation of B team, #because it's written thinking in A team try: clips.Load(self.teamA[1]) except clips.ClipsError as e: logging.error("####################") logging.error("ERROR de clips: %s", e) logging.error("Mensaje: ") logging.error(clips.ErrorStream.Read()) logging.error("####################") raise FileError( _('Error parsing the file ') + self.teamA[1] + "\n" + e) logging.info('Cargando %s', self.teamB[1]) try: clips.Load(temp_team) except clips.ClipsError as e: logging.error("####################") logging.error("ERROR de clips: %s", e) logging.error("Mensaje: ") logging.error(clips.ErrorStream.Read()) logging.error("####################") os.remove(temp_team) raise FileError(_('Error parsing the file ') + self.teamB[1]) os.remove(temp_team) os.remove(temp_form_A) os.remove(temp_form_B) try: fA.LoadFunctions(clips) logging.info('Cargando %s', self.teamA[0]) clips.Load(self.teamA[0]) except clips.ClipsError as e: logging.error("####################") logging.error("ERROR de clips: %s", e) logging.error("Mensaje: ") logging.error(clips.ErrorStream.Read()) logging.error("####################") raise FileError(_('Error parsing the file ') + self.teamA[0]) temp_rules = mirroring.mirroring_rules(self.teamB[0]) #same thing that for the formation, but this time using the rules try: fB.LoadFunctions(clips) logging.info('Cargando %s', self.teamB[0]) clips.Load(temp_rules) except clips.ClipsError as e: os.remove(temp_rules) logging.error("####################") logging.error("ERROR de clips: %s", e) logging.error("Mensaje: ") logging.error(clips.ErrorStream.Read()) logging.error("####################") raise FileError( _('Error parsing the file ') + self.teamB[0] + "\n") os.remove(temp_rules) clips.Reset() #restart the environment clips.Run() #start the simulation t = clips.StdoutStream.Read() #print the output clipsOutputFile = open("clipsOutputFile", "w") clipsOutputFile.write(t) clipsOutputFile.close() f = clips.FactList() last_fact = f[len(f) - 1].PPForm() prev_last_fact = f[len(f) - 2].PPForm() winner = self.__define_winner(last_fact, prev_last_fact) return winner