def cuestiones(): user = request.form['id'] tipo = request.form['tipo'] if tipo == "primaria": clips.Assert(("(alumnoPrimaria (id %s))" % user)) ret = render_template("primaria.html", user=user, idx=1) elif tipo == "infantil": clips.Assert(("(alumnoInfantil (id %s))" % user)) ret = render_template("infantil.html", user=user, idx=1) return ret
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 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 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 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))
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 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()
def load_facts_file_to_clips(): G = kb_services.load_semantic_network() # get all nouns nouns = kb_services.all_subclasses(G, 'stuff') + kb_services.all_objects(G, 'stuff') facts_to_load = [] for each_noun in nouns: att_dict = kb_services.get_attribute(G, each_noun, 'attribute') #print att_dict for each_attribute in att_dict: if each_attribute == 'nop': facts_to_load.append("(fact " + each_noun + " " + each_attribute + " " + att_dict[each_attribute][0] + ")") else: for each_value in att_dict[each_attribute]: #print "(fact " + each_noun + " " + each_attribute + " " + each_value + ")" facts_to_load.append("(fact " + each_noun + " " + each_attribute + " " + each_value + ")") for each_fact in facts_to_load: fi = clips.Assert(each_fact) fi = clips.Assert("(id_count 1)")
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 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 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)
def load_facts_file_to_clips(file_name): file = open(file_name, 'r') relations = [] lines = file.readlines() for line in lines: if re.match('\([\?\w]+\s+\w+\s+\w+\)\s+', line): relation = re.split('[^a-zA-Z0-9\?_]+', line)[1:4] relations.append(relation) #print relation file.close() for each in relations: facto = "(fact " + each[0] + " " + each[1] + " " + each[2] + ")" #print "asserted fact: ", facto fi = clips.Assert(facto)
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 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 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)
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 assert_this(self): #TODO: Convert value to CLIPS string value = '"' + self.value + '"' other_props = [ "(%s %s)" % (flag, str(value).upper()) for flag, value in self.flags.iteritems() ] if (self.children): child_ids = [str(child._id) for child in self.children] fstr = '(ASTTemplate (id %s) (name %s) (value %s) %s (children %s) )' % ( self._id, self.name, value, " ".join(other_props), " ".join(child_ids)) else: fstr = '(ASTTemplate (id %s) (name %s) (value %s) %s)' % ( self._id, self.name, value, " ".join(other_props), ) #print fstr self._fact = clips.Assert(fstr).Index _fact_lookup[self._fact] = self
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()
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 createStepGlobal(step): if step == 1: clips.Assert("(step-one)") elif step == 2: clips.Assert("(step-two)") elif step == 3: clips.Assert("(step-three)") elif step == 4: clips.Assert("(step-four)") elif step == 5: clips.Assert("(step-five)") elif step == 6: clips.Assert("(step-six)") elif step == 7: clips.Assert("(step-seven)") elif step == 8: clips.Assert("(step-eight)") elif step == 9: clips.Assert("(step-nine)") elif step == 10: clips.Assert("(step-ten)") elif step == 11: clips.Assert("(step-eleven)")
def resource_handler(req_aid, lat, longt, quantity, allies): if quantity == 0: return gathered_quantity = 0 rangedistance = 50 if req_aid == "Food": try: food = Food.objects.all() while (gathered_quantity <= quantity) and (rangedistance <= 1500): for aid in food: print( str(lat) + " " + str(longt) + "acquired " + str(aid.user.latitude) + " " + str(aid.user.longitude) + " " + str(rangedistance) + " " + str(quantity) + " gr" + str(gathered_quantity)) if distance((lat, longt), (aid.user.latitude, aid.user.longitude)) <= rangedistance: try: print("got " + aid.user.username) a = clips.Fact(allies) a.Slots['username'] = aid.user.username a.Slots['foraid'] = req_aid a.Slots['action'] = "Alert" a.Slots['quantity'] = aid.packet a.Assert() gathered_quantity = gathered_quantity + aid.packet except clips.ClipsError: print("Already Asserted Fact") rangedistance = rangedistance + 50 except Food.DoesNotExist: pass if req_aid == "Volunteer": try: vol = Volunteer.objects.all() while (gathered_quantity <= quantity) and (rangedistance <= 1500): for aid in vol: #print (str(lat)+" "+str(long)+"acquired " + str(aid.user.latitude) + " " + str(aid.user.longitude)+" "+str(rangedistance)+" "+str(quantity)+" gr"+str(gathered_quantity)) if distance((lat, longt), (aid.user.latitude, aid.user.longitude)) <= rangedistance: try: print("got " + aid.user.username) a = clips.Fact(allies) a.Slots['username'] = aid.user.username a.Slots['foraid'] = req_aid a.Slots['action'] = "Alert" a.Slots['quantity'] = aid.humanaid a.Assert() gathered_quantity = gathered_quantity + aid.humanaid except clips.ClipsError: print("Already Asserted Fact") rangedistance = rangedistance + 50 except Volunteer.DoesNotExist: pass if req_aid == "Hospital": try: hos = Hospital.objects.all() while (gathered_quantity <= quantity) and (rangedistance <= 1500): for aid in hos: #print (str(lat)+" "+str(long)+"acquired " + str(aid.user.latitude) + " " + str(aid.user.longitude)+" "+str(rangedistance)+" "+str(quantity)+" gr"+str(gathered_quantity)) if distance((lat, longt), (aid.user.latitude, aid.user.longitude)) <= rangedistance: try: print("got " + aid.user.username) a = clips.Fact(allies) a.Slots['username'] = aid.user.username a.Slots['foraid'] = req_aid a.Slots['action'] = "Alert" a.Slots['quantity'] = aid.canoccupy a.Assert() gathered_quantity = gathered_quantity + aid.canoccupy except clips.ClipsError: print("Already Asserted Fact") rangedistance = rangedistance + 50 except Hospital.DoesNotExist: pass if req_aid == "Accommodation": try: acc = Accomadation.objects.all() while (gathered_quantity <= quantity) and (rangedistance <= 1500): for aid in acc: #print (str(lat)+" "+str(long)+"acquired " + str(aid.user.latitude) + " " + str(aid.user.longitude)+" "+str(rangedistance)+" "+str(quantity)+" gr"+str(gathered_quantity)) if distance((lat, longt), (aid.user.latitude, aid.user.longitude)) <= rangedistance: try: print("got " + aid.user.username) a = clips.Fact(allies) a.Slots['username'] = aid.user.username a.Slots['foraid'] = req_aid a.Slots['action'] = "Alert" a.Slots['quantity'] = aid.capacity a.Assert() gathered_quantity = gathered_quantity + aid.capacity except clips.ClipsError: print("Already Asserted Fact") rangedistance = rangedistance + 50 except Accomadation.DoesNotExist: pass if req_aid == "Water": try: wat = Water.objects.all() while (gathered_quantity <= quantity) and (rangedistance <= 1500): for aid in wat: #print (str(lat)+" "+str(long)+"acquired " + str(aid.user.latitude) + " " + str(aid.user.longitude)+" "+str(rangedistance)+" "+str(quantity)+" gr"+str(gathered_quantity)) if distance((lat, longt), (aid.user.latitude, aid.user.longitude)) <= rangedistance: try: print("got " + aid.user.username) a = clips.Fact(allies) a.Slots['username'] = aid.user.username a.Slots['foraid'] = req_aid a.Slots['action'] = "Alert" a.Slots['quantity'] = aid.quantity a.Assert() gathered_quantity = gathered_quantity + aid.quantity except clips.ClipsError: print("Already Asserted Fact") rangedistance = rangedistance + 50 except Water.DoesNotExist: pass if req_aid == "RescueTool": try: restool = Rescuetool.objects.all() while (gathered_quantity <= quantity) and (rangedistance <= 1500): for aid in restool: #print (str(lat)+" "+str(long)+"acquired " + str(aid.user.latitude) + " " + str(aid.user.longitude)+" "+str(rangedistance)+" "+str(quantity)+" gr"+str(gathered_quantity)) if distance((lat, longt), (aid.user.latitude, aid.user.longitude)) <= rangedistance: try: print("got " + aid.user.username) a = clips.Fact(allies) a.Slots['username'] = aid.user.username a.Slots['foraid'] = req_aid a.Slots['action'] = "Alert" a.Slots['quantity'] = aid.box a.Assert() gathered_quantity = gathered_quantity + aid.box except clips.ClipsError: print("Already Asserted Fact") rangedistance = rangedistance + 50 except Rescuetool.DoesNotExist: pass if req_aid == "FirstAid": try: firstaid = Firstaid.objects.all() while (gathered_quantity <= quantity) and (rangedistance <= 1500): for aid in firstaid: #print (str(lat)+" "+str(long)+"acquired " + str(aid.user.latitude) + " " + str(aid.user.longitude)+" "+str(rangedistance)+" "+str(quantity)+" gr"+str(gathered_quantity)) if distance((lat, longt), (aid.user.latitude, aid.user.longitude)) <= rangedistance: try: print("got " + aid.user.username) a = clips.Fact(allies) a.Slots['username'] = aid.user.username a.Slots['foraid'] = req_aid a.Slots['action'] = "Alert" a.Slots['quantity'] = aid.kit a.Assert() gathered_quantity = gathered_quantity + aid.kit except clips.ClipsError: print("Already Asserted Fact") rangedistance = rangedistance + 50 except Firstaid.DoesNotExist: pass if req_aid == "Transport-Human": try: thuman = TransportHuman.objects.all() while (gathered_quantity <= quantity) and (rangedistance <= 1500): for aid in thuman: #print (str(lat)+" "+str(long)+"acquired " + str(aid.user.latitude) + " " + str(aid.user.longitude)+" "+str(rangedistance)+" "+str(quantity)+" gr"+str(gathered_quantity)) if distance((lat, longt), (aid.user.latitude, aid.user.longitude)) <= rangedistance: try: print("got " + aid.user.username) a = clips.Fact(allies) a.Slots['username'] = aid.user.username a.Slots['foraid'] = req_aid a.Slots['action'] = "Alert" a.Slots['quantity'] = aid.capacity a.Assert() gathered_quantity = gathered_quantity + aid.capacity except clips.ClipsError: print("Already Asserted Fact") rangedistance = rangedistance + 50 except TransportHuman.DoesNotExist: pass if req_aid == "Transport-Goods": try: tgoods = TransportGoods.objects.all() while (gathered_quantity <= quantity) and (rangedistance <= 1500): for aid in tgoods: #print (str(lat)+" "+str(long)+"acquired " + str(aid.user.latitude) + " " + str(aid.user.longitude)+" "+str(rangedistance)+" "+str(quantity)+" gr"+str(gathered_quantity)) if distance((lat, longt), (aid.user.latitude, aid.user.longitude)) <= rangedistance: try: print("got " + aid.user.username) a = clips.Fact(allies) a.Slots['username'] = aid.user.username a.Slots['foraid'] = req_aid a.Slots['action'] = "Alert" a.Slots['quantity'] = aid.capacity a.Assert() gathered_quantity = gathered_quantity + aid.capacity except clips.ClipsError: print("Already Asserted Fact") rangedistance = rangedistance + 50 except TransportGoods.DoesNotExist: pass if req_aid == "JCB": try: mach1 = Machine.objects.all() while (gathered_quantity <= quantity) and (rangedistance <= 1500): for aid in mach1: if aid.jcb != 0: #print (str(lat)+" "+str(long)+"acquired " + str(aid.user.latitude) + " " + str(aid.user.longitude)+" "+str(rangedistance)+" "+str(quantity)+" gr"+str(gathered_quantity)) if distance((lat, longt), (aid.user.latitude, aid.user.longitude)) <= rangedistance: try: print("got " + aid.user.username) a = clips.Fact(allies) a.Slots['username'] = aid.user.username a.Slots['foraid'] = req_aid a.Slots['action'] = "Alert" a.Slots['quantity'] = aid.jcb a.Assert() gathered_quantity = gathered_quantity + aid.jcb except clips.ClipsError: print("Already Asserted Fact") rangedistance = rangedistance + 50 except Machine.DoesNotExist: pass if req_aid == "FireEngine": try: mach2 = Food.objects.all() while (gathered_quantity <= quantity) and (rangedistance <= 1500): for aid in mach2: if aid.fireengine != 0: #print (str(lat)+" "+str(long)+"acquired " + str(aid.user.latitude) + " " + str(aid.user.longitude)+" "+str(rangedistance)+" "+str(quantity)+" gr"+str(gathered_quantity)) if distance((lat, longt), (aid.user.latitude, aid.user.longitude)) <= rangedistance: try: print("got " + aid.user.username) a = clips.Fact(allies) a.Slots['username'] = aid.user.username a.Slots['foraid'] = req_aid a.Slots['action'] = "Alert" a.Slots['quantity'] = aid.fireengine a.Assert() gathered_quantity = gathered_quantity + aid.fireengine except clips.ClipsError: print("Already Asserted Fact") rangedistance = rangedistance + 50 except Machine.DoesNotExist: pass if req_aid == "Ambulance": try: mach3 = Machine.objects.all() while (gathered_quantity <= quantity) and (rangedistance <= 1500): for aid in mach3: if aid.ambulance != 0: #print (str(lat)+" "+str(long)+"acquired " + str(aid.user.latitude) + " " + str(aid.user.longitude)+" "+str(rangedistance)+" "+str(quantity)+" gr"+str(gathered_quantity)) if distance((lat, longt), (aid.user.latitude, aid.user.longitude)) <= rangedistance: try: print("got " + aid.user.username) a = clips.Fact(allies) a.Slots['username'] = aid.user.username a.Slots['foraid'] = req_aid a.Slots['action'] = "Alert" a.Slots['quantity'] = aid.ambulance a.Assert() gathered_quantity = gathered_quantity + aid.ambulance except clips.ClipsError: print("Already Asserted Fact") rangedistance = rangedistance + 50 except Machine.DoesNotExist: pass if gathered_quantity < quantity: try: clips.Assert( "(Message \"Searched Aid : " + req_aid + " # Quantity is Unavailable in Perimeter , Gathered Quantity :" + str(gathered_quantity) + "\")") except clips.ClipsError: print("Error") return
def Assert(fact): _clipsLock.acquire() clips.Assert(fact) _clipsLock.release()
import clips clips.Reset() clips.Assert("(duck)") clips.BuildRule("duck-rule", "(duck)", "(assert (quack))", "the Duck Rule") clips.PrintRules() clips.PrintAgenda() clips.PrintFacts() clips.Run() clips.PrintFacts()
# Function to convert user question into clips form def parse_input_to_string(): user_input = raw_input("Enter your question : ") words_list = user_input.lower().split() final_string = "" for word in words_list : final_string += '"' + word +'"' return final_string # importing clips library import clips # get input from user and store it in a variable called user_input user_input = parse_input_to_string(); # build a global variable using clips library called Final_answer to store final answer inside it Final_answer = clips.BuildGlobal('Final_answer','sorry, i have no answers for you at this moment.') # load clips file clips.BatchStar("algorithm.clp") # reset clips environment clips.Reset() # add new fact using assert with user inputs clips.Assert('(User_input'+user_input+')') # run the program clips.Run() # print out the final answer print "Phronesis said : " + Final_answer.Value # t = clips.StdoutStream.Read() # print t
def launch_planner(com): load_expert_shell() load_facts_file_to_clips() fi = clips.Assert(com) execute()
def load_initial_facts(command_fact): fi = clips.Assert(command_fact) for each in initial_facts: fi = clips.Assert(each)
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 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}