Reputation: 3098
I want to force an undirected graph to a directed graph using a specific node as the root. I can do this using dfs_tree()
:
G = nx.Graph([(0, 1, {"color": "red"}), (1, 2, {"color": "blue"}), (3, 2, {"color": "green"})])
DG = nx.dfs_tree(G, 0)
But the problem is that the attributes are lost in the process:
DG.edges(data=True)
OutEdgeDataView([(0, 1, {}), (1, 2, {}), (2, 3, {})])
Is there a different way to do this, where you don't lose the attributes? Or do I have to map them back manually?
Upvotes: 1
Views: 517
Reputation: 4892
If you have enough memory available, you can first create the DiGraph
with all edges and then remove all, but the dfs_edges
. This will preserve all attribute information. Alternatively, you could iterate over dfs_edges
and retrieve the edge information to add the edge and the label to the directed graph.
import networkx as nx
G = nx.Graph([(0, 1, {"color": "red"}), (1, 2, {"color": "blue"}), (3, 2, {"color": "green"})])
DG = nx.DiGraph(G)
DG.remove_edges_from(DG.edges - nx.dfs_edges(G, 0))
print(DG.edges(data=True))
# [(0, 1, {'color': 'red'}), (1, 2, {'color': 'blue'}), (2, 3, {'color': 'green'})]
Upvotes: 2