module gain_fit_mod

use precision_def
!use tbt_interface

  USE nrtype;USE nrutil, ONLY : nrerror, assert_eq, diagmult
  USE nr

 type bpm_struct
   integer  button(4)
   real(rp) x,y
   real(rp) phase_h, phase_v
 end type

 type orbit_struct
   type (bpm_struct) detector(0:120)
   real(rp) current
 end type

 type (orbit_struct) orbit_data(300000)

 character(16) bpm_names(0:120)

 integer norbits, bpm, nvar, ind, nterms, gain_correct
 integer dets(100)
 integer rd_number
 real(rp) gain(4)
 real(rp) const, intercept
 real(rp) weight/0.0/
 real(rp) arb_gain(1:4,0:120)

  character*100 in_file, in_file_0/' e. g.  "RD-003175.dat" or "3175" or "0" for latest '/ 

  
 logical expert

contains


subroutine mrqmin_funcs(a,yfit,dyda, status)

 implicit none

    real(rp), dimension(:), intent(in) :: a
    real(rp), dimension(:,:), intent(out) :: dyda
    real(rp), dimension(:), intent(out) :: yfit
    real(rp) but(4)
    real(rp) current
    real(rp) chis, dchis_dy(5)

    integer i, iterm
    integer status


    call a_to_gain(gain, a, ind)
    const = a(5)

  do i=1, nterms
   if(i <= norbits) then 
    but(1:4) = orbit_data(i)%detector(bpm)%button(1:4)
    current = orbit_data(i)%current
   endif

    iterm = i
    call derivative(gain,const, but, current, chis, dchis_dy, iterm)
    dyda(i,1:nvar) = dchis_dy(1:nvar)
    yfit(i) = chis

 end do

 return

 end subroutine mrqmin_funcs

!*********************************************
!
subroutine derivative(gain,const, but, current, y, dyda, iterm)
! The quantity to minimize is 
!          the sum of the squares of y(i) =  g.Bpmmp(i) - c(g.Bpmpm(i))(g.Bppmm(i))
! The derivative matrix is dy(i)/da(j) and a(1:4) = gain(1:4), a(5) = c
! In this routine compute the 5 derivatives for one of the terms in the sum
 
 implicit none

 real(rp) Bpmpm(4), Bppmm(4), Bpmmp(4), but(4), gain(4), const, current
 real(rp), dimension(:), intent(out) :: dyda
 real(rp) y
 real(rp) GdotB

 integer iterm

