hsefunctional.F90 111 KB
Newer Older
1 2 3 4 5 6
!--------------------------------------------------------------------------------
! Copyright (c) 2016 Peter Grünberg Institut, Forschungszentrum Jülich, Germany
! This file is part of FLEUR and available as free software under the conditions
! of the MIT license as expressed in the LICENSE file in more detail.
!--------------------------------------------------------------------------------

7 8 9 10
! Provides all procedures needed to implement the HSE-exchange functional
! within a FLAPW framework
! Author: M. Schlipf 2009
MODULE m_hsefunctional
11
  USE m_judft
12
  IMPLICIT NONE
13

14 15 16 17
#ifdef __PGI
    REAL,EXTERNAL ::erfc
#endif
  ! Constant omega of the HSE exchange functional
18
   REAL, PARAMETER :: omega_HSE = 0.11
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 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


  ! Constant for the maximum number of G points
  INTEGER, PARAMETER :: maxNoGPts = 50

  ! these arrays are calculated once and then reused
  LOGICAL, ALLOCATABLE   :: already_known(:)
  REAL, ALLOCATABLE      :: known_potential(:,:)
#ifdef CPP_INVERSION
  REAL, ALLOCATABLE      :: known_fourier_trafo(:,:,:)
#else
  COMPLEX, ALLOCATABLE   :: known_fourier_trafo(:,:,:)
#endif

  ! variables needed for fourier transformation
  PRIVATE already_known, known_potential, known_fourier_trafo

  ! functions needed internally
  PRIVATE calcYlm, calcSphBes, my_dot_product3x1, my_dot_product3x3, my_dot_product4x1, &
       my_dot_product4x4, my_sum3d, my_sum4d, gPtsSummation, approximateIntegral, generateIntegrals, &
       integrateY1ExpErfc, integrateY3ExpErfc, integrateY5ExpErfc, integrateY7ExpErfc, &
       integrateY9ExpErfc, calculateF, calculateG, calculateH

  INTERFACE my_sum
     MODULE PROCEDURE my_sum3d, my_sum4d
  END INTERFACE

  INTERFACE my_dot_product
     MODULE PROCEDURE my_dot_product4x1, my_dot_product4x4, my_dot_product3x1, my_dot_product3x3
  END INTERFACE

  INTERFACE gPtsSummation
     MODULE PROCEDURE crc_gPtsSummation, rrr_gPtsSummation
  END INTERFACE

CONTAINS

  ! Calculate the enhancement factor of the HSE03 functional
  ! References:
  ! [1] Heyd, Scuseria, Ernzerhof: Hybrid functionals based on a screened Coulomb potential,
  !     J. Chem. Phys. 118 (2003) 8207-8215
  ! [2] Heyd, Scuseria: Assessment and validation of a screened Coulomb hybrid density
  !     functional, J. Chem. Phys. 120 (2004) 7274-7280
  ! [3] Ernzerhof, Perdew: Generalized gradient approximation to the angle- and system-
  !     averaged exchange hole, J. Chem. Phys. 109 (1998) 3313-3319
  ! Input:  kF       - kF = (3 pi^2 rho) ** 1/3
  !         s_inp    - reduced gradient = |grad rho| / 2 kF rho
  ! Output: F_x      - HSE03 enhancement factor
  !         dFx_ds   - derivative of this factor with respect to s
  !         d2Fx_ds2 - second derivative with respect to s
  SUBROUTINE calculateEnhancementFactor(kF, s_inp, F_x, dFx_Ds, d2Fx_Ds2, dFx_dkF, d2Fx_dsdkF)

71
 
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
    IMPLICIT NONE

    REAL, INTENT(IN)  :: kF, s_inp
    REAL, INTENT(OUT) :: F_x, dFx_ds, d2Fx_ds2
    REAL, INTENT(OUT) :: dFx_dkF, d2Fx_dsdkF

    ! Helper variables 
    REAL :: r1_kF, &                   ! 1 / kF
         omega_kF,omega_kF_Sqr, &      ! omega_HSE / kF, (omega/kF)^2
         s, s2, &                      ! reduced gradient s and s^2
         s_si2, r2s_si3, r6s_si4, &    ! quotient s_chg / s_inp^n (n = 2,3,4)
         F, G, H, &                    ! results of the functions F, G, and H defined in [3]
         Hs2, dHs2_ds, d2Hs2_ds2, &    ! H * s^2 and derivatives with respect to s
         Fs2, dFs2_ds, d2Fs2_ds2, &    ! F * s^2 and derivatives with respect to s
         dGs2_ds, d2Gs2_ds2, &         ! derivatives with respect to s of G s^2
         C_term, dCt_ds, d2Ct_ds2, &   ! C * (1 + F(s) s^2) and derivatives with respect to s
         E_term, dEt_ds, d2Et_ds2, &   ! E * (1 + G(s) s^2) and derivatives with respect to s
         D_term                        ! D + H s^2

    ! integrals of y^n Exp(-ay^2) Erfc(w/k y) for n = 1, 3, 5, 7, 9
    REAL :: intY1ExpErfc,intY3ExpErfc,intY5ExpErfc,intY7ExpErfc,intY9ExpErfc
    ! integrals of 2/sqrt(pi) y^n Exp(-arg*y^2) for n = 2, 4, 6, 8
    REAL :: r1_arg, intY2Gauss, intY4Gauss, intY6Gauss, intY8Gauss

    ! approximation of the not analytical part of the integral and derivatives
    REAL :: appInt, dAppInt_ds, d2AppInt_ds2
    REAL :: dAppInt_dkF, d2AppInt_dsdkF

    REAL, PARAMETER :: r8_9 = 8.0/9.0  ! 8/9
    REAL, PARAMETER :: &               ! Parameters of the exchange hole as defined in [3]
         B = -0.37170836, C = -0.077215461,&
         D =  0.57786348, E = -0.051955731

    REAL, PARAMETER :: &               ! Correction of the reduced gradient to ensure Lieb-Oxford bound [2]
         s_thresh = 8.3, s_max = 8.572844, s_chg = 18.796223
    LOGICAL :: correction              ! Has the value of s been corrected

    ! If a large value of s would violate the Lieb-Oxford bound, the value of s is reduced, 
    ! so that this condition is fullfilled
    correction = s_inp > s_thresh
    IF (correction) THEN
       s_si2 = s_chg / (s_inp * s_inp)
       s     = s_max - s_si2
    ELSE
       s = s_inp
    END IF

    ! Calculate different helper variables
    r1_kF        = 1.0 / kF
121
    omega_kF     = omega_hse * r1_kF !was omega_VHSE()
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 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 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 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 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 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 455 456 457 458 459 460 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 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 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 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 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 643 644 645 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 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 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 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 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 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 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 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 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 988 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 1037 1038 1039
    omega_kF_Sqr = omega_kF * omega_kF

    ! calculate the functions H and F in [3] and its derivatives
    CALL calculateH(s, H, dHs2_ds, d2Hs2_ds2)
    CALL calculateF(s, H, dHs2_ds, d2Hs2_ds2, F, dFs2_ds, d2Fs2_ds2) 
    s2  = s * s
    Hs2 = H * s2
    Fs2 = F * s2
    CALL calculateG(s2, Fs2, dFs2_ds, d2Fs2_ds2, Hs2, dHs2_ds, d2Hs2_ds2,& !Input
                    G, dGs2_ds, d2Gs2_ds2)                                 !Output

    C_term   = C * (1 + s2 * F)
    dCt_ds   = C * dFs2_ds
    d2Ct_ds2 = C * d2Fs2_ds2
    E_term   = E * (1 + s2 * G)
    dEt_ds   = E * dGs2_ds
    d2Et_ds2 = E * d2Gs2_ds2
    D_term   = D + Hs2

    ! approximate the integral using an expansion of the error function (cf. [2])
    CALL approximateIntegral(omega_kF, Hs2, D_term, dHs2_ds, d2Hs2_ds2,& !Input
         appInt, dAppInt_ds, d2AppInt_ds2, dAppInt_dkF, d2AppInt_dsdkF)  !Output

    ! Calculate the integrals
    !
    ! inf
    !   /                2   2      /       \
    !  |     n  -(D+H(s)s ) y      | omega   |
    !  | dy y  e               Erfc| ----- y |
    !  |                           |   k     |
    ! /                             \   F   /
    !  0
    ! for n = 1, 3, 5, 7, and 9
    ! 
    intY1ExpErfc = integrateY1ExpErfc(omega_kf, omega_kf_Sqr, D_term)
    intY3ExpErfc = integrateY3ExpErfc(omega_kf, omega_kf_Sqr, D_term)
    intY5ExpErfc = integrateY5ExpErfc(omega_kf, omega_kf_Sqr, D_term)
    intY7ExpErfc = integrateY7ExpErfc(omega_kf, omega_kf_Sqr, D_term)
    intY9ExpErfc = integrateY9ExpErfc(omega_kf, omega_kf_Sqr, D_term)

    ! Calculate the integrals
    !
    !       inf
    !         /          /                      2    \
    !   2    |     n    |          2   2   omega   2  |
    ! -----  | dy y  Exp| -(D+H(s)s ) y  - ------ y   |
    !  ____  |          |                   k ^2      |
    ! V Pi  /            \                   F       /
    !        0
    ! for n = 2, 4, 6, 8
    !
    r1_arg     = 1.0 / (D_term + omega_kF_Sqr)
    intY2Gauss = 0.5 * SQRT(r1_arg) * r1_arg
    intY4Gauss = 1.5 * intY2Gauss   * r1_arg
    intY6Gauss = 2.5 * intY4Gauss   * r1_arg
    intY8Gauss = 3.5 * intY6Gauss   * r1_arg

    ! Calculate the integral 
    !  inf
    !    /                 /       \
    !   |                 | omega   |
    !   | dy y J(s,y) Erfc| ----- y |
    !   |                 |   k     |
    !  /                   \   F   /
    !   0
    ! where J(s, y) is the exchange hole defined in [3]    
    ! the exchange factor is proportional to this integral
    F_x = - r8_9 * (appInt + B * intY1ExpErfc + C_term * intY3ExpErfc + E_term * intY5ExpErfc)

    ! Calculate the derivatives with respect to s using that the derivatative of the integral
    ! yields higher orders of the same kind of integral intY1 -> -intY3 -> intY5 ... times
    ! the derivative of the exponent
    dFx_ds   = -r8_9 * (dAppInt_ds - (B * intY3ExpErfc + C_term * intY5ExpErfc + E_term * intY7ExpErfc) * dHs2_ds &
                                   + dCt_ds * intY3ExpErfc + dEt_ds * intY5ExpErfc)
    d2Fx_ds2 = -r8_9 * (d2AppInt_ds2 + (B * intY5ExpErfc + C_term * intY7ExpErfc + E_term * intY9ExpErfc) * dHs2_ds**2 &
                                     - (B * intY3ExpErfc + C_term * intY5ExpErfc + E_term * intY7ExpErfc) * d2Hs2_ds2 &
                                     - 2.0 * (dCt_ds * intY5ExpErfc + dEt_ds * intY7ExpErfc) * dHs2_ds &
                                     + d2Ct_ds2 * intY3ExpErfc + d2Et_ds2 * intY5ExpErfc)

    dFx_dkF    = -r8_9 * r1_kF * (omega_kF * (B * intY2Gauss + C_term * intY4Gauss + E_term * intY6Gauss) + dAppInt_dkF)
    d2Fx_dsdkF = -r8_9 * r1_kF * ( d2AppInt_dsdkF + omega_kF * ( dCt_ds * intY4Gauss + dEt_ds * intY6Gauss &
         - (B * intY4Gauss + C_term * intY6Gauss + E_term * intY8Gauss) * dHs2_ds ) )

    ! Correction to the derivatives, if s_inp > s_thresh
    IF (correction) THEN
      r2s_si3    = 2.0 * s_si2   / s_inp
      r6s_si4    = 3.0 * r2s_si3 / s_inp
      d2Fx_ds2   = d2Fx_ds2   * r2s_si3**2 - dFx_ds * r6s_si4
      d2Fx_dsdkF = d2Fx_dsdkF * r2s_si3
      dFx_ds     = dFx_ds     * r2s_si3
    END IF

  END SUBROUTINE calculateEnhancementFactor

  ! Approximation for the first part of the exchange hole integral
  ! Calculated using the algorithm described in [2].
  ! Additionally the first and second derivative of this approximation with
  ! respect to s are calculated
  ! Input:  omega_kF       - omega / kF 
  !         Hs2            - H s^2
  !         D_Hs2          - D + H s^2
  !         dHs2_ds        - d (H s^2) / ds 
  !         d2Hs2_ds2      - d^2 (H s^2) / ds^2
  ! Output: appInt         - approximation for one part of the exchange hole integral 
  !         dAppInt_ds     - first derivative with respect to s
  !         d2AppInt_ds2   - second derivative with respect to s
  !         dAppInt_dkF    - first derivative with respect to kF
  !         d2AppInt_dsdkF - mixed derivative with respect to s and kF
  SUBROUTINE approximateIntegral(omega_kF, Hs2, D_Hs2, dHs2_ds, d2Hs2_ds2,&
       appInt, dAppInt_ds, d2AppInt_ds2, dAppInt_dkF, d2AppInt_dsdkF)

    USE m_exponential_integral, ONLY: calculateExponentialIntegral, gauss_laguerre

    IMPLICIT NONE

    REAL, INTENT(IN)  :: omega_kF, Hs2, D_Hs2, dHs2_ds, d2Hs2_ds2
    REAL, INTENT(OUT) :: appInt, dAppInt_ds, d2AppInt_ds2
    REAL, INTENT(OUT) :: dAppInt_dkF, d2AppInt_dsdkF

    REAL    :: w2, bw, r2bw, bw_Hs2, bw_D_Hs2
    ! variables for temporary storage of the integrals, the prefactors and the dot_product
    REAL    :: integral(0:12), a_omegaI(0:8), aI_omegaI(0:8), dotpr, dotpr2
    INTEGER :: i

    REAL    :: r2w2, r4w2, r2w2_Hs2, r2w2_D_Hs2, arg, exp_e1, dAppInt_dh, d2AppInt_dh2

    ! parameters of the erfc fit as given in [2]
    REAL, PARAMETER :: A_2 = 0.5080572, scale = 1.125 / A_2,&
         a(1:8) = (/-1.128223946706117, 1.452736265762971, &
                    -1.243162299390327, 0.971824836115601, &
                    -0.568861079687373, 0.246880514820192, &
                    -0.065032363850763, 0.008401793031216 /),&
         b = 1.455915450052607, cutoff = 14.0

    ! Calculate helper variables
    w2       = omega_kF**2
    bw       = b * w2
    r2bw     = 2.0 * bw
    bw_Hs2   = bw + Hs2
    bw_D_Hs2 = bw + D_Hs2

    IF (bw_Hs2 < cutoff) THEN
       ! integrate the erfc approximation times the exchange hole
       CALL generateIntegrals(bw_Hs2, bw_D_Hs2, integral)

       ! combine the solutions of the integrals with the appropriate prefactors
       a_omegaI(0)    = 1.0
       a_omegaI(1:8)  = a * (/ (omega_kF**i,i=1,8) /)
       aI_omegaI      = (/ (i * a_omegaI(i),i=0,8) /)
       appInt         = DOT_PRODUCT(a_omegaI, integral(0: 8))
       dotpr          = DOT_PRODUCT(a_omegaI, integral(2:10))
       dAppInt_ds     = -dotpr * dHs2_ds 
       dAppInt_dkF    = r2bw * dotpr - DOT_PRODUCT(aI_omegaI, integral(0:8))
       dotpr2         = DOT_PRODUCT(a_omegaI, integral(4:12))
       d2AppInt_ds2   = dotpr2 * dHs2_ds**2 - dotpr * d2Hs2_ds2
       d2AppInt_dsdkF = -(r2bw * dotpr2 - DOT_PRODUCT(aI_omegaI, integral(2:10))) * dHs2_ds
    ELSE
       r2w2           = 2.0 * w2
       r4w2           = 4.0 * w2
       r2w2_Hs2       = r2w2 + Hs2 
       r2w2_D_Hs2     = r2w2 + D_Hs2
       arg            = scale * r2w2_Hs2
       exp_e1         = gauss_laguerre(arg)
       appInt         = A_2 * (LOG(r2w2_Hs2 / r2w2_D_Hs2) + exp_e1)
       dAppInt_dh     = -A_2 / r2w2_D_Hs2 + 1.125 * exp_e1
       d2AppInt_dh2   = 1.125 / r2w2_Hs2 - A_2 / r2w2_D_Hs2**2 - 1.265625 / A_2 * exp_e1
       dAppInt_ds     = dAppInt_dh * dHs2_ds
       dAppInt_dkF    = -dAppInt_dh * r4w2
       d2AppInt_ds2   = d2AppInt_dh2 * dHs2_ds**2 + dAppInt_dh * d2Hs2_ds2
       d2AppInt_dsdkF = d2AppInt_dh2 * dHs2_ds * r4w2
    END IF

  END SUBROUTINE approximateIntegral

  ! Generate the integrals for n = 0, 1, ..., 12
  !
  ! inf
  !   /        /        2                  \      /                        \
  !  |     n  |  A   -Dy           A        |    |    /   omega      2\   2 |
  !  | dy y   | --- e     - --------------  | Exp| - (  b ----- + H s  ) y  |
  !  |        |  y            /    4   2\   |    |    \     k         /     |
  ! /          \            y( 1 + - Ay  ) /      \          F             /
  !  0                        \    9    /
  !
  ! Input:  bw_Hs2   - b (omega/kF)^2 + H s^2
  !         bw_D_Hs2 - b (omega/kF)^2 + D + H s^2
  ! Output: integral - array with the calculated integrals
  ! To simplify the calculation use integral(n+2) = - d(integral(n))/d(b omega/kF)
  SUBROUTINE generateIntegrals(bw_Hs2, bw_D_Hs2, integral)
    USE m_exponential_integral, ONLY: calculateExponentialIntegral, gauss_laguerre, series_laguerre
    USE m_constants
    IMPLICIT NONE

    REAL, INTENT(IN)  :: bw_Hs2, bw_D_Hs2
    REAL, INTENT(OUT) :: integral(0:12)

    ! Helper variables
    REAL :: bw_Hs2_Sqr, bw_Hs2_Cub, sqrt_bw_Hs2,&
         bw_D_Hs2_Sqr, bw_D_Hs2_Cub, bw_D_Hs2_Tet, sqrt_bw_D_Hs2, &
         arg, sqrt_arg, r1_arg, e1_arg, exp_arg, exp_erfc,&
         term1, factor2, term2, arg_n, sum_term, add_term, half_i2_1
    INTEGER :: i

    ! A is an exchange hole parameter [3] and b the fit parameter for erfc [2]
    REAL, PARAMETER :: &
         A = 1.0161144, A_2 = A / 2.0, scale = 2.25 / A, sqrtA =  1.008025,& !sqrt(A) 
         b = 1.455915450052607

    ! Calculate many helper variables
    bw_Hs2_Sqr    = bw_Hs2 * bw_Hs2
    bw_Hs2_Cub    = bw_Hs2 * bw_Hs2_Sqr
    sqrt_bw_Hs2   = SQRT(bw_Hs2)
    bw_D_Hs2_Sqr  = bw_D_Hs2 * bw_D_Hs2
    bw_D_Hs2_Cub  = bw_D_Hs2 * bw_D_Hs2_Sqr
    bw_D_Hs2_Tet  = bw_D_Hs2_Sqr * bw_D_Hs2_Sqr
    sqrt_bw_D_Hs2 = SQRT(bw_D_Hs2)

    ! arg = 9/4 * (b omega/kF + H s^2) / A
    arg      = scale * bw_Hs2
    sqrt_arg = SQRT(arg)
    r1_arg   = 1.0 / arg

    ! calculate e^(arg), E1(arg), and erfc(sqrt(arg))
    exp_arg  = EXP(arg)
    exp_erfc = exp_arg * erfc(sqrt_arg)

    IF (arg > series_laguerre) THEN
       term2    = gauss_laguerre(arg)
    ELSE
       CALL calculateExponentialIntegral(arg, e1_arg)
       term2    = exp_arg * e1_arg
    END IF

    ! The n = 0 integral is 
    ! A/2 ( ln((b omega/kF + H s^2) / (b omega/kF + D + H s^2))
    !     + e^(arg) E1(arg) )
    integral(0) = A_2 * (LOG(bw_Hs2 / bw_D_Hs2) + term2)

    ! Calculate now all even n's by successive derivation
    ! The log(...) term gives term proportional to 1/(b omega/kF + D + H s^2)^i
    ! The e^(arg) E1(arg) term reproduces itself with a prefactor and 
    ! generates an additional 1/arg term which produces higher 1/arg^i terms
    ! when further deriviated
    term1       = A_2 / bw_D_Hs2
    factor2     = -1.125
    arg_n       = -1.0 / arg
    integral(2) = term1 + factor2 * term2

    DO i = 1, 5
       term1   = term1 / bw_D_Hs2 * REAL(i)
       factor2 = -factor2 * scale
       term2   = term2 + arg_n

       integral(2*(i+1)) = term1 + factor2 * term2

       arg_n = -arg_n * REAL(i) / arg
    END DO

    ! The n = 1 integral is
    ! A/2 ( sqrt(pi) / sqrt( b omega/kF + D + H s2 )
    ! - 3/4 sqrt(A) pi e^(arg) erfc(sqrt(arg))
    term1   = A_2 * SQRT(PI_const) / sqrt_bw_D_Hs2
    term2   = PI_const * exp_erfc
    factor2 = -0.75 * sqrtA

    integral(1) = term1 + factor2 * term2

    ! Calculate now all uneven n's by successive derivation
    ! The 1 / sqrt(...) term gives higher orders of 1 / (...)^((2i+1)/2)
    ! The e^(arg) erfc(sqrt(arg)) term reproduces itself with a prefactor 
    ! and generates an additional 1/sqrt(arg) term which produces higher
    ! 1/(arg)^((2i+1)/2) terms when further deriviated
    sum_term  = -1.125 * SQRT(pi_const) / sqrt_bw_Hs2
    add_term  = sum_term
    half_i2_1 = -0.5

    DO i = 3, 11, 2
       factor2     = -factor2 * scale
       term1       = -term1 * half_i2_1 / bw_D_Hs2
       integral(i) = term1 + term2 * factor2 + sum_term

       add_term    = -add_term * half_i2_1 / bw_Hs2
       sum_term    = -sum_term * scale + add_term
       half_i2_1   = half_i2_1 - 1.0
    ENDDO

  END SUBROUTINE generateIntegrals

  ! Calculate the integral
  !
  ! inf
  !   /                  /       \         /                 ________________ \
  !  |       -a y^2     | omega   |    1  |     omega   /   /     / omega \2   |
  !  | dy y e       Erfc| ----- y | = --- | 1 - -----  /   / a + (  -----  )   |
  !  |                  |   k     |   2 a |       k   /   V       \   k   /    |
  ! /                    \   F   /         \       F                   F      /
  !  0
  !
  ! Input:  omega_kF     - omega / kF
  !         omega_kF_Sqr - (omega / kF)^2
  !         a            - factor of the gaussian function
  ! Return: result of the integration
  REAL FUNCTION integrateY1ExpErfc(omega_kF, omega_kF_Sqr, a)
    IMPLICIT NONE

    REAL, INTENT(IN)  :: omega_kF, omega_kF_Sqr, a

    ! helper variable sqrt(a + (omega/kF)^2)
    REAL :: sqrt_term

    ! calculate helper variable
    sqrt_term = SQRT(a + omega_kF_Sqr)

    ! calculate the integral
    integrateY1ExpErfc = 0.5 * (1 - omega_kF / sqrt_term) / a

  END FUNCTION integrateY1ExpErfc

  ! Calculate the integral
  !
  ! inf
  !   /                   /       \           /                   ________________                   ________________3 \
  !  |     3  -a y^2     | omega   |     1   |       omega   /   /     / omega \2       omega   /   /     / omega \2    |
  !  | dy y  e       Erfc| ----- y | = ----- | 2 - 2 -----  /   / a + (  -----  )  - a  -----  /   / a + (  -----  )    |
  !  |                   |   k     |   4 a^2 |         k   /   V       \   k   /          k   /   V       \   k   /     |
  ! /                     \   F   /           \         F                   F              F                   F       /
  !  0
  !
  ! Input:  omega_kF     - omega / kF
  !         omega_kF_Sqr - (omega / kF)^2
  !         a            - factor of the gaussian function
  ! Return: result of the integration
  REAL FUNCTION integrateY3ExpErfc(omega_kF, omega_kF_Sqr, a)
    IMPLICIT NONE

    REAL, INTENT(IN)  :: omega_kF, omega_kF_Sqr, a

    ! helper variables
    REAL :: term, sqrt_term, sqrt_term_3

    ! calculate helper variables
    term        = a + omega_kF_Sqr
    sqrt_term   = SQRT(term)
    sqrt_term_3 = term * sqrt_term

    ! calculate the integral
    integrateY3ExpErfc = 0.25 * (2.0 - a * omega_kF / sqrt_term_3 - 2.0 * omega_kF / sqrt_term) / (a * a)

  END FUNCTION integrateY3ExpErfc

  ! Calculate the integral
  !
  ! inf                                     /                                   \
  !   /                   /       \        |                  /              2\  |
  !  |     5  -a y^2     | omega   |    1  |       omega     |      a     3 a  | |
  !  | dy y  e       Erfc| ----- y | = --- | 1 - ----------  | 1 + --- + ----- | |
  !  |                   |   k     |   a^3 |     k  sqrt(x)  |     2 x   8 x^2 | |
  ! /                     \   F   /        |      F           \               /  |
  !  0                                      \                                   /
  ! where
  !          /     \ 2
  !         | omega |
  ! x = a + | ----- |
  !         |   k   |
  !          \   F /
  !
  ! Input:  omega_kF     - omega / kF
  !         omega_kF_Sqr - (omega / kF)^2
  !         a            - factor of the gaussian function
  ! Return: result of the integration
  REAL FUNCTION integrateY5ExpErfc(omega_kF, omega_kF_Sqr, a)
    IMPLICIT NONE

    REAL, INTENT(IN)  :: omega_kF, omega_kF_Sqr, a

    ! helper variables
    REAL :: term, sqrt_term, a_Sqr

    ! calculate helper variables
    term        = a + omega_kF_Sqr
    sqrt_term   = SQRT(term)
    a_Sqr       = a * a

    ! calculate the integral
    integrateY5ExpErfc = (1.0 - (0.375 * a_Sqr / (term * term) + a / (2.0 * term) + 1.0) * omega_kF / sqrt_term) / (a_Sqr * a)

  END FUNCTION integrateY5ExpErfc

  ! Calculate the integral
  !
  ! inf                                     /                                            \
  !   /                   /       \        |                  /              2       3 \  |
  !  |     7  -a y^2     | omega   |    3  |       omega     |      a     3 a     5 a   | |
  !  | dy y  e       Erfc| ----- y | = --- | 1 - ----------  | 1 + --- + ----- + ------ | |
  !  |                   |   k     |   a^4 |     k  sqrt(x)  |     2 x   8 x^2   16 x^3 | |
  ! /                     \   F   /        |      F           \                        /  |
  !  0                                      \                                            /
  ! where
  !          /     \ 2
  !         | omega |
  ! x = a + | ----- |
  !         |   k   |
  !          \   F /
  !
  ! Input:  omega_kF     - omega / kF
  !         omega_kF_Sqr - (omega / kF)^2
  !         a            - factor of the gaussian function
  ! Return: result of the integration
  REAL FUNCTION integrateY7ExpErfc(omega_kF, omega_kF_Sqr, a)
    IMPLICIT NONE

    REAL, INTENT(IN)  :: omega_kF, omega_kF_Sqr, a

    ! helper variables
    REAL :: term2, term, sqrt_term, a_Sqr

    ! calculate helper variables
    term        = a + omega_kF_Sqr
    term2       = term * term
    sqrt_term   = SQRT(term)
    a_Sqr       = a * a

    ! calculate the integral
    integrateY7ExpErfc = 3.0  / (a_Sqr * a_Sqr) * (1.0 - omega_kF / sqrt_term * &
         (0.3125 * (a_Sqr * a) / (term2 * term) + 0.375 * a_Sqr / term2 + a / (2.0 * term) + 1.0))

  END FUNCTION integrateY7ExpErfc

  ! Calculate the integral
  !
  ! inf                                     /                                                      \
  !   /                   /       \        |                  /              2       3           \  |
  !  |     9  -a y^2     | omega   |    12 |       omega     |      a     3 a     5 a      35 a^4 | |
  !  | dy y  e       Erfc| ----- y | = --- | 1 - ----------  | 1 + --- + ----- + ------ + ------- | |
  !  |                   |   k     |   a^5 |     k  sqrt(x)  |     2 x   8 x^2   16 x^3   128 x^4 | |
  ! /                     \   F   /        |      F           \                                  /  |
  !  0                                      \                                                      /
  ! where
  !          /     \ 2
  !         | omega |
  ! x = a + | ----- |
  !         |   k   |
  !          \   F /
  !
  ! Input:  omega_kF     - omega / kF
  !         omega_kF_Sqr - (omega / kF)^2
  !         a            - factor of the gaussian function
  ! Return: result of the integration
  REAL FUNCTION integrateY9ExpErfc(omega_kF, omega_kF_Sqr, a)
    IMPLICIT NONE

    REAL, INTENT(IN)  :: omega_kF, omega_kF_Sqr, a

    ! helper variables
    REAL :: term2, term, sqrt_term, a_Sqr, a_Tet

    ! calculate helper variables
    term        = a + omega_kF_Sqr
    term2       = term * term
    sqrt_term   = SQRT(term)
    a_Sqr       = a * a
    a_Tet       = a_Sqr * a_Sqr

    ! calculate the integral
    integrateY9ExpErfc = 12.0 * (1.0 - (0.2734375 * a_Tet / (term2 * term2) + 0.3125 * (a_Sqr * a) / (term2 * term) &
         + 0.375 * a_Sqr / term2 + a / (2.0 * term) + 1.0) * omega_kF / sqrt_term) / (a_Tet * a)

  END FUNCTION integrateY9ExpErfc

  ! Calculate the function F(s) given in [3]
  ! Input:  s         - reduced gradient
  !         H         - value of the function H(s)
  !         dHs2_ds   - first derivative of H(s)s^2
  !         dsHs2_ds2 - second derivative of H(s)s^2
  ! Output: F         - value of the function F
  !         dFs2_ds   - first derivative of F(s)s^2
  !         d2Fs2_ds2 - second derivative of F(s)s^2
  SUBROUTINE calculateF(s, H, dHs2_ds, d2Hs2_ds2, F, dFs2_ds, d2Fs2_ds2)
    IMPLICIT NONE

    REAL, INTENT(IN)  :: s, H, dHs2_ds, d2Hs2_ds2
    REAL, INTENT(OUT) :: F, dFs2_ds, d2Fs2_ds2

    REAL, PARAMETER   :: slope = 6.4753871
    REAL, PARAMETER   :: shift = 0.4796583

    ! calculate the function F(s), d(s^2F(s))/ds, and d^2(s^2F(s))/ds^2
    F         = slope * H + shift
    dFs2_ds   = slope * dHs2_ds + 2.0 * s * shift
    d2Fs2_ds2 = slope * d2Hs2_ds2 + 2.0 * shift
  END SUBROUTINE calculateF

  ! Calculate the function G(s) given in [3]
  ! Input:  s2        - s^2 where s is the reduced gradient
  !         Fs2       - F(s) s^2
  !         dFs2_ds   - first derivative of F(s)s^2 with respect to s
  !         d2Fs2_ds2 - second derivative of F(s)s^2
  !         Hs2       - H(s) s^2
  !         dHs2_ds   - first derivative of H(s)s^2 with respect to s
  !         d2Hs2_ds2 - second derivative of H(s)s^2
  ! Output: G         - value of the function G
  !         dGs2_ds   - first derivative of G(s)s^2 with respect to s
  !         d2Gs2_ds2 - second derivative of G(s)s^2
  SUBROUTINE calculateG(s2, Fs2, dFs2_ds, d2Fs2_ds2, Hs2, dHs2_ds, d2Hs2_ds2, G, dGs2_ds, d2Gs2_ds2)
    IMPLICIT NONE

    REAL, INTENT(IN)  :: s2, Fs2, dFs2_ds, d2Fs2_ds2, Hs2, dHs2_ds, d2Hs2_ds2
    REAL, INTENT(OUT) :: G, dGs2_ds, d2Gs2_ds2

    ! helper variables
    REAL :: AHs2_1_2, AHs2_3_2, r1_Fs2, D_Hs2, D_Hs2Sqr, D_Hs2Cub, &
         D_Hs2_5_2, D_Hs2_7_2, D_Hs2_9_2, D_Hs2_11_2
    REAL :: part1, dpart1_dh, d2part1_dh2
    REAL :: arg1, arg2, exp_erfc,&
         part2, dpart2_dh, d2part2_dh2
    REAL :: alpha, Ebeta, r3Pi_4_alpha, beta_s2, Ebeta_s2,&
         dalpha_dh, d2alpha_dh2, dalpha_df, d2alpha_dfdh, dbeta_dh, d2beta_dh2

    ! parameters of the exchange hole given in [3]
    REAL, PARAMETER :: PI_75 = 2.356194490192344929, SQRT_PI = 1.77245385090551602729816748334,&
         A = 1.0161144, sqrtA = 1.008025, r9_4A = 2.25 / A,& !sqrt(A), 9/4A
         B = -0.37170836,&
         C = -0.077215461,&
         D =  0.57786348,&
         E = -0.051955731

    ! calculate the helper variables
    AHs2_1_2   = sqrtA * SQRT(Hs2)
    AHs2_3_2   = AHs2_1_2 * A * Hs2
    r1_Fs2     = 1.0 + Fs2
    D_Hs2      = D + Hs2
    D_Hs2Sqr   = D_Hs2 * D_Hs2
    D_Hs2Cub   = D_Hs2 * D_Hs2Sqr
    D_Hs2_5_2  = D_Hs2Sqr * SQRT(D_Hs2)
    D_Hs2_7_2  = D_Hs2_5_2 * D_Hs2
    D_Hs2_9_2  = D_Hs2_5_2 * D_Hs2Sqr
    D_Hs2_11_2 = D_Hs2_5_2 * D_Hs2Cub

    ! calculate first part of the term called 'a' in [3] eq. (A2) and its derivatives with respect to H(s)s^2 and F(s)s^2
    !
    !                          2      2           2 2          2 3
    !          __ 15E + 6C(1+Fs )(D+Hs ) + 4B(D+Hs )  + 8A(D+Hs ) 
    ! part1 = VPi ------------------------------------------------
    !                                    2  7/2
    !                        16 ( D + H s  )
    !
    part1 = SQRT_PI * (15.0*E + 6.0*C * r1_Fs2 * D_Hs2 + 4.0*B * D_Hs2Sqr + 8.0*A * D_Hs2Cub) / (16.0 * D_Hs2_7_2)
    !
    !                               2      2            2 2          2 3
    ! d part1     __ 105E + 30C(1+Fs )(D+Hs ) + 12B(D+Hs )  + 8A(D+Hs ) 
    ! ------- = -VPi ---------------------------------------------------
    ! d(Hs^2)                                  2  9/2
    !                              32 ( D + H s  )
    !
    dpart1_dh = -SQRT_PI * (105.0*E + 30.0*C * r1_Fs2 * D_Hs2 + 12.0*B * D_Hs2Sqr + 8.0*A * D_Hs2Cub) / (32.0 * D_Hs2_9_2)
    !
    !  2                             2      2            2 2           2 3
    ! d  part1    __ 945E + 210C(1+Fs )(D+Hs ) + 60B(D+Hs )  + 24A(D+Hs ) 
    ! -------- = VPi -----------------------------------------------------
    !        2                                   2  11/2
    ! d(Hs^2)                        64 ( D + H s  )
    !
    d2part1_dh2 = SQRT_PI * (945.0*E + 210.0*C * r1_Fs2 * D_Hs2 + 60.0*B * D_Hs2Sqr + 24.0*A * D_Hs2Cub) / (64.0 * D_Hs2_11_2)
    !
    ! d part1    __       3 C 
    ! ------- = VPi -----------------
    ! d(Fs^2)                  2  5/2
    !               8 ( D + H s  )
    !
    dalpha_df = SQRT_PI * 0.375 * C / D_Hs2_5_2
    !
    !      2
    !     d part1         __       15 C 
    ! --------------- = -VPi ------------------
    ! d(Fs^2) d(Hs^2)                    2  7/2
    !                        16 ( D + H s  )
    !
    d2alpha_dfdh = -2.5 * dalpha_df / D_Hs2

    ! calculate second part of the term called 'a' in [3] eq. (A2) and its derivatives
    !                                            ________
    !                       /     2 \       /   /     2   \
    !         3 Pi  ___    | 9 H s   |     |   / 9 H s     |
    ! part2 = ---- V A  Exp| ------- | Erfc|  /  -------   |
    !          4           |   4 A   |     | V     4 A     |
    !                       \       /       \             /
    !
    arg1     = r9_4A * Hs2
    arg2     = SQRT(arg1)
    exp_erfc = EXP(arg1) * erfc(arg2)
    part2    = PI_75 * sqrtA * exp_erfc
    !
    !                      /                                \
    ! d part2   3 Pi  ___ |  9                    3          |
    ! ------- = ---- V A  | --- exp_erfc - ----------------  |
    ! d(Hs^2)    4        | 4 A                          2   |
    !                      \               2 sqrt(Pi A Hs ) /
    !
    dpart2_dh = PI_75 * sqrtA * (r9_4A * exp_erfc - 1.5 / (SQRT_PI * AHs2_1_2) )
    !
    !  2                    /                                 2    \
    ! d  part2   3 Pi  ___ |   81                  6 A - 27 Hs      |
    ! -------- = ---- V A  | ------ exp_erfc + -------------------- |
    !        2    4        | 16 A^2                           2 3/2 |
    ! d(Hs^2)               \                  8 sqrt(Pi)(A Hs )   /
    !
    d2part2_dh2 = PI_75 * sqrtA * (r9_4A**2 * exp_erfc + (6.0*A - 27.0*Hs2) / (8.0 * SQRT_PI * AHs2_3_2) )

    ! calculate the 'a' and 'b' terms ([3] eq. (A2) and (A3) )
    !
    ! a = part1 - part2
    !
    !             __  2
    !         15 VPi s
    ! b = -----------------
    !                2  7/2
    !     16 (D + H s  )
    !
    alpha   = part1 - part2
    beta_s2 = 0.9375 * SQRT_PI / D_Hs2_7_2
    Ebeta   = E * beta_s2 * s2

    ! the derivatives of a with respect to Fs^2 and Hs^2
    !
    !    da      d part1   d part2
    ! -------- = ------- - -------
    ! d (Hs^2)   d(Hs^2)   d(Hs^2)
    !
    dalpha_dh = dpart1_dh - dpart2_dh
    !
    !    2        2          2
    !   d a      d part1    d part2
    ! -------- = -------- - --------
    !        2          2          2
    ! d(Hs^2)    d(Hs^2)    d(Hs^2)
    !
    d2alpha_dh2 = d2part1_dh2 - d2part2_dh2
    !
    !    da      d part1
    ! -------- = -------
    ! d (Fs^2)   d(Fs^2)
    !
    !        2               2
    !       d a             d part1
    ! --------------- = ---------------
    ! d(Fs^2) d(Hs^2)   d(Fs^2) d(Hs^2)
    !
    ! (this expressions are already defined earlier)
    !
    ! and the derivatives of b/s^2 with respect to Hs^2
    !                        __
    ! d(b/s^2)          105 VPi          7  b / s^2
    ! -------- = - ----------------- = - -  --------
    ! d (Hs^2)                2  9/2     2         2
    !              32 (D + H s  )           D + H s
    !
    dbeta_dh = -3.5 * beta_s2 / D_Hs2
    !
    !  2                     __
    ! d (b/s^2)         945 VPi          9  d(b/s^2)
    ! --------- = ------------------ = - -  --------
    !         2              2  11/2     2  d (Hs^2)
    ! d (Hs^2)    64 (D + H s  )
    !
    d2beta_dh2 = -4.5 * dbeta_dh / D_Hs2

    ! calculate the function G(s) and its derivatives
    ! 
    !       3Pi/4 + a
    ! G = - ---------
    !          E b
    !
    r3Pi_4_alpha = PI_75 + alpha
    Ebeta_s2     = E * beta_s2
    G            = - r3Pi_4_alpha / Ebeta
    !
    !             /  /3 Pi    \  d(b/s^2)   /           d a    \  d(Hs^2)       d a   d(Fs^2) 
    !            <  ( ---- + a ) -------   /  b/s^2  - -------  > -------  -  ------- ------- 
    ! d (Gs^2)    \  \ 4      /  d(Hs^2)  /            d(Hs^2) /    d s       d(Fs^2)   ds    
    ! -------- = ----------------------------------------------------------------------------
    !    ds                                     E b/s^2
    !
    dGs2_ds = ( (r3Pi_4_alpha * dbeta_dh / beta_s2 - dalpha_dh) * dHs2_ds - dalpha_df * dFs2_ds ) / Ebeta_s2
    !
    !                                                     /3Pi    \  /             2\           /           \
    !                                                    ( --- + a )( b  h" + b   h' ) + 2b  h'( f'a  + h'a  ) + ...
    !                                            2        \ 4     /  \ h       hh   /      h    \   f      h/
    !  2         -f" a  - h" a  - 2 f' h' a   - h' a   + -----------------------------------------------------------
    ! d (Gs^2)        f       h            fh       hh                                b/s^2
    ! -------- = ---------------------------------------------------------------------------------------------------
    !   ds^2                                               E b/s^2
    !
    !            /3Pi    \   2  2
    !           ( --- + a ) b  h'
    !            \ 4     /   h
    ! ... = - 2 -----------------
    !                  b/s^2
    !
    ! where the primes indicate derivative with respect to s and the subscripts derivatives with respect to the subscript
    ! and f and h are abbrevations for f = Fs^2 and h = Hs^2
    !
    d2Gs2_ds2 = (-d2Fs2_ds2 * dalpha_df - d2Hs2_ds2 * dalpha_dh &
         - 2.0 * dFs2_ds * dHs2_ds * d2alpha_dfdh - dHs2_ds**2 * d2alpha_dh2 &
                  + ( r3Pi_4_alpha * (dbeta_dh * d2Hs2_ds2 + d2beta_dh2 * dHs2_ds**2) &
                      + 2.0 * dbeta_dh * dHs2_ds * (dFs2_ds * dalpha_df + dHs2_ds * dalpha_dh) &
                      - 2.0 * r3Pi_4_alpha * (dbeta_dh*dHs2_ds)**2 / beta_s2 ) / beta_s2 ) / Ebeta_s2
  END SUBROUTINE calculateG

  ! Calculate the function H(s) given in [3]
  ! Input:  s         - reduced gradient
  ! Output: H         - value of the function H
  !         dHs2_ds   - first derivative d(s^2*H(s))/ds
  !         d2Hs2_ds2 - second derivative d^2(s^2H(s))/ds^2
  SUBROUTINE calculateH(s,H,dHs2_ds,d2Hs2_ds2)
    IMPLICIT NONE

    REAL, INTENT(IN)  :: s
    REAL, INTENT(OUT) :: H, dHs2_ds, d2Hs2_ds2

    ! helper variables
    REAL :: s2, s3, s4, s5, s6
    REAL :: numer, denom
    REAL :: dnum_ds, dden_ds
    REAL :: d2num_ds2, d2den_ds2

    ! parameters given in [3]
    REAL, PARAMETER :: &
         a1 = 0.00979681,&
         a2 = 0.0410834,&
         a3 = 0.187440,&
         a4 = 0.00120824,&
         a5 = 0.0347188

    ! calculate helper variables
    s2 = s  * s
    s3 = s2 * s
    s4 = s2 * s2
    s5 = s3 * s2
    s6 = s4 * s2

    ! calculate function H(s) with [3] eq. (A5)
    !
    !            2         4
    !        a  s   +  a  s
    !         1         2
    ! H = -------------------------
    !             4       5       6
    !     1 + a  s  + a  s  + a  s
    !          3       4       5
    !
    numer = a1 * s2 + a2 * s4
    denom = 1.0 + a3 * s4 + a4 * s5 + a5 * s6
    H     = numer / denom

    ! calculate the first derivative of s^2 H(s)
    !
    !     /    \
    !  d | f(x) |   f'(x) - f(x)g'(x) / g(x)
    ! -- | ---- | = ------------------------
    ! dx | g(x) |            g(x)
    !     \    /
    !
    numer   = numer * s2
    dnum_ds = 4.0 * s3 * a1 + 6.0 * s5 * a2
    dden_ds = 4.0 * s3 * a3 + 5.0 * s4 * a4 + 6.0 * s5 * a5
    dHs2_ds = ( dnum_ds - (dden_ds * numer)/denom ) / denom

    ! calculate the second derivative of s^2 H(s)
    !
    !                                                               2
    !                         2 f'(x)g'(x) + f(x)g"(x) - 2 f(x)g'(x) /g(x)
    !    2  /    \    f"(x) - --------------------------------------------
    !   d  | f(x) |                              g(x)
    ! ---- | ---- | = ----------------------------------------------------
    ! dx^2 | g(x) |                          g(x)
    !       \    /
    !
    d2num_ds2 = 12.0 * s2 * a1 + 30.0 * s4 * a2
    d2den_ds2 = 12.0 * s2 * a3 + 20.0 * s3 * a4 + 30.0 * s4 * a5
    d2Hs2_ds2 = ( d2num_ds2 - ( 2.0*dnum_ds*dden_ds + numer*d2den_ds2 - 2.0*numer*dden_ds**2/denom ) / denom ) / denom
  END SUBROUTINE calculateH

  ! Calculate several Fourier transformations
  ! a) the Fourier transformed potential
  !                                                 /          \
  !          /      | erf |       \     4 Pi       |   |k+G|^2  |
  ! V (k) = ( k + G | --- | k + G  ) = -------  Exp| - -------  |                             [1]
  !  G       \      |  r  |       /    |k+G|^2     |    4 w^2   |
  !                                                 \          /
  !
  ! b) muffin-tin basis function
  !                                                            R
  !                                     -L                      /
  !           /      |      \     4 Pi i         ^     -i G R  |     2
  ! MT (k) = ( k + G | M     ) = ---------- Y ( k+G ) e        | dr r  Phi(r) j ( |k+G| r )  [2]
  !   G,I     \      |  k,I /     Sqrt(Om)   LM                |               L
  !                                                           /
  !                                                            0
  !
  ! c) interstitial basis function
  !                                                      -----
  !          /      |      \                       4 Pi   \     -i(G - G_I)R_a  Sin(|G_I - G| R_a) - |G_I - G| R_a Cos(|G_I - G| R_a) 
  ! IN    = ( k + G | M     ) = kronecker(G,G ) - ------   )   e               ------------------------------------------------------- [3]
  !   G,I    \      |  k,I /                 I      Om    /                                          |G_I - G|^3
  !                                                      -----
  !                                                        a
  !                                                                            \_________________________ ___________________________/
  !                                                                                                      V
  !                                                                                                     I_a
  !
  ! In the code:
  ! V_G(k):  potential
  ! MT_G(k): muffintin
  ! IN_G:    interstitial
  ! I_a:     inter_atom
  !
  ! Input:
  ! rmsh        - array of radial mesh points
  ! rmt         - radius of the muffin tin
  ! dx          - logarithmic increment of radial mesh
  ! jri         - number of radial mesh points
  ! jmtd        - dimension of radial mesh points
  ! bk          - one(!) k-vector for which FT is calculated
  ! bmat        - reciprocal lattice vector for all directions
  ! vol         - volume of the unit cell
  ! ntype       - number of atom types
  ! neq         - number of symmetry-equivalent atoms of atom type i
  ! natd        - dimesion of atoms in unit cell
  ! taual       - vector of atom positions (internal coordinates)
  ! lcutm       - l cutoff for mixed basis
  ! maxlcutm    - maximum of all these l cutoffs
  ! nindxm      - number of radial functions of mixed basis
  ! maxindxm    - maximum of these numbers
  ! gptm        - reciprocal lattice vectors of the mixed basis (internal coord.)
  ! ngptm       - number of vectors (for treated k-vector)
  ! pgptm       - pointer to the appropriate g-vector (for treated k-vector)
  ! gptmd       - dimension of gptm
  ! basm        - mixed basis functions (mt + inter) for treated k-vector
  ! lexp        - cutoff of spherical harmonics expansion of plane wave
  ! noGPts      - no g-vectors used for Fourier trafo
  ! Output:
  ! potential   - Fourier transformation of the potential
  ! muffintin   - Fourier transformation of all MT functions
  ! interstital - Fourier transformation of all IR functions
  SUBROUTINE calculate_fourier_transform( &
      ! Input
      rmsh,rmt,dx,jri,jmtd,bk,&
      bmat,vol,ntype,neq,natd,taual,lcutm,maxlcutm,&
      nindxm,maxindxm,gptm,ngptm,pgptm,gptmd,&
      basm,noGPts,irank,&
      ! Output
      potential,muffintin,interstitial)

    USE m_constants
    USE m_olap,      ONLY : gptnorm
    USE m_util,      ONLY : sphbessel,pure_intgrf,intgrf_init,intgrf_out,NEGATIVE_EXPONENT_WARNING,NEGATIVE_EXPONENT_ERROR

    IMPLICIT NONE

    ! scalar input
    INTEGER, INTENT(IN)    :: natd,ntype,maxlcutm
    INTEGER, INTENT(IN)    :: jmtd,irank
    INTEGER, INTENT(IN)    :: maxindxm
    INTEGER, INTENT(IN)    :: gptmd, noGPts
    REAL, INTENT(IN)       :: vol

    ! array input
    INTEGER, INTENT(IN)    :: lcutm(ntype)
    INTEGER, INTENT(IN)    :: nindxm(0:maxlcutm,ntype),neq(ntype)
    INTEGER, INTENT(IN)    :: jri(ntype)
    INTEGER, INTENT(IN)    :: gptm(3,gptmd)
    INTEGER, INTENT(IN)    :: ngptm
    INTEGER, INTENT(IN)    :: pgptm(ngptm)

    REAL, INTENT(IN)       :: bk(3)
    REAL, INTENT(IN)       :: rmsh(jmtd,ntype),rmt(ntype),dx(ntype)
    REAL, INTENT(IN)       :: basm(jmtd,maxindxm,0:maxlcutm,ntype)
    REAL, INTENT(IN)       :: bmat(3,3)!,amat(3,3)
    REAL, INTENT(IN)       :: taual(3,natd)

    ! array output
    REAL,    INTENT(OUT)   :: potential(noGPts)                           ! Fourier transformed potential
    COMPLEX, INTENT(OUT)   :: muffintin(noGPts,maxindxm,&                 ! muffin-tin overlap integral
                                        (maxlcutm+1)**2,ntype,MAXVAL(neq))
    COMPLEX, INTENT(OUT)   :: interstitial(noGPts,gptmd)                  ! interstistial overlap intergral

    ! private scalars
    INTEGER                :: cg,cg2,ci,cl,cn,cr                          ! counter variables
    REAL                   ::  r2Pi, r4Pi, pi_omega2                   !  2*Pi, 4*Pi, Pi/omega^2
    REAL                   :: sVol, r4Pi_sVol, r4Pi_Vol                   ! sqrt(vol), 4*Pi/sqrt(Vol), 4*Pi/Vol
    REAL                   :: omega, r1_omega2, r1_4omega2
!     REAL,    PARAMETER     :: omega = omega_VHSE()                        ! omega of the HSE functional
!     REAL,    PARAMETER     :: r1_omega2  = 1.0 / omega**2                 ! 1/omega^2
!     REAL,    PARAMETER     :: r1_4omega2 = 0.25 * r1_omega2               ! 1/(4 omega^2)
    COMPLEX, PARAMETER     :: img = (0d0,1d0)                             ! i

    ! private arrays
    INTEGER                :: gPts(3,noGPts)                              ! g vectors (internal units)
    INTEGER                :: gPts_gptm(3,noGpts,gptmd)                   ! gPts - gptm
    INTEGER                :: natdPtr(ntype+1)                            ! pointer to all atoms of one type
    REAL,    ALLOCATABLE   :: gridf(:,:)                                  ! grid for radial integration
    REAL                   :: k_G(3,noGPts)                               ! k + G
    REAL                   :: AbsK_G(noGPts),AbsK_G2(noGPts)              ! abs(k+G), abs(k+G)^2
    REAL                   :: arg(noGPts)                                 ! abs(k+G)^2 / (4*omega^2)
    REAL                   :: sphbesK_Gr(noGPts,jmtd,0:maxlcutm,ntype)    ! spherical bessel function of abs(k+G)r
    TYPE(intgrf_out)       :: intgrMT(noGPts,maxindxm,0:maxlcutm,ntype)   ! integration in muffin-tin
    REAL                   :: abs_dg(noGpts,gptmd)                        ! abs(gPts - gptm)
    COMPLEX                :: imgl(0:maxlcutm)                            ! i^l
    COMPLEX                :: Ylm(noGPts,(maxlcutm+1)**2)                 ! spherical harmonics for k+G and all lm
    COMPLEX                :: expIGR(noGPts,ntype,MAXVAL(neq))            ! exp(-iGR) for all atom types
    COMPLEX                :: sumInter_atom(noGpts,gptmd)                 ! sum over inter-atom factors

    ! Calculate helper variables
    r2Pi       = 2.0 * pi_const
    r4Pi       = 4.0 * pi_const
    sVol       = SQRT(vol)
    r4Pi_sVol  = r4Pi / sVol
    r4Pi_Vol   = r4Pi / Vol
