0

I need to make an adjacency metrics

I have the edges information.

edges = numpy.array([[0,1],[0,3],[1,2],[1,4],[2,5],[3,4],[3,5],[4,5]])

I need a python code to generate the adjacency metrics using NumPy only from the edges information. Can someone help?

1

2 Answers 2

2

It depends what type of adjacency matrix you want, but here's an example with 0 for not connected and 1 for connected, rows are from and columns are to.

import numpy

edges = numpy.array([[0,1],[0,3],[1,2],[1,4],[2,5],[3,4],[3,5],[4,5]])

matrix = numpy.zeros((edges.max()+1, edges.max()+1))
matrix[edges[:,0], edges[:,1]] = 1

gives

array([[0., 1., 0., 1., 0., 0.],
       [0., 0., 1., 0., 1., 0.],
       [0., 0., 0., 0., 0., 1.],
       [0., 0., 0., 0., 1., 1.],
       [0., 0., 0., 0., 0., 1.],
       [0., 0., 0., 0., 0., 0.]])

If you want the connections to be bidirectional (ie. 0->1 also connects 1->0), then add another line of code to do the reverse connection.

import numpy

edges = numpy.array([[0,1],[0,3],[1,2],[1,4],[2,5],[3,4],[3,5],[4,5]])

matrix = numpy.zeros((edges.max()+1, edges.max()+1))
matrix[edges[:,0], edges[:,1]] = 1
matrix[edges[:,1], edges[:,0]] = 1

gives

array([[0., 1., 0., 1., 0., 0.],
       [1., 0., 1., 0., 1., 0.],
       [0., 1., 0., 0., 0., 1.],
       [1., 0., 0., 0., 1., 1.],
       [0., 1., 0., 1., 0., 1.],
       [0., 0., 1., 1., 1., 0.]])
Sign up to request clarification or add additional context in comments.

2 Comments

It has a little issue. Node 1 is connected to node 0 as well and the matrics are showing 0 for that position while it should be 1.
I've updated the answer if you want connections to be bidirectional.
2

The easiest way to get the job done would be using the NetworkX package (if you are allowed to).

In [72]: import networkx as nx

In [73]: edges = [[0, 1], [0, 3], [1, 2], [1, 4], [2, 5], [3, 4], [3, 5], [4, 5]]

In [74]: nodes = sorted(set(node for edge in edges for node in edge))

In [75]: G = nx.Graph()

In [76]: G.add_nodes_from(nodes)

In [77]: G.add_edges_from(edges)

In [78]: A = nx.adjacency_matrix(G)

In [79]: A.toarray()
Out[79]: 
array([[0, 1, 0, 1, 0, 0],
       [1, 0, 1, 0, 1, 0],
       [0, 1, 0, 0, 0, 1],
       [1, 0, 0, 0, 1, 1],
       [0, 1, 0, 1, 0, 1],
       [0, 0, 1, 1, 1, 0]], dtype=int32)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.