Ejemplo n.º 1
0
 def test_solve_puzzle1(self):
     similarity = TaxonomySimilarity(self.example)
     puzzle = OddOneOutPuzzle("red",
                              ['orange', 'lemon'],
                              "citrus")
     expected = (0.5, 'citrus', 'red')
     assert solve_puzzle(puzzle, similarity) == expected
Ejemplo n.º 2
0
def doBasic(grid, size, iters, prob=0):
    grid2, value, solution = solver.solve_puzzle(grid, size)
    best_val = value
    best_found = False
    best_grid = list(grid)
    grid_gen = list(grid)
    best_grid_s = list(grid2)
    best_sol = solution
    iter_vals = []
    for i in range(iters):
        rand_val = random.uniform(0, 1)
        prev_grid = deepcopy(grid_gen)
        grid_gen, grid_s, value_gen, solution_s = generate_grid(grid_gen, size)
        # print("BEST: " + str(best_val) + "\nGEN: " + str(value_gen) + "\nRAND: " + str(rand_val) + "\n------------")
        if value_gen >= best_val:
            if not value_gen == best_val:
                best_found = True
            best_val = value_gen
            best_grid = grid_gen
            best_grid_s = grid_s
            best_sol = solution_s
        elif best_found and rand_val > prob:
            grid_gen = prev_grid
        iter_vals.append(best_val)
    best_grid = np.array(best_grid).tolist()
    best_grid = [item for sublist in best_grid for item in sublist]
    best_grid_s = np.array(best_grid_s).tolist()
    best_grid_s = [item for sublist in best_grid_s for item in sublist]
    if best_val > 0:
        best_sol = "Puzzle Value: " + str(best_val) + "\n" + best_sol
        # best_sol = "Puzzle Value: " + str(best_val) + "\n" + best_sol + "\nIterations: " + str(i) + "\nCompute Time: " + "{0:.2f}".format(end - start) + "s"

    return best_grid, best_grid_s, best_val, best_sol, i + 1, iter_vals
Ejemplo n.º 3
0
def doRestart(grid, size, iters, iters_per):
    grid2, value, solution = solver.solve_puzzle(grid, size)
    best_val = value
    new_best = False
    best_grid = list(grid)
    grid_gen = list(grid)
    best_grid_s = list(grid2)
    best_sol = solution
    start = time.time()
    it = 0
    iter_vals = []
    for i in range(iters):
        grid_gen = generate_rand_grid(size)
        grid_g, grid_s, value_gen, solution_s, iters, iter_vals = doBasic(
            grid_gen, size, iters_per)
        it += iters
        if value_gen >= best_val:
            new_best = True
            best_val = value_gen
            best_grid = grid_gen
            best_grid_s = grid_s
            best_sol = solution_s
        iter_vals.append(best_val)
    end = time.time()
    best_grid = np.array(best_grid).tolist()
    best_grid = [item for sublist in best_grid for item in sublist]
    best_grid_s = np.array(best_grid_s).tolist()
    if len(best_grid_s) <= size:
        best_grid_s = [item for sublist in best_grid_s for item in sublist]
    if not new_best:
        best_sol = "Puzzle Value: " + str(best_val) + "\n" + best_sol
    return best_grid, best_grid_s, best_val, best_sol, it, iter_vals
Ejemplo n.º 4
0
 def test_solve_puzzle(self):
     similarity = TaxonomySimilarity(self.taxonomy)
     puzzle = OddOneOutPuzzle("Golden Retriever", [
         "Poodle", "Irish Water Spaniel", "Wetterhoun", "Lagotto Romagnolo"
     ], "Water dogs")
     result = solve_puzzle(puzzle, similarity)
     assert result == (0.25, "Water dogs", "Golden Retriever")
Ejemplo n.º 5
0
 def test_solve_puzzle(self):
     similarity = TaxonomySimilarity(self.taxonomy)
     puzzle = OddOneOutPuzzle("beagle", [
         'large_poodle', 'miniature_poodle', 'standard_poodle', 'toy_poodle'
     ], "poodle")
     result = solve_puzzle(puzzle, similarity)
     assert result == (0.25, 'poodle.n.01', 'beagle')
