def ReloadClipsModels(self): ## Load model if self.model != None: try: clips.Load(self.model) except: raise ValueError, "Failed to load model" elif self.model_path != None and len(self.models) > 0: pm = 0 for m in self.models: mfile = "%s/%s.clp" % (self.model_path, m) if check_file_read(mfile): try: clips.Load(mfile) except: continue pm += 1 if pm == 0: raise ValueError, "Not enough models" elif self.main.args.shell == True: self.main.log( "info", "No models were provided, but Interactive shell were requested" ) else: raise ValueError, "Mo model specified"
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 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 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 bootstrap_dir(self, path): for f, fpath, fmod in get_dir_content(path): try: print fpath clips.Load(fpath) except KeyboardInterrupt: raise ValueError, "Error in bootstrapping from %s" % fpath
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 __init__(self): connect_rules(self) #mod=self.new_module('MAIN') #print (eng.clips_init()) clips.Clear() clips.Load('astrules.clp') clips.Reset()
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 guardarEnfermedad(request): if request.method == 'POST': sintomas = [] preguntas = [] form = request.POST nombre = request.POST.get("nombre") codigo = request.POST.get("codigo").replace(" ","") print codigo print type(codigo) causas = request.POST.get("causas") tratamiento = request.POST.get("tratamiento") sintomas = ast.literal_eval(form["sintomas"]) p = form["preguntas"].encode('UTF-8', 'replace') preguntas = ast.literal_eval(p) print type(preguntas) str_asserts = "" clips.Load("posibles-enfermedades.clp") try: enfermedad = Enfermedad(codigo=codigo,nombre=nombre,causas=causas,tratamiento=tratamiento) enfermedad.save() for id_sintoma in sintomas: print id_sintoma sintoma = SignoGeneral.objects.get(pk=id_sintoma) print sintoma e = EnfermedadSignoGeneral(signo_general=sintoma,enfermedad=enfermedad) e.save() str_asserts+= "(signo "+sintoma.identificador+" )" print "aqui no se cae" for pregunta in preguntas: print pregunta print type(pregunta) p = PreguntaEnfermedad(enfermedad=enfermedad,pregunta=pregunta) p.save() print "aqui no se cae" clips.Build(""" (defrule """+enfermedad.codigo+" "+str_asserts+""" => (python-call add_enfermedad """+str(enfermedad.pk)+" \""+enfermedad.nombre+"\")"+""" )""") clips.Save("posibles-enfermedades.clp") except Exception as e: print e enfermedad.delete() return HttpResponse(0) return HttpResponse(enfermedad.pk)
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 ReloadClipsModules(self): import posixpath ## Reload CLIPS modules for dir in self.mods.keys(): for mod in self.mods[dir].keys(): self.main.log("debug", "Loading PYCLIPS: %s" % mod) self.load_module(mod) if self.bootstrap_file != None: ## We do have a bootstrap try: clips.Load(self.bootstrap_file) except: raise ValueError, "Can not load bootstrap.clp" clp_base = posixpath.dirname(self.bootstrap_file) + "/bootstrap" if check_directory(clp_base): self.bootstrap_dir(clp_base) other_base = os.environ["HOME"] + ".zpp/bootstrap" if check_directory(other_base): self.bootstrap_dir(other_base)
def main(): """ Run bot. """ # Set default encoding to utf-8 reload(sys) sys.setdefaultencoding('utf-8') # Load the Beer EXpert system clips.Load('clips/beerex.clp') # Get the Telegram Bot Authorization Token token = os.environ.get('TOKEN') # Create the updater and pass it the bot's token updater = Updater(token) # Get the dispatcher to register handlers dispatcher = updater.dispatcher # Handler registers dispatcher.add_handler(CommandHandler('start', start)) dispatcher.add_handler(CommandHandler('new', new)) dispatcher.add_handler(MessageHandler(Filters.command, unknown)) dispatcher.add_handler(MessageHandler(Filters.text, handleEvent)) dispatcher.add_handler(CallbackQueryHandler(imageButton)) # Log all errors dispatcher.add_error_handler(error) # Start the bot updater.start_webhook(listen='0.0.0.0', port=int(os.environ.get('PORT', '5000')), url_path=token) updater.bot.set_webhook('https://beerex-telegram-bot.herokuapp.com/' + token) # updater.start_polling() # Run the bot until you press Ctrl-C or the process receives SIGINT, SIGTERM or SIGABRT. This should # be used most of the time, since start_polling() is non-blocking and will stop the bot gracefully. updater.idle()
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 __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
import clips clips.Load("vchro.clp") clips.Reset() clips.Run() s = clips.StdoutStream.Read() print s #clips.PrintFacts()
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 define_init_rules(): clips.Load("rules.clp") clips.Reset()
def define_IO_Routines(): clips.RegisterPythonFunction(pyprintout) clips.RegisterPythonFunction(pyreadline) clips.RegisterPythonFunction(pyread) clips.RegisterPythonFunction(capture_error) clips.Load("IO.clp")
for h in hechos: if h.Slots['id'] == user: if h.Relation == "alumnoInfantil": context[u'Lengua y cultura inglesas'] = h.Slots['ingles'] context[u'Educación Física'] = h.Slots['efisica'] context[u'Necesidades educativas especiales'] = h.Slots['nde'] context[u'Religión'] = h.Slots['religion'] elif h.Relation == "alumnoPrimaria": context[u'Lengua extranjera: Inglés'] = h.Slots['ingles'] context[u'Lengua extranjera: Francés'] = h.Slots['frances'] context[u'Música'] = h.Slots['musica'] context[u'Educación Física'] = h.Slots['efisica'] context[u'Pedagogía Terapéutica'] = h.Slots['apt'] context[u'Audición y Lenguaje'] = h.Slots['al'] context[u'Religión'] = h.Slots['religion'] h.Retract() break print context lista = u"" for idx, (mencion, puntos) in enumerate( sorted(context.items(), key=lambda x: x[1], reverse=True)): lista += u'<li class="list-group-item"><span class="badge">{3}/5</span><h{0}>{1}.- {2}</h{0}></li>'.format( 6 - puntos, idx + 1, mencion, puntos) return render_template("resultados.html", lista=lista, idx=2) if __name__ == '__main__': clips.Load("magisterio.clp") clips.Reset() app.run(debug=True)
def load_rules(rules_file): clips.Load(rules_file)