Skip to content

Instantly share code, notes, and snippets.

@tahsinkose
Last active June 22, 2019 15:51
Show Gist options
  • Save tahsinkose/f40ab039687f8db26702322bc2fb304f to your computer and use it in GitHub Desktop.
Save tahsinkose/f40ab039687f8db26702322bc2fb304f to your computer and use it in GitHub Desktop.
Python script that creates the product graph, which consists of pairs of identically labeled nodes and edges from G1 and G2.
import networkx as nx
import matplotlib.pyplot as plt
"""
Implements Product Graph operator proposed in https://sites.cs.ucsb.edu/~xyan/tutorial/GraphKernels.pdf.
"""
def product_graph(G1,G2):
G = nx.lexicographic_product(G1,G2)
PG = nx.Graph()
for n in G.nodes():
if n[0] == n[1]:
PG.add_node(n)
for e in G.edges.data('weight', default=0):
v1 = e[0][0]
w1 = e[0][1]
v2 = e[1][0]
w2 = e[1][1]
label = e[2]
if v1==w1 and v2==v2 and G1.get_edge_data(v1,v2,default=0) and G2.get_edge_data(w1,w2,default=0) and \
G1.get_edge_data(v1,v2,default=0) == G2.get_edge_data(w1,w2,default=0):
PG.add_edge((v1,w1),(v2,w2),weight=label)
return PG
if __name__=='__main__':
G1=nx.Graph()
G2=nx.Graph()
G1.add_nodes_from([('a'),'b','c'])
G1.add_weighted_edges_from([('a','b',1),('b','c',2),('a','c',3)])
G2.add_nodes_from(['a','b','c','d'])
G2.add_weighted_edges_from([('a','b',1),('b','c',2),('c','d',3),('a','d',4)])
PG = product_graph(G1,G2)
nx.draw(PG,with_labels=True)
labels = nx.get_edge_attributes(PG,'weight')
pos=nx.spring_layout(PG)
nx.draw_networkx_edge_labels(PG,pos,edge_labels=labels)
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment