LCOV - code coverage report
Current view: top level - src/common - mathlib.F (source / functions) Coverage Total Hit
Test: CP2K Regtests (git:1be8651) Lines: 76.0 % 767 583
Test Date: 2026-11-24 01:22:08 Functions: 91.7 % 48 44

            Line data    Source code
       1              : !--------------------------------------------------------------------------------------------------!
       2              : !   CP2K: A general program to perform molecular dynamics simulations                              !
       3              : !   Copyright 2000-2026 CP2K developers group <https://cp2k.org>                                   !
       4              : !                                                                                                  !
       5              : !   SPDX-License-Identifier: GPL-2.0-or-later                                                      !
       6              : !--------------------------------------------------------------------------------------------------!
       7              : 
       8              : ! **************************************************************************************************
       9              : !> \brief Collection of simple mathematical functions and subroutines
      10              : !> \par History
      11              : !>      FUNCTION angle updated and FUNCTION dihedral angle added; cleaned
      12              : !>      (13.03.2004,MK)
      13              : !> \author MK (15.11.1998)
      14              : ! **************************************************************************************************
      15              : MODULE mathlib
      16              : 
      17              :    USE kinds, ONLY: default_string_length, &
      18              :                     dp
      19              :    USE mathconstants, ONLY: euler, &
      20              :                             fac, &
      21              :                             oorootpi, &
      22              :                             pi, &
      23              :                             z_one, &
      24              :                             z_zero
      25              : #include "../base/base_uses.f90"
      26              :    #:include 'expint.fypp'
      27              : 
      28              :    IMPLICIT NONE
      29              :    PRIVATE
      30              : 
      31              :    CHARACTER(len=*), PARAMETER, PRIVATE :: moduleN = 'mathlib'
      32              :    REAL(KIND=dp), PARAMETER             :: eps_geo = 1.0E-6_dp
      33              : 
      34              :    ! Public subroutines
      35              : 
      36              :    PUBLIC :: build_rotmat, &
      37              :              jacobi, &
      38              :              diamat_all, &
      39              :              invmat, &
      40              :              invmat_symm, &
      41              :              invert_matrix, &
      42              :              get_pseudo_inverse_svd, &
      43              :              get_pseudo_inverse_diag, &
      44              :              symmetrize_matrix, &
      45              :              unit_matrix, diag, &
      46              :              erfc_cutoff, &
      47              :              diag_antisym, &
      48              :              diag_complex, &
      49              :              gemm_square, &
      50              :              geeig_right, &
      51              :              gauss_legendre
      52              : 
      53              :    ! Public functions
      54              : 
      55              :    PUBLIC :: angle, &
      56              :              binomial, &
      57              :              binomial_gen, &
      58              :              multinomial, &
      59              :              det_3x3, &
      60              :              dihedral_angle, &
      61              :              digamma, &
      62              :              gcd, &
      63              :              inv_3x3, &
      64              :              lcm, &
      65              :              vector_product, &
      66              :              pswitch, &
      67              :              rotate_vector, &
      68              :              reflect_vector, &
      69              :              expint, abnormal_value, &
      70              :              get_diag, &
      71              :              set_diag
      72              : 
      73              :    INTERFACE det_3x3
      74              :       MODULE PROCEDURE det_3x3_1, det_3x3_2
      75              :    END INTERFACE
      76              : 
      77              :    INTERFACE invert_matrix
      78              :       MODULE PROCEDURE invert_matrix_d, invert_matrix_z
      79              :    END INTERFACE
      80              : 
      81              :    INTERFACE set_diag
      82              :       MODULE PROCEDURE set_diag_scalar_d, set_diag_scalar_z
      83              :    END INTERFACE
      84              : 
      85              :    INTERFACE swap
      86              :       MODULE PROCEDURE swap_scalar, swap_vector
      87              :    END INTERFACE
      88              : 
      89              :    INTERFACE unit_matrix
      90              :       MODULE PROCEDURE unit_matrix_d, unit_matrix_z
      91              :    END INTERFACE
      92              : 
      93              :    INTERFACE gemm_square
      94              :       MODULE PROCEDURE zgemm_square_2, zgemm_square_3, dgemm_square_2, dgemm_square_3
      95              :    END INTERFACE
      96              : 
      97              : CONTAINS
      98              : 
      99              : ! **************************************************************************************************
     100              : !> \brief Polynomial (5th degree) switching function
     101              : !>        f(a) = 1 .... f(b) = 0 with f'(a) = f"(a) = f'(b) = f"(b) = 0
     102              : !> \param x ...
     103              : !> \param a ...
     104              : !> \param b ...
     105              : !> \param order ...
     106              : !> \return =0 : f(x)
     107              : !> \return =1 : f'(x)
     108              : !> \return =2 : f"(x)
     109              : ! **************************************************************************************************
     110        29870 :    FUNCTION pswitch(x, a, b, order) RESULT(fx)
     111              :       REAL(KIND=dp)                                      :: x, a, b
     112              :       INTEGER                                            :: order
     113              :       REAL(KIND=dp)                                      :: fx
     114              : 
     115              :       REAL(KIND=dp)                                      :: u, u2, u3
     116              : 
     117        29870 :       CPASSERT(b > a)
     118        29870 :       IF (x < a .OR. x > b) THEN
     119              :          ! outside switching intervall
     120        27934 :          IF (order > 0) THEN
     121              :             ! derivatives are 0
     122              :             fx = 0.0_dp
     123              :          ELSE
     124        13967 :             IF (x < a) THEN
     125              :                ! x < a => f(x) = 1
     126              :                fx = 1.0_dp
     127              :             ELSE
     128              :                ! x > b => f(x) = 0
     129        13640 :                fx = 0.0_dp
     130              :             END IF
     131              :          END IF
     132              :       ELSE
     133              :          ! renormalized coordinate
     134         1936 :          u = (x - a)/(b - a)
     135         2904 :          SELECT CASE (order)
     136              :          CASE (0)
     137          968 :             u2 = u*u
     138          968 :             u3 = u2*u
     139          968 :             fx = 1._dp - 10._dp*u3 + 15._dp*u2*u2 - 6._dp*u2*u3
     140              :          CASE (1)
     141          968 :             u2 = u*u
     142          968 :             fx = -30._dp*u2 + 60._dp*u*u2 - 30._dp*u2*u2
     143          968 :             fx = fx/(b - a)
     144              :          CASE (2)
     145            0 :             u2 = u*u
     146            0 :             fx = -60._dp*u + 180._dp*u2 - 120._dp*u*u2
     147            0 :             fx = fx/(b - a)**2
     148              :          CASE DEFAULT
     149         1936 :             CPABORT('order not defined')
     150              :          END SELECT
     151              :       END IF
     152              : 
     153        29870 :    END FUNCTION pswitch
     154              : 
     155              : ! **************************************************************************************************
     156              : !> \brief determines if a value is not normal (e.g. for Inf and Nan)
     157              : !>        based on IO to work also under optimization.
     158              : !> \param a input value
     159              : !> \return TRUE for NaN and Inf
     160              : ! **************************************************************************************************
     161      4080088 :    LOGICAL FUNCTION abnormal_value(a)
     162              :       REAL(KIND=dp)                                      :: a
     163              : 
     164              :       CHARACTER(LEN=32)                                  :: buffer
     165              : 
     166      4080088 :       abnormal_value = .FALSE.
     167              :       ! the function should work when compiled with -ffast-math and similar
     168              :       ! unfortunately, that option asserts that all numbers are normals,
     169              :       ! which the compiler uses to optimize the function to .FALSE. if based on the IEEE module
     170              :       ! therefore, pass this to the Fortran runtime/printf, if things are NaN or Inf, error out.
     171      4080088 :       WRITE (buffer, *) a
     172      4080088 :       IF (INDEX(buffer, "N") /= 0 .OR. INDEX(buffer, "n") /= 0) abnormal_value = .TRUE.
     173              : 
     174      4080088 :    END FUNCTION abnormal_value
     175              : 
     176              : ! **************************************************************************************************
     177              : !> \brief  Calculation of the angle between the vectors a and b.
     178              : !>         The angle is returned in radians.
     179              : !> \param a ...
     180              : !> \param b ...
     181              : !> \return ...
     182              : !> \date    14.10.1998
     183              : !> \author  MK
     184              : !> \version 1.0
     185              : ! **************************************************************************************************
     186       760171 :    PURE FUNCTION angle(a, b) RESULT(angle_ab)
     187              :       REAL(KIND=dp), DIMENSION(:), INTENT(IN)            :: a, b
     188              :       REAL(KIND=dp)                                      :: angle_ab
     189              : 
     190              :       REAL(KIND=dp)                                      :: length_of_a, length_of_b
     191       760171 :       REAL(KIND=dp), DIMENSION(SIZE(a, 1))               :: a_norm, b_norm
     192              : 
     193      3040684 :       length_of_a = NORM2(a)
     194      3040684 :       length_of_b = NORM2(b)
     195              : 
     196       760171 :       IF ((length_of_a > eps_geo) .AND. (length_of_b > eps_geo)) THEN
     197      3040684 :          a_norm(:) = a(:)/length_of_a
     198      3040684 :          b_norm(:) = b(:)/length_of_b
     199      3040684 :          angle_ab = ACOS(MIN(MAX(DOT_PRODUCT(a_norm, b_norm), -1.0_dp), 1.0_dp))
     200              :       ELSE
     201              :          angle_ab = 0.0_dp
     202              :       END IF
     203              : 
     204       760171 :    END FUNCTION angle
     205              : 
     206              : ! **************************************************************************************************
     207              : !> \brief   The binomial coefficient n over k for 0 <= k <= n is calculated,
     208              : !>            otherwise zero is returned.
     209              : !> \param n ...
     210              : !> \param k ...
     211              : !> \return ...
     212              : !> \date    08.03.1999
     213              : !> \author  MK
     214              : !> \version 1.0
     215              : ! **************************************************************************************************
     216    566057436 :    ELEMENTAL FUNCTION binomial(n, k) RESULT(n_over_k)
     217              :       INTEGER, INTENT(IN)                                :: n, k
     218              :       REAL(KIND=dp)                                      :: n_over_k
     219              : 
     220    566057436 :       IF ((k >= 0) .AND. (k <= n)) THEN
     221    562659952 :          n_over_k = fac(n)/(fac(n - k)*fac(k))
     222              :       ELSE
     223              :          n_over_k = 0.0_dp
     224              :       END IF
     225              : 
     226    566057436 :    END FUNCTION binomial
     227              : 
     228              : ! **************************************************************************************************
     229              : !> \brief   The generalized binomial coefficient z over k for 0 <= k <= n is calculated.
     230              : !>            (z)   z*(z-1)*...*(z-k+2)*(z-k+1)
     231              : !>            ( ) = ---------------------------
     232              : !>            (k)                 k!
     233              : !> \param z ...
     234              : !> \param k ...
     235              : !> \return ...
     236              : !> \date    11.11.2019
     237              : !> \author  FS
     238              : !> \version 1.0
     239              : ! **************************************************************************************************
     240     22050700 :    ELEMENTAL FUNCTION binomial_gen(z, k) RESULT(z_over_k)
     241              :       REAL(KIND=dp), INTENT(IN)                          :: z
     242              :       INTEGER, INTENT(IN)                                :: k
     243              :       REAL(KIND=dp)                                      :: z_over_k
     244              : 
     245              :       INTEGER                                            :: i
     246              : 
     247     22050700 :       IF (k >= 0) THEN
     248              :          z_over_k = 1.0_dp
     249     35691497 :          DO i = 1, k
     250     35691497 :             z_over_k = z_over_k*(z - i + 1)/REAL(i, dp)
     251              :          END DO
     252              :       ELSE
     253              :          z_over_k = 0.0_dp
     254              :       END IF
     255              : 
     256     22050700 :    END FUNCTION binomial_gen
     257              : 
     258              : ! **************************************************************************************************
     259              : !> \brief Calculates the multinomial coefficients
     260              : !> \param n ...
     261              : !> \param k ...
     262              : !> \return ...
     263              : !> \author Ole Schuett
     264              : ! **************************************************************************************************
     265         6150 :    PURE FUNCTION multinomial(n, k) RESULT(res)
     266              :       INTEGER, INTENT(IN)                                :: n
     267              :       INTEGER, DIMENSION(:), INTENT(IN)                  :: k
     268              :       REAL(KIND=dp)                                      :: res
     269              : 
     270              :       INTEGER                                            :: i
     271              :       REAL(KIND=dp)                                      :: denom
     272              : 
     273        49200 :       IF (ALL(k >= 0) .AND. SUM(k) == n) THEN
     274         3156 :          denom = 1.0_dp
     275        12624 :          DO i = 1, SIZE(k)
     276        12624 :             denom = denom*fac(k(i))
     277              :          END DO
     278         3156 :          res = fac(n)/denom
     279              :       ELSE
     280              :          res = 0.0_dp
     281              :       END IF
     282              : 
     283         6150 :    END FUNCTION multinomial
     284              : 
     285              : ! **************************************************************************************************
     286              : !> \brief   The rotation matrix rotmat which rotates a vector about a
     287              : !>          rotation axis defined by the vector a is build up.
     288              : !>          The rotation angle is phi (radians).
     289              : !> \param phi ...
     290              : !> \param a ...
     291              : !> \param rotmat ...
     292              : !> \date    16.10.1998
     293              : !> \author  MK
     294              : !> \version 1.0
     295              : ! **************************************************************************************************
     296        15761 :    PURE SUBROUTINE build_rotmat(phi, a, rotmat)
     297              :       REAL(KIND=dp), INTENT(IN)                          :: phi
     298              :       REAL(KIND=dp), DIMENSION(3), INTENT(IN)            :: a
     299              :       REAL(KIND=dp), DIMENSION(3, 3), INTENT(OUT)        :: rotmat
     300              : 
     301              :       REAL(KIND=dp)                                      :: cosp, cost, length_of_a, sinp
     302              :       REAL(KIND=dp), DIMENSION(3)                        :: d
     303              : 
     304        15761 :       length_of_a = SQRT(a(1)*a(1) + a(2)*a(2) + a(3)*a(3))
     305              :       ! Check the length of the vector a
     306        15761 :       IF (length_of_a > eps_geo) THEN
     307              : 
     308        63044 :          d(:) = a(:)/length_of_a
     309              : 
     310        15761 :          cosp = COS(phi)
     311        15761 :          sinp = SIN(phi)
     312        15761 :          cost = 1.0_dp - cosp
     313              : 
     314        15761 :          rotmat(1, 1) = d(1)*d(1)*cost + cosp
     315        15761 :          rotmat(1, 2) = d(1)*d(2)*cost - d(3)*sinp
     316        15761 :          rotmat(1, 3) = d(1)*d(3)*cost + d(2)*sinp
     317        15761 :          rotmat(2, 1) = d(2)*d(1)*cost + d(3)*sinp
     318        15761 :          rotmat(2, 2) = d(2)*d(2)*cost + cosp
     319        15761 :          rotmat(2, 3) = d(2)*d(3)*cost - d(1)*sinp
     320        15761 :          rotmat(3, 1) = d(3)*d(1)*cost - d(2)*sinp
     321        15761 :          rotmat(3, 2) = d(3)*d(2)*cost + d(1)*sinp
     322        15761 :          rotmat(3, 3) = d(3)*d(3)*cost + cosp
     323              :       ELSE
     324            0 :          CALL unit_matrix(rotmat)
     325              :       END IF
     326              : 
     327        15761 :    END SUBROUTINE build_rotmat
     328              : 
     329              : ! **************************************************************************************************
     330              : !> \brief   Returns the determinante of the 3x3 matrix a.
     331              : !> \param a ...
     332              : !> \return ...
     333              : !> \date    13.03.2004
     334              : !> \author  MK
     335              : !> \version 1.0
     336              : ! **************************************************************************************************
     337     16608932 :    PURE FUNCTION det_3x3_1(a) RESULT(det_a)
     338              :       REAL(KIND=dp), DIMENSION(3, 3), INTENT(IN)         :: a
     339              :       REAL(KIND=dp)                                      :: det_a
     340              : 
     341              :       det_a = a(1, 1)*(a(2, 2)*a(3, 3) - a(2, 3)*a(3, 2)) + &
     342              :               a(1, 2)*(a(2, 3)*a(3, 1) - a(2, 1)*a(3, 3)) + &
     343     16608932 :               a(1, 3)*(a(2, 1)*a(3, 2) - a(2, 2)*a(3, 1))
     344              : 
     345     16608932 :    END FUNCTION det_3x3_1
     346              : 
     347              : ! **************************************************************************************************
     348              : !> \brief   Returns the determinante of the 3x3 matrix a given by its columns.
     349              : !> \param a1 ...
     350              : !> \param a2 ...
     351              : !> \param a3 ...
     352              : !> \return ...
     353              : !> \date    13.03.2004
     354              : !> \author  MK
     355              : !> \version 1.0
     356              : ! **************************************************************************************************
     357         5962 :    PURE FUNCTION det_3x3_2(a1, a2, a3) RESULT(det_a)
     358              :       REAL(KIND=dp), DIMENSION(3), INTENT(IN)            :: a1, a2, a3
     359              :       REAL(KIND=dp)                                      :: det_a
     360              : 
     361              :       det_a = a1(1)*(a2(2)*a3(3) - a3(2)*a2(3)) + &
     362              :               a2(1)*(a3(2)*a1(3) - a1(2)*a3(3)) + &
     363         5962 :               a3(1)*(a1(2)*a2(3) - a2(2)*a1(3))
     364              : 
     365         5962 :    END FUNCTION det_3x3_2
     366              : 
     367              : ! **************************************************************************************************
     368              : !> \brief Diagonalize the symmetric n by n matrix a using the LAPACK
     369              : !>        library. Only the upper triangle of matrix a is used.
     370              : !>        Externals (LAPACK 3.0)
     371              : !> \param a ...
     372              : !> \param eigval ...
     373              : !> \param dac ...
     374              : !> \date    29.03.1999
     375              : !> \par Variables
     376              : !>      - a       : Symmetric matrix to be diagonalized (input; upper triangle) ->
     377              : !>      -           eigenvectors of the matrix a (output).
     378              : !>      - dac     : If true, then the divide-and-conquer algorithm is applied.
     379              : !>      - eigval  : Eigenvalues of the matrix a (output).
     380              : !> \author  MK
     381              : !> \version 1.0
     382              : ! **************************************************************************************************
     383        78748 :    SUBROUTINE diamat_all(a, eigval, dac)
     384              :       REAL(KIND=dp), DIMENSION(:, :), INTENT(INOUT)      :: a
     385              :       REAL(KIND=dp), DIMENSION(:), INTENT(OUT)           :: eigval
     386              :       LOGICAL, INTENT(IN), OPTIONAL                      :: dac
     387              : 
     388              :       CHARACTER(len=*), PARAMETER                        :: routineN = 'diamat_all'
     389              : 
     390              :       INTEGER                                            :: handle, info, liwork, lwork, n, nb
     391        78748 :       INTEGER, ALLOCATABLE, DIMENSION(:)                 :: iwork
     392              :       INTEGER, EXTERNAL                                  :: ilaenv
     393              :       LOGICAL                                            :: divide_and_conquer
     394        78748 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:)           :: work
     395              : 
     396              :       EXTERNAL dsyev, dsyevd
     397              : 
     398        78748 :       CALL timeset(routineN, handle)
     399              : 
     400              :       ! Get the size of the matrix a
     401        78748 :       n = SIZE(a, 1)
     402              : 
     403              :       ! Check the size of matrix a
     404        78748 :       IF (SIZE(a, 2) /= n) THEN
     405            0 :          CPABORT("Check the size of matrix a (parameter #1)")
     406              :       END IF
     407              : 
     408              :       ! Check the size of vector eigval
     409        78748 :       IF (SIZE(eigval) /= n) THEN
     410            0 :          CPABORT("The dimension of vector eigval is too small")
     411              :       END IF
     412              : 
     413              :       ! Check, if the divide-and-conquer algorithm is requested
     414              : 
     415        78748 :       IF (PRESENT(dac)) THEN
     416          309 :          divide_and_conquer = dac
     417              :       ELSE
     418              :          divide_and_conquer = .FALSE.
     419              :       END IF
     420              : 
     421              :       ! Get the optimal work storage size
     422              : 
     423          309 :       IF (divide_and_conquer) THEN
     424          309 :          lwork = 2*n**2 + 6*n + 1
     425          309 :          liwork = 5*n + 3
     426              :       ELSE
     427        78439 :          nb = ilaenv(1, "DSYTRD", "U", n, -1, -1, -1)
     428        78439 :          lwork = (nb + 2)*n
     429              :       END IF
     430              : 
     431              :       ! Allocate work storage
     432              : 
     433       236244 :       ALLOCATE (work(lwork))
     434        78748 :       IF (divide_and_conquer) THEN
     435          927 :          ALLOCATE (iwork(liwork))
     436              :       END IF
     437              : 
     438              :       ! Diagonalize the matrix a
     439              : 
     440        78748 :       info = 0
     441              :       IF (divide_and_conquer) THEN
     442          309 :          CALL dsyevd("V", "U", n, a, n, eigval, work, lwork, iwork, liwork, info)
     443              :       ELSE
     444        80263 :          CALL dsyev("V", "U", n, a, n, eigval, work, lwork, info)
     445              :       END IF
     446              : 
     447        78748 :       IF (info /= 0) THEN
     448            0 :          IF (divide_and_conquer) THEN
     449            0 :             CPABORT("The matrix diagonalization with dsyevd failed")
     450              :          ELSE
     451            0 :             CPABORT("The matrix diagonalization with dsyev failed")
     452              :          END IF
     453              :       END IF
     454              : 
     455              :       ! Release work storage
     456        78748 :       DEALLOCATE (work)
     457              : 
     458        78748 :       IF (divide_and_conquer) THEN
     459          309 :          DEALLOCATE (iwork)
     460              :       END IF
     461              : 
     462        78748 :       CALL timestop(handle)
     463              : 
     464       157496 :    END SUBROUTINE diamat_all
     465              : 
     466              : ! **************************************************************************************************
     467              : !> \brief   Returns the dihedral angle, i.e. the angle between the planes
     468              : !>          defined by the vectors (-ab,bc) and (cd,-bc).
     469              : !>          The dihedral angle is returned in radians.
     470              : !> \param ab ...
     471              : !> \param bc ...
     472              : !> \param cd ...
     473              : !> \return ...
     474              : !> \date    13.03.2004
     475              : !> \author  MK
     476              : !> \version 1.0
     477              : ! **************************************************************************************************
     478          117 :    PURE FUNCTION dihedral_angle(ab, bc, cd) RESULT(dihedral_angle_abcd)
     479              :       REAL(KIND=dp), DIMENSION(3), INTENT(IN)            :: ab, bc, cd
     480              :       REAL(KIND=dp)                                      :: dihedral_angle_abcd
     481              : 
     482              :       REAL(KIND=dp)                                      :: det_abcd
     483              :       REAL(KIND=dp), DIMENSION(3)                        :: abc, bcd
     484              : 
     485          468 :       abc = vector_product(bc, -ab)
     486          468 :       bcd = vector_product(cd, -bc)
     487              :       ! Calculate the normal vectors of the planes
     488              :       ! defined by the points a,b,c and b,c,d
     489              : 
     490          468 :       det_abcd = det_3x3(abc, bcd, -bc)
     491          117 :       dihedral_angle_abcd = SIGN(1.0_dp, det_abcd)*angle(abc, bcd)
     492              : 
     493          117 :    END FUNCTION dihedral_angle
     494              : 
     495              : ! **************************************************************************************************
     496              : !> \brief   Return the diagonal elements of matrix a as a vector.
     497              : !> \param a ...
     498              : !> \return ...
     499              : !> \date    20.11.1998
     500              : !> \author  MK
     501              : !> \version 1.0
     502              : ! **************************************************************************************************
     503        63502 :    PURE FUNCTION get_diag(a) RESULT(a_diag)
     504              :       REAL(KIND=dp), DIMENSION(:, :), INTENT(IN)         :: a
     505              :       REAL(KIND=dp), &
     506              :          DIMENSION(MIN(SIZE(a, 1), SIZE(a, 2)))          :: a_diag
     507              : 
     508              :       INTEGER                                            :: i, n
     509              : 
     510        63502 :       n = MIN(SIZE(a, 1), SIZE(a, 2))
     511              : 
     512      6369514 :       DO i = 1, n
     513      6369514 :          a_diag(i) = a(i, i)
     514              :       END DO
     515              : 
     516        63502 :    END FUNCTION get_diag
     517              : 
     518              : ! **************************************************************************************************
     519              : !> \brief   Returns the inverse of the 3 x 3 matrix a.
     520              : !> \param a ...
     521              : !> \return ...
     522              : !> \date    13.03.2004
     523              : !> \author  MK
     524              : !> \version 1.0
     525              : ! **************************************************************************************************
     526     15792429 :    PURE FUNCTION inv_3x3(a) RESULT(a_inv)
     527              :       REAL(KIND=dp), DIMENSION(3, 3), INTENT(IN)         :: a
     528              :       REAL(KIND=dp), DIMENSION(3, 3)                     :: a_inv
     529              : 
     530              :       REAL(KIND=dp)                                      :: det_a
     531              : 
     532     15792429 :       det_a = 1.0_dp/det_3x3(a)
     533              : 
     534     15792429 :       a_inv(1, 1) = (a(2, 2)*a(3, 3) - a(3, 2)*a(2, 3))*det_a
     535     15792429 :       a_inv(2, 1) = (a(2, 3)*a(3, 1) - a(3, 3)*a(2, 1))*det_a
     536     15792429 :       a_inv(3, 1) = (a(2, 1)*a(3, 2) - a(3, 1)*a(2, 2))*det_a
     537              : 
     538     15792429 :       a_inv(1, 2) = (a(1, 3)*a(3, 2) - a(3, 3)*a(1, 2))*det_a
     539     15792429 :       a_inv(2, 2) = (a(1, 1)*a(3, 3) - a(3, 1)*a(1, 3))*det_a
     540     15792429 :       a_inv(3, 2) = (a(1, 2)*a(3, 1) - a(3, 2)*a(1, 1))*det_a
     541              : 
     542     15792429 :       a_inv(1, 3) = (a(1, 2)*a(2, 3) - a(2, 2)*a(1, 3))*det_a
     543     15792429 :       a_inv(2, 3) = (a(1, 3)*a(2, 1) - a(2, 3)*a(1, 1))*det_a
     544     15792429 :       a_inv(3, 3) = (a(1, 1)*a(2, 2) - a(2, 1)*a(1, 2))*det_a
     545              : 
     546     15792429 :    END FUNCTION inv_3x3
     547              : 
     548              : ! **************************************************************************************************
     549              : !> \brief returns inverse of matrix using the lapack routines DGETRF and DGETRI
     550              : !> \param a ...
     551              : !> \param info ...
     552              : ! **************************************************************************************************
     553         8401 :    SUBROUTINE invmat(a, info)
     554              :       REAL(KIND=dp), INTENT(INOUT)                       :: a(:, :)
     555              :       INTEGER, INTENT(OUT)                               :: info
     556              : 
     557              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'invmat'
     558              : 
     559              :       INTEGER                                            :: handle, lwork, n
     560         8401 :       INTEGER, ALLOCATABLE                               :: ipiv(:)
     561         8401 :       REAL(KIND=dp), ALLOCATABLE                         :: work(:)
     562              : 
     563         8401 :       CALL timeset(routineN, handle)
     564              : 
     565         8401 :       n = SIZE(a, 1)
     566         8401 :       lwork = 20*n
     567        25203 :       ALLOCATE (ipiv(n))
     568        25203 :       ALLOCATE (work(lwork))
     569         8401 :       ipiv = 0
     570         8401 :       work = 0._dp
     571         8401 :       info = 0
     572       480175 :       CALL dgetrf(n, n, a, n, ipiv, info)
     573         8401 :       IF (info == 0) THEN
     574       479171 :          CALL dgetri(n, a, n, ipiv, work, lwork, info)
     575              :       END IF
     576         8401 :       DEALLOCATE (ipiv, work)
     577              : 
     578         8401 :       CALL timestop(handle)
     579              : 
     580         8401 :    END SUBROUTINE invmat
     581              : 
     582              : ! **************************************************************************************************
     583              : !> \brief returns inverse of real symmetric, positive definite matrix
     584              : !> \param a matrix
     585              : !> \param potrf if cholesky decomposition of a was already done using dpotrf.
     586              : !>        If not given, cholesky decomposition of a will be done before inversion.
     587              : !> \param uplo indicating if the upper or lower triangle of a is stored.
     588              : !> \author Dorothea Golze [02.2015]
     589              : ! **************************************************************************************************
     590         3075 :    SUBROUTINE invmat_symm(a, potrf, uplo)
     591              :       REAL(KIND=dp), INTENT(INOUT)                       :: a(:, :)
     592              :       LOGICAL, INTENT(IN), OPTIONAL                      :: potrf
     593              :       CHARACTER(LEN=1), INTENT(IN), OPTIONAL             :: uplo
     594              : 
     595              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'invmat_symm'
     596              : 
     597              :       CHARACTER(LEN=1)                                   :: myuplo
     598              :       INTEGER                                            :: handle, info, n
     599              :       LOGICAL                                            :: do_potrf
     600              : 
     601         3075 :       CALL timeset(routineN, handle)
     602              : 
     603         3075 :       do_potrf = .TRUE.
     604         3075 :       IF (PRESENT(potrf)) do_potrf = potrf
     605              : 
     606         3075 :       myuplo = 'U'
     607         3075 :       IF (PRESENT(uplo)) myuplo = uplo
     608              : 
     609         3075 :       n = SIZE(a, 1)
     610         3075 :       info = 0
     611              : 
     612              :       ! do cholesky decomposition
     613         3075 :       IF (do_potrf) THEN
     614         4058 :          CALL dpotrf(myuplo, n, a, n, info)
     615         2858 :          IF (info /= 0) CPABORT("DPOTRF failed")
     616              :       END IF
     617              : 
     618              :       ! do inversion using the cholesky decomposition
     619         4275 :       CALL dpotri(myuplo, n, a, n, info)
     620         3075 :       IF (info /= 0) CPABORT("Matrix inversion failed")
     621              : 
     622              :       ! complete the matrix
     623         3075 :       IF ((myuplo == "U") .OR. (myuplo == "u")) THEN
     624         3075 :          CALL symmetrize_matrix(a, "upper_to_lower")
     625              :       ELSE
     626            0 :          CALL symmetrize_matrix(a, "lower_to_upper")
     627              :       END IF
     628              : 
     629         3075 :       CALL timestop(handle)
     630              : 
     631         3075 :    END SUBROUTINE invmat_symm
     632              : 
     633              : ! **************************************************************************************************
     634              : !> \brief  Compute the inverse of the n by n real matrix a using the LAPACK
     635              : !>         library
     636              : !> \param a ...
     637              : !> \param a_inverse ...
     638              : !> \param eval_error ...
     639              : !> \param option ...
     640              : !> \param improve ...
     641              : !> \date   23.03.1999
     642              : !> \par Variables
     643              : !>       - a        : Real matrix to be inverted (input).
     644              : !>       - a_inverse: Inverse of the matrix a (output).
     645              : !>       - a_lu     : LU factorization of matrix a.
     646              : !>       - a_norm   : Norm of matrix a.
     647              : !>       - error    : Estimated error of the inversion.
     648              : !>       - r_cond   : Reciprocal condition number of the matrix a.
     649              : !>       - trans    : "N" => invert a
     650              : !>       -            "T" => invert transpose(a)
     651              : !> \author MK
     652              : !> \version 1.0
     653              : !> \note NB add improve argument, used to disable call to dgerfs
     654              : ! **************************************************************************************************
     655        12066 :    SUBROUTINE invert_matrix_d(a, a_inverse, eval_error, option, improve)
     656              :       REAL(KIND=dp), DIMENSION(:, :), INTENT(IN)         :: a
     657              :       REAL(KIND=dp), DIMENSION(:, :), INTENT(OUT)        :: a_inverse
     658              :       REAL(KIND=dp), INTENT(OUT)                         :: eval_error
     659              :       CHARACTER(LEN=1), INTENT(IN), OPTIONAL             :: option
     660              :       LOGICAL, INTENT(IN), OPTIONAL                      :: improve
     661              : 
     662              :       CHARACTER(LEN=1)                                   :: norm, trans
     663              :       CHARACTER(LEN=default_string_length)               :: message
     664              :       INTEGER                                            :: info, iter, n
     665        12066 :       INTEGER, ALLOCATABLE, DIMENSION(:)                 :: ipiv, iwork
     666              :       LOGICAL                                            :: do_improve
     667              :       REAL(KIND=dp)                                      :: a_norm, old_eval_error, r_cond
     668        12066 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:)           :: berr, ferr, work
     669        12066 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :)        :: a_lu, b
     670              :       REAL(KIND=dp), EXTERNAL                            :: dlange
     671              : 
     672              :       EXTERNAL dgecon, dgerfs, dgetrf, dgetrs
     673              : 
     674              :       ! Check for optional parameter
     675        12066 :       IF (PRESENT(option)) THEN
     676          582 :          trans = option
     677              :       ELSE
     678        11484 :          trans = "N"
     679              :       END IF
     680              : 
     681        12066 :       IF (PRESENT(improve)) THEN
     682         1106 :          do_improve = improve
     683              :       ELSE
     684              :          do_improve = .TRUE.
     685              :       END IF
     686              : 
     687              :       ! Get the dimension of matrix a
     688        12066 :       n = SIZE(a, 1)
     689              : 
     690              :       ! Check array dimensions
     691        12066 :       IF (n == 0) THEN
     692            0 :          CPABORT("Matrix to be inverted of zero size")
     693              :       END IF
     694              : 
     695        12066 :       IF (n /= SIZE(a, 2)) THEN
     696            0 :          CPABORT("Check the array bounds of parameter #1")
     697              :       END IF
     698              : 
     699        12066 :       IF ((n /= SIZE(a_inverse, 1)) .OR. &
     700              :           (n /= SIZE(a_inverse, 2))) THEN
     701            0 :          CPABORT("Check the array bounds of parameter #2")
     702              :       END IF
     703              : 
     704              :       ! Allocate work storage
     705        48264 :       ALLOCATE (a_lu(n, n))
     706        36198 :       ALLOCATE (b(n, n))
     707        36198 :       ALLOCATE (berr(n))
     708        24132 :       ALLOCATE (ferr(n))
     709        36198 :       ALLOCATE (ipiv(n))
     710        24132 :       ALLOCATE (iwork(n))
     711        36198 :       ALLOCATE (work(4*n))
     712              : 
     713      2942906 :       a_lu(1:n, 1:n) = a(1:n, 1:n)
     714              : 
     715              :       ! Compute the LU factorization of the matrix a
     716        12066 :       CALL dgetrf(n, n, a_lu, n, ipiv, info)
     717              : 
     718        12066 :       IF (info /= 0) THEN
     719            0 :          CPABORT("The LU factorization in dgetrf failed")
     720              :       END IF
     721              : 
     722              :       ! Compute the norm of the matrix a
     723              : 
     724        12066 :       IF (trans == "N") THEN
     725        11788 :          norm = '1'
     726              :       ELSE
     727          278 :          norm = 'I'
     728              :       END IF
     729              : 
     730        12066 :       a_norm = dlange(norm, n, n, a, n, work)
     731              : 
     732              :       ! Compute the reciprocal of the condition number of a
     733              : 
     734        12066 :       CALL dgecon(norm, n, a_lu, n, a_norm, r_cond, work, iwork, info)
     735              : 
     736        12066 :       IF (info /= 0) THEN
     737            0 :          CPABORT("The computation of the condition number in dgecon failed")
     738              :       END IF
     739              : 
     740        12066 :       IF (r_cond < EPSILON(0.0_dp)) THEN
     741            0 :          WRITE (message, "(A,ES10.3)") "R_COND =", r_cond
     742              :          CALL cp_abort(__LOCATION__, &
     743              :                        "Bad condition number "//TRIM(message)//" (smaller than the machine "// &
     744            0 :                        "working precision)")
     745              :       END IF
     746              : 
     747              :       ! Solve a system of linear equations using the LU factorization computed by dgetrf
     748              : 
     749        12066 :       CALL unit_matrix(a_inverse)
     750              : 
     751        12066 :       CALL dgetrs(trans, n, n, a_lu, n, ipiv, a_inverse, n, info)
     752              : 
     753        12066 :       IF (info /= 0) THEN
     754            0 :          CPABORT("Solving the system of linear equations in dgetrs failed")
     755              :       END IF
     756              : 
     757              :       ! Improve the computed solution iteratively
     758        12066 :       CALL unit_matrix(b) ! Initialize right-hand sides
     759              : 
     760        12066 :       eval_error = 0.0_dp
     761              : 
     762        12066 :       IF (do_improve) THEN
     763        27504 :          DO iter = 1, 10
     764              : 
     765              :             CALL dgerfs(trans, n, n, a, n, a_lu, n, ipiv, b, n, a_inverse, n, ferr, berr, &
     766        27248 :                         work, iwork, info)
     767              : 
     768        27248 :             IF (info /= 0) THEN
     769            0 :                CPABORT("Improving the computed solution in dgerfs failed")
     770              :             END IF
     771              : 
     772        27248 :             old_eval_error = eval_error
     773       294408 :             eval_error = MAXVAL(ferr)
     774              : 
     775        27504 :             IF (ABS(eval_error - old_eval_error) <= EPSILON(1.0_dp)) EXIT
     776              : 
     777              :          END DO
     778              :       END IF
     779              : 
     780              :       ! Release work storage
     781        12066 :       DEALLOCATE (work)
     782        12066 :       DEALLOCATE (iwork)
     783        12066 :       DEALLOCATE (ipiv)
     784        12066 :       DEALLOCATE (ferr)
     785        12066 :       DEALLOCATE (berr)
     786        12066 :       DEALLOCATE (b)
     787        12066 :       DEALLOCATE (a_lu)
     788              : 
     789        12066 :    END SUBROUTINE invert_matrix_d
     790              : 
     791              : ! **************************************************************************************************
     792              : !> \brief  Compute the inverse of the n by n complex matrix a using the LAPACK
     793              : !>         library
     794              : !> \param a ...
     795              : !> \param a_inverse ...
     796              : !> \param eval_error ...
     797              : !> \param option ...
     798              : !> \date   08.06.2009
     799              : !> \par Variables
     800              : !>       - a        : Complex matrix to be inverted (input).
     801              : !>       - a_inverse: Inverse of the matrix a (output).
     802              : !>       - a_lu     : LU factorization of matrix a.
     803              : !>       - a_norm   : Norm of matrix a.
     804              : !>       - error    : Estimated error of the inversion.
     805              : !>       - r_cond   : Reciprocal condition number of the matrix a.
     806              : !>       - trans    : "N" => invert a
     807              : !>       -            "T" => invert transpose(a)
     808              : !> \author MK
     809              : !> \version 1.0
     810              : ! **************************************************************************************************
     811            0 :    SUBROUTINE invert_matrix_z(a, a_inverse, eval_error, option)
     812              :       COMPLEX(KIND=dp), DIMENSION(:, :), INTENT(IN)      :: a
     813              :       COMPLEX(KIND=dp), DIMENSION(:, :), INTENT(OUT)     :: a_inverse
     814              :       REAL(KIND=dp), INTENT(OUT)                         :: eval_error
     815              :       CHARACTER(LEN=1), INTENT(IN), OPTIONAL             :: option
     816              : 
     817              :       CHARACTER(LEN=1)                                   :: norm, trans
     818              :       CHARACTER(LEN=default_string_length)               :: message
     819            0 :       COMPLEX(KIND=dp), ALLOCATABLE, DIMENSION(:)        :: work
     820            0 :       COMPLEX(KIND=dp), ALLOCATABLE, DIMENSION(:, :)     :: a_lu, b
     821              :       INTEGER                                            :: info, iter, n
     822            0 :       INTEGER, ALLOCATABLE, DIMENSION(:)                 :: ipiv
     823              :       REAL(KIND=dp)                                      :: a_norm, old_eval_error, r_cond
     824            0 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:)           :: berr, ferr, rwork
     825              :       REAL(KIND=dp), EXTERNAL                            :: zlange
     826              : 
     827              :       EXTERNAL zgecon, zgerfs, zgetrf, zgetrs
     828              : 
     829              :       ! Check for optional parameter
     830            0 :       IF (PRESENT(option)) THEN
     831            0 :          trans = option
     832              :       ELSE
     833            0 :          trans = "N"
     834              :       END IF
     835              : 
     836              :       ! Get the dimension of matrix a
     837            0 :       n = SIZE(a, 1)
     838              : 
     839              :       ! Check array dimensions
     840            0 :       IF (n == 0) THEN
     841            0 :          CPABORT("Matrix to be inverted of zero size")
     842              :       END IF
     843              : 
     844            0 :       IF (n /= SIZE(a, 2)) THEN
     845            0 :          CPABORT("Check the array bounds of parameter #1")
     846              :       END IF
     847              : 
     848            0 :       IF ((n /= SIZE(a_inverse, 1)) .OR. &
     849              :           (n /= SIZE(a_inverse, 2))) THEN
     850            0 :          CPABORT("Check the array bounds of parameter #2")
     851              :       END IF
     852              : 
     853              :       ! Allocate work storage
     854            0 :       ALLOCATE (a_lu(n, n))
     855            0 :       ALLOCATE (b(n, n))
     856            0 :       ALLOCATE (berr(n))
     857            0 :       ALLOCATE (ferr(n))
     858            0 :       ALLOCATE (ipiv(n))
     859            0 :       ALLOCATE (rwork(2*n))
     860            0 :       ALLOCATE (work(2*n))
     861              : 
     862            0 :       a_lu(1:n, 1:n) = a(1:n, 1:n)
     863              : 
     864              :       ! Compute the LU factorization of the matrix a
     865            0 :       CALL zgetrf(n, n, a_lu, n, ipiv, info)
     866              : 
     867            0 :       IF (info /= 0) THEN
     868            0 :          CPABORT("The LU factorization in dgetrf failed")
     869              :       END IF
     870              : 
     871              :       ! Compute the norm of the matrix a
     872              : 
     873            0 :       IF (trans == "N") THEN
     874            0 :          norm = '1'
     875              :       ELSE
     876            0 :          norm = 'I'
     877              :       END IF
     878              : 
     879            0 :       a_norm = zlange(norm, n, n, a, n, work)
     880              : 
     881              :       ! Compute the reciprocal of the condition number of a
     882              : 
     883            0 :       CALL zgecon(norm, n, a_lu, n, a_norm, r_cond, work, rwork, info)
     884              : 
     885            0 :       IF (info /= 0) THEN
     886            0 :          CPABORT("The computation of the condition number in dgecon failed")
     887              :       END IF
     888              : 
     889            0 :       IF (r_cond < EPSILON(0.0_dp)) THEN
     890            0 :          WRITE (message, "(A,ES10.3)") "R_COND =", r_cond
     891              :          CALL cp_abort(__LOCATION__, &
     892              :                        "Bad condition number "//TRIM(message)//" (smaller than the machine "// &
     893            0 :                        "working precision)")
     894              :       END IF
     895              : 
     896              :       ! Solve a system of linear equations using the LU factorization computed by dgetrf
     897              : 
     898            0 :       CALL unit_matrix(a_inverse)
     899              : 
     900            0 :       CALL zgetrs(trans, n, n, a_lu, n, ipiv, a_inverse, n, info)
     901              : 
     902            0 :       IF (info /= 0) THEN
     903            0 :          CPABORT("Solving the system of linear equations in dgetrs failed")
     904              :       END IF
     905              : 
     906              :       ! Improve the computed solution iteratively
     907            0 :       CALL unit_matrix(b) ! Initialize right-hand sides
     908              : 
     909            0 :       eval_error = 0.0_dp
     910              : 
     911            0 :       DO iter = 1, 10
     912              : 
     913              :          CALL zgerfs(trans, n, n, a, n, a_lu, n, ipiv, b, n, a_inverse, n, ferr, berr, &
     914            0 :                      work, rwork, info)
     915              : 
     916            0 :          IF (info /= 0) THEN
     917            0 :             CPABORT("Improving the computed solution in dgerfs failed")
     918              :          END IF
     919              : 
     920            0 :          old_eval_error = eval_error
     921            0 :          eval_error = MAXVAL(ferr)
     922              : 
     923            0 :          IF (ABS(eval_error - old_eval_error) <= EPSILON(1.0_dp)) EXIT
     924              : 
     925              :       END DO
     926              : 
     927              :       ! Release work storage
     928            0 :       DEALLOCATE (work)
     929            0 :       DEALLOCATE (rwork)
     930            0 :       DEALLOCATE (ipiv)
     931            0 :       DEALLOCATE (ferr)
     932            0 :       DEALLOCATE (berr)
     933            0 :       DEALLOCATE (b)
     934            0 :       DEALLOCATE (a_lu)
     935              : 
     936            0 :    END SUBROUTINE invert_matrix_z
     937              : 
     938              : ! **************************************************************************************************
     939              : !> \brief returns the pseudoinverse of a real, square matrix using singular
     940              : !>         value decomposition
     941              : !> \param a matrix a
     942              : !> \param a_pinverse pseudoinverse of matrix a
     943              : !> \param rskip parameter for setting small singular values to zero
     944              : !> \param determinant determinant of matrix a (optional output)
     945              : !> \param sval array holding singular values of matrix a (optional output)
     946              : !> \author Dorothea Golze [02.2015]
     947              : ! **************************************************************************************************
     948         1497 :    SUBROUTINE get_pseudo_inverse_svd(a, a_pinverse, rskip, determinant, sval)
     949              :       REAL(KIND=dp), DIMENSION(:, :)                     :: a, a_pinverse
     950              :       REAL(KIND=dp), INTENT(IN)                          :: rskip
     951              :       REAL(KIND=dp), INTENT(OUT), OPTIONAL               :: determinant
     952              :       REAL(KIND=dp), DIMENSION(:), INTENT(INOUT), &
     953              :          OPTIONAL, POINTER                               :: sval
     954              : 
     955              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'get_pseudo_inverse_svd'
     956              : 
     957              :       INTEGER                                            :: handle, i, info, lwork, n
     958         1497 :       INTEGER, ALLOCATABLE, DIMENSION(:)                 :: iwork
     959         1497 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:)           :: sig, work
     960         1497 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :)        :: sig_plus, temp_mat, u, vt
     961              : 
     962         1497 :       CALL timeset(routineN, handle)
     963              : 
     964         1497 :       n = SIZE(a, 1)
     965        20958 :       ALLOCATE (u(n, n), vt(n, n), sig(n), sig_plus(n, n), iwork(8*n), work(1), temp_mat(n, n))
     966         1497 :       u(:, :) = 0.0_dp
     967         1497 :       vt(:, :) = 0.0_dp
     968         1497 :       sig(:) = 0.0_dp
     969         1497 :       sig_plus = 0.0_dp
     970         1497 :       work = 0.0_dp
     971         1497 :       iwork = 0
     972         1497 :       IF (PRESENT(determinant)) determinant = 1.0_dp
     973              : 
     974              :       ! work size query
     975         1497 :       lwork = -1
     976              :       CALL dgesdd('A', n, n, a(1, 1), n, sig(1), u(1, 1), n, vt(1, 1), n, work(1), &
     977         1497 :                   lwork, iwork(1), info)
     978              : 
     979         1497 :       IF (info /= 0) THEN
     980            0 :          CPABORT("ERROR in DGESDD: Could not retrieve work array sizes")
     981              :       END IF
     982         1497 :       lwork = INT(work(1))
     983         1497 :       DEALLOCATE (work)
     984         4491 :       ALLOCATE (work(lwork))
     985              : 
     986              :       ! do SVD
     987              :       CALL dgesdd('A', n, n, a(1, 1), n, sig(1), u(1, 1), n, vt(1, 1), n, work(1), &
     988         1497 :                   lwork, iwork(1), info)
     989              : 
     990         1497 :       IF (info /= 0) THEN
     991            0 :          CPABORT("SVD failed")
     992              :       END IF
     993              : 
     994         1497 :       IF (PRESENT(sval)) THEN
     995            0 :          CPASSERT(.NOT. ASSOCIATED(sval))
     996            0 :          ALLOCATE (sval(n))
     997            0 :          sval(:) = sig
     998              :       END IF
     999              : 
    1000              :       ! set singular values that are too small to zero
    1001         9503 :       DO i = 1, n
    1002        91945 :          IF (sig(i) > rskip*MAXVAL(sig)) THEN
    1003         7900 :             IF (PRESENT(determinant)) THEN
    1004            0 :                determinant = determinant*sig(i)
    1005              :             END IF
    1006         7900 :             sig_plus(i, i) = 1._dp/sig(i)
    1007              :          ELSE
    1008          106 :             sig_plus(i, i) = 0.0_dp
    1009              :          END IF
    1010              :       END DO
    1011              : 
    1012              :       ! build pseudoinverse: V*sig_plus*UT
    1013         1497 :       CALL dgemm("N", "T", n, n, n, 1._dp, sig_plus, n, u, n, 0._dp, temp_mat, n)
    1014         1497 :       CALL dgemm("T", "N", n, n, n, 1._dp, vt, n, temp_mat, n, 0._dp, a_pinverse, n)
    1015              : 
    1016         1497 :       DEALLOCATE (u, vt, sig, iwork, work, sig_plus, temp_mat)
    1017              : 
    1018         1497 :       CALL timestop(handle)
    1019              : 
    1020         1497 :    END SUBROUTINE get_pseudo_inverse_svd
    1021              : 
    1022              : ! **************************************************************************************************
    1023              : !> \brief returns the pseudoinverse of a real, symmetric and positive definite
    1024              : !>        matrix using diagonalization.
    1025              : !> \param a matrix a
    1026              : !> \param a_pinverse pseudoinverse of matrix a
    1027              : !> \param rskip parameter for setting small eigenvalues to zero
    1028              : !> \author Dorothea Golze [02.2015]
    1029              : ! **************************************************************************************************
    1030         2339 :    SUBROUTINE get_pseudo_inverse_diag(a, a_pinverse, rskip)
    1031              :       REAL(KIND=dp), DIMENSION(:, :)                     :: a, a_pinverse
    1032              :       REAL(KIND=dp), INTENT(IN)                          :: rskip
    1033              : 
    1034              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'get_pseudo_inverse_diag'
    1035              : 
    1036              :       INTEGER                                            :: handle, i, info, lwork, n
    1037         2339 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:)           :: eig, work
    1038         2339 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :)        :: dinv, temp_mat
    1039              : 
    1040         2339 :       CALL timeset(routineN, handle)
    1041              : 
    1042         2339 :       info = 0
    1043         2339 :       n = SIZE(a, 1)
    1044        18712 :       ALLOCATE (dinv(n, n), eig(n), work(1), temp_mat(n, n))
    1045         2339 :       dinv(:, :) = 0.0_dp
    1046         2339 :       eig(:) = 0.0_dp
    1047         2339 :       work(:) = 0.0_dp
    1048         2339 :       temp_mat = 0.0_dp
    1049              : 
    1050              :       ! work size query
    1051         2339 :       lwork = -1
    1052         2339 :       CALL dsyev('V', 'U', n, a, n, eig(1), work(1), lwork, info)
    1053         2339 :       IF (info /= 0) THEN
    1054            0 :          CPABORT("ERROR in DSYEV: Could not retrieve work array sizes")
    1055              :       END IF
    1056         2339 :       lwork = INT(work(1))
    1057         2339 :       DEALLOCATE (work)
    1058         7017 :       ALLOCATE (work(lwork))
    1059         2339 :       work = 0.0_dp
    1060              : 
    1061              :       ! get eigenvalues and eigenvectors
    1062         2339 :       CALL dsyev('V', 'U', n, a, n, eig(1), work(1), lwork, info)
    1063              : 
    1064         2339 :       IF (info /= 0) THEN
    1065            0 :          CPABORT("Matrix diagonalization failed")
    1066              :       END IF
    1067              : 
    1068              :       ! set eigenvalues that are too small to zero
    1069        30005 :       DO i = 1, n
    1070       364025 :          IF (eig(i) > rskip*MAXVAL(eig)) THEN
    1071        24838 :             dinv(i, i) = 1.0_dp/eig(i)
    1072              :          ELSE
    1073         2828 :             dinv(i, i) = 0._dp
    1074              :          END IF
    1075              :       END DO
    1076              : 
    1077              :       ! build pseudoinverse: U*dinv*UT
    1078         2339 :       CALL dgemm("N", "T", n, n, n, 1._dp, dinv, n, a, n, 0._dp, temp_mat, n)
    1079         2339 :       CALL dgemm("N", "N", n, n, n, 1._dp, a, n, temp_mat, n, 0._dp, a_pinverse, n)
    1080              : 
    1081         2339 :       DEALLOCATE (eig, work, dinv, temp_mat)
    1082              : 
    1083         2339 :       CALL timestop(handle)
    1084              : 
    1085         2339 :    END SUBROUTINE get_pseudo_inverse_diag
    1086              : 
    1087              : ! **************************************************************************************************
    1088              : !> \brief  Reflection of the vector a through a mirror plane defined by the
    1089              : !>         normal vector b. The reflected vector a is stored in a_mirror.
    1090              : !> \param a ...
    1091              : !> \param b ...
    1092              : !> \return ...
    1093              : !> \date    16.10.1998
    1094              : !> \author  MK
    1095              : !> \version 1.0
    1096              : ! **************************************************************************************************
    1097        19491 :    PURE FUNCTION reflect_vector(a, b) RESULT(a_mirror)
    1098              :       REAL(KIND=dp), DIMENSION(3), INTENT(IN)            :: a, b
    1099              :       REAL(KIND=dp), DIMENSION(3)                        :: a_mirror
    1100              : 
    1101              :       REAL(KIND=dp)                                      :: length_of_b, scapro
    1102              :       REAL(KIND=dp), DIMENSION(3)                        :: d
    1103              : 
    1104        19491 :       length_of_b = SQRT(b(1)*b(1) + b(2)*b(2) + b(3)*b(3))
    1105              : 
    1106        19491 :       IF (length_of_b > eps_geo) THEN
    1107              : 
    1108        77964 :          d(:) = b(:)/length_of_b
    1109              : 
    1110              :          ! Calculate the mirror image a_mirror of the vector a
    1111        19491 :          scapro = a(1)*d(1) + a(2)*d(2) + a(3)*d(3)
    1112              : 
    1113        77964 :          a_mirror(:) = a(:) - 2.0_dp*scapro*d(:)
    1114              : 
    1115              :       ELSE
    1116              : 
    1117            0 :          a_mirror(:) = 0.0_dp
    1118              : 
    1119              :       END IF
    1120              : 
    1121        19491 :    END FUNCTION reflect_vector
    1122              : 
    1123              : ! **************************************************************************************************
    1124              : !> \brief   Rotation of the vector a about an rotation axis defined by the
    1125              : !>          vector b. The rotation angle is phi (radians). The rotated vector
    1126              : !>          a is stored in a_rot.
    1127              : !> \param a ...
    1128              : !> \param phi ...
    1129              : !> \param b ...
    1130              : !> \return ...
    1131              : !> \date    16.10.1998
    1132              : !> \author  MK
    1133              : !> \version 1.0
    1134              : ! **************************************************************************************************
    1135         4098 :    PURE FUNCTION rotate_vector(a, phi, b) RESULT(a_rot)
    1136              :       REAL(KIND=dp), DIMENSION(3), INTENT(IN)            :: a
    1137              :       REAL(KIND=dp), INTENT(IN)                          :: phi
    1138              :       REAL(KIND=dp), DIMENSION(3), INTENT(IN)            :: b
    1139              :       REAL(KIND=dp), DIMENSION(3)                        :: a_rot
    1140              : 
    1141              :       REAL(KIND=dp)                                      :: length_of_b
    1142              :       REAL(KIND=dp), DIMENSION(3, 3)                     :: rotmat
    1143              : 
    1144         4098 :       length_of_b = SQRT(b(1)*b(1) + b(2)*b(2) + b(3)*b(3))
    1145         4098 :       IF (length_of_b > eps_geo) THEN
    1146              : 
    1147              :          ! Build up the rotation matrix rotmat
    1148         3964 :          CALL build_rotmat(phi, b, rotmat)
    1149              : 
    1150              :          ! Rotate the vector a by phi about the axis defined by vector b
    1151        63424 :          a_rot(:) = MATMUL(rotmat, a)
    1152              : 
    1153              :       ELSE
    1154              : 
    1155          536 :          a_rot(:) = 0.0_dp
    1156              : 
    1157              :       END IF
    1158              : 
    1159         4098 :    END FUNCTION rotate_vector
    1160              : 
    1161              : ! **************************************************************************************************
    1162              : !> \brief   Set the diagonal elements of matrix a to b.
    1163              : !> \param a ...
    1164              : !> \param b ...
    1165              : !> \date    20.11.1998
    1166              : !> \author  MK
    1167              : !> \version 1.0
    1168              : ! **************************************************************************************************
    1169        61957 :    PURE SUBROUTINE set_diag_scalar_d(a, b)
    1170              :       REAL(KIND=dp), DIMENSION(:, :), INTENT(INOUT)      :: a
    1171              :       REAL(KIND=dp), INTENT(IN)                          :: b
    1172              : 
    1173              :       INTEGER                                            :: i, n
    1174              : 
    1175        61957 :       n = MIN(SIZE(a, 1), SIZE(a, 2))
    1176       325831 :       DO i = 1, n
    1177       325831 :          a(i, i) = b
    1178              :       END DO
    1179              : 
    1180        61957 :    END SUBROUTINE set_diag_scalar_d
    1181              : 
    1182              : ! **************************************************************************************************
    1183              : !> \brief ...
    1184              : !> \param a ...
    1185              : !> \param b ...
    1186              : ! **************************************************************************************************
    1187            0 :    PURE SUBROUTINE set_diag_scalar_z(a, b)
    1188              :       COMPLEX(KIND=dp), DIMENSION(:, :), INTENT(INOUT)   :: a
    1189              :       COMPLEX(KIND=dp), INTENT(IN)                       :: b
    1190              : 
    1191              :       INTEGER                                            :: i, n
    1192              : 
    1193            0 :       n = MIN(SIZE(a, 1), SIZE(a, 2))
    1194            0 :       DO i = 1, n
    1195            0 :          a(i, i) = b
    1196              :       END DO
    1197              : 
    1198            0 :    END SUBROUTINE set_diag_scalar_z
    1199              : 
    1200              : ! **************************************************************************************************
    1201              : !> \brief   Symmetrize the matrix a.
    1202              : !> \param a ...
    1203              : !> \param option ...
    1204              : !> \date    16.10.1998
    1205              : !> \author  MK
    1206              : !> \version 1.0
    1207              : ! **************************************************************************************************
    1208        20167 :    SUBROUTINE symmetrize_matrix(a, option)
    1209              :       REAL(KIND=dp), DIMENSION(:, :), INTENT(INOUT)      :: a
    1210              :       CHARACTER(LEN=*), INTENT(IN)                       :: option
    1211              : 
    1212              :       INTEGER                                            :: i, n
    1213              : 
    1214        20167 :       n = MIN(SIZE(a, 1), SIZE(a, 2))
    1215              : 
    1216        20167 :       IF (option == "lower_to_upper") THEN
    1217            0 :          DO i = 1, n - 1
    1218            0 :             a(i, i + 1:n) = a(i + 1:n, i)
    1219              :          END DO
    1220        20167 :       ELSE IF (option == "upper_to_lower") THEN
    1221       523527 :          DO i = 1, n - 1
    1222     29745601 :             a(i + 1:n, i) = a(i, i + 1:n)
    1223              :          END DO
    1224           42 :       ELSE IF (option == "anti_lower_to_upper") THEN
    1225            0 :          DO i = 1, n - 1
    1226            0 :             a(i, i + 1:n) = -a(i + 1:n, i)
    1227              :          END DO
    1228           42 :       ELSE IF (option == "anti_upper_to_lower") THEN
    1229          660 :          DO i = 1, n - 1
    1230         5532 :             a(i + 1:n, i) = -a(i, i + 1:n)
    1231              :          END DO
    1232              :       ELSE
    1233            0 :          CPABORT("Invalid option <"//TRIM(option)//"> was specified for parameter #2")
    1234              :       END IF
    1235              : 
    1236        20167 :    END SUBROUTINE symmetrize_matrix
    1237              : 
    1238              : ! **************************************************************************************************
    1239              : !> \brief   Set the matrix a to be a unit matrix.
    1240              : !> \param a ...
    1241              : !> \date    16.10.1998
    1242              : !> \author  MK
    1243              : !> \version 1.0
    1244              : ! **************************************************************************************************
    1245        61957 :    PURE SUBROUTINE unit_matrix_d(a)
    1246              :       REAL(KIND=dp), DIMENSION(:, :), INTENT(INOUT)      :: a
    1247              : 
    1248      7785221 :       a(:, :) = 0.0_dp
    1249        61957 :       CALL set_diag(a, 1.0_dp)
    1250              : 
    1251        61957 :    END SUBROUTINE unit_matrix_d
    1252              : 
    1253              : ! **************************************************************************************************
    1254              : !> \brief ...
    1255              : !> \param a ...
    1256              : ! **************************************************************************************************
    1257            0 :    PURE SUBROUTINE unit_matrix_z(a)
    1258              :       COMPLEX(KIND=dp), DIMENSION(:, :), INTENT(INOUT)   :: a
    1259              : 
    1260            0 :       a(:, :) = (0.0_dp, 0.0_dp)
    1261            0 :       CALL set_diag(a, (1.0_dp, 0.0_dp))
    1262              : 
    1263            0 :    END SUBROUTINE unit_matrix_z
    1264              : 
    1265              : ! **************************************************************************************************
    1266              : !> \brief   Calculation of the vector product c = a x b.
    1267              : !> \param a ...
    1268              : !> \param b ...
    1269              : !> \return ...
    1270              : !> \date    16.10.1998
    1271              : !> \author  MK
    1272              : !> \version 1.0
    1273              : ! **************************************************************************************************
    1274         9515 :    PURE FUNCTION vector_product(a, b) RESULT(c)
    1275              :       REAL(KIND=dp), DIMENSION(3), INTENT(IN)            :: a, b
    1276              :       REAL(KIND=dp), DIMENSION(3)                        :: c
    1277              : 
    1278         9515 :       c(1) = a(2)*b(3) - a(3)*b(2)
    1279         9515 :       c(2) = a(3)*b(1) - a(1)*b(3)
    1280         9515 :       c(3) = a(1)*b(2) - a(2)*b(1)
    1281              : 
    1282         9515 :    END FUNCTION vector_product
    1283              : 
    1284              : ! **************************************************************************************************
    1285              : !> \brief computes the greatest common divisor of two number
    1286              : !> \param a ...
    1287              : !> \param b ...
    1288              : !> \return ...
    1289              : !> \author Joost VandeVondele
    1290              : ! **************************************************************************************************
    1291      1191873 :    ELEMENTAL FUNCTION gcd(a, b)
    1292              :       INTEGER, INTENT(IN)                                :: a, b
    1293              :       INTEGER                                            :: gcd
    1294              : 
    1295              :       INTEGER                                            :: aa, ab, l, rem, s
    1296              : 
    1297      1191873 :       aa = ABS(a)
    1298      1191873 :       ab = ABS(b)
    1299      1191873 :       IF (aa < ab) THEN
    1300              :          s = aa
    1301              :          l = ab
    1302              :       ELSE
    1303      1144573 :          s = ab
    1304      1144573 :          l = aa
    1305              :       END IF
    1306      1191873 :       IF (s /= 0) THEN
    1307              :          DO
    1308      1192075 :             rem = MOD(l, s)
    1309      1192075 :             IF (rem == 0) EXIT
    1310              :             l = s
    1311      1191873 :             s = rem
    1312              :          END DO
    1313              :          GCD = s
    1314              :       ELSE
    1315              :          GCD = l
    1316              :       END IF
    1317      1191873 :    END FUNCTION gcd
    1318              : 
    1319              : ! **************************************************************************************************
    1320              : !> \brief computes the least common multiplier of two numbers
    1321              : !> \param a ...
    1322              : !> \param b ...
    1323              : !> \return ...
    1324              : !> \author Joost VandeVondele
    1325              : ! **************************************************************************************************
    1326       548240 :    ELEMENTAL FUNCTION lcm(a, b)
    1327              :       INTEGER, INTENT(IN)                                :: a, b
    1328              :       INTEGER                                            :: lcm
    1329              : 
    1330              :       INTEGER                                            :: tmp
    1331              : 
    1332       548240 :       tmp = gcd(a, b)
    1333       548240 :       IF (tmp == 0) THEN
    1334              :          lcm = 0
    1335              :       ELSE
    1336              :          ! could still overflow if the true lcm is larger than maxint
    1337       548240 :          lcm = ABS((a/tmp)*b)
    1338              :       END IF
    1339       548240 :    END FUNCTION lcm
    1340              : 
    1341              : ! **************************************************************************************************
    1342              : !> \brief computes the exponential integral
    1343              : !>      Ei(x) = Int(exp(-x*t)/t,t=1..infinity)  x>0
    1344              : !> \param x ...
    1345              : !> \return ...
    1346              : !> \author JGH (adapted from Numerical recipies)
    1347              : ! **************************************************************************************************
    1348            0 :    FUNCTION ei(x)
    1349              :       REAL(dp)                                           :: x, ei
    1350              : 
    1351              :       INTEGER, PARAMETER                                 :: maxit = 100
    1352              :       REAL(dp), PARAMETER                                :: eps = EPSILON(0.0_dp), &
    1353              :                                                             fpmin = TINY(0.0_dp)
    1354              : 
    1355              :       INTEGER                                            :: k
    1356              :       REAL(dp)                                           :: fact, prev, sum1, term
    1357              : 
    1358            0 :       IF (x <= 0._dp) THEN
    1359            0 :          CPABORT("Invalid argument")
    1360              :       END IF
    1361              : 
    1362            0 :       IF (x < fpmin) THEN
    1363            0 :          ei = LOG(x) + euler
    1364            0 :       ELSE IF (x <= -LOG(EPS)) THEN
    1365              :          sum1 = 0._dp
    1366              :          fact = 1._dp
    1367            0 :          DO k = 1, maxit
    1368            0 :             fact = fact*x/REAL(k, dp)
    1369            0 :             term = fact/REAL(k, dp)
    1370            0 :             sum1 = sum1 + term
    1371            0 :             IF (term < eps*sum1) EXIT
    1372              :          END DO
    1373            0 :          ei = sum1 + LOG(x) + euler
    1374              :       ELSE
    1375              :          sum1 = 0._dp
    1376              :          term = 1._dp
    1377            0 :          DO k = 1, maxit
    1378            0 :             prev = term
    1379            0 :             term = term*REAL(k, dp)/x
    1380            0 :             IF (term < eps) EXIT
    1381            0 :             IF (term < prev) THEN
    1382            0 :                sum1 = sum1 + term
    1383              :             ELSE
    1384            0 :                sum1 = sum1 - prev
    1385            0 :                EXIT
    1386              :             END IF
    1387              :          END DO
    1388            0 :          ei = EXP(x)*(1._dp + sum1)/x
    1389              :       END IF
    1390              : 
    1391            0 :    END FUNCTION ei
    1392              : 
    1393              : ! **************************************************************************************************
    1394              : !> \brief Computes the digamma function, the logarithmic derivative of the gamma function.
    1395              : !> \param xx Argument of the digamma function.
    1396              : !> \return The digamma function at xx. Returns zero at poles and for arguments outside the
    1397              : !>         supported numerical range.
    1398              : !> \par History
    1399              : !>      Adapted from the FUNPACK routine PSI, written at Argonne National Laboratory and modified
    1400              : !>      by A. H. Morris (NSWC).
    1401              : !> \note The implementation uses the rational Chebyshev approximations of Cody, Strecok, and
    1402              : !>       Thacher, Math. Comp. 27, 123-127 (1973), together with the reflection formula.
    1403              : ! **************************************************************************************************
    1404         7564 :    PURE FUNCTION digamma(xx) RESULT(fn_val)
    1405              :       REAL(dp), INTENT(IN)                               :: xx
    1406              :       REAL(dp)                                           :: fn_val
    1407              : 
    1408              :       REAL(dp), PARAMETER :: dx0 = 1.461632144968362341262659542325721325e0_dp, p1(7) = [ &
    1409              :                              .895385022981970e-02_dp, .477762828042627e+01_dp, .142441585084029e+03_dp, &
    1410              :                              .118645200713425e+04_dp, .363351846806499e+04_dp, .413810161269013e+04_dp, &
    1411              :                              .130560269827897e+04_dp], p2(4) = [-.212940445131011e+01_dp, -.701677227766759e+01_dp, &
    1412              :                                          -.448616543918019e+01_dp, -.648157123766197e+00_dp], piov4 = .785398163397448e0_dp, q1(6) &
    1413              :                              = [.448452573429826e+02_dp, .520752771467162e+03_dp, .221000799247830e+04_dp, &
    1414              :                                 .364127349079381e+04_dp, .190831076596300e+04_dp, .691091682714533e-05_dp]
    1415              :       REAL(dp), PARAMETER :: q2(4) = [.322703493791143e+02_dp, .892920700481861e+02_dp, &
    1416              :                                       .546117738103215e+02_dp, .777788548522962e+01_dp]
    1417              : 
    1418              :       INTEGER                                            :: i, m, n, nq
    1419              :       REAL(dp)                                           :: aug, den, sgn, upper, w, x, xmax1, xmx0, &
    1420              :                                                             xsmall, z
    1421              : 
    1422              : ! piov4 is pi/4 and dx0 is the positive zero of the digamma function. The coefficient sets
    1423              : ! p1/q1 approximate digamma(x)/(x - dx0) for 0.5 <= x <= 3, while p2/q2 approximate
    1424              : ! digamma(x) - log(x) + 1/(2*x) for x > 3.
    1425              : 
    1426              :       ! xmax1 limits integer argument reduction for large negative values and marks the point beyond
    1427              :       ! which the asymptotic value log(x) is sufficient. For very small x, pi*cot(pi*x) is
    1428              :       ! approximated by 1/x.
    1429         7564 :       xmax1 = MIN(REAL(HUGE(0), KIND=dp), 1.0e0_dp/EPSILON(1.0e0_dp))
    1430         7564 :       xsmall = 1.e-9_dp
    1431              : 
    1432         7564 :       x = xx
    1433         7564 :       aug = 0.0e0_dp
    1434         7564 :       IF (x < 0.5e0_dp) THEN
    1435              :          ! Use digamma(x) = digamma(1 - x) - pi*cot(pi*x).
    1436            0 :          IF (ABS(x) <= xsmall) THEN
    1437            0 :             IF (x == 0.0e0_dp) THEN
    1438              :                ! The digamma function has a pole at zero.
    1439         7564 :                fn_val = 0.0e0_dp
    1440              :                RETURN
    1441              :             END IF
    1442              :             ! For small nonzero x, use -1/x for -pi*cot(pi*x).
    1443            0 :             aug = -1.0e0_dp/x
    1444            0 :             x = 1.0e0_dp - x
    1445              :          ELSE
    1446              :             ! Reduce the cotangent argument to the first quadrant and keep track of its sign.
    1447            0 :             w = -x
    1448            0 :             sgn = piov4
    1449            0 :             IF (w <= 0.0e0_dp) THEN
    1450            0 :                w = -w
    1451            0 :                sgn = -sgn
    1452              :             END IF
    1453            0 :             IF (w >= xmax1) THEN
    1454              :                ! Argument reduction is no longer reliable.
    1455         7564 :                fn_val = 0.0e0_dp
    1456              :                RETURN
    1457              :             END IF
    1458            0 :             nq = INT(w)
    1459            0 :             w = w - nq
    1460            0 :             nq = INT(w*4.0e0_dp)
    1461            0 :             w = 4.0e0_dp*(w - nq*.25e0_dp)
    1462              : 
    1463            0 :             n = nq/2
    1464            0 :             IF ((n + n) /= nq) w = 1.0e0_dp - w
    1465            0 :             z = piov4*w
    1466            0 :             m = n/2
    1467            0 :             IF ((m + m) /= n) sgn = -sgn
    1468              : 
    1469              :             ! Evaluate -pi*cot(pi*x), using either tan(z) or cot(z) after quadrant reduction.
    1470            0 :             n = (nq + 1)/2
    1471            0 :             m = n/2
    1472            0 :             m = m + m
    1473            0 :             IF (m /= n) THEN
    1474            0 :                aug = sgn*((SIN(z)/COS(z))*4.0e0_dp)
    1475              :             ELSE
    1476            0 :                IF (z == 0.0e0_dp) THEN
    1477              :                   ! Negative integers are poles of the digamma function.
    1478         7564 :                   fn_val = 0.0e0_dp
    1479              :                   RETURN
    1480              :                END IF
    1481            0 :                aug = sgn*((COS(z)/SIN(z))*4.0e0_dp)
    1482              :             END IF
    1483            0 :             x = 1.0e0_dp - x
    1484              :          END IF
    1485              :       END IF
    1486              : 
    1487         7564 :       IF (x <= 3.0e0_dp) THEN
    1488              :          ! Rational approximation on 0.5 <= x <= 3.
    1489            0 :          den = x
    1490            0 :          upper = p1(1)*x
    1491              : 
    1492            0 :          DO i = 1, 5
    1493            0 :             den = (den + q1(i))*x
    1494            0 :             upper = (upper + p1(i + 1))*x
    1495              :          END DO
    1496              : 
    1497            0 :          den = (upper + p1(7))/(den + q1(6))
    1498            0 :          xmx0 = x - dx0
    1499            0 :          fn_val = den*xmx0 + aug
    1500            0 :          RETURN
    1501              :       END IF
    1502              : 
    1503         7564 :       IF (x < xmax1) THEN
    1504              :          ! Asymptotic rational correction for 3 < x < xmax1.
    1505         7564 :          w = 1.0e0_dp/(x*x)
    1506         7564 :          den = w
    1507         7564 :          upper = p2(1)*w
    1508              : 
    1509        30256 :          DO i = 1, 3
    1510        22692 :             den = (den + q2(i))*w
    1511        30256 :             upper = (upper + p2(i + 1))*w
    1512              :          END DO
    1513              : 
    1514         7564 :          aug = upper/(den + q2(4)) - 0.5e0_dp/x + aug
    1515              :       END IF
    1516              :       ! For x >= xmax1, the correction is negligible and this reduces to log(x).
    1517         7564 :       fn_val = aug + LOG(x)
    1518              : 
    1519         7564 :    END FUNCTION digamma
    1520              : 
    1521    193588912 :    @:define_expint(impure=1)
    1522              : 
    1523              : ! **************************************************************************************************
    1524              : !> \brief  Jacobi matrix diagonalization. The eigenvalues are returned in
    1525              : !>         vector d and the eigenvectors are returned in matrix v in ascending
    1526              : !>         order.
    1527              : !>
    1528              : !> \param a ...
    1529              : !> \param d ...
    1530              : !> \param v ...
    1531              : !> \par History
    1532              : !>         - Creation (20.11.98, Matthias Krack)
    1533              : ! **************************************************************************************************
    1534        37765 :    SUBROUTINE jacobi(a, d, v)
    1535              :       REAL(KIND=dp), DIMENSION(:, :), INTENT(INOUT)      :: a
    1536              :       REAL(KIND=dp), DIMENSION(:), INTENT(OUT)           :: d
    1537              :       REAL(KIND=dp), DIMENSION(:, :), INTENT(OUT)        :: v
    1538              : 
    1539              :       INTEGER                                            :: n
    1540              : 
    1541        37765 :       n = SIZE(d(:))
    1542              : 
    1543              :       ! Diagonalize matrix a
    1544        37765 :       CALL diag(n, a, d, v)
    1545              : 
    1546              :       ! Sort eigenvalues and eigenvector in ascending order
    1547        37765 :       CALL eigsrt(n, d, v)
    1548              : 
    1549        37765 :    END SUBROUTINE jacobi
    1550              : 
    1551              : ! **************************************************************************************************
    1552              : !> \brief  Diagonalize matrix a. The eigenvalues are returned in vector d
    1553              : !>         and the eigenvectors are returned in matrix v.
    1554              : !>
    1555              : !> \param n matrix/vector extent (problem size)
    1556              : !> \param a matrix to be diagonalised
    1557              : !> \param d vector of eigenvalues
    1558              : !> \param v matrix of eigenvectors
    1559              : !> \par History
    1560              : !>         - Creation (20.11.98, Matthias Krack)
    1561              : ! **************************************************************************************************
    1562        37765 :    SUBROUTINE diag(n, a, d, v)
    1563              :       INTEGER, INTENT(IN)                                :: n
    1564              :       REAL(KIND=dp), DIMENSION(:, :), INTENT(INOUT)      :: a
    1565              :       REAL(KIND=dp), DIMENSION(:), INTENT(OUT)           :: d
    1566              :       REAL(KIND=dp), DIMENSION(:, :), INTENT(OUT)        :: v
    1567              : 
    1568              :       CHARACTER(len=*), PARAMETER                        :: routineN = 'diag'
    1569              :       INTEGER, PARAMETER                                 :: maxit = 100
    1570              :       REAL(KIND=dp), PARAMETER                           :: a_eps = 1.0E-10_dp, d_eps = 1.0E-3_dp
    1571              : 
    1572              :       CHARACTER(LEN=default_string_length)               :: max_iter
    1573              :       INTEGER                                            :: handle, i, ip, iq
    1574              :       REAL(KIND=dp)                                      :: a_max, apq, c, d_min, dip, diq, g, h, s, &
    1575              :                                                             t, tau, theta, tresh
    1576        37765 :       REAL(KIND=dp), DIMENSION(n)                        :: b, z
    1577              : 
    1578        37765 :       CALL timeset(routineN, handle)
    1579              : 
    1580        37765 :       a_max = 0.0_dp
    1581       129170 :       DO ip = 1, n - 1
    1582       892667 :          a_max = MAX(a_max, MAXVAL(ABS(a(ip, ip + 1:n))))
    1583       129170 :          b(ip) = a(ip, ip) ! get_diag(a)
    1584              :       END DO
    1585        37765 :       b(n) = a(n, n)
    1586              : 
    1587        37765 :       CALL unit_matrix(v)
    1588              : 
    1589       173797 :       DO i = 1, maxit
    1590      1029604 :          d = b
    1591      1029604 :          d_min = MAX(d_eps, MINVAL(ABS(b)))
    1592       173797 :          IF (a_max < a_eps*d_min) THEN
    1593        37765 :             CALL timestop(handle)
    1594              :             RETURN
    1595              :          END IF
    1596       136032 :          tresh = MERGE(a_max, 0.0_dp, (i < 4))
    1597       862669 :          z = 0.0_dp
    1598       726637 :          DO ip = 1, n - 1
    1599      6491999 :             DO iq = ip + 1, n
    1600      5765362 :                dip = d(ip)
    1601      5765362 :                diq = d(iq)
    1602      5765362 :                apq = a(ip, iq)
    1603      5765362 :                g = 100.0_dp*ABS(apq)
    1604      6355967 :                IF (tresh < ABS(apq)) THEN
    1605      3366956 :                   h = diq - dip
    1606      3366956 :                   IF ((ABS(h) + g) /= ABS(h)) THEN
    1607      2550876 :                      theta = 0.5_dp*h/apq
    1608      2550876 :                      t = 1.0_dp/(ABS(theta) + SQRT(1.0_dp + theta**2))
    1609      2550876 :                      IF (theta < 0.0_dp) t = -t
    1610              :                   ELSE
    1611       816080 :                      t = apq/h
    1612              :                   END IF
    1613      3366956 :                   c = 1.0_dp/SQRT(1.0_dp + t**2)
    1614      3366956 :                   s = t*c
    1615      3366956 :                   tau = s/(1.0_dp + c)
    1616      3366956 :                   h = t*apq
    1617      3366956 :                   z(ip) = z(ip) - h
    1618      3366956 :                   z(iq) = z(iq) + h
    1619      3366956 :                   d(ip) = dip - h
    1620      3366956 :                   d(iq) = diq + h
    1621      3366956 :                   a(ip, iq) = 0.0_dp
    1622      3366956 :                   CALL jrotate(a(1:ip - 1, ip), a(1:ip - 1, iq), s, tau)
    1623      3366956 :                   CALL jrotate(a(ip, ip + 1:iq - 1), a(ip + 1:iq - 1, iq), s, tau)
    1624      3366956 :                   CALL jrotate(a(ip, iq + 1:n), a(iq, iq + 1:n), s, tau)
    1625      3366956 :                   CALL jrotate(v(:, ip), v(:, iq), s, tau)
    1626              :                ELSE IF ((4 < i) .AND. &
    1627            0 :                         ((ABS(dip) + g) == ABS(dip)) .AND. &
    1628      2398406 :                         ((ABS(diq) + g) == ABS(diq))) THEN
    1629            0 :                   a(ip, iq) = 0.0_dp
    1630              :                END IF
    1631              :             END DO
    1632              :          END DO
    1633       862669 :          b = b + z
    1634              :          a_max = 0.0_dp
    1635       726637 :          DO ip = 1, n - 1
    1636      6491999 :             a_max = MAX(a_max, MAXVAL(ABS(a(ip, ip + 1:n))))
    1637              :          END DO
    1638              :       END DO
    1639            0 :       WRITE (max_iter, *) maxit
    1640              :       CALL cp_warn(__LOCATION__, &
    1641              :                    "Jacobi matrix diagonalization does not converge after "// &
    1642            0 :                    TRIM(ADJUSTL(max_iter))//" iterations; stop here anyway")
    1643              : 
    1644            0 :       CALL timestop(handle)
    1645              : 
    1646              :    END SUBROUTINE diag
    1647              : 
    1648              : ! **************************************************************************************************
    1649              : !> \brief  Perform a Jacobi rotation of the vectors a and b.
    1650              : !>
    1651              : !> \param a ...
    1652              : !> \param b ...
    1653              : !> \param ss ...
    1654              : !> \param tt ...
    1655              : !> \par History
    1656              : !>         - Creation (20.11.98, Matthias Krack)
    1657              : ! **************************************************************************************************
    1658     13467824 :    PURE SUBROUTINE jrotate(a, b, ss, tt)
    1659              :       REAL(KIND=dp), DIMENSION(:), INTENT(INOUT)         :: a, b
    1660              :       REAL(KIND=dp), INTENT(IN)                          :: ss, tt
    1661              : 
    1662              :       REAL(KIND=dp)                                      :: u, v
    1663              : 
    1664     13467824 :       u = 1.0_dp - ss*tt
    1665     13467824 :       v = ss/u
    1666              : 
    1667    229073864 :       a = a*u - b*ss
    1668    229073864 :       b = b*(u + ss*v) + a*v
    1669              : 
    1670     13467824 :    END SUBROUTINE jrotate
    1671              : 
    1672              : ! **************************************************************************************************
    1673              : !> \brief Sort the values in vector d in ascending order and swap the
    1674              : !>        corresponding columns of matrix v.
    1675              : !>
    1676              : !> \param n ...
    1677              : !> \param d ...
    1678              : !> \param v ...
    1679              : !> \par History
    1680              : !>         - Creation (20.11.98, Matthias Krack)
    1681              : ! **************************************************************************************************
    1682        37765 :    SUBROUTINE eigsrt(n, d, v)
    1683              :       INTEGER, INTENT(IN)                                :: n
    1684              :       REAL(KIND=dp), DIMENSION(:), INTENT(INOUT)         :: d
    1685              :       REAL(KIND=dp), DIMENSION(:, :), INTENT(INOUT)      :: v
    1686              : 
    1687              :       INTEGER                                            :: i, j
    1688              : 
    1689       129170 :       DO i = 1, n - 1
    1690      1075477 :          j = SUM(MINLOC(d(i:n))) + i - 1
    1691       129170 :          IF (j /= i) THEN
    1692        44741 :             CALL swap(d(i), d(j))
    1693        44741 :             CALL swap(v(:, i), v(:, j))
    1694              :          END IF
    1695              :       END DO
    1696              : 
    1697        37765 :    END SUBROUTINE eigsrt
    1698              : 
    1699              : ! **************************************************************************
    1700              : !> \brief Swap two scalars
    1701              : !>
    1702              : !> \param a ...
    1703              : !> \param b ...
    1704              : !> \par History
    1705              : !>         - Creation (20.11.98, Matthias Krack)
    1706              : ! **************************************************************************************************
    1707        44741 :    ELEMENTAL SUBROUTINE swap_scalar(a, b)
    1708              :       REAL(KIND=dp), INTENT(INOUT)                       :: a, b
    1709              : 
    1710              :       REAL(KIND=dp)                                      :: c
    1711              : 
    1712        44741 :       c = a
    1713        44741 :       a = b
    1714        44741 :       b = c
    1715              : 
    1716        44741 :    END SUBROUTINE swap_scalar
    1717              : 
    1718              : ! **************************************************************************
    1719              : !> \brief Swap two vectors
    1720              : !>
    1721              : !> \param a ...
    1722              : !> \param b ...
    1723              : !> \par History
    1724              : !>         - Creation (20.11.98, Matthias Krack)
    1725              : ! **************************************************************************************************
    1726        44741 :    SUBROUTINE swap_vector(a, b)
    1727              :       REAL(KIND=dp), DIMENSION(:), INTENT(INOUT)         :: a, b
    1728              : 
    1729              :       INTEGER                                            :: i, n
    1730              :       REAL(KIND=dp)                                      :: c
    1731              : 
    1732        44741 :       n = SIZE(a)
    1733              : 
    1734        44741 :       IF (n /= SIZE(b)) THEN
    1735            0 :          CPABORT("Check the array bounds of the parameters")
    1736              :       END IF
    1737              : 
    1738       966195 :       DO i = 1, n
    1739       921454 :          c = a(i)
    1740       921454 :          a(i) = b(i)
    1741       966195 :          b(i) = c
    1742              :       END DO
    1743              : 
    1744        44741 :    END SUBROUTINE swap_vector
    1745              : 
    1746              : ! **************************************************************************************************
    1747              : !> \brief - compute a truncation radius for the shortrange operator
    1748              : !> \param eps target accuracy!> \param omg screening parameter
    1749              : !> \param omg ...
    1750              : !> \param r_cutoff cutoff radius
    1751              : !> \par History
    1752              : !>      10.2012 created [Hossein Banihashemian]
    1753              : !>      05.2019 moved here from hfx_types (A. Bussy)
    1754              : !> \author Hossein Banihashemian
    1755              : ! **************************************************************************************************
    1756           78 :    SUBROUTINE erfc_cutoff(eps, omg, r_cutoff)
    1757              :       REAL(dp), INTENT(in)  :: eps, omg
    1758              :       REAL(dp), INTENT(out) :: r_cutoff
    1759              : 
    1760              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'erfc_cutoff'
    1761              : 
    1762              :       REAL(dp), PARAMETER :: abstol = 1E-10_dp, soltol = 1E-16_dp
    1763              :       REAL(dp) :: r0, f0, fprime0, delta_r
    1764              :       INTEGER :: iter, handle
    1765              :       INTEGER, PARAMETER :: iterMAX = 1000
    1766              : 
    1767           78 :       CALL timeset(routineN, handle)
    1768              : 
    1769              :       ! initial guess assuming that we are in the asymptotic regime of the erf, and the solution is about 10.
    1770           78 :       r0 = SQRT(-LOG(eps*omg*10**2))/omg
    1771           78 :       CALL eval_transc_func(r0, eps, omg, f0, fprime0)
    1772              : 
    1773          704 :       DO iter = 1, iterMAX
    1774          704 :          delta_r = f0/fprime0
    1775          704 :          r0 = r0 - delta_r
    1776          704 :          CALL eval_transc_func(r0, eps, omg, f0, fprime0)
    1777          704 :          IF (ABS(delta_r) < abstol .OR. ABS(f0) < soltol) EXIT
    1778              :       END DO
    1779           78 :       CPASSERT(iter <= itermax)
    1780           78 :       r_cutoff = r0
    1781              : 
    1782           78 :       CALL timestop(handle)
    1783              :    CONTAINS
    1784              : ! **************************************************************************************************
    1785              : !> \brief ...
    1786              : !> \param r ...
    1787              : !> \param eps ...
    1788              : !> \param omega ...
    1789              : !> \param fn ...
    1790              : !> \param df ...
    1791              : ! **************************************************************************************************
    1792          782 :       ELEMENTAL SUBROUTINE eval_transc_func(r, eps, omega, fn, df)
    1793              :          REAL(dp), INTENT(in)                               :: r, eps, omega
    1794              :          REAL(dp), INTENT(out)                              :: fn, df
    1795              : 
    1796              :          REAL(dp)                                           :: qr
    1797              : 
    1798          782 :          qr = omega*r
    1799          782 :          fn = ERFC(qr) - r*eps
    1800          782 :          df = -2.0_dp*oorootpi*omega*EXP(-qr**2) - eps
    1801          782 :       END SUBROUTINE eval_transc_func
    1802              :    END SUBROUTINE erfc_cutoff
    1803              : 
    1804              : ! **************************************************************************************************
    1805              : !> \brief Diagonalizes a local complex Hermitian matrix using LAPACK. Based on cp_cfm_heevd
    1806              : !> \param matrix Hermitian matrix is preserved
    1807              : !> \param eigenvectors ...
    1808              : !> \param eigenvalues ...
    1809              : !> \author A. Bussy
    1810              : ! **************************************************************************************************
    1811       104783 :    SUBROUTINE diag_complex(matrix, eigenvectors, eigenvalues)
    1812              :       COMPLEX(KIND=dp), DIMENSION(:, :), INTENT(IN)      :: matrix
    1813              :       COMPLEX(KIND=dp), DIMENSION(:, :), INTENT(OUT)     :: eigenvectors
    1814              :       REAL(KIND=dp), DIMENSION(:), INTENT(OUT)           :: eigenvalues
    1815              : 
    1816              :       CHARACTER(len=*), PARAMETER                        :: routineN = 'diag_complex'
    1817              : 
    1818       104783 :       COMPLEX(KIND=dp), DIMENSION(:), ALLOCATABLE        :: work
    1819              :       INTEGER                                            :: handle, info, liwork, lrwork, lwork, n
    1820       104783 :       INTEGER, DIMENSION(:), ALLOCATABLE                 :: iwork
    1821       104783 :       REAL(KIND=dp), DIMENSION(:), ALLOCATABLE           :: rwork
    1822              : 
    1823       104783 :       CALL timeset(routineN, handle)
    1824              : 
    1825       104783 :       IF (SIZE(matrix, 1) /= SIZE(matrix, 2)) CPABORT("Expected square matrix")
    1826              :       ! IF (MAXVAL(ABS(matrix - CONJG(TRANSPOSE(matrix)))) > 1e-14_dp) CPABORT("Expected hermitian matrix")
    1827              : 
    1828       104783 :       n = SIZE(matrix, 1)
    1829       104783 :       ALLOCATE (iwork(1), rwork(1), work(1))
    1830              : 
    1831              :       ! work space query
    1832       104783 :       lwork = -1
    1833       104783 :       lrwork = -1
    1834       104783 :       liwork = -1
    1835              : 
    1836       104783 :       CALL zheevd('V', 'U', n, eigenvectors, n, eigenvalues, work, lwork, rwork, lrwork, iwork, liwork, info)
    1837              : 
    1838       104783 :       lwork = CEILING(REAL(work(1), KIND=dp))
    1839       104783 :       lrwork = CEILING(rwork(1))
    1840       104783 :       liwork = iwork(1)
    1841              : 
    1842       104783 :       DEALLOCATE (iwork, rwork, work)
    1843       733481 :       ALLOCATE (iwork(liwork), rwork(lrwork), work(lwork))
    1844      5079521 :       eigenvectors(:, :) = matrix(:, :)
    1845              : 
    1846              :       ! final diagonalization
    1847       104783 :       CALL zheevd('V', 'U', n, eigenvectors, n, eigenvalues, work, lwork, rwork, lrwork, iwork, liwork, info)
    1848              : 
    1849       104783 :       DEALLOCATE (iwork, rwork, work)
    1850              : 
    1851       104783 :       IF (info /= 0) CPABORT("Diagonalisation of a complex matrix failed")
    1852              : 
    1853       104783 :       CALL timestop(handle)
    1854              : 
    1855       104783 :    END SUBROUTINE diag_complex
    1856              : 
    1857              : ! **************************************************************************************************
    1858              : !> \brief Helper routine for diagonalizing anti symmetric matrices
    1859              : !> \param matrix ...
    1860              : !> \param evecs ...
    1861              : !> \param evals ...
    1862              : ! **************************************************************************************************
    1863         1049 :    SUBROUTINE diag_antisym(matrix, evecs, evals)
    1864              :       REAL(dp), DIMENSION(:, :)                          :: matrix
    1865              :       COMPLEX(dp), DIMENSION(:, :)                       :: evecs
    1866              :       COMPLEX(dp), DIMENSION(:)                          :: evals
    1867              : 
    1868              :       COMPLEX(dp), ALLOCATABLE, DIMENSION(:, :)          :: matrix_c
    1869              :       INTEGER                                            :: n
    1870              :       REAL(dp), ALLOCATABLE, DIMENSION(:)                :: eigenvalues
    1871              : 
    1872         1049 :       IF (SIZE(matrix, 1) /= SIZE(matrix, 2)) CPABORT("Expected square matrix")
    1873              :       ! IF (MAXVAL(ABS(matrix + TRANSPOSE(matrix))) > 1e-14_dp) CPABORT("Expected anti-symmetric matrix")
    1874              : 
    1875         1049 :       n = SIZE(matrix, 1)
    1876         6294 :       ALLOCATE (matrix_c(n, n), eigenvalues(n))
    1877              : 
    1878        32519 :       matrix_c(:, :) = CMPLX(0.0_dp, -matrix, kind=dp)
    1879         1049 :       CALL diag_complex(matrix_c, evecs, eigenvalues)
    1880         6294 :       evals = CMPLX(0.0_dp, eigenvalues, kind=dp)
    1881              : 
    1882         1049 :       DEALLOCATE (matrix_c, eigenvalues)
    1883         1049 :    END SUBROUTINE diag_antisym
    1884              : ! **************************************************************************************************
    1885              : !> \brief Square array multiplication via LAPACK routines, leaves inputs unchanged
    1886              : !> \param A_in Input matrix 1
    1887              : !> \param A_trans 'N' - no transpose, 'T' - transpose, 'C' - hermitian conj. of matrix 1
    1888              : !> \param B_in Input matrix 2
    1889              : !> \param B_trans 'N' - no transpose, 'T' - transpose, 'C' - hermitian conj. of matrix 2
    1890              : !> \param C_out Output matrix
    1891              : !> \par History
    1892              : !>    11.2025 created [Stepan Marek]
    1893              : ! **************************************************************************************************
    1894        88172 :    SUBROUTINE zgemm_square_2(A_in, A_trans, B_in, B_trans, C_out)
    1895              :       COMPLEX(kind=dp), DIMENSION(:, :), INTENT(IN)      :: A_in
    1896              :       CHARACTER, INTENT(IN)                              :: A_trans
    1897              :       COMPLEX(kind=dp), DIMENSION(:, :), INTENT(IN)      :: B_in
    1898              :       CHARACTER, INTENT(IN)                              :: B_trans
    1899              :       COMPLEX(kind=dp), DIMENSION(:, :), INTENT(INOUT)   :: C_out
    1900              : 
    1901              :       CHARACTER(len=*), PARAMETER                        :: routineN = 'zgemm_square_2'
    1902              : 
    1903              :       INTEGER                                            :: handle, n
    1904              : 
    1905        88172 :       n = SIZE(A_in, 1)
    1906        88172 :       IF (n /= SIZE(A_in, 2)) CPABORT("Non-square array 1 (A).")
    1907        88172 :       IF (n /= SIZE(B_in, 1)) CPABORT("Incompatible (rows) array 2 (B).")
    1908        88172 :       IF (n /= SIZE(B_in, 2)) CPABORT("Non-square array 2 (B).")
    1909        88172 :       IF (n /= SIZE(C_out, 1)) CPABORT("Incompatible (rows) result array 3 (C).")
    1910        88172 :       IF (n /= SIZE(C_out, 2)) CPABORT("Incompatible (cols) result array 3 (C).")
    1911        88172 :       IF (.NOT. (A_trans == 'N' .OR. A_trans == 'n' .OR. &
    1912              :                  A_trans == 'T' .OR. A_trans == 't' .OR. &
    1913              :                  A_trans == 'C' .OR. A_trans == 'c')) THEN
    1914            0 :          CPABORT("Unknown transpose character for array 1 (A).")
    1915              :       END IF
    1916        88172 :       IF (.NOT. (B_trans == 'N' .OR. B_trans == 'n' .OR. &
    1917              :                  B_trans == 'T' .OR. B_trans == 't' .OR. &
    1918              :                  B_trans == 'C' .OR. B_trans == 'c')) THEN
    1919            0 :          CPABORT("Unknown transpose character for array 2 (B).")
    1920              :       END IF
    1921              : 
    1922        88172 :       CALL timeset(routineN, handle)
    1923              : 
    1924        88172 :       CALL ZGEMM(A_trans, B_trans, n, n, n, z_one, A_in, n, B_in, n, z_zero, C_out, n)
    1925              : 
    1926        88172 :       CALL timestop(handle)
    1927              : 
    1928        88172 :    END SUBROUTINE zgemm_square_2
    1929              : ! **************************************************************************************************
    1930              : !> \brief Square array multiplication via LAPACK routines, leaves inputs unchanged, real matrices
    1931              : !> \param A_in Input matrix 1
    1932              : !> \param A_trans 'N' - no transpose, 'T' - transpose, 'C' - hermitian conj. of matrix 1
    1933              : !> \param B_in Input matrix 2
    1934              : !> \param B_trans 'N' - no transpose, 'T' - transpose, 'C' - hermitian conj. of matrix 2
    1935              : !> \param C_out Output matrix
    1936              : !> \par History
    1937              : !>    11.2025 created [Stepan Marek]
    1938              : ! **************************************************************************************************
    1939            2 :    SUBROUTINE dgemm_square_2(A_in, A_trans, B_in, B_trans, C_out)
    1940              :       REAL(kind=dp), DIMENSION(:, :), INTENT(IN)         :: A_in
    1941              :       CHARACTER, INTENT(IN)                              :: A_trans
    1942              :       REAL(kind=dp), DIMENSION(:, :), INTENT(IN)         :: B_in
    1943              :       CHARACTER, INTENT(IN)                              :: B_trans
    1944              :       REAL(kind=dp), DIMENSION(:, :), INTENT(INOUT)      :: C_out
    1945              : 
    1946              :       CHARACTER(len=*), PARAMETER                        :: routineN = 'dgemm_square_2'
    1947              : 
    1948              :       INTEGER                                            :: handle, n
    1949              : 
    1950            2 :       n = SIZE(A_in, 1)
    1951            2 :       IF (n /= SIZE(A_in, 2)) CPABORT("Non-square array 1 (A).")
    1952            2 :       IF (n /= SIZE(B_in, 1)) CPABORT("Incompatible (rows) array 2 (B).")
    1953            2 :       IF (n /= SIZE(B_in, 2)) CPABORT("Non-square array 2 (B).")
    1954            2 :       IF (n /= SIZE(C_out, 1)) CPABORT("Incompatible (rows) result array 3 (C).")
    1955            2 :       IF (n /= SIZE(C_out, 2)) CPABORT("Incompatible (cols) result array 3 (C).")
    1956            2 :       IF (.NOT. (A_trans == 'N' .OR. A_trans == 'n' .OR. &
    1957              :                  A_trans == 'T' .OR. A_trans == 't' .OR. &
    1958              :                  A_trans == 'C' .OR. A_trans == 'c')) THEN
    1959            0 :          CPABORT("Unknown transpose character for array 1 (A).")
    1960              :       END IF
    1961            2 :       IF (.NOT. (B_trans == 'N' .OR. B_trans == 'n' .OR. &
    1962              :                  B_trans == 'T' .OR. B_trans == 't' .OR. &
    1963              :                  B_trans == 'C' .OR. B_trans == 'c')) THEN
    1964            0 :          CPABORT("Unknown transpose character for array 2 (B).")
    1965              :       END IF
    1966              : 
    1967            2 :       CALL timeset(routineN, handle)
    1968              : 
    1969            2 :       CALL DGEMM(A_trans, B_trans, n, n, n, 1.0_dp, A_in, n, B_in, n, 0.0_dp, C_out, n)
    1970              : 
    1971            2 :       CALL timestop(handle)
    1972              : 
    1973            2 :    END SUBROUTINE dgemm_square_2
    1974              : ! **************************************************************************************************
    1975              : !> \brief Square array multiplication via LAPACK routines, leaves inputs unchanged, for 3 matrices
    1976              : !> \param A_in Input matrix 1
    1977              : !> \param A_trans 'N' - no transpose, 'T' - transpose, 'C' - hermitian conj. of matrix 1
    1978              : !> \param B_in Input matrix 2
    1979              : !> \param B_trans 'N' - no transpose, 'T' - transpose, 'C' - hermitian conj. of matrix 2
    1980              : !> \param C_in Input matrix 3
    1981              : !> \param C_trans 'N' - no transpose, 'T' - transpose, 'C' - hermitian conj. of matrix 3
    1982              : !> \param D_out Output matrix
    1983              : !> \par History
    1984              : !>    11.2025 created [Stepan Marek]
    1985              : ! **************************************************************************************************
    1986        68127 :    SUBROUTINE zgemm_square_3(A_in, A_trans, B_in, B_trans, C_in, C_trans, D_out)
    1987              :       COMPLEX(kind=dp), DIMENSION(:, :), INTENT(IN)      :: A_in
    1988              :       CHARACTER, INTENT(IN)                              :: A_trans
    1989              :       COMPLEX(kind=dp), DIMENSION(:, :), INTENT(IN)      :: B_in
    1990              :       CHARACTER, INTENT(IN)                              :: B_trans
    1991              :       COMPLEX(kind=dp), DIMENSION(:, :), INTENT(IN)      :: C_in
    1992              :       CHARACTER, INTENT(IN)                              :: C_trans
    1993              :       COMPLEX(kind=dp), DIMENSION(:, :), INTENT(INOUT)   :: D_out
    1994              : 
    1995              :       CHARACTER(len=*), PARAMETER                        :: routineN = 'zgemm_square_3'
    1996              : 
    1997        68127 :       COMPLEX(kind=dp), ALLOCATABLE, DIMENSION(:, :)     :: work
    1998              :       INTEGER                                            :: handle, n
    1999              : 
    2000        68127 :       n = SIZE(A_in, 1)
    2001        68127 :       IF (n /= SIZE(A_in, 2)) CPABORT("Non-square array 1 (A).")
    2002        68127 :       IF (n /= SIZE(B_in, 1)) CPABORT("Incompatible (rows) array 2 (B).")
    2003        68127 :       IF (n /= SIZE(B_in, 2)) CPABORT("Non-square array 2 (B).")
    2004        68127 :       IF (n /= SIZE(C_in, 1)) CPABORT("Incompatible (rows) array 3 (C).")
    2005        68127 :       IF (n /= SIZE(C_in, 2)) CPABORT("Non-square array 3 (C).")
    2006        68127 :       IF (n /= SIZE(D_out, 1)) CPABORT("Incompatible (rows) result array 4 (D).")
    2007        68127 :       IF (n /= SIZE(D_out, 2)) CPABORT("Incompatible (cols) result array 4 (D).")
    2008        68127 :       IF (.NOT. (A_trans == 'N' .OR. A_trans == 'n' .OR. &
    2009              :                  A_trans == 'T' .OR. A_trans == 't' .OR. &
    2010              :                  A_trans == 'C' .OR. A_trans == 'c')) THEN
    2011            0 :          CPABORT("Unknown transpose character for array 1 (A).")
    2012              :       END IF
    2013        68127 :       IF (.NOT. (B_trans == 'N' .OR. B_trans == 'n' .OR. &
    2014              :                  B_trans == 'T' .OR. B_trans == 't' .OR. &
    2015              :                  B_trans == 'C' .OR. B_trans == 'c')) THEN
    2016            0 :          CPABORT("Unknown transpose character for array 2 (B).")
    2017              :       END IF
    2018        68127 :       IF (.NOT. (C_trans == 'N' .OR. C_trans == 'n' .OR. &
    2019              :                  C_trans == 'T' .OR. C_trans == 't' .OR. &
    2020              :                  C_trans == 'C' .OR. C_trans == 'c')) THEN
    2021            0 :          CPABORT("Unknown transpose character for array 3 (C).")
    2022              :       END IF
    2023              : 
    2024        68127 :       CALL timeset(routineN, handle)
    2025              : 
    2026       272508 :       ALLOCATE (work(n, n), source=z_zero)
    2027              : 
    2028        68127 :       CALL ZGEMM(A_trans, B_trans, n, n, n, z_one, A_in, n, B_in, n, z_zero, work, n)
    2029        68127 :       CALL ZGEMM('N', C_trans, n, n, n, z_one, work, n, C_in, n, z_zero, D_out, n)
    2030              : 
    2031        68127 :       DEALLOCATE (work)
    2032              : 
    2033        68127 :       CALL timestop(handle)
    2034              : 
    2035        68127 :    END SUBROUTINE zgemm_square_3
    2036              : ! **************************************************************************************************
    2037              : !> \brief Square array multiplication via LAPACK routines, leaves inputs unchanged, for 3 matrices
    2038              : !> \param A_in Input matrix 1
    2039              : !> \param A_trans 'N' - no transpose, 'T' - transpose, 'C' - hermitian conj. of matrix 1
    2040              : !> \param B_in Input matrix 2
    2041              : !> \param B_trans 'N' - no transpose, 'T' - transpose, 'C' - hermitian conj. of matrix 2
    2042              : !> \param C_in Input matrix 3
    2043              : !> \param C_trans 'N' - no transpose, 'T' - transpose, 'C' - hermitian conj. of matrix 3
    2044              : !> \param D_out Output matrix
    2045              : !> \par History
    2046              : !>    11.2025 created [Stepan Marek]
    2047              : ! **************************************************************************************************
    2048            4 :    SUBROUTINE dgemm_square_3(A_in, A_trans, B_in, B_trans, C_in, C_trans, D_out)
    2049              :       REAL(kind=dp), DIMENSION(:, :), INTENT(IN)         :: A_in
    2050              :       CHARACTER, INTENT(IN)                              :: A_trans
    2051              :       REAL(kind=dp), DIMENSION(:, :), INTENT(IN)         :: B_in
    2052              :       CHARACTER, INTENT(IN)                              :: B_trans
    2053              :       REAL(kind=dp), DIMENSION(:, :), INTENT(IN)         :: C_in
    2054              :       CHARACTER, INTENT(IN)                              :: C_trans
    2055              :       REAL(kind=dp), DIMENSION(:, :), INTENT(INOUT)      :: D_out
    2056              : 
    2057              :       CHARACTER(len=*), PARAMETER                        :: routineN = 'dgemm_square_3'
    2058              : 
    2059              :       INTEGER                                            :: handle, n
    2060            4 :       REAL(kind=dp), ALLOCATABLE, DIMENSION(:, :)        :: work
    2061              : 
    2062            4 :       n = SIZE(A_in, 1)
    2063            4 :       IF (n /= SIZE(A_in, 2)) CPABORT("Non-square array 1 (A).")
    2064            4 :       IF (n /= SIZE(B_in, 1)) CPABORT("Incompatible (rows) array 2 (B).")
    2065            4 :       IF (n /= SIZE(B_in, 2)) CPABORT("Non-square array 2 (B).")
    2066            4 :       IF (n /= SIZE(C_in, 1)) CPABORT("Incompatible (rows) array 3 (C).")
    2067            4 :       IF (n /= SIZE(C_in, 2)) CPABORT("Non-square array 3 (C).")
    2068            4 :       IF (n /= SIZE(D_out, 1)) CPABORT("Incompatible (rows) result array 4 (D).")
    2069            4 :       IF (n /= SIZE(D_out, 2)) CPABORT("Incompatible (cols) result array 4 (D).")
    2070            4 :       IF (.NOT. (A_trans == 'N' .OR. A_trans == 'n' .OR. &
    2071              :                  A_trans == 'T' .OR. A_trans == 't' .OR. &
    2072              :                  A_trans == 'C' .OR. A_trans == 'c')) THEN
    2073            0 :          CPABORT("Unknown transpose character for array 1 (A).")
    2074              :       END IF
    2075            4 :       IF (.NOT. (B_trans == 'N' .OR. B_trans == 'n' .OR. &
    2076              :                  B_trans == 'T' .OR. B_trans == 't' .OR. &
    2077              :                  B_trans == 'C' .OR. B_trans == 'c')) THEN
    2078            0 :          CPABORT("Unknown transpose character for array 2 (B).")
    2079              :       END IF
    2080            4 :       IF (.NOT. (C_trans == 'N' .OR. C_trans == 'n' .OR. &
    2081              :                  C_trans == 'T' .OR. C_trans == 't' .OR. &
    2082              :                  C_trans == 'C' .OR. C_trans == 'c')) THEN
    2083            0 :          CPABORT("Unknown transpose character for array 3 (C).")
    2084              :       END IF
    2085              : 
    2086            4 :       CALL timeset(routineN, handle)
    2087              : 
    2088           16 :       ALLOCATE (work(n, n), source=0.0_dp)
    2089              : 
    2090            4 :       CALL DGEMM(A_trans, B_trans, n, n, n, 1.0_dp, A_in, n, B_in, n, 0.0_dp, work, n)
    2091            4 :       CALL DGEMM('N', C_trans, n, n, n, 1.0_dp, work, n, C_in, n, 0.0_dp, D_out, n)
    2092              : 
    2093            4 :       DEALLOCATE (work)
    2094              : 
    2095            4 :       CALL timestop(handle)
    2096              : 
    2097            4 :    END SUBROUTINE dgemm_square_3
    2098              : 
    2099              : ! **************************************************************************************************
    2100              : !> \brief Solve the generalized eigenvalue equation for complex matrices A*v = B*v*λ
    2101              : !> \param A_in ...
    2102              : !> \param B_in ...
    2103              : !> \param eigenvalues ...
    2104              : !> \param eigenvectors ...
    2105              : !> \author Shridhar Shanbhag
    2106              : ! **************************************************************************************************
    2107            6 :    SUBROUTINE geeig_right(A_in, B_in, eigenvalues, eigenvectors)
    2108              :       COMPLEX(kind=dp), DIMENSION(:, :), INTENT(IN)      :: A_in, B_in
    2109              :       REAL(KIND=dp), DIMENSION(:), INTENT(OUT)           :: eigenvalues
    2110              :       COMPLEX(KIND=dp), DIMENSION(:, :), INTENT(OUT)     :: eigenvectors
    2111              : 
    2112              :       CHARACTER(len=*), PARAMETER                        :: routineN = 'geeig_right'
    2113              :       COMPLEX(KIND=dp), PARAMETER :: cone = CMPLX(1.0_dp, 0.0_dp, KIND=dp), &
    2114              :                                      czero = CMPLX(0.0_dp, 0.0_dp, KIND=dp)
    2115              : 
    2116            6 :       COMPLEX(KIND=dp), ALLOCATABLE, DIMENSION(:)        :: cevals
    2117              :       COMPLEX(kind=dp), ALLOCATABLE, DIMENSION(:, :)     :: A, B, work
    2118              :       INTEGER                                            :: handle, i, icol, irow, lda, ldb, ldc, &
    2119              :                                                             nao, nc, ncol, nmo, nx
    2120              :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:)           :: evals
    2121              : 
    2122            6 :       CALL timeset(routineN, handle)
    2123              : 
    2124              :       ! Test sizes
    2125            6 :       nao = SIZE(A_in, 1)
    2126            6 :       nmo = SIZE(eigenvalues)
    2127           30 :       ALLOCATE (evals(nao), cevals(nao))
    2128           48 :       ALLOCATE (work(nao, nao), B(nao, nao), A(nao, nao))
    2129        22334 :       A(:, :) = A_in(:, :)
    2130        22334 :       B(:, :) = B_in(:, :)
    2131              : 
    2132              :       ! Diagonalize -S matrix, this way the NULL space is at the end of the spectrum
    2133        22334 :       B = -B
    2134            6 :       CALL diag_complex(B, work, evals)
    2135          254 :       evals(:) = -evals(:)
    2136            6 :       nc = nao
    2137          254 :       DO i = 1, nao
    2138          254 :          IF (evals(i) < -1.0_dp) THEN
    2139            0 :             nc = i - 1
    2140            0 :             EXIT
    2141              :          END IF
    2142              :       END DO
    2143            6 :       CPASSERT(nc /= 0)
    2144              : 
    2145            6 :       IF (nc /= nao) THEN
    2146            0 :          IF (nc < nmo) THEN
    2147              :             ! Copy NULL space definition to last vectors of eigenvectors (if needed)
    2148            0 :             ncol = nmo - nc
    2149            0 :             CALL zcopy(ncol*nao, work(1, nc + 1), 1, eigenvectors(1, nc + 1), 1)
    2150              :          END IF
    2151              :          ! Set NULL space in eigenvector matrix of S to zero
    2152            0 :          DO icol = nc + 1, nao
    2153            0 :             DO irow = 1, nao
    2154            0 :                work(irow, icol) = czero
    2155              :             END DO
    2156              :          END DO
    2157              :          ! Set small eigenvalues to a dummy save value
    2158            0 :          evals(nc + 1:nao) = 1.0_dp
    2159              :       END IF
    2160              :       ! Calculate U*s**(-1/2)
    2161          254 :       cevals(:) = CMPLX(1.0_dp/SQRT(evals(:)), 0.0_dp, KIND=dp)
    2162          254 :       DO i = 1, MIN(SIZE(work, 2), SIZE(cevals))
    2163        22334 :          work(1:MIN(SIZE(work, 2), SIZE(cevals)), i) = cevals(i)*work(1:MIN(SIZE(work, 2), SIZE(cevals)), i)
    2164              :       END DO
    2165              :       ! Reduce to get U^(-C) * H * U^(-1)
    2166            6 :       CALL gemm_square(work, 'C', A, 'N', B)
    2167            6 :       CALL gemm_square(B, 'N', work, 'N', A)
    2168            6 :       IF (nc /= nao) THEN
    2169              :          ! set diagonal values to save large value
    2170            0 :          DO icol = nc + 1, nao
    2171            0 :             A(icol, icol) = 10000*cone
    2172              :          END DO
    2173              :       END IF
    2174              :       ! Diagonalize
    2175            6 :       CALL diag_complex(A, B, evals)
    2176          254 :       eigenvalues(1:nmo) = evals(1:nmo)
    2177            6 :       nx = MIN(nc, nmo)
    2178              :       ! Restore vectors C = U^(-1) * C*
    2179            6 :       lda = SIZE(work, 1)
    2180            6 :       ldb = SIZE(B, 1)
    2181            6 :       ldc = SIZE(eigenvectors, 1)
    2182              :       CALL ZGEMM("N", "N", nao, nx, nc, cone, work, &
    2183            6 :                  lda, B, ldb, czero, eigenvectors, ldc)
    2184              : 
    2185            6 :       DEALLOCATE (evals, cevals, work, B, A)
    2186              : 
    2187            6 :       CALL timestop(handle)
    2188            6 :    END SUBROUTINE geeig_right
    2189              : 
    2190              : ! **************************************************************************************************
    2191              : !> \brief Gauss-Legendre nodes and weights on [-1,1], with nodes in ascending order.
    2192              : !>        The Legendre roots are refined by Newton iterations to machine precision.
    2193              : !> \param n number of nodes
    2194              : !> \param nodes ...
    2195              : !> \param weights ...
    2196              : ! **************************************************************************************************
    2197          280 :    SUBROUTINE gauss_legendre(n, nodes, weights)
    2198              :       INTEGER, INTENT(IN)                                :: n
    2199              :       REAL(KIND=dp), DIMENSION(n), INTENT(OUT)           :: nodes, weights
    2200              : 
    2201              :       INTEGER, PARAMETER                                 :: max_iter = 100
    2202              : 
    2203              :       INTEGER                                            :: i, iter, j
    2204              :       REAL(KIND=dp)                                      :: derivative, dz, p0, p1, p2, z
    2205              : 
    2206         8920 :       DO i = 1, (n + 1)/2
    2207         8640 :          z = COS(pi*(REAL(i, dp) - 0.25_dp)/(REAL(n, dp) + 0.5_dp))
    2208        27868 :          DO iter = 1, max_iter
    2209              :             p0 = 1.0_dp
    2210              :             p1 = 0.0_dp
    2211      1978204 :             DO j = 1, n
    2212      1950336 :                p2 = p1
    2213      1950336 :                p1 = p0
    2214      1978204 :                p0 = (REAL(2*j - 1, dp)*z*p1 - REAL(j - 1, dp)*p2)/REAL(j, dp)
    2215              :             END DO
    2216        27868 :             derivative = REAL(n, dp)*(z*p0 - p1)/(z*z - 1.0_dp)
    2217        27868 :             dz = p0/derivative
    2218        27868 :             z = z - dz
    2219        27868 :             IF (ABS(dz) <= EPSILON(1.0_dp)) EXIT
    2220              :          END DO
    2221         8640 :          IF (iter > max_iter) CPABORT("Gauss-Legendre roots did not converge")
    2222         8640 :          nodes(i) = -z
    2223         8640 :          nodes(n + 1 - i) = z
    2224         8640 :          weights(i) = 2.0_dp/((1.0_dp - z*z)*derivative**2)
    2225         8920 :          weights(n + 1 - i) = weights(i)
    2226              :       END DO
    2227              : 
    2228          280 :    END SUBROUTINE gauss_legendre
    2229              : 
    2230              : END MODULE mathlib
        

Generated by: LCOV version 2.0-1