LCOV - code coverage report
Current view: top level - src - bse_davidson.F (source / functions) Coverage Total Hit
Test: CP2K Regtests (git:1be8651) Lines: 86.4 % 1232 1064
Test Date: 2026-11-24 01:22:08 Functions: 97.9 % 47 46

            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 Block Davidson solvers for the lowest excitations of the Bethe-Salpeter equation on top
      10              : !>        of the matrix-free application of A and B: the TDA problem sum_jb A_ia,jb X_jb = Ω X_ia
      11              : !>        (bse_davidson_tda) and the full problem, either as sum_jb [(A+B)(A-B)]_ia,jb x_jb = Ω^2 x_ia
      12              : !>        (bse_davidson_abba_mk) or as the pair sum_jb (A+B)_ia,jb y_jb = Ω x_ia, sum_jb (A-B)_ia,jb x_jb = Ω y_ia
      13              : !>        (bse_davidson_abba_os). Every solver projects its problem onto an orthonormal basis, takes the
      14              : !>        lowest Ritz pairs, extends the basis by the preconditioned residuals of the roots still in need
      15              : !>        and restarts thick at the subspace ceiling; the helpers below are shared by the three drivers
      16              : !> \par History
      17              : !>      09.2026 created [Maximilian Graml]
      18              : ! **************************************************************************************************
      19              : MODULE bse_davidson
      20              : 
      21              :    USE bibliography,                    ONLY: Bai2012,&
      22              :                                               Davidson1975,&
      23              :                                               Fukaya2014,&
      24              :                                               Olsen1988,&
      25              :                                               Stathopoulos1998,&
      26              :                                               Stratmann1998,&
      27              :                                               Vecharynski2017,&
      28              :                                               cite_reference
      29              :    USE bse_full_diag,                   ONLY: create_hermitian_form_of_ABBA
      30              :    USE bse_matvec,                      ONLY: bse_matvec_apply,&
      31              :                                               bse_matvec_diagonal,&
      32              :                                               bse_matvec_env_type,&
      33              :                                               bse_matvec_subblock,&
      34              :                                               bse_matvec_vector_struct,&
      35              :                                               bse_memory_left_GB
      36              :    USE bse_types,                       ONLY: bse_env_type
      37              :    USE cp_blacs_env,                    ONLY: cp_blacs_env_create,&
      38              :                                               cp_blacs_env_release,&
      39              :                                               cp_blacs_env_type
      40              :    USE cp_fm_basic_linalg,              ONLY: cp_fm_column_scale,&
      41              :                                               cp_fm_scale_and_add,&
      42              :                                               cp_fm_transpose,&
      43              :                                               cp_fm_triangular_multiply
      44              :    USE cp_fm_diag,                      ONLY: choose_eigv_solver
      45              :    USE cp_fm_struct,                    ONLY: cp_fm_struct_create,&
      46              :                                               cp_fm_struct_release,&
      47              :                                               cp_fm_struct_type
      48              :    USE cp_fm_types,                     ONLY: &
      49              :         cp_fm_create, cp_fm_get_info, cp_fm_get_submatrix, cp_fm_release, cp_fm_set_all, &
      50              :         cp_fm_set_submatrix, cp_fm_to_fm, cp_fm_to_fm_submat, cp_fm_type
      51              :    USE input_constants,                 ONLY: bse_iter_and_cond,&
      52              :                                               bse_iter_en_cond,&
      53              :                                               bse_iter_or_cond,&
      54              :                                               bse_iter_res_cond
      55              :    USE kinds,                           ONLY: dp
      56              :    USE machine,                         ONLY: m_walltime
      57              :    USE mathlib,                         ONLY: diamat_all
      58              :    USE message_passing,                 ONLY: mp_para_env_type
      59              :    USE parallel_gemm_api,               ONLY: parallel_gemm
      60              :    USE physcon,                         ONLY: evolt
      61              :    USE util,                            ONLY: sort
      62              : #include "./base/base_uses.f90"
      63              : 
      64              :    IMPLICIT NONE
      65              : 
      66              :    PRIVATE
      67              : 
      68              :    CHARACTER(len=*), PARAMETER, PRIVATE :: moduleN = 'bse_davidson'
      69              : 
      70              :    ! energies closer than this belong to one multiplet (Hartree)
      71              :    REAL(KIND=dp), PARAMETER, PRIVATE :: deg_thresh = 1.0E-6_dp
      72              :    ! a basis that is not orthonormal to this accuracy makes the residuals meaningless
      73              :    REAL(KIND=dp), PARAMETER, PRIVATE :: ortho_tol = 1.0E-8_dp
      74              : 
      75              :    ! outcome of an ABBA solver: solved, or A-B not positive definite on the trial space
      76              :    INTEGER, PARAMETER, PUBLIC :: abba_ok = 0, abba_indefinite = 1
      77              : 
      78              :    ! the three drivers, for the memory estimate
      79              :    INTEGER, PARAMETER, PRIVATE :: driver_tda = 1, driver_mk = 2, driver_os = 3
      80              : 
      81              :    PUBLIC :: bse_davidson_tda, bse_davidson_abba_mk, bse_davidson_abba_os, &
      82              :              bse_davidson_refcheck
      83              : 
      84              : CONTAINS
      85              : 
      86              : ! **************************************************************************************************
      87              : !> \brief Block Davidson with thick restart for the NUM_EXC_EN lowest solutions of
      88              : !>        sum_jb A_ia,jb X_jb^n = Ω^n X_ia^n. With the orthonormal basis Z_ia,m the reduced matrix is
      89              : !>        Ar_mn = sum_ia Z_ia,m (A Z)_ia,n with eigenpairs (θ_k, c_mk), X_ia^k = sum_m Z_ia,m c_mk,
      90              : !>        and the basis grows by the corrections t_ia,k = r_ia,k/(d_ia - θ_k) of the residuals
      91              : !>        r_ia,k = sum_m (A Z)_ia,m c_mk - θ_k X_ia^k, d_ia being the diagonal chosen by PRECONDITIONER.
      92              : !>        Arrays: Ar_mn (the reduced A) in fm_red_A on the process grid, c_mk in coef_ritz, θ_k c_mk in
      93              : !>        coef_ritz_theta
      94              : !> \param mv_env slabs, prefactors and transition energies of the matrix-free A
      95              : !> \param bse_env bse_env carries the BSE_ITERAT settings and BSE_DEBUG_PRINT
      96              : !> \param unit_nr output unit, positive on the writing rank only
      97              : !> \param exc_ens Ω^n in Hartree
      98              : !> \param fm_X X_ia^n on the process grid of mv_env, column n
      99              : ! **************************************************************************************************
     100            4 :    SUBROUTINE bse_davidson_tda(mv_env, bse_env, unit_nr, exc_ens, fm_X)
     101              : 
     102              :       TYPE(bse_matvec_env_type), INTENT(IN)              :: mv_env
     103              :       TYPE(bse_env_type), INTENT(IN)                     :: bse_env
     104              :       INTEGER, INTENT(IN)                                :: unit_nr
     105              :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:), &
     106              :          INTENT(OUT)                                     :: exc_ens
     107              :       TYPE(cp_fm_type), INTENT(OUT)                      :: fm_X
     108              : 
     109              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'bse_davidson_tda'
     110              : 
     111              :       INTEGER                                            :: block_size, handle, iter, k, m, m_max, &
     112              :                                                             n_act, n_cand, n_dependent, n_kernel, &
     113              :                                                             n_ov, n_req, n_restart, n_want, nt
     114              :       INTEGER, ALLOCATABLE, DIMENSION(:)                 :: selected
     115              :       LOGICAL                                            :: all_conv, has_prev, stalled
     116              :       LOGICAL, ALLOCATABLE, DIMENSION(:)                 :: conv, need
     117              :       REAL(KIND=dp)                                      :: dev, t_iter
     118              :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:)           :: dE, diag, res, theta, theta_prev, &
     119            4 :                                                             theta_sub
     120              :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :)        :: coef_restart, coef_restart_cand, &
     121            4 :                                                             coef_ritz, coef_ritz_theta, red_block
     122              :       TYPE(cp_blacs_env_type), POINTER                   :: diag_blacs_env
     123              :       TYPE(cp_fm_struct_type), POINTER                   :: fm_struct
     124              :       TYPE(cp_fm_type)                                   :: fm_AZ, fm_red_A, fm_work, fm_Z
     125              :       TYPE(mp_para_env_type), POINTER                    :: para_env
     126              : 
     127            4 :       CALL timeset(routineN, handle)
     128            4 :       CALL cite_reference(Davidson1975)
     129            4 :       CALL cite_reference(Stathopoulos1998)
     130            4 :       CALL cite_reference(Fukaya2014)
     131              : 
     132            4 :       para_env => mv_env%para_env
     133              :       ! every local_data use below takes whole rows per rank: the npe x 1 grid of bse_matvec_create
     134            4 :       CPASSERT(mv_env%blacs_env%num_pe(2) == 1)
     135              :       ! the trial vectors live on an npe x 1 grid, which is a bad one to diagonalize on
     136            4 :       NULLIFY (diag_blacs_env)
     137            4 :       CALL cp_blacs_env_create(diag_blacs_env, para_env)
     138            4 :       n_ov = mv_env%n_ov
     139            4 :       CALL davidson_sizes(bse_env, n_ov, unit_nr, n_want, n_act, block_size)
     140              : 
     141           12 :       ALLOCATE (diag(n_ov))
     142            4 :       CALL bse_matvec_diagonal(mv_env, bse_env%preconditioner, diag)
     143              : 
     144            4 :       CALL subspace_ceiling(bse_env, mv_env, driver_tda, n_act, block_size, unit_nr, m_max)
     145              : 
     146            4 :       CALL bse_matvec_vector_struct(mv_env, m_max, fm_struct)
     147            4 :       CALL cp_fm_create(fm_Z, fm_struct, name="fm_Z_davidson", set_zero=.TRUE.)
     148            4 :       CALL cp_fm_create(fm_AZ, fm_struct, name="fm_AZ_davidson", set_zero=.TRUE.)
     149            4 :       CALL cp_fm_struct_release(fm_struct)
     150            4 :       CALL bse_matvec_vector_struct(mv_env, MIN(2*n_act, m_max), fm_struct)
     151            4 :       CALL cp_fm_create(fm_work, fm_struct, name="fm_work_davidson", set_zero=.TRUE.)
     152            4 :       CALL cp_fm_struct_release(fm_struct)
     153            4 :       NULLIFY (fm_struct)
     154              :       CALL cp_fm_struct_create(fm_struct, para_env=para_env, context=diag_blacs_env, &
     155            4 :                                nrow_global=m_max, ncol_global=m_max)
     156            4 :       CALL cp_fm_create(fm_red_A, fm_struct, name="fm_red_A_davidson", set_zero=.TRUE.)
     157            4 :       CALL cp_fm_struct_release(fm_struct)
     158              : 
     159              :       ! c_mk and θ_k c_mk, the restart candidates (current and previous Ritz vectors) and the restart basis Q_pk
     160           40 :       ALLOCATE (coef_ritz(m_max, n_act), coef_restart_cand(m_max, 2*n_act), coef_ritz_theta(m_max, n_act))
     161           12 :       ALLOCATE (coef_restart(m_max, 2*n_act))
     162              :       ALLOCATE (theta(m_max), theta_prev(n_act), res(n_act), dE(n_act), conv(n_act), need(n_act), &
     163           44 :                 selected(n_act))
     164            4 :       coef_restart_cand(:, :) = 0.0_dp
     165            4 :       theta_prev(:) = 0.0_dp
     166            4 :       has_prev = .FALSE.
     167            4 :       stalled = .FALSE.
     168            4 :       n_restart = 0
     169            4 :       n_dependent = 0
     170              : 
     171            4 :       IF (bse_env%num_guess_transitions > 0) THEN
     172              :          CALL initial_guess_subblock(mv_env, bse_env, diag, n_act, m_max, deg_thresh, fm_Z, m, theta_sub, &
     173            2 :                                      unit_nr)
     174              :       ELSE
     175            2 :          CALL initial_guess(diag, n_act, m_max, deg_thresh, fm_Z, m)
     176              :       END IF
     177              :       ! both guess routines return orthonormal columns by construction; one Gram matrix checks it
     178            4 :       IF (extension_deviation(fm_Z, fm_Z, 0, m, para_env) > ortho_tol) THEN
     179            0 :          CPABORT("BSE Davidson: the initial guess is not orthonormal")
     180              :       END IF
     181              :       ! (A Z)_ia,m of the guess and Ar_mn = sum_ia Z_ia,m (A Z)_ia,n
     182            4 :       CALL bse_matvec_apply(mv_env, fm_Z, 1, m, fm_AZ)
     183            4 :       n_kernel = m
     184            4 :       CALL reduced_gram_blocks(fm_Z, m, fm_AZ, 1, m, block_size, para_env, fm_red_A)
     185              : 
     186            4 :       CALL print_iteration_header('Block Davidson iterations within the TDA:', unit_nr)
     187              : 
     188            4 :       all_conv = .FALSE.
     189           20 :       DO iter = 1, bse_env%max_iter
     190           20 :          t_iter = m_walltime()
     191              : 
     192              :          ! sum_n Ar_mn c_nk = θ_k c_mk, θ ascending
     193           20 :          CALL solve_reduced(fm_red_A, m, n_act, para_env, diag_blacs_env, theta, coef_ritz)
     194              : 
     195              :          ! thick restart onto the current and the previous Ritz vectors, no kernel application; with the
     196              :          ! restart basis Q_pk in coef_restart, Z_ia,k <- sum_p Z_ia,p Q_pk, A Z alike, Ar_kl <- sum_pq Q_pk Ar_pq Q_ql
     197           20 :          IF (m + block_size > m_max .AND. m > n_act .AND. m < n_ov) THEN
     198          706 :             coef_restart_cand(1:m, 1:n_act) = coef_ritz(1:m, 1:n_act)
     199            6 :             n_cand = n_act
     200            6 :             IF (has_prev) n_cand = 2*n_act
     201            6 :             CALL restart_basis(coef_restart_cand, m, n_cand, 2*n_act, coef_restart, k)
     202            6 :             CALL rotate_in_place(fm_Z, m, coef_restart, k, fm_work, fm_AZ)
     203            6 :             CALL reduced_rotate(fm_red_A, m, coef_restart, k, para_env, diag_blacs_env)
     204            6 :             m = k
     205            6 :             n_restart = n_restart + 1
     206            6 :             CALL solve_reduced(fm_red_A, m, n_act, para_env, diag_blacs_env, theta, coef_ritz)
     207              :          END IF
     208              : 
     209              :          ! r_ia,k = sum_m (A Z)_ia,m c_mk - θ_k sum_m Z_ia,m c_mk for all tracked roots k
     210          164 :          DO k = 1, n_act
     211         1736 :             coef_ritz_theta(1:m, k) = coef_ritz(1:m, k)*theta(k)
     212              :          END DO
     213         1736 :          CALL subspace_rotate(fm_AZ, m, coef_ritz(1:m, 1:n_act), n_act, fm_work, 1.0_dp, 0.0_dp)
     214         1736 :          CALL subspace_rotate(fm_Z, m, coef_ritz_theta(1:m, 1:n_act), n_act, fm_work, -1.0_dp, 1.0_dp)
     215           20 :          CALL column_norms(fm_work, 1, n_act, para_env, res)
     216              : 
     217              :          CALL convergence_step(bse_env, theta, theta_prev, res, m, n_ov, n_want, iter, t_iter, unit_nr, &
     218           20 :                                dE, conv, n_req, need)
     219           62 :          all_conv = .NOT. ANY(need)
     220           20 :          IF (all_conv) EXIT
     221              : 
     222           16 :          IF (iter == bse_env%max_iter) EXIT
     223              : 
     224              :          ! corrections for the lowest unconverged roots, t_ia,k = r_ia,k/(d_ia - θ_k)
     225           16 :          CALL select_roots(bse_env, need, res, MIN(block_size, m_max - m), selected, nt)
     226           16 :          CALL davidson_corrections(fm_work, selected(1:nt), theta, diag, fm_Z, m + 1)
     227           16 :          CALL extend_orthonormal(fm_Z, m, nt, para_env, n_dependent)
     228              :          ! no new vector: with an unchanged basis the next iteration finds dE = 0, which lets the roots that
     229              :          ! only wait for the energy criterion converge; a second empty pass means the residuals cannot improve
     230           16 :          IF (nt == 0 .AND. stalled) THEN
     231            0 :             CPABORT("BSE Davidson: correction vectors vanished before convergence")
     232              :          END IF
     233           16 :          stalled = nt == 0
     234              :          ! post-condition of the extension, one Gram matrix; the residual norms below rely on it
     235           16 :          IF (extension_deviation(fm_Z, fm_Z, m, nt, para_env) > ortho_tol) THEN
     236            0 :             CPABORT("BSE Davidson: the basis lost orthonormality")
     237              :          END IF
     238              : 
     239           16 :          IF (nt > 0) THEN
     240           14 :             CALL bse_matvec_apply(mv_env, fm_Z, m + 1, nt, fm_AZ)
     241           14 :             n_kernel = n_kernel + nt
     242              : 
     243              :             ! new columns Ar_mn = sum_ia Z_ia,m (A Z)_ia,n of the symmetric reduced matrix
     244           56 :             ALLOCATE (red_block(m + nt, nt))
     245           14 :             CALL subspace_gram(fm_Z, 1, m + nt, fm_AZ, m + 1, nt, para_env, red_block)
     246           14 :             CALL reduced_extend(fm_red_A, red_block, m, nt)
     247           14 :             DEALLOCATE (red_block)
     248              :          END IF
     249              : 
     250              :          ! the Ritz vectors of this iteration are the second block of restart candidates
     251         2956 :          coef_restart_cand(:, n_act + 1:2*n_act) = 0.0_dp
     252         1406 :          coef_restart_cand(1:m, n_act + 1:2*n_act) = coef_ritz(1:m, 1:n_act)
     253          130 :          has_prev = .TRUE.
     254          130 :          theta_prev(:) = theta(1:n_act)
     255           40 :          m = m + nt
     256              :       END DO
     257              : 
     258            4 :       IF (.NOT. all_conv) CALL abort_unconverged(theta, res, conv, need, n_req, unit_nr)
     259            4 :       IF (bse_env%bse_debug_print) CALL print_tracked_roots(theta, res, n_want, n_act, unit_nr)
     260              : 
     261            4 :       IF (bse_env%bse_debug_print) THEN
     262            0 :          dev = orthonormality_deviation(fm_Z, fm_Z, m, block_size, para_env)
     263            0 :          IF (unit_nr > 0) THEN
     264            0 :             WRITE (unit_nr, '(T2,A10,T13,A,T63,ES18.6)') 'BSE|DEBUG|', &
     265            0 :                'Max deviation of the basis from orthonormality', dev
     266              :          END IF
     267              :       END IF
     268              : 
     269            4 :       IF (ALLOCATED(theta_sub)) CALL check_guess_bound(theta_sub, theta, n_req, unit_nr)
     270            4 :       CALL print_summary(iter, n_kernel, n_restart, n_want, n_req, n_act, n_ov, unit_nr, n_dependent=n_dependent)
     271              : 
     272           12 :       ALLOCATE (exc_ens(n_want))
     273           18 :       exc_ens(:) = theta(1:n_want)
     274            4 :       CALL bse_matvec_vector_struct(mv_env, n_want, fm_struct)
     275            4 :       CALL cp_fm_create(fm_X, fm_struct, name="fm_X_davidson", set_zero=.TRUE.)
     276            4 :       CALL cp_fm_struct_release(fm_struct)
     277              :       ! X_ia^n = sum_m Z_ia,m c_mn
     278          154 :       CALL subspace_rotate(fm_Z, m, coef_ritz(1:m, 1:n_want), n_want, fm_X, 1.0_dp, 0.0_dp)
     279              : 
     280            4 :       CALL cp_fm_release(fm_Z)
     281            4 :       CALL cp_fm_release(fm_AZ)
     282            4 :       CALL cp_fm_release(fm_work)
     283            4 :       CALL cp_fm_release(fm_red_A)
     284            4 :       CALL cp_blacs_env_release(diag_blacs_env)
     285            0 :       DEALLOCATE (coef_ritz, coef_restart_cand, coef_ritz_theta, coef_restart, theta, theta_prev, res, dE, conv, &
     286            4 :                   need, selected, diag)
     287            4 :       IF (ALLOCATED(theta_sub)) DEALLOCATE (theta_sub)
     288              : 
     289            4 :       CALL timestop(handle)
     290              : 
     291           12 :    END SUBROUTINE bse_davidson_tda
     292              : 
     293              : ! **************************************************************************************************
     294              : !> \brief Block Davidson with thick restart for the NUM_EXC_EN lowest solutions of the full problem,
     295              : !>        written as sum_jb [(A+B)(A-B)]_ia,jb x_jb^n = (Ω^n)^2 x_ia^n with x^n = X^n - Y^n, which is
     296              : !>        symmetric in the inner product <u,v> = sum_ia,jb u_ia (A-B)_ia,jb v_jb. The basis V_ia,m is
     297              : !>        orthonormal in that inner product, W_ia,m = sum_jb (A-B)_ia,jb V_jb,m, and the reduced matrix
     298              : !>        Hr_mn = sum_ia,jb W_ia,m (A+B)_ia,jb W_jb,n has the eigenpairs ((Ω^k)^2, c_mk). Then
     299              : !>        x_ia^k = (Ω^k)^1/2 sum_m V_ia,m c_mk and y_ia^k = (X^k+Y^k)_ia = (Ω^k)^-1/2 sum_m W_ia,m c_mk
     300              : !>        obey sum_ia x_ia^k y_ia^k = 1, the residual is r_ia,k = sum_jb (A+B)_ia,jb y_jb^k - Ω^k x_ia^k
     301              : !>        and the correction t_ia,k = r_ia,k/(d_ia^2 - (Ω^k)^2), d_ia chosen by PRECONDITIONER.
     302              : !>        Arrays: Hr_mn in fm_red_M on the process grid, c_mk in coef_ritz, (Ω^k)^1/2 c_mk in coef_x,
     303              : !>        (Ω^k)^-1/2 c_mk in coef_y, Ω^k (Ω^k)^1/2 c_mk in coef_x_omega
     304              : !> \param mv_env slabs, prefactors and transition energies of the matrix-free A and B
     305              : !> \param bse_env bse_env carries the BSE_ITERAT settings and BSE_DEBUG_PRINT
     306              : !> \param unit_nr output unit, positive on the writing rank only
     307              : !> \param exc_ens Ω^n in Hartree
     308              : !> \param fm_X X_ia^n on the process grid of mv_env, column n; created only for abba_ok
     309              : !> \param fm_Y Y_ia^n, as fm_X
     310              : !> \param abba_status abba_indefinite if A-B is not positive definite on the trial space
     311              : !> \param ab_margin smallest eigenvalue of A-B on the trial space in Hartree
     312              : !> \param fm_X_tda converged TDA vectors as initial guess
     313              : ! **************************************************************************************************
     314            4 :    SUBROUTINE bse_davidson_abba_mk(mv_env, bse_env, unit_nr, exc_ens, fm_X, fm_Y, abba_status, &
     315              :                                    ab_margin, fm_X_tda)
     316              : 
     317              :       TYPE(bse_matvec_env_type), INTENT(IN)              :: mv_env
     318              :       TYPE(bse_env_type), INTENT(IN)                     :: bse_env
     319              :       INTEGER, INTENT(IN)                                :: unit_nr
     320              :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:), &
     321              :          INTENT(OUT)                                     :: exc_ens
     322              :       TYPE(cp_fm_type), INTENT(OUT)                      :: fm_X, fm_Y
     323              :       INTEGER, INTENT(OUT)                               :: abba_status
     324              :       REAL(KIND=dp), INTENT(OUT)                         :: ab_margin
     325              :       TYPE(cp_fm_type), INTENT(IN), OPTIONAL             :: fm_X_tda
     326              : 
     327              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'bse_davidson_abba_mk'
     328              : 
     329              :       INTEGER :: block_size, guess_col, handle, iter, k, m, m_max, n_act, n_cand, n_dependent, &
     330              :          n_guess_cols, n_kernel, n_ov, n_req, n_restart, n_seed, n_want, nrow_local, nt, nt_guess
     331            4 :       INTEGER, ALLOCATABLE, DIMENSION(:)                 :: selected
     332              :       LOGICAL                                            :: all_conv, has_prev, stalled
     333            4 :       LOGICAL, ALLOCATABLE, DIMENSION(:)                 :: conv, need
     334              :       REAL(KIND=dp)                                      :: dev, t_iter
     335            4 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:)           :: dE, diag, diag_sq, omega, omega_prev, &
     336            4 :                                                             omega_sq, res, theta, theta_sub
     337              :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :)        :: coef_restart, coef_restart_cand, &
     338            4 :                                                             coef_ritz, coef_x, coef_x_omega, &
     339            4 :                                                             coef_y, red_block
     340              :       TYPE(cp_blacs_env_type), POINTER                   :: diag_blacs_env
     341              :       TYPE(cp_fm_struct_type), POINTER                   :: fm_struct
     342              :       TYPE(cp_fm_type)                                   :: fm_metric, fm_metric_vec, fm_MW, &
     343              :                                                             fm_red_M, fm_scratch, fm_V, fm_W, &
     344              :                                                             fm_work
     345              :       TYPE(mp_para_env_type), POINTER                    :: para_env
     346              : 
     347            4 :       CALL timeset(routineN, handle)
     348            4 :       CALL cite_reference(Davidson1975)
     349            4 :       CALL cite_reference(Vecharynski2017)
     350            4 :       CALL cite_reference(Bai2012)
     351            4 :       CALL cite_reference(Stathopoulos1998)
     352            4 :       CALL cite_reference(Fukaya2014)
     353              : 
     354            4 :       abba_status = abba_ok
     355            4 :       ab_margin = 0.0_dp
     356            4 :       para_env => mv_env%para_env
     357              :       ! every local_data use below takes whole rows per rank: the npe x 1 grid of bse_matvec_create
     358            4 :       CPASSERT(mv_env%blacs_env%num_pe(2) == 1)
     359              :       ! the trial vectors live on an npe x 1 grid, which is a bad one to diagonalize on
     360            4 :       NULLIFY (diag_blacs_env)
     361            4 :       CALL cp_blacs_env_create(diag_blacs_env, para_env)
     362            4 :       n_ov = mv_env%n_ov
     363            4 :       CALL davidson_sizes(bse_env, n_ov, unit_nr, n_want, n_act, block_size)
     364              : 
     365           12 :       ALLOCATE (diag(n_ov))
     366            4 :       CALL bse_matvec_diagonal(mv_env, bse_env%preconditioner, diag)
     367              : 
     368            4 :       CALL subspace_ceiling(bse_env, mv_env, driver_mk, n_act, block_size, unit_nr, m_max)
     369              : 
     370            4 :       CALL bse_matvec_vector_struct(mv_env, m_max, fm_struct)
     371            4 :       CALL cp_fm_create(fm_V, fm_struct, name="fm_V_davidson", set_zero=.TRUE.)
     372            4 :       CALL cp_fm_create(fm_W, fm_struct, name="fm_W_davidson", set_zero=.TRUE.)
     373            4 :       CALL cp_fm_create(fm_MW, fm_struct, name="fm_MW_davidson", set_zero=.TRUE.)
     374            4 :       CALL cp_fm_struct_release(fm_struct)
     375            4 :       CALL bse_matvec_vector_struct(mv_env, MIN(2*n_act, m_max), fm_struct)
     376            4 :       CALL cp_fm_create(fm_work, fm_struct, name="fm_work_davidson", set_zero=.TRUE.)
     377            4 :       CALL cp_fm_struct_release(fm_struct)
     378            4 :       CALL bse_matvec_vector_struct(mv_env, block_size, fm_struct)
     379            4 :       CALL cp_fm_create(fm_scratch, fm_struct, name="fm_scratch_davidson", set_zero=.TRUE.)
     380            4 :       CALL cp_fm_struct_release(fm_struct)
     381            4 :       NULLIFY (fm_struct)
     382              :       CALL cp_fm_struct_create(fm_struct, para_env=para_env, context=diag_blacs_env, &
     383            4 :                                nrow_global=m_max, ncol_global=m_max)
     384            4 :       CALL cp_fm_create(fm_red_M, fm_struct, name="fm_red_M_davidson", set_zero=.TRUE.)
     385            4 :       CALL cp_fm_struct_release(fm_struct)
     386            4 :       CALL cp_fm_get_info(fm_V, nrow_local=nrow_local)
     387              : 
     388              :       ! c_mk, the restart candidates and basis, then (Ω^k)^1/2 c_mk, (Ω^k)^-1/2 c_mk and Ω^k (Ω^k)^1/2 c_mk
     389           40 :       ALLOCATE (coef_ritz(m_max, n_act), coef_restart_cand(m_max, 2*n_act), coef_restart(m_max, 2*n_act))
     390           28 :       ALLOCATE (coef_x(m_max, n_act), coef_y(m_max, n_act), coef_x_omega(m_max, n_act))
     391              :       ALLOCATE (theta(m_max), omega(n_act), omega_prev(n_act), res(n_act), dE(n_act), conv(n_act), &
     392           48 :                 need(n_act), selected(n_act))
     393            4 :       coef_restart_cand(:, :) = 0.0_dp
     394            4 :       omega_prev(:) = 0.0_dp
     395            4 :       has_prev = .FALSE.
     396            4 :       stalled = .FALSE.
     397            4 :       all_conv = .FALSE.
     398            4 :       n_restart = 0
     399            4 :       n_kernel = 0
     400            4 :       n_dependent = 0
     401              : 
     402              :       ! guess: the TDA vectors if given, then the eigenvectors of the exact guess block or unit
     403              :       ! vectors on the lowest entries of the diagonal
     404            4 :       n_seed = 0
     405            4 :       IF (PRESENT(fm_X_tda)) THEN
     406            0 :          CALL cp_fm_get_info(fm_X_tda, ncol_global=n_seed)
     407            0 :          n_seed = MIN(n_seed, n_act)
     408            0 :          CALL cp_fm_to_fm(fm_X_tda, fm_V, n_seed)
     409              :       END IF
     410            4 :       IF (bse_env%num_guess_transitions > 0) THEN
     411              :          CALL initial_guess_subblock(mv_env, bse_env, diag, n_act, m_max, deg_thresh, fm_V, n_guess_cols, theta_sub, &
     412            0 :                                      unit_nr, n_seed, abba_status, ab_margin)
     413              :       ELSE
     414            4 :          CALL initial_guess(diag, n_act, m_max, deg_thresh, fm_V, n_guess_cols, n_seed)
     415              :       END IF
     416              :       ! the corrections divide by d_ia^2 - (Ω^k)^2
     417            8 :       ALLOCATE (diag_sq(n_ov))
     418          196 :       diag_sq(:) = diag(:)**2
     419              : 
     420              :       ! the guess enters the basis in blocks of the scratch width
     421            4 :       m = 0
     422            4 :       guess_col = 1
     423            8 :       DO WHILE (guess_col <= n_guess_cols)
     424            4 :          nt_guess = MIN(block_size, n_guess_cols - guess_col + 1)
     425            4 :          nt = nt_guess
     426            4 :          IF (guess_col > m + 1) THEN
     427            0 :             CALL cp_fm_to_fm(fm_V, fm_V, nt, guess_col, m + 1)
     428              :          END IF
     429              :          CALL extend_basis_mk(mv_env, fm_V, fm_W, fm_MW, fm_scratch, m, nt, n_kernel, n_dependent, abba_status, &
     430            4 :                               ab_margin)
     431            4 :          IF (abba_status /= abba_ok) EXIT
     432            4 :          guess_col = guess_col + nt_guess
     433            4 :          m = m + nt
     434              :       END DO
     435              : 
     436            4 :       IF (abba_status == abba_ok) THEN
     437            4 :          fm_V%local_data(1:nrow_local, m + 1:n_guess_cols) = 0.0_dp
     438              :          ! Hr_mn = sum_ia W_ia,m (M W)_ia,n on the guess basis
     439            4 :          CALL reduced_gram_blocks(fm_W, m, fm_MW, 1, m, block_size, para_env, fm_red_M)
     440              : 
     441            4 :          CALL print_iteration_header('Block Davidson iterations for ABBA, (A+B)(A-B) x = E^2 x:', unit_nr)
     442              : 
     443           32 :          DO iter = 1, bse_env%max_iter
     444           32 :             t_iter = m_walltime()
     445              : 
     446              :             ! sum_n Hr_mn c_nk = θ_k c_mk with θ_k = (Ω^k)^2, ascending
     447           32 :             CALL solve_reduced(fm_red_M, m, n_act, para_env, diag_blacs_env, theta, coef_ritz)
     448              : 
     449              :             ! thick restart: V, W and MW are rotated alike by Q_pk in coef_restart, which keeps
     450              :             ! sum_ia V_ia,m W_ia,n = δ_mn, and Hr_kl <- sum_pq Q_pk Hr_pq Q_ql
     451           32 :             IF (m + block_size > m_max .AND. m > n_act .AND. m < n_ov) THEN
     452          648 :                coef_restart_cand(1:m, 1:n_act) = coef_ritz(1:m, 1:n_act)
     453            4 :                n_cand = n_act
     454            4 :                IF (has_prev) n_cand = 2*n_act
     455            4 :                CALL restart_basis(coef_restart_cand, m, n_cand, 2*n_act, coef_restart, k)
     456            4 :                CALL rotate_in_place(fm_V, m, coef_restart, k, fm_work, fm_W, fm_MW)
     457            4 :                CALL reduced_rotate(fm_red_M, m, coef_restart, k, para_env, diag_blacs_env)
     458            4 :                m = k
     459            4 :                n_restart = n_restart + 1
     460            4 :                CALL solve_reduced(fm_red_M, m, n_act, para_env, diag_blacs_env, theta, coef_ritz)
     461              :             END IF
     462              : 
     463              :             ! a Ritz value bounds an eigenvalue of (A+B)(A-B) from above
     464           32 :             IF (theta(1) <= 0.0_dp) THEN
     465              :                CALL cp_abort(__LOCATION__, &
     466              :                              "BSE Davidson (MK_DAVIDSON): negative squared excitation energy. Matrix "// &
     467            0 :                              "(A+B) is not positive definite, or the basis lost its orthonormality.")
     468              :             END IF
     469          256 :             omega(:) = SQRT(theta(1:n_act))
     470              : 
     471              :             ! r_ia,k = sum_m (M W)_ia,m c_mk (Ω^k)^-1/2 - Ω^k (Ω^k)^1/2 sum_m V_ia,m c_mk
     472          256 :             DO k = 1, n_act
     473         3584 :                coef_y(1:m, k) = coef_ritz(1:m, k)/SQRT(omega(k))
     474         3616 :                coef_x_omega(1:m, k) = coef_ritz(1:m, k)*omega(k)*SQRT(omega(k))
     475              :             END DO
     476         3616 :             CALL subspace_rotate(fm_MW, m, coef_y(1:m, 1:n_act), n_act, fm_work, 1.0_dp, 0.0_dp)
     477         3616 :             CALL subspace_rotate(fm_V, m, coef_x_omega(1:m, 1:n_act), n_act, fm_work, -1.0_dp, 1.0_dp)
     478           32 :             CALL column_norms(fm_work, 1, n_act, para_env, res)
     479              : 
     480              :             CALL convergence_step(bse_env, omega, omega_prev, res, m, n_ov, n_want, iter, t_iter, unit_nr, &
     481           32 :                                   dE, conv, n_req, need)
     482           76 :             all_conv = .NOT. ANY(need)
     483           32 :             IF (all_conv) EXIT
     484              : 
     485           28 :             IF (iter == bse_env%max_iter) EXIT
     486              : 
     487              :             ! corrections t_ia,k = r_ia,k/(d_ia^2 - (Ω^k)^2) for the lowest unconverged roots
     488           28 :             CALL select_roots(bse_env, need, res, MIN(block_size, m_max - m), selected, nt)
     489           28 :             CALL davidson_corrections(fm_work, selected(1:nt), theta, diag_sq, fm_V, m + 1)
     490              :             CALL extend_basis_mk(mv_env, fm_V, fm_W, fm_MW, fm_scratch, m, nt, n_kernel, n_dependent, abba_status, &
     491           28 :                                  ab_margin)
     492           28 :             IF (abba_status /= abba_ok) EXIT
     493              :             ! no new vector: with an unchanged basis the next iteration finds dE = 0, which lets the roots that
     494              :             ! only wait for the energy criterion converge; a second empty pass means the residuals cannot improve
     495           28 :             IF (nt == 0 .AND. stalled) THEN
     496            0 :                CPABORT("BSE Davidson: correction vectors vanished before convergence")
     497              :             END IF
     498           28 :             stalled = nt == 0
     499              : 
     500           28 :             IF (nt > 0) THEN
     501              :                ! new columns Hr_mn = sum_ia W_ia,m (M W)_ia,n of the symmetric reduced matrix
     502          112 :                ALLOCATE (red_block(m + nt, nt))
     503           28 :                CALL subspace_gram(fm_W, 1, m + nt, fm_MW, m + 1, nt, para_env, red_block)
     504           28 :                CALL reduced_extend(fm_red_M, red_block, m, nt)
     505           28 :                DEALLOCATE (red_block)
     506              :             END IF
     507              : 
     508              :             ! the Ritz vectors of this iteration are the second block of restart candidates
     509         5712 :             coef_restart_cand(:, n_act + 1:2*n_act) = 0.0_dp
     510         3080 :             coef_restart_cand(1:m, n_act + 1:2*n_act) = coef_ritz(1:m, 1:n_act)
     511          224 :             has_prev = .TRUE.
     512          224 :             omega_prev(:) = omega(:)
     513           64 :             m = m + nt
     514              :          END DO
     515              :       END IF
     516              : 
     517            4 :       IF (abba_status == abba_ok) THEN
     518            4 :          IF (.NOT. all_conv) CALL abort_unconverged(omega, res, conv, need, n_req, unit_nr)
     519            4 :          IF (bse_env%bse_debug_print) CALL print_tracked_roots(omega, res, n_want, n_act, unit_nr)
     520              : 
     521            4 :          IF (bse_env%bse_debug_print) THEN
     522            2 :             dev = orthonormality_deviation(fm_V, fm_W, m, block_size, para_env)
     523            2 :             IF (unit_nr > 0) THEN
     524            1 :                WRITE (unit_nr, '(T2,A10,T13,A,T63,ES18.6)') 'BSE|DEBUG|', &
     525            2 :                   'Max deviation of the basis from orthonormality', dev
     526              :             END IF
     527              :          END IF
     528              : 
     529              :          ! with sum_ia V_ia,m W_ia,n = δ_mn the smallest eigenvalue of A-B on the span of V is the
     530              :          ! inverse of the largest eigenvalue of the metric sum_ia V_ia,m V_ia,n
     531            4 :          NULLIFY (fm_struct)
     532              :          CALL cp_fm_struct_create(fm_struct, para_env=para_env, context=diag_blacs_env, &
     533            4 :                                   nrow_global=m, ncol_global=m)
     534            4 :          CALL cp_fm_create(fm_metric, fm_struct, name="bse_basis_metric")
     535            4 :          CALL cp_fm_create(fm_metric_vec, fm_struct, name="bse_basis_metric_vectors")
     536            4 :          CALL cp_fm_struct_release(fm_struct)
     537            4 :          CALL reduced_gram_blocks(fm_V, m, fm_V, 1, m, block_size, para_env, fm_metric)
     538           12 :          ALLOCATE (omega_sq(m))
     539            4 :          omega_sq(:) = 0.0_dp
     540            4 :          CALL choose_eigv_solver(fm_metric, fm_metric_vec, omega_sq)
     541            4 :          ab_margin = 1.0_dp/omega_sq(m)
     542            4 :          DEALLOCATE (omega_sq)
     543            4 :          CALL cp_fm_release(fm_metric)
     544            4 :          CALL cp_fm_release(fm_metric_vec)
     545              : 
     546            4 :          IF (ALLOCATED(theta_sub)) CALL check_guess_bound(theta_sub, omega, n_req, unit_nr)
     547            4 :          CALL print_summary(iter, n_kernel, n_restart, n_want, n_req, n_act, n_ov, unit_nr, ab_margin, n_dependent)
     548              : 
     549              :          ! x_ia^n = (Ω^n)^1/2 sum_m V_ia,m c_mn, y_ia^n = (Ω^n)^-1/2 sum_m W_ia,m c_mn,
     550              :          ! X_ia^n = (y_ia^n + x_ia^n)/2, Y_ia^n = (y_ia^n - x_ia^n)/2
     551           12 :          ALLOCATE (exc_ens(n_want))
     552           16 :          exc_ens(:) = omega(1:n_want)
     553           16 :          DO k = 1, n_want
     554          228 :             coef_x(1:m, k) = coef_ritz(1:m, k)*SQRT(omega(k))
     555          232 :             coef_y(1:m, k) = coef_ritz(1:m, k)/SQRT(omega(k))
     556              :          END DO
     557            4 :          CALL bse_matvec_vector_struct(mv_env, n_want, fm_struct)
     558            4 :          CALL cp_fm_create(fm_X, fm_struct, name="fm_X_davidson", set_zero=.TRUE.)
     559            4 :          CALL cp_fm_create(fm_Y, fm_struct, name="fm_Y_davidson", set_zero=.TRUE.)
     560            4 :          CALL cp_fm_struct_release(fm_struct)
     561          232 :          CALL subspace_rotate(fm_W, m, coef_y(1:m, 1:n_want), n_want, fm_X, 0.5_dp, 0.0_dp)
     562          232 :          CALL subspace_rotate(fm_V, m, coef_x(1:m, 1:n_want), n_want, fm_X, 0.5_dp, 1.0_dp)
     563          232 :          CALL subspace_rotate(fm_W, m, coef_y(1:m, 1:n_want), n_want, fm_Y, 0.5_dp, 0.0_dp)
     564          236 :          CALL subspace_rotate(fm_V, m, coef_x(1:m, 1:n_want), n_want, fm_Y, -0.5_dp, 1.0_dp)
     565              :       END IF
     566              : 
     567            4 :       CALL cp_fm_release(fm_V)
     568            4 :       CALL cp_fm_release(fm_W)
     569            4 :       CALL cp_fm_release(fm_MW)
     570            4 :       CALL cp_fm_release(fm_work)
     571            4 :       CALL cp_fm_release(fm_scratch)
     572            4 :       CALL cp_fm_release(fm_red_M)
     573            4 :       CALL cp_blacs_env_release(diag_blacs_env)
     574            0 :       DEALLOCATE (coef_ritz, coef_restart_cand, coef_x, coef_y, coef_x_omega, coef_restart, theta, omega, omega_prev, &
     575            4 :                   res, dE, conv, need, selected, diag, diag_sq)
     576            4 :       IF (ALLOCATED(theta_sub)) DEALLOCATE (theta_sub)
     577              : 
     578            4 :       CALL timestop(handle)
     579              : 
     580           16 :    END SUBROUTINE bse_davidson_abba_mk
     581              : 
     582              : ! **************************************************************************************************
     583              : !> \brief Block Davidson with thick restart for the NUM_EXC_EN lowest solutions of the full problem
     584              : !>        in the paired form of Olsen and Stratmann: with x^n = X^n - Y^n, y^n = X^n + Y^n, M = A+B and
     585              : !>        K = A-B, sum_jb M_ia,jb y_jb^n = Ω^n x_ia^n and sum_jb K_ia,jb x_jb^n = Ω^n y_ia^n. One
     586              : !>        orthonormal basis b_ia,m carries both vectors: Mr_mn = sum_ia b_ia,m (M b)_ia,n and
     587              : !>        Kr_mn = sum_ia b_ia,m (K b)_ia,n are solved by solve_reduced_paired for Ω^k, R_mk and L_mk with
     588              : !>        y_ia^k = sum_m b_ia,m R_mk, x_ia^k = sum_m b_ia,m L_mk and sum_ia x_ia^k y_ia^k = 1. The basis
     589              : !>        grows by the corrections t_ia,k = r_ia,k/(d_ia - Ω^k) of both residuals,
     590              : !>        rR_ia,k = sum_m (M b)_ia,m R_mk - Ω^k x_ia^k and rL_ia,k = sum_m (K b)_ia,m L_mk - Ω^k y_ia^k,
     591              : !>        d_ia chosen by PRECONDITIONER; the rR block enters before the rL block, which is nearly
     592              : !>        parallel to it for a small B. Arrays: Mr_mn and Kr_mn in fm_red_M and fm_red_K on the process
     593              : !>        grid, R_mk in coef_right, L_mk in coef_left
     594              : !> \param mv_env slabs, prefactors and transition energies of the matrix-free A and B
     595              : !> \param bse_env bse_env carries the BSE_ITERAT settings and BSE_DEBUG_PRINT
     596              : !> \param unit_nr output unit, positive on the writing rank only
     597              : !> \param exc_ens Ω^n in Hartree
     598              : !> \param fm_X X_ia^n on the process grid of mv_env, column n; created only for abba_ok
     599              : !> \param fm_Y Y_ia^n, as fm_X
     600              : !> \param abba_status abba_indefinite if A-B is not positive definite on the trial space
     601              : !> \param ab_margin smallest eigenvalue of A-B on the trial space in Hartree
     602              : !> \param fm_X_tda converged TDA vectors as initial guess, x = y = X
     603              : ! **************************************************************************************************
     604            2 :    SUBROUTINE bse_davidson_abba_os(mv_env, bse_env, unit_nr, exc_ens, fm_X, fm_Y, abba_status, &
     605              :                                    ab_margin, fm_X_tda)
     606              : 
     607              :       TYPE(bse_matvec_env_type), INTENT(IN)              :: mv_env
     608              :       TYPE(bse_env_type), INTENT(IN)                     :: bse_env
     609              :       INTEGER, INTENT(IN)                                :: unit_nr
     610              :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:), &
     611              :          INTENT(OUT)                                     :: exc_ens
     612              :       TYPE(cp_fm_type), INTENT(OUT)                      :: fm_X, fm_Y
     613              :       INTEGER, INTENT(OUT)                               :: abba_status
     614              :       REAL(KIND=dp), INTENT(OUT)                         :: ab_margin
     615              :       TYPE(cp_fm_type), INTENT(IN), OPTIONAL             :: fm_X_tda
     616              : 
     617              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'bse_davidson_abba_os'
     618              : 
     619              :       INTEGER :: block_size, guess_col, handle, iter, k, m, m_max, n_act, n_cand, n_dependent, &
     620              :          n_guess_cols, n_kernel, n_ov, n_pair, n_req, n_restart, n_seed, n_want, nrow_local, nt, &
     621              :          nt_guess, nt_L, nt_R, nt_sel
     622            2 :       INTEGER, ALLOCATABLE, DIMENSION(:)                 :: selected
     623              :       LOGICAL                                            :: all_conv, has_prev, stalled
     624            2 :       LOGICAL, ALLOCATABLE, DIMENSION(:)                 :: conv, need
     625              :       REAL(KIND=dp)                                      :: dev, kr_min, t_iter
     626            2 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:)           :: dE, diag, omega, omega_prev, res, res_L, &
     627            2 :                                                             theta_sub
     628              :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :)        :: coef_left, coef_restart, &
     629              :                                                             coef_restart_cand, coef_right, &
     630            2 :                                                             coef_work, red_block_K, red_block_M
     631              :       TYPE(cp_blacs_env_type), POINTER                   :: diag_blacs_env
     632              :       TYPE(cp_fm_struct_type), POINTER                   :: fm_struct
     633              :       TYPE(cp_fm_type)                                   :: fm_b, fm_Kb, fm_Mb, fm_red_K, fm_red_M, &
     634              :                                                             fm_scratch, fm_work
     635              :       TYPE(mp_para_env_type), POINTER                    :: para_env
     636              : 
     637            2 :       CALL timeset(routineN, handle)
     638            2 :       CALL cite_reference(Davidson1975)
     639            2 :       CALL cite_reference(Olsen1988)
     640            2 :       CALL cite_reference(Stratmann1998)
     641            2 :       CALL cite_reference(Bai2012)
     642            2 :       CALL cite_reference(Stathopoulos1998)
     643            2 :       CALL cite_reference(Fukaya2014)
     644              : 
     645            2 :       abba_status = abba_ok
     646            2 :       ab_margin = 0.0_dp
     647            2 :       para_env => mv_env%para_env
     648              :       ! every local_data use below takes whole rows per rank: the npe x 1 grid of bse_matvec_create
     649            2 :       CPASSERT(mv_env%blacs_env%num_pe(2) == 1)
     650              :       ! the trial vectors live on an npe x 1 grid, which is a bad one to diagonalize on
     651            2 :       NULLIFY (diag_blacs_env)
     652            2 :       CALL cp_blacs_env_create(diag_blacs_env, para_env)
     653            2 :       n_ov = mv_env%n_ov
     654            2 :       CALL davidson_sizes(bse_env, n_ov, unit_nr, n_want, n_act, block_size)
     655              : 
     656            6 :       ALLOCATE (diag(n_ov))
     657            2 :       CALL bse_matvec_diagonal(mv_env, bse_env%preconditioner, diag)
     658              : 
     659            2 :       CALL subspace_ceiling(bse_env, mv_env, driver_os, n_act, block_size, unit_nr, m_max)
     660              : 
     661            2 :       CALL bse_matvec_vector_struct(mv_env, m_max, fm_struct)
     662            2 :       CALL cp_fm_create(fm_b, fm_struct, name="fm_b_davidson", set_zero=.TRUE.)
     663            2 :       CALL cp_fm_create(fm_Mb, fm_struct, name="fm_Mb_davidson", set_zero=.TRUE.)
     664            2 :       CALL cp_fm_create(fm_Kb, fm_struct, name="fm_Kb_davidson", set_zero=.TRUE.)
     665            2 :       CALL cp_fm_struct_release(fm_struct)
     666              :       ! both residual blocks, or the restart basis
     667            2 :       CALL bse_matvec_vector_struct(mv_env, MAX(2*n_act, MIN(4*n_act, m_max)), fm_struct)
     668            2 :       CALL cp_fm_create(fm_work, fm_struct, name="fm_work_davidson", set_zero=.TRUE.)
     669            2 :       CALL cp_fm_struct_release(fm_struct)
     670            2 :       CALL bse_matvec_vector_struct(mv_env, 2*block_size, fm_struct)
     671            2 :       CALL cp_fm_create(fm_scratch, fm_struct, name="fm_scratch_davidson", set_zero=.TRUE.)
     672            2 :       CALL cp_fm_struct_release(fm_struct)
     673            2 :       NULLIFY (fm_struct)
     674              :       CALL cp_fm_struct_create(fm_struct, para_env=para_env, context=diag_blacs_env, &
     675            2 :                                nrow_global=m_max, ncol_global=m_max)
     676            2 :       CALL cp_fm_create(fm_red_M, fm_struct, name="fm_red_M_davidson", set_zero=.TRUE.)
     677            2 :       CALL cp_fm_create(fm_red_K, fm_struct, name="fm_red_K_davidson", set_zero=.TRUE.)
     678            2 :       CALL cp_fm_struct_release(fm_struct)
     679            2 :       CALL cp_fm_get_info(fm_b, nrow_local=nrow_local)
     680              : 
     681              :       ! R_mk, L_mk and a work block, then the restart candidates (current and previous pairs) and the basis Q_pk
     682           16 :       ALLOCATE (coef_right(m_max, n_act), coef_left(m_max, n_act), coef_work(m_max, n_act))
     683           14 :       ALLOCATE (coef_restart_cand(m_max, 4*n_act), coef_restart(m_max, 4*n_act))
     684              :       ALLOCATE (omega(n_act), omega_prev(n_act), res(n_act), res_L(n_act), dE(n_act), conv(n_act), &
     685           22 :                 need(n_act), selected(n_act))
     686            2 :       coef_restart_cand(:, :) = 0.0_dp
     687            2 :       omega_prev(:) = 0.0_dp
     688            2 :       kr_min = 0.0_dp
     689            2 :       has_prev = .FALSE.
     690            2 :       stalled = .FALSE.
     691            2 :       all_conv = .FALSE.
     692            2 :       n_restart = 0
     693            2 :       n_kernel = 0
     694            2 :       n_dependent = 0
     695              : 
     696              :       ! guess: the TDA vectors if given (each a pair by itself), then the pairs x_k, y_k of the exact
     697              :       ! guess block or unit vectors on the lowest entries of the diagonal
     698            2 :       n_seed = 0
     699            2 :       IF (PRESENT(fm_X_tda)) THEN
     700            0 :          CALL cp_fm_get_info(fm_X_tda, ncol_global=n_seed)
     701            0 :          n_seed = MIN(n_seed, n_act)
     702            0 :          CALL cp_fm_to_fm(fm_X_tda, fm_b, n_seed)
     703              :       END IF
     704            2 :       n_pair = 0
     705            2 :       IF (bse_env%num_guess_transitions > 0) THEN
     706              :          CALL initial_guess_subblock(mv_env, bse_env, diag, n_act, m_max, deg_thresh, fm_b, n_guess_cols, theta_sub, &
     707            0 :                                      unit_nr, n_seed, abba_status, ab_margin, n_pair)
     708              :       ELSE
     709            2 :          CALL initial_guess(diag, n_act, m_max, deg_thresh, fm_b, n_guess_cols, n_seed)
     710              :       END IF
     711            2 :       n_guess_cols = n_guess_cols + n_pair
     712              : 
     713              :       ! the guess enters the basis in blocks of the scratch width
     714            2 :       m = 0
     715            2 :       guess_col = 1
     716            4 :       DO WHILE (guess_col <= n_guess_cols)
     717            2 :          nt_guess = MIN(2*block_size, n_guess_cols - guess_col + 1)
     718            2 :          nt = nt_guess
     719            2 :          IF (guess_col > m + 1) THEN
     720            0 :             CALL cp_fm_to_fm(fm_b, fm_b, nt, guess_col, m + 1)
     721              :          END IF
     722            2 :          CALL extend_basis_os(mv_env, fm_b, fm_Mb, fm_Kb, fm_scratch, m, nt, n_kernel, n_dependent)
     723            2 :          guess_col = guess_col + nt_guess
     724            2 :          m = m + nt
     725              :       END DO
     726              : 
     727            2 :       IF (abba_status == abba_ok) THEN
     728            2 :          fm_b%local_data(1:nrow_local, m + 1:n_guess_cols) = 0.0_dp
     729              :          ! Mr_mn = sum_ia b_ia,m (M b)_ia,n and Kr_mn = sum_ia b_ia,m (K b)_ia,n on the guess basis
     730            2 :          CALL reduced_gram_blocks(fm_b, m, fm_Mb, 1, m, block_size, para_env, fm_red_M)
     731            2 :          CALL reduced_gram_blocks(fm_b, m, fm_Kb, 1, m, block_size, para_env, fm_red_K)
     732              : 
     733              :          CALL print_iteration_header('Block Davidson iterations for ABBA, Olsen-Stratmann paired subspace:', &
     734            2 :                                      unit_nr)
     735              : 
     736           18 :          DO iter = 1, bse_env%max_iter
     737           18 :             t_iter = m_walltime()
     738              : 
     739              :             ! Ω^k ascending with the coefficients R_mk of y^k and L_mk of x^k, sum_m R_mk L_mk = 1
     740              :             CALL solve_reduced_paired(fm_red_M, fm_red_K, m, n_act, para_env, omega, coef_right, coef_left, kr_min, &
     741           18 :                                       abba_status, diag_blacs_env)
     742              :             ! the smallest eigenvalue of A-B on the span of b is that of the last Kr
     743           18 :             ab_margin = kr_min
     744           18 :             IF (abba_status /= abba_ok) EXIT
     745              : 
     746              :             ! thick restart: b, Mb and Kb are rotated alike; the current pairs come first, so that
     747              :             ! they survive the cap that leaves room for one block of corrections; with Q_pk in
     748              :             ! coef_restart, b_ia,k <- sum_p b_ia,p Q_pk and Mr_kl <- sum_pq Q_pk Mr_pq Q_ql, Kr alike
     749           18 :             IF (m + 2*block_size > m_max .AND. m > 2*n_act .AND. m < n_ov) THEN
     750         2214 :                coef_restart_cand(1:m, 1:n_act) = coef_right(1:m, :)
     751         2214 :                coef_restart_cand(1:m, n_act + 1:2*n_act) = coef_left(1:m, :)
     752           16 :                n_cand = 2*n_act
     753           16 :                IF (has_prev) n_cand = 4*n_act
     754           16 :                CALL restart_basis(coef_restart_cand, m, n_cand, m_max - 2*block_size, coef_restart, k)
     755           16 :                CALL rotate_in_place(fm_b, m, coef_restart, k, fm_work, fm_Mb, fm_Kb)
     756           16 :                CALL reduced_rotate(fm_red_M, m, coef_restart, k, para_env, diag_blacs_env)
     757           16 :                CALL reduced_rotate(fm_red_K, m, coef_restart, k, para_env, diag_blacs_env)
     758           16 :                m = k
     759           16 :                n_restart = n_restart + 1
     760              :                CALL solve_reduced_paired(fm_red_M, fm_red_K, m, n_act, para_env, omega, coef_right, coef_left, kr_min, &
     761           16 :                                          abba_status, diag_blacs_env)
     762           16 :                ab_margin = kr_min
     763           16 :                IF (abba_status /= abba_ok) EXIT
     764              :             END IF
     765              : 
     766              :             ! rR_ia,k = sum_m (M b)_ia,m R_mk - Ω^k sum_m b_ia,m L_mk into the columns 1..n_act and
     767              :             ! rL_ia,k = sum_m (K b)_ia,m L_mk - Ω^k sum_m b_ia,m R_mk into the columns n_act+1..2 n_act
     768          144 :             DO k = 1, n_act
     769         1810 :                coef_work(1:m, k) = coef_left(1:m, k)*omega(k)
     770              :             END DO
     771         1810 :             CALL subspace_rotate(fm_Mb, m, coef_right(1:m, 1:n_act), n_act, fm_work, 1.0_dp, 0.0_dp)
     772         1810 :             CALL subspace_rotate(fm_b, m, coef_work(1:m, 1:n_act), n_act, fm_work, -1.0_dp, 1.0_dp)
     773          144 :             DO k = 1, n_act
     774         1810 :                coef_work(1:m, k) = coef_right(1:m, k)*omega(k)
     775              :             END DO
     776         1810 :             CALL subspace_rotate(fm_Kb, m, coef_left(1:m, 1:n_act), n_act, fm_work, 1.0_dp, 0.0_dp, n_act + 1)
     777         1810 :             CALL subspace_rotate(fm_b, m, coef_work(1:m, 1:n_act), n_act, fm_work, -1.0_dp, 1.0_dp, n_act + 1)
     778           18 :             CALL column_norms(fm_work, 1, n_act, para_env, res)
     779           18 :             CALL column_norms(fm_work, n_act + 1, n_act, para_env, res_L)
     780          144 :             res(:) = MAX(res(:), res_L(:))
     781              : 
     782              :             CALL convergence_step(bse_env, omega, omega_prev, res, m, n_ov, n_want, iter, t_iter, unit_nr, &
     783           18 :                                   dE, conv, n_req, need)
     784           32 :             all_conv = .NOT. ANY(need)
     785           18 :             IF (all_conv) EXIT
     786              : 
     787           16 :             IF (iter == bse_env%max_iter) EXIT
     788              : 
     789              :             ! corrections t_ia,k = r_ia,k/(d_ia - Ω^k) of the lowest unconverged roots: the rR block
     790              :             ! against the basis, then the rL block of the same roots against the extended basis;
     791              :             ! both fit the room, which is odd only when the ceiling is the number of transitions
     792           16 :             CALL select_roots(bse_env, need, res, MIN(block_size, (m_max - m + 1)/2), selected, nt_sel)
     793           16 :             nt_R = nt_sel
     794           16 :             CALL davidson_corrections(fm_work, selected(1:nt_R), omega, diag, fm_b, m + 1)
     795           16 :             CALL extend_basis_os(mv_env, fm_b, fm_Mb, fm_Kb, fm_scratch, m, nt_R, n_kernel, n_dependent)
     796           16 :             nt_L = MIN(nt_sel, m_max - m - nt_R)
     797           16 :             CALL davidson_corrections(fm_work, selected(1:nt_L), omega, diag, fm_b, m + nt_R + 1, n_act)
     798           16 :             CALL extend_basis_os(mv_env, fm_b, fm_Mb, fm_Kb, fm_scratch, m + nt_R, nt_L, n_kernel, n_dependent)
     799           16 :             nt = nt_R + nt_L
     800              :             ! no new vector: with an unchanged basis the next iteration finds dE = 0, which lets the roots that
     801              :             ! only wait for the energy criterion converge; a second empty pass means the residuals cannot improve
     802           16 :             IF (nt == 0 .AND. stalled) THEN
     803            0 :                CPABORT("BSE Davidson: correction vectors vanished before convergence")
     804              :             END IF
     805           16 :             stalled = nt == 0
     806              : 
     807           16 :             IF (nt > 0) THEN
     808              :                ! new columns n of Mr_mn = sum_ia b_ia,m (M b)_ia,n and Kr_mn = sum_ia b_ia,m (K b)_ia,n
     809           96 :                ALLOCATE (red_block_M(m + nt, nt), red_block_K(m + nt, nt))
     810           16 :                CALL subspace_gram(fm_b, 1, m + nt, fm_Mb, m + 1, nt, para_env, red_block_M)
     811           16 :                CALL subspace_gram(fm_b, 1, m + nt, fm_Kb, m + 1, nt, para_env, red_block_K)
     812           16 :                CALL reduced_extend(fm_red_M, red_block_M, m, nt)
     813           16 :                CALL reduced_extend(fm_red_K, red_block_K, m, nt)
     814           16 :                DEALLOCATE (red_block_M, red_block_K)
     815              :             END IF
     816              : 
     817              :             ! the pairs of this iteration are the second block of restart candidates
     818         6512 :             coef_restart_cand(:, 2*n_act + 1:4*n_act) = 0.0_dp
     819         1598 :             coef_restart_cand(1:m, 2*n_act + 1:3*n_act) = coef_right(1:m, :)
     820         1598 :             coef_restart_cand(1:m, 3*n_act + 1:4*n_act) = coef_left(1:m, :)
     821          128 :             has_prev = .TRUE.
     822          128 :             omega_prev(:) = omega(:)
     823           54 :             m = m + nt
     824              :          END DO
     825              :       END IF
     826              : 
     827            2 :       IF (abba_status == abba_ok) THEN
     828            2 :          IF (.NOT. all_conv) CALL abort_unconverged(omega, res, conv, need, n_req, unit_nr)
     829            2 :          IF (bse_env%bse_debug_print) CALL print_tracked_roots(omega, res, n_want, n_act, unit_nr)
     830              : 
     831            2 :          IF (bse_env%bse_debug_print) THEN
     832            0 :             dev = orthonormality_deviation(fm_b, fm_b, m, block_size, para_env)
     833            0 :             IF (unit_nr > 0) THEN
     834            0 :                WRITE (unit_nr, '(T2,A10,T13,A,T63,ES18.6)') 'BSE|DEBUG|', &
     835            0 :                   'Max deviation of the basis from orthonormality', dev
     836              :             END IF
     837              :          END IF
     838              : 
     839            2 :          IF (ALLOCATED(theta_sub)) CALL check_guess_bound(theta_sub, omega, n_req, unit_nr)
     840            2 :          CALL print_summary(iter, n_kernel, n_restart, n_want, n_req, n_act, n_ov, unit_nr, ab_margin, n_dependent)
     841              : 
     842              :          ! X_ia^n = sum_m b_ia,m (R_mn + L_mn)/2, Y_ia^n = sum_m b_ia,m (R_mn - L_mn)/2
     843            6 :          ALLOCATE (exc_ens(n_want))
     844            8 :          exc_ens(:) = omega(1:n_want)
     845            2 :          CALL bse_matvec_vector_struct(mv_env, n_want, fm_struct)
     846            2 :          CALL cp_fm_create(fm_X, fm_struct, name="fm_X_davidson", set_zero=.TRUE.)
     847            2 :          CALL cp_fm_create(fm_Y, fm_struct, name="fm_Y_davidson", set_zero=.TRUE.)
     848            2 :          CALL cp_fm_struct_release(fm_struct)
     849           92 :          coef_work(1:m, 1:n_want) = 0.5_dp*(coef_right(1:m, 1:n_want) + coef_left(1:m, 1:n_want))
     850           92 :          CALL subspace_rotate(fm_b, m, coef_work(1:m, 1:n_want), n_want, fm_X, 1.0_dp, 0.0_dp)
     851           92 :          coef_work(1:m, 1:n_want) = 0.5_dp*(coef_right(1:m, 1:n_want) - coef_left(1:m, 1:n_want))
     852           92 :          CALL subspace_rotate(fm_b, m, coef_work(1:m, 1:n_want), n_want, fm_Y, 1.0_dp, 0.0_dp)
     853              :       END IF
     854              : 
     855            2 :       CALL cp_fm_release(fm_b)
     856            2 :       CALL cp_fm_release(fm_Mb)
     857            2 :       CALL cp_fm_release(fm_Kb)
     858            2 :       CALL cp_fm_release(fm_work)
     859            2 :       CALL cp_fm_release(fm_scratch)
     860            2 :       CALL cp_fm_release(fm_red_M)
     861            2 :       CALL cp_fm_release(fm_red_K)
     862            2 :       CALL cp_blacs_env_release(diag_blacs_env)
     863            0 :       DEALLOCATE (coef_right, coef_left, coef_work, coef_restart_cand, coef_restart, omega, omega_prev, res, res_L, &
     864            2 :                   dE, conv, need, selected, diag)
     865            2 :       IF (ALLOCATED(theta_sub)) DEALLOCATE (theta_sub)
     866              : 
     867            2 :       CALL timestop(handle)
     868              : 
     869            8 :    END SUBROUTINE bse_davidson_abba_os
     870              : 
     871              : ! **************************************************************************************************
     872              : !> \brief Makes the nt columns T that follow column m of V orthonormal in the (A-B) inner product and
     873              : !>        stores their products: T_ia,k <- T_ia,k - sum_m V_ia,m sum_jb W_jb,m T_jb,k, Euclidean
     874              : !>        orthonormalisation of T, W_ia,k = sum_jb (A-B)_ia,jb T_jb,k, T_ia,k <- sum_l T_ia,l (R^-1)_lk and
     875              : !>        W alike with sum_p R_pk R_pl = sum_ia T_ia,k W_ia,l, and (M W)_ia,k = sum_jb (A+B)_ia,jb W_jb,k
     876              : !> \param mv_env the matrix-free A and B
     877              : !> \param fm_V basis; columns 1..m are kept, m+1..m+nt hold T on entry and the kept columns on exit
     878              : !> \param fm_W (A-B) V, extended in the same columns
     879              : !> \param fm_MW (A+B) W, extended in the same columns
     880              : !> \param fm_scratch scratch of at least nt columns
     881              : !> \param m columns of the basis before the extension
     882              : !> \param nt on exit the number of columns kept
     883              : !> \param n_kernel counter of the kernel applications
     884              : !> \param n_dependent counter of the correction vectors dropped as dependent
     885              : !> \param abba_status abba_indefinite if the Gram matrix of T in the (A-B) inner product is not positive definite
     886              : !> \param ab_margin smallest eigenvalue of T^T (A-B) T if that matrix is not positive definite
     887              : ! **************************************************************************************************
     888           32 :    SUBROUTINE extend_basis_mk(mv_env, fm_V, fm_W, fm_MW, fm_scratch, m, nt, n_kernel, n_dependent, abba_status, &
     889              :                               ab_margin)
     890              : 
     891              :       TYPE(bse_matvec_env_type), INTENT(IN)              :: mv_env
     892              :       TYPE(cp_fm_type), INTENT(IN)                       :: fm_V, fm_W, fm_MW, fm_scratch
     893              :       INTEGER, INTENT(IN)                                :: m
     894              :       INTEGER, INTENT(INOUT)                             :: nt, n_kernel, n_dependent, abba_status
     895              :       REAL(KIND=dp), INTENT(INOUT)                       :: ab_margin
     896              : 
     897              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'extend_basis_mk'
     898              : 
     899              :       INTEGER                                            :: handle
     900              : 
     901           32 :       CALL timeset(routineN, handle)
     902              : 
     903              :       ! T_ia,k <- T_ia,k - sum_m V_ia,m sum_jb W_jb,m T_jb,k, then Euclidean orthonormalisation
     904           32 :       CALL extend_orthonormal(fm_V, m, nt, mv_env%para_env, n_dependent, fm_W)
     905              : 
     906           32 :       IF (nt > 0) THEN
     907              :          ! W_ia,k = sum_jb (A-B)_ia,jb T_jb,k: A T into W, B T into the scratch
     908           32 :          CALL bse_matvec_apply(mv_env, fm_V, m + 1, nt, fm_W, fm_scratch, 1)
     909           32 :          CALL columns_axpy(-1.0_dp, fm_scratch, 1, fm_W, m + 1, nt)
     910           32 :          n_kernel = n_kernel + nt
     911              : 
     912              :          ! T_ia,k <- sum_l T_ia,l (R^-1)_lk and W alike, with sum_p R_pk R_pl = sum_ia T_ia,k W_ia,l
     913           32 :          CALL cholqr2_metric(fm_V, fm_W, m + 1, nt, mv_env%para_env, abba_status, ab_margin)
     914              : 
     915           32 :          IF (abba_status == abba_ok) THEN
     916              :             ! post-condition of the extension, one Gram matrix; the residual norms below rely on it
     917           32 :             IF (extension_deviation(fm_V, fm_W, m, nt, mv_env%para_env) > ortho_tol) THEN
     918            0 :                CPABORT("BSE Davidson: the basis lost orthonormality in the (A-B) inner product")
     919              :             END IF
     920              :             ! (M W)_ia,k = sum_jb (A+B)_ia,jb W_jb,k: A W into MW, B W into the scratch
     921           32 :             CALL bse_matvec_apply(mv_env, fm_W, m + 1, nt, fm_MW, fm_scratch, 1)
     922           32 :             CALL columns_axpy(1.0_dp, fm_scratch, 1, fm_MW, m + 1, nt)
     923           32 :             n_kernel = n_kernel + nt
     924              :          END IF
     925              :       END IF
     926              : 
     927           32 :       CALL timestop(handle)
     928              : 
     929           32 :    END SUBROUTINE extend_basis_mk
     930              : 
     931              : ! **************************************************************************************************
     932              : !> \brief Two Cholesky QR passes in the inner product of a symmetric K with the products KT at hand:
     933              : !>        G_kl = sum_ia T_ia,k (KT)_ia,l = sum_p R_pk R_pl, T_ia,k <- sum_l T_ia,l (R^-1)_lk, KT alike. A failed
     934              : !>        factorization of a G with a negative eigenvalue reports K as indefinite, any other failure
     935              : !>        is repeated once with a diagonal shift and a third pass. The Gram is the only communication:
     936              : !>        R is factorised on one rank and broadcast, the triangular solve runs on the local rows
     937              : !> \param fm_T the block to orthonormalise, columns first_col .. first_col+nt-1
     938              : !> \param fm_KT K T in the same columns, transformed alike
     939              : !> \param first_col first column of the block
     940              : !> \param nt number of columns in the block
     941              : !> \param para_env communicator of the row-distributed matrices
     942              : !> \param abba_status abba_indefinite if gram has a negative eigenvalue, else untouched
     943              : !> \param eig_min smallest eigenvalue of gram, set if it is negative
     944              : ! **************************************************************************************************
     945           32 :    SUBROUTINE cholqr2_metric(fm_T, fm_KT, first_col, nt, para_env, abba_status, eig_min)
     946              : 
     947              :       TYPE(cp_fm_type), INTENT(IN)                       :: fm_T, fm_KT
     948              :       INTEGER, INTENT(IN)                                :: first_col, nt
     949              :       TYPE(mp_para_env_type), INTENT(IN)                 :: para_env
     950              :       INTEGER, INTENT(INOUT)                             :: abba_status
     951              :       REAL(KIND=dp), INTENT(INOUT)                       :: eig_min
     952              : 
     953              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'cholqr2_metric'
     954              : 
     955              :       INTEGER                                            :: handle, info, ipass, k, n_ov, n_pass, &
     956              :                                                             nrow_local
     957              :       REAL(KIND=dp)                                      :: shift
     958              :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:)           :: eigval
     959           32 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :)        :: chol_factor, gram, gram_raw
     960              : 
     961           32 :       CALL timeset(routineN, handle)
     962           32 :       CALL cp_fm_get_info(fm_T, nrow_local=nrow_local, nrow_global=n_ov)
     963          320 :       ALLOCATE (gram_raw(nt, nt), gram(nt, nt), chol_factor(nt, nt), eigval(nt))
     964              : 
     965           32 :       n_pass = 2
     966           32 :       ipass = 0
     967           96 :       DO WHILE (ipass < n_pass)
     968           64 :          ipass = ipass + 1
     969              :          ! G_kl = (sum_ia T_ia,k (KT)_ia,l + sum_ia T_ia,l (KT)_ia,k)/2 = sum_p R_pk R_pl
     970           64 :          CALL subspace_gram(fm_T, first_col, nt, fm_KT, first_col, nt, para_env, gram_raw)
     971         1216 :          gram(:, :) = 0.5_dp*(gram_raw(:, :) + TRANSPOSE(gram_raw(:, :)))
     972         1216 :          chol_factor(:, :) = gram(:, :)
     973           64 :          info = 0
     974           64 :          IF (para_env%is_source()) CALL DPOTRF('U', nt, chol_factor, nt, info)
     975           64 :          CALL para_env%bcast(info)
     976           64 :          IF (info /= 0) THEN
     977            0 :             IF (n_pass == 3) THEN
     978              :                CALL cp_abort(__LOCATION__, &
     979            0 :                              "BSE Davidson: orthonormalisation in the (A-B) inner product broke down")
     980              :             END IF
     981            0 :             chol_factor(:, :) = gram(:, :)
     982            0 :             eigval(:) = 0.0_dp
     983            0 :             IF (para_env%is_source()) CALL diamat_all(chol_factor, eigval)
     984            0 :             CALL para_env%bcast(eigval)
     985            0 :             IF (eigval(1) < 0.0_dp) THEN
     986            0 :                abba_status = abba_indefinite
     987            0 :                eig_min = eigval(1)
     988            0 :                EXIT
     989              :             END IF
     990              :             ! a positive G that failed numerically: factorise G_kl + shift δ_kl and pass once more, the
     991              :             ! shift of shifted Cholesky QR (Fukaya et al. 2020), 11 (N_ov nt + nt (nt+1)) EPSILON |G|_F
     992            0 :             n_pass = 3
     993              :             shift = 11.0_dp*(REAL(n_ov, dp)*REAL(nt, dp) + REAL(nt, dp)*REAL(nt + 1, dp))* &
     994            0 :                     EPSILON(1.0_dp)*NORM2(gram)
     995            0 :             chol_factor(:, :) = gram(:, :)
     996            0 :             DO k = 1, nt
     997            0 :                chol_factor(k, k) = chol_factor(k, k) + shift
     998              :             END DO
     999            0 :             IF (para_env%is_source()) CALL DPOTRF('U', nt, chol_factor, nt, info)
    1000            0 :             CALL para_env%bcast(info)
    1001            0 :             IF (info /= 0) THEN
    1002              :                CALL cp_abort(__LOCATION__, &
    1003            0 :                              "BSE Davidson: orthonormalisation in the (A-B) inner product broke down")
    1004              :             END IF
    1005              :          END IF
    1006              :          ! T_ia,k <- sum_l T_ia,l (R^-1)_lk and KT alike, on the local rows
    1007           64 :          CALL para_env%bcast(chol_factor)
    1008           96 :          IF (nrow_local > 0) THEN
    1009              :             CALL DTRSM('R', 'U', 'N', 'N', nrow_local, nt, 1.0_dp, chol_factor, nt, &
    1010           64 :                        fm_T%local_data(:, first_col:first_col + nt - 1), SIZE(fm_T%local_data, 1))
    1011              :             CALL DTRSM('R', 'U', 'N', 'N', nrow_local, nt, 1.0_dp, chol_factor, nt, &
    1012           64 :                        fm_KT%local_data(:, first_col:first_col + nt - 1), SIZE(fm_KT%local_data, 1))
    1013              :          END IF
    1014              :       END DO
    1015              : 
    1016           32 :       DEALLOCATE (gram_raw, gram, chol_factor, eigval)
    1017           32 :       CALL timestop(handle)
    1018              : 
    1019           32 :    END SUBROUTINE cholqr2_metric
    1020              : 
    1021              : ! **************************************************************************************************
    1022              : !> \brief Paired reduced problem on the orthonormal basis b_ia,m,
    1023              : !>        Mr_mn = sum_ia b_ia,m (M b)_ia,n and Kr_mn = sum_ia b_ia,m (K b)_ia,n,
    1024              : !>        sum_n Mr_mn R_nk = Ω_k L_mk and sum_n Kr_mn L_nk = Ω_k R_mk,
    1025              : !>        solved as in initial_guess_subblock through the symmetric form:
    1026              : !>        Kr_mn = sum_p U_mp κ_p U_np and S_mn = sum_p U_mp √κ_p U_np, the square root of Kr,
    1027              : !>        sum_nop S_mn Mr_no S_op T_pk = λ_k T_mk with Ω_k = √λ_k,
    1028              : !>        R_mk = sum_n S_mn T_nk/√Ω_k and L_mk = sum_n Mr_mn R_nk/Ω_k.
    1029              : !>        κ_1 <= 0 reports K as indefinite on the span of b.
    1030              : !>        Every m x m step runs on the grid of blacs_env: the two eigensolves through
    1031              : !>        choose_eigv_solver and the four products through parallel_gemm; only the pair
    1032              : !>        coefficients come back replicated, R_mk in coef_right and L_mk in coef_left
    1033              : !> \param fm_red_M Mr in its live block, on the grid of blacs_env
    1034              : !> \param fm_red_K Kr in its live block, on the grid of blacs_env
    1035              : !> \param m dimension of the live block
    1036              : !> \param n_act number of pairs formed
    1037              : !> \param para_env communicator of the grid
    1038              : !> \param omega Ω_k in Hartree
    1039              : !> \param coef_right coefficients of y_k in column k, zero below row m
    1040              : !> \param coef_left coefficients of x_k in column k, zero below row m
    1041              : !> \param kr_min κ_1, the smallest eigenvalue of Kr
    1042              : !> \param abba_status abba_indefinite when κ_1 <= 0; omega, coef_right and coef_left are then untouched
    1043              : !> \param blacs_env grid the reduced problem is solved on
    1044              : ! **************************************************************************************************
    1045           34 :    SUBROUTINE solve_reduced_paired(fm_red_M, fm_red_K, m, n_act, para_env, omega, coef_right, coef_left, kr_min, &
    1046              :                                    abba_status, blacs_env)
    1047              : 
    1048              :       TYPE(cp_fm_type), INTENT(IN)                       :: fm_red_M, fm_red_K
    1049              :       INTEGER, INTENT(IN)                                :: m, n_act
    1050              :       TYPE(mp_para_env_type), INTENT(IN), TARGET         :: para_env
    1051              :       REAL(KIND=dp), DIMENSION(:), INTENT(OUT)           :: omega
    1052              :       REAL(KIND=dp), DIMENSION(:, :), INTENT(OUT)        :: coef_right, coef_left
    1053              :       REAL(KIND=dp), INTENT(OUT)                         :: kr_min
    1054              :       INTEGER, INTENT(INOUT)                             :: abba_status
    1055              :       TYPE(cp_blacs_env_type), INTENT(IN), TARGET        :: blacs_env
    1056              : 
    1057              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'solve_reduced_paired'
    1058              : 
    1059              :       INTEGER                                            :: handle
    1060              :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:)           :: kappa, lambda
    1061              :       TYPE(cp_fm_struct_type), POINTER                   :: fm_struct
    1062              :       TYPE(cp_fm_type)                                   :: fm_H, fm_H_eigvec, fm_K_eigvec, &
    1063              :                                                             fm_K_sqrt, fm_L, fm_Mr, fm_R, fm_work
    1064              : 
    1065           34 :       CALL timeset(routineN, handle)
    1066              :       ! n_act pairs are extracted from an m-dimensional basis
    1067           34 :       CPASSERT(n_act <= m)
    1068              : 
    1069              :       ! Kr_mn = sum_p U_mp κ_p U_np, S_mn = sum_p U_mp √κ_p U_np, H_mp = sum_no S_mn Mr_no S_op, T its eigenvectors:
    1070              :       ! κ, U in fm_K_eigvec, S in fm_K_sqrt, the symmetrised Mr, H, T in fm_H_eigvec and a work matrix,
    1071              :       ! all m x m on the grid of blacs_env
    1072          136 :       ALLOCATE (kappa(m), lambda(m))
    1073           34 :       NULLIFY (fm_struct)
    1074              :       CALL cp_fm_struct_create(fm_struct, para_env=para_env, context=blacs_env, &
    1075           34 :                                nrow_global=m, ncol_global=m)
    1076           34 :       CALL cp_fm_create(fm_K_eigvec, fm_struct, name="bse_paired_U")
    1077           34 :       CALL cp_fm_create(fm_K_sqrt, fm_struct, name="bse_paired_S")
    1078           34 :       CALL cp_fm_create(fm_Mr, fm_struct, name="bse_paired_Mr")
    1079           34 :       CALL cp_fm_create(fm_H, fm_struct, name="bse_paired_H")
    1080           34 :       CALL cp_fm_create(fm_H_eigvec, fm_struct, name="bse_paired_T")
    1081           34 :       CALL cp_fm_create(fm_work, fm_struct, name="bse_paired_work")
    1082           34 :       CALL cp_fm_struct_release(fm_struct)
    1083              : 
    1084              :       ! Kr_mn = sum_p U_mp κ_p U_np on the symmetrised live block, (Kr_mn + Kr_nm)/2
    1085           34 :       CALL cp_fm_to_fm_submat(fm_red_K, fm_work, m, m, 1, 1, 1, 1)
    1086           34 :       CALL symmetrise_in_place(fm_work, fm_K_eigvec)
    1087           34 :       kappa(:) = 0.0_dp
    1088           34 :       CALL choose_eigv_solver(fm_work, fm_K_eigvec, kappa)
    1089           34 :       kr_min = kappa(1)
    1090              : 
    1091           34 :       IF (kappa(1) <= 0.0_dp) THEN
    1092            0 :          abba_status = abba_indefinite
    1093              :       ELSE
    1094              :          ! S_mn = sum_p U_mp √κ_p U_np
    1095           34 :          CALL cp_fm_to_fm(fm_K_eigvec, fm_work)
    1096          570 :          CALL cp_fm_column_scale(fm_work, SQRT(kappa))
    1097           34 :          CALL parallel_gemm('N', 'T', m, m, m, 1.0_dp, fm_work, fm_K_eigvec, 0.0_dp, fm_K_sqrt)
    1098              : 
    1099              :          ! H_mp = sum_no S_mn Mr_no S_op with Mr_no <- (Mr_no + Mr_on)/2, then T holds its eigenvectors
    1100           34 :          CALL cp_fm_to_fm_submat(fm_red_M, fm_Mr, m, m, 1, 1, 1, 1)
    1101           34 :          CALL symmetrise_in_place(fm_Mr, fm_H_eigvec)
    1102           34 :          CALL parallel_gemm('N', 'N', m, m, m, 1.0_dp, fm_Mr, fm_K_sqrt, 0.0_dp, fm_work)
    1103           34 :          CALL parallel_gemm('N', 'N', m, m, m, 1.0_dp, fm_K_sqrt, fm_work, 0.0_dp, fm_H)
    1104           34 :          lambda(:) = 0.0_dp
    1105           34 :          CALL choose_eigv_solver(fm_H, fm_H_eigvec, lambda)
    1106              :          ! H is congruent to Mr = sum_ia b (M b), so λ_1 <= 0 means (A+B) indefinite on the span of b, or
    1107              :          ! round-off in a nearly dependent basis, which extension_deviation excludes at every extension
    1108           34 :          IF (lambda(1) <= 0.0_dp) THEN
    1109              :             CALL cp_abort(__LOCATION__, &
    1110              :                           "BSE Davidson (OLSEN_STRATMANN): negative squared excitation energy. Matrix "// &
    1111              :                           "(A+B) is not positive definite on the trial space, or the basis lost its "// &
    1112            0 :                           "orthonormality.")
    1113              :          END IF
    1114          272 :          omega(1:n_act) = SQRT(lambda(1:n_act))
    1115              : 
    1116              :          ! R_mk = sum_n S_mn T_nk/√Ω_k, L_mk = sum_n Mr_mn R_nk/Ω_k
    1117           34 :          NULLIFY (fm_struct)
    1118              :          CALL cp_fm_struct_create(fm_struct, para_env=para_env, context=blacs_env, &
    1119           34 :                                   nrow_global=m, ncol_global=n_act)
    1120           34 :          CALL cp_fm_create(fm_R, fm_struct, name="bse_paired_R")
    1121           34 :          CALL cp_fm_create(fm_L, fm_struct, name="bse_paired_L")
    1122           34 :          CALL cp_fm_struct_release(fm_struct)
    1123           34 :          CALL parallel_gemm('N', 'N', m, n_act, m, 1.0_dp, fm_K_sqrt, fm_H_eigvec, 0.0_dp, fm_R)
    1124          272 :          CALL cp_fm_column_scale(fm_R, 1.0_dp/SQRT(omega(1:n_act)))
    1125           34 :          CALL parallel_gemm('N', 'N', m, n_act, m, 1.0_dp, fm_Mr, fm_R, 0.0_dp, fm_L)
    1126          272 :          CALL cp_fm_column_scale(fm_L, 1.0_dp/omega(1:n_act))
    1127              : 
    1128         6936 :          coef_right(:, :) = 0.0_dp
    1129         6936 :          coef_left(:, :) = 0.0_dp
    1130           34 :          CALL cp_fm_get_submatrix(fm_R, coef_right(1:m, 1:n_act))
    1131           34 :          CALL cp_fm_get_submatrix(fm_L, coef_left(1:m, 1:n_act))
    1132           34 :          CALL cp_fm_release(fm_R)
    1133           34 :          CALL cp_fm_release(fm_L)
    1134              :       END IF
    1135              : 
    1136           34 :       CALL cp_fm_release(fm_K_eigvec)
    1137           34 :       CALL cp_fm_release(fm_K_sqrt)
    1138           34 :       CALL cp_fm_release(fm_Mr)
    1139           34 :       CALL cp_fm_release(fm_H)
    1140           34 :       CALL cp_fm_release(fm_H_eigvec)
    1141           34 :       CALL cp_fm_release(fm_work)
    1142           34 :       DEALLOCATE (kappa, lambda)
    1143           34 :       CALL timestop(handle)
    1144              : 
    1145           68 :    END SUBROUTINE solve_reduced_paired
    1146              : 
    1147              : ! **************************************************************************************************
    1148              : !> \brief Makes the nt columns T that follow column m of b orthonormal to b and to each other,
    1149              : !>        T_ia,k <- T_ia,k - sum_m b_ia,m sum_jb b_jb,m T_jb,k, then T_ia,k <- sum_l T_ia,l (R^-1)_lk with
    1150              : !>        sum_p R_pk R_pl = sum_ia T_ia,k T_ia,l (cholqr2), and stores the products
    1151              : !>        (M b)_ia,k = sum_jb (A+B)_ia,jb b_jb,k, (K b)_ia,k = sum_jb (A-B)_ia,jb b_jb,k of the kept
    1152              : !>        columns from one application of A and B
    1153              : !> \param mv_env the matrix-free A and B
    1154              : !> \param fm_b basis; columns 1..m are kept, m+1..m+nt hold T on entry and the kept columns on exit
    1155              : !> \param fm_Mb (A+B) b, extended in the same columns
    1156              : !> \param fm_Kb (A-B) b, extended in the same columns
    1157              : !> \param fm_scratch scratch of at least nt columns
    1158              : !> \param m columns of the basis before the extension
    1159              : !> \param nt on exit the number of columns kept
    1160              : !> \param n_kernel counter of the kernel applications
    1161              : !> \param n_dependent counter of the correction vectors dropped as dependent
    1162              : ! **************************************************************************************************
    1163           34 :    SUBROUTINE extend_basis_os(mv_env, fm_b, fm_Mb, fm_Kb, fm_scratch, m, nt, n_kernel, n_dependent)
    1164              : 
    1165              :       TYPE(bse_matvec_env_type), INTENT(IN)              :: mv_env
    1166              :       TYPE(cp_fm_type), INTENT(IN)                       :: fm_b, fm_Mb, fm_Kb, fm_scratch
    1167              :       INTEGER, INTENT(IN)                                :: m
    1168              :       INTEGER, INTENT(INOUT)                             :: nt, n_kernel, n_dependent
    1169              : 
    1170              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'extend_basis_os'
    1171              : 
    1172              :       INTEGER                                            :: handle
    1173              : 
    1174           34 :       CALL timeset(routineN, handle)
    1175              : 
    1176           34 :       CALL extend_orthonormal(fm_b, m, nt, mv_env%para_env, n_dependent)
    1177              : 
    1178           34 :       IF (nt > 0) THEN
    1179              :          ! post-condition of the extension, one Gram matrix; the residual norms below rely on it
    1180           34 :          IF (extension_deviation(fm_b, fm_b, m, nt, mv_env%para_env) > ortho_tol) THEN
    1181            0 :             CPABORT("BSE Davidson: the basis lost orthonormality")
    1182              :          END IF
    1183              :          ! A b into Mb and B b into the scratch, then K b = A b - B b and M b = A b + B b
    1184           34 :          CALL bse_matvec_apply(mv_env, fm_b, m + 1, nt, fm_Mb, fm_scratch, 1)
    1185           34 :          CALL cp_fm_to_fm(fm_Mb, fm_Kb, nt, m + 1, m + 1)
    1186           34 :          CALL columns_axpy(-1.0_dp, fm_scratch, 1, fm_Kb, m + 1, nt)
    1187           34 :          CALL columns_axpy(1.0_dp, fm_scratch, 1, fm_Mb, m + 1, nt)
    1188           34 :          n_kernel = n_kernel + nt
    1189              :       END IF
    1190              : 
    1191           34 :       CALL timestop(handle)
    1192              : 
    1193           34 :    END SUBROUTINE extend_basis_os
    1194              : 
    1195              : ! **************************************************************************************************
    1196              : !> \brief One convergence step of a driver: dE_k = |E_k - E_k^prev|, the flags from CONVERGENCE_CRITERION,
    1197              : !>        the last required root, every root converged once the basis spans all transitions, the roots
    1198              : !>        in need, and the line of the iteration table
    1199              : !> \param bse_env CONVERGENCE_CRITERION, EPS_ENERGY and EPS_RES
    1200              : !> \param energies tracked energies in Hartree, ascending; the first SIZE(res) are read
    1201              : !> \param energies_prev the same of the previous iteration
    1202              : !> \param res residual norms of the tracked roots
    1203              : !> \param m subspace dimension
    1204              : !> \param n_ov number of transitions
    1205              : !> \param n_want requested states
    1206              : !> \param iter iteration count
    1207              : !> \param t_iter wall time at the start of the iteration
    1208              : !> \param unit_nr output unit, positive on the writing rank only
    1209              : !> \param dE energy changes in Hartree
    1210              : !> \param conv convergence flags
    1211              : !> \param n_req last required root
    1212              : !> \param need roots in need
    1213              : ! **************************************************************************************************
    1214          140 :    SUBROUTINE convergence_step(bse_env, energies, energies_prev, res, m, n_ov, n_want, iter, t_iter, unit_nr, &
    1215          140 :                                dE, conv, n_req, need)
    1216              : 
    1217              :       TYPE(bse_env_type), INTENT(IN)                     :: bse_env
    1218              :       REAL(KIND=dp), DIMENSION(:), INTENT(IN)            :: energies, energies_prev, res
    1219              :       INTEGER, INTENT(IN)                                :: m, n_ov, n_want, iter
    1220              :       REAL(KIND=dp), INTENT(IN)                          :: t_iter
    1221              :       INTEGER, INTENT(IN)                                :: unit_nr
    1222              :       REAL(KIND=dp), DIMENSION(:), INTENT(OUT)           :: dE
    1223              :       LOGICAL, DIMENSION(:), INTENT(OUT)                 :: conv
    1224              :       INTEGER, INTENT(OUT)                               :: n_req
    1225              :       LOGICAL, DIMENSION(:), INTENT(OUT)                 :: need
    1226              : 
    1227              :       INTEGER                                            :: n_act
    1228              : 
    1229           70 :       n_act = SIZE(res)
    1230          564 :       dE(:) = ABS(energies(1:n_act) - energies_prev(1:n_act))
    1231           70 :       CALL convergence_flags(bse_env, dE, res, conv)
    1232           70 :       n_req = multiplet_end(energies, n_want, n_act, deg_thresh)
    1233              :       ! a subspace that spans all transitions is exact
    1234           70 :       IF (m == n_ov) conv(:) = .TRUE.
    1235           70 :       CALL roots_in_need(conv, energies, res, n_req, need)
    1236              :       ! the masked MAXVAL is -HUGE when no root is in need; the unmasked term covers that case
    1237              :       CALL print_iteration(iter, m, COUNT(conv(1:n_want)), &
    1238              :                            MAX(MAXVAL(res(1:n_req)), MAXVAL(res, MASK=need)), &
    1239         1216 :                            MAXVAL(dE(1:n_req)), energies(1), m_walltime() - t_iter, unit_nr)
    1240              : 
    1241           70 :    END SUBROUTINE convergence_step
    1242              : 
    1243              : ! **************************************************************************************************
    1244              : !> \brief Convergence flag of every tracked root k from CONVERGENCE_CRITERION: EN dE_k < EPS_ENERGY,
    1245              : !>        RES |r_k| < EPS_RES, OR either of the two, AND both
    1246              : !> \param bse_env CONVERGENCE_CRITERION, EPS_ENERGY and EPS_RES
    1247              : !> \param dE energy changes in Hartree
    1248              : !> \param res residual norms
    1249              : !> \param conv one flag per tracked root
    1250              : ! **************************************************************************************************
    1251           70 :    SUBROUTINE convergence_flags(bse_env, dE, res, conv)
    1252              : 
    1253              :       TYPE(bse_env_type), INTENT(IN)                     :: bse_env
    1254              :       REAL(KIND=dp), DIMENSION(:), INTENT(IN)            :: dE, res
    1255              :       LOGICAL, DIMENSION(:), INTENT(OUT)                 :: conv
    1256              : 
    1257              :       INTEGER                                            :: k
    1258              : 
    1259          564 :       DO k = 1, SIZE(conv)
    1260           70 :          SELECT CASE (bse_env%convergence_criterion)
    1261              :          CASE (bse_iter_en_cond)
    1262            0 :             conv(k) = dE(k) < bse_env%eps_energy
    1263              :          CASE (bse_iter_res_cond)
    1264            0 :             conv(k) = res(k) < bse_env%eps_res
    1265              :          CASE (bse_iter_or_cond)
    1266            0 :             conv(k) = dE(k) < bse_env%eps_energy .OR. res(k) < bse_env%eps_res
    1267              :          CASE (bse_iter_and_cond)
    1268          906 :             conv(k) = dE(k) < bse_env%eps_energy .AND. res(k) < bse_env%eps_res
    1269              :          END SELECT
    1270              :       END DO
    1271              : 
    1272           70 :    END SUBROUTINE convergence_flags
    1273              : 
    1274              : ! **************************************************************************************************
    1275              : !> \brief Last member of the multiplet that contains state n_first: the scan stops at the first gap of
    1276              : !>        at least thresh, or at n_limit. A multiplet cut by NUM_EXC_EN is thereby taken as a whole
    1277              : !> \param energies ascending energies in Hartree
    1278              : !> \param n_first first state of the scan
    1279              : !> \param n_limit last state the scan may reach
    1280              : !> \param thresh gap that ends a multiplet, in Hartree
    1281              : !> \return the last member, n_first <= n_last <= n_limit
    1282              : ! **************************************************************************************************
    1283           88 :    PURE FUNCTION multiplet_end(energies, n_first, n_limit, thresh) RESULT(n_last)
    1284              : 
    1285              :       REAL(KIND=dp), DIMENSION(:), INTENT(IN)            :: energies
    1286              :       INTEGER, INTENT(IN)                                :: n_first, n_limit
    1287              :       REAL(KIND=dp), INTENT(IN)                          :: thresh
    1288              :       INTEGER                                            :: n_last
    1289              : 
    1290           88 :       n_last = n_first
    1291           88 :       DO WHILE (n_last < n_limit)
    1292           86 :          IF (energies(n_last + 1) - energies(n_last) >= thresh) EXIT
    1293           88 :          n_last = n_last + 1
    1294              :       END DO
    1295              : 
    1296           88 :    END FUNCTION multiplet_end
    1297              : ! **************************************************************************************************
    1298              : !> \brief Roots that still need correction vectors: the unconverged ones up to n_req, and a tracked
    1299              : !>        root k above them as long as E_k - |r_k| < E_n_req. An eigenvalue of a symmetric matrix
    1300              : !>        lies within |r_k| of E_k, so such a root can still belong to the requested states; the ABBA
    1301              : !>        solvers, whose residuals are not those of a symmetric problem, use the same rule as a heuristic
    1302              : !> \param conv convergence flags of the tracked roots
    1303              : !> \param energies tracked energies in Hartree, ascending
    1304              : !> \param res residual norms
    1305              : !> \param n_req last required root
    1306              : !> \param need one flag per tracked root, set here
    1307              : ! **************************************************************************************************
    1308           70 :    SUBROUTINE roots_in_need(conv, energies, res, n_req, need)
    1309              : 
    1310              :       LOGICAL, DIMENSION(:), INTENT(IN)                  :: conv
    1311              :       REAL(KIND=dp), DIMENSION(:), INTENT(IN)            :: energies, res
    1312              :       INTEGER, INTENT(IN)                                :: n_req
    1313              :       LOGICAL, DIMENSION(:), INTENT(OUT)                 :: need
    1314              : 
    1315              :       INTEGER                                            :: k
    1316              : 
    1317          564 :       DO k = 1, SIZE(need)
    1318          494 :          need(k) = .NOT. conv(k)
    1319          828 :          IF (k > n_req) need(k) = need(k) .AND. energies(k) - res(k) < energies(n_req)
    1320              :       END DO
    1321              : 
    1322           70 :    END SUBROUTINE roots_in_need
    1323              : 
    1324              : ! **************************************************************************************************
    1325              : !> \brief The lowest roots in need, which receive a correction vector
    1326              : !> \param bse_env CONVERGENCE_CRITERION and EPS_RES
    1327              : !> \param need roots in need, from roots_in_need
    1328              : !> \param res residual norms
    1329              : !> \param n_max largest number of roots
    1330              : !> \param selected indices of the selected roots in ascending order, zero beyond nt
    1331              : !> \param nt number of selected roots
    1332              : ! **************************************************************************************************
    1333           60 :    SUBROUTINE select_roots(bse_env, need, res, n_max, selected, nt)
    1334              : 
    1335              :       TYPE(bse_env_type), INTENT(IN)                     :: bse_env
    1336              :       LOGICAL, DIMENSION(:), INTENT(IN)                  :: need
    1337              :       REAL(KIND=dp), DIMENSION(:), INTENT(IN)            :: res
    1338              :       INTEGER, INTENT(IN)                                :: n_max
    1339              :       INTEGER, DIMENSION(:), INTENT(OUT)                 :: selected
    1340              :       INTEGER, INTENT(OUT)                               :: nt
    1341              : 
    1342              :       INTEGER                                            :: k
    1343              : 
    1344          482 :       selected(:) = 0
    1345           60 :       nt = 0
    1346          482 :       DO k = 1, SIZE(need)
    1347          422 :          IF (.NOT. need(k)) CYCLE
    1348              :          ! a root below EPS_RES only waits for its energy criterion
    1349          156 :          IF (bse_env%convergence_criterion == bse_iter_and_cond .AND. &
    1350              :              res(k) < bse_env%eps_res) CYCLE
    1351          148 :          IF (nt == n_max) EXIT
    1352          148 :          nt = nt + 1
    1353          482 :          selected(nt) = k
    1354              :       END DO
    1355              : 
    1356           60 :    END SUBROUTINE select_roots
    1357              : 
    1358              : ! **************************************************************************************************
    1359              : !> \brief Title and column heads of the iteration table
    1360              : !> \param title line printed above the column heads
    1361              : !> \param unit_nr output unit, positive on the writing rank only
    1362              : ! **************************************************************************************************
    1363           10 :    SUBROUTINE print_iteration_header(title, unit_nr)
    1364              : 
    1365              :       CHARACTER(LEN=*), INTENT(IN)                       :: title
    1366              :       INTEGER, INTENT(IN)                                :: unit_nr
    1367              : 
    1368           10 :       IF (unit_nr > 0) THEN
    1369            5 :          WRITE (unit_nr, '(T2,A4)') 'BSE|'
    1370            5 :          WRITE (unit_nr, '(T2,A4,T7,A)') 'BSE|', title
    1371            5 :          WRITE (unit_nr, '(T2,A4)') 'BSE|'
    1372            5 :          WRITE (unit_nr, '(T2,A4,T7,A)') 'BSE|', &
    1373           10 :             '|r| in a.u., energies in eV, t the wall time of the iteration'
    1374            5 :          WRITE (unit_nr, '(T2,A4)') 'BSE|'
    1375            5 :          WRITE (unit_nr, '(T2,A4,T7,A5,T14,A8,T24,A6,T33,A12,T47,A12,T61,A12,T74,A7)') 'BSE|', &
    1376           10 :             'Iter.', 'Z-space', 'Conv.', 'Max |r|', 'Max dE', 'Lowest E', 't (s)'
    1377              :       END IF
    1378              : 
    1379           10 :    END SUBROUTINE print_iteration_header
    1380              : 
    1381              : ! **************************************************************************************************
    1382              : !> \brief One line of the iteration table
    1383              : !> \param iter iteration count
    1384              : !> \param m subspace dimension
    1385              : !> \param n_conv converged roots among the requested ones
    1386              : !> \param max_res largest residual norm over the required roots and the roots in need
    1387              : !> \param max_dE in Hartree
    1388              : !> \param lowest_E in Hartree
    1389              : !> \param t_iter wall time of the iteration in seconds
    1390              : !> \param unit_nr output unit, positive on the writing rank only
    1391              : ! **************************************************************************************************
    1392           70 :    SUBROUTINE print_iteration(iter, m, n_conv, max_res, max_dE, lowest_E, t_iter, unit_nr)
    1393              : 
    1394              :       INTEGER, INTENT(IN)                                :: iter, m, n_conv
    1395              :       REAL(KIND=dp), INTENT(IN)                          :: max_res, max_dE, lowest_E, t_iter
    1396              :       INTEGER, INTENT(IN)                                :: unit_nr
    1397              : 
    1398           70 :       IF (unit_nr > 0) THEN
    1399              :          WRITE (unit_nr, '(T2,A4,T7,I5,T14,I8,T24,I6,T33,ES12.4,T47,ES12.4,T61,F12.6,T74,F7.2)') &
    1400           35 :             'BSE|', iter, m, n_conv, max_res, max_dE*evolt, lowest_E*evolt, t_iter
    1401              :       END IF
    1402              : 
    1403           70 :    END SUBROUTINE print_iteration
    1404              : 
    1405              : ! **************************************************************************************************
    1406              : !> \brief Table of the requested roots and of the tracked roots in need, then the abort for MAX_ITER
    1407              : !> \param energies in Hartree
    1408              : !> \param res residual norms
    1409              : !> \param conv convergence flags
    1410              : !> \param need roots in need
    1411              : !> \param n_req last required root
    1412              : !> \param unit_nr output unit, positive on the writing rank only
    1413              : ! **************************************************************************************************
    1414            0 :    SUBROUTINE abort_unconverged(energies, res, conv, need, n_req, unit_nr)
    1415              : 
    1416              :       REAL(KIND=dp), DIMENSION(:), INTENT(IN)            :: energies, res
    1417              :       LOGICAL, DIMENSION(:), INTENT(IN)                  :: conv, need
    1418              :       INTEGER, INTENT(IN)                                :: n_req, unit_nr
    1419              : 
    1420              :       INTEGER                                            :: k
    1421              : 
    1422            0 :       IF (unit_nr > 0) THEN
    1423            0 :          WRITE (unit_nr, '(T2,A4)') 'BSE|'
    1424            0 :          WRITE (unit_nr, '(T2,A4,T7,A12,T30,A11,T50,A10,T67,A14)') 'BSE|', &
    1425            0 :             'Excitation n', 'Energy (eV)', '|r| (a.u.)', 'Converged'
    1426            0 :          DO k = 1, SIZE(need)
    1427            0 :             IF (k > n_req .AND. .NOT. need(k)) CYCLE
    1428            0 :             WRITE (unit_nr, '(T2,A4,T7,I12,T27,F14.6,T46,ES14.4,T67,L14)') 'BSE|', &
    1429            0 :                k, energies(k)*evolt, res(k), conv(k)
    1430              :          END DO
    1431              :       END IF
    1432              :       ! unconverged roots would enter postprocess_bse as converged states; the table above is the diagnostic
    1433            0 :       CPABORT("BSE Davidson: MAX_ITER reached before convergence")
    1434              : 
    1435            0 :    END SUBROUTINE abort_unconverged
    1436              : 
    1437              : ! **************************************************************************************************
    1438              : !> \brief Debug table of all tracked roots of a converged solve
    1439              : !> \param energies in Hartree
    1440              : !> \param res residual norms
    1441              : !> \param n_want requested states
    1442              : !> \param n_act tracked states
    1443              : !> \param unit_nr output unit, positive on the writing rank only
    1444              : ! **************************************************************************************************
    1445            2 :    SUBROUTINE print_tracked_roots(energies, res, n_want, n_act, unit_nr)
    1446              : 
    1447              :       REAL(KIND=dp), DIMENSION(:), INTENT(IN)            :: energies, res
    1448              :       INTEGER, INTENT(IN)                                :: n_want, n_act, unit_nr
    1449              : 
    1450              :       INTEGER                                            :: k
    1451              : 
    1452            2 :       IF (unit_nr > 0) THEN
    1453            1 :          WRITE (unit_nr, '(T2,A10,T13,A13,T27,A9,T45,A18,T67,A14)') 'BSE|DEBUG|', &
    1454            2 :             'Tracked state', 'Requested', 'Energy (eV)', '|r| (a.u.)'
    1455            8 :          DO k = 1, n_act
    1456            7 :             WRITE (unit_nr, '(T2,A10,T13,I13,T27,L9,T45,F18.10,T67,ES14.4)') 'BSE|DEBUG|', &
    1457           15 :                k, k <= n_want, energies(k)*evolt, res(k)
    1458              :          END DO
    1459              :       END IF
    1460              : 
    1461            2 :    END SUBROUTINE print_tracked_roots
    1462              : 
    1463              : ! **************************************************************************************************
    1464              : !> \brief Counters of a converged solve, the multiplet note and the warning for a degenerate group
    1465              : !>        that reaches the last buffer state
    1466              : !> \param iter iterations run
    1467              : !> \param n_kernel kernel applications
    1468              : !> \param n_restart thick restarts
    1469              : !> \param n_want requested states
    1470              : !> \param n_req last required root
    1471              : !> \param n_act tracked states
    1472              : !> \param n_ov number of transitions
    1473              : !> \param unit_nr output unit, positive on the writing rank only
    1474              : !> \param ab_margin smallest eigenvalue of A-B on the trial space in Hartree
    1475              : !> \param n_dependent correction vectors dropped as dependent, printed when not zero
    1476              : ! **************************************************************************************************
    1477           10 :    SUBROUTINE print_summary(iter, n_kernel, n_restart, n_want, n_req, n_act, n_ov, unit_nr, ab_margin, &
    1478              :                             n_dependent)
    1479              : 
    1480              :       INTEGER, INTENT(IN)                                :: iter, n_kernel, n_restart, n_want, &
    1481              :                                                             n_req, n_act, n_ov, unit_nr
    1482              :       REAL(KIND=dp), INTENT(IN), OPTIONAL                :: ab_margin
    1483              :       INTEGER, INTENT(IN), OPTIONAL                      :: n_dependent
    1484              : 
    1485           10 :       IF (unit_nr > 0) THEN
    1486            5 :          WRITE (unit_nr, '(T2,A4)') 'BSE|'
    1487            5 :          WRITE (unit_nr, '(T2,A4,T7,A,T71,I10)') 'BSE|', 'Davidson iterations', iter
    1488            5 :          WRITE (unit_nr, '(T2,A4,T7,A,T71,I10)') 'BSE|', 'Kernel applications', n_kernel
    1489            5 :          WRITE (unit_nr, '(T2,A4,T7,A,T71,I10)') 'BSE|', 'Thick restarts', n_restart
    1490            5 :          IF (PRESENT(n_dependent)) THEN
    1491            5 :             IF (n_dependent > 0) THEN
    1492            0 :                WRITE (unit_nr, '(T2,A4,T7,A,T71,I10)') 'BSE|', 'Correction vectors dropped as dependent', n_dependent
    1493              :             END IF
    1494              :          END IF
    1495            5 :          IF (PRESENT(ab_margin)) THEN
    1496            3 :             WRITE (unit_nr, '(T2,A4,T7,A,T65,F16.6)') 'BSE|', &
    1497            6 :                'A-B margin on the trial space (eV)', ab_margin*evolt
    1498              :          END IF
    1499            5 :          IF (n_req > n_want) THEN
    1500            0 :             WRITE (unit_nr, '(T2,A4,T7,A)') 'BSE|', &
    1501            0 :                'Note: the requested states end inside a degenerate multiplet.'
    1502              :          END IF
    1503            5 :          WRITE (unit_nr, '(T2,A4)') 'BSE|'
    1504              :       END IF
    1505              : 
    1506           10 :       IF (n_req > n_want .AND. n_req == n_act .AND. n_act < n_ov .AND. unit_nr > 0) THEN
    1507              :          CALL cp_warn(__LOCATION__, &
    1508              :                       "BSE Davidson: the degenerate group at NUM_EXC_EN reaches the last buffer state, "// &
    1509            0 :                       "further members may lie above it. Increase BSE_ITERAT%NUM_BUFFER_STATES.")
    1510              :       END IF
    1511              : 
    1512           10 :    END SUBROUTINE print_summary
    1513              : 
    1514              : ! **************************************************************************************************
    1515              : !> \brief Number of wanted and tracked states and the block size, capped at the problem size
    1516              : !> \param bse_env NUM_EXC_EN, NUM_BUFFER_STATES, BLOCK_SIZE and MAX_ITER
    1517              : !> \param n_ov number of transitions
    1518              : !> \param unit_nr output unit, positive on the writing rank only
    1519              : !> \param n_want NUM_EXC_EN, at most n_ov
    1520              : !> \param n_act wanted plus buffer states
    1521              : !> \param block_size BLOCK_SIZE, or MIN(32, n_act) for -1; at most n_act
    1522              : ! **************************************************************************************************
    1523           10 :    SUBROUTINE davidson_sizes(bse_env, n_ov, unit_nr, n_want, n_act, block_size)
    1524              : 
    1525              :       TYPE(bse_env_type), INTENT(IN)                     :: bse_env
    1526              :       INTEGER, INTENT(IN)                                :: n_ov, unit_nr
    1527              :       INTEGER, INTENT(OUT)                               :: n_want, n_act, block_size
    1528              : 
    1529           10 :       IF (bse_env%num_exc_en < 1) CPABORT("BSE_ITERAT%NUM_EXC_EN must be at least 1")
    1530           10 :       IF (bse_env%num_buffer_states < 0) CPABORT("BSE_ITERAT%NUM_BUFFER_STATES must not be negative")
    1531           10 :       IF (bse_env%block_size < 1 .AND. bse_env%block_size /= -1) THEN
    1532            0 :          CPABORT("BSE_ITERAT%BLOCK_SIZE must be at least 1, or -1 for the default")
    1533              :       END IF
    1534           10 :       IF (bse_env%max_iter < 1) CPABORT("BSE_ITERAT%MAX_ITER must be at least 1")
    1535              : 
    1536           10 :       n_want = bse_env%num_exc_en
    1537           10 :       IF (n_want > n_ov) THEN
    1538            0 :          IF (unit_nr > 0) CALL cp_warn(__LOCATION__, &
    1539            0 :                                        "BSE_ITERAT%NUM_EXC_EN exceeds the number of transitions and is reduced to it.")
    1540            0 :          n_want = n_ov
    1541              :       END IF
    1542           10 :       n_act = MIN(n_want + bse_env%num_buffer_states, n_ov)
    1543           10 :       block_size = bse_env%block_size
    1544              :       ! 32 was within 5 % of the best width on the L8 deck at 200 states; wider passes cost restarts
    1545           10 :       IF (block_size == -1) block_size = MIN(32, n_act)
    1546           10 :       IF (block_size > n_act) THEN
    1547            0 :          IF (unit_nr > 0) CALL cp_warn(__LOCATION__, &
    1548            0 :                                        "BSE_ITERAT%BLOCK_SIZE exceeds the number of tracked states and is reduced to it.")
    1549            0 :          block_size = n_act
    1550              :       END IF
    1551              : 
    1552           10 :    END SUBROUTINE davidson_sizes
    1553              : 
    1554              : ! **************************************************************************************************
    1555              : !> \brief Largest subspace dimension m_max: MAX_SUBSPACE_FACTOR x n_act, or 20 x n_act for -1, with
    1556              : !>        lowered to the largest whose arrays fit what MEMORY_PER_PROC leaves after the memory the rank
    1557              : !>        holds, never below 3 x n_act (4 x n_act for OLSEN_STRATMANN); the minimal subspace over that
    1558              : !>        remainder runs with a warning
    1559              : !> \param bse_env MAX_SUBSPACE_FACTOR and the resolved MEMORY_PER_PROC
    1560              : !> \param mv_env n_ov, the RI share per rank and block_cols
    1561              : !> \param driver driver_tda, driver_mk or driver_os
    1562              : !> \param n_act tracked states
    1563              : !> \param block_size correction vectors per iteration
    1564              : !> \param unit_nr output unit, positive on the writing rank only
    1565              : !> \param m_max the ceiling, 3 or 4 x n_act <= m_max <= n_ov
    1566              : ! **************************************************************************************************
    1567           20 :    SUBROUTINE subspace_ceiling(bse_env, mv_env, driver, n_act, block_size, unit_nr, m_max)
    1568              : 
    1569              :       TYPE(bse_env_type), INTENT(IN)                     :: bse_env
    1570              :       TYPE(bse_matvec_env_type), INTENT(IN)              :: mv_env
    1571              :       INTEGER, INTENT(IN)                                :: driver, n_act, block_size, unit_nr
    1572              :       INTEGER, INTENT(OUT)                               :: m_max
    1573              : 
    1574              :       CHARACTER(LEN=16)                                  :: bud_str, fac_str, mem_str
    1575              :       INTEGER                                            :: m_floor, m_hi, m_lo, m_mid, m_start, &
    1576              :                                                             min_fac, n_ri_max, nb
    1577              :       LOGICAL                                            :: floor_over, lowered
    1578              :       REAL(KIND=dp)                                      :: dist_GB, mem_left_GB, repl_GB
    1579              : 
    1580              :       ! the smallest ceiling that leaves room for the restart and one block: TDA and MK restart onto at
    1581              :       ! most 2 n_act vectors and add a block of at most n_act; OS restarts onto right and left pairs
    1582              :       ! under the cap m_max - 2 block_size, which has to hold the current 2 n_act
    1583           10 :       IF (driver == driver_os) THEN
    1584            2 :          min_fac = 4
    1585              :       ELSE
    1586            8 :          min_fac = 3
    1587              :       END IF
    1588           10 :       WRITE (fac_str, '(I16)') min_fac
    1589              : 
    1590              :       ! the start value: the keyword, or for -1 the generous 20 x n_act that the memory check below trims to what fits
    1591           10 :       IF (bse_env%max_subspace_factor == -1) THEN
    1592            0 :          m_start = 20*n_act
    1593           10 :       ELSE IF (bse_env%max_subspace_factor >= min_fac) THEN
    1594           10 :          m_start = bse_env%max_subspace_factor*n_act
    1595              :       ELSE
    1596              :          CALL cp_abort(__LOCATION__, &
    1597              :                        "BSE_ITERAT%MAX_SUBSPACE_FACTOR must be at least "//TRIM(ADJUSTL(fac_str))// &
    1598            0 :                        " (or -1) for the chosen solver")
    1599              :       END IF
    1600           10 :       m_floor = MIN(min_fac*n_act, mv_env%n_ov)
    1601           10 :       m_start = MIN(MAX(m_start, m_floor), mv_env%n_ov)
    1602           10 :       m_max = m_start
    1603              : 
    1604              :       ! the widest kernel call of the driver caps the pass width; the largest RI share of any rank
    1605              :       ! keeps the estimate, and so m_max, identical on all ranks
    1606            4 :       SELECT CASE (driver)
    1607              :       CASE (driver_tda)
    1608            4 :          nb = n_act
    1609              :       CASE (driver_mk)
    1610            4 :          nb = block_size
    1611              :       CASE DEFAULT
    1612           10 :          nb = 2*block_size
    1613              :       END SELECT
    1614           10 :       IF (mv_env%block_cols > 0) nb = MIN(nb, mv_env%block_cols)
    1615           10 :       n_ri_max = mv_env%n_ri_loc
    1616           10 :       CALL mv_env%para_env%max(n_ri_max)
    1617              : 
    1618              :       ! what MEMORY_PER_PROC leaves after the slabs and everything else the rank holds
    1619           10 :       mem_left_GB = bse_memory_left_GB(bse_env%memory_per_proc_gb, mv_env%para_env)
    1620           10 :       CALL davidson_footprint(driver, mv_env, m_max, n_act, block_size, nb, n_ri_max, dist_GB, repl_GB)
    1621           10 :       lowered = dist_GB + repl_GB > mem_left_GB
    1622           10 :       floor_over = .FALSE.
    1623           10 :       IF (lowered) THEN
    1624            0 :          CALL davidson_footprint(driver, mv_env, m_floor, n_act, block_size, nb, n_ri_max, dist_GB, repl_GB)
    1625            0 :          IF (dist_GB + repl_GB > mem_left_GB) THEN
    1626              :             ! nothing smaller than the minimal subspace exists: run with it and say so
    1627            0 :             floor_over = .TRUE.
    1628            0 :             m_max = m_floor
    1629              :          ELSE
    1630              :             ! the footprint grows with m: bisect for the largest m within what is left
    1631              :             m_lo = m_floor
    1632              :             m_hi = m_start
    1633            0 :             DO WHILE (m_hi - m_lo > 1)
    1634            0 :                m_mid = (m_lo + m_hi)/2
    1635            0 :                CALL davidson_footprint(driver, mv_env, m_mid, n_act, block_size, nb, n_ri_max, dist_GB, repl_GB)
    1636            0 :                IF (dist_GB + repl_GB <= mem_left_GB) THEN
    1637              :                   m_lo = m_mid
    1638              :                ELSE
    1639            0 :                   m_hi = m_mid
    1640              :                END IF
    1641              :             END DO
    1642            0 :             m_max = m_lo
    1643            0 :             CALL davidson_footprint(driver, mv_env, m_max, n_act, block_size, nb, n_ri_max, dist_GB, repl_GB)
    1644              :          END IF
    1645              :       END IF
    1646           10 :       IF (unit_nr > 0) THEN
    1647            5 :          WRITE (unit_nr, '(T2,A4)') 'BSE|'
    1648            5 :          IF (bse_env%max_subspace_factor == -1) THEN
    1649            0 :             WRITE (unit_nr, '(T2,A4,T7,A,T71,I10)') 'BSE|', 'Maximum subspace dimension (20 x buffered states)', &
    1650            0 :                m_start
    1651              :          ELSE
    1652            5 :             WRITE (unit_nr, '(T2,A4,T7,A,T71,I10)') 'BSE|', 'Maximum subspace dimension (MAX_SUBSPACE_FACTOR)', &
    1653           10 :                m_start
    1654              :          END IF
    1655            5 :          IF (m_max < m_start) THEN
    1656            0 :             WRITE (unit_nr, '(T2,A4,T7,A,T71,I10)') 'BSE|', 'Maximum subspace dimension lowered to the memory left', &
    1657            0 :                m_max
    1658              :          END IF
    1659            5 :          WRITE (unit_nr, '(T2,A4,T7,A)') 'BSE|', 'Memory per MPI rank at the subspace ceiling (GB)'
    1660            5 :          WRITE (unit_nr, '(T2,A4,T9,A,T67,F14.3)') 'BSE|', 'Distributed arrays', dist_GB
    1661            5 :          WRITE (unit_nr, '(T2,A4,T9,A,T67,F14.3)') 'BSE|', 'Replicated arrays', repl_GB
    1662            5 :          WRITE (unit_nr, '(T2,A4,T9,A,T67,F14.3)') 'BSE|', 'Total', dist_GB + repl_GB
    1663            5 :          WRITE (unit_nr, '(T2,A4,T7,A,T67,F14.3)') 'BSE|', 'Memory per MPI rank for the BSE, MEMORY_PER_PROC (GB)', &
    1664           10 :             bse_env%memory_per_proc_gb
    1665            5 :          WRITE (unit_nr, '(T2,A4,T7,A,T67,F14.3)') 'BSE|', 'Left for the solver after the memory held (GB)', &
    1666           10 :             mem_left_GB
    1667            5 :          WRITE (unit_nr, '(T2,A4)') 'BSE|'
    1668              :       END IF
    1669           10 :       IF (floor_over) THEN
    1670            0 :          WRITE (mem_str, '(F16.3)') dist_GB + repl_GB
    1671            0 :          WRITE (bud_str, '(F16.3)') mem_left_GB
    1672              :          CALL cp_warn(__LOCATION__, &
    1673              :                       "BSE Davidson: the minimal subspace of "//TRIM(ADJUSTL(fac_str))//" vectors per state needs "// &
    1674              :                       TRIM(ADJUSTL(mem_str))//" GB per MPI rank, "//TRIM(ADJUSTL(bud_str))// &
    1675            0 :                       " GB are left of MEMORY_PER_PROC; running with it. Raise MEMORY_PER_PROC or use more MPI ranks.")
    1676              :       END IF
    1677              : 
    1678           10 :    END SUBROUTINE subspace_ceiling
    1679              : 
    1680              : ! **************************************************************************************************
    1681              : !> \brief Memory per MPI rank of the solver's arrays at subspace dimension m, split into the family
    1682              : !>        spread over the ranks and the family every rank holds whole. The counts are those of the
    1683              : !>        ALLOCATE and cp_fm_create statements of the drivers at a thick restart, their peak:
    1684              : !>        distributed 8 B (N_ov (n_basis m + n_work + n_scratch) + (n_red + n_solve) m^2)/P,
    1685              : !>        replicated 8 B (c_coef m n_act + m block_size + n_mv N_ov nb + n_ri nb + n_virt virt^2)
    1686              : !> \param driver driver_tda, driver_mk or driver_os
    1687              : !> \param mv_env n_ov, virt and the communicator
    1688              : !> \param m subspace dimension
    1689              : !> \param n_act tracked states
    1690              : !> \param block_size correction vectors per iteration
    1691              : !> \param nb kernel pass width
    1692              : !> \param n_ri RI functions of a rank, the largest over the ranks
    1693              : !> \param dist_GB distributed family, falls as 1/P
    1694              : !> \param repl_GB replicated family, flat in P
    1695              : ! **************************************************************************************************
    1696           10 :    SUBROUTINE davidson_footprint(driver, mv_env, m, n_act, block_size, nb, n_ri, dist_GB, repl_GB)
    1697              : 
    1698              :       INTEGER, INTENT(IN)                                :: driver
    1699              :       TYPE(bse_matvec_env_type), INTENT(IN)              :: mv_env
    1700              :       INTEGER, INTENT(IN)                                :: m, n_act, block_size, nb, n_ri
    1701              :       REAL(KIND=dp), INTENT(OUT)                         :: dist_GB, repl_GB
    1702              : 
    1703              :       INTEGER                                            :: c_coef, n_basis, n_mv, n_red, n_scratch, &
    1704              :                                                             n_solve, n_virt, n_work
    1705              :       REAL(KIND=dp)                                      :: m_real, n_ov_real
    1706              : 
    1707              :       ! distributed 8 B (N_ov (n_basis m + n_work + n_scratch) + (n_red + n_solve) m^2)/P: the trial vector
    1708              :       ! arrays, the work and scratch columns, the reduced and the per-solve m x m matrices;
    1709              :       ! replicated 8 B (c_coef m n_act + m block_size + n_mv N_ov nb + n_ri nb + n_virt virt^2): the m x n_act
    1710              :       ! coefficient blocks with the restart work array, the pass buffers of the kernel, virt x virt for B
    1711           14 :       SELECT CASE (driver)
    1712              :       CASE (driver_tda)
    1713            4 :          n_basis = 2
    1714            4 :          n_work = MIN(2*n_act, m)
    1715            4 :          n_scratch = 0
    1716            4 :          n_red = 1
    1717            4 :          n_solve = 2
    1718            4 :          c_coef = 8
    1719            4 :          n_mv = 3
    1720            4 :          n_virt = 0
    1721              :       CASE (driver_mk)
    1722            4 :          n_basis = 3
    1723            4 :          n_work = MIN(2*n_act, m)
    1724            4 :          n_scratch = block_size
    1725            4 :          n_red = 1
    1726            4 :          n_solve = 2
    1727            4 :          c_coef = 10
    1728            4 :          n_mv = 4
    1729            4 :          n_virt = 1
    1730              :       CASE (driver_os)
    1731            2 :          n_basis = 3
    1732            2 :          n_work = MAX(2*n_act, MIN(4*n_act, m))
    1733            2 :          n_scratch = 2*block_size
    1734            2 :          n_red = 2
    1735            2 :          n_solve = 6
    1736            2 :          c_coef = 15
    1737            2 :          n_mv = 4
    1738            2 :          n_virt = 1
    1739              :       CASE DEFAULT
    1740              :          ! unreachable for the three driver constants; the DEFAULT keeps every counter defined
    1741           10 :          CPABORT("BSE Davidson: unknown driver in the memory estimate")
    1742              :       END SELECT
    1743              : 
    1744              :       ! in REAL: m^2 overflows INTEGER(4) above 46340
    1745           10 :       m_real = REAL(m, dp)
    1746           10 :       n_ov_real = REAL(mv_env%n_ov, dp)
    1747              :       dist_GB = 8.0E-9_dp*(n_ov_real*REAL(n_basis*m + n_work + n_scratch, dp) + REAL(n_red + n_solve, dp)*m_real*m_real)/ &
    1748           10 :                 REAL(mv_env%para_env%num_pe, dp)
    1749              :       repl_GB = 8.0E-9_dp*(REAL(c_coef, dp)*m_real*REAL(n_act, dp) + m_real*REAL(block_size, dp) + &
    1750              :                            REAL(n_mv, dp)*n_ov_real*REAL(nb, dp) + REAL(n_ri, dp)*REAL(nb, dp) + &
    1751           10 :                            REAL(n_virt, dp)*REAL(mv_env%virt, dp)**2)
    1752              : 
    1753           10 :    END SUBROUTINE davidson_footprint
    1754              : 
    1755              : ! **************************************************************************************************
    1756              : !> \brief Unit vectors Z_ia,k = δ_ia,diag_order(k) on the entries diag_order(1..n_used) with the lowest diagonal, never
    1757              : !>        cutting a degenerate group. The sorted diagonal is replicated; each rank writes the entries
    1758              : !>        that fall on its own rows
    1759              : !> \param diag the diagonal chosen by PRECONDITIONER, replicated
    1760              : !> \param n_guess guess vectors wanted
    1761              : !> \param n_max largest number of guess vectors
    1762              : !> \param deg_thresh_diag entries of the sorted diagonal closer than this form one degenerate group
    1763              : !> \param fm_Z receives the unit vectors in its columns 1..n_used
    1764              : !> \param n_used guess vectors written, n_guess <= n_used <= n_max
    1765              : !> \param n_given leading columns that the caller has filled; they replace the lowest unit vectors
    1766              : ! **************************************************************************************************
    1767            8 :    SUBROUTINE initial_guess(diag, n_guess, n_max, deg_thresh_diag, fm_Z, n_used, n_given)
    1768              : 
    1769              :       REAL(KIND=dp), DIMENSION(:), INTENT(IN)            :: diag
    1770              :       INTEGER, INTENT(IN)                                :: n_guess, n_max
    1771              :       REAL(KIND=dp), INTENT(IN)                          :: deg_thresh_diag
    1772              :       TYPE(cp_fm_type), INTENT(IN)                       :: fm_Z
    1773              :       INTEGER, INTENT(OUT)                               :: n_used
    1774              :       INTEGER, INTENT(IN), OPTIONAL                      :: n_given
    1775              : 
    1776              :       INTEGER                                            :: iloc, k, k_first, n_ov, nrow_local
    1777            8 :       INTEGER, ALLOCATABLE, DIMENSION(:)                 :: diag_order
    1778            8 :       INTEGER, DIMENSION(:), POINTER                     :: row_indices
    1779              :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:)           :: diag_sorted
    1780              : 
    1781            8 :       n_ov = SIZE(diag)
    1782           40 :       ALLOCATE (diag_sorted(n_ov), diag_order(n_ov))
    1783          392 :       diag_sorted(:) = diag(:)
    1784            8 :       CALL sort(diag_sorted, n_ov, diag_order)
    1785              : 
    1786            8 :       n_used = multiplet_end(diag_sorted, n_guess, n_max, deg_thresh_diag)
    1787              : 
    1788            8 :       k_first = 1
    1789            8 :       IF (PRESENT(n_given)) k_first = n_given + 1
    1790              : 
    1791            8 :       CALL cp_fm_get_info(fm_Z, nrow_local=nrow_local, row_indices=row_indices)
    1792           64 :       DO k = k_first, n_used
    1793         1408 :          DO iloc = 1, nrow_local
    1794         1400 :             IF (row_indices(iloc) == diag_order(k)) fm_Z%local_data(iloc, k) = 1.0_dp
    1795              :          END DO
    1796              :       END DO
    1797              : 
    1798            8 :       DEALLOCATE (diag_sorted, diag_order)
    1799              : 
    1800           16 :    END SUBROUTINE initial_guess
    1801              : 
    1802              : ! **************************************************************************************************
    1803              : !> \brief Initial guess from the exact A (and B) on the n_sub transitions with the lowest diagonal:
    1804              : !>        TDA: sum_q A_sub,pq V_qk = θ_k V_pk; ABBA: x_pk = sum_q (K_sub^-1/2)_pq t_qk with
    1805              : !>        sum_qrs (K_sub^1/2)_pq M_sub,qr (K_sub^1/2)_rs t_sk = θ_k^2 t_pk, K = A-B, M = A+B. The Ritz
    1806              : !>        values θ_k are upper bounds of the true energies (Rayleigh-Ritz for TDA, Cauchy-type
    1807              : !>        interlacing of Bai and Li for the linear response problem), kept for check_guess_bound. A
    1808              : !>        degenerate group at the upper boundary is taken as a whole. The block and its eigenvectors
    1809              : !>        are replicated; each rank writes the entries that fall on its own rows
    1810              : !> \param mv_env the matrix-free A and B, for the exact block
    1811              : !> \param bse_env NUM_GUESS_TRANSITIONS and BSE_DEBUG_PRINT
    1812              : !> \param diag the diagonal chosen by PRECONDITIONER, replicated; its lowest entries select the block
    1813              : !> \param n_guess guess vectors wanted
    1814              : !> \param n_max largest number of guess vectors
    1815              : !> \param deg_thresh_diag Ritz values closer than this form one degenerate group
    1816              : !> \param fm_Z receives the guess vectors in its columns 1..n_used
    1817              : !> \param n_used guess vectors written, n_guess <= n_used <= n_max; 0 for abba_indefinite
    1818              : !> \param theta_sub allocated here, the n_sub Ritz values in Hartree
    1819              : !> \param unit_nr output unit, positive on the writing rank only
    1820              : !> \param n_given leading columns that the caller has filled; they replace the lowest guess vectors
    1821              : !> \param abba_status ABBA problem when present; abba_indefinite if K_sub is not positive definite
    1822              : !> \param ab_margin smallest eigenvalue of K_sub in Hartree
    1823              : !> \param n_pair ABBA: partners y_k = K_sub x_k/θ_k of the guess vectors x_k not given by the caller,
    1824              : !>        written to the n_pair columns after n_used; n_used + n_pair stays within n_max
    1825              : ! **************************************************************************************************
    1826            2 :    SUBROUTINE initial_guess_subblock(mv_env, bse_env, diag, n_guess, n_max, deg_thresh_diag, fm_Z, n_used, &
    1827              :                                      theta_sub, unit_nr, n_given, abba_status, ab_margin, n_pair)
    1828              : 
    1829              :       TYPE(bse_matvec_env_type), INTENT(IN)              :: mv_env
    1830              :       TYPE(bse_env_type), INTENT(IN)                     :: bse_env
    1831              :       REAL(KIND=dp), DIMENSION(:), INTENT(IN)            :: diag
    1832              :       INTEGER, INTENT(IN)                                :: n_guess, n_max
    1833              :       REAL(KIND=dp), INTENT(IN)                          :: deg_thresh_diag
    1834              :       TYPE(cp_fm_type), INTENT(IN)                       :: fm_Z
    1835              :       INTEGER, INTENT(OUT)                               :: n_used
    1836              :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:), &
    1837              :          INTENT(OUT)                                     :: theta_sub
    1838              :       INTEGER, INTENT(IN)                                :: unit_nr
    1839              :       INTEGER, INTENT(IN), OPTIONAL                      :: n_given
    1840              :       INTEGER, INTENT(OUT), OPTIONAL                     :: abba_status
    1841              :       REAL(KIND=dp), INTENT(OUT), OPTIONAL               :: ab_margin
    1842              :       INTEGER, INTENT(OUT), OPTIONAL                     :: n_pair
    1843              : 
    1844              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'initial_guess_subblock'
    1845              : 
    1846              :       INTEGER                                            :: handle, iloc, k, k_first, n_ov, n_sub, &
    1847              :                                                             n_top, nrow_local
    1848            2 :       INTEGER, ALLOCATABLE, DIMENSION(:)                 :: diag_order, rank_in_block
    1849            2 :       INTEGER, DIMENSION(:), POINTER                     :: row_indices
    1850              :       LOGICAL                                            :: ok
    1851            2 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:)           :: diag_sorted, eig_K
    1852            2 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :)        :: A_sub, B_sub, eigvec_H, eigvec_K, &
    1853            2 :                                                             guess_x, guess_y, H_sub, K_mhalf, &
    1854            2 :                                                             K_phalf, K_sub, M_sub
    1855              :       TYPE(mp_para_env_type), POINTER                    :: para_env
    1856              : 
    1857            2 :       CALL timeset(routineN, handle)
    1858              : 
    1859            2 :       IF (PRESENT(n_pair)) n_pair = 0
    1860            2 :       para_env => mv_env%para_env
    1861            2 :       n_ov = SIZE(diag)
    1862            2 :       n_sub = MIN(n_ov, MAX(bse_env%num_guess_transitions, n_guess))
    1863           12 :       ALLOCATE (diag_sorted(n_ov), diag_order(n_ov), rank_in_block(n_ov))
    1864           98 :       diag_sorted(:) = diag(:)
    1865            2 :       CALL sort(diag_sorted, n_ov, diag_order)
    1866              : 
    1867           16 :       ALLOCATE (A_sub(n_sub, n_sub), guess_x(n_sub, n_sub), theta_sub(n_sub))
    1868            2 :       ok = .TRUE.
    1869            2 :       IF (PRESENT(abba_status)) THEN
    1870            0 :          abba_status = abba_ok
    1871              :          ALLOCATE (B_sub(n_sub, n_sub), K_sub(n_sub, n_sub), M_sub(n_sub, n_sub), H_sub(n_sub, n_sub), &
    1872              :                    eigvec_K(n_sub, n_sub), eigvec_H(n_sub, n_sub), K_phalf(n_sub, n_sub), &
    1873            0 :                    K_mhalf(n_sub, n_sub), eig_K(n_sub))
    1874            0 :          CALL bse_matvec_subblock(mv_env, diag_order(1:n_sub), A_sub, B_sub)
    1875              :          ! (K_sub^±1/2)_pq = sum_r U_pr κ_r^±1/2 U_qr from K_sub,pq = sum_r U_pr κ_r U_qr
    1876            0 :          K_sub(:, :) = A_sub(:, :) - B_sub(:, :)
    1877            0 :          CALL solve_replicated(K_sub, n_sub, para_env, eig_K, eigvec_K)
    1878            0 :          ab_margin = eig_K(1)
    1879            0 :          IF (eig_K(1) <= 0.0_dp) THEN
    1880            0 :             abba_status = abba_indefinite
    1881            0 :             ok = .FALSE.
    1882            0 :             n_used = 0
    1883              :          ELSE
    1884            0 :             DO k = 1, n_sub
    1885            0 :                K_phalf(:, k) = eigvec_K(:, k)*SQRT(eig_K(k))
    1886            0 :                K_mhalf(:, k) = eigvec_K(:, k)/SQRT(eig_K(k))
    1887              :             END DO
    1888            0 :             K_phalf(:, :) = MATMUL(K_phalf, TRANSPOSE(eigvec_K))
    1889            0 :             K_mhalf(:, :) = MATMUL(K_mhalf, TRANSPOSE(eigvec_K))
    1890              :             ! M_sub = 2 A_sub - K_sub, H_ps = sum_qr (K^1/2)_pq M_qr (K^1/2)_rs, x_pk = sum_q (K^-1/2)_pq t_qk
    1891            0 :             M_sub(:, :) = 2.0_dp*A_sub(:, :) - K_sub(:, :)
    1892            0 :             H_sub(:, :) = MATMUL(K_phalf, MATMUL(M_sub, K_phalf))
    1893            0 :             CALL solve_replicated(H_sub, n_sub, para_env, theta_sub, eigvec_H)
    1894              :             ! the same failure as in solve_reduced_paired: with K_sub positive definite, M_sub is indefinite
    1895            0 :             IF (theta_sub(1) <= 0.0_dp) THEN
    1896            0 :                CPABORT("BSE Davidson: the guess block gives a non-positive squared excitation energy")
    1897              :             END IF
    1898            0 :             theta_sub(:) = SQRT(theta_sub(:))
    1899            0 :             guess_x(:, :) = MATMUL(K_mhalf, eigvec_H)
    1900            0 :             IF (PRESENT(n_pair)) THEN
    1901              :                ! partners guess_y_k = K_sub guess_x_k/θ_k
    1902            0 :                ALLOCATE (guess_y(n_sub, n_sub))
    1903            0 :                guess_y(:, :) = MATMUL(K_sub, guess_x)
    1904            0 :                DO k = 1, n_sub
    1905            0 :                   guess_y(:, k) = guess_y(:, k)/theta_sub(k)
    1906              :                END DO
    1907              :             END IF
    1908              :          END IF
    1909            0 :          DEALLOCATE (B_sub, K_sub, M_sub, H_sub, eigvec_K, eigvec_H, K_phalf, K_mhalf, eig_K)
    1910              :       ELSE
    1911            2 :          CALL bse_matvec_subblock(mv_env, diag_order(1:n_sub), A_sub)
    1912            2 :          CALL solve_replicated(A_sub, n_sub, para_env, theta_sub, guess_x)
    1913              :       END IF
    1914              : 
    1915            0 :       IF (ok) THEN
    1916            2 :          k_first = 1
    1917            2 :          IF (PRESENT(n_given)) k_first = n_given + 1
    1918              : 
    1919            2 :          n_top = MIN(n_max, n_sub)
    1920              :          ! the partners of the columns k_first..n_used share the n_max columns with the guess
    1921            2 :          IF (PRESENT(n_pair)) n_top = MIN(n_top, (n_max + k_first - 1)/2)
    1922            2 :          n_used = multiplet_end(theta_sub, n_guess, n_top, deg_thresh_diag)
    1923              : 
    1924            2 :          rank_in_block(:) = 0
    1925           98 :          DO k = 1, n_sub
    1926           98 :             rank_in_block(diag_order(k)) = k
    1927              :          END DO
    1928            2 :          CALL cp_fm_get_info(fm_Z, nrow_local=nrow_local, row_indices=row_indices)
    1929           18 :          DO k = k_first, n_used
    1930          402 :             DO iloc = 1, nrow_local
    1931          400 :                IF (rank_in_block(row_indices(iloc)) > 0) fm_Z%local_data(iloc, k) = guess_x(rank_in_block(row_indices(iloc)), k)
    1932              :             END DO
    1933              :          END DO
    1934            2 :          IF (PRESENT(n_pair)) THEN
    1935            0 :             n_pair = MIN(n_used - k_first + 1, n_max - n_used)
    1936            0 :             DO k = 1, n_pair
    1937            0 :                DO iloc = 1, nrow_local
    1938            0 :                   IF (rank_in_block(row_indices(iloc)) > 0) THEN
    1939            0 :                      fm_Z%local_data(iloc, n_used + k) = guess_y(rank_in_block(row_indices(iloc)), k_first + k - 1)
    1940              :                   END IF
    1941              :                END DO
    1942              :             END DO
    1943              :          END IF
    1944              : 
    1945            2 :          IF (unit_nr > 0) THEN
    1946            1 :             WRITE (unit_nr, '(T2,A4,T7,A,T71,I10)') 'BSE|', 'Transitions in the exact guess block', n_sub
    1947            1 :             IF (bse_env%bse_debug_print) THEN
    1948            0 :                WRITE (unit_nr, '(T2,A10,T13,A,T67,F14.6)') 'BSE|DEBUG|', &
    1949            0 :                   'Lowest Ritz value of the guess block (eV)', theta_sub(1)*evolt
    1950              :             END IF
    1951              :          END IF
    1952              :       END IF
    1953              : 
    1954            2 :       DEALLOCATE (diag_sorted, diag_order, rank_in_block, A_sub, guess_x)
    1955            2 :       IF (ALLOCATED(guess_y)) DEALLOCATE (guess_y)
    1956              : 
    1957            2 :       CALL timestop(handle)
    1958              : 
    1959            4 :    END SUBROUTINE initial_guess_subblock
    1960              : 
    1961              : ! **************************************************************************************************
    1962              : !> \brief A converged energy above the Ritz value of the guess block with the same index is a
    1963              : !>        provable miss: both are upper bounds of the true eigenvalue with that index
    1964              : !> \param theta_sub Ritz values of the guess block in Hartree, ascending
    1965              : !> \param energies converged energies in Hartree
    1966              : !> \param n_req roots compared, the required ones
    1967              : !> \param unit_nr output unit, positive on the writing rank only
    1968              : ! **************************************************************************************************
    1969            2 :    SUBROUTINE check_guess_bound(theta_sub, energies, n_req, unit_nr)
    1970              : 
    1971              :       REAL(KIND=dp), DIMENSION(:), INTENT(IN)            :: theta_sub, energies
    1972              :       INTEGER, INTENT(IN)                                :: n_req, unit_nr
    1973              : 
    1974              :       REAL(KIND=dp)                                      :: excess
    1975              : 
    1976           10 :       excess = MAXVAL(energies(1:n_req) - theta_sub(1:n_req))
    1977            2 :       IF (unit_nr > 0) THEN
    1978            1 :          WRITE (unit_nr, '(T2,A4,T7,A,T65,F16.6)') 'BSE|', &
    1979            2 :             'Largest excess over the guess-block bound (eV)', excess*evolt
    1980              :       END IF
    1981            2 :       IF (excess > deg_thresh .AND. unit_nr > 0) THEN
    1982              :          CALL cp_warn(__LOCATION__, &
    1983              :                       "A converged BSE state lies above the upper bound given by the guess block, "// &
    1984              :                       "so a lower state was missed. Raise BSE_ITERAT%NUM_GUESS_TRANSITIONS or "// &
    1985            0 :                       "BSE_ITERAT%NUM_BUFFER_STATES.")
    1986              :       END IF
    1987              : 
    1988            2 :    END SUBROUTINE check_guess_bound
    1989              : 
    1990              : ! **************************************************************************************************
    1991              : !> \brief sum_q (red_pq + red_qp)/2 c_qk = θ_k c_pk for p, q <= m, red_pq the live block of fm_red, solved
    1992              : !>        on the grid of blacs_env: θ_k in theta ascending, c_pk of the first n_vec k gathered into
    1993              : !>        coef_ritz
    1994              : !> \param fm_red the reduced matrix; its live block is the first m rows and columns
    1995              : !> \param m dimension of the live block
    1996              : !> \param n_vec eigenvectors gathered; the drivers never read more than n_act
    1997              : !> \param para_env communicator of the grid
    1998              : !> \param blacs_env grid the reduced problem is solved on
    1999              : !> \param theta θ_k in the first m entries, zero beyond
    2000              : !> \param coef_ritz c_pk in the first m rows and n_vec columns, zero beyond
    2001              : ! **************************************************************************************************
    2002           62 :    SUBROUTINE solve_reduced(fm_red, m, n_vec, para_env, blacs_env, theta, coef_ritz)
    2003              : 
    2004              :       TYPE(cp_fm_type), INTENT(IN)                       :: fm_red
    2005              :       INTEGER, INTENT(IN)                                :: m, n_vec
    2006              :       TYPE(mp_para_env_type), INTENT(IN), TARGET         :: para_env
    2007              :       TYPE(cp_blacs_env_type), INTENT(IN), TARGET        :: blacs_env
    2008              :       REAL(KIND=dp), DIMENSION(:), INTENT(OUT)           :: theta
    2009              :       REAL(KIND=dp), DIMENSION(:, :), INTENT(OUT)        :: coef_ritz
    2010              : 
    2011              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'solve_reduced'
    2012              : 
    2013              :       INTEGER                                            :: handle, n_get
    2014              :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:)           :: eigval
    2015              :       TYPE(cp_fm_type)                                   :: fm_reduced_eigvec, fm_reduced_sym
    2016              : 
    2017           62 :       CALL timeset(routineN, handle)
    2018              : 
    2019           62 :       CALL reduced_live_block(fm_red, m, para_env, blacs_env, "bse_reduced", fm_reduced_sym)
    2020           62 :       CALL cp_fm_create(fm_reduced_eigvec, fm_reduced_sym%matrix_struct, name="bse_reduced_vectors")
    2021              :       ! a_pq <- (red_pq + red_qp)/2
    2022           62 :       CALL symmetrise_in_place(fm_reduced_sym, fm_reduced_eigvec)
    2023          186 :       ALLOCATE (eigval(m))
    2024           62 :       eigval(:) = 0.0_dp
    2025           62 :       CALL choose_eigv_solver(fm_reduced_sym, fm_reduced_eigvec, eigval)
    2026              : 
    2027         1724 :       theta(:) = 0.0_dp
    2028          944 :       theta(1:m) = eigval(:)
    2029        12326 :       coef_ritz(:, :) = 0.0_dp
    2030           62 :       n_get = MIN(m, n_vec)
    2031           62 :       CALL cp_fm_get_submatrix(fm_reduced_eigvec, coef_ritz(1:m, 1:n_get), 1, 1, m, n_get)
    2032              : 
    2033           62 :       DEALLOCATE (eigval)
    2034           62 :       CALL cp_fm_release(fm_reduced_sym)
    2035           62 :       CALL cp_fm_release(fm_reduced_eigvec)
    2036              : 
    2037           62 :       CALL timestop(handle)
    2038              : 
    2039           62 :    END SUBROUTINE solve_reduced
    2040              : 
    2041              : ! **************************************************************************************************
    2042              : !> \brief sum_q (mat_pq + mat_qp)/2 coef_qk = θ_k coef_pk for p, q <= m, a small replicated block solved
    2043              : !>        on one rank and broadcast: the fixed-size blocks of the guess and of cholqr2, never the
    2044              : !>        reduced matrix
    2045              : !> \param mat the block; its first m rows and columns are read
    2046              : !> \param m dimension of the block
    2047              : !> \param para_env communicator; the solve runs on its source rank
    2048              : !> \param theta ascending
    2049              : !> \param coef all m eigenvectors in the columns
    2050              : ! **************************************************************************************************
    2051            2 :    SUBROUTINE solve_replicated(mat, m, para_env, theta, coef)
    2052              : 
    2053              :       REAL(KIND=dp), DIMENSION(:, :), INTENT(IN)         :: mat
    2054              :       INTEGER, INTENT(IN)                                :: m
    2055              :       TYPE(mp_para_env_type), INTENT(IN)                 :: para_env
    2056              :       REAL(KIND=dp), DIMENSION(:), INTENT(OUT)           :: theta
    2057              :       REAL(KIND=dp), DIMENSION(:, :), INTENT(OUT)        :: coef
    2058              : 
    2059              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'solve_replicated'
    2060              : 
    2061              :       INTEGER                                            :: handle
    2062              :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:)           :: eigval
    2063              :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :)        :: mat_sym
    2064              : 
    2065            2 :       CALL timeset(routineN, handle)
    2066              : 
    2067           12 :       ALLOCATE (mat_sym(m, m), eigval(m))
    2068         4706 :       mat_sym(:, :) = 0.5_dp*(mat(1:m, 1:m) + TRANSPOSE(mat(1:m, 1:m)))
    2069            2 :       eigval(:) = 0.0_dp
    2070            2 :       IF (para_env%is_source()) CALL diamat_all(mat_sym, eigval)
    2071            2 :       CALL para_env%bcast(mat_sym)
    2072            2 :       CALL para_env%bcast(eigval)
    2073              : 
    2074           98 :       theta(:) = 0.0_dp
    2075           98 :       theta(1:m) = eigval(:)
    2076         4706 :       coef(:, :) = 0.0_dp
    2077         4706 :       coef(1:m, 1:m) = mat_sym(:, :)
    2078            2 :       DEALLOCATE (mat_sym, eigval)
    2079              : 
    2080            2 :       CALL timestop(handle)
    2081              : 
    2082            2 :    END SUBROUTINE solve_replicated
    2083              : 
    2084              : ! **************************************************************************************************
    2085              : !> \brief a_pq <- (a_pq + a_qp)/2 through a scratch matrix of the same shape: the eigensolvers read one triangle
    2086              : !> \param fm_a symmetrised in place
    2087              : !> \param fm_scratch overwritten with the transpose
    2088              : ! **************************************************************************************************
    2089          130 :    SUBROUTINE symmetrise_in_place(fm_a, fm_scratch)
    2090              : 
    2091              :       TYPE(cp_fm_type), INTENT(IN)                       :: fm_a, fm_scratch
    2092              : 
    2093          130 :       CALL cp_fm_transpose(fm_a, fm_scratch)
    2094          130 :       CALL cp_fm_scale_and_add(0.5_dp, fm_a, 0.5_dp, fm_scratch)
    2095              : 
    2096          130 :    END SUBROUTINE symmetrise_in_place
    2097              : 
    2098              : ! **************************************************************************************************
    2099              : !> \brief Orthonormal coefficient vectors of the restart basis from the candidate columns in their
    2100              : !>        order of priority, at most n_cap of them: per candidate k, u_p = cand_pk -
    2101              : !>        sum_j (sum_q coef_restart_qj cand_qk) coef_restart_pj over the vectors j kept so far, twice,
    2102              : !>        then coef_restart_p,new = u_p/|u| unless |u| is below coef_norm_drop
    2103              : !> \param cand candidate coefficient columns, zero-padded to m rows: the current Ritz vectors, then
    2104              : !>        the previous ones
    2105              : !> \param m rows of the coefficient vectors, the current basis size
    2106              : !> \param n_cand candidate columns
    2107              : !> \param n_cap largest number of vectors kept
    2108              : !> \param coef_restart m x n_new restart basis
    2109              : !> \param n_new vectors kept, at most MIN(n_cap, n_cand)
    2110              : ! **************************************************************************************************
    2111           26 :    SUBROUTINE restart_basis(cand, m, n_cand, n_cap, coef_restart, n_new)
    2112              : 
    2113              :       REAL(KIND=dp), DIMENSION(:, :), INTENT(IN)         :: cand
    2114              :       INTEGER, INTENT(IN)                                :: m, n_cand, n_cap
    2115              :       REAL(KIND=dp), DIMENSION(:, :), INTENT(OUT)        :: coef_restart
    2116              :       INTEGER, INTENT(OUT)                               :: n_new
    2117              : 
    2118              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'restart_basis'
    2119              :       REAL(KIND=dp), PARAMETER                           :: coef_norm_drop = 1.0E-8_dp
    2120              : 
    2121              :       INTEGER                                            :: handle, ipass, j, k
    2122              :       REAL(KIND=dp)                                      :: norm
    2123           26 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :)        :: basis
    2124              : 
    2125           26 :       CALL timeset(routineN, handle)
    2126              : 
    2127              :       ! never more columns than candidates: the paired solver's cap is close to m_max
    2128          104 :       ALLOCATE (basis(m, MIN(n_cap, n_cand)))
    2129           26 :       n_new = 0
    2130          390 :       DO k = 1, n_cand
    2131          380 :          IF (n_new == n_cap) EXIT
    2132         7084 :          basis(:, n_new + 1) = cand(1:m, k)
    2133              :          ! a previous vector is nearly parallel to its successor, one pass leaves the basis
    2134              :          ! non-orthonormal at the 1e-6 level and stalls the residuals there
    2135         1076 :          DO ipass = 1, 2
    2136         5318 :             DO j = 1, n_new
    2137              :                basis(:, n_new + 1) = basis(:, n_new + 1) - &
    2138       175946 :                                      DOT_PRODUCT(basis(:, j), basis(:, n_new + 1))*basis(:, j)
    2139              :             END DO
    2140        14038 :             norm = NORM2(basis(:, n_new + 1))
    2141          720 :             IF (norm < coef_norm_drop) EXIT
    2142        14272 :             basis(:, n_new + 1) = basis(:, n_new + 1)/norm
    2143              :          END DO
    2144              :          ! relative: a candidate that keeps less than this of its unit norm repeats the vectors kept
    2145          364 :          IF (norm < coef_norm_drop) CYCLE
    2146          390 :          n_new = n_new + 1
    2147              :       END DO
    2148        16490 :       coef_restart(:, :) = 0.0_dp
    2149         6980 :       coef_restart(1:m, 1:n_new) = basis(:, 1:n_new)
    2150           26 :       DEALLOCATE (basis)
    2151              : 
    2152           26 :       CALL timestop(handle)
    2153              : 
    2154           26 :    END SUBROUTINE restart_basis
    2155              : 
    2156              : ! **************************************************************************************************
    2157              : !> \brief out_ia,k = alpha sum_m V_ia,m coef_mk + beta out_ia,k for m <= nv, k <= nc on the local rows ia
    2158              : !>        On the npe x 1 grid whole columns are local, so the rotation is one local DGEMM
    2159              : !> \param fm_V basis, columns 1..nv read
    2160              : !> \param nv columns of fm_V read
    2161              : !> \param coef nv x nc coefficients, replicated
    2162              : !> \param nc columns written
    2163              : !> \param fm_out receives the rotated columns
    2164              : !> \param alpha scale of the product
    2165              : !> \param beta scale of the previous content of fm_out
    2166              : !> \param out_col first column of fm_out written, 1 by default
    2167              : ! **************************************************************************************************
    2168          544 :    SUBROUTINE subspace_rotate(fm_V, nv, coef, nc, fm_out, alpha, beta, out_col)
    2169              : 
    2170              :       TYPE(cp_fm_type), INTENT(IN)                       :: fm_V
    2171              :       INTEGER, INTENT(IN)                                :: nv
    2172              :       REAL(KIND=dp), CONTIGUOUS, DIMENSION(:, :), &
    2173              :          INTENT(IN)                                      :: coef
    2174              :       INTEGER, INTENT(IN)                                :: nc
    2175              :       TYPE(cp_fm_type), INTENT(IN)                       :: fm_out
    2176              :       REAL(KIND=dp), INTENT(IN)                          :: alpha, beta
    2177              :       INTEGER, INTENT(IN), OPTIONAL                      :: out_col
    2178              : 
    2179              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'subspace_rotate'
    2180              : 
    2181              :       INTEGER                                            :: handle, nrow_local, o_col
    2182              : 
    2183          272 :       CALL timeset(routineN, handle)
    2184              : 
    2185          272 :       o_col = 1
    2186          272 :       IF (PRESENT(out_col)) o_col = out_col
    2187          272 :       CALL cp_fm_get_info(fm_V, nrow_local=nrow_local)
    2188          272 :       IF (nrow_local > 0) THEN
    2189              :          CALL DGEMM('N', 'N', nrow_local, nc, nv, alpha, fm_V%local_data, SIZE(fm_V%local_data, 1), &
    2190          272 :                     coef, SIZE(coef, 1), beta, fm_out%local_data(:, o_col:o_col + nc - 1), SIZE(fm_out%local_data, 1))
    2191              :       END IF
    2192              : 
    2193          272 :       CALL timestop(handle)
    2194              : 
    2195          272 :    END SUBROUTINE subspace_rotate
    2196              : 
    2197              : ! **************************************************************************************************
    2198              : !> \brief V_ia,k <- sum_p V_ia,p coef_pk for p <= m, k <= nq through the work matrix, and the same rotation
    2199              : !>        of up to two further matrices that share the basis, so that a thick restart is one call
    2200              : !> \param fm_V basis; on exit columns 1..nq hold the rotation and nq+1..m are zero
    2201              : !> \param m columns of fm_V read
    2202              : !> \param coef restart basis, m x nq
    2203              : !> \param nq columns of the rotated basis
    2204              : !> \param fm_work at least nq columns
    2205              : !> \param fm_V2 rotated alike
    2206              : !> \param fm_V3 rotated alike
    2207              : ! **************************************************************************************************
    2208           26 :    SUBROUTINE rotate_in_place(fm_V, m, coef, nq, fm_work, fm_V2, fm_V3)
    2209              : 
    2210              :       TYPE(cp_fm_type), INTENT(IN)                       :: fm_V
    2211              :       INTEGER, INTENT(IN)                                :: m
    2212              :       REAL(KIND=dp), DIMENSION(:, :), INTENT(IN)         :: coef
    2213              :       INTEGER, INTENT(IN)                                :: nq
    2214              :       TYPE(cp_fm_type), INTENT(IN)                       :: fm_work
    2215              :       TYPE(cp_fm_type), INTENT(IN), OPTIONAL             :: fm_V2, fm_V3
    2216              : 
    2217           26 :       CALL rotate_one(fm_V)
    2218           26 :       IF (PRESENT(fm_V2)) CALL rotate_one(fm_V2)
    2219           26 :       IF (PRESENT(fm_V3)) CALL rotate_one(fm_V3)
    2220              : 
    2221              :    CONTAINS
    2222              : 
    2223              : ! **************************************************************************************************
    2224              : !> \brief The rotation of one matrix
    2225              : !> \param fm rotated in place
    2226              : ! **************************************************************************************************
    2227          144 :       SUBROUTINE rotate_one(fm)
    2228              : 
    2229              :       TYPE(cp_fm_type), INTENT(IN)                       :: fm
    2230              : 
    2231              :       INTEGER                                            :: nrow_local
    2232              : 
    2233        19664 :          CALL subspace_rotate(fm, m, coef(1:m, 1:nq), nq, fm_work, 1.0_dp, 0.0_dp)
    2234           72 :          CALL cp_fm_to_fm(fm_work, fm, nq)
    2235           72 :          CALL cp_fm_get_info(fm, nrow_local=nrow_local)
    2236         8922 :          fm%local_data(1:nrow_local, nq + 1:m) = 0.0_dp
    2237              : 
    2238           72 :       END SUBROUTINE rotate_one
    2239              : 
    2240              :    END SUBROUTINE rotate_in_place
    2241              : ! **************************************************************************************************
    2242              : !> \brief T_ia,t0+k-1 <- T_ia,t0+k-1 + alpha U_ia,u0+k-1 for k <= n
    2243              : !>        On the npe x 1 grid whole columns are local, so the update needs no communication
    2244              : !> \param alpha scale of the added columns
    2245              : !> \param fm_U columns added
    2246              : !> \param u0 first column read
    2247              : !> \param fm_T columns updated
    2248              : !> \param t0 first column written
    2249              : !> \param n number of columns
    2250              : ! **************************************************************************************************
    2251          132 :    SUBROUTINE columns_axpy(alpha, fm_U, u0, fm_T, t0, n)
    2252              : 
    2253              :       REAL(KIND=dp), INTENT(IN)                          :: alpha
    2254              :       TYPE(cp_fm_type), INTENT(IN)                       :: fm_U
    2255              :       INTEGER, INTENT(IN)                                :: u0
    2256              :       TYPE(cp_fm_type), INTENT(IN)                       :: fm_T
    2257              :       INTEGER, INTENT(IN)                                :: t0, n
    2258              : 
    2259              :       INTEGER                                            :: nrow_local
    2260              : 
    2261          132 :       CALL cp_fm_get_info(fm_T, nrow_local=nrow_local)
    2262              :       fm_T%local_data(1:nrow_local, t0:t0 + n - 1) = fm_T%local_data(1:nrow_local, t0:t0 + n - 1) + &
    2263        10432 :                                                      alpha*fm_U%local_data(1:nrow_local, u0:u0 + n - 1)
    2264              : 
    2265          132 :    END SUBROUTINE columns_axpy
    2266              : 
    2267              : ! **************************************************************************************************
    2268              : !> \brief G_kl = sum_ia U_ia,u0+k-1 V_ia,v0+l-1 for k <= nu, l <= nv, local product and sum over the ranks
    2269              : !>        The npe x 1 grid splits the rows over the ranks, which is what the one allreduce completes
    2270              : !> \param fm_U left factor
    2271              : !> \param u0 first column of fm_U
    2272              : !> \param nu columns of fm_U
    2273              : !> \param fm_V right factor
    2274              : !> \param v0 first column of fm_V
    2275              : !> \param nv columns of fm_V
    2276              : !> \param para_env communicator of the row-distributed matrices
    2277              : !> \param gram nu x nv, replicated
    2278              : ! **************************************************************************************************
    2279         1120 :    SUBROUTINE subspace_gram(fm_U, u0, nu, fm_V, v0, nv, para_env, gram)
    2280              : 
    2281              :       TYPE(cp_fm_type), INTENT(IN)                       :: fm_U
    2282              :       INTEGER, INTENT(IN)                                :: u0, nu
    2283              :       TYPE(cp_fm_type), INTENT(IN)                       :: fm_V
    2284              :       INTEGER, INTENT(IN)                                :: v0, nv
    2285              :       TYPE(mp_para_env_type), INTENT(IN)                 :: para_env
    2286              :       REAL(KIND=dp), CONTIGUOUS, DIMENSION(:, :), &
    2287              :          INTENT(OUT)                                     :: gram
    2288              : 
    2289              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'subspace_gram'
    2290              : 
    2291              :       INTEGER                                            :: handle, nrow_local
    2292              : 
    2293          560 :       CALL timeset(routineN, handle)
    2294              : 
    2295          560 :       CALL cp_fm_get_info(fm_U, nrow_local=nrow_local)
    2296        21320 :       gram(:, :) = 0.0_dp
    2297          560 :       IF (nrow_local > 0) THEN
    2298              :          CALL DGEMM('T', 'N', nu, nv, nrow_local, 1.0_dp, &
    2299              :                     fm_U%local_data(:, u0:u0 + nu - 1), SIZE(fm_U%local_data, 1), &
    2300              :                     fm_V%local_data(:, v0:v0 + nv - 1), SIZE(fm_V%local_data, 1), &
    2301          560 :                     0.0_dp, gram, SIZE(gram, 1))
    2302              :       END IF
    2303          560 :       CALL para_env%sum(gram)
    2304              : 
    2305          560 :       CALL timestop(handle)
    2306              : 
    2307          560 :    END SUBROUTINE subspace_gram
    2308              : 
    2309              : ! **************************************************************************************************
    2310              : !> \brief Overlaps of the whole basis U with a block of nv columns of V, written into the distributed
    2311              : !>        reduced matrix: fm_red_k,v0+l-1 <- sum_ia U_ia,k V_ia,v0+l-1 for k <= nu, l <= nv, in column
    2312              : !>        blocks of nb so that the replicated temporary is nu x nb and never nu x nv
    2313              : !> \param fm_U the basis, columns 1..nu
    2314              : !> \param nu columns of fm_U, rows of fm_red written
    2315              : !> \param fm_V the block of columns
    2316              : !> \param v0 first column of fm_V read and first column of fm_red written
    2317              : !> \param nv columns of fm_V read
    2318              : !> \param nb width of one column block
    2319              : !> \param para_env communicator of the row-distributed matrices
    2320              : !> \param fm_red the distributed reduced matrix, on the diagonalisation grid
    2321              : ! **************************************************************************************************
    2322           16 :    SUBROUTINE reduced_gram_blocks(fm_U, nu, fm_V, v0, nv, nb, para_env, fm_red)
    2323              : 
    2324              :       TYPE(cp_fm_type), INTENT(IN)                       :: fm_U
    2325              :       INTEGER, INTENT(IN)                                :: nu
    2326              :       TYPE(cp_fm_type), INTENT(IN)                       :: fm_V
    2327              :       INTEGER, INTENT(IN)                                :: v0, nv, nb
    2328              :       TYPE(mp_para_env_type), INTENT(IN)                 :: para_env
    2329              :       TYPE(cp_fm_type), INTENT(IN)                       :: fm_red
    2330              : 
    2331              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'reduced_gram_blocks'
    2332              : 
    2333              :       INTEGER                                            :: c0, handle, nc
    2334           16 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :)        :: gram_block
    2335              : 
    2336           16 :       CALL timeset(routineN, handle)
    2337              : 
    2338           64 :       ALLOCATE (gram_block(nu, nb))
    2339           40 :       DO c0 = v0, v0 + nv - 1, nb
    2340           24 :          nc = MIN(nb, v0 + nv - c0)
    2341           24 :          CALL subspace_gram(fm_U, 1, nu, fm_V, c0, nc, para_env, gram_block(:, 1:nc))
    2342           40 :          CALL cp_fm_set_submatrix(fm_red, gram_block(:, 1:nc), 1, c0, nu, nc)
    2343              :       END DO
    2344           16 :       DEALLOCATE (gram_block)
    2345              : 
    2346           16 :       CALL timestop(handle)
    2347              : 
    2348           16 :    END SUBROUTINE reduced_gram_blocks
    2349              : 
    2350              : ! **************************************************************************************************
    2351              : !> \brief fm_red_p,m+l <- red_block_pl for p <= m+nt and fm_red_m+l,p <- red_block_pl for p <= m,
    2352              : !>        l <= nt: the two blocks a basis extension by nt columns adds to the symmetric reduced matrix
    2353              : !> \param fm_red the reduced matrix, at least m+nt rows and columns
    2354              : !> \param red_block (m+nt) x nt, the new columns' overlaps with the whole extended basis
    2355              : !> \param m live dimension before the extension
    2356              : !> \param nt columns added
    2357              : ! **************************************************************************************************
    2358           74 :    SUBROUTINE reduced_extend(fm_red, red_block, m, nt)
    2359              : 
    2360              :       TYPE(cp_fm_type), INTENT(IN)                       :: fm_red
    2361              :       REAL(KIND=dp), DIMENSION(:, :), INTENT(IN)         :: red_block
    2362              :       INTEGER, INTENT(IN)                                :: m, nt
    2363              : 
    2364           74 :       CALL cp_fm_set_submatrix(fm_red, red_block, 1, m + 1, m + nt, nt)
    2365           74 :       IF (m > 0) CALL cp_fm_set_submatrix(fm_red, red_block(1:m, :), m + 1, 1, nt, m, transpose=.TRUE.)
    2366              : 
    2367           74 :    END SUBROUTINE reduced_extend
    2368              : 
    2369              : ! **************************************************************************************************
    2370              : !> \brief A new m x m matrix on blacs_env holding the live block fm_red(1:m, 1:m)
    2371              : !> \param fm_red the reduced matrix
    2372              : !> \param m dimension of the live block
    2373              : !> \param para_env communicator of the grid
    2374              : !> \param blacs_env grid of the new matrix
    2375              : !> \param name name of the new matrix
    2376              : !> \param fm_live created here, released by the caller
    2377              : ! **************************************************************************************************
    2378          208 :    SUBROUTINE reduced_live_block(fm_red, m, para_env, blacs_env, name, fm_live)
    2379              : 
    2380              :       TYPE(cp_fm_type), INTENT(IN)                       :: fm_red
    2381              :       INTEGER, INTENT(IN)                                :: m
    2382              :       TYPE(mp_para_env_type), INTENT(IN), TARGET         :: para_env
    2383              :       TYPE(cp_blacs_env_type), INTENT(IN), TARGET        :: blacs_env
    2384              :       CHARACTER(LEN=*), INTENT(IN)                       :: name
    2385              :       TYPE(cp_fm_type), INTENT(OUT)                      :: fm_live
    2386              : 
    2387              :       TYPE(cp_fm_struct_type), POINTER                   :: fm_struct
    2388              : 
    2389          104 :       NULLIFY (fm_struct)
    2390              :       CALL cp_fm_struct_create(fm_struct, para_env=para_env, context=blacs_env, &
    2391          104 :                                nrow_global=m, ncol_global=m)
    2392          104 :       CALL cp_fm_create(fm_live, fm_struct, name=name)
    2393          104 :       CALL cp_fm_struct_release(fm_struct)
    2394          104 :       CALL cp_fm_to_fm_submat(fm_red, fm_live, m, m, 1, 1, 1, 1)
    2395              : 
    2396          104 :    END SUBROUTINE reduced_live_block
    2397              : 
    2398              : ! **************************************************************************************************
    2399              : !> \brief fm_red_ij <- sum_pq coef_restart_pi fm_red_pq coef_restart_qj for p, q <= m and i, j <= k,
    2400              : !>        the rest of the matrix zeroed: two distributed products, no replicated m x m
    2401              : !> \param fm_red the reduced matrix, rotated in place
    2402              : !> \param m live dimension before the restart
    2403              : !> \param coef_restart replicated, zero-padded to m rows
    2404              : !> \param k vectors of the restart basis, the live dimension after
    2405              : !> \param para_env communicator of the grid
    2406              : !> \param blacs_env grid of fm_red and of the products
    2407              : ! **************************************************************************************************
    2408           42 :    SUBROUTINE reduced_rotate(fm_red, m, coef_restart, k, para_env, blacs_env)
    2409              : 
    2410              :       TYPE(cp_fm_type), INTENT(IN)                       :: fm_red
    2411              :       INTEGER, INTENT(IN)                                :: m
    2412              :       REAL(KIND=dp), DIMENSION(:, :), INTENT(IN)         :: coef_restart
    2413              :       INTEGER, INTENT(IN)                                :: k
    2414              :       TYPE(mp_para_env_type), INTENT(IN), TARGET         :: para_env
    2415              :       TYPE(cp_blacs_env_type), INTENT(IN), TARGET        :: blacs_env
    2416              : 
    2417              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'reduced_rotate'
    2418              : 
    2419              :       INTEGER                                            :: handle
    2420              :       TYPE(cp_fm_struct_type), POINTER                   :: fm_struct
    2421              :       TYPE(cp_fm_type)                                   :: fm_GQ, fm_live, fm_Q, fm_QGQ
    2422              : 
    2423           42 :       CALL timeset(routineN, handle)
    2424              : 
    2425           42 :       CALL reduced_live_block(fm_red, m, para_env, blacs_env, "bse_reduced_live", fm_live)
    2426           42 :       NULLIFY (fm_struct)
    2427              :       CALL cp_fm_struct_create(fm_struct, para_env=para_env, context=blacs_env, &
    2428           42 :                                nrow_global=m, ncol_global=k)
    2429           42 :       CALL cp_fm_create(fm_Q, fm_struct, name="bse_restart_basis")
    2430           42 :       CALL cp_fm_create(fm_GQ, fm_struct, name="bse_reduced_GQ")
    2431           42 :       CALL cp_fm_struct_release(fm_struct)
    2432              :       CALL cp_fm_struct_create(fm_struct, para_env=para_env, context=blacs_env, &
    2433           42 :                                nrow_global=k, ncol_global=k)
    2434           42 :       CALL cp_fm_create(fm_QGQ, fm_struct, name="bse_reduced_QGQ")
    2435           42 :       CALL cp_fm_struct_release(fm_struct)
    2436              : 
    2437           42 :       CALL cp_fm_set_submatrix(fm_Q, coef_restart(1:m, 1:k))
    2438              :       ! GQ_pj = sum_q fm_red_pq coef_restart_qj, then QGQ_ij = sum_p coef_restart_pi GQ_pj
    2439           42 :       CALL parallel_gemm('N', 'N', m, k, m, 1.0_dp, fm_live, fm_Q, 0.0_dp, fm_GQ)
    2440           42 :       CALL parallel_gemm('T', 'N', k, k, m, 1.0_dp, fm_Q, fm_GQ, 0.0_dp, fm_QGQ)
    2441           42 :       CALL cp_fm_set_all(fm_red, 0.0_dp)
    2442           42 :       CALL cp_fm_to_fm_submat(fm_QGQ, fm_red, k, k, 1, 1, 1, 1)
    2443              : 
    2444           42 :       CALL cp_fm_release(fm_live)
    2445           42 :       CALL cp_fm_release(fm_Q)
    2446           42 :       CALL cp_fm_release(fm_GQ)
    2447           42 :       CALL cp_fm_release(fm_QGQ)
    2448              : 
    2449           42 :       CALL timestop(handle)
    2450              : 
    2451           42 :    END SUBROUTINE reduced_rotate
    2452              : 
    2453              : ! **************************************************************************************************
    2454              : !> \brief max_kl |sum_ia U_ia,k V_ia,l - δ_kl| over k, l <= m, in column blocks of nb
    2455              : !> \param fm_U left basis
    2456              : !> \param fm_V right basis, fm_U for the Euclidean case
    2457              : !> \param m columns compared
    2458              : !> \param nb width of one column block
    2459              : !> \param para_env communicator of the row-distributed matrices
    2460              : !> \return the largest deviation
    2461              : ! **************************************************************************************************
    2462            2 :    FUNCTION orthonormality_deviation(fm_U, fm_V, m, nb, para_env) RESULT(dev)
    2463              : 
    2464              :       TYPE(cp_fm_type), INTENT(IN)                       :: fm_U, fm_V
    2465              :       INTEGER, INTENT(IN)                                :: m, nb
    2466              :       TYPE(mp_para_env_type), INTENT(IN)                 :: para_env
    2467              :       REAL(KIND=dp)                                      :: dev
    2468              : 
    2469              :       INTEGER                                            :: c0, l, nc
    2470            2 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :)        :: gram_block
    2471              : 
    2472            8 :       ALLOCATE (gram_block(m, nb))
    2473            2 :       dev = 0.0_dp
    2474            2 :       DO c0 = 1, m, nb
    2475            6 :          nc = MIN(nb, m - c0 + 1)
    2476            6 :          CALL subspace_gram(fm_U, 1, m, fm_V, c0, nc, para_env, gram_block(:, 1:nc))
    2477           42 :          DO l = 1, nc
    2478           42 :             gram_block(c0 + l - 1, l) = gram_block(c0 + l - 1, l) - 1.0_dp
    2479              :          END DO
    2480          690 :          dev = MAX(dev, MAXVAL(ABS(gram_block(:, 1:nc))))
    2481              :       END DO
    2482            2 :       DEALLOCATE (gram_block)
    2483              : 
    2484            2 :    END FUNCTION orthonormality_deviation
    2485              : 
    2486              : ! **************************************************************************************************
    2487              : !> \brief Euclidean norms of nt columns of a row-distributed matrix
    2488              : !>        Each rank sums the squares of its own rows of the npe x 1 grid, then one allreduce
    2489              : !> \param fm_T row-distributed matrix
    2490              : !> \param first_col first column measured
    2491              : !> \param nt number of columns
    2492              : !> \param para_env communicator of the rows
    2493              : !> \param norms nt Euclidean norms
    2494              : ! **************************************************************************************************
    2495          168 :    SUBROUTINE column_norms(fm_T, first_col, nt, para_env, norms)
    2496              : 
    2497              :       TYPE(cp_fm_type), INTENT(IN)                       :: fm_T
    2498              :       INTEGER, INTENT(IN)                                :: first_col, nt
    2499              :       TYPE(mp_para_env_type), INTENT(IN)                 :: para_env
    2500              :       REAL(KIND=dp), DIMENSION(:), INTENT(OUT)           :: norms
    2501              : 
    2502              :       INTEGER                                            :: k, nrow_local
    2503              : 
    2504          168 :       CALL cp_fm_get_info(fm_T, nrow_local=nrow_local)
    2505         1022 :       norms(:) = 0.0_dp
    2506         1022 :       DO k = 1, nt
    2507        21518 :          norms(k) = SUM(fm_T%local_data(1:nrow_local, first_col + k - 1)**2)
    2508              :       END DO
    2509         1876 :       CALL para_env%sum(norms)
    2510         1022 :       norms(:) = SQRT(norms(:))
    2511              : 
    2512          168 :    END SUBROUTINE column_norms
    2513              : 
    2514              : ! **************************************************************************************************
    2515              : !> \brief Davidson corrections t_ia,k = r_ia,k/(d_ia - θ_k) of the selected roots k, written to fm_Z
    2516              : !>        Each rank divides the entries of its own rows of the npe x 1 grid, no communication
    2517              : !> \param fm_R residuals, column r_offset + k belongs to root k
    2518              : !> \param selected indices of the roots corrected
    2519              : !> \param theta Ritz values, indexed by root
    2520              : !> \param diag d_ia, replicated
    2521              : !> \param fm_Z receives the corrections
    2522              : !> \param first_col first column of fm_Z written
    2523              : !> \param r_offset columns of fm_R before the residuals, 0 by default
    2524              : ! **************************************************************************************************
    2525           76 :    SUBROUTINE davidson_corrections(fm_R, selected, theta, diag, fm_Z, first_col, r_offset)
    2526              : 
    2527              :       TYPE(cp_fm_type), INTENT(IN)                       :: fm_R
    2528              :       INTEGER, DIMENSION(:), INTENT(IN)                  :: selected
    2529              :       REAL(KIND=dp), DIMENSION(:), INTENT(IN)            :: theta, diag
    2530              :       TYPE(cp_fm_type), INTENT(IN)                       :: fm_Z
    2531              :       INTEGER, INTENT(IN)                                :: first_col
    2532              :       INTEGER, INTENT(IN), OPTIONAL                      :: r_offset
    2533              : 
    2534              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'davidson_corrections'
    2535              :       REAL(KIND=dp), PARAMETER :: eref_scale = 0.99_dp, threshold = 16.0_dp*EPSILON(1.0_dp)
    2536              : 
    2537              :       INTEGER                                            :: handle, iloc, it, k, nrow_local, r_off
    2538           76 :       INTEGER, DIMENSION(:), POINTER                     :: row_indices
    2539              :       REAL(KIND=dp)                                      :: denom
    2540              : 
    2541           76 :       CALL timeset(routineN, handle)
    2542              : 
    2543           76 :       r_off = 0
    2544           76 :       IF (PRESENT(r_offset)) r_off = r_offset
    2545           76 :       CALL cp_fm_get_info(fm_Z, nrow_local=nrow_local, row_indices=row_indices)
    2546          268 :       DO it = 1, SIZE(selected)
    2547          192 :          k = selected(it)
    2548         4876 :          DO iloc = 1, nrow_local
    2549         4608 :             denom = diag(row_indices(iloc)) - theta(k)
    2550              :             ! near-degeneracy guard as in tddfpt_compute_residual_vects: threshold detects a numerically
    2551              :             ! zero d_ia - θ_k, which the shift (1 - eref_scale) θ_k replaces by the denominator at 0.99 θ_k
    2552         4608 :             IF (ABS(denom) < threshold) denom = denom + (1.0_dp - eref_scale)*theta(k)
    2553         4800 :             fm_Z%local_data(iloc, first_col + it - 1) = fm_R%local_data(iloc, r_off + k)/denom
    2554              :          END DO
    2555              :       END DO
    2556              : 
    2557           76 :       CALL timestop(handle)
    2558              : 
    2559           76 :    END SUBROUTINE davidson_corrections
    2560              : 
    2561              : ! **************************************************************************************************
    2562              : !> \brief T_ia,k <- T_ia,k - sum_m V_ia,m sum_jb U_jb,m T_jb,k for m <= nv and nt columns k, twice;
    2563              : !>        U = V for orthonormal columns V, else the dual basis with sum_ia U_ia,m V_ia,n = δ_mn
    2564              : !>        One allreduce per pass inside the Gram, the subtraction stays on the rows of the npe x 1 grid
    2565              : !> \param fm_T columns projected
    2566              : !> \param first_col first column of fm_T projected
    2567              : !> \param nt number of columns projected
    2568              : !> \param fm_V the basis projected out
    2569              : !> \param nv columns of fm_V
    2570              : !> \param para_env communicator of the row-distributed matrices
    2571              : !> \param fm_dual U
    2572              : ! **************************************************************************************************
    2573           82 :    SUBROUTINE project_out(fm_T, first_col, nt, fm_V, nv, para_env, fm_dual)
    2574              : 
    2575              :       TYPE(cp_fm_type), INTENT(IN)                       :: fm_T
    2576              :       INTEGER, INTENT(IN)                                :: first_col, nt
    2577              :       TYPE(cp_fm_type), INTENT(IN)                       :: fm_V
    2578              :       INTEGER, INTENT(IN)                                :: nv
    2579              :       TYPE(mp_para_env_type), INTENT(IN)                 :: para_env
    2580              :       TYPE(cp_fm_type), INTENT(IN), OPTIONAL             :: fm_dual
    2581              : 
    2582              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'project_out'
    2583              : 
    2584              :       INTEGER                                            :: handle, ipass, nrow_local
    2585              :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :)        :: coeff
    2586              : 
    2587           82 :       IF (nt == 0 .OR. nv == 0) RETURN
    2588           74 :       CALL timeset(routineN, handle)
    2589           74 :       CALL cp_fm_get_info(fm_T, nrow_local=nrow_local)
    2590          296 :       ALLOCATE (coeff(nv, nt))
    2591          222 :       DO ipass = 1, 2
    2592          148 :          IF (PRESENT(fm_dual)) THEN
    2593           56 :             CALL subspace_gram(fm_dual, 1, nv, fm_T, first_col, nt, para_env, coeff)
    2594              :          ELSE
    2595           92 :             CALL subspace_gram(fm_V, 1, nv, fm_T, first_col, nt, para_env, coeff)
    2596              :          END IF
    2597          222 :          IF (nrow_local > 0) THEN
    2598              :             CALL DGEMM('N', 'N', nrow_local, nt, nv, -1.0_dp, &
    2599              :                        fm_V%local_data, SIZE(fm_V%local_data, 1), coeff, nv, 1.0_dp, &
    2600          148 :                        fm_T%local_data(:, first_col:first_col + nt - 1), SIZE(fm_T%local_data, 1))
    2601              :          END IF
    2602              :       END DO
    2603           74 :       DEALLOCATE (coeff)
    2604           74 :       CALL timestop(handle)
    2605              : 
    2606           74 :    END SUBROUTINE project_out
    2607              : 
    2608              : ! **************************************************************************************************
    2609              : !> \brief Normalises nt columns and removes those that vanished in the projection
    2610              : !>        Only the norms communicate; the scaling and the zero-fill stay on the local rows
    2611              : !> \param fm_T row-distributed matrix; the kept columns move to the front of the block
    2612              : !> \param first_col first column of the block
    2613              : !> \param nt on exit the number of columns kept
    2614              : !> \param para_env communicator of the rows
    2615              : ! **************************************************************************************************
    2616           82 :    SUBROUTINE drop_small_columns(fm_T, first_col, nt, para_env)
    2617              : 
    2618              :       TYPE(cp_fm_type), INTENT(IN)                       :: fm_T
    2619              :       INTEGER, INTENT(IN)                                :: first_col
    2620              :       INTEGER, INTENT(INOUT)                             :: nt
    2621              :       TYPE(mp_para_env_type), INTENT(IN)                 :: para_env
    2622              : 
    2623              :       REAL(KIND=dp), PARAMETER                           :: col_norm_drop = 1.0E-10_dp
    2624              : 
    2625              :       INTEGER                                            :: k, n_kept, nrow_local
    2626              :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:)           :: norms
    2627              : 
    2628           82 :       IF (nt == 0) RETURN
    2629           80 :       CALL cp_fm_get_info(fm_T, nrow_local=nrow_local)
    2630          240 :       ALLOCATE (norms(nt))
    2631           80 :       CALL column_norms(fm_T, first_col, nt, para_env, norms)
    2632           80 :       n_kept = 0
    2633          314 :       DO k = 1, nt
    2634              :          ! absolute: the corrections r/(d - θ) arrive unnormalised, a column below this is numerically zero
    2635          234 :          IF (norms(k) < col_norm_drop) CYCLE
    2636          234 :          n_kept = n_kept + 1
    2637              :          fm_T%local_data(1:nrow_local, first_col + n_kept - 1) = &
    2638         5930 :             fm_T%local_data(1:nrow_local, first_col + k - 1)/norms(k)
    2639              :       END DO
    2640           80 :       fm_T%local_data(1:nrow_local, first_col + n_kept:first_col + nt - 1) = 0.0_dp
    2641           80 :       nt = n_kept
    2642           80 :       DEALLOCATE (norms)
    2643              : 
    2644           80 :    END SUBROUTINE drop_small_columns
    2645              : 
    2646              : ! **************************************************************************************************
    2647              : !> \brief Orthonormalises nt columns by two Cholesky QR passes on the replicated Gram matrix,
    2648              : !>        T_ia,k <- sum_l T_ia,l (R^-1)_lk with sum_p R_pk R_pl = G_kl = sum_ia T_ia,k T_ia,l. A
    2649              : !>        failed factorization means a numerically dependent block: the directions of the Gram matrix
    2650              : !>        below the drop tolerance are removed (canonical orthogonalisation), nt shrinks, and the
    2651              : !>        passes start again. The Gram is the only communication: R is factorised on one rank and
    2652              : !>        broadcast, the triangular solve runs on the rows of the npe x 1 grid
    2653              : !> \param fm_T the block to orthonormalise, columns first_col .. first_col+nt-1
    2654              : !> \param first_col first column of the block
    2655              : !> \param nt columns of the block; on exit the number kept
    2656              : !> \param para_env communicator of the row-distributed matrix
    2657              : !> \param ok .FALSE. when two drop rounds still leave no factorisable Gram matrix, or no direction survives
    2658              : !> \param n_dropped columns removed as dependent
    2659              : ! **************************************************************************************************
    2660           82 :    SUBROUTINE cholqr2(fm_T, first_col, nt, para_env, ok, n_dropped)
    2661              : 
    2662              :       TYPE(cp_fm_type), INTENT(IN)                       :: fm_T
    2663              :       INTEGER, INTENT(IN)                                :: first_col
    2664              :       INTEGER, INTENT(INOUT)                             :: nt
    2665              :       TYPE(mp_para_env_type), INTENT(IN)                 :: para_env
    2666              :       LOGICAL, INTENT(OUT)                               :: ok
    2667              :       INTEGER, INTENT(OUT), OPTIONAL                     :: n_dropped
    2668              : 
    2669              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'cholqr2'
    2670              :       REAL(KIND=dp), PARAMETER                           :: eig_drop_rel = 1.0E-10_dp
    2671              : 
    2672              :       INTEGER                                            :: handle, info, ipass, k, n_drop_calls, &
    2673              :                                                             n_keep, nrow_local
    2674           82 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:)           :: eig
    2675           82 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :)        :: chol_factor, gram, gram_eigvec, T_reduced
    2676              : 
    2677           82 :       ok = .TRUE.
    2678           82 :       IF (PRESENT(n_dropped)) n_dropped = 0
    2679           82 :       IF (nt == 0) RETURN
    2680           80 :       CALL timeset(routineN, handle)
    2681           80 :       CALL cp_fm_get_info(fm_T, nrow_local=nrow_local)
    2682          480 :       ALLOCATE (gram(nt, nt), chol_factor(nt, nt))
    2683              : 
    2684           80 :       n_drop_calls = 0
    2685           80 :       ipass = 0
    2686          240 :       DO WHILE (ipass < 2)
    2687          160 :          ipass = ipass + 1
    2688              :          ! G_kl = sum_ia T_ia,k T_ia,l = sum_p R_pk R_pl
    2689          160 :          CALL subspace_gram(fm_T, first_col, nt, fm_T, first_col, nt, para_env, gram)
    2690         2448 :          chol_factor(:, :) = gram(:, :)
    2691          160 :          info = 0
    2692          160 :          IF (para_env%is_source()) CALL DPOTRF('U', nt, chol_factor, nt, info)
    2693          160 :          CALL para_env%bcast(info)
    2694          160 :          IF (info /= 0) THEN
    2695            0 :             n_drop_calls = n_drop_calls + 1
    2696            0 :             IF (n_drop_calls > 2) THEN
    2697            0 :                ok = .FALSE.
    2698            0 :                EXIT
    2699              :             END IF
    2700              :             ! T_ia,k <- sum_l T_ia,l U_lk Λ_k^-1/2 over the eigenpairs of G above the drop tolerance,
    2701              :             ! eig_drop_rel of the largest eigenvalue: directions below it are numerically dependent
    2702            0 :             ALLOCATE (eig(nt), gram_eigvec(nt, nt))
    2703            0 :             CALL solve_replicated(gram, nt, para_env, eig, gram_eigvec)
    2704            0 :             n_keep = COUNT(eig > eig_drop_rel*eig(nt))
    2705            0 :             IF (n_keep == 0) THEN
    2706            0 :                ok = .FALSE.
    2707            0 :                DEALLOCATE (eig, gram_eigvec)
    2708            0 :                EXIT
    2709              :             END IF
    2710            0 :             DO k = 1, n_keep
    2711            0 :                gram_eigvec(:, nt - n_keep + k) = gram_eigvec(:, nt - n_keep + k)/SQRT(eig(nt - n_keep + k))
    2712              :             END DO
    2713            0 :             IF (nrow_local > 0) THEN
    2714            0 :                ALLOCATE (T_reduced(nrow_local, n_keep))
    2715              :                CALL DGEMM('N', 'N', nrow_local, n_keep, nt, 1.0_dp, &
    2716              :                           fm_T%local_data(:, first_col:first_col + nt - 1), SIZE(fm_T%local_data, 1), &
    2717            0 :                           gram_eigvec(:, nt - n_keep + 1:nt), nt, 0.0_dp, T_reduced, nrow_local)
    2718            0 :                fm_T%local_data(1:nrow_local, first_col:first_col + n_keep - 1) = T_reduced(:, :)
    2719            0 :                fm_T%local_data(1:nrow_local, first_col + n_keep:first_col + nt - 1) = 0.0_dp
    2720            0 :                DEALLOCATE (T_reduced)
    2721              :             END IF
    2722            0 :             IF (PRESENT(n_dropped)) n_dropped = n_dropped + nt - n_keep
    2723            0 :             nt = n_keep
    2724            0 :             DEALLOCATE (eig, gram_eigvec, gram, chol_factor)
    2725            0 :             ALLOCATE (gram(nt, nt), chol_factor(nt, nt))
    2726            0 :             ipass = 0
    2727            0 :             CYCLE
    2728              :          END IF
    2729              :          ! T_ia,k <- sum_l T_ia,l (R^-1)_lk on the local rows
    2730          160 :          CALL para_env%bcast(chol_factor)
    2731          240 :          IF (nrow_local > 0) THEN
    2732              :             CALL DTRSM('R', 'U', 'N', 'N', nrow_local, nt, 1.0_dp, chol_factor, nt, &
    2733          160 :                        fm_T%local_data(:, first_col:first_col + nt - 1), SIZE(fm_T%local_data, 1))
    2734              :          END IF
    2735              :       END DO
    2736              : 
    2737           80 :       DEALLOCATE (gram, chol_factor)
    2738           80 :       CALL timestop(handle)
    2739              : 
    2740          162 :    END SUBROUTINE cholqr2
    2741              : 
    2742              : ! **************************************************************************************************
    2743              : !> \brief Makes the nt columns T after column m of fm_V orthonormal to the basis and to each other:
    2744              : !>        T_ia,k <- T_ia,k - sum_p V_ia,p sum_jb U_jb,p T_jb,k twice, the columns that vanished dropped, then
    2745              : !>        the Euclidean cholqr2; nt shrinks by the vanished and the dependent columns
    2746              : !> \param fm_V basis in columns 1..m, the block T in columns m+1..m+nt
    2747              : !> \param m columns of the basis
    2748              : !> \param nt columns of T; on exit the number kept
    2749              : !> \param para_env communicator of the row-distributed matrix
    2750              : !> \param n_dependent counter of the columns dropped as dependent, incremented
    2751              : !> \param fm_dual U, the dual basis with sum_ia U_ia,p V_ia,q = δ_pq; fm_V itself when absent
    2752              : ! **************************************************************************************************
    2753           82 :    SUBROUTINE extend_orthonormal(fm_V, m, nt, para_env, n_dependent, fm_dual)
    2754              : 
    2755              :       TYPE(cp_fm_type), INTENT(IN)                       :: fm_V
    2756              :       INTEGER, INTENT(IN)                                :: m
    2757              :       INTEGER, INTENT(INOUT)                             :: nt
    2758              :       TYPE(mp_para_env_type), INTENT(IN)                 :: para_env
    2759              :       INTEGER, INTENT(INOUT)                             :: n_dependent
    2760              :       TYPE(cp_fm_type), INTENT(IN), OPTIONAL             :: fm_dual
    2761              : 
    2762              :       INTEGER                                            :: n_dropped
    2763              :       LOGICAL                                            :: ok
    2764              : 
    2765           82 :       CALL project_out(fm_V, m + 1, nt, fm_V, m, para_env, fm_dual)
    2766           82 :       CALL drop_small_columns(fm_V, m + 1, nt, para_env)
    2767           82 :       CALL cholqr2(fm_V, m + 1, nt, para_env, ok, n_dropped)
    2768              :       ! cholqr2 gives up after two rounds of dropping dependent directions, or when none is left
    2769           82 :       IF (.NOT. ok) CPABORT("BSE Davidson: orthonormalisation broke down")
    2770           82 :       n_dependent = n_dependent + n_dropped
    2771              : 
    2772           82 :    END SUBROUTINE extend_orthonormal
    2773              : 
    2774              : ! **************************************************************************************************
    2775              : !> \brief Largest deviation of the nt new columns from orthonormality against the whole basis,
    2776              : !>        sum_ia V_ia,m D_ia,n - δ_mn for m = 1..nv+nt, n = nv+1..nv+nt; D = V in the Euclidean case
    2777              : !> \param fm_V the basis with its nt new columns
    2778              : !> \param fm_dual D, fm_V itself in the Euclidean case
    2779              : !> \param nv columns of the basis before the extension
    2780              : !> \param nt new columns
    2781              : !> \param para_env communicator of the row-distributed matrices
    2782              : !> \return the largest deviation
    2783              : ! **************************************************************************************************
    2784           86 :    FUNCTION extension_deviation(fm_V, fm_dual, nv, nt, para_env) RESULT(dev)
    2785              : 
    2786              :       TYPE(cp_fm_type), INTENT(IN)                       :: fm_V, fm_dual
    2787              :       INTEGER, INTENT(IN)                                :: nv, nt
    2788              :       TYPE(mp_para_env_type), INTENT(IN)                 :: para_env
    2789              :       REAL(KIND=dp)                                      :: dev
    2790              : 
    2791              :       INTEGER                                            :: k
    2792           86 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :)        :: gram
    2793              : 
    2794           86 :       dev = 0.0_dp
    2795           86 :       IF (nt == 0) RETURN
    2796          336 :       ALLOCATE (gram(nv + nt, nt))
    2797           84 :       CALL subspace_gram(fm_V, 1, nv + nt, fm_dual, nv + 1, nt, para_env, gram)
    2798          348 :       DO k = 1, nt
    2799          348 :          gram(nv + k, k) = gram(nv + k, k) - 1.0_dp
    2800              :       END DO
    2801         4012 :       dev = MAXVAL(ABS(gram))
    2802           84 :       DEALLOCATE (gram)
    2803              : 
    2804           86 :    END FUNCTION extension_deviation
    2805              : 
    2806              : ! **************************************************************************************************
    2807              : !> \brief Debug check of a Davidson result against the full diagonalization of the explicit
    2808              : !>        matrices: energies, and per multiplet the smallest singular value of X_ref^T X for the
    2809              : !>        TDA, or of X_ref^T X - Y_ref^T Y for ABBA. ABBA diagonalizes the Hermitian reduction
    2810              : !>        C = U (A+B) U^T, A-B = U^T U, with C T^n = (Ω^n)^2 T^n,
    2811              : !>        (X+Y)^n = (Ω^n)^-1/2 U^T T^n, (X-Y)^n = (Ω^n)^1/2 U^-1 T^n.
    2812              : !>        A failed reference solve aborts: this is debug output with nothing to fall back on
    2813              : !> \param fm_A_explicit A from create_A_and_B, N_ov x N_ov
    2814              : !> \param exc_ens Davidson energies in Hartree
    2815              : !> \param fm_X Davidson X_ia^n, column n
    2816              : !> \param bse_env handed to create_hermitian_form_of_ABBA
    2817              : !> \param unit_nr output unit, positive on the writing rank only
    2818              : !> \param fm_B_explicit present for an ABBA result, together with fm_Y
    2819              : !> \param fm_Y Davidson Y_ia^n, with fm_B_explicit
    2820              : ! **************************************************************************************************
    2821            2 :    SUBROUTINE bse_davidson_refcheck(fm_A_explicit, exc_ens, fm_X, bse_env, unit_nr, fm_B_explicit, fm_Y)
    2822              : 
    2823              :       TYPE(cp_fm_type), INTENT(IN)                       :: fm_A_explicit
    2824              :       REAL(KIND=dp), DIMENSION(:), INTENT(IN)            :: exc_ens
    2825              :       TYPE(cp_fm_type), INTENT(IN)                       :: fm_X
    2826              :       TYPE(bse_env_type), INTENT(IN)                     :: bse_env
    2827              :       INTEGER, INTENT(IN)                                :: unit_nr
    2828              :       TYPE(cp_fm_type), INTENT(IN), OPTIONAL             :: fm_B_explicit, fm_Y
    2829              : 
    2830              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'bse_davidson_refcheck'
    2831              : 
    2832              :       INTEGER                                            :: diag_info, handle, k, n_ov, n_ref, n_want
    2833              :       REAL(KIND=dp)                                      :: min_overlap
    2834            2 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:)           :: ref_ens
    2835            2 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :)        :: diff_ref, sum_ref, X_dav, X_ref, Y_dav, &
    2836            2 :                                                             Y_ref
    2837              :       TYPE(cp_fm_type)                                   :: fm_A_plus_B, fm_C, fm_chol_A_minus_B, &
    2838              :                                                             fm_eigvec, fm_work
    2839              : 
    2840            2 :       CALL timeset(routineN, handle)
    2841              : 
    2842              :       ! B and Y arrive together or not at all
    2843            2 :       CPASSERT(PRESENT(fm_B_explicit) .EQV. PRESENT(fm_Y))
    2844            2 :       IF (unit_nr > 0) THEN
    2845            1 :          WRITE (unit_nr, '(T2,A4)') 'BSE|'
    2846            1 :          IF (PRESENT(fm_B_explicit)) THEN
    2847            1 :             WRITE (unit_nr, '(T2,A10,T13,A)') 'BSE|DEBUG|', 'Reference check against the explicit A and B'
    2848              :          ELSE
    2849            0 :             WRITE (unit_nr, '(T2,A10,T13,A)') 'BSE|DEBUG|', 'Reference check against the explicit A'
    2850              :          END IF
    2851              :       END IF
    2852            2 :       CALL cp_fm_get_info(fm_A_explicit, nrow_global=n_ov)
    2853            2 :       n_want = SIZE(exc_ens)
    2854            6 :       ALLOCATE (ref_ens(n_ov))
    2855              : 
    2856            2 :       IF (PRESENT(fm_B_explicit)) THEN
    2857              :          CALL create_hermitian_form_of_ABBA(fm_A_explicit, fm_B_explicit, fm_C, fm_chol_A_minus_B, &
    2858            2 :                                             fm_A_plus_B, unit_nr, bse_env)
    2859              :          ! the n_ref columns of X-Y come from the triangular solve here
    2860            2 :          CALL cp_fm_release(fm_A_plus_B)
    2861            2 :          CALL cp_fm_create(fm_eigvec, fm_C%matrix_struct)
    2862            2 :          CALL choose_eigv_solver(fm_C, fm_eigvec, ref_ens, diag_info)
    2863            2 :          IF (diag_info /= 0) CPABORT("Reference diagonalization of C failed in the BSE Davidson check")
    2864            2 :          IF (ref_ens(1) <= 0.0_dp) THEN
    2865              :             CALL cp_abort(__LOCATION__, &
    2866            0 :                           "Reference matrix C has a non-positive eigenvalue in the BSE Davidson check")
    2867              :          END IF
    2868           98 :          ref_ens(:) = SQRT(ref_ens(:))
    2869              : 
    2870            2 :          n_ref = multiplet_end(ref_ens, n_want, n_ov, deg_thresh)
    2871           12 :          ALLOCATE (sum_ref(n_ov, n_ref), diff_ref(n_ov, n_ref))
    2872            2 :          CALL cp_fm_create(fm_work, fm_C%matrix_struct)
    2873              :          ! X+Y ∝ U^T T and X-Y ∝ U^-1 T, with A-B = U^T U
    2874            2 :          CALL cp_fm_to_fm(fm_eigvec, fm_work)
    2875            2 :          CALL cp_fm_triangular_multiply(fm_chol_A_minus_B, fm_work, side="L", transpose_tr=.TRUE., n_cols=n_ref)
    2876            2 :          CALL cp_fm_get_submatrix(fm_work, sum_ref, 1, 1, n_ov, n_ref)
    2877            2 :          CALL cp_fm_to_fm(fm_eigvec, fm_work)
    2878            2 :          CALL cp_fm_triangular_multiply(fm_chol_A_minus_B, fm_work, side="L", invert_tr=.TRUE., n_cols=n_ref)
    2879            2 :          CALL cp_fm_get_submatrix(fm_work, diff_ref, 1, 1, n_ov, n_ref)
    2880            2 :          CALL cp_fm_release(fm_work)
    2881            2 :          CALL cp_fm_release(fm_C)
    2882            2 :          CALL cp_fm_release(fm_chol_A_minus_B)
    2883              : 
    2884           16 :          ALLOCATE (X_ref(n_ov, n_ref), Y_ref(n_ov, n_ref), Y_dav(n_ov, n_want))
    2885            8 :          DO k = 1, n_ref
    2886          294 :             sum_ref(:, k) = sum_ref(:, k)/SQRT(ref_ens(k))
    2887          296 :             diff_ref(:, k) = diff_ref(:, k)*SQRT(ref_ens(k))
    2888              :          END DO
    2889          296 :          X_ref(:, :) = 0.5_dp*(sum_ref(:, :) + diff_ref(:, :))
    2890          296 :          Y_ref(:, :) = 0.5_dp*(sum_ref(:, :) - diff_ref(:, :))
    2891            2 :          DEALLOCATE (sum_ref, diff_ref)
    2892            6 :          CALL cp_fm_get_submatrix(fm_Y, Y_dav)
    2893              :       ELSE
    2894              :          ! the eigensolver destroys its input
    2895            0 :          CALL cp_fm_create(fm_work, fm_A_explicit%matrix_struct)
    2896            0 :          CALL cp_fm_to_fm(fm_A_explicit, fm_work)
    2897            0 :          CALL cp_fm_create(fm_eigvec, fm_A_explicit%matrix_struct)
    2898            0 :          CALL choose_eigv_solver(fm_work, fm_eigvec, ref_ens, diag_info)
    2899            0 :          IF (diag_info /= 0) CPABORT("Reference diagonalization of A failed in the BSE Davidson check")
    2900            0 :          CALL cp_fm_release(fm_work)
    2901              : 
    2902            0 :          n_ref = multiplet_end(ref_ens, n_want, n_ov, deg_thresh)
    2903            0 :          ALLOCATE (X_ref(n_ov, n_ref))
    2904            0 :          CALL cp_fm_get_submatrix(fm_eigvec, X_ref, 1, 1, n_ov, n_ref)
    2905              :       END IF
    2906            2 :       CALL cp_fm_release(fm_eigvec)
    2907              : 
    2908            8 :       ALLOCATE (X_dav(n_ov, n_want))
    2909            2 :       CALL cp_fm_get_submatrix(fm_X, X_dav)
    2910              : 
    2911              :       ! Y_ref and Y_dav stay unallocated for the TDA and then count as absent (Fortran 2008)
    2912            2 :       CALL min_multiplet_overlap(ref_ens, n_want, n_ref, X_ref, X_dav, min_overlap, Y_ref, Y_dav)
    2913            8 :       CALL print_refcheck(MAXVAL(ABS(exc_ens(:) - ref_ens(1:n_want))), min_overlap, unit_nr)
    2914              : 
    2915            2 :       DEALLOCATE (ref_ens, X_ref, X_dav)
    2916            2 :       IF (ALLOCATED(Y_ref)) DEALLOCATE (Y_ref, Y_dav)
    2917              : 
    2918            2 :       CALL timestop(handle)
    2919              : 
    2920            8 :    END SUBROUTINE bse_davidson_refcheck
    2921              : 
    2922              : ! **************************************************************************************************
    2923              : !> \brief Smallest singular value over the multiplets of O_kl = sum_ia (X_ref,ia^k X_ia^l - Y_ref,ia^k Y_ia^l),
    2924              : !>        k over a multiplet of the reference and l over the Davidson states inside it. Degenerate
    2925              : !>        eigenvectors are arbitrary within their multiplet, so the vectors are not compared one by one:
    2926              : !>        every singular value of O is 1 when the Davidson states lie in the span of the multiplet
    2927              : !> \param ref_ens reference energies in Hartree, ascending
    2928              : !> \param n_want Davidson states compared
    2929              : !> \param n_ref reference states up to the end of the multiplet that contains state n_want
    2930              : !> \param X_ref reference X, N_ov x n_ref
    2931              : !> \param X_dav Davidson X, N_ov x n_want
    2932              : !> \param min_overlap the smallest singular value found, 1 if every multiplet is reproduced
    2933              : !> \param Y_ref reference Y for ABBA, with Y_dav
    2934              : !> \param Y_dav Davidson Y for ABBA
    2935              : ! **************************************************************************************************
    2936            2 :    SUBROUTINE min_multiplet_overlap(ref_ens, n_want, n_ref, X_ref, X_dav, min_overlap, Y_ref, Y_dav)
    2937              : 
    2938              :       REAL(KIND=dp), DIMENSION(:), INTENT(IN)            :: ref_ens
    2939              :       INTEGER, INTENT(IN)                                :: n_want, n_ref
    2940              :       REAL(KIND=dp), DIMENSION(:, :), INTENT(IN)         :: X_ref, X_dav
    2941              :       REAL(KIND=dp), INTENT(OUT)                         :: min_overlap
    2942              :       REAL(KIND=dp), DIMENSION(:, :), INTENT(IN), &
    2943              :          OPTIONAL                                        :: Y_ref, Y_dav
    2944              : 
    2945              :       INTEGER                                            :: info, lwork, mult_first, mult_last, &
    2946              :                                                             mult_last_dav
    2947            2 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:)           :: sing_vals, work
    2948            2 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :)        :: overlap
    2949              :       REAL(KIND=dp), DIMENSION(1, 1)                     :: dummy
    2950              : 
    2951            2 :       min_overlap = 1.0_dp
    2952            2 :       mult_first = 1
    2953            8 :       DO WHILE (mult_first <= n_want)
    2954            6 :          mult_last = multiplet_end(ref_ens, mult_first, n_ref, deg_thresh)
    2955            6 :          mult_last_dav = MIN(mult_last, n_want)
    2956           36 :          ALLOCATE (overlap(mult_last - mult_first + 1, mult_last_dav - mult_first + 1), sing_vals(mult_last_dav - mult_first + 1))
    2957          306 :          overlap(:, :) = MATMUL(TRANSPOSE(X_ref(:, mult_first:mult_last)), X_dav(:, mult_first:mult_last_dav))
    2958            6 :          IF (PRESENT(Y_ref)) THEN
    2959          336 :             overlap(:, :) = overlap(:, :) - MATMUL(TRANSPOSE(Y_ref(:, mult_first:mult_last)), Y_dav(:, mult_first:mult_last_dav))
    2960              :          END IF
    2961              :          ! DGESVD wants lwork >= MAX(3 n + m, 5 n) for the m x n overlap with n <= m; 5 m + 10 covers both
    2962            6 :          lwork = 5*(mult_last - mult_first + 1) + 10
    2963           18 :          ALLOCATE (work(lwork))
    2964              :  CALL DGESVD('N', 'N', mult_last - mult_first + 1, mult_last_dav - mult_first + 1, overlap, mult_last - mult_first + 1, sing_vals, &
    2965            6 :                      dummy, 1, dummy, 1, work, lwork, info)
    2966            6 :          IF (info /= 0) CPABORT("SVD failed in the BSE Davidson check")
    2967           12 :          min_overlap = MIN(min_overlap, MINVAL(sing_vals))
    2968            6 :          DEALLOCATE (overlap, sing_vals, work)
    2969            8 :          mult_first = mult_last + 1
    2970              :       END DO
    2971              : 
    2972            2 :    END SUBROUTINE min_multiplet_overlap
    2973              : 
    2974              : ! **************************************************************************************************
    2975              : !> \brief The two lines of a reference check
    2976              : !> \param dev_E largest energy deviation in Hartree
    2977              : !> \param min_overlap smallest singular value from min_multiplet_overlap
    2978              : !> \param unit_nr output unit, positive on the writing rank only
    2979              : ! **************************************************************************************************
    2980            2 :    SUBROUTINE print_refcheck(dev_E, min_overlap, unit_nr)
    2981              : 
    2982              :       REAL(KIND=dp), INTENT(IN)                          :: dev_E, min_overlap
    2983              :       INTEGER, INTENT(IN)                                :: unit_nr
    2984              : 
    2985            2 :       IF (unit_nr > 0) THEN
    2986            1 :          WRITE (unit_nr, '(T2,A10,T13,A,T63,ES18.6)') 'BSE|DEBUG|', &
    2987            2 :             'Max energy deviation vs full diagonalization (eV)', dev_E*evolt
    2988            1 :          WRITE (unit_nr, '(T2,A10,T13,A,T63,F18.12)') 'BSE|DEBUG|', &
    2989            2 :             'Min subspace overlap vs full diagonalization', min_overlap
    2990              :       END IF
    2991              : 
    2992            2 :    END SUBROUTINE print_refcheck
    2993              : 
    2994            6 : END MODULE bse_davidson
        

Generated by: LCOV version 2.0-1