networkxconnected-componentsstrongly-connected-graph

Removing nodes (but keeping graph strongly connected)


I'm trying to simulate a rectangular room with some rectilinear obstacles within it, and so I formulated the problem as a graph in networkx. To add the obstacles, I'll choose nodes and then delete all of its edges. In order to prevent the graph from partitioning, this is the code I used

        self.G = nx.grid_2d_graph(*room_size)

        # create obstacles but keep graph strongly connected
        for i in range(obstacles):
            copy = self.G.copy
            while nx.number_connected_components(copy) != 1:
                copy = self.G.copy
                copy.remove_node(sample(self.G.nodes(),1))
            self.G = copy

But it seems the 'nx.number_connected_components(copy) ' raises an error: 'function' object has no attribute 'is_directed'

Which makes no sense to me because the graph is a grid_2d_graph, which is clearly undirected. What is the problem and how do I fix it?


Solution

  • Got it.

    while obstacles > 0:
        copy = self.G.copy()
        copy.remove_node(choice(list(self.G.nodes)))
    
        if nx.number_connected_components(copy) == 1:
            self.G = copy
            obstacles -= 1
        else:
            continue