Ejemplo n.º 1
0
def CalculoRota(request):
    parametros =  JSONParser().parse(request)

    
    if not checkRequestValido(parametros):
        return JsonResponse({'mensagem': 'Parametros invalidos'}, status=status.HTTP_400_BAD_REQUEST)
    
    #obter rotas
    rotas = Rota.objects.all()
    rotas = rotas.filter(mapa__nome__icontains= parametros['mapa'])
    
    #checar se os objetos existem no banco
    if not rotas.exists():
        return JsonResponse({'mensagem': 'Mapa nao encontrado'}, status=status.HTTP_404_NOT_FOUND)

    if not  rotas.filter(origem__icontains= parametros['origem']):
        return JsonResponse({'mensagem': 'Origem nao encontrada no mapa'}, status=status.HTTP_404_NOT_FOUND)
    
    if not  rotas.filter(destino__icontains= parametros['destino']):
        return JsonResponse({'mensagem': 'Destino nao encontrado no mapa'}, status=status.HTTP_404_NOT_FOUND)

    
    graph = Graph()
    for rota in rotas:
        graph.add_edge(rota.origem, rota.destino, rota.distancia) 

    dijkstra = DijkstraSPF(graph, parametros['origem'])
    caminho = dijkstra.get_path(parametros['destino'])

    gasto = dijkstra.get_distance(parametros['destino'])/parametros['autonomia']*parametros['valorLitro']

    return JsonResponse({'origem': parametros['origem'],'destino': parametros['destino'],'gasto': gasto,'rota': caminho}, status=status.HTTP_200_OK) 
Ejemplo n.º 2
0
def get_path_info(g: Graph, stations:list, st_from : Station, st_to : Station, existing_spf=None) -> dict:
    # We are using caching of results to speed up the generations of spf trees and dijkstra path length calculations

    cache_key = f"{st_from.id}:{st_to.id}"
    if cache_key not in PATH_CACHE:
        d = DijkstraSPF(g, st_from.id) if existing_spf == None else existing_spf

        stops = [ stations[id - 1] for id in d.get_path(st_to.id)]
        time = 0
        stop_times = [0]

        # We must adjust the time in the path between two explicit stations, since we do not need to account
        #   for travel_interval in transit for subway neighbors (though, we do for taxi transit)
        for i in range(len(stops) - 1):
            st_1 = stops[i]
            st_2 = stops[i+1]

            for n in st_1.neighbours:
                if n.station.id == st_2.id:
                    if i == 0 or n.travel_method == "taxi":
                        time += n.get_wtt()
                    else:
                        time += n.get_travel_time()

            stop_times.append(time)

        PATH_CACHE[cache_key] = {
            "time" : time,
            "stations" :  stops,
            "stop_times": stop_times,
            "spf" : d,
        }

    return PATH_CACHE[cache_key]
Ejemplo n.º 3
0
def test_dijkstra():
    nodes = ("S", "T", "A", "B", "C", "D", "E", "F", "G")
    S, T, A, B, C, D, E, F, G = nodes

    graph = Graph()
    graph.add_edge(S, A, 4)
    graph.add_edge(S, B, 3)
    graph.add_edge(S, D, 7)
    graph.add_edge(A, C, 1)
    graph.add_edge(B, S, 3)
    graph.add_edge(B, D, 4)
    graph.add_edge(C, E, 1)
    graph.add_edge(C, D, 3)
    graph.add_edge(D, E, 1)
    graph.add_edge(D, T, 3)
    graph.add_edge(D, F, 5)
    graph.add_edge(E, G, 2)
    graph.add_edge(G, E, 2)
    graph.add_edge(G, T, 3)
    graph.add_edge(T, F, 5)

    dijkstra = DijkstraSPF(graph, S)

    for v in nodes:
        print("%3s %3s" % (v, dijkstra.get_distance(v)))

    assert dijkstra.get_distance(T) == 10
    assert dijkstra.get_path(T) == ["S", "D", "T"]
Ejemplo n.º 4
0
def get_itinerary(start, destination):
    # We check if the starting and ending point begins by B1 or B3
    if not start.startswith('B3') and not start.startswith('B1'):
        raise ValueError(
            f'Start name should start with either B1 or B3. Got {start}')
    if not destination.startswith('B3') and not destination.startswith('B1'):
        raise ValueError(
            f'Start name should start with either B1 or B3. Got {destination}')

    # We get all the rooms saved in the database
    rooms = query_db("SELECT name, linked_to FROM points")

    graph = Graph()
    for room in rooms:
        # We convert each room into a dictionary and we get the current room name
        room = dict(room)
        room_name = room.get("name", "")
        if room_name:
            # For each room connected to our current room
            for room_connected_and_distance in room.get("linked_to",
                                                        "").split("|"):
                # On the connected room we get the name of the room and the distance
                room_connected, distance = room_connected_and_distance.split(
                    ";")
                # We add the connection in our graph
                graph.add_edge(room_name, room_connected, int(distance))

    # We generate our dijkstra and we search ou path
    dijkstra = DijkstraSPF(graph, start)
    itinerary_list = dijkstra.get_path(destination)
    return itinerary_list
