1

I would like to read a netcdf file using python. This file contain a netcdf variable in the double format.

I know that this quantity should be complex and I know that the last argument is always 2 numbers (real and im).

I would like to read the nedcdf variable IN AN EFFICIENT WAY and allocate it to a complex python/numpy variable.

For the moment I have the following INEFFICIENT program that work:

import numpy as N
self.EIG2D = N.zeros((self.nkpt,self.nband,3,self.natom,3,self.natom),dtype=complex)
EIG2Dtmp = root.variables['second_derivative_eigenenergies'][:,:,:,:,:,:,:] #number_of_atoms, 
                                   # number_of_cartesian_directions, number_of_atoms, number_of_cartesian_directions,
                                   # number_of_kpoints, product_mband_nsppol, cplex
for ikpt in N.arange(nkpt):
  for iband in N.arange(nband):
    for icart in N.arange(3):
      for iatom in N.arange(natom):
        for jcart in N.arange(0,3):
          for jatom in N.arange(natom):
            self.EIG2D[ikpt,iband,icart,iatom,jcart,jatom] = complex(EIG2Dtmp[iatom,icart,jatom,jcart,ikpt,iband,0],\
                                                                     EIG2Dtmp[iatom,icart,jatom,jcart,ikpt,iband,1])

How to make this more efficient ?

Thank you in advance,

Samuel.

6
  • Look into the netCDF4-python module. Are you looping over every index of the EIG2Dtmp array? If so, you can just do self.EIG2D = root.variables[:] rather than looping through everything. Commented May 29, 2014 at 14:59
  • I'm not. There are 7 arguments to EIG2Dtmp and 6 to self.EIG2D. The missing one beeing simply the real and im part. Commented May 29, 2014 at 15:04
  • 2
    I see. The accepted answer to this question seems to be exactly what you need. Commented May 29, 2014 at 17:31
  • It is worth looking at the rest of the answers to that question. Depending on the array ordering, a simple "complex view" on the same array may suffice, as described in another answer (I unfortunately do not know how to link to a specific answer) Commented May 29, 2014 at 18:33
  • @Spencer Hill: It seems to work: numpy.vectorize(complex)(Data[...,0], Data[...,1]). The only issue for me is that I also need to change the ordering A[a,b,c] ==> A[c,b,a] but I should probably made a new thread for that I guess. Thanks a lot ! Commented May 29, 2014 at 21:18

1 Answer 1

2

Thanks to Spencer Hill, the solution for me was

self.EIG2D = numpy.vectorize(complex)(EIG2Dtmp[...,0], EIG2Dtmp[...,1])

You can also refer to Numpy: Creating a complex array from 2 real ones?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.