def solveMinCon(self): start = time.time() result = csp.min_conflicts(self,) end = time.time() print(result) print('total time in seconds for min-conflicts:') print(str(end - start))
times = '800MWF, 900MWF, 1030MWF, 1130MWF, 830TT, 1030TT,'.split() rooms = 'NH253 SB382'.split() domainsList = [] # Create every permutation of professor, time, and room for p in profs: for t in times: for r in rooms: key = p + t + r domainsList.append( key ) variables = ['cs108', 'cs112', 'cs104', 'cs212', 'cs214', 'cs262', 'cs232'] domains = {} # Assign each class to all the domain permutations for var in variables: domains[var] = domainsList neighbors = parse_neighbors("""cs108: DS,800MWF,NH253""", variables) for type in [domainsList, variables]: for A in type: for B in type: if A != B: if B not in neighbors[A]: neighbors[A].append(B) if A not in neighbors[B]: neighbors[B].append(A) problem = CSP(variables, domains, neighbors, schedule_constraint) result = min_conflicts(problem, max_steps=1000) print("Min conflicts:") printResult( result)
B_Course = B if(A_Prof == B_Prof and A_Slot == B_Slot): return False if(A_Room == B_Room and A_Slot == B_Slot): return False if('norman' in a and A == 'cs108'): return True if('adams' in a and A == 'cs112'): return True if('adams' in a and A == 'cs214'): return True if('pruim' in a and A == 'stat343'): return True if('vanderlinden' in a and A == 'cs336'): return True if('schuurman' in a and A == 'cs300'): return True if(A in courses and B in courses): return False if(recurse == 0): return scheduler_constraints(B, b, A, a, 1) return True return CSP(variables, domains, neighbors, scheduler_constraints) if __name__ == "__main__": schedule = Scheduler() solution = min_conflicts(schedule) print(solution)
elif (puzzle == 3): kenken = KenKen(given6x6()) else: kenken = KenKen(expert9x9()) solution = [] if (algorithm == 1): solution = csp.backtracking_search(kenken) elif (algorithm == 2): solution = csp.backtracking_search(kenken, select_unassigned_variable=csp.mrv) elif (algorithm == 3): solution = csp.backtracking_search(kenken, inference=csp.forward_checking) elif (algorithm == 4): solution = csp.backtracking_search(kenken, select_unassigned_variable=csp.mrv, inference=csp.forward_checking) elif (algorithm == 5): solution = csp.backtracking_search(kenken, inference=csp.mac) else: solution = csp.min_conflicts(kenken) kenken.displayMatrix(solution) end = time.time() elapsed_time = end - start print("Elapsed Time:", elapsed_time) print("nassigns:", kenken.nassigns) print("Constraint Calls:", kenken.constraint_calls)
from csp import backtracking_search, NQueensCSP, min_conflicts, mrv, \ forward_checking, AC3 from search import depth_first_graph_search import logging # 1. Set up the problem. n = 8 problem = NQueensCSP(n) # 2. Solve the problem. # There is a bug in the DFS code (even for 1-queens), so skip this one. #solution = depth_first_graph_search(problem) #solution = AC3(problem) #solution = backtracking_search(problem) solution = min_conflicts(problem) # 3. Print the results. # Handle AC3 solutions (boolean values) first, they behave differently. if type(solution) is bool: if solution and problem.goal_test(problem.infer_assignment()): print('AC3 Solution:') else: print('AC Failure:') print(problem.curr_domains) # Handle other solutions next. elif solution != None and problem.goal_test(solution): print('Solution:') print(solution) # problem.display(problem.infer_assignment())
for type in [variables]: for A in type: for B in type: if A != B: if B not in neighbors[A]: neighbors[A].append(B) if A not in neighbors[B]: neighbors[B].append(A) def scheduler_constraint(A, a, B, b, recurse=0): conflict = (a == b) if (a.split()[0] == b.split()[0]) and (a.split()[2] == b.split()[2]): return conflict if (a.split()[1] == b.split()[1]) and (a.split()[2] == b.split()[2]): return conflict if recurse == 0: return scheduler_constraint(B, b, A, a, 1) return True return CSP(variables, domains, neighbors, scheduler_constraint) print(backtracking_search(scheduler())) #print(AC3(scheduler())) print(min_conflicts(scheduler()))
#MAC print("Solving with MAC...") problem_MAC = KenKen(size, cages) start = time.time() result_MAC = csp.backtracking_search(problem_MAC, inference=csp.mac) end = time.time() print("Solved with MAC in %d seconds with %d assignments.\n" % (end - start, problem_MAC.nassigns)) #Min Conflicts print("Solving with Min Conflicts...") problem_MIN = KenKen(size, cages) max_steps = 10000 start = time.time() result_MIN = csp.min_conflicts(problem_MIN, max_steps) end = time.time() if result_MIN != None: print( "Solved with Min Conflicts in %d seconds with %d assignments.\n" % (end - start, problem_MIN.nassigns)) else: print("Min Conficts could not find a solution after %d steps.\n" % (max_steps)) print("\nSollution:\n") for i in range(size): for j in range(size): for (var, val) in result_BT.items(): if var == "X%d%d" % (i + 1, j + 1): print("%s = %d" % (var, val), end=" ")
#checks time/room if A[1] == B[1] and A[2] == A[2]: return False return True return CSP(variables, domains, neighbors, schedule_constraint) def print_solution(result): variables = 'cs108 cs112 cs212 cs214 cs232 cs262'.split() for h in variables: print('Course', h) for (var, val) in result.items(): if val == h: print('\t', var) puzzle = Schedule() #result = depth_first_graph_search(puzzle) #result = AC3(puzzle) #result = backtracking_search(puzzle) result = min_conflicts(puzzle, max_steps=1000) if puzzle.goal_test(puzzle.infer_assignment()): print("Solution:\n") print_solution(result) else: print("failed...") print(puzzle.curr_domains) puzzle.display(puzzle.infer_assignment())
def gather(iterations, out): """ Benchmark each one of the following algorithms for various kenken puzzles * For every one of the following algorithms * For every possible size of a kenken board * Create 'iterations' random kenken puzzles of the current size and evaluate the algorithm on each one of them in order to get statistically sound data. Then calculate the average evaluation of the algorithm for the current size. * Save the results into a csv file """ bt = lambda ken: csp.backtracking_search(ken) bt_mrv = lambda ken: csp.backtracking_search( ken, select_unassigned_variable=csp.mrv) fc = lambda ken: csp.backtracking_search(ken, inference=csp.forward_checking) fc_mrv = lambda ken: csp.backtracking_search( ken, inference=csp.forward_checking, select_unassigned_variable=csp.mrv) mac = lambda ken: csp.backtracking_search(ken, inference=csp.mac) mconflicts = lambda ken: csp.min_conflicts(ken) algorithms = { "BT": bt, "BT+MRV": bt_mrv, "FC": fc, "FC+MRV": fc_mrv, "MAC": mac, "MIN_CONFLICTS": mconflicts } with open(out, "w+") as file: out = writer(file) out.writerow([ "Algorithm", "Size", "Result", "Constraint checks", "Assignments", "Completion time" ]) for name, algorithm in algorithms.items(): for size in range(3, 10): checks, assignments, dt = (0, 0, 0) for iteration in range(1, iterations + 1): size, cliques = generate(size) assignment, data = benchmark(Kenken(size, cliques), algorithm) print("algorithm =", name, "size =", size, "iteration =", iteration, "result =", "Success" if assignment else "Failure", file=stderr) checks += data[0] / iterations assignments += data[1] / iterations dt += data[2] / iterations out.writerow([name, size, checks, assignments, dt])
def kenken_minConflicts(self): self.__display(csp.min_conflicts(self))
def solve_kenken(k): """ Solve a given Kenken CSP using a variety of algorithms """ # solve csp with BT algorithm print("Solving with BT algorithm...") start_time = time.clock() BT_ans = backtracking_search(k) end_time = time.clock() print("BT algorithm runtime: " + str(end_time - start_time) + " seconds") print("In this time, constraints got checked " + str(k.get_constraint_checks()) + " times and " + str(k.get_number_of_assignments()) + " assignments occurred") k.reset_constraint_checks() k.reset_number_of_assignments() print("\tBT = ", BT_ans) if BT_ans != None: k.display(BT_ans) # solve csp with BT+MRV algorithm print("Solving with BT+MRV algorithm...") start_time = time.clock() BT_MRV_ans = backtracking_search(k, select_unassigned_variable=mrv) end_time = time.clock() print("BT+MRV algorithm runtime: " + str(end_time - start_time) + " seconds") print("In this time, constraints got checked " + str(k.get_constraint_checks()) + " times and " + str(k.get_number_of_assignments()) + " assignments occurred") k.reset_constraint_checks() k.reset_number_of_assignments() print("\tBT_MRV_ans = ", BT_MRV_ans) if BT_MRV_ans != None: k.display(BT_MRV_ans) # solve csp with FC algorithm print("Solving with FC algorithm...") start_time = time.clock() FC_ans = backtracking_search(k, inference=forward_checking) end_time = time.clock() print("FC algorithm runtime: " + str(end_time - start_time) + " seconds") print("In this time, constraints got checked " + str(k.get_constraint_checks()) + " times and " + str(k.get_number_of_assignments()) + " assignments occurred") k.reset_constraint_checks() k.reset_number_of_assignments() print("\tFC_ans = ", FC_ans) if FC_ans != None: k.display(FC_ans) # solve csp with FC+MRV algorithm print("Solving with FC+MRV algorithm...") start_time = time.clock() FC_MRV_ans = backtracking_search(k, select_unassigned_variable=mrv, inference=forward_checking) end_time = time.clock() print("FC+MRV algorithm runtime: " + str(end_time - start_time) + " seconds") print("In this time, constraints got checked " + str(k.get_constraint_checks()) + " times and " + str(k.get_number_of_assignments()) + " assignments occurred") k.reset_constraint_checks() k.reset_number_of_assignments() print("\tFC_MRV_ans = ", FC_MRV_ans) if FC_MRV_ans != None: k.display(FC_MRV_ans) # solve csp with MAC algorithm print("Solving with MAC algorithm...") start_time = time.clock() MAC_ans = backtracking_search(k, inference=mac) end_time = time.clock() print("MAC algorithm runtime: " + str(end_time - start_time) + " seconds") print("In this time, constraints got checked " + str(k.get_constraint_checks()) + " times and " + str(k.get_number_of_assignments()) + " assignments occurred") k.reset_constraint_checks() k.reset_number_of_assignments() print("\tMAC_ans = ", MAC_ans) if MAC_ans != None: k.display(MAC_ans) # solve csp with MINCONFLICTS algorithm print("Solving with MINCONFLICTS...") start_time = time.clock() minconflicts_ans = min_conflicts(k) end_time = time.clock() print("MINCONFLICTS runtime: " + str(end_time - start_time) + " seconds") print("In this time, constraints got checked " + str(k.get_constraint_checks()) + " times and " + str(k.get_number_of_assignments()) + " assignments occurred") k.reset_constraint_checks() k.reset_number_of_assignments() print("\tMINCONFLICTS_ans = ", minconflicts_ans) if minconflicts_ans != None: k.display(minconflicts_ans)
return False if B == 'cs112' and b[0] != 'Adams': return False if A == 'cs212' and a[0] != 'Plantinga': return False if B == 'cs212' and b[0] != 'Plantinga': return False if A == 'cs214' and a[0] != 'Schuurman': return False if B == 'cs214' and b[0] != 'Schuurman': return False # a professor cannot teach two classes at the same time if a[0] == b[0] and a[1] == b[1]: return False # Two classes cannot be in the same room at the same time if a[1] == b[1] and a[2] == b[2]: return False return True return CSP(classes, domains, neighbors, schedule_constraint) result = min_conflicts(schedule(), max_steps=1000) if result is None: print("No solution found") else: print("Solution!") print(result)
return False # Check if same time and room if ((splitA[1] == splitB[1]) and (splitA[2] == splitB[2])): return False return True def get_csp(self): return CSP(self.get_variables(), self.get_domains(), self.get_neighbors(), self.constraint_check) if __name__ == '__main__': # the stuff to be scheduled ... courses = [ "CS-108", "CS-112", "CS-212", "CS-214", "CS-232", "CS-336", "CS-344" ] timeslots = ["MWF9AM", "MWF1030AM", "MWF130PM", "TTH1030AM", "TTH130PM"] professors = ["Plantinga", "Adams", "Norman", "VanderLinden", "Schuurman"] classrooms = ["SB-410", "SB-411"] t = time.time() Scheduler = Scheduler(courses, timeslots, professors, classrooms) solution = min_conflicts(Scheduler.get_csp()) total_time = time.time() - t if solution is not None: print('Schedule found:\t' + str(solution) + '\n\ttime: ' + str(total_time))
from csp import Sudoku, easy1, AC3, harder1, backtracking_search, mrv, \ forward_checking, min_conflicts from search import depth_first_graph_search # 1. Set up the puzzle. #puzzle = Sudoku('483921657967345821251876493548132976729564138136798245372689514814253769695417382') # solved (Figure 6.4.b) #puzzle = Sudoku('..3.2.6..9..3.5..1..18.64....81.29..7.......8..67.82....26.95..8..2.3..9..5.1.3..') # easy (Figure 6.4.a) puzzle = Sudoku('4173698.5.3..........7......2.....6.....8.4......1.......6.3.7.5..2.....1.4......') # harder (csp.py) #puzzle = Sudoku('1....7.9..3..2...8..96..5....53..9...1..8...26....4...3......1..4......7..7...3..') # hardest (AI Escargot) print('Start:') puzzle.display(puzzle.infer_assignment()) # 2. Solve the puzzle. #depth_first_graph_search(puzzle) #AC3(puzzle) #backtracking_search(puzzle) min_conflicts(puzzle) # 3. Print the results. print if puzzle.goal_test(puzzle.infer_assignment()): print('Solution:') puzzle.display(puzzle.infer_assignment()) else: print('Failed - domains: ' + str(puzzle.curr_domains)) puzzle.display(puzzle.infer_assignment())
from csp import backtracking_search, NQueensCSP, min_conflicts, mrv, \ forward_checking, AC3 from search import depth_first_graph_search import logging # 1. Set up the problem. n = 40 problem = NQueensCSP(n) # 2. Solve the problem. # There is a bug in the DFS code (even for 1-queens), so skip this one. #solution = depth_first_graph_search(problem) #solution = AC3(problem); #solution = backtracking_search(problem, inference=forward_checking) solution = min_conflicts(problem, max_steps=10) # 3. Print the results. # Handle AC3 solutions (boolean values) first, they behave differently. if type(solution) is bool: if solution and problem.goal_test(problem.infer_assignment()): print('AC3 Solution:') else: print('AC Failure:') print(problem.curr_domains) # Handle other solutions next. elif solution != None and problem.goal_test(solution): print('Solution:') print(solution) # problem.display(problem.infer_assignment())
"SA", "Q", "NSW", "V", "T", ] # Domains domains = {var: ["red", "green", "blue"] for var in variables} # Neighbors neighbors = { "WA": ["SA", "NT"], "NT": ["WA", "SA", "Q"], "SA": ["WA", "NT", "Q", "NSW", "V"], "Q": ["NT", "SA", "NSW"], "NSW": ["Q", "SA", "V"], "V": ["SA", "NSW"], "T": [] } def constraintFunc(var1, val1, var2, val2): return var2 not in neighbors[var1] or val1 != val2 problem = csp.CSP(variables, domains, neighbors, constraintFunc) # print(csp.backtracking_search(problem)) print(csp.min_conflicts(problem, 100000))
def test_min_conflicts(self): csp.min_conflicts(self.const_problem1, 100) self.assertTrue( self.const_problem1.is_completely_consistently_assigned())
def scheduling_constraints(courseA, variableA, courseB, variableB): """ if the courses have the same room, same time, that fails the requirements if the courses have the same prof, same time, that fails the requirements if the courses have the wrong prof, that also fails the requirements """ # check if they are in the same room or with the same faculty member at the same time if variableA[TIME] == variableB[TIME] and (variableA[ROOM] == variableB[ROOM] or variableA[PROF] == variableB[PROF]): return False # check that each course is with the correct professor if variableA[PROF] != assignments[courseA] or variableB[PROF] != assignments[courseB]: return False # if it didn't fail yet, it's valid return True result = min_conflicts(CSP(courses, domains, neighbors, scheduling_constraints)) print(result) """ An explanation of the reasoning of this solution should start at the end. Because of the requirements, the min_conflicts function and the CSP class are necessary components of the solution. To decide how to go about filling the requirements of the CSP class constructor, I looked at the Sudoku, Queens, and Zebra problems. The Sudoku was a particularly helpful one. The Zebra problem wsa confusing because of documentation issues, and the queens problem sent me down the wrong track with building a subclass of CSP. Making the list of requirements was very straightforward from the problem description. From there, the problem got more complicated to approach. It make sense to have the courses be the variables because they are fixed and the other parameters need to be assigned to them. Once we were told that it worked to make all the combinations of faculty, time, and room domains, the rest of it could use strategies from the Zebra problem, but actually simpler. As you can see by running the code, this solution works and gives a schedule that fills the requirements. """
for prof in Faculty: for time in Timeslot: for room in Rooms: # appending professor, time slot, room number to the course domains[course].append([prof, time, room]) # creating neighbors with each class to be neighbor to all other classes neighbors = parse_neighbors( """ cs108:cs112; cs108:cs212; cs108:cs344; cs108:cs214; cs112:cs212; cs112:cs344; cs112:cs214; cs212:cs344; cs212:cs214; cs344:cs212""", variable) def scheduling_constraints(courseA, a, courseB, b): # check if the assigned professor to the course and the professor in domain value are the same if (a[0] != Assignement[courseA]) or (b[0] != Assignement[courseB]): return False # check if the faculty and time slot are the same for different classes, then return false if a[0] == b[0] and a[1] == b[1]: return False # check if the time slot and the room number are the same for different classes, then return false if a[1] == b[1] and a[2] == b[2]: return False return True return CSP(variable, domains, neighbors, scheduling_constraints) # printing out the result result = min_conflicts(Scheduling()) print(result)
a = kenken((hard())) elif (number == 3): a = kenken(exerc_map()) else: a = kenken(expert()) if (number1 == 1): b = csp.backtracking_search(a) elif (number1 == 2): b = csp.backtracking_search(a, select_unassigned_variable=csp.mrv) elif (number1 == 3): b = csp.backtracking_search(a, inference=csp.forward_checking) elif (number1 == 4): b = csp.backtracking_search(a, select_unassigned_variable=csp.mrv, inference=csp.forward_checking) elif (number1 == 5): b = csp.backtracking_search(a, inference=csp.mac) else: b = csp.min_conflicts(a) if (b is not None): a.display(b) else: print("No solutions found") elapsed_time = time.time() - start_time print("\nNumber of assignments:", a.nassigns) print("Number of Constraint calls:", a.nconstraintscal) print("Time to solve:", elapsed_time, "seconds")