Ejemplo n.º 5
0
def check_solution(adj_matrix):
    from dijkstra import Graph, DijkstraSPF
    n = len(adj_matrix)
    node_names = [str(i) for i in adj_matrix]
    graph = Graph()
    for i in range(n):
        for j in range(n):
            graph.add_edge(node_names[i], node_names[j], adj_matrix[i, j])
    solution = DijkstraSPF(graph, node_names[0])
    result = [solution.get_distance(i) for i in node_names]
    return result
Ejemplo n.º 6
0
def findPath(start, dest):
    graph = createGraph()
    start_time = time.time()
    dijkstra = DijkstraSPF(graph, start)
    try:
        path = dijkstra.get_path(dest)
        print(path)
    except KeyError:
        print("No path found")
    end_time = time.time()
    total_time = end_time-start_time
    print("Total Elasped: ", total_time)
Ejemplo n.º 7
0
def Find_Path(start, end):
    global station_dict
    global graph

    score = float("inf")
    path = []
    for s in station_dict[start]:
        dijkstra = DijkstraSPF(graph, s)

        for e in station_dict[end]:
            value = dijkstra.get_distance(e)
            if value <= score:
                score = value
                path = dijkstra.get_path(e)

    path = list(dict.fromkeys([x.lstrip(ascii_letters) for x in path]))
    return score, path
Ejemplo n.º 8
0
def delivery_process(request):
    if request.method == 'POST':
        body_unicode = request.body.decode('utf-8')
        body = json.loads(body_unicode)
        map_name = body['map_name']
        origin = body['origin']
        destination = body['destination']
        truck_range = body['truck_range']
        fuel_cost = body['fuel_cost']

        if map_name == "" or map_name == "[]" or map_name is None:
            return JsonResponse("Invalid Parameters",
                                status=status.HTTP_400_BAD_REQUEST,
                                safe=False)

        deliveries = Delivery.objects.all()
        deliveries = deliveries.filter(map_name__icontains=map_name)
        if deliveries.count() == 0:
            return JsonResponse("Invalid Parameters: map name not found",
                                status=status.HTTP_400_BAD_REQUEST,
                                safe=False)

        deliveries_serializer = DeliverySerializer(deliveries, many=True)
        deliveries = dict(deliveries_serializer.data[0])['routes']

        nodes = set([origin, destination])
        g = Graph()
        for delivery in deliveries:
            route = list(delivery.items())
            nodes.add(route[0][1])
            nodes.add(route[1][1])
            g.add_edge(route[0][1], route[1][1], route[2][1])

        dijkstra = DijkstraSPF(g, origin)

        shortest_distance = dijkstra.get_distance(destination)
        path = " -> ".join(dijkstra.get_path(destination))
        cost = (shortest_distance / truck_range) * fuel_cost
        return JsonResponse({"route": path, "cost": cost}, safe=False)
Ejemplo n.º 9
0
 def shortest_distance(self, nodeA, nodeB):
     dijkstra = DijkstraSPF(self.graph, nodeA)
     return dijkstra.get_distance(nodeB)
Ejemplo n.º 10
0
 def shortest_path(self, nodeA, nodeB):
     dijkstra = DijkstraSPF(self.graph, nodeA)
     return dijkstra.get_path(nodeB)
Ejemplo n.º 11
0
grafo = Graph()

grafo.add_edge(F, C, 15)
grafo.add_edge(F, B, 5)
grafo.add_edge(F, E, 40)

grafo.add_edge(E, G, 10)
grafo.add_edge(E, B, 20)

grafo.add_edge(D, B, 40)
grafo.add_edge(D, G, 45)
grafo.add_edge(D, F, 10)
grafo.add_edge(D, E, 35)

grafo.add_edge(C, E, 5)
grafo.add_edge(C, G, 25)

grafo.add_edge(A, G, 75)
grafo.add_edge(A, D, 20)

graph_dijkstra = DijkstraSPF(grafo, A)

for i in nodos:
    print("%-5s %7d" % (i, graph_dijkstra.get_distance(i)))
