コード例 #1
0
def test_graph():
    G = Graph()
    G.add_edge(1, 2, 3)
    G.add_edge(1, 3, 2)
    assert G.get_edge_weight(1, 2) == 3
    assert G.get_edge_weight(1, 3) == 2
    assert G.get_adjacent_nodes(1) == {2, 3}
コード例 #2
0
ファイル: split.py プロジェクト: SebastianJHM/dev
def SPLIT(Distancias, Demandas, permutacion, capacidad, orden):

    NODOS = [i for i in range(len(permutacion) + 1)]
    GRAFO = []
    RUTAS = []

    for i in range(len(NODOS)):
        for j in range(i + 1, len(NODOS)):
            r = [0]
            acum = 0
            for k in range(j, i, -1):
                r.append(permutacion[k - 1])
                acum = acum + Demandas[permutacion[k - 1]]

            r.append(0)
            r.reverse()
            if (acum <= capacidad):
                d = calcularDistancia(r, Distancias, orden)
                arco = (i, j, round(d, 2))
                GRAFO.append(arco)
                RUTAS.append(r)

    print("GRAFO:")
    for i in range(len(GRAFO)):
        print(GRAFO[i], ":", RUTAS[i])

    sec = list(Graph(GRAFO).dijkstra(NODOS[0], NODOS[-1]))
    print("Secuencia: ", sec)

    PETALOS, FO = obtenerPetalos(GRAFO, RUTAS, sec)
    print("PETALOS PERMUTACIÓN:")
    print(PETALOS, FO, sum(FO))
    return (PETALOS, FO, sum(FO))
コード例 #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"]
コード例 #4
0
ファイル: graph.py プロジェクト: bastantoine/hackathoooon
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
コード例 #5
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) 
コード例 #6
0
ファイル: runner.py プロジェクト: carlofazioli/AdventOfCode
    def __init__(self, source_file=None):
        with open(source_file) as f:
            maze = [list(line.strip('\r\n')) for line in f]
        self.width = max([len(row) for row in maze])
        self.height = len(maze)
        self.loc_warp = dict()
        self.warp_loc = defaultdict(set)
        self.graph = Graph()
        self.interior = set()
        self.exterior = set()

        # Copy the file to the local dict:
        self.maze = self.copy_to_dict(maze)

        # Identify all the wormhole tokens:
        self.parse_warps()

        # Populate graph:
        self.build_graph()

        # Start/finish for the maze:
        self.source = self.warp_loc['AA'].pop()
        self.target = self.warp_loc['ZZ'].pop()

        # Part 2:
        self.scores = dict()
コード例 #7
0
def create_vis_graph(vertices: List[List[float]],
                     holes: List[List[List[float]]] = None) -> Graph:
    """
    Create a visibility graph based on the vertices of the polygon
    :param vertices: List[List[float]]
    :return: Graph object
    """

    graph = Graph()
    for i in range(len(vertices)):
        for j in range(i + 1, len(vertices)):
            vis = True
            for k in range(len(vertices)):
                k1 = k
                k2 = (k + 1) % (len(vertices))
                if (k1 == i) and (k2 == j):
                    vis = True
                    break

                if not diagonal(i, j, vertices) and (
                    (i + 1) % len(vertices)) != j and (
                        (j + 1) % len(vertices)) != i:
                    vis = False
                    break

                if intersectProp(vertices[i], vertices[j], vertices[k1],
                                 vertices[k2]):
                    vis = False
                    break

            if vis:
                d = l2_dist(vertices[i], vertices[j])
                graph.add_edge(i, j, d)
                graph.add_edge(j, i, d)
    return graph
コード例 #8
0
def create_graph(number_of_elements):
    global graph
    graph = Graph(number_of_elements)
    for i in range(1, number_of_elements):
        for j in range(i, number_of_elements + 1):
            if i % 2 == 1:
                if max(i - j, j - i) <= 3 and i != j:
                    graph.add_edge(i, j)
            else:
                if max(i - j, j - i) <= 2 and i != j:
                    graph.add_edge(i, j)
    start = time.time()
    (path_output,
     weight_output) = graph.dijkstra_shortest_path(int(from_entry.get()),
                                                   int(to_entry.get()))
    end = time.time()
    visualize_shortest_path(path_output)
    print("output ", path_output[::-1])
    print("time ", end - start)
    running_time.set("Running Time:" +
                     str("{0:.2f}".format(round((end - start) * 1000, 2))) +
                     "ms")
    string = "Path: "
    for i in range(len(path_output[::-1]) - 1):
        string += str(path_output[::-1][i]) + " -> "
    path_var.set(string + str(path_output[::-1][len(path_output) - 1]))
    weight_var.set("Total Weight: " + str(weight_output))
    print(graph.dijkstra_shortest_path_distances(int(to_entry.get())))
コード例 #9
0
def test_abstract_dijkstra_spf():
    graph = Graph()

    with pytest.raises(NotImplementedError):
        AbstractDijkstraSPF.get_adjacent_nodes(graph, 0)

    with pytest.raises(NotImplementedError):
        AbstractDijkstraSPF.get_edge_weight(graph, 0, 1)
コード例 #10
0
def createGraph():
    graph = Graph()
    f = open("p1_graph.txt", "r")
    for line in f:
        line = line.strip()
        path_values = line.split(",")
        graph.add_edge(int(path_values[0]),int(path_values[1]),int(path_values[2]))
    return graph
コード例 #11
0
 def test_floyd_negative(self):
     inf = float("inf")
     g = Graph(4)
     g.edges = [[0, inf, -2, inf],
                [4, 0, 3, inf],
                [inf, inf, 0, 2],
                [inf, -1, inf, 0]]
     expected = [[0, -1, -2, 0], [4, 0, 2, 4], [5, 1, 0, 2], [3, -1, 1, 0]]
     self.assertEqual(floyd(g), expected)
コード例 #12
0
def build_dijkstra_graph(stations: list) -> Graph:
    g = Graph()

    # Build the graph edges
    for s in stations:
        for n in s.neighbours:
            g.add_edge(s.id, n.station.id, n.get_wtt())

    return g
コード例 #13
0
def findPathBetweenTwoStationInSameLayer(id1, id2, layerName):
    if id1 == id2:
        return [id1]
    layer = mapNameToLayer[layerName]
    graph = mapNameToGraph[layerName]
    #
    listFakeId = convertFakeId([id1, id2], layer)
    g = Graph()
    route = g.dijkstra(graph, listFakeId[0], listFakeId[1])
    return convertToTrustId(route, layer)
コード例 #14
0
ファイル: main.py プロジェクト: nancyhwr/ITSC18
def main(condition, threshold, co, experiment,
         rounds):  # coalition = 10: psfa, others: baseline

    for t in range(experiment):
        dynamic_change(stream_rates, traffic_condition[condition])
        i_nodes = copy.deepcopy(nodes)
        i_edges = copy.deepcopy(edges)
        i_stream_rate = copy.deepcopy(stream_rates)
        graph = Graph(i_nodes, i_edges, i_stream_rate)
        if co == 10:
            coalitions = dk.coalition(graph, i_stream_rate, threshold)
        else:
            coalitions = adapt_baseline(
                form_baseline(baseline_groups[co - 1], i_stream_rate),
                i_stream_rate)
        group_lanes = [e[0] for e in coalitions]
        group_streams = [e[1] for e in coalitions]
        #print('group_streams = ', group_streams)
        interval_times = interval_time(group_streams, total_duration,
                                       minimum_waiting_time)
        streams = {lane: stream_rates[lane] for lane in nodes}
        prob_car = {lane: stream_rates[lane] / 100 for lane in nodes}  #0.25

        total_number = 0
        pass_cars = 0
        accident = 0
        pre_acc = 0

        for i in range(rounds):
            for c in range(len(coalitions)):
                group = coalitions[c][0]

                for j in range(int(interval_times[c])):  #every 10 seconds

                    all_cars = []
                    for lane in group:
                        all_cars = all_cars + lane_list[lane].car_list

                    accident_analysis = current_accident(all_cars)
                    accident = accident + accident_analysis[0]
                    remove_crash_cars(accident_analysis[1], all_cars)

                    pre_acc = pre_acc + tellCollapse(all_cars)
                    pre_acc = pre_acc + tellCollapse(all_cars)
                    for lane in group:
                        pass_cars = pass_cars + lane_list[lane].move_all()
                        if random.uniform(0, 1) < prob_car[lane]:
                            lane_list[lane].car_list.append(
                                Car(lane, lane + str(i) + str(j)))

        stat_pass_cars.append(pass_cars / rounds)
        stat_accident.append(accident / rounds)
        stat_pred_accident.append(pre_acc / rounds)

    return stat_pass_cars, stat_accident, stat_pred_accident
