def initialize_sudoku(): csp = CSP() N = 4 BLOCK = 2 rule = "x != y" for i in range(N): for j in range(N): csp.add_variable("(%s, %s)" % (i, j), list(range(N))) for x1 in range(N): for y1 in range(N): for x2 in range(N): for y2 in range(N): neighbors = False if x1 == x2: neighbors = True if y1 == y2: neighbors = True if x1 // BLOCK == x2 // BLOCK and y1 // BLOCK == y2 // BLOCK: neighbors = True if neighbors: csp.add_constraint("(%s, %s)" % (x1, y1), "(%s, %s)" % (x2, y2), rule) csp.export_to_json("sudoku.json") csp.all_solutions = False solution = csp.solve() board = [[0] * N for i in range(N)] print(len(board)) for key, value in solution.items(): print(key[1], key[4], value) board[int(key[1])][int(key[4])] = value[0] for i in range(N): print(board[i])
def __init__(self, nodes): """ Creates a new GUI :param nodes: List of Node objects to refrence """ self.nodes = nodes self.csp = CSP(self.nodes)
def solve(self): X = [] V = {} C = {} # all locations are variables # locations given number have domain size 1 for i in range(0, len(self.map)): for j in range(0, len(self.map[i])): X.append((i, j)) if self.map[i][j] == 0: V[(i, j)] = [1, 2, 3, 4, 5, 6, 7, 8, 9] else: V[(i, j)] = [self.map[i][j]] # get a list of different integer pairs from 1 to 9 diff_pair = [] for i in range(1, 10): for j in range(1, 10): if not i == j: diff_pair.append((i, j)) # a variable needs to be differnet from its row, column, and 3*3 square for i in range(0, len(X)): if len(V[X[i]]) == 9: for col in range(0, 9): if not col == X[i][1]: if not (X[i], (X[i][0], col)) in C and not ((X[i][0], col), X[i]) in C: C[(X[i], (X[i][0], col))] = diff_pair for row in range(0, 9): if not row == X[i][0]: if not (X[i], (row, X[i][1])) in C and not ((row, X[i][1]), X[i]) in C: C[(X[i], (row, X[i][1]))] = diff_pair lt = ((X[i][0]//3) * 3, (X[i][1]//3) * 3) for c_diff in range(0, 3): for r_diff in range(0, 3): if not (lt[0] + r_diff, lt[1] + c_diff) == X[i]: if not (X[i], (lt[0] + r_diff, lt[1] + c_diff)) in C and not ((lt[0] + r_diff, lt[1] + c_diff), X[i]) in C: C[X[i], (lt[0] + r_diff, lt[1] + c_diff)] = diff_pair problem = CSP(X, V, C) solution = problem.solve() return solution
def solve(self): X = [] V = {} C = {} # initialize variable and domain for i in range(0, len(self.Components)): X.append(i) component_width = self.Components[i][0] component_height = self.Components[i][1] # possible lower left point of a component for x in range(0, self.width): for y in range(0, self.height): # if legal, append to V if x + component_width <= self.width and y + component_height <= self.height: if i in V: V[i].append((x, y)) else: V[i] = [(x, y)] # initialize constraints for i in range(0, len(X)): for j in range(0, len(X)): if not i == j: if not (i, j) in C and not (j, i) in C: C[(i, j)] = self.get_cons(i, j, V) #print(X) #print(V) #print(C) problem = CSP(X, V, C) # solve if self.bt_mc == 1: solution = problem.solve() else: solution = problem.min_conflicts(1000) result = {} if solution == None: return None for idx in solution: result[tuple(self.Components[idx])] = solution[idx] return result
def csp_optimum(node_count, edge_count, edges): def get_degree(edges, node_count): degree = {n: 0 for n in range(node_count)} for x, y in edges: degree[x] += 1 degree[y] += 1 return degree def goal(nodes): return len(nodes) == node_count def gen_neighbors(nodes): node = list(csp.variables)[len(nodes)] neighbors = [] #colors = (csp.domain).copy() colors = set(nodes.values()) if len(nodes) > 0 else {1} for color in colors: assignment = nodes.copy() assignment.update({node: color}) if csp.consistent_var(assignment, node): neighbors.append(assignment) if len(neighbors) == 0: new_color = max(colors) + 1 assignment = nodes.copy() assignment.update({node: new_color}) if csp.consistent_var(assignment, node): neighbors.append(assignment) #colors.add(new_color) #csp.update_domain(colors) #print('Colors: ', colors) return neighbors def number_colors(nodes): return len(set(nodes.values())) constraints = [ Constraint(scope=edge, predicate=lambda x, y: x != y) for edge in edges ] #colors = set(range(1, node_count+1)) #domains = {n: colors for n in range(node_count)} domain = {1} degree = get_degree(edges, node_count) sorted_variables = sorted(degree, key=lambda n: degree[n], reverse=True) #print('VARIABLES: ', sorted_variables) csp = CSP(domain, constraints, variables=sorted_variables) assignments, path = dfs_with_prunning(goal, gen_neighbors, number_colors, bound=node_count) colors = set(assignments.values()) return colors, assignments
class AC3: csp = CSP(0, 0) def __init__(self, csp): self.csp = csp self.csp.mm = cm() def run(self): self.csp.mm.pStart() Q = Queue() for e in self.csp.eList: Q.put(e) tmpE = copy.deepcopy(e) tmpE[0] = tmpE[0] + len(self.csp.eList) tmp = tmpE[1] tmpE[1] = tmpE[2] tmpE[2] = tmp Q.put(tmpE) while not Q.empty(): e = Q.get() revised = self.csp.revise(e[1], e[2]) if len(self.csp.dm_set[str(e[1])]) == 0: return False if revised: items = self.csp.adj[str(e[1])].items() for itm in items: if [itm[1], int(itm[0]), e[1] ] not in Q.queue and e[2] != int(itm[0]): Q.put([itm[1], int(itm[0]), e[1]]) self.csp.mm.pEnd() return True
def create_map_coloring_csp(): """Instantiate a CSP representing the map coloring problem from the textbook. This can be useful for testing your CSP solver as you develop your code. """ csp = CSP() states = ['WA', 'NT', 'Q', 'NSW', 'V', 'SA', 'T'] edges = {'SA': ['WA', 'NT', 'Q', 'NSW', 'V'], 'NT': ['WA', 'Q'], 'NSW': ['Q', 'V']} colors = ['red', 'green', 'blue'] for state in states: csp.add_variable(state, colors) for state, other_states in edges.items(): for other_state in other_states: csp.add_constraint_one_way(state, other_state, lambda i, j: i != j) csp.add_constraint_one_way(other_state, state, lambda i, j: i != j) return csp
def solve(self): X = [] V = {} C = {} for i in range(0, len(self.Components)): X.append(i) bot_width = self.Components[i][0] bot_height = self.Components[i][1] up_width = self.Components[i][2] up_height = self.Components[i][3] shift = self.Components[i][4] for x in range(0, self.width): for y in range(0, self.height): if x + shift >= 0 and x + bot_width <= self.width and x + shift + up_width <= self.width and y + bot_height + up_height <= self.height: if i in V: V[i].append((x, y)) else: V[i] = [(x, y)] for i in range(0, len(X)): for j in range(0, len(X)): if not i == j: if not (i, j) in C and not (j, i) in C: C[(i, j)] = self.get_cons(i, j, V) #print(X) #print(V) #rint(C) problem = CSP(X, V, C) solution = problem.solve() result = {} #print(solution) if solution == None: return None for idx in solution: result[tuple(self.Components[idx])] = solution[idx] return result
def initialzing_NQueen(N): csp = CSP() rule = "x[0] != y[0] and x[1] != y[1] and abs((x[0] - y[0]) / (x[1] - y[1])) != 1" for v in range(N): csp.add_variable(str(v), [[x, y] for x in range(N) for y in range(N)]) for x in csp.variables: for y in csp.variables: if x != y: csp.add_constraint(x, y, rule) csp.solve() csp.save_solution() # print(csp.solutions) return csp
def run_csp(board): # CSP WITHOUT BACKTRACKING time_csp = time.time() board_csp, expanded_nodes_csp, path_csp = copy.deepcopy(board).solve(CSP()) time_csp = time.time() - time_csp print_result('CSP', expanded_nodes_csp, board_csp, time_csp) visualize(path_csp) draw_grid(path_csp)
def solve(self): X = [] V = {} C = {} # get a list of different color pairs color_pairs = get_color_pairs(self.Color) # initialize variable and domain for i in range(0, len(self.T)): X.append(i) V[i] = [] for c in self.Color: V[i].append(c) #V[i] = self.Color # initialize constraints for t in self.Neighbors: for n in self.Neighbors[t]: ti = self.T.index(t) ni = self.T.index(n) if not (ti, ni) in C and not (ni, ti) in C: C[(ti, ni)] = color_pairs #print(X) #print(V) #print(C) problem = CSP(X, V, C) # solve if self.bt_mc == 1: solution = problem.solve() else: solution = problem.min_conflicts(101) result = {} if solution == None: return None for idx in solution: result[self.T[idx]] = solution[idx] return result
def main(filename): csp = CSP(filename) if (ac3(csp)): if (csp.is_solved()): print "Sudoku Solved!" csp.print_game() else: assignment = backtrack({}, csp) if isinstance(assignment, dict): csp.assign(assignment) print "Sudoku Solved!" csp.print_game() else: print "No solution exists" else: print "No solution exists"
def run_gui_problem(): """ Determine the layout of some GUI elements """ # Define variables variables = [ ('th', [20,]), ('iph', [16,]), ('ip0y', range(0,100)), ('ip1y', range(0,100)), ('op0y', range(0,100)) ] # Generate constraints constraints = [] constraints.append( (('ip0y', 'iph'), lambda ip0y, iph: ip0y>=iph) ) constraints.append( (('ip1y', 'ip0y', 'iph'), lambda ip1y, ip0y, iph: ip1y>=ip0y+iph) ) constraints.append( (('op0y', 'ip0y'), lambda op0y, ip0y: op0y==ip0y) ) cprob = CSP(variables, constraints) sol = cprob.backtrack() print sol
def run(inFileName, outFileName): # Open file for reading infile = open(inFileName, 'r') # Create the CSP object # the three bool corresponding to LCV, MRV, and Forward checking csp = CSP(True, True, True) # Read the input file read(infile, csp) # Run back tracking search, and record time elapsed start = time.time() bt = BackTracking() result = bt.backtrackSearch(csp) end = time.time() execuTime = (end - start) * 1000 # Print output to console print "===============================" if not result.isComplete(): print "Assignment not possible..." # if result.checkTopLimit(): # print "checkTopLimit failed" # if result.checkBottomLimit(): # print "checkBottomLimit failed" # if result.checkUnaryIn(): # print "checkUnaryIn failed" # if result.checkUnaryEx(): # print "checkUnaryEx failed" # if result.checkBinaryEq(): # print "checkBinaryEq failed" # if result.checkBinaryNEq(): # print "checkBinaryNEq failed" # if result.checkMutualIn(): # print "checkMutualIn failed" # if result.checkMaxCapacity(): # print "checkMaxCapacity failed" print "===============================" exit(1) else: print "Assignment Complete..." print "Execution time: " + str(execuTime) + " milliseconds" print "===============================" # Write final result to output file outfile = open(outFileName, 'w') write(outfile, result) exit(0)
def csp_solver(node_count, edge_count, edges): def get_degree(edges, node_count): degree = {n: 0 for n in range(node_count)} for x, y in edges: degree[x] += 1 degree[y] += 1 return degree def goal(nodes): return len(nodes) == node_count def gen_neighbors(nodes): node = list(csp.variables)[len(nodes)] #print('NEW NODE: ', node) neighbors = [] colors = (csp.domain).copy() for color in colors: assignment = nodes.copy() assignment.update({node: color}) if csp.consistent_var(assignment, node): neighbors.append(assignment) if len(neighbors) == 0: new_color = max(colors) + 1 assignment = nodes.copy() assignment.update({node: new_color}) if csp.consistent_var(assignment, node): neighbors.append(assignment) colors.add(new_color) csp.update_domain(colors) return neighbors constraints = [ Constraint(scope=edge, predicate=lambda x, y: x != y) for edge in edges ] domain = {1} degree = get_degree(edges, node_count) sorted_variables = sorted(degree, key=lambda n: degree[n], reverse=True) #print(constraints) csp = CSP(domain, constraints, variables=sorted_variables) assignments, path = bfs_search(goal, gen_neighbors) colors = set(assignments.values()) return colors, assignments
def map_coloring_csp(points_number, width, height, line_distance, var_heuristics, val_heuristics, inference): coordinates = [] for _ in range(points_number): point = [rd.randint(1, width), rd.randint(1, height)] if point not in coordinates: coordinates.append(point) coordinates = [[x * line_distance, y * line_distance] for x, y in coordinates] gui = GUI(width, height, line_distance) gui.draw_background() lines = [] for _ in range(3): rd.shuffle(coordinates) for X in coordinates: distance_sort = sorted(coordinates, key=lambda p: math.dist(p, X)) for Y in distance_sort[1:]: if [X, Y] in lines or [Y, X] in lines: continue if any(map(lambda x: intersect(X, Y, *x), lines)): continue gui.draw_line(*X, *Y) lines.append([X, Y]) break neighbors = {str(c): [] for c in coordinates} for [start, end] in lines: if str(start) in neighbors: neighbors[str(start)].append(str(end)) neighbors[str(end)].append(str(start)) colors = ['red', 'blue', 'green', 'black'] domains = {str(c): [] for c in neighbors.keys()} for key in neighbors.keys(): domains[str(key)] = colors def different_values_constraint(var1, a, var2, b): return a != b map_csp = CSP(list(neighbors.keys()), domains, neighbors, different_values_constraint) solution = backtracking_search(map_csp, select_unassigned_variable=var_heuristics, order_domain_values=val_heuristics, inference=inference) gui.draw_color_points(coordinates, [x for x in solution.values()]) gui.root.mainloop()
def main(filename): csp = CSP(filename) if(ac3(csp)): if(csp.is_solved()): print "Sudoku Solved!" csp.print_game() else: assignment = backtrack({},csp) if isinstance(assignment,dict): csp.assign(assignment) print "Sudoku Solved!" csp.print_game() else: print "No solution exists" else: print "No solution exists"
def run_coin_problem(): """ Figure out how to make 0-99 cents in change (using quarters, dimes, nickels, and pennies) """ # Define variables variables = [ ('Q',[0,1,2,3]), ('D',[0,1,2]), ('N',[0,1]), ('P',[0,1,2,3,4]) ] # Generate constraints constraints=[] def make_constraint(n): return lambda Q,D,N,P:(Q*25+D*10+N*5+P==n) for i in xrange(100): constraints.append( (['Q','D','N','P'],make_constraint(i)) ) # Solve each constraint separately and print solutions cprob = CSP(variables) for i,con in enumerate(constraints): cprob.reset_constraints([con]) sol = cprob.backtrack() print "{0:2} cents: {1[Q]:2} quarters, {1[D]:2} dimes, {1[N]:2} nickels, {1[P]:2} pennies".format(i,sol)
class AC1: csp = CSP(0, 0) def __init__(self, csp): self.csp = csp self.csp.mm = cm() def run(self): self.csp.mm.pStart() changed = True while changed: changed = False for e in self.csp.eList: changed |= self.csp.revise(e[1], e[2]) changed |= self.csp.revise(e[2], e[1]) self.csp.mm.pEnd() for i in range(1, self.csp.N + 1): if len(self.csp.dm_set[str(i)]) == 0: return False return True
class AC2: csp = CSP(0, 0) def __init__(self, csp): self.csp = csp self.csp.mm = cm() def run(self): self.csp.mm.pStart() for i in range(1, self.csp.N + 1): frwdq = Queue() backq = Queue() for j in range(1, self.csp.N + 1): if j < i: if self.csp.mat[i][j] == 1: frwdq.put([i, j]) backq.put([j, i]) while not frwdq.empty(): while not frwdq.empty(): cur_edge = frwdq.get() revised = self.csp.revise(cur_edge[0], cur_edge[1]) if len(self.csp.dm_set[str(cur_edge[0])]) == 0: return False if revised: for j in range(1, i + 1): if j <= i and j != cur_edge[1]: if self.csp.mat[cur_edge[0]][ j] == 1 and self.csp.mat[j][ cur_edge[0]] == 1: if [j, cur_edge[0]] not in backq.queue: backq.put([j, cur_edge[0]]) frwdq = backq backq = Queue() self.csp.mm.pEnd() return True
for v in voisins: # On lit la couleur du voisin couleur_voisin = self.a.get(v) if(couleur_voisin!=None): # Si un voisin utilise déjà la couleur if(c == couleur_voisin): ok = False # On teste la couleur suivante break # else: # # Si le voisin n'a pas encore de couleur on sort du while # # pour attribuer la couleur à la variable en cours # break # Si aucun voisin n'utilise la couleur, on assigne la couleur if(ok==True): self.a[variable] = c return True return False if __name__ == "__main__": g = CSP("instances_moodle/flat20_3_0.col",3) g.trierParMaxContraintes() # print g.contraintes b = Backtrack(g)
def zebra_problem_csp(var_heuristics, val_heuristics, inference): colors = ['Red', 'Yellow', 'Blue', 'Green', 'Ivory'] pets = ['Dog', 'Fox', 'Snails', 'Horse', 'Zebra'] beverage = ['OrangeJuice', 'Tea', 'Coffee', 'Milk', 'Water'] nationality = [ 'Englishman', 'Spaniard', 'Norwegian', 'Ukrainian', 'Japanese' ] cigarettes = [ 'Kools', 'Chesterfields', 'OldGold', 'LuckyStrike', 'Parliaments' ] variables = colors + pets + beverage + nationality + cigarettes domains = {} for var in variables: domains[var] = list(range(1, 6)) neighbors = { 'Englishman': ['Red'], 'Red': ['Englishman'], 'Spaniard': ['Dog'], 'Dog': ['Spaniard'], 'Coffee': ['Green'], 'Green': ['Coffee', 'Ivory'], 'Ukrainian': ['Tea'], 'Tea': ['Ukrainian'], 'Ivory': ['Green'], 'Yellow': ['Kools'], 'OldGold': ['Snails'], 'Snails': ['OldGold'], 'Kools': ['Horse', 'Yellow'], 'Horse': ['Kools'], 'Chesterfields': ['Fox'], 'Fox': ['Chesterfields'], 'LuckyStrike': ['OrangeJuice'], 'OrangeJuice': ['LuckyStrike'], 'Japanese': ['Parliaments'], 'Parliaments': ['Japanese'], 'Norwegian': ['Blue'], 'Blue': ['Norwegian'], 'Zebra': [], 'Water': [], 'Milk': [] } for part in [colors, pets, beverage, nationality, cigarettes]: for A in part: for B in part: if A != B: if B not in neighbors[A]: neighbors[A].append(B) if A not in neighbors[B]: neighbors[B].append(A) domains['Norwegian'] = [1] domains['Milk'] = [3] def zebra_constraint(var1, a, var2, b, recurse=0): same = (a == b) next_to = abs(a - b) == 1 if var1 == 'Englishman' and var2 == 'Red': return same if var1 == 'Spaniard' and var2 == 'Dog': return same if var1 == 'Chesterfields' and var2 == 'Fox': return next_to if var1 == 'Norwegian' and var2 == 'Blue': return next_to if var1 == 'Kools' and var2 == 'Yellow': return same if var1 == 'OldGold' and var2 == 'Snails': return same if var1 == 'LuckyStrike' and var2 == 'OrangeJuice': return same if var1 == 'Ukrainian' and var2 == 'Tea': return same if var1 == 'Japanese' and var2 == 'Parliaments': return same if var1 == 'Kools' and var2 == 'Horse': return next_to if var1 == 'Coffee' and var2 == 'Green': return same if var1 == 'Green' and var2 == 'Ivory': return a - 1 == b if recurse == 0: return zebra_constraint(var2, b, var1, a, 1) if ((var1 in colors and var2 in colors) or (var1 in pets and var2 in pets) or (var1 in beverage and var2 in beverage) or (var1 in nationality and var2 in nationality) or (var1 in cigarettes and var2 in cigarettes)): return not same raise Exception('Variable is incorrect or missing') zebra_csp = CSP(variables, domains, neighbors, zebra_constraint) solution = backtracking_search(zebra_csp, select_unassigned_variable=var_heuristics, order_domain_values=val_heuristics, inference=inference) house1 = [] house2 = [] house3 = [] house4 = [] house5 = [] for key, value in zip(solution.keys(), solution.values()): if value == 1: house1.append(key) if value == 2: house2.append(key) if value == 3: house3.append(key) if value == 4: house4.append(key) if value == 5: house5.append(key) houses = [house1, house2, house3, house4, house5] gui = GUI() gui.print(houses) gui.root.mainloop()
44, 15, 17, 19, 45, 46, 48, 50, 52, 54, 60, 61, 62], :] # 원하는 채널 선택 10-20 label = np.concatenate((np.zeros(Ldata_num, ), np.ones(Rdata_num, ))) kf = KFold(n_splits=45) for train_idx, test_idx in kf.split(data): tr_data = data[train_idx] tr_label = label[train_idx] ts_data = data[test_idx] ts_label = data[test_idx] #%% w = CSP(Ldata, Rdata) # CSP filter # Z = w*x Z = np.zeros((45, 32, 640)) temp = np.zeros((45, 32)) for idx, x in enumerate(data): Z[idx] = w[0] @ x # (32, 32) * (32, 640) => (32, 640) temp[idx] = np.log(np.var(Z[idx], axis=1)/np.sum(np.var(Z[idx], axis=1))) a = [] b = [] for rn in rns: # 데이터 셔플링 a.append(temp[rn]) b.append(label[rn]) csp_data = np.array(a) # feature x 완성
class GUI(): """ GUI for displaying nodes, running CSP, and creating graph. """ _line_width = 2 _line_color = (255, 255, 255) _background_color = 50, 50, 50 _size = 1920, 1080 _circle_width = 10 _font = "Verdana" _font_size = 30 def __init__(self, nodes): """ Creates a new GUI :param nodes: List of Node objects to refrence """ self.nodes = nodes self.csp = CSP(self.nodes) def start(self): """ Starts the GUI displaying the window. """ pygame.init() pygame.font.init() font = pygame.font.SysFont(self._font, self._font_size) screen = pygame.display.set_mode(self._size) start_button = pygame.Rect(100, 100, 200, 50) reset_button = pygame.Rect(100, 300, 200, 50) while True: # Get events for event in pygame.event.get(): x, y = pygame.mouse.get_pos() add_node = True # Quit GUI if event.type == pygame.QUIT: sys.exit() # Buttons if start_button.collidepoint( (x, y)) and pygame.MOUSEBUTTONUP == event.type: if len(self.nodes) > 0: self.csp.performSearch(self.nodes[0]) add_node = False if reset_button.collidepoint( (x, y)) and pygame.MOUSEBUTTONUP == event.type: self.nodes = [] add_node = False # Add Node when mouse clicked if add_node and event.type == pygame.MOUSEBUTTONUP: new_node = Node(None, x, y) self.nodes.append(new_node) # Add a random neighbor if len(self.nodes) > 1: for _ in self.nodes: if randint(0, 1): random_neighbor = self.nodes[randint( 0, len(self.nodes) - 1)] new_node.addNeighbor(random_neighbor) screen.fill(self._background_color) # Draw lines first for node in self.nodes: for neighbor in node.neighbors: gfxdraw.line(screen, node._posX, node._posY, neighbor._posX, neighbor._posY, self._line_color) # Draw nodes second for node in self.nodes: color = 0, 0, 0 vector = (node._posX, node._posY) if node._color is not None: color = get_rgb_value(node._color) pygame.draw.circle(screen, color, vector, self._circle_width) # Draw Buttons pygame.draw.rect(screen, get_rgb_value(Color.GREEN), start_button) pygame.draw.rect(screen, get_rgb_value(Color.RED), reset_button) start_text = font.render('Start Search', False, (0, 0, 0)) reset_text = font.render('Reset', False, (0, 0, 0)) screen.blit(start_text, (105, 105)) screen.blit(reset_text, (145, 305)) pygame.display.flip()
def create_sudoku_csp(filename): """Instantiate a CSP representing the Sudoku board found in the text file named 'filename' in the current directory. """ csp = CSP() board = list(map(lambda x: x.strip(), open(filename, 'r'))) for row in range(9): for col in range(9): if board[row][col] == '0': csp.add_variable('%d-%d' % (row, col), map(str, range(1, 10))) else: csp.add_variable('%d-%d' % (row, col), [board[row][col]]) for row in range(9): csp.add_all_different_constraint( ['%d-%d' % (row, col) for col in range(9)]) for col in range(9): csp.add_all_different_constraint( ['%d-%d' % (row, col) for row in range(9)]) for box_row in range(3): for box_col in range(3): cells = [] for row in range(box_row * 3, (box_row + 1) * 3): for col in range(box_col * 3, (box_col + 1) * 3): cells.append('%d-%d' % (row, col)) csp.add_all_different_constraint(cells) return csp
# path = 'Dataset/D1_100Hz/Test/BCICIV_eval_ds1' # idx = 'a' plot_var = False data, labels, cue_position, other_info = loadDataset100Hz(path, idx, type_dataset = 'train') #%% Extract trials from data (Works only on dataset IV-1-a of BCI competition) fs = other_info['sample_rate'] trials_dict = computeTrial(data, cue_position, labels, fs,other_info['class_label']) #%% CSP_clf = CSP(trials_dict, fs) # CSP_clf.plotFeatures() # CSP_clf.plotPSD(15, 12) CSP_clf.trainClassifier(print_var = True) CSP_clf.trainLDA() # CSP_clf.trainClassifier(classifier = SVC(kernel = 'linear')) CSP_clf.plotFeaturesScatter() i = 79 for key in trials_dict.keys(): a = trials_dict[key][i, :, :] y = CSP_clf.evaluate(a)
# grab the file name for the constraints file parser.add_argument('constraintFileName') # grab the consistency enforcing procedure flag. (not implemented at this point, will always be "none" parser.add_argument('consistencyEnforcingProcedureFlag') # parse the args and put them in args args = parser.parse_args() # collect all the variables from file variables = init.getVariablesFromFile(args.varFileName) # collect all the constraints from file constraints = init.getConstraintsFromFile(args.constraintFileName) # at this point in development, we are not using any consistency enforcing procedures, this feature may be added later. none = "none" # create the constraint satisfaction problem csp = CSP(variables, constraints, none) # create the backtracking search instance and feed it the constraint satisfaction problem bsearch = Backtracking_Search(csp) # start the search at the root of the search tree bsearch.backtrack(bsearch.root) print "\nsolutions found:" for solution in bsearch.solutions: print "solution:" + str(solution)
m = assignment['M'] o = assignment['O'] r = assignment['R'] y = assignment['Y'] #Checking if condition is satisfied send = s * 1000 + e * 100 + n * 10 + d more = m * 1000 + o * 100 + r * 10 + e money = m * 10000 + o * 1000 + n * 100 + e * 10 + y return send + more == money return True if __name__ == "__main__": letters = ["S", "E", "N", "D", "M", "O", "R", "Y"] possible_digits = {} for letter in letters: possible_digits[letter] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] possible_digits["M"] = [1] # so we don't get answers starting with a 0 csp = CSP(letters, possible_digits) csp.add_constraint(SendMoreMoneyConstraint(letters)) solution = csp.backtracking_search() if solution is None: print("No solution found!") else: for key, val in solution.items(): print(str(key).ljust(10), str(val).ljust(30))
from cursesmenu import * from cursesmenu.items import * from CSP import CSP csp = CSP() def load_from_json(): print("Enter the file name to load csp from : ") filename = input() csp.load_from_json(filename) def export_to_json(): print("Enter the file name to export csp to : ") filename = input() csp.export_to_json(filename) def generate_single(): csp.all_solutions = False if csp.is_solved(): print("CSP already solved") else: csp.solve() print("SOLVED !!") input() def generate_all(): csp.all_solutions = True
def generateCSP(self, word_values, word_variables): CSP.__init__(self, self.values, self.variables, self.constraints, self.init_domains, self.inference_bool) final_assignment = CSP.backtracking_search(self) print("final assignment", final_assignment) return final_assignment
class AC4: csp = CSP(0, 0) mList = [] support = {} # list in dictionary in dictionary counter = {} # value in dictionary in dictionary tmpList = [] offset = 1003 Q = Queue() visited = {} def __init__(self, csp): self.csp = csp self.csp.mm = cm() def preINIT(self): for i in range(1, self.csp.N + 1): for j in range(0, len(self.csp.dm_set[str(i)])): if self.csp.dm_set[str(i)][j] < 0: self.csp.dm_set[str(i)][j] += self.offset for i in range(1, self.csp.N + 1): self.support[str(i)] = {} self.counter[str(i)] = {} self.visited[str(i)] = {} for j in self.csp.dm_set[str(i)]: self.support[str(i)][str(j)] = [] self.visited[str(i)][str(j)] = 0 self.counter[str(i)][str(j)] = {} for k in range(1, self.csp.N + 1): self.counter[str(i)][str(j)][str(k)] = 0 def postBack(self): for i in range(1, self.csp.N + 1): for j in range(0, len(self.csp.dm_set[str(i)])): if self.csp.dm_set[str(i)][j] > 103: self.csp.dm_set[str(i)][j] -= self.offset def initialize(self): self.preINIT() for node in range(1, self.csp.N + 1): tmpAdj = copy.deepcopy(self.csp.adj[str(node)]) uNode = copy.deepcopy(node) tmpAdj = tmpAdj.items() for itm in tmpAdj: vNode = int(itm[0]) edgeNum = int(itm[1]) is_reversed = False if edgeNum >= len(self.csp.eList): is_reversed = True for uDV in self.csp.dm_set[str(uNode)]: for vDV in self.csp.dm_set[str(vNode)]: curCon = copy.deepcopy(self.csp.cons_set[str(edgeNum)]) yes = False if is_reversed: curCon[2] = uDV if curCon[2] > 103: curCon[2] -= self.offset curCon[1] = vDV if curCon[1] > 103: curCon[1] -= self.offset else: curCon[1] = uDV if curCon[1] > 103: curCon[1] -= self.offset curCon[2] = vDV if curCon[2] > 103: curCon[2] -= self.offset yes = self.csp.cons.evaluatingConstraints(curCon) # print('Evaluating ', curCon, ' result: ',yes, ' at:', uNode) if yes: # print('Push: ', [vNode, vDV], ' at ',[uNode, uDV]) self.support[str(uNode)][str(uDV)].append( [vNode, vDV]) self.counter[str(uNode)][str(uDV)][str(vNode)] += 1 # for node in range(1 , self.csp.N+1): # for val in self.csp.dm_set[str(node)]: # # self.counter[str(node)][str(val)] = len(self.support[str(node)][str(val)]) # print([node, val], ': ', self.counter[str(node)][str(val)], ' : ', self.support[str(node)][str(val)]) def getDomainBack(self): for i in range(1, self.csp.N + 1): self.csp.dm_set[str(i)] = [] for itm in self.mList: if itm[1] not in self.csp.dm_set[str(itm[0])]: self.csp.dm_set[str(itm[0])].append(itm[1]) return def run(self): self.csp.mm.pStart() self.initialize() self.Q = Queue() self.mList = [] for i in range(1, self.csp.N + 1): tmpRVL = set() for j in self.csp.dm_set[str(i)]: for k in range(1, self.csp.N + 1): if int(i) != int(k) and self.csp.mat[i][k] == 1: if self.counter[str(i)][str(j)][str(k)] == 0: if j in self.csp.dm_set[str(i)]: tmpRVL.add(j) # self.mList.append([[i, j]]) if self.visited[str(i)][str(j)] == 0: # print('Queue pushing: ', [i, j]) self.visited[str(i)][str(j)] = 1 self.Q.put([int(i), int(j)]) # print(tmpRVL) for tmprvl in tmpRVL: self.csp.dm_set[str(i)].remove(tmprvl) if len(self.csp.dm_set[str(i)]) == 0: self.csp.mm.pEnd() return False while not self.Q.empty(): tmp = self.Q.get() self.mList.append(tmp) for xa in self.support[str(tmp[0])][str(tmp[1])]: if xa[1] in self.csp.dm_set[str( xa[0])] and self.csp.mat[xa[0]][ tmp[0]] == 1 and self.csp.mat[tmp[0]][xa[0]] == 1: self.counter[str(xa[0])][str(xa[1])][str(tmp[0])] -= 1 if self.counter[str(xa[0])][str(xa[1])][str(tmp[0])] == 0: if self.visited[str(xa[0])][str(xa[1])] == 0: self.visited[str(xa[0])][str(xa[1])] = 1 self.csp.dm_set[str(str(xa[0]))].remove(xa[1]) if len(self.csp.dm_set[str(xa[0])]) == 0: self.csp.mm.pEnd() return False self.Q.put([xa[0], xa[1]]) for tmprvl in self.mList: if tmprvl[1] in self.csp.dm_set[str(tmprvl[0])]: self.csp.dm_set[str(tmprvl[0])].remove(tmprvl[1]) if len(self.csp.dm_set[str(tmprvl[0])]) == 0: self.csp.mm.pEnd() return False # self.getDomainBack() for i in range(1, self.csp.N + 1): if len(self.csp.dm_set[str(i)]) == 0: return False self.postBack() self.csp.mm.pEnd() return True
def backtracking_search(self): import time import os if os.name == "posix": import resource csp = CSP(self.datamodelobj.ta_info, self.datamodelobj.course_info) memory_usage0 = 0 if os.name == "posix": import resource memory_usage0 = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss # pure backtracking only csp.backtrack_init() print("Running plain backtracking search") print("===============================================") start_time = time.clock() time_pbs = 0.0 time_bs_fc = 0.0 time_bs_fc_cp = 0.0 if self.backtrack(csp): time_pbs = (time.clock() - start_time) * 1000 csp.print_result(1) csp.print_result(2) else: print("Failed to find a solution!") if os.name == "posix": memory_usage1 = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss # backtracking with forward checking csp.backtrack_init() print("\nRunning backtracking search with forward checking") print("=======================================================") start_time = time.clock() if self.backtrack_fc(csp): time_bs_fc = (time.clock() - start_time) * 1000 csp.print_result(1) csp.print_result(2) else: print("Failed to find a solution!") if os.name == "posix": memory_usage2 = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss # backtracking with forward checking and contraint_propagation csp.backtrack_init() print("\nRunning backtracking search with fc and constraint propagation") print("================================================================") start_time = time.clock() if self.backtrack_mac(csp): time_bs_fc_cp = (time.clock() - start_time) * 1000 csp.print_result(1) csp.print_result(2) else: print("Failed to find a solution!") if os.name == "posix": memory_usage3 = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss print("\nSummary of running time of algorithms\n============================================") print("Plain backtracking search:", time_pbs, "milliseconds") print("Backtracking search with forward checking:", time_bs_fc, "milliseconds") print( "Plain backtracking search with forward checking and constraint propagation:", time_bs_fc_cp, "milliseconds" ) print() if os.name == "posix": print("\nSummary of memory usage of algorithms\n============================================") print("Plain backtracking search", memory_usage1 - memory_usage0, "kb") print("Plain bs + fc", memory_usage2 - memory_usage1, "kb") print("Plain bs + fc + cp", memory_usage3 - memory_usage2, "kb") print()
import sys import csv from CSP import CSP from Map import Map col = [ "#ffff00", "#09cd00", "#f71200", "#0005e0", "#c526ff", "#800080", "#FFFF00", "#00FF00", "#FF00FF" ] file = "" data = "" solution = CSP.CSP(col) if len(sys.argv) > 1 and sys.argv[1] == "it": file = "Map/Italy_Regions_Blank.svg" data = "data/italia.csv" elif len(sys.argv) > 2: file = sys.argv[1] data = sys.argv[2] else: if len(sys.argv) > 1 and sys.argv[1] != "wd": raise NameError(sys.argv[1] + " isn't a valid arg!") file = "Map/world.svg" data = "data/world.csv" with open(data) as csv_file: csv_reader = csv.reader(csv_file, delimiter=';') data = {} for row in csv_reader:
print "[6] Lancer un ForwardChecking sur le CSP courant" print "[Q] Quitter" print "#####################################################################" print OKBLUE+"Que voulez-vous faire ?"+ENDC, res = raw_input() print "" if (res=='Q' or res=='q'): continuer = False elif (res=='1'): print "Indiquez le chemin du fichier labyrinthe a charger: ", path = raw_input() print "Indiquez le nombre de couleurs à utiliser: ", nb_couleurs = input() csp = CSP(path,nb_couleurs) if(csp.erreur_chargement==False): print OKGREEN+"=> CSP chargé!"+ENDC else: csp=None elif (res=='2'): if(csp!=None): csp.trierParMaxContraintes() print OKGREEN+"=> CSP trié!"+ENDC else: print FAIL+"Aucun CSP n'a été chargé! Veuillez charger un CSP."+ENDC elif (res=='3'): afficher_trace = not afficher_trace
def generateCSP(self, size, circuit_components): CSP.__init__(self, self.values, self.variables, self.constraints, self.init_domains, self.inference_bool) final_assignment = CSP.backtracking_search(self) return final_assignment