Returns a NumPy matrix using attributes from G.
If only is passed in, then the adjacency matrix is constructed.
Let A be a discrete set of values for the node attribute . Then the elements of A represent the rows and columns of the constructed matrix. Now, iterate through every edge e=(u,v) in and consider the value of the edge attribute . If ua and va are the values of the node attribute for u and v, respectively, then the value of the edge attribute is added to the matrix element at (ua, va).
Parameters : | G : graph
edge_attr : str, optional
node_attr : str, optional
normalized : bool, optional
rc_order : list, optional
|
---|---|
Returns : | M : NumPy matrix
ordering : list
|
Other Parameters: | |
dtype : NumPy data-type, optional
order : {‘C’, ‘F’}, optional
|
Examples
Construct an adjacency matrix:
>>> G = nx.Graph()
>>> G.add_edge(0,1,thickness=1,weight=3)
>>> G.add_edge(0,2,thickness=2)
>>> G.add_edge(1,2,thickness=3)
>>> nx.attr_matrix(G, rc_order=[0,1,2])
matrix([[ 0., 1., 1.],
[ 1., 0., 1.],
[ 1., 1., 0.]])
Alternatively, we can obtain the matrix describing edge thickness.
>>> nx.attr_matrix(G, edge_attr='thickness', rc_order=[0,1,2])
matrix([[ 0., 1., 2.],
[ 1., 0., 3.],
[ 2., 3., 0.]])
We can also color the nodes and ask for the probability distribution over all edges (u,v) describing:
Pr(v has color Y | u has color X)
>>> G.node[0]['color'] = 'red'
>>> G.node[1]['color'] = 'red'
>>> G.node[2]['color'] = 'blue'
>>> rc = ['red', 'blue']
>>> nx.attr_matrix(G, node_attr='color', normalized=True, rc_order=rc)
matrix([[ 0.33333333, 0.66666667],
[ 1. , 0. ]])
For example, the above tells us that for all edges (u,v):
Pr( v is red | u is red) = 1/3 Pr( v is blue | u is red) = 2/3
Pr( v is red | u is blue) = 1 Pr( v is blue | u is blue) = 0
Finally, we can obtain the total weights listed by the node colors.
>>> nx.attr_matrix(G, edge_attr='weight', node_attr='color', rc_order=rc)
matrix([[ 3., 2.],
[ 2., 0.]])
Thus, the total weight over all edges (u,v) with u and v having colors:
(red, red) is 3 # the sole contribution is from edge (0,1) (red, blue) is 2 # contributions from edges (0,2) and (1,2) (blue, red) is 2 # same as (red, blue) since graph is undirected (blue, blue) is 0 # there are no edges with blue endpoints