4

我正在编写一个 mpi python 代码。例如,四个 proc 的数据如下:

data on procs0: [1, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0]
data on procs1: [0, 0, 0, 4, 5, 6, 0, 0, 0, 0, 0, 0]
data on procs2: [0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0]
data on procs3: [0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 11, 12]

我想在 mpi4py 库中使用 reduce 函数来减少 procs0 上的数据,结果:

result on procs0: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

如何使用 mpi4py lib 函数实现它?

编辑:上面是一个简单的特殊情况,set不能用,看下面的另一种情况:

data on procs0: [1,0,0,0,0,0]
data on procs1: [0,2,0,0,0,0]
data on procs2: [0,0,0,3,0,0]
data on procs3: [0,0,0,0,4,5]

理想的结果必须是:

result on procs0: [1,2,0,3,4,5]
4

2 回答 2

9

如果您想要数据的总和或最大值,我不确定您的问题。我使用 mpiReduce函数编写了一个简单的示例,该函数计算总和。

#!/usr/bin/env python
import numpy as np
from mpi4py import MPI
comm = MPI.COMM_WORLD

comm.Barrier()
t_start = MPI.Wtime()

# this array lives on each processor
data = np.zeros(5)
for i in xrange(comm.rank, len(data), comm.size):
    # set data in each array that is different for each processor
    data[i] = i

# print out the data arrays for each processor
print '[%i]'%comm.rank, data
comm.Barrier()

# the 'totals' array will hold the sum of each 'data' array
if comm.rank==0:
    # only processor 0 will actually get the data
    totals = np.zeros_like(data)
else:
    totals = None

# use MPI to get the totals 
comm.Reduce(
    [data, MPI.DOUBLE],
    [totals, MPI.DOUBLE],
    op = MPI.SUM,
    root = 0
)

# print out the 'totals'
# only processor 0 actually has the data
print '[%i]'%comm.rank, totals

comm.Barrier()
t_diff = MPI.Wtime() - t_start
if comm.rank==0: print t_diff

将此代码保存在文件中reduce_test.py并使用命令运行它会mpirun -np 3 ./reduce_test.py在我的机器上给出以下输出:

[0] [ 0.  0.  0.  3.  0.]
[1] [ 0.  1.  0.  0.  4.]
[2] [ 0.  0.  2.  0.  0.]
[1] None
[2] None
[0] [ 0.  1.  2.  3.  4.]
0.00260496139526

请注意,将op = MPI.SUM调用中的参数更改comm.Reduceop = MPI.MAX将计算最大值而不是总和。

于 2013-11-20T18:57:51.843 回答
0

将列表推导与 zip 一起使用,存储每列的最大值

In [1]: procs0=[1, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0]    
In [2]: procs1=[0, 0, 0, 4, 5, 6, 0, 0, 0, 0, 0, 0]
In [3]: procs2=[0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0]
In [4]: procs3=[0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 11, 12]

In [5]: [max(i) for i in zip(procs0, procs1, procs2, procs3)]
Out[5]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
于 2013-03-07T12:53:09.683 回答