Fortran

Guide To Learn

Putting it all together in the tsunami simulator

You now know how to import variables and procedures from modules, and also how to write your own modules. Finally, we get to put this all together to refactor, improve, and expand our wave simulator. If you’ve followed the lessons in this section, and if you’ve worked through both exercises in this chapter, you now have two modules and one main program that imports procedures from them. The following listing shows the complete code for the main program.

Listing 4.8 Full code for the main program of the tsunami simulator

program tsunami
 
  use iso_fortran_env, only: int32, real32             ❶
  use mod_diff, only: diff                             ❷
  use mod_initial, only: set_gaussian                  ❸
 
  implicit none
 
  integer(int32) :: n
 
  integer(int32), parameter :: grid_size = 100         ❹
  integer(int32), parameter :: num_time_steps = 100    ❹
  real(real32), parameter :: dt = 1, dx = 1, c = 1     ❺
 
  real(real32) :: h(grid_size)                         ❻
 
  integer(int32), parameter :: icenter = 25            ❼
  real(real32), parameter :: decay = 0.02              ❼
 
  if (grid_size <= 0) stop 'grid_size must be > 0'     ❽
  if (dt <= 0) stop 'time step dt must be > 0'         ❽
  if (dx <= 0) stop 'grid spacing dx must be > 0'      ❽
 
  call set_gaussian(h, icenter, decay)                 ❾
 
  print *, 0, h
  time_loop: do n = 1, num_time_steps                  ❿
    h = h - c * diff(h) / dx * dt                      ⓫
    print *, n, h                                      ⓫
  end do time_loop
 
end program tsunami

❶ Imports type kind parameters for numeric data

❷ Imports the finite difference function from the mod_diff module

❸ Imports the set_gaussian subroutine from the mod_initial module

❹ Sets grid size and number of time steps

❺ Sets time step, grid spacing, and gravitational acceleration

❻ Declares arrays to use in the simulation

❼ Parameters to use to set the initial condition for water height

❽ Checks input values and aborts if invalid

❾ Initializes water height and velocity arrays

❿ Loops for num_time_steps time steps

⓫ Computes the water velocity in next step and updates

⓫ Prints the values of the time step and water height

At this time, you can compile this program, and the one from the end of the previous chapter, and run each of them to confirm that they produce exactly the same result. They should, as the only thing we changed here was moving the set_gaussian and diff functions from the main program to external modules.

Putting it all together in the tsunami simulator

Leave a Reply

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

Scroll to top