Exemplo n.º 1
0
 def __init__(self):
     self.prolog = Prolog()
     self.prolog.consult("covidprologknowledgebase.pl")
     self.risk_of_getting_covid = 0
Exemplo n.º 2
0
    def __init__(self, main):
        #cargamos los datos de prolog aqui
        self.prolog = Prolog()
        self.cargarBaseBibliografo()
        self.perfil = Perfil.Perfil
        self.filtro = Filtro.Filtro

        self.main = main
        self.main.title('Titulo de la aplicacion')
        self.main.geometry('1020x650')
        self.main.resizable(width=0, height=0)

        #Creando el header frame de la aplicacion
        frameCabeza = LabelFrame(self.main, text='Opciones')
        frameCabeza.grid(row=0, column=0)

        #Creacion de botones para lanzar las configuraciones
        ttk.Button(frameCabeza, text="Filtros",
                   command=self.filtro).grid(row=0, column=0)
        ttk.Button(frameCabeza, text='Perfil',
                   command=self.perfil).grid(row=0, column=1)
        ttk.Button(frameCabeza, text='Filtrar',
                   command=self.filtrar).grid(row=0, column=2)
        #Creando un con Frame para contener los datos de la izquierda
        frameIzquierdo = LabelFrame(self.main, text='Lista de libros')
        frameIzquierdo.grid(row=1, column=0)

        frameDerecho = LabelFrame(self.main, text='Sugerencias')
        frameDerecho.grid(row=3, column=0)

        #Tabla para presentar todos los libros
        self.tablaIzquierda = ttk.Treeview(frameIzquierdo,
                                           columns=('Autor', 'Genero',
                                                    'Precio', 'Rating',
                                                    'Fecha', 'Estado'),
                                           height=15)

        #poniendo el scrollbar en la tabla
        vsb = ttk.Scrollbar(self.main,
                            orient="vertical",
                            command=self.tablaIzquierda.yview)
        vsb.place(x=985, y=86, height=300)
        self.tablaIzquierda.configure(yscrollcommand=vsb.set)

        self.tablaIzquierda.grid(row=4, column=0)
        self.tablaIzquierda.heading('#0', text='Titulo')
        self.tablaIzquierda.column('#0', minwidth=0, width=200, stretch=NO)

        self.tablaIzquierda.heading('#1', text='Autor')
        self.tablaIzquierda.column('#1', minwidth=0, width=200, stretch=NO)

        self.tablaIzquierda.heading('#2', text='Genero')
        self.tablaIzquierda.column('#2', minwidth=0, width=200, stretch=NO)

        self.tablaIzquierda.heading('#3', text='Precio')
        self.tablaIzquierda.column('#3', minwidth=0, width=100, stretch=NO)

        self.tablaIzquierda.heading('#4', text='Rating')
        self.tablaIzquierda.column('#4', minwidth=0, width=100, stretch=NO)

        self.tablaIzquierda.heading('#5', text='Fecha')
        self.tablaIzquierda.column('#5', minwidth=0, width=100, stretch=NO)

        self.tablaIzquierda.heading('#6', text='Estado')
        self.tablaIzquierda.column('#6', minwidth=0, width=100, stretch=NO)

        #llenando la tabla superior
        for libro in self.prolog.query("libro(T,A,G,P,D,R,E,_)"):
            self.tablaIzquierda.insert('',
                                       0,
                                       text=libro["T"],
                                       value=(libro["A"], libro["G"],
                                              libro["P"], libro["R"],
                                              libro["D"], libro["E"]))

        #Tabla para presentar las sugerencias
        self.tablaDerecha = ttk.Treeview(frameDerecho,
                                         columns=('Autor', 'Genero', 'Precio',
                                                  'Rating', 'Fecha', 'Estado'),
                                         height=10)

        #poniendo el scrollbar en la tabla
        vsb2 = ttk.Scrollbar(self.main,
                             orient="vertical",
                             command=self.tablaDerecha.yview)
        vsb2.place(x=985, y=430, height=203)
        self.tablaDerecha.configure(yscrollcommand=vsb2.set)

        self.tablaDerecha.grid(row=4, column=0)
        self.tablaDerecha.heading('#0', text='Titulo')
        self.tablaDerecha.column('#0', minwidth=0, width=200, stretch=NO)

        self.tablaDerecha.heading('#1', text='Autor')
        self.tablaDerecha.column('#1', minwidth=0, width=200, stretch=NO)

        self.tablaDerecha.heading('#2', text='Genero')
        self.tablaDerecha.column('#2', minwidth=0, width=200, stretch=NO)

        self.tablaDerecha.heading('#3', text='Precio')
        self.tablaDerecha.column('#3', minwidth=0, width=100, stretch=NO)

        self.tablaDerecha.heading('#4', text='Rating')
        self.tablaDerecha.column('#4', minwidth=0, width=100, stretch=NO)

        self.tablaDerecha.heading('#5', text='Fecha')
        self.tablaDerecha.column('#5', minwidth=0, width=100, stretch=NO)

        self.tablaDerecha.heading('#6', text='Estado')
        self.tablaDerecha.column('#6', minwidth=0, width=100, stretch=NO)
Exemplo n.º 3
0
from pyswip import Prolog

prolog = Prolog()
prolog.consult("/home/U4LEO/proyecto/hechos.pl")
print("----------------------------------------------------------")
print("SISTEMA EXPERTO PARA LA PREDICION DE LA ENFERMEDAD DE COVID19")
print("----------------------------------------------------------")
r = False

while not r:

    for valor in prolog.query("probable(X,covid)"):
        print(' TIENEN MAS PROBABILIDADES DE PADECER COVID19 => ', valor["X"])

    for valor in prolog.query("probvivir(X)"):
        print(' NO TIENEN PROBABILIDADES DE PADECER COVID19 => ', valor["X"])

    X = input(
        "--------------------------\nPOR SUS SINTOMAS\n--------------------------\n Inserta el nombre de la persona "
    )

    for valor in prolog.query("tiene(" + X + ", Y)"):
        print(X, ' TIENE SINTOMAS DE => ', valor["Y"], "URGENTE IR AL MÉDICO")

    X = input(
        "--------------------------\nPOR SUS ENFERMEDADES\n--------------------------\nInserta el nombre de la persona "
    )

    for valor in prolog.query("padece(" + X + ", Y)"):
        print(X, ' PADECE DE => ', valor["Y"], "NECESITA CUIDARSE")
Exemplo n.º 4
0
 def __init__(self):
     self.prolog_instance = Prolog()
     self.prolog_instance.consult(
         'C:/Users/jmlma/Documents/GitHub/arbol-genealogico-prolog/smart-hub-prolog/proyectofinal.pl'
     )
     self.graph = Digraph()
Exemplo n.º 5
0
 def __init__(self):
     self._prolog = Prolog()
     self._prolog.consult('utils/geo_eval/geobase.pl')
     self._prolog.consult('utils/geo_eval/geoquery.pl')
     self._prolog.consult('utils/geo_eval/eval.pl')
Exemplo n.º 6
0
        list_question = question.list_return()

        # 转换成prolog语言可处理的输入
        prolog_question = ""
        for item in list_question:
            if item == -1:
                prolog_question += "_"
            else:
                prolog_question += str(item + 1)
            prolog_question += ","
        prolog_question = prolog_question.rstrip(",")

    # 运行pl文件,求出结果
    # print(prolog_question)
    solution_pl = Prolog()
    solution_pl.consult("sudoku_solution.pl")
    # print(prolog_question)
    result = solution_pl.query("sudoku([" + prolog_question + "], X, " +
                               str(sudoku_size) + ").")
    # result = solution_pl.query("findall(Solution, sudoku([" + prolog_question + "],Solution), X).")
    # result = solution_pl.query("problem(1, Rows), sudoku(Rows), maplist(portray_clause, Rows).")

    # 打印结果
    count = 1
    for res in result:
        print("Possible answer " + str(count) + " :")
        # print(res)
        solution = res["X"]
        if len(solution) != 0:
            sudoku.list_print_like_sudoku(solution, sudoku_size)
