예제 #1
0
    def test_ternary_case(self):
        """ Tests a triangle. """
        test_graph = {"A": [(10, "B"), (20, "C")],
                      "B": [(10, "A"), (5, "C")],
                      "C": [(20, "A"), (5, "B")]}

        expected_path = (10, ["A", "B"])
        self.assertEqual(shortest_path(test_graph, "A", "B"), expected_path)

        expected_path = (5, ["B", "C"])
        self.assertEqual(shortest_path(test_graph, "B", "C"), expected_path)

        expected_path = (15, ["A", "B", "C"])
        self.assertEqual(shortest_path(test_graph, "A", "C"), expected_path)
예제 #2
0
    def test_five_nodes(self):
        """ Tests the algorithm on a graph with 5 nodes. """
        test_graph = {"A": [(10, "B"), (2, "C")],
                      "B": [(10, "A"), (5, "D")],
                      "C": [(2, "A"), (20, "D")],
                      "D": [(5, "B"), (20, "C"), (1, "E")],
                      "E": [(1, "D")]}

        expected_path = (12, ["B", "A", "C"])
        self.assertEqual(shortest_path(test_graph, "B", "C"), expected_path)

        expected_path = (16, ["A", "B", "D", "E"])
        self.assertEqual(shortest_path(test_graph, "A", "E"), expected_path)

        expected_path = (18, ["C", "A", "B", "D", "E"])
        self.assertEqual(shortest_path(test_graph, "C", "E"), expected_path)
예제 #3
0
def graph_tools_runner(g, input_file):
    start = g.get_start()
    finish = g.get_finish()
    target = g.get_vertex(finish)  # Destination point
    path = [target.get_id()]

    dijkstra(g, g.get_vertex(start), g.get_nearby())

    shortest_path(target, path)  # Find a shortest path to finish
    path_output = ' -> '.join(path[::-1]) + ': ' + str(target.get_distance())
    # Build reachable destiations string from Dictionary
    reachable_destinations = ', '.join(
        "%s: %r" % (key, val)
        for (key,
             val) in g.get_vertex(start).get_reachable_for_time().iteritems())
    return path_output, reachable_destinations
예제 #4
0
def random_walk(controller, limit=None):
    event = controller.step(action='GetReachablePositions')
    reachable_positions = event.metadata['actionReturn']
    src = event.metadata['agent']['position']
    src_rot = event.metadata['agent']['rotation']['y']

    src_index = reachable_positions.index(src)
    src_dists = [dist(src, dst) for dst in reachable_positions]

    graph = {}
    for i, p1 in enumerate(reachable_positions):
        dists = {}
        for j, p2 in enumerate(reachable_positions):
            d = dist(p1, p2)
            if d <= gridSize and i != j:
                dists[j] = d
        graph[i] = dists

    path = None
    while path is None:
        dst = random.choice(reachable_positions)
        dst_index = reachable_positions.index(dst)
        if dist(src, dst) > 0.5 * max(src_dists):
            path = dijkstra.shortest_path(graph, src_index, dst_index)
    path = [reachable_positions[i] for i in path]

    if limit is not None:
        path = path[:limit]

    follow_path(controller, src, src_rot, path)
