15 Jun 2022
Preserve and Add Edge & Node Level Attributes in Networkx Diagraph
If you are looking for a way to add the node and edge level attribute to contain basic data properties to use it while processing and developing the graph algorithms. This piece of code is for you. Find below the python code that elaborated how to add node and edge level attributes.
import networkx as nx
G = nx.DiGraph()
#sample json keys are labels and list contains sequences
data = {'1': ['B', 'D'],
'2': ['B', 'D', 'E'],
'3': ['A', 'F'],
'4': ['B'],
'5': ['B', 'D', 'C'],
'6': ['C', 'E']}
#iterate through the graph
for lst, key in enumerate(data.keys()):
prev = "STR"
for item in data[key]:
#maintain frequencies of occurrence of a node in data
if item not in G.nodes():
G.add_node(item)
G.nodes[item]['frequency']=1
else:
G.nodes[item]['frequency']+=1
#maintain labels of termopral co-occurrence in data
if not G.has_edge(prev, item):
G.add_edge(prev, item)
G.edges[prev, item]['labels'] =[key]
else:
G.edges[prev, item]['labels'].append(key)
prev = item
Since you have already constructed a graph from your sample data. The next step is how to retrieve that information.
#trace where node B->D co-occurred
In [1]: G['B']['D']['labels']
Out[1]: ['1', '2', '5']
#get node frequency
In [2]: G.nodes['B']['frequency']
Out[2]: 4
Now you can preserve the graph with it properties by simply writing it into Generalized Markup Language (GML).
#write graph in gml format
In [3]: nx.write_gml(G, "graph.gml")
#OR write it in compressed format
nx.write_gml(G, "graph.gml.gz")
#Output: GML file
graph [
directed 1
node [
id 0
label "B"
labels 4
]
node [
id 1
label "STR"
]
node [
id 2
label "D"
labels 3
]
node [
id 3
label "E"
labels 2
]
node [
id 4
label "A"
labels 1
]
node [
id 5
label "F"
labels 1
]
node [
id 6
label "C"
labels 2
]
edge [
source 0
target 2
weight "1"
weight "2"
weight "5"
]
edge [
source 1
target 0
weight "1"
weight "2"
weight "4"
weight "5"
]
edge [
source 1
target 4
weight "3"
]
edge [
source 1
target 6
weight "6"
]
edge [
source 2
target 3
weight "2"
]
edge [
source 2
target 6
weight "5"
]
edge [
source 4
target 5
weight "3"
]
edge [
source 6
target 3
weight "6"
]
]
You can also read the GML file to restore the graph contents.
In [4]: H = nx.read_gml("graph.gml")
In [5]: H.nodes['B']['labels']
Out[5]: 4
In [6]: H['B']['D']['weight']
Out[6]: ['1', '2', '5']
You can download the full code from here