print("Caminos:")
print(" -> ".join(graph_dijkstra.get_path(B)))
print(" -> ".join(graph_dijkstra.get_path(C)))
print(" -> ".join(graph_dijkstra.get_path(D)))
print(" -> ".join(graph_dijkstra.get_path(E)))
print(" -> ".join(graph_dijkstra.get_path(F)))
print(" -> ".join(graph_dijkstra.get_path(G)))
Ejemplo n.º 12
0
def dfs(polygons: List[PolyNode], root: PolyNode, polygon: List[List[float]],
        vis_graph: Graph, agents: List[List[float]],
        unvisited_children: List[PolyNode]) -> List[List[List[List[float]]]]:
    """
    The main function for sweeping with two agents.
    :param polygons: List[PolyNode], list of PolyNode in which each is a subpolygon after partitioning
    :param root: PolyNode, first subpolygon that the two agents start in
    :param polygon: List[List[float]], original polygon
    :param vis_graph: Graph, the visibility graph, used to find shortest path from a node to another
    :param agents: List[List[float]], starting locations of the two agents
    :param unvisited_children: List[PolyNode], list of unvisited branches so far in the DFS traversal
    :return: List[List[List[List[float]]]] (4 List), the strategy. The list of states of the two agents (line segments)
    Each of the inner List[List[List[float]]] (3 List) is a completely valid strategy, consisting of multiple line segments.
    """

    if root.visited:
        return []

    if root in unvisited_children:
        del unvisited_children[unvisited_children.index(root)]

    root.visited = True
    # print(str(root.verts) + ' ' + str(polygons.index(root)))
    schedule = []

    # Generate a list of children nodes, in counterclockwise order
    # edges is the list of edges, same length as children list
    # Each edge here is the edge that connects current node with the corresponding child
    children = []
    edges = []
    for i in range(len(root.verts)):
        i1 = i
        i2 = (i + 1) % len(root.verts)
        edge = [root.verts[i1], root.verts[i2]]
        for poly in polygons:
            if poly == root or poly.visited:
                continue
            if edge_in_poly(poly, edge):
                children.append(poly)
                edges.append(edge)

    # Generate a sweep schedule for the current root node (a convex subpoly)
    # Note that at the end of the schedule, the two agents will align with the edge shared with the best child found in find_closest_neighbor

    # Find shortest path from the previous locations of the agents to the gate of this node
    if (agents[0] not in root.verts) or (agents[1] not in root.verts):
        best_d = float('inf')
        best_convergent_point = -1
        best_next_point = -1

        leaf_poly = None
        for poly in polygons:
            if edge_in_poly(poly, [agents[0], agents[1]]):
                leaf_poly = poly
                break

        for e in range(len(root.verts)):
            next_edge = [
                polygon.index(root.verts[e]),
                polygon.index(root.verts[(e + 1) % len(root.verts)])
            ]

            min_d = float('inf')
            convergent_point = -1
            next_point = -1

            for i in range(len(leaf_poly.verts)):
                v = leaf_poly.verts[i]

                dijkstra = DijkstraSPF(vis_graph, polygon.index(v))
                path_lengths = [
                    dijkstra.get_distance(next_edge[0]),
                    dijkstra.get_distance(next_edge[1])
                ]
                total_length = min(path_lengths)
                total_length += max(l2_dist(v, agents[0]),
                                    l2_dist(v, agents[1]))
                if total_length < min_d:
                    min_d = total_length
                    convergent_point = polygon.index(v)

                    if path_lengths[0] < path_lengths[1]:
                        next_point = next_edge[0]
                    else:
                        next_point = next_edge[1]

            if min_d < best_d:
                best_convergent_point = convergent_point
                best_d = min_d

                best_next_point = next_point

        schedule_r = [agents]
        schedule_r += [[
            polygon[best_convergent_point], polygon[best_convergent_point]
        ]]
        schedule += [schedule_r]

        dijkstra = DijkstraSPF(vis_graph, best_convergent_point)
        path = dijkstra.get_path(best_next_point)
        schedule_r = []
        for p in path:
            schedule_r += [[polygon[p], polygon[p]]]

        schedule += [schedule_r]

        agents = schedule_r[-1]

    schedule_r = []
    # Special case if leaf node
    if len(children) == 0:
        l = l2_dist(agents[0], agents[1])
        poly_len = root.length()

        # i1 < j1 < j2 < i2 < i1 (counter clockwise)
        # i1---...---i2
        # |           |
        # |           |
        # j1---...---j2
        i1 = root.verts.index(agents[0])
        j1 = root.verts.index(agents[1])
        if (i1 + len(root.verts) - 1) % len(root.verts) == j1:
            i1, j1 = j1, i1
        schedule_r.append([root.verts[i1], root.verts[j1]])

        best_edge_ind = -1
        best_sweep_time = float('inf')
        for k in range(len(root.verts)):
            j2 = k
            i2 = (k + 1) % len(root.verts)
            if j2 == i1:
                continue
            sweep_time = compute_sweep_time(copy.copy(i1), copy.copy(j1), i2,
                                            j2, root.verts)
            if sweep_time < best_sweep_time:
                best_sweep_time = sweep_time
                best_edge_ind = k

        j2 = best_edge_ind
        i2 = (best_edge_ind + 1) % len(root.verts)
        di = 0
        dj = 0
        while i1 != i2 or j1 != j2:
            if i1 != i2:
                new_di = di + l2_dist(root.verts[(i1 - 1) % len(root.verts)],
                                      root.verts[i1])
            else:
                new_di = di
                j1 = (j1 + 1) % len(root.verts)
                schedule_r.append([root.verts[i1], root.verts[j1]])
                continue

            if j1 != j2:
                new_dj = dj + l2_dist(root.verts[(j1 + 1) % len(root.verts)],
                                      root.verts[j1])
            else:
                new_dj = dj
                i1 = (i1 - 1) % len(root.verts)
                schedule_r.append([root.verts[i1], root.verts[j1]])
                continue

            if new_di < new_dj:
                i1 = (i1 - 1) % len(root.verts)
            else:
                j1 = (j1 + 1) % len(root.verts)
            schedule_r.append([root.verts[i1], root.verts[j1]])

        # append_correct(schedule_r, [root.verts[j2], root.verts[i2]])

        schedule += [schedule_r]

        if len(unvisited_children) == 0:
            return schedule

        best_d_c = float('inf')
        best_c = -1
        for c in range(len(unvisited_children)):
            child = unvisited_children[c]
            best_d = float('inf')
            for e in range(len(child.verts)):
                next_edge = [
                    polygon.index(child.verts[e]),
                    polygon.index(child.verts[(e + 1) % len(child.verts)])
                ]

                min_d = float('inf')

                for i in range(len(root.verts)):
                    v = root.verts[i]

                    dijkstra = DijkstraSPF(vis_graph, polygon.index(v))
                    path_lengths = [
                        dijkstra.get_distance(next_edge[0]),
                        dijkstra.get_distance(next_edge[1])
                    ]
                    total_length = min(path_lengths)
                    total_length += max(l2_dist(v, agents[0]),
                                        l2_dist(v, agents[1]))
                    if total_length < min_d:
                        min_d = total_length
                        convergent_point = polygon.index(v)

                        # if path_lengths[0] < path_lengths[1]:
                        #     next_point = next_edge[0]
                        # else:
                        #     next_point = next_edge[1]

                if min_d < best_d:
                    # best_convergent_point = convergent_point
                    best_d = min_d

                    # best_next_point = next_point
            if best_d < best_d_c:
                best_d_c = best_d
                best_c = c

        schedule_r = dfs(polygons, unvisited_children[best_c], polygon,
                         vis_graph, schedule_r[-1], unvisited_children)
        # del unvisited_children[best_c]
        if len(schedule_r) > 1:
            schedule += schedule_r

        return schedule

    # General case, moving the segment from edge/diag (i1, j1) to edge/diag (i2, j2)
    i1 = root.verts.index(agents[0])
    j1 = root.verts.index(agents[1])

    closest_neighbor = find_cloest_neighbor(root, agents, children)

    if (i1 + len(root.verts) - 1) % len(root.verts) == j1:
        i1, j1 = j1, i1

    i2 = root.verts.index(edges[closest_neighbor][0])
    j2 = root.verts.index(edges[closest_neighbor][1])
    if (j2 + len(root.verts) - 1) % len(root.verts) == i2:
        i2, j2 = j2, i2

    schedule_r.append([root.verts[i1], root.verts[j1]])

    while i1 != i2 or j1 != j2:
        if i1 != i2:
            i1 = (i1 + len(root.verts) - 1) % len(root.verts)
        if j1 != j2:
            j1 = (j1 + 1) % len(root.verts)

        schedule_r.append([root.verts[i1], root.verts[j1]])

    schedule += [schedule_r]

    last_edge = edges[closest_neighbor]

    while len(children) > 0:
        # Find the next child with start_edge of closest moving distance from last_edge
        c = children[closest_neighbor]
        del children[closest_neighbor]
        closest_neighbor = 0
        if not c.visited:
            unvisited_children += children
            schedule_c = dfs(polygons, c, polygon, vis_graph, last_edge,
                             unvisited_children)

            # del edges[closest_neighbor]
            if len(schedule_c) > 0:
                last_edge = schedule_c[-1][-1]
                schedule += schedule_c

    return schedule
Ejemplo n.º 13
0
 def build_spf(self) -> None:
     self.spf = DijkstraSPF(self.rm.graph, self.route_stops[0].id)