if(iterm <=  norbits)then
  call bvecs(but, Bpmmp, Bpmpm, Bppmm)
  GdotB=dot_product(gain,but)
  Bpmmp = Bpmmp/dot_product(gain,but)
  Bpmpm = Bpmpm/dot_product(gain,but)
  Bppmm = Bppmm/dot_product(gain,but)


 if(ind == 1) &
  dyda(2:4) = 2*(Bpmmp(2:4) - const / current * & 
            (Bpmpm(2:4) * dot_product(gain,Bppmm)+Bppmm(2:4)*  dot_product(gain,Bpmpm)))

 if(ind == 4) &
  dyda(2:4) = 2*(Bpmmp(1:3) - const / current * & 
            (Bpmpm(1:3) * dot_product(gain,Bppmm)+Bppmm(1:3)*  dot_product(gain,Bpmpm)))

 if(ind == 2)then
  dyda(2) = 2*(Bpmmp(1) - const / current * & 
            (Bpmpm(1) * dot_product(gain,Bppmm)+Bppmm(1)*  dot_product(gain,Bpmpm)))

  dyda(3:4) = 2*(Bpmmp(3:4) - const / current * & 
            (Bpmpm(3:4) * dot_product(gain,Bppmm)+Bppmm(3:4)*  dot_product(gain,Bpmpm)))

 endif

 if(ind == 3)then
  dyda(4) = 2*(Bpmmp(4) - const / current * & 
            (Bpmpm(4) * dot_product(gain,Bppmm)+Bppmm(4)*  dot_product(gain,Bpmpm)))

  dyda(2:3) = 2*(Bpmmp(1:2) - const / current * & 
            (Bpmpm(1:2) * dot_product(gain,Bppmm)+Bppmm(1:2)*  dot_product(gain,Bpmpm)))

 endif

  dyda(1) = -2 / current * dot_product(Bpmpm,gain) * dot_product(gain, Bppmm)

  dyda(1:nvar) = dyda(1:nvar)  !* chi(gain, const, but, current)

  dyda(1:4) = 2*(Bpmmp(1:4) - const / current * & 
            (Bpmpm(1:4) * dot_product(gain,Bppmm)+Bppmm(1:4)*  dot_product(gain,Bpmpm))) &
            - 2*(but(1:4)*dot_product(gain,Bpmmp)/GdotB - 2*const / current * & 
            (but(1:4) * dot_product(gain,Bppmm)*dot_product(gain,Bpmpm))/GdotB)
  dyda(5) = -2 / current * dot_product(Bpmpm,gain) * dot_product(gain, Bppmm)
  y = chi(gain,const,but,current) ! **2
 endif

 if(iterm > norbits)then
   if(ind == 1) dyda(2:4) = 2*(gain(2:4)-1) * weight
   if(ind == 2) then
      dyda(2) = 2*(gain(1)-1)*weight
      dyda(3:4) = 2*(gain(3:4)-1)*weight
   endif
   if(ind == 3)then
      dyda(2:3) = 2*(gain(1:2)-1)*weight
      dyda(4) = 2*(gain(4)-1)*weight
   endif
   if(ind == 4) dyda(2:4) = 2*(gain(1:3)-1)*weight

   dyda(1) = 0
   y = ((gain(1)-1)**2 + (gain(2)-1)**2+ (gain(3)-1)**2 + (gain(4)-1)**2)*weight
 endif

return
end subroutine derivative
!
!************************************************************
!

!*********************************************
!
subroutine second_derivative(gain,const, but, current, y, d2y_da2)
 
 implicit none

 real(rp) Bpmpm(4), Bppmm(4), Bpmmp(4), but(4), gain(4), const, current
 real(rp) y
 real(rp) d_chi_da(4), d2_chi_da2(4,4), d2y_da2(4,4), alpha
 integer i

  call bvecs(but, Bpmmp, Bpmpm, Bppmm)

! chi**2, alpha = d(chi)/da, beta = d2(chi)/d2a
! first derivative

  d_chi_da(2:4) = Bpmmp(2:4) - const / current * & 
            (Bpmpm(2:4) * dot_product(gain,Bppmm)+Bppmm(2:4)*  dot_product(gain,Bpmpm))

  d_chi_da(1) = -1 / current * dot_product(Bpmpm,gain) * dot_product(gain, Bppmm)

  alpha = chi(gain, const, but, current)
 
! second derivative d2_chi_da2

   d2_chi_da2(2:4,1) = -1/current * (Bpmpm(2:4) * dot_product(gain,Bppmm)+Bppmm(2:4)*dot_product(gain,Bpmpm))
   d2_chi_da2(1,1) = 0.

   do i=2,4
    d2_chi_da2(2:4,i) = -const/current * (Bpmpm(2:4) * Bppmm(i) + Bppmm(2:4)*Bpmpm(i))
    d2_chi_da2(1,i) = -1/current * (Bpmpm(i) * dot_product(gain, Bppmm)  + dot_product(Bpmpm,gain)*Bpmpm(i))
   end do
 
! all together

  do i=1,4
   d2y_da2(1:4,i) = 2*(d_chi_da(1:4) * d_chi_da(i) + 2*alpha * d2_chi_da2(1:4,i))
  end do

  y = chi(gain,const,but,current) **2

return
end subroutine second_derivative

!*********************************************
!
! calculate the second derivative of the chis2 with respect to the 4 gains.
! Here chi2 = dot_product(gain,Bpmmp)-const/current * (dot_product(gain,Bppmm) * dot_product(gain,Bpmpm))

subroutine second_derivative_gains(gain,const, but, current, y, d2y_da2)


 implicit none

 real(rp) Bpmpm(4), Bppmm(4), Bpmmp(4), but(4), gain(4), const, current
 real(rp) y
 real(rp) d_chi_da(4), d2_chi_da2(4,4), d2y_da2(4,4), alpha
 integer i

  call bvecs(but, Bpmmp, Bpmpm, Bppmm)

