!= 乾燥対流調節
!
!= Dry convective adjustment
!
! Authors::   Yasuhiro MORIKAWA, Yukiko YAMADA
! Version::   $Id: dryconv_adjust.f90,v 1.4 2008-10-06 16:30:13 morikawa Exp $ 
! Tag Name::  $Name: dcpam5-20090108-1 $
! Copyright:: Copyright (C) GFD Dennou Club, 2008. All rights reserved.
! License::   See COPYRIGHT[link:../../../COPYRIGHT]
!

module dryconv_adjust
  !
  != 乾燥対流調節
  !
  != Dry convective adjustment
  !
  ! <b>Note that Japanese and English are described in parallel.</b>
  !
  ! 乾燥対流調節を行います. 
  !
  ! Dry convective adjustment is performed. 
  !
  !== Procedures List
  ! 
  ! DryConvectAdjust :: 乾燥対流調節を行う
  ! ------------     :: ------------
  ! DryConvectAdjust :: Dry convective adjustment is performed. 
  !
  !== NAMELIST
  !
  ! NAMELIST#dryconv_adjust_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. 

  ! NAMELIST ファイル入力に関するユーティリティ
  ! Utilities for NAMELIST file input
  !
  use namelist_util, only: MaxNmlArySize
                              ! NAMELIST から読み込む配列の最大サイズ. 
                              ! Maximum size of arrays loaded from NAMELIST

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

  ! 宣言文 ; Declaration statements
  !
  implicit none
  private

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

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

  ! 非公開変数
  ! Private variables
  !
  integer, save:: ItrtMax
                              ! イテレーション回数. 
                              ! Number of iteration

  real(DP), save:: TempSatMax(1:MaxNmlArySize)
                              ! 不安定の許容誤差. 
                              ! Admissible error of unstability
  
  character(*), parameter:: module_name = 'dryconv_adjust'
                              ! モジュールの名称. 
                              ! Module name
  character(*), parameter:: version = &
    & '$Name: dcpam5-20090108-1 $' // &
    & '$Id: dryconv_adjust.f90,v 1.4 2008-10-06 16:30:13 morikawa Exp $'
                              ! モジュールのバージョン
                              ! Module version

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

