# Parallel Computation of Pi (π) ::::::{tab-set} :sync-group: lang :class: lang-tabs :::::{tab-item} En :sync: en The number π can be approximated with the following formula ![](../../../files/figs/mpi4py/pi-approx.png) where the answer is obtained with an approximation that improves with increasing N. The iterations are independent of each other with respect to *i* and can therefore be parallelised. For the following examples use N=2310, which is divisible by 2,3,4,5,6,7,8,9,10,11 and 12 1. Modify hello.py so that each process independently computes the value of π and prints it to the screen ``` python # -*- coding: utf-8 -*- pi0.py from mpi4py import MPI comm = MPI.COMM_WORLD size = comm.Get_size() rank = comm.Get_rank() N = 2310 vsota=0.0 for i in range(N): vsota += 1/(1+((i+0.5)/N)**2) print "Pi = ", 4*vsota/N ``` 2. Now use different processes to compute the sum in parts. If we have only two processes, rank 0 will compute i in the range i=0,1,N/2-1 and rank 1 in the range i=N/2..N-1. Run the program with the command ``` bash srun --partition=rome --ntasks=2 python pi1.py ``` Note that ``` python range([start,] stop[, step]) -> list of integers ``` Add them up by hand and check whether the partial sums are correct. ``` python # -*- coding: utf-8 -*- pi1.py from mpi4py import MPI comm = MPI.COMM_WORLD size = comm.Get_size() rank = comm.Get_rank() N = 2310 vsota = 0.0 start = rank*N/size stop = (rank+1)*N/size for i in range(start, stop): vsota += 1/(1+((i+0.5)/N)**2) print "%f rank %d [%d,%d]" % (4*vsota/N, rank, start, stop) ``` For a larger number of processes we use awk ``` bash srun --partition=rome --nodes=1 --ntasks=11 python pi1.py|awk '{sum+=$1}END{print "Pi=",sum}' ``` 3. Now we want to add up all partial sums in the main process (rank 0) so that - All processes except the main one send their partial sum to the main process - The main process receives the values of all other processes and adds them up in a loop You must use the MPI send and receive commands ``` python # -*- coding: utf-8 -*- pi2.py from mpi4py import MPI comm = MPI.COMM_WORLD size = comm.Get_size() rank = comm.Get_rank() N = 2310 vsota = 0.0 start = rank*N/size stop = (rank+1)*N/size for i in range(start, stop): vsota += 1/(1+((i+0.5)/N)**2) if rank == 0: for i in range(1, size): vsota += comm.recv(source=i, tag=1) print "Pi =", 4*vsota/N else: comm.send(vsota, dest=0, tag=1) ``` 4. Make sure the program also works correctly if *N* is not an exact multiple of the number of processes *P*. 5. Instead of blocks, use strides (step) in the range() command 6. Use a reduction for the partial sums ``` python #.. pi = comm.reduce(vsota, op=MPI.SUM, root=0) if rank == 0: print "Pi =", 4*pi/N ``` 7. After computing the sum Pi, send it to all processes with ``` python pi = comm.bcast(vsota, root=0) ``` 8. Use the MPI.Wtime() function to measure wall-clock time. The function must be called at the beginning and then again at the end to compute the difference. This also lets us check whether the code is correctly balanced across processors. For example ``` python t0 = MPI.Wtime() #... računamo print "preteklo =", MPI.Wtime() - t0 ``` 9. Check whether receiving results in arbitrary order in the main process loop, by writing ``` python vsota += comm.recv(source=MPI.ANY_SOURCE, tag=1) ``` is faster than requiring an exact order. By what percentage is the *wildcard* receive faster? Try repeating the computation several times to get a better average result. And what if we create two parts of the code that run simultaneously, each computing its own Pi? Can these then be distinguished in the *wildcard* by choosing the tag? 10. Compare the approximation with ``` python import math #.. error = pi - math.pi ``` ::::: :::::{tab-item} Slo :sync: sl **Paralelno računanje števila Pi (π)** Aproksimacija števila π se lahko dobi z naslednjim približkom ![](../../../files/figs/mpi4py/pi-approx.png) kjer se odgovor dobi s približkom, ki postaja boljši z naraščajočim N. Iteracije so med seboj neodvisne od *i* in s tem jih je tako možno paralelizirati. Za naslednje primere uporabite N=2310, ki je deljivo z 2,3,4,5,6,7,8,9,10,11 in 12 1. Popravite hello.py tako, da bo vsak proces neodvisno izračunal vrednost π in ga izpisal na zaslon ``` python # -*- coding: utf-8 -*- pi0.py from mpi4py import MPI comm = MPI.COMM_WORLD size = comm.Get_size() rank = comm.Get_rank() N = 2310 vsota=0.0 for i in range(N): vsota += 1/(1+((i+0.5)/N)**2) print "Pi = ", 4*vsota/N ``` 2. Sedaj uporabite različne procese, da bodo po delih izračunali vsoto. Če imamo samo dva procesa, potem bo rank  0 izračunal i v mejah od i=0,1,N/2-1 ter rank 1 v mejah i=N/2..N-1. Program poženemo z ukazom ``` bash srun --partition=rome --ntasks=2 python pi1.py ``` Upoštevajte, da je ``` python range([start,] stop[, step]) -> list of integers ``` Na roke seštejte in preverite, če so delne vsote pravilne. ``` python # -*- coding: utf-8 -*- pi1.py from mpi4py import MPI comm = MPI.COMM_WORLD size = comm.Get_size() rank = comm.Get_rank() N = 2310 vsota = 0.0 start = rank*N/size stop = (rank+1)*N/size for i in range(start, stop): vsota += 1/(1+((i+0.5)/N)**2) print "%f rank %d [%d,%d]" % (4*vsota/N, rank, start, stop) ``` Za večje število procesov uporabimo awk ``` bash srun --partition=rome --nodes=1 --ntasks=11 python pi1.py|awk '{sum+=$1}END{print "Pi=",sum}' ``` 3. Sedaj želimo v glavnem procesu (rank 0) sešteti vse delne vsote tako da - Vsi procesi razen glavnega pošljejo svojo delno vsoto glavnemu procesu - Glavni proces sprejme v vrednosti vseh ostalih procesov in jih sešteje v zanki Uporabiti morate MPI ukaza za pošiljanje in sprejemanje ``` python # -*- coding: utf-8 -*- pi2.py from mpi4py import MPI comm = MPI.COMM_WORLD size = comm.Get_size() rank = comm.Get_rank() N = 2310 vsota = 0.0 start = rank*N/size stop = (rank+1)*N/size for i in range(start, stop): vsota += 1/(1+((i+0.5)/N)**2) if rank == 0: for i in range(1, size): vsota += comm.recv(source=i, tag=1) print "Pi =", 4*vsota/N else: comm.send(vsota, dest=0, tag=1) ``` 4. Zagotovite, da program deluje pravilno tudi če *N* ni natančno mnogokratnik procesov *P*. 5. Namesto po blokih raje uporabite preskoke (stride oziroma step) v ukazu range() 6. Uporabite redukcijo za delne vsote ``` python #.. pi = comm.reduce(vsota, op=MPI.SUM, root=0) if rank == 0: print "Pi =", 4*pi/N ``` 7. Potem ko ste izračunali vsoto Pi jo pošljite še vsem procesom z ``` python pi = comm.bcast(vsota, root=0) ``` 8. Uporabite funkcijo MPI.Wtime() za merjenje stenčasa. Funkcijo je potrebno klicati na začetku in potem še na koncu izračunati razliko. S tem lahko tudi preverimo ali je koda pravilno balansirana po procesorjih. Na primer ``` python t0 = MPI.Wtime() #... računamo print "preteklo =", MPI.Wtime() - t0 ``` 9. Preverite ali v primeru da v zanki glavnega procesa sprejemate rezultate v poljubnem vrstnem redu tako, da rečete ``` python vsota += comm.recv(source=MPI.ANY_SOURCE, tag=1) ``` deluje hitreje kot če zahtevate natančen vrstni red. Koliko procentov hitreje je *wildcard* sprejem? Poskusite ponoviti izračun večkrat, da dobite boljši povprečni rezultat. Kaj pa če naredimo dva dela kode, ki se hkrati izvajata in vsak računa svoj Pi. Ali lahko to potem ločimo v *wildcard* z izbiro tag-a? 10. Primerjajte aproksimacijo z ``` python import math #.. error = pi - math.pi ``` ::::: ::::::