Пример #1
0
    def render_once(self):
        self.screen.fill(rgb("black"))
        for wall in self.walls:
            self.screen.blit(self.wall_image, wall.rect)
        self.screen.blit(self.end_image, self.end_rect)
        draw_grid(self.screen, len(self.labyrinth[0]), len(self.labyrinth),
                  "darkgray")

        pygame.display.update()
Пример #2
0
 def predict(self, episode=1000):
     for e in range(episode):
         curr_s = self.env.reset()  # new episode
         while not self.env.is_terminal(curr_s):  # for every time step
             a = self.select_action(curr_s, policy='greedy')
             r = self.env.rewards(curr_s, a)
             next_s = self.env.next_state(curr_s, a)
             self.V[curr_s] += self.alpha \
                 * (r+self.gamma*self.V[next_s] - self.V[curr_s])
             curr_s = next_s
     # result display
     draw_grid(self.env, self, p=True, v=True, r=True)
Пример #3
0
 def predict(self, episode=1000):
     for e in range(episode):
         curr_s = self.env.reset()  # new episode
         while not self.env.is_terminal(curr_s):  # for every time step
             a = self.select_action(curr_s, policy='greedy')
             r = self.env.rewards(curr_s, a)
             next_s = self.env.next_state(curr_s, a)
             self.V[curr_s] += self.alpha \
                 * (r+self.gamma*self.V[next_s] - self.V[curr_s])
             curr_s = next_s
     # result display
     draw_grid(self.env, self, p=True, v=True, r=True)
Пример #4
0
    def control(self, method):
        assert method == 'qlearn' or method == 'sarsa'

        if method == 'qlearn':
            agent = Qlearn(self.env, self.epsilon, self.gamma)
        elif method == 'sarsa':
            agent = SARSA(self.env, self.epsilon, self.gamma)

        while agent.episode < self.max_episodes:
            agent.learn(agent.act())

        # resutl display
        draw_grid(self.env, agent, p=True, v=True, r=True)
        # draw episode steps
        draw_episode_steps(agent.avg_step_set)
Пример #5
0
    def control(self, method):
        assert method in ("qlearn", "sarsa")

        if method == "qlearn":
            agent = Qlearn(self.env, self.epsilon, self.gamma)
        else:
            agent = SARSA(self.env, self.epsilon, self.gamma)

        while agent.episode < self.max_episodes:
            agent.learn(agent.act())

        # result display
        draw_grid(self.env, agent, p=True, v=True, r=True)
        # draw episode steps
        draw_episode_steps(agent.avg_step_set)
Пример #6
0
    def control(self, method):
        assert method == 'qlearn' or method == 'sarsa'

        if method == 'qlearn':
            agent = Qlearn(self.env, self.epsilon, self.gamma)
        elif method == 'sarsa':
            agent = SARSA(self.env, self.epsilon, self.gamma)

        while agent.episode < self.max_episodes:
            agent.learn(agent.act())

        # resutl display
        draw_grid(self.env, agent, p=True, v=True, r=True)
        # draw episode steps
        draw_episode_steps(agent.avg_step_set)
Пример #7
0
def solve():

    grid = request.json.get("grid", [])
    logger.info("Call sudoku solver with grid: %s", grid)

    logger.info("Initializing sudoku...")
    sudoku = Sudoku(grid)
    logger.info("Sudoku initialized: %s", draw_grid(grid))

    logger.info("Try to solve sudoku")
    sudoku.solve()
    logger.info("Sudoku solved!")
    solution = sudoku.get_grid()
    logger.info("Returning solution for sudoku: %s", draw_grid(solution))
    return jsonify(status="ok", grid=solution)
Пример #8
0
 def solve(self) -> None:
     if not self.__is_valid(
     ):  # если грид не удовлетворяет правилам судоку - поднимаем ошибку
         raise ValueError('Sudoku rules are violated')
     while True:
         logger.debug("New iteration. Current sudoku status: %s",
                      draw_grid(self.get_grid()))
         is_any_cell_solved = False
         logger.debug("Using basic rules...")
         for i, j in product(range(9), range(9)):
             if not self.__rows[i][j].is_solved:
                 self.__rows[i][j].exclude(self.__rows[i])
                 self.__rows[i][j].exclude(self.__columns[j])
                 self.__rows[i][j].exclude(self.__get_square(i, j))
                 is_any_cell_solved |= self.__rows[i][j].is_solved
         if not is_any_cell_solved:
             logger.debug("Using Exclude Equal Alternatives method...")
             for grid_view in [self.__rows, self.__columns, self.__squares]:
                 is_any_cell_solved |= self.__exclude_equal_alternatives(
                     grid_view)
         if not is_any_cell_solved:
             break
         logger.debug("Some new cells are solved")
Пример #9
0
    def render(self):
        if not self.rendered_once:
            self.render_once()
            self.rendered_once = True

        rects_to_draw = []

        for block in self.old_blocks:
            rects_to_draw.append(
                pygame.draw.rect(self.screen, rgb("black"), block.rect))

        draw_grid(self.screen, len(self.labyrinth[0]), len(self.labyrinth),
                  "darkgray")

        for i, block in enumerate(self.blocks):
            if i == self.selected_block:
                if block.new_direction == "left":
                    selected_rect = self.screen.blit(self.block_left,
                                                     block.rect)
                elif block.new_direction == "right":
                    selected_rect = self.screen.blit(self.block_right,
                                                     block.rect)
                elif block.new_direction == "down":
                    selected_rect = self.screen.blit(self.block_down,
                                                     block.rect)
                elif block.new_direction == "up":
                    selected_rect = self.screen.blit(self.block_up, block.rect)
                else:
                    selected_rect = self.screen.blit(self.block_standing,
                                                     block.rect)
            else:
                if block.new_direction == "left":
                    selected_rect = self.screen.blit(
                        self.block_unselected_left, block.rect)
                elif block.new_direction == "right":
                    selected_rect = self.screen.blit(
                        self.block_unselected_right, block.rect)
                elif block.new_direction == "down":
                    selected_rect = self.screen.blit(
                        self.block_unselected_down, block.rect)
                elif block.new_direction == "up":
                    selected_rect = self.screen.blit(self.block_unselected_up,
                                                     block.rect)
                else:
                    selected_rect = self.screen.blit(
                        self.block_unselected_standing, block.rect)

            rects_to_draw.append(selected_rect)

            number = self.number_font.render(str(block.number_id), 0,
                                             rgb("lightgreen"))
            # This rect should be inside the Userblock rect
            # so there is no need to put it in the rects to draw
            self.screen.blit(
                number,
                (
                    block.rect.x +
                    (self.block_size[0] / 2 - number.get_width() / 2),
                    block.rect.y +
                    (self.block_size[1] / 2 - number.get_height() / 2),
                ),
            )

        bottom_left_wall = Wall(
            (0, SCREEN_HEIGTH - self.block_size[1]),
            self.block_size[0],
            self.block_size[1],
        )
        rects_to_draw.append(
            self.screen.blit(self.wall_image, bottom_left_wall.rect))

        timer = self.timer_font.render(str(self.seconds_left), 0,
                                       rgb("yellow"))
        rects_to_draw.append(
            self.screen.blit(
                timer,
                (
                    self.block_size[0] / 2 - (timer.get_width() / 2),
                    SCREEN_HEIGTH - self.block_size[1] +
                    timer.get_height() / 2,
                ),
            ))

        pygame.display.update(rects_to_draw)
Пример #10
0
    plt.title('image')
    io.imshow(X_train[ix])
    plt.subplot(222)
    plt.title('elastic')
    io.imshow(elt_img)
    plt.subplot(223)
    io.imshow(Y_train[ix])
    plt.subplot(224)
    io.imshow(np.squeeze(elt_label))

if 0:
    ix = 267
    img = X_train[ix]
    label = Y_train[ix]
    label.dtype = np.uint8
    draw_grid(img, 50)
    alpha = img.shape[1] * 1
    sigma = img.shape[1] * 0.05
    elt_img = elastic_transform(img, alpha, sigma)
    elt_label = elastic_transform(label, alpha, sigma)
    elt_label.dtype = np.bool

    Y_train = np.squeeze(Y_train)
    plt.figure(figsize=(8, 8))
    plt.subplot(221)
    plt.title('image')
    io.imshow(X_train[ix])
    plt.subplot(222)
    plt.title('elastic')
    io.imshow(elt_img)
    plt.subplot(223)
