[Numpy-discussion] example reading binary Fortran file

David Froger david.froger.info@gmail....
Fri Jan 30 11:59:02 CST 2009


Thank Sturla and Christopher,

yes, with the Fortran code :

!=========================================
program makeArray

implicit none

integer,parameter:: nx=2,ny=5
real(4),dimension(nx,ny):: ux,uy,p
integer :: i,j

open(11,file='uxuyp.bin',form='unformatted')

do i = 1,nx
do j = 1,ny
   ux(i,j) = 100  + j+(i-1)*10
   uy(i,j) = 200. + j+(i-1)*10
   p (i,j) = 300. + j+(i-1)*10
enddo
enddo

write(11) ux,uy
write(11) p

close(11)

write(*,*) 'ux='
do i = 1,nx
   write(*,*) ( ux(i,j) , j =1,ny)
enddo
write(*,*)

write(*,*) 'uy='
do i = 1,nx
   write(*,*) ( uy(i,j) , j =1,ny)
enddo
write(*,*)

write(*,*) 'p='
do i = 1,nx
   write(*,*) ( p(i,j) , j =1,ny)
enddo
write(*,*)

end program makeArray
!=========================================

the size of the 'uxuyp.bin' file is:

  4bytes + ux_bytes + uy_bytes + 4bytes
+ 4bytes + p_bytes + 4bytes

= 4 + nx*ny*4 + nx*ny*4 + 4 + 4 +nx*ny*4 + 4 =  136 bytes


the arrays are :

 ux=
   101.00000       102.00000       103.00000       104.00000       105.00000
   111.00000       112.00000       113.00000       114.00000       115.00000

 uy=
   201.00000       202.00000       203.00000       204.00000       205.00000
   211.00000       212.00000       213.00000       214.00000       215.00000

 p=
   301.00000       302.00000       303.00000       304.00000       305.00000
   311.00000       312.00000       313.00000       314.00000       315.00000


and with the Python script :

#===============================================
import numpy as np

nx,ny = 2,5

fourBytes = np.fromfile('uxuyp.bin', count=1, dtype=np.float32)
ux = np.fromfile('uxuyp.bin', count=nx*ny,
dtype=np.float32).reshape((nx,ny), order='F')

print ux
#===============================================

I get :

[[  1.12103877e-43   1.11000000e+02   1.12000000e+02   1.13000000e+02
    1.14000000e+02]
 [  1.01000000e+02   1.02000000e+02   1.03000000e+02   1.04000000e+02
    1.05000000e+02]]


this function do the trick, but is it optimized?

#===============================================
def lread(f,fourBeginning,fourEnd,*tuple):
    from struct import unpack
    """Reading a Fortran binary file in litte-endian"""

    if fourBeginning: f.seek(4,1)
    for array in tuple:
        for elt in xrange(array.size):
            transpose(array).flat[elt] =
unpack(array.dtype.char,f.read(array.itemsize))[0]
    if fourEnd: f.seek(4,1)
#===============================================
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://projects.scipy.org/pipermail/numpy-discussion/attachments/20090130/9f0babaf/attachment.html 


More information about the Numpy-discussion mailing list