示例#1
0
def shortest_path(body, trans_mode):
    if trans_mode == "car":
        grid = car_grid
        nodes = car_nodes
    elif trans_mode == "bike":
        grid = bike_grid
        nodes = bike_nodes

    body = json.loads(body)

    try:
        lat1 = float(body['lat1'])
        lng1 = float(body['lng1'])
        lat2 = float(body['lat2'])
        lng2 = float(body['lng2'])
    except ValueError:
        print("ValueError: Could not parse lat/lng")

    # Uncomment to test closest node performance
    # start = clock()
    # source_id = get_closest_node_id(nodes, Node('-1', lat1, lng1))
    # target_id = get_closest_node_id(nodes, Node('-1', lat2, lng2))
    # end = clock()
    # print("Closest node speed:", end-start)

    start = clock()
    source_id = get_closest_node_id_grid_search(grid, Node('-1', lat1, lng1))
    target_id = get_closest_node_id_grid_search(grid, Node('-1', lat2, lng2))
    end = clock()
    print("Grid search speed:", end - start)

    # uncomment to test Dijkstra performance
    # start = clock()
    # path = dijkstra(nodes, source_id, target_id)
    # end = clock()
    # print("Dijkstra speed:", end-start)

    start = clock()
    path = a_star(nodes, source_id, target_id)
    end = clock()
    print("A* speed:", end - start)

    if path == (float("inf"), []):
        print("No path found.")
        return

    path_nodes = path[1]
    print("source_id:", source_id)
    print("target_id:", target_id)
    print(path)
    for i in range(len(path_nodes)):
        path_nodes[i] = (nodes[path_nodes[i]].lat, nodes[path_nodes[i]].lng)
    response = {
        'path': path_nodes,
        'start': [lat1, lng1],
        'end': [lat2, lng2]
    }  #
    #'end' and 'start' is the markers coordinates, saved for user options

    if logged_in:
        with open('users.json') as json_file:
            users = json.load(json_file)

            if trans_mode == "car":
                users[logged_in_user]['last_car_path'] = response

            elif trans_mode == "bike":
                users[logged_in_user]['last_bike_path'] = response

            with open('users.json', 'w') as json_file:
                json.dump(users,
                          json_file,
                          sort_keys=True,
                          indent=4,
                          separators=(',', ': '))

    return json.dumps(response)
示例#2
0
def update_npc():
    global global_npc
    global global_restart_flag
    global global_damage
    global total_blocked
    global runtime

    runtime = 0

    # Local method
    def heuristic(a, b):  # using distance between nodes for heuristic
        # start_time = time.time()
        x2 = global_graph.nodes[a]['x']
        x3 = global_graph.nodes[b]['x']
        y2 = global_graph.nodes[a]['y']
        y3 = global_graph.nodes[b]['y']
        return osmnx.distance.euclidean_dist_vec(y2, x2, y3, x3)

    for i in range(1):
        # Update npc locations
        npc_updated = []
        for npc_nodes in global_npc:
            if npc_nodes == global_destination:
                global_damage += 1
            else:
                try:
                    # route = nx.shortest_path(graph, npc_nodes, destination, weight="length")
                    if global_algorithm == 'default':
                        # route = nx.astar_path(global_graph, npc_nodes, global_destination, heuristic=heuristic,
                        #                       weight="length")
                        tic = time.perf_counter()
                        route = algorithms.a_star(global_graph,
                                                  npc_nodes,
                                                  global_destination,
                                                  heuristic=None,
                                                  weight="length")
                        toc = time.perf_counter()
                        runtime = runtime + (toc - tic)

                    else:
                        # Change algorithm here
                        # route = nx.astar_path(global_graph, npc_nodes, global_destination, heuristic=heuristic,
                        #                       weight="length")
                        tic = time.perf_counter()
                        route = algorithms.a_star(global_graph,
                                                  npc_nodes,
                                                  global_destination,
                                                  heuristic=heuristic,
                                                  weight="length")
                        toc = time.perf_counter()
                        runtime = runtime + (toc - tic)
                    if len(route) <= global_npc_step + 1:
                        npc_updated.append(route[-1])
                    else:
                        npc_updated.append(route[global_npc_step + 1])
                except:
                    print("no path")
                    total_blocked = total_blocked + 1
        global_npc = npc_updated
        print(f"Ran in {runtime:0.4f} seconds")
        if len(global_npc) == 0:
            global_restart_flag = True
            return i
    return global_npc_step
