Beispiel #1
0
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 m_button1OnButtonClick(self, event):
        answers.append('yes')
        global step
        step = step + 1
        self.parent.status.gauge.SetValue(10 * step)

        if step == len(questions):
            createStepGlobal(step)
            clips.BuildGlobal('ten_answer', 1)
            clips.Run()
            changePanel(self.parent, 6)

        else:
            createStepGlobal(step)
            self.m_staticText1.SetLabel(questions[step])
            # 1 == YES  0 == NO
            if step == 1:
                clips.BuildGlobal('one_answer', 1)
            elif step == 9:
                clips.BuildGlobal('nine_answer', 1)

            if step == 1 and answers[0] == 'yes':
                step = step + 1
                answers.append('NULL')
                changePanel(self.parent, 1)
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 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
Beispiel #5
0
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()
Beispiel #6
0
def nextUIState(bot, update):
    """
    Re-creates the dialog window to match the current state in working memory.
    """

    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)
    state = current_ui[0].Slots['state']
    if state == 'initial':
        clips.Assert('(next %s)' % current_id)
        clips.Run()
        nextUIState(bot, update)
    elif state == 'final':
        keyboard = [[KeyboardButton(text=emojize(':back: Previous', use_aliases=True))],
                    [KeyboardButton(text=emojize(':repeat: Restart', use_aliases=True))],
                    [KeyboardButton(text=emojize(':x: Cancel', use_aliases=True))]]
        update.message.reply_text(text=current_ui[0].Slots['display'],
                                  parse_mode=ParseMode.MARKDOWN,
                                  disable_web_page_preview=True,
                                  reply_markup=ReplyKeyboardMarkup(keyboard))
    else:
        keyboard = list()
        for answer in current_ui[0].Slots['valid-answers']:
            keyboard.append([KeyboardButton(text=answer)])
        if current_ui[0].Slots['help']:
            keyboard.append([KeyboardButton(text=emojize(':sos: Help', use_aliases=True))])
        if current_ui[0].Slots['why']:
            keyboard.append([KeyboardButton(text=emojize(':question: Why', use_aliases=True))])
        if len(clips.Eval('(find-fact ((?s state-list)) TRUE)')[0].Slots['sequence']) > 2:
            keyboard.append([KeyboardButton(text=emojize(':back: Previous', use_aliases=True))])
        keyboard.append([KeyboardButton(text=emojize(':x: Cancel', use_aliases=True))])
        update.message.reply_text(text=current_ui[0].Slots['display'],
                                  reply_markup=ReplyKeyboardMarkup(keyboard))
Beispiel #7
0
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 execute():
    #clips.PrintFacts()
    #clips.PrintRules()
    clips.Run()
    s = clips.StdoutStream.Read()
    #clips.PrintFacts()
    print s
Beispiel #9
0
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)
Beispiel #10
0
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'])
Beispiel #11
0
 def OnLanzarSimulacion(self, event):
     """Lanzar toda la simulacion"""
     if self.clipsFile != "":
         clips.Assert("(Seguir S)")
         clips.Run()
         self.office.updatePeopleLocation()
         self.Refresh()
     else:
         dlg = wx.MessageDialog(self, "No se ha cargado fichero .clp",
                                "Error en ASSERT", wx.OK)
         dlg.ShowModal()
Beispiel #12
0
 def Run(self):
     import traceback
     clips.Run()
     out = clips.StdoutStream.Read()
     ret = ""
     if type(out) == type(""):
         ret = out
     err = clips.ErrorStream.Read()
     if type(err) == type(""):
         ret += err
         ret += traceback.format_exc()
     return ret
Beispiel #13
0
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()
Beispiel #14
0
 def OnNuevoCiclo(self, event):
     """Incrementar ciclo de la simulacion"""
     if self.clipsFile != "":
         clips.Assert("(Seguir S)")
         clips.Run()
         self.office.updatePeopleLocation()
         self.Refresh()
         error = clips.ErrorStream.Read()
         if error != None:
             print(error)
     else:
         dlg = wx.MessageDialog(self, "No se ha cargado fichero .clp",
                                "Error en ASSERT", wx.OK)
         dlg.ShowModal()
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)
Beispiel #16
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()
Beispiel #17
0
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 execute():
	print "loaded:"
	#clips.PrintFacts()
	clips.PrintRules()
	clips.DebugConfig.WatchAll()
	clips.Run()
	t = clips.TraceStream.Read()
	s = clips.StdoutStream.Read()

	
	

	
	print "-------------------------"
	print "ACTIVATION TRACE"
	print t
	
	print "-------------------------"
	print "PLANNING OUTPUT"
	print s
    def m_button2OnButtonClick(self, event):
        global step
        step = step + 1
        self.parent.status.gauge.SetValue(10 * step)
        if step == len(questions):
            createStepGlobal(step)
            clips.BuildGlobal('ten_answer', 0)
            clips.Run()
            changePanel(self.parent, 6)
        else:
            createStepGlobal(step)
            self.m_staticText1.SetLabel(questions[step])
            answers.append('no')

            if step == 1 and answers[0] == 'no':
                clips.Assert("(YN_second)")
                changePanel(self.parent, 2)
            if step == 1:
                clips.BuildGlobal('one_answer', 0)
            elif step == 9:
                clips.BuildGlobal('nine_answer', 0)
Beispiel #20
0
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()
Beispiel #21
0
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()
Beispiel #22
0
def resultados(user):
    cuestiones = [(k[6:], v) for k, v in request.form.items()
                  if k.startswith('hecho_')]
    for hecho, respuesta in cuestiones:
        if respuesta == "Si":
            clips.Assert("(%s (id %s))" % (hecho, user))
        elif respuesta == "ingles":
            clips.Assert("(%s (id %s) (idioma %s))" % (hecho, user, respuesta))
        elif respuesta == "frances":
            clips.Assert("(%s (id %s) (idioma %s))" % (hecho, user, respuesta))
    clips.Run()
    context = {}
    hechos = clips.FactList()[1:]
    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)
Beispiel #23
0
    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()
Beispiel #24
0
def execute():
    add_wrong_rules()
    clips.Run()
Beispiel #25
0
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
clips.DebugConfig.ActivationsWatched = True
r0 = clips.BuildRule("sayhello", "(hello)",
                     '(printout stdout "hello, world!" crlf)')
print r0.PPForm()
clips.Assert("(hello)")
t = clips.TraceStream.Read()
print t
clips.Run()
t = clips.StdoutStream.Read()
print t
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)')
Beispiel #28
0
def run_checks(facts_file, rules_file):
    clips.Reset()
    load_rules(rules_file)
    load_facts(facts_file)
    clips.Run()
Beispiel #29
0
 def run(self):
     clips.Run()
    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