Generate, populate, and build a hexagonal grid in Python

I would like to modify my square lattice Python script (this is an agent model for biology) to work in a hexagonal universe.

This is how I create and initialize a 2D matrix in a square model: basically, N is the size of the lattice, and R is the radius of the part of the matrix where I need to change the value at the beginning of the algorithm

a = np.zeros(shape=(N,N)) center = N/2 for i in xrange(N): for j in xrange(N): if( ( pow((i-center),2) + pow((j-center),2) ) < pow(R,2) ): a[i,j] = 1 

Then I let the matrix evolve according to certains rules and finally print through the creation of a pickle file:

 name = "{0}-{1}-{2}-{3}-{4}.pickle".format(R, A1, A2, B1, B2) pickle.dump(a, open(name,"w")) 

Now I would like to do the same, but on a hexagonal grid. I read this interesting StackOverflow question, which clarified how to represent positions on a hexagonal grid with three coordinates, but several things remain unclear as far as I know, i.e.

(a) how should I deal with three axes in Python, believing that what I want is not equivalent to a three-dimensional matrix due to restrictions on coordinates and

(b) how to do it?

Regarding (a), this is what I tried to do:

 a = np.zeros(shape=(N,N,N)) for i in xrange(N/2-R, N/2+R+1): for j in xrange(N/2-R, N/2+R+1): for k in xrange(N/2-R, N/2+R+1): if((abs(i)+abs(j)+abs(k))/2 <= 3*N/4+R/2): a[i,j,k] = 1 

I find it rather confusing to initialize such an NxNxN matrix, and then find a way to print a subset of it in accordance with the restrictions on the coordinates. I am looking for an easier way and, more importantly, to understand how to build a hexagonal lattice obtained as a result of the algorithm (I don’t know, at the moment I haven’t tried anything).

+5
source share
1 answer

I agree that trying to curb the hexagonal grid into a cube is problematic. My suggestion is to use a common scheme - to represent neighboring sites in a graph. This works very well with the pythons dictionary object, and it is trivial to implement the "axial coordinate scheme" in one of the links that you specified. Here is an example that creates and draws a grid using networkx.

 import networkx as nx G = nx.Graph(directed=False) G.add_node((0,0)) for n in xrange(4): for (q,r) in G.nodes(): G.add_edge((q,r),(q,r-1)) G.add_edge((q,r),(q-1,r)) G.add_edge((q,r),(q-1,r+1)) G.add_edge((q,r),(q,r+1)) G.add_edge((q,r),(q+1,r-1)) G.add_edge((q,r),(q+1,r)) pos = nx.graphviz_layout(G,prog="neato") nx.draw(G,pos,alpha=.75) import pylab as plt plt.axis('equal') plt.show() 

enter image description here

This is not the most optimal implementation, but it can generate arbitrarily large lattices:

enter image description here

+3
source

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


All Articles