均匀采样的 3D 网格

时间:2021-04-17 00:01:27

标签: python arrays numpy multidimensional-array

我有一个使用以下代码生成的 3 维网格:

x = np.linspace(-1,1,100)
xx, yy, zz = np.meshgrid(x, x, x)

这会生成一个 100 x 100 x 100 点的 3-d 点网格。我想绘制同一网格的均匀空间子采样,而不必生成新网格。我的方法是使用 np.linspace() 从原始数组中获取 10000 个均匀空间索引的数组,以绘制 xx[subsample]yy[subsample]zz[subsample]。我用过

subsample = np.linspace(0,len(xx.flatten())-1,10000,dtype=int)

但是,当我将此数组传递给我的绘图函数时,我会在 3 维中得到不均匀的结构(对角线):

enter image description here

我的猜测是发生这种情况是因为我展平了数组,然后使用了 np.linspace(),但我不知道如何在 3 维中对网格进行采样并使其均匀分布。如果可能,我想避免生成新的网格。

我的问题是如何对原始 3 维网格进行均匀子采样,而不必生成新的网格?

2 个答案:

答案 0 :(得分:1)

In [117]: x = np.linspace(-1,1,100)
     ...: xx, yy, zz = np.meshgrid(x, x, x)
In [118]: xx.shape
Out[118]: (100, 100, 100)

xx 中的 1000 个等距点,对于所有其他网格也类似:

In [119]: xx[::10,::10,::10].shape
Out[119]: (10, 10, 10)

或使用高级索引(制作副本)

In [123]: i=np.arange(0,100,10)
In [124]: xx[np.ix_(i,i,i)].shape
Out[124]: (10, 10, 10)

我认为我们可以使用 np.ravel_multi_index 来获取扁平索引数组。我们必须生成 1000 个索引元组才能做到这一点!

我不明白我们怎么能得到 10,000 分。 ::5 会给 8000 分。

答案 1 :(得分:0)

您是否尝试过使用 arange?对整数使用 linspace 可能会有一些舍入问题。

您可以尝试以下方法吗?

subsample = np.arange(0, xx.size, xx.size // 10000) # the last parameter is the step size

另外,请确保 xx.size 可以被 10000 整除,这就是您的 100x100x100 的情况。

提示:使用 .size 获取数组中元素的数量。使用 .ravel 而不是 .flatten,因为后者会创建一个副本,但 ravel 只是一个视图。

编辑:那个子样本没有生成那些对角线,但它只有一个平面。

subsample_axis = [np.arange(0, xx.shape[i], 10) for i in range(len(xx.shape))]
subsample = np.zeros([len(axis) for axis in subsample_axis])
for i, axis in enumerate(subsample_axis):
    shape = [len(axis) if j == i else 1 for j in range(len(xx.shape))]
    subsample += axis.reshape(shape)*np.prod(xx.shape[i+1:])
subsample = subsample.ravel().astype('int')