! chi**2, alpha = d(chi)/da, beta = d2(chi)/d2a
! first derivative

  d_chi_da(1:4) = Bpmmp(1:4) - const / current * & 
            (Bpmpm(1:4) * dot_product(gain,Bppmm)+Bppmm(1:4)*  dot_product(gain,Bpmpm))

  alpha = chi(gain, const, but, current)
 
! second derivative d2_chi_da2

   do i=1,4
    d2_chi_da2(1:4,i) = -const/current * (Bpmpm(1:4) * Bppmm(i) + Bppmm(1:4) * Bpmpm(i))

   end do
 
! all together

  do i=1,4
   d2y_da2(1:4,i) = 2*(d_chi_da(1:4) * d_chi_da(i) + 2*alpha * d2_chi_da2(1:4,i))
  end do

  y = chi(gain,const,but,current) **2

return
end subroutine second_derivative_gains
!
!************************************************************
!

function chi(gain,c,but,current)


 implicit none

 real(rp) chi
 real(rp) gain(4), c, but(4), current
 real(rp) Bpmmp(4), Bpmpm(4), Bppmm(4), chi1, chi2
 real(rp) den

 call bvecs(but,Bpmmp,Bpmpm, Bppmm)
  Bpmmp=Bpmmp/dot_product(but,gain) ! experiment 10/20/16
  Bpmpm=Bpmpm/dot_product(but,gain) ! experiment 10/20/16
  Bppmm=Bppmm/dot_product(but,gain) ! experiment 10/20/16

  chi1 = dot_product(Bpmmp,gain)
  chi2 = c/current * dot_product(Bpmpm,gain)*dot_product(Bppmm,gain)
 chi = dot_product(Bpmmp,gain) - c/current*dot_product(Bpmpm,gain)*dot_product(Bppmm,gain) &
           + weight*(dot_product(gain,gain) - 1.)
 
 return
end function chi

subroutine bvecs(but, Bpmmp, Bpmpm, Bppmm)

  implicit none

 real(rp) but(4)
 real(rp) Bpmmp(4), Bpmpm(4), Bppmm(4)

 real(rp) spmmp(4)/1.,-1.,-1.,1./
 real(rp) spmpm(4)/1.,-1.,1.,-1./
 real(rp) sppmm(4)/1.,1.,-1.,-1./

 Bpmmp(1:4) = but(1:4)*spmmp(1:4)
 Bpmpm(1:4) = but(1:4)*spmpm(1:4)
 Bppmm(1:4) = but(1:4)*sppmm(1:4)

 return
 end subroutine bvecs
!
!******************************
!
subroutine chi_square(g,c, chis, dc_dg)

 implicit none

    real(rp) but(4)
    real(rp) current
    real(rp) chis
    real(rp) g(4),c, dc_dg(5)
    real(rp) dyda(5)
    real(rp) y

   

    integer i, iterm

    chis = 0.
    dc_dg(1:nvar) = 0.
  do i=1,norbits
    but(1:4) = orbit_data(i)%detector(bpm)%button(1:4)

    current = orbit_data(i)%current

    chis = chi(g,c, but,current) **2 + chis

    call derivative(g,c,but,current,y,dyda, iterm)
    dc_dg(1:nvar) = dc_dg(1:nvar) + (dyda(1:nvar))

 end do
 

! chis = chis /norbits


 return
end subroutine chi_square
!
!******************************
!
subroutine h_matrix(g,c, chis, d2c_dg2)

 implicit none

    real(rp) but(4)
    real(rp) current
    real(rp) chis
    real(rp) g(4),c, d2c_dg2(5,5)
    real(rp) d2y_da2(5,5)
    real(rp) y

   

    integer i

    chis = 0.
    d2c_dg2(1:nvar,1:nvar) = 0.
  do i=1,norbits
    but(1:4) = orbit_data(i)%detector(bpm)%button(1:4)

    current = orbit_data(i)%current

    chis = chi(g,c, but,current) **2 + chis

    call second_derivative(g,c,but,current,y,d2y_da2)
    d2c_dg2(1:nvar,1:nvar) = d2c_dg2(1:nvar,1:nvar) + d2y_da2(1:nvar,1:nvar)

 end do

