pw2wan90epw.f90 70.7 KB
Newer Older
sponce's avatar
sponce committed
1 2 3 4 5 6 7 8 9 10 11 12
  !
  ! Copyright (C) 2010-2016 Samuel Ponce', Roxana Margine, Carla Verdi, Feliciano Giustino 
  ! Copyright (C) 2007-2009 Jesse Noffsinger, Brad Malone, Feliciano Giustino  
  !                                                                            
  ! This file is distributed under the terms of the GNU General Public         
  ! License. See the file `LICENSE' in the root directory of the               
  ! present distribution, or http://www.gnu.org/copyleft.gpl.txt .             
  !                                                                            
  ! Adapted from the code PP/pw2wannier - Quantum-ESPRESSO group               
  !------------------------------------------------------------------------
  SUBROUTINE pw2wan90epw 
  !------------------------------------------------------------------------
13 14 15 16 17 18 19 20 21 22
  !! This is the interface to the Wannier90 code: see http://www.wannier.org
  !!
  !!
  !! 10/2008  Parellel computation of Amn and Mmn 
  !! 12/2008  Added phase setting of overlap matrix elements
  !! 02/2009  works with standard nk1*nk2*nk3 grids
  !! 12/2009  works with USPP 
  !! 12/2014  RM: Imported the noncolinear case implemented by xlzhang
  !! 06/2016  SP: Debug of SOC + print/reading of nnkp file
  !!
sponce's avatar
sponce committed
23 24 25 26 27 28 29 30 31 32 33
  !------------------------------------------------------------------------
  USE io_global,  ONLY : stdout
  USE klist,      ONLY : nkstot
  USE io_files,   ONLY : prefix
  USE epwcom,     ONLY : write_wfn
  USE noncollin_module, ONLY : noncolin
  USE wannier,    ONLY : seedname2, wvfn_formatted, reduce_unk, ispinw, &
                         ikstart, ikstop, iknum
  !
  IMPLICIT NONE
  CHARACTER(LEN=4)   :: spin_component
34
  !! Determine the spin case
sponce's avatar
sponce committed
35
  CHARACTER(len=256) :: outdir
36
  !! Name of the output directory
sponce's avatar
sponce committed
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
  !
  !
  outdir = './'
  seedname2 = prefix
  spin_component = 'none'
  wvfn_formatted = .false.
  reduce_unk= .false.
  !
  !
  WRITE(stdout,*)
  SELECT CASE ( TRIM( spin_component ) )
  CASE ( 'up' )
     WRITE(stdout,*) '    Spin CASE ( up )'
     ispinw  = 1
     ikstart = 1
     ikstop  = nkstot/2
     iknum   = nkstot/2
  CASE ( 'down' )
     WRITE(stdout,*) '    Spin CASE ( down )'
     ispinw = 2
     ikstart = nkstot/2 + 1
     ikstop  = nkstot
     iknum   = nkstot/2
  CASE DEFAULT
     IF (noncolin) THEN
        WRITE(stdout,*) '    Spin CASE ( non-collinear )'
     ELSE
        WRITE(stdout,*) '    Spin CASE ( default = unpolarized )'
     ENDIF
     ispinw = 0
     ikstart = 1
     ikstop  = nkstot
     iknum   = nkstot
  END SELECT
  !
  WRITE(stdout,*) 
  WRITE(stdout,*) '    Initializing Wannier90'
  WRITE(stdout,*) 
  CALL setup_nnkp
  CALL ylm_expansion
  CALL compute_amn_para
  CALL compute_mmn_para
  !
  CALL phases_a_m
  !
  CALL write_band
  !
  IF(write_wfn) CALL write_plot
  !
  WRITE(stdout,*)
  WRITE(stdout,*) '    Running Wannier90'
  CALL run_wannier
  !
  CALL lib_dealloc
  !
  END SUBROUTINE pw2wan90epw
!
94
!-------------------------------------------------------------------------
sponce's avatar
sponce committed
95 96
SUBROUTINE lib_dealloc
  !-----------------------------------------------------------------------
97
  !! Routine to de-allocate Wannier related matrices. 
sponce's avatar
sponce committed
98 99 100 101 102 103 104 105 106 107 108 109 110 111
  !
  USE wannier
  !
  implicit none
  IF (ALLOCATED(m_mat) )     DEALLOCATE(m_mat)
  IF (ALLOCATED(u_mat) )     DEALLOCATE(u_mat)
  IF (ALLOCATED(u_mat_opt) ) DEALLOCATE(u_mat_opt)
  IF (ALLOCATED(a_mat) )     DEALLOCATE(a_mat)
  IF (ALLOCATED(eigval) )    DEALLOCATE(eigval)
  IF (ALLOCATED(lwindow) )   DEALLOCATE(lwindow)
  !

END SUBROUTINE lib_dealloc
!
112
!-------------------------------------------------------------------------
sponce's avatar
sponce committed
113 114
SUBROUTINE setup_nnkp (  )
  !-----------------------------------------------------------------------
115 116 117 118 119 120 121 122 123 124 125 126 127 128
  !! 
  !! This routine write and read the .nnkp file. 
  !! The file specifies
  !! 1) The initial projections functions in the format
  !! num_proj
  !! proj_site(1,i),proj_site(2,i),proj_site(3,i) proj_l(i),proj_m(i),proj_radial(i)
  !! proj_z(1,i),proj_z(2,i),proj_z(3,i),proj_x(1,i),proj_x(2,i),proj_x(3,i), proj_zona(i)
  !! proj_s(i), proj_s_qaxis(1,i),proj_s_qaxis(2,i),proj_s_qaxis(3,i) 
  !!
  !! 2) begin nnkpts: the nearest neighbours of each         
  !! k-point, and therefore provides the information required to      
  !! calculate the M_mn(k,b) matrix elements 
  !! 
  ! ---------------------------------------------------------------------- 
129 130
  USE io_global, ONLY : meta_ionode
  USE io_global, ONLY : stdout, meta_ionode_id
sponce's avatar
sponce committed
131 132 133 134 135 136 137 138 139
  USE mp_world,  ONLY : world_comm
  USE kinds,     ONLY : DP
  USE constants, ONLY : eps6, tpi
  USE cell_base, ONLY : at, bg, alat
  USE gvect,     ONLY : g, gg
  USE ions_base, ONLY : nat, tau, ityp, atm
  USE mp,        ONLY : mp_bcast
  USE wvfct,     ONLY : nbnd, npwx
  USE wannier,   ONLY : num_nnmax, mp_grid, atcart, atsym, kpb, g_kpb, &
140 141 142 143 144
                        center_w, alpha_w, l_w, mr_w, r_w, zaxis,      &
                        xaxis, excluded_band, rlatt, glatt, gf,        &
                        csph, ig_, iknum, seedname2, kpt_latt, nnb,    &
                        num_bands, n_wannier, nexband, nnbx, n_proj,   &
                        spin_eig, spin_qaxis
sponce's avatar
sponce committed
145 146
  USE noncollin_module, ONLY : noncolin
  USE constants_epw,    ONLY : bohr
147
!  USE w90_parameters,   ONLY : postproc_setup
sponce's avatar
sponce committed
148
  USE mp_global,        ONLY : intra_pool_comm, mp_sum
149 150
  USE w90_parameters,   ONLY : postproc_setup
  USE w90_io,           ONLY : post_proc_flag
151
  ! 
sponce's avatar
sponce committed
152 153
  implicit none
  real(DP) :: g_(3), gg_
154 155
  integer  :: ik, ib, ig, iw, ia, indexb, type, idum, ipol
  INTEGER, ALLOCATABLE :: ig_check(:,:)
sponce's avatar
sponce committed
156
  real(DP) :: xnorm, znorm, coseno
157 158 159 160 161 162 163
  integer  :: exclude_bands(nbnd), i, iun_nnkp
  LOGICAL  :: have_nnkp
  !! Check if the .nnkp file exists.
  LOGICAL  :: found
  !! Check if the section in the .nnkp file is found. 
  INTEGER, EXTERNAL :: find_free_unit
  !! Look for a free unit for the .nnkp file.
sponce's avatar
sponce committed
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252

! SP: An interface is required because the Wannier routine has optional
!     arguments
  Interface
    Subroutine wannier_setup(seed__name,mp_grid_loc,num_kpts_loc,&
     real_lattice_loc,recip_lattice_loc,kpt_latt_loc,num_bands_tot, &
     num_atoms_loc,atom_symbols_loc,atoms_cart_loc, gamma_only_loc,spinors_loc,&
     nntot_loc,nnlist_loc,nncell_loc,num_bands_loc,num_wann_loc, &
     proj_site_loc,proj_l_loc,proj_m_loc,proj_radial_loc,proj_z_loc, &
     proj_x_loc,proj_zona_loc,exclude_bands_loc,proj_s_loc,proj_s_qaxis_loc)

     USE kinds,    ONLY : dp
     USE wannier,  ONLY : num_nnmax

     implicit none

     character(len=*), intent(in) :: seed__name
     integer, dimension(3), intent(in) :: mp_grid_loc
     integer, intent(in) :: num_kpts_loc
     real(kind=dp), dimension(3,3), intent(in) :: real_lattice_loc
     real(kind=dp), dimension(3,3), intent(in) :: recip_lattice_loc
     real(kind=dp), dimension(3,num_kpts_loc), intent(in) :: kpt_latt_loc
     integer, intent(in) :: num_bands_tot
     integer, intent(in) :: num_atoms_loc
     character(len=*), dimension(num_atoms_loc), intent(in) :: atom_symbols_loc
     real(kind=dp), dimension(3,num_atoms_loc), intent(in) :: atoms_cart_loc
     logical, intent(in) :: gamma_only_loc
     logical, intent(in) :: spinors_loc
     integer, intent(out) :: nntot_loc
     integer, dimension(num_kpts_loc,num_nnmax), intent(out) :: nnlist_loc
     integer,dimension(3,num_kpts_loc,num_nnmax), intent(out) :: nncell_loc
     integer, intent(out) :: num_bands_loc
     integer, intent(out) :: num_wann_loc
     real(kind=dp), dimension(3,num_bands_tot), intent(out) :: proj_site_loc
     integer, dimension(num_bands_tot), intent(out) :: proj_l_loc
     integer, dimension(num_bands_tot), intent(out) :: proj_m_loc
     integer, dimension(num_bands_tot), intent(out) :: proj_radial_loc
     real(kind=dp), dimension(3,num_bands_tot), intent(out) :: proj_z_loc
     real(kind=dp), dimension(3,num_bands_tot), intent(out) :: proj_x_loc
     real(kind=dp), dimension(num_bands_tot), intent(out) :: proj_zona_loc
     integer, dimension(num_bands_tot), intent(out) :: exclude_bands_loc
     integer, dimension(num_bands_tot), optional, intent(out) :: proj_s_loc
     real(kind=dp), dimension(3,num_bands_tot), optional, intent(out) :: proj_s_qaxis_loc

    End Subroutine wannier_setup
  End Interface

  num_nnmax = 32

  ! aam: translations between PW2Wannier90 and Wannier90
  ! pw2wannier90   <==>   Wannier90
  !    nbnd                num_bands_tot
  !    n_wannier           num_wann
  !    num_bands           num_bands
  !    nat                 num_atoms
  !    iknum               num_kpts
  !    rlatt               transpose(real_lattice)
  !    glatt               transpose(recip_lattice)
  !    kpt_latt            kpt_latt
  !    nnb                 nntot
  !    kpb                 nnlist
  !    g_kpb               nncell
  !    mp_grid             mp_grid
  !    center_w            proj_site
  !    l_w,mr_w,r_w        proj_l,proj_m,proj_radial
  !    xaxis,zaxis         proj_x,proj_z
  !    alpha_w             proj_zona
  !    exclude_bands       exclude_bands
  !    atcart              atoms_cart
  !    atsym               atom_symbols

  ALLOCATE( atcart(3,nat), atsym(nat) )
  ALLOCATE( kpb(iknum,num_nnmax), g_kpb(3,iknum,num_nnmax) )
  ALLOCATE( center_w(3,nbnd), alpha_w(nbnd), l_w(nbnd), &
       mr_w(nbnd), r_w(nbnd), zaxis(3,nbnd), xaxis(3,nbnd) )
  ALLOCATE( excluded_band(nbnd) )

  ! real lattice (Cartesians, Angstrom)
  rlatt(:,:) = transpose(at(:,:))*alat*bohr
  ! reciprocal lattice (Cartesians, Angstrom)
  glatt(:,:) = transpose(bg(:,:))*tpi/(alat*bohr)
  ! atom co-ordinates in Cartesian co-ords and Angstrom units
  atcart(:,:) = tau(:,:)*bohr*alat
  ! atom symbols
  DO ia=1,nat
     type=ityp(ia)
     atsym(ia)=atm(type)
  ENDDO

253
  IF (meta_ionode) THEN
254 255 256
    !postproc_setup = .true.
    post_proc_flag = .true.
    !print*,'postproc_setup ',postproc_setup
257
    CALL wannier_setup(seedname2, mp_grid, iknum,      &  ! input
sponce's avatar
sponce committed
258 259 260 261 262
           rlatt, glatt, kpt_latt, nbnd,                 &  ! input
           nat, atsym, atcart, .false., noncolin,        &  ! input
           nnb, kpb, g_kpb, num_bands, n_wannier,        &  ! output
           center_w, l_w, mr_w, r_w, zaxis,              &  ! output
           xaxis, alpha_w, exclude_bands)                   ! output
263 264
   ! SP: In wannier_setup, the .nnkp file is produced.
  ENDIF
sponce's avatar
sponce committed
265
   
266 267 268 269 270 271 272 273 274 275 276 277 278 279
  CALL mp_bcast(nnb,          meta_ionode_id, world_comm )
  CALL mp_bcast(kpb,          meta_ionode_id, world_comm )
  CALL mp_bcast(g_kpb,        meta_ionode_id, world_comm )
  CALL mp_bcast(num_bands,    meta_ionode_id, world_comm )
  CALL mp_bcast(n_wannier,    meta_ionode_id, world_comm )
  CALL mp_bcast(center_w,     meta_ionode_id, world_comm )
  CALL mp_bcast(l_w,          meta_ionode_id, world_comm )
  CALL mp_bcast(mr_w,         meta_ionode_id, world_comm )
  CALL mp_bcast(r_w,          meta_ionode_id, world_comm )
  CALL mp_bcast(zaxis,        meta_ionode_id, world_comm )
  CALL mp_bcast(xaxis,        meta_ionode_id, world_comm )
  CALL mp_bcast(alpha_w,      meta_ionode_id, world_comm )
  CALL mp_bcast(exclude_bands,meta_ionode_id, world_comm )
  CALL mp_bcast(noncolin,     meta_ionode_id, world_comm )
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
  !
  ! SP: Commented because we now write on file the .nnkp file and read from it.
  ! 
  ! n_proj = nr. of projections (=#WF unless spinors then =#WF/2) 
  !IF (noncolin) THEN
  !   n_proj=n_wannier/2
  !ELSE
     n_proj=n_wannier
  !ENDIF
  !
  WRITE (stdout,*)
  WRITE (stdout,*) '    Initial Wannier projections'
  WRITE (stdout,*)
  !
  DO iw=1,n_proj
     WRITE (stdout, '(5x,"(",3f10.5,") :  l = ",i3, " mr = ", i3)') center_w(:,iw), l_w(iw), mr_w(iw)
  ENDDO
  !
  WRITE(stdout,'(/,"      - Number of bands is (",i3,")")') num_bands 
  WRITE(stdout,'("      - Number of wannier functions is (",i3,")")') n_wannier 
  !
  excluded_band(1:nbnd)=.false.
  nexband=0
  band_loop: DO ib=1,nbnd
     indexb=exclude_bands(ib)
     IF (indexb>nbnd .or. indexb<0) THEN
        CALL errore('setup_nnkp',' wrong excluded band index ', 1)
     ELSEIF (indexb.eq.0) THEN
        exit band_loop
     ELSE
        nexband=nexband+1
        excluded_band(indexb)=.true.
     ENDIF
  ENDDO band_loop
  !
  IF ( (nbnd-nexband).ne.num_bands ) &
      CALL errore('setup_nnkp',' something wrong with num_bands',1)
  ! 
  ! Now we read the .nnkp file 
  ! 
320 321
  IF (meta_ionode) CLOSE (iun_nnkp)
  IF (meta_ionode) THEN  ! Read nnkp file on ionode only
322 323 324 325 326 327 328 329 330
    INQUIRE(file=trim(seedname2)//".nnkp",exist=have_nnkp)
    IF(.not. have_nnkp) THEN
       CALL errore( 'pw2wannier90', 'Could not find the file '&
          &//trim(seedname2)//'.nnkp', 1 )
    ENDIF

    iun_nnkp = find_free_unit()
    OPEN (unit=iun_nnkp, file=trim(seedname2)//".nnkp",form='formatted')
  ENDIF
331
  IF (meta_ionode) THEN   ! read from ionode only
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
    IF(noncolin) THEN
       CALL scan_file_to(iun_nnkp,'spinor_projections',found)
       IF(.not.found) THEN
          !try old style projections
          CALL scan_file_to(iun_nnkp,'projections',found)
       ENDIF
    ELSE
       CALL scan_file_to(iun_nnkp,'projections',found)
       IF(.not.found) THEN
          CALL errore( 'pw2wannier90', 'Could not find projections block in '&
             &//trim(seedname2)//'.nnkp', 1 )
       ENDIF
    ENDIF
    READ(iun_nnkp,*) n_proj
  ENDIF
347
  CALL mp_bcast(n_proj,meta_ionode_id, world_comm)
348 349 350 351
  ! 
  ALLOCATE( gf(npwx,n_proj), csph(16,n_proj) )
  IF(noncolin) ALLOCATE( spin_eig(n_proj),spin_qaxis(3,n_proj) )
  ! 
352
  IF (meta_ionode) THEN   ! read from ionode only
353 354 355
    DO iw=1,n_proj
      READ(iun_nnkp,*) (center_w(i,iw), i=1,3), l_w(iw), mr_w(iw), r_w(iw)
      READ(iun_nnkp,*) (zaxis(i,iw),i=1,3),(xaxis(i,iw),i=1,3),alpha_w(iw)
sponce's avatar
sponce committed
356 357
      xnorm = sqrt(xaxis(1,iw)*xaxis(1,iw) + xaxis(2,iw)*xaxis(2,iw) + &
           xaxis(3,iw)*xaxis(3,iw))
358
      IF (xnorm < eps6) CALL errore ('read_nnkp',' |xaxis| < eps ',1)
sponce's avatar
sponce committed
359 360
      znorm = sqrt(zaxis(1,iw)*zaxis(1,iw) + zaxis(2,iw)*zaxis(2,iw) + &
           zaxis(3,iw)*zaxis(3,iw))
361
      IF (znorm < eps6) CALL errore ('read_nnkp',' |zaxis| < eps ',1)
sponce's avatar
sponce committed
362 363 364
      coseno = (xaxis(1,iw)*zaxis(1,iw) + xaxis(2,iw)*zaxis(2,iw) + &
           xaxis(3,iw)*zaxis(3,iw))/xnorm/znorm
      IF (abs(coseno) > eps6) &
365
           CALL errore('read_nnkp',' xaxis and zaxis are not orthogonal !',1)
sponce's avatar
sponce committed
366
      IF (alpha_w(iw) < eps6) &
367
           CALL errore('read_nnkp',' zona value must be positive', 1)
sponce's avatar
sponce committed
368 369
      ! convert wannier center in cartesian coordinates (in unit of alat)
      CALL cryst_to_cart( 1, center_w(:,iw), at, 1 )
370 371 372 373 374 375 376 377 378 379 380 381 382
      IF(noncolin) THEN
         READ(iun_nnkp,*) spin_eig(iw),(spin_qaxis(i,iw),i=1,3)
         xnorm = sqrt(spin_qaxis(1,iw)*spin_qaxis(1,iw) + spin_qaxis(2,iw)*spin_qaxis(2,iw) + &
           spin_qaxis(3,iw)*spin_qaxis(3,iw))
         IF (xnorm < eps6) CALL errore ('read_nnkp',' |xaxis| < eps ',1)
         spin_qaxis(:,iw)=spin_qaxis(:,iw)/xnorm
      ENDIF
    ENDDO
  ENDIF
  ! 
  WRITE(stdout,*) '     - All guiding functions are given '
  ! 
  ! Broadcast
383 384 385 386 387 388 389
  CALL mp_bcast(center_w,meta_ionode_id, world_comm)
  CALL mp_bcast(l_w,meta_ionode_id, world_comm)
  CALL mp_bcast(mr_w,meta_ionode_id, world_comm)
  CALL mp_bcast(r_w,meta_ionode_id, world_comm)
  CALL mp_bcast(zaxis,meta_ionode_id, world_comm)
  CALL mp_bcast(xaxis,meta_ionode_id, world_comm)
  CALL mp_bcast(alpha_w,meta_ionode_id, world_comm)
390
  IF(noncolin) THEN
391 392
     CALL mp_bcast(spin_eig,meta_ionode_id, world_comm)
     CALL mp_bcast(spin_qaxis,meta_ionode_id, world_comm)
393 394
  ENDIF
  !
395
  IF (meta_ionode) THEN   ! read from ionode only
396 397 398 399 400 401 402 403
    CALL scan_file_to(iun_nnkp,'nnkpts',found)
    IF(.not.found) THEN
       CALL errore( 'pw2wannier90epw', 'Could not find nnkpts block in '&
          &//trim(seedname2)//'.nnkp', 1 )
    ENDIF
    READ (iun_nnkp,*) nnb
  ENDIF
  ! Broadcast
404
  CALL mp_bcast(nnb,meta_ionode_id, world_comm)
405 406 407 408 409 410 411 412 413 414
  !
  !
  nnbx = 0
  nnbx = max (nnbx, nnb )
  ALLOCATE ( ig_(iknum,nnbx), ig_check(iknum,nnbx) )
  !
  ! Read data about neighbours
  WRITE(stdout,*)
  WRITE(stdout,*) ' Reading data about k-point neighbours '
  WRITE(stdout,*)
415
  IF (meta_ionode) THEN
416
    DO ik=1, iknum
sponce's avatar
sponce committed
417
      DO ib = 1, nnb
418
        READ(iun_nnkp,*) idum, kpb(ik,ib), (g_kpb(ipol,ik,ib), ipol =1,3)
sponce's avatar
sponce committed
419
      ENDDO
420 421 422
    ENDDO
  ENDIF
  ! Broadcast
423 424
  CALL mp_bcast(kpb,meta_ionode_id, world_comm)
  CALL mp_bcast(g_kpb,meta_ionode_id, world_comm)
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454
  ! 
  DO ik=1, iknum
    DO ib = 1, nnb
      g_(:) = REAL( g_kpb(:,ik,ib) )
      CALL cryst_to_cart (1, g_, bg, 1)
      gg_ = g_(1)*g_(1) + g_(2)*g_(2) + g_(3)*g_(3)
      ig_(ik,ib) = 0
      ig = 1
      DO WHILE  (gg(ig) <= gg_ + eps6)
        IF ( (abs(g(1,ig)-g_(1)) < eps6) .and.  &
             (abs(g(2,ig)-g_(2)) < eps6) .and.  &
             (abs(g(3,ig)-g_(3)) < eps6)  ) ig_(ik,ib) = ig
        ig= ig +1
      ENDDO
    ENDDO
  ENDDO
  ig_check(:,:) = ig_(:,:)
  CALL mp_sum( ig_check, intra_pool_comm )
  DO ik=1, iknum
    DO ib = 1, nnb
      IF (ig_check(ik,ib) ==0) &
        CALL errore('read_nnkp', &
                    ' g_kpb vector is not in the list of Gs', 100*ik+ib )
    ENDDO
  ENDDO
  DEALLOCATE (ig_check)
  !
  WRITE(stdout,*) '     - All neighbours are found '
  WRITE(stdout,*)
  !
455
  IF (meta_ionode)THEN
456 457 458 459
    CLOSE (iun_nnkp)
  ENDIF
  RETURN
  !
sponce's avatar
sponce committed
460
END SUBROUTINE setup_nnkp
461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
!--------------------------------------------------------------------------
!--------------------------------------------------------------------------
SUBROUTINE scan_file_to (iun_nnkp,keyword,found)
   !-----------------------------------------------------------------------
   !
   IMPLICIT NONE
   CHARACTER(len=*), intent(in) :: keyword
   INTEGER, intent(in)          :: iun_nnkp
   logical, intent(out)         :: found
   CHARACTER(len=80)            :: line1, line2
!
! by uncommenting the following line the file scan restarts every time
! from the beginning thus making the reading independent on the order
! of data-blocks
!   rewind (iun_nnkp)
!
10 CONTINUE
   READ(iun_nnkp,*,end=20) line1, line2
   IF(line1/='begin')  GOTO 10
   IF(line2/=keyword) GOTO 10
   found=.true.
   RETURN
20 found=.false.
   rewind (iun_nnkp)

END SUBROUTINE scan_file_to
! ------------------------------------------------------------------------
! ------------------------------------------------------------------------
sponce's avatar
sponce committed
489 490 491
SUBROUTINE run_wannier
  !-----------------------------------------------------------------------
  !
492
  USE io_global, ONLY : stdout, meta_ionode_id, meta_ionode
sponce's avatar
sponce committed
493 494 495 496 497 498 499 500 501
  USE ions_base, ONLY : nat
  USE mp,        ONLY : mp_bcast
  USE mp_world,  ONLY : world_comm
  USE cell_base, ONLY : celldm
  USE io_files,  ONLY : prefix
  USE wannier
  USE epwcom,    ONLY : eig_read
  USE wvfct,     ONLY : nbnd
  USE constants_epw, ONLY : czero, bohr
502
  !
sponce's avatar
sponce committed
503
  implicit none
504
  ! 
sponce's avatar
sponce committed
505 506 507 508 509 510 511 512 513 514 515
  integer             :: i, ik, ibnd, dummy1, dummy2, ios
  character (len=256) :: tempfile
  !
  ALLOCATE(u_mat(n_wannier,n_wannier,iknum))
  ALLOCATE(u_mat_opt(num_bands,n_wannier,iknum))
  ALLOCATE(lwindow(num_bands,iknum))
  ALLOCATE(wann_centers(3,n_wannier))
  ALLOCATE(wann_spreads(n_wannier))
  !
  u_mat_opt = czero
  !
516
  IF (meta_ionode) THEN
sponce's avatar
sponce committed
517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536
     ! read in external eigenvalues, e.g.  GW
     IF (eig_read) then
        WRITE (stdout,'(5x,a,i5,a,i5,a)') "Reading electronic eigenvalues (", &
             nbnd, ",", iknum,")"
        tempfile=trim(prefix)//'.eig'
        OPEN(1, file=tempfile, form='formatted', action='read', iostat=ios)
        IF (ios /= 0) CALL errore ('run_wannier','error opening' // tempfile, 1)
        !
        ! the form should be band, kpt, eigenvalue
        !
        DO ik = 1, iknum
           DO ibnd = 1, nbnd
              READ (1,*) dummy1, dummy2, eigval (ibnd,ik)
              IF (dummy1.ne.ibnd) CALL errore('run_wannier', "Incorrect eigenvalue file", 1)
              IF (dummy2.ne.ik) CALL errore('run_wannier', "Incorrect eigenvalue file", 1)
           ENDDO
        ENDDO
        CLOSE(1)
     ENDIF
     !
sponce's avatar
sponce committed
537 538 539 540 541 542
! SP : This file is not used for now. Only required to build the UNK file
!      tempfile=trim(prefix)//'.mmn'
!      OPEN(iummn, file=tempfile, iostat=ios, form='unformatted')
!      WRITE(iummn) m_mat
!      CLOSE(iummn)

sponce's avatar
sponce committed
543
     CALL wannier_run(seedname2, mp_grid, iknum,   &                 ! input
sponce's avatar
sponce committed
544 545 546 547 548 549
           rlatt, glatt, kpt_latt, num_bands,       &                 ! input
           n_wannier, nnb, nat, atsym,              &                 ! input
           atcart, .false., m_mat, a_mat, eigval,   &                 ! input
           u_mat, u_mat_opt, lwindow, wann_centers, &                 ! output
           wann_spreads, spreads)                                     ! output

sponce's avatar
sponce committed
550
  ENDIF
sponce's avatar
sponce committed
551
  !
552 553 554 555 556 557
  CALL mp_bcast(u_mat,       meta_ionode_id, world_comm )
  CALL mp_bcast(u_mat_opt,   meta_ionode_id, world_comm )
  CALL mp_bcast(lwindow,     meta_ionode_id, world_comm )
  CALL mp_bcast(wann_centers,meta_ionode_id, world_comm )
  CALL mp_bcast(wann_spreads,meta_ionode_id, world_comm )
  CALL mp_bcast(spreads,     meta_ionode_id, world_comm )
sponce's avatar
sponce committed
558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582
  !
  !
  ! output the results of the wannierization
  !
  WRITE (stdout,*)
  WRITE (stdout,*) '    Wannier Function centers (cartesian, alat) and spreads (ang):'
  WRITE (stdout,*)
  ! RM - loop is up to n_wannier according to W90/wannierise.F90
  DO i=1,n_wannier
     WRITE (stdout, '(5x,"(",3f10.5,") :  ",f8.5)') wann_centers(:,i)/celldm(1)/bohr, wann_spreads(i)
  ENDDO
  WRITE (stdout,*)
  !
  ! store the final minimisation matrix on disk for later use
  !
  CALL write_filukk
  !
  RETURN
  !
END SUBROUTINE run_wannier
!-----------------------------------------------------------------------
!
!-----------------------------------------------------------------------
SUBROUTINE compute_amn_para
!-----------------------------------------------------------------------
583 584 585 586
!!  adapted from compute_amn in pw2wannier90.f90
!!  parallelization on k-points has been added
!!  10/2008 Jesse Noffsinger UC Berkeley
!!
587 588
  USE io_global,       ONLY : stdout 
  USE kinds,           ONLY : DP
589
  USE klist,           ONLY : xk, nks, igk_k
590 591 592 593 594 595 596 597 598 599 600 601 602 603
  USE wvfct,           ONLY : nbnd, npw, npwx, g2kin
  USE gvecw,           ONLY : ecutwfc
  USE wavefunctions_module,  ONLY : evc
  USE gvect,           ONLY : g, ngm
  USE cell_base,       ONLY : tpiba2
  USE uspp,            ONLY : nkb, vkb
  USE becmod,          ONLY : becp, calbec, deallocate_bec_type, allocate_bec_type
  USE wannier,         ONLY : csph, excluded_band, gf, num_bands, &
                              n_wannier, iknum, n_proj, a_mat,  spin_qaxis, &
                              spin_eig
  USE uspp_param,      ONLY : upf
  USE noncollin_module,ONLY : noncolin, npol
  USE constants_epw,   ONLY : czero, eps6
  USE mp_global,       ONLY : my_pool_id
604
#if defined(__NAG)
605
  USE f90_unix_io,    ONLY : flush
sponce's avatar
sponce committed
606
#endif
607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642
  USE mp_global,       ONLY : npool, intra_pool_comm, inter_pool_comm
  USE mp,              ONLY : mp_sum
  ! 
  implicit none
  ! 
  complex(DP) :: amn, ZDOTC, amn_tmp, fac(2)
  complex(DP), allocatable :: sgf(:,:)
  integer :: ik, ibnd, ibnd1, iw, nkq, nkq_abs, ipool, ik_g, ipol, &
             istart
  logical            :: any_uspp, spin_z_pos, spin_z_neg
  real(kind=DP)      :: zero_vect(3)
  !
  !nocolin: we have half as many projections g(r) defined as wannier
  !         functions. We project onto (1,0) (ie up spin) and then onto
  !         (0,1) to obtain num_wann projections. jry
  !
  any_uspp = ANY( upf(:)%tvanp )
  !
  IF (any_uspp .and. noncolin) CALL errore('pw2wan90epw',&
      'noncolin calculation not implimented with USP',1)
  !
  ALLOCATE( a_mat(num_bands,n_wannier,iknum))
  ALLOCATE( sgf(npwx,n_proj) )
  !
  ! initialize
  a_mat = czero
  zero_vect = 0.d0
  !
  WRITE (stdout,'(5x,a)') 'AMN'
  !
  IF (any_uspp) then
     CALL deallocate_bec_type ( becp )
     CALL allocate_bec_type ( nkb, n_wannier, becp )
     CALL init_us_1
  ENDIF
  !
643
#if defined(__MPI)
644
  WRITE(stdout,'(6x,a,i5,a,i4,a)') 'k points = ',iknum, ' in ', npool, ' pools'
sponce's avatar
sponce committed
645
#endif
646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684
  ! 
  DO ik=1,nks
    CALL ktokpmq ( xk(:,ik), zero_vect, +1, ipool, nkq, nkq_abs )
    ik_g = nkq_abs
    !
    WRITE (stdout,'(5x,i8, " of ", i4,a)') ik , nks, ' on ionode'
    CALL flush(6)
    ! SP: Replaced by our wrapper to deal with parallel
    CALL readwfc(my_pool_id+1, ik, evc) 
    !CALL davcio( evc, lrwfc, iuwfc, ik, -1 )
    !
    CALL gk_sort (xk(1,ik), ngm, g, ecutwfc / tpiba2, npw, igk_k (1,ik), g2kin)
    CALL generate_guiding_functions(ik)   ! they are called gf(npw,n_proj)
    !
    !  USPP
    !
    IF (any_uspp) THEN
       CALL init_us_2 (npw, igk_k(1,ik), xk (1, ik), vkb)
       ! below we compute the product of beta functions with trial func.
       CALL calbec ( npw, vkb, gf, becp, n_proj )
       ! and we use it for the product S|trial_func>
       CALL s_psi (npwx, npw, n_proj, gf, sgf)  
    ELSE
       sgf(:,:) = gf(:,:)
    ENDIF
    !
    IF (noncolin) THEN
      ! we do the projection as g(r)*a(r) and g(r)*b(r)
      DO iw = 1,n_proj
         spin_z_pos=.false.;spin_z_neg=.false.
         ! detect if spin quantisation axis is along z
         if((abs(spin_qaxis(1,iw)-0.0d0)<eps6).and.(abs(spin_qaxis(2,iw)-0.0d0)<eps6) &
              .and.(abs(spin_qaxis(3,iw)-1.0d0)<eps6)) then
            spin_z_pos=.true.
         elseif(abs(spin_qaxis(1,iw)-0.0d0)<eps6.and.abs(spin_qaxis(2,iw)-0.0d0)<eps6 &
              .and.abs(spin_qaxis(3,iw)+1.0d0)<eps6) then
            spin_z_neg=.true.
         endif
         IF(spin_z_pos .or. spin_z_neg) THEN
sponce's avatar
sponce committed
685 686 687
            ibnd1 = 0
            DO ibnd = 1,nbnd
               IF (excluded_band(ibnd)) CYCLE
688 689 690 691 692 693
               IF(spin_z_pos) THEN
                  ipol=(3-spin_eig(iw))/2
               ELSE
                  ipol=(3+spin_eig(iw))/2
               ENDIF
               istart = (ipol-1)*npwx + 1
sponce's avatar
sponce committed
694
               amn=(0.0_dp,0.0_dp)
695
               amn = zdotc(npw,evc(istart,ibnd),1,sgf(1,iw),1)
sponce's avatar
sponce committed
696 697
               CALL mp_sum(amn, intra_pool_comm)
               ibnd1=ibnd1+1
698 699
               ! 
               ! a_mat(ibnd1,iw+n_proj*(ipol-1),ik_g) = amn
sponce's avatar
sponce committed
700
               a_mat(ibnd1,iw,ik_g) = amn
701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758
            ENDDO
         ELSE
           ! general routine
           ! for quantisation axis (a,b,c) 
           ! 'up'    eigenvector is 1/sqrt(1+c) [c+1,a+ib]
           ! 'down'  eigenvector is 1/sqrt(1-c) [c-1,a+ib]
           IF(spin_eig(iw)==1) THEN
              fac(1)=(1.0_dp/sqrt(1+spin_qaxis(3,iw)))*(spin_qaxis(3,iw)+1)*cmplx(1.0d0,0.0d0,dp)
              fac(2)=(1.0_dp/sqrt(1+spin_qaxis(3,iw)))*cmplx(spin_qaxis(1,iw),spin_qaxis(2,iw),dp)
           ELSE
              fac(1)=(1.0_dp/sqrt(1+spin_qaxis(3,iw)))*(spin_qaxis(3,iw))*cmplx(1.0d0,0.0d0,dp)
              fac(2)=(1.0_dp/sqrt(1-spin_qaxis(3,iw)))*cmplx(spin_qaxis(1,iw),spin_qaxis(2,iw),dp)
           ENDIF
           ibnd1 = 0
           DO ibnd = 1,nbnd
              IF (excluded_band(ibnd)) CYCLE
              amn=(0.0_dp,0.0_dp)
              DO ipol=1,npol
                 istart = (ipol-1)*npwx + 1
                 amn_tmp=(0.0_dp,0.0_dp)
                 amn_tmp = zdotc(npw,evc(istart,ibnd),1,sgf(1,iw),1)
                 CALL mp_sum(amn_tmp, intra_pool_comm)
                 amn=amn+fac(ipol)*amn_tmp
              ENDDO
              ibnd1=ibnd1+1
              !a_mat(ibnd1,iw+n_proj*(ipol-1),ik_g) = amn
              a_mat(ibnd1,iw,ik_g) = amn
           ENDDO
         ENDIF ! spin_z_pos
      ENDDO
! -----------
    ELSE ! scalar wavefunction
      DO iw = 1,n_proj
         ibnd1 = 0
         DO ibnd = 1,nbnd
            IF (excluded_band(ibnd)) CYCLE
            amn=(0.0_dp,0.0_dp)
            amn = ZDOTC(npw,evc(1,ibnd),1,sgf(1,iw),1)
            CALL mp_sum(amn, intra_pool_comm)
            ibnd1=ibnd1+1
            a_mat(ibnd1,iw,ik_g) = amn
         ENDDO !bands
      ENDDO !wannier fns
    ENDIF
  ENDDO  ! k-points
  !
  DEALLOCATE (sgf)
  DEALLOCATE (csph)
  IF (any_uspp) CALL deallocate_bec_type ( becp )
  !
  CALL mp_sum(a_mat, inter_pool_comm)
  !
  !
  WRITE(stdout,*)
  WRITE(stdout,'(5x,a)') 'AMN calculated'
  !
  !
  RETURN
sponce's avatar
sponce committed
759 760 761 762 763 764 765 766 767 768 769 770 771
!-----------------------------------------------------------------------
END SUBROUTINE compute_amn_para
!-----------------------------------------------------------------------
!
!
!-----------------------------------------------------------------------
SUBROUTINE compute_mmn_para
!-----------------------------------------------------------------------
!
!  adapted from compute_mmn in pw2wannier90.f90
!  parallelization on k-points has been added
!  10/2008 Jesse Noffsinger UC Berkeley
!
772
   USE io_global,       ONLY : stdout, meta_ionode
sponce's avatar
sponce committed
773 774 775 776
   USE io_files,        ONLY : diropn
   USE mp_global,       ONLY : my_pool_id
   USE mp_global,       ONLY : npool, intra_pool_comm
   USE kinds,           ONLY : DP
777
   USE wvfct,           ONLY : nbnd, npw, npwx, g2kin
sponce's avatar
sponce committed
778 779 780 781 782 783 784
   USE gvecw,           ONLY : ecutwfc
   USE control_flags,   ONLY : gamma_only
   USE wavefunctions_module, ONLY : evc, psic, psic_nc
   USE units_ph,        ONLY : lrwfc, iuwfc
   USE gvecs,           ONLY : nls, nlsm
   USE fft_base,        ONLY : dffts
   USE fft_interfaces,  ONLY : fwfft, invfft
785
   USE klist,           ONLY : nkstot, xk, nks, igk_k
sponce's avatar
sponce committed
786 787 788 789 790 791 792 793 794 795
   USE gvect,           ONLY : g, ngm, gstart
   USE cell_base,       ONLY : tpiba2, omega, tpiba, bg
   USE ions_base,       ONLY : nat, ntyp => nsp, ityp, tau
   USE uspp,            ONLY : nkb, vkb
   USE uspp_param,      ONLY : upf, lmaxq, nh
   USE becmod,          ONLY : becp, calbec, allocate_bec_type, deallocate_bec_type
   USE noncollin_module,ONLY : noncolin, npol
   USE wannier,         ONLY : m_mat, num_bands, nnb, iknum, g_kpb, kpb, ig_, &
                               excluded_band
   USE constants_epw,   ONLY : czero, twopi
796
#if defined(__NAG)
sponce's avatar
sponce committed
797 798 799 800
   USE f90_unix_io,     ONLY : flush
#endif
   USE mp,              ONLY : mp_sum
   USE mp_global,       ONLY : inter_pool_comm
sponce's avatar
sponce committed
801
   ! 
sponce's avatar
sponce committed
802
   implicit none
sponce's avatar
sponce committed
803
   !
sponce's avatar
sponce committed
804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833
   integer :: mmn_tot ,ik, ikp, ib, npwq, i, m, n
   integer :: ikb, jkb, ih, jh, na, nt, ijkb0, ind, nbt
   complex(DP), allocatable :: phase(:), aux(:), aux2(:),  evcq(:,:), & 
                               Mkb(:,:), aux_nc(:,:),becp2(:,:)
   complex(DP), allocatable :: qb(:,:,:,:), qgm(:)
   real(DP), allocatable    :: qg(:), ylm(:,:), dxk(:,:)
   real(DP), ALLOCATABLE    :: rbecp2(:,:)
   integer, allocatable     :: igkq(:)
   real(DP)                 :: xktot(3,nkstot)
   real(DP), dimension(3)   :: zero_vect
   complex(DP)              :: mmn, ZDOTC, phase1
   real(DP)                 :: arg, g_(3)
   logical                  :: any_uspp, exst
   integer                  :: nkq, nkq_abs, ipool, ipol, istart, iend
   integer                  :: ik_g, ikp_g, ind0 !, iummn
   ! 
   any_uspp = ANY( upf(:)%tvanp )
   !
   IF (any_uspp .and. noncolin) CALL errore('pw2wan90epw',&
       'noncolin calculation not implimented with USP',1)
   !
   ALLOCATE( phase(dffts%nnr) ) 
   ALLOCATE( igkq(npwx) )
   ALLOCATE( evcq(npol*npwx,nbnd) )
   !
   IF (noncolin) THEN
      ALLOCATE( aux_nc(npwx,npol) )
   ELSE
      ALLOCATE( aux(npwx) )
   ENDIF
834
   !
sponce's avatar
sponce committed
835 836 837 838 839 840 841 842 843 844 845 846 847
   IF (gamma_only) ALLOCATE(aux2(npwx))
   !
   ALLOCATE(m_mat(num_bands,num_bands,nnb,iknum))
   !
   !
   ! close all the wfc files to allow access for each pool to all wfs
   CLOSE (unit = iuwfc,  status = 'keep')
   !
   WRITE (stdout,*)
   WRITE (stdout,'(5x,a)') 'MMN'
   !
   ! Get all the k-vector coords to each pool via xktot
   xktot = 0.d0
848
   IF (meta_ionode) then
sponce's avatar
sponce committed
849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917
      DO i = 1,nkstot
         xktot(:,i) = xk(:,i)
      ENDDO
   ENDIF
   CALL mp_sum(xktot, inter_pool_comm)
   !
   zero_vect = 0.0d0
   m_mat = czero
   !
   mmn_tot = iknum * nnb * nbnd * nbnd
   !
   !   USPP
   !
   IF(any_uspp) THEN
      CALL init_us_1
      CALL allocate_bec_type ( nkb, nbnd, becp )
      IF (gamma_only) THEN
         ALLOCATE ( rbecp2(nkb,nbnd))
      ELSE
         ALLOCATE ( becp2(nkb,nbnd) )
      ENDIF
   ENDIF
   !
   nbt = nnb * iknum
   !
   ALLOCATE( qg(nbt) )
   ALLOCATE (dxk(3,nbt))
   !
   ind = 0
   DO ik=1,iknum
      DO ib=1,nnb
         ind = ind + 1
         ikp = kpb(ik,ib) 
         !
         g_(:) = REAL( g_kpb(:,ik,ib) )
         CALL cryst_to_cart (1, g_, bg, 1)
         dxk(:,ind) = xktot(:,ikp) +g_(:) - xktot(:,ik) 
         qg(ind) = dxk(1,ind)*dxk(1,ind)+dxk(2,ind)*dxk(2,ind)+dxk(3,ind)*dxk(3,ind)
      ENDDO
  ENDDO
  !
  !  USPP
  !
  IF (any_uspp) THEN
     !
     ALLOCATE( ylm(nbt,lmaxq*lmaxq), qgm(nbt) )
     ALLOCATE( qb (nkb, nkb, ntyp, nbt) )
     !
     CALL ylmr2 (lmaxq*lmaxq, nbt, dxk, qg, ylm)
     qg(:) = sqrt(qg(:)) * tpiba
     !
     DO nt = 1, ntyp
        IF ( upf(nt)%tvanp ) THEN
           DO ih = 1, nh (nt)
              DO jh = 1, nh (nt)
                 CALL qvan2 (nbt, ih, jh, nt, qg, qgm, ylm)
                 qb (ih, jh, nt, 1:nbt) = omega * qgm(1:nbt)
              ENDDO
           ENDDO
        ENDIF
     ENDDO
     !
     DEALLOCATE (qg, qgm, ylm )
     !
  ENDIF
  !
  !
  ALLOCATE( Mkb(nbnd,nbnd) )
  !
918
#if defined(__MPI)
sponce's avatar
sponce committed
919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935
  WRITE(stdout,'(6x,a,i5,a,i4,a)') 'k points = ',iknum, ' in ', npool, ' pools'
#endif
  ! get the first k-point in this pool 
  CALL ktokpmq( xk(:, 1), zero_vect, +1, ipool, nkq, nkq_abs )
  ind0 = (nkq_abs-1) * nnb
  !
  ind = ind0
  DO ik=1,nks 
     CALL ktokpmq( xk(:, ik), zero_vect, +1, ipool, nkq, nkq_abs)
     ik_g = nkq_abs
     !
     WRITE (stdout,'(5x,i8, " of ", i4,a)') ik , nks, ' on ionode'
     CALL flush(6)
     !
     !
     CALL readwfc(my_pool_id+1, ik, evc)
     !
936
     CALL gk_sort (xk(1,ik), ngm, g, ecutwfc / tpiba2, npw, igk_k(1,ik), g2kin)
sponce's avatar
sponce committed
937 938 939 940
     !
     !  USPP
     !
     IF (any_uspp) THEN
941
        CALL init_us_2 (npw, igk_k(1,ik), xk(1,ik), vkb)
sponce's avatar
sponce committed
942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987
        CALL calbec(npw, vkb, evc, becp) 
     ENDIF
     !
     !
     DO ib=1,nnb  ! loop on finite diff vectors
        ind = ind + 1
        !
        ikp = kpb(ik_g,ib)
        ikp_g = ikp 
        !
        CALL ktokpmq( xk(:, ik), xktot(:,ikp_g)-xk(:,ik), +1, ipool, nkq, nkq_abs )
        !
        ! read wfc at k+b
        !
        CALL readwfc( ipool, nkq, evcq )
        !
        CALL gk_sort (xktot(1,ikp_g), ngm, g, ecutwfc / tpiba2, npwq, igkq, g2kin)
        !
        ! compute the phase
        !
        phase(:) = (0.d0,0.d0)
        IF ( ig_(ik_g,ib)>0) phase( nls(ig_(ik_g,ib)) ) = (1.d0,0.d0)
        CALL invfft ('Wave', phase, dffts)
        !
        !  USPP
        !
        IF(any_uspp) THEN
           CALL init_us_2 (npwq, igkq, xk(1,ikp), vkb)
           ! below we compute the product of beta functions with |psi>
           IF (gamma_only) THEN
              CALL calbec ( npwq, vkb, evcq, rbecp2 )
           ELSE
              CALL calbec ( npwq, vkb, evcq, becp2 )
           ENDIF
        ENDIF
        !
        !
        Mkb(:,:) = (0.0d0,0.0d0) 
        !
        IF (any_uspp) THEN
           ijkb0 = 0
           DO nt = 1, ntyp
              IF ( upf(nt)%tvanp ) THEN
                 DO na = 1, nat
                    !
                    arg = DOT_PRODUCT( dxk(:,ind), tau(:,na) ) * twopi
988
                    phase1 = CMPLX ( COS(arg), -SIN(arg), kind=DP )
sponce's avatar
sponce committed
989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036
                    !
                    IF ( ityp(na) == nt ) THEN
                       DO jh = 1, nh(nt)
                          jkb = ijkb0 + jh
                          DO ih = 1, nh(nt)
                             ikb = ijkb0 + ih
                             !
                             DO m = 1,nbnd
                               IF (excluded_band(m)) CYCLE
                               IF (gamma_only) THEN
                                 DO n=1,m ! Mkb(m,n) is symmetric in m and n for gamma_only case
                                    IF (excluded_band(n)) CYCLE
                                    Mkb(m,n) = Mkb(m,n) + &
                                         phase1 * qb(ih,jh,nt,ind) * &
                                         becp%r(ikb,m) * rbecp2(jkb,n)
                                 ENDDO
                               ELSE
                                 DO n=1,nbnd
                                    IF (excluded_band(n)) CYCLE
                                    Mkb(m,n) = Mkb(m,n) + &
                                         phase1 * qb(ih,jh,nt,ind) * &
                                         conjg( becp%k(ikb,m) ) *becp2(jkb,n)

                                 ENDDO
                               ENDIF
                             ENDDO ! m
                          ENDDO !ih
                       ENDDO !jh
                       ijkb0 = ijkb0 + nh(nt)
                    ENDIF  !ityp
                 ENDDO  !nat 
              ELSE  !tvanp
                 DO na = 1, nat
                    IF ( ityp(na) == nt ) ijkb0 = ijkb0 + nh(nt)
                 ENDDO
              ENDIF !tvanp
           ENDDO !ntyp
        ENDIF ! any_uspp
        !
        !
        DO m=1,nbnd  ! loop on band m
           IF (excluded_band(m)) CYCLE
           !
           IF (noncolin) THEN
              psic_nc(:,:) = (0.d0, 0.d0)
              DO ipol=1,2!npol
                 istart=(ipol-1)*npwx+1
                 iend=istart+npw-1
1037
                 psic_nc(nls (igk_k (1:npw,ik) ),ipol ) = evc(istart:iend, m)
sponce's avatar
sponce committed
1038 1039 1040 1041 1042 1043 1044 1045
                 CALL invfft ('Wave', psic_nc(:,ipol), dffts)
                 psic_nc(1:dffts%nnr,ipol) = psic_nc(1:dffts%nnr,ipol) * &
                                               phase(1:dffts%nnr)
                 CALL fwfft ('Wave', psic_nc(:,ipol), dffts)
                 aux_nc(1:npwq,ipol) = psic_nc(nls (igkq(1:npwq) ),ipol )
              ENDDO
           ELSE
              psic(:) = (0.d0, 0.d0)
1046 1047
              psic(nls (igk_k (1:npw,ik) ) ) = evc (1:npw, m)
              IF(gamma_only) psic(nlsm(igk_k (1:npw,ik) ) ) = conjg(evc (1:npw, m))
sponce's avatar
sponce committed
1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094
              CALL invfft ('Wave', psic, dffts)
              psic(1:dffts%nnr) = psic(1:dffts%nnr) * phase(1:dffts%nnr)
              CALL fwfft ('Wave', psic, dffts)
              aux(1:npwq)  = psic(nls (igkq(1:npwq) ) )
           ENDIF
           IF(gamma_only) THEN
              IF (gstart==2) psic(nlsm(1)) = (0.d0,0.d0)
              aux2(1:npwq) = conjg(psic(nlsm(igkq(1:npwq) ) ) )
           ENDIF
         !  aa = 0.d0
           !
           !  Mkb(m,n) = Mkb(m,n) + \sum_{ijI} qb_{ij}^I * e^-i(b*tau_I)
           !             <psi_m,k1| beta_i,k1 > < beta_j,k2 | psi_n,k2 > 
           !
           IF (gamma_only) THEN
             DO n=1,m ! Mkb(m,n) is symmetric in m and n for gamma_only case
                IF (excluded_band(n)) CYCLE
                mmn = zdotc (npwq, aux,1,evcq(1,n),1) &
                     + conjg(zdotc(npwq,aux2,1,evcq(1,n),1))
                CALL mp_sum(mmn, intra_pool_comm)
                Mkb(m,n) = mmn + Mkb(m,n)
                IF (m/=n) Mkb(n,m) = Mkb(m,n) ! fill other half of matrix by symmetry
             ENDDO
           ELSEIF (noncolin) THEN
              DO n=1,nbnd
                 IF (excluded_band(n)) CYCLE
                 mmn=(0.d0, 0.d0)
!                 DO ipol=1,2
!                    mmn = mmn+ZDOTC (npwq, aux_nc(1,ipol),1,evcq_nc(1,ipol,n),1)
                 mmn = mmn + ZDOTC (npwq, aux_nc(1,1),1,evcq(1,n),1) &
                       + ZDOTC (npwq, aux_nc(1,2),1,evcq(npwx+1,n),1)
!                 ENDDO
                 CALL mp_sum(mmn, intra_pool_comm)
                 Mkb(m,n) = mmn + Mkb(m,n)
               !  aa = aa + abs(mmn)**2
              ENDDO
           ELSE
              DO n=1,nbnd
                 IF (excluded_band(n)) CYCLE
                 mmn = ZDOTC (npwq, aux,1,evcq(1,n),1)
                 CALL mp_sum(mmn, intra_pool_comm)
                 Mkb(m,n) = mmn + Mkb(m,n)
!                 aa = aa + abs(mmn)**2
              ENDDO
           ENDIF
        ENDDO   ! m
        !
1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109
        ! SP: This should be the correct implementation but requires also changes
        !     at the level of m_mat a_mat dim etc. 
        !     Currently EPW uses all bands. exclude_band cannot be used. 
        !     We use nbndskip
        !ibnd_n = 0
        !DO n=1,nbnd
        !   IF (excluded_band(n)) CYCLE
        !   ibnd_n = ibnd_n + 1
        !   ibnd_m = 0
        !   DO m=1,nbnd
        !      IF (excluded_band(m)) CYCLE
        !      ibnd_m = ibnd_m + 1
        !      m_mat(ibnd_m,ibnd_n,ib,ik_g)=Mkb(m,n)
        !   ENDDO
        !ENDDO
sponce's avatar
sponce committed
1110 1111 1112 1113
        DO n=1,nbnd
           IF (excluded_band(n)) CYCLE
           DO m=1,nbnd
              IF (excluded_band(m)) CYCLE
1114
              m_mat(m,n,ib,ik_g)=Mkb(m,n)
sponce's avatar
sponce committed
1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156
           ENDDO
        ENDDO
        !
        !
     ENDDO !ib
  ENDDO !ik
  !
  CALL mp_sum(m_mat, inter_pool_comm)
  !
  IF (gamma_only) DEALLOCATE(aux2)
  DEALLOCATE (Mkb, dxk, phase, evcq, igkq)
  IF (noncolin) THEN
     DEALLOCATE(aux_nc)
  ELSE
     DEALLOCATE(aux)
  ENDIF
  IF(any_uspp) THEN
     DEALLOCATE (  qb)
     CALL deallocate_bec_type (becp)
     IF (gamma_only) THEN
         DEALLOCATE (rbecp2)
      ELSE
         DEALLOCATE (becp2)
      ENDIF
   ENDIF
  !
  !
  WRITE(stdout,'(5x,a)') 'MMN calculated'
  !
  ! reopen wfc here, leaving unit=20 in the same state
  iuwfc = 20
  CALL diropn(iuwfc,'wfc',lrwfc,exst)  
  !
  RETURN
END SUBROUTINE compute_mmn_para
!
!------------------------------------------------------------------------
!
!-----------------------------------------------------------------------
SUBROUTINE compute_pmn_para
!-----------------------------------------------------------------------
!
1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260
!!
!!  Computes dipole matrix elements.
!!  This can be used to compute the velocity in the local approximation.
!!  The commutator with the non-local psp is neglected.
!!
!!  06/2010  Jesse Noffsinger: adapted from compute_amn_para
!!  08/2016  Samuel Ponce: adapted to work with SOC
!! 
!
  USE io_global,       ONLY : stdout
  USE mp,              ONLY : mp_sum
  USE kinds,           ONLY : DP
  USE klist,           ONLY : xk, nks, igk_k
  USE wvfct,           ONLY : nbnd, npw, npwx, g2kin
  USE gvecw,           ONLY : ecutwfc
  USE wavefunctions_module,  ONLY : evc
  USE units_ph,        ONLY : lrwfc, iuwfc
  USE gvect,           ONLY : g, ngm
  USE cell_base,       ONLY : tpiba2, tpiba
  USE noncollin_module,ONLY : noncolin
  USE elph2,           ONLY : dmec
  USE constants_epw,   ONLY : czero
  USE uspp_param,      ONLY : upf
  USE becmod,          ONLY : becp, deallocate_bec_type, allocate_bec_type
  USE uspp,            ONLY : nkb
  USE wannier,         ONLY : n_wannier
  !
  implicit none
  !  
  LOGICAL :: any_uspp
  !! Check if USPP is present
  !
  INTEGER :: ik
  !! Counter on k-point
  INTEGER :: ibnd
  !! Conter on bands
  INTEGER :: jbnd
  !! Conter on bands
  INTEGER :: ig
  !! Counter on G vector
  ! 
  COMPLEX(kind=DP) :: dipole_aux(3,nbnd,nbnd)
  !! Auxilary dipole
  COMPLEX(kind=DP) :: caux 
  !! Wavefunction squared
  !
  any_uspp = ANY( upf(:)%tvanp )
  !
  IF (any_uspp .and. noncolin) CALL errore('pw2wan90epw',&
             'noncolin calculation not implimented with USP',1)
  !
  ALLOCATE( dmec(3,nbnd,nbnd,nks) )
  !
  ! initialize
  dmec = czero
  dipole_aux(:,:,:) = (0.0d0,0.0d0)
  !
  IF (any_uspp) then
    CALL deallocate_bec_type ( becp )
    CALL allocate_bec_type ( nkb, n_wannier, becp )
    CALL init_us_1
  ENDIF
  !
  DO ik=1,nks
    !
    ! read wfc for the given kpt
    CALL davcio( evc, lrwfc, iuwfc, ik, -1 )
    !
    ! setup k+G grids for each kpt
    !CALL gk_sort (xk(1,ik), ngm, g, ecutwfc / tpiba2, npw, igk_k(1,ik), g2kin)
    !
    dipole_aux = (0.d0, 0.d0)
    DO jbnd = 1,nbnd
      DO ibnd = 1,nbnd
        !
        IF ( ibnd .eq. jbnd ) CYCLE
        !
        ! taken from PP/epsilon.f90 SUBROUTINE dipole_calc
        DO ig = 1, npw
          IF (igk_k(ig,ik) > SIZE(g,2) .or. igk_k(ig,ik) < 1) CYCLE
          !
          caux = conjg(evc(ig,ibnd))*evc(ig,jbnd) 
          !
          IF (noncolin) THEN
             !
             caux = caux + conjg(evc(ig+npwx,ibnd))*evc(ig+npwx,jbnd)
             !
          ENDIF
          !
          dipole_aux(:,ibnd,jbnd) = dipole_aux(:,ibnd,jbnd) + &
                                  ( g(:,igk_k(ig,ik)) ) * caux
          !
        ENDDO
        !
      ENDDO !bands i
    ENDDO ! bands j
    ! metal diagonal part
    DO ibnd = 1, nbnd
       DO ig = 1, npw
         IF (igk_k(ig,ik) > SIZE(g,2) .or. igk_k(ig,ik) < 1) CYCLE
         !
         caux = conjg(evc(ig,ibnd))*evc(ig,ibnd) 
         !
         IF (noncolin) THEN
sponce's avatar
sponce committed
1261
            !
1262
            caux = caux + conjg(evc(ig+npwx,ibnd))*evc(ig+npwx,ibnd)
sponce's avatar
sponce committed
1263
            !
1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280
         ENDIF
         !
         dipole_aux(:,ibnd,ibnd) = dipole_aux(:,ibnd,ibnd) + &
                                         ( g(:,igk_k(ig,ik)) + xk(:,ik) ) * caux
         !
       ENDDO
    ENDDO
    ! need to divide by 2pi/a to fix the units
    dmec(:,:,:,ik) = dipole_aux(:,:,:) * tpiba
    !
  ENDDO  ! k-points
  !
  !
  WRITE(stdout,'(/5x,a)') 'Dipole matrix elements calculated'
  WRITE(stdout,*)
  !
  RETURN
sponce's avatar
sponce committed
1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299
END SUBROUTINE compute_pmn_para
!-----------------------------------------------------------------------
!!
!-----------------------------------------------------------------------
SUBROUTINE write_filukk
!-----------------------------------------------------------------------
!
!  Here we compute and write out the final ukk matrix which is used by
!  epw.x to localize the electron wavefuctions (and therefore the ep-matrix 
!  elements)
!  10/2008 Jesse Noffsinger UC Berkeley
!  07/2010 Fixed the rotation for ndimwin when lower bands are not included
!
   USE kinds,        ONLY : DP
   USE io_epw,       ONLY : iuukk
   USE wvfct,        ONLY : nbnd
   USE wannier,      ONLY : n_wannier, iknum, u_mat, u_mat_opt, lwindow
   USE epwcom,       ONLY : filukk
   USE constants_epw,ONLY : czero
1300
   USE io_global,    ONLY : meta_ionode
sponce's avatar
sponce committed
1301 1302 1303 1304 1305 1306 1307 1308
   !
   implicit none
   !
   complex(kind=DP), allocatable :: u_kc(:,:,:)
   integer :: jbnd, k_wan, ik, ndimwin(iknum)
   !
   !
   !
1309
   IF (meta_ionode) THEN
sponce's avatar
sponce committed
1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344
     !
     ndimwin(:) = 0
     DO ik = 1, iknum
        DO jbnd = 1, nbnd
           IF (lwindow(jbnd,ik)) ndimwin(ik) = ndimwin(ik) + 1
        ENDDO
     ENDDO
     ALLOCATE( u_kc(nbnd, n_wannier, iknum) )
     u_kc = czero
     !
     ! get the final rotation matrix, which is the product of the optimal
     ! subspace and the rotation among the n_wannier wavefunctions
     DO ik = 1, iknum
        !
        u_kc(1:ndimwin(ik),1:n_wannier,ik) = &
             matmul (u_mat_opt(1:ndimwin(ik),:,ik), u_mat(:,1:n_wannier,ik))
        !
     ENDDO
     !
     open (unit = iuukk, file = filukk, form = 'formatted')
     DO ik = 1,iknum
        DO jbnd = 1, nbnd
           DO k_wan = 1, n_wannier
              WRITE (iuukk,*) u_kc(jbnd,k_wan,ik)
           ENDDO
        ENDDO
     ENDDO
     ! needs also lwindow when disentanglement is used
     DO ik = 1,iknum
        DO jbnd = 1,nbnd
           WRITE (iuukk,*) lwindow(jbnd,ik)
        ENDDO
     ENDDO
     close (iuukk)
     IF ( ALLOCATED(u_kc) ) DEALLOCATE(u_kc)
sponce's avatar
sponce committed
1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362
   ENDIF
   !
!-----------------------------------------------------------------------
END SUBROUTINE write_filukk
!-----------------------------------------------------------------------


!-----------------------------------------------------------------------
SUBROUTINE phases_a_m
!-----------------------------------------------------------------------
! will set phases here on the matrices.  Should not affect the spreads and
! centers found in w90, but will leave the u_mat_opt and u_mat to reflect the
! known phases
!
!
   USE mp_global,       ONLY : inter_pool_comm
   USE mp,              ONLY : mp_sum
   USE kinds,           ONLY : DP
1363
   USE io_global,       ONLY : meta_ionode
sponce's avatar
sponce committed
1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379
   USE klist,           ONLY : nkstot, xk, nks
   USE wvfct,           ONLY : nbnd
   USE wannier,         ONLY : a_mat, m_mat, n_wannier, nnb, kpb, iknum
   USE elph2,           ONLY : umat, umat_all
   USE constants_epw,   ONLY : czero, cone

   implicit none

   integer                      ::  ik, ipool, ib, ikb, i,nkq, &
                                    ik_g
   real(kind=DP)                ::  xktot(3,nkstot)
   complex(kind=DP), allocatable ::  a_mat_tmp(:,:,:), m_mn_tmp1(:,:), &
       m_mn_tmp2(:,:), m_mn_tmp3(:,:,:,:)
   real(DP), dimension(3)   :: zero_vect

   xktot = 0.d0
1380
   IF (meta_ionode) then
sponce's avatar
sponce committed
1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462
      DO i = 1,nkstot
         xktot(:,i) = xk(:,i)
      ENDDO
   ENDIF
   CALL mp_sum(xktot, inter_pool_comm)
   !
   ALLOCATE(m_mn_tmp3(nbnd,nbnd,nnb,iknum))
   ALLOCATE(a_mat_tmp(nbnd,n_wannier,iknum)) 
   ALLOCATE(m_mn_tmp1(nbnd,nbnd))
   ALLOCATE(m_mn_tmp2(nbnd,nbnd))
   !
   ! zero all temporary/work quantities
   !
   zero_vect = 0.0d0
   a_mat_tmp = czero
   m_mn_tmp1 = czero
   m_mn_tmp2 = czero
   m_mn_tmp3 = czero
   !
   DO ik=1,nks
      CALL ktokpmq ( xk(:,ik), zero_vect, +1, ipool, nkq, ik_g )
      !
      !  GF_n are the guiding functions which are our initial guesses 
      !  Amn(k) = <psi_k,m|GF_n>.  
      !  We want U(k)^dagger<psi_k,m|GF_m>
      !
      CALL zgemm ('c', 'n', nbnd, n_wannier, nbnd, cone, umat(:,:,ik), & 
           nbnd, a_mat(:,:,ik_g), nbnd, czero, a_mat_tmp(:,:,ik_g), nbnd)
      !
   ENDDO
   CALL mp_sum(a_mat_tmp, inter_pool_comm)
   !
   a_mat(:,:,:) = a_mat_tmp(:,:,:)
   !
   !
   DO ik=1,nks
      CALL ktokpmq ( xk(:,ik), zero_vect, +1, ipool, nkq, ik_g )
      !
      DO ib = 1,nnb
         ikb = kpb(ik_g,ib)
         !
         ! Mmn(k,k+b)  = <psi_k_m| psi_(k+b)_n> so we need
         !  (U(k)^dagger <psi_k_m| ) * (|psi_k+b_n> U(k+b)
         ! = U(k)^dagger (M_mn) = m_mat_tmp, 
         ! Mmn(k,k+b)' = m_mat_tmp*U(k+b) 
         !
         CALL zgemm ('c', 'n', nbnd, nbnd, nbnd, cone, umat(:,:,ik), & 
              nbnd, m_mat(:,:,ib,ik_g), nbnd, czero, m_mn_tmp1(:,:), nbnd)
         CALL zgemm ('n', 'n', nbnd, nbnd, nbnd, cone, m_mn_tmp1(:,:), & 
              nbnd, umat_all(:,:,ikb), nbnd, czero, m_mn_tmp2(:,:), nbnd)
         !         !
         !         m_mn_tmp1 = matmul ( conjg( transpose (umat(:,:,ik) )), m_mat(:,:,ib,ik_g ) )
         !         m_mn_tmp2 = matmul ( m_mn_tmp1, umat_g(:,:,ikb) )
         !
         m_mn_tmp3(:,:,ib,ik_g) = m_mn_tmp2
      ENDDO
   ENDDO
   CALL mp_sum(m_mn_tmp3, inter_pool_comm)

   m_mat(:,:,:,:) = m_mn_tmp3(:,:,:,:)
   !
   DEALLOCATE(m_mn_tmp3, m_mn_tmp2, m_mn_tmp1, a_mat_tmp)
   !
   !
   RETURN
!-----------------------------------------------------------------------
END SUBROUTINE phases_a_m
!-----------------------------------------------------------------------
!
!---------------------------------------
!
! SUBROUTINEs below are largely unchanged
! from pw2wannier90.x of esp-4.0.1
!
!---------------------------------------
!
SUBROUTINE generate_guiding_functions(ik)
   !
   USE kinds,          ONLY : DP
   USE mp_global,      ONLY : intra_pool_comm
   USE mp,             ONLY : mp_sum
   USE constants,      ONLY : tpi, eps8
1463
   USE wvfct,          ONLY : npw
sponce's avatar
sponce committed
1464 1465 1466 1467
   USE gvect,          ONLY : g
   USE cell_base,      ONLY : tpiba
   USE wannier,        ONLY : n_proj, gf, center_w, csph, alpha_w, &
                              r_w
1468
   USE klist,          ONLY : xk, igk_k 
sponce's avatar
sponce committed
1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482

   implicit none

   integer, parameter :: lmax=3, lmax2=(lmax+1)**2
   integer :: iw, ig, ik, l
   integer :: lm, iig
   real(DP) :: arg, anorm
   complex(DP) :: ZDOTC, lphase
   real(DP), allocatable :: gk(:,:), qg(:), ylm(:,:), radial(:,:)
   complex(DP), allocatable :: sk(:) 
   !
   ALLOCATE( gk(3,npw), qg(npw), ylm(npw,lmax2), sk(npw), radial(npw,0:lmax) )
   !
   DO ig = 1, npw
1483 1484 1485
      gk (1,ig) = xk(1, ik) + g(1, igk_k(ig,ik) )
      gk (2,ig) = xk(2, ik) + g(2, igk_k(ig,ik) )
      gk (3,ig) = xk(3, ik) + g(3, igk_k(ig,ik) )
sponce's avatar
sponce committed
1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509
      qg(ig) = gk(1, ig)**2 +  gk(2, ig)**2 + gk(3, ig)**2
   ENDDO

   CALL ylmr2 (lmax2, npw, gk, qg, ylm)
   ! define qg as the norm of (k+g) in a.u.
   qg(:) = sqrt(qg(:)) * tpiba
   ! RM changed according to QE4.0.3/PP/pw2wannier90 
   Do iw = 1, n_proj
   !DO iw = 1, n_wannier
      !
      gf(:,iw) = (0.d0,0.d0)

      CALL radialpart(npw, qg, alpha_w(iw), r_w(iw), lmax, radial) 

      DO lm = 1, lmax2
         IF ( abs(csph(lm,iw)) < eps8 ) CYCLE
         l = int (sqrt( lm-1.d0))
         lphase = (0.d0,-1.d0)**l
         !
         DO ig=1,npw
            gf(ig,iw) = gf(ig,iw) + csph(lm,iw) * ylm(ig,lm) * radial(ig,l) * lphase
         ENDDO !ig
      ENDDO ! lm
      DO ig=1,npw
1510
         iig = igk_k(ig,ik)
sponce's avatar
sponce committed
1511 1512 1513
         arg = ( gk(1,ig)*center_w(1,iw) + gk(2,ig)*center_w(2,iw) + &
                                           gk(3,ig)*center_w(3,iw) ) * tpi
         ! center_w are cartesian coordinates in units of alat 
1514
         sk(ig) = CMPLX(cos(arg), -sin(arg) , kind=DP)
sponce's avatar
sponce committed
1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561
         gf(ig,iw) = gf(ig,iw) * sk(ig) 
      ENDDO
      anorm = REAL(ZDOTC(npw,gf(1,iw),1,gf(1,iw),1))
      CALL mp_sum(anorm, intra_pool_comm)
      gf(:,iw) = gf(:,iw) / dsqrt(anorm)
   ENDDO
   !
   DEALLOCATE ( gk, qg, ylm, sk, radial)
   !
   RETURN
END SUBROUTINE generate_guiding_functions

SUBROUTINE write_band
   USE wvfct,         ONLY : nbnd, et
   USE constants_epw, ONLY: ryd2ev
   USE wannier

   implicit none

   integer ik, ibnd, ibnd1, ikevc

   ALLOCATE(eigval(num_bands,iknum))

   DO ik=ikstart,ikstop
      ikevc = ik - ikstart + 1
      ibnd1=0
      DO ibnd=1,nbnd
         IF (excluded_band(ibnd)) CYCLE
         ibnd1=ibnd1 + 1
         eigval(ibnd1,ikevc) = et(ibnd,ik)*ryd2ev
      ENDDO
   ENDDO
   !
   RETURN
END SUBROUTINE write_band

!---------------------------------------
SUBROUTINE write_plot
!---------------------------------------
!
! JN 06/2009: 
! added a couple of calls -- now works with multiple
! pools/procs (but one proc per pool)
!
   USE kinds,           ONLY : DP
   USE io_global,       ONLY : stdout
   USE io_epw,          ONLY : iun_plot
1562
   USE wvfct,           ONLY : nbnd, npw, g2kin
sponce's avatar
sponce committed
1563 1564 1565 1566 1567 1568 1569
   USE gvecw,           ONLY : ecutwfc
   USE control_flags,   ONLY : gamma_only
   USE wavefunctions_module, ONLY : evc, psic
   USE units_ph,        ONLY : lrwfc, iuwfc
   USE wannier,         ONLY : reduce_unk, wvfn_formatted, ispinw, nexband, &
                               excluded_band 
   USE gvecs,           ONLY : nls, nlsm
1570
   USE klist,           ONLY : xk, nks, igk_k
sponce's avatar
sponce committed
1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586
   USE gvect,           ONLY : g, ngm 
   USE cell_base,       ONLY : tpiba2
   USE fft_base,        ONLY : dffts
   USE fft_interfaces,  ONLY : invfft
   USE noncollin_module,ONLY : noncolin
   USE scatter_mod,        ONLY : gather_grid
   !
   implicit none
   integer ik, ibnd, ibnd1, j, spin, nkq, nkq_abs, ipool
   character(len=20) wfnname

   ! aam: 1/5/06: for writing smaller unk files 
   integer :: n1by2,n2by2,n3by2,i,k,idx,pos
   COMPLEX(DP),allocatable :: psic_small(:)   
   real(kind=DP)      :: zero_vect(3)
   !-------------------------------------------!
1587
#if defined(__MPI)
sponce's avatar
sponce committed
1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631
   integer nxxs
   COMPLEX(DP),allocatable :: psic_all(:)
   nxxs = dffts%nr1x * dffts%nr2x * dffts%nr3x
   ALLOCATE(psic_all(nxxs) )
#endif
   !
   IF (noncolin) CALL errore('pw2wan90epw',&
       'write_unk not implemented with noncolin',1)
   !
   zero_vect = 0.d0
   WRITE (stdout,*) '    Writing out UNK plot files'
   !
   IF (reduce_unk) then
      WRITE(stdout,'(3(a,i5))') 'nr1s =',dffts%nr1,'nr2s=',dffts%nr2,'nr3s=',dffts%nr3
      n1by2=(dffts%nr1+1)/2;n2by2=(dffts%nr2+1)/2;n3by2=(dffts%nr3+1)/2
      WRITE(stdout,'(3(a,i5))') 'n1by2=',n1by2,'n2by2=',n2by2,'n3by2=',n3by2
      ALLOCATE(psic_small(n1by2*n2by2*n3by2))   
   ENDIF
   !
   DO ik=1,nks
      CALL ktokpmq ( xk(:,ik), zero_vect, +1, ipool, nkq, nkq_abs )
      !
      spin=ispinw
      IF(ispinw.eq.0) spin=1
      WRITE(wfnname,200) nkq_abs, spin
200   FORMAT ('UNK',i5.5,'.',i1)
      !
      IF (wvfn_formatted) THEN 
         OPEN (unit=iun_plot, file=wfnname,form='formatted')
         IF (reduce_unk) THEN
            WRITE(iun_plot,*)  n1by2,n2by2,n3by2, nkq_abs, nbnd-nexband
         ELSE
            WRITE(iun_plot,*)  dffts%nr1,dffts%nr2,dffts%nr3, nkq_abs, nbnd-nexband
         ENDIF
      ELSE
         OPEN (unit=iun_plot, file=wfnname,form='unformatted')
         IF (reduce_unk) THEN
            WRITE(iun_plot)  n1by2,n2by2,n3by2, nkq_abs, nbnd-nexband
         ELSE
            WRITE(iun_plot)  dffts%nr1,dffts%nr2,dffts%nr3, nkq_abs, nbnd-nexband
         ENDIF
      ENDIF
      !
      CALL davcio (evc, lrwfc, iuwfc, ik, -1 )
1632
      CALL gk_sort (xk(1,ik), ngm, g, ecutwfc / tpiba2, npw, igk_k(1,ik), g2kin)
sponce's avatar
sponce committed
1633 1634 1635 1636 1637 1638
      !
      ibnd1 = 0
      DO ibnd=1,nbnd
         IF (excluded_band(ibnd)) CYCLE
         ibnd1=ibnd1 + 1
         psic(:) = (0.d0, 0.d0)
1639 1640
         psic(nls (igk_k (1:npw,ik) ) ) = evc (1:npw, ibnd)
         IF (gamma_only)  psic(nlsm(igk_k (1:npw,ik) ) ) = conjg(evc (1:npw, ibnd))
sponce's avatar
sponce committed
1641 1642
         CALL invfft ('Wave', psic, dffts)
         IF (reduce_unk) pos=0
1643
#if defined(__MPI)
sponce's avatar
sponce committed
1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704
         CALL gather_grid(dffts,psic,psic_all)
         !
         IF (reduce_unk) THEN
            DO k=1,dffts%nr3,2
               DO j=1,dffts%nr2,2
                  DO i=1,dffts%nr1,2
                     idx = (k-1)*dffts%nr3*dffts%nr2 + (j-1)*dffts%nr2 + i
                     pos=pos+1
                     psic_small(pos) = psic_all(idx) 
                  ENDDO
               ENDDO
            ENDDO
         ENDIF
         !
         IF (wvfn_formatted) THEN
            IF (reduce_unk) THEN
               WRITE (iun_plot,'(2ES20.10)') (psic_small(j),j=1,n1by2*n2by2*n3by2)
            ELSE
               WRITE (iun_plot,*) (psic_all(j),j=1,dffts%nr1*dffts%nr2*dffts%nr3)
            ENDIF
         ELSE
            IF (reduce_unk) THEN
               WRITE (iun_plot) (psic_small(j),j=1,n1by2*n2by2*n3by2)
            ELSE
               WRITE (iun_plot) (psic_all(j),j=1,dffts%nr1*dffts%nr2*dffts%nr3)
            ENDIF
         ENDIF
#else
         IF (reduce_unk) THEN
            DO k=1,dffts%nr3,2
               DO j=1,dffts%nr2,2
                  DO i=1,dffts%nr1,2
                     idx = (k-1)*dffts%nr3*dffts%nr2 + (j-1)*dffts%nr2 + i
                     pos=pos+1
                     psic_small(pos) = psic(idx) 
                  ENDDO
               ENDDO
            ENDDO
         ENDIF
         IF (wvfn_formatted) THEN
            IF (reduce_unk) THEN
               WRITE (iun_plot,'(2ES20.10)') (psic_small(j),j=1,n1by2*n2by2*n3by2)
            ELSE
               WRITE (iun_plot,*) (psic(j),j=1,dffts%nr1*dffts%nr2*dffts%nr3)
            ENDIF
         ELSE
            IF (reduce_unk) THEN
               WRITE (iun_plot) (psic_small(j),j=1,n1by2*n2by2*n3by2)
            ELSE
               WRITE (iun_plot) (psic(j),j=1,dffts%nr1*dffts%nr2*dffts%nr3)
            ENDIF
         ENDIF
#endif
      ENDDO !ibnd
      !
      CLOSE (iun_plot)
      !
   ENDDO  !ik
   !
   IF (reduce_unk) DEALLOCATE(psic_small)   
   !
1705
#if defined(__MPI)
sponce's avatar
sponce committed
1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131
   DEALLOCATE( psic_all )
#endif
   !
   RETURN
END SUBROUTINE write_plot
!---------------------------------------
SUBROUTINE ylm_expansion 
   USE kinds,         ONLY : DP
   USE random_numbers,ONLY : randy
   USE wannier,       ONLY : n_proj , xaxis, zaxis, csph, l_w, mr_w
   USE matrix_inversion, ONLY: invmat