Пример #1
0
def main(graph_path):
    """Display the result of dijkstra's algorithm for a given graph

    Parameters:
    -----------
    graph_path: path of matrix which be used (str)

    """

    #get the graph
    graph = graph_loader(graph_path)

    #display it
    print("--- matrix of used graph ---")
    for line in graph:
        print(line)

    #set all 0 to inf
    for x in range(len(graph)):
        for y in range(len(graph[0])):
            if graph[x][y] == 0:
                graph[x][y] = inf

    #ask to user starting node and ending node
    starting_node = int(input("\nStarting node (index): "))
    ending_node = int(input("Ending node (index): "))

    #call dijkstra's algorithm:
    shortest_way, total_cost = dijkstra(graph, starting_node, ending_node)

    #display the shortest way and his total weight
    print("the shortest path from %d to %d is %s and his total cost his %d" %
          (starting_node, ending_node, shortest_way, total_cost))
Пример #2
0
 def djonson(self):
     self.textEdit.setText("")
     for i in range(len(self.graph.vertexes)):
         distance = algorithm.dijkstra(str(i + 1), self.graph.to_matrix())
         for j in range(len(distance)):
             self.textEdit.append(
                 f'Расстояние от {i + 1} до {j + 1} = {distance[j]}')
     self.graph.update()
Пример #3
0
def run():
    click.clear()
    print("Executando " + argv[0] + "...")

    if (len(argv) != 3):
        print("Sem parâmetros informados!\n    Modo de uso:")
        print(" > python " + argv[0] + " [ARQUIVO] [VÉRTICE INICIAL]")
        exit()
    else:
        file = Path(argv[1])
        if (not (file.is_file() and file.exists())):
            print("Arquivo \"" + argv[1] +
                  "\" não existe, enviar arquivo existente!")
            print(" > python " + argv[0] + " [ARQUIVO] [VÉRTICE INICIAL]")
            exit()
        else:
            print("Arquivo do grafo: \"" + argv[1] + "\"   |OK|")
            num = 0
            for line in open(file):
                if (line is "\n"):
                    continue
                num += 1
            index = ord(argv[2]) - 65
            if (index < num and index >= 0 and index < 26):
                print("Vértice inicial do grafo: " + argv[2] + " |OK|")
            else:
                print("Vértice inicial [" + argv[2] + "] inexistente.")
                print("Vértices existentes = { ", end='')
                for i in range(num):
                    print(chr(i + 65) + " ", end='')
                print("}\nSelecionar vértice existente!")
                print(" > python " + argv[0] + " [ARQUIVO] [VÉRTICE INICIAL]")
                exit()

    graph = Graph(argv[1])
    graph.setStart(argv[2])
    print("\\--" + "--" * 14 + "---/")
    print(" Executando Algoritmo de DIJKSTRA")
    dijkstra(graph)
    print(" Algoritmo executado!")
    print("/--" + "--" * 14 + "---\\")

    return graph
    def visualize(self, algo):
        if self.executing:
            return
        case = algo.get()
        if case != None:
            self.clear()
            self.executing = True
            start = self.grids[self.startPos[1]][self.startPos[0]]
            goal = self.grids[self.goalPos[1]][self.goalPos[0]]

            if case == 0:
                algorithm.AStar(self, start, goal)
            elif case == 1:
                algorithm.dijkstra(self, start, goal)
            elif case == 2:
                algorithm.greedy(self, start, goal)
            elif case == 3:
                algorithm.bfs(self, start, goal)
            elif case == 4:
                algorithm.dfs(self,start, goal)
Пример #5
0
def find_center(graph):
    if isConnected(graph.to_matrix(), graph.oriented) == "Граф не связный":
        return "Граф не связный", None
    size = graph.size()
    ecscentr = []
    centres = []
    for i in range(size):
        dist = dijkstra(str(i + 1), graph.to_matrix())
        ecscentr.append(max(dist))
    r = min(ecscentr)
    for i in range(len(ecscentr)):
        if r == ecscentr[i]:
            centres.append(str(i + 1))

    return centres, r
Пример #6
0
    def dijkstra(self):
        '''
        Run Dijkstra's algorithm.
        '''
        if self._adjlist.is_empty():
            self.display_error("graph is empty")
            return
        start_node, err = self.get_node("Enter start node", True)
        if err is not None:
            self.display_error(err)
            return

        dist, prev = dijkstra(self._adjlist, start_node)
        self.display_sequence_head(self._adjlist.list_nodes())
        self.display_sequence_data([
            ("distance", dist, None),
            ("previous", prev, None),
        ])
Пример #7
0
    def radius_diametr(self):
        self.textEdit.setText("")
        with open("res.txt", "w", encoding='utf8') as f:
            size = self.graph.size()
            ecscentr = []
            for i in range(size):
                dist = algorithm.dijkstra(str(i + 1), self.graph.to_matrix())
                maximum = np.inf * -1
                for j in range(len(dist)):
                    if dist[j] > maximum:
                        maximum = dist[j]
                ecscentr.append(maximum)
            self.textEdit.append(f'Эксцентриситеты: {ecscentr}')
            f.write(f'Эксцентриситеты: {str(ecscentr)}\n')
            diam = np.inf * -1
            rad = np.inf
            for i in range(len(ecscentr)):
                if ecscentr[i] > diam:
                    diam = ecscentr[i]
                if ecscentr[i] < rad:
                    rad = ecscentr[i]

            if diam == np.inf:
                self.textEdit.append(f'Граф не связный')
            else:
                self.textEdit.append(f'Диаметр = {diam}')
                self.textEdit.append(f'Радиус = {rad}')
            f.write(f'Диаметр = {str(diam)}\n')
            f.write(f'Радиус = {str(rad)}\n')

            matrix = self.graph.to_matrix()
            degrees = np.zeros(size)
            for i in range(len(matrix)):
                for j in range(len(matrix)):
                    if matrix[i][j] != 0:
                        degrees[i] += 1
                        degrees[j] += 1
            if not self.graph.oriented:
                for i in range(len(degrees)):
                    degrees[i] = degrees[i] // 2
            self.textEdit.append(f'Вектор степеней: {degrees}')
            f.write(f'Вектор степеней: {str(degrees)}\n')
