优化 numpy 网格创建以实现高效插值

我正在从文本文件中读取磁场数据。我的目标是正确有效地加载网格点(3 维)和相关字段(为简单起见,我将在下面假设我有一个标量场)。


我设法让它工作,但是我觉得有些步骤可能没有必要。特别是,阅读numpy文档可能是“广播”将能够发挥其魔力对我有利。


import numpy as np

from scipy import interpolate

# Loaded from a text file, here the sampling over each dimension is identical but it is not required

x = 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 explicitely

mx, my, mz = np.meshgrid(x, y, z, indexing='ij')  # I have to switch from 'xy' to 'ij'

# These 3 lines seem odd

mx = mx.reshape(np.prod(mx.shape))

my = my.reshape(np.prod(my.shape))

mz = mz.reshape(np.prod(mz.shape))

# Loaded from a text file

field = np.random.rand(len(mx))

# Put it all together

data = np.array([mx, my, mz, field]).T

# Interpolate

interpolation_points = np.array([[0, 0, 0]])

interpolate.griddata(data[:, 0:3], data[:, 3], interpolation_points, method='linear')

真的有必要像这样构造网格吗?有没有可能让它更有效率?


繁星点点滴滴
浏览 225回答 1
1回答

慕仙森

这是一个直接从中broadcasted-assignment生成并因此避免创建所有网格网格的内存开销的方法,并有望带来更好的性能-datax,y,zm,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]  = zout[...,3]  = np.random.rand(m,n,r)data_out = out.reshape(-1,out.shape[-1])
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python