コード例 #1
0
def solve_sudoku(knowledge_base, puzzle, method='dpll', puzzle_display='off', dim=9):
    
    # Convert puzzles to CNF 
    premises = cnf_conversion(puzzle,dim)
    #print("premises", premises)

    # Add premises to the knowledgebase 
    CNF = knowledge_base + premises #+ [[101,101]]

    # Resolve sudoku
    if method == 'dpll':
        solution = dpll(CNF,[])
        if solution:
            solution = np.array(solution)
            solution = solution[solution > 0]
            # fix output format for displaying the result in console 
            solution = extractDigits(solution)
            #print('satisfied')
        else:
            print('s UNSATISFIABLE')

    if puzzle_display == 'on' and solution:
        puzzle_size = dim 
        print('Puzzle: ')
        display_sudoku(premises, puzzle_size)
        print('Solved:')
        display_sudoku(solution, puzzle_size)
コード例 #2
0
def satProbability(n, m, k, num):
    # Genera la lista dei simboli e successivamente esegue
    # num volte l'implementazione dell'algoritmo di
    # Davis-Putnam, la funzione dpll. La lista results tiene
    # traccia degli esempi positivi e negativi.
    # La funzione restituisce i risultati sotto forma di lista
    # e il numero medio di chiamate ricorsive alla funzione
    # "dpll". Viene inoltre stampato a video il tempo
    # impiegato.
    
    global count
    count = 0
    start = time.time()
    symbols = generateSymbols(n)
    results = [0,0]
    for _ in range(0,num):
        clauses = randomSentence(symbols, m, k)
        if (clauses == None):
            return
        val = dpll.dpll(clauses, symbols, [])
        if (val == True):
            results[0] += 1
        if (val == False):
            results[1] += 1
    end = time.time()
    print end - start
    return results, count / num, float(m / float(n))
コード例 #3
0
ファイル: main.py プロジェクト: Guitheg/dpll_sat
def main():
    duration = Duration()

    if len(sys.argv) < 1 + 2 or len(sys.argv) > 1 + 3:
        print("usage:", sys.argv[0],"<filename(str)> <verbose(bool)> [optionnal : <nb_col(int)>]")
        print("Liste des fichiers disponibles :", get_files(DATA, ext=["cnf"]))
        print("Liste des fichiers disponibles :", get_files(DATA, ext=["col"]))
    else :
        filename = sys.argv[1]
        verbose = bool(int(sys.argv[2]))
        
        if get_file_ext(filename) == "col":
            if len(sys.argv) != 1 + 3:
                n_col = NB_COL_DEFAULT
            else : 
                n_col = int(sys.argv[3])
            data, nb_som, _ = col_parser(filename)
            cnf , n = col_to_cnf(data, nb_som, n_col)
        elif get_file_ext(filename) == "cnf":
            cnf, n, _ = cnf_parser(filename)
        else:
            Exception("only .col or .cnf file are granted")
        
        print("Ensemble des clauses : \n", cnf)
        print("Nombre de littéraux :", n)
        if n_col :
            print("Nombre de couleurs :", n_col)
        duration()
        s = dpll(cnf, n, verbose=verbose)
        duree = duration()
        print("Solution : ", s)
        print("Solution", "a priori vraie" if verif_solution(s, cnf, n) else "fausse")
        print("Temps de résolution :", duree, "secondes")
コード例 #4
0
def satisfy_dir(directory, walk=True, hill=True, deepee=True):
    all_results = []
    for file in os.listdir(directory):
        if file.endswith(".cnf"):
            formula, var_dict = util.read_dimacs(directory + "/" + file)

            if walk:
                for i in range(1, 11):
                    formula_walk = copy.copy(formula)
                    var_dict_walk = copy.copy(var_dict)
                    current = time.time()
                    try:
                        walk_formula, walk_result, walk_score, walk_flips = walksat.walk_sat(
                            formula_walk, var_dict_walk, i, 5000)
                        result = [
                            directory + "/" + file, "WalkSAT", walk_result,
                            str(walk_score) + "/" + str(len(formula)),
                            walk_flips,
                            time.time() - current
                        ]
                    except:
                        result = [directory + "/" + file, "WalkSAT", "ERROR"]
                    print(result)
                    all_results.append(result)
            if hill:
                current = time.time()

                hill_formula, hill_result, hill_score, hill_flips = hillclimbing.hill_climb(
                    formula, var_dict)
                result = [
                    directory + "/" + file, "HillClimb", hill_result,
                    str(hill_score) + "/" + str(len(formula)), hill_flips,
                    time.time() - current
                ]
                print(result)
                all_results.append(result)

            if deepee:
                current = time.time()
                for var in var_dict:
                    var_dict[var] = None
                for line in formula:
                    line[1] = None
                result, new_var_dict = dpll.dpll(formula, var_dict)
                new_formula, result, score = util.check_formula(
                    formula, new_var_dict)
                if result == False:
                    result = "Unsatisfied"
                else:
                    result = "Satisfied"
                result = [
                    directory + "/" + file, "DPLL", result, 'NA', 'NA',
                    time.time() - current
                ]
                print(result)
                all_results.append(result)

    return all_results
