# How to compute the mean 2D slice of a 3D set of data in MPI

I have a 3D set of data v(i,j,k), and I want to compute the mean 2D slice vmean(i,j) summing up the nz slices of the v(i,j,k) set along its third dimension. I wrote down this piece of FORTRAN90 code but it does not produce the correct results. Anyone can suggest me the solution? Thanks in advance

gbl_sum = 0.0
do j    = mystarty,myendy
do i = mystartx,myendy

lcl_sum = sum(v(i,j,mystartz:myendz))

call MPI_REDUCE(lcl_sum, gbl_sum(i,j), &
1, real, mpi_sum, root,mpi_comm_world,err)

gbl_sum(i,j) = lcl_sum

enddo
enddo

call mpi_BCAST(gbl_sum,gbl_sumSize,real,root,&
mpi_comm_world,err)

do j    = mystarty,myendy
do i = mystartx,myendy
vmean(i,j) = gbl_sum(i,j)/real(nz)
enddo
enddo

• The algorithm you need depends on how you split up your data across the MPI processes. You should describe how you do that. Jan 25 '20 at 20:43
• @spektr The data are split with a Cartesian-type topology, employing a Cartesian communicator Jan 26 '20 at 8:24

## 1 Answer

1. You're doing the right thing by first doing a local reduction and then reducing that single scalar.
2. You're using Reduce followed by Bcast: you should really be using Allreduce.
3. Your code otherwise looks correct, but you're obscuring one crucial detail: how is your "v" array allocated? Are you using explicit lower bounds for that?
4. You specify "real" has the MPI type. Does that exist? Shouldn't that be MPI_REAL4 or so? I'm wondering if you have a precision problem.
• 1. ok thanks @Victor; 2. If I use mpi_allreduce the program goes in deadlock. I do not know why; 3. v is a 3D allocatable array v(mystartx:myendx, mystarty:myendy, mystartz:myendz) 4. Sorry, real is mpi_double_precision or equivalently mpi_real8 Jan 26 '20 at 8:41
• Allreduce does not go into deadlock if you make sure that each process calls it. Jan 26 '20 at 22:08