Example #1
0
    def test_exchangerate(self):
        graph = Graph([("USD", "CNY", 6.71), ("EUR", "USD", 1.12),
                       ("QUE", "USD", 0.13), ("QUE", "VES", 428),
                       ("EUR", "VES", 3694.16), ("ARS", "MXN", 0.44),
                       ("ZWD", "MXN", 0.052), ("CHF", "MXN", 19.61),
                       ("CHF", "USD", 0.99), ("USD", "QUE", 7.7)])

        self.assertEqual("7.515200000000001",
                         str((graph.get_exchange("EUR", "CNY")[-1])))
Example #2
0
def produce_paths(start, dest, scaling):
    if (scaling < .1):
        scaling = .1
    if (scaling > .9):
        scaling = .9
    f = Flight()
    edges = f.edges
    edges = create_edges(edges)
    graph = Graph(edges)
    paths = graph.get_unique_paths(start, dest)
    cache = Cache()
    sorted_paths = sort_paths(paths, scaling, cache)
    sorted_p = []
    sorted_overall = []
    sorted_distance = []
    sorted_turbulence = []
    for x in sorted_paths:
        if not sorted_p:
            sorted_p = [x[0]]
            sorted_overall = [x[1]]
            sorted_distance = [x[2]]
            sorted_turbulence = [x[3]]
        else:
            sorted_p.append(x[0])
            sorted_overall.append(x[1])
            sorted_distance.append(x[2])
            sorted_turbulence.append(x[3])
    sorted_travel_paths = []
    sorted_p_strings = ""
    for y in sorted_p:
        sorted_p_strings = ""
        sorted_p_strings += (y[0])
        for i in range(1, len(y)):
            sorted_p_strings += " &rarr; " + y[i]
        sorted_travel_paths.append(sorted_p_strings)
    dict = ParseData(sorted_p[0][0] + '')
    Morning = []
    Afternoon = []
    Evening = []
    Night = []
    max = get_max(
        lambda x: x,
        [dict['Morning'], dict['Afternoon'], dict['Evening'], dict['Night']])
    for z in sorted_p:
        Morning.append(dict['Morning'] / max)
        Afternoon.append(dict['Afternoon'] / max)
        Evening.append(dict['Evening'] / max)
        Night.append(dict['Night'] / max)
    print([
        sorted_travel_paths, sorted_overall, sorted_distance,
        sorted_turbulence, Morning, Afternoon, Evening, Night
    ])
    return [
        sorted_travel_paths, sorted_overall, sorted_distance,
        sorted_turbulence, Morning, Afternoon, Evening, Night
    ]
Example #3
0
def exchange_rate():
    graph = Graph([("USD", "CNY", 6.71), ("EUR", "USD", 1.12),
                   ("QUE", "USD", 0.13), ("QUE", "VES", 428),
                   ("EUR", "VES", 3694.16), ("ARS", "MXN", 0.44),
                   ("ZWD", "MXN", 0.052), ("CHF", "MXN", 19.61),
                   ("CHF", "USD", 0.99), ("USD", "QUE", 7.7)])

    print(graph.dijkstra("EUR", "CNY"))
    print(graph.get_exchange("EUR", "CNY"))
    print("Exchange rate: " + str((graph.get_exchange("EUR", "CNY")[-1])))
Example #4
0
def test_dijkstra_path1():
    graph = nx.DiGraph()
    e=[('a','b',0.3),('b','c',0.9),('a','c',0.5),('c','d',1.2),('c','e',1.6),('b','e',0.7),('d','e',1.3)]
    graph.add_weighted_edges_from(e)
    path = nx.dijkstra_path(graph, 'a', 'e')

    assert nx.dijkstra_path_length(graph, 'a', 'e') == 1

    #Dijkstra implementation should equal shortest path
    dijkstraImpl = Graph(e)
    assert dijkstraImpl.dijkstra('a', 'e') == path
Example #5
0
def test_dijkstra_DiGraph(graph):
    source = random.choice(list(graph.nodes))
    target = random.choice(list(graph.nodes))
    while (target == source):
        target = random.choice(graph.nodes)

    dijkstraImpl = Graph(graph.edges)
    # print('source: ' + str(source) + ', target: ' + str(target))
    # print(graph.edges())

    if (nx.has_path(graph, source, target)
            or len(dijkstraImpl.dijkstra(source, target)) > 0):
        assert nx.dijkstra_path(graph, source,
                                target) == dijkstraImpl.dijkstra(
                                    source, target)
def test_shortest_path_dijkstra():
    graph = nx.Graph()
    e = [('a', 'b', 0.3), ('b', 'c', 0.9), ('a', 'c', 0.5), ('c', 'd', 1.2),
         ('c', 'e', 1.6), ('b', 'e', 0.7), ('d', 'e', 1.3)]
    graph.add_weighted_edges_from(e)
    #follows a -> c -> e

    path = nx.shortest_path(graph, 'a', 'e')
    assert nx.shortest_path_length(graph, 'a', 'e') == len(path) - 1
    assert nx.has_path(graph, 'a', 'e') == True
    allPaths = nx.all_shortest_paths(graph, 'a', 'e')
    assert path in allPaths

    graph2 = nx.Graph()
    e2 = [('a', 'b', 0.3), ('b', 'c', 0.9), ('a', 'c', 0.5), ('c', 'd', 1.2),
          ('c', 'e', 1.6), ('b', 'e', 0.7), ('d', 'e', 1.3), ('a', 'e', 0.4)]
    graph2.add_weighted_edges_from(e2)
    #follows a -> e

    path2 = nx.shortest_path(graph2, 'a', 'e')
    assert nx.shortest_path_length(graph2, 'a', 'e') == len(path2) - 1
    assert nx.has_path(graph2, 'a', 'e') == True
    allPaths2 = nx.all_shortest_paths(graph2, 'a', 'e')
    assert path2 in allPaths2

    #graph1 shortest path should be diffrent from graph2 shortest path
    assert nx.shortest_path_length(graph, 'a', 'e') != nx.shortest_path_length(
        graph2, 'a', 'e')
    #graph1 paths should not contain graph2 shortest path
    assert nx.shortest_path(graph2, 'a',
                            'e') not in nx.all_shortest_paths(graph, 'a', 'e')
    #When removed edge, they should equal again
    graph2.remove_edge('a', 'e')
    assert nx.shortest_path_length(graph, 'a', 'e') == nx.shortest_path_length(
        graph2, 'a', 'e')
    assert nx.shortest_path(graph2, 'a',
                            'e') in nx.all_shortest_paths(graph, 'a', 'e')

    #Outputs the same path as dijkstra_path
    assert nx.shortest_path(graph, 'a',
                            'e') == nx.dijkstra_path(graph, 'a', 'e')

    #Path should equal Dijkstra implementation path
    dijkstraImpl = Graph(e)
    assert dijkstraImpl.dijkstra('a', 'e') == nx.shortest_path(graph, 'a', 'e')
    assert nx.dijkstra_path(graph, 'a',
                            'e') == nx.shortest_path(graph, 'a', 'e')
def build_graph():
    graph = Graph()
    add_subway_pair(graph)
    add_bus_pair(graph)
    add_taxi_od(graph)
    add_bike_pair(graph)
    add_lirr_pair(graph)
    add_edges_of_closest_stations(graph)
    add_airport_express(graph)
    add_waiting_time(graph)
    delete_edge(graph)
    return graph
Example #8
0
    def read_hallway_data(self):
        with open(self.hallway_data, newline='') as f:
            reader = csv.reader(f)
            edge_list = []
            for row in reader:
                if row[0] == "X":
                    continue
                ID = row[0]
                x = row[1]
                y = row[2]
                edges = row[3:]

                for i in range(len(edges)):
                    edges[i] = edges[i].lstrip(' ')
                coordinate = MyCoordinate(x, y, 'hallway', ID, edges)

                for edge in edges:
                    edge_list.append((ID, edge, 1))

                self.list_of_coordinates.append(coordinate)

        edge_list.pop(0)
        graph = Graph(edge_list)
        #print(edge_list)
        print(graph.dijkstra('2263', '2254'))
        path = graph.dijkstra('2263', '2254')

        coord_list = []
        for i in range(len(path)):
            #print(path[i])
            for item in self.list_of_coordinates:
                if path[i] in item.ID:
                    coord_list.append((item.x.lstrip(' '), item.y.lstrip(' ')))

        pprint(coord_list)
        draw(coord_list)
def getGraphe(jsonmap):

    print("in getGraphe")

    themap = jsonmap
    #pprint(themap)
    pprint("---------------------")
    # pprint(themap['areas'])
    # for area in themap['areas']:
    #    pprint("---------------------")
    #    pprint(area)
    for map in themap['areas']:
        for point in (map['map']['vertices']):
            verticeList.append(
                [map['name'] + '.' + point['name'], point['x'], point['y']])
        for arc in (map['map']['streets']):
            for point in verticeList:
                if point[0] == (map['name'] + '.' + arc['path'][0]):
                    x1 = point[1]
                    y1 = point[2]
                if point[0] == (map['name'] + '.' + arc['path'][1]):
                    x2 = point[1]
                    y2 = point[2]
            edgeList.append([
                unicode(map['name'] + '.' + arc['path'][0]),
                unicode(map['name'] + '.' + arc['path'][1]),
                math.sqrt(math.pow(x2 - x1, 2) + math.pow(y2 - y1, 2))
            ])
            #print([map['name'] + '.' + arc['path'][0], map['name'] + '.' + arc['path'][1],
            #       math.sqrt(math.pow(x2 - x1, 2) + math.pow(y2 - y1, 2))])

        for arc in (map['map']['bridges']):
            for point in verticeList:
                if point[0] == (map['name'] + '.' + arc['from']):
                    x1 = point[1]
                    y1 = point[2]
                if point[0] == (arc['to']['area'] + '.' + arc['to']['vertex']):
                    x2 = point[1]
                    y2 = point[2]
            edgeList.append([
                unicode(map['name'] + '.' + arc['from']),
                unicode(arc['to']['area'] + '.' + arc['to']['vertex']),
                arc['weight']
            ])
            #print([map['name'] + '.' + arc['from'], arc['to']['area'] + '.' + arc['to']['vertex'], arc['weight']])

    g = Graph()

    print("vertices")
    for vertex in verticeList:

        print(vertex)

        g.add_vertex(vertex[0])

        pass

    print("edges")
    for edge in edgeList:

        print(edge)

        g.add_edge(edge[0], edge[1], edge[2])

        pass

    return g
Example #10
0
def random_dijkstra():
    """ calculate the random path """
    random_path = Graph.random_dijkstra(TOPOLOGY)
    # print(random_path[1:])
    return random_path[1:]  # removing alice
Example #11
0
def lis2graph(layer):
    """Maakt Graph met LIS-netwerk en bepaalt onderbemalingen.
       Vult [ONTV_VAN] en [X_OBEMAL].
       Gebruikt [LOOST_OP] en [VAN_KNOOPN] als edge (relation) en VAN_KNOOPN als node"""
    # graph aanmaken
    graph = Graph()
    graph_rev = Graph()
    d_K_ONTV_VAN = {}  # alle onderliggende gemalen
    d_K_ONTV_VAN_n1 = {
    }  # alle onderliggende gemalen op 1 niveau diep ivm optellen overcapaciteit

    print_log("netwerk opslaan als graph...", "i")
    for feature in layer.getFeatures():  # .getFeatures()
        VAN_KNOOPN = feature["VAN_KNOOPN"]
        LOOST_OP = feature["K_LOOST_OP"]
        graph.add_node(VAN_KNOOPN)
        graph_rev.add_node(VAN_KNOOPN)
        if LOOST_OP != None:
            graph.add_edge(VAN_KNOOPN, LOOST_OP,
                           1)  # richting behouden voor bovenliggende gebied
            graph_rev.add_edge(
                LOOST_OP, VAN_KNOOPN,
                1)  # richting omdraaien voor onderliggende gebied
    edges_as_tuple = list(
        graph.distances)  # lijst met tuples: [('A', 'B'), ('C', 'B')]

    print_log("onderbemaling bepalen voor rioolgemalen en zuiveringen...", "i")
    where_clause = "Join_Count > 0"
    layer.startEditing()
    for i, feature in enumerate(layer.getFeatures()):  # .getFeatures()
        if not feature["count"] >= 1: continue
        VAN_KNOOPN = feature["VAN_KNOOPN"]
        nodes = dijkstra(graph, VAN_KNOOPN)[0]
        print_log("nodes for {}: {}".format(VAN_KNOOPN, nodes), 'd')
        K_KNP_EIND, X_OPPOMP = [(key, value) for key, value in sorted(
            nodes.iteritems(), key=lambda (k, v): (v, k))][-1]
        print_log(
            "endnode for {}: {},{}".format(VAN_KNOOPN, K_KNP_EIND, X_OPPOMP),
            'd')
        d_edges = dijkstra(graph_rev,
                           VAN_KNOOPN)[1]  # {'B': 'A', 'C': 'B', 'D': 'C'}
        l_onderliggende_gemalen = str(list(d_edges))  # [u'ZRE-123',u'ZRE-234']
        l_onderliggende_gemalen = l_onderliggende_gemalen.replace(
            "u'", "'").replace("[", "").replace("]", "")
        layer.changeAttributeValue(
            feature.id(), layer.fieldNameIndex("K_ONTV_VAN"),
            l_onderliggende_gemalen)  # K_ONTV_VAN = 'ZRE-1','ZRE-2'
        layer.changeAttributeValue(
            feature.id(), layer.fieldNameIndex("X_OBEMAL"),
            len(list(d_edges)))  # X_OBEMAL = 2 (aantal onderbemalingen)
        layer.changeAttributeValue(
            feature.id(), layer.fieldNameIndex("X_OPPOMP"), X_OPPOMP + 1
        )  # X_OPPOMP = 1 (aantal keer oppompen tot rwzi) met shortestPath ('RWZI','ZRE-4')
        layer.changeAttributeValue(
            feature.id(), layer.fieldNameIndex("K_KNP_EIND"), K_KNP_EIND
        )  # eindbemalingsgebied / overnamepunt. bepaald uit netwerk.
        d_K_ONTV_VAN[VAN_KNOOPN] = l_onderliggende_gemalen

        # onderbemalingen 1 niveau diep
        l_onderliggende_gemalen_n1 = [
            start for start, end in edges_as_tuple if end == VAN_KNOOPN
        ]  # dus start['A', 'C'] uit tuples[('A', 'B'),('C', 'B')] als end == 'B'
        d_K_ONTV_VAN_n1[VAN_KNOOPN] = str(l_onderliggende_gemalen_n1).replace(
            "u'", "'").replace("[", "").replace(
                "]", "")  # naar str() en verwijder u'tjes en haken
    layer.commitChanges()

    return [d_K_ONTV_VAN, d_K_ONTV_VAN_n1]