コード例 #5
0
def main():
    txt = input("Type the name of the file.txt : ")
    txt_output = input(
        "Type the name of the file.txt where you want to write the output' : ")
    list = open(txt).readlines()[3:]
    cnf2 = [row.split() for row in list]
    d = dpll(cnf2, list, [])
    f = str(' '.join(d))
    output = open(txt_output, 'w')
    output.write(f)
コード例 #6
0
def solve(expr: str, silent: bool = False) -> Tuple[bool, Dict]:
    clauses, original_literals = tseitin(expr)
    cnf = CNFFormula(clauses)
    is_sat, model = dpll(cnf)

    if not silent:
        if is_sat:
            model_str = '\n'.join(
                list(
                    map(
                        lambda key: f'{key}: {model[key]}',
                        filter(lambda key: key in original_literals,
                               model.keys()))))
            print(f'SAT: {expr}\n' f'Model: \n{model_str}')
        else:
            print('UNSAT')

    return is_sat, model
コード例 #7
0
print "Sudoku", X2SATsudoku(sud)
print ":: END SUDOKU ::\n"
print "::: END SAT PREVEDBE :::\n"
"""
######################################################
#################DPLL################################
######################################################
"""
# Metoda prejme za parameter logicno formulo
# Metoda vrne resitev formule, ce je to mogoce
# Opozorilo! Paziti moramo, da so negacije nahajo pri spremenljivkah! Potrebno je torej klicati metodo simplify preden
# vsavimo formulo v dpll.

from dpll import dpll
print "::: BEGIN DPLL :::"
print dpll(V("X"))
print dpll(And([V("X"), V("Y")]))
print dpll(And([XOR(V("X"), V("Y")), Or([V("X"), V("Y")])]))


G = [(V("a"), V("b"))]
print "Barvanje", dpll(barvanje(G, 2))
print "Hadamard 2", dpll(hadamardova_matrika(2))    # Hadamardovo za 4 ne resi v normalnem casu.

# Petersenov graf.
petersen = [
    (6, 7), (7, 8), (8, 9), (9, 10), (10, 6),
    (10, 5), (6, 1), (2, 7), (3, 8), (4, 9),
    (1, 3), (1, 4), (2, 5), (2, 4), (3, 5)
]
コード例 #8
0
def solve_sudoku(knowledge_base,
                 puzzle,
                 method='dpll',
                 puzzle_display='off',
                 dim=9):

    # Convert puzzles to CNF
    premises = cnf_conversion(puzzle, dim)
    #print("premises", premises)

    # Add premises to the knowledgebase
    CNF = knowledge_base + premises  #+ [[101,101]]

    # Resolve sudoku
    if method == 'dpll':
        solution = dpll(CNF, [])
        if solution:
            solution = np.array(solution)
            solution = solution[solution > 0]
            solution = extractDigits(solution)
        else:
            print('s UNSATISFIABLE')
    elif method == 'dpll_dlcs':
        solution = dpll_dlcs(CNF, [])
        if solution:
            solution = np.array(solution)
            solution = solution[solution > 0]
            solution = extractDigits(solution)
        else:
            print('s UNSATISFIABLE')

    elif method == 'dpll_dlis':
        solution = dpll_dlis(CNF, [])
        if solution:
            solution = np.array(solution)
            solution = solution[solution > 0]
            solution = extractDigits(solution)
        else:
            print('s UNSATISFIABLE')
    elif method == 'dpll_moms':
        solution = dpll_moms(CNF, [])
        if solution:
            solution = np.array(solution)
            solution = solution[solution > 0]
            solution = extractDigits(solution)
        else:
            print('s UNSATISFIABLE')
    elif method == 'dpll_jw':
        solution = dpll_jw(CNF, [])
        if solution:
            solution = np.array(solution)
            solution = solution[solution > 0]
            solution = extractDigits(solution)
        else:
            print('s UNSATISFIABLE')
    elif method == 'nocnf':
        solution = oldFashioned(puzzle, dim, puzzle_display)
        if solution:
            solution = np.array(solution)
            solution = solution[solution > 0]
            solution = extractDigits(solution)
        else:
            print('s UNSATISFIABLE')

    if puzzle_display == 'on' and solution:
        puzzle_size = dim
        print('Puzzle: ')
        display_sudoku(premises, puzzle_size)
        print('Solved:')
        display_sudoku(solution, puzzle_size)
