Objectif : I have a graph,for each node having degree two, i would like to remove that node and add an edge between the neighbors of that node (weight = a*b/a+b , with a and b are weights of the adjacent edges to the node in question).I want to do those operations every time the graph changes,to eventually have a graph without any node with dgree 2 . here is my code attached. PS:I'm very new to python(3.4.0),NetworkX 2.2 (Any other suggestion to give similar result is appreciated)
import networkx as nx
import matplotlib.pyplot as plt
G=nx.MultiGraph()
G.add_nodes_from([1,2,3,4,5,6,7])
G.add_edges_from([(1,2),(1,3),(2,4),(2,5),(3,6),(6,7)])
for u, v, d in G.edges(data=True):
d['weight'] = 1
def fun(G) :
L= G.degree() # L=list of all nodes of a random graph G ,and their nodes [(node, degree),(node,degree)...]
for x in L :
if x[1] == 2 : #if a certain node in L has a degree 2
adja=G.edges(x[0],data=True) #adjacent edges to the node of degree 2
weights = [d['weight'] for u,v,weight in adja] #weights=list of weights of the adjacent edges to the node x[0](the one having degree 2)
numerator=weights[0]*weights[1]
denominator=sum(weights)
var=numerator/denominator #var is the weight i would like to assign to my new edge created,it is computed like : a*b /(a+b) with a and b are weights of the adjacent edges to the node in question
tmp=list(G.neighbors(x[0])) #tmp = list of neighbors of the node to remove(neighbors in term of nodes)
G.remove_node(x[0]) #remove the node of degree 2
G.add_edge(tmp[0],tmp[1],weight=var) #add an edge between the neighbors of the node of degree 2
nx.draw(G,with_labels=True)
plt.show()
print(fun(G))