我正在从文本文件中读取磁场数据。我的目标是正确有效地加载网格点(3 维)和相关字段(为简单起见,我将在下面假设我有一个标量场)。我设法让它工作,但是我觉得有些步骤可能没有必要。特别是,阅读numpy文档可能是“广播”将能够发挥其魔力对我有利。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')真的有必要像这样构造网格吗?有没有可能让它更有效率?
1 回答
慕仙森
TA贡献1827条经验 获得超7个赞
这是一个直接从中broadcasted-assignment生成并因此避免创建所有网格网格的内存开销的方法,并有望带来更好的性能-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
提交
取消