module yaeos__models_ar_volume_translations_ji_lempe
   !! Ji and Lempe's temperature-dependent volume translation for cubic EOS.
   !! \(c_i=c_{c,i} 0.35/(0.35+\eta_i|\alpha_i(T/T_{c,i})-T/T_{c,i}|^{\gamma_i})\).
   !! The original correlation was fitted to SRK; another cubic uses its own alpha.
   !!
   !! W.-R. Ji and D.A. Lempe, Fluid Phase Equilibria 130 (1997), 49–63.
   use yaeos__constants, only: pr
   use yaeos__models_ar_genericcubic, only: CubicEoS
   use yaeos__models_ar_volume_translated, only: VolumeTranslatedModel
   implicit none
   private

   public :: JiLempeVolumeTranslation

   type, extends(VolumeTranslatedModel) :: JiLempeVolumeTranslation
      !! Component shifts are additive in mole amounts.
      !! Construct with `JiLempeVolumeTranslation(base, vc, eta, gamma)`;
      !! `base` must be a cubic EOS and `vc` contains pure critical molar
      !! volumes in L/mol. The base volume is solved at each supplied Tc and Pc.
      !!
      !! The absolute-value correlation can have undefined temperature
      !! derivatives where alpha equals reduced temperature. For a simple
      !! zero, the first derivative is undefined for gamma <= 1, and the
      !! second is undefined for gamma < 2 (for nonzero cc*eta).
      !! Expressions are evaluated directly, without special values at the
      !! cusp or smoothing. Floating-point singularities propagate normally.
      real(pr), allocatable :: cc(:)
      !! Base critical molar volume minus supplied critical molar volume [L/mol].
      real(pr), allocatable :: eta(:)
      !! Dimensionless Ji–Lempe parameter.
      real(pr), allocatable :: gamma(:)
      !! Positive exponent of the absolute reduced-temperature distance.
   contains
      procedure :: translation => ji_lempe_translation
   end type JiLempeVolumeTranslation

   interface JiLempeVolumeTranslation
      module procedure :: new_ji_lempe
   end interface JiLempeVolumeTranslation

contains

   function new_ji_lempe(base, vc, eta, gamma) result(model)
      !! # JiLempeVolumeTranslation constructor
      !! Construct from a cubic EOS and experimental critical molar volumes.
      !!
      !! # Description
      !! The base volume is evaluated for each pure component at its Tc and Pc.
      !! Supply initialized cubic parameters and arrays in component order,
      !! with matching lengths, vc > 0, eta >= 0 and gamma > 0.
      class(CubicEoS), intent(in) :: base
      real(pr), intent(in) :: vc(:) !! Critical molar volumes [L/mol].
      real(pr), intent(in) :: eta(:) !! Nonnegative dimensionless parameters.
      real(pr), intent(in) :: gamma(:) !! Positive exponents.
      type(JiLempeVolumeTranslation) :: model
      real(pr) :: n(size(vc))
      real(pr) :: volume
      integer :: i

      call model%init(base)

      model%eta = eta
      model%gamma = gamma

      allocate(model%cc(size(vc)))

      do i = 1, size(vc)
         n = 0._pr
         n(i) = 1._pr
         call base%volume(n, base%components%Pc(i), base%components%Tc(i), volume, "stable")

         model%cc(i) = volume - vc(i)
      end do
   end function new_ji_lempe

   subroutine ji_lempe_translation(self, n, T, C, CT, CT2, Cn, CTn, Cn2)
      !! # Ji–Lempe shift and derivatives
      !! Evaluate C = sum(n_i*c_i) and its requested derivatives.
      !!
      !! # Description
      !! With q = alpha(Tr)-Tr and D = 0.35+eta*abs(q)**gamma:
      !! c = 0.35*cc/D, c_T = -0.35*cc*D_T/D**2 and
      !! c_TT = 0.35*cc*(2*D_T**2/D**3-D_TT/D**2).
      !! These expressions apply away from zeros of q. No limiting-value
      !! substitution is made at q=0; see the Ji–Lempe guide for differentiability.
      class(JiLempeVolumeTranslation), intent(in) :: self
      real(pr), intent(in) :: n(:) !! Component amounts [mol].
      real(pr), intent(in) :: T !! Temperature [K].
      real(pr), intent(out) :: C !! Extensive displacement [L].
      real(pr), optional, intent(out) :: CT !! Temperature derivative [L/K].
      real(pr), optional, intent(out) :: CT2 !! Second temperature derivative [L/K²].
      real(pr), optional, intent(out) :: Cn(size(n)) !! Molar shifts [L/mol].
      real(pr), optional, intent(out) :: CTn(size(n)) !! Shift slopes [L/(mol K)].
      real(pr), optional, intent(out) :: Cn2(size(n), size(n)) !! Zero amount Hessian [L/mol²].
      real(pr) :: tr(size(n))
      real(pr) :: alpha(size(n))
      real(pr) :: alpha_tr(size(n))
      real(pr) :: alpha_tr2(size(n))
      real(pr) :: ci(size(n))
      real(pr) :: ci_t(size(n))
      real(pr) :: ci_tt(size(n))
      real(pr) :: q
      real(pr) :: qt
      real(pr) :: qtt
      real(pr) :: distance
      real(pr) :: denom_t
      real(pr) :: denom_tt
      real(pr) :: denom
      integer :: i

      select type (base => self%base)
       class is (CubicEoS)
         tr = T / base%components%Tc
         call base%alpha%alpha(tr, alpha, alpha_tr, alpha_tr2)
         ci_t = 0._pr
         ci_tt = 0._pr
         do i = 1, size(n)
            q = alpha(i) - tr(i)
            distance = abs(q)
            denom = 0.35_pr + self%eta(i)*distance**self%gamma(i)
            ci(i) = self%cc(i)*0.35_pr/denom
            if (.not. (present(CT) .or. present(CT2) .or. present(CTn))) cycle

            ! Alpha derivatives are supplied with respect to Tr, not T.
            qt = (alpha_tr(i) - 1._pr)/base%components%Tc(i)
            qtt = alpha_tr2(i)/base%components%Tc(i)**2

            denom_t = self%eta(i)*self%gamma(i)*distance**(self%gamma(i)-1._pr)*sign(1._pr, q)*qt
            ci_t(i) = -0.35_pr*self%cc(i)*denom_t/denom**2

            if (present(CT2)) then
               denom_tt = self%eta(i)*self%gamma(i)*distance**(self%gamma(i)-2._pr) * &
                  ((self%gamma(i)-1._pr)*qt**2 + q*qtt)

               ci_tt(i) = 0.35_pr*self%cc(i)*(2._pr*denom_t**2/denom**3 - denom_tt/denom**2)
            end if
         end do
       class default
         error stop "JiLempe: base model must be cubic"
      end select

      C = dot_product(n, ci)
      if (present(CT)) CT = dot_product(n, ci_t)
      if (present(CT2)) CT2 = dot_product(n, ci_tt)
      if (present(Cn)) Cn = ci
      if (present(CTn)) CTn = ci_t
      if (present(Cn2)) Cn2 = 0._pr
   end subroutine ji_lempe_translation
end module yaeos__models_ar_volume_translations_ji_lempe
