Ejemplo n.º 1
0
 def iconClickHandle(self, name):
     # down menu handlers
     if name == "restart":
         self.model.reInit()
         self.gameOver = False
         self.onPause = True
         # self.shuffleBoard()
         self.t.stop()
         self.t.delete()
         self.startGame()
         return
     if name == "bot":
         self.robotSolved = True
         s = Solver(self.model, self.n)
         self.loading = True
         solution, time = s.getSolution()
         self.loading = False
         print(time)
         self.shuffleAnimaion(solution)
     if name == "home":
         self.onMenu = True
         self.showMenu()
         self.t.stop()
     if name == "pause":
         self.onPauseMenu = True
         self.showPause()
         self.t.stop()
     if name == "play":
         self.onPauseMenu = False
         self.t.resume()
         self.draw()
Ejemplo n.º 2
0
 def __init__(self, model_dir=DEFAULT_MODEL_DIR, data_dir=DEFAULT_DATA_DIR, gpu=-1):
     self.data_dir = data_dir
     self.dataset_file = os.path.join(data_dir, "dataset.json")
     self.solver = Solver(dirname=model_dir, gpu=gpu)
     self.dataset = {}
     if os.path.exists(self.dataset_file):
         with open(self.dataset_file, "r") as fp:
             self.dataset = json.load(fp)
Ejemplo n.º 3
0
 def solveSudoku(self, board):
     """ 解决并打印数独 """
     time_s = time.time()
     solver = Solver()
     solved_board = solver.solveSudoku(board)
     time_e = time.time()
     # --------------------
     self.printBoard(solved_board)
     print('解决程序执行时间:{:.04f}秒, 共执行了{}次递归'.format(time_e - time_s,
                                                 solver.count))
Ejemplo n.º 4
0
def run_case(args):
    C = random_cube()
    original = Cube(C)
    solver = Solver(C)

    if args % 100000 == 0:
        print(args[0])

    training_data = []
    try:
        # print("Solving\n", original)
        solver.solve()
    except Exception as e:
        print(e)

    if not C.is_solved():
        print("Failed to solve. Rerunning with DEBUG = True")
        solve.DEBUG = True
        solver = Solver(Cube(original))
        solver.solve()
    else:
        check = Cube(original)
        for move in solver.moves:
            move_string = str(check).replace("\n", "").replace(" ", "")
            training_data.append([move_string, move])
            check.sequence(move)
        # check.sequence(" ".join(solver.moves))
        assert check.is_solved()
        # solved_string = str(check).replace("\n","").replace(" ", "")
        # print(str(check))
        # print(SOLVED_CUBE_STR)
        # assert solved_string == SOLVED_CUBE_STR
    return training_data
Ejemplo n.º 5
0
def main():
    problem = read_input(vocal=False)
    # print('Problem', problem)
    solver = Solver(problem)

    dep = solver.dependency_relation
    print('Dependency graph', dep)
    traces = solver.get_trace()
    print('Traces', traces)
    foata = solver.get_foata()
    print('Foata', foata)
    foata = solver.get_foata_from_graph()
    print('Foata', foata)
    solver.dependency_graph.plot()
Ejemplo n.º 6
0
def main(config):
    cudnn.benchmark = True
    if not os.path.exists(config.log_dir):
        os.makedirs(config.log_dir)
    if not os.path.exists(config.model_save_dir):
        os.makedirs(config.model_save_dir)
    if not os.path.exists(config.sample_dir):
        os.makedirs(config.sample_dir)
    if not os.path.exists(config.result_dir):
        os.makedirs(config.result_dir)

    celeba_loader = None
    rafd_loader = None
    if config.dataset in ['CelebA', 'Both']:
        celeba_loader = get_loader(config.celeba_image_dir, config.attr_path, config.selected_attrs,
                                   config.celeba_crop_size, config.image_size, config.batch_size,
                                   'CelebA', config.mode, config.num_workers)
    if config.dataset in ['RaFD', 'Both']:
        rafd_loader = get_loader(config.rafd_image_dir, None, None,
                                 config.rafd_crop_size, config.image_size, config.batch_size,
                                 'RaFD', config.mode, config.num_workers)

    print('zz')
    solver = Solver(celeba_loader, rafd_loader, config)
    print(solver)
