Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to read an outputted fortran binary NxNxN matrix into Python

I wrote out a matrix in Fortran as follows:

real(kind=kind(0.0d0)), dimension(256,256,256) :: dense

[...CALCULATION...]

inquire(iolength=reclen)dense
open(unit=8,file=fname,&
form='unformatted',access='direct',recl=reclen)
write(unit=8,rec=1)dense(:,:,:) 
close(unit=8)

I want to read this back into Python. Everything I've seen is for 2D NxN arrays not 3D arrays. In Matlab I can read it as:

fid =    fopen(nfilename,'rb');
mesh_raw = fread(fid,ndim*ndim*ndim,'double');
fclose(fid);
mesh_reshape = reshape(mesh_raw,[ndim ndim ndim]);

I just need the equivalent in Python - presumably there is a similar load/reshape tool available. If there is a more friendly compact way to write it out for Python to understand, I am open to suggestions. It will presumably look something this: . I am just unfamiliar with the equivalent syntax for my case. A good reference would suffice. Thanks.

like image 541
Griff Avatar asked Dec 11 '12 19:12

Griff


1 Answers

Using IRO-bot's link I modified/made this for my script (nothing but numpy magic):

def readslice(inputfilename,ndim):
    shape = (ndim,ndim,ndim)
    fd = open(fname, 'rb')
    data = np.fromfile(file=fd, dtype=np.double).reshape(shape)
    fd.close()
    return data

I did a mean,max,min & sum on the cube and it matches my fortran code. Thanks for your help.

like image 192
Griff Avatar answered Nov 14 '22 20:11

Griff