Three-dimensional grid of regularly located points

I want to create a list containing three-dimensional grid coordinates at regular intervals, each of which is a 3-element tuple. I am looking for advice on the most effective way to do this.

In C ++, for example, I just iterate over three nested loops, one for each coordinate. In Matlab, I would probably use the meshgrid function (which would do this in one command). I read about meshgrid and mgrid in Python, and I also read that using numpy broadcast rules is more efficient. It seems to me that using a zip function in combination with numpy broadcast rules may be the most efficient way, but zip does not overload in numpy.

+3
source share
5 answers

Use ndindex:

import numpy as np
ind=np.ndindex(3,3,2)
for i in ind:
    print(i)

# (0, 0, 0)
# (0, 0, 1)
# (0, 1, 0)
# (0, 1, 1)
# (0, 2, 0)
# (0, 2, 1)
# (1, 0, 0)
# (1, 0, 1)
# (1, 1, 0)
# (1, 1, 1)
# (1, 2, 0)
# (1, 2, 1)
# (2, 0, 0)
# (2, 0, 1)
# (2, 1, 0)
# (2, 1, 1)
# (2, 2, 0)
# (2, 2, 1)
+3
source

Instead of meshgrid and mgrid you can use ogrid, which is a "rare" version of mgrid. That is, only the size by which the values ​​are changed is filled. The rest are just broadcast. This uses far less memory for large meshes than non-sparse alternatives.

For instance:

>>> import numpy as np
>>> x, y = np.ogrid[-1:2, -2:3]
>>> x
array([[-1],
      [ 0],
      [ 1]])
>>> y
array([[-2, -1,  0,  1,  2]])
>>> x**2 + y**2
array([[5, 2, 1, 2, 5],
      [4, 1, 0, 1, 4],
      [5, 2, 1, 2, 5]])
+3
source

multi-d ( 2) meshgrids, numpy.lib.index_tricks.nd_grid :

import numpy
grid = numpy.lib.index_tricks.nd_grid()
g1 = grid[:3,:3,:3]
g2 = grid[0:1:0.5, 0:1, 0:2]
g3 = grid[0:1:3j, 0:1:2j, 0:2:2j]

g1 [0,1,2] g2 [0,.5], g3 x [0,0,0,5,1,0] (3j, ). documentation .

+1

, meshgrid mgrid, , . , Numpy , meshgrid , .

+1

, ++, :

import numpy, itertools, collections
def grid(xmin, xmax, xstep, ymin, ymax, ystep, zmin, zmax, zstep):
    "return nested tuples of grid-sampled coordinates that include maxima"
    return collections.deque( itertools.product( 
        numpy.arange(xmin, xmax+xstep, xstep).tolist(),
        numpy.arange(ymin, ymax+ystep, ystep).tolist(),
        numpy.arange(zmin, zmax+zstep, zstep).tolist() ) )

( ) a.tolist(), , a.flat deque(), , . , () list() deque() ( , ).

0

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


All Articles