[Numpy-discussion] I,J,K Coordinates from Cell ID
Fri Feb 29 01:34:11 CST 2008
On Fri, Feb 29, 2008 at 12:16 AM, Timothy Hochberg wrote:
> On Thu, Feb 28, 2008 at 1:47 PM, Andrea Gavana <email@example.com>
> > Hi All,
> > I have some problems in figuring out a solution for an issue I am
> > trying to solve. I have a 3D grid of dimension Nx, Ny, Nz; for every
> > cell of this grid, I calculate the cell centroids (with the cell
> > coordinates x, y, and z) and then I try to find which cell centroid is
> > the closest to a specified point in 3D (which I supply). I still
> > haven't figured out how to do this, even if I have some ideas (and
> > suggestions for this problem are welcome :-D ). But the problem is
> > another one.
> > When I find the closest centroid, I know only the cell ID of this
> > centroid. The cell ID is (usually) defined as:
> > ID = (K-1)*Nx*Ny + (J-1)*Nx + I - 1
> > Where I, J, K are the cell indexes. Now, the problem is, how can I
> > calculate back the I, J, K indexes knowing only the cell ID? I am
> > trying to solve this using numpy (as my grid is stored using a numpy
> > array), but it's something akin to the Matlab function ind2sub...
> > Thank you for your suggestions.
> I think you are going to want to use mod (aka '%'). Something like:
> >>> def coord(id):
> ... return (id % NX + 1, id // NX % NY + 1, id // (NX*NY) + 1 )
> should work. I believe there are a few things you could do to improve the
> efficiency here, but try this and see if it works for you before you worry
> about that.
Thank you for the suggestion. I was so concentrated on another kind of
solution that I didn't even think about your approach, which is far
more elegant than mine.
> Note that the above definition for cell ID is probably a little weird in the
> context of numpy where all of the indexing starts at zero.
Yep, but actually this is perfect for my case as I have to input those
numbers in a reservoir simulator where all of the indexing starts at 1
:-D . It's perfect.
Thank you very much.
"Imagination Is The Only Weapon In The War Against Reality."
More information about the Numpy-discussion