! Solve Laplace's equation on a 2D grid using repeated averaging,
! and compare to analytic solution. Intended as an example of
! how to use MPI, not how to solve Laplace's equation (for which
! better methods exist)

program poisson
  use mpi
  implicit none
  real (kind(1d0)),pointer,dimension(:,:) :: g1,g2,p
  real (kind(1d0)) :: pi,x,y,z,scale,err,err_posn(2)
  integer :: i,j,k,img, ht, n, niter, nprocs, nrank, ierr
  integer :: reqs(2),stat(mpi_status_size)
  integer :: stats(mpi_status_size,2)
  integer, parameter :: SIZE=400


  call mpi_init(ierr)
  call mpi_comm_rank(mpi_comm_world, nrank, ierr)
  call mpi_comm_size(mpi_comm_world, nprocs, ierr)
  
  ht=(nrank+1)*SIZE/nprocs-nrank*SIZE/nprocs+2
  niter=40000

  ! We send the grid back to nrank=0. Need to ensure that this process
  ! has a big enough array. If nprocs does not divide SIZE, the array
  ! sizes will differ between different ranks by up to one.
  if (nrank.eq.0) then
     allocate (g1(SIZE,ht+1),g2(SIZE,ht+1))
  else
     allocate (g1(SIZE,ht),g2(SIZE,ht))
  endif

  ! Boundary conditions are 0.5 at bottom of grid,
  ! and the same plus a cosine at the top
  ! This gives a well-known analytic solution
  
  pi=4*atan(1d0)
  g1=0.5d0
  do i=1,SIZE
     g1(i,ht)=0.5d0+0.5d0*cos((4d0/SIZE)*pi*i)
  enddo
  
! Top
  g2(:,1)=g1(:,1)
! Bottom
  g2(:,ht)=g1(:,ht)

  reqs=mpi_request_null
  do n=1,niter

    if (n.gt.1) call mpi_waitall(2,reqs,stats,ierr)

    if (nrank.ne.nprocs-1) &
         call mpi_isend(g1(:,ht-1),size,mpi_double_precision,  &
         nrank+1,1,mpi_comm_world,reqs(1),ierr)

    if (nrank.ne.0) &
         call mpi_isend(g1(:,2),size,mpi_double_precision, &
         nrank-1,1,mpi_comm_world,reqs(2),ierr)

    if (nrank.eq.0) then
       g2(:,1)=g1(:,1)
    else
       call mpi_recv(g1(:,1),size,mpi_double_precision, &
            nrank-1,mpi_any_tag,mpi_comm_world,stat,ierr)
    endif

    if (nrank.eq.nprocs-1) then
       g2(:,ht)=g1(:,ht)
    else
       call mpi_recv(g1(:,ht),size,mpi_double_precision, &
            nrank+1,mpi_any_tag,mpi_comm_world,stat,ierr)
    endif
       
     
    do j=2,ht-1
! Left (use periodic boundary conditions, as analytic solution does)
      g2(1,j)=0.25*(g1(1,j-1)+g1(1,j+1)+g1(2,j)+g1(SIZE,j))
! Body
      do i=2,SIZE-1
        g2(i,j)=0.25*(g1(i,j-1)+g1(i,j+1)+g1(i-1,j)+g1(i+1,j))
      enddo
! Right
      g2(SIZE,j)=0.25*(g1(SIZE,j-1)+g1(SIZE,j+1)+g1(SIZE-1,j)+g1(1,j))
    enddo

    p=>g1
    g1=>g2
    g2=>p

  enddo

  img=10
  if (nrank.eq.0) then
     open(unit=img,file='poisson.pgm')
     write(img,'(a2)')"P2"
     write(img,'(I0,x,I0,x,I0)')SIZE,SIZE,255
     scale=1d0/(2d0*(exp(4*pi)-exp(-4*pi)))
     err=0
     do j=2,ht-1
        y=(j-1)*(400d0/(SIZE+1))
        do i=1,SIZE
           x=i
           z=(exp(0.01d0*pi*y)-exp(-0.01d0*pi*y))*cos((4d0/SIZE)*pi*x)*scale+0.5d0
           if (abs(g1(i,j)-z).gt.err) then
              err=abs(g1(i,j)-z)
              err_posn=(/x,y/)
           endif
           write(img,'(I0)')int(255*g1(i,j))
        enddo
     enddo
     do k=1,nprocs-1
        ht=(k+1)*SIZE/nprocs-k*SIZE/nprocs+2
        call mpi_recv(g1,ht*size,mpi_double_precision,k, &
             mpi_any_tag,mpi_comm_world,stat,ierr)
        do j=2,ht-1
           y=(k*SIZE/nprocs+j-1)*(400d0/(SIZE+1))
           do i=1,SIZE
              x=i
              z=(exp(0.01d0*pi*y)-exp(-0.01d0*pi*y))*cos((4d0/SIZE)*pi*x)*scale+0.5d0
              if (abs(g1(i,j)-z).gt.err) then
                 err=abs(g1(i,j)-z)
                 err_posn=(/x,y/)
              endif
              write(img,'(I0)')int(255*g1(i,j))
           enddo
        enddo
     enddo
     close(img)
     write(*,*)'Max error is ',err, ' at ',err_posn(1),',',err_posn(2)
  else
     call mpi_send(g1,ht*size,mpi_double_precision,0,1,mpi_comm_world,ierr)
  endif

  call mpi_finalize(ierr)
        
end
