我正在從文本文件中讀取磁場數(shù)據(jù)。我的目標是正確有效地加載網(wǎng)格點(3 維)和相關(guān)字段(為簡單起見,我將在下面假設(shè)我有一個標量場)。我設(shè)法讓它工作,但是我覺得有些步驟可能沒有必要。特別是,閱讀numpy文檔可能是“廣播”將能夠發(fā)揮其魔力對我有利。import numpy as npfrom scipy import interpolate# Loaded from a text file, here the sampling over each dimension is identical but it is not requiredx = np.array([-1.0, -0.5, 0.0, 0.5, 1.0])y = np.array([-1.0, -0.5, 0.0, 0.5, 1.0])z = np.array([-1.0, -0.5, 0.0, 0.5, 1.0])# Create a mesh explicitelymx, my, mz = np.meshgrid(x, y, z, indexing='ij') # I have to switch from 'xy' to 'ij'# These 3 lines seem oddmx = mx.reshape(np.prod(mx.shape))my = my.reshape(np.prod(my.shape))mz = mz.reshape(np.prod(mz.shape))# Loaded from a text filefield = np.random.rand(len(mx))# Put it all togetherdata = np.array([mx, my, mz, field]).T# Interpolateinterpolation_points = np.array([[0, 0, 0]])interpolate.griddata(data[:, 0:3], data[:, 3], interpolation_points, method='linear')真的有必要像這樣構(gòu)造網(wǎng)格嗎?有沒有可能讓它更有效率?
1 回答

慕仙森
TA貢獻1827條經(jīng)驗 獲得超8個贊
這是一個直接從中broadcasted-assignment生成并因此避免創(chuàng)建所有網(wǎng)格網(wǎng)格的內(nèi)存開銷的方法,并有望帶來更好的性能-datax,y,z
m,n,r = len(x),len(y),len(z)
out = np.empty((m,n,r,4))
out[...,0] = x[:,None,None]
out[...,1] = y[:,None]
out[...,2] = z
out[...,3] = np.random.rand(m,n,r)
data_out = out.reshape(-1,out.shape[-1])
添加回答
舉報
0/150
提交
取消