!
! License-Identifier: GPL
!
! Copyright (C) 2006 The Yambo Team
!
! Authors (see AUTHORS file for details): AM
!
module functions
 !
 use pars, ONLY: SP
 implicit none
 !
 real(SP)     :: bose_E_cut
#if defined(_FUJITSU)
 logical, external :: isnan
#endif
 !
 interface
   !
   integer function Fermi_fnc_fit(RT_occ_in,nstates,T_fit,Ef_fit,err_fit,RT_occ_fit_out,RT_E_fit_out)
     !
     use pars, ONLY: SP
     !
     ! This function makes a fit of RT_occ_in to the Fermi-Dirac function using two
     ! temperature and two fermi level, one for the valence and one for the conduction
     !
     integer,  intent(in)  :: nstates
     real(SP), intent(in)  :: RT_occ_in(nstates)
     !
     real(SP), intent(out) :: T_fit(2)
     real(SP), intent(out) :: Ef_fit(2)
     real(SP), intent(out) :: err_fit(4)
     real(SP), intent(out), optional :: RT_occ_fit_out(1000,2)
     real(SP), intent(out), optional :: RT_E_fit_out(1000,2)
     !
   end function Fermi_fnc_fit
   !
 end interface
 !
 contains
   !
   logical function infinity(E)
     use pars, ONLY: infinity_dfl
     real(SP)     :: E
     infinity= E > infinity_dfl
   end function infinity
   !
   logical function NAN(E)
#if defined(_XLF) || defined(_PGI) || defined(_NV)
     use ieee_arithmetic
     real(SP), intent(in) :: E
     NAN= ieee_is_nan(E)
#else
     real(SP), intent(in) :: E
     NAN= isnan(E)
