!= 
!
!= Slab ocean sea ice thermal budget
!
! Authors::   Yoshiyuki O. TAKAHASHI
! Version::   $Id: gridset.F90,v 1.4 2026/06/05 22:00:00 takepiro Exp $ 
! Tag Name::  $Name:  $
! Copyright:: Copyright (C) GFD Dennou Club, 2013-2026. All rights reserved.
! License::   See COPYRIGHT[link:../../../COPYRIGHT]
!

module sosi_dynamics
  !
  != 
  !
  != Slab sea ice horizontal transport
  !
  ! <b>Note that Japanese and English are described in parallel.</b>
  !
  ! Horizontal transport of slab sea ice (sea ice on slab ocean) is calculated
  ! based on diffusion.
  !
  !== Procedures List
  !
  ! SOSIDynamics     :: スラブオーシャンメイン
  ! SOSIDynamicsInit :: スラブオーシャン初期化
  ! ---------------------     :: ------------
  ! SOSIDynamics     :: Main subroutine for SOSI
  ! SOSIDynamicsInit :: Initialization for SOSI
  !
  !== NAMELIST
  !
  ! NAMELIST#
  !
  !== References
  !
  !
  ! モジュール引用 ; USE statements
  !
  ! 種別型パラメタ
  ! Kind type parameter
  !
  use dc_types, only: DP,  & ! 倍精度実数型. Double precision.
    &                 TOKEN  ! キーワード.   Keywords. 

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

  !
  ! MPI
  !
  use mpi_wrapper, only : MPIWrapperFindMaxVal

  ! 格子点設定
  ! 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
    &                ksimax  ! 海氷の鉛直層数.
                             ! Number of sea ice vertical level

  ! 組成に関わる配列の設定
  ! Settings of array for atmospheric composition
  !
  use composition, only:                              &
    &                    ncmax
                             ! 成分の数
                             ! Number of composition

  ! 質量の補正
  ! Mass fixer
  !
!!$  use mass_fixer, only: &
!!$    & MassFixerBC02, MassFixerBC02Layer, MassFixerBC02Column, &
!!$    & MassFixer, MassFixerR95, MassFixerWO94, MassFixerColumn!, MassFixerLayer


  ! 宣言文 ; Declaration statements
  !
  implicit none
  private

  ! 公開手続き
  ! Public procedure
  !
  public :: SOSIDynamics
  public :: SOSIDynamicsInit


  ! 公開変数
  ! Public variables
  !

  ! 非公開変数
  ! Private variables
  !
  logical, save      :: FlagSlabOcean
  ! flag for use of slab ocean

  real(DP)    , save              :: SOSeaIceDiffCoef

  logical, save :: sosi_dynamics_inited = .false.
                              ! 初期設定フラグ.
                              ! Initialization flag


  character(*), parameter:: module_name = 'sosi_dynamics'
                              ! モジュールの名称.
                              ! Module name
  character(*), parameter:: version = &
    & '$Name:  $' // &
    & '$Id: sltt.F90,v 1.8 2026/06/06 22:00:00 takepiro Exp $'
                              ! モジュールのバージョン
                              ! Module version


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

contains

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

  subroutine SOSIDynamics(                                &
    & xy_SurfType,                                        & !(in   )
    & xy_SurfTemp, xy_SOSeaIceMass, xyz_SOSeaIceTemp,     & !(inout)
    & xy_DSOSeaIceMassDtPhyTop, xy_DSOSeaIceMassDtPhyBot, & !(in   )
    & xyz_DSOSeaIceTempDtPhy                              & !(in   )
    & )
    ! 
    ! Calculates slab sea ice horizontal transports by diffusion

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

    use timeset    , only : &
      & DelTime
                              ! $\Delta t$

    ! 物理・数学定数設定
    ! Physical and mathematical constants settings
    !
    use constants0, only: &
      & WaterHeatCap

    ! 物理定数設定
    ! Physical constants settings
    !
    use constants, only: &
      & SOMass
                              ! Slab ocean mass

    ! 雪と海氷の定数の設定
    ! Setting constants of snow and sea ice
    !
    use constants_snowseaice, only: &
      & TempCondWater,              &
      & SeaIceDen,                  &
      & SeaIceHeatCap,              &
      & TempBelowSeaIce,            &
      & SOSeaIceThresholdMass,      &
      & LatentHeatFusionBelowSeaIce

    !
    ! Slab ocean sea ice utility module
    !
    use sosi_utils, only :             &
      & SOSIUtilsChkSOSeaIce,          &
      & SOSIUtilsSetSOSeaIceLevels,    &
      & SOSeaIceMassNegativeThreshold, &
      & SOSIUtilsAddPhysics


    ! 宣言文 ; Declaration statements
    !
    integer , intent(in ) :: xy_SurfType       (0:imax-1, 1:jmax)
                              ! 土地利用.
                              ! Surface index
    real(DP), intent(inout) :: xy_SurfTemp        (0:imax-1, 1:jmax)
    real(DP), intent(inout) :: xy_SOSeaIceMass    (0:imax-1, 1:jmax)
                              ! $ M_si $ . 海氷質量 (kg m-2)
                              ! Slab ocean sea ice mass (kg m-2)
    real(DP), intent(inout) :: xyz_SOSeaIceTemp   (0:imax-1, 1:jmax, 1:ksimax)
    real(DP), intent(in   ) :: xy_DSOSeaIceMassDtPhyTop(0:imax-1, 1:jmax)
    real(DP), intent(in   ) :: xy_DSOSeaIceMassDtPhyBot(0:imax-1, 1:jmax)
                              !
                              ! Slab sea ice mass at next time step
    real(DP), intent(in   ) :: xyz_DSOSeaIceTempDtPhy(0:imax-1, 1:jmax, 1:ksimax)


    ! 作業変数
    ! Work variables
    !
    real(DP) :: xy_SurfTempSave     (0:imax-1, 1:jmax)
    real(DP) :: xy_SOSeaIceMassSave (0:imax-1, 1:jmax)
    real(DP) :: xyz_SOSeaIceTempSave(0:imax-1, 1:jmax, ksimax)

    real(DP) :: xy_SOSeaIceThickness(0:imax-1, 1:jmax)

    real(DP) :: xyz_SOSeaIceThickness(0:imax-1, 1:jmax, 1:ksimax)
                 !
                 ! Sea ice thickness
    integer  :: xy_SOSILocalKMax  (0:imax-1, 1:jmax)
    real(DP) :: xyr_SOSILocalDepth(0:imax-1, 1:jmax, 0:ksimax)
    real(DP) :: xyz_SOSILocalDepth(0:imax-1, 1:jmax, 1:ksimax)

!!$    real(DP) :: xy_SeaIceThicknessA(0:imax-1, 1:jmax)
                 !
                 ! Sea ice thickness
!!$    integer  :: xy_SOSILocalKMaxA  (0:imax-1, 1:jmax)
!!$    real(DP) :: xyr_SOSILocalDepthA(0:imax-1, 1:jmax, 0:ksimax)
!!$    real(DP) :: xyz_SOSILocalDepthA(0:imax-1, 1:jmax, 1:ksimax)

    logical  :: xy_FlagSlabOcean(0:imax-1, 1:jmax)

    real(DP) :: xyz_DSOSeaIceThicknessDt(0:imax-1, 1:jmax, 1:ksimax)
    real(DP) :: xyz_DSOSeaIceTempDt     (0:imax-1, 1:jmax, 1:ksimax)
    real(DP) :: xy_DSOTempDt            (0:imax-1, 1:jmax)

!!$    real(DP) :: xy_DSOSeaIceMassDt(0:imax-1, 1:jmax)
!!$                              !
!!$                              ! Slab sea ice mass tendency

    real(DP) :: xy_SOTemp               (0:imax-1, 1:jmax)

    real(DP) :: xyz_SOSeaIceThicknessAdv(0:imax-1, 1:jmax, 1:ksimax)
    real(DP) :: xyz_SOSeaIceTempAdv     (0:imax-1, 1:jmax, 1:ksimax)
    real(DP) :: xy_SOTempAdv            (0:imax-1, 1:jmax)

    real(DP) :: xyz_SOSIMassEachLayer(0:imax-1, 1:jmax, 1:ksimax)

    real(DP) :: SOSIMass
    real(DP) :: SOSIMass1L
    real(DP) :: DelSOSIMass

    real(DP) :: SOTempTent
    real(DP) :: SOTempTent1st

    logical, parameter :: FlagSOSIAdv = .false.

    logical  :: FlagCalc

    integer:: i               ! 東西方向に回る DO ループ用作業変数
                              ! Work variables for DO loop in zonal direction
    integer:: j               ! 南北方向に回る DO ループ用作業変数
                              ! Work variables for DO loop in meridional direction
    integer:: k


    if ( .not. sosi_dynamics_inited ) then
      call MessageNotify( 'E', module_name, 'This module has not been initialized.' )
    end if


    ! add physics tendency
    call SOSIUtilsAddPhysics(                         &
      & xy_SOSeaIceMass, xyz_SOSeaIceTemp,            & !(inout)
      & xy_DSOSeaIceMassDtPhyTop, xy_DSOSeaIceMassDtPhyBot, & !(in   )
      & xyz_DSOSeaIceTempDtPhy                           & !(in   )
      & )


    xy_FlagSlabOcean = .false.
    FlagCalc         = .false.
    if ( FlagSlabOcean ) then
      do j = 1, jmax
        do i = 0, imax-1
          if ( xy_SurfType(i,j) <= 0 ) then
            ! slab ocean
            xy_FlagSlabOcean(i,j) = .true.
            FlagCalc              = .true.
          end if
        end do
      end do
    end if

    if ( SOSeaIceDiffCoef <= 0.0_DP ) then
      FlagCalc = .false.
!!$    else
!!$      call MessageNotify( 'E', module_name, &
!!$        & '  Now, SOSeaIceDiffCoef has to be zero.' )
    end if

    if ( .not. FlagCalc ) then
       return
    end if

  end subroutine SOSIDynamics

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

  subroutine SOSIDynamicsInit( &
    & ArgFlagSlabOcean &
    & )
    ! flag for use of slab ocean
    ! 
    ! Initialization of module


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

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

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

    use mpi_wrapper   , only : myrank, nprocs

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

    ! 組成に関わる配列の設定
    ! Settings of array for atmospheric composition
    !
    use composition, only:                              &
      &                    ncmax
                             ! 成分の数
                             ! Number of composition

    ! 座標データ設定
    ! Axes data settings
    !
    use axesset, only: &
      & x_Lon, y_Lat, &
      & AxNameX, AxNameY, AxNameZ, AxNameT

    use constants0, only : PI

    ! 雪と海氷の定数の設定
    ! Setting constants of snow and sea ice
    !
    use constants_snowseaice, only: &
      & ConstantsSnowSeaIceInit

    !
    ! Slab ocean sea ice utility module
    !
    use sosi_utils, only : SOSIUtilsInit

    ! メッセージ制御
    ! Message control
    !
    use mpi_messagecntl, only : DoesOutputMPIMessage


    logical, intent(in ) :: ArgFlagSlabOcean


    !
    ! local variables
    !
    integer:: i               ! 東西方向に回る DO ループ用作業変数
                              ! Work variables for DO loop in zonal direction
    integer:: j               ! 南北方向に回る DO ループ用作業変数
                              ! Work variables for DO loop in meridional direction

    integer:: unit_nml        ! NAMELIST ファイルオープン用装置番号. 
                              ! Unit number for NAMELIST file open
    integer:: iostat_nml      ! NAMELIST 読み込み時の IOSTAT. 
                              ! IOSTAT of NAMELIST read
    ! NAMELIST 変数群
    ! NAMELIST group name
    !
    namelist /sosi_dynamics_nml/ &
      & SOSeaIceDiffCoef


    ! 実行文 ; Executable statement
    !

    if ( sosi_dynamics_inited ) return



    FlagSlabOcean = ArgFlagSlabOcean


    if ( mod( jmax, 2 ) /= 0 ) then
      stop 'jmax cannot be divided by 2.'
    end if


    ! Initialization of modules used in this module
    !

    ! 雪と海氷の定数の設定
    ! Setting constants of snow and sea ice
    !
    call ConstantsSnowSeaIceInit

    !
    ! Slab ocean sea ice utility module
    !
    call SOSIUtilsInit


    ! デフォルト値の設定
    ! Default values settings
    !
    SOSeaIceDiffCoef              =  0.0e0_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 = sosi_dynamics_nml, &  ! (out)
        & iostat = iostat_nml )       ! (out)
      close( unit_nml )

      call NmlutilMsg( iostat_nml, module_name ) ! (in)
      if ( iostat_nml == 0 .AND. DoesOutputMPIMessage() ) write( STDOUT, nml = sosi_dynamics_nml )
    end if


    ! ヒストリデータ出力のためのへの変数登録
    ! Register of variables for history data output
    !
!!$    do n = 1, ncmax
!!$      call HistoryAutoAddVariable( 'SLD'//trim(a_QMixName(n))//'DtHorMassFix', &
!!$        & (/ AxNameX, AxNameY, AxNameZ, AxNameT /), &
!!$        & 'tendency of horizontal mass fix of '//trim(a_QMixName(n)), 's-1' )
!!$      call HistoryAutoAddVariable( 'SLD'//trim(a_QMixName(n))//'DtVerMassFix', &
!!$        & (/ AxNameX, AxNameY, AxNameZ, AxNameT /), &
!!$        & 'tendency of vertical mass fix of '//trim(a_QMixName(n)), 's-1' )
!!$      call HistoryAutoAddVariable( 'SLD'//trim(a_QMixName(n))//'DtTotMassFix', &
!!$        & (/ AxNameX, AxNameY, AxNameZ, AxNameT /), &
!!$        & 'tendency of mass fix of '//trim(a_QMixName(n)), 's-1' )
!!$    end do


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

    sosi_dynamics_inited = .true.

  end subroutine SOSIDynamicsInit

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

end module sosi_dynamics

