如何将2D查找表映射到数组(python)?

我有三个相同形状的2D阵列,让我们称它们为θ,phi和A。设θ和phi是与从表面上不同距离看到的法向量的角度:


size = 100 # this value is fixed

x = np.arange(-size, size)

y = np.arange(-size, size)

xx, yy = np.meshgrid(xx, yy)

theta = np.arctan((xx**2+yy**2)**0.5 / 100) # angle from distance 100

phi = np.arctan((xx**2+yy**2)**0.5 / 1000) # angle from distance 1000

设 A 是测量值的 2D 映射,其中 x 轴是 θ,y 轴是 phi,在已知和线性步长中(实际上与 θ 和 phi 的形状不同)。我需要的是用A(x,y)表示的A(theta,phi)的值。似乎我不知道如何将A(theta,phi)转换为A(x,y),即使我知道theta(x,y)和phi(x,y)。


我尝试了什么: 通过 scipy.interpolate.interp2d,我可以将 A 映射到与 theta 和 phi 相同数量的行和列。现在,我可以迭代索引并猜测/舍入数组中最匹配的索引


B = np.zeros(A.shape)

for i in range(0,A.shape[0]):

  for j in range(0,A.shape[1]):

    B[i,j] = A[int(f_theta*theta[i,j]),int(f_phi*phi[i,j])]

其中f_theta和f_phi是由索引步长测量的步长确定的前因数。这对我来说看起来非常糟糕和低效的编码,就像我实际想要做的事情的粗略近似(这是反向插值映射?)。这让我想起了查找表,坐标转换和插值,但是由于没有这些关键字,我找到了合适的方法来解决问题。我的python经验大声疾呼,将有一个模块/函数,我不知道。


编辑限制:A(theta,phi)中的轴的范围大于θ(x,y)和phi(x,y)的范围,使得映射值始终存在。我不需要将B映射回A,因此不存在缺失值的问题。映射 A(theta,phi)中的许多值永远不会被使用。


关于清晰度的编辑:我将给出一个带有小矩阵的示例,希望澄清一些事情:


# phi given in degrees

phi = np.array([

    [2,1,2],

    [1,0,1],

    [2,1,2],

])

# theta given in degrees

theta = np.array([

    [6,4,6],

    [4,0,5],

    [6,5,6],

])

# A[0,0] is the value at phi=0deg, theta=0deg

# A[0,1] is the value at phi=1deg, theta=0deg

# A[1,1] is the value at phi=1deg, theta=1deg etc

# this is a toy example, the actual A cannot be constructed by a simple rule

A = np.array([

    [0.0,0.1,0.2],

    [1.0,1.1,1.2],

    [2.0,2.1,2.2],

    [3.0,3.1,3.2],

    [4.0,4.1,4.2],

    [5.0,5.1,5.2],

    [6.0,6.1,6.2],

])

# what I want to reach:

B = [[6.2,4.1,6.2],

     [4.1,0.0,5.1],

     [6.2,5.1,6.2]]

我需要澄清的是,我在这里做了一些简化:


1)对于给定的θ,我可以通过查看表格来检查相应的phi:theta[i,j]对应于phi[i,j]。但是这个例子的构造太简单了,它们不共享相同的来源,它是嘈杂的数据,因此我无法给出解析表达式theta(phi)或phi(theta)


2)我的实际θ和phi中的值是浮点数,我的实际A也以非整数步长测量(例如,在θ方向上每步0.45度,在phi方向上每步0.2度)


3)原则上,由于θ和phi之间存在严格的关系,我只需要值A的特定1D“迹线”来找到B,但我不知道如何找到这个迹线,也不知道如何创建B出来的迹线。示例中的此迹线为 [A[0,0],A[4,1],A[5,1],A[6,2]] = [0.0,4.1,5.1,6.2]


慕少森
浏览 127回答 1
1回答

MMMHUHU

例如,您可以执行双线性插值:from scipy.interpolate import interpndelta = [1.0, 1.0] # theta, phipoints = [np.arange(s)*d for s, d in zip(A.shape, delta)]xi = np.stack((theta, phi), axis = -1)B = interpn(points, A, xi)这给出了:print(B)[[6.2 4.1 6.2] [4.1 0.  5.1] [6.2 5.1 6.2]]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python