示例#3
0
def main():
    
    bs = int(input("Board size: "))
    board = Board(bs)
    
    set_goal(bs)
    start_node = get_start_node(bs)
    
    vb = input("Do you want to print intermediate steps? (y/n): ")
    if vb == 'y' or vb == 'Y':
        verbose = True
    elif vb == 'n' or vb == 'N':
        verbose = False
    
    running = True
    choice = 0
    dls_limit = None
    while running:
        print("\n---------------------------------------------------")
        print("Choose and algorithm (1-6) or press 0 to quit:")
        print("1. Breadth-First Search (BFS)")
        print("2. Uninformed Cost Search (UCS)")
        print("3. Depth Limited Search (DLS)")
        print("4. Iterativee Deepening Depth-First Search (IDS)")
        print("5. Greedy Best-First Search (GBFS)")
        print("6. A* Search")
        print("7. Generate Graphs on 8-Puzzle (time, nodes generated, cost)")
        try:
            choice = int(input("Choice: "))
        except:
            print("Only interger input allowed")
            continue
        
        if choice == 0:
            break
        
        elif choice == 1:
            print(f"Running BFS on: {start_state}")
            print(f"Goal: {goal_state}\n...")
            result = bfs(start_node, board, verbose)
            dls_limit = result.max_depth
            if result.verdict == 'success':
                print("Goal State Found!")
                show_statistics(result)
                path(result.node)
                path_to_goal()
            elif result.verdict == 'failed':
                print("Goal Not Found")
        
        elif choice == 2:
            print(f"Running UCS on: {start_state}")
            print(f"Goal: {goal_state}\n...")
            start_node_ucs = NodeGCost(start_state, goal_state, None, None, 0, 0)
            result = ucs(start_node_ucs, board, verbose)
            dls_limit = result.max_depth
            if result.verdict == 'success':
                print("Goal State Found!")
                show_statistics(result)
                path(result.node)
                path_to_goal()
            elif result.verdict == 'failed':
                print("Goal Not Found")
        
        elif choice == 3:
            if dls_limit is None:
                print("DLS limit not set by BFS yet")
                dls_limit = int(input("Limit: "))
            else:
                print(f"BFS set limit to {dls_limit}")
            print(f"Running DLS on: {start_state}")
            print(f"Goal: {goal_state}")
            print(f"limit: {dls_limit}\n...")
            
            result = dls(start_node, board, dls_limit, verbose)
            if result.verdict == 'success':
                print("Goal State Found!")
                show_statistics(result)
                path(result.node)
                path_to_goal()
            elif result.verdict == 'failed':
                print("Goal Not Found")
        
        elif choice == 4:
            print(f"Running IDS on: {start_state}")
            print(f"Goal: {goal_state}")
            result = ids(start_node, board, 0 ,verbose)
            if result.verdict == 'success':
                print("Goal State Found!")
                show_statistics(result)
                path(result.node)
                path_to_goal()
            elif result.verdict == 'failed':
                print("Goal Not Found")
        
        elif choice == 5:
            print(f"Running GBFS on: {start_state}")
            print(f"Goal: {goal_state}\n...")
            result = gbfs(start_node, board, verbose)
            if result.verdict == 'success':
                print("Goal State Found!")
                show_statistics(result)
                path(result.node)
                path_to_goal()
            elif result.verdict == 'failed':
                print("Goal Not Found")
        
        elif choice == 6:
            print(f"Running A* on: {start_state}")
            print(f"Goal: {goal_state}\n...")
            start_node_a = NodeFCost(start_state, goal_state, None, None, 0, 0) 
            result = a_star(start_node_a, board, verbose)
            if result.verdict == 'success':
                print("Goal State Found!")
                show_statistics(result)
                path(result.node)
                path_to_goal()
            elif result.verdict == 'failed':
                print("Goal Not Found")
        
        elif choice == 7:
            unleash_chaos(goal_state)
