2012-12-11 90 views
7

我在Fortran語言寫了一個矩陣如下:如何讀取輸出FORTRAN二進制NxNxN矩陣成Python

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) 

我想讀這回的Python。我見過的所有東西都是2D NxN數組而不是3D數組。在Matlab中,我可以把它讀作:

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

我只需要在Python等效 - 大概有類似的負載/重塑可用的工具。如果有一種更加友好的緊湊方式來寫出來供Python理解,我很樂意提供建議。它可能會看起來像this:。我只是不熟悉我的案例的等效語法。一個很好的參考就足夠了。謝謝。

+0

struct.unpack似乎是要走的路,但我不知道該怎麼辦我的情況。 – Griff

+0

做任何[這些方法使用scipy/numpy](http://www.scipy.org/Cookbook/InputOutput#head-b0de67a6dbb3b1ba2584c65263552dc519225cb1)幫助你? –

+0

你會在這裏找到解決方案:http://stackoverflow.com/questions/10475839/reading-a-direct-access-fortran-unformatted-file-in-python – milancurcic

回答

8

使用IRO-BOT的鏈接我修改/使這個對我的腳本(只是numpy的魔法):

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 

我做了一個平均值,最大值,最小值&總和立方體和它匹配我的fortran代碼。謝謝你的幫助。

+0

只要確保你考慮到陣列維度排序差異Fortran(列專業)和Python(行專業)。 – milancurcic

+0

是不是有一個命令來告訴它在.reshape(shape)結尾處重新排序爲fortran? – Griff

+0

在將Fortran數組聲明爲dimension(im,jm,km)的情況下,您希望從Python讀取它作爲np.fromfile(file = fd,dtype = np.double).reshape((km,jm, IM))。在im = jm = km的情況下,您不需要任何額外的步驟,但請記住最後一個索引變化最快。 – milancurcic

0

我看不到任何東西,只是在這裏工作的直接閱讀。 Python在二維數組方面做得不是很好,更不用說3-d,但是這些代碼應該可以工作。

fin=open('filename.dat','rb') 
output=[] 
for x in range(0,ndim): 
    xarr=[] 
    for y in range(0,ndim): 
     yarr=[] 
     for z in range(0,ndim): 
      yarr.append(struct.unpack('i', fin.read(4))) 
     xarr.append(yarr) 
    output.append(xarr)