0

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?

JaP
  • 87
  • 6
  • Glad you solved it. In the future, giving the full "traceback" for the error will help us diagnose the problem. – Joel Apr 22 '19 at 03:50

2 Answers2

0

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
Sparky05
  • 4,692
  • 1
  • 10
  • 27
JaP
  • 87
  • 6
0

Your method of copying the graph, removing a random node and then checking if the graph remains connected, is likely not efficient for large graphs.

Instead, get the list of nodes you can safely remove via: list(nx.bridges(self.G)).

A bridge in a graph is an edge whose removal causes the number of connected components of the graph to increase. Equivalently, a bridge is an edge that does not belong to any cycle. Bridges are also known as cut-edges, isthmuses, or cut arcs.

https://networkx.org/documentation/stable/reference/algorithms/generated/networkx.algorithms.bridges.bridges.html#networkx.algorithms.bridges.bridges

Michael Currie
  • 13,721
  • 9
  • 42
  • 58