示例#4
0
def main(display, width, rows):
    grid = helpers.make_grid(rows, WIDTH)

    start_pos = None
    end_pos = None
    running = True
    already_executed = False
    generated_walls = False

    # game loop
    while running:
        helpers.draw(display, grid, rows, width, buttons)

        # event loop
        for event in pygame.event.get():
            pos = pygame.mouse.get_pos()
            if event.type == pygame.QUIT:
                running = False

            # process mouse input
            if pygame.mouse.get_pressed()[0]:  # left mouseclick
                # if click is in the bottom of the game screen (buttons)
                if pos[1] > WIDTH:
                    # check each button for a click (needs refactoring)
                    for button in buttons:
                        if button.is_clicked(pos):
                            print("Clicked the button " + button.label)
                            if button.label == "A*":
                                if start_pos and end_pos and already_executed is False:
                                    for row in grid:
                                        for cell in row:
                                            cell.update_neighbors(grid)
                                    a_star(
                                        lambda: helpers.draw(
                                            display, grid, rows, width), grid,
                                        start_pos, end_pos)
                                    already_executed = True
                                elif already_executed is True:
                                    Tk().wm_withdraw()
                                    messagebox.showwarning(
                                        "Invalid state",
                                        "You must clear the board first")
                                else:
                                    Tk().wm_withdraw()
                                    messagebox.showwarning(
                                        "Invalid state",
                                        "You must set start and end positions")
                            if button.label == "Clear":
                                start_pos = None
                                end_pos = None
                                already_executed = False
                                generated_walls = False
                                grid = helpers.make_grid(rows, WIDTH)
                            if button.label == "Visited":
                                for row in grid:
                                    for cell in row:
                                        if cell.is_visited(
                                        ) or cell.is_available(
                                        ) or cell.is_path():
                                            cell.reset()
                                already_executed = False
                            if button.label == "Dijkstra":
                                if start_pos and end_pos and already_executed is False:
                                    for row in grid:
                                        for cell in row:
                                            cell.update_neighbors(grid)
                                    # dijkstra(lambda: helpers.draw(display, grid,
                                    # rows, width), grid, start_pos, end_pos)
                                    dijkstra(
                                        lambda: helpers.draw(
                                            display, grid, rows, width), grid,
                                        start_pos, end_pos)
                                    already_executed = True
                                elif already_executed is True:
                                    Tk().wm_withdraw()
                                    messagebox.showwarning(
                                        "Invalid state",
                                        "You must clear the board first")
                                else:
                                    Tk().wm_withdraw()
                                    messagebox.showwarning(
                                        "Invalid state",
                                        "You must set start and end positions")
                            if button.label == "Walls" and generated_walls is False:
                                draw_borders(
                                    lambda: helpers.draw(
                                        display, grid, rows, width), grid,
                                    start_pos, end_pos)
                                generate_walls(
                                    lambda: helpers.draw(
                                        display, grid, rows, width), grid,
                                    start_pos, end_pos)
                                generated_walls = True
                            button.clicked = False
                else:
                    row, col = helpers.get_mouse_pos(pos, rows, WIDTH)
                    cell = grid[row][col]
                    if not start_pos and cell != end_pos:
                        start_pos = cell
                        start_pos.set_start()
                    elif not end_pos and cell != start_pos:
                        end_pos = cell
                        end_pos.set_end()
                    elif cell != end_pos and cell != start_pos:
                        cell.set_barrier()

            elif pygame.mouse.get_pressed()[2]:  # right mouseclick
                row, col = helpers.get_mouse_pos(pos, rows, WIDTH)
                cell = grid[row][col]
                cell.reset()

                if cell == start_pos:
                    start_pos = None
                if cell == end_pos:
                    end_pos = None

    pygame.quit()
from utility import read_input_file
from problem import Problem
from algorithms import ucs, bfs, a_star

if __name__ == '__main__':
    input_dict = read_input_file()
    for key, value in input_dict.items():
        print(key, value, sep=':')
    for target in input_dict['targets']:
        problem = Problem(
            init_state=input_dict['state_grid'][input_dict['landing_site'][1]][
                input_dict['landing_site'][0]],
            state_space=input_dict['state_grid'],
            goal_state=input_dict['state_grid'][target[1]][target[0]],
            actions=['E', 'W', 'N', 'S', 'NE', 'SE', 'SW', 'NW'],
            max_elev_diff=input_dict['max_elevation_diff'])
        # print(problem)
        if input_dict['algorithm'].lower() == 'bfs':
            print(bfs(problem))
        elif input_dict['algorithm'].lower() == 'ucs':
            print(ucs(problem))
        else:
            print(a_star(problem))
示例#6
0
    # Rendering path and visited nodes between start and end node
    if start_node_created and end_node_created:
        for node in visited_list:
            if (node.position_x, node.position_y) != grid.start_node and (
                    node.position_x, node.position_y) != grid.end_node:
                if node.visited:
                    draw_node(node.position_x, node.position_y, yellow)
                if node.obstacle:
                    draw_node(node.position_x, node.position_y, dark_grey)

        for node in old_visited_list:
            if node not in visited_list and not node.obstacle:
                draw_node(node.position_x, node.position_y, white)

        if run_a_star:
            visited_list, old_visited_list, total_cost, total_time = algorithms.a_star(
                nodes_list, grid.start_node, grid.end_node, visited_list)
        elif run_dijkstra:
            visited_list, old_visited_list, total_cost, total_time = algorithms.dijkstra(
                nodes_list, grid.start_node, grid.end_node, visited_list)
        if run_a_star or run_dijkstra:
            start_node = nodes_list[grid.start_node[0]][grid.start_node[1]]
            end_node = nodes_list[grid.end_node[0]][grid.end_node[1]]
            path = end_node
            path_dist = 0
            path_list.clear()
            while path.parent is not None:
                if path.position_x == start_node.position_x and path.position_y == start_node.position_y:
                    break
                path_dist = path_dist + path.parent_dist
                path_list.append(path.parent)
                path = path.parent
示例#7
0
from algorithms.a_star import *
from algorithms.csp import *

#building grid object, you can change to GRID_5_6 (use: words2.txt) or GRID_11_11
gb = GridBuilder(GRID_7_7)
gb.build_as_words_list()

#loading dictionary with necessary elements and methods
dictionary = DictionaryCollection("resources/words.txt")
dictionary.load(gb.words_list)


def a_star():
    alg1 = A_Star(gb, dictionary)
    alg1.solve()


def csp_p():

    alg2 = csp(gb.words_list, dictionary)
    alg2.create_variables()
    alg2.create_constraints()

    time, solutions = alg2.get_solutions(100)
    print(time, solutions[0])


if __name__ == '__main__':
    a_star()
    #csp_p()
示例#8
0
def plan_route_from_graph(name: str,
                          G,
                          orig_coords,
                          dest_coords,
                          show: bool = None):
    """Diese Funktion wendet einen Algorithmus (name) auf einen Graphen G an, um den besten Weg
    von den Startkoordinaten (orig_coords) zu den Zielkoordinaten (dest_coords) zu ermitteln.
    Steht show auf True, wird der Graph geplottet, ansonsten (auch bei weglassen), werden nur die Daten ausgegeben.

    Zulässige name-Werte (Aufsteigend: ungefähre Laufzeit):
    * a-star
    * dijkstra
    * bellman-ford
    * floyd-warshall
    """
    # fetch nodes and prepare fields
    orig_node = ox.get_nearest_node(G, orig_coords)
    dest_node = ox.get_nearest_node(G, dest_coords)

    dist = {}
    pred = {}
    route = []

    if show is None:
        show = False

    print(f"===== START {name}, ({orig_coords[2]} → {dest_coords[2]})")
    if (name == "floyd-warshall"):
        # call algorithm
        dist, next, count = floyd_warshall(G)
        # prepare route
        u = orig_node
        v = dest_node
        while u != v:
            route += [u]
            u = next[u][v]

    else:
        # call algorithm
        if (name == "dijkstra"):
            dist, pred, count = dijkstra(G, orig_node)
        elif (name == "a-star"):
            dist, pred, count = a_star(G, orig_node, dest_node)
        elif (name == "bellman-ford"):
            dist, pred, count = bellman_ford(G, orig_node)
        # prepare route
        v = dest_node
        while v is not None:
            route = [v] + route
            v = pred[v]

    printInfos(G, dist, pred, count, route, dist[dest_node])
    print(f"===== ENDE {name}")

    nc = ['r' if x in dist.keys() else 'black' for x in G.nodes]
    fig, ax = ox.plot_graph_route(G,
                                  route,
                                  node_size=24,
                                  node_color=nc,
                                  node_alpha=0.6,
                                  route_color='b',
                                  route_alpha=0.7,
                                  show=show)
import problem
import algorithms
import sys
from copy import deepcopy

print("Initialization Phase")
state = []
for i in range(3):
    state.append([])
    a, b, c = input().split()
    state[i].append(int(a))
    state[i].append(int(b))
    state[i].append(int(c))
puzzle = problem.Problem(state)
if sys.argv[1] == "dfs":
    algorithms.dfs(puzzle)
elif sys.argv[1] == "bfs":
    algorithms.bfs(puzzle)
elif sys.argv[1] == "bi":
    algorithms.bidirectional(puzzle)
elif sys.argv[1] == "uni":
    algorithms.uniform_cost(puzzle)
elif sys.argv[1] == "as":
    algorithms.a_star(puzzle)
elif sys.argv[1] == "log":
    parents = [[deepcopy(puzzle.state), "NOP", "NOA", 5]]
    parent = deepcopy(puzzle.state)
    x = algorithms.parent_distance(parent, parents)
    x += 1
    print(x)
