python - 如何将输出的 Fortran 二进制 NxNxN 矩阵读入 Python

标签 python numpy matrix binary fortran

我用Fortran写了一个矩阵如下:

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 中的等效项——大概有一个类似的加载/ reshape 工具可用。如果有更友好的紧凑方式将其写出来供 Python 理解,我愿意接受建议。它可能看起来像this : 。我只是不熟悉我的案例的等效语法。一个好的引用就足够了。谢谢。

最佳答案

使用 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 代码相匹配。感谢您的帮助。

关于python - 如何将输出的 Fortran 二进制 NxNxN 矩阵读入 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13827368/

相关文章:

Python 将 txt 文件读入数字列表列表

python - 连接时保留 Altair slider 与绘图

java - 将矩阵(二维数组)旋转 X.XX°

Java Chess,如何更新棋盘?

python - Django - 如何使变量可用于所有模板?

Python seaborn.distplot 返回计数而不是概率

python - 将 stdint 与 swig 和 numpy.i 一起使用

python - 在 osx 上使用 numpy 的 lapack_lite 进行多处理的段错误,而不是 linux

python - 当 numpy 数组不包含零时运行循环

visual-studio-2008 - 为什么我在 Windows 上安装预编译版本的 LAPACK 时会出错?