#endif
   end function NAN
   !
   real(SP) function theta_function(T,step,order)
     !
     ! This is an easy numerical implementation of the
     ! theta function and its derivatives (the delta and the sign).
     !
     integer :: order
     real(SP):: T,step
     character(4) :: step_case
     !
     theta_function=0._SP
     if (abs(T/step)>1.05_SP) then
       if(order==0.and.T>0._SP) theta_function= 1._SP
       return
     endif
     !
     if( abs(T/step+1.0_SP)<0.1 ) step_case="-1.0"
     if( abs(T/step+0.5_SP)<0.1 ) step_case="-0.5"
     if( abs(T/step+0.0_SP)<0.1 ) step_case=" 0.0"
     if( abs(T/step-0.5_SP)<0.1 ) step_case="+0.5"
     if( abs(T/step-1.0_SP)<0.1 ) step_case="+1.0"
     !
     select case(step_case)
     case("-1.0")
       if (order==0) theta_function= 0.00_SP
       if (order==1) theta_function= 0.00_SP
       if (order==2) theta_function= 1.00_SP/step**2
     case("-0.5")
       if (order==0) theta_function= 0.25_SP
       if (order==1) theta_function= 0.50_SP/step
       if (order==2) theta_function= 1.00_SP/step**2
     case(" 0.0")
       if (order==0) theta_function= 0.5_SP
       if (order==1) theta_function= 1.0_SP/step
       if (order==2) theta_function= 0.0_SP
     case("+0.5")
       if (order==0) theta_function= 0.75_SP
       if (order==1) theta_function= 0.50_SP/step
       if (order==2) theta_function=-1.00_SP/step**2
     case("+1.0")
       if (order==0) theta_function= 1.00_SP
       if (order==1) theta_function= 0.00_SP
       if (order==2) theta_function=-1.00_SP/step**2
     end select
     !
   end function
   !
   ! Lorentzian function
   !
   pure function Lorentzian_func(x, damp)
     !
     ! From Mathworld
     ! https://mathworld.wolfram.com/LorentzianFunction.html
     !
     use pars, ONLY:DP,pi
     real(SP), intent(in) :: x,damp
     real(SP) :: Lorentzian_func
     !
     ! Double-precision temporaries
     real(DP) :: xd, dd, val
     !
     xd = real(x, DP)
     dd = real(damp, DP)
     !
     val = (0.5_DP * dd) / (xd*xd + (0.5_DP*dd)**2) / real(pi, DP)
     !
     Lorentzian_func = real(val, SP)
     !  
   end function Lorentzian_func
   !
   pure function Gaussian_func(x, damp)
     !
     ! Normalized Gaussian Function
     ! damp is treated as FWHM (Full Width at Half Maximum)
     !
     use pars, ONLY:DP,pi
     real(SP), intent(in) :: x,damp
     real(SP) :: Gaussian_func
     !
     ! Double-precision temporaries
     real(DP) :: xd, dd, val, ln2
     !
     xd = real(x, DP)
     dd = real(damp, DP)
     ln2 = log(2.0_DP)
     !
     ! Normalized Gaussian formula using FWHM:
     ! val = sqrt(4*ln2 / (pi * dd**2)) * exp(-4*ln2 * xd**2 / dd**2)
     !
     val = sqrt(4.0_DP * ln2 / (real(pi, DP) * dd**2)) * &
           exp(-4.0_DP * ln2 * (xd**2 / dd**2))
     !
     Gaussian_func = real(val, SP)
     !  
   end function Gaussian_func
   !
   ! Fermi functions
   !-----------------
   !
   function Fermi_fnc(E,T)
     !
     use electrons, ONLY:filled_tresh
     real(SP)::E,T,Fermi_fnc
     Fermi_fnc=1._SP
     if (T==0._SP.and.E>0._SP) Fermi_fnc=0._SP
     !
     if (T/=0._SP) Fermi_fnc=1._SP/(1._SP+exp(E/T))
     !
     if (Fermi_fnc<filled_tresh)  Fermi_fnc=0._SP
     !
   end function
   !
   pure function Fermi_fnc_derivative(E,T)
     !
     ! This is the energy derivative of the Fermi-Dirac function.
     ! It can be considered and approximation to the delta function.
     !
     ! Note that the function defined here is integrated to 1.
     !
     real(SP) ::Fermi_fnc_derivative
     real(SP), intent(in) :: E,T
     real(SP),parameter :: tresh=0._SP
     Fermi_fnc_derivative=0._SP
     if (T/=0._SP) Fermi_fnc_derivative=1._SP/(2._SP+exp(E/T)+exp(-E/T))/T
     if (Fermi_fnc_derivative<tresh)  Fermi_fnc_derivative=0._SP
   end function
   !
   pure function Fermi_fnc_T_derivative(E,T)
     !
     ! This is the Temperature derivative of the Fermi-Dirac function.
     !
     real(SP) :: Fermi_fnc_T_derivative
     real(SP), intent(in) :: E,T
     real(SP),parameter :: tresh=0._SP
     Fermi_fnc_T_derivative=0._SP
     if (T/=0._SP) Fermi_fnc_T_derivative=E/(2._SP+exp(E/T)+exp(-E/T))/T**2
   end function
   !
   ! Bose functions
   !----------------
   !
   pure function bose_f(Eb)
     !
     use drivers,   ONLY:Finite_Tel
     use D_lattice, ONLY:Bose_Temp
     use electrons, ONLY:spin_occ
     real(SP), intent(in):: Eb
     real(SP)            :: bose_f
     bose_f=0.
     if (Eb<0.) bose_f=-spin_occ
     if (.not.Finite_Tel) return
     !
     if (abs(Eb)>epsilon(1.)) then
       if (abs(Eb)<=bose_E_cut*Bose_Temp) bose_f=spin_occ*Bose_Temp/Eb
       if (abs(Eb)> bose_E_cut*Bose_Temp) bose_f=spin_occ/(exp(Eb/Bose_Temp)-1.)
     else
       bose_f=spin_occ*Bose_Temp/epsilon(1.)
     endif
     !
   end function
   !
   pure function bose_decay(E)
     !
     use drivers,   ONLY:Finite_Tel
     !
     use D_lattice, ONLY:Tel
     real(SP), intent(in):: E
     real(SP)            :: bose_decay
     bose_decay=1.
     !
     if (.not.Finite_Tel) return
     if (abs(E)<=bose_E_cut*Tel) bose_decay=E**2/(Tel*bose_E_cut)**2
     !
   end function
   !
   ! Boltzman function
   !----------------
   !
   function boltzman_f(Eb)
     !
     use D_lattice, ONLY:Boltz_Temp
     use units,     ONLY:HA2EV,HA2KEL
     real(SP), intent(in):: Eb
     real(SP)            :: boltzman_f
     !
     real(SP) :: E_small=0.005/HA2EV  ! Threashold for degenerate excitons
     real(SP) :: T_small=1._SP/HA2KEL
     !
     if(abs(Eb)>E_small.and.abs(Boltz_Temp)>T_small) then
       boltzman_f=exp(-Eb/Boltz_Temp)  ! Normal case
     elseif(abs(Eb)>E_small.and.abs(Boltz_Temp)<=T_small) then
       boltzman_f=0._SP  ! Case  E>0 but T=0
     elseif(abs(Eb)<E_small) then
       boltzman_f=1._SP  ! Limit E=0 
     endif
     !
   end function

   !
   logical function K_scatter(E,Ep,Er,Dr)
     !
     real(SP)::E,Ep,Er(2),Dr(2),D
     K_scatter=.false.
     D=Dr(1)+(E-Er(1))/(Er(2)-Er(1))*(Dr(2)-Dr(1))
     D=max(D,0._SP)
     K_scatter=abs(E-Ep)<=D
   end function
   !
   integer function BZ_index(ik,k)
     !
     ! Returns the BZ index of a given ik in the IBZ
     !
     use R_lattice,      ONLY:bz_samp
     type(bz_samp) :: k
     integer       :: ik
     if (ik==1) BZ_index=1
     if (ik>1 ) BZ_index=1+sum(k%nstar(:ik-1))
   end function
   !
   pure function Lorentzian_FT(W,pole,ordering)
    !
    ! This subrutine returns the frequency dependent Green function
    ! which is the imaginary part of the
    ! Fourier transform of the Lorentzian function
    ! theta(t)*e^{-i*pole*t} [this is the retarded version, other ordering are computed]
    !
    ! AM,01/08/16. Note that aimag(pole)<0, while aimag(W)>0
    !
    ! DS,31/10/18. Note that the present structure, at finite q, uses the relation e_{n,k}=e_{n,-k},
    !              See Fetter-Walecka, p.158 from Eq.(12.29) to (12.30)
    !              Such relation is not always true. See for example magnetic systems with SOC and no SI.
    !              See also finite-q BSE where resonant and anti-resonant block are explicitly computed if needed
    !              via the flag l_BS_res_from_ares
    !
    !              Moreover, as used in Xo, it implies
    !              - f_{n,k}=f_{n,-k} (occupations)
    !              - R_{nm,k}=R_{nm,-k} (residuals, eventually with a star)
    !              For chi_rr, R_{nmk}=rho_{nm,k}
    !              There are two cases where this is not true:
    !              a) with SOC rho_{n,k}/=rho_{n,-k} if SI is not a symmetry of the system
    !              b) in NEQ f_{n,k}=f_{n,-k} may not be true
    !              
    !
    use pars, ONLY:SP
    !
    implicit none
    !
    complex(SP), intent(in)  :: pole,W
    character(*), intent(in) :: ordering
    complex(SP)  ::Lorentzian_FT
    !              
    logical      ::ord_t_ordered,ord_true_t_or,ord_retarded_,ord_resonant_,ord_ares_tord,ord_ares_reta
    !
    ord_t_ordered= trim(ordering)=="T"      ! T-ordered
    ord_true_t_or= trim(ordering)=="t"      ! T-ordered with null damping !DALV: true time ordering for MPA
    ord_retarded_= trim(ordering)=="R"      ! Retarded 
    ord_resonant_= trim(ordering)=="r"      ! Resonant      part of the T-ordered/Retarded
    ord_ares_tord= trim(ordering)=="Ta"     ! Anti-resonant part of the T-ordered
    ord_ares_reta= trim(ordering)=="Ra"     ! Anti-resonant part of the Retarded
    !
    !                                  RESONANT       ANTIRESONANT
    !
    if ( ord_t_ordered ) Lorentzian_FT=1._SP/(W-pole)-1._SP/(conjg(W)+      pole )
    if ( ord_true_t_or ) Lorentzian_FT=1._SP/(W-pole)-1._SP/(      W +      pole ) 
    if ( ord_retarded_ ) Lorentzian_FT=1._SP/(W-pole)-1._SP/(      W +conjg(pole))       
    if ( ord_resonant_ ) Lorentzian_FT=1._SP/(W-pole)
    if ( ord_ares_tord ) Lorentzian_FT=              -1._SP/(conjg(W)+      pole )
    if ( ord_ares_reta ) Lorentzian_FT=              -1._SP/(      W +conjg(pole))
    !
   end function
   !
   !> Maps the bare Lorentzian pole 1/Z to its Kramers-Kronig compliant Gaussian equivalent
   pure function gauss_pole(Z) result(res)
    use pars,	ONLY:SQRT_PI	
    complex(SP), intent(in) :: Z
    complex(SP)             :: res
    real(SP)                :: X, Y, X_over_Y
    real(SP), parameter     :: EPS = 1.0E-12_SP

    X = real(Z, kind=SP)
    Y = aimag(Z)

    if (abs(Y) < EPS) then
        ! Limit of zero broadening -> Principal value 1/X
        res = cmplx(1._SP / X, 0._SP, kind=SP)
    else
        X_over_Y = X / Y
        
        ! The imaginary part provides the pure Gaussian absorption/smearing.
        ! The real part uses Dawson's integral to preserve causality (Kramers-Kronig).
        res = cmplx( 2._SP / Y * dawson(X_over_Y), &
                    -SQRT_PI / Y * exp(-X_over_Y**2), kind=SP)
    end if
  end function gauss_pole

  !> High-precision approximation for Dawson's Integral F(x)
  pure function dawson(x) result(f)
    real(SP), intent(in) :: x
    real(SP)             :: f
    real(SP)             :: abs_x, x2

    abs_x = abs(x)
    x2 = x*x

    if (abs_x <= 2.5_SP) then
        ! Polynomial approximation for the core peak
        f = x * (1.0_SP + x2 * (-0.4_SP + x2 * (0.112_SP + x2 * (-0.024444444444444444_SP &
            + x2 * (0.004419047619047619_SP - x2 * 0.000673015873015873_SP)))))
    else
        ! Asymptotic limit for the tails. Notice how the limit 1/(2x) beautifully 
        ! recovers the 1/w dispersive decay of the original Lorentzian.
        f = sign(1.0_SP, x) * (0.5_SP / abs_x + 0.25_SP / (abs_x * x2) &
            + 0.75_SP / (abs_x * x2 * x2) + 3.75_SP / (abs_x * x2 * x2 * x2))
    end if
  end function dawson
   ! 
  pure function Gaussian_FT(W,pole,ordering)
    !
    ! Gaussian equivalent of the Lorentzian function
    ! 
    use pars, ONLY:SP
    !
    implicit none
    !
    complex(SP),  intent(in) :: pole,W
    character(*), intent(in) :: ordering
    complex(SP)  :: Gaussian_FT
    !              
    logical      ::ord_t_ordered,ord_true_t_or,ord_retarded_,ord_resonant_,ord_ares_tord,ord_ares_reta
    !
    ord_t_ordered= trim(ordering)=="T"      ! T-ordered
    ord_true_t_or= trim(ordering)=="t"      ! T-ordered with null damping !DALV: true time ordering for MPA
    ord_retarded_= trim(ordering)=="R"      ! Retarded 
    ord_resonant_= trim(ordering)=="r"      ! Resonant      part of the T-ordered/Retarded
    ord_ares_tord= trim(ordering)=="Ta"     ! Anti-resonant part of the T-ordered
    ord_ares_reta= trim(ordering)=="Ra"     ! Anti-resonant part of the Retarded
    !
    ! Initialize output
    Gaussian_FT = 0._SP
    !
    !                  RESONANT                            ANTIRESONANT
    !
    if ( ord_t_ordered ) Gaussian_FT =  gauss_pole(W - pole) - gauss_pole(conjg(W) + pole)
    if ( ord_true_t_or ) Gaussian_FT =  gauss_pole(W - pole) - gauss_pole(W + pole)
    if ( ord_retarded_ ) Gaussian_FT =  gauss_pole(W - pole) - gauss_pole(W + conjg(pole))
    if ( ord_resonant_ ) Gaussian_FT =  gauss_pole(W - pole)
    if ( ord_ares_tord ) Gaussian_FT =                       - gauss_pole(conjg(W) + pole)
    if ( ord_ares_reta ) Gaussian_FT =                       - gauss_pole(W + conjg(pole))
    !
  end function Gaussian_FT ! Gaussian equivalent of the Lorentzian one

end module