1040
    omega      = omega_hse!omega_VHSE()
1041 1042 1043 1044 1045 1046 1047 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
    r1_omega2  = 1.0 / omega**2
    r1_4omega2 = 0.25 * r1_omega2
    pi_omega2  = pi_const * r1_omega2

    ! calculate pointers for all atom-types to all atoms
    natdPtr(ntype+1) = natd
    DO cn=ntype,1,-1
       natdPtr(cn) = natdPtr(cn+1) - neq(cn)
    END DO

    ! Define imgl(l) = img**l
    imgl(0) = 1.0
    DO ci=1,maxlcutm
       imgl(ci) = imgl(ci-1) * img
    END DO

    ! generate grid for fast radial integration
    CALL intgrf_init(ntype,jmtd,jri,dx,rmsh,gridf)

    ! Set all arrays to 0
    gPts           = 0
    k_G            = 0
    AbsK_G         = 0
    arg            = 0
    sphbesK_Gr     = 0
    intgrMT%value  = 0
    intgrMT%ierror = 0
    Ylm            = 0
    expIGR         = 0
    gPts_gptm      = 0
    abs_dg         = 0
    sumInter_atom  = 0
    potential      = 0
    muffintin      = 0
    interstitial   = 0

! Calculate the muffin-tin basis function overlap integral
!                                                            R
!                                     -L                      /
!           /      |      \     4 Pi i         ^     -i G R  |     2
! MT (k) = ( k + G | M     ) = ---------- Y ( k+G ) e        | dr r  Phi(r) j ( |k+G| r )  [2]
!   G,I     \      |  k,I /     Sqrt(Om)   LM                |               L
!                                                           /
!                                                            0
    IF (ngptm < noGpts) STOP 'hsefunctional: error calculating Fourier coefficients, noGpts too large'

    gPts(:,:) = gptm(:,pgptm(1:noGPts))
