简体   繁体   English

从另一个具有移位索引的数组中创建 NumPy 数组

[英]Creating a NumPy array out of another array with shifted indices

I would like to produce a 4D array from a 2D one by periodic shifts, in a way that can be summarized by the following:我想通过周期性移位从 2D 数组生成 4D 数组,其方式可以总结如下:

uuvv[kx,ky,qx,qy] = uu[kx+qx,ky+qy]

This is easiest to illustrate with a "2D from 1D" MWE:这最容易用“2D from 1D”MWE 来说明:

def pc(idx):
    return idx - Npts*int(idx/Npts)

uu = np.square(np.arange(Npts))
uv = np.zeros((Npts,Npts))
for kx in np.arange(Npts):
    for qx in np.arange(Npts):
        uv[kx,qx] = uu[pc(kx+qx)]

Here, the periodicity condition pc just brings the index back into the allowed range.在这里,周期性条件pc只是将索引带回到允许的范围内。 The output for Npts=4 is: Npts=4的 output 是:

array([[0., 1., 4., 9.],
       [1., 4., 9., 0.],
       [4., 9., 0., 1.],
       [9., 0., 1., 4.]])

So that each value is shifted slightly.这样每个值都会稍微移动。 For the "4D from 2D" case, I could obviously use:对于“2D 中的 4D”案例,我显然可以使用:

def pbc(idx):
    return idx - Npts*int(idx/Npts)

uv = np.zeros((Npts,Npts,Npts,Npts))
for kx in np.arange(Npts):
    for ky in np.arange(Npts):
        for qx in np.arange(Npts):
            for qy in np.arange(Npts):
                uv[kx,ky,qx,qy] = uu[pbc(kx+qx),pbc(ky+qy)]

However, using four loops is going to be slow, as I will be doing this multiple times for much larger arrays.但是,使用四个循环会很慢,因为对于更大的 arrays,我将多次执行此操作。 How can I do this more efficiently?我怎样才能更有效地做到这一点?

Please note that, although the MWE example could be reproduced by applying the square function to a 2D array, that would not be a helpful solution.请注意,虽然可以通过将正方形 function 应用于 2D 阵列来重现 MWE 示例,但这不是一个有用的解决方案。 Using the MWE to illustrate, the goal is to apply the function as few times as possible (ie only on the 1D array) and then to create the 2D array without for loops.使用 MWE 来说明,目标是尽可能少地应用 function(即仅在 1D 阵列上),然后创建没有 for 循环的 2D 阵列。 Ultimately, I will need to do this to generate a 4D array from a 2D array.最终,我需要这样做以从 2D 数组生成 4D 数组。 How can I do this?我怎样才能做到这一点?

You can replicate the 2D array and then extract the shifted 2D sub-arrays (avoiding modulus and conditionals).您可以复制 2D 数组,然后提取移位的 2D 子数组(避免模数和条件)。 Here is how to do that:以下是如何做到这一点:

uuRep = np.tile(uu, (2,2))
uv = np.zeros((Npts,Npts,Npts,Npts))
for kx in np.arange(Npts):
    for ky in np.arange(Npts):
        uv[kx,ky,:,:] = uuRep[kx:kx+Npts,ky:ky+Npts]

With Npts=64 , this solution is about 1000 times faster .使用Npts=64时,此解决方案的速度大约快 1000 倍

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM