如何读取输出FORTRAN二进制NxNxN矩阵到Python [英] how to read an outputted fortran binary NxNxN matrix into Python
问题描述
我在Fortran语言写了一个矩阵如下:
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)
我要读这回的Python。我所看到的一切是N×N的二维数组不是三维数组。在Matlab中,我可以把它读作:
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]);
我只需要在Python等效 - presumably有一个类似的负载/重塑可用的工具。如果写出来的Python了解更友好简洁的方式,我很开放的建议。它将presumably看起来<一个href=\"http://stackoverflow.com/questions/13728591/simple-reading-of-fortran-binary-data-not-so-simple-in-python\">this: 。我只是用我的情况相当于语法陌生。一个很好的参考就足够了。谢谢你。
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.
推荐答案
使用IRO-机器人的链接我修改/使这个对我的脚本(只是numpy的魔法):
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
我做了一个平均值,最大值,最小值和放大器;综上所述立方体,它FORTRAN我的code相匹配。感谢您的帮助。
I did a mean,max,min & sum on the cube and it matches my fortran code. Thanks for your help.
这篇关于如何读取输出FORTRAN二进制NxNxN矩阵到Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!