Ejemplo n.º 6
0
 def test_solve_puzzle(self):
     similarity = TaxonomySimilarity(self.taxonomy)
     puzzle = OddOneOutPuzzle("'Turkey_Wrap'",
                              ["'Candied_Sweet_Potatoes'", 
                               "'Holiday_Stuffing'",
                               "'Whole,_Roasted_Turkey_with_Stuffing'",
                               "'Yam_Casserole'"],
                              "'Thanksgiving_recipes'")
     result = solve_puzzle(puzzle, similarity)
     assert result == (0.1, "'Thanksgiving_recipes'", "'Turkey_Wrap'")
Ejemplo n.º 7
0
def solve_puzzle_optimized():
    rows, columns, tiles = get_board_state()
    solution = solve_puzzle(rows, columns, tiles)
    assert solution is not None, 'Failed to solve puzzle.'
    solution = optimize_solution(solution)
    if rospy.get_param('verbose'):
        print('\n')
        display_solution(rows, columns, solution, scale=4, offset=4)
        print('\n')
        for tile in solution:
            rospy.loginfo('Tile: ({}, {}), type={}, rotations={}'.format(tile.row, tile.column, tile.tile_name, tile.rotations))
    return solution
Ejemplo n.º 8
0
def generate_rand_grid(n):
    while True:
        num_arr = []
        for i in range(0, n):
            row = []
            for j in range(0, n):
                row.append(random.randint(1, n - 1))
            num_arr.append(row)
        num_arr[n - 1][n - 1] = 0
        grid2, value, solution = solver.solve_puzzle(num_arr, n)
        if value > 0:
            return num_arr
Ejemplo n.º 9
0
def generate_grid(grid, size):
    orig_grid = list(grid)
    while True:
        rand_coord = [random.randint(0, size - 1), random.randint(0, size - 1)]
        rand_mag = random.randint(1, size - 1)
        if not (rand_coord == [size - 1, size - 1]
                ) and rand_mag != grid[rand_coord[0]][rand_coord[1]]:
            grid_gen = grid[:]
            grid_gen[rand_coord[0]][rand_coord[1]] = rand_mag
            grid_s, value_gen, solution_s = solver.solve_puzzle(grid_gen, size)
            if value_gen > 0:
                return grid_gen, grid_s, value_gen, solution_s
            else:
                grid = list(orig_grid)
def solve_a_puzzle(puz_file, component_list_path,mode=1,limit=300,score_adjust=20):
    print puz_file
    all_output,comps_eval = components_eval.run_all_components(puz_file, component_list_path, False)
    print "TESTING JFAN" 
    print "ALL OUTPUT"
    print all_output
    print "COMPS EVAL"
    print comps_eval
    print " ____________________"
    p = puzzle.Puzzle(puz_file)
    print p.get_initial_state()
    print p.get_all_clues()
    print p.get_grid()
    solver_evaluation,solution = solver.solve_puzzle(p,all_output,mode,limit,score_adjust)
    return p.get_side_by_side_comparison(), solver_evaluation, comps_eval, solution
Ejemplo n.º 11
0
def solve_a_puzzle(puz_file, component_list_path,mode=1,limit=300,score_adjust=20, n=1, second_round=True):
    print puz_file
    picklefile = 'cache/' + puz_file.replace('.', '').replace('/', '') + '.dat'
    try:
        all_output, comps_eval = pickle.load(open(picklefile))
    except IOError:
        # doesn't exist
        all_output,comps_eval = components_eval.run_all_components(puz_file, component_list_path, False)
        pickle.dump((all_output, comps_eval), open(picklefile, 'w'))

    print "####################### finished component ####################### "
    
    p = puzzle.Puzzle(puz_file)
    print p.get_initial_state()
    print p.get_all_clues()
    print p.get_grid()
    solver_evaluation,solution = solver.solve_puzzle(p,all_output,mode,limit,score_adjust, n=n, second_round=second_round)
    return p.get_side_by_side_comparison(), solver_evaluation, comps_eval, solution
Ejemplo n.º 12
0
def solve_a_puzzle(puz_file, component_list_path,mode=1,limit=300,score_adjust=20):

    start = time.time()
    print puz_file

    #get all candidate words
    all_output,comps_eval = components_eval.run_all_components(puz_file, component_list_path, False)
    #all_output,comps_eval = components_eval_multi.run_all_components(puz_file, component_list_path, False)

    p = puzzle.Puzzle(puz_file)

    print p.get_initial_state()
    print p.get_all_clues()
    print p.get_grid()

    solver_evaluation,solution = solver.solve_puzzle(p,all_output,mode,limit,score_adjust)

    end = time.time()
    print "Overall time: ", end-start 
    return p.get_side_by_side_comparison(), solver_evaluation, comps_eval, solution
Ejemplo n.º 13
0
def doAnneal(grid, size, iters, temp_init, decay):
    grid2, value, solution = solver.solve_puzzle(grid, size)
    best_val = value
    prev_val = best_val
    best_found = False
    best_grid = list(grid)
    grid_gen = list(grid)
    best_grid_s = list(grid2)
    best_sol = solution
    accept_prob = 1
    iter_vals = []
    for i in range(iters):
        prev_grid = deepcopy(grid_gen)
        grid_gen, grid_s, value_gen, solution_s = generate_grid(grid_gen, size)
        try:
            accept_prob = math.exp((value_gen - prev_val) / (1.0 * temp_init))
        except:
            accept_prob = 1
        rand_val = random.uniform(0, 1)
        # print("Prev Val: " + str(prev_val) + "\nGen Val: " + str(value_gen) + "\nTemp: " + str(temp_init) + "\nAccept prob: " + str(accept_prob)  + "\nRandom Value: " + str(rand_val) + "\n---------------")
        prev_val = value_gen
        if value_gen >= best_val:
            best_found = True
            best_val = value_gen
            best_grid = grid_gen
            best_grid_s = grid_s
            best_sol = solution_s
        elif best_found and rand_val > accept_prob:
            grid_gen = prev_grid
        temp_init *= decay
        iter_vals.append(best_val)
        temp_init = max(.01, temp_init)
    best_grid = np.array(best_grid).tolist()
    best_grid = [item for sublist in best_grid for item in sublist]
    best_grid_s = np.array(best_grid_s).tolist()
    best_grid_s = [item for sublist in best_grid_s for item in sublist]
    if best_val > 0:
        best_sol = "Puzzle Value: " + str(best_val) + "\n" + best_sol
        # best_sol = "Puzzle Value: " + str(best_val) + "\n" + best_sol + "\nIterations: " + str(i) + "\nCompute Time: " + "{0:.2f}".format(end - start) + "s"

    return best_grid, best_grid_s, best_val, best_sol, i + 1, iter_vals
Ejemplo n.º 14
0
def main():
    """Run the end to end solver program.
    
    This will run a loop to continually re-capture images 
    when SPACE is pressed until the solver finds a valid solution
    
    If a GPU is available, this will be used to run real-time inference 
    displayed back on the input image at ~20 FPS
    """

    logger.info('-' * 10 + ' new run ' + '-' * 10)
    
    # load puzzle semantic segmentation model, download from GCS if not done already
    p = Predictor('../models/best_model_3.pth')
    auto_capture = False
    
    while True:
        try:
            image = p.video_overlay(capture=True, pred_size=False, auto_capture=auto_capture) 
            boxes = process_image(image, debug=True)  # process captured image

            start_numbers, inequals = scan_images(boxes) # run ocr

            logger.debug(f'inequals: {inequals}')
            
            print('Solutions:')
            status = solve_puzzle(start_numbers, inequals)

            if status != 0:
                logger.info('-' * 10 + ' run exiting ' + '-' * 10)
                return status
            
        except KeyboardInterrupt:
            raise            
            
        except Exception:
            auto_capture = True
            pass
Ejemplo n.º 15
0
def solve():
    print(clusters)
    solution = solver.solve_puzzle(clusters)
    return json.dumps(str(solution))
Ejemplo n.º 16
0
                used[tile] = (new_letter, new_color)
                current += 1
            letter, color = used[tile]
            print(colored(letter, color), end='')
        print('')


parser = argparse.ArgumentParser()
parser.add_argument('difficulty', choices=list(puzzles.keys()))
parser.add_argument('level', type=int)
args = parser.parse_args()

difficulty = args.difficulty
level = args.level - 1

if (level not in range(len(puzzles[difficulty]))) or (
        puzzles[difficulty][level]['puzzle'] is None):
    parser.error(
        f"Level {args.level} does not have a puzzle for difficulty {difficulty}"
    )

begin = time.monotonic()
puzzle = puzzles[difficulty][level]['puzzle']
solution = solve_puzzle(puzzle)
end = time.monotonic()
print_puzzle(puzzle)
print(
    f'Solved puzzle {args.level} of the {args.difficulty} levels in {round(end - begin, 2)} seconds'
)
print_solution(solution)
Ejemplo n.º 17
0
def main():
    global solved, run
    solved = False
    DISPLAY_WI, DISPLAY_HE = 680, 570
    FPS = 30
    WIN = pygame.display.set_mode((DISPLAY_WI, DISPLAY_HE))
    pygame.display.set_caption("My Sudoku")
    clock = pygame.time.Clock()
    main_font = pygame.font.SysFont("comicsans", 30)
    # Variables
    mistakes = 0
    won = False
    board = make_puzzle()
    grid = Grid(board)
    solved_board = deepcopy(board)
    solve_puzzle(solved_board)
    run = True

    def redraw_window():
        WIN.fill((200, 200, 200))

        # Draw grid
        if not solved:
            grid.draw(WIN)
        else:
            solved_grid = Grid(solved_board)
            solved_grid.draw(WIN)

        # Draw text
        mistakes_label = main_font.render(f"Mistakes: {mistakes}", True,
                                          (255, 255, 255))
        WIN.blit(mistakes_label, (10, DISPLAY_HE - 30))

        # Draw buttons
        button(WIN, "New Puzzle", DISPLAY_WI - 135, 10, 120, 50,
               (255, 255, 255), (127, 152, 240), new_puzzle)
        button(WIN, "Solve Puzzle", DISPLAY_WI - 135, 70, 120, 50,
               (255, 255, 255), (127, 152, 240), do_solve)
        button(WIN, "Quit Game", DISPLAY_WI - 135, DISPLAY_HE - 90, 120, 50,
               (255, 255, 255), (127, 152, 240), quit_game)

        # Draw victory text
        if won:
            victory_label = main_font.render("Completed", True,
                                             (127, 152, 240))
            WIN.blit(victory_label,
                     (DISPLAY_WI - victory_label.get_width() - 30, 130))

        # Update
        pygame.display.update()

    while run:
        clock.tick(FPS)
        redraw_window()

        # Activate select function in grid
        grid.select()

        # Key press
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
            if event.type == pygame.KEYDOWN and grid.selected_square.real_value == 0:
                if event.key == pygame.K_1:
                    grid.selected_square.temp_value = 1
                if event.key == pygame.K_2:
                    grid.selected_square.temp_value = 2
                if event.key == pygame.K_3:
                    grid.selected_square.temp_value = 3
                if event.key == pygame.K_4:
                    grid.selected_square.temp_value = 4
                if event.key == pygame.K_5:
                    grid.selected_square.temp_value = 5
                if event.key == pygame.K_6:
                    grid.selected_square.temp_value = 6
                if event.key == pygame.K_7:
                    grid.selected_square.temp_value = 7
                if event.key == pygame.K_8:
                    grid.selected_square.temp_value = 8
                if event.key == pygame.K_9:
                    grid.selected_square.temp_value = 9
                if event.key == pygame.K_DELETE:
                    grid.selected_square.temp_value = 0
                if event.key == pygame.K_BACKSPACE:
                    grid.selected_square.temp_value = 0
                if event.key == pygame.K_RETURN and grid.selected_square.temp_value != 0:
                    row = grid.selected_square.row
                    col = grid.selected_square.col
                    if grid.selected_square.temp_value == solved_board[row][
                            col]:
                        grid.selected_square.real_value = grid.selected_square.temp_value
                        grid.selected_square.temp_value = 0
                        board[row][col] = solved_board[row][col]
                    else:
                        mistakes += 1
                        grid.selected_square.temp_value = 0

        if 0 not in [board[row][col] for col in range(9) for row in range(9)]:
            won = True
Ejemplo n.º 18
0
 def setUp(self):
     self.p = solve_puzzle('000801000000000430500000000000070800000000100020030000600000075003400000000200600',
                  "Puzzle Name")
Ejemplo n.º 19
0
def test_search_solve():
    solution = solver.solve_puzzle(search_puzzle)
    str_solution = solver.convert_solution(solution)
    assert str_solution == search_solution
