Skip to content

Instantly share code, notes, and snippets.

@mbdriscoll
Created November 16, 2017 21:04
Show Gist options
  • Select an option

  • Save mbdriscoll/44757ee6ded326695b41014a42de6e37 to your computer and use it in GitHub Desktop.

Select an option

Save mbdriscoll/44757ee6ded326695b41014a42de6e37 to your computer and use it in GitHub Desktop.
Example of mpi4py MPI_Reduce with custom operator
import numpy as np
from mpi4py import MPI
rank = MPI.COMM_WORLD.rank
# create numpy arrays to reduce
src = (np.arange(8) + rank*8).reshape(4,2)
dst = np.zeros_like(src)
def myadd(xmem, ymem, dt):
x = np.frombuffer(xmem, dtype=src.dtype)
y = np.frombuffer(ymem, dtype=src.dtype)
z = x + y
print("Rank %d reducing %s (%s) and %s (%s), yielding %s" % (rank, x, type(x), y, type(y), z))
y[:] = z
op = MPI.Op.Create(myadd, commute=True)
MPI.COMM_WORLD.Reduce(src, dst, op)
if MPI.COMM_WORLD.rank == 0:
print("ANSWER: %s" % dst)
@HasanatJahan
Copy link

thank you for the gist! helped a lot in final

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment