!=
!
!= Saturation adjustment
!
! Authors::   Yoshiyuki O. Takahashi
! Version::   $Id: saturation_adjust.f90,v 1.4 2015/01/29 12:03:22 yot Exp $
! Tag Name::  $Name:  $
! Copyright:: Copyright (C) GFD Dennou Club, 2008. All rights reserved.
! License::   See COPYRIGHT[link:../../../COPYRIGHT]
!

module saturation_adjust
  !
  !=
  !
  != Saturation adjustment
  !
  ! <b>Note that Japanese and English are described in parallel.</b>
  !
  !
  !
  ! Adjust temperature and specific humidity by the use of saturation
  ! adjustment
  !
  !== References
  !
!!$  !  Manabe, S., J. Smagorinsky, R. F. Strickler,
!!$  !    Simulated climatology of a general circulation model with a hydrologic cycle,
!!$  !    Mon. Wea. Rev., 93, 769-798, 1965.
  !
  !== Procedures List
  !
  ! SaturationAdjust :: æ¸©åº¦ã¨æ¯”æ¹¿ã®èª¿ç¯€
  ! ---------------- :: ------------
  ! SaturationAdjust :: Adjust temperature and specific humidity
  !
  !== NAMELIST
  !
  ! NAMELIST#saturation_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.

  ! ãƒ¡ãƒƒã‚»ãƒ¼ã‚¸å‡ºåŠ›
  ! Message output
  !
  use dc_message, only: MessageNotify

  ! å®£è¨€æ–‡ ; Declaration statements
  !
  implicit none
  private

  ! å…¬é–‹æ‰‹ç¶šã
  ! Public procedure
  !
  public:: SaturationAdjust
  public:: SaturationAdjustInit

  ! å…¬é–‹å¤‰æ•°
  ! Public variables
  !
  logical, save :: saturation_adjust_inited = .false.
                              ! åˆæœŸè¨å®šãƒ•ãƒ©ã‚°.
                              ! Initialization flag

  ! éžå…¬é–‹å¤‰æ•°
  ! Private variables
  !
  logical, save:: FlagSublimation
                              !
                              ! flag for treating sublimation

  character(*), parameter:: module_name = 'saturation_adjust'
                              ! ãƒ¢ã‚¸ãƒ¥ãƒ¼ãƒ«ã®åç§°.
                              ! Module name
  character(*), parameter:: version = &
    & '$Name:  $' // &
    & '$Id: saturation_adjust.f90,v 1.4 2015/01/29 12:03:22 yot Exp $'
                              ! ãƒ¢ã‚¸ãƒ¥ãƒ¼ãƒ«ã®ãƒãƒ¼ã‚¸ãƒ§ãƒ³
                              ! Module version

