Fortran

Guide To Learn

Exercise 2: Writing a function that returns the indices of neighbor images

If you’ve practiced using the this_image and num_images built-in functions long enough, the solution will be straightforward. For any image that calls this function, its left neighbor will be this_image() - 1, and its right neighbor this_image() + 1. (Except when this_image() is at the boundary, that is, this_image() == 1 or this_image() == num_images().) The following listing provides the solution.

Listing 7.9 Calculating the index of neighbor images

pure function tile_neighbors()
 
  integer :: tile_neighbors(2)                  ❶
  integer :: left, right                        ❷
 
  if (num_images() > 1) then
    left = this_image() - 1                     ❸
    right = this_image() + 1                    ❸
     if (this_image() == 1) then
      left = num_images()                       ❹
    else if (this_image() == num_images()) then
      right = 1                                 ❺
    end if
  else
    left = 1                                    ❻
    right = 1                                   ❻
  end if
 
  tile_neighbors(1) = left                      ❼
  tile_neighbors(2) = right                     ❼
 
end function tile_neighbors

❶ Two-element integer array to store the result

❷ Neighbor indices

❸ General case

❹ Special case for the first image

❺ Special case for the last image

❻ Special case if we’re working with only one image

❼ Stores the indices in the result array

This is also a function that’s essential for the tsunami simulator and is defined in src/ch07/mod_parallel.f 90.

Exercise 2: Writing a function that returns the indices of neighbor images

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top