!
! License-Identifier: GPL
!
! Copyright (C) 2026 The Lumen Team
!
! Authors (see AUTHORS file for details): TQ
!
! headers
!
!
#include<y_memory.h>
!
!
subroutine shift_current(Xen,Xk,Xq)
 !
 use pars,            ONLY:SP,pi,cZERO,rZERO,cI,schlen
 use parser_m,        ONLY:parser
 use R_lattice,       ONLY:bz_samp
 use electrons,       ONLY:levels
 use LIVE_t,          ONLY:live_timing
 use vec_operate,     ONLY:v_norm,v_rotate
 use ALLOC,           ONLY:DIPOLE_ALLOC_elemental
 use YPP_post_bse,    ONLY:PB_conf,DIP_plane,Def_DIP_dir,&
&                          RES_right,exc_exc_E,sc_ijk,&
&                          logi_EPS,EPS_label,Exc_Range,BS_mat_q,&
&                          Zeroing_Disconnected_cut,eq_res,RES_V_right,RES_R_right,eq_res_gra
 use YPPm,            ONLY:DIPs,BS_E
 use X_m,             ONLY:global_gauge
 use BS,              ONLY:BS_bands,BS_K_dim,BS_H_dim
 use BS_solvers,      ONLY:BSS_n_eig,BS_mat
 use frequency,       ONLY:w_samp
 use parallel_int,    ONLY:PARALLEL_global_indexes,PP_redux_wait,PARALLEL_index
 use parallel_m,      ONLY:PAR_COM_DIPk_ibz_INDEX,PAR_COM_DIPk_ibz_A2A,PP_indexes,PP_indexes_reset,&
&                         par_dipk_bz_index
 use wave_func,       ONLY:WF_phases_b_map
 use stderr,          ONLY:STRING_match,STRING_same
 use com,             ONLY:msg
 use units,           ONLY:HA2EV
 use DIPOLES,         ONLY:eval_OVERLAPS
 use y_memory_alloc
 !
 implicit none
 !
 type(levels)      :: Xen
 type(bz_samp)     :: Xk,Xq
 !
 ! Work space 
 !
 type(w_samp)            :: W_bss,W_bssm
 integer                 :: N_trans,io_err,i_trans,i1,i_l_refer2,i_m,&
