I want to replace a subgraph S of a networkx graph G by a single node N that again contains the entire subgraph S.
I need to do that because I need an edge from N to other nodes of my graph.
Because I did not get the subgraph method of network x to work, I wrote my own code to do it. But I am confused with the results.
This is a small example script:
import networkx as nx
from copy import deepcopy
from collections import deque
class XGraph(nx.MultiDiGraph):
def dographthings(self, graph_edges, graph_nodes, subgraph_nodes):
self.add_edges_from(graph_edges)
subgraph = deepcopy(self)
# remove all nodes and their transitive children from subgraph,that are
# not in subgraph_nodes
remove_subtree(deque((set(graph_nodes) - set(subgraph_nodes))), subgraph)
# remove all nodes from self that are now in subgraph
self.remove_nodes_from(subgraph)
print "subgraph:"
print type(subgraph)
for node in subgraph.nodes_iter():
print node
print "self:"
print type(self)
for node in self.nodes_iter():
print node
self.add_node(subgraph)
print self.node[subgraph]
def remove_subtree(nodes, graph):
"""
Removes all nodes that are successors of the nodes in ``nodes``.
Is robust for cyclic graphs.
Parameters
----------
graph : referance to networkx.graph
graph to remove nodes from
nodes : deque of nodes-ids
the nodes the successors of which to remove from graph
"""
to_remove = set()
to_add = list()
for node in nodes:
to_remove.add(node)
if node in graph:
to_add.extend(graph.successors(node))
graph.remove_node(node)
for node in to_remove:
nodes.remove(node)
for node in to_add:
nodes.append(node)
if len(nodes) > 0:
graph = remove_subtree(nodes, graph)
g = XGraph()
g.dographthings([(1,2),(2,3),(2,4),(1,5)], [1,2,3,4,5], [3,2,1])
The class XGraph has a method that add edges to the graph and also build a subgraph as described above.
When I then iterate over the nodes of the graph and the subgraph, everything appears to be correct. Then when I add
the subgraph as a node, and access it via the get_item-method, it seems to have become an empty dictionary rather than a
MultiDiGraph, as it was before adding it as a node.
The output of the script is this:
subgraph:
<class '__main__.XGraph'>
1
2
3
self:
<class '__main__.XGraph'>
4
5
{}
Why does my subgraph become a dictionary upon being added as a node and where does all its data go?
EDIT
I accessed the node incorrectly. Doing it like this works:
for node in self.nodes_iter(data=True):
if isinstance(node[0], nx.MultiDiGraph):
print "this is the subgraph-node:"
print node
print "these are its internal nodes:"
for x in node[0].nodes_iter():
print x
else:
print "this is an atomic node:"
print node
The output:
this is the subgraph-node:
(<__main__.XGraph object at 0xb5ec21ac>, {})
these are its internal nodes:
1
2
3
this is an atomic node:
(4, {})
this is an atomic node:
(5, {})