问题陈述
需要将N维MeshGrid拆分为“多维数据集”:
例如) 二维案例:
(-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上除以2的幂。
我需要这个容器,因此对于每个单元格,我需要引用所有关联的2 ^ D点并计算距原点的距离。
编辑说明
K应将网格划分为K ** D个单元格,并具有(K + 1)** D个点。每个像元应具有2 ** D个点。每个“单元”的体积为(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 +右上方,左下,左下+左上方的输出。这个集合中将有16个像元,每个像元都有四个坐标。如果增加K,则说K =8。将有64个像元,每个像元有四个点。
答案 0 :(得分:4)
这应该给您您所需要的:
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情况,这是同一件事:
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
: