def Compute_Sat(KB, facts, print_info):
    """Prints symbols, propositions, and additional information from a knowledge base, 
    then runs a DPLL satisfiability search and prints the result"""
    # Create new KB initialized from current KB and extra facts
    new_KB = KB[:]
    for fact in facts:
        if fact not in KB:
            new_KB.append(fact)
    symbols = find_symbols(new_KB)  # Collect list of symbols
    model = {}  # Initialize model to 'None' for each symbol
    for symbol in symbols:
        model[symbol] = None
    print("Props:")  # Print propositional symbols
    for symbol in symbols:
        print(symbol, end=' ')
    print("\nInitial clauses:")  # Print original KB
    i = 0
    for clause in KB:
        print(str(i) + ": " + format_clause(clause))
        i += 1
    if facts:
        print("Additional facts:")  # Print additional facts
        for fact in facts:
            print(str(i) + ": " + format_clause(fact))
            i += 1
    print("-----------")
    model = DPLL(new_KB, symbols, model,
                 print_info)  # Satisfiability computation
    if model:  # If the model was populated
        print("KB and additional facts can be satisfied with the given model")
        print(model)
        print("-----------")
        print("True props:")
        for assignment in model:
            if model[assignment]:
                print(assignment)
    else:  # If no solution was returned
        print("There is no solution given the current KB and additional facts")
예제 #2
0
    notdisp = [
        letra(i) for i in range(1, 21) if i not in disponibilidad_professor2
    ]
    addrule = '(' + letra(42) + '>' + friendly_multiNEGAND(notdisp) + ')'
    Rules = '(' + Rules + 'Y' + addrule + ')'

    #same for A2
    notdisp = [
        letra(i + 20) for i in range(1, 21)
        if i not in disponibilidad_professor2
    ]
    addrule = '(' + letra(44) + '>' + friendly_multiNEGAND(notdisp) + ')'
    Rules = '(' + Rules + 'Y' + addrule + ')'

clausal = formaClausal(Tseitin(Rules, letras))

satisfacible, solucion = DPLL(clausal, {})

solucion_filter = {}
for i in solucion.keys():
    if i in letras:
        solucion_filter[i] = solucion[i]

decoded = {}
for i in solucion_filter.keys():
    decoded[inverse_letra(i)] = solucion_filter[i]
print(satisfacible, decoded)

export_horario(decoded, professor1, professor2, signature1, signature2,
               filename)
예제 #3
0
###############################################################################

#Verificamos que las reglas estén bien escritas
print(
    "------------------------Regla_1-----------------------------------------")
print(regla1)
#print(tuplas(regla1,letras))
print(
    "------------------------Regla_2-----------------------------------------")
print(regla2)
#print(tuplas(regla2,letras))
print(
    "------------------------Regla_3-----------------------------------------")
print(regla3)
#print(tuplas(regla3,letras))
print(
    "------------------------Regla_4-----------------------------------------")
print(regla4)
#print(tuplas(regla4,letras))

lista_solucion = [letras[0], regla1, regla2, regla3, regla4]
solucion = conjuncion(lista_solucion)
tseitin = Tseitin(solucion, letras)
fc = formaClausal(tseitin)
dpll = DPLL(fc, {})
interp = {}
for i in dpll[1]:
    if i in letras:
        interp[i] = dpll[1][i]
print(interp)
예제 #4
0
if __name__ == '__main__':

    R1 = subregla1NC(Nf, Nc, No)
    R2 = sub_regla2NC(Nf, Nc, No)
    RF = regla_final(R1, R2)

    TRF = str(RF)

    #se pasa por Tseitin para que genere una formula equisatisfacible mas sencilla que TRF (regla oficial)
    teis = fn.Tseitin(TRF, letrasProposicionales)
    #pasando a forma clausal
    hk = fn.formaClausal(teis)
    #se ingresa al DPLL (este genera una interpretacion para la formula de Tseitin, pero se sabe que dicha interpretacion tambien
    #es modelo de TRF)
    S, I = dp.DPLL(hk, {})
    #ii es una lista con las letras proposicionales de la interpretacion I
    ii = list(I.keys())
    I2 = {}
    #este ciclo selecciona todas las letrasproposicionales que estan en letras(lista original con codificacion) y crea un nuevo diccionario
    #I2 donde se guardan solo esas letras que son las de interes.
    for j in ii:
        if j in letrasProposicionales:
            if I[j] == 1:
                I2[j] = 1
            else:
                I2[j] = 0

    #print(len(I2))
    # aqui se imprime la interpretacion que encuentra el programa, es decir una solucion al problema
    print(I2)