Пример #11
0
def analyze(path, debug=False):
    try:
        info(f"Analyzing: {path}")
        # triggers = np.array([])
        # events = np.array([])
        triggers = []
        events = []
        frame_number = 0
        video_capture = cv2.VideoCapture(path)
        reference_frame = None
        start_time = time.monotonic()
        while True:

            status, frame = video_capture.read()

            if not status:
                new_triggers = ca.on_destroy(events)
                if new_triggers is not None:
                    triggers += new_triggers
                break

            resized_frame = ca.resize_frame(frame)

            background_removed = remove_v2(resized_frame)
            preprocessed = ca.preprocess_frame(background_removed)

            # if the first frame is None, initialize it
            if reference_frame is None:
                reference_frame = preprocessed
                continue

            contours = ca.get_contours(preprocessed, reference_frame)

            ca.extract_events(contours, events, frame_number, filename=path)

            new_triggers = ca.update_events(events, frame_number)

            if new_triggers is not None:
                triggers += new_triggers

            if debug:

                ca.annotate_frame(background_removed, events)

                utils.draw_grid(background_removed)

                preview = imutils.resize(background_removed, width=1500)
                cv2.imshow("Preview", preview)
                # Get the pressed key
                key = cv2.waitKey(1) & 0xFF
                if key == ord('q'):
                    new_events = ca.on_destroy(events)
                    if new_events is not None:
                        triggers = new_events
                    break
                if key == ord('s'):
                    with open("interesting", "a") as f:
                        f.write(path + frame_number + "\n")
                    info("Saved image")

            frame_number += 1

            now = time.monotonic()
            # if file takes more than 5 minutes stop
            if now - start_time > 5 * 60:
                err(f"Analyzing file took too long - stopping ({path})")
                new_triggers = ca.on_destroy(events)
                if new_triggers is not None:
                    triggers += new_triggers
                break

        frame_time = (time.monotonic() - start_time) / frame_number
        frame_rate = 60 / frame_time
        info(f"Framerate {frame_rate:.2f} fps")

        video_capture.release()
        cv2.destroyAllWindows()
    except Exception as error:
        raise error
        critical(f"analysys failed for file: {path} with: {error}")
        video_capture.release()
        cv2.destroyAllWindows()
        return triggers
    return triggers
Пример #12
0
            if event.user_type == pygame_gui.UI_BUTTON_PRESSED:
                if event.ui_element == dijkstra_btn:
                    pathfinder(dijkstra, "Dijkstra's Algorithm", WIN, ROWS,
                               WIN_WIDTH, LINE_HEIGHT)
                if event.ui_element == astar_btn:
                    pathfinder(astar, "A* Search", WIN, ROWS, WIN_WIDTH,
                               LINE_HEIGHT)
                if event.ui_element == greedy_best_first_btn:
                    pathfinder(greedy_best_first, "Greedy Best-first Search",
                               WIN, ROWS, WIN_WIDTH, LINE_HEIGHT)
                if event.ui_element == breadth_first_btn:
                    pathfinder(breadth_first, "Breadth-first Search", WIN,
                               ROWS, WIN_WIDTH, LINE_HEIGHT)
                if event.ui_element == depth_first_btn:
                    pathfinder(depth_first, "Depth-first Search", WIN, ROWS,
                               WIN_WIDTH, LINE_HEIGHT)
        pygame.display.set_caption("Path Finding Visualizer")
        manager.process_events(event)

    manager.update(time_delta)

    WIN.blit(background, (0, 0))
    manager.draw_ui(WIN)
    utils.draw_grid(WIN,
                    ROWS,
                    WIN_WIDTH,
                    line_height=LINE_HEIGHT,
                    btn_height=BTN_HEIGHT)
    pygame.display.update()

pygame.quit()