You want to construct the graph with edges between nodes in original graph as nodes and nodes in original graphs as edges, as I understand. In this case, your graph in post is incorrect. For example: you have node be
, which is a successor of ae
, but in original graph it is not true, ae
and be
are parallel. I constructed a code to solve this problem:
import networkx as nx
import random
from itertools import groupby
# Create a random DAG
G = nx.gnp_random_graph(10,0.3,directed=True)
DAG = nx.DiGraph([(u,v) for (u,v) in G.edges() if u<v])
res = nx.DiGraph()
# Create nodes in new DAG as edges in original DAG
res.add_nodes_from(list(DAG.edges()))
sorted_res_nodes = sorted(res.nodes, key=lambda x: x[1])
# Connect all nodes with end of node1 is equal to start of node2
for n1 in sorted_res_nodes:
for n2 in sorted_res_nodes:
if n1[1] == n2[0]:
res.add_edge(n1, n2)
# Draw graphs
nx.draw(
DAG,
with_labels=True,
pos=nx.drawing.nx_agraph.graphviz_layout(
DAG, prog='dot'
)
)
nx.draw(
res,
with_labels=True,
pos=nx.drawing.nx_agraph.graphviz_layout(
res, prog='dot'
)
)
For this graph:
The new graph will be constructed:
Note, that all edges from roots in original DAG transformed into roots in new DAG. Also note that for every edge the end of the start node is equal to the start of the end node.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.