Exemplo n.º 7
0
def get_trash(day: str):
    prolog = Prolog()
    from os import sep  # os invariant separator
    prolog.consult(f"Logic{sep}TrashRecognition{sep}TrashKnowledge.pl")
    print(list(prolog.query("collect_trash(X)")))
inplist = []
inp11 = input('Are you a creative person liking arts and patterns?')
tok1 = word_tokenize(inp11)
for wod in tok1:
    stem1 = ps.stem(wod)
    inplist.append(stem1)
if "ye" in inplist:
  f.write("creative(yes).\n")
else:
  f.write("creative(no).\n")

inplist = []
inp12 = input('Do you like planning and organising things and situation?')
tok1 = word_tokenize(inp12)
for wod in tok1:
    stem1 = ps.stem(wod)
    inplist.append(stem1)
if "ye" in inplist:
  f.write("planning(yes).\n")
else:
  f.write("planning(no).\n")

f.close()

swipl = Prolog()
swipl.consult("/content/careerAdvisory.pl")
career_suggested = list(swipl.query("find_career(Career)"))
for i in range(len(career_suggested)):
    var = career_suggested[i]['Career'].decode('utf-8')
    output(var)
Exemplo n.º 9
0
def find_solution(size=8, num_boxes=2, time_limit=10, seed=0):
    dim_room = (size, size)

    env = SokobanEnvFast(dim_room=dim_room,
                         num_boxes=num_boxes,
                         seed=seed,
                         penalty_for_step=0)
    # The encoding of the board is described in README
    board = env.reset()

    wall = board[:,:,0] # this is a one-hot encoding of walls
    # For readibility first we deal with tops and then with rights
    tops = []
    for i in range(dim_room[0]):
        for j in range(dim_room[1]-1):
            if wall[i,j] == 0 and wall[i,j+1] == 0:
                tops.append("top(x{}y{},x{}y{})".format(i,j,i,j+1))

    rights = []
    for i in range(dim_room[0]-1):
        for j in range(dim_room[1]):
            if wall[i,j] == 0 and wall[i+1,j] == 0:
                rights.append("right(x{}y{},x{}y{})".format(i,j,i+1,j))

    boxes_initial_locations = board[:,:,4]
    boxes_initial = []
    for i in range(dim_room[0]):
        for j in range(dim_room[1]):
            if boxes_initial_locations[i,j] == 1:
                boxes_initial.append("box(x{}y{})".format(i,j))

    boxes_target_locations = board[:,:,2]
    boxes_target = []
    for i in range(dim_room[0]):
        for j in range(dim_room[1]):
            if boxes_target_locations[i,j] == 1:
                boxes_target.append("solution(x{}y{})".format(i,j))

    sokoban_initial_location = board[:,:,5] + board[:,:,6]
    for i in range(dim_room[0]):
        for j in range(dim_room[1]):
            if sokoban_initial_location[i,j] == 1:
                sokoban_string = "sokoban(x{}y{})".format(i,j)
                break

    tops_string = "[" + ','.join(tops) + ']'
    rights_string = "[" + ','.join(rights) + ']'
    boxes_initial_string = "[" + ','.join(boxes_initial) + ']'
    boxes_target_string = "[" + ','.join(boxes_target) + ']'

    prolog = Prolog()
    prolog.consult("sokoban.pl")
    query = "call_with_time_limit({},solve([{},{},{},{},{}],Solution))".format(time_limit,
                                                                               tops_string,
                                                                               rights_string,
                                                                               boxes_initial_string,
                                                                               boxes_target_string,
                                                                               sokoban_string)
    
    if len(boxes_target) != 2:
        print("rozna od 2 ilosc miejsc docelowych")
    print(query)
    try:
        result = list(prolog.query(query))
        print(result)
        rewards = []
        for i, r in enumerate(result):
            solution = r['Solution']
            print(solution)
            # observation, reward, done, info = env.step(action)

            return 1, solution

    except:
        return 0, []
Exemplo n.º 10
0
def create_blocks(blocks, matches):
    pblocks = []
    types = []
    ranges = []
    dependant_types = []
    block_lookup = {}
    match_f = []
    for i, mi in matches:
        match_f.append(f'match({i}, {mi})')
    for block in blocks:
        block_id = block.block_id
        block_lookup[block.block_id] = block
        if isinstance(block, Block):
            pblocks.append(
                f'data_block({block_id}, {block.x1}, {block.y1}, {block.x2}, {block.y2}, {block.width}, {block.height})'
            )
        if isinstance(block, FormulaBlockHorizontal):
            template = block.template.replace('"', '')
            pblocks.append(
                f'h_formula_block({block_id}, "{template}", {block.i1}, {block.i2}, {block.height}, {block.relative})'
            )
            for range_name, range_types in block.dependant_types.items():
                ranges.append(
                    f'range({block_id}, {block_id}_{range_name}, {range_name})'
                )
                for type in range_types:
                    dependant_types.append(
                        f'raw_depends({block_id}_{range_name}, {type})')
        if isinstance(block, FormulaBlockVertical):
            template = block.template.replace('"', '')
            pblocks.append(
                f'v_formula_block({block_id}, "{template}", {block.i1}, {block.i2}, {block.width}, {block.relative})'
            )
            for range_name, range_types in block.dependant_types.items():
                ranges.append(
                    f'range({block_id}, {block_id}_{range_name}, {range_name})'
                )  # Otherwise ranges from different formulas interfere
                for type in range_types:
                    dependant_types.append(
                        f'raw_depends({block_id}_{range_name}, {type})')
        for type in block.types:
            types.append(f'raw_type({block_id}, {type})')

    prolog = Prolog()
    print('prolog:-----')
    with open('/tmp/rules.pl', 'w') as outfile:
        with open(os.path.join(PACKAGE_PATH, 'rules.pl'), 'r') as infile:
            for line in infile:
                outfile.write(line)
        for s in pblocks + types + ranges + dependant_types + match_f:
            sout = s + '.'
            outfile.write(sout + '\n')
            print(sout)

    #for s in pblocks + types + dependant_types + match_f:
    #    print(s)
    #    prolog.assertz(s)
    print('-------------')
    prolog.consult('/tmp/rules.pl')

    for ans in prolog.query('output(Blocks)'):
        oblocks = list(ans['Blocks'])
    print('outputb', oblocks)

    blocks = [
        OutputBlock([orb.value
                     for orb in b.args[0]], b.args[1].value, b.args[2].value,
                    b.args[3].value, b.args[4].value, b.args[5], b.args[6],
                    [block_lookup[orb.value] for orb in b.args[0]],
                    [(debb.args[0].value, debb.args[1].value,
                      unpack_dependency_trace(debb.args[2]))
                     for debb in b.args[7]]) for b in oblocks
    ]
    # Convert dependencies list to references to OutputBlocks
    block_name_map = {(bid, tuple([(deps[0], deps[1])] + deps[2])): block
                      for block in blocks for bid in block.id
                      for deps in block.dependencies}
    print('block_name_map', block_name_map)
    for block in blocks:
        new_dependencies = {}
        for name, range_name, trace in block.dependencies:
            if name != 'none':
                edep = new_dependencies.get(range_name, [])
                edep.append(block_name_map[name, tuple(trace)])
                new_dependencies[range_name] = edep
        block.old_dependencies = block.dependencies
        block.dependencies = new_dependencies
    print('blocks! ', blocks)
    return blocks
Exemplo n.º 11
0
 def __init__(self):
     self.prolog_instance = Prolog()
     self.prolog_instance.consult('/home/saulfeliciano/IdeaProjects/arbol-genealogico-prolog/smart-hub-prolog/proyectofinal.pl')
     self.graph = Digraph()
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
Exemplo n.º 13
0
def get_schedules():
    p = Prolog()
    p.consult('knowledge_base.pl')
    route = request.args.get('route')
    return ""
Exemplo n.º 14
0
def set_board_size(board):
    prolog = Prolog()
    prolog.consult(KnowledgeBase.PATH)
    prolog.assertz(KnowledgeBase.BOARD_SIZE_FACT.format(
        board.ROWS, board.COLS))
Exemplo n.º 15
0
 def __init__(self):
     self.prolog = Prolog()
     build_facts()
     self.prolog.consult(f"{PROLOG_FILE}")
     self.prolog.consult(f"{TODAY}")
Exemplo n.º 16
0
    def __init__(self, file):

        self.file = file
        self.prolog = Prolog()
        self.board = None
        self.prolog.consult(file)
Exemplo n.º 17
0
import meta_grammar as meta
from cmd import Cmd
from pyswip import Prolog
from datetime import datetime
from shutil import copy2
import re

pl = Prolog()


class ProlexaPlus(Cmd):
    intro = '­Ъцќ: Hello! I\'m Hyprolexa! Did you know that a dog is a kind of domesticated animal? ­ЪљЋ Anyway...'
    prompt = '­ЪДа: '
    file = None

    def preloop(self):
        ks = input(
            '\n­Ъцќ: Before we begin, would you like to jog my memory? Give me the name of an existing knowledge store...\n­ЪДа: '
        )
        try:
            copy2(f'history/{ks}.pl', 'knowledge_store.pl')
            print('­Ъцќ: Oh yes, I remember now!\n')

            # Maybe say 'we spoke about cows and honey'
        except:
            print("­Ъцќ: That doesn't remind me of anything.\n")

    def default(self, input_):

        # Quit program using the follwing words:
        stopwords = ["bye", "halt", "quit", "exit", "stop"]
Exemplo n.º 18
0
 def __init__(self, decisionsLen, factsLen):
     self.__prologEngine = Prolog(
     )  # The engine given by Pyswip SWI Prolog library
     self.__learning = learning.Learning(self.__prologEngine)
     self.__memory = memory.Memory(decisionsLen, factsLen)
     self.__behaviour = behaviour.Behaviour(self.__prologEngine)
Exemplo n.º 19
0
class Main(tk.Frame):
    mydb = connector.connect(host="localhost",
                             user="******",
                             password="******",
                             database="prologdb",
                             auth_plugin='mysql_native_password')

    prolog = Prolog()
    prolog.consult("./ind2.pl")

    def __init__(self, root):
        super().__init__(root)
        self.init_main()

    def init_main(self):
        self.label_firstTeamWin = tk.Label(text="Победы первой команды:",
                                           font="times 12")
        self.label_firstTeamWin.place(relx=0.05, rely=0.01)

        self.entry_firstTeamWin = tk.Entry(width=20,
                                           font="times 12",
                                           justify="c")
        self.entry_firstTeamWin.place(relx=0.05, rely=0.08)

        self.label_firstTeamWeak = tk.Label(text="Больные первой команды:",
                                            font="times 12")
        self.label_firstTeamWeak.place(relx=0.05, rely=0.16)

        self.entry_firstTeamWeak = tk.Entry(width=20,
                                            font="times 12",
                                            justify="c")
        self.entry_firstTeamWeak.place(relx=0.05, rely=0.22)

        self.label_resTT = tk.Label(text="Победы между командами:",
                                    font="times 12")
        self.label_resTT.place(relx=0.05, rely=0.3)

        self.entry_resTT = tk.Entry(width=20, font="times 12", justify="c")
        self.entry_resTT.place(relx=0.05, rely=0.36)

        self.label_secondTeamWin = tk.Label(text="Победы второй команды:",
                                            font="times 12")
        self.label_secondTeamWin.place(relx=0.05, rely=0.44)

        self.entry_secondTeamWin = tk.Entry(width=20,
                                            font="times 12",
                                            justify="c")
        self.entry_secondTeamWin.place(relx=0.05, rely=0.5)

        self.label_secondTeamWeak = tk.Label(text="Больные второй команды:",
                                             font="times 12")
        self.label_secondTeamWeak.place(relx=0.05, rely=0.56)

        self.entry_secondTeamWeak = tk.Entry(width=20,
                                             font="times 12",
                                             justify="c")
        self.entry_secondTeamWeak.place(relx=0.05, rely=0.64)

        self.label_db = tk.Label(text="Данные в базе:", font="times 12")
        self.label_db.place(relx=0.6, rely=0.01)

        self.listbox = tk.Listbox(root)
        self.listbox.place(relx=0.6, rely=0.08)

        self.scrollbar = tk.Scrollbar(root)
        self.scrollbar.pack(side=tk.RIGHT, fill=tk.BOTH)

        self.listbox.config(yscrollcommand=self.scrollbar.set)
        self.scrollbar.config(command=self.listbox.yview)

        self.text = tk.StringVar()
        self.label_qtyFunc = tk.Label(textvariable=self.text, font="times 12")
        self.label_qtyFunc.place(relx=0.05, rely=0.8)

        btn_apply = tk.Button(text="Результат", font="times 12", width=12)
        btn_apply.place(relx=0.6, rely=0.5)
        btn_apply.bind(
            '<Button-1>', lambda event: self.calculate(
                self.entry_firstTeamWin.get(), self.entry_firstTeamWeak.get(),
                self.entry_resTT.get(), self.entry_secondTeamWin.get(),
                self.entry_secondTeamWeak.get()))

    def solution(self, x, Mx, TgX, y, My, TgY, R, z, Mz, TgZ, x1, y1):
        try:
            URL = f'http://localhost:4040'
            PARAMS = {
                'x': x,
                'y': y,
                'z': z,
                'x1': x1,
                'y1': y1,
                'mx': Mx,
                'my': My,
                'mz': Mz,
                'tgx': TgX,
                'tgy': TgY,
                'tgz': TgZ,
                'ry': R
            }
            res = requests.get(url=URL, params=PARAMS)
            data = res.json()
            return data

        except:
            return {
                'status': False,
                'message': 'Getting personality type failed'
            }

    def calculate(self, x1, y1, z, x2, y2):
        item1 = (x1, y1, z)
        item2 = (x2, y2, z)

        cursor = self.mydb.cursor()

        query = "INSERT INTO testdb.fuzzy VALUES (null, %s, %s, %s)"
        cursor.execute(query, item1)
        cursor.execute(query, item2)

        cursor.execute("SELECT * FROM testdb.fuzzy;")
        data = cursor.fetchall()
        self.mydb.commit()

        Mx = 0
        My = 0
        Mz = 0
        x_data = list()
        y_data = list()
        z_data = list()

        for item in data:
            Mx += item[1]
            My += item[2]
            Mz += item[3]

            st = "X={}, Y={}, Z={}".format(item[1], item[2], item[3])
            self.listbox.insert(tk.END, st)

            x_data.append(item[1])
            y_data.append(item[2])
            z_data.append(item[3])

        count = len(data)

        Mx = round(Mx / count)
        My = round(My / count)
        Mz = round(Mz / count)

        sigmaX = numpy.std(x_data)
        sigmaY = numpy.std(y_data)
        sigmaZ = numpy.std(z_data)

        TgX = 1 / sigmaX
        TgY = 1 / sigmaY
        TgZ = 1 / sigmaZ
        R = sigmaY / 2
        print(item1[0], item1[1], item1[2], item2[0], item2[1])

        data = self.solution(item1[0], Mx, TgX, item1[1], My, TgY, R, item1[2],
                             Mz, TgZ, item2[0], item2[1])
        if (data['type'] == 0):
            value = "Результат: победа первой команды"
        elif (data['type'] == 1):
            value = "Результат: ничья"
        else:
            value = "Результат: победа второй команды"
        self.text.set(value)
Exemplo n.º 20
0
 def cargarConocimientos(self):
     
     self.prolog = None                                              #Se elimina la base de conocimientos anterior
     self.prolog = Prolog()                                          #Se abre nuevamente prolog
     self.prolog.consult(self.direccion)                             #Se carga el código con la dirección obtenida anteriormente
Exemplo n.º 21
0
def main():

    # Initialize the prolog code
	prolog = Prolog()

	#Read "mekid.pl" file as a Prolog Source File 
	prolog.consult("3.kid_prolog.pl")

	#Initialise variables used
	activity = 'eat_noodles'		#Activity that child did
	frontWord = ''					#Word to place at the start of next sentence to denote feelings
	startLoop = True				#Loop Variable
	firstQuestion = True			#Variable to denote initial question asked
	kidReply = True					#Whether kid has done activity or not
	relatedQnReply = True			#Whether kid liked the activity or not
	positiveCounter = 0				#Counter for positive replies
	negativeCounter = 0				#Counter for negative replies

	# Main Program Loop
	while startLoop:
		
		#Ask first question 
		if firstQuestion:
			askFirst()
			kidReply = ask(activity, frontWord)
			firstQuestion = False	
		
		#Ask subsequent questions for activity 
		else:
			#If child has positive reply, ask with positive front word
			if relatedQnReply:
				kidReply = ask(activity, frontWord)
			#If chid has negative reply, ask with negative front word
			else:
				kidReply = ask(activity, frontWord)

		#Kid has done activity asked; Ask related question next
		if kidReply:
			relatedQnList = list(prolog.query('getRelatedQuestion({}, Y)'.format(activity)))#Query prolog
			relatedQn = random.choice(relatedQnList)['Y']									#Choose random related question to ask
			relatedQnReply = askRelatedQn(relatedQn)										#Ask related question

			#If kid likes activity
			if relatedQnReply:
				prolog.assertz('kidLike({})'.format(activity))								#Assert fact
				positiveWordList = list(prolog.query('getPositiveFront(positive,X)')) 		#Query prolog
				positiveFrontWord = random.choice(positiveWordList)['X']					#Choose random front word
				frontWord = positiveFrontWord
				relatedQnReply = True 
				positiveCounter = positiveCounter +1 										#Increment positive counter
			
			#If kid does not like activity
			else:
				prolog.assertz('kidDidntLike({})'.format(activity))							#Assert fact
				negativeWordList = list(prolog.query('getNegativeFront(negative,X)'))		#Query prolog
				negativeFrontWord = random.choice(negativeWordList)['X']					#Choose random front word
				frontWord = negativeFrontWord
				relatedQnReply = False
				negativeCounter = negativeCounter +1										#Increment negative counter

		#Kid has not done activity 
		else:
			neutralWordList = list(prolog.query('getNeutralFront(neutral,X)'))				#Query prolog
			neutralFrontWord = random.choice(neutralWordList)['X']							#Choose random front word
			frontWord = neutralFrontWord
			relatedQnReply = False
        
		#Assert fact
		prolog.assertz('kidAsked({})'.format(activity))

		#Query prolog for list of activities to ask next
		toAskList = list(prolog.query('getQuestion(X, {})'.format(activity)))
		listLength = len(toAskList)
		
		#No more activities to ask ie. all activities asked
		if listLength == 0:
			if(positiveCounter > negativeCounter):											#Child had positive day
				title = "Conclusion - Positive Day"
				image = "positive_day.png"
				msg = 'Good job sweetheart! Glad that you had an awesome day in school!'
				choices = ["OK"]
				easygui.buttonbox(msg, title=title, image=image, choices=choices)
			elif(negativeCounter > positiveCounter):										#Child has negative day
				title = "Conclusion - Negative Day"
				image = "negative_day.png"
				msg = 'Its alright sweetheart! I am sure you will have more fun tomorrow!'
				choices = ["OK"]
				easygui.buttonbox(msg, title=title, image=image, choices=choices)
			else:																			#Child had neutral day
				title = "Conclusion - Neutral Day"
				image = "neutral_day.png"
				msg = 'Seems like your day is fine!'
				choices = ["OK"]
				easygui.buttonbox(msg, title= title, image=image, choices=choices)																		
			
			startLoop = False 		#Stop main loop
			break

		#Take first element from the list as activity to be asked
		activity = toAskList[0]['X']
Exemplo n.º 22
0
	def __init__(self, tilemap, tilemap_obs, prolog_facts):

		self.prolog = Prolog()
		self.prolog.consult(tilemap)
		self.prolog.consult(prolog_facts)
		self.prolog.consult(tilemap_obs)
