示例#1
0
    def run_algorithm(self):
        print(self.num_of_vertices.get())
        print(self.num_of_edges.get())
        print(self.num_of_colors.get())
        print("ssssssssssssssssss: ", self.var.get())
        print(self.max_num_of_edges.get())

        #M, g = csp.create_graph(self.num_of_vertices.get(), self.num_of_edges.get() , self.max_num_of_edges.get())
        graph = csp.Graph(self.g)
        colors = csp.colors_for_map(self.num_of_colors.get())
        print(graph)
        print("Colors: ", colors)
        constraints = []
        for edge in graph.edges():
            if len(edge) is not 2:
                continue
            le = list(edge)
            # print(le, " ",edge)
            c = csp.BinaryConstraint(le[0], le[1])
            constraints.append(c)
        csp_var = csp.ConstraintSatisfactionProblem(list(graph.vertices()),
                                                    colors, constraints)

        if self.var.get() is 0:
            x = csp.solve(csp_var)
        else:
            x = csp.solve(csp_var)
        if csp.print_graph_gui(self.M, self.g, x, len(colors),
                               self.pos) is False:
            messagebox.showerror('Error', 'There is no satisfiable answer')
            return

        img = Image.open('graph.jpg')
        '''# Change size of image if needed.
        width, height = img.size

        if width > self.width/2-10:
            width = self.width/2-10

        if height > self.height/6*5-40:
            height = self.height/6*5-40

        img = img.resize((int(width), int(height)))'''
        photo = ImageTk.PhotoImage(img)

        # Delete previous label which has image.
        for i in self.image_frame.winfo_children():
            if i.winfo_class() == 'Label':
                i.destroy()

        # Create new label with the selected image.
        label = tk.Label(
            self.image_frame,
            #bg='gray80',
            image=photo,
            bd=0)
        label.pack()
        label.photo = photo

        print('\n\ndone\n\n')
示例#2
0
def main():

	colorama.init()

	if len(sys.argv) < 3:
		printUsage()

	elif sys.argv[1] == 'solve':
		grid = puzzle.parsePuzzleFile( sys.argv[2] )
		monitor = '--monitor' in sys.argv

		#print grid
		startTime = time.time()
		grid = csp.solve(grid, monitor=monitor)
		endTime = time.time()
		print grid
		print 'Solved in {} seconds with {} backtracks'.format(round(endTime - startTime, 3), grid.fails)

	elif sys.argv[1] == 'generate':
		monitor = '--monitor' in sys.argv
		grid = puzzle.generatePuzzle(int(sys.argv[2]), monitor)
		print grid

	else:
		printUsage()
示例#3
0
文件: puzzle.py 项目: money71/stevoku
def complicatePuzzle(grid):

	row = random.randrange(grid.base)
	col = random.randrange(grid.base)

	cell1 = grid.cellAt(row,col)
	cell2 = grid.cellAt( grid.base-row-1, grid.base-col-1 )
	if cell1.value == None or cell2.value == None:
		return complicatePuzzle(grid)

	# reset cells
	for cell in [cell1, cell2]:
		cell.value = None
		cell.given = False
		cell.domain = set(range(grid.base))

	# flag all unremoved cells as dirty and rebalance
	for dep in reduce(lambda a,b: a|b, grid.rows) - grid.unsolvedCells():
		grid.dirtyCells.append(dep)
	diff = csp.fixArcConsistency(grid)

	# find all solutions
	solutions = csp.solve(grid, complete=True)
		
	csp.unfixArcConsistency(diff)
	if len(solutions) != 1:
		return grid
	else:
		return complicatePuzzle(grid)
示例#4
0
文件: puzzle.py 项目: money71/stevoku
def generatePuzzle(base = 9, monitor = False):

	# initialize an empty grid
	grid = Grid(base)
	for row in range(base):
		for col in range(base):
			newCell = Cell(base, given=True)
			grid.insertCellAt(newCell, row, col)

	# randomly seed with one of each possible value
	for val in range(base):

		placed = False
		while not placed:

			# put an x randomly in row x, and rebalance
			col = random.randrange(base)
			cell = grid.cellAt(val,col)
			if val not in cell.row | cell.column | cell.block:
			#if val in cell.domain:
				cell.value = val
				cell.domain = set([val])
				grid.dirtyCells.append(cell)
				placed = True

	# solve randomly-seeded puzzle
	seedGrid = csp.solve( grid, complete=False, monitor=monitor )
	grid = None

	return complicatePuzzle(seedGrid)
示例#5
0
import csp
import json
import pprint

with open('state_neighbors.json', 'r') as f:
    data = json.loads(f.read())

us = {}
us['variables'] = {
    state: ['red', 'green', 'blue', 'yellow']
    for state in data.keys()
}
us['constraints'] = [(s1, s2, lambda x, y: x != y) for s1 in data.keys()
                     for s2 in data[s1]]

result = csp.solve(us)
status = 'SUCCESS'
if result == 'FAILURE' or not all(
    (result[s1] != result[s2] for s1 in data.keys() for s2 in data[s1])):
    status = 'FAILURE'

print '\n***************'
print '    ' + status
print '***************\n'
pprint.PrettyPrinter(indent=2).pprint(result)
print '\n'
示例#6
0
文件: sudoku.py 项目: PrajitR/jusCSP
# Replace empty dict with dict of filled in values.
filled_in = { pos:[val - 1] for pos,val in {}.iteritems() } 
variables.update(filled_in)
sudoku['variables'] = variables

neq = lambda x,y: x != y
horiz = [((i,k), (j,k), neq) for k in range(SIZE) for i in range(SIZE) for j in range(SIZE) if neq(i,j)]
vert  = [((k,i), (k,j), neq) for k in range(SIZE) for i in range(SIZE) for j in range(SIZE) if neq(i,j)]
block = []
for (k,l) in [(k,l) for k in range(SIZE) for l in range(SIZE)]:
  v,h = k // BLOCK_SIZE, l // BLOCK_SIZE
  for (i,j) in [(i,j) for i in range(v * 3, (v + 1) * 3) for j in range(h * 3, (h + 1) * 3) 
                    if neq((k,l), (i,j))]:
    block.append(((k,l), (i,j), neq))
sudoku['constraints'] = [v for a in [horiz, vert, block] for v in a]

def print_sudoku(result):
  divider = '|' + '-' * 35 + '|'
  print divider
  for i in range(SIZE):
    row = '| '
    for j in range(SIZE):
      row += str(result[(i,j)] + 1)
      row += '   ' if j % 3 != (BLOCK_SIZE - 1) else ' | '
    print row
    if i % 3 == (BLOCK_SIZE - 1):
      print divider

result = csp.solve(sudoku)
print_sudoku(result)
示例#7
0
neq = lambda x, y: x != y
horiz = [((i, k), (j, k), neq) for k in range(SIZE) for i in range(SIZE)
         for j in range(SIZE) if neq(i, j)]
vert = [((k, i), (k, j), neq) for k in range(SIZE) for i in range(SIZE)
        for j in range(SIZE) if neq(i, j)]
block = []
for (k, l) in [(k, l) for k in range(SIZE) for l in range(SIZE)]:
    v, h = k // BLOCK_SIZE, l // BLOCK_SIZE
    for (i, j) in [(i, j) for i in range(v * 3, (v + 1) * 3)
                   for j in range(h * 3, (h + 1) * 3) if neq((k, l), (i, j))]:
        block.append(((k, l), (i, j), neq))
sudoku['constraints'] = [v for a in [horiz, vert, block] for v in a]


def print_sudoku(result):
    divider = '|' + '-' * 35 + '|'
    print divider
    for i in range(SIZE):
        row = '| '
        for j in range(SIZE):
            row += str(result[(i, j)] + 1)
            row += '   ' if j % 3 != (BLOCK_SIZE - 1) else ' | '
        print row
        if i % 3 == (BLOCK_SIZE - 1):
            print divider


result = csp.solve(sudoku)
print_sudoku(result)

#Credit : github.com/PrajitR/
示例#8
0
文件: nqueens.py 项目: PrajitR/jusCSP
import csp
import pprint

SIZE = 8
board = {}

board['variables'] = { i: [(i, j) for j in range(SIZE)] for i in range(SIZE) }

def not_colliding(i, j):
  def diagonal(a, b):
    return abs(a[0] - b[0]) == abs(a[1] - b[1])
  return not(i[0] == j[0] or i[1] == j[1] or diagonal(i, j))

board['constraints'] = [(i, j, not_colliding) for i in range(SIZE) for j in range(SIZE) if i != j]

result = csp.solve(board)
status = 'SUCCESS'
if result == 'FAILURE' or not all((not_colliding(result[i], result[j]) for i in range(SIZE) 
                                      for j in range(i + 1, SIZE))):
  status = 'FAILURE'

print '\n***************'
print '    ' + status
print '***************\n'
pprint.PrettyPrinter(indent=2).pprint(result)
print '\n'
示例#9
0
文件: nqueens.py 项目: yawetse/jusCSP
import pprint

SIZE = 8
board = {}

board['variables'] = {i: [(i, j) for j in range(SIZE)] for i in range(SIZE)}


def not_colliding(i, j):
    def diagonal(a, b):
        return abs(a[0] - b[0]) == abs(a[1] - b[1])

    return not (i[0] == j[0] or i[1] == j[1] or diagonal(i, j))


board['constraints'] = [(i, j, not_colliding) for i in range(SIZE)
                        for j in range(SIZE) if i != j]

result = csp.solve(board)
status = 'SUCCESS'
if result == 'FAILURE' or not all((not_colliding(result[i], result[j])
                                   for i in range(SIZE)
                                   for j in range(i + 1, SIZE))):
    status = 'FAILURE'

print '\n***************'
print '    ' + status
print '***************\n'
pprint.PrettyPrinter(indent=2).pprint(result)
print '\n'
示例#10
0
import csp
import json
import pprint

with open('state_neighbors.json', 'r') as f:
  data = json.loads(f.read())

us = {}
us['variables'] = { state:['red', 'green', 'blue', 'yellow'] for state in data.keys() }
us['constraints'] = [(s1, s2, lambda x,y: x != y) for s1 in data.keys() for s2 in data[s1]]

result = csp.solve(us)
status = 'SUCCESS'
if result == 'FAILURE' or not all((result[s1] != result[s2] for s1 in data.keys() for s2 in data[s1])):
  status = 'FAILURE'

print '\n***************'
print '    ' + status
print '***************\n'
pprint.PrettyPrinter(indent=2).pprint(result)
print '\n'