コード例 #9
0
ファイル: primerjavaCasov.py プロジェクト: EvaBr/LVRSAT
D = input("Primerjam DPLL s čisto pojavitvijo? (y/n)  ")
D1 = input("Primerjam DPLL z le eno izvedbo čiste pojavitve (takoj na začetku)?  (y/n)  ")
DB = input("Primerjam osnoven DPLL, brez implementacije čiste pojavitve? (y/n)  ")
L = 0
if not (D=="n" and D1=="n" and DB=="n"):
	L = int(input("Koliko naključnih polnitev polj (sudokujev) zgeneriram? Vnesi naravno št."))

if not (D=="n" and D1=="n" and DB=="n"):
	print("\n Prazen sudoku:")
	print("="*25)
	CNF = sudoku([]).cnf()

if D=="y":
	kopija = Cnf([Stavek([i for i in s.literali]) for s in CNF.stavki])
	before1 = clock()
	rez1 = dpll(kopija)
	after1 = clock()
	print("Dpll z večkratno čisto pojavitvijo potrebuje {0} sec.".format(after1-before1))

if D1=="y":
	kopija = Cnf([Stavek([i for i in s.literali]) for s in CNF.stavki])
	before2 = clock()
	rez2 = dpll_brez_ciste(kopija)
	after2 = clock()
	print("Dpll z enkratno čisto pojavitvijo potrebuje {0} sec.".format(after2-before2))

if DB=="y":
	before3 = clock()
	rez3 = dpll_osnoven(CNF)
	after3 = clock()
	print("Dpll brez vsakršne čiste pojavitve potrebuje {0} sec.".format(after3-before3))
コード例 #10
0
def dpllSat(clauses, symbols):
    return dpll.dpll(clauses, symbols, [])
コード例 #11
0
ファイル: plogic.py プロジェクト: Vekteur/plogic
"""plogic

Usage:
	plogic.py <input_file> [--cnf] [--dpll]
"""
from docopt import docopt

from logic_parser import LogicParser
from dpll import dpll

args = docopt(__doc__)


def read(file):
    with open(file) as f:
        return f.read()


tree = LogicParser().parse(read(args['<input_file>']))

print('Parsed expression :', tree)
if args['--cnf']:
    print('CNF expression :', tree.toCNF())
if args['--dpll']:
    print('DPLL solutions :')
    for sol in dpll(tree.toCNF()):
        print(', '.join(atom + ': ' + str(value)
                        for atom, value in sol.items()))
コード例 #12
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

__author__ = 'Breno Alef Dourado Sá'

from Tkinter import *
import nQueenCNF
import dpll

n = input("Board size: ")
nQueenCNF.generateFile(n)

clauses = dpll.readDimacs(str(n) + "queens.dimacs")

result = dpll.dpll(clauses, [])

if result != False:
    root = Tk()
    root.title(str(n) + ' queens')
    canvas = Canvas(root, bg='white', height=500, width=500)
    canvas.pack(side=TOP, padx=10, pady=10)
    queen = PhotoImage(file="queen.gif")
    queen = queen.subsample(n, n)
    board_rows = n
    board_cols = n
    x = 1
    y = 1
    square_size = 500 / n
    for rows in range(board_rows):
        color_white = not (rows % 2)
        for columns in range(board_cols):
コード例 #13
0
ファイル: sudoku_solve.py プロジェクト: neal-o-r/SAT
def dpll_solve(sudo: Circuit) -> Solution:
    return dpll(sudo)
コード例 #14
0
ファイル: main.py プロジェクト: yeiipi/Rubik-2x2
# print(len(fFNC))
#print(fFNC)

# Se obtiene la forma clausal como lista de listas de literales
# print("inicio a Clausal")

fClaus = fn.formaClausal(formula)
# print(fClaus)

#print(len(fClaus))
# print(regla2())

test = {}
print("inicio a DPLL")
test = dpll(fClaus,test)

sat, dic = test

# print(test)

final = deco_dict3(dic,Ncuadros,Ncolores,Nturnos)
print(dic)

for k in  dic.keys():
    if k in lC:
        s,c,t = decodifica3(ord(k)-256, Ncuadros,Ncolores,Nturnos)
        print(f'S{s} C{c} T{t} -> {dic[k]}')
    else:
        print("fail")