1088
#ifndef __PGI 
1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 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 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

    gpoints: FORALL ( cg=1:noGPts )
      ntypesA: FORALL ( cn=1:ntype )
        ! Calculate the phase factor exp(-iGR) for all atoms
        FORALL ( ci=1:neq(cn) )
          expIGR(cg,cn,ci)        = EXP( -r2Pi * img * DOT_PRODUCT(taual(:,natdPtr(cn)+ci),gPts(:,cg)) )
          muffintin(cg,:,:,cn,ci) = r4Pi_sVol * expIGR(cg,cn,ci)
        END FORALL

        ! Multiplication with i^-L
        FORALL ( cl=0:lcutm(cn) )
          muffintin(cg,:,cl*cl+1:(cl+1)*(cl+1),cn,:) = muffintin(cg,:,cl*cl+1:(cl+1)*(cl+1),cn,:) / imgl(cl)
        END FORALL

      END FORALL ntypesA

      ! Calculate the k+G, abs(k+G), and abs(k+G)^2
      k_G(:,cg)   = MATMUL( gPts(:,cg)+bk(:), bmat(:,:) )
      AbsK_G2(cg) = SUM( k_G(:,cg)**2 )
      AbsK_G(cg)  = SQRT(AbsK_G2(cg))

      ! Spherical harmonics are calculated for all lm's and k+G's
      Ylm(cg,:) = calcYlm(k_G(:,cg),maxlcutm)

      ! Perform the integration in eq.[2] for all muffin-tins
      ntypesB: FORALL ( cn=1:ntype )

        ! Multiplication with the spherical harmonic
        FORALL ( cl=1:(lcutm(cn)+1)**2 )
          muffintin(cg,:,cl,cn,:) = muffintin(cg,:,cl,cn,:) * Ylm(cg,cl)
        END FORALL

        ! Calculate the spherical bessel function
        FORALL ( cr=1:jri(cn) )
          sphbesK_Gr(cg,cr,:,cn) = calcSphBes(AbsK_G(cg)*rmsh(cr,cn),maxlcutm)
        END FORALL
        ! integrate the function and multiplicate to the result
        FORALL ( cl=0:lcutm(cn) )
          FORALL ( ci=1:nindxm(cl,cn) )
            intgrMT(cg,ci,cl,cn) = pure_intgrf(rmsh(:,cn) * basm(:,ci,cl,cn) * &
              sphbesK_Gr(cg,:,cl,cn),jri,jmtd,rmsh,dx,ntype,cn,gridf)
            muffintin(cg,ci,cl*cl+1:(cl+1)*(cl+1),cn,:) = &
              muffintin(cg,ci,cl*cl+1:(cl+1)*(cl+1),cn,:) * intgrMT(cg,ci,cl,cn)%value
          END FORALL
        END FORALL

      END FORALL ntypesB

! calculate the overlap with the interstitial basis function
!                                                      -----
!          /      |      \                       4 Pi   \     -i(G - G_I)R_a  Sin(|G_I - G| R_a) - |G_I - G| R_a Cos(|G_I - G| R_a) 
! IN    = ( k + G | M     ) = kronecker(G,G ) - ------   )   e               ------------------------------------------------------- [3]
!   G,I    \      |  k,I /                 I      Om    /                                          |G_I - G|^3
!                                                      -----
!                                                        a
!                                                                            \_________________________ ___________________________/
!                                                                                                      V
!                                                                                                     I_a
      ! Calculate the difference of the G vectors and its absolute value
      FORALL ( cg2=1:gptmd )

        gPts_gptm(:,cg,cg2) = gPts(:,cg) - gptm(:,cg2)
        abs_dg(cg,cg2)      = gptnorm( gPts_gptm(:,cg,cg2),bmat )

      END FORALL

    END FORALL gpoints

    ! Check if any of the integrations failed and abort if one did
    IF ( ANY( intgrMT%ierror == NEGATIVE_EXPONENT_ERROR ) ) THEN
        IF ( irank == 0 ) WRITE(6,*) 'intgrf: Warning! Negative exponent x in extrapolation a+c*r**x'
    ELSEIF ( ANY( intgrMT%ierror == NEGATIVE_EXPONENT_WARNING ) ) THEN
      IF ( irank == 0 ) WRITE(6,*) 'intgrf: Negative exponent x in extrapolation a+c*r**x'
      STOP       'intgrf: Negative exponent x in extrapolation a+c*r**x'
    END IF

    ! Calculate the interstitial value with eq.[3] using the limit
    !           3
    !        R_a
    ! I_a = ------
    !         3
    ! if there's no difference of the two G vectors
    WHERE ( abs_dg == 0 )
      sumInter_atom = DOT_PRODUCT(rmt**3, neq) / 3.0
      interstitial  = 1.0 - r4Pi_Vol * sumInter_atom
    ELSEWHERE
      sumInter_atom = calculateSummation(abs_dg,gPts_gptm)
      interstitial  = -r4Pi_Vol * sumInter_atom
    END WHERE

! Calculate the Fourier transformed potential
!                                                 /          \
!          /      | erf |       \      4 Pi      |   |k+G|^2  |
! V (k) = ( k + G | --- | k + G' ) = -------  Exp| - -------  | kronecker(G,G')             [1]
!  G       \      |  r  |       /    |k+G|^2     |    4 w^2   |
!                                                 \          /
    WHERE ( absK_G.NE.0 )
      ! Calculate (k+G)^2 / 4*w^2
      arg = -r1_4omega2 * AbsK_G2

      ! The potential is calculated using eq.[1]
      potential = r4Pi / AbsK_G2 * EXP(arg)

! Calculate the Fourier transformed potential for the full(!) potential
!
!          /          | erfc |          \      Pi
! V (k) = ( k + G = 0 | ---- | k + G = 0 ) = -----
!  G       \          |   r  |          /     w^2
!
    ELSEWHERE
      ! the negative sign is added to compensate the sign when the
      ! contribution is added to the Coulomb matrix
      potential = -pi_omega2
    endwhere

    DEALLOCATE( gridf )
1205 1206 1207
#else
    call judft_error("hsefunctional not implemented for PGI")
#endif
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 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 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 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401
  CONTAINS

    ! Calculates the inter-atom parts and the summation over all atoms:
    ! -----
    !  \     -i(G - G_I)R_a  Sin(|G_I - G| R_a) - |G_I - G| R_a Cos(|G_I - G| R_a) 
    !   )   e               -------------------------------------------------------
    !  /                                          |G_I - G|^3
    ! -----
    !   a
    ! Input:  abs_dg    - absolute value |G_I - G|
    !         gPts_gptm - vector G - G_I
    PURE FUNCTION calculateSummation(abs_dg,gPts_gptm)
      IMPLICIT NONE
      INTEGER, INTENT(IN) :: gPts_gptm(3,noGPts,gptmd)
      REAL, INTENT(IN)    :: abs_dg(noGPts,gptmd)
      COMPLEX             :: calculateSummation(noGPts,gptmd)
      INTEGER             :: cn,ci                                     ! counter variables
      REAL                :: abs_dgR(noGPts,gptmd,ntype)               ! abs(gPts - gptm)*R (R: radius MT)
      REAL                :: inter_atom(noGPts,gptmd,ntype)            ! inter-atom interaction for interstitial
      COMPLEX             :: expIdGR(noGPts,gptmd,ntype,MAXVAL(neq))   ! exp(-i(gPts-gptm)R)
      COMPLEX             :: sumExpIdGR(noGPts,gptmd,ntype)            ! sum over atom of same type

      atoms: FORALL ( cn=1:ntype )
        !                                                         -i(G-G_I)R_a
        ! Calculate for all similar atoms (same type) the factor e
        ! use that the G vectors and atomic positions are given in internal units
        FORALL ( ci=1:neq(cn) )
          expIdGR(:,:,cn,ci) = EXP( -r2pi * img * my_dot_product( gPts_gptm(:,:,:),taual(:,natdPtr(cn)+ci) ) )
        END FORALL
        ! Add all factors for atoms of the same type
        sumExpIdGR(:,:,cn) = my_sum(expIdGR(:,:,cn,:))

        ! Calculate the inter-atom factor which is the same for all atoms of the same type
        abs_dgR(:,:,cn)    = abs_dg * rmt(cn)
        inter_atom(:,:,cn) = ( SIN(abs_dgR(:,:,cn)) - abs_dgR(:,:,cn) * COS(abs_dgR(:,:,cn)) ) / abs_dg**3
      END FORALL atoms

      ! Add the factors of all atoms together
      calculateSummation = my_dot_product(sumExpIdGR, inter_atom)
    END FUNCTION calculateSummation

  END SUBROUTINE calculate_fourier_transform

  ! Calculate several Fourier transformations
  ! a) the Fourier transformed potential
  !                                                 /          \
  !          /      | erf |       \     4 Pi       |   |k+G|^2  |
  ! V (k) = ( k + G | --- | k + G  ) = -------  Exp| - -------  |                             [1]
  !  G       \      |  r  |       /    |k+G|^2     |    4 w^2   |
  !                                                 \          /
  !
  ! b) muffin-tin basis function
  !                                                            R
  !                                     -L                      /
  !           /      |      \     4 Pi i         ^     -i G R  |     2
  ! MT (k) = ( k + G | M     ) = ---------- Y ( k+G ) e        | dr r  Phi(r) j ( |k+G| r )  [2]
  !   G,I     \      |  k,I /     Sqrt(Om)   LM                |               L
  !                                                           /
  !                                                            0
  !
  ! In the code:
  ! V_G(k):  potential
  ! MT_G(k): muffintin
  !
  ! Input:
  ! rmsh        - array of radial mesh points
  ! rmt         - radius of the muffin tin
  ! dx          - logarithmic increment of radial mesh
  ! jri         - number of radial mesh points
  ! jmtd        - dimension of radial mesh points
  ! bk          - one(!) k-vector for which FT is calculated
  ! bmat        - reciprocal lattice vector for all directions
  ! vol         - volume of the unit cell
  ! ntype       - number of atom types
  ! neq         - number of symmetry-equivalent atoms of atom type i
  ! natd        - dimesion of atoms in unit cell
  ! taual       - vector of atom positions (internal coordinates)
  ! lcutm       - l cutoff for mixed basis
  ! maxlcutm    - maximum of all these l cutoffs
  ! nindxm      - number of radial functions of mixed basis
  ! maxindxm    - maximum of these numbers
  ! gptm        - reciprocal lattice vectors of the mixed basis (internal coord.)
  ! ngptm       - number of vectors (for treated k-vector)
  ! pgptm       - pointer to the appropriate g-vector (for treated k-vector)
  ! gptmd       - dimension of gptm
  ! basm        - mixed basis functions (mt + inter) for treated k-vector
  ! lexp        - cutoff of spherical harmonics expansion of plane wave
  ! noGPts      - no g-vectors used for Fourier trafo
  ! Output:
  ! potential   - Fourier transformation of the potential
  ! muffintin   - Fourier transformation of all MT functions
  SUBROUTINE calculate_fourier_transform_once( &
      ! Input
      rmsh,rmt,dx,jri,jmtd,bk,ikpt,nkptf,           &
      bmat,vol,ntype,neq,natd,taual,lcutm,maxlcutm, &
      nindxm,maxindxm,gptm,ngptm,pgptm,gptmd,       &
      nbasp,basm,noGPts,invsat,invsatnr,irank,      &
      ! Output
      potential, fourier_trafo)

    USE m_constants
    USE m_util,      ONLY : sphbessel,pure_intgrf,intgrf_init,intgrf_out,NEGATIVE_EXPONENT_WARNING,NEGATIVE_EXPONENT_ERROR
    USE m_trafo,     ONLY : symmetrize

    IMPLICIT NONE

    ! scalar input
    INTEGER, INTENT(IN)    :: natd,ntype,maxlcutm
    INTEGER, INTENT(IN)    :: ikpt,nkptf,jmtd
    INTEGER, INTENT(IN)    :: maxindxm,irank
    INTEGER, INTENT(IN)    :: gptmd,noGPts
    REAL, INTENT(IN)       :: vol

    ! array input
    INTEGER, INTENT(IN)    :: lcutm(ntype)
    INTEGER, INTENT(IN)    :: nindxm(0:maxlcutm,ntype),neq(ntype)
    INTEGER, INTENT(IN)    :: jri(ntype)
    INTEGER, INTENT(IN)    :: gptm(3,gptmd)
    INTEGER, INTENT(IN)    :: ngptm,nbasp
    INTEGER, INTENT(IN)    :: pgptm(ngptm)
    INTEGER, INTENT(IN)    :: invsat(natd),invsatnr(natd)

    REAL, INTENT(IN)       :: bk(3)
    REAL, INTENT(IN)       :: rmsh(jmtd,ntype),rmt(ntype),dx(ntype)
    REAL, INTENT(IN)       :: basm(jmtd,maxindxm,0:maxlcutm,ntype)
    REAL, INTENT(IN)       :: bmat(3,3)
    REAL, INTENT(IN)       :: taual(3,natd)

    ! array output
    REAL,    INTENT(OUT)   :: potential(noGPts)                           ! Fourier transformed potential
#ifdef CPP_INVERSION
    REAL,    INTENT(OUT)   :: fourier_trafo(nbasp,noGPts) !muffintin_out(nbasp,noGPts)
#else
    COMPLEX, INTENT(OUT)   :: fourier_trafo(nbasp,noGPts) !muffintin_out(nbasp,noGPts)
#endif

    ! private scalars
    INTEGER                :: cg,cg2,ci,cl,cm,cn,cr                       ! counter variables
    REAL                   :: r2Pi, r4Pi, pi_omega2                   ! Pi, 2*Pi, 4*Pi, Pi/omega^2
    REAL                   :: sVol, r4Pi_sVol, r4Pi_Vol                   ! sqrt(vol), 4*Pi/sqrt(Vol), 4*Pi/Vol
    REAL                   :: omega, r1_omega2, r1_4omega2
!     REAL,    PARAMETER     :: omega = omega_VHSE()                        ! omega of the HSE functional
!     REAL,    PARAMETER     :: r1_omega2  = 1.0 / omega**2                 ! 1/omega^2
!     REAL,    PARAMETER     :: r1_4omega2 = 0.25 * r1_omega2               ! 1/(4 omega^2)
    COMPLEX, PARAMETER     :: img = (0d0,1d0)                             ! i

    ! private arrays
    INTEGER                :: gPts(3,noGPts)                              ! g vectors (internal units)
    INTEGER                :: natdPtr(ntype+1)                            ! pointer to all atoms of one type
    INTEGER                :: ptrType(nbasp),ptrEq(nbasp),&               ! pointer from ibasp to corresponding
                              ptrLM(nbasp),ptrN(nbasp)                    ! type, atom, l and m, and n
    REAL,    ALLOCATABLE   :: gridf(:,:)                                  ! grid for radial integration
    REAL                   :: k_G(3,noGPts)                               ! k + G
    REAL                   :: AbsK_G(noGPts),AbsK_G2(noGPts)              ! abs(k+G), abs(k+G)^2
    REAL                   :: arg(noGPts)                                 ! abs(k+G)^2 / (4*omega^2)
    REAL                   :: sphbesK_Gr(noGPts,jmtd,0:maxlcutm,ntype)    ! spherical bessel function of abs(k+G)r
    TYPE(intgrf_out)       :: intgrMT(noGPts,maxindxm,0:maxlcutm,ntype)   ! integration in muffin-tin
    COMPLEX                :: imgl(0:maxlcutm)                            ! i^l
    COMPLEX                :: Ylm(noGPts,(maxlcutm+1)**2)                 ! spherical harmonics for k+G and all lm
    COMPLEX                :: expIGR(noGPts,ntype,MAXVAL(neq))            ! exp(-iGR) for all atom types
    COMPLEX                :: muffintin(noGPts,maxindxm,&                 ! muffin-tin overlap integral
                                        (maxlcutm+1)**2,ntype,MAXVAL(neq))