Example #12
0
# (start_node,end_node,cost)
edges = [   ("A","2",10),
            ("2","3",5),
            ("3","5",2),
            ("2","5",4),
            ("A","3",6)     ]

# Another possibility is to import the edges from a file, in a specific format.
# An example file with edges is presented named Edges.txt. You can create your
# own file with edges, as long as it follows the same format, and just replace
# the name in the function below with the name of your file.
edges = edges_from_file("Edges.txt")
print edges

# Create the graph
g = Graph(edges)

###### Obtain the costs from a node to all others
###############################################################################
source_node = "A"
g.dijkstra_all(source_node)

###### Obtain the shortest path from a node to another
###############################################################################
source_node = "A"
goal_node = "5"
cost,path = g.dijkstra(source_node,goal_node)

# Present the results
string = ""
for p in path:
def getGraphe(jsonmap):

    print("in getGraphe")

    themap = jsonmap
    #pprint(themap)
    pprint("---------------------")
    # pprint(themap['areas'])
    # for area in themap['areas']:
    #    pprint("---------------------")
    #    pprint(area)
    for map in themap['areas']:
        for point in (map['map']['vertices']):
            verticeList.append([map['name'] + '.' + point['name'], point['x'], point['y']])
        for arc in (map['map']['streets']):
            for point in verticeList:
                if point[0] == (map['name'] + '.' + arc['path'][0]):
                    x1 = point[1]
                    y1 = point[2]
                if point[0] == (map['name'] + '.' + arc['path'][1]):
                    x2 = point[1]
                    y2 = point[2]
            edgeList.append([unicode(map['name'] + '.' + arc['path'][0]),
                             unicode(map['name'] + '.' + arc['path'][1]),
                             math.sqrt(math.pow(x2 - x1, 2) + math.pow(y2 - y1, 2))])
            #print([map['name'] + '.' + arc['path'][0], map['name'] + '.' + arc['path'][1],
            #       math.sqrt(math.pow(x2 - x1, 2) + math.pow(y2 - y1, 2))])

        for arc in (map['map']['bridges']):
            for point in verticeList:
                if point[0] == (map['name'] + '.' + arc['from']):
                    x1 = point[1]
                    y1 = point[2]
                if point[0] == (arc['to']['area'] + '.' + arc['to']['vertex']):
                    x2 = point[1]
                    y2 = point[2]
            edgeList.append(
                [unicode(map['name'] + '.' + arc['from']),
                 unicode(arc['to']['area'] + '.' + arc['to']['vertex']),
                 arc['weight']])
            #print([map['name'] + '.' + arc['from'], arc['to']['area'] + '.' + arc['to']['vertex'], arc['weight']])


    g = Graph()

    print("vertices")
    for vertex in verticeList:

        print (vertex)

        g.add_vertex(vertex[0])

        pass

    print("edges")
    for edge in edgeList:

        print (edge)

        g.add_edge(edge[0], edge[1], edge[2])

        pass

    return g