[Numpy-discussion] mgrid, ogrid and back again

Andrew Jaffe a.h.jaffe at bakerjaffe.plus.com
Mon Jul 24 09:04:05 CDT 2006

Hi All,

I'm finding myself dealing with n-dimensional grids quite a lot, and 
trying to do some 'tricky' index manipulation. The main problem is 
manipulating arrays when I don't know a priori the number of dimensions; 
in essence I need to be able to iterate across dimensions.

first, I've got three arrays of lower-bounds (param_min), upper-bounds 
(param_max) and numbers of steps (nstep). I'm using the following 
incantations to produce the association mgrid an ogrid arrays:

     args = tuple(slice(p1, p2, n*1j)
                  for p1,p2,n in zip(param_min, param_max, nstep))
     param_grid = N.mgrid.__getitem__(args)

Is this the easiest way to do this?

Second, from the mgrid object, param_grid, I want to recover the step 
sizes (assume I've thrown away the args so I can't make an ogrid 
object). This seems to work:

     deltas = numpy.empty(npar)
     for i in xrange(npar):
         idxtup = (i,)+(0,)*i + (1,) + (0,)*(npar-1-i)
         deltas[i] = param_grid[idxtup] - param_grid[((i,)+(0,)*npar )]

(Or I could compress this into a single somewhat complicated list 
comprehension). Again, this seems a bit overly complicated. Any ideas 
for simplifying it?

But at least I can work out how to do these things.

Finally, however, I need to reconstruct the individual 
param_min:param_max:(nstep*1j) 1-d arrays (i.e., the flattened versions 
of the ogrid output). These are effectively param_grid[i,0,,,,:,,,,] 
where ':' is in slot i. But I don't know how to emulate ':' in either a 
slice object or tuple-indexing notation. Obviously I could just do a 
more complicated version of the deltas[] calculation, or direct 
manipulation on param_grid.flat, but both seem like too much work on my 

Thanks in advance!


p.s. thanks to travis for all his hard work, especially in the run-up to 
1.0b (although test() crashes on my PPC Mac... more on that later when 
I've had time to play).

More information about the Numpy-discussion mailing list