LCOV - code coverage report
Current view: top level - src - gw_auto_ri_generate_RI_basis.F (source / functions) Coverage Total Hit
Test: CP2K Regtests (git:1be8651) Lines: 90.7 % 945 857
Test Date: 2026-11-24 01:22:08 Functions: 97.4 % 39 38

            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 Automatic RI basis set optimization for molecular and periodic GW.
      10              : !> \par History
      11              : !>      09.2026 created [Jan Wilhelm]
      12              : ! **************************************************************************************************
      13              : MODULE gw_auto_ri_generate_RI_basis
      14              :    USE ai_contraction_sphi,             ONLY: ab_contract,&
      15              :                                               abc_contract
      16              :    USE atomic_kind_types,               ONLY: get_atomic_kind_set
      17              :    USE basis_set_types,                 ONLY: get_gto_basis_set,&
      18              :                                               gto_basis_set_type
      19              :    USE constants_operator,              ONLY: operator_coulomb,&
      20              :                                               operator_truncated,&
      21              :                                               operator_verfc
      22              :    USE coulomb_integral_interface,      ONLY: compute_coulomb_2c,&
      23              :                                               compute_coulomb_3c,&
      24              :                                               coulomb_integral_cleanup,&
      25              :                                               coulomb_integral_context_type,&
      26              :                                               coulomb_integral_init,&
      27              :                                               coulomb_operator_type
      28              :    USE cp_blacs_env,                    ONLY: cp_blacs_env_type
      29              :    USE cp_cfm_types,                    ONLY: cp_cfm_get_submatrix
      30              :    USE cp_dbcsr_api,                    ONLY: &
      31              :         dbcsr_create, dbcsr_distribution_get, dbcsr_distribution_new, dbcsr_distribution_release, &
      32              :         dbcsr_distribution_type, dbcsr_finalize, dbcsr_put_block, dbcsr_release, dbcsr_type, &
      33              :         dbcsr_type_symmetric
      34              :    USE cp_dbcsr_operations,             ONLY: copy_dbcsr_to_fm
      35              :    USE cp_fm_basic_linalg,              ONLY: cp_fm_column_scale,&
      36              :                                               cp_fm_syrk,&
      37              :                                               cp_fm_uplo_to_full
      38              :    USE cp_fm_diag,                      ONLY: cp_fm_geeig
      39              :    USE cp_fm_struct,                    ONLY: cp_fm_struct_create,&
      40              :                                               cp_fm_struct_release,&
      41              :                                               cp_fm_struct_type
      42              :    USE cp_fm_types,                     ONLY: cp_fm_create,&
      43              :                                               cp_fm_get_info,&
      44              :                                               cp_fm_release,&
      45              :                                               cp_fm_type
      46              :    USE generic_os_integrals,            ONLY: int_operators_r12_ab_os
      47              :    USE ieee_arithmetic,                 ONLY: ieee_is_finite
      48              :    USE input_constants,                 ONLY: do_potential_coulomb,&
      49              :                                               do_potential_short,&
      50              :                                               do_potential_truncated,&
      51              :                                               ri_rs_small_cell_full_kp,&
      52              :                                               tensor_small_cell_full_kp
      53              :    USE integral_library_types,          ONLY: active_integral_library,&
      54              :                                               coulomb_operator_type,&
      55              :                                               library_libint
      56              :    USE kinds,                           ONLY: dp
      57              :    USE local_gemm_api,                  ONLY: LOCAL_GEMM_PU_HOST,&
      58              :                                               local_gemm_ctxt_type
      59              :    USE machine,                         ONLY: m_walltime
      60              :    USE mathconstants,                   ONLY: z_zero
      61              :    USE mathlib,                         ONLY: diamat_all
      62              :    USE message_passing,                 ONLY: mp_para_env_type
      63              :    USE orbital_pointers,                ONLY: init_orbital_pointers,&
      64              :                                               ncoset
      65              :    USE orbital_transformation_matrices, ONLY: init_spherical_harmonics
      66              :    USE post_scf_bandstructure_types,    ONLY: post_scf_bandstructure_type
      67              :    USE qs_environment_types,            ONLY: get_qs_env,&
      68              :                                               qs_environment_type
      69              :    USE r12_fundamentals,                ONLY: r12_fundamentals_init
      70              :    USE util,                            ONLY: sort
      71              : #include "base/base_uses.f90"
      72              : 
      73              :    IMPLICIT NONE
      74              :    PRIVATE
      75              : 
      76              :    CHARACTER(len=*), PARAMETER, PRIVATE :: moduleN = 'gw_auto_ri_generate_RI_basis'
      77              : 
      78              :    ! Numerical cutoffs for the reference M_PQ eigenspace and final M_pq pseudoinverse.
      79              :    REAL(KIND=dp), PARAMETER :: reference_M_eigenval_threshold = 1.0E-10_dp
      80              :    REAL(KIND=dp), PARAMETER :: optimized_M_eigenval_threshold = 1.0E-6_dp
      81              :    ! Discard null target directions and reject non-positive-semidefinite M_PQ or B_PQ spectra.
      82              :    REAL(KIND=dp), PARAMETER :: relative_target_eigenval_threshold = 1.0E-12_dp
      83              :    REAL(KIND=dp), PARAMETER :: negative_eigenval_tolerance = 1.0E-10_dp
      84              :    REAL(KIND=dp), PARAMETER :: conditioned_negative_eigenval_tolerance = SQRT(EPSILON(1.0_dp))
      85              :    ! Largest accepted deviation of the periodic AA metric from the identity after refinement.
      86              :    REAL(KIND=dp), PARAMETER :: eps_metric_defect = 1.0E-7_dp
      87              : 
      88              :    PUBLIC :: generate_auto_ri_basis
      89              : 
      90              : CONTAINS
      91              : 
      92              : !**************************************************************************************************!
      93              : ! The full derivation of the AUTO_RI algorithm will be published separately.                       !
      94              : !                                                                                                  !
      95              : ! The equations below define the notation used throughout this automatic RI basis optimizer.       !
      96              : !                                                                                                  !
      97              : ! The RI scalar product uses the truncated Coulomb operator:                                       !
      98              : !                                                                                                  !
      99              : ! (f|g) = ∫dr∫dr' f(r) V_rc(r-r') g(r').                                                     (1)   !
     100              : !                                                                                                  !
     101              : ! For the RI basis-set optimization, we consider orbital-product densities formed by               !
     102              : ! AOs on the same atom A:                                                                           !
     103              : !                                                                                                  !
     104              : ! ρ_mn^AA(r) = Σ_{μ∈A} Σ_{ν∈A} C_μm C_νn ϕ_μ(r) ϕ_ν(r).                                      (2)   !
     105              : !                                                                                                  !
     106              : ! The atom-local correlation target B_PQ^{A,C} mimics contributions to the density response χ,     !
     107              : ! and the exchange target B_PQ^{A,X} mimics contributions to the exchange self-energy:             !
     108              : !                                                                                                  !
     109              : ! B_PQ^{A,C} = (1/N_C^A) Σ_ia^oe w_ia (φ_P^A|ρ_ia^AA)(ρ_ia^AA|φ_Q^A).                        (3)   !
     110              : !                                                                                                  !
     111              : ! B_PQ^{A,X} = (1/N_X^A) Σ_{n∈W_occ} Σ_i^occ (φ_P^A|ρ_ni^AA)(ρ_ni^AA|φ_Q^A).                 (4)   !
     112              : !                                                                                                  !
     113              : ! W_occ = [ε_HOMO-E_win, ε_LUMO+E_win], where E_win is OCC_EMPTY_FRONTIER_ORBITAL_WINDOW.          !
     114              : !                                                                                                  !
     115              : ! Here w_ia gives larger weight to frontier-orbital products close to the HOMO and LUMO:           !
     116              : !                                                                                                  !
     117              : ! w_ia = 1/(|ε_i-E_F| |ε_a-E_F|),   E_F = (ε_HOMO+ε_LUMO)/2.                                 (5)   !
     118              : !                                                                                                  !
     119              : ! Diagonalizing B^A = B^{A,C}+B^{A,X} identifies the most important atom-local RI functions        !
     120              : ! that we use in the optimized RI basis set. The contraction coefficients U_Pp^A [see Eq. (7)]     !
     121              : ! used for optimized RI basis functions are obtained from the eigenvalue problem                   !
     122              : !                                                                                                  !
     123              : ! B^A U^A = M^A U^A λ^A,   Σ_Q B_PQ^A U_Qp^A = λ_p^A Σ_Q M_PQ^A U_Qp^A.                      (6)   !
     124              : !                                                                                                  !
     125              : ! The eigenvectors with the largest eigenvalues are the contracted RI functions φ_p^A(r)           !
     126              : ! used for the optimized RI basis set:                                                             !
     127              : !                                                                                                  !
     128              : ! φ_p^A(r) = Σ_P U_Pp^A φ_P^A(r).                                                            (7)   !
     129              : !                                                                                                  !
     130              : ! Molecular and periodic GW retain only the atom-local AA contractions in Eq. (7).                 !
     131              : ! The requested optimized size is distributed among atoms using their target eigenvalues.         !
     132              : !                                                                                                  !
     133              : ! The retained size can be smaller only when B^A or M^A has fewer numerically non-null modes.      !
     134              : !                                                                                                  !
     135              : !**************************************************************************************************!
     136              : 
     137              : ! **************************************************************************************************
     138              : !> \brief Selects molecular or periodic atom-local AA RI-basis optimization.
     139              : !> \param qs_env Quickstep environment needed by the molecular RI metric.
     140              : !> \param bs_env Band-structure environment containing GW parameters.
     141              : ! **************************************************************************************************
     142           12 :    SUBROUTINE generate_auto_ri_basis(qs_env, bs_env)
     143              :       TYPE(qs_environment_type), POINTER                 :: qs_env
     144              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
     145              : 
     146           12 :       IF (bs_env%do_periodic) THEN
     147            8 :          CALL generate_auto_ri_basis_periodic(bs_env)
     148              :       ELSE
     149            4 :          CALL generate_auto_ri_basis_molecular(qs_env, bs_env)
     150              :       END IF
     151              : 
     152           12 :    END SUBROUTINE generate_auto_ri_basis
     153              : 
     154              : ! **************************************************************************************************
     155              : !> \brief Optimizes the molecular AA basis and computes its M⁻¹ and V using Eqs. (1)-(7).
     156              : !> \param qs_env ...
     157              : !> \param bs_env Band-structure environment containing GW parameters.
     158              : ! **************************************************************************************************
     159            4 :    SUBROUTINE generate_auto_ri_basis_molecular(qs_env, bs_env)
     160              :       TYPE(qs_environment_type), POINTER                 :: qs_env
     161              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
     162              : 
     163              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'generate_auto_ri_basis_molecular'
     164              : 
     165              :       INTEGER                                            :: handle
     166              :       REAL(KIND=dp)                                      :: time_start
     167            4 :       REAL(KIND=dp), ALLOCATABLE                         :: U_Pp_A(:, :, :)
     168              : 
     169            4 :       CALL timeset(routineN, handle)
     170              : 
     171            4 :       CPASSERT(.NOT. bs_env%do_periodic)
     172            4 :       time_start = m_walltime()
     173              : 
     174              :       ! Compute AA target matrices B^{AA,C}, B^{AA,X} and contraction U_Pp^A in Eqs. (3)-(7).
     175            4 :       CALL compute_AA_optimized_RI_basis(bs_env, U_Pp_A)
     176              : 
     177            4 :       CALL store_AA_basis(bs_env, U_Pp_A)
     178            4 :       DEALLOCATE (U_Pp_A)
     179              : 
     180              :       ! Form M⁻¹ and V in the optimized molecular RI basis.
     181            4 :       CALL compute_M_pq_inv_and_V_pq_molecular(qs_env, bs_env)
     182              : 
     183              :       ! Print the optimized RI basis dimension and total optimization time.
     184            4 :       CALL print_auto_ri_summary(bs_env, time_start)
     185              : 
     186            4 :       CALL timestop(handle)
     187              : 
     188            4 :    END SUBROUTINE generate_auto_ri_basis_molecular
     189              : 
     190              : ! **************************************************************************************************
     191              : !> \brief Optimizes atom-local AA contractions for periodic GW using Eqs. (1)-(7).
     192              : !> \param bs_env Band-structure environment containing GW parameters.
     193              : ! **************************************************************************************************
     194            8 :    SUBROUTINE generate_auto_ri_basis_periodic(bs_env)
     195              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
     196              : 
     197              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'generate_auto_ri_basis_periodic'
     198              : 
     199              :       INTEGER                                            :: handle
     200              :       REAL(KIND=dp)                                      :: time_start
     201            8 :       REAL(KIND=dp), ALLOCATABLE                         :: U_Pp_A(:, :, :)
     202              : 
     203            8 :       CALL timeset(routineN, handle)
     204              : 
     205            8 :       CPASSERT(bs_env%do_periodic)
     206            8 :       time_start = m_walltime()
     207              : 
     208              :       ! Compute AA target matrices B^{AA,C}, B^{AA,X} and contraction U_Pp^A in Eqs. (3)-(7).
     209            8 :       CALL compute_AA_optimized_RI_basis(bs_env, U_Pp_A)
     210              : 
     211            8 :       CALL store_AA_basis(bs_env, U_Pp_A)
     212            8 :       DEALLOCATE (U_Pp_A)
     213              : 
     214              :       ! Activate AA basis sizes; q-dependent M⁻¹ and V are built in the periodic GW driver.
     215            8 :       CALL set_optimized_RI_basis_sizes(bs_env)
     216              : 
     217              :       ! Print the optimized RI basis dimension and total optimization time.
     218            8 :       CALL print_auto_ri_summary(bs_env, time_start)
     219              : 
     220            8 :       CALL timestop(handle)
     221              : 
     222            8 :    END SUBROUTINE generate_auto_ri_basis_periodic
     223              : 
     224              : ! **************************************************************************************************
     225              : !> \brief Computes the atom-local contraction coefficients U^A from Eqs. (3)-(7):
     226              : !>
     227              : !>          B_PQ^{A,C} = (1/N_C^A) Σ_ia^oe w_ia (φ_P^A|ρ_ia^AA)(ρ_ia^AA|φ_Q^A),         (3)
     228              : !>
     229              : !>          B_PQ^{A,X} = (1/N_X^A) Σ_{n∈W_occ} Σ_i^occ (φ_P^A|ρ_ni^AA)(ρ_ni^AA|φ_Q^A),  (4)
     230              : !>
     231              : !>          w_ia = 1/(|ε_i-E_F| |ε_a-E_F|),  E_F = (ε_HOMO+ε_LUMO)/2,                   (5)
     232              : !>
     233              : !>          B^A U^A = M^A U^A λ^A,                                                      (6)
     234              : !>
     235              : !>          Contracted RI basis functions for optimized RI basis:
     236              : !>
     237              : !>          φ_p^A(r) = Σ_P U_Pp^A φ_P^A(r).                                             (7)
     238              : !>
     239              : !> \param bs_env ...
     240              : !> \param U_Pp_A temporary atom-local contraction coefficients
     241              : ! **************************************************************************************************
     242           12 :    SUBROUTINE compute_AA_optimized_RI_basis(bs_env, U_Pp_A)
     243              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
     244              :       REAL(KIND=dp), ALLOCATABLE, INTENT(OUT)            :: U_Pp_A(:, :, :)
     245              : 
     246              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'compute_AA_optimized_RI_basis'
     247              : 
     248              :       INTEGER :: handle, iatom, ikind, max_nAO_kind, max_nRI_kind, nAO_kind, natom, nkind, &
     249              :          nRI_kind, RI_size_opt_AA_requested, root_rank
     250           12 :       INTEGER, ALLOCATABLE, DIMENSION(:)                 :: kind_of_atom, sizes_opt_RI_AA
     251              :       REAL(KIND=dp)                                      :: target_norm
     252           12 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:)           :: eigenval
     253           12 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :)        :: B_PQ, eigenval_AA, M_PQ, U_Pp_A_atom, &
     254           12 :                                                             X_Pi
     255           12 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :, :)     :: M_PQ_by_kind
     256           12 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :, :, :)  :: Int_3c
     257              : 
     258           12 :       CALL timeset(routineN, handle)
     259              : 
     260              :       ! Determine reference dimensions and the number of AA RI functions (i.e. number of
     261              :       ! eigenvectors U_Pp^A used for RI-basis contractions).
     262              :       CALL initialize_AA_optimization(bs_env, kind_of_atom, natom, nkind, &
     263           12 :                                       max_nRI_kind, RI_size_opt_AA_requested)
     264           48 :       ALLOCATE (eigenval_AA(max_nRI_kind, natom), source=0.0_dp)
     265           36 :       ALLOCATE (sizes_opt_RI_AA(natom))
     266              : 
     267           12 :       CALL initialize_auto_ri_integrals(bs_env)
     268           40 :       max_nAO_kind = MAXVAL(bs_env%sizes_AO)
     269            0 :       ALLOCATE (U_Pp_A(max_nRI_kind, max_nRI_kind, natom), &
     270          108 :                 M_PQ_by_kind(max_nRI_kind, max_nRI_kind, nkind), source=0.0_dp)
     271           72 :       ALLOCATE (Int_3c(max_nAO_kind, max_nAO_kind, max_nRI_kind, nkind), source=0.0_dp)
     272              : 
     273              :       ! The few atom-kind integral blocks are inexpensive; compute them on every rank.
     274           28 :       DO ikind = 1, nkind
     275           16 :          nAO_kind = bs_env%basis_set_AO(ikind)%gto_basis_set%nsgf
     276           16 :          nRI_kind = bs_env%basis_set_RI(ikind)%gto_basis_set%nsgf
     277              :          CALL compute_int_3c( &
     278              :             ao_basis=bs_env%basis_set_AO(ikind)%gto_basis_set, &
     279              :             ri_basis=bs_env%basis_set_RI(ikind)%gto_basis_set, &
     280              :             potential=bs_env%ri_metric, M_PQ=M_PQ, &
     281           16 :             Int_3c=Int_3c(1:nAO_kind, 1:nAO_kind, 1:nRI_kind, ikind))
     282              :          ! Full-k RI-RS applies REGULARIZATION_RI as an eigenvalue cutoff during inversion.
     283           16 :          IF (bs_env%gw_implementation /= ri_rs_small_cell_full_kp) THEN
     284              :             CALL add_RI_metric_regularization(bs_env%basis_set_RI(ikind)%gto_basis_set, &
     285            8 :                                               bs_env%regularization_RI, M_PQ)
     286              :          END IF
     287        79908 :          M_PQ_by_kind(1:nRI_kind, 1:nRI_kind, ikind) = M_PQ
     288           28 :          DEALLOCATE (M_PQ)
     289              :       END DO
     290              : 
     291           40 :       bs_env%auto_ri%sizes_opt_RI = 0
     292           40 :       DO iatom = 1, natom
     293           28 :          root_rank = MODULO(iatom - 1, bs_env%para_env%num_pe)
     294           28 :          ikind = kind_of_atom(iatom)
     295           28 :          nRI_kind = bs_env%basis_set_RI(ikind)%gto_basis_set%nsgf
     296           28 :          nAO_kind = bs_env%sizes_AO(iatom)
     297          112 :          ALLOCATE (M_PQ(nRI_kind, nRI_kind))
     298        93764 :          M_PQ(:, :) = M_PQ_by_kind(1:nRI_kind, 1:nRI_kind, ikind)
     299              :          ! Eqs. (3)-(5): form B^{A,C}, B^{A,X}, and their weighted sum B^A.
     300           28 :          IF (bs_env%do_periodic) THEN
     301              :             CALL compute_B_ij_AA_kaveraged(bs_env, iatom, root_rank, &
     302              :                                            Int_3c(1:nAO_kind, 1:nAO_kind, 1:nRI_kind, ikind), &
     303          868 :                                            M_PQ, B_PQ, target_norm, X_Pi)
     304              :          ELSE
     305              :             CALL compute_B_PQ_AA(bs_env, iatom, root_rank, &
     306              :                                  Int_3c(1:nAO_kind, 1:nAO_kind, 1:nRI_kind, ikind), &
     307        17204 :                                  M_PQ, B_PQ, target_norm)
     308              :          END IF
     309           28 :          DEALLOCATE (M_PQ)
     310           28 :          IF (root_rank /= bs_env%para_env%mepos) THEN
     311           14 :             DEALLOCATE (B_PQ)
     312           14 :             IF (ALLOCATED(X_Pi)) DEALLOCATE (X_Pi)
     313              :             CYCLE
     314              :          END IF
     315              :          ! Eq. (6): solve B^A U^A = M^A U^A λ^A.
     316           14 :          IF (bs_env%do_periodic) THEN
     317              :             CALL solve_AA_eigenproblem_periodic(M_PQ_by_kind(1:nRI_kind, 1:nRI_kind, ikind), &
     318            8 :                                                 X_Pi, B_PQ, target_norm, U_Pp_A_atom, eigenval)
     319            8 :             DEALLOCATE (X_Pi)
     320              :          ELSE
     321              :             CALL solve_AA_eigenproblem(M_PQ_by_kind(1:nRI_kind, 1:nRI_kind, ikind), &
     322            6 :                                        B_PQ, target_norm, U_Pp_A_atom, eigenval)
     323              :          END IF
     324           62 :          eigenval_AA(1:SIZE(U_Pp_A_atom, 2), iatom) = eigenval(1:SIZE(U_Pp_A_atom, 2))
     325           14 :          bs_env%auto_ri%sizes_opt_RI(iatom) = SIZE(U_Pp_A_atom, 2)
     326         4016 :          U_Pp_A(1:SIZE(U_Pp_A_atom, 1), 1:SIZE(U_Pp_A_atom, 2), iatom) = U_Pp_A_atom
     327           26 :          DEALLOCATE (U_Pp_A_atom, eigenval, B_PQ)
     328              :       END DO
     329           12 :       CALL bs_env%para_env%sum(bs_env%auto_ri%sizes_opt_RI)
     330           12 :       CALL bs_env%para_env%sum(U_Pp_A)
     331           12 :       CALL bs_env%para_env%sum(eigenval_AA)
     332           12 :       IF (bs_env%do_periodic) THEN
     333            8 :          CALL select_RI_sizes_periodic(eigenval_AA, RI_size_opt_AA_requested, 1, sizes_opt_RI_AA)
     334              :       ELSE
     335            4 :          CALL select_RI_sizes(eigenval_AA, RI_size_opt_AA_requested, 1, sizes_opt_RI_AA)
     336              :       END IF
     337           40 :       bs_env%auto_ri%sizes_opt_RI(:) = sizes_opt_RI_AA
     338           40 :       DO iatom = 1, natom
     339       194450 :          U_Pp_A(:, sizes_opt_RI_AA(iatom) + 1:, iatom) = 0.0_dp
     340              :       END DO
     341           12 :       DEALLOCATE (Int_3c, M_PQ_by_kind)
     342              : 
     343           12 :       CALL timestop(handle)
     344              : 
     345           24 :    END SUBROUTINE compute_AA_optimized_RI_basis
     346              : 
     347              : ! **************************************************************************************************
     348              : !> \brief Initializes dimensions for the atom-local AA optimization.
     349              : !>
     350              : !>        Distributes the full requested RI dimension among atom-local contractions.
     351              : !> \param bs_env ...
     352              : !> \param kind_of_atom ...
     353              : !> \param natom ...
     354              : !> \param nkind ...
     355              : !> \param max_nRI_kind ...
     356              : !> \param RI_size_opt_AA_requested ...
     357              : ! **************************************************************************************************
     358           12 :    SUBROUTINE initialize_AA_optimization(bs_env, kind_of_atom, &
     359              :                                          natom, nkind, max_nRI_kind, &
     360              :                                          RI_size_opt_AA_requested)
     361              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
     362              :       INTEGER, ALLOCATABLE, INTENT(OUT)                  :: kind_of_atom(:)
     363              :       INTEGER, INTENT(OUT)                               :: natom, nkind, max_nRI_kind, &
     364              :                                                             RI_size_opt_AA_requested
     365              : 
     366              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'initialize_AA_optimization'
     367              : 
     368              :       INTEGER                                            :: handle, ikind, nAO_total, nRI_reference, &
     369              :                                                             RI_size_requested
     370           12 :       INTEGER, ALLOCATABLE                               :: sizes_ref_RI_by_kind(:)
     371              : 
     372           12 :       CALL timeset(routineN, handle)
     373              : 
     374           12 :       natom = bs_env%n_atom
     375           12 :       CPASSERT(ASSOCIATED(bs_env%ri_rs%atomic_kind_set))
     376           12 :       CPASSERT(ASSOCIATED(bs_env%ri_rs%particle_set))
     377           12 :       CPASSERT(ASSOCIATED(bs_env%para_env) .AND. natom > 0)
     378           12 :       CPASSERT(ALLOCATED(bs_env%basis_set_AO))
     379           12 :       CPASSERT(ALLOCATED(bs_env%basis_set_RI))
     380           12 :       nkind = SIZE(bs_env%basis_set_RI)
     381           12 :       CPASSERT(nkind > 0)
     382           12 :       CPASSERT(SIZE(bs_env%basis_set_AO) == nkind)
     383           12 :       CPASSERT(bs_env%do_gw_ri_rs)
     384           12 :       IF (bs_env%do_periodic .AND. &
     385              :           bs_env%gw_implementation /= ri_rs_small_cell_full_kp) THEN
     386            0 :          CPABORT("Periodic AUTO_RI requires RI_RS_SMALL_CELL_FULL_KP")
     387              :       END IF
     388              : 
     389           12 :       CPASSERT(bs_env%gw_implementation /= tensor_small_cell_full_kp)
     390              : 
     391              :       CALL get_atomic_kind_set(atomic_kind_set=bs_env%ri_rs%atomic_kind_set, &
     392           12 :                                kind_of=kind_of_atom)
     393           36 :       ALLOCATE (bs_env%auto_ri%sizes_opt_RI(natom))
     394           36 :       ALLOCATE (sizes_ref_RI_by_kind(nkind))
     395           28 :       DO ikind = 1, nkind
     396           16 :          CPASSERT(ASSOCIATED(bs_env%basis_set_AO(ikind)%gto_basis_set))
     397           16 :          CPASSERT(ASSOCIATED(bs_env%basis_set_RI(ikind)%gto_basis_set))
     398           28 :          sizes_ref_RI_by_kind(ikind) = bs_env%basis_set_RI(ikind)%gto_basis_set%nsgf
     399              :       END DO
     400           28 :       max_nRI_kind = MAXVAL(sizes_ref_RI_by_kind)
     401           36 :       ALLOCATE (bs_env%auto_ri%sizes_ref_RI(natom))
     402           40 :       bs_env%auto_ri%sizes_ref_RI(:) = sizes_ref_RI_by_kind(kind_of_atom)
     403           40 :       nAO_total = SUM(bs_env%sizes_AO)
     404           40 :       nRI_reference = SUM(bs_env%auto_ri%sizes_ref_RI)
     405           12 :       CPASSERT(nAO_total > 0 .AND. nRI_reference > 0)
     406           12 :       RI_size_requested = NINT(bs_env%auto_ri%ri_ao_ratio*REAL(nAO_total, dp))
     407           12 :       IF (bs_env%do_periodic) THEN
     408            8 :          IF (RI_size_requested < natom) THEN
     409            0 :             CPABORT("AUTO_RI RI_AO_RATIO requests fewer RI functions than atoms")
     410              :          END IF
     411            8 :          RI_size_opt_AA_requested = MIN(RI_size_requested, nRI_reference)
     412              :       ELSE
     413            4 :          RI_size_opt_AA_requested = MAX(natom, MIN(RI_size_requested, nRI_reference))
     414              :       END IF
     415           12 :       DEALLOCATE (sizes_ref_RI_by_kind)
     416              : 
     417           12 :       CALL timestop(handle)
     418              : 
     419           12 :    END SUBROUTINE initialize_AA_optimization
     420              : 
     421              : !> \brief Sets the RI-RS block sizes to the optimized RI basis dimensions.
     422              : !> \param bs_env ...
     423              : ! **************************************************************************************************
     424           12 :    SUBROUTINE set_optimized_RI_basis_sizes(bs_env)
     425              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
     426              : 
     427              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'set_optimized_RI_basis_sizes'
     428              : 
     429              :       INTEGER                                            :: handle
     430              : 
     431           12 :       CALL timeset(routineN, handle)
     432              : 
     433           40 :       bs_env%sizes_RI(:) = bs_env%auto_ri%sizes_opt_RI
     434           12 :       bs_env%auto_ri%ready = .TRUE.
     435              : 
     436           12 :       CALL timestop(handle)
     437              : 
     438           12 :    END SUBROUTINE set_optimized_RI_basis_sizes
     439              : 
     440              : ! **************************************************************************************************
     441              : !> \brief Prints the optimized RI basis size and total optimization time.
     442              : !> \param bs_env ...
     443              : !> \param time_start ...
     444              : ! **************************************************************************************************
     445           12 :    SUBROUTINE print_auto_ri_summary(bs_env, time_start)
     446              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
     447              :       REAL(KIND=dp), INTENT(IN)                          :: time_start
     448              : 
     449              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'print_auto_ri_summary'
     450              : 
     451              :       INTEGER                                            :: handle, RI_size_optimized, unit_nr
     452              :       REAL(KIND=dp)                                      :: elapsed
     453              : 
     454           12 :       CALL timeset(routineN, handle)
     455              : 
     456           40 :       RI_size_optimized = SUM(bs_env%auto_ri%sizes_opt_RI)
     457           12 :       elapsed = m_walltime() - time_start
     458           12 :       CALL bs_env%para_env%max(elapsed)
     459           12 :       unit_nr = bs_env%unit_nr
     460           12 :       IF (unit_nr > 0) THEN
     461            6 :          WRITE (unit_nr, '(A)') ' '
     462              :          WRITE (unit_nr, '(T2,A,T74,I9)') &
     463            6 :             'AUTO_RI| Number of automatic RI functions for χ, ε, W:', RI_size_optimized
     464              :          WRITE (unit_nr, '(T2,A,T71,F8.1,A)') &
     465            6 :             'AUTO_RI| Total RI basis optimization time:', elapsed, ' s'
     466              :       END IF
     467              : 
     468           12 :       CALL timestop(handle)
     469              : 
     470           12 :    END SUBROUTINE print_auto_ri_summary
     471              : 
     472              : ! **************************************************************************************************
     473              : !> \brief Adds REGULARIZATION_RI to a two-center RI metric matrix (P|Q).
     474              : !> \param basis ...
     475              : !> \param regularization ...
     476              : !> \param M_PQ reference RI metric M_PQ
     477              : !> \param offset ...
     478              : ! **************************************************************************************************
     479            8 :    SUBROUTINE add_RI_metric_regularization(basis, regularization, M_PQ, offset)
     480              :       USE basis_set_types, ONLY: gto_basis_set_type
     481              :       TYPE(gto_basis_set_type), INTENT(IN)               :: basis
     482              :       REAL(KIND=dp), INTENT(IN)                          :: regularization
     483              :       REAL(KIND=dp), DIMENSION(:, :), INTENT(INOUT)      :: M_PQ
     484              :       INTEGER, INTENT(IN), OPTIONAL                      :: offset
     485              : 
     486              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'add_RI_metric_regularization'
     487              : 
     488              :       INTEGER                                            :: first, handle, i, iset, nset, start
     489            8 :       INTEGER, DIMENSION(:), POINTER                     :: npgf, nsgf_set
     490            8 :       INTEGER, DIMENSION(:, :), POINTER                  :: first_sgf
     491              :       REAL(KIND=dp)                                      :: shift
     492            8 :       REAL(KIND=dp), DIMENSION(:, :), POINTER            :: zet
     493              : 
     494            8 :       CALL timeset(routineN, handle)
     495              : 
     496            8 :       start = 0
     497            8 :       IF (PRESENT(offset)) start = offset
     498              :       CALL get_gto_basis_set(basis, first_sgf=first_sgf, npgf=npgf, nset=nset, &
     499            8 :                              nsgf_set=nsgf_set, zet=zet)
     500            8 :       CPASSERT(start >= 0 .AND. start + basis%nsgf <= SIZE(M_PQ, 1))
     501            8 :       CPASSERT(start + basis%nsgf <= SIZE(M_PQ, 2))
     502          180 :       DO iset = 1, nset
     503          344 :          shift = regularization*MAX(1.0_dp, 1.0_dp/MINVAL(zet(1:npgf(iset), iset)))
     504          172 :          first = start + first_sgf(1, iset)
     505          912 :          DO i = first, first + nsgf_set(iset) - 1
     506          904 :             M_PQ(i, i) = M_PQ(i, i) + shift
     507              :          END DO
     508              :       END DO
     509              : 
     510            8 :       CALL timestop(handle)
     511              : 
     512            8 :    END SUBROUTINE add_RI_metric_regularization
     513              : 
     514              : ! **************************************************************************************************
     515              : !> \brief Copies atom-local diagonal blocks M^AA from a distributed metric M.
     516              : !> \param M_pq_local locally stored entries of the optimized RI metric M_pq
     517              : !> \param M_pq_AA_local locally stored entries of the atom-block-diagonal metric
     518              : !> \param row_indices global indices of the locally owned rows
     519              : !> \param col_indices global indices of the locally owned columns
     520              : !> \param sizes_RI optimized RI functions in each atomic matrix block
     521              : ! **************************************************************************************************
     522            4 :    SUBROUTINE copy_M_pq_AA_blocks(M_pq_local, M_pq_AA_local, row_indices, &
     523            4 :                                   col_indices, sizes_RI)
     524              :       REAL(KIND=dp), DIMENSION(:, :), INTENT(IN)         :: M_pq_local
     525              :       REAL(KIND=dp), DIMENSION(:, :), INTENT(OUT)        :: M_pq_AA_local
     526              :       INTEGER, DIMENSION(:), INTENT(IN)                  :: row_indices, col_indices, sizes_RI
     527              : 
     528              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'copy_M_pq_AA_blocks'
     529              : 
     530              :       INTEGER                                            :: handle, i, j, last_index
     531            4 :       INTEGER, ALLOCATABLE, DIMENSION(:)                 :: block_ends, col_atom, row_atom
     532              : 
     533            4 :       CALL timeset(routineN, handle)
     534              : 
     535            4 :       CPASSERT(SIZE(M_pq_local, 1) == SIZE(row_indices))
     536            4 :       CPASSERT(SIZE(M_pq_local, 2) == SIZE(col_indices))
     537           12 :       CPASSERT(ALL(SHAPE(M_pq_AA_local) == SHAPE(M_pq_local)))
     538           16 :       CPASSERT(SIZE(sizes_RI) > 0 .AND. ALL(sizes_RI > 0))
     539              : 
     540           12 :       ALLOCATE (block_ends(SIZE(sizes_RI)))
     541            4 :       block_ends(1) = sizes_RI(1)
     542           12 :       DO i = 2, SIZE(sizes_RI)
     543           12 :          block_ends(i) = block_ends(i - 1) + sizes_RI(i)
     544              :       END DO
     545            4 :       last_index = block_ends(SIZE(block_ends))
     546           29 :       CPASSERT(ALL(row_indices >= 1 .AND. row_indices <= last_index))
     547           54 :       CPASSERT(ALL(col_indices >= 1 .AND. col_indices <= last_index))
     548              : 
     549           20 :       ALLOCATE (row_atom(SIZE(row_indices)), col_atom(SIZE(col_indices)))
     550           29 :       DO i = 1, SIZE(row_indices)
     551           29 :          row_atom(i) = M_pq_index_atom(row_indices(i), block_ends)
     552              :       END DO
     553           54 :       DO j = 1, SIZE(col_indices)
     554           54 :          col_atom(j) = M_pq_index_atom(col_indices(j), block_ends)
     555              :       END DO
     556              : 
     557          371 :       M_pq_AA_local = 0.0_dp
     558           54 :       DO j = 1, SIZE(col_indices)
     559          371 :          DO i = 1, SIZE(row_indices)
     560          367 :             IF (row_atom(i) == col_atom(j)) THEN
     561          229 :                M_pq_AA_local(i, j) = M_pq_local(i, j)
     562              :             END IF
     563              :          END DO
     564              :       END DO
     565              : 
     566            4 :       CALL timestop(handle)
     567              : 
     568            8 :    END SUBROUTINE copy_M_pq_AA_blocks
     569              : 
     570              : ! **************************************************************************************************
     571              : !> \brief Forms f_i=1/sqrt(λ_i) for eigenvalues of the RI metric matrix M_PQ.
     572              : !> \param eigenval generalized metric eigenvalues
     573              : !> \param factors inverse-square-root weights, or zero for discarded modes
     574              : ! **************************************************************************************************
     575            4 :    SUBROUTINE compute_optimized_M_pq_inv_factors(eigenval, factors)
     576              :       REAL(KIND=dp), DIMENSION(:), INTENT(IN)            :: eigenval
     577              :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:), &
     578              :          INTENT(OUT)                                     :: factors
     579              : 
     580              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'compute_optimized_M_pq_inv_factors'
     581              : 
     582              :       INTEGER                                            :: handle, i, n_dependent
     583              :       REAL(KIND=dp)                                      :: largest, threshold
     584              : 
     585            4 :       CALL timeset(routineN, handle)
     586              : 
     587            4 :       CPASSERT(SIZE(eigenval) > 0)
     588              : 
     589           54 :       largest = MAXVAL(eigenval)
     590            4 :       CPASSERT(largest > 0.0_dp)
     591            4 :       threshold = optimized_M_eigenval_threshold*largest
     592           12 :       ALLOCATE (factors(SIZE(eigenval)))
     593            4 :       factors = 0.0_dp
     594            4 :       n_dependent = 0
     595           54 :       DO i = 1, SIZE(eigenval)
     596           54 :          IF (eigenval(i) > 0.0_dp .AND. eigenval(i) >= threshold) THEN
     597           50 :             factors(i) = 1.0_dp/SQRT(eigenval(i))
     598              :          ELSE
     599            0 :             n_dependent = n_dependent + 1
     600              :          END IF
     601              :       END DO
     602            4 :       CPASSERT(n_dependent < SIZE(eigenval))
     603              : 
     604            4 :       CALL timestop(handle)
     605              : 
     606            4 :    END SUBROUTINE compute_optimized_M_pq_inv_factors
     607              : 
     608              : ! **************************************************************************************************
     609              : !> \brief Finds the atom owning a global RI metric index.
     610              : !> \param global_index global metric index
     611              : !> \param block_ends inclusive end index of each consecutive atom block
     612              : !> \return atom index
     613              : ! **************************************************************************************************
     614           75 :    PURE FUNCTION M_pq_index_atom(global_index, block_ends) RESULT(atom_index)
     615              :       INTEGER, INTENT(IN)                                :: global_index
     616              :       INTEGER, DIMENSION(:), INTENT(IN)                  :: block_ends
     617              :       INTEGER                                            :: atom_index
     618              : 
     619              :       INTEGER                                            :: high, low, middle
     620              : 
     621           75 :       low = 1
     622           75 :       high = SIZE(block_ends)
     623          219 :       DO WHILE (low < high)
     624          144 :          middle = (low + high)/2
     625          219 :          IF (global_index <= block_ends(middle)) THEN
     626              :             high = middle
     627              :          ELSE
     628           12 :             low = middle + 1
     629              :          END IF
     630              :       END DO
     631           75 :       atom_index = low
     632              : 
     633           75 :    END FUNCTION M_pq_index_atom
     634              : 
     635              : ! **************************************************************************************************
     636              : !> \brief Computes X=U diag(1/sqrt(λ)) with X^T M X=I.
     637              : !>
     638              : !>        The columns of X span the non-null eigenspace of the symmetric
     639              : !>        two-center RI metric matrix M=U diag(λ) U^T.
     640              : !> \param M_PQ ...
     641              : !> \param X_Pi ...
     642              : !> \param rank ...
     643              : ! **************************************************************************************************
     644           28 :    SUBROUTINE compute_reference_M_PQ_inv_factor(M_PQ, X_Pi, rank)
     645              :       REAL(KIND=dp), DIMENSION(:, :), INTENT(IN)         :: M_PQ
     646              :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :), &
     647              :          INTENT(OUT)                                     :: X_Pi
     648              :       INTEGER, INTENT(OUT)                               :: rank
     649              : 
     650              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'compute_reference_M_PQ_inv_factor'
     651              : 
     652              :       INTEGER                                            :: column, handle, i, n
     653              :       REAL(KIND=dp)                                      :: largest
     654           28 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:)           :: eigenval
     655           28 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :)        :: eigenvec
     656              : 
     657           28 :       CALL timeset(routineN, handle)
     658              : 
     659           28 :       n = SIZE(M_PQ, 1)
     660           28 :       CPASSERT(n > 0 .AND. SIZE(M_PQ, 2) == n)
     661       187584 :       ALLOCATE (eigenvec, source=0.5_dp*(M_PQ + TRANSPOSE(M_PQ)))
     662           84 :       ALLOCATE (eigenval(n))
     663           28 :       CALL diamat_all(eigenvec, eigenval, dac=.TRUE.)
     664         1184 :       largest = MAXVAL(eigenval)
     665           28 :       IF (largest <= 0.0_dp) CPABORT("AUTO_RI metric has no positive non-null range")
     666         1184 :       IF (MINVAL(eigenval) < -negative_eigenval_tolerance*largest) THEN
     667            0 :          CPABORT("AUTO_RI metric has no positive non-null range")
     668              :       END IF
     669         1184 :       rank = COUNT(eigenval > reference_M_eigenval_threshold*largest)
     670           28 :       IF (rank == 0) CPABORT("AUTO_RI metric has no positive non-null range")
     671          112 :       ALLOCATE (X_Pi(n, rank))
     672           28 :       column = 0
     673         1184 :       DO i = 1, n
     674         1156 :          IF (eigenval(i) <= reference_M_eigenval_threshold*largest) CYCLE
     675         1156 :          column = column + 1
     676        93764 :          X_Pi(:, column) = eigenvec(:, i)/SQRT(eigenval(i))
     677              :       END DO
     678              : 
     679           28 :       CALL timestop(handle)
     680              : 
     681           56 :    END SUBROUTINE compute_reference_M_PQ_inv_factor
     682              : 
     683              : ! **************************************************************************************************
     684              : !> \brief Solves eigenvalue problem B^A U^A=M^A U^A λ^A in Eq. (6).
     685              : !>
     686              : !>        Columns are ordered from the largest to the smallest λ^A.
     687              : !>        Columns are retained when λ_i/λ_max >= eigenval_threshold.
     688              : !> \param M_PQ metric of the large reference RI basis
     689              : !> \param B_PQ normalized atom-local target matrix B^A
     690              : !> \param target_normalization ...
     691              : !> \param U_Pp_A selected AA contractions from the large RI basis P to optimized functions p
     692              : !> \param eigenval normalized target eigenvalues in descending order
     693              : ! **************************************************************************************************
     694            6 :    SUBROUTINE solve_AA_eigenproblem(M_PQ, B_PQ, target_normalization, U_Pp_A, eigenval)
     695              :       REAL(KIND=dp), DIMENSION(:, :), INTENT(IN)         :: M_PQ, B_PQ
     696              :       REAL(KIND=dp), INTENT(IN)                          :: target_normalization
     697              :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :), &
     698              :          INTENT(OUT)                                     :: U_Pp_A
     699              :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:), &
     700              :          INTENT(OUT)                                     :: eigenval
     701              : 
     702              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'solve_AA_eigenproblem'
     703              : 
     704              :       INTEGER                                            :: handle, i, j, M_PQ_rank, n, nret
     705              :       REAL(KIND=dp)                                      :: largest_score, relative_fitting_defect
     706            6 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:)           :: eigenval_B, eigenval_M
     707            6 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :)        :: B_ij, M_pp_check, U_ij, U_Pp_A_rotated, &
     708            6 :                                                             X_Pi
     709              : 
     710            6 :       CALL timeset(routineN, handle)
     711              : 
     712            6 :       n = SIZE(M_PQ, 1)
     713            6 :       CPASSERT(n > 0)
     714            6 :       CPASSERT(SIZE(M_PQ, 2) == n)
     715           18 :       CPASSERT(ALL(SHAPE(B_PQ) == [n, n]))
     716            6 :       CPASSERT(target_normalization > 0.0_dp)
     717            6 :       CALL compute_reference_M_PQ_inv_factor(M_PQ, X_Pi, M_PQ_rank)
     718              : 
     719           24 :       ALLOCATE (B_ij(M_PQ_rank, M_PQ_rank))
     720            6 :       B_ij(:, :) = MATMUL(TRANSPOSE(X_Pi), &
     721        90712 :                           MATMUL(0.5_dp*(B_PQ + TRANSPOSE(B_PQ)), X_Pi))/target_normalization
     722        45368 :       ALLOCATE (U_ij, source=B_ij)
     723           18 :       ALLOCATE (eigenval_B(M_PQ_rank))
     724            6 :       CALL diamat_all(U_ij, eigenval_B, dac=.TRUE.)
     725          482 :       largest_score = MAXVAL(eigenval_B)
     726            6 :       IF (largest_score <= 0.0_dp) THEN
     727            0 :          CPABORT("AUTO_RI conditioned atom-local eigensolver failed")
     728              :       END IF
     729          482 :       IF (MINVAL(eigenval_B) < -conditioned_negative_eigenval_tolerance*largest_score) THEN
     730            0 :          CPABORT("AUTO_RI conditioned atom-local eigensolver failed")
     731              :       END IF
     732          482 :       eigenval_B(:) = MAX(eigenval_B, 0.0_dp)
     733          482 :       nret = COUNT(eigenval_B/largest_score >= relative_target_eigenval_threshold)
     734           30 :       ALLOCATE (U_Pp_A(n, nret), eigenval(M_PQ_rank))
     735          482 :       DO i = 1, M_PQ_rank
     736          482 :          eigenval(i) = eigenval_B(M_PQ_rank - i + 1)
     737              :       END DO
     738           38 :       DO i = 1, nret
     739           32 :          j = M_PQ_rank - i + 1
     740      1420202 :          U_Pp_A(:, i) = MATMUL(X_Pi, U_ij(:, j))
     741              :       END DO
     742              : 
     743              :       relative_fitting_defect = 1.0_dp
     744           38 :       DO i = 1, nret
     745           32 :          j = M_PQ_rank - i + 1
     746              :          relative_fitting_defect = relative_fitting_defect - &
     747       478562 :                                    DOT_PRODUCT(U_ij(:, j), MATMUL(B_ij, U_ij(:, j)))
     748              :       END DO
     749            6 :       IF (ABS(relative_fitting_defect) < 100.0_dp*EPSILON(1.0_dp)) THEN
     750              :          relative_fitting_defect = 0.0_dp
     751              :       END IF
     752              :       ! A projection cannot capture more than the exact product norm.
     753            6 :       IF (relative_fitting_defect < -1.0E-8_dp .OR. &
     754              :           relative_fitting_defect > 1.0_dp + 1.0E-8_dp) THEN
     755            0 :          CPABORT("AUTO_RI conditioned atom-local eigensolver failed")
     756              :       END IF
     757            6 :       IF (nret > 0) THEN
     758           48 :          ALLOCATE (M_pp_check(nret, nret), eigenval_M(nret), U_Pp_A_rotated(n, nret))
     759            6 :          M_pp_check(:, :) = MATMUL(TRANSPOSE(U_Pp_A), &
     760       271804 :                                    MATMUL(0.5_dp*(M_PQ + TRANSPOSE(M_PQ)), U_Pp_A))
     761            6 :          CALL diamat_all(M_pp_check, eigenval_M, dac=.TRUE.)
     762           38 :          IF (MINVAL(eigenval_M) <= reference_M_eigenval_threshold) THEN
     763            0 :             CPABORT("AUTO_RI conditioned atom-local eigensolver failed")
     764              :          END IF
     765       202018 :          U_Pp_A_rotated(:, :) = MATMUL(U_Pp_A, M_pp_check)
     766           38 :          DO i = 1, nret
     767         3842 :             U_Pp_A_rotated(:, i) = U_Pp_A_rotated(:, i)/SQRT(eigenval_M(i))
     768              :          END DO
     769       202018 :          U_Pp_A(:, :) = MATMUL(U_Pp_A_rotated, TRANSPOSE(M_pp_check))
     770            6 :          M_pp_check(:, :) = MATMUL(TRANSPOSE(U_Pp_A), &
     771       372596 :                                    MATMUL(0.5_dp*(M_PQ + TRANSPOSE(M_PQ)), U_Pp_A))
     772           38 :          DO i = 1, nret
     773           38 :             M_pp_check(i, i) = M_pp_check(i, i) - 1.0_dp
     774              :          END DO
     775          434 :          IF (MAXVAL(ABS(M_pp_check)) >= 1.0E-7_dp) THEN
     776            0 :             CPABORT("AUTO_RI conditioned atom-local eigensolver failed")
     777              :          END IF
     778              :       END IF
     779              : 
     780            6 :       CALL timestop(handle)
     781              : 
     782           12 :    END SUBROUTINE solve_AA_eigenproblem
     783              : 
     784              : !> \brief Selects the requested RI sizes from the largest positive eigenvalues.
     785              : !> \param eigenval_by_block descending eigenvalues; zero pads unavailable modes
     786              : !> \param RI_size_requested requested total number of functions
     787              : !> \param RI_size_minimum minimum retained size in every nonempty block
     788              : !> \param sizes_RI_selected number retained from each block
     789              : ! **************************************************************************************************
     790            4 :    SUBROUTINE select_RI_sizes(eigenval_by_block, RI_size_requested, RI_size_minimum, &
     791            4 :                               sizes_RI_selected)
     792              :       REAL(KIND=dp), INTENT(IN)                          :: eigenval_by_block(:, :)
     793              :       INTEGER, INTENT(IN)                                :: RI_size_requested, RI_size_minimum
     794              :       INTEGER, INTENT(OUT)                               :: sizes_RI_selected(:)
     795              : 
     796              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'select_RI_sizes'
     797              : 
     798              :       INTEGER                                            :: block, handle, i, n, nmode, remaining
     799            4 :       INTEGER, ALLOCATABLE                               :: indices(:)
     800            4 :       REAL(KIND=dp), ALLOCATABLE                         :: values(:)
     801              : 
     802            4 :       CALL timeset(routineN, handle)
     803              : 
     804            4 :       nmode = SIZE(eigenval_by_block, 1)
     805           12 :       n = SIZE(eigenval_by_block)
     806            4 :       CPASSERT(SIZE(sizes_RI_selected) == SIZE(eigenval_by_block, 2))
     807            4 :       CPASSERT(RI_size_minimum >= 0)
     808           16 :       sizes_RI_selected(:) = 0
     809            4 :       IF (n > 0) THEN
     810           20 :          ALLOCATE (values(n), indices(n))
     811         1544 :          values(:) = -RESHAPE(eigenval_by_block, [n])
     812           16 :          DO block = 1, SIZE(sizes_RI_selected)
     813              :             sizes_RI_selected(block) = &
     814         1548 :                MIN(RI_size_minimum, COUNT(eigenval_by_block(:, block) > 0.0_dp))
     815              :             values((block - 1)*nmode + 1: &
     816           28 :                    (block - 1)*nmode + sizes_RI_selected(block)) = 0.0_dp
     817              :          END DO
     818            4 :          CALL sort(values, n, indices)
     819         1552 :          remaining = MIN(MAX(0, RI_size_requested - SUM(sizes_RI_selected)), COUNT(values < 0.0_dp))
     820           42 :          DO i = 1, remaining
     821           38 :             block = (indices(i) - 1)/nmode + 1
     822           42 :             sizes_RI_selected(block) = sizes_RI_selected(block) + 1
     823              :          END DO
     824              :       END IF
     825              : 
     826            4 :       CALL timestop(handle)
     827              : 
     828            4 :    END SUBROUTINE select_RI_sizes
     829              : 
     830              : ! **************************************************************************************************
     831              : !> \brief Computes orbital factors for the occupied-empty weight in Eq. (5).
     832              : !>
     833              : !>        weights(n) = 1/|ε_n-E_F|, so weights(i)*weights(a) = w_ia.
     834              : !>
     835              : !> \param eigenval_MO molecular-orbital eigenvalues, occupied first
     836              : !> \param homo Last occupied state in this spin channel.
     837              : !> \param weights factors whose occupied-empty products give w_ia
     838              : ! **************************************************************************************************
     839           12 :    SUBROUTINE compute_orbital_weights(eigenval_MO, homo, weights)
     840              :       REAL(KIND=dp), INTENT(IN)                          :: eigenval_MO(:)
     841              :       INTEGER, INTENT(IN)                                :: homo
     842              :       REAL(KIND=dp), INTENT(OUT)                         :: weights(:)
     843              : 
     844              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'compute_orbital_weights'
     845              : 
     846              :       INTEGER                                            :: handle, n
     847              :       REAL(KIND=dp)                                      :: gap, middle
     848              : 
     849           12 :       CALL timeset(routineN, handle)
     850              : 
     851           12 :       CPASSERT(SIZE(weights) == SIZE(eigenval_MO))
     852           12 :       IF (homo < 1 .OR. homo >= SIZE(eigenval_MO)) THEN
     853            0 :          CPABORT("AUTO_RI orbital weights require occupied and empty states")
     854              :       END IF
     855           96 :       IF (.NOT. ALL(ieee_is_finite(eigenval_MO))) THEN
     856            0 :          CPABORT("AUTO_RI orbital weights require finite eigenvalues")
     857              :       END IF
     858           12 :       gap = eigenval_MO(homo + 1) - eigenval_MO(homo)
     859           12 :       IF (.NOT. ieee_is_finite(gap) .OR. gap <= 0.0_dp) THEN
     860            0 :          CPABORT("AUTO_RI orbital weights require a finite positive gap")
     861              :       END IF
     862           12 :       middle = 0.5_dp*(eigenval_MO(homo) + eigenval_MO(homo + 1))
     863           96 :       DO n = 1, SIZE(eigenval_MO)
     864           96 :          weights(n) = 1.0_dp/ABS(eigenval_MO(n) - middle)
     865              :       END DO
     866              : 
     867           12 :       CALL timestop(handle)
     868              : 
     869           12 :    END SUBROUTINE compute_orbital_weights
     870              : 
     871              : ! **************************************************************************************************
     872              : !> \brief Computes the occupied-empty contribution B_PQ^C in Eqs. (3) or (10).
     873              : !>
     874              : !>        B_PQ^C = Σ_ia w_ia (P|ρ_ia)(ρ_ia|Q).
     875              : !>
     876              : !> \param Int_3c atom-local or atom-pair three-center integrals (μν|P)
     877              : !> \param C_mu_n molecular-orbital coefficients restricted to the relevant AO rows
     878              : !> \param weights Per-orbital weights for this spin channel.
     879              : !> \param homo Last occupied state.
     880              : !> \param B_PQ unnormalized transition matrix for this spin channel
     881              : ! **************************************************************************************************
     882            6 :    SUBROUTINE compute_B_PQ_transition(Int_3c, C_mu_n, weights, homo, B_PQ)
     883              :       REAL(KIND=dp), CONTIGUOUS, INTENT(IN)              :: Int_3c(:, :, :), C_mu_n(:, :), weights(:)
     884              :       INTEGER, INTENT(IN)                                :: homo
     885              :       REAL(KIND=dp), INTENT(OUT)                         :: B_PQ(:, :)
     886              : 
     887              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'compute_B_PQ_transition'
     888              : 
     889              :       INTEGER                                            :: handle, n, nAO, nRI, nstates
     890            6 :       REAL(KIND=dp), ALLOCATABLE                         :: empty(:, :), occupied(:, :), scaled(:, :)
     891              :       TYPE(local_gemm_ctxt_type)                         :: gemm_context
     892              : 
     893            6 :       CALL timeset(routineN, handle)
     894              : 
     895            6 :       CALL gemm_context%create(LOCAL_GEMM_PU_HOST)
     896            6 :       nAO = SIZE(C_mu_n, 1)
     897            6 :       nstates = SIZE(C_mu_n, 2)
     898            6 :       nRI = SIZE(Int_3c, 3)
     899            6 :       CPASSERT(SIZE(Int_3c, 1) == nAO .AND. SIZE(Int_3c, 2) == nAO)
     900            6 :       CPASSERT(SIZE(B_PQ, 1) == nRI .AND. SIZE(B_PQ, 2) == nRI)
     901            6 :       CPASSERT(SIZE(weights) == nstates .AND. homo > 0 .AND. homo < nstates)
     902           54 :       ALLOCATE (scaled(nAO, nstates), occupied(nAO, nAO), empty(nAO, nAO))
     903           48 :       DO n = 1, nstates
     904          146 :          scaled(:, n) = C_mu_n(:, n)*SQRT(weights(n))
     905              :       END DO
     906              :       CALL gemm_context%gemm( &
     907              :          'N', 'T', nAO, nAO, homo, 1.0_dp, scaled, nAO, scaled, nAO, &
     908            6 :          0.0_dp, occupied, nAO)
     909              :       CALL gemm_context%gemm('N', 'T', nAO, nAO, nstates - homo, 1.0_dp, &
     910              :                              scaled(:, homo + 1:), nAO, scaled(:, homo + 1:), nAO, &
     911            6 :                              0.0_dp, empty, nAO)
     912            6 :       CALL contract_B_PQ(Int_3c, occupied, empty, B_PQ)
     913            6 :       CALL gemm_context%destroy()
     914              : 
     915            6 :       CALL timestop(handle)
     916              : 
     917           12 :    END SUBROUTINE compute_B_PQ_transition
     918              : 
     919              : ! **************************************************************************************************
     920              : !> \brief Computes the frontier-exchange contribution B_PQ^X in Eqs. (4) or (11).
     921              : !>
     922              : !>        B_PQ^X = Σ_{n∈W_occ} Σ_i^occ (P|ρ_ni)(ρ_ni|Q).
     923              : !>
     924              : !> \param Int_3c atom-local or atom-pair three-center integrals (μν|P)
     925              : !> \param C_mu_n molecular-orbital coefficients restricted to the relevant AO rows
     926              : !> \param eigenval_MO molecular-orbital eigenvalues, occupied first, in Hartree
     927              : !> \param homo Last occupied state in this spin channel.
     928              : !> \param occ_energy_window frontier-window extension in Hartree
     929              : !> \param B_PQ unnormalized exchange matrix
     930              : ! **************************************************************************************************
     931            6 :    SUBROUTINE compute_B_PQ_exchange(Int_3c, C_mu_n, eigenval_MO, homo, occ_energy_window, B_PQ)
     932              :       REAL(KIND=dp), CONTIGUOUS, INTENT(IN)              :: Int_3c(:, :, :), C_mu_n(:, :), &
     933              :                                                             eigenval_MO(:)
     934              :       INTEGER, INTENT(IN)                                :: homo
     935              :       REAL(KIND=dp), INTENT(IN)                          :: occ_energy_window
     936              :       REAL(KIND=dp), INTENT(OUT)                         :: B_PQ(:, :)
     937              : 
     938              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'compute_B_PQ_exchange'
     939              : 
     940              :       INTEGER                                            :: handle, n, nAO, nstates
     941              :       REAL(KIND=dp), ALLOCATABLE                         :: frontier(:, :), occupied(:, :), &
     942            6 :                                                             selected(:, :)
     943              :       TYPE(local_gemm_ctxt_type)                         :: gemm_context
     944              : 
     945            6 :       CALL timeset(routineN, handle)
     946              : 
     947        45350 :       B_PQ(:, :) = 0.0_dp
     948            6 :       nstates = SIZE(eigenval_MO)
     949            6 :       IF (homo < 1 .OR. homo >= nstates) THEN
     950            0 :          CPABORT("AUTO_RI exchange target requires occupied and empty states")
     951              :       END IF
     952           48 :       IF (.NOT. ieee_is_finite(occ_energy_window) .OR. &
     953              :           .NOT. ALL(ieee_is_finite(eigenval_MO))) THEN
     954            0 :          CPABORT("AUTO_RI exchange target requires finite input")
     955              :       END IF
     956            6 :       IF (occ_energy_window < 0.0_dp .OR. eigenval_MO(homo + 1) <= eigenval_MO(homo)) THEN
     957            0 :          CPABORT("AUTO_RI exchange target requires a valid frontier window")
     958              :       END IF
     959            6 :       nAO = SIZE(C_mu_n, 1)
     960            6 :       CPASSERT(SIZE(C_mu_n, 2) == nstates)
     961           54 :       ALLOCATE (occupied(nAO, nAO), frontier(nAO, nAO), selected(nAO, nstates), source=0.0_dp)
     962           48 :       DO n = 1, nstates
     963           42 :          IF (eigenval_MO(n) < eigenval_MO(homo) - occ_energy_window .OR. &
     964              :              eigenval_MO(n) > eigenval_MO(homo + 1) + occ_energy_window) CYCLE
     965           92 :          selected(:, n) = C_mu_n(:, n)
     966              :       END DO
     967            6 :       CALL gemm_context%create(LOCAL_GEMM_PU_HOST)
     968              :       ! D_μν = Σ_i^occ C_μi C_νi.
     969              :       ! F_μν = Σ_{n: ε_n ∈ [ε_H−E_win,ε_L+E_win]} C_μn C_νn.
     970              :       CALL gemm_context%gemm('N', 'T', nAO, nAO, homo, 1.0_dp, C_mu_n, nAO, C_mu_n, nAO, &
     971            6 :                              0.0_dp, occupied, nAO)
     972              :       CALL gemm_context%gemm('N', 'T', nAO, nAO, nstates, 1.0_dp, selected, nAO, selected, nAO, &
     973            6 :                              0.0_dp, frontier, nAO)
     974            6 :       CALL contract_B_PQ(Int_3c, occupied, frontier, B_PQ)
     975            6 :       CALL gemm_context%destroy()
     976              : 
     977            6 :       CALL timestop(handle)
     978              : 
     979           12 :    END SUBROUTINE compute_B_PQ_exchange
     980              : 
     981              : ! **************************************************************************************************
     982              : !> \brief Contracts AO density matrices and (μν|P) to form B_PQ.
     983              : !>
     984              : !>        B_PQ = Σ_μν (μν|P) [left (..|Q) right]_μν.
     985              : !>
     986              : !> \param Int_3c atom-local or atom-pair three-center integrals (μν|P)
     987              : !> \param left First density block, for occupied partners.
     988              : !> \param right Second density block, for empty or hard-window target states.
     989              : !> \param B_PQ symmetric RI-basis product matrix
     990              : ! **************************************************************************************************
     991           12 :    SUBROUTINE contract_B_PQ(Int_3c, left, right, B_PQ)
     992              :       REAL(KIND=dp), CONTIGUOUS, INTENT(IN)              :: Int_3c(:, :, :), left(:, :), right(:, :)
     993              :       REAL(KIND=dp), INTENT(OUT)                         :: B_PQ(:, :)
     994              : 
     995              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'contract_B_PQ'
     996              : 
     997              :       INTEGER                                            :: b, handle, mu, naux, nu, p, q
     998           12 :       REAL(KIND=dp), ALLOCATABLE                         :: weighted(:, :), work(:, :)
     999              :       TYPE(local_gemm_ctxt_type)                         :: gemm_context
    1000              : 
    1001           12 :       CALL timeset(routineN, handle)
    1002              : 
    1003           12 :       b = SIZE(Int_3c, 1)
    1004           12 :       naux = SIZE(Int_3c, 3)
    1005           12 :       CPASSERT(SIZE(Int_3c, 2) == b)
    1006           12 :       CPASSERT(SIZE(left, 1) == b .AND. SIZE(left, 2) == b)
    1007           12 :       CPASSERT(SIZE(right, 1) == b .AND. SIZE(right, 2) == b)
    1008           12 :       CPASSERT(SIZE(B_PQ, 1) == naux .AND. SIZE(B_PQ, 2) == naux)
    1009           72 :       ALLOCATE (work(b, b), weighted(b, b))
    1010           12 :       CALL gemm_context%create(LOCAL_GEMM_PU_HOST)
    1011          964 :       DO q = 1, naux
    1012              :          ! B_PQ = Σ_μν (μν|P) [left (..|Q) right]_μν.
    1013              :          CALL gemm_context%gemm('N', 'N', b, b, b, 1.0_dp, left, b, Int_3c(:, :, q), b, &
    1014          952 :                                 0.0_dp, work, b)
    1015          952 :          CALL gemm_context%gemm('N', 'N', b, b, b, 1.0_dp, work, b, right, b, 0.0_dp, weighted, b)
    1016        46308 :          DO p = 1, q
    1017        45344 :             B_PQ(p, q) = 0.0_dp
    1018       222784 :             DO nu = 1, b
    1019      1060704 :                DO mu = 1, b
    1020      1015360 :                   B_PQ(p, q) = B_PQ(p, q) + Int_3c(mu, nu, p)*weighted(mu, nu)
    1021              :                END DO
    1022              :             END DO
    1023        46296 :             B_PQ(q, p) = B_PQ(p, q)
    1024              :          END DO
    1025              :       END DO
    1026           12 :       CALL gemm_context%destroy()
    1027              : 
    1028           12 :       CALL timestop(handle)
    1029              : 
    1030           24 :    END SUBROUTINE contract_B_PQ
    1031              : 
    1032              : ! **************************************************************************************************
    1033              : !> \brief Adds separately normalized transition and exchange matrices.
    1034              : !> \param X_Pi inverse metric factor, X_Pi X_Qi = M_PQ^+
    1035              : !> \param B_PQ_transition transition matrix, replaced by the combined target
    1036              : !> \param B_PQ_exchange unnormalized hard-window exchange covariance
    1037              : !> \param target_norm number of nonzero normalized terms
    1038              : ! **************************************************************************************************
    1039            6 :    SUBROUTINE combine_transition_and_exchange_targets( &
    1040            6 :       X_Pi, B_PQ_transition, B_PQ_exchange, target_norm)
    1041              :       REAL(KIND=dp), CONTIGUOUS, INTENT(IN)              :: X_Pi(:, :)
    1042              :       REAL(KIND=dp), INTENT(INOUT)                       :: B_PQ_transition(:, :)
    1043              :       REAL(KIND=dp), CONTIGUOUS, INTENT(IN)              :: B_PQ_exchange(:, :)
    1044              :       REAL(KIND=dp), INTENT(OUT)                         :: target_norm
    1045              : 
    1046              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'combine_transition_and_exchange_targets'
    1047              : 
    1048              :       INTEGER                                            :: handle, k
    1049              :       REAL(KIND=dp)                                      :: exchange_norm, transition_norm
    1050            6 :       REAL(KIND=dp), ALLOCATABLE                         :: work(:, :)
    1051              : 
    1052            6 :       CALL timeset(routineN, handle)
    1053              : 
    1054           24 :       ALLOCATE (work(SIZE(X_Pi, 1), SIZE(X_Pi, 2)))
    1055            6 :       work(:, :) = MATMUL(B_PQ_transition, X_Pi)
    1056            6 :       transition_norm = 0.0_dp
    1057          482 :       DO k = 1, SIZE(X_Pi, 2)
    1058        45350 :          transition_norm = transition_norm + DOT_PRODUCT(X_Pi(:, k), work(:, k))
    1059              :       END DO
    1060            6 :       work(:, :) = MATMUL(B_PQ_exchange, X_Pi)
    1061            6 :       exchange_norm = 0.0_dp
    1062          482 :       DO k = 1, SIZE(X_Pi, 2)
    1063        45350 :          exchange_norm = exchange_norm + DOT_PRODUCT(X_Pi(:, k), work(:, k))
    1064              :       END DO
    1065              :       CALL normalize_transition_and_exchange_targets(B_PQ_transition, B_PQ_exchange, &
    1066            6 :                                                      transition_norm, exchange_norm, target_norm)
    1067              : 
    1068            6 :       CALL timestop(handle)
    1069              : 
    1070           12 :    END SUBROUTINE combine_transition_and_exchange_targets
    1071              : 
    1072              : ! **************************************************************************************************
    1073              : !> \brief Combine the transition and exchange targets using their squared-norm traces.
    1074              : !> \param B_PQ_transition ...
    1075              : !> \param B_PQ_exchange ...
    1076              : !> \param transition_norm ...
    1077              : !> \param exchange_norm ...
    1078              : !> \param target_norm ...
    1079              : ! **************************************************************************************************
    1080           14 :    SUBROUTINE normalize_transition_and_exchange_targets(B_PQ_transition, B_PQ_exchange, &
    1081              :                                                         transition_norm, exchange_norm, target_norm)
    1082              :       REAL(KIND=dp), INTENT(INOUT)                       :: B_PQ_transition(:, :)
    1083              :       REAL(KIND=dp), INTENT(IN)                          :: B_PQ_exchange(:, :), transition_norm, &
    1084              :                                                             exchange_norm
    1085              :       REAL(KIND=dp), INTENT(OUT)                         :: target_norm
    1086              : 
    1087           14 :       target_norm = 0.0_dp
    1088              :       IF (.NOT. ieee_is_finite(transition_norm) .OR. &
    1089              :           .NOT. ieee_is_finite(exchange_norm) .OR. &
    1090           14 :           transition_norm < 0.0_dp .OR. exchange_norm < 0.0_dp) THEN
    1091            0 :          CPABORT("AUTO_RI target normalization is invalid")
    1092              :       END IF
    1093              :       ! B = B_ia / Tr(M^+ B_ia) + B_ni / Tr(M^+ B_ni), with zero-norm terms omitted.
    1094           14 :       IF (transition_norm > 0.0_dp) THEN
    1095        46882 :          B_PQ_transition(:, :) = B_PQ_transition/transition_norm
    1096           14 :          target_norm = target_norm + 1.0_dp
    1097              :       ELSE
    1098            0 :          B_PQ_transition(:, :) = 0.0_dp
    1099              :       END IF
    1100           14 :       IF (exchange_norm > 0.0_dp) THEN
    1101        46882 :          B_PQ_transition(:, :) = B_PQ_transition + B_PQ_exchange/exchange_norm
    1102           14 :          target_norm = target_norm + 1.0_dp
    1103              :       END IF
    1104        46882 :       IF (target_norm <= 0.0_dp .OR. .NOT. ALL(ieee_is_finite(B_PQ_transition))) THEN
    1105            0 :          CPABORT("AUTO_RI target normalization is invalid")
    1106              :       END IF
    1107              : 
    1108           14 :    END SUBROUTINE normalize_transition_and_exchange_targets
    1109              : 
    1110              : ! **************************************************************************************************
    1111              : !> \brief Computes the atom-local matrix B_PQ^A in Eqs. (3)-(6).
    1112              : !>
    1113              : !>        B_PQ^A = B_PQ^{A,C}/N_C^A + B_PQ^{A,X}/N_X^A.
    1114              : !>
    1115              : !>        The molecular-orbital coefficient rows belonging to one atom are
    1116              : !>        collected on one MPI rank. No global AO-pair matrix is formed.
    1117              : !> \param bs_env ...
    1118              : !> \param iatom Atom whose AO rows are needed.
    1119              : !> \param root_rank MPI rank performing the atomic contractions.
    1120              : !> \param Int_3c atom-local three-center integrals (μν|P)
    1121              : !> \param M_PQ atom-local metric of the large reference RI basis
    1122              : !> \param B_PQ normalized atom-local matrix B_PQ^A
    1123              : !> \param target_norm number of nonzero normalized contributions
    1124              : ! **************************************************************************************************
    1125           12 :    SUBROUTINE compute_B_PQ_AA(bs_env, iatom, root_rank, Int_3c, M_PQ, &
    1126              :                               B_PQ, target_norm)
    1127              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    1128              :       INTEGER, INTENT(IN)                                :: iatom, root_rank
    1129              :       REAL(KIND=dp), CONTIGUOUS, INTENT(IN)              :: Int_3c(:, :, :), M_PQ(:, :)
    1130              :       REAL(KIND=dp), ALLOCATABLE, INTENT(OUT)            :: B_PQ(:, :)
    1131              :       REAL(KIND=dp), INTENT(OUT)                         :: target_norm
    1132              : 
    1133              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'compute_B_PQ_AA'
    1134              : 
    1135              :       INTEGER                                            :: column, first, handle, i, j, nAO, nRI, &
    1136              :                                                             nstates, rank, row, spin
    1137           12 :       INTEGER, POINTER                                   :: cols(:), rows(:)
    1138              :       REAL(KIND=dp), ALLOCATABLE                         :: B_PQ_exchange(:, :), B_PQ_spin(:, :), &
    1139           12 :                                                             C_mu_n(:, :), weights(:), X_Pi(:, :)
    1140              : 
    1141           12 :       CALL timeset(routineN, handle)
    1142           12 :       CPASSERT(.NOT. bs_env%do_periodic)
    1143           12 :       NULLIFY (rows, cols)
    1144           12 :       nAO = SIZE(Int_3c, 1)
    1145           12 :       nRI = SIZE(Int_3c, 3)
    1146           12 :       nstates = bs_env%n_mo_retained
    1147           12 :       CPASSERT(ALLOCATED(bs_env%eigenval_scf_Gamma))
    1148           24 :       first = 1 + SUM(bs_env%sizes_AO(:iatom - 1))
    1149           48 :       ALLOCATE (B_PQ(nRI, nRI), source=0.0_dp)
    1150           96 :       ALLOCATE (C_mu_n(nAO, nstates), weights(nstates), B_PQ_spin(nRI, nRI))
    1151           12 :       target_norm = 0.0_dp
    1152           36 :       ALLOCATE (B_PQ_exchange(nRI, nRI), source=0.0_dp)
    1153           24 :       DO spin = 1, bs_env%n_spin
    1154              :          CALL compute_orbital_weights(bs_env%eigenval_scf_Gamma(1:nstates, spin), &
    1155           12 :                                       bs_env%n_occ(spin), weights)
    1156           12 :          CALL cp_fm_get_info(bs_env%fm_mo_coeff_Gamma(spin), row_indices=rows, col_indices=cols)
    1157           12 :          C_mu_n(:, :) = 0.0_dp
    1158           54 :          DO i = 1, SIZE(rows)
    1159           42 :             row = rows(i) - first + 1
    1160           42 :             IF (row < 1 .OR. row > nAO) CYCLE
    1161          124 :             DO j = 1, SIZE(cols)
    1162           98 :                column = cols(j)
    1163           98 :                IF (column > nstates) CYCLE
    1164          140 :                C_mu_n(row, column) = bs_env%fm_mo_coeff_Gamma(spin)%local_data(i, j)
    1165              :             END DO
    1166              :          END DO
    1167           12 :          CALL bs_env%para_env%sum(C_mu_n, root_rank)
    1168           12 :          IF (bs_env%para_env%mepos /= root_rank) CYCLE
    1169            6 :          CALL compute_B_PQ_transition(Int_3c, C_mu_n, weights, bs_env%n_occ(spin), B_PQ_spin)
    1170        45350 :          B_PQ(:, :) = B_PQ + B_PQ_spin
    1171              :          CALL compute_B_PQ_exchange(Int_3c, C_mu_n, &
    1172              :                                     bs_env%eigenval_scf_Gamma(1:nstates, spin), &
    1173            6 :                                     bs_env%n_occ(spin), bs_env%auto_ri%occ_energy_window, B_PQ_spin)
    1174        45368 :          B_PQ_exchange(:, :) = B_PQ_exchange + B_PQ_spin
    1175              :       END DO
    1176           12 :       IF (bs_env%para_env%mepos /= root_rank) THEN
    1177            6 :          CALL timestop(handle)
    1178            6 :          RETURN
    1179              :       END IF
    1180            6 :       CALL compute_reference_M_PQ_inv_factor(M_PQ, X_Pi, rank)
    1181            6 :       CALL combine_transition_and_exchange_targets(X_Pi, B_PQ, B_PQ_exchange, target_norm)
    1182            6 :       CALL timestop(handle)
    1183              : 
    1184           30 :    END SUBROUTINE compute_B_PQ_AA
    1185              : 
    1186              : ! **************************************************************************************************
    1187              : !> \brief Normalizes each contraction coefficient vector U_Pp.
    1188              : !>
    1189              : !>        U_Pp <- U_Pp/sqrt(Σ_P |U_Pp|^2).
    1190              : !>
    1191              : !> \param U_Pp contractions from the large RI basis P to optimized functions p
    1192              : ! **************************************************************************************************
    1193           28 :    SUBROUTINE normalize_RI_coefficients(U_Pp)
    1194              :       REAL(KIND=dp), DIMENSION(:, :), INTENT(INOUT)      :: U_Pp
    1195              : 
    1196              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'normalize_RI_coefficients'
    1197              : 
    1198              :       INTEGER                                            :: handle, j
    1199              :       REAL(KIND=dp)                                      :: column_norm
    1200              : 
    1201           28 :       CALL timeset(routineN, handle)
    1202              : 
    1203          110 :       DO j = 1, SIZE(U_Pp, 2)
    1204         6198 :          column_norm = NORM2(U_Pp(:, j))
    1205           82 :          IF (column_norm <= TINY(1.0_dp)) THEN
    1206            0 :             CPABORT("AUTO_RI produced a numerically zero localized column")
    1207              :          END IF
    1208         6226 :          U_Pp(:, j) = U_Pp(:, j)/column_norm
    1209              :       END DO
    1210              : 
    1211           28 :       CALL timestop(handle)
    1212              : 
    1213           28 :    END SUBROUTINE normalize_RI_coefficients
    1214              : 
    1215              : ! **************************************************************************************************
    1216              : !> \brief Creates a matrix in the existing molecular BLACS context.
    1217              : !> \param qs_env ...
    1218              : !> \param matrix ...
    1219              : !> \param nr ...
    1220              : !> \param nc ...
    1221              : ! **************************************************************************************************
    1222           24 :    SUBROUTINE create_distributed_matrix(qs_env, matrix, nr, nc)
    1223              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    1224              :       TYPE(cp_fm_type), INTENT(OUT)                      :: matrix
    1225              :       INTEGER, INTENT(IN)                                :: nr, nc
    1226              : 
    1227              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'create_distributed_matrix'
    1228              : 
    1229              :       INTEGER                                            :: handle
    1230              :       TYPE(cp_blacs_env_type), POINTER                   :: blacs
    1231              :       TYPE(cp_fm_struct_type), POINTER                   :: layout
    1232              :       TYPE(mp_para_env_type), POINTER                    :: para
    1233              : 
    1234           24 :       CALL timeset(routineN, handle)
    1235              : 
    1236           24 :       NULLIFY (blacs, para, layout)
    1237           24 :       CALL get_qs_env(qs_env, blacs_env=blacs, para_env=para)
    1238           24 :       CALL cp_fm_struct_create(layout, context=blacs, nrow_global=nr, ncol_global=nc, para_env=para)
    1239           24 :       CALL cp_fm_create(matrix, layout, set_zero=.TRUE.)
    1240           24 :       CALL cp_fm_struct_release(layout)
    1241              : 
    1242           24 :       CALL timestop(handle)
    1243              : 
    1244           24 :    END SUBROUTINE create_distributed_matrix
    1245              : 
    1246              : ! **************************************************************************************************
    1247              : !> \brief Reads the normalized AA contraction for one atom.
    1248              : !> \param bs_env Band-structure environment
    1249              : !> \param atom Atom index
    1250              : !> \param U_Pp Atom-local AA contraction
    1251              : ! **************************************************************************************************
    1252           36 :    SUBROUTINE load_AA_contraction(bs_env, atom, U_Pp)
    1253              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    1254              :       INTEGER, INTENT(IN)                                :: atom
    1255              :       REAL(KIND=dp), ALLOCATABLE, INTENT(OUT)            :: U_Pp(:, :)
    1256              : 
    1257              :       INTEGER                                            :: first, nopt, nref
    1258              : 
    1259           36 :       nref = bs_env%auto_ri%sizes_ref_RI(atom)
    1260           36 :       nopt = bs_env%auto_ri%sizes_opt_RI(atom)
    1261           36 :       first = bs_env%auto_ri%U_Pp_atom_offset(atom)
    1262          144 :       ALLOCATE (U_Pp(nref, nopt))
    1263          108 :       U_Pp(:, :) = RESHAPE(bs_env%auto_ri%U_Pp_atom(first:first + nref*nopt - 1), [nref, nopt])
    1264           36 :    END SUBROUTINE load_AA_contraction
    1265              : 
    1266              : ! **************************************************************************************************
    1267              : !> \brief Adds REGULARIZATION_RI to one atom-local reference metric block.
    1268              : !> \param bs_env ...
    1269              : !> \param atom ...
    1270              : !> \param M_PQ atom-local metric block in the large reference RI basis
    1271              : ! **************************************************************************************************
    1272            0 :    SUBROUTINE regularize_M_PQ_block(bs_env, atom, M_PQ)
    1273              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    1274              :       INTEGER, INTENT(IN)                                :: atom
    1275              :       REAL(KIND=dp), DIMENSION(:, :), INTENT(INOUT)      :: M_PQ
    1276              : 
    1277              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'regularize_M_PQ_block'
    1278              : 
    1279              :       INTEGER                                            :: handle, i, iset, kind, nset
    1280            0 :       INTEGER, DIMENSION(:), POINTER                     :: npgf, nsgf_set
    1281            0 :       INTEGER, DIMENSION(:, :), POINTER                  :: first_sgf
    1282            0 :       REAL(KIND=dp), DIMENSION(:, :), POINTER            :: zet
    1283              : 
    1284            0 :       CALL timeset(routineN, handle)
    1285              : 
    1286            0 :       CPASSERT(SIZE(M_PQ, 1) == SIZE(M_PQ, 2))
    1287            0 :       kind = bs_env%ri_rs%particle_set(atom)%atomic_kind%kind_number
    1288              :       CALL get_gto_basis_set(bs_env%basis_set_RI(kind)%gto_basis_set, &
    1289              :                              first_sgf=first_sgf, npgf=npgf, nset=nset, &
    1290            0 :                              nsgf_set=nsgf_set, zet=zet)
    1291            0 :       DO iset = 1, nset
    1292            0 :          DO i = first_sgf(1, iset), first_sgf(1, iset) + nsgf_set(iset) - 1
    1293              :             M_PQ(i, i) = M_PQ(i, i) + &
    1294              :                          bs_env%regularization_RI* &
    1295            0 :                          MAX(1.0_dp, 1.0_dp/MINVAL(zet(1:npgf(iset), iset)))
    1296              :          END DO
    1297              :       END DO
    1298              : 
    1299            0 :       CALL timestop(handle)
    1300              : 
    1301            0 :    END SUBROUTINE regularize_M_PQ_block
    1302              : 
    1303              : ! **************************************************************************************************
    1304              : !> \brief Contracts a physical two-center metric block with AA coefficients.
    1305              : !>
    1306              : !>        M_pq^{IJ} = (U^I)^T M_IJ U^J. Each reference block is discarded after contraction.
    1307              : !> \param bs_env ...
    1308              : !> \param atom_a First atom
    1309              : !> \param atom_b Second atom
    1310              : !> \param coulomb true for Coulomb; false for the GW fitting operator
    1311              : !> \param matrix_optimized contracted M_pq or V_pq block in the optimized RI basis
    1312              : ! **************************************************************************************************
    1313           24 :    SUBROUTINE compute_optimized_RI_matrix_block( &
    1314              :       bs_env, atom_a, atom_b, coulomb, matrix_optimized)
    1315              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    1316              :       INTEGER, INTENT(IN)                                :: atom_a, atom_b
    1317              :       LOGICAL, INTENT(IN)                                :: coulomb
    1318              :       REAL(KIND=dp), ALLOCATABLE, INTENT(OUT)            :: matrix_optimized(:, :)
    1319              : 
    1320              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'compute_optimized_RI_matrix_block'
    1321              : 
    1322              :       INTEGER                                            :: handle
    1323           24 :       REAL(KIND=dp), ALLOCATABLE                         :: matrix_reference(:, :), U_a(:, :), &
    1324           24 :                                                             U_b(:, :)
    1325              : 
    1326           24 :       CALL timeset(routineN, handle)
    1327           24 :       CALL load_AA_contraction(bs_env, atom_a, U_a)
    1328           24 :       IF (atom_a == atom_b) THEN
    1329         5914 :          ALLOCATE (U_b, source=U_a)
    1330              :       ELSE
    1331           12 :          CALL load_AA_contraction(bs_env, atom_b, U_b)
    1332              :       END IF
    1333           24 :       IF (coulomb) THEN
    1334           12 :          CALL compute_M_PQ_atom_pair(bs_env, atom_a, atom_b, matrix_reference)
    1335              :       ELSE
    1336           12 :          CALL compute_M_PQ_atom_pair(bs_env, atom_a, atom_b, matrix_reference, bs_env%ri_metric)
    1337           12 :          IF (atom_a == atom_b .AND. bs_env%regularization_RI > 0.0_dp .AND. &
    1338              :              bs_env%gw_implementation /= ri_rs_small_cell_full_kp) THEN
    1339            0 :             CALL regularize_M_PQ_block(bs_env, atom_a, matrix_reference)
    1340              :          END IF
    1341              :       END IF
    1342           96 :       ALLOCATE (matrix_optimized(SIZE(U_a, 2), SIZE(U_b, 2)))
    1343       523820 :       matrix_optimized(:, :) = MATMUL(TRANSPOSE(U_a), MATMUL(matrix_reference, U_b))
    1344          708 :       IF (.NOT. ALL(ieee_is_finite(matrix_optimized))) THEN
    1345            0 :          CPABORT("AUTO_RI optimized metric block contains invalid values")
    1346              :       END IF
    1347           24 :       DEALLOCATE (matrix_reference, U_a, U_b)
    1348           24 :       CALL timestop(handle)
    1349              : 
    1350           24 :    END SUBROUTINE compute_optimized_RI_matrix_block
    1351              : 
    1352              : ! **************************************************************************************************
    1353              : !> \brief Builds M_opt or V_opt directly from contracted atom-pair blocks.
    1354              : !> \param qs_env ...
    1355              : !> \param bs_env ...
    1356              : !> \param matrix_pq contracted M_pq or V_pq in the optimized RI basis
    1357              : !> \param coulomb true for Coulomb; false for the GW fitting operator
    1358              : ! **************************************************************************************************
    1359            8 :    SUBROUTINE compute_contracted_RI_matrix(qs_env, bs_env, matrix_pq, coulomb)
    1360              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    1361              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    1362              :       TYPE(cp_fm_type), INTENT(OUT)                      :: matrix_pq
    1363              :       LOGICAL, INTENT(IN)                                :: coulomb
    1364              : 
    1365              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'compute_contracted_RI_matrix'
    1366              : 
    1367              :       INTEGER                                            :: handle, iatom, jatom, npcol, nprow, &
    1368              :                                                             pair_index, RI_size_opt
    1369            8 :       INTEGER, CONTIGUOUS, POINTER                       :: col_dist(:), row_dist(:), sizes_opt_RI(:)
    1370            8 :       REAL(KIND=dp), ALLOCATABLE                         :: matrix_pq_block(:, :)
    1371              :       TYPE(dbcsr_distribution_type)                      :: dist
    1372              :       TYPE(dbcsr_distribution_type), POINTER             :: template
    1373              :       TYPE(dbcsr_type)                                   :: blocks
    1374              : 
    1375            8 :       CALL timeset(routineN, handle)
    1376              : 
    1377           40 :       ALLOCATE (sizes_opt_RI(bs_env%n_atom), row_dist(bs_env%n_atom), col_dist(bs_env%n_atom))
    1378           64 :       sizes_opt_RI(:) = bs_env%auto_ri%sizes_opt_RI
    1379            8 :       CALL get_qs_env(qs_env, dbcsr_dist=template)
    1380            8 :       CALL dbcsr_distribution_get(template, nprows=nprow, npcols=npcol)
    1381           32 :       DO iatom = 1, SIZE(sizes_opt_RI)
    1382           24 :          row_dist(iatom) = MOD(iatom - 1, nprow)
    1383           32 :          col_dist(iatom) = MOD(iatom - 1, npcol)
    1384              :       END DO
    1385           32 :       RI_size_opt = SUM(sizes_opt_RI)
    1386            8 :       CALL create_distributed_matrix(qs_env, matrix_pq, RI_size_opt, RI_size_opt)
    1387            8 :       CALL dbcsr_distribution_new(dist, template=template, row_dist=row_dist, col_dist=col_dist)
    1388              :       CALL dbcsr_create(blocks, name='AUTO_RI contracted metric', dist=dist, &
    1389              :                         matrix_type=dbcsr_type_symmetric, &
    1390            8 :                         row_blk_size=sizes_opt_RI, col_blk_size=sizes_opt_RI)
    1391              : 
    1392            8 :       pair_index = 0
    1393           32 :       DO iatom = 1, SIZE(sizes_opt_RI)
    1394           80 :          DO jatom = 1, iatom
    1395           48 :             pair_index = pair_index + 1
    1396           48 :             IF (MOD(pair_index - 1, bs_env%para_env%num_pe) /= bs_env%para_env%mepos) CYCLE
    1397              :             CALL compute_optimized_RI_matrix_block( &
    1398           24 :                bs_env, iatom, jatom, coulomb, matrix_pq_block)
    1399           24 :             IF (iatom == jatom) THEN
    1400         1040 :                matrix_pq_block(:, :) = 0.5_dp*(matrix_pq_block + TRANSPOSE(matrix_pq_block))
    1401              :             END IF
    1402           24 :             CALL dbcsr_put_block(blocks, iatom, jatom, matrix_pq_block)
    1403           72 :             DEALLOCATE (matrix_pq_block)
    1404              :          END DO
    1405              :       END DO
    1406            8 :       CALL dbcsr_finalize(blocks)
    1407            8 :       CALL copy_dbcsr_to_fm(blocks, matrix_pq)
    1408            8 :       CALL dbcsr_release(blocks)
    1409            8 :       CALL dbcsr_distribution_release(dist)
    1410            8 :       DEALLOCATE (sizes_opt_RI, row_dist, col_dist)
    1411              : 
    1412            8 :       CALL timestop(handle)
    1413              : 
    1414           32 :    END SUBROUTINE compute_contracted_RI_matrix
    1415              : 
    1416              : ! **************************************************************************************************
    1417              : !> \brief Computes the pseudoinverse of the optimized fitting metric M_opt.
    1418              : !>
    1419              : !>        The generalized problem M_opt X=M_AA X λ separates linearly
    1420              : !>        dependent directions. The result is M_opt^+=X diag(1/λ) X^T.
    1421              : !> \param qs_env ...
    1422              : !> \param bs_env ...
    1423              : !> \param M_pq optimized RI fitting metric
    1424              : ! **************************************************************************************************
    1425            4 :    SUBROUTINE compute_M_pq_inv(qs_env, bs_env, M_pq)
    1426              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    1427              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    1428              :       TYPE(cp_fm_type), INTENT(INOUT)                    :: M_pq
    1429              : 
    1430              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'compute_M_pq_inv'
    1431              : 
    1432              :       INTEGER                                            :: handle, ncol_local, nrow_local, &
    1433              :                                                             RI_size_opt
    1434            4 :       INTEGER, DIMENSION(:), POINTER                     :: col_indices, row_indices
    1435            4 :       REAL(KIND=dp), ALLOCATABLE                         :: eigenval(:), factors(:)
    1436              :       REAL(KIND=dp), CONTIGUOUS, DIMENSION(:, :), &
    1437            4 :          POINTER                                         :: M_pq_AA_local, M_pq_local
    1438              :       TYPE(cp_fm_type)                                   :: M_pq_AA, work, X_pq
    1439              : 
    1440            4 :       CALL timeset(routineN, handle)
    1441              : 
    1442           16 :       RI_size_opt = SUM(bs_env%auto_ri%sizes_opt_RI)
    1443              :       CALL create_distributed_matrix(qs_env, bs_env%auto_ri%M_pq_inv, &
    1444            4 :                                      RI_size_opt, RI_size_opt)
    1445            4 :       CALL create_distributed_matrix(qs_env, X_pq, RI_size_opt, RI_size_opt)
    1446            4 :       CALL create_distributed_matrix(qs_env, M_pq_AA, RI_size_opt, RI_size_opt)
    1447            4 :       CALL create_distributed_matrix(qs_env, work, RI_size_opt, RI_size_opt)
    1448              :       CALL cp_fm_get_info(M_pq, nrow_local=nrow_local, ncol_local=ncol_local, &
    1449              :                           row_indices=row_indices, col_indices=col_indices, &
    1450            4 :                           local_data=M_pq_local)
    1451            4 :       CALL cp_fm_get_info(M_pq_AA, local_data=M_pq_AA_local)
    1452            4 :       M_pq_AA_local = 0.0_dp
    1453              :       CALL copy_M_pq_AA_blocks(M_pq_local(:nrow_local, :ncol_local), &
    1454              :                                M_pq_AA_local(:nrow_local, :ncol_local), &
    1455              :                                row_indices(:nrow_local), col_indices(:ncol_local), &
    1456            4 :                                bs_env%auto_ri%sizes_opt_RI)
    1457              : 
    1458           12 :       ALLOCATE (eigenval(RI_size_opt))
    1459            4 :       CALL cp_fm_geeig(M_pq, M_pq_AA, X_pq, eigenval, work)
    1460            4 :       CALL compute_optimized_M_pq_inv_factors(eigenval, factors)
    1461            4 :       CALL cp_fm_column_scale(X_pq, factors)
    1462              :       CALL cp_fm_syrk("U", "N", RI_size_opt, 1.0_dp, X_pq, 1, 1, 0.0_dp, &
    1463            4 :                       bs_env%auto_ri%M_pq_inv)
    1464            4 :       CALL cp_fm_uplo_to_full(bs_env%auto_ri%M_pq_inv, work)
    1465              : 
    1466            4 :       DEALLOCATE (eigenval, factors)
    1467            4 :       CALL cp_fm_release(X_pq)
    1468            4 :       CALL cp_fm_release(M_pq_AA)
    1469            4 :       CALL cp_fm_release(work)
    1470              : 
    1471            4 :       CALL timestop(handle)
    1472              : 
    1473            8 :    END SUBROUTINE compute_M_pq_inv
    1474              : 
    1475              : ! **************************************************************************************************
    1476              : !> \brief Computes molecular M_opt and V_opt without constructing M_ref or V_ref.
    1477              : !> \param qs_env ...
    1478              : !> \param bs_env ...
    1479              : ! **************************************************************************************************
    1480            4 :    SUBROUTINE compute_M_pq_inv_and_V_pq_molecular(qs_env, bs_env)
    1481              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    1482              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    1483              : 
    1484              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'compute_M_pq_inv_and_V_pq_molecular'
    1485              : 
    1486              :       INTEGER                                            :: handle
    1487              :       TYPE(cp_fm_type)                                   :: M_pq
    1488              : 
    1489            4 :       CALL timeset(routineN, handle)
    1490              : 
    1491            4 :       CALL initialize_auto_ri_integrals(bs_env)
    1492            4 :       CALL compute_contracted_RI_matrix(qs_env, bs_env, M_pq, .FALSE.)
    1493            4 :       CALL compute_M_pq_inv(qs_env, bs_env, M_pq)
    1494            4 :       CALL cp_fm_release(M_pq)
    1495            4 :       CALL compute_contracted_RI_matrix(qs_env, bs_env, bs_env%auto_ri%V_pq, .TRUE.)
    1496              : 
    1497              :       ! Activate the optimized per-atom RI block sizes for RI-RS.
    1498            4 :       CALL set_optimized_RI_basis_sizes(bs_env)
    1499              : 
    1500            4 :       CALL timestop(handle)
    1501              : 
    1502            4 :    END SUBROUTINE compute_M_pq_inv_and_V_pq_molecular
    1503              : 
    1504              : ! **************************************************************************************************
    1505              : !> \brief Computes the atom-local two-center RI metric (P|Q) and the
    1506              : !>        three-center integrals (μν|P) used in Eqs. (3) and (4).
    1507              : !> \param ao_basis ...
    1508              : !> \param ri_basis ...
    1509              : !> \param potential fitting operator used for both integral types
    1510              : !> \param M_PQ two-center metric of the large reference RI basis
    1511              : !> \param Int_3c three-center integrals (μν|P)
    1512              : ! **************************************************************************************************
    1513           16 :    SUBROUTINE compute_int_3c(ao_basis, ri_basis, potential, M_PQ, Int_3c)
    1514              :       TYPE(gto_basis_set_type), INTENT(IN)               :: ao_basis, ri_basis
    1515              :       TYPE(coulomb_operator_type), INTENT(IN)            :: potential
    1516              :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :), &
    1517              :          INTENT(OUT)                                     :: M_PQ
    1518              :       REAL(KIND=dp), INTENT(OUT)                         :: Int_3c(:, :, :)
    1519              : 
    1520              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'compute_int_3c'
    1521              : 
    1522              :       INTEGER                                            :: handle, iset, jset, kset, max_ao_l, &
    1523              :                                                             max_l, max_ri_l, nAO, ncoa, ncob, &
    1524              :                                                             ncoc, nRI, nsgfa, nsgfb, nsgfc, sgfa, &
    1525              :                                                             sgfb, sgfc
    1526           16 :       INTEGER, DIMENSION(:), POINTER                     :: lmax_a, lmax_c, lmin_a, lmin_c, npgf_a, &
    1527           16 :                                                             npgf_c, nsgf_set_a, nsgf_set_c
    1528           16 :       INTEGER, DIMENSION(:, :), POINTER                  :: first_sgf_a, first_sgf_c
    1529           16 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :)        :: Int_2c_cart, Int_2c_spherical
    1530           16 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :, :)     :: Int_3c_cart, Int_3c_spherical_all, &
    1531           16 :                                                             Int_3c_spherical_block
    1532              :       REAL(KIND=dp), DIMENSION(3)                        :: center
    1533           16 :       REAL(KIND=dp), DIMENSION(:), POINTER               :: radius_a, radius_b, radius_c
    1534           16 :       REAL(KIND=dp), DIMENSION(:, :), POINTER            :: pgf_radius_a, pgf_radius_c, sphi_a, &
    1535           16 :                                                             sphi_c, zeta_a, zeta_c
    1536           16 :       TYPE(coulomb_integral_context_type)                :: context
    1537              : 
    1538           16 :       CALL timeset(routineN, handle)
    1539              : 
    1540              :       CALL get_gto_basis_set(ao_basis, nsgf=nAO, lmax=lmax_a, lmin=lmin_a, &
    1541              :                              npgf=npgf_a, nsgf_set=nsgf_set_a, first_sgf=first_sgf_a, &
    1542           16 :                              pgf_radius=pgf_radius_a, sphi=sphi_a, zet=zeta_a)
    1543              :       CALL get_gto_basis_set(ri_basis, nsgf=nRI, lmax=lmax_c, lmin=lmin_c, &
    1544              :                              npgf=npgf_c, nsgf_set=nsgf_set_c, first_sgf=first_sgf_c, &
    1545           16 :                              pgf_radius=pgf_radius_c, sphi=sphi_c, zet=zeta_c)
    1546           16 :       CPASSERT(nAO > 0 .AND. nRI > 0)
    1547           36 :       max_ao_l = MAXVAL(lmax_a)
    1548          202 :       max_ri_l = MAXVAL(lmax_c)
    1549           16 :       max_l = MAX(max_ao_l, max_ri_l)
    1550           16 :       CALL init_orbital_pointers(MAX(max_l, 2*max_ao_l))
    1551           16 :       CALL init_spherical_harmonics(max_l, -1)
    1552           16 :       IF (potential%potential_type == do_potential_truncated .OR. &
    1553              :           potential%potential_type == do_potential_short) THEN
    1554           16 :          IF (active_integral_library%coulomb2_library /= library_libint .OR. &
    1555              :              active_integral_library%coulomb3_library /= library_libint) THEN
    1556              :             CALL cp_abort(__LOCATION__, &
    1557              :                           "AUTO_RI range-separated fitting requires LIBINT for "// &
    1558            0 :                           "COULOMB_2C and COULOMB_3C")
    1559              :          END IF
    1560              :       END IF
    1561              :       ! Libint initialization takes the maximum angular momentum of one shell,
    1562              :       ! not the sum of angular momenta entering an integral.
    1563           16 :       CALL coulomb_integral_init(context, max_am_2c=max_ri_l, max_am_3c=max_l)
    1564           16 :       center = 0.0_dp
    1565              : 
    1566          128 :       ALLOCATE (M_PQ(nRI, nRI), Int_3c_spherical_all(nAO, nAO, nRI))
    1567           16 :       M_PQ = 0.0_dp
    1568           16 :       Int_3c_spherical_all = 0.0_dp
    1569              : 
    1570          202 :       DO iset = 1, ri_basis%nset
    1571          186 :          ncoa = npgf_c(iset)*ncoset(lmax_c(iset))
    1572          186 :          sgfa = first_sgf_c(1, iset)
    1573          186 :          nsgfa = nsgf_set_c(iset)
    1574          186 :          radius_a => pgf_radius_c(1:npgf_c(iset), iset)
    1575         4264 :          DO jset = 1, ri_basis%nset
    1576         4062 :             ncob = npgf_c(jset)*ncoset(lmax_c(jset))
    1577         4062 :             sgfb = first_sgf_c(1, jset)
    1578         4062 :             nsgfb = nsgf_set_c(jset)
    1579         4062 :             radius_b => pgf_radius_c(1:npgf_c(jset), jset)
    1580        28434 :             ALLOCATE (Int_2c_cart(ncoa, ncob), Int_2c_spherical(nsgfa, nsgfb))
    1581         4062 :             Int_2c_cart = 0.0_dp
    1582              :             CALL compute_coulomb_2c(context, lmin_c(iset), lmax_c(iset), &
    1583              :                                     lmin_c(jset), lmax_c(jset), &
    1584              :                                     npgf_c(iset), npgf_c(jset), zeta_c(1:npgf_c(iset), iset), &
    1585              :                                     zeta_c(1:npgf_c(jset), jset), &
    1586         4062 :                                     radius_a, radius_b, center, center, Int_2c_cart, potential)
    1587              :             CALL ab_contract(Int_2c_spherical, Int_2c_cart, sphi_c(:, sgfa:), sphi_c(:, sgfb:), &
    1588         4062 :                              ncoa, ncob, nsgfa, nsgfb)
    1589       100948 :             M_PQ(sgfa:sgfa + nsgfa - 1, sgfb:sgfb + nsgfb - 1) = Int_2c_spherical
    1590         4248 :             DEALLOCATE (Int_2c_spherical, Int_2c_cart)
    1591              :          END DO
    1592              :       END DO
    1593              : 
    1594           36 :       DO iset = 1, ao_basis%nset
    1595           20 :          ncoa = npgf_a(iset)*ncoset(lmax_a(iset))
    1596           20 :          sgfa = first_sgf_a(1, iset)
    1597           20 :          nsgfa = nsgf_set_a(iset)
    1598           20 :          radius_a => pgf_radius_a(1:npgf_a(iset), iset)
    1599           64 :          DO jset = 1, ao_basis%nset
    1600           28 :             ncob = npgf_a(jset)*ncoset(lmax_a(jset))
    1601           28 :             sgfb = first_sgf_a(1, jset)
    1602           28 :             nsgfb = nsgf_set_a(jset)
    1603           28 :             radius_b => pgf_radius_a(1:npgf_a(jset), jset)
    1604          570 :             DO kset = 1, ri_basis%nset
    1605          522 :                ncoc = npgf_c(kset)*ncoset(lmax_c(kset))
    1606          522 :                sgfc = first_sgf_c(1, kset)
    1607          522 :                nsgfc = nsgf_set_c(kset)
    1608          522 :                radius_c => pgf_radius_c(1:npgf_c(kset), kset)
    1609            0 :                ALLOCATE (Int_3c_cart(ncoa, ncob, ncoc), &
    1610         4698 :                          Int_3c_spherical_block(nsgfa, nsgfb, nsgfc))
    1611          522 :                Int_3c_cart = 0.0_dp
    1612              :                CALL compute_coulomb_3c(context, lmin_a(iset), lmax_a(iset), &
    1613              :                                        lmin_a(jset), lmax_a(jset), &
    1614              :                                        lmin_c(kset), lmax_c(kset), npgf_a(iset), npgf_a(jset), &
    1615              :                                        npgf_c(kset), zeta_a(1:npgf_a(iset), iset), &
    1616              :                                        zeta_a(1:npgf_a(jset), jset), zeta_c(1:npgf_c(kset), kset), &
    1617              :                                        radius_a, radius_b, radius_c, center, center, center, &
    1618          522 :                                        Int_3c_cart, potential)
    1619              :                CALL abc_contract(Int_3c_spherical_block, Int_3c_cart, &
    1620              :                                  sphi_a(:, sgfa:), sphi_a(:, sgfb:), &
    1621          522 :                                  sphi_c(:, sgfc:), ncoa, ncob, ncoc, nsgfa, nsgfb, nsgfc)
    1622              :                Int_3c_spherical_all(sgfa:sgfa + nsgfa - 1, sgfb:sgfb + nsgfb - 1, &
    1623        21576 :                                     sgfc:sgfc + nsgfc - 1) = Int_3c_spherical_block
    1624          550 :                DEALLOCATE (Int_3c_spherical_block, Int_3c_cart)
    1625              :             END DO
    1626              :          END DO
    1627              :       END DO
    1628              : 
    1629        16974 :       Int_3c(:, :, :) = Int_3c_spherical_all
    1630           16 :       CALL coulomb_integral_cleanup(context)
    1631        79908 :       IF (.NOT. ALL(ieee_is_finite(M_PQ))) THEN
    1632            0 :          CPABORT("AUTO_RI metric contains invalid values")
    1633              :       END IF
    1634        16974 :       IF (.NOT. ALL(ieee_is_finite(Int_3c))) THEN
    1635            0 :          CPABORT("AUTO_RI three-center integrals contain invalid values")
    1636              :       END IF
    1637              : 
    1638           16 :       CALL timestop(handle)
    1639              : 
    1640           32 :    END SUBROUTINE compute_int_3c
    1641              : 
    1642              : ! **************************************************************************************************
    1643              : !> \brief Initializes the integral kernels used by the AUTO_RI optimization.
    1644              : !> \param bs_env ...
    1645              : ! **************************************************************************************************
    1646           16 :    SUBROUTINE initialize_auto_ri_integrals(bs_env)
    1647              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    1648              : 
    1649              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'initialize_auto_ri_integrals'
    1650              : 
    1651              :       INTEGER                                            :: handle, ikind, max_ao_l, max_l, &
    1652              :                                                             max_ri_l, table_lmax
    1653              : 
    1654           16 :       CALL timeset(routineN, handle)
    1655              : 
    1656           16 :       CPASSERT(ALLOCATED(bs_env%basis_set_AO))
    1657           16 :       CPASSERT(ALLOCATED(bs_env%basis_set_RI))
    1658           16 :       CPASSERT(SIZE(bs_env%basis_set_AO) == SIZE(bs_env%basis_set_RI))
    1659           16 :       CPASSERT(SIZE(bs_env%basis_set_RI) > 0)
    1660           16 :       max_ao_l = 0
    1661           16 :       max_ri_l = 0
    1662           40 :       DO ikind = 1, SIZE(bs_env%basis_set_RI)
    1663           24 :          CPASSERT(ASSOCIATED(bs_env%basis_set_AO(ikind)%gto_basis_set))
    1664           24 :          CPASSERT(ASSOCIATED(bs_env%basis_set_RI(ikind)%gto_basis_set))
    1665           56 :          max_ao_l = MAX(max_ao_l, MAXVAL(bs_env%basis_set_AO(ikind)%gto_basis_set%lmax))
    1666          398 :          max_ri_l = MAX(max_ri_l, MAXVAL(bs_env%basis_set_RI(ikind)%gto_basis_set%lmax))
    1667              :       END DO
    1668           16 :       max_l = MAX(max_ao_l, max_ri_l)
    1669              :       ! The OS two-center kernel accesses l+1 even without force evaluation.
    1670           16 :       CALL init_orbital_pointers(max_l + 1)
    1671           16 :       CALL init_spherical_harmonics(max_l, -1)
    1672              : 
    1673           16 :       IF (bs_env%ri_metric%potential_type == do_potential_truncated) THEN
    1674              :          ! Cover both the RI-RI two-center and AO-AO-RI three-center kernels.
    1675            8 :          table_lmax = MAX(2*max_ri_l + 1, 2*max_ao_l + max_ri_l)
    1676            8 :          CALL r12_fundamentals_init(table_lmax, bs_env%ri_metric, bs_env%para_env)
    1677              :       END IF
    1678              : 
    1679           16 :       CALL timestop(handle)
    1680              : 
    1681           16 :    END SUBROUTINE initialize_auto_ri_integrals
    1682              : 
    1683              : ! **************************************************************************************************
    1684              : !> \brief Computes the coupling metric between atom-local RI blocks.
    1685              : !> \param bs_env ...
    1686              : !> \param atom_A ...
    1687              : !> \param atom_B ...
    1688              : !> \param M_PQ metric block in the large reference RI basis
    1689              : !> \param ri_potential ...
    1690              : ! **************************************************************************************************
    1691           24 :    SUBROUTINE compute_M_PQ_atom_pair(bs_env, atom_A, atom_B, M_PQ, ri_potential)
    1692              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    1693              :       INTEGER, INTENT(IN)                                :: atom_A, atom_B
    1694              :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :), &
    1695              :          INTENT(OUT)                                     :: M_PQ
    1696              :       TYPE(coulomb_operator_type), INTENT(IN), OPTIONAL  :: ri_potential
    1697              : 
    1698              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'compute_M_PQ_atom_pair'
    1699              : 
    1700              :       INTEGER                                            :: atom_1, atom_2, handle, kind_1, kind_2
    1701           24 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :)        :: M_PQ_canonical
    1702              :       TYPE(coulomb_operator_type)                        :: potential
    1703              : 
    1704           24 :       CALL timeset(routineN, handle)
    1705              : 
    1706           24 :       CPASSERT(ASSOCIATED(bs_env%ri_rs%particle_set))
    1707           24 :       CPASSERT(atom_A >= 1 .AND. atom_A <= bs_env%n_atom)
    1708           24 :       CPASSERT(atom_B >= 1 .AND. atom_B <= bs_env%n_atom)
    1709           24 :       IF (atom_A >= atom_B) THEN
    1710              :          atom_1 = atom_A
    1711              :          atom_2 = atom_B
    1712              :       ELSE
    1713            0 :          atom_1 = atom_B
    1714            0 :          atom_2 = atom_A
    1715              :       END IF
    1716           24 :       kind_1 = bs_env%ri_rs%particle_set(atom_1)%atomic_kind%kind_number
    1717           24 :       kind_2 = bs_env%ri_rs%particle_set(atom_2)%atomic_kind%kind_number
    1718              : 
    1719           24 :       IF (PRESENT(ri_potential)) THEN
    1720           12 :          IF (ri_potential%potential_type /= do_potential_truncated) THEN
    1721            0 :             CPASSERT(ri_potential%potential_type == do_potential_short)
    1722              :          END IF
    1723           12 :          potential = ri_potential
    1724              :       ELSE
    1725              :          potential%potential_type = do_potential_coulomb
    1726              :       END IF
    1727              :       CALL compute_M_PQ( &
    1728              :          basis_a=bs_env%basis_set_RI(kind_1)%gto_basis_set, &
    1729              :          basis_b=bs_env%basis_set_RI(kind_2)%gto_basis_set, &
    1730              :          center_a=bs_env%ri_rs%particle_set(atom_1)%r, &
    1731              :          center_b=bs_env%ri_rs%particle_set(atom_2)%r, &
    1732           24 :          potential=potential, M_PQ=M_PQ_canonical)
    1733              : 
    1734           24 :       IF (atom_A >= atom_B) THEN
    1735           24 :          CALL MOVE_ALLOC(M_PQ_canonical, M_PQ)
    1736              :       ELSE
    1737            0 :          ALLOCATE (M_PQ(SIZE(M_PQ_canonical, 2), SIZE(M_PQ_canonical, 1)))
    1738            0 :          M_PQ(:, :) = TRANSPOSE(M_PQ_canonical)
    1739            0 :          DEALLOCATE (M_PQ_canonical)
    1740              :       END IF
    1741              : 
    1742           24 :       CALL timestop(handle)
    1743              : 
    1744           48 :    END SUBROUTINE compute_M_PQ_atom_pair
    1745              : 
    1746              : ! **************************************************************************************************
    1747              : !> \brief Computes one contracted two-center RI metric block (P_A|Q_B).
    1748              : !> \param basis_a ...
    1749              : !> \param basis_b ...
    1750              : !> \param center_a ...
    1751              : !> \param center_b ...
    1752              : !> \param potential ...
    1753              : !> \param M_PQ metric block in the large reference RI basis
    1754              : ! **************************************************************************************************
    1755           24 :    SUBROUTINE compute_M_PQ(basis_a, basis_b, center_a, center_b, potential, M_PQ)
    1756              :       TYPE(gto_basis_set_type), POINTER                  :: basis_a, basis_b
    1757              :       REAL(KIND=dp), DIMENSION(3), INTENT(IN)            :: center_a, center_b
    1758              :       TYPE(coulomb_operator_type), INTENT(IN)            :: potential
    1759              :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :), &
    1760              :          INTENT(OUT)                                     :: M_PQ
    1761              : 
    1762              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'compute_M_PQ'
    1763              : 
    1764              :       INTEGER                                            :: handle
    1765              : 
    1766           24 :       CALL timeset(routineN, handle)
    1767              : 
    1768           96 :       ALLOCATE (M_PQ(basis_a%nsgf, basis_b%nsgf), source=0.0_dp)
    1769           24 :       SELECT CASE (potential%potential_type)
    1770              :       CASE (do_potential_truncated)
    1771              :          CALL int_operators_r12_ab_os(operator_truncated, M_PQ, rab=center_b - center_a, &
    1772              :                                       fba=basis_a, fbb=basis_b, &
    1773           48 :                                       r_cutoff=potential%cutoff_radius, calculate_forces=.FALSE.)
    1774              :       CASE (do_potential_coulomb)
    1775              :          CALL int_operators_r12_ab_os(operator_coulomb, M_PQ, rab=center_b - center_a, &
    1776           48 :                                       fba=basis_a, fbb=basis_b, calculate_forces=.FALSE.)
    1777              :       CASE (do_potential_short)
    1778              :          CALL int_operators_r12_ab_os(operator_verfc, M_PQ, rab=center_b - center_a, &
    1779              :                                       fba=basis_a, fbb=basis_b, &
    1780            0 :                                       omega=potential%omega, calculate_forces=.FALSE.)
    1781              :       CASE DEFAULT
    1782           24 :          CPABORT("AUTO_RI two-center metric requires COULOMB, TRUNCATED or SHORT")
    1783              :       END SELECT
    1784              : 
    1785           24 :       CALL timestop(handle)
    1786              : 
    1787           24 :    END SUBROUTINE compute_M_PQ
    1788              : 
    1789              : ! **************************************************************************************************
    1790              : !> \brief Packs normalized atom-local AA coefficients for both paths.
    1791              : !> \param bs_env Band-structure environment
    1792              : !> \param U_Pp_A Atom-local contraction coefficients
    1793              : ! **************************************************************************************************
    1794           12 :    SUBROUTINE store_AA_basis(bs_env, U_Pp_A)
    1795              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    1796              :       REAL(KIND=dp), INTENT(IN)                          :: U_Pp_A(:, :, :)
    1797              : 
    1798              :       INTEGER                                            :: first, iatom, nopt, nref
    1799           12 :       REAL(KIND=dp), ALLOCATABLE                         :: U_Pp_normalized(:, :)
    1800              : 
    1801           36 :       ALLOCATE (bs_env%auto_ri%U_Pp_atom_offset(bs_env%n_atom))
    1802            0 :       ALLOCATE (bs_env%auto_ri%U_Pp_atom( &
    1803           64 :                 SUM(bs_env%auto_ri%sizes_ref_RI*bs_env%auto_ri%sizes_opt_RI)))
    1804           12 :       first = 1
    1805           40 :       DO iatom = 1, bs_env%n_atom
    1806           28 :          nref = bs_env%auto_ri%sizes_ref_RI(iatom)
    1807           28 :          nopt = bs_env%auto_ri%sizes_opt_RI(iatom)
    1808           28 :          bs_env%auto_ri%U_Pp_atom_offset(iatom) = first
    1809           28 :          IF (nopt > 0) THEN
    1810          112 :             ALLOCATE (U_Pp_normalized(nref, nopt))
    1811         6226 :             U_Pp_normalized(:, :) = U_Pp_A(1:nref, 1:nopt, iatom)
    1812           28 :             CALL normalize_RI_coefficients(U_Pp_normalized)
    1813              :             bs_env%auto_ri%U_Pp_atom(first:first + nref*nopt - 1) = &
    1814         6172 :                RESHAPE(U_Pp_normalized, [nref*nopt])
    1815           28 :             DEALLOCATE (U_Pp_normalized)
    1816              :          END IF
    1817           40 :          first = first + nref*nopt
    1818              :       END DO
    1819           12 :    END SUBROUTINE store_AA_basis
    1820              : 
    1821              : ! **************************************************************************************************
    1822              : !> \brief Forms the periodic atom-local AA target from k-averaged density matrices.
    1823              : !>
    1824              : !> The separable transition weight w_ia(k,k') = a_i(k) b_a(k') permits the
    1825              : !> complete independent k,k' sum to be evaluated as
    1826              : !> J_μν,i = Σ_P (μν|P) X_Pi, with X^T M X = I.
    1827              : !> B_ij = Re Tr[J_i D_empty J_j D_occ]; exchange uses D_frontier and D_occ_exchange.
    1828              : !> Each target is normalized by its trace before adding both terms, Eqs. (3)-(6).
    1829              : !> Transforming the integrals first avoids cancellation in X^T B_PQ X.
    1830              : !> Occupied and empty density matrices use the full SCF k mesh, not the
    1831              : !> band-structure path. The same factorization applies to the frontier target.
    1832              : !> This is an atom-local training objective, not a q-resolved GW error norm.
    1833              : !> \param bs_env ...
    1834              : !> \param iatom ...
    1835              : !> \param root_rank ...
    1836              : !> \param Int_3c ...
    1837              : !> \param M_PQ ...
    1838              : !> \param B_ij ...
    1839              : !> \param target_norm ...
    1840              : !> \param X_Pi inverse metric factor defining the orthonormal RI coordinates
    1841              : ! **************************************************************************************************
    1842           16 :    SUBROUTINE compute_B_ij_AA_kaveraged(bs_env, iatom, root_rank, Int_3c, M_PQ, &
    1843              :                                         B_ij, target_norm, X_Pi)
    1844              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    1845              :       INTEGER, INTENT(IN)                                :: iatom, root_rank
    1846              :       REAL(KIND=dp), CONTIGUOUS, INTENT(IN)              :: Int_3c(:, :, :), M_PQ(:, :)
    1847              :       REAL(KIND=dp), ALLOCATABLE, INTENT(OUT)            :: B_ij(:, :)
    1848              :       REAL(KIND=dp), INTENT(OUT)                         :: target_norm
    1849              :       REAL(KIND=dp), ALLOCATABLE, INTENT(OUT)            :: X_Pi(:, :)
    1850              : 
    1851              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'compute_B_ij_AA_kaveraged'
    1852              : 
    1853           16 :       COMPLEX(KIND=dp), ALLOCATABLE                      :: C_mu_n(:, :), D_empty(:, :), &
    1854           16 :                                                             D_frontier(:, :), D_occ(:, :), &
    1855           16 :                                                             D_occ_exchange(:, :)
    1856              :       INTEGER                                            :: first, handle, i, ikp, ispin, nAO, nRI, &
    1857              :                                                             nstates, rank
    1858              :       REAL(KIND=dp)                                      :: CBM, E_F, exchange_norm, &
    1859              :                                                             transition_norm, VBM, weight
    1860           16 :       REAL(KIND=dp), ALLOCATABLE                         :: B_exchange(:, :), B_spin(:, :), &
    1861           16 :                                                             B_transition(:, :), &
    1862           16 :                                                             Int_3c_metric(:, :, :), weights(:)
    1863              : 
    1864           16 :       CALL timeset(routineN, handle)
    1865              : 
    1866           16 :       CPASSERT(ALLOCATED(bs_env%cfm_mo_coeff_kp))
    1867           16 :       CPASSERT(ALLOCATED(bs_env%eigenval_scf))
    1868           16 :       CPASSERT(ASSOCIATED(bs_env%kpoints_scf_desymm))
    1869           16 :       CPASSERT(bs_env%nkp_scf_desymm > 0)
    1870           16 :       CPASSERT(SIZE(bs_env%cfm_mo_coeff_kp, 1) >= bs_env%nkp_scf_desymm)
    1871           16 :       CPASSERT(SIZE(bs_env%eigenval_scf, 2) >= bs_env%nkp_scf_desymm)
    1872              : 
    1873           16 :       nAO = bs_env%sizes_AO(iatom)
    1874           16 :       nRI = bs_env%auto_ri%sizes_ref_RI(iatom)
    1875           16 :       nstates = bs_env%n_mo_retained
    1876           16 :       CPASSERT(nstates > 0 .AND. nstates <= SIZE(bs_env%eigenval_scf, 1))
    1877           32 :       CPASSERT(ALL(bs_env%n_occ(1:bs_env%n_spin) > 0))
    1878           32 :       CPASSERT(ALL(bs_env%n_occ(1:bs_env%n_spin) < nstates))
    1879           24 :       first = 1 + SUM(bs_env%sizes_AO(:iatom - 1))
    1880           16 :       CALL compute_reference_M_PQ_inv_factor(M_PQ, X_Pi, rank)
    1881           80 :       ALLOCATE (Int_3c_metric(nAO, nAO, rank))
    1882        11184 :       Int_3c_metric(:, :, :) = RESHAPE(MATMUL(RESHAPE(Int_3c, [nAO*nAO, nRI]), X_Pi), [nAO, nAO, rank])
    1883           64 :       ALLOCATE (B_ij(rank, rank), source=0.0_dp)
    1884              :       ALLOCATE (B_exchange(rank, rank), B_spin(rank, rank), B_transition(rank, rank), &
    1885              :                 C_mu_n(nAO, nstates), weights(nstates), &
    1886              :                 D_empty(nAO, nAO), D_frontier(nAO, nAO), &
    1887          336 :                 D_occ(nAO, nAO), D_occ_exchange(nAO, nAO))
    1888           16 :       B_exchange = 0.0_dp
    1889           16 :       B_transition = 0.0_dp
    1890              : 
    1891           32 :       DO ispin = 1, bs_env%n_spin
    1892           16 :          D_empty = z_zero
    1893           16 :          D_frontier = z_zero
    1894           16 :          D_occ = z_zero
    1895           16 :          D_occ_exchange = z_zero
    1896          116 :          VBM = MAXVAL(bs_env%eigenval_scf(bs_env%n_occ(ispin), 1:bs_env%nkp_scf_desymm, ispin))
    1897          116 :          CBM = MINVAL(bs_env%eigenval_scf(bs_env%n_occ(ispin) + 1, 1:bs_env%nkp_scf_desymm, ispin))
    1898           16 :          IF (.NOT. ieee_is_finite(VBM) .OR. .NOT. ieee_is_finite(CBM) .OR. CBM <= VBM) THEN
    1899            0 :             CPABORT('Periodic AUTO_RI k-averaged training requires a finite positive gap')
    1900              :          END IF
    1901           16 :          E_F = 0.5_dp*(VBM + CBM)
    1902              : 
    1903          116 :          DO ikp = 1, bs_env%nkp_scf_desymm
    1904              :             CALL cp_cfm_get_submatrix(bs_env%cfm_mo_coeff_kp(ikp, ispin), C_mu_n, &
    1905          100 :                                       start_row=first, n_rows=nAO, n_cols=nstates)
    1906          116 :             IF (bs_env%para_env%mepos == root_rank) THEN
    1907          214 :                weights(:) = 1.0_dp/ABS(bs_env%eigenval_scf(1:nstates, ikp, ispin) - E_F)
    1908           50 :                weight = bs_env%kpoints_scf_desymm%wkp(ikp)
    1909              :                CALL accumulate_AA_density_matrices( &
    1910              :                   C_mu_n, bs_env%eigenval_scf(1:nstates, ikp, ispin), &
    1911              :                   weights, bs_env%n_occ(ispin), weight, VBM, CBM, &
    1912              :                   bs_env%auto_ri%occ_energy_window, &
    1913           50 :                   D_occ, D_empty, D_occ_exchange, D_frontier)
    1914              :             END IF
    1915              :          END DO
    1916           32 :          IF (bs_env%para_env%mepos == root_rank) THEN
    1917            8 :             CALL contract_B_PQ_density(Int_3c_metric, D_empty, D_occ, B_spin)
    1918         1532 :             B_transition(:, :) = B_transition + B_spin
    1919            8 :             CALL contract_B_PQ_density(Int_3c_metric, D_frontier, D_occ_exchange, B_spin)
    1920         1532 :             B_exchange(:, :) = B_exchange + B_spin
    1921              :          END IF
    1922              :       END DO
    1923              : 
    1924           16 :       IF (bs_env%para_env%mepos == root_rank) THEN
    1925          220 :          transition_norm = SUM([(B_transition(i, i), i=1, rank)])
    1926          220 :          exchange_norm = SUM([(B_exchange(i, i), i=1, rank)])
    1927              :          CALL normalize_transition_and_exchange_targets(B_transition, B_exchange, &
    1928            8 :                                                         transition_norm, exchange_norm, target_norm)
    1929         1532 :          B_ij(:, :) = B_transition
    1930              :       END IF
    1931            0 :       DEALLOCATE (B_exchange, B_spin, B_transition, C_mu_n, weights, &
    1932           16 :                   D_empty, D_frontier, D_occ, D_occ_exchange)
    1933           16 :       CALL timestop(handle)
    1934              : 
    1935           32 :    END SUBROUTINE compute_B_ij_AA_kaveraged
    1936              : 
    1937              : ! **************************************************************************************************
    1938              : !> \brief Accumulates occupied, empty and frontier AA density matrices on one atom.
    1939              : !> \param C_mu_n ...
    1940              : !> \param eigenval ...
    1941              : !> \param weights ...
    1942              : !> \param homo ...
    1943              : !> \param wk ...
    1944              : !> \param VBM ...
    1945              : !> \param CBM ...
    1946              : !> \param energy_window ...
    1947              : !> \param D_occ ...
    1948              : !> \param D_empty ...
    1949              : !> \param D_occ_exchange ...
    1950              : !> \param D_frontier ...
    1951              : ! **************************************************************************************************
    1952           50 :    SUBROUTINE accumulate_AA_density_matrices(C_mu_n, eigenval, weights, homo, wk, VBM, CBM, &
    1953           50 :                                              energy_window, D_occ, D_empty, D_occ_exchange, &
    1954           50 :                                              D_frontier)
    1955              :       COMPLEX(KIND=dp), INTENT(IN)                       :: C_mu_n(:, :)
    1956              :       REAL(KIND=dp), INTENT(IN)                          :: eigenval(:), weights(:)
    1957              :       INTEGER, INTENT(IN)                                :: homo
    1958              :       REAL(KIND=dp), INTENT(IN)                          :: wk, VBM, CBM, energy_window
    1959              :       COMPLEX(KIND=dp), INTENT(INOUT)                    :: D_occ(:, :), D_empty(:, :), &
    1960              :                                                             D_occ_exchange(:, :), D_frontier(:, :)
    1961              : 
    1962              :       COMPLEX(KIND=dp)                                   :: product
    1963              :       INTEGER                                            :: imode, imu, inu
    1964              : 
    1965          214 :       DO imode = 1, SIZE(eigenval)
    1966          570 :          DO inu = 1, SIZE(C_mu_n, 1)
    1967         1452 :             DO imu = 1, SIZE(C_mu_n, 1)
    1968          932 :                product = wk*C_mu_n(imu, imode)*CONJG(C_mu_n(inu, imode))
    1969          932 :                IF (imode <= homo) THEN
    1970          178 :                   D_occ(imu, inu) = D_occ(imu, inu) + weights(imode)*product
    1971          178 :                   D_occ_exchange(imu, inu) = D_occ_exchange(imu, inu) + product
    1972              :                ELSE
    1973          754 :                   D_empty(imu, inu) = D_empty(imu, inu) + weights(imode)*product
    1974              :                END IF
    1975          932 :                IF (eigenval(imode) >= VBM - energy_window .AND. &
    1976          356 :                    eigenval(imode) <= CBM + energy_window) THEN
    1977          350 :                   D_frontier(imu, inu) = D_frontier(imu, inu) + product
    1978              :                END IF
    1979              :             END DO
    1980              :          END DO
    1981              :       END DO
    1982              : 
    1983           50 :    END SUBROUTINE accumulate_AA_density_matrices
    1984              : 
    1985              : ! **************************************************************************************************
    1986              : !> \brief Contracts the factorized local AA density target over complex k-point orbitals.
    1987              : !> \param Int_3c ...
    1988              : !> \param D_right ...
    1989              : !> \param D_left ...
    1990              : !> \param B_PQ ...
    1991              : ! **************************************************************************************************
    1992           16 :    SUBROUTINE contract_B_PQ_density(Int_3c, D_right, D_left, B_PQ)
    1993              :       REAL(KIND=dp), CONTIGUOUS, INTENT(IN)              :: Int_3c(:, :, :)
    1994              :       COMPLEX(KIND=dp), INTENT(IN)                       :: D_right(:, :), D_left(:, :)
    1995              :       REAL(KIND=dp), INTENT(OUT)                         :: B_PQ(:, :)
    1996              : 
    1997           16 :       COMPLEX(KIND=dp), ALLOCATABLE                      :: weighted(:, :)
    1998              :       INTEGER                                            :: ip, iq
    1999              : 
    2000           64 :       ALLOCATE (weighted(SIZE(D_left, 1), SIZE(D_left, 2)))
    2001          220 :       DO iq = 1, SIZE(Int_3c, 3)
    2002         6072 :          weighted(:, :) = MATMUL(D_right, MATMUL(Int_3c(:, :, iq), D_left))
    2003         3064 :          DO ip = 1, SIZE(Int_3c, 3)
    2004        10176 :             B_PQ(ip, iq) = REAL(SUM(Int_3c(:, :, ip)*TRANSPOSE(weighted)), KIND=dp)
    2005              :          END DO
    2006              :       END DO
    2007         6128 :       B_PQ = 0.5_dp*(B_PQ + TRANSPOSE(B_PQ))
    2008              : 
    2009           16 :    END SUBROUTINE contract_B_PQ_density
    2010              : 
    2011              : ! **************************************************************************************************
    2012              : !> \brief Solves eigenvalue problem B^A U^A=M^A U^A λ^A in Eq. (6).
    2013              : !>
    2014              : !>        Columns are ordered from the largest to the smallest λ^A.
    2015              : !>        Columns are retained when λ_i/λ_max >= eigenval_threshold.
    2016              : !> \param M_PQ metric of the large reference RI basis
    2017              : !> \param X_Pi inverse metric factor with X^T M X = I
    2018              : !> \param B_PQ normalized target X^T B^A X, formed directly from transformed integrals
    2019              : !> \param target_normalization ...
    2020              : !> \param U_Pp_A selected AA contractions from the large RI basis P to optimized functions p
    2021              : !> \param eigenval normalized target eigenvalues in descending order
    2022              : ! **************************************************************************************************
    2023            8 :    SUBROUTINE solve_AA_eigenproblem_periodic(M_PQ, X_Pi, B_PQ, target_normalization, U_Pp_A, eigenval)
    2024              :       REAL(KIND=dp), DIMENSION(:, :), INTENT(IN)         :: M_PQ, X_Pi, B_PQ
    2025              :       REAL(KIND=dp), INTENT(IN)                          :: target_normalization
    2026              :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :), &
    2027              :          INTENT(OUT)                                     :: U_Pp_A
    2028              :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:), &
    2029              :          INTENT(OUT)                                     :: eigenval
    2030              : 
    2031              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'solve_AA_eigenproblem_periodic'
    2032              : 
    2033              :       CHARACTER(LEN=256)                                 :: diagnostic
    2034              :       INTEGER                                            :: handle, i, iortho, j, M_PQ_rank, n, nret
    2035              :       REAL(KIND=dp)                                      :: largest_score, metric_defect, &
    2036              :                                                             relative_fitting_defect
    2037            8 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:)           :: eigenval_B, eigenval_M
    2038            8 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :)        :: B_ij, M_pp_check, U_ij, U_Pp_A_rotated
    2039              : 
    2040            8 :       CALL timeset(routineN, handle)
    2041              : 
    2042            8 :       n = SIZE(M_PQ, 1)
    2043            8 :       CPASSERT(n > 0)
    2044            8 :       CPASSERT(SIZE(M_PQ, 2) == n)
    2045            8 :       M_PQ_rank = SIZE(X_Pi, 2)
    2046            8 :       CPASSERT(SIZE(X_Pi, 1) == n)
    2047           24 :       CPASSERT(ALL(SHAPE(B_PQ) == [M_PQ_rank, M_PQ_rank]))
    2048            8 :       CPASSERT(target_normalization > 0.0_dp)
    2049              : 
    2050           32 :       ALLOCATE (B_ij(M_PQ_rank, M_PQ_rank))
    2051         1532 :       B_ij(:, :) = 0.5_dp*(B_PQ + TRANSPOSE(B_PQ))/target_normalization
    2052         1556 :       ALLOCATE (U_ij, source=B_ij)
    2053           24 :       ALLOCATE (eigenval_B(M_PQ_rank))
    2054            8 :       CALL diamat_all(U_ij, eigenval_B, dac=.TRUE.)
    2055          110 :       largest_score = MAXVAL(eigenval_B)
    2056            8 :       IF (largest_score <= 0.0_dp) THEN
    2057            0 :          CPABORT("AUTO_RI conditioned atom-local eigensolver failed")
    2058              :       END IF
    2059              :       ! Only positive target modes can contribute to the optimized RI basis.
    2060              :       ! Discard negative modes after diagonalization; they are never selected.
    2061          110 :       eigenval_B(:) = MAX(eigenval_B, 0.0_dp)
    2062          110 :       nret = COUNT(eigenval_B/largest_score >= relative_target_eigenval_threshold)
    2063           40 :       ALLOCATE (U_Pp_A(n, nret), eigenval(M_PQ_rank))
    2064          110 :       DO i = 1, M_PQ_rank
    2065          110 :          eigenval(i) = eigenval_B(M_PQ_rank - i + 1)
    2066              :       END DO
    2067           94 :       eigenval(nret + 1:) = 0.0_dp
    2068           24 :       DO i = 1, nret
    2069           16 :          j = M_PQ_rank - i + 1
    2070         2034 :          U_Pp_A(:, i) = MATMUL(X_Pi, U_ij(:, j))
    2071              :       END DO
    2072              : 
    2073            8 :       relative_fitting_defect = 1.0_dp
    2074           24 :       DO i = 1, nret
    2075           16 :          j = M_PQ_rank - i + 1
    2076              :          relative_fitting_defect = relative_fitting_defect - &
    2077         2066 :                                    DOT_PRODUCT(U_ij(:, j), MATMUL(B_ij, U_ij(:, j)))
    2078              :       END DO
    2079            8 :       IF (ABS(relative_fitting_defect) < conditioned_negative_eigenval_tolerance) THEN
    2080            8 :          relative_fitting_defect = 0.0_dp
    2081              :       END IF
    2082              :       ! A projection cannot capture more than the exact product norm.
    2083            8 :       IF (relative_fitting_defect < -conditioned_negative_eigenval_tolerance .OR. &
    2084              :           relative_fitting_defect > 1.0_dp + conditioned_negative_eigenval_tolerance) THEN
    2085              :          WRITE (diagnostic, '(A,ES13.5,A,ES13.5,A,ES13.5,A,I0)') &
    2086            0 :             'AUTO_RI AA defect=', relative_fitting_defect, &
    2087            0 :             ' min eig=', MINVAL(eigenval_B), &
    2088            0 :             ' max eig=', largest_score, ' kept=', nret
    2089            0 :          CPABORT(TRIM(diagnostic))
    2090              :       END IF
    2091            8 :       IF (nret > 0) THEN
    2092           64 :          ALLOCATE (M_pp_check(nret, nret), eigenval_M(nret), U_Pp_A_rotated(n, nret))
    2093            8 :          M_pp_check(:, :) = MATMUL(TRANSPOSE(U_Pp_A), &
    2094         6782 :                                    MATMUL(0.5_dp*(M_PQ + TRANSPOSE(M_PQ)), U_Pp_A))
    2095            8 :          CALL diamat_all(M_pp_check, eigenval_M, dac=.TRUE.)
    2096           24 :          IF (MINVAL(eigenval_M) <= reference_M_eigenval_threshold) THEN
    2097            0 :             CPABORT("AUTO_RI conditioned atom-local eigensolver failed")
    2098              :          END IF
    2099         1640 :          U_Pp_A_rotated(:, :) = MATMUL(U_Pp_A, M_pp_check)
    2100           24 :          DO i = 1, nret
    2101          174 :             U_Pp_A_rotated(:, i) = U_Pp_A_rotated(:, i)/SQRT(eigenval_M(i))
    2102              :          END DO
    2103         1640 :          U_Pp_A(:, :) = MATMUL(U_Pp_A_rotated, TRANSPOSE(M_pp_check))
    2104              :          ! Refine M-orthogonality when whitening the reference metric amplifies roundoff.
    2105            8 :          DO iortho = 1, 5
    2106            8 :             M_pp_check(:, :) = MATMUL(TRANSPOSE(U_Pp_A), &
    2107        10982 :                                       MATMUL(0.5_dp*(M_PQ + TRANSPOSE(M_PQ)), U_Pp_A))
    2108           24 :             DO i = 1, nret
    2109           24 :                M_pp_check(i, i) = M_pp_check(i, i) - 1.0_dp
    2110              :             END DO
    2111           80 :             metric_defect = MAXVAL(ABS(M_pp_check))
    2112            8 :             IF (metric_defect < eps_metric_defect) EXIT
    2113            0 :             IF (iortho == 5) EXIT
    2114            0 :             DO i = 1, nret
    2115            0 :                M_pp_check(i, i) = M_pp_check(i, i) + 1.0_dp
    2116              :             END DO
    2117            0 :             CALL diamat_all(M_pp_check, eigenval_M, dac=.TRUE.)
    2118            0 :             IF (MINVAL(eigenval_M) <= reference_M_eigenval_threshold) THEN
    2119            0 :                CPABORT("AUTO_RI selected atom-local metric is singular")
    2120              :             END IF
    2121            0 :             U_Pp_A_rotated(:, :) = MATMUL(U_Pp_A, M_pp_check)
    2122            0 :             DO i = 1, nret
    2123            0 :                U_Pp_A_rotated(:, i) = U_Pp_A_rotated(:, i)/SQRT(eigenval_M(i))
    2124              :             END DO
    2125            0 :             U_Pp_A(:, :) = MATMUL(U_Pp_A_rotated, TRANSPOSE(M_pp_check))
    2126              :          END DO
    2127            8 :          IF (metric_defect >= eps_metric_defect) THEN
    2128              :             WRITE (diagnostic, '(A,ES13.5,A,I0)') &
    2129            0 :                'AUTO_RI selected atom metric defect=', metric_defect, ' refinements=', iortho
    2130            0 :             CPABORT(TRIM(diagnostic))
    2131              :          END IF
    2132              :       END IF
    2133              : 
    2134            8 :       CALL timestop(handle)
    2135              : 
    2136           16 :    END SUBROUTINE solve_AA_eigenproblem_periodic
    2137              : 
    2138              : ! **************************************************************************************************
    2139              : !> \brief Selects the requested RI sizes from the largest positive eigenvalues.
    2140              : !> Scores within sqrt(machine epsilon) times the largest target score are numerically tied.
    2141              : !> Each group is anchored at its largest score; in the partially retained group, prefer the
    2142              : !> least populated block, then its index. Sorting and integer level filling retain descending
    2143              : !> prefixes in O(N log N + nblock log nmode), with at most the tolerance lost per selected mode.
    2144              : !> \param eigenval_by_block descending eigenvalues; zero pads unavailable modes
    2145              : !> \param RI_size_requested requested total number of functions
    2146              : !> \param RI_size_minimum minimum retained size in every nonempty block
    2147              : !> \param sizes_RI_selected number retained from each block
    2148              : ! **************************************************************************************************
    2149            8 :    SUBROUTINE select_RI_sizes_periodic(eigenval_by_block, RI_size_requested, RI_size_minimum, &
    2150            8 :                                        sizes_RI_selected)
    2151              :       REAL(KIND=dp), INTENT(IN)                          :: eigenval_by_block(:, :)
    2152              :       INTEGER, INTENT(IN)                                :: RI_size_requested, RI_size_minimum
    2153              :       INTEGER, INTENT(OUT)                               :: sizes_RI_selected(:)
    2154              : 
    2155              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'select_RI_sizes_periodic'
    2156              : 
    2157              :       INTEGER                                            :: handle, i, iblock, ifirst, ilast, lower, &
    2158              :                                                             middle, n, nmode, npositive, &
    2159              :                                                             remaining, upper
    2160            8 :       INTEGER, ALLOCATABLE                               :: capacity(:), indices(:)
    2161              :       REAL(KIND=dp)                                      :: tolerance
    2162            8 :       REAL(KIND=dp), ALLOCATABLE                         :: values(:)
    2163              : 
    2164            8 :       CALL timeset(routineN, handle)
    2165              : 
    2166            8 :       nmode = SIZE(eigenval_by_block, 1)
    2167           24 :       n = SIZE(eigenval_by_block)
    2168            8 :       CPASSERT(SIZE(sizes_RI_selected) == SIZE(eigenval_by_block, 2))
    2169            8 :       CPASSERT(RI_size_minimum >= 0)
    2170           24 :       sizes_RI_selected(:) = 0
    2171            8 :       IF (n > 0) THEN
    2172           40 :          ALLOCATE (values(n), indices(n))
    2173          228 :          tolerance = SQRT(EPSILON(1.0_dp))*MAXVAL(ABS(eigenval_by_block))
    2174          220 :          values(:) = -RESHAPE(eigenval_by_block, [n])
    2175           24 :          DO iblock = 1, SIZE(sizes_RI_selected)
    2176              :             sizes_RI_selected(iblock) = &
    2177          220 :                MIN(RI_size_minimum, COUNT(eigenval_by_block(:, iblock) > 0.0_dp))
    2178              :             values((iblock - 1)*nmode + 1: &
    2179           40 :                    (iblock - 1)*nmode + sizes_RI_selected(iblock)) = 0.0_dp
    2180              :          END DO
    2181            8 :          CALL sort(values, n, indices)
    2182          212 :          npositive = COUNT(values < 0.0_dp)
    2183           24 :          remaining = MIN(MAX(0, RI_size_requested - SUM(sizes_RI_selected)), npositive)
    2184            8 :          ifirst = 1
    2185           14 :          DO WHILE (remaining > 0)
    2186              :             ilast = ifirst
    2187           16 :             DO WHILE (ilast < npositive)
    2188           14 :                IF (values(ilast + 1) - values(ifirst) > tolerance) EXIT
    2189            6 :                ilast = ilast + 1
    2190              :             END DO
    2191           14 :             IF (ilast - ifirst + 1 <= remaining) THEN
    2192           22 :                DO i = ifirst, ilast
    2193           16 :                   iblock = (indices(i) - 1)/nmode + 1
    2194           22 :                   sizes_RI_selected(iblock) = sizes_RI_selected(iblock) + 1
    2195              :                END DO
    2196            6 :                remaining = remaining - (ilast - ifirst + 1)
    2197            6 :                ifirst = ilast + 1
    2198              :             ELSE
    2199            0 :                ALLOCATE (capacity(SIZE(sizes_RI_selected)), SOURCE=0)
    2200            0 :                DO i = ifirst, ilast
    2201            0 :                   iblock = (indices(i) - 1)/nmode + 1
    2202            0 :                   capacity(iblock) = capacity(iblock) + 1
    2203              :                END DO
    2204              :                ! Fill the boundary group to a common block size; resolve the last layer by index.
    2205            0 :                lower = MINVAL(sizes_RI_selected)
    2206            0 :                upper = MAXVAL(sizes_RI_selected + capacity)
    2207            0 :                DO WHILE (upper - lower > 1)
    2208            0 :                   middle = lower + (upper - lower)/2
    2209            0 :                   IF (SUM(MIN(capacity, MAX(0, middle - sizes_RI_selected))) <= remaining) THEN
    2210              :                      lower = middle
    2211              :                   ELSE
    2212            0 :                      upper = middle
    2213              :                   END IF
    2214              :                END DO
    2215            0 :                DO iblock = 1, SIZE(sizes_RI_selected)
    2216            0 :                   i = MIN(capacity(iblock), MAX(0, lower - sizes_RI_selected(iblock)))
    2217            0 :                   sizes_RI_selected(iblock) = sizes_RI_selected(iblock) + i
    2218            0 :                   capacity(iblock) = capacity(iblock) - i
    2219            0 :                   remaining = remaining - i
    2220              :                END DO
    2221            0 :                DO iblock = 1, SIZE(sizes_RI_selected)
    2222            0 :                   IF (remaining == 0) EXIT
    2223            0 :                   IF (capacity(iblock) == 0 .OR. sizes_RI_selected(iblock) /= lower) CYCLE
    2224            0 :                   sizes_RI_selected(iblock) = sizes_RI_selected(iblock) + 1
    2225            0 :                   remaining = remaining - 1
    2226              :                END DO
    2227            0 :                CPASSERT(remaining == 0)
    2228              :             END IF
    2229              :          END DO
    2230              :       END IF
    2231              : 
    2232            8 :       CALL timestop(handle)
    2233              : 
    2234            8 :    END SUBROUTINE select_RI_sizes_periodic
    2235              : 
    2236          326 : END MODULE gw_auto_ri_generate_RI_basis
        

Generated by: LCOV version 2.0-1