CF84 - 6 months ago 32

Python Question

Having created a grid network like this:

`from __future__ import division`

import networkx as nx

from pylab import *

import matplotlib.pyplot as plt

%pylab inline

ncols=10

N=10 #Nodes per side

G=nx.grid_2d_graph(N,N)

labels = dict( ((i,j), i + (N-1-j) * N ) for i, j in G.nodes() )

nx.relabel_nodes(G,labels,False)

inds=labels.keys()

vals=labels.values()

inds=[(N-j-1,N-i-1) for i,j in inds]

pos2=dict(zip(vals,inds))

And having assigned each edge a weight corresponding to its length (in this trivial case, all lenghts=1):

`#Weights`

from math import sqrt

weights = dict()

for source, target in G.edges():

x1, y1 = pos2[source]

x2, y2 = pos2[target]

weights[(source, target)] = round((math.sqrt((x2-x1)**2 + (y2-y1)**2)),3)

for e in G.edges():

G[e[0]][e[1]] = weights[e] #Assigning weights to G.edges()

This is what my

`G.edges()`

`[(0, 1, 1.0),`

(0, 10, 1.0),

(1, 11, 1.0),

(1, 2, 1.0),... ] #Trivial case: all weights are unitary

How can I create an incidence matrix that takes into account the weights that have just been defined? I want to use

`nx.incidence_matrix(G, nodelist=None, edgelist=None, oriented=False, weight=None)`

`weight`

The docs say that

`weight`

Any ideas?

Answer

Here is a simple example showing how to properly set edge attributes and how to generate a weighted incidence matrix.

```
import networkx as nx
from math import sqrt
G = nx.grid_2d_graph(3,3)
for s, t in G.edges():
x1, y1 = s
x2, y2 = t
G[s][t]['weight']=sqrt((x2-x1)**2 + (y2-y1)**2)*42
print(nx.incidence_matrix(G,weight='weight').todense())
```

OUTPUT

```
[[ 42. 42. 42. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[ 0. 0. 0. 42. 42. 42. 0. 0. 0. 0. 0. 0.]
[ 42. 0. 0. 0. 0. 0. 42. 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0. 0. 0. 42. 42. 42. 0. 0.]
[ 0. 42. 0. 42. 0. 0. 0. 0. 42. 0. 42. 0.]
[ 0. 0. 0. 0. 0. 0. 0. 42. 0. 0. 0. 42.]
[ 0. 0. 0. 0. 0. 42. 0. 0. 0. 42. 0. 0.]
[ 0. 0. 0. 0. 0. 0. 42. 0. 0. 0. 42. 42.]
[ 0. 0. 42. 0. 42. 0. 0. 0. 0. 0. 0. 0.]]
```

If you want a particular ordering of the nodes and edges in the matrix use the nodelist= and edgelist= optional parameters to networkx.indicence_matrix().