Accumulate "neigborhood" values ​​from edgelist with numpy

I have a non-oriented network, where each node can be one of the types k . For each node, I need to calculate the number of neighbors that the node I have for each type.

I now represent edges using edgelist, where the columns are node indices. Nodes are represented as an nxk matrix , where each column represents a node type. If a node is of type k, then the value of the kth column is 1, 0.

Here is my current code, which is correct but too slow.

# example nodes and edges, both typically much longer
nodes = np.array([[0, 0, 1], 
                  [0, 1, 0],                       
                  [1, 0, 0]])
edges = np.array([[0, 1],
                  [1, 2]])

neighbors = np.zeros_like(nodes)

for i, j in edges:
   neighbors[i] += nodes[j]
   neighbors[j] += nodes[i]

Is there any clever numpy that would allow me to avoid this loop? If the best way to do this is with an adjacency matrix, this is also acceptable.

+4
2

np.add.at -

out = np.zeros_like(nodes)
np.add.at(out, edges[:,0],nodes[edges[:,1]])
np.add.at(out, edges[:,1],nodes[edges[:,0]])
+1

, numpy_indexed ( : ) :

# generate a random example graph
n_edges = 50
n_nodes = 10
n_types = 3
edges = np.random.randint(0, n_nodes, size=(n_edges, 2))
node_types = np.random.randint(0, 2, size=(n_nodes, n_types)).astype(np.bool)

# Note; this is for a directed graph
s, e = edges.T
# for undirected, add reversed edges
s, e = np.concatenate([edges, edges[:,::-1]], axis=0).T
import numpy_indexed as npi
node_idx, neighbor_type_count = npi.group_by(s).sum(node_types[e])

, .

+2

Source: https://habr.com/ru/post/1656418/


All Articles