def run_test(array_puzzle, logger):
    """
    Runs a test on puzzle and outputs data on outcome to logger.
    """

    # String format to cohere with Prolog
    puzzle = str(array_puzzle.tolist()).replace("'", "")

    logger.print(f"Test {1+logger.log_len:4d} {puzzle}", coerce=True)

    # Run test
    timeStarted = time.time()
    prolog = swi.Prolog()
    try:
        # Access file
        prolog.consult(f"{os.getcwd()}\\proj2.pl".replace("\\", "/"))

        # NOTE: Outcome is of form [] i.e. false, [{}] i.e. true OR [{'A':1,'B':2,etc.}]
        outcome = list(prolog.query(f'puzzle_solution({puzzle})'))
        timeDelta = round(time.time() - timeStarted, TIME_ACCURACY)
    except Exception as e:
        timeDelta = round(time.time() - timeStarted, TIME_ACCURACY)
        logger.outcome(puzzle, timeDelta, "Error")
        logger.print(f"ERROR: {str(e)}")
        return

    if len(outcome):
        # Verify correctness
        if valid_soln(array_puzzle, outcome[0], logger):
            logger.outcome(puzzle, timeDelta, "Correct")
        else:
            logger.outcome(puzzle, timeDelta, "Wrong")
    else:
        # Log unsolvable
        logger.outcome(puzzle, timeDelta, "Null")
def prolo(toInput, dictHold):
    import pyswip
    prolog = pyswip.Prolog()
    prolog.assertz(
        "approve(PNA,TM,AVG,BUD,TIME,HAZ,ENS,ON,CAN,EX) :- constraints(PNA,TM,AVG,BUD,TIME), content(PNA,HAZ,ENS), valid(X,ON,CAN,EX)"
    )
    prolog.assertz(
        "constraints(PNA,TM,AVG,BUD,TIME) :- stAMS(TM, AVG), bgt(BUD, TIME), write('this is Constraints')"
    )
    prolog.assertz("stAMS('n4', 'l75l')")
    prolog.assertz("stAMS('n5', 'l75l')")
    prolog.assertz("stAMS('n2', 'u75u')")
    prolog.assertz("stAMS('n3', 'u75u')")
    prolog.assertz("bgt('l250l', 'mo1')")
    prolog.assertz("bgt('l250l', 'mo2')")
    prolog.assertz("bgt('l400l', 'mo0.5')")
    prolog.assertz("bgt('l400l', 'mo1')")
    prolog.assertz("content(PNA,HAZ,ENS) :- safe(HAZ,ENS)")
    #self.prolog.assertz("part(_,_,'u75u')")
    prolog.assertz("safe(no, no)")
    prolog.assertz("safe(fire, engi)")
    prolog.assertz("safe(lab, med)")
    prolog.assertz(
        "valid(PNA,ON,CAN,EX) :- intime(ON,CAN,EX), write('this is valid')")
    prolog.assertz("intime(yes,_,_)")
    prolog.assertz("intime(no,yes,_)")
    prolog.assertz("intime(no,no,a)")
    prolog.assertz("intime(no,no,b)")

    for i in prolog.query(toInput):
        if i['X'] == dictHold['Excuses']:
            return True
    return False
Ejemplo n.º 3
0
def consultaProlog(consulta):
    #Cria objeto Prolog
    p = pyswip.Prolog()

    p.consult("regras.pl")

    #Faz a consulta com o string passado
    resultado = list(p.query(consulta))

    # Cria lista de velocidades das rodas
    velocidades = []


        # Armazena em temp uma lista com os valores do dicionario criado em resultado
    temp = resultado[0]

        # Se houver dados pra retornar
        # Preenche velocidades com os valores da consulta - lembre que Y vem antes de X pelo resultado

    for i in temp.values():
            # Converte o resultado para float pois eh produzido um str
        velocidades.append(float(i))


    return velocidades
Ejemplo n.º 4
0
 def prolog_log(self):
     try:
         prolog = ps.Prolog()
         prolog.consult("./prolog.pl")
         for i in prolog.query("order(X,Y)"):
             print('{}\torder\t{}'.format(i['X'].upper(), i['Y'].upper()))
     except:
         pass
Ejemplo n.º 5
0
    def compile_function(self):
        ## Store the prolog interpreter as self.fvalue

        # This is probably slow, but we write it to a file
        with open('tmp.pl', 'w') as f: ## TODO : replace with tempfile
            print >>f, self.base_facts
            print >>f, str(self), "\n"

        prolog = pyswip.Prolog()
        prolog.consult('tmp.pl')

        return prolog
Ejemplo n.º 6
0
def get_restaurant():
    chosen_cuisines = []
    chosen_cuisines = [
        key for key, ans in zip(cuisine.keys(),
                                [cuisine[key].get() for key in cuisine.keys()])
        if ans
    ]
    chosen_payment = []
    chosen_payment = [
        key for key, ans in zip(payment.keys(),
                                [payment[key].get() for key in payment.keys()])
        if ans
    ]

    prolog = pyswip.Prolog()  # Global handle to interpreter
    prolog.consult("KB.pl")  # open the KB
    pick_restaurant = Functor("pick_restaurant", 1)

    # declaring dynamic procedures to allow multiple executions
    # to allow asserta and retractall as inputs change
    prolog.dynamic('cuisine/1')
    prolog.dynamic('payment/1')
    prolog.dynamic('price/1')
    prolog.dynamic('rating/1')
    prolog.dynamic('distance/1')

    # assert user input (list object) into the respective predicates
    prolog.asserta("cuisine(" + str(chosen_cuisines) + ")")
    prolog.asserta("payment(" + str(chosen_payment) + ")")
    prolog.asserta("price(" + str(price.get()) + ")")
    prolog.asserta("rating(" + str(rating.get()) + ")")
    prolog.asserta("distance(" + str(distance.get()) + ")")

    q = prolog.query('pick_restaurant(X)')
    sols = []  # used to find length of solution
    ans = ''  # placeholder for answers for printing
    for value in list(q):
        if value not in sols:
            # iterate over solutions and remove repetitions
            sols.append(value)

    ans = ', '.join(d['X'] for d in sols)  # convert list of dicts to string

    if not len(sols): ans = "Sorry, couldn't found any restaurant."

    ans_label.config(text="You can get food from: " + ans)

    # retract all assertions after obtaining results
    prolog.retractall("cuisine(" + str(chosen_cuisines) + ")")
    prolog.retractall("payment(" + str(chosen_payment) + ")")
    prolog.retractall("price(" + str(price.get()) + ")")
    prolog.retractall("rating(" + str(rating.get()) + ")")
    prolog.retractall("distance(" + str(distance.get()) + ")")
Ejemplo n.º 7
0
 def get_prolog_data(self):
     data = {}
     try:
         prolog = ps.Prolog()
         prolog.consult("./prolog.pl")
         for i in prolog.query("order(X,Y)"):
             # print(i['X'])
             # print(i['Y'])
             if i['X'] in data:
                 data[i['X']].append(i['Y'])
             else:
                 data[i['X']] = [i['Y']]
         return data
     except:
         pass
Ejemplo n.º 8
0
    def __init__(self):

        self.trace = False

        self.prolog = pyswip.Prolog()

        # load geolog_plugins
        self.plugins = [(geolog_plugins.__path__, "geolog_plugins"),
                        (geolog_core.__path__, "geolog_core")]
        self.classes = set()
        self.load_plugins()
        self.load_prolog_files()

        # setup for xpce
        self.query("[swi('swipl-win.rc')]")

        # set gui tracer
        self.query("guitracer")
Ejemplo n.º 9
0
    def generate_with_pyswip(self, domain_file_path, actions, parameters):
        """ Generate a macro using pyswip.

        This generates a macro by using pyswip to call generate_macro from
        ../generation/macro_generator.pl. Note that this currently does not work
        because of serveral issues in pyswip.

        Args:
            domain_file_path: The path to the domain file to read from.
            actions: The actions that the macro should consist of.
            parameters: The parameter assignment for the macro, e.g. [[1,2],[1]]
        """
        macro_file = tempfile.NamedTemporaryFile()
        prolog = pyswip.Prolog()
        prolog.consult('../generation/macro_generator.pl')
        query_string = 'generate_macro_to_file({}, {}, {}, {})'.format(
            domain_file_path, actions, parameters, macro_file.name)
        prolog_query = prolog.query(query_string)
        query_result = next(prolog_query)
        self.initialized = True
