Thursday, November 13, 2014

Example MPI code in Python (using mpi4pi)

from mpi4py import MPI

#send()
#recv()
#bcast()
#scatter()
#gather()
#reduce()

comm=MPI.COMM_WORLD
size=comm.size
rank=comm.rank
name=MPI.Get_processor_name()
shared=(rank+1)*5

data3=None
data4=None

print 'name:', name
if rank==0:
  data=shared
  comm.send(data,dest=1,tag=1)
  print 'From rank ', rank, 'we sent ', data

  data2={'key1':10,'key2':20}
  comm.send(data2,dest=1,tag=2)

  data3=100
  data4= [(x+1)**x for x in range(size)]

elif rank==1:
  #use tag to specify which SEND() you want to RECV()
  data=comm.recv(source=0,tag=1)
  print 'on node ',rank, 'we received: ', data
  data2=comm.recv(source=0,tag=2)
  print data

public=comm.bcast(data3,root=0)
print 'rank',rank, 'public=',public

data4=comm.scatter(data4, root=0)
print 'rank ', rank, 'has data4: ', data4

data4+=1
data5=comm.gather(data4,root=0)
data6=comm.reduce(data4,root=0)
if rank==0:
  print 'gather data4 to rank 0:', data5
  print 'reduce data4 to rank 0:', data6


No comments:

Post a Comment