contains

  subroutine DryConvectAdjust( &
    & xyz_Press, xyr_Press, & ! (in)
    & xyz_Temp &              ! (inout)
    & )
    !
    ! 対流調節スキームにより, 温度と比湿を調節します. 
    !
    ! Adjust temperature and specific humidity by 
    ! convective adjustment scheme. 
    !

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

    ! 物理定数設定
    ! Physical constants settings
    !
    use constants, only: &
      & GasRDry, &
                              ! $ R $ [J kg-1 K-1]. 
                              ! 乾燥大気の気体定数. 
                              ! Gas constant of air
      & CpDry
                              ! $ C_p $ [J kg-1 K-1]. 
                              ! 乾燥大気の定圧比熱. 
                              ! Specific heat of air at constant pressure

    ! 時刻管理
    ! Time control
    !
    use timeset, only: &
      & DelTime, &            ! $ \Delta t $
      & TimeN, &              ! ステップ $ t $ の時刻. Time of step $ t $. 
      & TimesetClockStart, TimesetClockStop

    ! ヒストリデータ出力
    ! History data output
    !
    use gtool_historyauto, only: HistoryAutoPut

    ! 宣言文 ; Declaration statements
    !
    implicit none

    real(DP), intent(in):: xyz_Press (0:imax-1, 1:jmax, 1:kmax)
                              ! $ p $ . 気圧 (整数レベル). 
                              ! Air pressure (full level)
    real(DP), intent(in):: xyr_Press (0:imax-1, 1:jmax, 0:kmax)
                              ! $ \hat{p} $ . 気圧 (半整数レベル). 
                              ! Air pressure (half level)
    real(DP), intent(inout):: xyz_Temp (0:imax-1, 1:jmax, 1:kmax)
                              ! $ T $ .     温度. Temperature

    ! 作業変数
    ! Work variables
    !
    real(DP):: xyz_DTempDt (0:imax-1, 1:jmax, 1:kmax)
                              ! $ \DP{T}{t} $ . 乾燥対流調節による温度変化率. 
                              ! Temperature tendency by dry convective adjustment

    real(DP):: xyz_TempB (0:imax-1, 1:jmax, 1:kmax)
                              ! 調節前の温度. 
                              ! Temperature before adjust. 
    logical:: xy_Adjust (0:imax-1, 1:jmax)
                              ! 今回調節されたか否か?. 
                              ! Whether it was adjusted this time or not?
    logical:: xy_AdjustB (0:imax-1, 1:jmax)
                              ! 前回調節されたか否か?. 
                              ! Whether it was adjusted last time or not?
    real(DP):: xyz_DPressDz (0:imax-1, 1:jmax, 1:kmax)
                              ! $ \DD{p}{z} $
                              !
    real(DP):: xyz_DDPressDDPress (0:imax-1, 1:jmax, 1:kmax)
                              ! $ \DD{p_{k}}{p_{k-1}} $
                              !
    real(DP):: xyz_DPFact (0:imax-1, 1:jmax, 1:kmax)
                              ! $ (R / C_p)
                              ! \frac{p_{k-1} - p_{k}}{2 p_{k-1/2}} $ . 
                              !
                              ! ファクター. 
                              ! Factor
    real(DP):: TempSat        ! $ S_t $ .
                              ! 飽和温度. 
                              ! Saturation temperature
    real(DP):: DelTemp
                              ! 調節による温度の変化量. 
                              ! Temperature variation by adjustment
    logical:: Adjust
                              ! 今回全領域において一度でも調節されたか否か?. 
                              ! Whether it was adjusted even once in global 
                              ! this time or not?

    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
    integer:: itr             ! イテレーション方向に回る DO ループ用作業変数
                              ! Work variables for DO loop in iteration direction


    ! 実行文 ; Executable statement
    !

    ! 計算時間計測開始
    ! Start measurement of computation time
    !
    call TimesetClockStart( module_name )

    ! 初期化
    ! Initialization
    !
    if ( .not. dryconv_adjust_inited ) call DryConvAdjInit

    ! 調節前 "Temp" の保存
    ! Store "Temp" before adjustment
    !
    xyz_TempB  = xyz_Temp
    
    ! ファクターの計算
    ! Calculate factor
    !
    do k = 1, kmax
      xyz_DPressDz(:,:,k) = xyr_Press(:,:,k-1) - xyr_Press(:,:,k)
    end do
    
    do k = 2, kmax

      xyz_DDPressDDPress(:,:,k) = xyz_DPressDz(:,:,k) / xyz_DPressDz(:,:,k-1)
      
      xyz_DPFact(:,:,k) = &
        &   GasRDry / CpDry &
        &   * ( xyz_Press(:,:,k-1) - xyz_Press(:,:,k) ) &
        &   / ( xyz_DPressDz(:,:,k-1) + xyz_DPressDz(:,:,k) ) &
        &   / xyr_Press(:,:,k-1)

    end do
    
    ! 調節
    ! Adjustment
    !
    xy_AdjustB = .true.
    
    ! イテレーション
    ! iteration
    !
    do itr = 1, ItrtMax
      xy_Adjust = .false.
      
      do k = 2, kmax
        do i = 0, imax-1
          do j = 1, jmax
            if ( xy_AdjustB(i,j) ) then
              
              TempSat = xyz_Temp(i,j,k-1) - xyz_Temp(i,j,k) &
                & - xyz_DPFact(i,j,k) &
                &    * (   xyz_DPressDz(i,j,k-1) * xyz_Temp(i,j,k-1) &
                &        + xyz_DPressDz(i,j,k)   * xyz_Temp(i,j,k)     )
              
              ! 不安定であるならば
              ! If it is unstable
              !
              if ( TempSat > TempSatMax(itr) ) then
                
                DelTemp = TempSat / ( 1.0_DP + xyz_DDPressDDPress(i,j,k) )
                xyz_Temp(i,j,k) = xyz_Temp(i,j,k) + DelTemp
                xyz_Temp(i,j,k-1) = &
                  &   xyz_Temp(i,j,k-1) &
                  & - DelTemp * xyz_DDPressDDPress(i,j,k)
                
                ! 調節したか否か?
                ! Whether it was adjusted or not?
                !
                xy_Adjust(i,j) = .true.
              end if
              
            end if
          end do
        end do
      end do
      
      Adjust = .false.
      do i = 0, imax-1
        do j = 1, jmax
          xy_AdjustB(i,j) = xy_Adjust(i,j)
          Adjust          = Adjust .or. xy_Adjust(i,j)
        end do
      end do
      
      if ( .not. Adjust ) exit
      
    end do
    
    ! 温度変化率の算出
    ! Calculate temperature tendency
    !
    xyz_DTempDt = ( xyz_Temp - xyz_TempB ) / ( 2.0_DP * DelTime )

    ! ヒストリデータ出力
    ! History data output
    !
    call HistoryAutoPut( TimeN, 'DTempDtDryConv', xyz_DTempDt)


    ! 計算時間計測一時停止
    ! Pause measurement of computation time
    !
    call TimesetClockStop( module_name )

  end subroutine DryConvectAdjust

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

  subroutine DryConvAdjInit
    !
    ! dryconv_adjust モジュールの初期化を行います. 
    ! NAMELIST#dryconv_adjust_nml の読み込みはこの手続きで行われます. 
    !
    ! "dryconv_adjust" module is initialized. 
    ! "NAMELIST#dryconv_adjust_nml" is loaded in this procedure. 
    !

    ! モジュール引用 ; 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

    ! 種別型パラメタ
    ! Kind type parameter
    !
    use dc_types, only: STDOUT ! 標準出力の装置番号. Unit number of standard output

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

    ! ヒストリデータ出力
    ! History data output
    !
    use gtool_historyauto, only: HistoryAutoAddVariable

    ! 宣言文 ; 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 /dryconv_adjust_nml/ &
      & ItrtMax, TempSatMax
          !
          ! デフォルト値については初期化手続 "dryconv_adjust#DryConvAdjInit" 
          ! のソースコードを参照のこと. 
          !
          ! Refer to source codes in the initialization procedure
          ! "dryconv_adjust#DryConvAdjInit" for the default values. 
          !

    ! 実行文 ; Executable statement
    !

    if ( dryconv_adjust_inited ) return
    call InitCheck

    ! デフォルト値の設定
    ! Default values settings
    !
    ItrtMax = 10
    TempSatMax(1:ItrtMax) = &
      & (/ 0.01_DP, 0.02_DP, 0.02_DP, 0.05_DP, 0.05_DP, &
      &    0.10_DP, 0.10_DP, 0.20_DP, 0.20_DP, 0.40_DP  /)


    ! 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 = dryconv_adjust_nml, &  ! (out)
        & iostat = iostat_nml )        ! (out)
      close( unit_nml )

      call NmlutilMsg( iostat_nml, module_name ) ! (in)
