gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 08:11:44 25 4
gpt4 key购买 nike

我正在从文本文件中读取磁场数​​据。我的目标是正确有效地加载网格点(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')

真的有必要这样构造网格吗?是否可以提高效率?

最佳答案

这里使用广播分配直接从x,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])

关于python - 优化 numpy 网格创建以实现高效插值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55206169/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com