!= 地下における熱の鉛直拡散
!
!= Vertical diffusion of heat under the ground
!
! Authors::   Yoshiyuki O. Takahashi
! Version::   $Id: subsurface_diffusion_heat.f90,v 1.3 2009-08-04 09:42:36 yot Exp $
! Tag Name::  $Name: dcpam5-20100424 $
! Copyright:: Copyright (C) GFD Dennou Club, 2008-2009. All rights reserved.
! License::   See COPYRIGHT[link:../../../COPYRIGHT]
!

module subsurface_diffusion_heat
  !
  != 地下の鉛直拡散
  !
  != Vertical diffusion under the ground
  !
  ! <b>Note that Japanese and English are described in parallel.</b>
  !
  !== Procedures List
  !
  ! PhyImplTendency      :: 時間変化率の計算
  ! ------------         :: ------------
  ! PhyImplTendency      :: Calculate tendency
  !
  !--
  !== NAMELIST
  !
  ! NAMELIST#phy_implicit_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
    &                  kslmax  ! 地下の鉛直層数. 
                               ! Number of subsurface 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:: SubsurfaceDiffusion

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

  ! 非公開変数
  ! Private variables
  !
  character(*), parameter:: module_name = 'subsurface_diffusion_heat'
                              ! モジュールの名称. 
                              ! Module name
  character(*), parameter:: version = &
    & '$Name: dcpam5-20100424 $' // &
    & '$Id: subsurface_diffusion_heat.f90,v 1.3 2009-08-04 09:42:36 yot Exp $'
                              ! モジュールのバージョン
                              ! Module version

  real(DP), allocatable, save, public:: xy_SoilSpecHeat    (:,:)
                              ! Specific heat of soil (J K-1 kg-1)
  real(DP), allocatable, save, public:: xy_SoilRho         (:,:)
                              ! Density of soil (kg m-3)
  real(DP), allocatable, save, public:: xy_SoilHeatCap     (:,:)
                              ! Volumetric heat capacity of soil (J m-3 K-1)
  real(DP), allocatable, save, public:: xy_SoilHeatDiffCoef(:,:)
                              ! Heat conduction coefficient of soil (J K-1 m-1 s-1)


  ! INTERFACE 文 ; INTERFACE statements
  !
!!$  interface PhyImplTendency
!!$    module procedure PhyImplTendency
!!$  end interface

contains

  subroutine SubsurfaceDiffusion(              &
    & xy_GroundTempFlux,                       &          ! (in )
    & xy_SurfTemp, xyz_SoilTemp,               &          ! (in )
    & xyr_SoilTempTransCoef, xyr_SoilTempFlux  &          ! (out)
    & )
    !
    ! 時間変化率の計算を行います. 
    !
    ! Calculate tendencies. 
    !

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

    ! 時刻管理
    ! Time control
    !
    use timeset, only: &
      & TimesetClockStart, TimesetClockStop

    ! 座標データ設定
    ! Axes data settings
    !
    use axesset, only: &
      r_SSDepth, & ! subsurface grid on interface of layer
      z_SSDepth    ! subsurface grid at midpoint of layer


    ! 時刻管理
    ! Time control
    !

    ! 宣言文 ; Declaration statements
    !
    implicit none

    real(DP), intent(in ):: xy_GroundTempFlux (0:imax-1, 1:jmax)
                              ! 地中熱フラックス. 
                              ! Ground temperature flux
    real(DP), intent(in ):: xy_SurfTemp (0:imax-1, 1:jmax)
                              ! 地表面温度. 
                              ! Surface temperature
    real(DP), intent(in ):: xyz_SoilTemp (0:imax-1, 1:jmax, 1:kslmax)
                              ! 土壌温度 (K)
                              ! Soil temperature (K)
    real(DP), intent(out):: xyr_SoilTempTransCoef (0:imax-1, 1:jmax, 0:kslmax)
                              ! 輸送係数：土壌温度.
                              ! Transfer coefficient: soil temperature
    real(DP), intent(out):: xyr_SoilTempFlux (0:imax-1, 1:jmax, 0:kslmax)
                              ! 土壌の熱フラックス. 
                              ! Heat flux in sub-surface soil



    ! 作業変数
    ! Work variables
    !
    integer:: k               ! 鉛直方向に回る DO ループ用作業変数
                              ! Work variables for DO loop in vertical direction

    ! 実行文 ; Executable statement
    !

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

    ! 初期化
    ! Initialization
    !
    if ( .not. subsurface_diffusion_inited ) call SubsurfaceDiffusionInit


    ! 土壌温度計算用の輸送係数の計算
    ! Calculate transfer coefficient for heat diffusion in the soil
    !
    k = 0
    if ( kslmax == 0 ) then
      ! This line is used when kslmax == 0, because z_SSDepth(k+1) does not exist. 
      xyr_SoilTempTransCoef(:,:,k) = 0.0d0
    else
      xyr_SoilTempTransCoef(:,:,k) = &
        & xy_SoilHeatDiffCoef(:,:) / ( z_SSDepth(k+1) - 0.0d0 )
    end if
    do k = 1, kslmax-1
      xyr_SoilTempTransCoef(:,:,k) = &
        & xy_SoilHeatDiffCoef(:,:) / ( z_SSDepth(k+1) - z_SSDepth(k) )
    end do
    k = kslmax
    xyr_SoilTempTransCoef(:,:,k) = 0.0d0


    ! 土壌中の熱フラックスの計算
    ! Calculate heat flux in sub-surface soil
    !
    k = 0
    if ( kslmax == 0 ) then
      ! This line is used when kslmax == 0, because xyz_SoilTemp(:,:,k+1) does not exist. 
      xyr_SoilTempFlux(:,:,k) = 0.0d0
    else
      xyr_SoilTempFlux(:,:,k) = &
        & - xyr_SoilTempTransCoef(:,:,k) * ( xyz_SoilTemp(:,:,1) - xy_SurfTemp(:,:) )
    end if
    do k = 1, kslmax-1
      xyr_SoilTempFlux(:,:,k) =                               &
        & - xyr_SoilTempTransCoef(:,:,k)                      &
        &   * ( xyz_SoilTemp(:,:,k+1) - xyz_SoilTemp(:,:,k) )
    end do
    k = kslmax
    xyr_SoilTempFlux(:,:,k) = xy_GroundTempFlux


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

  end subroutine SubsurfaceDiffusion

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

  subroutine SubsurfaceDiffusionInit
    !
    ! subsurface_diffusion_heat モジュールの初期化を行います. 
    ! NAMELIST#subsurface_diffusion_heat_nml の読み込みはこの手続きで行われます. 
    !
    ! "subsurface_diffusion_heat" module is initialized. 
    ! "NAMELIST#subsurface_diffusion_heat_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

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

    ! NAMELIST 変数群
    ! NAMELIST group name
    !