contains

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

  subroutine SaturationAdjust(         &
    & xyz_Temp, xyz_QVap,              &  ! (inout)
    & xyz_QH2OLiq,                     &  ! (in)
    & xyz_Press, xyr_Press,            &  ! (in)
    & xyz_DQH2OLiqDt                   &  ! (out)
    & )
    !
    !
    !
    ! Adjust temperature and specific humidity by the use of saturation
    ! adjustment
    !

    ! ãƒ¢ã‚¸ãƒ¥ãƒ¼ãƒ«å¼•ç”¨ ; USE statements
    !

    ! ç‰©ç†å®šæ•°è¨å®š
    ! Physical constants settings
    !
    use constants, only: &
      & Grav, &
                              ! $ g $ [m s-2].
                              ! é‡åŠ›åŠ é€Ÿåº¦.
                              ! Gravitational acceleration
      & CpDry, &
                              ! $ C_p $ [J kg-1 K-1].
                              ! ä¹¾ç‡¥å¤§æ°—ã®å®šåœ§æ¯”ç†±.
                              ! Specific heat of air at constant pressure
      & LatentHeat, &
                              ! $ L $ [J kg-1] .
                              ! å‡çµã®æ½œç†±.
                              ! Latent heat of condensation
      & LatentHeatFusion
                              ! $ L $ [J kg-1] .
                              ! èžè§£ã®æ½œç†±.
                              ! Latent heat of fusion

    ! æ™‚åˆ»ç®¡ç†
    ! Time control
    !
    use timeset, only: &
      & DelTime, &            ! $ \Delta t $
      & TimeN, &              ! ã‚¹ãƒ†ãƒƒãƒ— $ t $ ã®æ™‚åˆ». Time of step $ t $.
      & TimesetClockStart, TimesetClockStop

    ! ãƒ’ã‚¹ãƒˆãƒªãƒ‡ãƒ¼ã‚¿å‡ºåŠ›
    ! History data output
    !
    use gtool_historyauto, only: HistoryAutoPut

    ! é£½å’Œæ¯”æ¹¿ã®ç®—å‡º
    ! Evaluate saturation specific humidity
    !
    use saturate, only: xyz_CalcQVapSat

    ! å¤§è¦æ¨¡å‡çµ (éžå¯¾æµæ€§å‡çµ) (Manabe, 1965)
    ! Large scale condensation (non-convective condensation) (Le Treut and Li, 1991)
    use lscond, only : LScaleCond

    ! å®£è¨€æ–‡ ; Declaration statements
    !
    implicit none

    real(DP), intent(inout):: xyz_Temp (0:imax-1, 1:jmax, 1:kmax)
                              ! $ T $ .     æ¸©åº¦. Temperature
    real(DP), intent(inout):: xyz_QVap   (0:imax-1, 1:jmax, 1:kmax)
                              ! $ q $ .     æ¯”æ¹¿. Specific humidity
    real(DP), intent(in   ):: xyz_QH2OLiq(0:imax-1, 1:jmax, 1:kmax)
                              ! $ q_w $ .   é›²æ°´æ··åˆæ¯”. Cloud water mixing ratio
    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(out) :: xyz_DQH2OLiqDt(0:imax-1,1:jmax,1:kmax)

    ! ä½œæ¥å¤‰æ•°
    ! Work variables
    !
    real(DP):: xyz_QVapSat      (0:imax-1, 1:jmax, 1:kmax)
                              ! é£½å’Œæ¯”æ¹¿.
                              ! Saturation specific humidity.
    real(DP):: xy_RainLsc (0:imax-1, 1:jmax)
                              ! é™æ°´é‡.
                              ! Precipitation
    real(DP):: xyz_DTempDtLsc (0:imax-1, 1:jmax, 1:kmax)
                              ! æ¸©åº¦å¤‰åŒ–çŽ‡.
                              ! Temperature tendency
    real(DP):: xyz_DQVapDtLsc (0:imax-1, 1:jmax, 1:kmax)
                              ! æ¯”æ¹¿å¤‰åŒ–çŽ‡.
                              ! Specific humidity tendency

    real(DP):: xyz_QVapB (0:imax-1, 1:jmax, 1:kmax)
                              ! èª¿ç¯€å‰ã®æ¯”æ¹¿.
                              ! Specific humidity before adjust.
    real(DP):: xyz_QH2OLiqB (0:imax-1, 1:jmax, 1:kmax)
                              ! èª¿ç¯€å‰ã®é›²æ°´æ··åˆæ¯”.
                              ! Mixing ratio of cloud water before adjust.
    real(DP):: xyz_TempB (0:imax-1, 1:jmax, 1:kmax)
                              ! èª¿ç¯€å‰ã®æ¸©åº¦.
                              ! Temperature before adjust.
                              !
    real(DP):: xyz_RainLSC(0:imax-1, 1:jmax, 1:kmax)

    real(DP):: xyz_EvapQH2OLiq(0:imax-1, 1:jmax, 1:kmax)
    real(DP):: TempTentative

    real(DP):: LatentHeatLocal
                              !
                              ! Latent heat used in this routine
    integer:: i
    integer:: j
    integer:: k               ! é‰›ç›´æ–¹å‘ã«å›žã‚‹ DO ãƒ«ãƒ¼ãƒ—ç”¨ä½œæ¥å¤‰æ•°
                              ! Work variables for DO loop in vertical direction

    ! å®Ÿè¡Œæ–‡ ; Executable statement
    !

    ! åˆæœŸåŒ–ç¢ºèª
    ! Initialization check
    !
    if ( .not. saturation_adjust_inited ) then
      call MessageNotify( 'E', module_name, 'This module has not been initialized.' )
    end if

    ! è¨ˆç®—æ™‚é–“è¨ˆæ¸¬é–‹å§‹
    ! Start measurement of computation time
    !
    call TimesetClockStart( module_name )

    ! Set a value for latent heat
    if ( FlagSublimation ) then
      LatentHeatLocal = LatentHeat + LatentHeatFusion
    else
      LatentHeatLocal = LatentHeat
    end if

    ! èª¿ç¯€å‰ "QVap", "QH2OLiq", "Temp" ã®ä¿å˜
    ! Store "QVap", "QH2OLiq", "Temp" before adjustment
    !
    xyz_QVapB    = xyz_QVap
    xyz_QH2OLiqB = xyz_QH2OLiq
    xyz_TempB    = xyz_Temp

    ! é£½å’Œæ¯”æ¹¿è¨ˆç®—
    ! Calculate saturation specific humidity
    !
    xyz_QVapSat = xyz_CalcQVapSat( xyz_Temp, xyz_Press )

    ! Evaporate all of cloud liquid water temporarily
