Ejemplo n.º 1
0
 def __init__(self, file_name):
     self.file_name = file_name
     self.Scales = Variable()
     self.Path = Variable()
     self.Cost = Variable()
     self.assertz = Functor("assertz", 1)
     self.retract = Functor("retract", 1)
     self.vuelos = Functor("vuelos", 5)
     self.edge = Functor("edge", 3)
     self.prolog = Prolog()
     self.prolog.consult(self.file_name)
    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)
Ejemplo n.º 3
0
    def test_issue_3(self):
        """
       	Problem with variables in lists

        https://code.google.com/p/pyswip/issues/detail?id=3
        """

        from pyswip import Prolog, Functor, Variable, Atom
        from deepstr import deep_str

        p = Prolog()

        f = Functor('f', 1)
        A = Variable()
        B = Variable()
        C = Variable()

        x = f([A, B, C])
        x = Functor.fromTerm(x)
        args = x.args[0]

        self.assertFalse(args[0] == args[1], "Var A equals var B")
        self.assertFalse(args[0] == args[2], "Var A equals var C")
        self.assertFalse(args[1] == args[2], "Var B equals var C")

        self.assertFalse(A == B, "Var A equals var B")
        self.assertFalse(B == C, "Var A equals var C")
        self.assertFalse(A == C, "Var B equals var C")

        # A more complex test
        x = f([A, B, 'c'])
        x = Functor.fromTerm(x)
        args = x.args[0]
        self.assertEqual(type(args[0]), Variable)
        self.assertEqual(type(args[1]), Variable)
        self.assertEqual(type(args[2]), Atom)

        # A test with repeated variables
        x = f([A, B, A])
        x = Functor.fromTerm(x)
        args = x.args[0]
        self.assertEqual(type(args[0]), Variable)
        self.assertEqual(type(args[1]), Variable)
        self.assertEqual(type(args[2]), Variable)
        self.assertTrue(
            args[0] == args[2], "The first and last var of "
            "f([A, B, A]) should be the same")
    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)
Ejemplo n.º 5
0
def main():
    letters = "S E N D M O R Y".split()
    prolog = Prolog()
    sendmore = Functor("sendmore")
    prolog.consult("money.pl")

    X = Variable()
    call(sendmore(X))
    r = X.value
    for i, letter in enumerate(letters):
        print(letter, "=", r[i])
    print("That's all...")
Ejemplo n.º 6
0
    def test_issue_5(self):
        """
       	Patch: hash and eq methods for Atom class.

        Ensures that the patch is working.

        https://code.google.com/p/pyswip/issues/detail?id=5
        """

        from pyswip import Atom, Variable

        a = Atom('test')
        b = Atom('test2')
        c = Atom('test')  # Should be equal to a

        self.assertNotEqual(a, b)
        self.assertNotEqual(c, b)
        self.assertEqual(a, c)

        atomSet = set()
        atomSet.add(a)
        atomSet.add(b)
        atomSet.add(c)  # This is equal to a
        self.assertEqual(len(atomSet), 2)
        self.assertEqual(atomSet, set([a, b]))

        # The same semantics should be valid for other classes
        A = Variable()
        B = Variable()
        C = Variable(A.handle)  # This is equal to A

        self.assertNotEqual(A, B)
        self.assertNotEqual(C, B)
        self.assertEqual(A, C)
        varSet = set()
        varSet.add(A)
        varSet.add(B)
        varSet.add(C)  # This is equal to A
        self.assertEqual(len(varSet), 2)
        self.assertEqual(varSet, set([A, B]))
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
Ejemplo n.º 8
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()
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()
Ejemplo n.º 10
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()
Ejemplo n.º 11
0
    def parse_ins(instruction) -> list and list and list:
        if instruction[-1] != ';':
            instruction += ';'
        terms = []  # if need var(s)
        vars = []
        statements = []  # if need True or False
        pnames = re.compile(
            r'\[.+\]|[\w\d]+')  # find names(vars|lists|strings|ints) in atoms
        plist = re.compile(r'\[.+\]')  # find list
        # find predirects
        for pred, atoms in re.findall(r'([^\(\)\,\s]+|\S)(\([^\)]+\))\;',
                                      instruction):
            names = pnames.findall(atoms)
            items = []
            there_is_var = False
            for atom in names:
                atom = atom.strip()

                if atom[0].isupper():  # check for var
                    any_var = Variable()  # link to Prologs var
                    items.append(any_var)
                    vars.append((atom, any_var))
                    there_is_var = True

                elif atom.isdigit():  # check for int
                    items.append(int(atom))

                elif plist.search(atom):  # check for list
                    items.append(literal_eval(atom))

                else:
                    try:  # check for float
                        items.append(float(atom))
                    except ValueError:
                        items.append(atom)
            if there_is_var:
                terms.append(Functor(pred, len(names))(*items))
            else:
                statements.append((Functor(pred,
                                           len(names))(*items), pred + atoms))
        return terms, vars, statements
Ejemplo n.º 12
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
# LEDtest.py by D. J. Norris  Jan, 2017
# Uses Prolog with Python type functions
import time
import RPi.GPIO as GPIO
from pyswip import Functor, Variable, Query, call

# Setup Python like functions for Prolog statements
assertz = Functor(“assertz”, 1)
father = Functor(“father”, 2)

# Add facts to a dynamic database
call(assertz(father(“michael”,”john”)))
call(assertz(father(“michael”,”gina”)))

# Setup an iterative query session
X = Variable()
q = Query(father(“michael”,X))
while q.nextSolution():
    print “Hello,”, X.value
    if X.value == “john”:          # Lite LED #4 if john is a child of michael
        GPIO.output(4,GPIO.HIGH)
        time.sleep(5)
        GPIO.output(4,GPIO.LOW)
    if X.value == “gina”:          # Lite LED #17 if gina is a child of michael
        GPIO.output(17,GPIO.HIGH)
        time.sleep(5)
        GPIO.output(17,GPIO.LOW)

Ejemplo n.º 14
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
Ejemplo n.º 15
0
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):
    for estado in result['V']:
        print estado.args

V = Variable()
C = Variable()
E = Variable()
aStar = Functor("aStar", 3)
posicao = Functor("posicao",2)
q = Query(posicao( V, C) )
pos= '3/7'
#q = Query(aStar(pos, V, C) )
while q.nextSolution():
    vec = V.get_value()
    cust = C.get_value()
    print "aa"

q.closeQuery()

print "*** FIM ***"
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
Ejemplo n.º 17
0
 def test_unifying_list_correctly(self):
     variable = Variable()
     variable.value = [1, 2]
     self.assertEquals(variable.value, [1, 2],
                       'Lists should be unifyed correctly.')
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
Ejemplo n.º 19
0
#     print(mainDefFact.split(';',1)[0])
    prolog.assertz(mainDefFact.split(';',1)[0])
    try:
        mainDefFact = mainDefFact.split(';',1)[1]
    except:
        mainDefFact = str()


if entryP != "":#self-definition method
    entryLabStr = "entry_point("+ entryP+",ELab)"
    for solution in prolog.query(entryLabStr):  
        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__())
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