def backtracking(problem): start_time = time.time() csp.backtracking_search(problem, select_unassigned_variable=csp.mrv, order_domain_values=csp.lcv, inference=csp.forward_checking) #problem.display(problem.infer_assignment()) csp.AC3(problem) #problem.display(problem.infer_assignment()) solution = problem.infer_assignment() end_time = time.time() elapsed_time = end_time - start_time file_sudoku_print("backtracking", elapsed_time, solution)
def scheduleCourses(file, slots): f = open(file, "r") variables = [] domains = {} courseList = f.readlines() for line in range(len(courseList)): course = courseList[line].split(";") variables.append(course[1]) for var in variables: domains[var] = list(range(1, int(slots))) neighbors = variables.remove(var) scheduler = courseSchedule(variables, domains, neighbors) csp.backtracking_search(scheduler, select_unassigned_variable=csp.mrv, order_domain_values=csp.unordered_domain_values, inference=csp.AC3) csp.backtracking_search(scheduler, select_unassigned_variable=csp.first_unassigned_variable, order_domain_values=csp.lcv, inference=csp.AC3)
def bs(domains): print('\n\nBS') australia_bs = copy.copy(australia_csp) australia_bs.domains = domains result = backtracking_search(australia_bs) print("Current domains:", australia_bs.curr_domains) print("Result:", result)
def test_suite(): """ This function will run through all the pre-planned garden beds from gardeners.com several times and average the results for each. It was used to test performance improvement """ print("Running test suite, this will take some time... (15-25 minutes depending on computer speed)") print("Selecting default sun facing of South") print("Enabling minimum-remaining-values heuristic") print("Enabling degree heuristic") print("Enabling least contraining value heuristic") direction_selection = "South" results = {} for g in preplanned_gardens: counts = [] success_rate = [] for i in range(10): garden = Garden(preplanned_gardens[g], direction_selection) garden.minimum_remaining_values = True garden.degree_heuristic = True garden.least_constraining_value = True plan, cnt = csp.backtracking_search(garden) if plan is None: success_rate.append(False) else: success_rate.append(True) counts.append(cnt) results[g] = {"success_rate": "{}".format(success_rate.count(True)/len(success_rate)), "time": int(sum(counts)/len(counts))} print("\n") for g in results: print(g) print(results[g]) print("Success rate is the fraction of times a solution was found within the time contraints") print("A solution may not exists for all scenerios") print("'time' is the number of calls to backtrack()")
def start(self, inf): s = SudokuCSP(self.original_board) if AC3(s): if s.is_solved(): print(" ") print("\nSolution found with AC3") else: self.start = timer() a = backtracking_search( s, select_unassigned_variable=mrv, order_domain_values=unordered_domain_values, inference=inf) self.end = timer() if a: print(" ") print("\nSolution found") for i in range(9): print(" ") for j in range(9): name = i * 9 + j print(" " + str(a["CELL" + str(name)]) + " ", end='') else: print( "\nPlease check the sudoku initial board, solution not found!" ) self.bt = s.n_bt
def solve(input_file, output_file): p = Problem(input_file) domain_state = True result = set() while (p.iterate_domain()): if not p.conditions(): continue result = csp.backtracking_search(p, select_unassigned_variable=csp.mrv, order_domain_values=csp.lcv, inference=csp.forward_checking) if result: break # result = csp.backtracking_search(p, # select_unassigned_variable = csp.mrv, # order_domain_values = csp.lcv, # inference = csp.forward_checking) # while(not p.conditions()): # domain_state = p.iterate_domain() # while(domain_state or len(result)==0): # result = csp.backtracking_search(p, # select_unassigned_variable = csp.mrv, # order_domain_values = csp.lcv, # inference = csp.forward_checking) # domain_state = p.iterate_domain() p.dump_solution(output_file, result)
def solve(input_file, output_file): # Start counting the running time startTime = datetime.now() # Possible hours, in a descending order, in order to optimize the schedule for earliest timetable slots b_list = get_possible_shift_hours(input_file) for b in b_list: # Return the reading pointer to the beginning input_file.seek(0) p = Problem(input_file, b) p.result = csp.backtracking_search( p, select_unassigned_variable=csp.first_unassigned_variable, order_domain_values=csp.unordered_domain_values, inference=csp.no_inference) # Try getting a solution if p.result == None: # Stop running the code when no solution is found for the current latest hour b break else: # Save a copy when a solution exists prev_p = p.copy() # Output the best working solution prev_p.dump_solution(output_file) # See how much time our code took to get the solution print(datetime.now() - startTime)
def backtracking_solve(k, n): global bs_time knights = Knights(k, n) if DEBUG: print 'Knights:' if DEBUG: knights.display() t0 = time.time() print 'backtracking_search...' solution = csp.backtracking_search(knights, options['var order'], options['val order'], options['inference']) if DEBUG: print '' if solution: knights.update_knights_with_assignment(solution) if DEBUG: knights.display(solution) if solution: sol = extract_solution(solution) # print 'Solution:', solution else: if DEBUG: print 'BS: No solution found.' sol = None bs_time = time.time() - t0 if DEBUG: print 'BS time: ' + PRECISION % bs_time if DEBUG: print '' return sol
def kenken_forward__checking_mrv(self): self.__display( csp.backtracking_search( self, select_unassigned_variable=csp.mrv, order_domain_values=csp.unordered_domain_values, inference=csp.forward_checking))
def kenken_mac(self): self.__display( csp.backtracking_search( self, select_unassigned_variable=csp.first_unassigned_variable, order_domain_values=csp.unordered_domain_values, inference=csp.mac))
def start(self, inf): s = SudokuCSP(self.original_board) self.start = timer() a = backtracking_search(s, select_unassigned_variable=mrv, order_domain_values=unordered_domain_values, inference=inf) self.end = timer() if a: if (inf == mac): solution = "mac" if (inf == forward_checking): solution = "forward_checking" if (inf == no_inference): solution = "no_inference" #print("\nSolution found by "+solution) # displaySudoku(a) else: print( "\n Please check the sudoku initial board, solution not found!" ) self.bt = s.n_bt
def main(): f = open("input/input90.txt", "r") Lines = f.readlines() f.close() print("Reading file") graph, color = readFile(Lines) print("File reading complete! Start CSP graph coloring.") variables = graph.vertices() domains = {} for variable in variables: domains[variable] = [i for i in range(color)] csp = CSP(variables, domains) for constraint in graph.edges(): (vertex1, vertex2) = tuple(constraint) csp.add_constraint(GraphColoringConstraint(vertex1, vertex2)) assignment = {} solution = backtracking_search(csp, assignment, domains) if solution is None: print("No solution!") else: print("Result of graph coloring:") print(sorted(solution.items(), key=operator.itemgetter(0))) if check(solution, graph): print("Algorithm correct!") else: print("Something went wrong!")
def calculate_desirability(self): print "PhalanxEvaluator::calculate_desirability" phalanx_csp = formation_csp(self.thinker.board.phalanx, self.thinker.board) # all formations are desirable if they can be achieved, and undesirable if they can't. if backtracking_search(phalanx_csp, select_unassigned_variable=mrv, inference=forward_checking): return 0.9 else: return 0.0
def calculate_desirability(self): print "ShortDykeEvaluator::calculate_desirability" short_dyke_csp = formation_csp(self.thinker.board.short_dyke, self.thinker.board) # all formations are desirable if they can be achieved, and undesirable if they can't. if backtracking_search(short_dyke_csp, select_unassigned_variable=mrv, inference=forward_checking): return 1.0 else: return 0.0
def try_csps(csps): for c in csps: assignment = backtracking_search( **c # order_domain_values=lcv, # select_unassigned_variable=mrv, # inference=mac ) print(assignment)
def testCSP(self): short_dyke_csp = formation_csp(self.board.short_dyke, self.board) result = backtracking_search(short_dyke_csp, select_unassigned_variable=mrv, inference=forward_checking) self.assertEqual(result[8], 8) self.assertEqual(result[9], 9) self.assertEqual(result[14], 14) self.assertTrue(result[17] in BLACK_MAP[17] and result[17] != result[23] and result[17] != result[29]) self.assertTrue(result[23] in BLACK_MAP[23] and result[23] != result[29] and result[23] != result[17]) self.assertTrue(result[29] in BLACK_MAP[29] and result[29] != result[17] and result[29] != result[23])
def solveBT(self): start = time.time() result = csp.backtracking_search(self,) end = time.time() print(result) print('total time in seconds for backtrack:') print(str(end - start))
def calculate_desirability(self): print "MillEvaluator::calculate_desirability" mill_csp = formation_csp(self.thinker.board.mill, self.thinker.board) # all formations are desirable if they can be achieved, and undesirable if they can't. if backtracking_search(mill_csp, select_unassigned_variable=mrv, inference=forward_checking): return 0.9 else: return 0.0
def main(): dictionary = {} readFile(openFile(), dictionary) length = int(len(dictionary)/2) domains = filterUnaryConstraints({i for i in itertools.product([0, 1], repeat=length)}) neighbors = createNeighbors(dictionary,length) dictionary = createDomain(dictionary, domains) problem = CSP(list(dictionary.keys()), dictionary, neighbors, constraints) result = backtracking_search(problem,select_unassigned_variable=mrv,order_domain_values=lcv,inference=mac) printAnswer(result, length)
def try_csps(csps): for c in csps: # myCSPs.eliminateVariables(state) assignment = backtracking_search(**c, order_domain_values=lcv, select_unassigned_variable=mrv, inference=mac) # print(assignment) final = assignment return final
def q1(puzzle): """ Solve the given puzzle with basic backtracking search :param puzzle (dictionary): The dictionary keys are tuples (row, column) representing the filled puzzle squares and the values are the corresponding numbers assigned to these squares. :return: a tuple consisting of a solution (dictionary) and the CSP object. """ csp = build_csp(puzzle) return csp.backtracking_search(), csp
def main(): if (len(sys.argv) != 3): print("Use the program as follows:") print("python scheduler.py <input file> <# of slots for courses>") exit() inputFile = sys.argv[1] slots = sys.argv[2] # Open the file and load line by line classInfos = list() with open(inputFile, "r") as f: for line in f: classInfos.append(line) classDicts = [] # This array will hold multiple dictionaries of class info for classInfo in classInfos: classInfo = classInfo.split(";") classDict = {} # This dictionary will contain key->vals for class info classDict["name"] = classInfo[0] classDict["number"] = classInfo[1] classDict["sections"] = classInfo[2] classDict["professors"] = parseProfessors(classInfo[5], classInfo[6]) if len(classInfo[7].rstrip()) == 0: classDict["areas"] = None else: classDict["areas"] = classInfo[7].rstrip().split(",") classDicts.append(classDict) # printClassDictionaries(classDict) mySchedule = Scheduler(classDicts, slots) # Uses MRV, LCV, and a custom inference function called "degree" backtracking_search(mySchedule, select_unassigned_variable=degree, order_domain_values=lcv, inference=no_inference) assignments = mySchedule.infer_assignment() output = open("output.txt", "w+") for course, time in assignments.items(): output.write(course + "," + str(time) + ";") print(course + ": time slot " + str(time))
def sudokuSolver(grid, alg): board = sudoku2(grid) if alg == "bfs": bfs(board) elif alg == "dfs": dfs(board) elif alg=="backtracking": backtracking(board) elif alg == "backtracking-ordered": start_time = time.time() csp.backtracking_search(board, select_unassigned_variable=csp.mrv, order_domain_values=csp.lcv, inference=csp.forward_checking) end_time = time.time() elapsed_time = (end_time-start_time) solution = board.infer_assignment() #put into format of input # for index in range(len(solution)): # print(solution[index]) file_sudoku_print("BT-ordered", elapsed_time, solution) elif alg == "backtracking-noOrdering": #no value and variable ordering start_time = time.time() csp.backtracking_search(board, select_unassigned_variable=csp.first_unassigned_variable, order_domain_values=csp.unordered_domain_values, inference=csp.forward_checking) end_time = time.time() solution = board.infer_assignment() elapsed_time = print(end_time-start_time) file_sudoku_print("BT-noOrder", elapsed_time, solution) elif alg == "backtracking-reverse": start_time = time.time() csp.backtracking_search(board, select_unassigned_variable=csp.lcvar, order_domain_values=csp.mcv, inference=csp.forward_checking) solution = board.infer_assignment() end_time = time.time() elapsed_time = end_time-start_time file_sudoku_print("BT-reverse", elapsed_time, solution)
def q3(puzzle): """ Solve the given puzzle with backtracking search and MRV ordering and AC-3 as a preprocessing step. :param puzzle (dictionary): The dictionary keys are tuples (row, column) representing the filled puzzle squares and the values are the corresponding numbers assigned to these squares. :return: a tuple consisting of a solution (dictionary) and the CSP object. """ csp = build_csp(puzzle) csp.ac3_algorithm() return csp.backtracking_search("MRV"), csp
def combined_solve(k, n): """Combines AC3 with backtracking search.""" problem = Knights(k, n) print "Combined solve" t0 = time.time() csp.AC3(problem) # print problem.vars # print problem.neighbours # print problem.domains print time.time() - t0 solution = csp.backtracking_search(problem) print time.time() - t0 return solution
def main(): problem = Problem('p2.txt') csp = CSP(problem.vars, problem.domains, problem.neighbors, problem.constraints) result = backtracking_search(csp, select_unassigned_variable=mrv, order_domain_values=lcv, inference=mac) for result_index in range(problem.board_length): row = '' for value_index in range(len(result[result_index])): row = row + str(result[result_index][value_index]) print(row)
def optimize_preplanned(): print("Which garden?") for idx, garden in enumerate(preplanned_gardens): print("{}. {}".format(idx, garden)) while True: try: choice = int(input(">> ")) garden_selection = preplanned_gardens[list(preplanned_gardens.keys())[int(choice)]] except ValueError: print("Invalid Input") continue except IndexError: print("Invalid Selection") continue else: break directions = ["North", "East", "South", "West", "North-East", "North-West", "South-East", "South-West"] print("From what direction does the sun predominatly shine on the garden?") for idx, direction in enumerate(directions): print("{}. {}".format(idx, direction)) while True: try: choice = int(input(">> ")) direction_selection = directions[choice] except ValueError: print("Invalid Input") continue except IndexError: print("Invalid Selection") continue else: break garden = Garden(garden_selection, direction_selection) print("Creating a CSP with the following garden: ") print("Layout:\n", garden.layout) print("Selected plants:\n", garden.selected_plants) print("Positions of the sun:\n", garden.sun_positions) garden.minimum_remaining_values = False garden.degree_heuristic = False garden.least_constraining_value = False plan, cnt = csp.backtracking_search(garden) if plan is None: print("Unable to create garden plan that satisfies all constraints") else: print("plan: ", plan) for a in plan: garden.layout[a[0], a[1]] = int(plan[a].height) print(garden.layout)
def solve(input_file, output_file): p = Problem(input_file) p.upper_bound = 4 down = False up = False p.solution = csp.backtracking_search(p, csp.first_unassigned_variable, csp.unordered_domain_values) if p.solution != None: # Solution exists must decrease bound p.upper_bound -= 1 down = True else: # Solution does not exist must increase bound p.upper_bound += 1 up = True while True: p.solution = csp.backtracking_search(p, csp.first_unassigned_variable, csp.unordered_domain_values) if down: if p.solution != None: p.upper_bound -= 1 print("Upper Bound ", p.upper_bound) else: p.upper_bound += 1 print("Upper Bound ", p.upper_bound) p.solution = csp.backtracking_search( p, csp.first_unassigned_variable, csp.unordered_domain_values) break elif up: if p.solution == None: p.upper_bound += 1 print("Upper Bound ", p.upper_bound) else: break print(p.solution) p.dump_solution(output_file)
def solve_sudoku(self): s = SudokuCSP(self.current_board) inf, dv, suv = None, None, None if self.inference.get() == "NO_INFERENCE": inf = no_inference elif self.inference.get() == "FC": inf = forward_checking elif self.inference.get() == "MAC": inf = mac if self.var_to_choose.get() == "MRV": suv = mrv start = timer() a = backtracking_search(s, select_unassigned_variable=suv, order_domain_values=unordered_domain_values, inference=inf) end = timer() # if a isn't null we found a solution so we will show it in the current board # if a is null then we send a message to the user that the initial board # breaks some constraints if a: for i in range(9): for j in range(9): index = i * 9 + j self.current_board[i][j] = a.get("CELL" + str(index)) else: messagebox.showerror( "Error", "Invalid sudoku puzzle, please check the initial state") # showing solution self.__draw_puzzle() self.time.set("Time: " + str(round(end - start, 5)) + " seconds") self.n_bt.set("N. BR: " + str(s.n_bt)) # re-enabling buttons for search a new solution for rb in self.radio: rb.config(state=NORMAL) self.clear_button.config(state=NORMAL) self.solve_button.config(state=NORMAL) self.menu_bar.entryconfig("Level", state="normal")
def solve(input_file, output_file): p = Problem(input_file) # Place here your code that calls function csp.backtracking_search(self, ... I = p.latest_time_slot for i in range(I): prob = deepcopy(p) # reduce latest time slot by 1 with each iteration prob.latest_time_slot = I - i # new csp solution prob.solution = csp.backtracking_search(prob, csp.mrv, csp.unordered_domain_values, csp.forward_checking) if prob.solution is not None: # update solution p.solution = deepcopy(prob.solution) continue else: break p.dump_solution(output_file)
def scheduleCourses(filename, slots): sections = [] lines = [line.rstrip('\n') for line in open(filename)] for course in lines: components = course.split(";") course_code = components[0] profs = components[5].split(",") prof_sections = components[6].split(",") if len(components) == 8: areas = components[7] else: areas = "" for i in range(0, len(profs)): profs[i] = profs[i].strip() for i in range(0, len(prof_sections)): prof_sections[i] = int(prof_sections[i].strip(), 10) index = 1 for i in range(0, len(profs)): prof = profs[i] num_sec = prof_sections[i] for j in range(0, num_sec): string = course_code + "-" + prof + "-" + str( index) + "-" + areas sections.append(string) index += 1 schedulingCSP = CourseScheduling(sections, slots) result, num = csp.backtracking_search(schedulingCSP, "course-scheduling") schedule = schedulingCSP.display(result) f = open("Course-Schedule.txt", "w") f.write("Course Schedule assuming " + str(slots) + " time slots with mrv heuristics and degree heuristic as " "tiebreaker\n") f.write(schedule + "\n") f.write("\n") f.close() print("Course Scheduling finished")
def combined_solve(k, n): global cs_time knights = Knights(k, n) # first_unassigned_variable / mrv # unordered_domain_values / lcv # no_inference / forward_checking / mac # print 'Knights:' if DEBUG: knights.display() t0 = time.time() print 'combined search...' if DEBUG: print 'CS: AC3...' csp.AC3(knights) if DEBUG: print 'CS: Backtracking search...' solution = csp.backtracking_search(knights, options['var order'], options['val order'], options['inference']) if DEBUG: print '' if solution: knights.update_knights_with_assignment(solution) if DEBUG: knights.display(solution) if solution: sol = extract_solution(solution) # print 'Solution:', solution else: if DEBUG: print 'CS: No solution found.' sol = None cs_time = time.time() - t0 if DEBUG: print 'CS time: ' + PRECISION % cs_time if DEBUG: print '' return sol
cur_vars.append(cur_var) cur_func = substrings[1] if cur_func == "\'\'": cur_func = 'const' cur_res = int(substrings[2]) cur_cage = [cur_vars, cur_func, cur_res] cages.append(cur_cage) #BT print("Solving with BT...") problem_BT = KenKen(size, cages) start = time.time() result_BT = csp.backtracking_search(problem_BT) end = time.time() print("Solved with BT in %d seconds with %d assignments.\n" % (end - start, problem_BT.nassigns)) #BT+MRV print("Solving with BT+MRV...") problem_BTMRV = KenKen(size, cages) start = time.time() result_BTMRV = csp.backtracking_search( problem_BTMRV, select_unassigned_variable=csp.mrv) end = time.time() print("Solved with BT+MRV in %d seconds with %d assignments.\n" % (end - start, problem_BTMRV.nassigns)) #FC
def testCSP(self): short_dyke_csp = formation_csp(self.board.short_dyke, self.board) result = backtracking_search(short_dyke_csp, select_unassigned_variable=mrv, inference=forward_checking) self.assertEqual(result, None)
def test_forward_checking_backtracking(self): csp.backtracking_search(self.const_problem1, csp.forward_check) self.assertTrue( self.const_problem1.is_completely_consistently_assigned())
from keisuke1 import Keisuke from csp import backtracking_search, forward_checking, mrv,min_conflicts N=5 p = Keisuke(N,[13,23,233,3221,21222],[12,21,22,232,3132,33313]) #N=3 #p = Keisuke(N,[231,458,72],[357]) #p = Keisuke(N,[2,5,8],[23,51]) #p = Keisuke(N,[231,458,272],[357,182]) s = backtracking_search(p,select_unassigned_variable=mrv,inference=forward_checking) #s = backtracking_search(p,select_unassigned_variable=mrv) #s = backtracking_search(p,inference=forward_checking) #s = backtracking_search(p) #s =min_conflicts(p) print s print p.nassigns