!= 初期値データ提供
!
!= Prepare initial data
!
! Authors::   Yasuhiro MORIKAWA
! Version::   $Id: initial_data_primitive.F90,v 1.1.1.1 2010-08-17 05:24:50 takepiro Exp $
! Tag Name::  $Name:  $
! Copyright:: Copyright (C) GFD Dennou Club, 2008. All rights reserved.
! License::   See COPYRIGHT[link:../../../COPYRIGHT]
!

module initial_data
  !
  != 初期値データ提供
  !
  != Prepare initial data
  !
  ! 初期値データのサンプルを提供します.
  !
  ! 現在は以下のデータを提供します.
  !
  ! * Small Disturbance of Temperature
  !   * 風速: 0 [m/s], 地表面気圧: 1.0e+5 [Pa],
  !   * 温度: 250 [K] に微小擾乱を加えたもの
  !
  ! * [AGCM 5.3]{http://www.gfd-dennou.org/library/agcm5} Default
  !   * 風速: 0 [m/s], 地表面気圧: 1.0e+5 [Pa],
  !   * 温度: 250 [K] に微小擾乱を加えたもの
  !
  ! Prepare sample data of initial data (restart data)
  !
  ! Now, following data are provided.
  !
  ! * Small Disturbance of Temperature
  !   * Velocity: 0 [m/s], Surface pressure: 1.0e+5 [Pa].
  !   * Temperature: 250 [K] and perturbation
  !
  ! * [AGCM 5.3]{http://www.gfd-dennou.org/library/agcm5} Default
  !   * Velocity: 0 [m/s], Surface pressure: 1.0e+5 [Pa].
  !   * Temperature: 250 [K] and perturbation
  !
  !== Procedures List
  !
  ! SetInitData   :: 初期値データ取得
  ! ------------  :: ------------
  ! SetInitData   :: Get initial data
  !
  !== NAMELIST
  !
  ! NAMELIST#initial_data_nml
  !

  ! モジュール引用 ; USE statements
  !

  ! 格子点設定
  ! Grid points settings
  !
  use gridset, only: imax, & ! 経度格子点数.
                             ! Number of grid points in longitude
    &                jmax, & ! 緯度格子点数.
                             ! Number of grid points in latitude
    &                kmax    ! 鉛直層数.
                             ! Number of vertical level

  ! 種別型パラメタ
  ! Kind type parameter
  !
  use dc_types, only: DP, &      ! 倍精度実数型. Double precision.
    &                 STRING     ! 文字列.       Strings.

  ! 種別型パラメタ
  ! Kind type parameter
  !
  use dc_types, only: DP     ! 倍精度実数型. Double precision.

  ! メッセージ出力
  ! Message output
  !
  use dc_message, only: MessageNotify

  ! 宣言文 ; Declaration statements
  !
  implicit none
  private

  ! 公開手続き
  ! Public procedure
  !
  public:: SetInitData

  ! 公開変数
  ! Public variables
  !
  logical, save, public:: initial_data_inited = .false.
                              ! 初期設定フラグ.
                              ! Initialization flag

  character(STRING), save, public:: Pattern
                              ! 初期値データのパターン.
                              ! 以下のパターンを選択可能.
                              !
                              ! Initial data pattern
                              ! Available patterns are as follows.
                              !
                              ! * "Small Disturbance of Temperature" (default value)
                              ! * "AGCM 5.3 Default"
                              ! * "Sugiyama et al. (2008)"
                              !
  real(DP), save, public:: TempAvr
                              ! $ \bar{T} $ .     温度平均値. Mean temperature
  real(DP), save, public:: PsAvr
                              ! $ \bar{p_s} $ .   地表面気圧平均値. Mean surface pressure
  real(DP), save, public:: Ueq
                              ! $ u_{eq} $ .      赤道上の東西風速. Eastward wind on the equator

  ! 非公開変数
  ! Private variables
  !
  character(*), parameter:: module_name = 'initial_data'
                              ! モジュールの名称.
                              ! Module name
  character(*), parameter:: version = &
    & '$Name:  $' // &
    & '$Id: initial_data_primitive.F90,v 1.1.1.1 2010-08-17 05:24:50 takepiro Exp $'
                              ! モジュールのバージョン
                              ! Module version

  ! INTERFACE 文 ; INTERFACE statements
  !
  interface SetInitData
    module procedure SetInitData
  end interface

contains

  subroutine SetInitData( &
    & xyz_U, xyz_V, xyz_Temp, xy_Ps &   ! (out)
    & )
    !
    ! 初期値データのサンプルを提供します.
    !
    ! Prepare sample data of initial data
    !

    ! モジュール引用 ; USE statements
    !

    ! 座標データ設定
    ! Axes data settings
    !
    use axesset, only: &
      & x_Lon, &
                              ! $ \lambda $ [rad.] . 経度. Longitude
      & y_Lat, &
                              ! $ \varphi $ [rad.] . 緯度. Latitude
      & z_Sigma
                              ! $ \sigma $ レベル (整数).
                              ! Full $ \sigma $ level

    ! 文字列操作
    ! Character handling
    !
    use dc_string, only: LChar

    ! 宣言文 ; Declaration statements
    !
    implicit none
    real(DP), intent(out):: xyz_U  (0:imax-1, 1:jmax, 1:kmax)
                              ! $ u $ .   東西風速. Eastward wind
    real(DP), intent(out):: xyz_V  (0:imax-1, 1:jmax, 1:kmax)
                              ! $ v $ .   南北風速. Northward wind
    real(DP), intent(out):: xyz_Temp  (0:imax-1, 1:jmax, 1:kmax)
                              ! $ T $ .   温度. Temperature
    real(DP), intent(out):: xy_Ps (0:imax-1, 1:jmax)
                              ! $ p_s $ . 地表面気圧. Surface pressure

    ! 作業変数
    ! Work variables
    !
    integer:: i               ! 経度方向に回る DO ループ用作業変数
                              ! Work variables for DO loop in longitude
    integer:: j               ! 緯度方向に回る DO ループ用作業変数
                              ! Work variables for DO loop in latitude
    integer:: k               ! 鉛直方向に回る DO ループ用作業変数
                              ! Work variables for DO loop in vertical direction

    ! 実行文 ; Executable statement

    if ( .not. initial_data_inited ) call InitDataInit

    ! 微小な温度擾乱のある静止場
    ! Stationary field with small disturbance of temperature
    !
    select case ( LChar( trim(Pattern) ) )
    case ( 'small disturbance of temperature' )
      xyz_U    = 0.0_DP
      xyz_V    = 0.0_DP
      xyz_Temp = TempAvr
      xy_Ps    = PsAvr

      ! 温度に擾乱を与える
      ! Add perturbation to temperature
      !
      do k = 1, kmax
        do j = 1, jmax
          do i = 0, imax - 1
            xyz_Temp(i,j,k) = &
              &    xyz_Temp(i,j,k) &
              &  + 0.1_DP * sin ( x_Lon(i) * y_Lat(j) ) &
              &  - 0.1_DP * ( 1.0_DP - z_Sigma(k) )
          end do
        end do
      end do

      ! 東西風速を与える
      ! Add eastward wind
      !
      do j = 1, jmax
        xyz_U(:,j,:) = Ueq * cos(y_Lat(j))
      end do

    ! AGCM5.3 のデフォルト初期値
    ! AGCM5.3 default initial values
    !
    case ( 'agcm 5.3 default' )
      xyz_U    = 0.0_DP
      xyz_V    = 0.0_DP
      xyz_Temp = TempAvr
      xy_Ps    = PsAvr

      ! 温度に擾乱を与える
      ! Add perturbation to temperature
      !
      do k = 1, kmax
        do j = 1, jmax
          do i = 0, imax - 1
            xyz_Temp(i,j,k) = &
              &    xyz_Temp(i,j,k) &
              &  + 0.1_DP &
              &    * sin ( real( ( i + 1 ) &
              &                  * ( jmax - j + 1 ) &
              &                  * ( kmax - k ), DP ) &
              &            / real( imax &
              &                    * jmax &
              &                    * kmax, DP ) * 10.0_DP &
              &                 )
          end do
        end do
      end do

      ! 東西風速を与える
      ! Add eastward wind
      !
      do j = 1, jmax
        xyz_U(:,j,:) = Ueq * cos(y_Lat(j))
      end do
    end select

  end subroutine SetInitData

  !-------------------------------------------------------------------

  subroutine InitDataInit

    ! モジュール引用 ; USE statements
    !

    ! NAMELIST ファイル入力に関するユーティリティ
    ! Utilities for NAMELIST file input
    !
    use namelist_util, only: namelist_filename, NmlutilMsg, NmlutilAryValid

    ! ファイル入出力補助
    ! File I/O support
    !
    use dc_iounit, only: FileOpen

    ! 文字列操作
    ! Character handling
    !
    use dc_string, only: LChar

    ! 宣言文 ; Declaration statements
    !
    implicit none

    integer:: unit_nml        ! NAMELIST ファイルオープン用装置番号.
                              ! Unit number for NAMELIST file open
    integer:: iostat_nml      ! NAMELIST 読み込み時の IOSTAT.
                              ! IOSTAT of NAMELIST read

    ! NAMELIST 変数群
    ! NAMELIST group name
    !
    namelist /initial_data_nml/ Pattern, &
      & TempAvr, PsAvr, Ueq
          !
          ! デフォルト値については初期化手続 "initial_data#InitDataInit"
          ! のソースコードを参照のこと.
          !
          ! Refer to source codes in the initialization procedure
          ! "initial_data#InitDataInit" for the default values.
          !

    ! 実行文 ; Executable statement

    if ( initial_data_inited ) return
    call InitCheck

    ! デフォルト値の設定 (まずは Pattern のみ)
    ! Default values settings (At first, "Pattern" only)
    !
    Pattern = 'Small Disturbance of Temperature'
    !Pattern = 'AGCM 5.3 Default'

    ! NAMELIST の読み込み (まずは Pattern のみ)
    ! NAMELIST is input (At first, "Pattern" only)
    !
    if ( trim(namelist_filename) /= '' ) then
      call FileOpen( unit_nml, &          ! (out)
        & namelist_filename, mode = 'r' ) ! (in)

      rewind( unit_nml )
      read( unit_nml, &             ! (in)
        & nml = initial_data_nml, & ! (out)
        & iostat = iostat_nml )     ! (out)
      close( unit_nml )

      call NmlutilMsg( iostat_nml, module_name ) ! (in)
    end if

    ! デフォルト値の設定
    ! Default values settings
    !
    select case ( LChar( trim(Pattern) ) )
    case ( 'small disturbance of temperature' )
      TempAvr = 250.0_DP
      PsAvr   = 1.0e+5_DP
      Ueq     = 0.0_DP
    case ( 'agcm 5.3 default' )
      TempAvr = 250.0_DP
      PsAvr   = 1.0e+5_DP
      Ueq     = 0.0_DP
    case default
      call MessageNotify( 'E', module_name, 'Pattern=<%c> is invalid.', &
        & c1 = trim(Pattern) )
    end select

    ! NAMELIST の読み込み
    ! NAMELIST is input
    !
    if ( trim(namelist_filename) /= '' ) then
      call FileOpen( unit_nml, &          ! (out)
        & namelist_filename, mode = 'r' ) ! (in)

      rewind( unit_nml )
      read( unit_nml, &             ! (in)
        & nml = initial_data_nml, & ! (out)
        & iostat = iostat_nml )     ! (out)
      close( unit_nml )

      call NmlutilMsg( iostat_nml, module_name ) ! (in)
    end if

    ! 印字 ; Print
    !
    call MessageNotify( 'M', module_name, '----- Initialization Messages -----' )
    call MessageNotify( 'M', module_name, '  Pattern = %c', c1 = trim(Pattern) )
    call MessageNotify( 'M', module_name, '  TempAvr = %f', d = (/ TempAvr  /) )
    call MessageNotify( 'M', module_name, '  PsAvr   = %f', d = (/ PsAvr  /) )
    call MessageNotify( 'M', module_name, '  Ueq     = %f', d = (/ Ueq  /) )
    call MessageNotify( 'M', module_name, '' )
    call MessageNotify( 'M', module_name, '-- version = %c', c1 = trim(version) )

    initial_data_inited = .true.
  end subroutine InitDataInit

  !-------------------------------------------------------------------

  subroutine InitCheck
    !
    ! 依存モジュールの初期化チェック
    !
    ! Check initialization of dependency modules

    ! モジュール引用 ; USE statements
    !

    ! NAMELIST ファイル入力に関するユーティリティ
    ! Utilities for NAMELIST file input
    !
    use namelist_util, only: namelist_util_inited

    ! 格子点設定
    ! Grid points settings
    !
    use gridset, only: gridset_inited

    ! 物理定数設定
    ! Physical constants settings
    !
    use constants, only: constants_inited

    ! 座標データ設定
    ! Axes data settings
    !
    use axesset, only: axesset_inited

    ! 実行文 ; Executable statement

    if ( .not. namelist_util_inited ) &
      & call MessageNotify( 'E', module_name, '"namelist_util" module is not initialized.' )

    if ( .not. gridset_inited ) &
      & call MessageNotify( 'E', module_name, '"gridset" module is not initialized.' )

    if ( .not. constants_inited ) &
      & call MessageNotify( 'E', module_name, '"constants" module is not initialized.' )

    if ( .not. axesset_inited ) &
      & call MessageNotify( 'E', module_name, '"axesset" module is not initialized.' )

  end subroutine InitCheck

end module initial_data