def findShortestPath(from_input, to_input): prolog = Prolog() loadDatabase(prolog) prolog_query = "path(" + from_input + "," + to_input + ",PATH,COST)" shortest_path_result = list(prolog.query(prolog_query)) path_list = [] shortest_path_lst = shortest_path_result if len(shortest_path_lst) <= 0: return False for i in range(len(shortest_path_lst[0]['PATH'])): path_list.append(str(shortest_path_result[0]['PATH'][i])) train_query = "theTrainIs(" + str(path_list) + ",TRAIN)" train_result = list(prolog.query(train_query)) train_list = [] for i in range(len(train_result[0]['TRAIN'])): train_list.append(str(train_result[0]['TRAIN'][i])) path_type_list = [] include_walk_query = "includeWalk(" + str(train_list) + ",PATH_TYPE)" include_walk_result = list(prolog.query(include_walk_query)) for i in range(len(include_walk_result[0]['PATH_TYPE'])): path_type_list.append(str(include_walk_result[0]['PATH_TYPE'][i])) print("Train: " + str(train_list)) print "" print("Train+Walk: " + str(path_type_list)) print "" print("TrainLen: " + str(len(train_list)) + "->" + str(len(path_type_list))) return path_list, shortest_path_result[0]['COST']
def main(): prolog = Prolog() #membuka file coins.pl prolog.consult("prolog_file/coins.pl") #mendeklarasi nilai count dan total #menginputkan nilai count dan nilai total berupa angka count = int(input("Berapa jumlah koin(default: 100)? ") or 100) total = int(input("Jumlah target total (default: 500)? ") or 500) #melakukan perulangan dengan menampilkan nilai yang ada di dalam list #enumerate berfungsi untuk mengembalikan sebuah objek iterable yang setiap itemnya memiliki indeks #memanggil fungsi coins pada prolog for i, soln in enumerate(prolog.query("coins(S, %d, %d)." % (count, total))): # [1,5,10,50,100] S = zip(soln["S"], [1, 5, 10, 50, 100]) print(i), #cetak nilai #melakukan perulangan untuk menampilkan angka perkalian for c, v in S: print("%dx%d" % (c, v)), #cetak perkalian print #cetak hasil perulangan #fungsi list yaitu mengembalikan list berisi anggota-anggota dari objek yang menjadi argumennya #jika argumennya kosong, maka fungsi ini akan mengembalikan list kosong #jika argumennya berisikan data, maka yang digunakan adalah data-data yang digunakan dari list tersebut #hasil akhirnya akan menampilkan perhitungan perkalian dari jumlah nilai yang diinputkan list(prolog.query("coins(S, %d, %d)." % (count, total)))
def main(): prolog = Prolog() prolog.consult("coins.pl") count = int(input("How many coins (default: 100)? ") or 100) total = int(input("What should be the total (default: 500)? ") or 500) for i, soln in enumerate(prolog.query("coins(S, %d, %d)." % (count,total))): S = zip(soln["S"], [1, 5, 10, 50, 100]) print(i, end=" ") for c, v in S: print("%dx%d" % (c,v), end=" ") print() list(prolog.query("coins(S, %d, %d)." % (count,total)))
def main(): prolog = Prolog() prolog.consult("coins.pl") count = int(input("How many coins (default: 100)? ") or 100) total = int(input("What should be the total (default: 500)? ") or 500) for i, soln in enumerate(prolog.query("coins(S, %d, %d)." % (count,total))): # [1,5,10,50,100] S = list(zip(soln["S"], [1, 5, 10, 50, 100])) print(i, end=' ') for c, v in S: print("%dx%d" % (c,v), end=' ') print() list(prolog.query("coins(S, %d, %d)." % (count,total)))
def main(): prolog = Prolog() prolog.consult("kanankiri.pl") #membaca file prolog (kanankiri.pl) kiri = int(input("Berapa jumlahnya kiri? ") or 10) total = int(input("Berapa total semuanya? ") or 100) for i, soln in enumerate( prolog.query("kanankiri(S, %d, %d)." % (kiri, total))): S = zip(soln["S"], [1, 5, 10, 50, 100]) print(i), for c, v in S: print("%dx%d" % (c, v)) print() list(prolog.query("kanankiri(S, %d, %d)." % (kiri, total)))
def diagnose(self, symptoms, age_group=None): """Returns a list of possible diagnosis, if any, given a list of symptoms. For example, if german measles has the symptoms 'runny nose', 'fever', 'headache' and 'rash', the system will return a list containing a dict with the diagnosis. symptoms = ['runnynose', 'fever', 'headache', 'rash'] doctor = Doctor('medical') results = doctor.diagnose(symptoms) results >>> [{'Diagnosis': 'germanmeasles'}] The diagnosis can be accessed with the key 'Diagnosis'. NOTE: The capital D is important. diagnosis = results[0] diagnosis['Diagnosis'] >>> 'germanmeasles' """ prolog = Prolog() if age_group is not None: prolog.assertz('age_group(patient,%s)' % age_group) for symptom in symptoms: prolog.assertz('symptom(patient,%s)' % symptom) prolog.consult(self.prolog_file) return list(prolog.query('hypothesis(patient,Diagnosis)'))
def _query(pl=None, query=None, debug=False): if not query: return if not pl: pl = Prolog() pl.consult('init.pl') if isinstance(query[0], str): query = [query] query_list = [] var_list = [] for pred, args in query: arg_list = [] for arg in args: if (isinstance(arg, str) and arg[:3] == '_v:'): # and arg[0] == arg[0].upper() var = arg[3:] var_list += [var] arg_list += [var] elif (isinstance(arg, str) and '^^' in arg): arg_list += [arg] elif (isinstance(arg, list)): arg_list += [f"{arg}"] else: arg_list += [f"'{arg}'"] arg_str = ','.join(arg_list) query_list += [pred + '(' + arg_str + ')'] query_str = ','.join(query_list) if debug: print(query_str, end="\n\n") return var_list, pl.query(query_str)
def query_prolog(data, output): from pyswip.prolog import Prolog from pyswip.easy import call, Functor, registerForeign prolog = Prolog() # handle for Prolog interpreter # Fetch Prolog inputs distance = str(data[0]) price = str(data[1]) type = str(data[2]) veg_options = str(data[3]) # open KB file from static location prolog.consult('static/KB.pl') # assert knowledge at top of KB prolog.asserta("veg_options(" + veg_options + ")") prolog.asserta("distance(" + distance + ")") prolog.asserta("price(" + price + ")") prolog.asserta("type(" + type + ")") # get results from KB results = [ sol['X'] for sol in prolog.query("recommendation(X).", maxresult=1) ] if results: output.put(("You should eat at " + results[0] + "!")) else: output.put(("No restaurant could be identified!"))
def main(): def notify(t): print "move disk from %s pole to %s pole." % tuple(t) notify.arity = 1 prolog = Prolog() registerForeign(notify) prolog.consult("hanoi.pl") list(prolog.query("hanoi(%d)" % N))
def main(): """ Trying to modify this example https://github.com/yuce/pyswip/blob/master/examples/coins/coins.py to provide a nice pythonic interface to petyhaker's code """ prolog = Prolog() prolog.consult("agent.pl") count = int(raw_input("How many coins (default: 100)? ") or 100) total = int(raw_input("What should be the total (default: 500)? ") or 500) for i, soln in enumerate(prolog.query("coins(S, %d, %d)." % (count, total))): # [1,5,10,50,100] S = zip(soln["S"], [1, 5, 10, 50, 100]) print i, for c, v in S: print "%dx%d" % (c, v), print list(prolog.query("coins(S, %d, %d)." % (count, total)))
def main(): #digunakan untuk membuat fungsi main() N = 3 #pendeklarasian nilai N adalah 3 INTERACTIVITY = True prolog = Prolog() tower = Tower(N, INTERACTIVITY) notifier = Notifier(tower.move) registerForeign(notifier.notify) prolog.consult("prolog_file/hanoi.pl") list(prolog.query("hanoi(%d)" % N))
def main(): N = 3 INTERACTIVITY = True prolog = Prolog() tower = Tower(N, INTERACTIVITY) notifier = Notifier(tower.move) registerForeign(notifier.notify) prolog.consult("hanoi.pl") list(prolog.query("hanoi(%d)" % N))
def imprimirPlato(): p = Prolog() p.consult("plati.pl") resultados = [] for plato in p.query("platillo(_,A,_,_,_)"): r = plato["A"] resultados.append(str(r)) log = file("log.txt", "a") log.write(str(resultados) + "\n") log.close() return resultados
def restaurantesXtipo(tipocomida): p = Prolog() p.consult("rest.pl") resultados = [] for restaurante in p.query("restaurantesXtipo(A," + tipocomida + ")"): r = restaurante["A"] resultados.append(str(r)) log = file("log.txt", "a") log.write(str(resultados) + "\n") log.close() return resultados
def buscaRestaurantesXPais(pais): p = Prolog() p.consult("plati.pl") resultados = [] for restaurante in p.query("buscaRestXPais(Nombre," + pais + ")"): r = restaurante["Nombre"] resultados.append(str(r)) log = file("log.txt", "a") log.write(str(resultados) + "\n") log.close() return resultados
def imprimirRest(): p = Prolog() p.consult('rest.pl') resultados = [] for result in p.query("restaurante(A,_,_,_,_)"): r = result["A"] resultados.append(str(r)) log = file("log.txt", "a") log.write(str(resultados) + "\n") log.close() return resultados
def main(): prolog = Prolog() prolog.consult("puzzle1.pl") for soln in prolog.query("solve(B)."): #B = eval(soln["B"]) B = soln["B"] # [NW,N,NE,W,E,SW,S,SE] print "%d %d %d" % tuple(B[:3]) print "%d %d" % tuple(B[3:5]) print "%d %d %d" % tuple(B[5:]) cont = raw_input("Press 'n' to finish: ") if cont.lower() == "n": break
def platillosXrestIngrediente(restaurante, ingrediente): p = Prolog() p.consult("plati.pl") resultados = [] resultados.append("Lista de platillos de " + restaurante + " que incluyen " + ingrediente + ":") for restaurante in p.query("platillosXrestIngrediente(" + restaurante + ",Nombre,Sabor,Pais," + ingrediente + ")"): resultados.append(restaurante["Nombre"]) log = file("log.txt", "a") log.write(str(resultados) + "\n") log.close() return resultados
def main(): prolog = Prolog() prolog.consult("puzzle.pl") #membaca file prolog (puzzle.pl) for soln in prolog.query("solusi(B)."): #B = eval(soln["B"]) B = soln["B"] # [NW,N,NE,W,E,SW,S,SE] print("%d %d %d" % tuple(B[:3])) print("%d %d" % tuple(B[3:5])) print("%d %d %d" % tuple(B[5:])) cont = input("Tekan 'n' untuk selesai: ") if cont.lower() == "n": break
def main(): prolog = Prolog() prolog.consult("prolog_file/puzzle1.pl") #membuka file prolog puzzle.pl for soln in prolog.query( "solve(B)."): #menjalankan predikat solve seperti pada file prolog B = soln["B"] # [NW,N,NE,W,E,SW,S,SE] print("%d %d %d" % tuple(B[:3])) #mencetak angka pada papan print("%d %d" % tuple(B[3:5])) print("%d %d %d" % tuple(B[5:])) cont = input("Press 'n' to finish: ") if cont.lower() == "n": break #jika ditekan n, program selesai
def modified_run(self): try: from pyswip.prolog import Prolog p = Prolog() p.assertz('setup_prolog(1)') list(p.query('setup_prolog(1)')) except: print('----------------------') print('There is a problem with SWI-Prolog Installation') print('Please, check if you have it installed with shared Libraries') print('Installation guide: https://github.com/yuce/pyswip/blob/master/INSTALL') print('----------------------') orig_run(self)
def findShortestPath(from_input, to_input): prolog = Prolog() loadDatabase(prolog) prolog_query = "path(" + from_input + "," + to_input + ",PATH,COST)" shortest_path_result = list(prolog.query(prolog_query)) path_list = [] shortest_path_lst = shortest_path_result if len(shortest_path_lst) <= 0: return False for i in range(len(shortest_path_lst[0]['PATH'])): path_list.append(str(shortest_path_result[0]['PATH'][i])) return path_list, shortest_path_result[0]['COST']
def modified_run(self): try: from pyswip.prolog import Prolog p = Prolog() p.assertz('setup_prolog(1)') list(p.query('setup_prolog(1)')) except: print('----------------------') print('There is a problem with SWI-Prolog Installation') print( 'Please, check if you have it installed with shared Libraries') print( 'Installation guide: https://github.com/yuce/pyswip/blob/master/INSTALL' ) print('----------------------') orig_run(self)
def main(): prolog = Prolog() a1 = PL_new_term_refs(2) a2 = a1 + 1 t = PL_new_term_ref() ta = PL_new_term_ref() animal2 = PL_new_functor(PL_new_atom("animal"), 2) assertz = PL_new_functor(PL_new_atom("assertz"), 1) PL_put_atom_chars(a1, "gnu") PL_put_integer(a2, 50) PL_cons_functor_v(t, animal2, a1) PL_cons_functor_v(ta, assertz, t) PL_call(ta, None) print(list(prolog.query("animal(X,Y)", catcherrors=True)))
def partial_diagnosis(self, symptoms): prolog = Prolog() for file in self.prolog_files: prolog.consult(file) differntial_diagnosis = [] for symptom in symptoms: for result in prolog.query('hasSymptom(Illness, %s)' % symptom): differntial_diagnosis.append(result['Illness']) sick_list = [] # Removes multiple illnesses from the list sick_list = list(set(differntial_diagnosis)) return sick_list
def partial_diagnosis(self, symptoms): prolog = Prolog() for file in self.prolog_files: prolog.consult(file) differntial_diagnosis = [] for symptom in symptoms: for result in prolog.query("hasSymptom(Illness, %s)" % symptom): differntial_diagnosis.append(result["Illness"]) sick_list = [] # Removes multiple illnesses from the list sick_list = list(set(differntial_diagnosis)) return sick_list
def main(): prolog = Prolog() a1 = PL_new_term_refs(2) a2 = a1 + 1 t = PL_new_term_ref() ta = PL_new_term_ref() animal2 = PL_new_functor(PL_new_atom("animal"), 2) assertz = PL_new_functor(PL_new_atom("assertz"), 1) PL_put_atom_chars(a1, "gnu") PL_put_integer(a2, 50) # PL_cons_functor(t, animal2, a1, a2) PL_cons_functor_v(t, animal2, a1) PL_cons_functor_v(ta, assertz, t) PL_call(ta, None) # prolog.assertz("animal(gnu, 50)") print list(prolog.query("animal(X,Y)", catcherrors=True))
def buscaPlatillosRest(restaurante): p = Prolog() p.consult("plati.pl") resultados = [] for restaurante in p.query("platillosXrest(" + restaurante + ",Nombre,Sabor,Pais,Ingredientes)"): temporal = [] temporal.append("Nombre: " + str(restaurante["Nombre"])) temporal.append("Sabor: " + str(restaurante["Sabor"])) temporal.append("Pais de origen: " + restaurante["Pais"]) t = "" for i in list(restaurante["Ingredientes"]): t += str(i) + " - " temporal.append(str("Ingredientes: " + t)) t = "" resultados.append(temporal) temporal = [] log = file("log.txt", "a") log.write(str(resultados) + "\n") log.close() return resultados
def buscaRestaurantesXNombre(nombre): p = Prolog() p.consult("rest.pl") resultados = [] for restaurante in p.query("buscaRest(" + nombre + ",A,B,C,D)"): temporal = [] tipo = restaurante["A"] ubicacion = restaurante["B"] telefono = str(restaurante["C"]) jornada = restaurante["D"] temporal.append(str(tipo)) temporal.append(str(ubicacion)) temporal.append(str(telefono)) temporal.append(str(jornada)) temporal.append("Fin de restaurante") resultados.append(temporal) temporal = [] log = file("log.txt", "a") log.write(str(resultados) + "\n") log.close() return resultados
class MainController: def __init__(self): # http://nullege.com/codes/search/pyswip.prolog.Prolog.query self.__root = '' self.__on_prolog = 'prolog' self.__of_prolog = 'halt.' # Preguntas self.__a_animal = 'animal(X).' self.__prolog = Prolog() self._probando() def _verifica_animal(self): self.__prolog.consult(self.__root) print '\nprolog dame ejemplos de animales: ' for soln in self.__prolog.query(self.__a_animal): X = soln["X"] print X def _probando(self): Question().run()
def main(): # Initialize the prolog code prolog = Prolog() prolog.consult("talking_to_kid.pl") item = 'slides' stop = False first = True positive = True # Main program loop while not stop: #Ask someone a question based on their previous answer if first: # If this is the first question, we have a neutral statement first = False response = query(item, 'Hello!', '?') else: if positive: # We pick a random positive prefix and suffix if they answered positively previously response = query(item, random.choice(positivePrefix), random.choice(positiveSuffix)) else: # We pick a random negative prefix and suffix if they answered 'no' to the previous queries response = query(item, random.choice(negativePrefix), random.choice(negativeSuffix)) if response: #If the response is True, ask a followup followup = list(prolog.query('followup({}, Y)'.format(item))) # Retrieve a random followup question related to the item (Since some items can have multiple followups) followup_item = random.choice(followup)['Y'] followup_true = askFollow(followup_item) # If the followup is true, then we can say that they like the item. Otherwise they dislike it # We add the item to the knowledge base as something that is liked or disliked by asserting this to the prolog script. if followup_true: prolog.assertz('like({})'.format(item)) positive = True # Remember the positivity of the statement to change the statement else: prolog.assertz('dislike({})'.format(item)) positive = False else:
#!/usr/bin/env python3 from pyswip.prolog import Prolog from rdflib import Graph from rdf_util.namespaces import XCAT from rdflib.namespace import RDF, RDFS, OWL, XSD prolog = Prolog() prolog.consult('init.pl') subjects_result = prolog.query("rdf_current_prefix(X, Y)") for i, result in enumerate(subjects_result): print(i, result) print("rdf_assert('https://vantanarow.bandcamp.com'," f"'{RDF.type}', '{XCAT.Artist}')") triple_add = prolog.query("rdf_assert('https://vantanarow.bandcamp.com'," f"'{RDF.type}', '{XCAT.Artist}')") for idx, result in enumerate(triple_add): print(idx, type(result), result) for i, result in enumerate(prolog.query(f"rdf(W, X, '{XCAT.Artist}', Y)")): print(i, result) for i, result in enumerate(prolog.query(f"rdf('{XCAT.TrackList}', X, Y, Z)")): print(i, result)
def main(): registerForeign(hello) prolog = Prolog() prolog.assertz("father(michael,john)") prolog.assertz("father(michael,gina)") list(prolog.query("father(michael,X), hello(X)"))
class Agent(): # The Agent class' point of entry is the mainLoop method. # This method cycles through simulations and exits when it receives a 'bye' # message or encounters an anomalous situation. The mainLoop method calls the # perceiveActLoop, which encapsulates message reception and handling. # If an action-request message is received, the processActionRequest method is # called. # This in turn calls the processPerception method, which uses the various other # process* methods to update the agent's KB with information from the # perception. # Decision making takes place in the processActionRequest method. #----------------------------------------------------------------------------------------------# def __init__(self, USER, PASS, logToFile, massimHost, perceptServerHost, perceptServerPort, dummy, communication, verbose): self.firstTurn = True self.username = USER self.password = PASS self.dummy = dummy if (dummy): print "@Agent: Running in dummy mode." self.auxTimeDummy = 10 #10 milisegundos para ejecutar dummy self.communication = communication if (communication): print "@Agent: Running with communication protocol activated." self.verbose = verbose if (verbose): print "@Agent: Running in verbose mode." self.logToFile = logToFile if (logToFile): print "@Agent: Logging to file." sys.stdout = open('logs/%s-log.txt' % USER, 'w') else: pass self.log = sys.stdout self.massimHost = '127.0.0.1' if (massimHost): self.massimHost = massimHost self.deadline = 0 print "@Agent: Basic initialization", self.massimConnection = MASSimConnection(self.massimHost, 12300, USER, PASS) self.perceptServerHost = perceptServerHost self.perceptServerPort = perceptServerPort if (perceptServerPort and perceptServerHost): self.perceptConnection = PerceptConnection(perceptServerHost, int(perceptServerPort), USER) else: self.perceptConnection = VortexPerceptConnection() print "done" #----------------------------------------------------------------------------------------------# def connect(self): # Connect and authenticate to the MASSim server. try: self.massimConnection.connect() except: print "@Agent: Error during connection attempt to the MASSim server." quit() #----------------------------------------------------------------------------------------------# def disconnect(self): # Let both the MASSim server and the percept server know that we will no # longer be connecting. self.massimConnection.disconnect() self.perceptConnection.disconnect() if (self.logToFile): self.log.close() self.log = sys.__stdout__ sys.stdout = sys.__stdout__ #----------------------------------------------------------------------------------------------# def prologInitialization(self): print "@Agent: Prolog initialization", self.prolog = Prolog() self.prolog.consult("pl/agent.pl") if (self.logToFile): self.prolog.query("redirect_output('logs/%s-kb%d.xml')" % (self.username, self.currentLoop)).next() if (self.verbose): self.prolog.query("assert(verbose)").next() print "done" #----------------------------------------------------------------------------------------------# def prologFinalization(self): print "@Agent: Prolog finalization", self.prolog.query("retractall(k(_))").next() self.prolog.query("retractall(b(_))").next() self.prolog.query("retractall(h(_))").next() self.prolog.query("retractall(myName(_))").next() self.prolog.query("retractall(visibleNode(_))").next() self.prolog.query("retractall(notVisible(_))").next() self.prolog.query("retractall(explored(_))").next() self.prolog.query("retractall(notExplored(_))").next() self.prolog.query("retractall(inRange(_))").next() self.prolog.query("retractall(buyCount(_,_))").next() if self.verbose: self.prolog.query("saveKB('-%d')" % self.currentLoop).next() self.prolog.query("close_output").next() self.prolog = None print "done" #----------------------------------------------------------------------------------------------# def processSimulationStart(self, msg_dict): def roleHardCode(username): roledict = { '1' : 'explorer' , '2' : 'explorer' , '3' : 'repairer' , '4' : 'repairer' , '5' : 'saboteur' , '6' : 'saboteur' , '7' : 'sentinel' , '8' : 'sentinel' , '9' : 'inspector' , '10' : 'inspector' } number = username[-1:] if (number == '0'): number = '10' return roledict[number] defaultVisionRange = { 'explorer' : 2 , 'repairer' : 1 , 'saboteur' : 1 , 'sentinel' : 3 , 'inspector': 1 } self.role = roleHardCode(self.username) self.prolog_role_file = "pl/%s.pl" % (self.role) self.prolog.consult(self.prolog_role_file) if self.username[-1] == '0': team = self.username[:-2] else: team = self.username[:-1] for x in range(1,11): self.prolog.query("assertOnce(k(agentRole(%s%d, %s)))" % (team, x, roleHardCode(str(x)))).next() self.prolog.query("updateMyName(%s)" % self.username).next() if (self.communication): self.prolog.query("conectar(%s)" % self.username).next() self.prolog.query("registrar([d3lp0r, %s], mapc)" % self.role).next() print "@Agent: Saving the visual range of %s: %s" % (self.role, defaultVisionRange[self.role]) self.prolog.query("assert(myVisionRange(%s))" % defaultVisionRange[self.role]).next() self.prolog.query("assert(k(agentVisionRange(0,%s,%s)))" % (self.username, defaultVisionRange[self.role])).next() #----------------------------------------------------------------------------------------------# def merge_percepts(self, msg_dict_public, msg_dict_difference): msg_dict_public['position'].extend( msg_dict_difference.get('position', [])) msg_dict_public['vis_verts'].extend( msg_dict_difference.get('vis_verts', [])) msg_dict_public['vis_edges'].extend( msg_dict_difference.get('vis_edges', [])) msg_dict_public['vis_ents'].extend( msg_dict_difference.get('vis_ents', [])) msg_dict_public['probed_verts'].extend( msg_dict_difference.get('probed_verts', [])) msg_dict_public['surveyed_edges'].extend( msg_dict_difference.get('surveyed_edges', [])) msg_dict_public['inspected_ents'].extend( msg_dict_difference.get('inspected_ents', [])) #----------------------------------------------------------------------------------------------# def processNodes(self, msg_dict): # First, we obtain all the probed vertices. # Then, for each visible vertex, we check whether the vertx is among the probed vertices. # If it is, it's information is updated with it's value. # Otherwise, it's information is updated with the value unknown. probed_verts = msg_dict.get('probed_verts', []) self.prolog.query("retractall(inRange(_))").next() for x in msg_dict.get('vis_verts', []): self.prolog.query("asserta(inRange(%s))" % x['name']).next() # in_pv == "in probed vertices" in_pv = False for pv in probed_verts: if (pv['name'] == x['name']): in_pv = True break if (in_pv): self.prolog.query('updateNodeValue(%s,%s)' % (x['name'], pv['value'])).next() else: self.prolog.query('updateNodeValue(%s,unknown)' % x['name']).next() self.prolog.query('updateNodeTeam(%s,%s)' % (x['name'], x['team'])).next() #----------------------------------------------------------------------------------------------# def processEdges(self, msg_dict): # We update the map state with edges. for e in msg_dict.get('vis_edges', []): self.prolog.query("updateEdge(%s,%s,unknown)" % (e['node1'], e['node2'])).next() for e in msg_dict.get('surveyed_edges', []): self.prolog.query("updateEdge(%s,%s,%s)" % (e['node1'], e['node2'], e['weight'])).next() #----------------------------------------------------------------------------------------------# def processEntities(self, msg_dict_private, msg_dict_public): # Process the rest of the visible entities. for vis_ent in msg_dict_public['vis_ents']: self.prolog.query("updateEntityTeamPosition(%s,%s,%s,%s)" % (vis_ent['name'], vis_ent['team'], vis_ent['node'], vis_ent['status'])).next() # Proceso las entidades en la percepcion compartida. # Si o si son de tu equipo, luego el team se fija a el propio. for p in msg_dict_public.get('position', []): # Get my own team name from the list of visible entities. team = 'd3lp0r' for e in msg_dict_public['vis_ents']: if (unicode(self.username) == e['name']): team = e['team'] break # Caso especial: cuando soy yo mismo. if (p['name'] == 'self'): parameters = ( self.username , team , p['node'] , self.role , msg_dict_private['energy'] , msg_dict_private['max_energy'] , msg_dict_private['health'] , msg_dict_private['max_health'] , msg_dict_private['strength'] , msg_dict_private['vis_range'] ) self.prolog.query("updateEntity(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)" % parameters).next() else: parameters = ( p['name'] , team , p['node'] , p['health'] , p['max_health'] , p['vis_range'] ) self.prolog.query("updateTeammateEntity(%s,%s,%s,%s,%s,%s)" % parameters).next() # Proceso las entidades inspeccionadas. for e in msg_dict_public['inspected_ents']: parameters = ( e['name'] , e['team'] , e['node'] , e['role'] , e['energy'] , e['max_energy'] , e['health'] , e['max_health'] , e['strength'] , e['vis_range'] ) self.prolog.query("updateEntity(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)" % parameters).next() #----------------------------------------------------------------------------------------------# def processPerception(self, msg_dict_private, msg_dict_public): # Actualizamos cada uno de los campos individuales del agente. self.prolog.query("updateStep(%s)" % msg_dict_private['step']).next() self.prolog.query("updateMaxEnergyDisabled(%s)" % msg_dict_private['max_energy_disabled']).next() self.prolog.query("updateLastAction(%s)" % msg_dict_private['last_action']).next() self.prolog.query("updateLastActionResult(%s)" % msg_dict_private['last_action_result']).next() self.prolog.query("updateMoney(%s)" % msg_dict_private['money']).next() self.prolog.query("updateScore(%s)" % msg_dict_private['score']).next() self.prolog.query("updateZoneScore(%s)" % msg_dict_private['zone_score']).next() self.prolog.query("updateLastStepScore(%s)" % msg_dict_private['last_step_score']).next() self.processNodes(msg_dict_public) self.processEdges(msg_dict_public) self.processEntities(msg_dict_private, msg_dict_public) self.prolog.query("updatePhase").next() #----------------------------------------------------------------------------------------------# def processActionRequest(self, action_id, msg_dict_private, msg_dict_public): print "@Agent: received request-action. id: %s" % action_id # Synchronize perceptions with others. if (self.firstTurn): msg_dict_difference = self.perceptConnection.send_and_recv(msg_dict_public, True) print "@Agent: first turn running, requesting history from percept server." print_message(msg_dict_difference) else: msg_dict_difference = self.perceptConnection.send_and_recv(msg_dict_public) self.merge_percepts(msg_dict_public, msg_dict_difference) # Process perception. self.processPerception(msg_dict_private, msg_dict_public) # Decide action. now = time.time() if self.dummy or (now > self.deadline): query_result = self.prolog.query("execDummy(X)").next() else: self.remainingTime = self.deadline - now query_result = self.prolog.query("run(%s, X)" % self.remainingTime).next() actionList = query_result['X'] if (len(actionList) == 1): action_xml = action(action_id, actionList[0]) action_str = actionList[0] print "@Agent: action: %s" % actionList[0] elif (len(actionList) == 2): print "@Agent: action: %s %s" % (actionList[0], actionList[1]) action_str = '%s(%s)' % (actionList[0], actionList[1]) action_xml = action(action_id, actionList[0], actionList[1]) else: print "@Agent: error in returned action." print "@Agent: return value: %s" % actionList action_xml = action(action_id, "skip") action_str = 'skip' return (action_xml, action_str) #----------------------------------------------------------------------------------------------# def perceiveActLoop(self): # Receive simulation start notification. print "@Agent: Waiting for message from MASSim server." xml = self.massimConnection.receive() msg_type, _, msg_dict, _ = parse(xml) quitPerceiveActLoop = False while (not quitPerceiveActLoop): xml = self.massimConnection.receive() msg_type, action_id, msg_dict_private, msg_dict_public = parse(xml) # Apparently, the sim-start message is not received at the very beginning. self.processSimulationStart(msg_dict) if (msg_type == 'sim-start'): print "\n\n===== NEW SIMULATION =====\n\n" print "@Agent: Received simulation start notification." print_message(msg_dict) print "@Agent: Processing simulation start...", self.processSimulationStart(msg_dict) print "done" quitPerceiveActLoop = False elif (msg_type == 'request-action'): print "@Agent: %s receiving perception from server..." % self.username self.turnStartTime = time.time() self.deadline = self.massimConnection.messageReceived + msg_dict_private['total_time'] / 1000 - 0.2 # VALOR A CAMBIAR print "------------------------------------------------------------" print "@Agent: Step: %s" % msg_dict_private['step'] # Primera fase deliberativa: el agente considera por si mismo que accion realizar. action_xml, action_str = self.processActionRequest(action_id, msg_dict_private, msg_dict_public) # Segunda fase: los agentes se comunican entre si, y se reconsideran las acciones. if (self.communication): self.prolog.query("communicateAndResolveConflicts(%s, NewAction)" % action_str).next() # Send the action to the MASSim server. self.massimConnection.send(action_xml) self.firstTurn = False elif (msg_type == 'sim-end'): print "@Agent: Received sim-end" print_message(msg_dict_private) quitPerceiveActLoop = True elif (msg_type == 'bye'): print "@Agent: Received bye" print_message(msg_dict_private) self.quit = True quitPerceiveActLoop = True else: print "@Agent: In area 51." print_message(msg_dict_private) quitPerceiveActLoop = True self.quit = True #----------------------------------------------------------------------------------------------# def mainLoop(self): self.quit = False agent.connect() self.currentLoop = 0 while (not self.quit): self.currentLoop += 1 self.prologInitialization() try: self.perceiveActLoop() except socket.error: self.prolog.query("catch(saveKB('-fin-%d'),E,writeln(E))" % self.currentLoop).next() sys.exit(0) self.prologFinalization() if not self.logToFile: raw_input("\nFinished. Press ENTER to continue...") agent.disconnect()
class MainSystem: def __init__(self): self.api_key = "AIzaSyB70wPQAQR-5P86DJ2j1QcAgYVbR0-xD_k" self.prolog = Prolog() def get_existing_nodes(self): self.prolog.consult("nodes_kb.pl") try: outcomes = list(self.prolog.query("node(P_id,Name,Address).")) except: outcomes = [] return outcomes def get_distance(self,p1,p2): distance = 0 self.prolog.consult("pairs_kb.pl") try: distance = list(self.prolog.query("arc("+p1+","+p2+",Distance).")) if(distance == []): distance = list(self.prolog.query("arc("+p2+","+p1+",Distance).")) except: distance = 0 return distance[0]['Distance'] def write_node(self, p_id,name, address): replace_list = [' ','/',',','-','_'] f = open('nodes_kb.pl', 'a') for i in replace_list: if(i == '/'): p_id = p_id.replace(i, 'xSLASHx') name = name.replace(i,'xSLASHx') address = address.replace(i,'xSLASHx') elif (i == '-'): p_id = p_id.replace(i, 'xMINUSx') name = name.replace(i, 'xMINUSx') address = address.replace(i,'xMINUSx') elif (i == '_'): p_id = p_id.replace(i, 'xUNDERx') name = name.replace(i, 'xUNDERx') address = address.replace(i,'xUNDERx') elif(i == ','): p_id = p_id.replace(i, 'xCOMMAx') name = name.replace(i, 'xCOMMAx') address = address.replace(i,'xCOMMAx') elif(i == ' '): p_id = p_id.replace(i, 'xSPACEx') name = name.replace(i, 'xSPACEx') address = address.replace(i,'xSPACEx') address = 'a'+re.sub('[^A-Za-z0-9 _]+', '', address) name = 'n'+re.sub('[^A-Za-z0-9 _]+', '', name) p_id = 'x'+p_id.replace('-','_') statement = '\nnode('+p_id+','+name+','+address+').' f.write(statement) f.close() def add_stop(self,p_id,name, address): ex_nodes = self.get_existing_nodes() formatted_p_id = 'x'+p_id.replace('-','xMINUSx').replace('_','xUNDERx') f = open('pairs_kb.pl', 'a') No_duplicate = True for check in ex_nodes: if(formatted_p_id == check['P_id']): No_duplicate = False if(No_duplicate == True): for i in ex_nodes: existing_p_id = i['P_id'] formatted_existing_p_id = existing_p_id.replace('xMINUSx','-').replace('xUNDERx','_')[1:] url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=place_id:"+p_id+"&destinations=place_id:"+formatted_existing_p_id+"&key="+self.api_key response = urllib.request.urlopen(url) data = json.loads(response.read().decode()) distance_str = data['rows'][0]['elements'][0]['distance']['text'] distance = float(re.findall("\d+\.\d+",distance_str)[0]) f.write('\narc('+formatted_p_id+','+existing_p_id+','+str(distance)+').') self.write_node(p_id,name, address) f.close() def get_shortest_path(self,start,nodes): self.prolog.consult("test_final.pl") outcomes = list(self.prolog.query("travel("+start+","+nodes+",Path,C).")) path_list = [] for i in range(len(outcomes[0]['Path'])): path_list.append(str(outcomes[0]['Path'][i])) f_outcomes = [] f_outcomes.append(path_list) f_outcomes.append(outcomes[0]['C']) return f_outcomes
return term.value else: return str(term) def compactify(game_state): game_state_stringified = {key: compact(val) for key, val in game_state.items()} return "game_state(all_balls({AllBalls}), all_cards({AllCards}), current_player_index({CurrentPlayerIndex}), turn_state({TurnState}))".format(**game_state_stringified) # Actual program pygame.init() screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT)) done = False Prolog.consult("tac") game_state = next(Prolog.query("sample_state(game_state(all_balls(AllBalls), all_cards(AllCards), current_player_index(CurrentPlayerIndex), turn_state(TurnState)))")) while not done: print(compactify(game_state)) draw_everything(screen, game_state) pygame.display.flip() action = input("Enter action:") if (action == "quit"): done = True continue query = "InitialState = {}, player_action({}, {}, InitialState, game_state(all_balls(AllBalls), all_cards(AllCards), current_player_index(CurrentPlayerIndex), turn_state(TurnState)))".format(compactify(game_state), action, game_state["CurrentPlayerIndex"]) next_state = next(Prolog.query(query), None) if next_state is not None: game_state = next_state else: