After creating nodes in NetworkX, I would like add edges between nodes if both nodes have (at least) one overlapping same attribute. It seems to be a problem that not all nodes contain the same number of attributes - could this be the case, and if so, how should I solve it?
import networkx as nx
from itertools import product
# Mothernodes
M = [('E_%d' % h, {'a': i, 'b': j, 'c': k, 'd': l})
for h, (i, j, k, l) in enumerate(product(range(2), repeat=4), start=1)]
# children nodes
a = [ ( 'a_%d' % i, {'a' : i}) for i in range(0,2) ]
b = [ ( 'b_%d' % i, {'b' : i}) for i in range(0,2) ]
c = [ ( 'c_%d' % i, {'c' : i}) for i in range(0,2) ]
d = [ ( 'd_%d' % i, {'d' : i}) for i in range(0,2) ]
# graph containing both
M_c = nx.Graph()
M_c.add_nodes_from(M)
ls_children = [a, b, c , d]
for ls_c in ls_children:
M_c.add_nodes_from(ls_c)
list(M_c.nodes(data=True))[0:20]
[('E_9', {'a': 1, 'b': 0, 'c': 0, 'd': 0}),
('d_0', {'d': 0}),
('E_10', {'a': 1, 'b': 0, 'c': 0, 'd': 1}),
('b_0', {'b': 0}),
('E_2', {'a': 0, 'b': 0, 'c': 0, 'd': 1}),
('E_1', {'a': 0, 'b': 0, 'c': 0, 'd': 0}),
('c_1', {'c': 1}),
...
]
# attempting to add edges if one attribute is overlapping/the same:
for start in M_c.nodes(data=True):
for end in M_c.nodes(data=True):
for attr in list(start[1].keys()):
if start[1][attr] == end[1][attr]:
M_c.add_edge(start[0] ,end[0] )
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-4-22b88809e853> in <module>()
2 for end in M_c.nodes(data=True):
3 for attr in list(start[1].keys()):
----> 4 if start[1][attr] == end[1][attr]:
5 M_c.add_edge(start[0] ,end[0] )
KeyError: 'b'
EDIT2:
I have now tried to test both start and end for existence of attributes, but I still get an error:
for start in M_c.nodes(data=True):
for end in M_c.nodes(data=True):
for attr in list(start[1].keys()):
if start[1][attr]:
if end[1][attr]:
if start[1][attr] == end[1][attr]:
M_c.add_edge(start[0], end[0] )
# Adding an else and continue statement does not affect the error,
# even adding three of them, for each if statement
# else:
# continue
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-5-32ae2a6095e5> in <module>()
3 for attr in list(start[1].keys()):
4 if start[1][attr]:
----> 5 if end[1][attr]:
6 if start[1][attr] == end[1][attr]:
7 M_c.add_edge(start[0], end[0] )
KeyError: 'a'
Creating edges between nodes sharing the same attribute value
[out:]
Creating edges
Plotting the network