Get Adjacency matrix from a Shapefile

2k Views Asked by At

I have a folder containing shapefiles about British Power Grid Network. I need to extract an adjacency matrix of this network from tese files. As I have no experience with shapefiles I need a clear explaination of what to do to get such matrix.

By Adjacency Matrix I mean a squared matrix with as many dimensions as the number of the nodes of the Network and that has zeros in cells referring to two nodes that are not connected and has ones in cells referring to two nodes that are connected. I need such Matrix because I want to test an epidemiological system on this Network, which is English National Power Grid.

I tried running this code on Python:

    import networkx as nx
import pickle as serializer
#from osgeo import ogr
#import gdal
#import graphviz as pgv
G=nx.read_shp('NationalGrid-ElecTrans-MT-2012_Nodes.shp')
A = nx.adjacency_matrix(G)
nx.draw(G)
#nx.average_shortest_path_length(G)
#nx.degree(G)
#nx.density(G)
#nx.betweenness_centrality(G)
with open('some_file3.txt', 'w') as f:
    serializer.dump( A, f)

but now I don't know how to use the output, which I am attaching. https://ufile.io/3917f

1

There are 1 best solutions below

9
On

nx.adj_matrix(G) returns SciPy sparse matrix, You probably need DataFrame or array. using nx.convert.to_dict_of_dicts(G):

import pandas as pd
import networkx as nx
G = nx.Graph()
G.add_cycle([1,2,3,4,5])
G.add_cycle([33,3,34,35])
A = pd.DataFrame(nx.convert.to_dict_of_dicts(G)).fillna(0).replace([{}],1)
out: 

    1   2   3   4   5   33  34  35
1   0   1   0   0   1   0   0   0
2   1   0   1   0   0   0   0   0
3   0   1   0   1   0   1   1   0
4   0   0   1   0   1   0   0   0
5   1   0   0   1   0   0   0   0
33  0   0   1   0   0   0   0   1
34  0   0   1   0   0   0   0   1
35  0   0   0   0   0   1   1   0

or better:

A = nx.convert_matrix.to_pandas_dataframe(K)

if you need numpy array you can get values by A.values, and if you need numpy matrix:

A = nx.convert_matrix.to_numpy_matrix(K)