Beispiel #1
0
def main():
    m40 = load_map('map-40.pickle')
    m10 = load_map('map-10.pickle')
    print("shortest_path(m10, 0, 2) = [0, 5, 3, 2]:", shortest_path(m10, 0, 2))
    print("shortest_path(m40, 5, 34) = [5, 16, 37, 12, 34]:",
          shortest_path(m40, 5, 34))
    print("shortest_path(m40, 8, 24) = [8, 14, 16, 37, 12, 17, 10, 24]",
          shortest_path(m40, 8, 24))
    print("shortest_path(m40, 5, 5) = [5]:", shortest_path(m40, 5, 5))
    print("shortest_path(m10, 6, 8) = None:", shortest_path(m10, 6, 8))
Beispiel #2
0
def test_route_planer():
    map_10 = load_map('map-10.pickle')
    show_map(map_10)

    map_40 = load_map('map-40.pickle')
    show_map(map_40)

    planner = RoutePlanner(map_40)
    path = planner.find_shortest_path(start=5, goal=34)

    if path == [5, 16, 37, 12, 34]:
        print("great! Your code works for these inputs!")
    else:
        print("something is off, your code produced the following:")
        print(path)
Beispiel #3
0
def test(pickle_file, answers):
    """
    Testing function for our shortest path solution.

    Args:
        pickle_file: A given pickle file representing a graph.
        answers: a list of tuples representing the expected output.

    Returns:
        Prints wether the test passed or not.
    """
    print('Testing: ', pickle_file)
    map = load_map(pickle_file)
    correct = 0
    for start, goal, answer_path in answers:
        path = shortest_path.get_shortest_path(map, start, goal)
        if path == answer_path:
            correct += 1
        else:
            print("For start:", start, "Goal:     ", goal, "Your path:", path,
                  "Correct:  ", answer_path)
    if correct == len(answers):
        print("All tests pass! Congratulations!")
    else:
        print("You passed", correct, "/", len(answers), "test cases")
    print('----------------------------------')
Beispiel #4
0
def test(shortest_path_function):
    map_40 = load_map('map-40.pickle')
    correct = 0
    for start, goal, answer_path in MAP_40_ANSWERS:
        path = shortest_path_function(map_40, start, goal)
        if path == answer_path:
            correct += 1
        else:
            print("For start:", start, "Goal:     ", goal, "Your path:", path,
                  "Correct:  ", answer_path)
    if correct == len(MAP_40_ANSWERS):
        print("All tests pass! Congratulations!")
    else:
        print("You passed", correct, "/", len(MAP_40_ANSWERS), "test cases")
Beispiel #5
0
def test(shortest_path_function):
    map_40 = load_map(
        '/Users/ad7073/Documents/Sharpen the saw/Udacity/DSAND/projects/Project 4/map-40.pickle'
    )
    correct = 0
    for start, goal, answer_path in MAP_40_ANSWERS:
        path = shortest_path_function(map_40, start, goal)
        if path == answer_path:
            correct += 1
        else:
            print("For start:", start, "Goal:     ", goal, "Your path:", path,
                  "Correct:  ", answer_path)
    if correct == len(MAP_40_ANSWERS):
        print("All tests pass! Congratulations!")
    else:
        print("You passed", correct, "/", len(MAP_40_ANSWERS), "test cases")
Beispiel #6
0
def test(shortest_path_function):
    """Test function for the shortest_path function.

    Args:
        shortest_path_function: A func representing the A* algorithm
            implementation to find the shortest path between two nodes in a
            graph
    """
    map_40 = load_map("map-40.pickle")
    correct = 0
    for start, end, answer_path in MAP_40_ANSWERS:
        path = shortest_path_function(map_40, start, end)
        if path == answer_path:
            correct += 1
        else:
            print("For start:", start)
            print("End:      ", end)
            print("Your path:", path)
            print("Correct:  ", answer_path)
    if correct == len(MAP_40_ANSWERS):
        print("All tests pass! Congratulations!")
    else:
        print("You passed", correct, "/", len(MAP_40_ANSWERS), "test cases")
Beispiel #7
0
def main():
    """
    Start a pygame version of minesweeper and enter the GUI event loop.
    """
    game = MinesweeperPygame(hp.load_map('1'))
    game.game_loop()
Beispiel #8
0
                heuristic_cost = dist(M.intersections[adjacent_node], M.intersections[goal])
                estimated_total_cost = total_to_adjacent + heuristic_cost
                heapq.heappush(frontier_q, (estimated_total_cost, adjacent_node))
                prev_nodes[adjacent_node] = current_node

    # We've explored the entire frontier and haven't reached the goal. Must be a disconnected graph.
    return 'No route found.'


if __name__ == "__main__":

    from helpers import load_map
    from tests import test

    # Tests on a connected map
    map_40 = load_map('/Users/ad7073/Documents/Sharpen the saw/Udacity/DSAND/projects/Project 4/map-40.pickle')

    assert shortest_path(map_40, 5, 5) == [5]  # Single hop route
    assert shortest_path(map_40, 5, 9000) == 'Invalid start or goal nodes.'  # Invalid goal node
    assert shortest_path(map_40, 5000, 5) == 'Invalid start or goal nodes.'  # Invalid start node

    assert shortest_path(map_40, 5, 34) == [5, 16, 37, 12, 34]  # Example routes
    assert shortest_path(map_40, 19, 24) == [19, 2, 36, 28, 31, 10, 24]
    assert shortest_path(map_40, 38, 11) == [38, 29, 22, 12, 17, 15, 11]

    # Tests on a disconnected map
    map_10 = load_map('/Users/ad7073/Documents/Sharpen the saw/Udacity/DSAND/projects/Project 4/map-10.pickle')
    assert shortest_path(map_10, 6, 4) == [6, 0, 5, 3, 4]  # Works on one subgraph
    assert shortest_path(map_10, 9, 8) == [9, 8]  # Also works on the other subgraph
    assert shortest_path(map_10, 6, 9) == 'No route found.'  # Cannot route between the disconnected subgraphs
from helpers import load_map

from student_code import RoutePlanner

MAP_40_TEST_CASES = [(5, 34, [5, 16, 37, 12, 34]), (5, 5, [5]),
                     (8, 24, [8, 14, 16, 37, 12, 17, 10, 24])]


def test(route_planner, test_cases):
    correct = 0
    for start, goal, answer_path in test_cases:
        path = route_planner.compute_shortest_path(start, goal)
        if path == answer_path:
            print("\nShortest path from {} to {} is:\n{}".format(
                start, goal, path))
            correct += 1
        else:
            print("For start:", start, "Goal:     ", goal, "Your path:", path,
                  "Correct:  ", answer_path)
    if correct == len(test_cases):
        print("\nAll tests pass! Congratulations!")
    else:
        print("\nYou passed", correct, "/", len(test_cases), "test cases")


if __name__ == "__main__":
    map_40 = load_map('map-40.pickle')
    route_planner = RoutePlanner()
    route_planner.import_map(map_40)
    test(route_planner, MAP_40_TEST_CASES)
        # Use A* to find and return the shortest path from start to goal
        return self.a_star_search()


def shortest_path(M, start_id, goal_id):
    debug_print(
        f"\n======= Start Search for (start, goal): ({start_id}, {goal_id}) =======\n"
    )
    if start_id == goal_id:
        path = [start_id]
    else:
        a_star = AStar()
        path = a_star.shortest_path(M, start_id, goal_id)
    debug_print(f"\nRESULT: {path}")
    return path


def debug_print(text):
    if DEBUG:
        print(text)


if __name__ == "__main__":
    assert (len(sys.argv) == 3
            ), "Needs two command line arguments: state_id_1 and state_id_2"
    DEBUG = True
    map = load_map('map-40.pickle')
    # map = load_map('map-10.pickle')

    print("\n----\n")
    path = shortest_path(map, int(sys.argv[1]), int(sys.argv[2]))
    # path cost is distance between two points
    return math.hypot(end[0] - start[0], end[1] - start[1])


def best_route(came_from, start, goal):
    # traverse backwards to find optimal path
    node = goal
    path = []

    if node not in came_from:
        print(f"Node: {node} not found in map.")
        return

    while node != start:
        path.append(node)
        node = came_from[node]
    path.append(start)
    path.reverse()
    print(path)
    return path


# test maps
map_10 = load_map("map-10.pickle")
map_40 = load_map("map-40.pickle")
# example 1
shortest_path(map_40, 8, 24)  # path: [8, 14, 16, 37, 12, 17, 10, 24]
# example 2
shortest_path(map_10, 2, 0)  # path: [2, 3, 5, 0]
# example 3
shortest_path(map_10, 3, 9)
Beispiel #12
0
 def setUp(self):
     self.M = load_map('map-1000.pickle')
     self.shortest_path = student_code.shortest_path
Beispiel #13
0
 def setUp(self):
     # call before every test case
     self.M = load_map('map-40.pickle')
     self.shortest_path = student_code.shortest_path
Beispiel #14
0
# Run this cell first!

from helpers import Map, load_map, show_map
from student_code import shortest_path

#%load_ext autoreload
#%autoreload 2

map_10 = load_map('map-10.pickle')
show_map(map_10)
# In[30]:

# Run this cell first!

from helpers import Map, load_map, show_map
from student_code import shortest_path

get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')

# ### Map Basics

# In[31]:

map_10 = load_map('map-10.pickle')
show_map(map_10)

# The map above (run the code cell if you don't see it) shows a disconnected network of 10 intersections. The two intersections on the left are connected to each other but they are not connected to the rest of the road network. On the graph above, the edge between 2 nodes(intersections) represents a literal straight road not just an abstract connection of 2 cities.
#
# These `Map` objects have two properties you will want to use to implement A\* search: `intersections` and `roads`
#
# **Intersections**
#
# The `intersections` are represented as a dictionary.
#
# In this example, there are 10 intersections, each identified by an x,y coordinate. The coordinates are listed below. You can hover over each dot in the map above to see the intersection number.

# In[32]:

map_10.intersections
Beispiel #16
0
def main():
    """
    Start a pygame version of minesweeper and enter the GUI event loop.
    """
    game = MinesweeperPygame(hp.load_map('1'))
    game.game_loop()
Beispiel #17
0
from time import clock
from bcolors import bcolors


if __name__=='__main__':
    parser = OptionParser()
    parser.add_option('-f', '--file', dest='map_filename',
                        help='Map file name in pickle format.')
    parser.add_option('-s', '--start', 
                        dest='start', help='Starting node.')
    parser.add_option('-g', '--goal',
                        dest='goal', help='Goal node.')
    
    (options, arg) = parser.parse_args()
    # check for options
    if not options.start or not options.goal or not options.map_filename:
        parser.error(bcolors.FAIL + "you must specify options, please type -h for details." + bcolors.ENDC)
    #
    start = int(options.start)
    goal = int(options.goal)
    map_filename = options.map_filename
    # load map
    M = load_map(map_filename)
    start_t = clock()
    print('Starting search...', end='', flush=True)
    path = shortest_path(M, start, goal)
    end_t = clock()
    print(bcolors.OKGREEN + '\t[DONE]' + bcolors.ENDC) 
    print('Best path found {}'.format(path))
    print('Lapsed time: {0:2.4f} secs'.format(end_t - start_t))