Ejemplo n.º 10
0
    def __init__(self):
        # Это здесь нужно для доступа к переменным, методам
        # и т.д. в файле design.py
        super().__init__()
        self.setupUi(self)  # Это нужно для инициализации нашего дизайна
        #кнопка выхода
        self.exitButton.clicked.connect(self.close)

        # ------------------- врубаем консультанта...
        self.akkinator = pyswip.Prolog()
        self.akkinator.consult('ind_72.pl')
        # -------------------

        # файл с записанными пользователями животными
        self.fileDynamicAnimals =[]
        self.readNewStart()

        # картинка для неизвестных штук
        self.newImagePath = ""


        # кол-во плеев
        self.numberOfPLays = 0

        #ответы
        self.answers = [-1, -1, -1, -1, -1, -1, -1, -1]

        #слушатель, который чекает заполненость чекбоксов
        self.checkBoxes[4].stateChanged.connect(self.checkEnabled)

        #слушатель, для нового животного
        self.nameEdit.textChanged[str].connect(self.checkText)



        self.startButton.clicked.connect(lambda: self.startAkkinator(1, 1))
Ejemplo n.º 11
0
#!/usr/bin/python
# coding: utf-8

import os
import pyswip
import textHandler
import time

### element structure
# element(userName, currentDate, currentTime, topic, description, input)

p = pyswip.Prolog()


def reloadPrologFile():
    # Open files, retract each line and add it subsequently.
    # This loads all lines from 'logic.pl' and ensures that there is no repetition
    with open(textHandler.getPrologFileName()) as prologFile:
        for line in prologFile:
            line = line.rstrip('\n')
            result = list(p.query('retract({line}),fail'.format(line=line)))
            p.assertz(line.rstrip('\n'))


def swapDescription(userName, savedDescription, newDescription, input):
    #swaps on 'logic.pl'
    lineNumber, line = getLineWithInput(input)
    #removes the line
    textHandler.removeLineFromPrologFile(lineNumber)

    #alters the line
Ejemplo n.º 12
0
            print(e)

# make sure training data dir exists
value_train_dir = "{}/stage{}/train_value".format(args.outdir, args.stage)
policy_train_dir = "{}/stage{}/train_policy".format(args.outdir, args.stage)
clause_dir = "{}/stage{}/clauses".format(args.outdir, args.stage)
proof_dir = "{}/stage{}/proofs".format(args.outdir, args.stage)
os.makedirs(value_train_dir, exist_ok=True)
os.makedirs(policy_train_dir, exist_ok=True)
os.makedirs(clause_dir, exist_ok=True)
os.makedirs(proof_dir, exist_ok=True)

if args.modeldir == None:
    args.modeldir = args.outdir

prolog = pyswip.Prolog()
if (args.model_type == "gnn") or ("gnn" in args.output_format):
    from gnn.gnn_util import *

if args.guided > 0:
    if args.model_type == "xgboost":
        value_modelfile = "{}/value_xgb".format(args.modeldir)
        policy_modelfile = "{}/policy_xgb".format(args.modeldir)
        if args.guided == 1:  # using python to access xgboost
            import xgboost as xgb
            value_model = xgb.Booster()
            value_model.load_model(value_modelfile)
            policy_model = xgb.Booster()
            policy_model.load_model(policy_modelfile)
    elif args.model_type == "gnn":
        from gnn.network import Network, NetworkConfig
Ejemplo n.º 13
0
 def __init__(self):
     self.prolog = pyswip.Prolog()
     self.prolog.consult('mushrooms.pl')
Ejemplo n.º 14
0
    with open('prolog.pl', 'a+') as pl:
        # lines = [x.strip() for x in pl.readlines()]
        if str not in lines:
            pl.write('\n'+str)


print('Say \'Hi\'')
b = Bot.Bot('food-en', 'en')

# while True:
#     str = input('>>> ')
#
#
#     res, i = b.say(str)
#     c = b.contexts
#     check_dict(c)
#     print(res)
#     if i == 'By':
#         break
botMess = UI.BotMessaging(b)


try:
    prolog = ps.Prolog()
    prolog.consult("./prolog.pl")
    for i in prolog.query("order(X,Y)"):
        print('{}\torder\t{}'.format(i['X'].upper(), i['Y'].upper()))
except:

    pass