Exemple #1
0
    def makeFeedback(self,
                     keepBestPrevious=True,
                     keepValidOnly=False,
                     allMoves=False,
                     victoryPath=True,
                     discountRate=0.95,
                     interactive=False):
        hsize = 1000000
        feedback_dataset = []
        board_queue = [self]
        found_boards = [None for n in range(hsize)]
        found_boards[hash(self) % hsize] = {'board': self, 'feedback': []}
        winner_boards = []
        if interactive:
            vis = visualisation.Visualisation(self)

        while len(board_queue) > 0:
            # print(len(board_queue), len(feedback))
            current_board = randomPop(board_queue)
            if interactive:
                vis.new_board(current_board)
            if current_board.didWin():
                print('won!')
                winner_boards.append(hash(current_board) % hsize)
                if interactive:
                    vis.new_board(current_board, 2)
            else:
                for b, p in current_board.makeAllMoves(allMoves):
                    tested_board = copy.deepcopy(current_board)
                    feedback = tested_board.getMoveResponse(b, p[0], p[1])
                    if feedback['response']:
                        hash_val = hash(tested_board) % hsize
                        if found_boards[hash_val] is None:
                            board_queue.append(tested_board)
                            found_boards[hash_val] = {
                                'board': tested_board,
                                'feedback': feedback
                            }
                        elif keepBestPrevious:  # me quedo con el mejor?
                            if found_boards[hash_val][
                                    'board'].moves < tested_board.moves:
                                feedback['response'] = False
                            else:  # no era el mejor
                                found_boards[hash_val]['feedback'][
                                    'response'] = False
                                found_boards[hash_val]['feedback'] = feedback
                        feedback_dataset.append(feedback)
                    elif not keepValidOnly:  # keep only valid moves
                        feedback_dataset.append(feedback)

        if victoryPath:
            for f in feedback_dataset:
                f['response'] = -1

            for w in winner_boards:
                b = found_boards[w]
                distance = 0
                while len(b['feedback']) > 0:
                    # print(b['board'].toHuman())
                    b['feedback']['response'] = pow(discountRate, distance)
                    prev_board = b['feedback']['board']
                    hash_val = hash(prev_board) % hsize
                    b = found_boards[hash_val]
                    distance += 1
        else:
            for f in feedback_dataset:
                f['response'] = 1 if ['response'] else -1

        print('hash usage ' +
              str(sum([h is not None for h in found_boards]) / hsize))
        return feedback_dataset
    closed = dict()
    closed[root.get_hash()] = None
    stack = collections.deque()
    stack.append(root)

# start the timer
start = timer()

# get first route to solution
node = iterative_deepening(root)

# stop the timer
end = timer()

# get the moves to the winning state
moves = []
while closed[node] is not None:
    moves.append(closed[node][1])
    node = closed[node][0]
moves.reverse()

# print results
print "\nExplored %d states in %f seconds" % (len(closed), (end - start))
print "\nSolved in %d moves" % (len(moves))
print moves
print

# start visualisation if wanted
if raw_input("View visualisation of solution? (Y/N): ").lower() == 'y':
    vis = visualisation.Visualisation(root, moves)
Exemple #3
0
start = timer()

# get first route to solution
dfs()

# stop the timer
end = timer()

# get the shortest path to solution from all possible solutions
shortest_solution = list()
for node in solutions:
    solution = list()
    while closed[node] is not None:
        solution.append(closed[node][1])
        node = closed[node][0]

    # determine if solution is shorter than current shortest solution
    if len(shortest_solution) == 0 or len(shortest_solution) > len(solution):
        solution.reverse()
        shortest_solution = solution

# print results
print "\nExplored %d states in %f seconds" % (len(closed), (end - start))
print "\nFound %d solutions, shortest solution takes %d moves" % (len(solutions), len(shortest_solution))
print shortest_solution
print

# start visualisation if wanted
if raw_input("View visualisation of solution? (Y/N): ").lower() == 'y':
    vis = visualisation.Visualisation(root, shortest_solution)
            if vehicle[0]:
                self.board[vehicle[1]][vehicle[2]] = index
                self.board[vehicle[1]][vehicle[3]] = index
                if vehicle[3] - vehicle[2] > 1:
                    self.board[vehicle[1]][vehicle[2] + 1] = index

            # write indexes of vertical vehicle
            else:
                self.board[vehicle[2]][vehicle[1]] = index
                self.board[vehicle[3]][vehicle[1]] = index
                if vehicle[3] - vehicle[2] > 1:
                    self.board[vehicle[2] + 1][vehicle[1]] = index

        # replace '.' with None
        for row in range(Board.width):
            for col in range(Board.width):
                if self.board[row][col] == ".":
                    self.board[row][col] = None

        # update Board.width, other usages all require to subtract one from Board.width
        Board.width -= 1


string = ast.literal_eval(raw_input('Paste the string of the board board. For example: "..abbc..a..c..a??c...eddhgge..h..eff": '))
solution = ast.literal_eval(raw_input('Paste a solution. For example: [[0,1],[1,-2]]: '))

board = Board()
board.load(string)

vis = visualisation.Visualisation(board, solution)
    # Register a callback for CTRL+C
    signal.signal(signal.SIGINT, signal_handler)

    running, ser = sensors.initialize_serial('/dev/ttyUSB0')

    robot = go.EasyGoPiGo3()
    robot.set_speed(60)

    # Open the camera
    cap = cv2.VideoCapture(0)

    # Create timer
    timer = pg.QtCore.QTimer()

    # Initialize visualization logic
    visual = visualisation.Visualisation()
    visual.set_on_close_function(close, "Plotter window closed.")

    # Create fast_worker in a separate thread
    fast_thread = threading.Thread(target=loc.fast_worker,
                                   args=(running, robot, positions, ser,
                                         close))
    fast_thread.daemon = True
    fast_thread.start()

    # Connecting slow_worker to timer, it will be executed with certain interval
    timer.timeout.connect(slow_worker)

    # Start timer with interval 100 msec
    timer.start(100)