Example #1
0
 def get_n_ans_new(self,
                   instructions: str,
                   maxresults=-1,
                   solves=True) -> list:
     ' functors and items of predicates, variables'
     terms, vars, statements = self.parse_ins(instructions)
     vars_ans = [] if solves else {i[0]: []
                                   for i in vars
                                   }  # list/dict of variable values
     statements_ans = {}  # list of statements
     if terms:
         q = Query(*terms)  # make query
         while q.nextSolution() and maxresults:  # find solutions
             maxresults -= 1
             if solves:
                 # append values
                 vars_ans.append({k: v.value for k, v in vars})
             else:
                 for k, v in vars:
                     if v.value not in vars_ans[k]:
                         vars_ans[k].append(v.value)
         q.closeQuery()
     if statements:
         for statement in statements:
             statements_ans.update({statement[1]: call(statement[0])})
     return vars_ans, statements_ans
    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 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
Example #4
0
File: TP2.py Project: Ydr/TP2Prolog
    def consultar_receta(self):
        self.ingredientesc = self.entry_ingredientesc.get()
        self.pasosc = self.entry_pasosc.get()
        self.nombrec = self.entry_nombrec.get()
        self.autorc = self.entry_autorc.get()
        self.estiloc = self.entry_estiloc.get()

        self.ingredientesc = self.ingredientesc.lower()
        self.pasosc = self.pasosc.lower()
        self.nombrec = self.nombrec.lower()
        self.autorc = self.estiloc.lower()
        self.estiloc = self.estiloc.lower()

        receta = Functor("receta", 5)
        Var1 = Variable()
        Var2 = Variable()
        Var3 = Variable()
        Var4 = Variable()
        Var5 = Variable()

        banderas = [
            "0",
            "0",
            "0",
            "0",
            "0",
        ]  # Arreglo de banderas, nos sirve para saber si el usuario ingreso o no valores en
        # los entry
        if self.ingredientesc != "":
            Var1 = self.ingredientesc
            banderas[0] = "1"
        if self.pasosc != "":
            Var2 = self.pasosc
            banderas[1] = "1"
        if self.nombrec != "":
            Var3 = self.nombrec
            banderas[2] = "1"
        if self.autorc != "":
            Var4 = self.autorc
            banderas[3] = "1"
        if self.estiloc != "":
            Var5 = self.estiloc
            banderas[4] = "1"

        consulta = Query(receta(Var1, Var2, Var3, Var4, Var5))

        contadorConsulta = consulta.nextSolution()
        self.entry_ingredientesc.delete(0, END)
        self.entry_pasosc.delete(0, END)
        self.entry_nombrec.delete(0, END)
        self.entry_autorc.delete(0, END)
        self.entry_estiloc.delete(0, END)

        if contadorConsulta == 0:  # Si no hay coincidencias con la busqueda
            showinfo("Consulta", "No se encontraron coincidencias")
        else:  # Sino se llama a la funcion de muestra de datos
            return self.mostrar_resultados_de_BC(Var1, Var2, Var3, Var4, Var5, banderas)  #
Example #5
0
def computeControl(lab1,lab2):
    controlQ = Query(control(X,lab1))
    controlF = '_' 
    while controlQ.nextSolution():
        controlLab = X.value.__str__()
        endControlLab = controlStack[controlLab]
        if bt(endControlLab,lab2):
#         if not bt(lab2,endControlLab):
            controlF = "control("+controlLab+","+lab2+")"
    controlQ.closeQuery()
    return controlF
Example #6
0
 def query_flight_with_scale(self, origin, destination, scales):
     q = Query(
         self.vuelos(origin, destination, scales, self.Path, self.Cost))
     flight = Flight()
     flight_list = []
     while q.nextSolution():
         flight = Flight()
         flight.scale_number = scales
         flight.path_list = [node.chars for node in self.Path.value]
         flight.cost = self.Cost.value
         flight_list.append(flight)
     q.closeQuery()
     return flight_list
