Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is numpy.mgrid, technically?

Tags:

python

numpy

I have been using numpy.mgrid for a while and I am familiar with what it does. But ever since, I have been wondering what it actually is...

A typical use case and syntax for mgrid would be

xx, yy = mgrid[0:5, 0:3]

What bothers me is the syntax mgrid[...], which makes me believe that mgrid is not a function or a method. The docs say that mgrid is a

nd_grid instance which returns a dense multi-dimensional “meshgrid”.

What does it do in the background? And why is it used like a function, but the syntax differs from that of a function (I would expect something like mgrid((0,5), (0,3))). I am really lost at trying to understand what mgrid is.

Any insights are welcome!

like image 582
mommermi Avatar asked Jan 19 '19 19:01

mommermi


1 Answers

numpy.mgrid is an object of the MGridClass in numpy/index_tricks.py. This object allows you to construct multi-dimensional meshgrids, as you already know.

MGridClass extends the nd_grid class, which implements a __getitem__ method. The square braces actually delegates a call to nd_grid.__getitem__, which implements the core logic for constructing the meshgrid based on the slices passed.

A brief MCVE of the working of nd_grid can be found here.

class dummy_1d_grid:
    def __getitem__(self, val):
        print(val)
        return np.arange(val.start, val.stop, val.step, )

mgrid_1d = dummy_1d_grid()
mgrid_1d[:5]

slice(0, 5, None)
# array([0, 1, 2, 3, 4])

np.mgrid[0:5]
# array([0, 1, 2, 3, 4])

Of course, this is all an implementation detail, so the layout and classes are all subject to change. The point to focus on is that it is an instance of a class implementing the __getitem__ method. Hence it is sliced, not called.

like image 146
cs95 Avatar answered Nov 10 '22 00:11

cs95