我正在嘗試讀取流數據並將數據分發到網格文件中以獲得最終繪圖。我有一個用於處理的MATLAB代碼,並且它可以成功運行。我需要將這些代碼轉換爲Python,但我是初學者。調試時總是崩潰,任何人都可以告訴我我做錯了什麼?提前致謝!讀取二進制數據並在網格文件中分發數據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)
歡迎使用堆棧溢出。目前我認爲不可能回答這個問題,因爲你沒有提供你正在閱讀的文件結構的例子 - 你能否以某種方式提供摘錄? Python代碼中的分號讓我覺得你在這些點上掙扎(它們不是必需的,所以我認爲它們來自Matlab)並且它似乎比它需要的更加冗長 – roganjosh
@roganjosh非常感謝! MATLAB對於工程人員來說是一個方便的工具。但我必須爲特定項目運行Python腳本。 – Max
歡迎來到Stack Overflow。退房[mcve],下載一個100 MB的文件並不理想,除非真的無法避免。 – roadrunner66