예제 #5
0
def main():

    bs = 10
    size = 750
    start = [np.random.randint(size // bs), np.random.randint(size // bs)]
    end = [np.random.randint(size // bs), np.random.randint(size // bs)]

    dsp = dg.shortest_path(start_idx=start,
                           target_idx=end,
                           blk_size=bs,
                           size=size,
                           blockage=0)
    asp = ag.shortest_path(start_idx=start,
                           target_idx=end,
                           blk_size=bs,
                           size=size,
                           blockage=0)

    dsp.find_path()
    asp.find_path()

    dsp.show_path()
    asp.show_path()

    cv2.destroyAllWindows()
예제 #6
0
 def test_by_comparison(self):
     weights = random_graph(value_generator=lambda: random.randint(1, 1000),
                            vertex_count=20,
                            edge_count=100)
     fw_result = shortest_distances(weights)
     for v1, v2 in product(weights.keys(), repeat=2):
         dijkstra_result = dijkstra.shortest_path(weights, v1, v2)[0]
         self.assertEqual(fw_result[0][v1][v2], dijkstra_result)
예제 #7
0
 def move_sequence_between(self, src_point, dest_point):
     path = dijkstra.shortest_path(self.dijkstra_repr(), src_point, dest_point)
     previous_identifier = path[0]
     move_dests = []
     for identifier in path[1:]:
         move_dests.append((self.points[identifier], self.edges[(previous_identifier, identifier)].anim))
         previous_identifier = identifier
     return dest_point, move_dests
 def testAL(self):
     """Part (c): short path"""
     source = dijkstra.node_by_name(self.nodes, 'BRIDGEPORT', 'AL')
     destination = dijkstra.node_by_name(self.nodes, 'STEVENSON', 'AL')
     ans = dijkstra.shortest_path(self.nodes, self.links, dijkstra.distance,
                                  source, destination)
     self.assertEqual(3, len(ans))
     self.verifyPath(ans, self.links, source, destination)
예제 #9
0
def visualize_map_graph(starting_point: str, end_point: str,
                        graph: MapGraph) -> None:
    """return the map visualization of the graph
    """
    coordinates = []
    total_distance = 0.0
    path = shortest_path(starting_point, end_point, graph)
    coordinates.append(list(graph.get_location(path[0])))

    # Get the list of coordinates from the shortest path between two places
    for i in range(1, len(path)):
        curr_loc = graph.get_location(path[i])
        coordinates.append(list(curr_loc))
        total_distance += graph.get_distance(path[i], path[i - 1])

    times = {
        'car': min_sec(vehicle_mode_time(total_distance, 'car')),
        'bicycle': min_sec(vehicle_mode_time(total_distance, 'bicycle')),
        'walking': min_sec(vehicle_mode_time(total_distance, 'walking'))
    }

    # Create a Map with two markers
    m = folium.Map(location=coordinates[0],
                   zoom_start=17)  # Adjusted according to the UofT Map
    folium.Marker(location=coordinates[0],
                  popup=folium.Popup("<b>Departure:</b> {start}<br>".format(
                      start=starting_point),
                                     max_width=160),
                  icon=folium.Icon(color='blue')).add_to(m)

    message = ("<b>Destination:</b> {end}<br>"
               "<b>Transportation:</b> <br>"
               "<i>Car:</i> {car_m} m {car_s} s<br>"
               "<i>Bicycle</i>: {bi_m} m {bi_s} s<br>"
               "<i>Walking</i>: {w_m} m {w_s} s<br>").format(
                   end=end_point,
                   car_m=str(times['car'][0]),
                   car_s=str(times['car'][1]),
                   bi_m=str(times['bicycle'][0]),
                   bi_s=str(times['bicycle'][1]),
                   w_m=str(times['walking'][0]),
                   w_s=str(times['walking'][1]))

    folium.Marker(location=coordinates[-1],
                  popup=folium.Popup(html=message, max_width=160, sticy=True),
                  icon=folium.Icon(color='red')).add_to(m)

    # Add a colored line of the shortest path between two points
    my_polyline = folium.PolyLine(locations=coordinates,
                                  color='black',
                                  weight=5)
    m.add_child(my_polyline)
    output = 'UofTMap.html'
    m.save(output)  # save the HTML file of the map

    # Open a map
    url = 'file://{path}/{mapfile}'.format(path=os.getcwd(), mapfile=output)
    webbrowser.open(url, new=1)
 def testLonger(self):
     """Part (c): long path"""
     source = self.nodes[0]
     destination = self.nodes[100]
     ans = dijkstra.shortest_path(self.nodes, self.links, dijkstra.distance,
                                  source, destination)
     self.verifyPath(ans, self.links, source, destination)
     self.assertAlmostEqual(2076299, self.sumPath(ans, dijkstra.distance),
                            0)
예제 #11
0
def test_shortest_path():
    '''
    Get shortest path distances from start to end node.

    '''
    graph = {'a': {'b': 1}, 'b': {'c': 2, 'b': 5}, 'c': {'d': 1}, 'd': {}}
    assert shortest_path(graph, 'a', 'a') == ['a']
    assert shortest_path(graph, 'a', 'b') == ['a', 'b']
    assert shortest_path(graph, 'a', 'c') == ['a', 'b', 'c']
    assert shortest_path(graph, 'a', 'd') == ['a', 'b', 'c', 'd']

    graph = {
        'a': {
            'b': 14,
            'c': 9,
            'd': 7
        },
        'b': {
            'a': 14,
            'c': 2,
            'e': 9
        },
        'c': {
            'a': 9,
            'b': 2,
            'd': 10,
            'f': 11
        },
        'd': {
            'a': 7,
            'c': 10,
            'f': 15
        },
        'e': {
            'b': 9,
            'f': 6
        },
        'f': {
            'c': 11,
            'd': 15,
            'e': 6
        }
    }
    assert shortest_path(graph, 'a', 'e') == ['a', 'c', 'b', 'e']
예제 #12
0
def create_matrix_subpaths(graph, edges):
	matrix = []
	for i in range(0, len(graph.vertices)):
		matrix.append([])
		for j in range(0, len(graph.vertices)):
			if (i != j):
				matrix[i].append(dijkstra.shortest_path(graph, i, j))
			else:
				matrix[i].append(0)
	return matrix
예제 #13
0
 def testAL(self):
     """Part (c): short path"""
     source = dijkstra.node_by_name(self.nodes, 'BRIDGEPORT', 'AL')
     destination = dijkstra.node_by_name(self.nodes, 'STEVENSON', 'AL')
     ans = dijkstra.shortest_path(self.nodes, 
                                  self.links,
                                  dijkstra.distance,
                                  source,
                                  destination)
     self.assertEqual(3, len(ans))
     self.verifyPath(ans, self.links, source, destination)
예제 #14
0
def flat_earth(filename="path_flat.kml"):
    """Test long path"""

    loader = nhpn.Loader()
    nodes = loader.nodes()
    links = loader.links()

    source = dijkstra.node_by_name(nodes, "CAMDEN", "NJ")
    destination = dijkstra.node_by_name(nodes, "SAN DIEGO", "CA")
    ans = dijkstra.shortest_path(nodes, links, dijkstra.distance, source, destination)
    nhpn.Visualizer.toKML(ans, "path_flat.kml")
예제 #15
0
 def move_sequence_between(self, src_point, dest_point):
     path = dijkstra.shortest_path(self.dijkstra_repr(), src_point,
                                   dest_point)
     previous_identifier = path[0]
     move_dests = []
     for identifier in path[1:]:
         move_dests.append(
             (self.points[identifier], self.edges[(previous_identifier,
                                                   identifier)].anim))
         previous_identifier = identifier
     return dest_point, move_dests
예제 #16
0
파일: test.py 프로젝트: joyrexus/dijkstra
def test_shortest_path():
    '''
    Get shortest path distances from start to end node.

    '''
    graph = {'a': {'b': 1}, 
             'b': {'c': 2, 'b': 5}, 
             'c': {'d': 1},
             'd': {}}
    assert shortest_path(graph, 'a', 'a') == ['a']
    assert shortest_path(graph, 'a', 'b') == ['a', 'b']
    assert shortest_path(graph, 'a', 'c') == ['a', 'b', 'c']
    assert shortest_path(graph, 'a', 'd') == ['a', 'b', 'c', 'd']

    graph = {'a': {'b':14, 'c':9, 'd':7},
             'b': {'a':14, 'c':2, 'e':9},
             'c': {'a':9, 'b':2, 'd':10, 'f':11},
             'd': {'a':7, 'c':10, 'f':15},
             'e': {'b':9, 'f':6},
             'f': {'c':11, 'd':15, 'e':6}}
    assert shortest_path(graph, 'a', 'e') == ['a', 'c', 'b', 'e']
def flat_earth(filename='path_flat.kml'):
    """Test long path"""

    loader = nhpn.Loader()
    nodes = loader.nodes()
    links = loader.links()

    source = dijkstra.node_by_name(nodes, 'CAMDEN', 'NJ')
    destination = dijkstra.node_by_name(nodes, 'SAN DIEGO', 'CA')
    ans = dijkstra.shortest_path(nodes, links, dijkstra.distance, source,
                                 destination)
    nhpn.Visualizer.toKML(ans, 'path_flat.kml')
예제 #18
0
    def shortest_path(self, origin, destination):
        """Find and return shortest path between origin and destination.
        Will return in-order list of Points of the shortest path found. If
        origin or destination are not in the visibility graph, their respective
        visibility edges will be found, but only kept temporarily for finding
        the shortest path. 
        """

        origin_exists = origin in self.visgraph
        dest_exists = destination in self.visgraph
        if origin_exists and dest_exists:
            return shortest_path(self.visgraph, origin, destination)
        orgn = None if origin_exists else origin
        dest = None if dest_exists else destination
        add_to_visg = Graph([])
        if not origin_exists:
            for v in visible_vertices(origin, self.graph, destination=dest):
                add_to_visg.add_edge(Edge(origin, v))
        if not dest_exists:
            for v in visible_vertices(destination, self.graph, origin=orgn):
                add_to_visg.add_edge(Edge(destination, v))
        return shortest_path(self.visgraph, origin, destination, add_to_visg)
예제 #19
0
 def testLonger(self):
     """Part (c): long path"""
     source = self.nodes[0]
     destination = self.nodes[100]
     ans = dijkstra.shortest_path(self.nodes,
                                  self.links,
                                  dijkstra.distance,
                                  source,
                                  destination)
     self.verifyPath(ans, self.links, source, destination)
     self.assertAlmostEqual(2076299,
                            self.sumPath(ans, dijkstra.distance),
                            0)
예제 #20
0
def flat_earth(filename = 'path_flat.kml'):
    """Test long path"""

    nodes, links = dijkstra.load_data()
    dijkstra.create_adjacency_lists(nodes, links)

    source = dijkstra.node_by_name(nodes, 'PASADENA', 'CA')
    destination = dijkstra.node_by_name(nodes, 'CAMBRIDGE', 'MA')
    ans = dijkstra.shortest_path(nodes,
                                 links,
                                 dijkstra.distance,
                                 source,
                                 destination)
    nhpn.Visualizer.toKML(ans, 'path_flat.kml')
    print "path_flat.kml created"
def tree_dijk(root, nodes, edges):
    flag = False
    graph = dk.Graph()
    list = []

    for node in nodes:
        graph.add_node(node)

    for edge in edges:
        c, v1, v2 = edge.split(" ")
        graph.add_edge(str(v1), str(v2), int(c))

    for i in nodes:
        if (i != root):
            cost, path = dk.shortest_path(graph, root, i, flag)
            list.append(path)
    return list
def pathFinder(adjMX, adjMY, Mweight, roi,
               szImgNew):  #Mweight can be either MW or MmW
    findroiImg = (np.nonzero(np.ravel(roi, order='F')))[0]
    includeX = iM.ismember(adjMX, findroiImg)
    includeY = iM.ismember(adjMY, findroiImg)
    keepInd = np.logical_and(includeX, includeY)
    newLen = np.count_nonzero(keepInd)
    (RealadjMW, RealadjMX, RealadjMY) = (np.zeros(newLen), np.zeros(newLen),
                                         np.zeros(newLen))
    q = 0
    for r in range(0, (keepInd.size)):
        if keepInd[r]:
            RealadjMW[q] = Mweight[r]
            RealadjMX[q] = adjMX[r]
            RealadjMY[q] = adjMY[r]
            q = q + 1
    strmin = str(np.amin(RealadjMX))
    strmax = str(np.amax(RealadjMX))

    #finding the 'shortest path' on the light to dark boundary (MW)
    #or dark to light boundary (MmW)
    wGraph = sparseToDict(RealadjMX, RealadjMY,
                          RealadjMW)  #convert graph to hashtable
    pathW = dj.shortest_path(wGraph, strmin, strmax)
    fullPathLen = len(pathW)
    pathX, pathY = np.zeros(fullPathLen), np.zeros(fullPathLen)
    for a in range(0, fullPathLen):
        (pathY[a], pathX[a]) = np.unravel_index(int(float(pathW[a])),
                                                szImgNew,
                                                order='F')

    xmin = np.amin(pathX)
    xmax = np.amax(pathX)
    truepathX1 = []
    truepathY1 = []
    #Removes the first and lost points (through the padded zeros)
    z = 0
    for xele in pathX:
        if xele != xmin and xele != xmax:
            truepathX1.append(xele - 1)  #because you removed the first column
            truepathY1.append(pathY[z])
        z = z + 1

    return truepathX1, truepathY1
def pathFinder (adjMX, adjMY, Mweight, roi, szImgNew):  #Mweight can be either MW or MmW
    findroiImg = (np.nonzero(np.ravel(roi, order='F')))[0]   
    includeX = iM.ismember(adjMX, findroiImg)
    includeY = iM.ismember(adjMY, findroiImg)
    keepInd = np.logical_and (includeX, includeY)
    newLen = np.count_nonzero(keepInd)
    (RealadjMW, RealadjMX, RealadjMY)  = (np.zeros(newLen), 
                                          np.zeros(newLen), 
                                          np.zeros(newLen))
    q = 0
    for r in range (0, (keepInd.size)):
        if keepInd[r]:
            RealadjMW[q] = Mweight[r]
            RealadjMX[q] = adjMX[r]
            RealadjMY[q] = adjMY[r]            
            q = q + 1     
    strmin = str(np.amin(RealadjMX))
    strmax = str(np.amax(RealadjMX))

    #finding the 'shortest path' on the light to dark boundary (MW)
    #or dark to light boundary (MmW)
    wGraph = sparseToDict(RealadjMX, RealadjMY, RealadjMW) #convert graph to hashtable                                            
    pathW = dj.shortest_path(wGraph, strmin, strmax)
    fullPathLen = len(pathW)
    pathX, pathY = np.zeros(fullPathLen), np.zeros(fullPathLen)
    for a in range (0,fullPathLen):
        (pathY[a],pathX[a]) = np.unravel_index(int(float(pathW[a])),
                                                 szImgNew, order='F')

    xmin = np.amin(pathX)
    xmax = np.amax(pathX)
    truepathX1 = []
    truepathY1 = []
    #Removes the first and lost points (through the padded zeros)
    z = 0
    for xele in pathX:
        if xele != xmin and xele != xmax:
            truepathX1.append(xele - 1) #because you removed the first column
            truepathY1.append(pathY[z])
        z = z + 1
                                    
    return truepathX1, truepathY1
예제 #24
0
def curved_earth(filename="path_curved.kml"):
    """Test long path"""

    loader = nhpn.Loader()
    nodes = loader.nodes()
    links = loader.links()

    def distance(node1, node2):
        """Returns the distance between node1 and node2, including the
        Earth's curvature."""
        A = node1.latitude * pi / 10 ** 6 / 180
        B = node1.longitude * pi / 10 ** 6 / 180
        C = node2.latitude * pi / 10 ** 6 / 180
        D = node2.longitude * pi / 10 ** 6 / 180
        return acos(sin(A) * sin(C) + cos(A) * cos(C) * cos(B - D))

    source = dijkstra.node_by_name(nodes, "CAMDEN", "NJ")
    destination = dijkstra.node_by_name(nodes, "SAN DIEGO", "CA")
    ans = dijkstra.shortest_path(nodes, links, distance, source, destination)
    nhpn.Visualizer.toKML(ans, "path_curved.kml")
def curved_earth(filename='path_curved.kml'):
    """Test long path"""

    loader = nhpn.Loader()
    nodes = loader.nodes()
    links = loader.links()

    def distance(node1, node2):
        """Returns the distance between node1 and node2, including the
        Earth's curvature."""
        A = node1.latitude * pi / 10**6 / 180
        B = node1.longitude * pi / 10**6 / 180
        C = node2.latitude * pi / 10**6 / 180
        D = node2.longitude * pi / 10**6 / 180
        return acos(sin(A) * sin(C) + cos(A) * cos(C) * cos(B - D))

    source = dijkstra.node_by_name(nodes, 'CAMDEN', 'NJ')
    destination = dijkstra.node_by_name(nodes, 'SAN DIEGO', 'CA')
    ans = dijkstra.shortest_path(nodes, links, distance, source, destination)
    nhpn.Visualizer.toKML(ans, 'path_curved.kml')
예제 #26
0
def main():
    # Initial parameters
    height    = int(720)
    width     = int(1280)
    nsize     = int(9)
    num_nodes = int(50)
    
    # Correct node size
    if (nsize%2) == 0:
        nsize = nsize + 1
    
    # Create figure
    fig = create_newimage(width,height,nsize,num_nodes)
    plt.figure(0)
    plt.imshow(fig, interpolation='nearest')
    plt.title('Base image')
    plt.show(block=False)
    
    # Find nodes
    pos_node = find_node(fig,width,height,nsize);
    print(pos_node)
    
    # Calculate energy = f(distance)
    energy = calc_energy(pos_node);
    
    # Calculate the shortest path
    dijkstra_res = dijkstra.shortest_path(energy,0,num_nodes-1,num_nodes)
    energy_req = dijkstra_res[0]
    path = dijkstra_res[1]
    length_path = dijkstra_res[2]
    
    # Plot the lines on the image
    final_fig = bresenham.line(path,length_path,pos_node,fig);
    plt.figure(1)
    plt.imshow(final_fig, interpolation='nearest')
    plt.title('Final image')
    plt.show()
예제 #27
0
 def draw_path(event, x, y, flags, param):
     if event == cv2.EVENT_LBUTTONDOWN:
         cv2.circle(color_image, (x, y), 5, (0, 255, 0), -1)
         if main.start_point is None:
             main.start_point = (y, x)
         else:
             end_point = (y, x)
             min_bounds = (min(main.start_point[0], end_point[0]),
                           min(main.start_point[1], end_point[1]))
             max_bounds = (max(main.start_point[0], end_point[0]),
                           max(main.start_point[1], end_point[1]))
             if display_bounding_boxes is True:
                 top_left = tuple(reversed(min_bounds))
                 bottom_right = tuple(reversed(max_bounds))
                 cv2.rectangle(color_image, top_left, bottom_right,
                               (255, 0, 0), 3)
             adj_list = partial_adj_list(min_bounds, max_bounds, gradient,
                                         laplacian, max_filter_response)
             # Draw pixels from start_point to end_point, in color red.
             dist, parent = dijkstra.shortest_path(adj_list,
                                                   main.start_point,
                                                   end_point)
             # Construct the path itself from the parent dictionary.
             path = []
             temp = end_point
             while temp is not None:
                 path.append(temp)
                 temp = parent[temp]
             # Paint all those pixels red.
             for pixel in path:
                 cv2.circle(color_image, (pixel[1], pixel[0]), 1,
                            (0, 0, 255), -1)
             # Get ready for next iteration by refreshing the start_point.
             main.start_point = end_point
     if event == cv2.EVENT_RBUTTONDOWN:
         main.start_point = None
예제 #28
0
def curved_earth(filename = 'path_curved.kml'):
    """Test long path"""

    nodes, links = dijkstra.load_data()
    dijkstra.create_adjacency_lists(nodes, links)

    def distance(node1, node2):
        """Returns the distance between node1 and node2, including the
        Earth's curvature."""
        A = node1.latitude*pi/10**6/180
        B = node1.longitude*pi/10**6/180
        C = node2.latitude*pi/10**6/180
        D = node2.longitude*pi/10**6/180
        return acos(sin(A)*sin(C)+cos(A)*cos(C)*cos(B-D))

    source = dijkstra.node_by_name(nodes, 'PASADENA', 'CA')
    destination = dijkstra.node_by_name(nodes, 'CAMBRIDGE', 'MA')
    ans = dijkstra.shortest_path(nodes,
                                 links,
                                 distance,
                                 source,
                                 destination)
    nhpn.Visualizer.toKML(ans, 'path_curved.kml')
    print "path_curved.kml created"
예제 #29
0
with Network("sqlite:///db/app.db") as network, Traffic(
        "sqlite:///db/traffic.db") as traffic:
    end_load = perf_counter()
    print("Databases loaded, took {0:.2} seconds".format(end_load -
                                                         start_load))

    # Query program
    print("Graph loaded.")
    print()
    src = int(input("Source: "))
    dest = int(input("Destination: "))
    print("Calculating shortest path from '{0}' to '{1}'".format(
        network.stops.filter(Stop.id == src).first().name,
        network.stops.filter(Stop.id == dest).first().name,
    ))

    start_dijk = perf_counter()
    path, time = shortest_path(network.graph, src, dest, [traffic])
    end_dijk = perf_counter()

    print("Dijkstra's took {0:.2} seconds".format(end_dijk - start_dijk))

    start_parse = perf_counter()
    trip = parse_route(path, network, [traffic])
    end_parse = perf_counter()

    print("parse_route() took {0:.2} seconds".format(end_parse - start_parse))
    print()
    print(trip)
    print()
예제 #30
0
        vertex_matrix[int(knoten_to_take_from[0])][int(
            knoten_to_take_from[1])] -= delta1

time_end = TimestampMillisec64()

# Ausgabe und Formatierung wie in Eingabedatei
outstring = ""
outstring += str(size) + "\n"
for i in range(0, size):
    for k in range(0, size):
        vertex_matrix[i][k] = round(vertex_matrix[i][k], 3)
        outstring += ("{0:.3f}".format(vertex_matrix[i][k])) + " "
    outstring += "\n"

# Konsolenausgabe
print(outstring)
print("{0:.2f}".format(round(round(verschobene_erde, 3) * 100, 2)) +
      " Euro werden benötigt.")
print("Laufzeit des Programms:", time_end - time_start, "Millisekunden")

# Dateiausgabe
fp = open(filename.split(".")[0] + "-lsg.txt", "w")
fp.write(outstring)
fp.close()

print()
print("Erweiterung für Eingabematrix: ")
dijkstra.shortest_path(old_vertex_matrix)
print("Erweiterung für Ausgabematrix: ")
dijkstra.shortest_path(vertex_matrix)
예제 #31
0
RealadjMmW = np.zeros(newLen)
RealadjMX = np.zeros(newLen)
RealadjMY = np.zeros(newLen)

q = 0
for r in range(0, (keepInd.size)):
    if keepInd[r]:
        RealadjMW[q] = adjMW[np.unravel_index(r, szadjMW, order='F')]
        RealadjMmW[q] = adjMmW[np.unravel_index(r, szadjMW, order='F')]
        RealadjMX[q] = adjMX[np.unravel_index(r, szadjMW, order='F')]
        RealadjMY[q] = adjMY[np.unravel_index(r, szadjMW, order='F')]
        q = q + 1

#finding the 'shortest path'from dark to light
wGraph = sD.sparseToDict(RealadjMX, RealadjMY, RealadjMW)
#finding the 'shortest path' from light to dark
mwGraph = sD.sparseToDict(RealadjMX, RealadjMY, RealadjMmW)
path1 = dj.shortest_path(wGraph, str(np.amin(RealadjMX)),
                         str(np.amax(RealadjMX)))
path2 = dj.shortest_path(mwGraph, str(np.amin(RealadjMX)),
                         str(np.amax(RealadjMX)))

#sparse matrices, 29400 * 29400

#adjMatrixW = sA.sparser(RealadjMX, RealadjMY, RealadjMW, imgNew.size, imgNew.size)
#adjMatrixMW = sA.sparser(RealadjMX, RealadjMY, RealadjMmW, imgNew.size, imgNew.size)

#plt.imshow(img, cmap=plt.cm.gray)
#plt.show
#print (gradImgMinus)
예제 #32
0
파일: console.py 프로젝트: blubits/lakbay
with Network("sqlite:///db/app.db") as network, Traffic(
             "sqlite:///db/traffic.db") as traffic:
    end_load = perf_counter()
    print("Databases loaded, took {0:.2} seconds".format(
        end_load - start_load))

    # Query program
    print("Graph loaded.")
    print()
    src = int(input("Source: "))
    dest = int(input("Destination: "))
    print("Calculating shortest path from '{0}' to '{1}'".format(
        network.stops.filter(Stop.id == src).first().name,
        network.stops.filter(Stop.id == dest).first().name,
    ))

    start_dijk = perf_counter()
    path, time = shortest_path(network.graph, src, dest, [traffic])
    end_dijk = perf_counter()

    print("Dijkstra's took {0:.2} seconds".format(end_dijk - start_dijk))

    start_parse = perf_counter()
    trip = parse_route(path, network, [traffic])
    end_parse = perf_counter()

    print("parse_route() took {0:.2} seconds".format(end_parse - start_parse))
    print()
    print(trip)
    print()
RealadjMY = np.zeros(newLen)

q = 0
for r in range (0, (keepInd.size)):
    if keepInd[r]:
        RealadjMW[q] = adjMW[np.unravel_index(r,szadjMW, order='F')]
        RealadjMmW[q] = adjMmW[np.unravel_index(r,szadjMW, order='F')]
        RealadjMX[q] = adjMX[np.unravel_index(r,szadjMW, order='F')]
        RealadjMY[q] = adjMY[np.unravel_index(r,szadjMW, order='F')]
        q = q + 1

#finding the 'shortest path'from dark to light
wGraph = sD.sparseToDict(RealadjMX, RealadjMY, RealadjMW)
#finding the 'shortest path' from light to dark
mwGraph = sD.sparseToDict(RealadjMX, RealadjMY, RealadjMmW)
path1 = dj.shortest_path(wGraph, str(np.amin(RealadjMX)), str(np.amax(RealadjMX)))
path2 = dj.shortest_path(mwGraph, str(np.amin(RealadjMX)), str(np.amax(RealadjMX)))








#sparse matrices, 29400 * 29400

#adjMatrixW = sA.sparser(RealadjMX, RealadjMY, RealadjMW, imgNew.size, imgNew.size)
#adjMatrixMW = sA.sparser(RealadjMX, RealadjMY, RealadjMmW, imgNew.size, imgNew.size)

#plt.imshow(img, cmap=plt.cm.gray)
 def paved_path_planning(self,startNode,endNode):
     path=shortest_path(graph, startNode, endNode)
     return path
예제 #35
0
        'e': 13
    },
    'k': {
        'j': 5.5,
        'c': 10
    },
    'l': {
        'h': 12,
        'm': 5.2
    },
    'm': {
        'o': 5.2,
        'l': 5.2
    },
    'o': {
        'm': 5.2,
        'p': 5.2
    },
    'p': {
        'o': 5.2,
        'q': 5.2
    },
    'q': {
        'p': 5.2,
        'g': 13
    }
}

path = shortest_path(graph, 'm', 'a')
print(path)
예제 #36
0
import dijkstra

graph = dijkstra.Graph()

for node in ['A', 'B', 'C', 'D', 'E', 'F', 'G']:
    graph.add_node(node)

graph.add_edge('A', 'B', 1)
graph.add_edge('A', 'C', 1)
graph.add_edge('B', 'D', 1)
graph.add_edge('C', 'D', 1)
graph.add_edge('B', 'E', 1)
graph.add_edge('D', 'E', 1)
graph.add_edge('E', 'F', 1)
graph.add_edge('F', 'G', 1)

print(dijkstra.shortest_path(graph, 'A', 'D')) # output: (25, ['A', 'B', 'D'])
예제 #37
0
    def test_binary_case(self):
        """ Tests case where there are only 2 vertices. """
        test_graph = {"A": [(10, "B")], "B": [(10, "A")]}

        self.assertEqual(shortest_path(test_graph, "A", "B"), (10, ["A", "B"]))
        self.assertEqual(shortest_path(test_graph, "B", "A"), (10, ["B", "A"]))
def paved_shortest_path(startNode, endNode):
    graph = {
        'a': {
            'c': 7.2
        },
        'b': {
            'd': 7.2
        },
        'c': {
            'a': 7.2,
            'k': 11,
            'f': 20
        },
        'd': {
            'g': 15
        },
        'e': {
            'j': 13,
            'f': 12,
            'i': 13
        },
        'f': {
            'h': 13,
            'c': 20,
            'e': 12
        },
        'g': {
            'q': 13,
            'd': 15
        },
        'h': {
            'l': 12,
            'i': 12,
            'f': 13
        },
        'i': {
            'h': 12,
            'e': 13
        },
        'j': {
            'k': 5.5,
            'e': 13
        },
        'k': {
            'j': 5.5,
            'c': 10
        },
        'l': {
            'h': 12,
            'm': 5.2
        },
        'm': {
            'o': 5.2,
            'l': 5.2
        },
        'o': {
            'm': 5.2,
            'p': 5.2
        },
        'p': {
            'o': 5.2,
            'q': 5.2
        },
        'q': {
            'p': 5.2,
            'g': 13
        }
    }
    path = shortest_path(graph, startNode, endNode)
    cost = 0
    for i, node in enumerate(path[:-1]):
        cost += graph[path[i]][path[i + 1]]
    return cost, path
예제 #39
0
def handler(event, context):

    status_code = 200

    total_elapsed = 0
    total_turns = 0

    m = eval(event['map_matrix'])
    map_matrix = Map.map_matrix_transfer(m)
    start_position = eval(event['start_position'])
    start_direction = event['start_direction']
    # Algorithm, default=DFS
    algorithm = 'dfs'
    if 'algorithm' in event:
        algorithm = event['algorithm']

    if algorithm == "bfs" or algorithm == "dfs":
        if algorithm == "bfs":
            # run with bfs
            robot = Robot(map_matrix, start_position, start_direction)
            sweeper = BFSSweeper(robot)
        else:
            # run with dfs
            robot = Robot(map_matrix, start_position, start_direction)
            sweeper = DFSSweeper(robot)

        start = time.time()
        sweeper.sweep()
        path_history = robot.path_history

        finished_x = path_history[len(path_history) - 1][0]
        finished_y = path_history[len(path_history) - 1][1]

        back_path_steps = 0
        if str(start_position['x']) + '_' + str(start_position['y']) != str(
                finished_x) + '_' + str(finished_y):
            graph = Graph()
            # print(map_matrix)
            for i in range(len(map_matrix)):
                for j in range(len(map_matrix[i])):
                    floor_type = map_matrix[i][j]
                    if floor_type == 0:
                        graph.add_node(str(j) + '_' + str(i))
                        near_spots = find_adjacent_spot(i, j, map_matrix)
                        for spot_inf in near_spots:
                            spot = spot_inf[0]
                            weight = spot_inf[1]
                            graph.add_edge(str(j) + '_' + str(i), spot, weight)

            back_path_result = shortest_path(
                graph,
                str(finished_x) + '_' + str(finished_y),
                str(start_position['x']) + '_' + str(start_position['y']))

            back_path_steps = back_path_result[0]
            back_path_arr = back_path_result[1]

            for back_spot_str in back_path_arr:
                back_spot_arr = back_spot_str.split('_')
                back_spot_x = int(back_spot_arr[0])
                back_spot_y = int(back_spot_arr[1])
                path_history.append([back_spot_x, back_spot_y])

        elapsed = time.time() - start

        path = Map.path_append_attributes(m, path_history)

        total_elapsed += elapsed
        total_steps = robot.move_count + back_path_steps
        total_turns += robot.turn_count

        result = {
            "path": str(path),
            "steps_taken": total_steps,
            "turns_taken": total_turns,
            "times_taken": round(total_elapsed * 1000, 6)
        }

    elif algorithm == "dijkstra":
        if 'end_position' in event:
            end_position = eval(event['end_position'])

            graph = Graph()
            for i in range(len(map_matrix)):
                for j in range(len(map_matrix[i])):

                    floor_type = map_matrix[i][j]
                    if floor_type == 0:
                        graph.add_node(str(j) + '_' + str(i))
                        near_spots = find_adjacent_spot(i, j, map_matrix)
                        for spot_inf in near_spots:
                            spot = spot_inf[0]
                            weight = spot_inf[1]
                            graph.add_edge(str(j) + '_' + str(i), spot, weight)

            start = time.time()

            to_path_result = shortest_path(
                graph,
                str(start_position['x']) + '_' + str(start_position['y']),
                str(end_position['x']) + '_' + str(end_position['y']))

            back_path_result = shortest_path(
                graph,
                str(end_position['x']) + '_' + str(end_position['y']),
                str(start_position['x']) + '_' + str(start_position['y']))

            elapsed = time.time() - start

            to_path_steps = to_path_result[0]
            to_path_arr = to_path_result[1]

            back_path_steps = back_path_result[0]
            back_path_arr = back_path_result[1]

            path_history = []
            for to_spot_str in to_path_arr:
                to_spot_arr = to_spot_str.split('_')
                to_spot_x = int(to_spot_arr[0])
                to_spot_y = int(to_spot_arr[1])
                path_history.append([to_spot_x, to_spot_y])

            for back_spot_str in back_path_arr:
                back_spot_arr = back_spot_str.split('_')
                back_spot_x = int(back_spot_arr[0])
                back_spot_y = int(back_spot_arr[1])
                path_history.append([back_spot_x, back_spot_y])

            path = Map.path_append_attributes(m, path_history)
            total_steps = to_path_steps + back_path_steps

            result = {
                "path": str(path),
                "steps_taken": total_steps,
                "turns_taken": 0,
                "times_taken": round(elapsed * 1000, 6)
            }
        else:
            status_code = 401
            result = {
                "type": "Params error",
                "code": "401",
                "reason": "Required param not exist"
            }

    return {
        "statusCode": status_code,
        "headers": {
            "Content-Type": "application/json"
        },
        "body": result
    }
예제 #40
0
def get_ride_dictionnary(departure, input_departure_time, destination):

    ## intializing object to track every necessary info for end user on its requested ride ##
    ride_dict = dict()
    ride_dict['Ride_initialization'] = [
        departure, functions.minutes(input_departure_time), '', ''
    ]

    #get the shortest path by executing Dijkstra's algorithm
    ride = dijkstra.shortest_path(departure, input_departure_time, destination)

    stops_of_ride = ride[0]
    times_of_ride = ride[1]

    for stop, time in zip(stops_of_ride, times_of_ride):

        ## retrieving full name of recommended stop by dijkstra ##
        stop_name = Stops.query.with_entities(
            Stops.stop_name).filter(Stops.id == stop).all()[0][0]

        #if it a current stop needs a transfer and is not the arrival: mark it as transfer
        if (stop != stops_of_ride[-1]) and (
                stop, stops_of_ride[stops_of_ride.index(stop) +
                                    1]) in Transfers.query.with_entities(
                                        Transfers.from_stop_id,
                                        Transfers.to_stop_id).all():
            departure_time_at_stop = time
            route_of_trip = "Transfer"
            direction_of_trip = stops_of_ride[
                stops_of_ride.index(stop) + 1]  #where to move for the transfer
            ride_dict[stop] = [
                stop_name, departure_time_at_stop, route_of_trip,
                direction_of_trip
            ]
            is_terminus = "No"
            #if not a transfer
        else:

            ## retreiving departure time at this stop  ##
            schedules_and_tripid_at_stop = Stop_times.query.with_entities(
                Stop_times.departure_time, Stop_times.trip_id
            ).filter(
                Stop_times.stop_id == stop
            )  #get all departure schedules at this stop & associated trip id
            schedules_and_tripid_at_stop_in_minutes = [
                (functions.minutes(i[0]), i[1])
                for i in schedules_and_tripid_at_stop
            ]  #convert schedules in minutes
            departure_time_at_stop = min(
                filter(lambda x: x >= 0, [
                    i - time
                    for (i, _) in schedules_and_tripid_at_stop_in_minutes
                ])
            ) + time  #retrieve the departure time recommended by dijkstra (will only change for the departure)

            ## retreiving the trip id of stop given its departure time ##
            trip_of_stop = list(
                filter(lambda tuple: tuple[0] == departure_time_at_stop,
                       schedules_and_tripid_at_stop_in_minutes))[0][1]

            ## checking if current stop is a service terminus (no departure time from it, it is actually just an  arrival time so it will need a transit, or it can a departure time but for a different destination, so a different service)
            check_for_departure_at_this_time = Timetable.query.with_entities(
                Timetable.departure_time).filter(
                    Timetable.from_stop_id == stop, Timetable.departure_time ==
                    int(departure_time_at_stop)).all()
            #flagging if its the case
            if check_for_departure_at_this_time == []:  #it is just an arrival time (end of service)
                is_terminus = "Yes"
            else:
                is_terminus = "No"

            ## retrieving the route associated to the stop ##
            route_of_trip = Trips.query.with_entities(
                Trips.route_id).filter(Trips.id == trip_of_stop).all()[0][0]

            ## retreiving the direction informaiton associated to the trip ##
            direction_of_trip = Trips.query.with_entities(
                Trips.trip_headsign).filter(
                    Trips.id == trip_of_stop).all()[0][0]

            ## storing every useful info on the stop given its departure time, for documenting the requested ride by user ##
            ride_dict[stop] = [
                stop_name, departure_time_at_stop, route_of_trip,
                direction_of_trip, is_terminus, trip_of_stop
            ]

    return ride_dict
예제 #41
0
def retinal_segmentation(input_image):
    img = misc.imread(input_image)

    #Blur the image (gaussian blur)
    kernel = matlab_style_gauss2D()
    img = Image.fromarray(
        ndimage.filters.correlate(img, kernel, mode='constant'))
    #img = cv2.GaussianBlur(img, (5,21), 3) A different blurring technique

    #resize the image (to 1/10th), with antialiasing.  Otherwise will not be the
    #same as MATLAB's resize.
    rsFactor = 0.1
    img = img.resize(
        ((int(img.size[0] * rsFactor)), (int(img.size[1] * rsFactor))),
        Image.ANTIALIAS)
    img = np.array(img)
    szImg = img.shape

    #add a column of zeros on both sides, which saves us from having to know the
    #endpoints of the layers a priori.
    imgNew = np.lib.pad(img, ((0, 0), (1, 1)), 'constant')
    szImgNew = imgNew.shape
    gradImg = np.zeros(szImgNew)

    for i in range(0, (int(szImgNew[1]))):
        #Change to float, otherwise negative gradient values will be reported as
        #(value)mod4 (and then converted to floats without telling anyone)
        #>:-(
        gradImg[:, i] = np.gradient(([float(ele) for ele in imgNew[:, i]]), 2)

    #vertical gradient, scaled so that all values are between 0 and 1
    gradImg = (gradImg - np.amin(gradImg)) / (np.amax(gradImg) -
                                              np.amin(gradImg))
    #'inverts' the image
    gradImgMinus = gradImg * (-1) + 1

    #Adjacency matrix

    minWeight = 1.0 * 10**(-5)

    #weights
    adjMW = np.empty((((int(szImgNew[0])) * (int(szImgNew[1]))), 8))
    #neg weights
    adjMmW = np.empty((((int(szImgNew[0])) * (int(szImgNew[1]))), 8))
    #point A
    adjMX = np.empty((((int(szImgNew[0])) * (int(szImgNew[1]))), 8))
    #point B
    adjMY = np.empty((((int(szImgNew[0])) * (int(szImgNew[1]))), 8))

    adjMW[:] = np.NAN
    adjMmW[:] = np.NAN
    adjMX[:] = np.NAN
    adjMY[:] = np.NAN

    neighborIter = np.array([[1, 1, 1, 0, 0, -1, -1, -1],
                             [1, 0, -1, 1, -1, 1, 0, -1]])

    szadjMW = adjMmW.shape

    ind = 0
    #indR = 0
    #creating the adjacency matrix
    while ind != ((int(szadjMW[0])) * (int(szadjMW[1])) - 1):
        #order='F' means fortran style, or column-major (like MATLAB)
        (i, j) = np.unravel_index(ind, szadjMW, order='F')
        (iX, iY) = np.unravel_index(i, szImgNew, order='F')
        (jX, jY) = ((iX + neighborIter[0, j]), (iY + neighborIter[1, j]))
        if jX >= 0 and jX <= (int(szImgNew[0]) -
                              1) and jY >= 0 and jY <= (int(szImgNew[1]) - 1):
            if jY == 0 or jY == (int(szImgNew[1]) - 1):
                adjMW[i, j] = minWeight
                adjMmW[i, j] = minWeight
            else:
                adjMW[i, j] = 2 - gradImg[iX, iY] - gradImg[jX, jY] + minWeight
                adjMmW[i,
                       j] = 2 - gradImgMinus[iX,
                                             iY] - gradImgMinus[jX,
                                                                jY] + minWeight
            #save subscripts
            adjMX[i, j] = np.ravel_multi_index((iX, iY), szImgNew, order='F')
            adjMY[i, j] = np.ravel_multi_index((jX, jY), szImgNew, order='F')
        ind = ind + 1

    #ASSEMBLE
    a = np.logical_and(np.ravel(~np.isnan(adjMW[:]), order='F'),
                       np.ravel(~np.isnan(adjMX[:]), order='F'))
    b = np.logical_and(np.ravel(~np.isnan(adjMY[:]), order='F'),
                       np.ravel(~np.isnan(adjMmW[:]), order='F'))
    keepInd = np.logical_and(a, b)

    newLen = 0
    for p in range(0, (keepInd.size)):
        if keepInd[p]:
            newLen = newLen + 1

    RealadjMW = np.zeros(newLen)
    RealadjMmW = np.zeros(newLen)
    RealadjMX = np.zeros(newLen)
    RealadjMY = np.zeros(newLen)

    q = 0
    for r in range(0, (keepInd.size)):
        if keepInd[r]:
            RealadjMW[q] = adjMW[np.unravel_index(r, szadjMW, order='F')]
            RealadjMmW[q] = adjMmW[np.unravel_index(r, szadjMW, order='F')]
            RealadjMX[q] = adjMX[np.unravel_index(r, szadjMW, order='F')]
            RealadjMY[q] = adjMY[np.unravel_index(r, szadjMW, order='F')]
            q = q + 1

    #finding the 'shortest path' on the dark to light boundary
    wGraph = sparseToDict(RealadjMX, RealadjMY, RealadjMW)
    path1 = dj.shortest_path(wGraph, str(np.amin(RealadjMX)),
                             str(np.amax(RealadjMX)))

    #finding the 'shortest path' on the light to dark boundary
    mwGraph = sparseToDict(RealadjMX, RealadjMY, RealadjMmW)
    path2 = dj.shortest_path(mwGraph, str(np.amin(RealadjMX)),
                             str(np.amax(RealadjMX)))

    fullPathLen1 = len(path1)
    fullPathLen2 = len(path2)

    pathX1 = np.zeros(fullPathLen1)
    pathY1 = np.zeros(fullPathLen1)
    pathX2 = np.zeros(fullPathLen2)
    pathY2 = np.zeros(fullPathLen2)

    #indicies reversed again??
    for a in range(0, fullPathLen1):
        (pathY1[a], pathX1[a]) = np.unravel_index(int(float(path1[a])),
                                                  szImgNew,
                                                  order='F')
    for b in range(0, fullPathLen2):
        (pathY2[b], pathX2[b]) = np.unravel_index(int(float(path2[b])),
                                                  szImgNew,
                                                  order='F')

    #display
    fig = plt.figure(figsize=(12, 12))
    imgplot = plt.imshow(imgNew, cmap=plt.cm.gray, figure=fig)
    plt.plot(pathX1, pathY1, 'b-', figure=fig)
    plt.plot(pathX2, pathY2, 'r-', figure=fig)