Пример #1
1
class Consultor(object):
    """Clase que implementa el mecanismo de consultas a la base de conocimientos usando Prolog"""

    def __init__(self, consulta):
        self.consultor = Prolog()
        self.consultor.consult(os.path.join(settings.MEDIA_ROOT, 'colombianCrush.pl').replace('\\','/'))
        self.consulta = consulta
        self.resultado = []
    
    def buscarSugerencia(self):
        """Genera la respuesta a la consulta de una sugerencia de movimiento para el jugador"""
        return self._validarConsulta(self.consultor.query("buscarSugerencia(X, " + self.consulta + ")"))
    
    def buscarPosibilidad(self):
        """Genera la respuesta a la consulta de una posibilidad de destruccion de figuras"""
        return self._validarConsulta(self.consultor.query("buscarPosibilidad(X, " + self.consulta + ")"))
    
    def _validarConsulta(self, consulta):
        """Metodo interno que extrae el menor valor obtenido de Prolog al consultar la base de conocimiento"""
        for valor in consulta:
            self.resultado.append(valor["X"])
        if len(self.resultado)>PASIVO:
            return min(self.resultado)
        else:
            return PASIVO
Пример #2
0
class ConnectProlog(ConnectLivestatus):
    """As it is senseless to call Prolog without starting a connection to Nagios/Icinga, this module does it."""
    def __init__(self):
	prolog=None
	ConnectLivestatus.__init__(self)
	self.prolog=Prolog()
	self.prolog.consult('vanyad.pl')
Пример #3
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...")
Пример #4
0
    def test_swipl(self):
        from pyswip import Prolog
        from reloop.languages.rlp.logkb import PrologKB
        prolog = Prolog()

        prolog.consult("../examples/RLP/maxflow_swipl.pl")
        logkb = PrologKB(prolog)
        # BlockGrounding not supported yet
        grounder = RecursiveGrounder(logkb)
        solver = CvxoptSolver()
        model = maxflow_example.maxflow(grounder, solver)
        self.assertEqual(model, 0, "SWI-Prolog Recursive Failed")
Пример #5
0
def index(request):
    if request.method == "GET":
        print "AQUI"
        prolog = Prolog()
        print "AQUI TAMBIEN"
        #prolog.consult("recetas.pl")
        print "AQUI TAMBIEN ES"
        ingredientes = list(prolog.query("ingrediente(X)"))
        #salida = str(ingredientes)
        salida = "Hola"

    return HttpResponse(salida)
Пример #6
0
def query_hyp_in_event_db(hyp, event_db_file):
    prolog = Prolog()
    
    str2num_file = '/home/csunix/visdata/cofriend/sandeep/Dropbox/code/my_code/trunk/python/cofriend/str2num.pl'
    prolog.consult(str2num_file)
    
    print 'Reading event database ...'
    all_prolog_modules  = pickle.load(open(event_db_file))
    (modeh, modeb)      = all_prolog_modules['modes']
    pos_ex              = all_prolog_modules['pos_ex']
    test_pos_ex         = all_prolog_modules['test_pos_ex']
    pos_prolog_modules  = all_prolog_modules['pos']
    neg_prolog_modules  = all_prolog_modules['neg']
    test_prolog_modules = all_prolog_modules['test']        
    
    pos_event_dbs = []
    neg_event_dbs = []
    print 'Asserting pos prolog modules ...'
    for vid in pos_prolog_modules:
        for i in xrange(len(pos_prolog_modules[vid])):
            pos_prolog_module  = pos_prolog_modules[vid][i][0]
            pos_prolog_blanket = pos_prolog_modules[vid][i][1]
            pos_event_dbs.append(pos_prolog_module)
            assert_blanket_to_prolog_str_int(pos_prolog_blanket, prolog, pos_prolog_module)
            
    print 'Asserting neg prolog modules ...'            
    for vid in neg_prolog_modules:
        for i in xrange(len(neg_prolog_modules[vid])):
            neg_prolog_module  = neg_prolog_modules[vid][i][0]
            neg_prolog_blanket = neg_prolog_modules[vid][i][1]
            neg_event_dbs.append(neg_prolog_module)
            assert_blanket_to_prolog_str_int(neg_prolog_blanket, prolog, neg_prolog_module)
                
    print 'num of pos: ' + repr(len(pos_event_dbs))
    print 'num of neg: ' + repr(len(neg_event_dbs))
    print 'Querying in pos prolog modules ...'        
    t0 = time.clock()
    print time.asctime()
    for i in xrange(100000):
        pos_cover = hyp.pyswip_covers(prolog, pos_event_dbs, True, False, neg=0)
    print time.asctime()
    pos_eval_time = (time.clock() - t0)
    
    print 'Querying in neg prolog modules ...'        
    t0 = time.clock()
    print time.asctime()
    for i in xrange(100000):
        neg_cover = hyp.pyswip_covers(prolog, neg_event_dbs, True, False, neg=1)
    print time.asctime()
    neg_eval_time = (time.clock() - t0)
    print pos_eval_time
    print neg_eval_time
Пример #7
0
def index(request, table):

    import MySQLdb as db

    conn = db.connect(host='localhost', user='******', passwd='prologpass', db='prolog_test')
    cursor = conn.cursor()

    cursor.execute('SELECT * FROM `children`')
    result = cursor.fetchall()

    prolog = Prolog()

    for row in result:
        prolog.assertz("father("+ row[1]  +","+ row[2]  +")")


    prolog.consult('family')

    prolog.assertz("father(michael,john)")
    prolog.assertz("father(michael,gina)")
    
    father = list(prolog.query("father(Y, X)"))

    #return HttpResponse(response, mimetype="application/xml")
    t = loader.get_template('index/select.html')
    c = RequestContext(request, {'table': table, 'father': father})


    return HttpResponse(
        t.render(c), 
        mimetype="application/xml"
    )
Пример #8
0
    def test_issue_Unicode_consult(self):
        """
        Unicode support
        """
        from pyswip import Prolog

        Prolog.consult('unicode.pl')
        result = list(Prolog.query('мать(Мать,Ребенок)'))
        k = len(result)
        self.assertEqual(k, 2)
        result = list(Prolog.query('дочь(света,саша)'))
        self.assertEqual(result, [])
        result = list(Prolog.query('дочь(света,аня)'))
        self.assertNotEqual(result, [])
Пример #9
0
    def test_issue_1(self):
        """
        Segmentation fault when assertz-ing

        Notes: This issue manifests only in 64bit stacks (note that a full 64
        bit stack is needed. If running 32 in 64bit, it will not happen.)
        
        http://code.google.com/p/pyswip/issues/detail?id=1
        """

        # The simple code below should be enough to trigger the issue. As with
        # issue 13, if it does not work, it will segfault Python.
        from pyswip import Prolog
        prolog = Prolog()
        prolog.assertz("randomTerm(michael,john)")
Пример #10
0
def query_hyp_in_video_db(hyps, video_db):
    prolog = Prolog()
    
    str2num_file = '/home/csunix/visdata/cofriend/sandeep/Dropbox/code/my_code/trunk/python/cofriend/str2num.pl'
    prolog.consult(str2num_file)
    
    print 'Asserting the database ...'
    assert_blanket_to_prolog_str_int(video_db, prolog, 'vid_db')
    result = {}        
    for event in hyps:
        result[event] = []
        print 'Querying in the video for event: ' + event
        for hyp in hyps[event]:
            pos_cover = hyp.pyswip_covers(prolog, [('vid_db',video_db)], True, False, neg=0)
            result[event].append(pos_cover)
    return result
Пример #11
0
class GamePL(object):
    def __init__(self):
        self.prolog = Prolog()
        self.prolog.consult("pl/GameDatabase.pl")
        self.prolog.consult("pl/GameLogic.pl")

    def nuevoJugador(self, name):
        None

    def actualizaPuntuacion(self, jugador, puntos):
        None

    def borrarMemoria(self):
        None

    def getPuntuacion(self, jugador):
        None

    def getCategorias(self):
        return self.prolog.query("categoria(Categoria, Descripcion)")

    def getPreguntas(self):
        return self.prolog.query("pregunta(Numero, Pregunta, Categoria, Puntos)")

    def getRespuestas(self):
        return self.prolog.query("respuesta(Numero, Respuesta)")
Пример #12
0
def main():
    prolog = Prolog()
    prolog.consult("coins.pl")
    count = int(input("How many coins (default: 100)? ") or 100)
    total = int(input("What should be the total (default: 500)? ") or 500)
    coins = Functor("coins", 3)
    S = Variable()
    q = Query(coins(S, count, total))
    i = 0
    while q.nextSolution():
        ## [1,5,10,50,100]
        s = zip(S.value, [1, 5, 10, 50, 100])
        print(i, end=" ")
        for c, v in s:
            print("%dx%d" % (c,v), end=" ")
        print()
        i += 1
    q.closeQuery()
def solveSudoku(sudokuString):
	print "in solve"
	answerString = ""
	prolog = Prolog()
	prolog.consult('sudokusolver.pl')
	queryString = "Puzzle = [" + sudokuString + "],  Puzzle = [A,B,C,D,E,F,G,H,I],  sudoku([A,B,C,D,E,F,G,H,I]).  "
	#queryString = queryS
	res =  list(prolog.query(queryString, maxresult=1))	
	print res
	if not res:
		#results is empty
		return "Invalid Sudoku"
	else:	
		final = []
		cols = ["A","B","C","D","E","F","G","H","I"]
		for col in cols:
			final.append(" ".join(map( str,res[0][col])))
			
		return "<br>".join(final)
Пример #14
0
def main():

    mod = sys.argv[1]
    what = sys.argv[2]
    who = sys.argv[3]
    find = False

    prolog = Prolog()
    prolog.consult(mod)

    for soln in prolog.query("%s(X,%s)" % (what, who)):
        if what == 'pere' :
            print soln["X"], "est le %s de %s" % (what, who)
        else :
            print soln["X"], "est la %s de %s" % (what, who)
        find = True

    if not find:
        print "Je suis désolé, je ne dispose pas des informations requise pour vous répondre. Souhaitez-vous que jeffectue une recherche sur Internet"
    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)
Пример #16
0
def index():
    bs = BaseHandler()
    dt = None
    sol2 = None
    error = None
    form = HelpForm()
    if form.validate_on_submit():
        bsg = bs.big_suggest(str(form.quiz.data))
        sol2 = bs.find_elements(bsg)
    try:
        from pyswip import Prolog
        prolog = Prolog()
        prolog.consult("kb.txt")
#        prolog.assertz("father(michael,gina)")
#        prolog.assertz("father(michael,john)")
        dt = list(prolog.query("elements(X)"))
#        sol2 = list(prolog.query("battery(hot,X)"))
    except Exception,e:
        error = e
        traceback.print_exc()
Пример #17
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--rules", dest="rule_path", default=None)
    parser.add_argument("--db-source", dest="db_path", default="postgresql://dgarant@localhost:5432/movielens")

    args = parser.parse_args()

    if args.rule_path:
        with open(args.rule_path, 'r') as rule_handle:
            rules = [r.strip() for r in rule_handle.readlines()]
    else:
        rules = build_schema_rules(args.db_path)
    rules.extend(register_qeds())

    prolog = Prolog()
    for rule in rules:
        print(rule)
        prolog.assertz(rule)

    report_on_qeds(prolog, "movie_gross")
Пример #18
0
	def __init__(self):
		if self.band:
			self.prolog = Prolog()
			if not os.path.isfile('prolog/kb_recetas.pl'):
				print "Generando Recetas..."
				self.cargarRecetas()
			print "Cargando Recetas..."
			self.prolog.consult('prolog/kb_recetas.pl')
			print "Cargando Querys..."
			self.prolog.consult('prolog/motorinferencia.pl')
			self.band = False
		else:
			print "Ya se cargo"
Пример #19
0
class PrologAA:
    def __init__(self):
        self.prolog = Prolog()
        self.prolog.assertz(":-use_module(library(lists))")
        self.ficheiro = None

    def assercao(self,texto):
        if self.ficheiro is None:
            self.ficheiro = open(r"f:\temp\pee.pl","w")
        self.ficheiro.write(texto+ '.\n')

    def query(self, texto):
        if self.ficheiro is None:
            self.ficheiro = open(r"f:\temp\factos_pee.pl","w")
        self.ficheiro.write(texto + '.\n')
        self.ficheiro.close()
        return dict(V=['a','b','c'])

    def procurar(self, problema):
        prlg = self.prolog

        objectivo = [ (x,y) for (x,y) in problema.modelo_mundo._elementos if problema.modelo_mundo._elementos[(x,y)] == 'alvo'][0]

        self.assercao( "final({}/{}/G/H/V,V,C) :- C is G+H.".format( objectivo[0], objectivo[1]))
        posicoes = [ (x,y) for (x,y) in problema.modelo_mundo._elementos if problema.modelo_mundo._elementos[(x,y)] != 'obst']
        for (x,y) in posicoes:
            self.assercao("posicao({},{})".format(x,y))

        accoes=[(1,0,1), (1,1,2), (0,1,3),(-1,1,4),(-1,0,5),(-1,-1,6),(0,-1,7),(1,-1,8)]
        for (x,y, z) in accoes:
            self.assercao("accao({},{},{},{})".format(x,y, z/8.0 * 2.0* math.pi, math.sqrt( x**2 + y**2)))

        self.problema = problema
        (xi, yi) = problema.estado_inicial() #(0,1)
        caminho = list(self.query("teste( V, _) :-  aStar( {}/{},V, C )".format(xi, yi)))
        input("Parar aqui, foi apenas usado para obter a representacao do mundo num ficheiro de factos a usar em prolog")
Пример #20
0
    def test_issue_8(self):
        """
        Callbacks can cause segv's

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

        from pyswip import Prolog, registerForeign

        callsToHello = []
        def hello(t):
            callsToHello.append(t)
        hello.arity = 1

        registerForeign(hello)

        prolog = Prolog()
        prolog.assertz("parent(michael,john)")
        prolog.assertz("parent(michael,gina)")
        p = prolog.query("parent(michael,X), hello(X)")
        result = list(p)   # Will run over the iterator
        
        self.assertEqual(len(callsToHello), 2)  # ['john', 'gina']
        self.assertEqual(len(result), 2) # [{'X': 'john'}, {'X': 'gina'}]
Пример #21
0
class Bridge:
  def __init__(self):
    self.prolog = Prolog()
    self.prolog.consult('facts.pl')
    self.prolog.consult('logic/agent.pl')

  def best_action(self):
    actions = list(self.prolog.query('best_action(Action, Arg1, Arg2)', maxresult=1))
    if len(actions) > 0:
      return actions[0]
    else:
      return None

  def assertz(self, what):
    return list(self.prolog.query("assertz(%s)" % what))

  def retract(self, what):
    return list(self.prolog.query("retract(%s)" % what))

  def retractall(self, what):
    return list(self.prolog.query("retractall(%s)" % what))

  def assert_perceptions(self, perceptions, x, y):
    for p in perceptions.keys():
      self.retract("percept_%s(%d, %d)" % (p, x, y))
      if perceptions[p] == True:
        self.assertz("percept_%s(%d, %d)" % (p, x, y))

  def assert_on(self, x, y):
    self.retractall('on(X, Y)')
    self.retract('visited(%d, %d)' % (x, y))
    self.assertz('on(%d, %d)' % (x, y))
    self.assertz('visited(%d, %d)' % (x, y))
    self.retract('connex(%d, %d)' % (x, y))
    self.assertz('connex(%d, %d)' % (x, y))

  def assert_energy(self, e):
    self.retractall('energy(E)')
    self.assertz('energy(%d)' % e)

  def assert_attacked(self, x, y):
    self.assertz('attacked(%d, %d)' % (x, y))
Пример #22
0
 def __init__(self,radius=80):
     self.win = Tk()
     self.radius = radius
     self.pawnList1 = []
     self.pawnList2 = []
     self.generatePawns()
     self.playerOne = True
     self.pawnSelected = False
     self.chaining = False
     self.capturing = False
     self.selectedPawn = None
     self.captured = None
     self.prolog = Prolog()
     self.prolog.consult("clauses.pl")
     self.prolog.asserta("hos(dummy)")
     self.defaultPosition()
     self.board = Board(self.pawnList1,self.pawnList2,self.radius,self.win,self)
     self.board.mainloop()
Пример #23
0
 def find_elements(self,long_string):
     elements = []
     solution = []
     arr = long_string.strip().split(" ")
     arr_len = len(arr)
     from pyswip import Prolog
     prolog = Prolog()
     prolog.consult("kb.txt")
     for x in xrange(arr_len):
         q = list(prolog.query("elements(%s)"%arr[x]))
         if len(q) > 0:
             s = list(prolog.query("problem(%s,X)"%arr[x]))
             kw = [x['X'] for x in s]
             for k in kw:
                 if arr.__contains__(k):
                     solution.append(list(prolog.query("solution(%s,Y)"%k)))
                     for h in solution:
                         if len(h) > 0:
                             for j in h:
                                 elements.append(j['Y'])
     return elements
Пример #24
0
def pathplan(start,end):
    prolog = Prolog() 
    prolog.consult('a_star_4.0.pl')
    startlist=start.split('+')
    len_start=len(startlist)
    endlist=end.split('+')
    len_end=len(endlist)
    if len_start==3 and len_end==3 :
        qqq = "once(path_plan1(" + startlist[0] + "," + startlist[1]+ "," + startlist[2]+ "," + endlist[0] + "," + endlist[1]+ "," + endlist[2] + ",Coorlist))"
        for result in prolog.query(qqq): 
            path = result["Coorlist"]
        print path
    elif len_start==3 and len_end==1 and end=='last_starter' :
        qqq = "once(path_plan3(" + startlist[0] + "," + startlist[1]+ "," + startlist[2]+ ",last_starter,Coorlist))"
        for result in prolog.query(qqq): 
            path = result["Coorlist"]
        print path
    else :
        qqq = "once(path_plan2(" + startlist[0] + "," + startlist[1]+ "," + startlist[2]+ "," + end + ",Coorlist))"
        for result in prolog.query(qqq): 
            path = result["Coorlist"]
        print path
from pyswip import Prolog

prolog = Prolog()
prolog.consult("./pl/engine.pl")
# def fact(string):
# 	prolog.assertz(string)

# def isOld(age):
# 	if(age > 60):
# 		fact("isOld(a)")
# 		return True
# 	fact("isOld(a):-false")
# 	return False

# def hasChild(has):
# 	if(has):
# 		fact("hasChild(a)")
# 	else:
# 		fact("hasChild(a):-false")
# 	return has

# def isTall(height):
# 	if(height > 180):
# 		fact("isTall(a)")
# 		return True
# 	fact("isTall(a):-false")
# 	return False

# def privacy(need_privacy):
# 	if(need_privacy):
# 		prolog.query("rules:private(a)")
Пример #26
0
from pyswip import Prolog
prolog = Prolog()
prolog.assertz("father(michael,john)")
prolog.assertz("father(michael,gina)")
list(prolog.query("father(michael,X)")) == [{'X': 'john'}, {'X': 'gina'}]
for soln in prolog.query("father(X,Y)"):
    print(soln["X"], "is the father of", soln["Y"])
# michael is the father of john
# michael is the father of gina    //
Пример #27
0
"""
PySWIP usage example. See also:
    https://github.com/yuce/pyswip
"""

from pyswip import Prolog

prolog = Prolog()
prolog.assertz("father(michael,john)")
prolog.assertz("father(michael,gina)")
query_results = list(prolog.query("father(michael,X)"))

# check if results are correct:
if query_results == [{'X': 'john'}, {'X': 'gina'}]:
    print("Correct results")
else:
    print("Incorrect results")
for soln in prolog.query("father(X,Y)"):
    print(soln["X"], "is the father of", soln["Y"])

# michael is the father of john
# michael is the father of gina
Пример #28
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
Пример #29
0
class PrologGrammarEngine:
    """
    This class is used to :
        - initialize a interface toward Prolog using pyswip
        - transform and load a grammar into the prolog engine
        - define methods to query the grammar

    This class must be instanciate ony one
    """

    all_ready_initialize = False

    def __init__(self, path_to_methods_file: str):
        """
        :param path_to_methods_file: path toward prolog knowledge base that contains
                                     the predicates used to query the grammar
        """
        assert not PrologGrammarEngine.all_ready_initialize
        self.prolog = Prolog()
        self.prolog.consult(path_to_methods_file)

        # We keep in memory all the predicates that had been added to the prolog engine
        # in order to be able to remove them if needed
        self.current_predicates: List[str] = []

        # We keep in memoery all the terminal symbol of the grammar
        # in order to not have to communicate each time with prolog
        # when we need to know if a symbol is terminal
        self.terminals: Set[str] = set()

        PrologGrammarEngine.all_ready_initialize = True

    def delete_grammar(self):
        """
        Remove all the grammar predicates from the prolog engine
        """
        for rule in self.current_predicates:
            self.prolog.retractall(rule)
        self.current_predicates = []
        self.terminals = {}

    def retrieve_terminal(self):
        """
        Load the terminal symbol in memory once for all
        """
        answers = self.prolog.query("terminal(X)")
        self.terminals = {answer["X"] for answer in answers}

    def load_grammar(self, ntlk_str_grammar: str):
        """
        Transform the grammar into prolog predicates
        and load it in the prolog engine
        """
        self.current_predicates = parse_to_prolog(ntlk_str_grammar)
        for rule in self.current_predicates:
            self.prolog.assertz(rule)
        self.retrieve_terminal()

    def valid_children(self, symbols: List[str]) -> List[List[str]]:
        """
        Given a derivation (list of terms), return all the valide children node. Ie:
            - all symbols string that can derivate from this derivation using only one rule
            - all symbols string from which a terminal leaf can be reached
        """
        try:
            answer = next(
                self.prolog.query("all_valid_children([%s], X)" %
                                  join(symbols)))
            return format_term(answer["X"])
        except StopIteration:
            return []

    def leaf(self, symbols: List[str]) -> Union[List[str], None]:
        """
        Given a derivation, return a random terminal leaf if it exists, None else
        """
        answers = self.prolog.query("random_leaf([%s], X)" % join(symbols))
        try:
            answer = next(answers)
            return format_term(answer["X"])
        except StopIteration:
            return None

    def is_terminal(self, symbol: str) -> bool:
        """
        return true is the symbol is terminal
        """
        return symbol in self.terminals

    def set_random_seed(self, seed: int):
        """
        set the random seed of prolog engine
        """
        # WARNING - This does not seem to work !
        self.prolog.assertz("set_random(seed(%d))" % seed)
Пример #30
0
                    action='store_true',
                    help='test only accepted queries')
parser.add_argument('--rejected',
                    default=False,
                    action='store_true',
                    help='test only rejected queries')
parser.add_argument('--display',
                    default=False,
                    action='store_true',
                    help='display')

args = parser.parse_args()

queries = open('./tests/queries.txt', 'r')

prolog = Prolog()
prolog.consult(PROLOG_FILE)


def smoothen_print(str):
    return str["PT"] + '\n'


def color_output(str, step):
    linked_list = LinkedList()
    for i in range(len(str)):
        charac = str[i]
        if (charac == "("):
            linked_list.add(i, str)
        elif (charac == ")"):
            linked_list.close(i)
Пример #31
0
	def give_graph(self):
		if self._state is None: #exception-like condition, maybe NoStateException
			print('No state is ready!')
			return
		state, n = self._state, self._state.length
		if self._big_anchor_state is None:
			print('No big anchor state is ready!')
			return
		if 'graph' in self._big_anchor_state:
			return self._big_anchor_state['graph']
		word_set = self._big_anchor_state['word_set']
		self.decide_graph_module()
		if self.graph_module == 'networkx':
			import networkx as nx
			G = nx.DiGraph()
			index = word_set.index()
			for i in range(n):
				G.add_node(index[(i, 0)], word = self._l[i][0])
				for j, word in enumerate(self._l[i][1:], 1):
					G.add_edge(index[(i, j - 1)], index[(i, j)])
					G.nodes[index[(i, j)]]['word'] = word
				for j, word in enumerate(self._l[i]):
					if 'appearance' not in G.nodes[index[(i, j)]]:
						G.nodes[index[(i, j)]]['appearance'] = []
					G.nodes[index[(i, j)]]['appearance'].append(i)
			self._big_anchor_state['graph'] = G
			return G
		elif self.graph_module == 'pyswip':
			from pyswip import Prolog
			prolog = Prolog()
			prolog.consult('knowledge.pl')
			#clear the previos graph which is created in this object
			deque(prolog.query(f'clear_register({id(self)})'), maxlen = 0)
			index = word_set.index()
			id_word_map = {} #prevent overlapping
			for i in range(n):
				id_word_map[index[(i, 0)]] = self._l[i][0]
				for j, word in enumerate(self._l[i][1:], 1):
					prolog.assertz(f'edge({index[(i, j - 1)]}, {index[(i, j)]})')
					id_word_map[index[(i, j)]] = word
				for j in range(len(self._l[i])):
					prolog.assertz(f'appear({index[(i, j)]}, {i})')
			for word_id, word in id_word_map.items():
				prolog.assertz(f"word({word_id}, '{word}')") #word is atom, not string (list of codes)
				prolog.assertz(f'node_register({id(self)}, {word_id})') #register the word ID under a key (python ID of self)
			#prolog.assertz('all_node([{}])'.format(', '.join([str(i) for i in id_word_map.keys()])))
			self._big_anchor_state['graph'] = prolog
			return prolog
		elif self.graph_module is None:
			print('Failed to draw graph!')
			return

#EQUIPO: CRISTIAN CAAMAL, HENRY UICAB, DIANA BALAM
#Importando pyswip para realizar el puente para python que permite consultar prolog
from pyswip import Prolog
prolog = Prolog()
#realizando la consulta en el programa prolog de los hechos
prolog.consult("hechos.pl")
#Imprimiendo el titulo
print("Sistema para la predicción de problemas de software y hardware de una laptop")

r = False
# REALIZANDO LOS CICLOS FOR PARA LAS CONSTRUCCIÓN DEL PROGRAMA, AQUÍ SE EJECUTAN LAS SENTENCIAS MIENTRAS LA CONDICIÓN SEA VERDADERA, AL MOMENTO DE SER FALSA TERMINA EL CICLO
while not r:
    
    #LLAMA E IMPRIME LAS PERSONAS QUE TIENEN PROBLEMAS EN SU EQUIPO
    for valor in prolog.query("reparacion(X,falla)"):
        print (' REQUIERE VERIFICAR EL EQUIPO => ', valor ["X"])
    #MUESTRAS LOS LAS PERSONAS QUE SU EQUIPO REQUIERE UNA REPARACION
    for valor in prolog.query("sinreparacion(X)"):
        print (' REQUIERE REPARACIÓN SU EQUIPO => ', valor ["X"])

     #IMPRIME LAS PERSONAS QUE TIENEN UN DAÑO FISICO EN SU EQUIPO   
    for valor in prolog.query("equipodanado(X,covid)"):
        print (' SU EQUIPO TIENE DAÑOS => ', valor ["X"])
    #IMPRIME LAS PERSONAS QUE NO TIENEN DAÑO FISICO EN SU EQUIPO
    for valor in prolog.query("sindano(X)"):
        print (' SU EQUIPO NO TIENE DAÑOS => ', valor ["X"])
    #LEE EL NOMBRE DE LA PERSONA INGRESADA CON PROBLEMAS DE SOFTWARE
    X= input("----\nPor Software\n----\n Inserta el nombre de la persona ")
    #DICE QUE PROBLEMA TIENE EL EQUIPO POR SOFTWARE
Пример #33
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)
Пример #34
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()
Пример #35
0
import time
from pyswip import Prolog

prolog = Prolog()

prolog.assertz('fun(X) :- red(X),car(X)')
prolog.assertz('happy(X) :- red(X);car(X)')

prolog.assertz('car(vw_beatle)')
prolog.assertz('car(ferrari)')
#prolog.assertz('car(hyundai)')
prolog.assertz('bike(harley_davidson)')
prolog.assertz('red(ferrari)')
prolog.assertz('red(vw_beatle)')
prolog.assertz('blue(hyundai)')

#print(list(prolog.query('car(Which)')))
#print(list(prolog.query('fun(Which)')))
print(list(prolog.query('car(ferrari)')))
inicio = time.time()
prolog.assertz('fatorial(0,1)')
prolog.assertz('fatorial(N,F) :- N>0,N1 is (N-1),fatorial(N1,F1),F is (N*F1)')
#print(list(prolog.query('fatorial(0,X)')))
print(list(prolog.query('fatorial(20,X)')))
fim = time.time()

print(fim - inicio)
Пример #36
0
# Basic Autonomous Rover Cognitive Architecture (BARCA)
# (Simple) World Model Test (Beta 0.01)
# www.revelation3.com

# insert 3 entries into the brain's "world model" memory component
# indicating what's been detected by Bot
# index (for ordering purposes), substance detected & timestamp

# setup SWI-Prolog to Python interface

from pyswip import Prolog
prolog = Prolog()

# declare what's been detected and when in a list (for testing)
# generated by Bot's sensors in the Real World!

detected = [
    "'METAL','2027'", "'GAS','2028'", "'METAL','2029'", "'GAMMA','2033'",
    "'SMOKE', '2045'"
]

# add the above list to the prolog world model plus the software generated index

index = 1
for x in detected:
    prolog.assertz("brain(world_model(memory(detect(" + "'" + str(index) +
                   "'," + str(x) + "))))")
    index = index + 1

# retrieve the detection list & index from the prolog world model memory & print
Пример #37
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
Пример #38
0
from pyswip import Prolog, Query, Variable, Functor
from tkinter import *
from tkinter import scrolledtext
from tkinter import ttk
from datetime import date
from tkinter.ttk import *
# Prolog instance created and opened file
prolog = Prolog()
prolog.consult("reglas_test.pl")
date = date.today()


def changeSalary(sueldo):
    print(list(prolog.query("sueldo(X)")))
    change = list(prolog.query("cambiar_sueldo(" + sueldo.get() + ")"))
    save = list(prolog.query("guardar_sueldo"))
    print(list(prolog.query("sueldo(X)")))


def create_window():
    prolog.consult("a_db.txt")
    window = Tk()
    window.title("El presupuesto del bibliófilo")
    window.geometry("720x480")

    tabControl = ttk.Notebook(window)

    #Label 1
    lbl = Label(window,
                text="El presupuesto del bibliófilo",
                font=("Arial Bold", 15))
Пример #39
0
# This program is written in Python 3
from pyswip import Prolog

prolog = Prolog()
prolog.consult("project.pl")

plmode = False


# ===========================================================
# Main loop:
# 1. Repeat "input-response" cycle until input starts with "bye"
#    Each "input-response" cycle consists of:
# 		1.1 Reading an input string and convert it to a tokenized list
# 		1.2 Processing tokenized list
# ===========================================================
def chat():
    global plmode
    while (True):
        if plmode:
            userInput = input()
        else:
            userInput = readinput()
        if userInput[0].startswith("bye"):
            print("Bye!")
            break
        elif userInput[0].startswith("plmode"):
            plmode = True
            continue
        elif userInput[0].startswith("plend"):
            plmode = False
Пример #40
0
from pyswip import Prolog

prolog = Prolog()
prolog.assertz("father(michael,john)")
prolog.assertz("father(michael,gina)")
result = list(prolog.query("father(michael,X)"))
print result
Пример #41
0
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))
Пример #42
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)
Пример #43
0
class ManejoProlog:
    

    #Definición de la función constructora.
    #E: dirección del código de prolog.
    #S: ninguna
    #R: ninguna
    def __init__(self, texto):

        try:                                                            #Validación de que archivo exista.
            
            archivo = open(texto, "r")
            archivo.close
            self.direccion = texto                                      #Se define el atributo con la dirección del código de prolog.
            self.cargarConocimientos()                                  #Se cargan los conocimientos del código.
            self.error = False

            
        except:
            
            archivo = open("Recetas.pl", "w")                           #Creación de uno nuevo.
            archivo.close()
            self.direccion = "Recetas.pl"                               #Se define el atributo con la dirección del código de prolog.
            self.cargarConocimientos()                                  #Se cargan los conocimientos del código.
            self.error = True

    
    #Definición de la función que crea una nueva regla.
    #E: texto con el código de prolog.
    #S: ninguna
    #R: ninguna(método llamado internamente)
    def nuevaRegla(self, texto):

        archivo = open(self.direccion, "a")
        archivo.write('\n' + texto + '.')
        archivo.close()
        self.cargarConocimientos()
        

    #Definición de la función que lee el código de prolog y carga cada línea en una lista
    #E: ninguna.
    #S: lista con cada línea del código fuente de prolog.
    #R: ninguna.
    def leer(self):

        archivo = open(self.direccion, "r")
        lineas = archivo.readlines()
        archivo.close()
        return lineas


    #Función que borra una receta.
    #E: nombre de la receta por borrar.
    #S: ninguna.
    #R: ninguna.
    def borrarReceta(self, receta):

        lineas = self.leer()
        contador = 0
        
        for i in lineas:                                                #Se recorre el código de prolog en busca de la receta.
            
            if (i.startswith("receta("+receta+",")):                    #Se verifica que la receta sea igual a la ingresada.
                
                lineas.pop(contador)                                    #Se elimina de la lista
                contador += 1
                
            else:
                
                contador += 1
                
        archivo = open(self.direccion, "w")                             #Se reescribe el archivo con la receta eliminada.
        
        for i in lineas:
            
            archivo.write(i)
            
        archivo.close()
        self.cargarConocimientos()
        box.showinfo("Éxito", "La receta se ha borrado con éxito.")


    #Función que actualiza alguna receta.
    #E: lista con las posiciones a modificar y todos los datos de la receta (dato vacío si no se va a modificar y nombre de la receta siempre estará).
        #Ejemplo:
        #         Se tiene una receta(pizza, giovanni, italiana, queso, calentar)
        #         Se desea cambiar solamente el dato de 'giovanni'(autor) y 'queso'(ingredientes) por 'giussepe' y 'jamón'.
        #         Los datos de entrada serían: posiciones = [1,3], datos = ['pizza', 'giussepe', '', 'jamon', '']
    #S: ninguna.
    #R: ninguna.
    def actualizarReceta(self, posiciones, datos):

        lineas = self.leer()
        contador = 0
        
        for i in lineas:                                                #Se recorre el código de prolog en busca de la receta a actualizar
            
            if (i.startswith("receta("+datos[0]+",")):                  #Se verifica que la receta sea igual a la que se desee cambiar
                
                lineas[contador] = self.actualizarReceta_aux(posiciones, datos, i[7:])  #Se sustituye la línea con el resultado de la función auxiliar.
                contador += 1
                
            else:
                
                contador += 1
                
        archivo = open(self.direccion, "w")                             #Se reescribe el archivo con los nuevos datos.
        
        for i in lineas:
            
            archivo.write(i)
            
        archivo.close()
        self.cargarConocimientos()
        box.showinfo("Éxito", "La receta se ha borrado con éxito.")


    #Función auxiliar que se encarga de actualizar los datos.
    #E: lista de las posiciones por modificar, datos por cambiar, datos originales.
        #Continuando el ejemplo:
                #datos = ['pizza', 'giussepe', '', 'jamon', '']
                #posiciones = [1,3]
                #original = 'pizza, giovanni, italiana, queso, calentar'
    #S: línea de código prolog con los nuevos valores.
    #R: ninguna.
    def actualizarReceta_aux(self, posiciones, datos, original):

        separacion = original.split(",")                                #Se hace una lista con los datos viejos. Continuando el ejemplo anterior:
                                                                                #Se obtiene separacion =  ['pizza', 'giovanni', 'italiana', 'queso', 'calentar']  (DATOS ORIGINALES)                                      
        for i in posiciones:                                            #Se recorre la lista con las posiciones de la lista separacion por cambiar.
            separacion[i] = datos[i]                                    #Se cambia la posición obtenida en la lista posiciones, con la misma posición de la lista datos.
                                                                                #Se cambiaría la posición separacion[1] = datos[1] ('giussepe') y luego separacion[3] = datos[3] ('jamon')
        return "receta({},{},{},{},{}).\n".format(separacion[0], separacion[1], separacion[2], separacion[3], separacion[4])
                                                                        #Se retorna la nueva línea de código prolog.

    #Función que se encarga de cargar los conocimientos.
    #E: ninguna.
    #S: código prolog cargado.
    #R: ninguna.
    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
from pyswip import Prolog

prolog = Prolog()
prolog.consult('sinonimos')
palabra = 'terminar'

solucion = list(prolog.query("P=%s,sinonimo_de(P, S)" % palabra, maxresult=-1))
for sinonimo in range(0, len(solucion)):
    print(solucion[sinonimo]['S'])
Пример #45
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)
Пример #46
0
parser.add_argument('-f',
                   help='Write to file.')
parser.add_argument('-n',
                   help='Number of answers.')
parser.add_argument('--module',
                   help='Name of module to compile. Shortcut for "-c module.cosmos -o module.pl"')
parser.add_argument('-s',
                   help='Blah.')
parser.add_argument('-q',
                   help='Blah.')
parser.add_argument('-i',
                   help='Open the interpreter.', action="store_true")

args = parser.parse_args()

p = Prolog()

if args.module:
	module = args.module
else:
	module = 'cosmos'
	#raise "Required --module flag."

#Prolog Query
i = 0
if args.n:
	n = int(args.n)
else:
	n = float('inf')
	
#p.consult(module+'.pl')
from ConceptNetInterface import GetAllEdges

from pyswip import Prolog

import string


prolog = Prolog()


def isEnglish(s):
    try:
        s.encode(encoding='utf-8').decode('ascii')
    except UnicodeDecodeError:
        return False
    else:
        return True


Edges = GetAllEdges("word",1,100,False)


for edge in Edges:

    Start = edge.Get_StartNode().lower()
    End = edge.Get_EndNode().lower()
    Relation = edge.Get_Relation().lower()

    Con1 = Start.isalpha()
    Con2 = End.isalpha()
Пример #48
0
    def __init__(self):
	prolog=None
	ConnectLivestatus.__init__(self)
	self.prolog=Prolog()
	self.prolog.consult('vanyad.pl')
Пример #49
0
import logging
import json
import cgi

from urllib.parse import urlparse, parse_qs
from pyswip import Prolog
from http.server import BaseHTTPRequestHandler, HTTPServer

pl = Prolog()


# HTTP Server Handler Class.
class HttpServerHandler(BaseHTTPRequestHandler):
    def _set_response(
        self
    ):  # função para ajustar os headers a retornarem conteúdo em formato HTML.
        self.send_response(200)
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
        self.send_header("Access-Control-Allow-Headers", "X-Requested-With")
        self.send_header('Content-type', 'text/html')
        self.end_headers()

    def _set_json_response(
        self
    ):  # função para ajustar os headers a retornarem conteúdo em formato JSON.
        self.send_response(200)
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
        self.send_header("Access-Control-Allow-Headers", "X-Requested-With")
        self.send_header('Content-type', 'application/json')
Пример #50
0
from pyswip import Prolog

p = Prolog()

p.consult("ds/minhaBD.pl")

q = list(p.query('filho(X,nao)'))

print(len(q))
Пример #51
0
from pyswip import Prolog, registerForeign, Atom

def atom_checksum(*a):
    print 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)"))
Пример #52
0
from pyswip import Prolog

from service.search_key import search_key
import knowledge.dictionary3_n as dct
prolog = Prolog()
prolog.consult("knowledge/task3_n.pl")


def to_swi_param(param):
    for key, val in dct.dictionary.items():
        if val.lower() == param.lower():
            return key
    return None


def print_result(query_result):
    if query_result is not None:
        for answer in query_result:
            for key, value in answer.items():
                print(dct.dictionary[str(value, 'utf-8')])
        print()


def parse(msg):
    msg = msg.lower()

    cur_project = ""
    for pr in dct.projects:
        if pr.lower() in msg:
            cur_project = pr
Пример #53
0
 def __init__(self):
   self.prolog = Prolog()
   self.prolog.consult('facts.pl')
   self.prolog.consult('logic/agent.pl')
Пример #54
0
from pyswip import Prolog

prolog = Prolog()
prolog.consult("utf_facts.pl", catcherrors=True)
print(list(prolog.query("current_prolog_flag(encoding,X)")))
print(list(prolog.query("father(X)")))
Пример #55
0
 def __init__(self):
     self.prolog = Prolog()
     self.prolog.consult("pl/GameDatabase.pl")
     self.prolog.consult("pl/GameLogic.pl")
Пример #56
0
import os
import io
import sys
import re

if __name__ == "__main__":
    filename = str(sys.argv[1])
    with open(filename, "r") as f:
        raw_text = f.read()
    inp = re.split('[\.\!\?\。\!\?\n]', raw_text)
    print(inp)
    query = 'author(_author,_work):-semantic(生成),type(X0,verb),(main(X0,書く);main(X0,描く)),role(X1,動作主),main(X1,_author),role(X2,対象),main(X2,_work).'
    queryy = "author(X,Y)"

    match = 0
    prolog = Prolog()

    print("以下の条件でパタンマッチを開始します")
    print("-[条件1]", query)
    print("")
    print("")

    start = time()

    for i in range(len(inp) - 1):
        # for i in range(len(inp)-1):
        a2p = ASAtoProlog.ASAtoProlog(inp[i])

        with open("testfile.pl", mode="w") as f:
            f.write("\n".join(a2p) + "\n" + query)
Пример #57
0
from bottle import request, route, run, template
from pyswip import Prolog
import json

prolog = Prolog()
prolog.consult("ArbEstFam.pl")


@route('/agregarfamilia', method='POST')
def agregarfamilia():
    data = request.json
    for d in data["padres"]:
        prolog.assertz('padres("' + d[0] + '","' + d[1] + '")')
    return data


@route('/Tio', method='POST')
def tio():
    data = request.json
    for d in data["es_tio"]:
        print(d[0])
        print(d[1])
        tt = prolog.query('tios("' + d[0] + '","' + d[1] + '")')
        T = list(tt)
    if T:
        return {"Es Tio": T[1]}
    else:
        return {"No es Tio": T}


@route('/Primo', method='POST')
Пример #58
0
from pyswip import Prolog
from gifs import gif
import tkinter as tk
from ventana import ImageLabel

prolog = Prolog()
# Lectura del archivo
mapa = open("laberinto.txt")
map = []
for i in mapa:
    map += [i.split(" ")]

def buscar_en_matriz(matriz, cont, para):
    if matriz == []:
        return (-1, -1)
    if para in matriz[0]:
        return [cont, matriz[0].index(para)]
    return buscar_en_matriz(matriz[1:], cont + 1, para)

def caminoLlegada(pos, k, j):
    alf = ["+", "|", "-"]
    try:
        for i in alf:
            temStr = map[pos[0]+k][pos[1]+j].replace(i, "")
        temInt = int(temStr)
        prolog.assertz(
            "conecta(" + map[pos[0]][pos[1]] + "," + temStr + ")")
    except:
        pass

def inicializar():
Пример #59
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)
Пример #60
0
    def test_issue_4(self):
        """
       	Patch for a dynamic method

        Ensures that the patch is working.

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

        from pyswip import Prolog
        
        Prolog.dynamic('test_issue_4_d/1')
        Prolog.assertz('test_issue_4_d(test1)')
        Prolog.assertz('test_issue_4_d(test1)')
        Prolog.assertz('test_issue_4_d(test1)')
        Prolog.assertz('test_issue_4_d(test2)')
        results = list(Prolog.query('test_issue_4_d(X)'))
        self.assertEqual(len(results), 4)
        
        Prolog.retract('test_issue_4_d(test1)')
        results = list(Prolog.query('test_issue_4_d(X)'))
        self.assertEqual(len(results), 3)
        
        Prolog.retractall('test_issue_4_d(test1)')
        results = list(Prolog.query('test_issue_4_d(X)'))
        self.assertEqual(len(results), 1)