!!$    xyz_EvapQH2OLiq = xyz_QH2OLiq
    ! Evaporate part of cloud liquid water temporarily
    do k = 1, kmax
      do j = 1, jmax
        do i = 0, imax-1
          xyz_EvapQH2OLiq(i,j,k) = &
            & min( max( xyz_QVapSat(i,j,k), xyz_QVap(i,j,k) ) - xyz_QVap(i,j,k), &
            &      xyz_QH2OLiq(i,j,k) )
          xyz_EvapQH2OLiq(i,j,k) = &
            & xyz_EvapQH2OLiq(i,j,k) * ( 1.0_DP - 1.0e-10_DP )
          TempTentative = xyz_Temp(i,j,k) - LatentHeatLocal * xyz_EvapQH2OLiq(i,j,k) / CpDry
          if ( TempTentative < 1.0_DP ) then
            TempTentative = 1.0_DP
            xyz_EvapQH2OLiq(i,j,k) = &
              & ( xyz_Temp(i,j,k) - TempTentative ) / ( LatentHeatLocal / CpDry )
          end if
        end do
      end do
    end do
    !
    xyz_Temp    = xyz_Temp    - LatentHeatLocal * xyz_EvapQH2OLiq / CpDry
    xyz_QVap    = xyz_QVap    +                   xyz_EvapQH2OLiq
    ! QH2OLiq will be updated in cloud model. Tendency will be updated below.