Exemplo n.º 23
0
class RobotBrain(object):
    '''
    The main intelligent controller of the simulated robot
    '''
    __prologEngine = Prolog()  # The engine given by Pyswip SWI Prolog library
    __stateN = None  # Sate obtained by observing data received by North sensors,
    __stateS = None  # State obtained by observing data received by South sensors
    # Example: [['Pioneer_p3dx_ultrasonicSensor1', 'False'], ['Pioneer_p3dx_ultrasonicSensor2', 'True'],
    # ['Pioneer_p3dx_ultrasonicSensor3', 'True'], ['Pioneer_p3dx_ultrasonicSensor4', 'True'],
    # ['Pioneer_p3dx_ultrasonicSensor5', 'True'], ['Pioneer_p3dx_ultrasonicSensor6', 'True'],
    # ['Pioneer_p3dx_ultrasonicSensor7', 'True'], ['Pioneer_p3dx_ultrasonicSensor8', 'False']]
    # List of default North sensors
    __proximitySensorsN = [
        'Pioneer_p3dx_ultrasonicSensor1', 'Pioneer_p3dx_ultrasonicSensor2',
        'Pioneer_p3dx_ultrasonicSensor3', 'Pioneer_p3dx_ultrasonicSensor4',
        'Pioneer_p3dx_ultrasonicSensor5', 'Pioneer_p3dx_ultrasonicSensor6',
        'Pioneer_p3dx_ultrasonicSensor7', 'Pioneer_p3dx_ultrasonicSensor8'
    ]
    # List of default South sensors
    __proximitySensorsS = [
        'Pioneer_p3dx_ultrasonicSensor9', 'Pioneer_p3dx_ultrasonicSensor10',
        'Pioneer_p3dx_ultrasonicSensor11', 'Pioneer_p3dx_ultrasonicSensor12',
        'Pioneer_p3dx_ultrasonicSensor13', 'Pioneer_p3dx_ultrasonicSensor14',
        'Pioneer_p3dx_ultrasonicSensor15', 'Pioneer_p3dx_ultrasonicSensor16'
    ]
    __velocityList = [5, 10, 15, 20,
                      25]  # List of velocities from the lowest to the higher
    __decision = None  # The next action to perform

    def __init__(self, proximitySensorsN=[], proximitySensorsS=[]):
        if len(proximitySensorsN) > 0:
            self.setProxinitySensorsN(proximitySensorsN)
        if len(proximitySensorsS) > 0:
            self.setProxinitySensorsS(proximitySensorsS)

    def setStateN(self, newStateN):
        assert isinstance(newStateN, list)
        assert len(newStateN) == len(self.getProximitySensorsN())
        for elem in newStateN:
            assert isinstance(elem, list)
            assert len(elem) == 2
        self.__stateN = newStateN

    def setStateS(self, newStateS):
        assert isinstance(newStateS, list)
        assert len(newStateS) == len(self.getProximitySensorsS())
        for elem in newStateS:
            assert isinstance(elem, list)
            assert len(elem) == 2
        self.__stateS = newStateS

    def getStateN(self):
        return self.__stateN

    def getStateS(self):
        return self.__stateS

    def getProximitySensorsN(self):
        return self.__proximitySensorsN

    def getProximitySensorsS(self):
        return self.__proximitySensorsS

    def setProxinitySensorsN(self, newProximitySensorsN):
        assert isinstance(newProximitySensorsN, list)
        for elem in newProximitySensorsN:
            assert isinstance(elem, str)
        self.__proximitySensorsN = newProximitySensorsN

    def setProxinitySensorsS(self, newProximitySensorsS):
        assert isinstance(newProximitySensorsS, list)
        for elem in newProximitySensorsS:
            assert isinstance(elem, str)
        self.__proximitySensorsS = newProximitySensorsS

    def getDecision(self):
        return self.__decision

    def setDecision(self, newDecision):
        assert isinstance(newDecision, str)
        assert newDecision in ['North', 'South', 'East', 'West', 'Stay']
        self.__decision = newDecision

    def learn(self, prologFilePath):
        '''
        Learns from a SWI Prolog file.
        :param prologFilePath: The path of the Prolog (.pl or .txt) file we need to use.
        :return:
        '''
        assert isinstance(prologFilePath, str)
        self.__prologEngine.consult(prologFilePath)

    def singlePerception(self, externalInput):
        '''
        Read state and build a part of world representation (given only one sensor).
        :param externalInput : what is at the sensor layer:
            [sensorID, [sensorReading]], where:
                sensorID is a string.
                [sensorReading] is a tuple of 5 elements:
                    The 1st element is the state of the reading on the sensor (0 os ok).
                    The 2nd element is a Boolean that says if the sensor is detecting something in front of it.
                    The 3rd element is the point of the detected object.
                    The 4th element is the handle of the detected object.
                    The 5th element is the normal vector of the detected surface.
        :return: what does the robot percept as happened:
            ['<sensorID>', '<sensorReading_second_element>'] if we have a perception from sensor works,
            ['<sensorID>', 'None'] otherwise.
        '''
        # print(externalInput)  # Test
        assert isinstance(externalInput, list)
        assert isinstance(externalInput[0], str)
        assert isinstance(externalInput[1], tuple)
        assert len(externalInput[1]) == 5
        if externalInput[1][0] == 0:  # If sensor returns state_ok
            out = [
                externalInput[0],
                str(externalInput[1][1]).replace('"', "'")
            ]
            # The escape is very important for Prolog
        else:
            out = [externalInput[0], 'None']
        return out

    def globalPerception(self, externalInputsList):
        '''
        Read state and build a world representation
        :param A list of externalInputs. An externalInput is what is at the sensor layer:
            [sensorID, [sensorReading]], where:
                sensorID is a string.
                [sensorReading] is a list of 5 elements:
                    The 1st element is the state of the reading on the sensor (0 os ok).
                    The 2nd element is a Boolean that says if the sensor is detecting something in front of it.
                    The 3rd element is the point of the detected object.
                    The 4th element is the handle of the detected object.
                    The 5th element is the normal vector of the detected surface.
        :return: what does the robot percept as happened: [sensorID, sensorReading_second_element] the perception
            from sensor works, None otherwise.
        '''
        assert isinstance(externalInputsList, list)
        out = []
        for input in externalInputsList:
            out.append(self.singlePerception(input))
        return out

    def decision(self):
        '''
        The state contains the worlds representation
        :return: action
        '''
        self.__prologEngine.retractall('perceptionNorth(_)')
        self.__prologEngine.assertz('perceptionNorth(' +
                                    str(self.getStateN()) + ')')
        try:
            out = list(self.__prologEngine.query('takeDecision(D)'))
        except:  # Il Prolog doesn't work (maybe because it can't receive data from sensors) the robot has to stay
            out = []
        # print(out)  # test
        if len(
                out
        ) > 0:  # If we can take more than one decision, we take the 1st one
            # print(out[0]['D'])  # Test
            toDo = out[0]['D']
        else:
            toDo = 'Stay'
        self.setDecision(toDo)
        return toDo

    def thinkN(self, sensorReadings):
        '''
        It decides with action to take given North sensor readings
        :param sensorReadings: list of sensor values, that is a list of externalInputs.
            An externalInput is what is at the sensor layer:
            [sensorID, [sensorReading]], where:
                sensorID is a string.
                [sensorReading] is a list of 5 elements:
                    The 1st element is the state of the reading on the sensor (0 os ok).
                    The 2nd element is a Boolean that says if the sensor is detecting something in front of it.
                    The 3rd element is the point of the detected object.
                    The 4th element is the handle of the detected object.
                    The 5th element is the normal vector of the detected surface.
        :return: action
        '''
        assert isinstance(sensorReadings, list)
        self.setStateN(self.globalPerception(sensorReadings))
        action = self.decision()
        return action
Exemplo n.º 24
0
    def buscardatos(self):
        paciente = ""
        inicio = "Y"

        #inicio el ciclo solicitando campo "NOMBRE" y verificando que el campo
        while paciente == "":
            paciente = input("Inserte un nombre y apellido: ")
            print()
            print("\t*****************************************")
            # se eliminan espacios entre el nombre y apellidos
        query = paciente.replace(" ", "")
        #se crea una instancia del metodo prolog
        prolog = Prolog()

        #se crea variable para controlar el bucle, en caso de que el usuario introduzca un campo vacio
        paciente = ""
        inicio = "Y"

        while inicio == "Y":

            #se cargan los documentos prolog para las consultas
            prolog.consult("paciente.pl")
            #se realiza una consulta para verificar que el nombre introducido exista entre la lista de pacientes
            result = bool(list(prolog.query("paciente(" + query + ")")))
            # si existe se realizan las busquedas adicionales
            if result == True:
                #se emite un mensaje que el paciente esta registrado
                print("\tEl paciente " + paciente + " esta registrado")
                #se carga el archivo edades.pl para ser analizado
                prolog.consult("edades.pl")
                #se construye la consulta
                for valor in prolog.query("edad(" + query + ",Y)"):
                    #se imprime la edad del paciente
                    print("\tEdad: ", valor["Y"])
                #se carga el archivo status.pl para ser analizado y conocer el estado del paciente
                prolog.consult("status.pl")
                # se crea y carga la consulta
                for valor in prolog.query("status(" + query + ",Y)"):
                    # se emite el resultado y se almacena en la variable n
                    print("\tStatus: ", valor["Y"])
                    n = valor["Y"]
                    #se carga el archivo hospital.pl para ser analizado
                prolog.consult("hospital.pl")
                #se crea la consulta para conocer en que hospital se encuentra el paciente
                for valor in prolog.query("hospital(" + query + ",Y)"):
                    #se almacena el hospital para luego conocer el estado en el que se encuentra el hospital
                    hospital = valor["Y"]
                    #se imprime el nombre del hospital
                    print("\tHospital: ", valor["Y"])
                    #se genera el query para conocer la entidad federativa del hospital
                for valor in prolog.query("estado(" + hospital + ",Y)"):
                    # se emite la entidad federativa
                    print("\tEstado: ", valor["Y"])
                    #se almacena la entidad
                    estado = valor["Y"]
                    # se crea la consulta para saber en que ciudad se encuentra el hospital
                for valor in prolog.query("ciudad(" + estado + ",Y)"):
                    # se emite la ciudad en donde se encuentra el hospital
                    print("\tCiudad: ", valor["Y"])
                    # se analiza el estado del ṕaciente para estimar una fecha de alta
                    if (n == 'recuperado'):
                        alta = date.today()
                        print("\tFecha de Alta: ", alta)
                    else:
                        #en caso de contrario se le notifica al usuario
                        print("\tFecha de Alta: No establecida")
            # si no se encuentra el paciente se emite el mensaje
            else:
                print("El paciente " + paciente + " No ha sido registrado")
            print("\t****************************************")
            print()
            inicio = input("¿Desea continuar? y/n: ")
            if (inicio != "y"):
                print("Sistema Finalizado")
            else:
                covid.buscardatos()