! chis = chis /norbits


 return
end subroutine h_matrix
!
!******************************
!
subroutine chi_square_num(g,c, chis, dc_dg_sum)

 implicit none

    real(rp) but(4)
    real(rp) current
    real(rp) chis
    real(rp) g(4),c, dc_dg(4), dc_dg_sum(4), dc_dg_sum1(4)
    real(rp) dyda(4)
    real(rp) y
    real(rp) delta/1.e-6/, delta_chis, gp(4), gm(4)
   

    integer i,j, iterm

    chis = 0.
    dc_dg_sum(1:nvar) = 0.
    dc_dg_sum1(1:nvar) = 0.
  do i=1,norbits
    but(1:4) = orbit_data(i)%detector(bpm)%button(1:4)

    current = orbit_data(i)%current
    chis = chi(g,c, but,current) **2 + chis

    gp = g
    gm = g
    do j=2,4
     gp(j) = g(j)+delta
     gm(j) = g(j)-delta
     dc_dg(j) = (chi(gp,c,but,current)**2-chi(gm,c,but,current)**2)/2/delta
     gp(j) = g(j)
     gm(j) = g(j)
    end do
    call derivative(g,c,but,current,y,dyda, iterm)
   write(29,'(i,3e14.6,1x,3e14.6)')i,dc_dg(2:4),dyda(2:4)
   dc_dg_sum(2:4) = dc_dg_sum(2:4) + dc_dg(2:4) 
   dc_dg_sum1(2:4) = dc_dg_sum1(2:4)+ dyda(2:4)
   write(30,'(i,a,3e14.6,a,3e14.6)')i,' dc_dg= ',dc_dg_sum(2:4),' dc_dg_sum1(2:4)= ',dc_dg_sum1(2:4)
 end do

! chis = chis /norbits
  print '(a,3e14.6,a,3e14.5)','dc_dg_sum',dc_dg_sum(2:4), ' dc_dg_sum1',dc_dg_sum1(2:4)

 return


 end subroutine chi_square_num


 subroutine slope(g, c, k)

  implicit none


    real(rp) but(4)
    real(rp) current
    real(rp) chis
    real(rp) g(4),c, k
    real(rp) Bpmmp(4), Bpmpm(4), Bppmm(4)
    real(rp) t1,t2, sum1, sum2, sum3, sum4, sum5
    real(rp) M(2,2), V(2), Minv(2,2), X(2)
    real(rp) det
    real(rp) f/1.e6/
    integer i

    chis = 0.
    sum1=0.
    sum2=0.
    sum3=0.
    sum4=0.
    sum5 = 0.

  do i=1,norbits
    but(1:4) = orbit_data(i)%detector(bpm)%button(1:4)/f

    current = orbit_data(i)%current
    call bvecs(but, Bpmmp, Bpmpm, Bppmm)
    Bpmmp = Bpmmp/dot_product(gain,but)
    Bpmpm = Bpmpm/dot_product(gain,but)
    Bppmm = Bppmm/dot_product(gain,but)


    t1 = dot_product(g,Bpmmp)
    t2 = 1./current * dot_product(g,Bpmpm)*dot_product(g,Bppmm)

    sum1 = sum1 + t1*t2
    sum2 = sum2 + t2*t2
    sum3 = sum3 + t2
    sum4 = sum4 + t1
    sum5 = sum5 +1

 end do

! c = sum1/sum2

  M(1,1) = sum2
  M(1,2) = sum3
  M(2,1) = sum3
  M(2,2) = sum5

  V(1) = sum1
  V(2) = sum4

  det = M(1,1)*M(2,2)-M(1,2)*M(2,1)

  Minv(1,1) =  M(2,2)/det
  Minv(1,2) = -M(1,2)/det
  Minv(2,1) = -M(2,1)/det
  Minv(2,2) =  M(1,1)/det

  X = matmul(Minv,V)

  c = X(1)/f
  k = X(2)*f

 return

end subroutine slope

end module
