def readUndirectedGraph(filename):
    '''
    the information about a graph is read from a given textfile and the graph is created
    :param filename: the given file
    :return: the read graph
             raises ValueError if file not found
    '''
    try:
        with open(filename, "r") as file:
            lines = file.readlines()
            lines[0] = lines[0].strip("\n")
            graphVerticesAndEdges = lines[0].split(" ")
            numberOfVertices = int(graphVerticesAndEdges[0])
            numberOfEdges = int(graphVerticesAndEdges[1])
            graph = UndirectedGraph(numberOfVertices, numberOfEdges)
            lines = lines[1:]
            for line in lines:
                line = line.strip("\n")
                edge = line.split(" ")
                vertex1 = int(edge[0])
                vertex2 = int(edge[1])
                cost = int(edge[2])
                graph.addEdge(vertex1, vertex2, cost)
    except:
        raise ValueError("File not found")
    return graph
Пример #2
0
    def create_graph(self, start_position, initial_pheromone):
        # calculate the cooverages of each sensor at each power level
        for sensor in self.__repository.sensors.values():
            sensor.calculate_coverage(self.__repository.mapp)

        self.__graph = UndirectedGraph()

        # transform the starting point and each sensor's different states into vertices
        start_vertex = Vertex(start_position, 0, 0)
        self.__graph.add_vertex(start_vertex)

        for sensor in self.__repository.sensors.values():
            for i, coverage in enumerate(sensor.coverages):
                vertex = Vertex(sensor.position, i, coverage)
                self.__graph.add_vertex(vertex)

        vertices = list(self.__graph.parse_vertices())

        for i in range(len(vertices) - 1):
            start = vertices[i]

            for j in range(i + 1, len(vertices)):
                end = vertices[j]

                if start.position[0] != end.position[0] and start.position[1] != end.position[1]:
                    path = self.search_a_star(
                        start.position[0], start.position[1], end.position[0], end.position[1])

                    cost = len(path)
                    edge = Edge(start, end, cost, path, initial_pheromone)
                    self.__graph.add_edge(edge)
Пример #3
0
def run():
    graph = UndirectedGraph()
    #random_graph(graph, 100, 10)
    load_from_file(graph, "graph5.txt")
    service = Service(graph)
    ui = UI(graph, service)
    ui.run()
    save_to_file(graph, "graph_out.txt")
Пример #4
0
    def setUp(self):
        graph = UndirectedGraph(7)
        graph.addEdge(0, 1)
        graph.addEdge(1, 2)
        graph.addEdge(1, 3)
        graph.addEdge(1, 4)
        graph.addEdge(4, 5)
        graph.addEdge(4, 6)
        graph.addEdge(0, 4)

        self.solver = DFSSolver(graph)
Пример #5
0
    def setUp(self):
        self.graph = UndirectedGraph()

        for i in range(6):
            self.graph.add_vertex(i+1)

        self.graph.add_edge(1, 2)
        self.graph.add_edge(1, 4)
        self.graph.add_edge(2, 4)
        self.graph.add_edge(2, 3)
        self.graph.add_edge(4, 3)
        self.graph.add_edge(3, 6)
        self.graph.add_edge(4, 5)
        self.graph.add_edge(5, 6)
Пример #6
0
 def __ui_read_graph_from_file(self):
     file_name = input("insert name of the file:\n>>>")
     with open(file_name, "r") as f:
         line = f.readline()
         line = line.strip()
         parts = line.split()
         no_of_vertices = int(parts[0])
         no_of_edges = int(parts[1])
         graph = UndirectedGraph(no_of_vertices)
         for _ in range(no_of_edges):
             line = f.readline()
             line = line.strip()
             parts = line.split()
             graph.add_edge(int(parts[0]), int(parts[1]), int(parts[2]))
     self.__graph = graph
Пример #7
0
def readGraph(file):
    graph_file =  open(file, 'r')
    graph = None

    for line_no, line in enumerate(graph_file):
        if line_no == 0:
            matrix_size = int(line)
            graph = UndirectedGraph(matrix_size)
        else:
            line = line.strip()
            for col_no, col in enumerate(line):
                if col == "1":
                    graph.addEdge(line_no - 1, col_no)
        line_no += 1

    graph_file.close()
    return graph
def _construct_undirected_graph(filename: str) -> UndirectedGraph:
    """
    Private helper function to construct a undirected graph from the given
    undirected graph file.
    :param filename: str
    :return: UndirectedGraph
    """
    with open(filename, 'rt') as f:
        graph = UndirectedGraph()
        # Add the vertices
        n_vtx = int(f.readline())
        for vtx_id in range(1, n_vtx + 1):
            graph.add_vtx(new_vtx_id=vtx_id)
        # Add the edges
        for line in f.readlines():
            ends = line.split(' ')
            graph.add_edge(end1_id=int(ends[0]), end2_id=int(ends[1]))
        return graph
Пример #9
0
    def test_findBestSolutionFor10(self):
        graph = UndirectedGraph(10)
        graph.addEdge(0, 4)
        graph.addEdge(0, 5)
        graph.addEdge(0, 6)
        graph.addEdge(0, 8)
        graph.addEdge(0, 9)

        graph.addEdge(1, 2)
        graph.addEdge(1, 3)
        graph.addEdge(1, 5)
        graph.addEdge(1, 6)
        graph.addEdge(1, 7)
        graph.addEdge(1, 8)

        graph.addEdge(2, 6)
        graph.addEdge(2, 7)
        graph.addEdge(2, 9)

        graph.addEdge(3, 5)
        graph.addEdge(3, 6)
        graph.addEdge(3, 7)

        graph.addEdge(4, 5)
        graph.addEdge(4, 6)
        graph.addEdge(4, 8)
        graph.addEdge(4, 9)

        graph.addEdge(5, 9)

        graph.addEdge(6, 7)
        graph.addEdge(6, 9)

        graph.addEdge(7, 8)

        solver = DFSSolver(graph)

        # self.solver.DEBUG = True
        solution, price = solver.findBestSolution()
        self.assertEqual(2, price)
        expected = [Edge(0, 9), Edge(1, 2), Edge(1, 3), Edge(3, 5), Edge(4, 5), Edge(4, 8), Edge(6, 7), Edge(6, 9), Edge(7, 8)]
        self.assertEqual(set(expected), set(solution.edgeList()))
Пример #10
0
 def setUp(self):
     self.graph = UndirectedGraph(5)
Пример #11
0
        neighborVertex.cost = newCost
        neighborVertex.prev = current

  # current is end
  # is the final node unreachable
  if vertexes[current].cost == float("Inf"):
    return None

  # walk back from current, using vertex.prev, building the list
  finalPath = []
  while vertexes[current].cost != 0:
    finalPath.append(vertexes[current].index)
    current = vertexes[current].prev
  finalPath.append(current)

  # return the list and the final cost
  return (list(reversed(finalPath)), vertexes[finalPath[0]].cost)




ug = UndirectedGraph(10)

startEndOptions = range(ug.nodeCount)
start = startEndOptions.pop(random.randint(0, len(startEndOptions) - 1))
end = startEndOptions.pop(random.randint(0, len(startEndOptions) - 1))

print 'paths', ug.paths
print 'costs', ug.costs
print 'path from', start, 'to', end
print dijkstra(ug, start, end)
        return False

    def contains_cycle(self):
        for i in range(self.vertices_count):
            if not self.visited[i]:
                if self.dfs(i, -1):
                    return True

        return False


if __name__ == '__main__':

    # https://www.geeksforgeeks.org/detect-cycle-undirected-graph/
    graph = UndirectedGraph()
    graph.add_edge(1, 0)
    graph.add_edge(1, 2)
    graph.add_edge(2, 0)
    graph.add_edge(0, 3)
    graph.add_edge(3, 4)
    dfs_graph = DetectCycleDFS(graph)
    if dfs_graph.contains_cycle():
        print('contains cycle!')
    else:
        print('no cycle found')

    graph2 = UndirectedGraph()
    graph2.add_edge(0, 1)
    graph2.add_edge(1, 2)
    dfs_graph2 = DetectCycleDFS(graph2)
from undirected_graph import UndirectedGraph, Node, Edge

nodes = [
    Node(0),
    Node(1),
    Node(2),
    Node(3),
    Node(4),
    Node(5),
    Node(6),
    Node(7),
    Node(8)
]

edges = [ \
    Edge(nodes[0], nodes[3], 2), \
    Edge(nodes[0], nodes[4], 4), \
    Edge(nodes[4], nodes[1], 3), \
    Edge(nodes[1], nodes[2], 1), \
    Edge(nodes[1], nodes[5], 7), \
    Edge(nodes[2], nodes[5], 6), \
    Edge(nodes[5], nodes[8], 4), \
    Edge(nodes[5], nodes[7], 0), \
    Edge(nodes[8], nodes[7], 8), \
    Edge(nodes[7], nodes[6], 9)]

graph = UndirectedGraph(nodes, edges)
Пример #14
0
    def setUp(self):
        self.client = Redis()
        self.client.flushdb()

        self.graph = UndirectedGraph(self.client, "test-graph")
                self.dfs(i)

    def dfs(self, at):
        self.visited[at] = True
        # marking connecting components of 'at'
        self.connected_components[at] = self.count
        neighbors = self.graph.get_adjacent_vertices(at)
        for neighbor in neighbors:
            if not self.visited[neighbor]:
                self.previous[neighbor] = at
                self.dfs(neighbor)


if __name__ == '__main__':
    # create graph and add edges for testing bfs
    graph = UndirectedGraph()
    #graph = DirectedGraph()
    # graph in Algorithms pg. 529
    graph.add_edge(0, 5)
    graph.add_edge(4, 3)
    graph.add_edge(0, 1)
    graph.add_edge(9, 12)
    graph.add_edge(6, 4)
    graph.add_edge(5, 4)
    graph.add_edge(0, 2)
    graph.add_edge(11, 12)
    graph.add_edge(9, 10)
    graph.add_edge(0, 6)
    graph.add_edge(7, 8)
    graph.add_edge(9, 11)
    graph.add_edge(5, 3)