Ejemplo n.º 20
0
 def test_solve_puzzle3(self):
     similarity = TaxonomySimilarity(self.example)
     puzzle = OddOneOutPuzzle("red",
                              ['orange', 'lime'],
                              "citrus")
     assert solve_puzzle(puzzle, similarity) is None
Ejemplo n.º 21
0
 def setUp(self):
     self.p = solve_puzzle('286000004530208100000030082000400610002315800054006000640070000005904068300000479',
                  "Puzzle Name")
Ejemplo n.º 22
0
 def test_solve_puzzle2(self):
     similarity = TaxonomySimilarity(self.example)
     puzzle = OddOneOutPuzzle("apple",
                              ['orange', 'peach', 'red'],
                              "color")
     assert solve_puzzle(puzzle, similarity) is None
Ejemplo n.º 23
0
def doGenetic(grid, size, iters, initial_pop, num_child, mutation_rate):
    current_pop = []
    if initial_pop % 2 == 1:
        initial_pop += 1
    for i in range(initial_pop):
        grid_gen, value_gen = generate_rand_grid(size)
        current_pop.append([grid_gen, value_gen])
    current_pop.sort(key=itemgetter(1), reverse=True)
    iter_vals = []
    for j in range(iters):
        children = []
        for k in range(0, len(current_pop) - 1, 2):
            for ch in range(num_child):
                curr_parent1 = deepcopy(current_pop[k][0])
                curr_parent2 = deepcopy(current_pop[k + 1][0])
                while True:
                    rand_x = random.sample(range(0, (size)), 2)
                    rand_y = random.sample(range(0, (size)), 2)
                    rand_x_start = rand_x[0]
                    rand_x_end = rand_x[1]
                    rand_y_start = rand_y[0]
                    rand_y_end = rand_y[1]

                    if rand_x_start >= rand_x_end:
                        temp = rand_x_start
                        rand_x_start = rand_x_end
                        rand_x_end = temp
                    if rand_y_start >= rand_y_end:
                        temp = rand_y_start
                        rand_y_start = rand_y_end
                        rand_y_end = temp
                    if [rand_x_end, rand_y_end] != [size - 1, size - 1]:
                        break
                tmp_chromo1 = []
                tmp_chromo2 = []
                for num in range(rand_x_start, rand_x_end):
                    for num2 in range(rand_y_start, rand_y_end):
                        tmp_chromo1.append(curr_parent1[num][num2])
                        tmp_chromo2.append(curr_parent2[num][num2])
                count = 0
                rand_val1 = random.uniform(0, 1)
                rand_val2 = random.uniform(0, 1)
                for num in range(rand_x_start, rand_x_end):
                    for num2 in range(rand_y_start, rand_y_end):
                        if rand_val1 < mutation_rate:
                            tmp_chromo1[count] = random.randint(1, (size) - 1)
                        if rand_val2 < mutation_rate:
                            tmp_chromo2[count] = random.randint(1, (size) - 1)
                        curr_parent1[num][num2] = tmp_chromo2[count]
                        curr_parent2[num][num2] = tmp_chromo1[count]
                        count += 1
                children.append(curr_parent1)
                children.append(curr_parent2)
        if len(children) % 2 == 1:
            children = children[:len(children) - 2]
        current_pop = []
        for l in children:
            grid2, value, solution = solver.solve_puzzle(l, size)
            current_pop.append([l, value])
        current_pop.sort(key=itemgetter(1), reverse=True)
        iter_vals.append(current_pop[0][1])
        # for i in current_pop:
        #     print(i[1])
        # print("--------------------")
        current_pop = current_pop[:initial_pop]

    best_grid = np.array(current_pop[-1][0]).tolist()
    best_grid_s, best_val, best_sol = solver.solve_puzzle(best_grid, size)
    best_grid = [item for sublist in best_grid for item in sublist]
    best_grid_s = np.array(best_grid_s).tolist()
    best_grid_s = [item for sublist in best_grid_s for item in sublist]
    if best_val > 0:
        best_sol = "Puzzle Value: " + str(best_val) + "\n" + best_sol
        # best_sol = "Puzzle Value: " + str(best_val) + "\n" + best_sol + "\nIterations: " + str(i) + "\nCompute Time: " + "{0:.2f}".format(end - start) + "s"

    return best_grid, best_grid_s, best_val, best_sol, iter_vals