Example #7
0
def consulta(raza, nombre, genero, edad, ecosistema, comida):
    # Se definen las variables
    A = Variable()
    B = Variable()
    C = Variable()
    D = Variable()
    E = Variable()
    F = Variable()
    a = A
    b = B
    c = C
    d = D
    e = E
    f = F

    # Condiciones para encontar las variables unificadoras
    if raza != "vacio":
        a = raza
    if nombre != "vacio":
        b = nombre
    if genero != "vacio":
        c = genero
    if edad != "vacio":
        d = edad
    if ecosistema != "vacio":
        e = ecosistema
    if comida != "vacio":
        f = comida
        # esta lista almacena todas las consultas
    lista = []
    # apertura del query para iniciar consulta en prolog
    q = Query(Animal(a, b, c, d, e, f))
    while q.nextSolution():
        if raza == "vacio":
            a = A.value
        if nombre == "vacio":
            b = B.value
        if genero == "vacio":
            c = C.value
        if edad == "vacio":
            d = D.value
        if ecosistema == "vacio":
            e = E.value
        if comida == "vacio":
            f = F.value
        lista2 = [a, b, c, d, e, f]
        print "consulto", a, b, c, d, e, f
        lista.insert(len(lista), lista2)
        # cierre del query
    q.closeQuery()
    return lista
def main():
    prolog = Prolog()
    prolog.consult("Parientes.pl")
    result = []
    progenitor = Functor("progenitor", 2)

    X = Variable()

    q = Query(progenitor("pedro", X))
    while q.nextSolution():
        print(X.value)
        result.append(X.value)
    q.closeQuery()
    return result
Example #9
0
File: TP2.py Project: Ydr/TP2Prolog
    def mostrar_resultados_de_BC(self, Var1, Var2, Var3, Var4, Var5, banderas):
        ventconsulta = Toplevel()
        ventconsulta.resizable(width=NO, height=NO)

        ventconsulta.title("Consulta")
        ventconsulta.geometry("570x600")

        self.s = Scrollbar(ventconsulta)
        self.TextoResultado = Text(ventconsulta)
        self.TextoResultado.focus_set()
        self.s.pack(side=RIGHT, fill=Y)
        self.TextoResultado.pack(side=LEFT, fill=Y)
        self.s.config(command=self.TextoResultado.yview)
        self.TextoResultado.config(yscrollcommand=self.s.set)
        self.TextoResultado.insert(END, "Coincidencias\n")
        receta = Functor("receta", 5)
        q = Query(receta(Var1, Var2, Var3, Var4, Var5))

        while q.nextSolution():  # Mientras existan soluciones en la base de conocimientos
            if banderas[0] == "1":  # Se verifican las banderas del arreglo, estas se realizan con el fin de verificar
                # la unificacion de la consulta, si en la bandera existe un 1, quiere decir que este
                # argumento se uso para consultar, los demas tienen que ser sacados de la bc por medio
                # de Varn.value
                self.TextoResultado.insert(END, "\nIngredientes: " + Var1 + " ")
            if banderas[1] == "1":
                self.TextoResultado.insert(END, "Pasos: " + Var2 + " ")
            if banderas[2] == "1":
                self.TextoResultado.insert(END, "Receta: " + Var3 + " ")
            if banderas[3] == "1":
                self.TextoResultado.insert(END, "Nombre: " + Var4 + " ")
            if banderas[4] == "1":
                self.TextoResultado.insert(END, "Estilo: " + Var5 + " ")

            if banderas[0] != "1":
                self.TextoResultado.insert(END, "\nIngredientes: %s " % (Var1.value))
            if banderas[1] != "1":
                self.TextoResultado.insert(END, "Pasos: %s " % (Var2.value))
            if banderas[2] != "1":
                self.TextoResultado.insert(END, "Nombre: %s " % (Var3.value))
            if banderas[3] != "1":
                self.TextoResultado.insert(END, "Autor: %s " % (Var4.value))
            if banderas[4] != "1":
                self.TextoResultado.insert(END, "Estilo: %s " % (Var5.value))

        q.closeQuery()

        ventconsulta.mainloop()