!!$      if ( iostat_nml == 0 ) write( STDOUT, nml = dryconv_adjust_nml )
    end if

    ! イテレーション回数, 不安定の許容誤差のチェック
    ! Check number of iteration, admissible error of unstability
    !
    call NmlutilAryValid( module_name, & ! (in)
      & TempSatMax, 'TempSatMax', &      ! (in)
      & ItrtMax,    'ItrtMax' )          ! (in)


    ! ヒストリデータ出力のためのへの変数登録
    ! Register of variables for history data output
    !
    call HistoryAutoAddVariable( 'DTempDtDryConv', &
      & (/ 'lon ', 'lat ', 'sig ', 'time' /), &
      & 'temperature tendency by dry convective adjustment', 'K s-1' )

    ! 印字 ; Print
    !
    call MessageNotify( 'M', module_name, '----- Initialization Messages -----' )
    call MessageNotify( 'M', module_name, '  ItrtMax = %d', i = (/ ItrtMax /) )
    call MessageNotify( 'M', module_name, '  TempSatMax = (/ %*r /)', &
      & r = real( TempSatMax(1:ItrtMax) ), n = (/ ItrtMax /) )
    call MessageNotify( 'M', module_name, '-- version = %c', c1 = trim(version) )

    dryconv_adjust_inited = .true.
  end subroutine DryConvAdjInit

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

  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

    ! 時刻管理
    ! Time control
    !
    use timeset, only: timeset_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.' )

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

  end subroutine InitCheck

end module dryconv_adjust