コード例 #15
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
コード例 #16
0
def generate_random_graph(nodes, edges_per_node, max_weight):
    graph = Graph()

    for node_index in range(1, nodes + 1):
        for edge_index in range(edges_per_node):
            weight = randint(1, max_weight)
            neighbour = node_index
            while neighbour == node_index:
                neighbour = randint(0, nodes)
            graph.add_edge_with_cost(node_index, neighbour, weight)

    return graph
コード例 #17
0
ファイル: TSP.py プロジェクト: fredrikwaaler/cs170
def find_shortest_traversal(matrix, node_list):
    """
    Given a matrix and a list of nodes, this function will output the shortest traversal visiting the nodes in that order.
    :param matrix: The matrix
    :param node_list: The list of nodes
    :return: List with path
    """
    path = [node_list[0]]
    graph = Graph()
    for i in range(len(node_list[:-1])):
        path.extend(graph.dijkstra(graph=matrix, src=node_list[i])[node_list[i+1]+1][1:])
    return path
コード例 #18
0
def from_file():
    instance = Graph()
    path = os.path.join(os.path.dirname(__file__), 'dijkstraData.txt')
    testfile = open(path, 'r')
    while testfile:
        line = testfile.readline().rstrip()
        if not line:
            break
        values = line.split('\t')
        head = int(values.pop(0))
        for pair in values:
            tail, weight = map(int, pair.split(','))
            instance.add_edge(head, tail, weight)
    return instance
コード例 #19
0
def create_new_nodeset_graph_and_paint(screen, num_of_nodes,
                                       connections_per_node):
    global nodes, g
    #nodes = generate_list_of_connected_nodes(260, 5)
    nodes = generate_list_of_connected_nodes(num_of_nodes,
                                             connections_per_node)
    #nodes = generate_list_of_connected_nodes(160, 2)
    g = Graph()
    generate_graph_from_node_list(g, nodes)

    screen.fill((0, 0, 0))

    draw_node_list(screen, nodes)

    return g
コード例 #20
0
ファイル: TSP.py プロジェクト: fredrikwaaler/cs170
def get_distance_dict(adj_mat):
    """
    Returns a dictionary of the shortest distances from all node to all others in the parameter adjacency matrix.
    :param adj_mat: A adjacency matrix (mxn array) for the graph to calculate distances from
    :return: A dictionary with shortest distances from all nodes to all others
    """
    distances = {}
    graph = Graph()
    for i in range(len(adj_mat)):
        distances[i] = {}
    for i in range(len(adj_mat)):
        for j in range(len(adj_mat)):
            distances[i][j] = graph.dijkstra(adj_mat, i)[0][j]

    return distances