def main():
    prolog = Prolog()
    prolog.consult("kanankiri.pl")
    count = int(input("Berapa jumlahnya kiri? ") or 100)
    total = int(input("Berapa total semuanya? ") or 500)
    kanankiri = Functor("kanankiri", 3)
    S = Variable()
    q = Query(kanankiri(S, count, total))
    i = 0
    while q.nextSolution():
        ## [1,5,10,50,100]
        s = zip(S.value, [1, 5, 10, 50, 100])
        print(i),
        for c, v in s:
            print("%dx%d" % (c, v)),
        print()
        i += 1
    q.closeQuery()
Example #11
0
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)
    coins = Functor("coins", 3)
    S = Variable()
    q = Query(coins(S, count, total))
    i = 0
    while q.nextSolution():
        ## [1,5,10,50,100]
        s = zip(S.value, [1, 5, 10, 50, 100])
        print(i, end=" ")
        for c, v in s:
            print("%dx%d" % (c,v), end=" ")
        print()
        i += 1
    q.closeQuery()
Example #12
0
def main():
    prolog = Prolog()
    prolog.consult("coins.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)
    coins = Functor("coins", 3)
    S = Variable()
    q = Query(coins(S, count, total))
    i = 0
    while q.nextSolution():
        ## [1,5,10,50,100]
        s = zip(S.value, [1, 5, 10, 50, 100])
        print i,
        for c, v in s:
            print "%dx%d" % (c, v),
        print
        i += 1
    q.closeQuery()
Example #13
0
def consult(values):
    prolog = Prolog()  # Call class
    prolog.consult("coins.pl")  # Call consult
    count = int(values[0] or 100)
    total = int(values[1] or 500)
    coins = Functor("coins", 3)
    S = Variable()
    q = Query(coins(S, count, total))
    i = 0
    # Consult the kdb
    while q.nextSolution():
        ## [1,5,10,50,100]
        s = zip(S.value, [1, 5, 10, 50, 100])
        print(i, end=" ")
        for c, v in s:
            print("%dx%d" % (c, v), end=" ")
        print()
    i += 1
    q.closeQuery()
Example #14
0
def lab2Instr(myLab):
    if type(myLab).__name__ == 'dict':
        ks = myLab.keys()
        for key in ks:
            q = Query(find_instr(key,X,Y))
            if q.nextSolution():                
                instrM[instrTrans(X.value.__str__())] = M[key]
            q.closeQuery()
#         print("instrM:"+str(instrM))
#         return instrM
    elif type(myLab).__name__ == 'list':
        i = 0
        while i < len(myLab):
            
            tempLab = myLab[i]
            q = Query(find_instr(tempLab,X,Y))
            if q.nextSolution():                
                instrR.append(instrTrans(X.value.__str__()))
            q.closeQuery()
            i = i+1
Example #15
0
    def Pick(self, occupation: str, age: int, prev_accidents: int,
             car_model: int) -> Set[Tuple[int, str, str, int, float, str]]:
        INSURANCE_ID, INSURANCE_TYPE, INSURANCE_COVERAGE, \
        INSURANCE_DURATION, INSURANCE_PRICE, INSURANCE_PRICE_RANGE = \
            Variable(), Variable(), Variable(), Variable(), Variable(), Variable()
        fpick = Functor("pick", 10)

        query = Query(
            fpick(occupation, age, prev_accidents, car_model, INSURANCE_ID,
                  INSURANCE_TYPE, INSURANCE_COVERAGE, INSURANCE_DURATION,
                  INSURANCE_PRICE, INSURANCE_PRICE_RANGE))

        results = set()
        while query.nextSolution():
            results.add(
                (INSURANCE_ID.value, str(INSURANCE_TYPE.value),
                 str(INSURANCE_COVERAGE.value), INSURANCE_DURATION.value,
                 INSURANCE_PRICE.value, str(INSURANCE_PRICE_RANGE.value)))
        query.closeQuery()

        return results
def consultaProlog(pregunta):
    relacion = '0'
    nombre1 = '0'
    nombre2 = '0'
    unica = 0
    result = []
    value = ''

    #Instancia de la clase prolog
    prolog = Prolog()

    #Definicion del erchivo que se consultara
    prolog.consult("Ejercicio1.pl")

    y = pregunta.split(' ')

    p = 0

    while p != len(y):

        #si no hay ninguna relacion en la variable relacion, busco dentro de los diccionarios
        if relacion == '0':
            relacion, unica = relaciones(y[p])

        #Verifico que existan los nombres dentro del diccionario
        if nombre1 == '0':
            nombre1 = nombres(y[p])
        elif nombre2 == '0' and nombre1 != '0':
            nombre2 = nombres(y[p])

        p = p + 1

    #Verifica si es consulta de tipo hecho
    if relacion != '0' and nombre1 != '0' and nombre2 != '0':
        #Consulta por medio de prolog.query(la consulta) y esta devuelve true o false
        if bool(
                list(
                    prolog.query("" + relacion + "(" + nombre1 + "," +
                                 nombre2 + ")"))):
            value = 'Asi es!'
            return value
        else:
            value = 'Incorrecto!'
            return value

    #Verifica si es consulta de tipo variable incognita
    elif relacion != 0 and nombre1 != '0' and nombre2 == '0' and unica != 1:
        #Se define la estrucutura arbitraria functor
        rel = Functor("" + relacion + "", 2)
        #Variable incognita X
        X = Variable()
        #Consulta
        q = Query(rel("" + nombre1 + "", X))
        while q.nextSolution():
            value = value + ', ' + str(X.value)
        q.closeQuery()
        return value

    #Verifica si es consulta de tipo unica
    elif relacion != '0' and nombre1 != '0' and nombre2 == '0' and unica == 1:
        if bool(list(prolog.query("" + relacion + "(" + nombre1 + ")"))):
            value = 'Asi es!'
            return value
        else:
            value = 'Incorrecto!'
            return value

    #Si no existe ninguna palabra dentro de los diccionarios, no entiende la sentencia el sistema
    elif relacion == '0' and nombre1 == '0' and nombre2 == '0':
        value = 'Perdon, no logro entenderte!!'
        return value
Example #17
0
__author__ = 'btavares e fferreira'


from pyswip import Functor, Variable, Query, call,Prolog


assertz = Functor("assertz", 1)
father = Functor("father", 2)

call(assertz(father("michael","john")))
call(assertz(father("michael","gina")))

X = Variable()

q = Query(father("michael",X))
while q.nextSolution():
    print "Hello,", X.value
q.closeQuery()


prolog = Prolog()

#prolog.consult("e:/ia/testeXadrezBFa.pl")
prolog.consult("f:/temp/pee1.pl")
#prolog.assertz("posicao(2,3)")

for result in prolog.query("mover( 3/4, X/Y, C )"):
    print result['X'], result['Y'], result['C']


for result in prolog.query("aStar( 6/6, V, C)",maxresult=1):
Example #18
0
        entryLab = solution["ELab"]
      
find_instr = Functor("find_instr",3)#add new fact,rule to the .pl file
prolog.assertz("find_instr(X,Y,Z):-instr(X,Y,Z)")#the definition of fact or gule
X = Variable()
# lab1 = "fD__workspace_antlr_C_DynamixMem_c___mmain_r3c3"
lab1 = entryLab
flowM2Ep = "flow("+mainM+","+lab1+")"
prolog.assertz(flowM2Ep)


Y = Variable()
Z = Variable()
V = Variable()
# lab1 = "fD__workspace_swipl_tryEX_c___mmain_r17c3"
q = Query(find_instr(lab1,Y,Z))
# IniflowFact = str()
while True:
    if q.nextSolution() :        
        print("The instr of " + lab1 + " is:    " + Y.value.__str__())
#         print(" and the next instr is in:" + Z.value.__str__())
        instr = Y.value.__str__()
        tempLab = lab1
        lab1 = Z.value.__str__()
        lab2 = Z.value.__str__()
        q.closeQuery()
            
        if not (instr.startswith("ite(") or instr.startswith("switch(")):
            if instr.startswith("for(") or instr.startswith("while("):
                IniflowFact = "flow("+tempLab+","+lab1+")"   
                controlFact = computeControl(tempLab,lab1)
Example #19
0
def consultaProlog(pregunta):
    relacion = '0'
    nombre1 = '0'
    nombre2 = '0'
    unica = 0
    prolog = Prolog()
    prolog.consult("Parientes.pl")
    result = []
    value = ''

    # Solicito la entrada
    #print('Ingrese la pregunta:')
    #pregunta = input()

    y = pregunta.split(' ')

    p = 0
    while p != len(y):

        if relacion == '0':
            relacion, unica = relaciones(y[p])

        if nombre1 == '0':
            nombre1 = nombres(y[p])
        elif nombre2 == '0' and nombre1 != '0':
            nombre2 = nombres(y[p])

        p = p + 1

    if relacion != '0' and nombre1 != '0' and nombre2 != '0':
        if bool(
                list(
                    prolog.query("" + relacion + "(" + nombre1 + "," +
                                 nombre2 + ")"))):
            value = 'Asi es!'
            #print("Asi es!")
            return value
        else:
            value = 'Incorrecto!'
            #print('Incorrecto!')
            return value

    elif relacion != 0 and nombre1 != '0' and nombre2 == '0' and unica != 1:
        rel = Functor("" + relacion + "", 2)

        X = Variable()

        q = Query(rel("" + nombre1 + "", X))
        print('')
        print('')
        while q.nextSolution():
            value = value + ', ' + str(X.value)
            #print("LA RESPUESTA ES: ", X.value)

        q.closeQuery()
        return value
    elif relacion != '0' and nombre1 != '0' and nombre2 == '0' and unica == 1:

        if bool(list(prolog.query("" + relacion + "(" + nombre1 + ")"))):
            value = 'Asi es!'
            #print("Asi es!")
            return value
        else:
            value = 'Incorrecto!'
            return value
            #print("Incorrecto!")
    elif relacion == '0' and nombre1 == '0' and nombre2 == '0':
        value = 'Perdon, no logro entenderte!!'
        return value
Example #20
0
def notExsitFact(factStr):
    tempFact = factStr
    if tempFact.startswith("flow("):
        para1 = str(tempFact.split(",")[0][5:])
        para2 = str(tempFact.split(",")[1][:-1])
        query = Query(flow(para1,para2))
    elif tempFact.startswith("control("):
        para1 = str(tempFact.split(",")[0][8:])
        para2 = str(tempFact.split(",")[1][:-1])
        query = Query(control(para1,para2))
    elif tempFact.startswith("refF("):
        para1 = str(tempFact.split(",")[0][5:])
        para2 = str(tempFact.split(",")[1][:-1])
        query = Query(refF(para1,para2))
    elif tempFact.startswith("defF("):
        para1 = str(tempFact.split(",")[0][5:])
        para2 = str(tempFact.split(",")[1][:-1])
        query = Query(defF(para1,para2))
    elif tempFact.startswith("dataDepF("):
        para1 = str(tempFact.split(",")[0][8:])
        para2 = str(tempFact.split(",")[1])
        para3 = str(tempFact.split(",")[2][:-1])
        query = Query(dataDepF(para1,para2,para3))
    if query.nextSolution():
        #print("already exsit")
        query.closeQuery()
        return False
    query.closeQuery()
    return True
Example #21
0
from pyswip import Functor, Variable, Query, call
assertz = Functor("assertz", 1)
father = Functor("father", 2)

call(assertz(father("mi", "j")))
call(assertz(father("mi", "g")))

X = Variable()
q = Query(father("mi", X))
while q.nextSolution():
    print "Hello,", X.value
q.closeQuery()
Example #22
0
def consultarBC(Raza, Edad,Genero,Nombre,Ecosistema,Comida):
    print "Consultando..."
    q = Query(animal(Raza,Edad,Genero,Nombre,Ecosistema,Comida))
    while q.nextSolution():
        print "Hello,",Raza.value, Edad.value, Genero.value, Nombre.value, Ecosistema.value, Comida.value