Ejemplo n.º 7
0
 def testVector(self):
     solver = Solver()
     a = vector(2)
     solver.eq(vector([1, 2]) + a, vector([3, 3]))
     self.failUnlessAlmostEqual(float(a.x), 2)
     self.failUnlessAlmostEqual(float(a.y), 1)
     b = vector(2)
     solver.eq(a*b) # => solver.eq(a*b, 0)
     solver.eq(b.y, 2)
     self.failUnlessAlmostEqual(float(b.x), -1)
Ejemplo n.º 8
0
def count_number_successful():
    successes = 0
    failures = 0

    # moves_made = []
    avg_opt_moves = 0
    avg_moves = 0
    avg_time = 0
    while True:
        C = random_cube()
        solver = Solver(C)
        try:
            start = time.time()
            solver.solve()
            duration = time.time() - start
        except Exception as e:
            pass

        if C.is_solved():
            opt_moves = optimize_moves(solver.moves)
            print(opt_moves[0])
            successes += 1
            avg_moves = (avg_moves * (successes - 1) +
                         len(solver.moves)) / float(successes)
            avg_time = (avg_time *
                        (successes - 1) + duration) / float(successes)
            avg_opt_moves = (avg_opt_moves * (successes - 1) +
                             len(opt_moves)) / float(successes)
            # moves_made.append(len(solver.moves))
        else:
            failures += 1
            print("Failed (%s): %s" % (successes + failures, C.flat_str()))
        total = float(successes + failures)
        if (total == 1 or total % 100 == 0) and C.is_solved():
            print(
                "%s: %s successes (%.3f%% passing)" %
                (int(total), successes, 100 * successes / total), )
            print("moves=%s avg_moves=%0.3f" %
                  (len(solver.moves), avg_moves), )
            print(
                "opt_moves=%s avg_opt_moves=%0.3f" %
                (len(opt_moves), avg_opt_moves), )
            print("time=%0.3f avg_time=%0.3f" % (duration, avg_time))
Ejemplo n.º 9
0
 def testMatrix(self):
     solver = Solver()
     A = matrix([2, 2])
     solver.eq(A*vector([1, -1]), vector([2, 0]))
     solver.eq(A*vector([1, 1]), vector([0, 2]))
     self.failUnlessAlmostEqual(float(A[0, 0]), 1)
     self.failUnlessAlmostEqual(float(A[0, 1]), -1)
     self.failUnlessAlmostEqual(float(A[1, 0]), 1)
     self.failUnlessAlmostEqual(float(A[1, 1]), 1)
     B = matrix([2, 2])
     solver.eq(A*B, identitymatrix(2))
     self.failUnlessAlmostEqual(float(B[0, 0]), 0.5)
     self.failUnlessAlmostEqual(float(B[0, 1]), 0.5)
     self.failUnlessAlmostEqual(float(B[1, 0]), -0.5)
     self.failUnlessAlmostEqual(float(B[1, 1]), 0.5)
     self.failUnlessAlmostEqual(float((B * vector([2, 0]))[0]), 1)
     self.failUnlessAlmostEqual(float((B * vector([2, 0]))[1]), -1)
     self.failUnlessAlmostEqual(float((B * vector([0, 2]))[0]), 1)
     self.failUnlessAlmostEqual(float((B * vector([0, 2]))[1]), 1)
