【发布时间】:2016-08-09 11:01:36
【问题描述】:
我正在尝试读取流量数据并将数据分发到最终绘图的网格文件中。我有一个用于处理的 MATLAB 代码,它可以成功运行。我需要将此代码转移到 Python 中,但我是初学者。调试时总是崩溃,谁能告诉我我做错了什么?提前致谢!
数据文件(共约100mb):
https://www.dropbox.com/sh/3gtsmatq56pm0gc/AADUnNLjdrELjvdUy4wtDiiBa?dl=0
MATLAB 代码
%% Read Grid grid file is used as a guide for the positon where data is put
fid = fopen('FLOW_phys_GRID_1.xyz', 'r');
a = fread(fid, 3, 'int');
Nx = a(1); % number of points in x direction
Ny = a(2); % number of points in y direction
Nz = a(3); % numebr of points in z direction
xx = fread(fid, Nx*Ny*Nz, 'float');
yy = fread(fid, Nx*Ny*Nz, 'float');
xx = reshape(xx, [Nx, Ny]);
yy = reshape(yy, [Nx, Ny]);
fclose(fid);
x = squeeze(xx(:,1));
y = squeeze(yy(1,:));
%% Read Data
fid = fopen('FLOW_phys.raw', 'r'); %flow data in binary format
a = fread(fid, 3, 'int');
Nx = a(1); % number of points in x direction
Ny = a(2); % number of points in y direction
Nz = a(3); % number of points in z direction
Ma = fread(fid, 1, 'float');
some_num = fread(fid, 1, 'float');
Re = fread(fid, 1, 'float');
time = fread(fid, 1, 'float');
xx1 = fread(fid, 2*Nx*Ny*Nz, 'float');
xx1 = reshape(xx1, [Nx, 2*Ny, Nz]);
fclose(fid);
[XX, YY] = meshgrid(x, y);
% plot (squeeze(xx1(2,:,1)));
h = pcolor(XX, YY, squeeze(xx1)');
set(h, 'EdgeColor', 'none');
colorbar
Python 代码:
import struct
import numpy
import matplotlib
unpackformat_int = '<i'
unpackformat_flo = '<f'
fid = open('FLOW_phys_GRID_1.xyz', 'r+')
Nx = struct.unpack(unpackformat_int,fid.read(4))[0]
Ny = struct.unpack(unpackformat_int,fid.read(4))[0]
Nz = struct.unpack(unpackformat_int,fid.read(4))[0]
aa = Nx*Ny*Nz
xx = struct.unpack('i'*aa, fid.read(aa*4))[0]
yy = struct.unpack('i'*aa, fid.read(aa*4))[0]
xx = xx.reshape([Nx, Ny])
yy = yy.reshape([Nx, Ny])
fid.close()
fid = open('FLOW_phys.raw', 'r+')
Nx = struct.unpack(unpackformat_int,fid.read(4))[0]
Ny = struct.unpack(unpackformat_int,fid.read(4))[0]
Nz = struct.unpack(unpackformat_int,fid.read(4))[0]
Ma = struct.unpack(unpackformat_flo, fid.read(4))[0]
some = struct.unpack(unpackformat_flo, fid.read(4))[0]
Re = struct.unpack(unpackformat_flo, fid.read(4))[0]
time = struct.unpack(unpackformat_flo, fid.read(4))[0]
bb = Nx*Ny*Nz
xx1 = struct.unpack('f'*bb, fid.read(bb*4))[0]
xx2 = struct.unpack('f'*bb, fid.read(bb*4))[0]
xx1 = xx1.reshape([Nx, Ny, Nz])
xx2 = xx2.reshape ([Nx, Ny, Nz])
fid.close()
[XX, YY] = numpy.meshgrid(xx, yy)
matplotlib.plot(XX,YY,xx2)
【问题讨论】:
-
欢迎来到 Stack Overflow。目前我认为不可能回答这个问题,因为你没有提供你正在阅读的文件结构的例子——你能以某种方式提供一个摘录吗? Python 代码中的分号让我觉得你在这些方面很挣扎(它们不是必需的,所以我认为它们来自 Matlab)而且它似乎也比它需要的更冗长
-
@roganjosh 提前非常感谢! MATLAB 是一种方便的工程工具。但我必须为特定项目运行 Python 脚本。
-
欢迎来到 Stack Overflow。看看minimal reproducible example,下载一个100MB的文件并不理想,除非真的无法避免。
-
@roganjosh 以我使用 Python 的方式编写它很难还是我做错了什么?无论如何感谢您的帮助。
-
@roadrunner66 感谢您的评论。其实我不认为下载是必要的。由于代码是从 MATLAB 转过来的,由于 MATLAB 和 Python 之间的命令不同,似乎出现了一些结构错误。
标签: python matlab numpy matplotlib binary