我在这个演示https://jonasteuwen.github.io/numpy/python/multiprocessing/2017/01/07/multiprocessing-numpy-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模块来执行此操作,但是对于实现相似的目标也持开放态度。谢谢。
答案 0 :(得分:0)
通过将数组分为实部和虚部,分别处理然后合并以形成复杂变量来解决了这个问题。
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))