Say I make a DiGraph in NetworkX:
import networkx as nx
G = nx.DiGraph()
n = ["A","B","C","D","E","F","H","I","J","K","L","X","Y","Z"]
e = [("A","Z"),("Z","B"),("B","Y"),("Y","C"),("C","G"),("G","H"),("G","I"),("I","J"),("K","J"),("J","L"),("F","E"),("E","D"),("D","X"),("X","C")]
G.add_nodes_from(n)
G.add_edges_from(e)
How would I remove all the nodes with a in-degree and an out-degree equal to 1, so that my graph would look like this?:
import networkx as nx
G = nx.DiGraph()
n = ["A","C","F","G","H","J","K","L"]
e = [("A","C"),("C","G"),("G","H"),("G","J"),("K","J"),("J","L")
G.add_nodes_from(n)
G.add_edges_from(e)
The idea is to remove the "flow-through" nodes and retain connectivity.
The following code does what you want although I don't see where you would get edges from ("A", "C") and ("G", "J") in the final result.
import networkx as nx
def remove_edges(g, in_degree=1, out_degree=1):
g2=g.copy()
d_in=g2.in_degree(g2)
d_out=g2.out_degree(g2)
print(d_in)
print(d_out)
for n in g2.nodes():
if d_in[n]==in_degree and d_out[n] == out_degree:
g2.remove_node(n)
return g2
G_trimmed = remove_edges(G)
G_trimmed.edges()
#outputs [('C', 'G'), ('G', 'H'), ('K', 'J'), ('J', 'L')]
G_trimmed.nodes()
#outputs ['A', 'C', 'G', 'F', 'H', 'K', 'J', 'L']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With