[Numpy-discussion] populating an array

2009-03-02 Thread Brennan Williams
Ok... I'm using Traits and numpy.
I have a 3D grid with directions I,J and K.
I have NI,NJ,NK cells in the I,J,K directions so I have NI*NJ*NK cells 
overall.
I have data arrays with a value for each cell in the grid.
I'm going to store this as a 1D array, i.e. 1ncells where 
ncells=NI*NJ*NK rather than as a 3D array
Apart from lots of other data arrays that will be read in from external 
files, I want to create I, J and K data arrays
where the 'I' array contains the I index for the cell, the 'J' array the 
J index etc.

I haven't used numpy extensively and I'm coming from a Fortran/C 
background so I'm hideously inefficient.
At the moment I have something like

  self.iarray=zeros(self.ncells,dtype=int)
  for icell in arange(1,self.ncells+2):
#icell=i+(j-1)*ni+(k-1)*ni*nj
i,j,k=rn2ijk(icell,self.ni,self.nj)
self.yarray[icell]=i


rn2ijk is defined as...

def rn2ijk(n,ni,nj):
nij=ni*nj
k=(n+nij-1)/nij
ij=n-(k-1)*nij
j=(ij+ni-1)/ni
i=ij-(j-1)*ni
return i,j,k

Obviously I can improve my use of rn2ijk as for a start I'm 
recalculating nij  for every cell (and I can have anything from a few 
thousand to a few million cells).

But I'm sure I could do this more efficiently by probably starting off 
with a 3d array, looping over i,j,k and then reshaping it into a 1d array.

Ideas?

Brennan


___
Numpy-discussion mailing list
Numpy-discussion@scipy.org
http://projects.scipy.org/mailman/listinfo/numpy-discussion


Re: [Numpy-discussion] populating an array

2009-03-02 Thread Robert Kern
On Mon, Mar 2, 2009 at 05:08, Brennan Williams
brennan.willi...@visualreservoir.com wrote:
 Ok... I'm using Traits and numpy.
 I have a 3D grid with directions I,J and K.
 I have NI,NJ,NK cells in the I,J,K directions so I have NI*NJ*NK cells
 overall.
 I have data arrays with a value for each cell in the grid.
 I'm going to store this as a 1D array, i.e. 1ncells where
 ncells=NI*NJ*NK rather than as a 3D array
 Apart from lots of other data arrays that will be read in from external
 files, I want to create I, J and K data arrays
 where the 'I' array contains the I index for the cell, the 'J' array the
 J index etc.

I, J, K = numpy.mgrid[0:self.ni, 0:self.nj, 0:self.nk]
self.iarray = I.ravel()
self.jarray = J.ravel()
self.karray = K.ravel()

-- 
Robert Kern

I have come to believe that the whole world is an enigma, a harmless
enigma that is made terrible by our own mad attempt to interpret it as
though it had an underlying truth.
  -- Umberto Eco
___
Numpy-discussion mailing list
Numpy-discussion@scipy.org
http://projects.scipy.org/mailman/listinfo/numpy-discussion