コード例 #21
0
ファイル: pa3_grader.py プロジェクト: MiSecLab/cse4589-pa3
def get_shortest_path(src, dst, link_costs, ROUTER_ID_MAPPING):
    if src == dst: return 0, int(ROUTER_ID_MAPPING[src])

    # Make link_costs symmetrical
    symm_link_costs = []
    for link in link_costs:
        symm_link_costs.append(link)
        symm_link_costs.append((link[1], link[0], link[2]))

    network = Graph(symm_link_costs)
    try:
        shortest_path = network.dijkstra(src, dst)
    except: return 65535, 65535
    path_cost = 0
    for hop in range(len(shortest_path)-1):
        path_cost += utils.get_link_cost(shortest_path[hop], shortest_path[hop+1], symm_link_costs)
    return path_cost, int(ROUTER_ID_MAPPING[shortest_path[1]])
コード例 #22
0
def main():
    count = 0
    input = open('dij10.txt', 'r')
    x = input.read()
    tamanhoMatriz = 0

    #leitura do arquivo da matriz de adjacencia
    for row, line in enumerate(x.split('\n')):
        for col, val in enumerate(line.split(' ')):
            if (count == 0):
                tamanhoMatriz = int(val)
                count += 1
                break
            break

    count = 0
    matriz = np.zeros((tamanhoMatriz, tamanhoMatriz))
    matrizFinal = np.zeros((tamanhoMatriz, tamanhoMatriz))

    for row, line in enumerate(x.split('\n')):
        for col, val in enumerate(line.split(' ')):
            if (count == 0):
                tamanhoMatriz = int(val)
                count += 1
                break
            else:
                count += 2
                matriz[int(row - 1)][int(col)] = int(val)

    for i in range(0, tamanhoMatriz):
        for j in range(i, tamanhoMatriz):
            if i == j:
                continue
            else:
                matrizFinal[i][j] = matriz[i][j - i - 1]
                matrizFinal[j][i] = matriz[i][j - i - 1]

    print('Matriz de adjacencias: \n')
    print(matrizFinal)

    g = Graph(tamanhoMatriz)
    g.graph = matrizFinal

    g.dijkstra(2)

    count -= 1
コード例 #23
0
 def get_distance_list_fast(self, adj_mat):
     """
     Returns a list of the shortest distances from all node to all others in the parameter adjacency matrix.
     index corresponds to node, value correponds to distances.
     :param adj_mat: An adjacency matrix (mxn array) for the graph to calculate distances from
     :return: A list with shortest distances from all nodes to all others
     """
     distances = [0 for j in range(len(adj_mat))]
     dijkstras = [0 for j in range(len(adj_mat))]
     graph = Graph()
     for i in range(len(adj_mat)):
         distances[i] = [0 for j in range(len(adj_mat))]
         dijkstras[i] = graph.dijkstra(adj_mat, i)[0]
     for i in range(len(adj_mat)):
         for j in range(len(adj_mat)):
             distances[i][j] = dijkstras[i][j]
     return distances
コード例 #24
0
 def compute_graphs(self, data, my_coords: Coords):
     graphs = list()
     # Crea tots els ordres possibles de recorregut
     used_orders = set()
     for i, key_order in enumerate(permutations(data.keys(), len(data)), start=1):
         if key_order in used_orders:
             continue
         used_orders.add(key_order)
         used_orders.add(key_order[::-1])  # Only one direction is enough
         init = time()
         ordered_shops = list()
         ordered_shops.append([Shop(identifier='A', coords=my_coords)])
         ordered_shops.extend([data[key] for key in key_order])
         ordered_shops.append([Shop(identifier='B', coords=my_coords)])
         graph = Graph(self.compute_edges(ordered_shops))
         graphs.append(graph)
         print(f'Computed subgraph {i} in {time() - init:.2f}s')
     return graphs
コード例 #25
0
ファイル: TSP.py プロジェクト: fredrikwaaler/cs170
def get_path_dict(adj_mat):
    """
    Returns a dictionary where the key values are node-indexes and the values are a new dict.
    The keys in this new dict are all nodes in graph. The values for these keys are shortest paths from original
    node to key node.
    :param adj_mat:
    :return:
    """
    paths = {}
    graph = Graph()
    for i in range(len(adj_mat)):
        paths[i] = {}
    for i in range(len(adj_mat)):
        for j in range(len(adj_mat)):
            if i == j:
                paths[i][j] = [i]
            else:
                paths[i][j] = graph.dijkstra(adj_mat, i)[j+1]

    return paths
コード例 #26
0
ファイル: TSP.py プロジェクト: fredrikwaaler/cs170
def calculate_cluster_distances(ad_mat, indexes):
    """
    Calculate the distances between the given list of indexes in the given adjacency matrix, using dijkstra.
    :param ad_mat: The adjacency matrix representing the graph
    :param indexes: The indexes you want to calculate distances for
    :return: A dict {node: {other_node: distance}}
    """
    distances = {}
    graph = Graph()
    # Each node maintains a list with nodes distances to itself
    for i in indexes:
        for j in indexes:
            distances[i] = {j:0}
    for i in indexes:
        for j in indexes:
            try:
                distances[i][j] = graph.dijkstra(ad_mat, i)[0][j]
            except:
                distances[i][j] = 0

    return distances
コード例 #27
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)
コード例 #28
0
def output_path(ad_mat):
    # Create a graph
    graph = Graph()
    visited = [0]  # Start at node 0
    home_drops = []
    path = [0]
    while len(visited) != len(ad_mat):
        remaining = []
        for node in range(len(ad_mat)):
            if node not in visited:
                remaining.append(node)
        best = remaining[0]
        for j in remaining[1:]:
            if graph.dijkstra(ad_mat, visited[-1])[0][j] < graph.dijkstra(
                    ad_mat, visited[-1])[0][best]:
                best = j
        path.extend(graph.dijkstra(ad_mat, visited[-1])[best + 1][1:])
        visited.append(best)

    # Route from end node to start node
    path.extend(graph.dijkstra(ad_mat, visited[-1])[1][1:])

    return path
コード例 #29
0
from configure import configure
from dijkstra import Graph
import numpy as np
if __name__ == '__main__':
    conf = configure()
    graph = Graph(graph=conf.dis)
    num = graph.VertexNum
    table = np.zeros(shape=[num, num], dtype=int)

    for i in range(num):
        for j in range(num):
            dist, path = graph.Dijkstra(i, j)
            Path = []
            for t in range(len(path)):
                Path.append(graph.labels[path[len(path) - 1 - t]])
            if (len(Path) > 1):
                table[i][j] = Path[1]
            else:
                table[i][j] = Path[0]
            print('从节点{}到节点{}的最短路径为:\n{}\n最短路径长度为:{}'.format(i, j, Path, dist))
    # print(table)
    for i in range(num):
        print('节点{}的路由表为:'.format(i))
        print('-------------------------------------------------------')
        for j in range(num):
            if i == j:
                continue
            else:
                print('到节点{}\t转发给节点{}'.format(j, table[i][j]))
        print('-------------------------------------------------------')
コード例 #30
0
    plotter2 = Plotter()

    plotter2.add_obstacles(workspace_obstacles)
    plotter2.add_c_space_obstacles(c_space_obstacles)
    plotter2.add_visibility_graph(lines)
    plotter2.add_robot(source, dist)

    plotter2.show_graph()

    # step 3:
    with open(query, 'r') as f:
        dest = tuple(map(float, f.readline().split(',')))

    lines = get_visibility_graph(c_space_obstacles, source, dest)
    # TODO: fill in the next line
    graph = Graph()
    for l in lines:
        graph.add_node(l.coords[0])
        graph.add_node(l.coords[1])
        graph.add_edge(l.coords[0], l.coords[1], l.length)
        graph.add_edge(l.coords[1], l.coords[0], l.length)
    visited, path = dijsktra(graph, source)
    shortest_path = []
    curr = dest
    while True:
        shortest_path.insert(0, curr)
        if curr == source:
            break
        curr = path[curr]

    cost = visited[dest]