!!$    namelist /phy_implicit_nml/
!!$          !
!!$          ! デフォルト値については初期化手続 "phy_implicit#PhyImplInit" 
!!$          ! のソースコードを参照のこと. 
!!$          !
!!$          ! Refer to source codes in the initialization procedure
!!$          ! "phy_implicit#PhyImplInit" for the default values. 
!!$          !

    ! 実行文 ; Executable statement
    !

    if ( subsurface_diffusion_inited ) return
!!$    call InitCheck

    ! デフォルト値の設定
    ! Default values settings
    !

    ! 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 = phy_implicit_nml, &  ! (out)
!!$        & iostat = iostat_nml )   ! (out)
!!$      close( unit_nml )
!!$
!!$      call NmlutilMsg( iostat_nml, module_name ) ! (in)
!!$    end if



    allocate( xy_SoilSpecHeat    ( 0:imax-1, 1:jmax ) )
    allocate( xy_SoilRho         ( 0:imax-1, 1:jmax ) )
    allocate( xy_SoilHeatCap     ( 0:imax-1, 1:jmax ) )
    allocate( xy_SoilHeatDiffCoef( 0:imax-1, 1:jmax ) )


    xy_SoilSpecHeat     = 1.0d100     ! This variable is not used.
    xy_SoilRho          = 1.0d100     ! This variable is not used.

    xy_SoilHeatCap      = 2.1d6
    ! J m-3 K-1
    ! Value of Clay for porosity f=0.4, volumetric wetness theta=0.2 in Table 12.3 by 
    ! Hillel (2004). 
    ! Note that the unit of Table 12.3 of Hillel (2004) would be wrong. Although the 
    ! unit in the Table is wrong, the volumetric heat capacity of 2.1d6 J m-3 K-1 is 
    ! within the range of typical value of it. 

    xy_SoilHeatDiffCoef = 1.2d0
    ! W m-1 K-1
    ! Value of Clay for porosity f=0.4, volumetric wetness theta=0.2 in Table 12.3 by 
    ! Hillel (2004). 

    ! Reference
    !
    ! Hillet, D., 
    !   Introduction to Environmental Soil Physics, 
    !   Elsevier Academic Press, pp494, 2004.


    ! 印字 ; Print
    !
    call MessageNotify( 'M', module_name, '----- Initialization Messages -----' )
    call MessageNotify( 'M', module_name, '-- version = %c', c1 = trim(version) )

    subsurface_diffusion_inited = .true.

  end subroutine SubsurfaceDiffusionInit

  !-------------------------------------------------------------------
!!$
!!$  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 subsurface_diffusion_heat