Ejemplo n.º 10
0
def run_case():
    C = random_cube()
    original = Cube(C)
    solver = Solver(C)
    try:
        print "Solving\n", original
        solver.solve()
    except Exception as e:
        print e

    if not C.is_solved():
        print "Failed to solve. Rerunning with DEBUG = True"
        solve.DEBUG = True
        solver = Solver(Cube(original))
        solver.solve()
    else:
        check = Cube(original)
        check.sequence(" ".join(solver.moves))
        assert check.is_solved()
        assert str(check) == SOLVED_CUBE_STR
Ejemplo n.º 11
0
class AutoAnnotator:
    def __init__(self, model_dir=DEFAULT_MODEL_DIR, data_dir=DEFAULT_DATA_DIR, gpu=-1):
        self.data_dir = data_dir
        self.dataset_file = os.path.join(data_dir, "dataset.json")
        self.solver = Solver(dirname=model_dir, gpu=gpu)
        self.dataset = {}
        if os.path.exists(self.dataset_file):
            with open(self.dataset_file, "r") as fp:
                self.dataset = json.load(fp)

    def run(self):
        for giffile in sorted(glob.glob(os.path.join(self.data_dir, "*.gif"))):
            key = os.path.basename(giffile)
            if key in self.dataset:
                entry = self.dataset[key]
                if 'text' in entry and len(entry['text']) != 0:
                    print("{}: annotation already exists. skip.".format(key))
                    continue
            text, bbox, score = self.solver.solve(giffile)
            self.dataset[key] = { 'file': key, 'text': text, 'bbs': bbox.tolist() }
        with open(os.path.join(self.data_dir, "dataset.json"), "w") as fp:
            json.dump(self.dataset, fp, indent=2)
Ejemplo n.º 12
0
def main():
    solver = Solver(inputs, debug=1)
    res = solver.solve(depth = 10)

    print(f"Best move: {res.best_move}")
    yc = []
    for line in gcode:
        if 'X' in line:
            xc.append(float(line.split('X')[1].split(' ')[0]))
        if 'Y' in line:
            yc.append(float(line.split('Y')[1].split(' ')[0]))

    return xc, yc


#########################

#And now to actually generate gcode

#First solve the puzzle
solver = Solver(puzzle_filename, words_filename)
paths = solver.solve()

#Generate and rotate gcode
gcode = generate_gcode(paths)
gcode = rotate_gcode(gcode)

#Write gcode file
gcode_file = open("puzzle.gcode", "w+")
for line in gcode:
    gcode_file.write(line)

gcode_file.close()

#Plot
xc, yc = get_all_coordinates(gcode)
Ejemplo n.º 14
0
def main():
    """ Main program for playing the game. """
    pg.init()
    clock = pg.time.Clock()
    fps = 60
    pg.display.set_caption('Tricky Circles')
    icon = pg.image.load('resources/icon.jpg')
    pg.display.set_icon(icon)

    # Create display
    screen = pg.display.set_mode(SCREEN_SIZE)

    # Load resources such as wallpaper and fonts
    bg = pg.image.load('resources/desert.jpg')
    font = pg.font.Font('resources/western.ttf', 30)
    font_big = pg.font.Font('resources/western.ttf', 50)

    # Create buttons
    space = 50  # Space in between action buttons: a, b, x
    button_x = pg.Rect((WIDTH / 2 - BUTTON_WIDTH / 2, 250), BUTTON_SIZE)
    button_a = pg.Rect((button_x.x - space - BUTTON_WIDTH, button_x.y),
                       BUTTON_SIZE)
    button_b = pg.Rect((button_x.x + space + BUTTON_WIDTH, button_x.y),
                       BUTTON_SIZE)

    button_solve = pg.Rect((10, 0), BUTTON_SIZE)
    button_reset = pg.Rect((BUTTON_WIDTH + 20, button_solve.y), BUTTON_SIZE)
    button_info = pg.Rect((WIDTH - BUTTON_WIDTH / 2, button_solve.y),
                          BUTTON_SMALL)

    button_difficulty = pg.Rect((WIDTH / 2 - BUTTON_WIDTH / 2, 0), BUTTON_SIZE)
    button_min = pg.Rect(button_difficulty.topleft, BUTTON_SMALL)
    button_plus = pg.Rect(button_difficulty.midtop, BUTTON_SMALL)

    buttons = {
        'A': button_a,
        'X': button_x,
        'B': button_b,
        'Solve': button_solve,
        'Reset': button_reset,
        '-': button_min,
        '+': button_plus,
        '?': button_info
    }

    # Create starting level
    difficulty = 4  # Number of circles
    level_maker = CreateLevels()
    level = level_maker.get_random(difficulty)
    solver = Solver(level)
    min_moves, _ = solver.solve()  # Minimum moves needed to solve level

    # Creates Drawer for drawing levels
    drawer = Drawer(screen, WIDTH, level)
    drawer.draw_level(font, bg, min_moves, buttons, animation=False)

    auto_solve = False

    while True:

        if level.circles == level.answer:  # Level is solved

            # Draw finish-screen, depending on how level was solved
            if auto_solve:
                new_level = drawer.draw_solved(font_big, "Try it yourself?")
                auto_solve = False
            elif level.counter == min_moves:
                new_level = drawer.draw_solved(font_big, "Perfect score!")
            else:
                new_level = drawer.draw_solved(
                    font_big, "Solved in {} moves!".format(level.counter))

            if new_level:
                # Start a new game
                print('New game')
                level = level_maker.get_random(difficulty)
                drawer.level = level
                solver = Solver(level)
                min_moves, _ = solver.solve()
            else:
                # Reset level to try again
                print('Retry level')
                level.reset()

            drawer.draw_level(font, bg, min_moves, buttons, animation=False)

        for event in pg.event.get():

            # Quit when exit-button is clicked
            if event.type == pg.QUIT:
                pg.quit()
                exit()

            if event.type == pg.MOUSEBUTTONDOWN:
                mouse_pos = event.pos  # Get mouse position

                # Checks if mouse position is over a button
                # Perform corresponding action
                if button_info.collidepoint(*mouse_pos):
                    print('Show info')
                    drawer.show_help()

                if button_a.collidepoint(*mouse_pos):
                    print('A clicked, ', level.counter + 1)
                    drawer.animate_ab(font, bg, min_moves, buttons, 'a')
                    level.click_a()
                if button_b.collidepoint(*mouse_pos):
                    print('B clicked, ', level.counter + 1)
                    drawer.animate_ab(font, bg, min_moves, buttons, 'b')
                    level.click_b()
                if button_x.collidepoint(*mouse_pos):
                    print('X clicked, ', level.counter + 1)
                    drawer.animate_x(font, bg, min_moves, buttons)
                    level.click_x()

                if button_reset.collidepoint(*mouse_pos):
                    print("Reset level")
                    level.reset()

                if button_difficulty.collidepoint(*mouse_pos):
                    changed = False

                    # Check whether - or + was clicked
                    if button_min.collidepoint(*mouse_pos):
                        if difficulty > 4:  # 4 is minimum
                            difficulty -= 1
                            changed = True
                    else:
                        if difficulty < 8:  # 8 is maximum
                            difficulty += 1
                            changed = True

                    if changed:  # When minimum/maximum was not exceeded
                        print("Set difficulty {}".format(difficulty))

                        # Create new level with new difficulty
                        level = level_maker.get_random(difficulty)
                        drawer.level = level
                        solver = Solver(level)
                        min_moves, _ = solver.solve()

                if button_solve.collidepoint(*mouse_pos):
                    print('Show solution')
                    auto_solve = True

                    # Get solution for current level-state
                    # Solution is represented by sequence of actions to perform
                    solver = Solver(level)
                    _, min_actions = solver.solve()

                    # Execute and animate each action separately
                    for action in min_actions:
                        if action == 'a':
                            drawer.animate_ab(font, bg, min_moves, buttons,
                                              'a')
                            level.click_a()
                        if action == 'b':
                            drawer.animate_ab(font, bg, min_moves, buttons,
                                              'b')
                            level.click_b()
                        if action == 'x':
                            drawer.animate_x(font, bg, min_moves, buttons)
                            level.click_x()

                        # Redraw Level after each animated action
                        drawer.draw_level(font,
                                          bg,
                                          min_moves,
                                          buttons,
                                          animation=False)
                        pg.display.update()
                        pg.time.delay(500)  # So that animation can be followed

                # Redraw Level after each event
                drawer.draw_level(font,
                                  bg,
                                  min_moves,
                                  buttons,
                                  animation=False)

        pg.display.update()
        clock.tick(fps)
Ejemplo n.º 15
0
 def testScalars(self):
     solver = Solver()
     a = scalar()
     solver.eq(2 + a, 3)
     self.failUnlessAlmostEqual(float(a), 1)
     self.failUnlessRaises(RuntimeError, solver.eq, 2 + a, 3) # the solver is broken after that
     solver = Solver()
     a = scalar()
     b = scalar()
     solver.eq(2*a, b)
     solver.eq(2 + a + b, 5)
     self.failUnlessAlmostEqual(float(a), 1)
     self.failUnlessAlmostEqual(float(b), 2)
     a = scalar()
     b = scalar()
     solver.eq(a, b)
     self.failUnlessRaises(Exception, solver.eq, a, b)
Ejemplo n.º 16
0
import matplotlib.animation as animation
import matplotlib.pyplot as plt
import numpy as np

from solve import Solver


#Boundary conditions
def fn(x):
    return 1.5 + np.tanh(x)


solver = Solver(101, [-2, 15], fn, CFL=0.01)

#Plot
line, = plt.plot(solver.xs, solver.u)
txt = plt.text(0.1, 0.9, 't = 0', transform=plt.gca().transAxes)
plt.xlabel('x')
plt.ylabel('y')
plt.minorticks_on()
plt.tick_params(which='both', top=True, right=True, direction='in')


#Animate
def animate(t):
    while solver.t < t:
        solver.next()
    txt.set_text('t = %f' % (solver.t))
    line.set_ydata(solver.u)

Ejemplo n.º 17
0
 def __init__(self):
     self.row = ROW
     self.col = COL
     self.solver = Solver()
     self.dig_list = [(8, 8)]
     self.bb = []
Ejemplo n.º 18
0
 def testTrafo(self):
     solver = Solver()
     A = trafo([2, 2])
     solver.eq(A.getmatrix()[0, 0], A.getmatrix()[1, 1]) # restrict to rotation + scaling + translation
     solver.eq(A.getmatrix()[0, 1], -A.getmatrix()[1, 0])
     solver.eq(A*vector([0, 1]), vector([-1, 2]))
     solver.eq(A*vector([1, 0]), vector([1, 4]))
     self.failUnlessEqual(float((A * vector([0, 0]))[0]), 1)
     self.failUnlessEqual(float((A * vector([0, 0]))[1]), 2)
     self.failUnlessEqual(float(A.getmatrix()[0, 0]), 0)
     self.failUnlessEqual(float(A.getmatrix()[0, 1]), -2)
     self.failUnlessEqual(float(A.getmatrix()[1, 0]), 2)
     self.failUnlessEqual(float(A.getmatrix()[1, 1]), 0)
     B = trafo([2, 2])
     solver.eq(A*B, identitytrafo(2))
     self.failUnlessEqual(float((B * vector([0, 0]))[0]), -1)
     self.failUnlessEqual(float((B * vector([0, 0]))[1]), 0.5)
     self.failUnlessEqual(float(B.getmatrix()[0, 0]), 0)
     self.failUnlessEqual(float(B.getmatrix()[0, 1]), 0.5)
     self.failUnlessEqual(float(B.getmatrix()[1, 0]), -0.5)
     self.failUnlessEqual(float(B.getmatrix()[1, 1]), 0)