1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
|
import pathlib
import numpy as np
from mpi4py import MPI
x1 = -2.0
x2 = +1.0
y1 = -1.0
y2 = +1.0
w = 600
h = 400
maxit = 255
dirname = pathlib.Path(__file__).resolve().parent
executable = dirname / "mandelbrot-worker.exe"
# spawn worker
worker = MPI.COMM_SELF.Spawn(executable, maxprocs=7)
size = worker.Get_remote_size()
# send parameters
rmsg = np.array([x1, x2, y1, y2], dtype="f")
imsg = np.array([w, h, maxit], dtype="i")
worker.Bcast([rmsg, MPI.REAL], root=MPI.ROOT)
worker.Bcast([imsg, MPI.INTEGER], root=MPI.ROOT)
# gather results
counts = np.empty(size, dtype="i")
indices = np.empty(h, dtype="i")
cdata = np.empty([h, w], dtype="i")
worker.Gather(sendbuf=None, recvbuf=[counts, MPI.INTEGER], root=MPI.ROOT)
worker.Gatherv(
sendbuf=None, recvbuf=[indices, (counts, None), MPI.INTEGER], root=MPI.ROOT
)
worker.Gatherv(
sendbuf=None,
recvbuf=[cdata, (counts * w, None), MPI.INTEGER],
root=MPI.ROOT,
)
# disconnect worker
worker.Disconnect()
# reconstruct full result
M = np.zeros([h, w], dtype="i")
M[indices, :] = cdata
# eye candy (requires matplotlib)
if 1:
import contextlib
with contextlib.suppress(Exception):
from matplotlib import pyplot as plt
plt.imshow(M, aspect="equal")
try:
plt.nipy_spectral()
except AttributeError:
plt.spectral()
plt.pause(2)
|