Exemplo n.º 25
0
def get_expert_rule():
    Rice = 'Rice'
    # Rice = str(request.json[u'riceName'])
    # if Rice == '' :
    #     Rice = 'Rice'
    RiceType = str(request.json[u'riceType'])
    if RiceType == '':
        RiceType = 'RiceType'
    SubDis = str(request.json[u'subDis'])
    if SubDis == '':
        SubDis = 'SubDis'
    Disrict = str(request.json[u'district'])
    if Disrict == '':
        Disrict = 'Disrict'
    Province = str(request.json[u'province'])
    if Province == '':
        Province = 'Province'
    Price = str(request.json[u'price'])
    if Price == '':
        Price = 'Price'
    SellPlace = str(request.json[u'sellPlace'])
    if SellPlace == '':
        SellPlace = 'SellPlace'
    Humidity = str(request.json[u'humidity'])
    if Humidity == '':
        Humidity = 'Humidity'
    Season = str(request.json[u'season'])
    if Season == '':
        Season = 'Season'
    PhotoPeriod = str(request.json[u'photoPeriod'])
    if PhotoPeriod == '':
        PhotoPeriod = 'PhotoPeriod'

    Thrips = 'Thrips'
    Mealybug = 'Mealybug'
    BrownPlantHopper = 'BrownPlantHopper'
    WhiteBackedPlantHopper = 'WhiteBackedPlantHopper'
    ZigzagLeafHopper = 'ZigzagLeafHopper'
    GreenRiceLeafHopper = 'GreenRiceLeafHopper'
    RiceHispa = 'RiceHispa'
    StemBorer = 'StemBorer'
    CutWorm = 'CutWorm'
    RiceEarCuttingCaterpilla = 'RiceEarCuttingCaterpilla'
    RiceLeafFolder = 'RiceLeafFolder'
    RiceCaseWorm = 'RiceCaseWorm'
    RiceWhorlMaggot = 'RiceWhorlMaggot'
    RiceBlackBug = 'RiceBlackBug'
    RiceGallMidge = 'RiceGallMidge'
    RiceBug = 'RiceBug'
    pestGroup = request.json[u'pestGroup']
    for i in pestGroup:
        if i == 'thrips':
            Thrips = '"true"'
        elif i == 'mealybug':
            Mealybug = '"true"'
        elif i == 'brownPlantHopper':
            BrownPlantHopper = '"true"'
        elif i == 'whiteBackedPlantHopper':
            WhiteBackedPlantHopper = '"true"'
        elif i == 'greenRiceLeafHopper':
            GreenRiceLeafHopper = '"true"'
        elif i == 'riceHispa':
            RiceHispa = '"true"'
        elif i == 'stemBorer':
            StemBorer = '"true"'
        elif i == 'cutWorm':
            CutWorm = '"true"'
        elif i == 'riceEarCuttingCaterpilla':
            RiceEarCuttingCaterpilla = '"true"'
        elif i == 'riceLeafFolder':
            RiceLeafFolder = '"true"'
        elif i == 'riceCaseWorm':
            RiceCaseWorm = '"true"'
        elif i == 'riceWhorlMaggot':
            RiceWhorlMaggot = '"true"'
        elif i == 'riceBlackBug':
            RiceBlackBug = '"true"'
        elif i == 'riceGallMidge':
            RiceGallMidge = '"true"'
        elif i == 'riceBug':
            RiceBug = '"true"'

    SeedlingRotInNurseyBox = 'SeedlingRotInNurseyBox'
    SheathRot = 'SheathRot'
    SheathBlight = 'SheathBlight'
    BacterialLeafBlight = 'BacterialLeafBlight'
    GrassyStunt = 'GrassyStunt'
    FalseSmut = 'FalseSmut'
    Bakanae = 'Bakanae'
    BacterialLeafStreak = 'BacterialLeafStreak'
    NarrowBrownSpot = 'NarrowBrownSpot'
    BrownSpot = 'BrownSpot'
    RedStripe = 'RedStripe'
    LeafScald = 'LeafScald'
    RiceTungro = 'RiceTungro'
    OrangeLeaf = 'OrangeLeaf'
    RiceRaggedStunt = 'RiceRaggedStunt'
    DirtyPanicle = 'DirtyPanicle'
    Akiochi = 'Akiochi'
    RootKnot = 'RootKnot'
    StemRot = 'StemRot'
    GallDwarf = 'GallDwarf'
    YellowDwarf = 'YellowDwarf'
    RiceBlast = 'RiceBlast'

    disceaseGroup = request.json[u'diseaseGroup']
    for i in pestGroup:
        if i == 'seedlingRotInNurseyBox':
            SeedlingRotInNurseyBox = '"true"'
        elif i == 'sheathRot':
            SheathRot = '"true"'
        elif i == 'sheathBlight':
            SheathBlight = '"true"'
        elif i == 'bacterialLeafBlight':
            BacterialLeafBlight = '"true"'
        elif i == 'grassyStunt':
            GrassyStunt = '"true"'
        elif i == 'falseSmut':
            FalseSmut = '"true"'
        elif i == 'bakanae':
            Bakanae = '"true"'
        elif i == 'bacterialLeafStreak':
            BacterialLeafStreak = '"true"'
        elif i == 'narrowBrownSpot':
            NarrowBrownSpot = '"true"'
        elif i == 'brownSpot':
            BrownSpot = '"true"'
        elif i == 'redStripe':
            RedStripe = '"true"'
        elif i == 'leafScald':
            LeafScald = '"true"'
        elif i == 'riceTungro':
            RiceTungro = '"true"'
        elif i == 'orangeLeaf':
            OrangeLeaf = '"true"'
        elif i == 'riceRaggedStunt':
            RiceRaggedStunt = '"true"'
        elif i == 'dirtyPanicle':
            DirtyPanicle = '"true"'
        elif i == 'akiochi':
            Akiochi = '"true"'
        elif i == 'rootKnot':
            RootKnot = '"true"'
        elif i == 'stemRot':
            StemRot = '"true"'
        elif i == 'gallDwarf':
            GallDwarf = '"true"'
        elif i == 'yellowDwarf':
            YellowDwarf = '"true"'
        elif i == 'riceBlast':
            RiceBlast = '"true"'
    prolog = Prolog()
    prolog.consult('src/engine.pl')
    rule = 'expertRule(' + Rice + ',' + RiceType + ',' + SubDis + ',' + Disrict + ',' + Province + ',' + Price + ',' + SellPlace + ',' + Humidity
    rule = rule + ',' + Season + ',' + PhotoPeriod + ',' + Thrips + ',' + Mealybug + ',' + BrownPlantHopper + ',' + WhiteBackedPlantHopper
    rule = rule + ',' + ZigzagLeafHopper + ',' + GreenRiceLeafHopper + ',' + RiceHispa + ',' + StemBorer + ',' + CutWorm + ','
    rule = rule + RiceEarCuttingCaterpilla + ',' + RiceLeafFolder + ',' + RiceCaseWorm + ',' + RiceWhorlMaggot + ','
    rule = rule + RiceBlackBug + ',' + RiceGallMidge + ',' + RiceBug + ',' + SeedlingRotInNurseyBox + ',' + SheathRot + ',' + SheathBlight
    rule = rule + ',' + BacterialLeafBlight + ',' + GrassyStunt + ',' + FalseSmut + ',' + Bakanae + ',' + BacterialLeafStreak + ','
    rule = rule + NarrowBrownSpot + ',' + BrownSpot + ',' + RedStripe + ',' + LeafScald + ',' + RiceTungro + ',' + OrangeLeaf + ','
    rule = rule + RiceRaggedStunt + ',' + DirtyPanicle + ',' + Akiochi + ',' + RootKnot + ',' + StemRot + ',' + GallDwarf + ','
    rule = rule + YellowDwarf + ',' + RiceBlast + ')'
    re_list = list(prolog.query(rule))
    return jsonify(re_list)
Exemplo n.º 26
0
from pyswip import Prolog

interprete = Prolog()

interprete.consult("hanoi.pl")
solucion = interprete.query("mover_disco(3,1,3,2)")

for paso in solucion:
    print(paso)
Exemplo n.º 27
0
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

from pyswip import Prolog, registerForeign, Atom


def atom_checksum(*a):
    if isinstance(a[0], Atom):
        r = sum(ord(c) & 0xFF for c in str(a[0]))
        a[1].value = r & 0xFF
        return True
    else:
        return False


p = Prolog()
registerForeign(atom_checksum, arity=2)
print(list(p.query("X='Python', atom_checksum(X, Y)", catcherrors=False)))
Exemplo n.º 28
0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on 
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
See the License for the specific language governing permissions and limitations under the License
'''

import os
import time
from pyswip import Prolog
import logging
import ast

behaviourFilePath = 'behaviour.pl'

logging.basicConfig(level=logging.INFO)
prologEngine = Prolog()  # The engine given by Pyswip SWI Prolog library

print("Learning started...")
prologEngine.consult(behaviourFilePath)
print("Learning finished")


def eternity():
    print('Loop started')

    while (True):
        patience = True
        while (patience):
            try:
                inFile = open('query.txt')
                patience = False
Exemplo n.º 29
0
    def solve(self):
        p = Prolog()
        if (self.count % 3 == 1):
            p = Prolog()
            p.consult('func.pl')

            #X = (list(p.query('sudoku(Solution,[[_,_,_,_,3,8,_,_,_],[_,8,_,9,_,_,2,7,_],[3,_,4,_,_,_,_,_,1],[9,4,_,1,7,_,_,_,5],[_,_,7,_,6,_,_,_,_],[_,5,_,_,_,_,_,2,6],[_,9,_,_,_,_,_,5,_],[_,_,_,6,8,_,_,4,_],[_,6,_,_,1,_,9,_,7]])')))

            X = ((p.query(
                'sudoku(Solution,[[_,_,_,_,_,_,_,3,1],[_,1,_,_,6,2,4,_,_],[5,_,3,7,_,_,_,_,_],[_,9,_,8,2,_,_,_,_],[6,_,_,_,_,_,_,8,_],[_,5,4,9,_,_,7,6,_],[_,_,_,_,5,_,8,1,_],[_,8,_,6,_,4,_,7,_],[_,4,_,_,9,_,_,_,_]])'
            )))

            #X = (list(p.query('sudoku(Solution,[_,_,_,_,_,_,_,3,1,_,1,_,_,6,2,4,_,_,5,_,3,7,_,_,_,_,_,_,9,_,8,2,_,_,_,_,6,_,_,_,_,_,_,8,_,_,5,4,9,_,_,7,6,_,_,_,_,_,5,_,8,1,_,_,8,_,6,_,4,_,7,_,_,4,_,_,9,_,_,_,_])')))
            A = X.next()
            Z = list(A['Solution'])

            print(Z)

            self.a1.setText(str(Z[0]))
            self.a2.setText(str(Z[1]))
            self.a3.setText(str(Z[2]))
            self.a4.setText(str(Z[3]))
            self.a5.setText(str(Z[4]))
            self.a6.setText(str(Z[5]))
            self.a7.setText(str(Z[6]))
            self.a8.setText(str(Z[7]))
            self.a9.setText(str(Z[8]))

            self.b1.setText(str(Z[9]))
            self.b2.setText(str(Z[10]))
            self.b3.setText(str(Z[11]))
            self.b4.setText(str(Z[12]))
            self.b5.setText(str(Z[13]))
            self.b6.setText(str(Z[14]))
            self.b7.setText(str(Z[15]))
            self.b8.setText(str(Z[16]))
            self.b9.setText(str(Z[17]))

            self.c1.setText(str(Z[18]))
            self.c2.setText(str(Z[19]))
            self.c3.setText(str(Z[20]))
            self.c4.setText(str(Z[21]))
            self.c5.setText(str(Z[22]))
            self.c6.setText(str(Z[23]))
            self.c7.setText(str(Z[24]))
            self.c8.setText(str(Z[25]))
            self.c9.setText(str(Z[26]))

            self.d1.setText(str(Z[27]))
            self.d2.setText(str(Z[28]))
            self.d3.setText(str(Z[29]))
            self.d4.setText(str(Z[30]))
            self.d5.setText(str(Z[31]))
            self.d6.setText(str(Z[32]))
            self.d7.setText(str(Z[33]))
            self.d8.setText(str(Z[34]))
            self.d9.setText(str(Z[35]))

            self.e1.setText(str(Z[36]))
            self.e2.setText(str(Z[37]))
            self.e3.setText(str(Z[38]))
            self.e4.setText(str(Z[39]))
            self.e5.setText(str(Z[40]))
            self.e6.setText(str(Z[41]))
            self.e7.setText(str(Z[42]))
            self.e8.setText(str(Z[43]))
            self.e9.setText(str(Z[44]))

            self.f1.setText(str(Z[45]))
            self.f2.setText(str(Z[46]))
            self.f3.setText(str(Z[47]))
            self.f4.setText(str(Z[48]))
            self.f5.setText(str(Z[49]))
            self.f6.setText(str(Z[50]))
            self.f7.setText(str(Z[51]))
            self.f8.setText(str(Z[52]))
            self.f9.setText(str(Z[53]))

            self.g1.setText(str(Z[54]))
            self.g2.setText(str(Z[55]))
            self.g3.setText(str(Z[56]))
            self.g4.setText(str(Z[57]))
            self.g5.setText(str(Z[58]))
            self.g6.setText(str(Z[59]))
            self.g7.setText(str(Z[60]))
            self.g8.setText(str(Z[61]))
            self.g9.setText(str(Z[62]))

            self.h1.setText(str(Z[63]))
            self.h2.setText(str(Z[64]))
            self.h3.setText(str(Z[65]))
            self.h4.setText(str(Z[66]))
            self.h5.setText(str(Z[67]))
            self.h6.setText(str(Z[68]))
            self.h7.setText(str(Z[69]))
            self.h8.setText(str(Z[70]))
            self.h9.setText(str(Z[71]))

            self.i1.setText(str(Z[72]))
            self.i2.setText(str(Z[73]))
            self.i3.setText(str(Z[74]))
            self.i4.setText(str(Z[75]))
            self.i5.setText(str(Z[76]))
            self.i6.setText(str(Z[77]))
            self.i7.setText(str(Z[78]))
            self.i8.setText(str(Z[79]))
            self.i9.setText(str(Z[80]))

        elif (self.count % 3 == 2):

            X = (list(
                p.query(
                    'sudoku(Solution,[7,_,8,6,_,_,_,_,_,6,_,_,5,_,3,4,1,_,_,_,_,_,1,_,_,7,_,_,_,_,_,_,_,_,9,2,_,8,1,2,_,_,3,_,_,4,_,_,_,5,9,_,_,_,_,_,5,_,_,_,7,2,_,1,3,_,7,_,_,_,4,_,_,_,6,3,_,_,_,_,_])'
                )))
            #Y = dict(X[0])
            #Z = list(Y['Solution'])
            X = ((p.query(
                'sudoku(Solution,[[7,_,8,6,_,_,_,_,_],[6,_,_,5,_,3,4,1,_],[_,_,_,_,1,_,_,7,_],[_,_,_,_,_,_,_,9,2],[_,8,1,2,_,_,3,_,_],[4,_,_,_,5,9,_,_,_],[_,_,5,_,_,_,7,2,_],[1,3,_,7,_,_,_,4,_],[_,_,6,3,_,_,_,_,_]])'
            )))

            A = X.next()
            Z = list(A['Solution'])
            print(Z)

            self.a1.setText(str(Z[0]))
            self.a2.setText(str(Z[1]))
            self.a3.setText(str(Z[2]))
            self.a4.setText(str(Z[3]))
            self.a5.setText(str(Z[4]))
            self.a6.setText(str(Z[5]))
            self.a7.setText(str(Z[6]))
            self.a8.setText(str(Z[7]))
            self.a9.setText(str(Z[8]))

            self.b1.setText(str(Z[9]))
            self.b2.setText(str(Z[10]))
            self.b3.setText(str(Z[11]))
            self.b4.setText(str(Z[12]))
            self.b5.setText(str(Z[13]))
            self.b6.setText(str(Z[14]))
            self.b7.setText(str(Z[15]))
            self.b8.setText(str(Z[16]))
            self.b9.setText(str(Z[17]))

            self.c1.setText(str(Z[18]))
            self.c2.setText(str(Z[19]))
            self.c3.setText(str(Z[20]))
            self.c4.setText(str(Z[21]))
            self.c5.setText(str(Z[22]))
            self.c6.setText(str(Z[23]))
            self.c7.setText(str(Z[24]))
            self.c8.setText(str(Z[25]))
            self.c9.setText(str(Z[26]))

            self.d1.setText(str(Z[27]))
            self.d2.setText(str(Z[28]))
            self.d3.setText(str(Z[29]))
            self.d4.setText(str(Z[30]))
            self.d5.setText(str(Z[31]))
            self.d6.setText(str(Z[32]))
            self.d7.setText(str(Z[33]))
            self.d8.setText(str(Z[34]))
            self.d9.setText(str(Z[35]))

            self.e1.setText(str(Z[36]))
            self.e2.setText(str(Z[37]))
            self.e3.setText(str(Z[38]))
            self.e4.setText(str(Z[39]))
            self.e5.setText(str(Z[40]))
            self.e6.setText(str(Z[41]))
            self.e7.setText(str(Z[42]))
            self.e8.setText(str(Z[43]))
            self.e9.setText(str(Z[44]))

            self.f1.setText(str(Z[45]))
            self.f2.setText(str(Z[46]))
            self.f3.setText(str(Z[47]))
            self.f4.setText(str(Z[48]))
            self.f5.setText(str(Z[49]))
            self.f6.setText(str(Z[50]))
            self.f7.setText(str(Z[51]))
            self.f8.setText(str(Z[52]))
            self.f9.setText(str(Z[53]))

            self.g1.setText(str(Z[54]))
            self.g2.setText(str(Z[55]))
            self.g3.setText(str(Z[56]))
            self.g4.setText(str(Z[57]))
            self.g5.setText(str(Z[58]))
            self.g6.setText(str(Z[59]))
            self.g7.setText(str(Z[60]))
            self.g8.setText(str(Z[61]))
            self.g9.setText(str(Z[62]))

            self.h1.setText(str(Z[63]))
            self.h2.setText(str(Z[64]))
            self.h3.setText(str(Z[65]))
            self.h4.setText(str(Z[66]))
            self.h5.setText(str(Z[67]))
            self.h6.setText(str(Z[68]))
            self.h7.setText(str(Z[69]))
            self.h8.setText(str(Z[70]))
            self.h9.setText(str(Z[71]))

            self.i1.setText(str(Z[72]))
            self.i2.setText(str(Z[73]))
            self.i3.setText(str(Z[74]))
            self.i4.setText(str(Z[75]))
            self.i5.setText(str(Z[76]))
            self.i6.setText(str(Z[77]))
            self.i7.setText(str(Z[78]))
            self.i8.setText(str(Z[79]))
            self.i9.setText(str(Z[80]))

        elif (self.count % 3 == 0):

            X = (list(
                p.query(
                    'sudoku(Solution,[_,_,_,1,2,_,7,4,_,_,_,_,5,7,3,_,_,2,3,_,_,_,_,_,_,_,_,7,1,_,_,_,_,2,_,6,_,5,2,_,_,_,8,9,_,6,_,8,_,_,_,_,7,4,_,_,_,_,_,_,_,_,5,8,_,_,3,4,1,_,_,_,_,6,3,_,5,9,_,_,_])'
                )))
            #Y = dict(X[0])
            #Z = list(Y['Solution'])
            X = ((p.query(
                'sudoku(Solution,[[_,_,_,1,2,_,7,4,_],[_,_,_,5,7,3,_,_,2],[3,_,_,_,_,_,_,_,_],[7,1,_,_,_,_,2,_,6],[_,5,2,_,_,_,8,9,_],[6,_,8,_,_,_,_,7,4],[_,_,_,_,_,_,_,_,5],[8,_,_,3,4,1,_,_,_],[_,6,3,_,5,9,_,_,_]])'
            )))

            A = X.next()
            Z = list(A['Solution'])
            print(Z)

            self.a1.setText(str(Z[0]))
            self.a2.setText(str(Z[1]))
            self.a3.setText(str(Z[2]))
            self.a4.setText(str(Z[3]))
            self.a5.setText(str(Z[4]))
            self.a6.setText(str(Z[5]))
            self.a7.setText(str(Z[6]))
            self.a8.setText(str(Z[7]))
            self.a9.setText(str(Z[8]))

            self.b1.setText(str(Z[9]))
            self.b2.setText(str(Z[10]))
            self.b3.setText(str(Z[11]))
            self.b4.setText(str(Z[12]))
            self.b5.setText(str(Z[13]))
            self.b6.setText(str(Z[14]))
            self.b7.setText(str(Z[15]))
            self.b8.setText(str(Z[16]))
            self.b9.setText(str(Z[17]))

            self.c1.setText(str(Z[18]))
            self.c2.setText(str(Z[19]))
            self.c3.setText(str(Z[20]))
            self.c4.setText(str(Z[21]))
            self.c5.setText(str(Z[22]))
            self.c6.setText(str(Z[23]))
            self.c7.setText(str(Z[24]))
            self.c8.setText(str(Z[25]))
            self.c9.setText(str(Z[26]))

            self.d1.setText(str(Z[27]))
            self.d2.setText(str(Z[28]))
            self.d3.setText(str(Z[29]))
            self.d4.setText(str(Z[30]))
            self.d5.setText(str(Z[31]))
            self.d6.setText(str(Z[32]))
            self.d7.setText(str(Z[33]))
            self.d8.setText(str(Z[34]))
            self.d9.setText(str(Z[35]))

            self.e1.setText(str(Z[36]))
            self.e2.setText(str(Z[37]))
            self.e3.setText(str(Z[38]))
            self.e4.setText(str(Z[39]))
            self.e5.setText(str(Z[40]))
            self.e6.setText(str(Z[41]))
            self.e7.setText(str(Z[42]))
            self.e8.setText(str(Z[43]))
            self.e9.setText(str(Z[44]))

            self.f1.setText(str(Z[45]))
            self.f2.setText(str(Z[46]))
            self.f3.setText(str(Z[47]))
            self.f4.setText(str(Z[48]))
            self.f5.setText(str(Z[49]))
            self.f6.setText(str(Z[50]))
            self.f7.setText(str(Z[51]))
            self.f8.setText(str(Z[52]))
            self.f9.setText(str(Z[53]))

            self.g1.setText(str(Z[54]))
            self.g2.setText(str(Z[55]))
            self.g3.setText(str(Z[56]))
            self.g4.setText(str(Z[57]))
            self.g5.setText(str(Z[58]))
            self.g6.setText(str(Z[59]))
            self.g7.setText(str(Z[60]))
            self.g8.setText(str(Z[61]))
            self.g9.setText(str(Z[62]))

            self.h1.setText(str(Z[63]))
            self.h2.setText(str(Z[64]))
            self.h3.setText(str(Z[65]))
            self.h4.setText(str(Z[66]))
            self.h5.setText(str(Z[67]))
            self.h6.setText(str(Z[68]))
            self.h7.setText(str(Z[69]))
            self.h8.setText(str(Z[70]))
            self.h9.setText(str(Z[71]))

            self.i1.setText(str(Z[72]))
            self.i2.setText(str(Z[73]))
            self.i3.setText(str(Z[74]))
            self.i4.setText(str(Z[75]))
            self.i5.setText(str(Z[76]))
            self.i6.setText(str(Z[77]))
            self.i7.setText(str(Z[78]))
            self.i8.setText(str(Z[79]))
            self.i9.setText(str(Z[80]))
Exemplo n.º 30
0
 def __init__(self, myposition, planedimension):
     self.__prolog = Prolog()
     self.__behaviour = Behaviour.Behaviour(self.__prolog)
     self.__learning = Learning.Learning(self.__prolog)
     self.__memory = Memory.Memory(myposition, planedimension)