&                           N_DIP_dirs,i_dir,j_dir,N_res,DIP_dir_table(3),i_l_refer,&
&                           io_err_Overlaps,sc_dir1,sc_dir2,sc_dir3,&
&                           exc_range_save(2)
 real(SP)                :: DIP_dir(3,3),N_sum,delta_w,dE
 complex(SP),allocatable :: den3a(:),den3b(:)
 real(SP),external       :: FREQUENCIES_damping
 logical                 :: l_Gradient_A
 type(PP_indexes)        :: PX_bs

 !
 call section("+","Shift current with excitons")

 ! only work for TDA
 if (BS_K_dim(1)>0 .and. BS_H_dim/=BS_K_dim(1)) then
   call warning("Shift current implemented only for TDA BSE")
   return
 endif
 ! Dimensions, Constant, Logicals and allocs
 !
 ! ...logicals
 global_gauge='length'
 call parser("GradientA", l_Gradient_A)
 eval_OVERLAPS = .true.
 sc_dir1=2
 sc_dir2=2
 sc_dir3=2
 ! ...transitions
 !
 !
 N_sum = 0
 !
 ! map k and q
 call k_build_up_BZ_tables(Xq)
 call k_build_up_BZ_tables(Xk)
 !
 call build_inverse_BS_eh_table_from_BSS_table(Xk%nbz)
 !
 !
 ! Setup of Report
 !
 DIPs%ib =BS_bands
 !
 ! Par Setup
 !
 if (.not. allocated(par_dipk_bz_index)) then
   call PARALLEL_global_indexes(Xen,Xk,Xq," ",RESET=.TRUE.)
   call PARALLEL_global_indexes(Xen,Xk,Xq,"DIPOLES",Dip=DIPs)
 endif
 !
 ! Dipoles...
 !------------
 !
 ! ... EPS_ij components, which written in input gives true
 do i_dir=1,3
   do j_dir=1,3
     logi_EPS(i_dir,j_dir)=STRING_match(DIP_plane,EPS_label(i_dir,j_dir))
     if (STRING_match(DIP_plane,"all"))  logi_EPS(i_dir,j_dir)=.TRUE.
   enddo
 enddo
 if (STRING_same(DIP_plane,"none"))  logi_EPS(1,1)=.TRUE.
 !
 ! ... # of DIPOLE directions to compute
 ! N_DIP_dirs number 1-3
 N_DIP_dirs=0
 DIP_dir_table=0
 do i_dir=1,3
   if (any(logi_EPS(i_dir,:)).or.any(logi_EPS(:,i_dir))) then
     N_DIP_dirs=N_DIP_dirs+1
     DIP_dir_table(N_DIP_dirs)=i_dir
   endif
 enddo
 !
 ! ... computing directions
 DIP_dir=rZERO
 call msg('s','Creating '//trim(DIP_plane)//' related dipole directions')
 call msg('s','Dipole direction seed (defines `x` axis)',Def_DIP_dir)
 !
 Def_DIP_dir=Def_DIP_dir/v_norm( Def_DIP_dir )
 !
 !
 do i_dir=1,N_DIP_dirs
   if (DIP_dir_table(i_dir)==1) DIP_dir(i_dir,:)=Def_DIP_dir
   if (DIP_dir_table(i_dir)==2) call v_rotate("xy",-pi/2._SP,Def_DIP_dir,v_out=DIP_dir(i_dir,:))
   if (DIP_dir_table(i_dir)==3) call v_rotate("xz",-pi/2._SP,Def_DIP_dir,v_out=DIP_dir(i_dir,:))
 enddo
 !
 ! ... I/O
 call DIPOLE_IO(Xk,Xen,DIPs,'read',io_err,'DIP')
 if (io_err/=0) call error(" Dipoles not found")
 !
 if (DIPs%bands_ordered) &
 &  call error(" Dipoles need with bands_ordered=.false. for inter-exciton transitions")
 !
 ! build equbrim <0|r|n>
 !
 !
 !-----get phase fixing
 if (l_Gradient_A) then
   ! temperaly use DIPs%ib
   DIPs%ib(1)=1
   ! only read
   io_err_Overlaps=-1
   if (eval_OVERLAPS) then
     call OVERLAPS_IO(Xk,Xen,Dips,'check',io_err_Overlaps,'DIP')
     if (io_err_Overlaps/=0)  then
       call error(" Overlaps not found")
     else
       call OVERLAPS_IO(Xk,Xen,DIPs,'read',io_err_Overlaps,'DIP')
     endif
   endif
   !
   call load_qr_allk(Xen,Xk,Dips%ib(2),max(Zeroing_Disconnected_cut,0.001/HA2EV))
   !
   call DIPOLE_ALLOC_elemental('DIP_S')
   !
   DIPs%ib =BS_bands
 endif ! phase fixing
 !
 ! Allocations
 !
 ! ... Residuals 
 N_res=1
 YAMBO_ALLOC(RES_right,(BSS_n_eig*N_res,N_DIP_dirs,2)) ! (BSE/IP or BSE/EXC, i_dir , Res/delta_Res)
 YAMBO_ALLOC(RES_V_right,(BSS_n_eig*N_res,N_DIP_dirs,2))
 YAMBO_ALLOC(RES_R_right,(BSS_n_eig*N_res,N_DIP_dirs,2))
 YAMBO_ALLOC(eq_res,(BSS_n_eig*N_res,N_DIP_dirs))
 YAMBO_ALLOC(eq_res_gra,(BSS_n_eig*N_res,N_DIP_dirs))
 !
 ! ... Energies
 N_res=1
 YAMBO_ALLOC(exc_exc_E,(BSS_n_eig*N_res))
 !
 ! ... Observables
 YAMBO_ALLOC(sc_ijk,(PB_conf%W_n_steps,4))
 sc_ijk=cZERO
 !
 ! ... BS_mat_q to store rotated wave functions of exciton
 YAMBO_ALLOC(BS_mat_q,(BS_H_dim,BSS_n_eig))
 !
 !
 !
 ! Frequency setup by self
 !
 W_bss%er=PB_conf%X_W_range
 W_bss%n_freqs=PB_conf%W_n_steps
 W_bss%per_memstps=100._SP
 W_bss%dr=PB_conf%damp_factor
 !
 if (W_bss%er(2)==W_bss%er(1)) W_bss%n_freqs=1
 W_bss%n_freqs=nint(W_bss%per_memstps*real(W_bss%n_freqs)/100._SP)
 !
 YAMBO_ALLOC(W_bss%p,(W_bss%n_freqs))
 YAMBO_ALLOC(W_bssm%p,(W_bss%n_freqs))
 YAMBO_ALLOC(den3a,(W_bss%n_freqs))
 YAMBO_ALLOC(den3b,(W_bss%n_freqs))
 !
 W_bss%p(1)=cmplx(W_bss%er(1),W_bss%dr(1),SP)
 if (W_bss%n_freqs==1) then
     W_bss%er(2)=W_bss%er(1)
     W_bss%dr(2)=W_bss%dr(1)
     return
 endif
 !
 delta_w=(W_bss%er(2)-W_bss%er(1))/(W_bss%n_freqs-1)
 !
 forall (i1=1:W_bss%n_freqs-1) W_bss%p(i1+1)=cmplx(W_bss%er(1)+delta_w*real(i1,SP),0.,SP)
 !
 do i1=1,W_bss%n_freqs
   W_bss%p(i1)=real(W_bss%p(i1))+FREQUENCIES_damping(W_bss,real(W_bss%p(i1)))*cI
   W_bssm%p(i1)=real(W_bss%p(i1))-FREQUENCIES_damping(W_bss,real(W_bss%p(i1)))*cI
   if(abs(W_bss%p(i1))==0._SP) W_bss%p(i1)=W_bss%p(i1)+1.E-10_SP
   if(abs(W_bssm%p(i1))==0._SP) W_bssm%p(i1)=W_bssm%p(i1)+1.E-10_SP
 enddo
 !
 if(Exc_Range(1)<=0) Exc_Range(1)=1
 if(Exc_Range(2)==0) Exc_Range(2)=BSS_n_eig
 if(Exc_Range(2)>BSS_n_eig) Exc_Range(2)=BSS_n_eig
 !
 BS_mat_q=cZERO
 BS_mat_q(:,1:BSS_n_eig) = BS_mat(:,1:BSS_n_eig)
 !
 N_trans=Exc_Range(2)-Exc_Range(1)+1
 call PP_indexes_reset(PX_bs)
 call PARALLEL_index(PX_bs,(/N_trans/))
 !
 ! build equbrim <0|r|n>
 eq_res=cZERO
 call equilibrium_residuals(N_DIP_dirs,DIP_dir,Xen,Xk)
 call PP_redux_wait(eq_res,COMM=PAR_COM_DIPk_ibz_INDEX%COMM)
 call PP_redux_wait(eq_res,COMM=PAR_COM_DIPk_ibz_A2A%COMM)
 !
 call equilibrium_residuals_gra_eqdipole(N_DIP_dirs,DIP_dir,Xen,Xk)
 call PP_redux_wait(eq_res_gra,COMM=PAR_COM_DIPk_ibz_INDEX%COMM)
 call PP_redux_wait(eq_res_gra,COMM=PAR_COM_DIPk_ibz_A2A%COMM)
 write(*,*) eq_res_gra(1,1)
 write(*,*) eq_res_gra(1,2)
 write(*,*) eq_res_gra(2,1)
 write(*,*) eq_res_gra(2,2)
 !
 !
 ! loop for il exciton, i.e.  range for the initial state
 do i_l_refer=Exc_Range(1),Exc_Range(2)
   exc_exc_E =rZERO
   RES_right=cZERO
   !
   call msg("s","starting initial exciton state is",i_l_refer)
   call msg('s','Length gauge EXC-EXC  transitions :',N_trans)
   !
   ! Inter and intra excitons transitions
   !
   call exc_exc_residuals(N_DIP_dirs,DIP_dir,DIP_dir_table,Xen,Xk,1,1,1,i_l_refer,.true.)
   !
   !
   call PP_redux_wait(RES_right,COMM=PAR_COM_DIPk_ibz_INDEX%COMM)
   call PP_redux_wait(RES_right,COMM=PAR_COM_DIPk_ibz_A2A%COMM)
   !
   RES_R_right=cZERO
   do i_l_refer2 = 1, Exc_Range(2)-Exc_Range(1)+1
     i_m=Exc_Range(1)+i_l_refer2-1
     RES_R_right(i_m,:,:)=RES_right(i_l_refer2,:,:)
   enddo
   !
   ! to do: get velocity exciton dipole
   !
   RES_V_right = cZERO
   exc_range_save = Exc_Range
   Exc_Range = (/exc_range_save(2)+1, 0/)
   do i_l_refer2 = 1, exc_range_save(2)
      dE = real(BS_E(i_l_refer)-BS_E(i_l_refer2),SP)
      if (abs(dE) < 0.001_SP) then
         Exc_Range(1) = min(Exc_Range(1), i_l_refer2)
         Exc_Range(2) = max(Exc_Range(2), i_l_refer2)
      else
         RES_V_right(i_l_refer2,:,:) = cI * RES_R_right(i_l_refer2,:,:) * dE
      endif
   enddo
   if (Exc_Range(2)>=Exc_Range(1)) then
     global_gauge="velocity"
     RES_right=cZERO
     call msg('s','Velocity gauge EXC-EXC  transitions for degenaration:',Exc_Range(2)-Exc_Range(1)+1)
     call exc_exc_residuals(N_DIP_dirs,DIP_dir,DIP_dir_table,Xen,Xk,1,1,1,i_l_refer,.true.)
     call PP_redux_wait(RES_right,COMM=PAR_COM_DIPk_ibz_INDEX%COMM)
     call PP_redux_wait(RES_right,COMM=PAR_COM_DIPk_ibz_A2A%COMM)
     do i_l_refer2 = 1, Exc_Range(2)-Exc_Range(1)+1
       i_m=Exc_Range(1)+i_l_refer2-1
       RES_V_right(i_m,:,:)=RES_right(i_l_refer2,:,:)
     enddo
   endif
   Exc_Range=exc_range_save
   global_gauge="length"
   !
   !
   !
   call build_up_sc(i_l_refer)
   !
 enddo
 !
 call PP_redux_wait(sc_ijk)
 !
 call SC_output()
 !
 !
 ! Free...
 YAMBO_FREE(WF_phases_b_map)
 YAMBO_FREE(BS_mat_q)
 YAMBO_FREE(sc_ijk)
 YAMBO_FREE(den3a)
 YAMBO_FREE(den3b)
 YAMBO_FREE(exc_exc_E)
 YAMBO_FREE(RES_right)
 YAMBO_FREE(eq_res)
 YAMBO_FREE(eq_res_gra)
 YAMBO_FREE(RES_V_right)
 YAMBO_FREE(RES_R_right)
 !
 call live_timing()
 !
 contains
   !
   subroutine build_up_sc(i_n)
     !
     integer       :: i_n,i_m
     ! Here eq_res,RES_right in length; RES_V_right in velocity
     do i_trans=1,Exc_Range(2)-Exc_Range(1)+1
       if (.not.PX_bs%element_1D(i_trans)) cycle
       i_m=Exc_Range(1)+i_trans-1
       den3a=(W_bssm%p(:)+BS_E(i_m))*(W_bss%p(:)+BS_E(i_n))
       den3b=(-W_bss%p(:)+BS_E(i_m))*(-W_bssm%p(:)+BS_E(i_n))
       sc_ijk(:,1)=sc_ijk(:,1) &
       &                          +cI*eq_res(i_n,sc_dir1)*RES_R_right(i_m,sc_dir2,1)*conjg(eq_res(i_m,sc_dir3))&
       &                          /(W_bss%p(:)-BS_E(i_m)) &
       &                          +cI*eq_res(i_n,sc_dir1)*RES_R_right(i_m,sc_dir3,1)*conjg(eq_res(i_m,sc_dir2))&
       &                          /(-W_bssm%p(:)-BS_E(i_m))
       !
       sc_ijk(:,2)=sc_ijk(:,2) &
       &                          +cI*eq_res(i_n,sc_dir2)*RES_R_right(i_m,sc_dir3,1)*conjg(eq_res(i_m,sc_dir1))&
       &                          /(-W_bssm%p(:)+BS_E(i_n)) &
       &                          +cI*eq_res(i_n,sc_dir3)*RES_R_right(i_m,sc_dir2,1)*conjg(eq_res(i_m,sc_dir1))&
       &                          /(W_bss%p(:)+BS_E(i_n))
       !
       sc_ijk(:,3)=sc_ijk(:,3) &
       &                          +cI*eq_res(i_n,sc_dir3)*RES_V_right(i_m,sc_dir1,1)*conjg(eq_res(i_m,sc_dir2))&
       &                          /den3a &
       &                          +cI*eq_res(i_n,sc_dir2)*RES_V_right(i_m,sc_dir1,1)*conjg(eq_res(i_m,sc_dir3))&
       &                          /den3b
       if (i_m==i_n) then
       sc_ijk(:,4)=sc_ijk(:,4) &
       &      +cI*eq_res(i_n,sc_dir1)*(RES_R_right(i_m,sc_dir2,1) &
&                +eq_res_gra(i_m,sc_dir2)/eq_res(i_m,sc_dir2))*conjg(eq_res(i_m,sc_dir3))&
       &                          /(W_bss%p(:)-BS_E(i_m))
       write(*,*) 's states=',i_m,'         Rss=',RES_R_right(i_m,sc_dir2,1),&
&      '        grad_dip=',eq_res_gra(i_m,sc_dir2)/eq_res(i_m,sc_dir2),      &
&      '        eq_res_gra(i_m,sc_dir2)=',eq_res_gra(i_m,sc_dir2),'        eq_res(i_m,sc_dir2)=',eq_res(i_m,sc_dir2)
       endif
     enddo
   end subroutine
   !
   subroutine SC_output()
     use com,                ONLY:of_open_close
     !
     character(schlen)       :: filename,headers(6)
     complex(SP)             :: sc_total
     real(SP)                :: values(8)
     integer                 :: sstep
     !
     filename="YPP-SC_shift_current"
     headers(1)="E [eV]"
     headers(2)="Re SC"
     headers(3)="Im SC"
     headers(4)="Re SC(1)"
     headers(5)="Re SC(2)"
     headers(6)="Re SC(3)"
     !
     call of_open_close(filename,'ot')
     call msg("o "//trim(filename),'#')
     call msg("o "//trim(filename),'#')
     call msg("o "//trim(filename),'#',headers,INDENT=0,USE_TABS=.TRUE.)
     call msg("o "//trim(filename),'#')
     !
     do sstep=1,size(W_bss%p)
       sc_total=sum(sc_ijk(sstep,1:3))
       values(1)=real(W_bss%p(sstep),SP)*HA2EV
       values(2)=real(sc_total,SP)
       values(3)=aimag(sc_total)
       values(4)=real(sc_ijk(sstep,1),SP)
       values(5)=real(sc_ijk(sstep,2),SP)
       values(6)=real(sc_ijk(sstep,3),SP)
       values(7)=real(sc_ijk(sstep,4),SP)
       values(8)=aimag(sc_ijk(sstep,4))
       call msg("o "//trim(filename),'',values,INDENT=-2,USE_TABS=.TRUE.)
     enddo
     !
     call of_open_close(filename)
   end subroutine
end subroutine shift_current
