FFXX
FFXX

Reputation: 115

convert 0/1 matrix to a 2D grid graph in python

Given a .txt file which contains 0/1 matrix, implement the grid graph in python.I should create a grid graph for that matrix but the problem is that I should create grid in those parts that has 0s and blocks in parts that has 1s. so my txt file contains this:

1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 0 0 0 0 0 0 1 1 0 0 0 0 0 1 1 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 1
0 0 0 0 0 0 0 1 1 0 0 0 0 0 1 1 0 0 0 0 0 1
0 0 0 0 0 0 0 1 1 0 0 0 0 0 1 1 0 0 0 0 0 1
1 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 1 1 0 0 0 0 0 1 1 0 0 0 0 0 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1
1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
1 1 1 1 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1

and I should create the bellow grid according to the above matrix but don't know how:

enter image description here

Upvotes: 3

Views: 1062

Answers (1)

yatu
yatu

Reputation: 88285

We could define a grid graph with nx.grid_2d_graph, and keep only those nodes where the values in the matrix are 0. We could then use the coordinates from the grid graph to position the nodes:

from matplotlib import pyplot as plt
import numpy as np
import networkx as nx

# lines to 2d array
with open('myfile.txt') as f:
    a = np.array([list(map(int,i.split())) for i in f.readlines()])

# define grid graph according to the shape of a
G = nx.grid_2d_graph(*a.shape)

# remove those nodes where the corresponding value is != 0
for val,node in zip(a.ravel(), sorted(G.nodes())):
    if val!=0:
        G.remove_node(node)

plt.figure(figsize=(9,9))
# coordinate rotation
pos = {(x,y):(y,-x) for x,y in G.nodes()}
nx.draw(G, pos=pos, 
        node_color='grey',
        width = 4,
        node_size=400)

enter image description here

Upvotes: 2

Related Questions