def init_round(self): """Inialise un début de tour.""" self.deck = Deck() self.can.reset() self.proof = Proof() self.demo = Demo(self.proof) self.num_player = (self.num_player + 1) % 4 self.liar = [0] * 4 self.can.display_current_player(self.num_player) self.ordi_player = [False] * self.nb_player + [True ] * (4 - self.nb_player) self.hands = [self.deck.draw(5) for _ in range(4)] self.hands[self.num_player].extend(self.deck.draw(2)) self.cards_played = 0 self.can.display_cards("hand", self.hands[self.num_player]) if self.ordi_player[self.num_player]: self.can.reset_bind() self.ordi_plays() else: self.can.init_bind()
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")
def run(self, puzzleFilename, outputFilename): dpll = DPLL() print "" print "/"*10 + "NEW SUDOKU PUZZLE - USING DPLL" + "/"*10 print "Unsolved Puzzle:" self.loadPuzzleMatrix(puzzleFilename) self.printPuzzle() literals = self.loadLiteralList() clauseList = self.encodeMinimal(outputFilename) queue0 = Queue() print "" print "-"*40 print "Solved Puzzle Using MINIMAL Encoding:" t0 = clock() dpll.runDPLL(clauseList, {}, list(literals), queue0) print "Elapsed Time:" + str(clock() - t0) if queue0.get() == False: print "Didn't find encoding using minimal" else: print "Found encoding using minimal" dpll = DPLL() clauseList = self.encodeExtended(outputFilename) queue1 = Queue() print "" print "-"*40 print "Solved Puzzle Using EXTENDED Encoding:" t0 = clock() dpll.runDPLL(clauseList, {}, list(literals), queue1) print "Elapsed Time:" + str(clock() - t0) if queue1.get() == False: print "Didn't find encoding using extended" print "No Solution found...." else: print "Found encoding using extended"
+ str(1) + " " + str(file.variables) + " " + str(file.clauses) + " " + str(cpu_secsWalkSAT) + " " + str(0) + "\n" ) file.writeOutput(output, solution) DPLL = DPLL(KB, file) start_time = time.time() solution = DPLL.satisfiable() cpu_secsDPLL = time.time() - start_time cpu_secsDPLL = round(cpu_secsDPLL, 2) # Write to the .sol text file if not solution: output.write( "s" + " " + str(file.formatID) + " " + str(0) + " " + str(file.variables) + " " + str(file.clauses)
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)
############################################################################### #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)
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)
class Main(tk.Tk): """Programme principal.""" def __init__(self): """Constructeur de la classe :return: Objet Main :rtype: Main """ tk.Tk.__init__(self) self.title("PrYE") self.resizable(width=False, height=False) if platform == "linux": self.iconbitmap("@images/carteBack.icon") else: self.iconbitmap(default="images/carteBack.ico") self.__init_menu__() self.nb_player = 4 self.scores = [0] * 4 self.player_names = ["Joueur " + chr(ord('A') + i) for i in range(4)] self.num_player = 3 # sera incrémenté de 1 par init_round self.can = PryeCanvas(self) self.can.grid(row=0, column=1, rowspan=7) for i in range(4): tk.Label(text="Prémisse " + str(i + 1)).grid(row=i, column=2) tk.Label(text="PrYE le jeu", font="Arial 16 italic").grid(row=0, column=0) tk.Label(text="Prove You Exist ...", font="Arial 28 italic").grid(row=7, column=1) tk.Button(text="jouer", command=self.play).grid(row=5, column=0) PryeIntro() def __init_menu__(self): """creation de la barre de menu qui permet d'afficher l'aide, les règles, la version et de pouvoir quitter le jeu.""" self.barre_menu = tk.Menu(self) # creation du menu "Aide" self.aide = tk.Menu(self.barre_menu, tearoff=0) self.barre_menu.add_cascade(label="Aide", underline=0, menu=self.aide) self.aide.add_command(label="Règles", underline=0, command=self.rules) self.aide.add_command(label="A propos", underline=0, command=self.version) self.aide.add_command(label="Quitter", underline=0, command=self.quitter) # afficher le menu self.config(menu=self.barre_menu) def start(self, nb_player, cheat): """Lance une partie :param nbplayer: le nombre de joueurs humains :type nbplayer: int :param cheat: indique si le cheatmode (affichage des varibale prouvées) est activé :type cheat: bool """ self.nb_player = nb_player for num_player in range(nb_player, 4): self.player_names[num_player] = "Ordi " + chr( ord('A') + num_player) if cheat: tk.Button(text="cheat", command=self.cheat).grid(row=7, column=0) self.init_round() def init_round(self): """Inialise un début de tour.""" self.deck = Deck() self.can.reset() self.proof = Proof() self.demo = Demo(self.proof) self.num_player = (self.num_player + 1) % 4 self.liar = [0] * 4 self.can.display_current_player(self.num_player) self.ordi_player = [False] * self.nb_player + [True ] * (4 - self.nb_player) self.hands = [self.deck.draw(5) for _ in range(4)] self.hands[self.num_player].extend(self.deck.draw(2)) self.cards_played = 0 self.can.display_cards("hand", self.hands[self.num_player]) if self.ordi_player[self.num_player]: self.can.reset_bind() self.ordi_plays() else: self.can.init_bind() def play(self): """Valide un coup si possible.""" if self.cards_played != 2: messagebox.showwarning("PrYE", "Il faut jouer 2 cartes pour valider.") return if not self.proof.is_all_correct(): messagebox.showwarning("PrYE", "Jeu invalide") return self.next_player() def cheat(self): """Affiche les noms des joueurs prouvés.""" prouve = self.demo.conclusion() if prouve is None: msg = "La preuve contient une contradiction" else: msg = "" for index, val in enumerate(prouve): if val: msg += self.player_names[index] + " " tk.messagebox.showinfo("cheat", msg) def next_player(self): """Passe au joueur suivant.""" if self.deck.is_finished(): self.fin_manche() return self.proof.reset_added() self.cards_played = 0 self.unbind("<Escape>") self.can.delete("pile") if self.liar[self.num_player] > 0: self.liar[self.num_player] -= 1 self.num_player = (self.num_player + 1) % 4 self.hands[self.num_player].extend(self.deck.draw(2)) self.can.display_cards("hand", self.hands[self.num_player]) self.can.display_current_player(self.num_player) if self.ordi_player[self.num_player]: self.can.reset_bind() self.ordi_plays() else: self.can.init_bind() def ordi_plays(self): """Fait jouer l'ordinateur.""" ordi = Ordi(self.proof, self.hands[self.num_player], self.num_player, self.scores, self.liar) msg, special_cards = ordi.joue(self.player_names) qed_played = False for special in special_cards: if special == "QED": qed_played = True elif special == "Truth": self.liar[self.num_player] = 0 else: # special == ("Liar", num_player) num_other = special[1] self.liar[num_other] = 3 for num_premise in range(4): cards = self.proof.premises[num_premise] if qed_played and num_premise == 3: cards = cards + [Card("QED")] self.can.display_cards("premise", cards, num_premise) self.can.display_current_player(self.num_player) self.can.display_cards("hand", self.hands[self.num_player]) messagebox.showinfo(self.player_names[self.num_player], msg) if qed_played: self.fin_manche() else: self.next_player() def fin_manche(self): """Fin de la manche, affichage des gagnants et du score.""" provens = self.demo.conclusion() if provens is None: msg = "La preuve contient une contradiction,\ personne ne marque de point" else: score = self.proof.score() winers = "" for index, proven in enumerate(provens): if proven: winers += self.player_names[index] + " " self.scores[index] += score if winers: msg = winers + "\nBravo, vous marquez {} points".format(score) else: msg = "Personne n'est prouvé, personne ne marque de point" self.can.display_current_player(self.num_player) messagebox.showinfo("Fin de la manche", msg) score_max = max(self.scores) if score_max >= 50: self.fin_partie(score_max) else: self.init_round() def fin_partie(self, score_max): """Affiche le nom des gagnants et ferme la fenêtre. :param score_max: le score du ou des gagnant(s) :type score_max: int """ winers = "" for index, score in enumerate(self.scores): if score == score_max: winers += self.player_names[index] + " " msg = winers + "\nBravo, vous avez gagné !" messagebox.showinfo("Fin de la partie", msg) self.quitter() def version(self): """Affiche la version du jeu""" messagebox.showinfo("PrYE", "Version finale 31/05/19") def rules(self): """Affiche les règles du jeu dans le navigateur wenb par défaut.""" webbrowser.open("regles_prye.html") def quitter(self): """Quitte""" self.quit() self.destroy()
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()
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)
# 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':
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'")