class Connector: def __init__(self, file): self.file = file self.prolog = Prolog() self.board = None self.prolog.consult(file) def setBoard(self,board): tranformedBoard = [] for i in board: for j in i: tranformedBoard.append(j) self.board = tranformedBoard def addRule(self, rule): self.prolog.assertz(rule) def command(self, cmd): return self.prolog.query(cmd) def getMove(self, direction): if direction == 'up': return list(self.prolog.query('move(' + str(self.board) + ',u, New)')) elif direction == 'down': return list(self.prolog.query('move(' + str(self.board) + ',d, New)')) elif direction == 'left': return list(self.prolog.query('move(' + str(self.board) + ',l, New)')) elif direction == 'right': return list(self.prolog.query('move(' + str(self.board) + ',r, New)')) def aiMove(self, board, depth): self.setBoard(board) return list( self.prolog.query('aigame(' + str(self.board) + ',' + str(depth) + ',Move)'))
def start(): kitchen_env = "resources/kitchen.env.xml" env = Environment() # create the environment env.SetViewer('qtcoin') # start the viewer env.Load(kitchen_env) # load a model ssRave = interpeter_extended() ssRave.addVariable('kitchen', env) ## Example 1: Generate a map from the enitre environment expr = """SELECT above(a.this, b.this), below(a.this, b.this), isEnabled(a.this), volume(a.this), position(a.this), isRobot(a.this), isKinbody(a.this) FROM a=kitchen, b=kitchen WHERE not (isSensor(a.this) or isSensor(b.this)) AS prolog;""" print "query:", expr prog = SelectScript.compile(expr) prolog = Prolog() for result in ssRave.eval(prog): print result prolog.assertz(result) print list(prolog.query("above(table, X)")) print list(prolog.query("volume(Obj, V), V > 1.0")) print list(prolog.query("position(_, P)"))
def index(request, table): import MySQLdb as db conn = db.connect(host='localhost', user='******', passwd='prologpass', db='prolog_test') cursor = conn.cursor() cursor.execute('SELECT * FROM `children`') result = cursor.fetchall() prolog = Prolog() for row in result: prolog.assertz("father("+ row[1] +","+ row[2] +")") prolog.consult('family') prolog.assertz("father(michael,john)") prolog.assertz("father(michael,gina)") father = list(prolog.query("father(Y, X)")) #return HttpResponse(response, mimetype="application/xml") t = loader.get_template('index/select.html') c = RequestContext(request, {'table': table, 'father': father}) return HttpResponse( t.render(c), mimetype="application/xml" )
def build_model(self, examples): pl = Prolog() pl.consult(self.subtle_path) pl.consult(self.glgg_path) for example in examples: pl.assertz(example[:-1]) return pl
def test_issue_Unicode(self): """ Unicode support """ from pyswip import Prolog, registerForeign Prolog.assertz('отец(дима,миша)') Prolog.assertz('отец(дима,настя)') Prolog.assertz('отец(дима,света)') Prolog.assertz('отец(сергей,оля)') Prolog.assertz('отец(сергей,саша)') results = list(Prolog.query('отец(дима,Ребенок)')) self.assertEqual(len(results), 3) results = list(Prolog.query('отец(Отец,Ребенок)')) self.assertEqual(len(results), 5) callsToHello = [] def hello(t): callsToHello.append(t.value) hello.arity = 1 registerForeign(hello) p = Prolog.query("отец(дима,X), hello(X)") result = list(p) self.assertEqual(callsToHello, ['миша', 'настя', 'света'])
def main(busqueda,script): prolog = Prolog() for linea in script: prolog.assertz(linea.replace(".","")) prueba = list(prolog.query("buscarReceta("+busqueda+",Tipo,Ing,Pasos,Fotos)")) res = {} i = 0 while i < len(prueba[0]["Pasos"]): temp = str(prueba[0]["Pasos"][i]) prueba[0]["Pasos"][i] = temp i = i+1 i = 0 while i < len(prueba[0]["Ing"]): temp = str(prueba[0]["Ing"][i]) prueba[0]["Ing"][i] = temp i = i+1 i = 0 while i < len(prueba[0]["Fotos"]): temp = str(prueba[0]["Fotos"][i]) prueba[0]["Fotos"][i] = temp i = i+1 res["Nombre"] = busqueda res["Tipo"] = prueba[0]["Tipo"] res["Pasos"] = prueba[0]["Pasos"] res["Ingredientes"] = prueba[0]["Ing"] res["Fotos"] = prueba[0]["Fotos"] print (res)
def create_contract_prolog(e,q_in,q_out): print('Process create contract: starting...') while(1): e.wait() #we take the contract body from queue #each contract is identified by guid, and has a specific query guid, query, contract_body = q_in.get().split("\n",2) contract_clauses = contract_body.split("\n") #create the Prolog instance prolog = Prolog() #assert each clause to Prolog knowledge base for clause in contract_clauses: #empty clauses are ignored if clause == "": continue clause_for_assert = "("+clause.split(".")[0]+")" #the assert statement equivalent to assertz Prolog command prolog.assertz(clause_for_assert) #consult Prolog with the given query #check if the answer list is null then the answer is False answer = bool(list(prolog.query(query))) print(query) q_out.put(guid+"\n"+str(answer))
def test_issue_8(self): """ Callbacks can cause segv's https://code.google.com/p/pyswip/issues/detail?id=8 """ from pyswip import Prolog, registerForeign callsToHello = [] def hello(t): callsToHello.append(t) hello.arity = 1 registerForeign(hello) prolog = Prolog() prolog.assertz("parent(michael,john)") prolog.assertz("parent(michael,gina)") p = prolog.query("parent(michael,X), hello(X)") result = list(p) # Will run over the iterator self.assertEqual(len(callsToHello), 2) # ['john', 'gina'] self.assertEqual(len(result), 2) # [{'X': 'john'}, {'X': 'gina'}]
def assertz(assertz): prolog = Prolog() for line in assertz: Utilities().lprint("ASSERT: '%s' -> '%s'" % (line, line.strip(" ."))) if line.strip() == "": Utilities().lprint("... ignoring") continue prolog.assertz(line.strip(" ."))
def main(busqueda, script): prolog = Prolog() script = script.split(".\n") script = script[:-1] for linea in script: prolog.assertz(linea) prueba = bool(list(prolog.query("receta(" + busqueda + ",_,_,_,_)"))) print(prueba)
def get_schema(): prolog = Prolog() prolog.consult('engine.pl') prolog.assertz('raining("Bangkok")') rule = "can_growing(P1, 'GROW1')." re_list = list(prolog.query(rule)) # return "hello" return jsonify(re_list)
def get_api(): query = request.args.get('query') prolog = Prolog() prolog.consult('engine.pl') prolog.assertz('raining("Bangkok")') rule = "can_growing(P1, 'GROW1')." re_list = list(prolog.query(query)) # return "hello" return jsonify(re_list)
def run(code): prolog = Prolog() output = [] ok = True tmp = "" isQuery = False for line in code.split("\n"): line = line.strip() if line == "" or line[0] == "%": continue if line[:2] == "?-": isQuery = True line = line[2:] tmp += " " + line if tmp[-1] == ".": # End of statement tmp = tmp[:-1] # Removes "." maxresults = DEFAULT_LIMIT # Checks for maxresults if tmp[-1] == "}": tmp = tmp[:-1] # Removes "." limitStart = tmp.rfind('{') if limitStart == -1: ok = False output.append( "ERROR: Found '}' before '.' but opening '{' is missing!" ) else: limit = tmp[limitStart + 1:] try: maxresults = int(limit) except: ok = False output.append("ERROR: Invalid limit {" + limit + "}!") tmp = tmp[:limitStart] try: if isQuery: result = prolog.query(tmp, maxresult=maxresults) output.append(format_result(result)) result.close() else: prolog.assertz('(' + tmp + ')') except PrologError as error: ok = False output.append("ERROR: {}".format(error)) tmp = "" isQuery = False return output, ok
def main(script): prolog = Prolog() script = script.split(".\n") script = script[:-1] for linea in script: prolog.assertz(linea) prueba = list(prolog.query("getRecetas(Nombre)")) i = 0 while i < len(prueba): prueba[i] = prueba[i]["Nombre"] i = i + 1 print(prueba)
def get_api(): query = request.args.get('query') prolog = Prolog() prolog.consult('engine.pl') prolog.assertz('raining("Bangkok")') rule = "can_growing(P1, 'GROW1')." # query = ' recommend("Bangkok","RD1","GROW1",10,4,DAY,MONTH,YEAR).' print query re_list = list(prolog.query(query, catcherrors=False)) # re_list = list(prolog.query(query)) # return "hello" print re_list return jsonify(re_list)
def main(busqueda, script): prolog = Prolog() script = script.split(".\n") script = script[:-1] for linea in script: prolog.assertz(linea) prueba = list(prolog.query("buscarPorTipo(" + busqueda + ",Nombre)")) i = 0 while i < len(prueba): prueba[i] = prueba[i]["Nombre"] i = i + 1 print(prueba)
def test_issue_4(self): """ Patch for a dynamic method Ensures that the patch is working. https://code.google.com/p/pyswip/issues/detail?id=4 """ from pyswip import Prolog Prolog.dynamic('test_issue_4_d/1') Prolog.assertz('test_issue_4_d(test1)') Prolog.assertz('test_issue_4_d(test1)') Prolog.assertz('test_issue_4_d(test1)') Prolog.assertz('test_issue_4_d(test2)') results = list(Prolog.query('test_issue_4_d(X)')) self.assertEqual(len(results), 4) Prolog.retract('test_issue_4_d(test1)') results = list(Prolog.query('test_issue_4_d(X)')) self.assertEqual(len(results), 3) Prolog.retractall('test_issue_4_d(test1)') results = list(Prolog.query('test_issue_4_d(X)')) self.assertEqual(len(results), 1)
def test_issue_4(self): """ Patch for a dynamic method Ensures that the patch is working. https://code.google.com/p/pyswip/issues/detail?id=4 """ from pyswip import Prolog Prolog.dynamic('test_issue_4_d/1') Prolog.assertz('test_issue_4_d(test1)') Prolog.assertz('test_issue_4_d(test1)') Prolog.assertz('test_issue_4_d(test1)') Prolog.assertz('test_issue_4_d(test2)') results = list(Prolog.query('test_issue_4_d(X)')) self.assertEqual(len(results), 4) Prolog.retract('test_issue_4_d(test1)') results = list(Prolog.query('test_issue_4_d(X)')) self.assertEqual(len(results), 3) Prolog.retractall('test_issue_4_d(test1)') results = list(Prolog.query('test_issue_4_d(X)')) self.assertEqual(len(results), 1)
def test_issue_1(self): """ Segmentation fault when assertz-ing Notes: This issue manifests only in 64bit stacks (note that a full 64 bit stack is needed. If running 32 in 64bit, it will not happen.) http://code.google.com/p/pyswip/issues/detail?id=1 """ # The simple code below should be enough to trigger the issue. As with # issue 13, if it does not work, it will segfault Python. from pyswip import Prolog prolog = Prolog() prolog.assertz("randomTerm(michael,john)")
def test_issue_1(self): """ Segmentation fault when assertz-ing Notes: This issue manifests only in 64bit stacks (note that a full 64 bit stack is needed. If running 32 in 64bit, it will not happen.) http://code.google.com/p/pyswip/issues/detail?id=1 """ # The simple code below should be enough to trigger the issue. As with # issue 13, if it does not work, it will segfault Python. from pyswip import Prolog prolog = Prolog() prolog.assertz("randomTerm(michael,john)")
def test_deterministic_foreign(self): def hello(t): print("Hello,", t) hello.arity = 1 registerForeign(hello) prolog = Prolog() prolog.assertz("father(michael,john)") prolog.assertz("father(michael,gina)") result = list(prolog.query("father(michael,X), hello(X)")) self.assertEqual(len(result), 2, 'Query should return two results') for name in ('john', 'gina'): self.assertTrue({'X': name} in result, 'Expected result X:{} not present'.format(name))
def main(): parser = argparse.ArgumentParser() parser.add_argument("--rules", dest="rule_path", default=None) parser.add_argument("--db-source", dest="db_path", default="postgresql://dgarant@localhost:5432/movielens") args = parser.parse_args() if args.rule_path: with open(args.rule_path, 'r') as rule_handle: rules = [r.strip() for r in rule_handle.readlines()] else: rules = build_schema_rules(args.db_path) rules.extend(register_qeds()) prolog = Prolog() for rule in rules: print(rule) prolog.assertz(rule) report_on_qeds(prolog, "movie_gross")
def give_graph(self): if self._state is None: #exception-like condition, maybe NoStateException print('No state is ready!') return state, n = self._state, self._state.length if self._big_anchor_state is None: print('No big anchor state is ready!') return if 'graph' in self._big_anchor_state: return self._big_anchor_state['graph'] word_set = self._big_anchor_state['word_set'] self.decide_graph_module() if self.graph_module == 'networkx': import networkx as nx G = nx.DiGraph() index = word_set.index() for i in range(n): G.add_node(index[(i, 0)], word = self._l[i][0]) for j, word in enumerate(self._l[i][1:], 1): G.add_edge(index[(i, j - 1)], index[(i, j)]) G.nodes[index[(i, j)]]['word'] = word for j, word in enumerate(self._l[i]): if 'appearance' not in G.nodes[index[(i, j)]]: G.nodes[index[(i, j)]]['appearance'] = [] G.nodes[index[(i, j)]]['appearance'].append(i) self._big_anchor_state['graph'] = G return G elif self.graph_module == 'pyswip': from pyswip import Prolog prolog = Prolog() prolog.consult('knowledge.pl') #clear the previos graph which is created in this object deque(prolog.query(f'clear_register({id(self)})'), maxlen = 0) index = word_set.index() id_word_map = {} #prevent overlapping for i in range(n): id_word_map[index[(i, 0)]] = self._l[i][0] for j, word in enumerate(self._l[i][1:], 1): prolog.assertz(f'edge({index[(i, j - 1)]}, {index[(i, j)]})') id_word_map[index[(i, j)]] = word for j in range(len(self._l[i])): prolog.assertz(f'appear({index[(i, j)]}, {i})') for word_id, word in id_word_map.items(): prolog.assertz(f"word({word_id}, '{word}')") #word is atom, not string (list of codes) prolog.assertz(f'node_register({id(self)}, {word_id})') #register the word ID under a key (python ID of self) #prolog.assertz('all_node([{}])'.format(', '.join([str(i) for i in id_word_map.keys()]))) self._big_anchor_state['graph'] = prolog return prolog elif self.graph_module is None: print('Failed to draw graph!') return
def run_env(env): p = Prolog() p.consult("main.pl") p.assertz("bh(%s)" % env["bh"]) p.assertz("bw(%s)" % env["bw"]) p.assertz("time(%s)" % env["time"]) p.assertz("child_count(%s)" % env["child_count"]) p.assertz("dirtiness_percent(%s)" % env["dirtiness_percent"]) p.assertz("obstacle_percent(%s)" % env["obstacle_percent"]) # list(p.query("findall(_,main,_)")) list(p.query("init.")) # list(p.query("summary.")) for result in p.query( "summaryPy(Avg,RobotFired,ChildInCorral,CleanHouse)"): avg = result["Avg"] robot_fired = result["RobotFired"] child_in_corral = result["ChildInCorral"] clean_house = result["CleanHouse"] # print(avg,robot_fired,child_in_corral,clean_house) return (avg, robot_fired, child_in_corral, clean_house)
def getrecetaIngrediente(): #se consuige la informacin del JSON de entrada request_data = request.get_json() nombreIn = request_data['nombre'] tipoIn = request_data['tipo'] pasosIn = request_data['pasos'] ingredienteIn = request_data['ingredientes'] fotoIn = request_data['foto'] insertar = 0 listaJson = [] prolog = Prolog() #se consulta la base de conocimientos prolog.consult("conocimientos.pl") prolog.assertz("buscarIng(Z,A,B,C,D,E):-receta(A,B,C,D,E),member2(Z,D)") for soln in prolog.query("buscarIng(" + ingredienteIn + ",A,B,C,D,E)"): listaPasos = "" listaIngredientes = "" for paso in soln["C"]: listaPasos += paso.value + "," for ingrediente in soln["D"]: listaIngredientes += ingrediente.value + "," for l in listaJson: if (l["nombre"] == soln["A"] and l["tipo"] == soln["B"]): insertar = 1 if (insertar == 1): insertar = 0 else: listaJson.append({ "nombre": soln["A"], "tipo": soln["B"], "pasos": listaPasos, "ingredientes": listaIngredientes, "foto": soln["E"][0].value }) #listaJson.append(jsonify(nombre=soln["A"],tipo = soln["B"],pasos = soln["C"][0].value,ingredientes = soln["D"][0].value,foto=soln["E"][0].value)) return Response(json.dumps(listaJson), mimetype='application/json')
def main(busqueda, script): prolog = Prolog() script = script.split(".\n") script = script[:-1] for linea in script: prolog.assertz(linea) prueba = list( prolog.query("buscarReceta(" + busqueda + ",Tipo,Ing,Pasos,Fotos)")) if (prueba == []): print({'message': 'No existe ninguna receta con ese nombre'}) return res = {} i = 0 while i < len(prueba[0]["Pasos"]): temp = str(prueba[0]["Pasos"][i]) prueba[0]["Pasos"][i] = temp i = i + 1 i = 0 while i < len(prueba[0]["Ing"]): temp = str(prueba[0]["Ing"][i]) prueba[0]["Ing"][i] = temp i = i + 1 i = 0 while i < len(prueba[0]["Fotos"]): temp = str(prueba[0]["Fotos"][i]) prueba[0]["Fotos"][i] = temp i = i + 1 res["Nombre"] = busqueda res["Tipo"] = prueba[0]["Tipo"] res["Pasos"] = prueba[0]["Pasos"] res["Ingredientes"] = prueba[0]["Ing"] res["Fotos"] = prueba[0]["Fotos"] print(res)
class FamilyTree: def __init__(self): self.prolog = Prolog() self.predicates = list() self.table = list() self.apply([str(datetime.today().year), 'current_year']) def apply(self, args: list): args[0], args[1] = args[1], args[0] predicate = f"{args[0]}({','.join(args[1:])})" self.prolog.assertz(predicate) self.predicates.append(predicate) args[0], args[1] = args[1], args[0] self.table.append(args) def query(self, query: str): for item in self.prolog.query(query): for key in item.keys(): print(f'\t {key} = {item[key]} ; \t', end='') print() def consult(self, prolog_program_file: str): self.prolog.consult(prolog_program_file) def remove_last_predicate(self): last_predicate = self.predicates[-1] self.prolog.retract(last_predicate) del self.predicates[-1] del self.table[-1] def print_as_table(self): columns = max([len(row) for row in self.table]) headers = ['Subject', 'Predicate'] + [f'Object-{i}' for i in range(columns - 2)] t = PrettyTable(headers) for row in self.table: t.add_row(row + ['' for _ in range(len(headers) - len(row))]) print(t)
def main(): prolog = Prolog() with open(args.ast, 'r') as f: try: ast = json.loads(f.read()) except: print("Can't read ast file!") exit() for library in LIBRARIES: prolog.assertz(library) for rule in RULES: prolog.assertz(rule) if ast['kind'] == 'TranslationUnitDecl': items = ast['inner'] current_file = '' for item in items: if 'loc' in item and 'file' in item[ 'loc'] and item['loc']['file'] != '': current_file = item['loc']['file'] # print('Handling file: {}'.format(current_file)) if current_file == args.src_name: collect_facts(prolog, None, item) else: print('Invalid root declaration') exit() solutions = prolog.query(args.test) try: specific_solution = next(solutions) print('PASSED') except: print('FAILED') solutions.close()
class PrologAA: def __init__(self): self.prolog = Prolog() self.prolog.assertz(":-use_module(library(lists))") self.ficheiro = None def assercao(self,texto): if self.ficheiro is None: self.ficheiro = open(r"f:\temp\pee.pl","w") self.ficheiro.write(texto+ '.\n') def query(self, texto): if self.ficheiro is None: self.ficheiro = open(r"f:\temp\factos_pee.pl","w") self.ficheiro.write(texto + '.\n') self.ficheiro.close() return dict(V=['a','b','c']) def procurar(self, problema): prlg = self.prolog objectivo = [ (x,y) for (x,y) in problema.modelo_mundo._elementos if problema.modelo_mundo._elementos[(x,y)] == 'alvo'][0] self.assercao( "final({}/{}/G/H/V,V,C) :- C is G+H.".format( objectivo[0], objectivo[1])) posicoes = [ (x,y) for (x,y) in problema.modelo_mundo._elementos if problema.modelo_mundo._elementos[(x,y)] != 'obst'] for (x,y) in posicoes: self.assercao("posicao({},{})".format(x,y)) accoes=[(1,0,1), (1,1,2), (0,1,3),(-1,1,4),(-1,0,5),(-1,-1,6),(0,-1,7),(1,-1,8)] for (x,y, z) in accoes: self.assercao("accao({},{},{},{})".format(x,y, z/8.0 * 2.0* math.pi, math.sqrt( x**2 + y**2))) self.problema = problema (xi, yi) = problema.estado_inicial() #(0,1) caminho = list(self.query("teste( V, _) :- aStar( {}/{},V, C )".format(xi, yi))) input("Parar aqui, foi apenas usado para obter a representacao do mundo num ficheiro de factos a usar em prolog")
def test_issue_8(self): """ Callbacks can cause segv's https://code.google.com/p/pyswip/issues/detail?id=8 """ from pyswip import Prolog, registerForeign callsToHello = [] def hello(t): callsToHello.append(t) hello.arity = 1 registerForeign(hello) prolog = Prolog() prolog.assertz("parent(michael,john)") prolog.assertz("parent(michael,gina)") p = prolog.query("parent(michael,X), hello(X)") result = list(p) # Will run over the iterator self.assertEqual(len(callsToHello), 2) # ['john', 'gina'] self.assertEqual(len(result), 2) # [{'X': 'john'}, {'X': 'gina'}]
def consulta_aux(nombre): from pyswip import Prolog prolog = Prolog() s3 = boto3.resource('s3') file = s3.Object('progralenguajes', 'base.pl').get()['Body'].read().decode().replace( '\n', '') cont = 0 rule = "" lis = [] while (cont < len(file)): while (file[cont] != '.'): rule += file[cont] cont += 1 lis.append(rule) cont += 1 rule = "" cont = 0 while (cont < len(lis)): prolog.assertz(lis[cont]) cont += 1 x = list(prolog.query('comida(' + nombre + ',X,Y,Z,A)')) return x
def helloworld(): prolog = Prolog() prolog.assertz("use_module(library(semweb/turtle))") prolog.assertz("use_module(library(semweb/rdf_http_plugin))") prolog.assertz("use_module(library(semweb/rdf_db))") for soln in prolog.query( "rdf_load('https://www.dropbox.com/s/33v1zze5fpbmnzh/model.ttl?raw=1', [format('turtle'), register_namespaces(false), base_uri('http://anonymous.org/vocab/'), graph('http://anonymous.org/vocab')])" ): print(soln)
from pyswip import Prolog prolog = Prolog() prolog.assertz("father(michael,john)") prolog.assertz("father(michael,gina)") list(prolog.query("father(michael,X)")) [{'X': 'john'}, {'X': 'gina'}] for soln in prolog.query("father(X,Y)"): print(soln["X"], "is the father of", soln["Y"])
# Load knowledge base. All facts and rules in assumptionsKbAuto.pl, guaranteesKbAuto.pl and rulesFactsManual.pl # are read from the files and asserted into the working prolog_interface environment in run-time. This SHOULD NOT be necessary # (prolog_interface.consult(sys.args[3]) should be sufficient), # but the <consult> method provided in PySWIP is not behaving as described in the documentation: it seems to always # fail to access the given file. print 'Loading knowledge base...' #prolog_interface.consult(sys.args[3]) lns = open(sys.argv[3], 'rt').readlines() for ln in lns: sln = ln.strip() if len(sln) > 0 and sln[-1] == '.': slnnp = sln.strip('.') prolog_interface.assertz(slnnp) lns = open(sys.argv[4], 'rt').readlines() for ln in lns: sln = ln.strip() if len(sln) > 0 and sln[-1] == '.': slnnp = sln.strip('.') prolog_interface.assertz(slnnp) lns = open(sys.argv[5], 'rt').readlines() for ln in lns: sln = ln.strip() if len(sln) > 0 and sln[-1] == '.' and ':- [' not in sln: slnnp = sln.strip('.') if ':-' in slnnp: slnnp = '(' + slnnp + ')'
class Filtro: def __init__(self): self.prolog = Prolog() self.prolog.consult("ProyectoFinal.pl") self.prolog.consult("libros.pl") self.__getFiltro() def __getFiltro(self): self.dialogFiltro = Toplevel() self.dialogFiltro.title('Filtro del Bibliofilo') Label(self.dialogFiltro, text='Título: ').grid(row=1, column=0) self.titulo = Entry(self.dialogFiltro) self.titulo.focus() self.titulo.grid(row=1, column=1) self.estadoCheckTitulo = IntVar() self.tituloCheck = Checkbutton(self.dialogFiltro, text="No Titulo", variable=self.estadoCheckTitulo, onvalue=1, offvalue=0) self.tituloCheck.grid(row=1, column=2) self.estadoCheckNoFiltro = IntVar() self.NoFiltroCheck = Checkbutton(self.dialogFiltro, text="No Filtro", variable=self.estadoCheckNoFiltro, onvalue=1, offvalue=0) self.NoFiltroCheck.grid(row=1, column=4) Label(self.dialogFiltro, text='Autor: ').grid(row=2, column=0) self.autor = Entry(self.dialogFiltro) self.autor.grid(row=2, column=1) self.estadoCheckAutor = IntVar() self.autorCheck = Checkbutton(self.dialogFiltro, text="No Autor", variable=self.estadoCheckAutor, onvalue=1, offvalue=0) self.autorCheck.grid(row=2, column=2) Label(self.dialogFiltro, text='Categoría: ').grid(row=3, column=0) self.categoria = Entry(self.dialogFiltro) self.categoria.grid(row=3, column=1) Label(self.dialogFiltro, text='Cantidad: ').grid(row=3, column=2) self.cantidad = Entry(self.dialogFiltro) self.cantidad.grid(row=3, column=3) self.estadoCheckCategoria = IntVar() self.categoriaCheck = Checkbutton(self.dialogFiltro, text="No Categoría", variable=self.estadoCheckCategoria, onvalue=1, offvalue=0) self.categoriaCheck.grid(row=3, column=4) Label(self.dialogFiltro, text='Estado: ').grid(row=5, column=0) self.estado = ttk.Combobox(self.dialogFiltro, values=["Nuevo", "Usado", "n/a"]) self.estado.grid(row=5, column=1) self.estado.current(0) self.estadoCheckEstado = IntVar() self.estadoCheck = Checkbutton(self.dialogFiltro, text="No Estado", variable=self.estadoCheckEstado, onvalue=1, offvalue=0) self.estadoCheck.grid(row=5, column=2) Label(self.dialogFiltro, text='Estado Extra: ').grid(row=6, column=0) self.estadoExtra = ttk.Combobox(self.dialogFiltro, values=[ "Porcentaje", "Ingreso Extra", "Porcentaje e Ingraso Extra" ]) self.estadoExtra.grid(row=6, column=1) self.estadoExtra.current(0) self.estadoCheckestadoExtra = IntVar() self.estadoExtraCheck = Checkbutton( self.dialogFiltro, text="No Estado Extra", variable=self.estadoCheckestadoExtra, onvalue=1, offvalue=0) self.estadoExtraCheck.grid(row=6, column=2) Label(self.dialogFiltro, text='Dias: ').grid(row=7, column=0) self.dia = Entry(self.dialogFiltro) self.dia.grid(row=7, column=1) self.estadoCheckFechaI = IntVar() self.FechaICheck = Checkbutton(self.dialogFiltro, text="No Dias", variable=self.estadoCheckFechaI, onvalue=1, offvalue=0) self.FechaICheck.grid(row=7, column=2) ttk.Button(self.dialogFiltro, text='Guardar', command=self.guardar).grid(row=9, column=2) self.dialogFiltro.mainloop() def guardar(self): if len(list(self.prolog.query("filtrodb(T,A,C,E,EE,D,ES)"))) > 0: for e in list( self.prolog.query("retract(filtrodb(_,_,_,_,_,_,_))")): print titulo = "no" autor = "no" categoria = "no" estado = "no" estadoExtra = "no" cantidad = "no" if self.estadoCheckTitulo.get() == 0 and self.titulo.get() != '': titulo = self.titulo.get() if self.estadoCheckAutor.get() == 0 and self.autor.get() != '': autor = self.autor.get() if self.estadoCheckCategoria.get() == 0 and self.categoria.get() != '': categoria = self.categoria.get().split(",") print(categoria) if self.estadoCheckEstado.get() == 0: estado = self.estado.get().lower() if self.estadoCheckestadoExtra.get() == 0: estadoExtra = self.estadoExtra.get().lower() if self.cantidad.get() != '': if int(self.cantidad.get()) > 1: cantidad = self.cantidad.get() self.prolog.assertz("filtrodb(" + str(titulo) + "," + str(autor) + "," + str(categoria) + "," + str(estado) + ",'" + str(estadoExtra) + "', " + str(cantidad) + "," + str(self.estadoCheckNoFiltro.get()) + ")")
""" prolog = Prolog() ############################################################################################################### # Directly inserts the predicates into the PrologKB via the prolog object. nodes = ["a", "b", "c", "d", "e", "f", "g"] edges = ["a,b", "a,c", "b,d", "b,e", "c,d", "c,f", "d,e", "d,f", "e,g", "f,g"] costs = ["a,b,'50'", "a,c,'100'", "b,d,'40'", "b,e,'20'", "c,d,'60'", "c,f,'20'", "d,e,'50'", "d,f,'60'", "e,g,'70'", "f,g,'70'"] source = ["a"] target = ["g"] prolog.assertz("source(" + source[0] + ")") prolog.assertz("target(" + target[0] + ")") # print list(prolog.query("test(A,B,C,D,E,F,G)")) for node in nodes: prolog.assertz("node(" + node + ")") for edge in edges: insert = "edge(" + edge + ")" # print insert prolog.assertz(insert) for cost in costs: insert = "cost(" + cost + ")" # print insert prolog.assertz(insert) #prolog.consult("maxflow_swipl.pl")
class Trabalho_Sistema_Expecialista(): def __init__(self): self.prolog = Prolog() self.X = Variable() self.resultado = ['corinthians', 'atletico_mg', 'gremio', 'santos', 'sao_paulo', 'palmeiras', 'flamengo', 'internacional', 'ponte_preta', 'sport', 'fluminense', 'atletico_pr', 'cruzeiro', 'chapecoense', 'figueirense', 'avai', 'coritiba', 'goias', 'vasco', 'joinville', 'botafogo'] arquivo_pl = open('jogos.pl') for linha in arquivo_pl.readlines(): if linha[len(linha) - 1] == '\n': linha = linha.replace("\n", "") self.prolog.assertz(linha) def Imprimir_Resultados(self): os.system('clear') if len(self.resultado) == 1: print("O esporte que você está pensando é :\n") for resultado in self.resultado: print(resultado, '\n') sys.exit(0) # else: # print(''' # Não consegui achar o esporte mas acho # que ele está nessa lista. Não está? # ''') # for resultado in self.resultado: # print(resultado) def Imprimir(self, lista): for esporte in lista: print(esporte) def Tamanho(self): print(len(self.resultado)) def Query(self, parametro): lista = [] parametro = Functor(parametro) query = Query(parametro(self.X)) while query.nextSolution(): lista.append(str(self.X.get_value())) query.closeQuery() return lista def Intersection(self, lista1): if set(lista1).intersection(self.resultado) == set(): self.resultado = lista1 else: self.resultado = set(lista1).intersection(self.resultado) def Difference(self, lista1): Times = set(self.resultado) if Times.difference(lista1) == set(): self.resultado = lista1 else: self.resultado = Times.difference(lista1) def Pergunta(self, pergunta, caracteristica): resp = input(pergunta + '\n') Times = self.Query(caracteristica) if (resp == 's' or resp == 'S'): self.Intersection(Times) return True else: self.Difference(Times) return False
def createKB(): kb = Prolog() kb.assertz("caserma(caserma_1)") kb.assertz("caserma(caserma_2)") kb.assertz("caserma(caserma_3)") kb.assertz("agenti(caserma_1,30)") kb.assertz("agenti(caserma_2,40)") kb.assertz("agenti(caserma_3,50)") kb.assertz("speciali(caserma_1,10)") kb.assertz("speciali(caserma_2,7)") kb.assertz("speciali(caserma_3,3)") kb.assertz("veicoli(caserma_1,7)") kb.assertz("veicoli(caserma_2,20)") kb.assertz("veicoli(caserma_3,13)") return kb
from pyswip import Prolog prolog = Prolog() prolog.assertz("father(michael,john)") prolog.assertz("father(michael,gina)") result = list(prolog.query("father(michael,X)")) print result
from pyswip import Prolog prolog = Prolog() prolog.assertz("hello(test)") prolog.assertz("hello(world)") print list(prolog.query("hello(world)")) print list(prolog.query("hello(x)")) for result in prolog.query("hello(X)"): print result["X"] print "--------------" for result in prolog.query("retractall(hello(_))"): continue for result in prolog.query("hello(X)"): print result["X"] print "--------------"
# A short Python script to demonstrate how the Prolog is meant to be used. # Requires pyswip and a running instance of MySQL. from pyswip import Prolog prolog = Prolog() prolog.consult("appraise.pl") # A couple preliminary assertions. prolog.assertz("value(banana, 1 rdiv 4, bitcoin)") prolog.assertz("value(bitcoin, 1 rdiv 30, namecoin)") prolog.assertz("value(apple, 3 rdiv 4, banana)") prolog.assertz("value(orange, 1 rdiv 5, apple)") # Now, how much is an orange worth in bitcoins? result = prolog.query("appraise_float(orange, Price, bitcoin)").next() print "An orange is worth %s bitcoins." % result["Price"] # And how much is a bitcoin worth in apples? result = prolog.query("appraise_float(bitcoin, Price, apple)").next() print "A bitcoin is worth %s apples." % result["Price"]
class se(Singleton): band = True def __init__(self): if self.band: self.prolog = Prolog() if not os.path.isfile('recetas.pl'): print "Generando Recetas..." self.cargarRecetas() print "Cargando Recetas..." self.prolog.consult('recetas.pl') print "Cargando Querys..." self.prolog.consult('querys.pl') self.band = False else: print "Ya se cargo" def cargarRecetas(self): recetario = open("recetas.pl", "w") header = """%====================\n% BASE DE HECHOS\n%====================\n""" recetario.write(header) # Cargar ingredientes en la Base de Conocimiento headerIng = """\n%--------------------\n% Ingredientes\n%--------------------\n""" recetario.write(headerIng) listaIngredientes = Ingrediente.objects.values_list('nombre',flat=True) bufferIng = ["ingrediente('"+x.encode('utf-8')+"').\n" for x in listaIngredientes] recetario.writelines(bufferIng) # Cargar Categorias en la Base de Conocimiento headerCat = """\n%--------------------\n% Categorias\n%--------------------\n""" recetario.write(headerCat) listaCategorias = Categoria.objects.values_list('nombre',flat=True) bufferCat = ["categoria('"+x.encode('utf-8')+"').\n" for x in listaCategorias] recetario.writelines(bufferCat) # Cargar Recetas en la Base de Conocimiento listaRecetas = Receta.objects.values_list('nombre','categoria') headerRec = """\n%--------------------\n% Recetas\n%--------------------\n""" recetario.write(headerRec) for receta in listaRecetas: recingr = Receta.objects.get(nombre=receta[0]).ingredientes.values_list('nombre',flat=True) reccat = Categoria.objects.values_list('nombre',flat=True).get(id=receta[1]) reccant = DetalleReceta.objects.filter(receta__nombre=receta[0]).values_list('cantidad', flat=True) recprep = Receta.objects.get(nombre=receta[0]).preparacion bufferRec = "receta(\tnombre('"+receta[0]+"'),\n\tcategoria('"+str(reccat)+"'),\n\tingredientes(['"+"', '".join(recingr)+"']),\n\tcantidades(['"+"', '".join(reccant)+"']),\n\tpreparacion('"+recprep+"')\n\t).\n" recetario.write(bufferRec.encode('utf-8')) recetario.close() def lista_ingredientes(self): lista = self.prolog.query("ingrediente(X)") return [d['X'] for d in lista] def hay(self,listaIngredientes): #listaIngr = [str(x) for x in listaIngredientes] hay = "hay("+str(listaIngredientes)+")" self.prolog.assertz(hay) return list(self.prolog.query("hay(X)")) def quePuedoHacer(self): return list(self.prolog.query("quePuedoHacer(Receta,Cat)"))
def question_finder(question, ans): p = Prolog() p.consult('/home/jordanhudgens/code/coderprofile/survey/knowledgebase.pl') # When placed on server, be sure to change this path!!!! # Question 1: Type of Projects Desired to Learn if question == "What type of projects do you want to learn how to build?": p.dynamic('projectdesired/1') ## To account for going back p.retractall('projectdesired(_)') ## To account for going back if ans == "iPhone App": p.assertz('projectdesired(iphoneapp)') if ans == "Android App": p.assertz('projectdesired(androidapp)') if ans == "Web Application": p.assertz('projectdesired(webapp)') if ans == "Front End Website Development": p.assertz('projectdesired(frontend)') if ans == "just programming": p.assertz('projectdesired(generalprogramming)') # Question 2: Budget if question == "What is your budget?": p.dynamic('budget/1') ## To account for going back p.retractall('budget(_)') ## To account for going back if ans == "$0": p.assertz('budget(0)') if ans == "$50-$250": p.assertz('budget(250)') if ans == "$251-$500": p.assertz('budget(500)') if ans == "$501-$1000": p.assertz('budget(1000)') if ans == "$1001-$1500": p.assertz('budget(1500)') if ans == "$1501+": p.assertz('budget(1000000)') # Question 3: Level of Education if question == "What is the highest level of education you've completed?": p.dynamic('education/1') ## To account for going back p.retractall('education(_)') ## To account for going back if ans == "High School": p.assertz('education(highschool)') if ans == "Associates": p.assertz('education(associates)') if ans == "Bachelors": p.assertz('education(bachelors)') if ans == "Graduate": p.assertz('education(graduate)') # Question 4: Programming Experience if question == "What programming experience do you have?": p.dynamic('experience/1') ## To account for going back p.retractall('experience(_)') ## To account for going back if ans == "None": p.assertz('experience(none)') if ans == "Low": p.assertz('experience(low)') if ans == "Intermediate": p.assertz('experience(intermediate)') if ans == "Extensive": p.assertz('experience(extensive)') # Question 5: Learning Priority if question == "What's more of a priority for you to learn?": p.dynamic('priority/1') ## To account for going back p.retractall('priority(_)') ## To account for going back if ans == "Theory of coding": p.assertz('priority(theory)') if ans == "Real life projects": p.assertz('priority(practical)') # Question 6: Employment Status if question == "Are you currently employed full time?": p.dynamic('employment/1') ## To account for going back p.retractall('employment(_)') ## To account for going back if ans == "Yes": p.assertz('employment(fulltime)') if ans == "No": p.assertz('employment(none)') # Question 7: Weekly Time Dedication if question == "How many hours can you dedicate to learning each week?": p.dynamic('hoursfree/1') ## To account for going back p.retractall('hoursfree(_)') ## To account for going back if ans == "5": p.assertz('hoursfree(5)') if ans == "6-10": p.assertz('hoursfree(10)') if ans == "11-20": p.assertz('hoursfree(20)') if ans == "21-30": p.assertz('hoursfree(30)') if ans == "31-40": p.assertz('hoursfree(40)') if ans == "40+": p.assertz('hoursfree(168)') # Question 8: Feature Driven Developer if question == "Do you like to see the potential features you're going to build before learning how to implement them?": p.dynamic('featuredriven/1') ## To account for going back p.retractall('featuredriven(_)') ## To account for going back if ans == "Yes (I prefer to watch first)": p.assertz('featuredriven(true)') if ans == "No (I want to start coding right away)": p.assertz('featuredriven(false)') # Question 9: Mentor Driven Developer if question == "Do you like working out problems with experts or do you prefer working out issues on your own?": p.dynamic('mentor/1') ## To account for going back p.retractall('mentor(_)') ## To account for going back if ans == "I would prefer to work with an expert": p.assertz('mentor(mentordriven)') if ans == "I like working issues out on my own": p.assertz('mentor(notmentordriven)') # Question 10: Audience if question == "What type of audience do you want to develop for? I want to build: ": p.dynamic('targetaudience/1') ## To account for going back p.retractall('targetaudience(_)') ## To account for going back if ans == "Business applications": p.assertz('targetaudience(business)') if ans == "Games": p.assertz('targetaudience(games)') if ans == "Social apps": p.assertz('targetaudience(socialapps)') if ans == "eCommerce": p.assertz('targetaudience(ecommerce)') if ans == "No audience - just programming theory": p.assertz('targetaudience(programmingtheory)') # Question 11: Competitive if question == "Does testing your coding skills against other developers appeal to you?": p.dynamic('competitive/1') ## To account for going back p.retractall('competitive(_)') ## To account for going back if ans == "Yes": p.assertz('competitive(iscompetitive)') if ans == "No": p.assertz('competitive(notcompetitive)') # Question 12: High Speed Internet Status if question == "Do you have access to high speed internet?": p.dynamic('highspeedinternet/1') ## To account for going back p.retractall('highspeedinternet(_)') ## To account for going back if ans == "Yes": p.assertz('highspeedinternet(highspeed)') if ans == "No": p.assertz('highspeedinternet(lowspeed)') # Question 13: Code Motivation if question == "Why do you want to learn to code?": p.dynamic('motivation/1') ## To account for going back p.retractall('motivation(_)') ## To account for going back if ans == "Build my own project": p.assertz('motivation(project)') if ans == "Learn a new hobby": p.assertz('motivation(hobby)') if ans == "Improve for my current job": p.assertz('motivation(job)') # Question 14: Machine Type if question == "What type of computer do you have to work on?": p.dynamic('machine/1') ## To account for going back p.retractall('machine(_)') ## To account for going back if ans == "Mac": p.assertz('machine(mac)') if ans == "Windows": p.assertz('machine(windows)') if ans == "Linux": p.assertz('machine(linux)') # Question 15: Timeframe for Learning if question == "What is your timeframe?": p.dynamic('timeframe/1') ## To account for going back p.retractall('timeframe(_)') ## To account for going back if ans == "< 30 days": p.assertz('timeframe(30)') if ans == "31-90 days": p.assertz('timeframe(90)') if ans == "91+ days": p.assertz('timeframe(365)')
from pyswip import Prolog import cgi, cgitb prolog = Prolog() prolog.consult("../data/mod2.pl") prolog.assertz("variety(tkm12,rice)") result = prolog.query("season(When),days(Give),avgyield(Gives),feat(With),places(Where)").next() print "Content-type: text/html\n\n"; print '<html>'; print '<head>'; print '<meta name="author" content="Kay Vogelgesang">'; print '<link href="/xampp/xampp.css" rel="stylesheet" type="text/css">'; print '</head>'; print "<body>" print "%s." % result["When"] print "%s" %result["Give"] print "%s." % result["Gives"] print "%s." % result["With"] print "%s." % result["Where"] print "</body></html>";