numpy 将Python MeshGrid拆分为单元格

abithluo  于 2023-10-19  发布在  Python
关注(0)|答案(1)|浏览(112)

问题陈述

需要将N维MeshGrid拆分为“立方体”:
Ex)二维病例:
(-1、1)|(0,1)|(1、1)
(-1,0)|(0,0)|(1,0)
(-1,-1)|(0,-1)|(1,-1)
将有4个单元格,每个单元格具有2^D点:
我希望能够处理网格,将每个单元格的坐标点放入容器中进行进一步处理。

Cells =   [{(-1,1) (0,1)(-1,0),(0,0)},

          {(0,1),(1,1),(0,0),(1,0)},

          {(-1,0),(0,0)(-1,-1),(0,-1)}

          {(0,0),(1,0)(0,-1),(1,-1)}]

我使用以下方法生成任意尺寸d的网格:

grid = [np.linspace(-1.0 , 1.0, num = K+1) for i in range(d)]
res_to_unpack = np.meshgrid(*grid,indexing = 'ij')

它有输出:

[array([[-1., -1., -1.],
   [ 0.,  0.,  0.],
   [ 1.,  1.,  1.]]), array([[-1.,  0.,  1.],
   [-1.,  0.,  1.],
   [-1.,  0.,  1.]])]

因此,我希望能够为给定的D维网格生成上述单元格容器。在给定的K上分裂,K是2的幂。
我需要这个容器,所以对于每个单元格,我需要引用所有相关的2^D点,并计算到原点的距离。

编辑以澄清

K应将网格划分为K**D个单元格,具有(K+1)D个点。每个单元格应该有2D个点。每个“单元格”的体积为(2/K)^D。
所以对于K = 4,D = 2

Cells = [ {(-1,1),(-0.5,1),(-1,0.5),(-0.5,0.5)},
          {(-0.5,1),(-0.5,0.5)(0.0,1.0),(0,0.5)},
            ...
          {(0.0,-0.5),(0.5,-0.5),(0.0,-1.0),(0.5,-1.0)},
          {(0.5,-1.0),(0.5,-1.0),(1.0,-0.5),(1.0,-1.0)}]

这是TopLeft、TopLeft + Right Over、Bottom Left、Bottom Left + Over Left的输出。在这个集合中,我们将有16个单元格,每个单元格有四个坐标。对于增加K,假设K = 8。将有64个单元格,每个单元格有4个点。

dgjrabp2

dgjrabp21#

这应该给你给予你所需要的:

from itertools import product
import numpy as np

def splitcubes(K, d):
    coords = [np.linspace(-1.0 , 1.0, num=K + 1) for i in range(d)]
    grid = np.stack(np.meshgrid(*coords)).T

    ks = list(range(1, K))
    for slices in product(*([[slice(b,e) for b,e in zip([None] + ks, [k+1 for k in ks] + [None])]]*d)):
        yield grid[slices]

def cubesets(K, d):
    if (K & (K - 1)) or K < 2:
        raise ValueError('K must be a positive power of 2. K: %s' % K)

    return [set(tuple(p.tolist()) for p in c.reshape(-1, d)) for c in splitcubes(K, d)]

二维案例演示

下面是2D案例的一个小演示:

import matplotlib.pyplot as plt

def assemblecube(c, spread=.03):
    c = np.array(list(c))
    c = c[np.lexsort(c.T[::-1])]

    d = int(np.log2(c.size))
    for i in range(d):
        c[2**i:2**i + 2] = c[2**i + 1:2**i - 1:-1]

    # get the point farthest from the origin
    sp = c[np.argmax((c**2).sum(axis=1)**.5)]
    # shift all points a small distance towards that farthest point
    c += sp * .1 #np.copysign(np.ones(sp.size)*spread, sp)

    # create several different orderings of the same points so that matplotlib will draw a closed shape
    return [(np.roll(c, i, axis=1) - (np.roll(c, i, axis=1)[0] - c[0])[None,:]).T for i in range(d)]

fig = plt.figure(figsize=(6,6))
ax = fig.gca()

for i,c in enumerate(cubesets(4, 2)):
    for cdata in assemblecube(c):
        p = ax.plot(*cdata, c='C%d' % (i % 9))

ax.set_aspect('equal', 'box')
fig.show()

输出量:

为了可视化的目的,立方体已经稍微分开了(这样它们就不会重叠和互相覆盖)。

3D案例演示

对于3D的情况也是一样的:

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

fig = plt.figure(figsize=(6,6))
ax = fig.add_subplot(111, projection='3d')

for i,c in enumerate(cubesets(2,3)):
    for cdata in assemblecube(c, spread=.05):
        ax.plot(*cdata, c=('C%d' % (i % 9)))

plt.gcf().gca().set_aspect('equal', 'box')
plt.show()

输出量:

K=4演示

下面是与上面相同的2D和3D演示的输出,但是使用K=4

相关问题