!!$    xyz_QH2OLiq = 0.0_DP

    call LScaleCond(              &
      & xyz_Temp, xyz_QVap,       &  ! (inout)
      & xyz_Press, xyr_Press,     &  ! (in)
      & xyz_DQH2OLiqDt,           &  ! (out)
      & .false.                   &
      & )

    ! æ¯”æ¹¿å¤‰åŒ–çŽ‡, æ¸©åº¦å¤‰åŒ–çŽ‡, é™æ°´é‡ã®ç®—å‡º
    ! Calculate specific humidity tendency, temperature tendency,
    ! precipitation
    !
    xyz_DQVapDtLsc = ( xyz_QVap - xyz_QVapB ) / ( 2.0_DP * DelTime )
    xyz_DTempDtLsc = ( xyz_Temp - xyz_TempB ) / ( 2.0_DP * DelTime )

    xyz_DQH2OLiqDt = xyz_DQH2OLiqDt - xyz_EvapQH2OLiq / ( 2.0_DP * DelTime )

    ! calculation for output
    xy_RainLsc     = 0.0_DP
    do k = kmax, 1, -1
      xy_RainLsc = xy_RainLsc                                     &
        & + xyz_DQH2OLiqDt(:,:,k) * ( xyr_Press(:,:,k-1) - xyr_Press(:,:,k) ) / Grav
    end do

    ! ãƒ’ã‚¹ãƒˆãƒªãƒ‡ãƒ¼ã‚¿å‡ºåŠ›
    ! History data output
    !
    call HistoryAutoPut( TimeN, 'RainLsc',    xy_RainLsc     )
    call HistoryAutoPut( TimeN, 'DTempDtLsc', xyz_DTempDtLsc )
    call HistoryAutoPut( TimeN, 'DQVapDtLsc', xyz_DQVapDtLsc )

    ! è¨ˆç®—æ™‚é–“è¨ˆæ¸¬ä¸€æ™‚åœæ¢
    ! Pause measurement of computation time
    !
    call TimesetClockStop( module_name )

  end subroutine SaturationAdjust

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

  subroutine SaturationAdjustInit( &
    & FlagSnow &
    & )
    !
    ! saturation_adjust ãƒ¢ã‚¸ãƒ¥ãƒ¼ãƒ«ã®åˆæœŸåŒ–ã‚’è¡Œã„ã¾ã™.
    ! NAMELIST#saturation_adjust_nml ã®èªã¿è¾¼ã¿ã¯ã“ã®æ‰‹ç¶šãã§è¡Œã‚ã‚Œã¾ã™.
    !
    ! "saturation_adjust" module is initialized.
    ! "NAMELIST#saturation_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

    ! é£½å’Œæ¯”æ¹¿ã®ç®—å‡º
    ! Evaluate saturation specific humidity
    !
    use saturate, only: SaturateInit

    ! å¤§è¦æ¨¡å‡çµ (éžå¯¾æµæ€§å‡çµ) (Manabe, 1965)
    ! Large scale condensation (non-convective condensation) (Le Treut and Li, 1991)
    use lscond, only : LScaleCondInit

    ! å®£è¨€æ–‡ ; Declaration statements
    !
    implicit none

    logical, intent(in) :: FlagSnow

    integer:: unit_nml        ! NAMELIST ãƒ•ã‚¡ã‚¤ãƒ«ã‚ªãƒ¼ãƒ—ãƒ³ç”¨è£…ç½®ç•ªå·.
                              ! Unit number for NAMELIST file open
    integer:: iostat_nml      ! NAMELIST èªã¿è¾¼ã¿æ™‚ã® IOSTAT.
                              ! IOSTAT of NAMELIST read

    ! NAMELIST å¤‰æ•°ç¾¤
    ! NAMELIST group name
    !
    namelist /saturation_adjust_nml/ &
      & FlagSublimation
          !
          ! ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆå€¤ã«ã¤ã„ã¦ã¯åˆæœŸåŒ–æ‰‹ç¶š "saturation_adjust#SaturationAdjustInit"
          ! ã®ã‚½ãƒ¼ã‚¹ã‚³ãƒ¼ãƒ‰ã‚’å‚ç…§ã®ã“ã¨.
          !
          ! Refer to source codes in the initialization procedure
          ! "saturation_adjust#SaturationAdjustInit" for the default values.
          !

    ! å®Ÿè¡Œæ–‡ ; Executable statement
    !

    if ( saturation_adjust_inited ) return

    ! ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆå€¤ã®è¨å®š
    ! Default values settings
    !
    FlagSublimation = .false.

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

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

    ! Initialization of modules used in this routine

    ! é£½å’Œæ¯”æ¹¿ã®ç®—å‡º
    ! Evaluate saturation specific humidity
    !
    call SaturateInit

    ! å¤§è¦æ¨¡å‡çµ (éžå¯¾æµæ€§å‡çµ) (Manabe, 1965)
    ! Large scale condensation (non-convective condensation) (Le Treut and Li, 1991)
    !
    call LScaleCondInit( &
      & FlagSnow &
      & )

    ! ãƒ’ã‚¹ãƒˆãƒªãƒ‡ãƒ¼ã‚¿å‡ºåŠ›ã®ãŸã‚ã®ã¸ã®å¤‰æ•°ç™»éŒ²
    ! Register of variables for history data output
    !
    ! HistoryAutoAddVariable is called in LScaleCond for variables below.
    !
!!$    call HistoryAutoAddVariable( 'RainLsc', &
!!$      & (/ 'lon ', 'lat ', 'time' /), &
!!$      & 'precipitation by large scale condensation', 'kg m-2 s-1' )
!!$    call HistoryAutoAddVariable( 'DTempDtLsc', &
!!$      & (/ 'lon ', 'lat ', 'sig ', 'time' /), &
!!$      & 'large-scale condensation heating', 'K s-1' )
!!$    call HistoryAutoAddVariable( 'DQVapDtLsc', &
!!$      & (/ 'lon ', 'lat ', 'sig ', 'time' /), &
!!$      & 'large-scale condensation moistening', 'kg kg-1 s-1' )

    ! å°å— ; Print
    !
    call MessageNotify( 'M', module_name, '----- Initialization Messages -----' )
    call MessageNotify( 'M', module_name, '  FlagSublimation = %b', l = (/ FlagSublimation /) )
    call MessageNotify( 'M', module_name, '-- version = %c', c1 = trim(version) )

    saturation_adjust_inited = .true.

  end subroutine SaturationAdjustInit

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

end module saturation_adjust