示例#10
0
def find_astar_route(source, target):
    return algorithms.a_star(source, target, 'a')
示例#11
0
def run_algos(state_dict, goal, board):
    
    entry = {}
    clear_dict(entry)
    
    #BFS
    sys.stdout.write("Generating stats for BFS..")         
    for x in range(1, 21):
        result = bfs(Node(state_dict[x], goal, None, None, 0, 0), board, verbose=False)
        if result.verdict == "success":
            entry[x]["time"] = result.elapsed_time
            entry[x]["nodes"] = result.gen_nodes
            entry[x]["cost"] = result.node.path_cost
            sys.stdout.write(f" #{x},")
        else:
            entry[x]["time"] = 0.0
            entry[x]["nodes"] = 0
            entry[x]["cost"] = 0
            sys.stdout.write(f" #{x}(F),")
    print("")
    write_file(entry, "bfs")
    clear_dict(entry)
    
    #DLS
    sys.stdout.write("Generating stats for DLS..")         
    for x in range(1, 21):
        result = dls(Node(state_dict[x], goal, None, None, 0, 0), board, x+1, verbose=False)
        if result.verdict == "success":
            entry[x]["time"] = result.elapsed_time
            entry[x]["nodes"] = result.gen_nodes
            entry[x]["cost"] = result.node.path_cost
            sys.stdout.write(f" #{x},")
        else:
            entry[x]["time"] = 0.0
            entry[x]["nodes"] = 0
            entry[x]["cost"] = 0
            sys.stdout.write(f" #{x}(F),")
    print("")
    write_file(entry, "dls")
    clear_dict(entry)
    
    #IDS
    sys.stdout.write("Generating stats for IDS..")         
    for x in range(1, 21):
        result = ids(Node(state_dict[x], goal, None, None, 0, 0), board, 0, verbose=False)
        if result.verdict == "success":
            entry[x]["time"] = result.elapsed_time
            entry[x]["nodes"] = result.gen_nodes
            entry[x]["cost"] = result.node.path_cost
            sys.stdout.write(f" #{x},")
        else:
            entry[x]["time"] = 0.0
            entry[x]["nodes"] = 0
            entry[x]["cost"] = 0
            sys.stdout.write(f" #{x}(F),")
    print("")
    write_file(entry, "ids")
    clear_dict(entry)
    
    #UCS
    sys.stdout.write("Generating stats for UCS..")         
    for x in range(1, 21):
        result = ucs(NodeGCost(state_dict[x], goal, None, None, 0, 0), board, verbose=False)
        if result.verdict == "success":
            entry[x]["time"] = result.elapsed_time
            entry[x]["nodes"] = result.gen_nodes
            entry[x]["cost"] = result.node.path_cost
            sys.stdout.write(f" #{x},")
        else:
            entry[x]["time"] = 0.0
            entry[x]["nodes"] = 0
            entry[x]["cost"] = 0
            sys.stdout.write(f" #{x}(F),")
    print("")
    write_file(entry, "ucs")
    clear_dict(entry)
    
    #GBFS
    sys.stdout.write("Generating stats for GBFS..")         
    for x in range(1, 21):
        result = gbfs(Node(state_dict[x], goal, None, None, 0, 0), board, verbose=False)
        if result.verdict == "success":
            entry[x]["time"] = result.elapsed_time
            entry[x]["nodes"] = result.gen_nodes
            entry[x]["cost"] = result.node.path_cost
            sys.stdout.write(f" #{x},")
        else:
            entry[x]["time"] = 0.0
            entry[x]["nodes"] = 0
            entry[x]["cost"] = 0
            sys.stdout.write(f" #{x}(F),")
    print("")
    write_file(entry, "gbfs")
    clear_dict(entry)
    
    #ASTAR
    sys.stdout.write("Generating stats for A*..")         
    for x in range(1, 21):
        result = a_star(NodeFCost(state_dict[x], goal, None, None, 0, 0), board, verbose=False)
        if result.verdict == "success":
            entry[x]["time"] = result.elapsed_time
            entry[x]["nodes"] = result.gen_nodes
            entry[x]["cost"] = result.node.path_cost
            sys.stdout.write(f" #{x},")
        else:
            entry[x]["time"] = 0.0
            entry[x]["nodes"] = 0
            entry[x]["cost"] = 0
            sys.stdout.write(f" #{x}(F),")
    print("")
    write_file(entry, "astar")
    clear_dict(entry)