From 564a430868e0c44e024f4a1449762cfba0eead6e Mon Sep 17 00:00:00 2001 From: Garrett Mills Date: Wed, 1 May 2019 15:08:23 -0500 Subject: [PATCH] add calculate pi demo --- demos/calculate_pi/calculate_pi.py | 44 +++++++++++++++++++ .../calculate_pi/slurm_submit_calculate_pi.sh | 10 +++++ 2 files changed, 54 insertions(+) create mode 100644 demos/calculate_pi/calculate_pi.py create mode 100644 demos/calculate_pi/slurm_submit_calculate_pi.sh diff --git a/demos/calculate_pi/calculate_pi.py b/demos/calculate_pi/calculate_pi.py new file mode 100644 index 0000000..212f3dd --- /dev/null +++ b/demos/calculate_pi/calculate_pi.py @@ -0,0 +1,44 @@ +#!/usr/bin/env python +""" +Parallel PI computation using Collective Communication Operations (CCO) +within Python objects exposing memory buffers (requires NumPy). + +usage:: + + $ mpiexec -n python cpi-buf.py +""" + +from mpi4py import MPI +from math import pi as PI +from numpy import array + +def comp_pi(n, myrank=0, nprocs=1): + h = 1.0 / n + s = 0.0 + for i in range(myrank + 1, n + 1, nprocs): + x = h * (i - 0.5) + s += 4.0 / (1.0 + x**2) + return s * h + +def prn_pi(pi, PI): + message = "pi is approximately %.16f, error is %.16f" + print (message % (pi, abs(pi - PI))) + +comm = MPI.COMM_WORLD +nprocs = comm.Get_size() +myrank = comm.Get_rank() + +n = array(0, dtype=int) +pi = array(0, dtype=float) +mypi = array(0, dtype=float) + +if myrank == 0: + _n = 10000000 + n.fill(_n) +comm.Bcast([n, MPI.INT], root=0) +_mypi = comp_pi(n, myrank, nprocs) +mypi.fill(_mypi) +comm.Reduce([mypi, MPI.DOUBLE], [pi, MPI.DOUBLE], + op=MPI.SUM, root=0) +if myrank == 0: + prn_pi(pi, PI) diff --git a/demos/calculate_pi/slurm_submit_calculate_pi.sh b/demos/calculate_pi/slurm_submit_calculate_pi.sh new file mode 100644 index 0000000..b133773 --- /dev/null +++ b/demos/calculate_pi/slurm_submit_calculate_pi.sh @@ -0,0 +1,10 @@ +#!/bin/bash +#SBATCH --ntasks=6 + +# Requires python3, a configured MPI environment +# and the Python packages mpi4py and numpy to be +# available in PATH. + +cd $SLURM_SUBMIT_DIR + +mpiexec -n 6 python3 ./calculate_pi.py