예제 #5
0
from DPLL import DPLL
import time
from plot_tools import n_queens_plotter
from nqueens import n_queens
import os

solver = DPLL()

# # test capacity of solver
# for n in range(1,100):
#     print("n is: ", n)
#     if not os.path.isfile("/Users/Chelsea/scratch/n_queens_"+str(n)+".txt"):
#         n_queens(n).encode("/Users/Chelsea/scratch")
#     t = time.time()
#     solver.run_solver("/Users/Chelsea/scratch/n_queens_"+str(n)+".txt", testing=False)
#     dt = time.time() - t
#     print("dt: ", dt, " seconds, aka ", dt/60, " minutes.")
#     print("counter: ", solver.counter)
#     print("decisions: ", solver.dec_counter)
#     if dt/60 > 5:
#         break

n = 5
n_queens(n).encode("/Users/Chelsea/scratch")
solver.run_solver("/Users/Chelsea/scratch/n_queens_" + str(n) + ".txt",
                  testing=False)
n_queens_plotter(solver.nvars, solver.model).plot()
예제 #6
0
import sys
from SAT import SAT

if __name__ == "__main__":
    # for testing, always initialize the pseudorandom number generator to output the same sequence
    #  of values:
    random.seed(1)

    sudoku_problem = Sudoku(int(sys.argv[3]) == 1)
    sudoku_problem.load(sys.argv[1])

    puzzle_name = str(sys.argv[1][:-4])
    cnf_filename = "cnfs/{}.cnf".format(puzzle_name)
    sol_filename = puzzle_name + ".sol"

    sudoku_problem.generate_cnf(cnf_filename)

    if int(sys.argv[2]) == 1:
        solver = SAT(cnf_filename)
        result = solver.gsat()
    elif int(sys.argv[2]) == 2:
        solver = SAT(cnf_filename)
        result = solver.walksat()
    else:
        solver = DPLL(cnf_filename)
        result = solver.dpll_satisfiable()

    if result:
        solver.write_solution(sol_filename)
        display_sudoku_solution(sol_filename)
예제 #7
0
# print(REGLAFINAL) # Polaca Inversa
arbol = string2Tree(REGLAFINAL, letras, nums)
formula = InOrder(arbol)
# print(formula) # Forma Comun
# print("".join(formula))

###############################################################################

# Solucion al problema

FNC, cont = Tseitin(formula, letrasTs)
# print(FNC)
print()
print("Letras de Tseitin: ", cont)
# FNCSN = withoutDN(FNC)
# print(FNCSN)
FC = formaClausal(FNC)
# print(FC)

inter = {}

respuesta, interpretacion = DPLL(FC, inter)
print()
print("Tablero 3x3: ")
print()
print("La formula es: ", respuesta)
print("Su interpretación es: ", interpretacion)
print("Por lo tanto este problema no tiene solución. ")

###############################################################################
    B = cnf.deMorgan(A)
    B = cnf.quitarDobleNegacion(B)
    aux2 = cnf.Inorder(B)
    if aux1 != aux2:
        OK = True
        A = B
    else:
        OK = False
OK = True
while OK:
    OK, A = cnf.aplicaDistributiva(A)
    conjuntoClausulas = cnf.formaClausal(A)
clausulas.append(conjuntoClausulas)

k = clausulas[0]
o = DPLL(k, {})
U, L = o.DO_DPLL()
print "Satisfacible?"
print U
print "Interpretacion:"
print L

lista = []
for i in L:
    if L[i] == False:
        h = '-' + i
        lista.append(h)
    else:
        lista.append(i)

if U == 'satisfacible':
예제 #9
0
from display import display_sudoku_solution
import random, sys
from DPLL import DPLL

if __name__ == "__main__":
    # for testing, always initialize the pseudorandom number generator to output the same sequence
    #  of values:
    #random.seed(2)
    seed = 2
    random.seed(seed)
    thresh = .7
    #seed 8 thresh .6? puzz 1 - a mil iterations w no luck
    puzzle_name = str(sys.argv[1][:-4])
    sol_filename = puzzle_name + ".sol"

    dpll = DPLL(sys.argv[1], 729, var_start=110)
    print("Seed: " + str(seed))
    result = dpll.init_dpll()
    print("Seed: " + str(seed))
    if result:
        dpll.write_solution(sol_filename)
        display_sudoku_solution(sol_filename)
    else:
        print("Oh no bb what is u doin'")