Пример #8
0
    def slotConfirm(self):
        self.area.clearTemp()
        #check S and G existence
        if self.area.vertexS is None:
            QMessageBox.critical(self, 'No Start Vertex',
                                 'Algorithm requires a start vertex.')
            return
        if self.area.vertexG is None:
            QMessageBox.critical(self, 'No Goal Vertex',
                                 'Algorithm requires a goal vertex.')
            return

        #run dijkstra
        self.graph = alg.dijkstra(self.area.vertexSet, self.area.edgeSet,
                                  self.area.vertexS, self.area.vertexG)
        self.graph.preprocess()
        self.graph.preprocessDijkstra()
        self.graph.dijkstraLoop()

        warn = False
        #check connectivity
        if self.area.vertexG.distG == float('inf'):
            warn = True
            QMessageBox.warning(
                self, 'No Path',
                'No path from S to G. \nTips: this is a direct graph.')

        res = False
        #check under-estimation
        for v in self.area.vertexSet.values():
            res = res or v.checkPotential()
        if res:
            warn = True
            QMessageBox.warning(self, 'Bad Estimation',
                                'Some estimations are over-estimated.')

        if not warn:
            QMessageBox.information(self, 'Check Complete',
                                    'Now you can run BDA*.')
        self.BDASBtn.setEnabled(True)
        return
Пример #9
0
 def run(self, origin, destination):
     return algorithm.dijkstra(self.graph, origin, destination)
Пример #10
0
 def dijkstra(self, begin: str):
     return algorithm.dijkstra(begin, self.graph.to_matrix())
Пример #11
0
def letsfind():
    startsize = int(input("Enter the starting  size "))
    endsize = int(input("Enter the max size "))
    step = int(input("Enter the growth size "))
    data = {}  # The main dictionary
    probability_list = [
        0.1,
        0.3,
        0.5,
        0.7,
    ]  # Probability list
    for probability in probability_list:  # Looping for each probability
        subdict = {}
        for size in range(startsize, endsize + step,
                          step):  # Looping for each size defined
            successcount = 0  # Initializations
            paths_bfs = []
            paths_dfs = []
            paths_dijk = []
            paths_bibfs = []
            time_bfs = []
            time_dfs = []
            time_dijk = []
            time_bibfs = []

            for x in range(0, 2):  # 10 Iterations and mean results
                maze = mz.create_maze(size, probability)
                print("Maze Moving to Next")

                graph = mz.create_graph(maze)  # Create graph through maze
                print("Graph Moving to Next")

                start = (0, 0)  # start point
                end = ((maze.shape[0] - 1), (maze.shape[0] - 1))  # End point

                bfs_sol = al.bfs(graph, start, end)  # BFS
                print("BFS  Moving to Next")
                paths_bfs.append(len(bfs_sol[2]))
                time_bfs.append(bfs_sol[3])
                if bfs_sol[0] == "S":
                    successcount = successcount + 1  # Success count incrementing

                dfs_sol = al.dfs(graph, start, end)  # DFS
                print("DFS  Moving to Next")
                paths_dfs.append(len(dfs_sol[2]))
                time_dfs.append(dfs_sol[3])

                dijk_sol = al.dijkstra(graph, start, end)  # DIJKSTRA
                print("Dijkstra Moving to Next")
                paths_dijk.append(len(dijk_sol[2]))
                time_dijk.append(dijk_sol[3])

                bibfs_sol = al.bibfs(graph, start, end)  # BI-BFS
                print("BiBFS Moving to Next")
                paths_bibfs.append(len(bibfs_sol[2]))
                time_bibfs.append(bibfs_sol[3])

            # Dictionary holding size as keys and Means results of each algorithm
            subdict[size] = {
                "TotalSuccessRate": successcount,
                "bfs_path": statistics.mean(paths_bfs),
                "bfs_time": statistics.mean(time_bfs),
                "dfs_path": statistics.mean(paths_dfs),
                "dfs_time": statistics.mean(time_dfs),
                "dijk_path": statistics.mean(paths_dijk),
                "dijk_time": statistics.mean(time_dijk),
                "bibfs_path": statistics.mean(paths_bibfs),
                "bibfs_time": statistics.mean(time_bibfs)
            }

        data[
            probability] = subdict  # Adding Probability as keys and Values as the sub dictionary

    vis.disp_stats_for_probab(data, startsize, endsize, step,
                              probability_list)  # success rate vs size
    vis.disp_time_for_probab3(data, startsize, endsize, step)  # time vs size
    vis.disp_path_for_probab3(data, startsize, endsize, step)  # Path vs size