#ifdef CPP_INVERSION
    COMPLEX                :: sym_muffintin(nbasp,noGPts)                 ! symmetrized muffin tin
#endif

    LOGICAL, SAVE          :: first_entry = .TRUE.                        ! allocate arrays in first entry

    ! allocate arrays in first entry reuse later
    IF ( first_entry ) THEN
      ALLOCATE ( already_known(nkptf),                       &            ! stores which elements are known
                 known_potential(maxNoGPts,nkptf),           &            ! stores the potential for all k-points
                 known_fourier_trafo(nbasp, maxNoGPts,nkptf) )            ! stores the fourier transform of the mixed basis
      ! initialization
      already_known       = .FALSE.
      known_potential     = 0.0
      known_fourier_trafo = 0.0
      ! unset flag as arrays are allocated
      first_entry         = .FALSE.
    ELSE
      ! check if size of arrays has changed and stop with error if they did
      IF ( SIZE(already_known) /= nkptf )         STOP 'hsefunctional: Array size changed!'
      IF ( SIZE(known_fourier_trafo,1) /= nbasp ) STOP 'hsefunctional: Array size changed!'
    END IF

    ! if the current k-point was not calculated yet
    IF ( .NOT.(already_known(ikpt)) ) THEN

      ! Calculate helper variables
      r2Pi       = 2.0 * pi_const
      r4Pi       = 4.0 * pi_const
      sVol       = SQRT(vol)
      r4Pi_sVol  = r4Pi / sVol
      r4Pi_Vol   = r4Pi / Vol
1402
      omega      = omega_hse!omega_VHSE()
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 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 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 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 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 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 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 1705 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
      r1_omega2  = 1.0 / omega**2
      r1_4omega2 = 0.25 * r1_omega2
      pi_omega2  = pi_const * r1_omega2

      ! calculate pointers for all atom-types to all atoms
      natdPtr(ntype+1) = natd
      DO cn=ntype,1,-1
        natdPtr(cn) = natdPtr(cn+1) - neq(cn)
      END DO

      ! Define imgl(l) = img**l
      imgl(0) = 1.0
      DO ci=1,maxlcutm
        imgl(ci) = imgl(ci-1) * img
      END DO

      ! generate grid for fast radial integration
      CALL intgrf_init(ntype,jmtd,jri,dx,rmsh,gridf)

      ! Set all arrays to 0
      gPts           = 0
      k_G            = 0
      AbsK_G         = 0
      arg            = 0
      sphbesK_Gr     = 0
      intgrMT%value  = 0
      intgrMT%ierror = 0
      Ylm            = 0
      expIGR         = 0
      potential      = 0
      muffintin      = 0

! Calculate the muffin-tin basis function overlap integral
!                                                            R
!                                     -L                      /
!           /      |      \     4 Pi i         ^     -i G R  |     2
! MT (k) = ( k + G | M     ) = ---------- Y ( k+G ) e        | dr r  Phi(r) j ( |k+G| r )  [2]
!   G,I     \      |  k,I /     Sqrt(Om)   LM                |               L
!                                                           /
!                                                            0
      IF (ngptm < noGpts) STOP 'hsefunctional: error calculating Fourier coefficients, noGpts too large'

      gPts(:,:) = gptm(:,pgptm(1:noGPts))

      gpoints: FORALL ( cg=1:noGPts )
        ntypesA: FORALL ( cn=1:ntype )

          ! Calculate the phase factor exp(-iGR) for all atoms
          FORALL ( ci=1:neq(cn) )
            expIGR(cg,cn,ci)        = EXP( -r2Pi * img * DOT_PRODUCT(taual(:,natdPtr(cn)+ci),gPts(:,cg)) )
            muffintin(cg,:,:,cn,ci) = r4Pi_sVol * expIGR(cg,cn,ci)
          END FORALL

          ! Multiplication with i^-L
          FORALL ( cl=0:lcutm(cn) )
            muffintin(cg,:,cl*cl+1:(cl+1)*(cl+1),cn,:) = muffintin(cg,:,cl*cl+1:(cl+1)*(cl+1),cn,:) / imgl(cl)
          END FORALL

        END FORALL ntypesA

        ! Calculate the k+G, abs(k+G), and abs(k+G)^2
        k_G(:,cg)   = MATMUL( gPts(:,cg)+bk(:), bmat(:,:) )
        AbsK_G2(cg) = SUM( k_G(:,cg)**2 )
        AbsK_G(cg)  = SQRT(AbsK_G2(cg))

        ! Spherical harmonics are calculated for all lm's and k+G's
        Ylm(cg,:) = calcYlm(k_G(:,cg),maxlcutm)

        ! Perform the integration in eq.[2] for all muffin-tins
        ntypesB: FORALL ( cn=1:ntype )

          ! Multiplication with the spherical harmonic
          FORALL ( cl=1:(lcutm(cn)+1)**2 )
            muffintin(cg,:,cl,cn,:) = muffintin(cg,:,cl,cn,:) * Ylm(cg,cl)
          END FORALL

          ! Calculate the spherical bessel function
          FORALL ( cr=1:jri(cn) )
            sphbesK_Gr(cg,cr,:,cn) = calcSphBes(AbsK_G(cg)*rmsh(cr,cn),maxlcutm)
          END FORALL
          ! integrate the function and multiplicate to the result
          FORALL ( cl=0:lcutm(cn) )
            FORALL ( ci=1:nindxm(cl,cn) )
              intgrMT(cg,ci,cl,cn) = pure_intgrf(rmsh(:,cn) * basm(:,ci,cl,cn) * &
                sphbesK_Gr(cg,:,cl,cn),jri,jmtd,rmsh,dx,ntype,cn,gridf)
              muffintin(cg,ci,cl*cl+1:(cl+1)*(cl+1),cn,:) = &
                muffintin(cg,ci,cl*cl+1:(cl+1)*(cl+1),cn,:) * intgrMT(cg,ci,cl,cn)%value
            END FORALL
          END FORALL

        END FORALL ntypesB

      END FORALL gpoints

      ! Check if any of the integrations failed and abort if one did
      IF ( ANY( intgrMT%ierror == NEGATIVE_EXPONENT_ERROR ) ) THEN
          IF ( irank == 0 ) WRITE(6,*) 'intgrf: Warning! Negative exponent x in extrapolation a+c*r**x'
      ELSEIF ( ANY( intgrMT%ierror == NEGATIVE_EXPONENT_WARNING ) ) THEN
        IF ( irank == 0 ) WRITE(6,*) 'intgrf: Negative exponent x in extrapolation a+c*r**x'
        STOP       'intgrf: Negative exponent x in extrapolation a+c*r**x'
      END IF

! Calculate the Fourier transformed potential
!                                                 /          \
!          /      | erf |       \      4 Pi      |   |k+G|^2  |
! V (k) = ( k + G | --- | k + G' ) = -------  Exp| - -------  | kronecker(G,G')             [1]
!  G       \      |  r  |       /    |k+G|^2     |    4 w^2   |
!                                                 \          /
      WHERE ( absK_G.NE.0 )
        ! Calculate (k+G)^2 / 4*w^2
        arg = -r1_4omega2 * AbsK_G2

        ! The potential is calculated using eq.[1]
        potential = r4Pi / AbsK_G2 * EXP(arg)

! Calculate the Fourier transformed potential for the full(!) potential
!
!          /          | erfc |          \      Pi
! V (k) = ( k + G = 0 | ---- | k + G = 0 ) = -----
!  G       \          |   r  |          /     w^2
!
      ELSEWHERE
        ! the negative sign is added to compensate the sign when the
        ! contribution is added to the Coulomb matrix
        potential = -pi_omega2
      endwhere

      DEALLOCATE( gridf )

      !
      ! Create pointer which correlate the position in the array with the
      ! appropriate indices of the MT mixed basis function
      !
      cg = 0
      DO cn=1,ntype
        DO ci=1,neq(cn)
          DO cl=0,lcutm(cn)
            DO cm=-cl,cl
              DO cr=1,nindxm(cl,cn)
                cg = cg + 1
                ptrType(cg) = cn
                ptrEq(cg)   = ci
                ptrLM(cg)   = (cl+1)*cl+cm+1
                ptrN(cg)    = cr
              END DO
            END DO
          END DO
        END DO
      END DO
      IF ( nbasp /= cg ) STOP 'hsefunctional: wrong array size: nbasp'

#ifdef CPP_INVERSION
      ! Symmetrize muffin tin fourier transform
      DO ci=1,nbasp
        sym_muffintin(ci,:noGPts) = muffintin(:,ptrN(ci),ptrLM(ci),ptrType(ci),ptrEq(ci))
      END DO
      DO cg=1,noGPts
        CALL symmetrize( sym_muffintin(:,cg),1,nbasp,2,.FALSE., &
                         ntype,ntype,neq,lcutm,maxlcutm,        &
                         nindxm,natd,invsat,invsatnr )
      END DO
      ! store the fourier transform of the muffin tin basis
      known_fourier_trafo(:,:,ikpt) = REAL( sym_muffintin )
#else
      ! store the fourier transform of the muffin tin basis
      DO ci=1,nbasp
        known_fourier_trafo(ci,:noGPts,ikpt) = CONJG( muffintin(:,ptrN(ci),ptrLM(ci),ptrType(ci),ptrEq(ci)) )
      END DO
#endif
      ! store the fourier transform of the potential
      known_potential(:noGPts,ikpt)   = potential
      ! set the flag so that the fourier transform is not calculated again
      already_known(ikpt)             = .TRUE.
      IF ( MINVAL( ABS(potential) ) > 1e-12 ) THEN
        WRITE(*,*) 'hsefunctional: Warning! Smallest potential bigger than numerical precision!', MINVAL( ABS(potential) )
        WRITE(*,*) 'Perhaps you should increase the number of g-Points used and recompile!'
      END IF

    END IF

    ! return the fourier transform
    potential     = known_potential(:noGPts,ikpt)
    fourier_trafo = known_fourier_trafo(:,:noGPts,ikpt)

  END SUBROUTINE calculate_fourier_transform_once

  ! Correct the pure Coulomb Matrix with by subtracting the long-range component
  !
  !  /     |      |      \     /     |       |      \     /     |     |      \
  ! ( M    | V    | M     ) = ( M    | V     | M     ) - ( M    | V   | M     )
  !  \ k,I |  HSE |  k,J /     \ k,I |  coul |  k,J /     \ k,I |  LR |  k,J /
  !
  ! The long-range component is given py the potential
  !
  !         erf( w r )
  ! V (r) = ----------
  !  LR         r
  !
  ! Input:
  ! rmsh     - array of radial mesh points
  ! rmt      - radius of the muffin tin
  ! dx       - logarithmic increment of radial mesh
  ! jri      - number of radial mesh points
  ! jmtd     - dimension of radial mesh points
  ! nkptf    - number of total k-points
  ! nkptd    - dimension of k-points
  ! nkpti    - number of irreducible k-points in window (in KPTS)
  ! bk       - k-vector for all irreduble k-points
  ! bmat     - reciprocal lattice vector for all directions
  ! vol      - volume of unit cell
  ! ntype    - number of atom types
  ! neq      - number of symmetry-equivalent atoms of atom type i
  ! natd     - dimension of atoms in unit cell
  ! taual    - vector of atom positions (internal coordinates)
  ! lcutm    - l cutoff for mixed basis
  ! maxlcutm - maximum of all these l cutoffs
  ! nindxm   - number of radial functions of mixed basis
  ! maxindxm - maximum of these numbers
  ! gptm     - reciprocal lattice vectors of the mixed basis (internal coord.)
  ! ngptm    - number of vectors
  ! pgptm    - pointer to the appropriate g-vector
  ! gptmd    - dimension of gptm
  ! basm     - radial mixed basis functions (mt + inter)
  ! lexp     - cutoff of spherical harmonics expansion of plane wave
  ! maxbasm  - maximum number of mixed basis functions
  ! nbasm    - number of mixed basis function
  ! invsat   - number of inversion-symmetric atom
  ! invsatnr - number of inversion-symmetric atom
  ! Inout:
  ! coulomb  - Coulomb matrix which is changed
  SUBROUTINE change_coulombmatrix(&
      ! Input
      rmsh,rmt,dx,jri,jmtd,nkptf,nkptd,nkpti,bk,      &
      bmat,vol,ntype,neq,natd,taual,lcutm,maxlcutm,   &
      nindxm,maxindxm,gptm,ngptm,pgptm,gptmd,         &
      basm,lexp,maxbasm,nbasm,invsat,invsatnr,irank,  &
      ! Input & output
      coulomb)

    USE m_trafo, ONLY: symmetrize
    USE m_wrapper, ONLY: packmat, unpackmat, diagonalize, inverse
    USE m_olap,  ONLY: olap_pw

    IMPLICIT NONE

    ! scalar input
    INTEGER, INTENT(IN)    :: natd,ntype,maxlcutm,lexp
    INTEGER, INTENT(IN)    :: jmtd,nkptf,nkptd,nkpti
    INTEGER, INTENT(IN)    :: maxindxm
    INTEGER, INTENT(IN)    :: gptmd,irank
    INTEGER, INTENT(IN)    :: maxbasm
    REAL, INTENT(IN)       :: vol

    ! array input
    INTEGER, INTENT(IN)    :: lcutm(ntype)
    INTEGER, INTENT(IN)    :: nindxm(0:maxlcutm,ntype),neq(ntype)
    INTEGER, INTENT(IN)    :: jri(ntype)
    INTEGER, INTENT(IN)    :: gptm(3,gptmd)
    INTEGER, INTENT(IN)    :: ngptm(nkptf)
    INTEGER, INTENT(IN)    :: pgptm(MAXVAL(ngptm),nkptf)
    INTEGER, INTENT(IN)    :: nbasm(nkptf)
    INTEGER, INTENT(IN)    :: invsat(natd),invsatnr(natd)

    REAL, INTENT(IN)       :: bk(3,nkptd)
    REAL, INTENT(IN)       :: rmsh(jmtd,ntype),rmt(ntype),dx(ntype)
    REAL, INTENT(IN)       :: basm(jmtd,maxindxm,0:maxlcutm,ntype)
    REAL, INTENT(IN)       :: bmat(3,3)
    REAL, INTENT(IN)       :: taual(3,natd)

    ! array inout
#ifdef CPP_INVERSION
    REAL, INTENT(INOUT)    :: coulomb(maxbasm*(maxbasm+1)/2,nkpti)
#else
    COMPLEX, INTENT(INOUT) :: coulomb(maxbasm*(maxbasm+1)/2,nkpti)
#endif

    ! private scalars
    INTEGER                :: ikpt,itype,ieq,il,im,iindxm,idum,n1,n2,ok    ! counters and other helper variables
    INTEGER                :: noGPts,nbasp                                 ! no used g-vectors, no MT functions

    ! private arrays
    INTEGER, ALLOCATABLE   :: ptrType(:),ptrEq(:),ptrL(:),ptrM(:),ptrN(:)  ! Pointer
    REAL                   :: potential(maxNoGPts)                         ! Fourier transformed potential
    COMPLEX                :: muffintin(maxNoGPts,maxindxm,&               ! muffin-tin overlap integral
                                        (maxlcutm+1)**2,ntype,MAXVAL(neq))
    COMPLEX                :: interstitial(maxNoGPts,gptmd)                ! interstistial overlap intergral
    COMPLEX, ALLOCATABLE   :: coulmat(:,:)                                 ! helper array to symmetrize coulomb

    ! Check size of arrays
    IF (nkpti > nkptd) STOP 'hsefunctional: missmatch in dimension of arrays'
    nbasp = maxbasm - MAXVAL(ngptm)
    IF ( ANY( nbasm - ngptm /= nbasp ) ) STOP 'hsefunctional: wrong assignment of nbasp'

    !
    ! Create pointer which correlate the position in the array with the
    ! appropriate indices of the MT mixed basis function
    !
    ALLOCATE( ptrType(nbasp), ptrEq(nbasp), ptrL(nbasp), ptrM(nbasp), ptrN(nbasp) )
    nbasp = 0
    DO itype=1,ntype
       DO ieq=1,neq(itype)
          DO il=0,lcutm(itype)
             DO im=-il,il
                DO iindxm=1,nindxm(il,itype)
                   nbasp = nbasp + 1
                   ptrType(nbasp) = itype
                   ptrEq(nbasp)   = ieq
                   ptrL(nbasp)    = il
                   ptrM(nbasp)    = im
                   ptrN(nbasp)    = iindxm
                END DO
             END DO
          END DO
       END DO
    END DO

    !
    ! Change the Coulomb matrix for all k-points
    !
    DO ikpt=1,nkpti
      ! use the same g-vectors as in the mixed basis
      ! adjust the limit of the array if necessary
      IF (ngptm(ikpt) < maxNoGPts) THEN
        noGPts = ngptm(ikpt)
      ELSE
        noGPts = maxNoGPts
      END IF

      !
      ! Calculate the Fourier transform of the mixed basis and the potential
      !
      CALL calculate_fourier_transform( &
           ! Input
           rmsh,rmt,dx,jri,jmtd,bk(:,ikpt),&
           bmat,vol,ntype,neq,natd,taual,lcutm,maxlcutm,&
           nindxm,maxindxm,gptm,ngptm(ikpt),pgptm(:,ikpt),gptmd,&
           basm,noGPts,irank,&
           ! Output
           potential,muffintin,interstitial)
      interstitial = CONJG(interstitial)

      ! Helper matrix for temporary storage of the attenuated Coulomb matrix
      ALLOCATE ( coulmat(nbasm(ikpt),nbasm(ikpt)) , stat=ok )
      IF ( ok /= 0 ) STOP 'hsefunctional: failure at matrix allocation'
      coulmat = 0
      !
      ! Calculate the difference of the Coulomb matrix by the attenuation
      !
      DO n1 = 1,nbasp
        DO n2 = 1,n1
          ! muffin tin - muffin tin contribution
          coulmat(n2,n1) = - gPtsSummation( noGpts,&
                                muffintin(:,ptrN(n2),(ptrL(n2)+1)*ptrL(n2)+ptrM(n2)+1,ptrType(n2),ptrEq(n2)),potential,&
                                CONJG(muffintin(:,ptrN(n1),(ptrL(n1)+1)*ptrL(n1)+ptrM(n1)+1,ptrType(n1),ptrEq(n1))) )
          coulmat(n1,n2) = CONJG(coulmat(n2,n1))
        END DO
      END DO
      DO n1 = nbasp+1,nbasm(ikpt)
        DO n2 = 1,n1
          IF ( n2 <= nbasp ) THEN
            ! muffin tin - interstitial contribution
            coulmat(n2,n1) = - gPtsSummation( noGPts,&
                                  muffintin(:,ptrN(n2),(ptrL(n2)+1)*ptrL(n2)+ptrM(n2)+1,ptrType(n2),ptrEq(n2)),&
                                  potential,CONJG(interstitial(:,pgptm(n1-nbasp,ikpt))) )
            coulmat(n1,n2) = CONJG(coulmat(n2,n1))
          ELSE
            ! interstitial - interstitial contribution
            coulmat(n2,n1) = - gPtsSummation( noGPts,&
                                  interstitial(:,pgptm(n2-nbasp,ikpt)),potential,&
                                  CONJG(interstitial(:,pgptm(n1-nbasp,ikpt))) )
            coulmat(n1,n2) = CONJG(coulmat(n2,n1))
          END IF
        END DO
      END DO

#ifdef CPP_INVERSION
      ! symmetrize matrix if system has inversion symmetry
      CALL symmetrize(coulmat,nbasm(ikpt),nbasm(ikpt),3,.FALSE., &
                      ntype,ntype,neq,lcutm,maxlcutm, &
                      nindxm,natd,invsat,invsatnr)
#endif
      ! add the changes to the Coulomb matrix
      coulomb(:nbasm(ikpt)*(nbasm(ikpt)+1)/2,ikpt) = packmat( coulmat ) + coulomb(:nbasm(ikpt)*(nbasm(ikpt)+1)/2,ikpt)
      DEALLOCATE ( coulmat )

    END DO

    DEALLOCATE( ptrType, ptrEq, ptrL, ptrM, ptrN )

  END SUBROUTINE change_coulombmatrix

  ! Correct the pure Coulomb Matrix with by subtracting the long-range component
  ! during execution time
  !
  !  /     |      |      \     /     |       |      \     /     |     |      \
  ! ( M    | V    | M     ) = ( M    | V     | M     ) - ( M    | V   | M     )
  !  \ k,I |  HSE |  k,J /     \ k,I |  coul |  k,J /     \ k,I |  LR |  k,J /
  !
  ! The long-range component is given py the potential
  !
  !         erf( w r )
  ! V (r) = ----------
  !  LR         r
  !
  ! Input:
  ! rmsh     - array of radial mesh points
  ! rmt      - radius of the muffin tin
  ! dx       - logarithmic increment of radial mesh
  ! jri      - number of radial mesh points
  ! jmtd     - dimension of radial mesh points
  ! bk       - k-vector for this k-point
  ! ikpt     - number of this k-point
  ! nkptf    - number of total k-points
  ! bmat     - reciprocal lattice vector for all directions
  ! vol      - volume of unit cell
  ! ntype    - number of atom types
  ! neq      - number of symmetry-equivalent atoms of atom type i
  ! natd     - dimension of atoms in unit cell
  ! taual    - vector of atom positions (internal coordinates)
  ! lcutm    - l cutoff for mixed basis
  ! maxlcutm - maximum of all these l cutoffs
  ! nindxm   - number of radial functions of mixed basis
  ! maxindxm - maximum of these numbers
  ! gptm     - reciprocal lattice vectors of the mixed basis (internal coord.)
  ! ngptm    - number of vectors
  ! pgptm    - pointer to the appropriate g-vector
  ! gptmd    - dimension of gptm
  ! basm     - radial mixed basis functions (mt + inter)
  ! nbasm    - number of mixed basis function
  ! nobd     - dimension of occupied bands
  ! nbands   - number of bands
  ! nsst     - size of indx
  ! indx     - pointer to bands
  ! invsat   - number of inversion-symmetric atom
  ! invsatnr - number of inversion-symmetric atom
  ! cprod    - scalar product of mixed basis and wavefunction product basis
  ! wl_iks   -
  ! n_q      -
  ! Return:
  ! Change of the Coulomb matrix
  FUNCTION dynamic_hse_adjustment( &
      rmsh,rmt,dx,jri,jmtd,bk,ikpt,nkptf,bmat,vol,&
      ntype,neq,natd,taual,lcutm,maxlcutm,nindxm,maxindxm,&
      gptm,ngptm,pgptm,gptmd,basm,nbasm,&
      nobd,nbands,nsst,ibando,psize,indx,invsat,invsatnr,irank,&
Daniel Wortmann's avatar
Daniel Wortmann committed
1848
      cprod_r,cprod_c,l_real,wl_iks,n_q)
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

    USE m_trafo, ONLY: symmetrize
    USE m_olap,  ONLY: olap_pw, olap_pwp
    USE m_wrapper, ONLY: diagonalize, dotprod, matvec, packmat, inverse

    IMPLICIT NONE

    ! scalar input
    INTEGER, INTENT(IN)  :: natd,ntype,maxlcutm
    INTEGER, INTENT(IN)  :: jmtd,ikpt,nkptf
    INTEGER, INTENT(IN)  :: maxindxm
    INTEGER, INTENT(IN)  :: gptmd,irank
    INTEGER, INTENT(IN)  :: nbasm,nobd,nbands,ibando,psize
    INTEGER, INTENT(IN)  :: n_q
    REAL, INTENT(IN)     :: vol

    ! array input
    INTEGER, INTENT(IN)  :: lcutm(ntype)
    INTEGER, INTENT(IN)  :: nindxm(0:maxlcutm,ntype),neq(ntype)
    INTEGER, INTENT(IN)  :: jri(ntype)
    INTEGER, INTENT(IN)  :: gptm(3,gptmd)
    INTEGER, INTENT(IN)  :: ngptm
    INTEGER, INTENT(IN)  :: pgptm(ngptm)
    INTEGER, INTENT(IN)  :: nsst(nbands),indx(nbands,nbands)
    INTEGER, INTENT(IN)  :: invsat(natd),invsatnr(natd)
    REAL, INTENT(IN)     :: bk(3)
    REAL, INTENT(IN)     :: rmsh(jmtd,ntype),rmt(ntype),dx(ntype)
    REAL, INTENT(IN)     :: basm(jmtd,maxindxm,0:maxlcutm,ntype)
    REAL, INTENT(IN)     :: bmat(3,3)
    REAL, INTENT(IN)     :: taual(3,natd)
    REAL, INTENT(IN)     :: wl_iks(nobd)
Daniel Wortmann's avatar
Daniel Wortmann committed
1880 1881 1882
    REAL, INTENT(IN)     :: cprod_r(nbasm,psize,nbands)
    COMPLEX, INTENT(IN)  :: cprod_c(nbasm,psize,nbands)
    LOGICAL,INTENT(IN)   :: l_real
1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904

    ! return type definition
    COMPLEX              :: dynamic_hse_adjustment(nbands,nbands)

    ! private scalars
    INTEGER              :: noGpts,nbasp
    INTEGER              :: itype,ieq,il,im,iindxm,ibasp
    INTEGER              :: igpt,iobd,iobd0,isst,iband1,iband2
    COMPLEX              :: cdum,gPtsSum

    ! private arrays
    INTEGER, ALLOCATABLE :: ptrType(:),ptrEq(:),ptrL(:),ptrM(:),ptrN(:) ! pointer to reference muffintin-array
    REAL                 :: potential(maxNoGPts)                        ! Fourier transformed potential
    COMPLEX              :: muffintin(maxNoGPts,maxindxm,&              ! muffin-tin overlap integral
                                        (maxlcutm+1)**2,ntype,MAXVAL(neq))
    COMPLEX              :: interstitial(maxNoGPts,gptmd)               ! interstistial overlap intergral
#ifdef CPP_INVERSION
    REAL                 :: fourier_trafo(nbasm-ngptm,maxNoGPts)        ! Fourier trafo of all mixed basis functions
#else
    COMPLEX              :: fourier_trafo(nbasm-ngptm,maxNoGPts)        ! Fourier trafo of all mixed basis functions
#endif

Daniel Wortmann's avatar
Daniel Wortmann committed
1905 1906
    REAL                 :: cprod_fourier_trafo_r(maxNoGpts,psize,nbands)  ! Product of cprod and Fourier trafo
    COMPLEX              :: cprod_fourier_trafo_c(maxNoGpts,psize,nbands)  ! Product of cprod and Fourier trafo
1907 1908 1909 1910 1911

    ! Initialisation
    dynamic_hse_adjustment = 0.0
    potential              = 0.0
    fourier_trafo          = 0.0
Daniel Wortmann's avatar
Daniel Wortmann committed
1912 1913
    cprod_fourier_trafo_r    = 0.0
    cprod_fourier_trafo_c    = 0.0
1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934
    noGPts                 = MIN(ngptm,maxNoGPts)
    nbasp                  = nbasm - ngptm

    !
    ! Calculate the fourier transform of the mixed basis once
    ! If it was already calculated load the old results
    !
    CALL calculate_fourier_transform_once(          &
      rmsh,rmt,dx,jri,jmtd,bk,ikpt,nkptf,           &
      bmat,vol,ntype,neq,natd,taual,lcutm,maxlcutm, &
      nindxm,maxindxm,gptm,ngptm,pgptm,gptmd,       &
      nbasp,basm,noGPts,invsat,invsatnr,irank,      &
      potential,fourier_trafo)

    ! Calculate the Fourier transform of the 'normal' basis
    ! by summing over the mixed basis
    DO igpt = 1,noGPts
      DO iobd0 = 1,psize!ibando,min(ibando+psize,nobd)
        iobd = iobd0 + ibando - 1
        IF( iobd .GT. nobd ) CYCLE
        DO iband1 = 1,nbands
Daniel Wortmann's avatar
Daniel Wortmann committed
1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947
           if (l_real) THEN
              cprod_fourier_trafo_r(igpt,iobd0,iband1) = &
                   ! muffin tin contribution
                   dotprod( fourier_trafo(:nbasp,igpt), cprod_r(:nbasp,iobd0,iband1) ) &
                   ! interstitial contribution (interstitial is kronecker_G,G')
                   + cprod_r(nbasp+igpt,iobd0,iband1)
           else
              cprod_fourier_trafo_c(igpt,iobd0,iband1) = &
                   ! muffin tin contribution
                   dotprod( cprod_c(:nbasp,iobd0,iband1), fourier_trafo(:nbasp,igpt) ) &
                   ! interstitial contribution (interstitial is kronecker_G,G')
                   + CONJG( cprod_c(nbasp+igpt,iobd0,iband1) )
           endif
1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961
        END DO
      END DO
    END DO

    ! Summation over all G-vectors
    DO iband1 = 1,nbands
      DO iobd0 = 1,psize!ibando,min(ibando+psize,nobd)
        iobd = iobd0 + ibando - 1
        IF( iobd .GT. nobd ) CYCLE
        ! prefactor for all elements
        cdum = wl_iks(iobd) / n_q
        DO isst = 1,nsst(iband1)
          iband2  = indx(isst,iband1)
          ! do summation over G-vectors
Daniel Wortmann's avatar
Daniel Wortmann committed
1962 1963 1964 1965 1966 1967 1968 1969 1970
          if (l_real) THEN
             gPtsSum = cdum * gPtsSummation(noGPts,&
                  cprod_fourier_trafo_r(:,iobd0,iband1),&
                  potential,cprod_fourier_trafo_r(:,iobd0,iband2) )
          ELSE
             gPtsSum = cdum * gPtsSummation(noGPts,&
                  conjg(cprod_fourier_trafo_c(:,iobd0,iband1)),&
                  potential,cprod_fourier_trafo_c(:,iobd0,iband2) )
          endif
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 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597
          dynamic_hse_adjustment(iband2,iband1) = &
              dynamic_hse_adjustment(iband2,iband1) - gPtsSum
        END DO
      END DO
    END DO

  END FUNCTION dynamic_hse_adjustment

  ! Helper function needed to use forall statements instead of do loop's
  ! calls the harmonicsr subroutine from 'util.F'
  PURE FUNCTION calcYlm(rvec,ll)
    USE m_util, ONLY : harmonicsr
    IMPLICIT NONE
    REAL, INTENT(IN)    :: rvec(3)
    INTEGER, INTENT(IN) :: ll
    COMPLEX             :: calcYlm( (ll+1)**2 )
    CALL harmonicsr(calcYlm, rvec, ll)
  END FUNCTION calcYlm

  ! Helper function needed to use forall statements instead of do loop's
  ! calls the sphbessel subroutine from 'util.F'
  PURE FUNCTION calcSphBes(x,l)
    USE m_util, ONLY : sphbessel
    IMPLICIT NONE
    REAL, INTENT(IN)    :: x
    INTEGER, INTENT(IN) :: l
    REAL                :: calcSphBes(0:l)
    CALL sphbessel(calcSphBes,x,l)
  END FUNCTION calcSphBes

  ! Dot_product definition for two arrays (3d x 1d) with common size of first dimension
  PURE FUNCTION my_dot_product3x1(first,second)
    IMPLICIT NONE
    INTEGER, INTENT(IN) :: first(:,:,:)
    REAL, INTENT(IN)    :: second( SIZE(first,1) )
    REAL                :: my_dot_product3x1( SIZE(first,2), SIZE(first,3) )
    INTEGER             :: ci, cj

    FORALL ( ci=1:SIZE(first,2), cj=1:SIZE(first,3) )
       my_dot_product3x1(ci,cj) = DOT_PRODUCT(first(:,ci,cj), second)
    END FORALL
  END FUNCTION my_dot_product3x1

  ! Dot_product definition for two arrays (4d x 1d) with common size of first dimension
  PURE FUNCTION my_dot_product4x1(first,second)
    IMPLICIT NONE
    INTEGER, INTENT(IN) :: first(:,:,:,:)
    REAL, INTENT(IN)    :: second( SIZE(first,1) )
    REAL                :: my_dot_product4x1( SIZE(first,2), SIZE(first,3), SIZE(first,4) )
    INTEGER             :: ci, cj, ck

    FORALL ( ci=1:SIZE(first,2), cj=1:SIZE(first,3), ck=1:SIZE(first,4) )
       my_dot_product4x1(ci,cj,ck) = DOT_PRODUCT(first(:,ci,cj,ck), second)
    END FORALL
  END FUNCTION my_dot_product4x1

  ! Dot_product definition for two arrays (3d x 3d) with common size of all dimensions,
  ! The scalar product is evaluated over the last index
  PURE FUNCTION my_dot_product3x3(first, second)
    IMPLICIT NONE
    COMPLEX, INTENT(IN) :: first(:,:,:)
    REAL,    INTENT(IN) :: second( SIZE(first,1), SIZE(first,2), SIZE(first,3) )
    COMPLEX             :: my_dot_product3x3( SIZE(first,1), SIZE(first,2) )
    INTEGER             :: ci, cj

    FORALL ( ci=1:SIZE(first,1), cj=1:SIZE(first,2) )
       my_dot_product3x3(ci,cj) = DOT_PRODUCT( first(ci,cj,:), second(ci,cj,:) )
    END FORALL
  END FUNCTION my_dot_product3x3

  ! Dot_product definition for two arrays (4d x 4d) with common size of all dimensions,
  ! The scalar product is evaluated over the last index
  PURE FUNCTION my_dot_product4x4(first, second)
    IMPLICIT NONE
    COMPLEX, INTENT(IN) :: first(:,:,:,:)
    REAL,    INTENT(IN) :: second( SIZE(first,1), SIZE(first,2), SIZE(first,3), SIZE(first,4) )
    COMPLEX             :: my_dot_product4x4( SIZE(first,1), SIZE(first,2), SIZE(first,3) )
    INTEGER             :: ci, cj, ck

    FORALL ( ci=1:SIZE(first,1), cj=1:SIZE(first,2), ck=1:SIZE(first,3) )
       my_dot_product4x4(ci,cj,ck) = DOT_PRODUCT( first(ci,cj,ck,:), second(ci,cj,ck,:) )
    END FORALL
  END FUNCTION my_dot_product4x4

  ! Sum over last index of 4d array
  PURE FUNCTION my_sum3d(array)
    IMPLICIT NONE
    COMPLEX, INTENT(IN) :: array(:,:,:)
    COMPLEX             :: my_sum3d( SIZE(array,1), SIZE(array,2) )
    INTEGER             :: ci, cj

    FORALL ( ci=1:SIZE(array,1), cj=1:SIZE(array,2) )
       my_sum3d(ci,cj) = SUM( array(ci,cj,:) )
    END FORALL
  END FUNCTION my_sum3d

  ! Sum over last index of 4d array
  PURE FUNCTION my_sum4d(array)
    IMPLICIT NONE
    COMPLEX, INTENT(IN) :: array(:,:,:,:)
    COMPLEX             :: my_sum4d( SIZE(array,1), SIZE(array,2), SIZE(array,3) )
    INTEGER             :: ci, cj, ck

    FORALL ( ci=1:SIZE(array,1), cj=1:SIZE(array,2), ck=1:SIZE(array,3) )
       my_sum4d(ci,cj,ck) = SUM( array(ci,cj,ck,:) )
    END FORALL
  END FUNCTION my_sum4d

  ! Sum product of three vectors
  COMPLEX PURE FUNCTION crc_gPtsSummation(noGpts, vec1, vec2, vec3)
    IMPLICIT NONE
    INTEGER, INTENT(IN) :: noGPts
    COMPLEX, INTENT(IN) :: vec1(noGPts)
    REAL, INTENT(IN)    :: vec2(noGPts)
    COMPLEX, INTENT(IN) :: vec3(noGPts)
    COMPLEX             :: temp(noGPts)
    temp          = vec1 * vec3
    crc_gPtsSummation = DOT_PRODUCT(temp,vec2)
  END FUNCTION crc_gPtsSummation
  REAL PURE FUNCTION rrr_gPtsSummation(noGpts, vec1, vec2, vec3)
    IMPLICIT NONE
    INTEGER, INTENT(IN) :: noGPts
    REAL, INTENT(IN)    :: vec1(noGPts)
    REAL, INTENT(IN)    :: vec2(noGPts)
    REAL, INTENT(IN)    :: vec3(noGPts)
    REAL                :: temp(noGPts)
    temp          = vec1 * vec3
    rrr_gPtsSummation = DOT_PRODUCT(temp,vec2)
  END FUNCTION rrr_gPtsSummation

  ! Include the core valence exchange for the HSE functional
  ! The HSE potential is the Coulomb one attenuated with the complementary
  ! error function which can be expanded in Legendre polynomials (r' > r)
  !
  !                      -----                l+2n
  ! erfc( w |r - r'| )    \                  r           /         \
  ! ------------------ =   )    d  (w r')  ---------  P ( cos(r,r') )
  !    | r - r' |         /      ln          l+2n+1    l \         /
  !                      -----              r'
  !                       l,n
  !
  ! Then an analytical integration of the angular part of the exchange
  ! potential is possible and only the radial part remains
  !
  !          R                        r                              R
  !           /   -----  /  d (w r)    /                              /           d  (w r')  \
  !  4 Pi    |     \    |    ln       |            l+2n+2      l+2n  |             ln         |
  ! -------  | dr   )   |  ---------  | dr' f(r') r'       +  r      | dr' f(r') -----------  |
  ! 2 l + 1  |     /    |    l+2n+1   |                              |              l+2n-1    |
  !         /     -----  \  r        /                              /              r'        /
  !          0      n                 0                              r
  !
  ! The function f is a product of core and valence function
  ! (note: in the code f is defined with an additional 1/r factor)
  !
  SUBROUTINE exchange_vccvHSE(nk,bkpt,nkptd,nkpt,nkpti,ntype,neq,natd, &
                              lmax,lmaxd,nindx,maxindx,lmaxc,nindxc,   &
                              maxindxc,core1,core2,lcutm,maxlmindx,    &
                              bas1,bas2,jmtd,rmsh,dx,jri,jspd,jsp,     &
                              maxfac,fac,sfac,nv,neigd,nbasfcn,nbands, &
                              gridf,nsymop,nsest,indx_sest,irank,      &
                              a_ex,nobd,w_iks,                         &
                              mat_ex,te_hfex_core)

    USE m_constants
    USE m_util
    USE m_wrapper

    IMPLICIT NONE

!   -scalars -
    INTEGER,INTENT(IN)      ::  ntype,jmtd,lmaxd,jspd,jsp,neigd
    INTEGER,INTENT(IN)      ::  maxfac,nbands,maxlmindx,natd,&
                                maxindxc,nk,maxindx,nbasfcn
    INTEGER,INTENT(IN)      ::  nkptd,nkpt,nkpti,irank
    INTEGER,INTENT(IN)      ::  nsymop
    REAL,   INTENT(IN)      ::  a_ex
    REAL,   INTENT(INOUT)   ::  te_hfex_core
    
!   - arrays -
    INTEGER,INTENT(IN)      ::  neq(ntype),lcutm(ntype),lmax(ntype),&
                                lmaxc(ntype),jri(ntype),nv(jspd),&
                                nindxc(0:MAXVAL(lmaxc),ntype),&
                                nindx(0:lmaxd,ntype)
    INTEGER,INTENT(IN)      ::  nsest(nbands),indx_sest(nbands,nbands)
    INTEGER,INTENT(IN)      ::  nobd(nkpt)
    REAL,INTENT(IN)         ::  rmsh(jmtd,ntype),dx(ntype)
    REAL,INTENT(IN)         ::  bas1(jmtd,maxindx,0:lmaxd,ntype),&
                                bas2(jmtd,maxindx,0:lmaxd,ntype)
    REAL,INTENT(IN)         ::  core1(jmtd,maxindxc,0:MAXVAL(lmaxc),ntype),&
                                core2(jmtd,maxindxc,0:MAXVAL(lmaxc),ntype)
    REAL,INTENT(IN)         ::  fac( 0:maxfac),sfac( 0:maxfac)
    REAL,INTENT(IN)         ::  bkpt(3)
    REAL,INTENT(IN)         ::  gridf(jmtd,ntype)
    REAL,INTENT(IN)         ::  w_iks(neigd,nkptd,jspd)

#ifdef CPP_INVERSION
    REAL    ,INTENT(INOUT)  ::  mat_ex(nbasfcn*(nbasfcn+1)/2)
#else
    COMPLEX ,INTENT(INOUT)  ::  mat_ex(nbasfcn*(nbasfcn+1)/2)
#endif
    INTEGER, PARAMETER      ::  ncut = 5                  ! cut-off value of n-summation
    INTEGER                 ::  cn                        ! counter for n-summation
    REAL                    ::  d_ln(jmtd,0:lmaxd,0:ncut) ! expansion coefficients of erfc(wr)/r 
                                                          ! in Legendre polynomials


!   - local scalars - 
    INTEGER                 ::  iatom,ieq,itype,ic,l,l1,l2,&
                                ll,lm,m,m1,m2,p1,p2,n,n1,n2,nn2,i,j
    INTEGER                 ::  iband1,iband2,ndb1,ndb2,ic1,ic2
    INTEGER                 ::  irecl_cmt

    REAL                    ::  rdum
    REAL                    ::  sum_offdia

    COMPLEX                 ::  cdum
!   - local arrays -
    INTEGER,ALLOCATABLE     ::  larr(:),larr2(:)
    INTEGER,ALLOCATABLE     ::  parr(:),parr2(:)

    REAL                    ::  sum_primf(jmtd), integrand(jmtd)
    REAL                    ::  primf1(jmtd),primf2(jmtd)
    REAL,ALLOCATABLE        ::  fprod(:,:),fprod2(:,:)
    REAL,ALLOCATABLE        ::  integral(:,:)

    COMPLEX                 ::  cmt(neigd,maxlmindx,natd)
    COMPLEX                 ::  exchange(nbands,nbands)
    COMPLEX,ALLOCATABLE     ::  carr(:,:),carr2(:,:),carr3(:,:)

    LOGICAL                 ::  ldum(nbands,nbands)


    ! check if a_ex is consistent
!     IF ( a_ex /= aMix_HSE ) STOP 'hsefunctional: inconsistent mixing!'

    ! read in mt wavefunction coefficients from file cmt
    irecl_cmt = neigd*maxlmindx*natd*16
    OPEN(unit=777,file='cmt',form='unformatted',access='direct',recl=irecl_cmt)
    READ(777,rec=nk) cmt(:,:,:)