使用多处理模块填充复杂的Numpy阵列



我遇到了此演示https://jonasteuwen.github.io/numpy/numpy/python/multiprocessing/2017/01/01/01/07/multipprocessing-numpy-arlay-arlay-arlay-array-array.html使用多处理模块的Numpy数组。我想在代码中做类似的事情,但是我要填充的数组,即我的X是一个复杂的数组。CTYPES模块在NotImplementedError: Converting dtype('complex128') to a ctypes type的线路上给了我一个错误。

因此,在链接的示例中,我想要的是在非并行版本中有效替换:

X = np.random.random((100, 100))

X = np.random.random((100, 100)) + 1j * np.random.random((100, 100))

tmp = np.zeros((100, 100))

tmp = np.zeros((100, 100)) + 1j * np.random.random((100, 100))

我不确定如何使用numpy.ctypes模块做到这一点,但对其他想法开放以实现类似的目标。谢谢。

通过将数组分成真实和虚构的部分,分别处理,然后组合形成复杂变量。

import numpy as np
import itertools
from multiprocessing import Pool #  Process pool
from multiprocessing import sharedctypes
size = 100
block_size = 4
X = np.random.random((size, size)) + 1j * np.random.random((size, size))
X_r = X.real 
X_i = X.imag
result_r = np.ctypeslib.as_ctypes(np.zeros((size, size)))
result_i = np.ctypeslib.as_ctypes(np.zeros((size, size)))
shared_array_r = sharedctypes.RawArray(result_r._type_, result_r)
shared_array_i = sharedctypes.RawArray(result_i._type_, result_i)
def fill_per_window(args):
    window_x, window_y = args
    tmp_r = np.ctypeslib.as_array(shared_array_r)
    tmp_i = np.ctypeslib.as_array(shared_array_i)
    for idx_x in range(window_x, window_x + block_size):
        for idx_y in range(window_y, window_y + block_size):
            tmp_r[idx_x, idx_y] = X_r[idx_x, idx_y]
            tmp_i[idx_x, idx_y] = X_i[idx_x, idx_y]
window_idxs = [(i, j) for i, j in
           itertools.product(range(0, size, block_size),
                             range(0, size, block_size))]
p = Pool()
res = p.map(fill_per_window, window_idxs)
result_r = np.ctypeslib.as_array(shared_array_r)
result_i = np.ctypeslib.as_array(shared_array_i)
result = result_r + 1j * result_i
print(np.array_equal(X, result))

最新更新