LCOV - code coverage report
Current view: top level - src - qs_scf_loop_utils.F (source / functions) Coverage Total Hit
Test: CP2K Regtests (git:1be8651) Lines: 93.4 % 1731 1617
Test Date: 2026-11-24 01:22:08 Functions: 100.0 % 32 32

            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              : !> \brief Utility routines for qs_scf
       9              : ! **************************************************************************************************
      10              : MODULE qs_scf_loop_utils
      11              :    USE cp_cfm_types,                    ONLY: cp_cfm_create,&
      12              :                                               cp_cfm_p_type,&
      13              :                                               cp_cfm_release,&
      14              :                                               cp_cfm_to_cfm,&
      15              :                                               cp_cfm_to_fm,&
      16              :                                               cp_cfm_type,&
      17              :                                               cp_fm_to_cfm
      18              :    USE cp_control_types,                ONLY: dft_control_type,&
      19              :                                               hairy_probes_type
      20              :    USE cp_dbcsr_api,                    ONLY: dbcsr_copy,&
      21              :                                               dbcsr_get_info,&
      22              :                                               dbcsr_p_type,&
      23              :                                               dbcsr_release,&
      24              :                                               dbcsr_release_p,&
      25              :                                               dbcsr_scale,&
      26              :                                               dbcsr_set,&
      27              :                                               dbcsr_type
      28              :    USE cp_dbcsr_contrib,                ONLY: dbcsr_dot,&
      29              :                                               dbcsr_get_diag,&
      30              :                                               dbcsr_scale_by_vector
      31              :    USE cp_dbcsr_operations,             ONLY: copy_dbcsr_to_fm,&
      32              :                                               copy_fm_to_dbcsr,&
      33              :                                               cp_dbcsr_sm_fm_multiply,&
      34              :                                               dbcsr_allocate_matrix_set,&
      35              :                                               dbcsr_deallocate_matrix_set
      36              :    USE cp_external_control,             ONLY: external_control
      37              :    USE cp_fm_basic_linalg,              ONLY: cp_complex_fm_gemm,&
      38              :                                               cp_fm_column_scale,&
      39              :                                               cp_fm_scale_and_add
      40              :    USE cp_fm_struct,                    ONLY: cp_fm_struct_create,&
      41              :                                               cp_fm_struct_equivalent,&
      42              :                                               cp_fm_struct_release,&
      43              :                                               cp_fm_struct_type
      44              :    USE cp_fm_types,                     ONLY: cp_fm_create,&
      45              :                                               cp_fm_get_info,&
      46              :                                               cp_fm_get_submatrix,&
      47              :                                               cp_fm_p_type,&
      48              :                                               cp_fm_release,&
      49              :                                               cp_fm_set_submatrix,&
      50              :                                               cp_fm_to_fm,&
      51              :                                               cp_fm_type
      52              :    USE cp_log_handling,                 ONLY: cp_to_string
      53              :    USE dft_plus_u,                      ONLY: lowdin_kp_apply,&
      54              :                                               lowdin_kp_apply_mo,&
      55              :                                               lowdin_kp_kernel,&
      56              :                                               lowdin_kp_population
      57              :    USE ieee_arithmetic,                 ONLY: ieee_is_finite
      58              :    USE input_constants,                 ONLY: diag_update_method_adiis,&
      59              :                                               smear_fermi_dirac,&
      60              :                                               smear_gaussian,&
      61              :                                               smear_mp,&
      62              :                                               smear_mv
      63              :    USE input_section_types,             ONLY: section_vals_get,&
      64              :                                               section_vals_get_subs_vals,&
      65              :                                               section_vals_type
      66              :    USE kinds,                           ONLY: default_string_length,&
      67              :                                               dp
      68              :    USE kpoint_methods,                  ONLY: kpoint_density_matrices,&
      69              :                                               kpoint_density_transform,&
      70              :                                               kpoint_set_mo_occupation
      71              :    USE kpoint_types,                    ONLY: get_kpoint_info,&
      72              :                                               kpoint_env_type,&
      73              :                                               kpoint_type
      74              :    USE local_gemm_api,                  ONLY: LOCAL_GEMM_PU_GPU,&
      75              :                                               local_gemm_ctxt_type
      76              :    USE message_passing,                 ONLY: mp_para_env_type
      77              :    USE physcon,                         ONLY: evolt
      78              :    USE qs_density_matrices,             ONLY: calculate_density_matrix
      79              :    USE qs_density_mixing_types,         ONLY: broyden_mixing_nr,&
      80              :                                               direct_mixing_nr,&
      81              :                                               gspace_mixing_nr,&
      82              :                                               modified_broyden_mixing_nr,&
      83              :                                               multisecant_mixing_nr,&
      84              :                                               new_pulay_mixing_nr,&
      85              :                                               no_mixing_nr,&
      86              :                                               pulay_mixing_nr
      87              :    USE qs_energy_types,                 ONLY: qs_energy_type
      88              :    USE qs_environment_types,            ONLY: get_qs_env,&
      89              :                                               qs_environment_type
      90              :    USE qs_fb_env_methods,               ONLY: fb_env_do_diag
      91              :    USE qs_gspace_mixing,                ONLY: gspace_mixing
      92              :    USE qs_kind_types,                   ONLY: get_qs_kind,&
      93              :                                               qs_kind_type,&
      94              :                                               set_qs_kind
      95              :    USE qs_kpoint_operators,             ONLY: kpoint_operator_context_create,&
      96              :                                               kpoint_operator_context_release,&
      97              :                                               kpoint_operator_context_type,&
      98              :                                               kpoint_operator_get,&
      99              :                                               kpoint_operator_get_local,&
     100              :                                               kpoint_operator_prepare,&
     101              :                                               kpoint_operator_store,&
     102              :                                               kpoint_slot_ks
     103              :    USE qs_kpp1_env_types,               ONLY: kpp1_release,&
     104              :                                               qs_kpp1_env_type
     105              :    USE qs_ks_types,                     ONLY: qs_ks_did_change,&
     106              :                                               qs_ks_env_type
     107              :    USE qs_linres_kernel,                ONLY: apply_hxc_kernel_kp
     108              :    USE qs_mixing_utils,                 ONLY: self_consistency_check
     109              :    USE qs_mo_occupation,                ONLY: set_mo_occupation
     110              :    USE qs_mo_types,                     ONLY: get_mo_set,&
     111              :                                               mo_set_type
     112              :    USE qs_mom_methods,                  ONLY: do_mom_diag
     113              :    USE qs_neighbor_list_types,          ONLY: neighbor_list_set_p_type
     114              :    USE qs_ot_kp,                        ONLY: &
     115              :         qs_ot_antihermitian_spectral_norm, qs_ot_density_secant_orbital_overlaps, &
     116              :         qs_ot_density_secant_projected_hessian, qs_ot_density_tangent, &
     117              :         qs_ot_finite_rotation_response, qs_ot_fixed_n_energy_gradient, &
     118              :         qs_ot_fixed_n_multigroup_schur_block, qs_ot_get_orbitals_complex, &
     119              :         qs_ot_get_orbitals_local_batch, qs_ot_get_orbitals_ref_complex, &
     120              :         qs_ot_projected_response_update, qs_ot_symmetric_abs_solve
     121              :    USE qs_ot_minimizer,                 ONLY: ot_mermin_response_preparation_needed,&
     122              :                                               ot_mermin_secant_curvature,&
     123              :                                               ot_mini,&
     124              :                                               ot_mini_prepare,&
     125              :                                               ot_mini_prepare_gradient
     126              :    USE qs_ot_scf,                       ONLY: ot_scf_destroy,&
     127              :                                               ot_scf_mini
     128              :    USE qs_ot_types,                     ONLY: qs_ot_channel_index,&
     129              :                                               qs_ot_check_channel_context,&
     130              :                                               qs_ot_physical_secant_type,&
     131              :                                               qs_ot_type
     132              :    USE qs_outer_scf,                    ONLY: outer_loop_gradient
     133              :    USE qs_rho_methods,                  ONLY: qs_rho_update_rho
     134              :    USE qs_rho_types,                    ONLY: qs_rho_get,&
     135              :                                               qs_rho_type
     136              :    USE qs_scf_diagonalization,          ONLY: &
     137              :         do_block_davidson_diag, do_block_davidson_diag_kp, do_block_krylov_diag, &
     138              :         do_block_krylov_diag_kp, do_general_diag, do_general_diag_kp, do_ot_diag, do_ot_diag_kp, &
     139              :         do_roks_diag, do_scf_diag_subspace, do_special_diag
     140              :    USE qs_scf_methods,                  ONLY: cp_sm_mix,&
     141              :                                               scf_env_density_mixing
     142              :    USE qs_scf_output,                   ONLY: qs_scf_print_summary
     143              :    USE qs_scf_types,                    ONLY: &
     144              :         block_davidson_diag_method_nr, block_krylov_diag_method_nr, filter_matrix_diag_method_nr, &
     145              :         general_diag_method_nr, ot_diag_method_nr, ot_method_nr, qs_scf_env_type, &
     146              :         scf_env_release_ot_operators, smeagol_method_nr, special_diag_method_nr
     147              :    USE scf_control_types,               ONLY: scf_control_type,&
     148              :                                               smear_type
     149              :    USE smeagol_interface,               ONLY: run_smeagol_emtrans
     150              :    USE smearing_utils,                  ONLY: Smearkp,&
     151              :                                               Smearkp2,&
     152              :                                               smearing_response_weight,&
     153              :                                               smearing_separate_spin,&
     154              :                                               smearing_spin_targets
     155              :    USE tblite_interface,                ONLY: tb_native_scc_mixer_active
     156              : 
     157              : !$ USE OMP_LIB, ONLY: omp_get_max_threads, omp_get_thread_num
     158              : #include "./base/base_uses.f90"
     159              : 
     160              :    IMPLICIT NONE
     161              : 
     162              :    PRIVATE
     163              : 
     164              :    CHARACTER(len=*), PARAMETER, PRIVATE :: moduleN = 'qs_scf_loop_utils'
     165              : 
     166              :    PUBLIC :: qs_scf_set_loop_flags, &
     167              :              qs_scf_new_mos, qs_scf_new_mos_kp, &
     168              :              qs_scf_kp_ref_refresh_ready, qs_scf_kp_search_endpoint, &
     169              :              qs_scf_candidate_density_delta, qs_scf_commit_density_candidate, &
     170              :              qs_scf_density_mixing, qs_scf_check_inner_exit, &
     171              :              qs_scf_check_outer_exit, qs_scf_inner_finalize, qs_scf_rho_update
     172              : 
     173              : CONTAINS
     174              : 
     175              : ! **************************************************************************************************
     176              : !> \brief identify an accepted OT search endpoint from its iteration label
     177              : !> \param method OT iteration label
     178              : !> \return true for the primary endpoint of every supported minimizer
     179              : ! **************************************************************************************************
     180         3144 :    PURE FUNCTION qs_scf_kp_search_endpoint(method) RESULT(endpoint)
     181              : 
     182              :       CHARACTER(LEN=*), INTENT(IN)                       :: method
     183              :       LOGICAL                                            :: endpoint
     184              : 
     185         3144 :       SELECT CASE (TRIM(method))
     186              :       CASE ("OT CG", "OT SD", "OT DIIS", "OT BROY", "OT LBFGS")
     187         1278 :          endpoint = .TRUE.
     188              :       CASE DEFAULT
     189         3144 :          endpoint = .FALSE.
     190              :       END SELECT
     191              : 
     192         3144 :    END FUNCTION qs_scf_kp_search_endpoint
     193              : 
     194              : ! **************************************************************************************************
     195              : !> \brief decide whether a mature variable-occupation REF chart should be rebuilt
     196              : !> \param accepted_searches accepted search directions in the current REF chart
     197              : !> \param residual current OT residual
     198              : !> \param eps_scf requested SCF threshold
     199              : !> \param base_state whether the current point can start a new search direction
     200              : !> \param allow_exit_window whether a prior physical REF rebuild permits an exit-only rebuild
     201              : !> \return true inside the asymptotic residual window after sufficient accepted history
     202              : ! **************************************************************************************************
     203         1500 :    PURE FUNCTION qs_scf_kp_ref_refresh_ready( &
     204              :       accepted_searches, residual, eps_scf, base_state, allow_exit_window) &
     205              :       RESULT(refresh)
     206              : 
     207              :       INTEGER, INTENT(IN)                                :: accepted_searches
     208              :       REAL(KIND=dp), INTENT(IN)                          :: residual, eps_scf
     209              :       LOGICAL, INTENT(IN)                                :: base_state
     210              :       LOGICAL, INTENT(IN), OPTIONAL                      :: allow_exit_window
     211              :       LOGICAL                                            :: refresh
     212              : 
     213              :       INTEGER, PARAMETER                                 :: min_accepted_searches = 12
     214              : 
     215              :       LOGICAL                                            :: exit_window
     216              :       REAL(KIND=dp)                                      :: eps
     217              : 
     218         1500 :       eps = MAX(eps_scf, EPSILON(1.0_dp))
     219         1500 :       exit_window = .FALSE.
     220         1500 :       IF (PRESENT(allow_exit_window)) exit_window = allow_exit_window
     221              :       refresh = base_state .AND. accepted_searches >= min_accepted_searches .AND. &
     222              :                 ((residual > 10.0_dp*eps .AND. residual <= 0.2_dp*SQRT(eps)) .OR. &
     223         1500 :                  (exit_window .AND. residual > 0.25_dp*eps .AND. residual <= 10.0_dp*eps))
     224              : 
     225         1500 :    END FUNCTION qs_scf_kp_ref_refresh_ready
     226              : 
     227              : ! **************************************************************************************************
     228              : !> \brief computes properties for a given hamiltonian using the current wfn
     229              : !> \param scf_env ...
     230              : !> \param diis_step ...
     231              : !> \param energy_only ...
     232              : !> \param just_energy ...
     233              : !> \param exit_inner_loop ...
     234              : ! **************************************************************************************************
     235        26043 :    SUBROUTINE qs_scf_set_loop_flags(scf_env, diis_step, &
     236              :                                     energy_only, just_energy, exit_inner_loop)
     237              : 
     238              :       TYPE(qs_scf_env_type), POINTER                     :: scf_env
     239              :       LOGICAL                                            :: diis_step, energy_only, just_energy, &
     240              :                                                             exit_inner_loop
     241              : 
     242              : ! Some flags needed to be set at the beginning of the loop
     243              : 
     244        26043 :       diis_step = .FALSE.
     245        26043 :       energy_only = .FALSE.
     246        26043 :       just_energy = .FALSE.
     247              : 
     248              :       ! SCF loop, optimisation of the wfn coefficients
     249              :       ! qs_env%rho%rho_r and qs_env%rho%rho_g should be up to date here
     250              : 
     251        26043 :       scf_env%iter_count = 0
     252        26043 :       scf_env%adiis_check_next = .FALSE.
     253        26043 :       scf_env%adiis_validated = .FALSE.
     254        26043 :       scf_env%step_norm = 0.0_dp
     255        26043 :       scf_env%raw_map_delta = 0.0_dp
     256        26043 :       scf_env%raw_map_delta_valid = .FALSE.
     257        26043 :       exit_inner_loop = .FALSE.
     258              : 
     259        26043 :    END SUBROUTINE qs_scf_set_loop_flags
     260              : 
     261              : ! **************************************************************************************************
     262              : !> \brief takes known energy and derivatives and produces new wfns
     263              : !>        and or density matrix
     264              : !> \param qs_env ...
     265              : !> \param scf_env ...
     266              : !> \param scf_control ...
     267              : !> \param scf_section ...
     268              : !> \param diis_step ...
     269              : !> \param energy_only ...
     270              : !> \param probe ...
     271              : ! **************************************************************************************************
     272       203883 :    SUBROUTINE qs_scf_new_mos(qs_env, scf_env, scf_control, scf_section, diis_step, &
     273              :                              energy_only, probe)
     274              :       TYPE(qs_environment_type), POINTER                 :: qs_env
     275              :       TYPE(qs_scf_env_type), POINTER                     :: scf_env
     276              :       TYPE(scf_control_type), POINTER                    :: scf_control
     277              :       TYPE(section_vals_type), POINTER                   :: scf_section
     278              :       LOGICAL                                            :: diis_step, energy_only
     279              :       TYPE(hairy_probes_type), DIMENSION(:), OPTIONAL, &
     280              :          POINTER                                         :: probe
     281              : 
     282              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'qs_scf_new_mos'
     283              : 
     284              :       INTEGER                                            :: handle, ispin
     285              :       LOGICAL                                            :: disable_diis, has_unit_metric, &
     286              :                                                             skip_diag_sub
     287              :       REAL(KIND=dp)                                      :: saved_eps_diis
     288       203883 :       TYPE(dbcsr_p_type), DIMENSION(:), POINTER          :: matrix_ks, matrix_s
     289              :       TYPE(dft_control_type), POINTER                    :: dft_control
     290       203883 :       TYPE(mo_set_type), DIMENSION(:), POINTER           :: mos
     291              :       TYPE(qs_energy_type), POINTER                      :: energy
     292              :       TYPE(qs_ks_env_type), POINTER                      :: ks_env
     293              :       TYPE(qs_rho_type), POINTER                         :: rho
     294              : 
     295       203883 :       CALL timeset(routineN, handle)
     296              : 
     297       203883 :       NULLIFY (energy, ks_env, matrix_ks, matrix_s, rho, mos, dft_control)
     298              : 
     299              :       CALL get_qs_env(qs_env=qs_env, &
     300              :                       matrix_s=matrix_s, energy=energy, &
     301              :                       ks_env=ks_env, &
     302              :                       matrix_ks=matrix_ks, rho=rho, mos=mos, &
     303              :                       dft_control=dft_control, &
     304       203883 :                       has_unit_metric=has_unit_metric)
     305       203883 :       scf_env%iter_param = 0.0_dp
     306              : 
     307              :       disable_diis = dft_control%qs_control%xtb_control%do_tblite .AND. &
     308       203883 :                      tb_native_scc_mixer_active(dft_control)
     309              :       IF (disable_diis) THEN
     310        12168 :          saved_eps_diis = scf_control%eps_diis
     311        12168 :          scf_control%eps_diis = 0.0_dp
     312              :       END IF
     313              : 
     314              :       ! transfer total_zeff_corr from qs_env to scf_env only if
     315              :       ! correct_el_density_dip is switched on [SGh]
     316       203883 :       IF (dft_control%correct_el_density_dip) THEN
     317           40 :          scf_env%sum_zeff_corr = qs_env%total_zeff_corr
     318           40 :          IF (ABS(qs_env%total_zeff_corr) > 0.0_dp) THEN
     319           40 :             IF (scf_env%method /= general_diag_method_nr) THEN
     320              :                CALL cp_abort(__LOCATION__, &
     321              :                              "Please use ALGORITHM STANDARD in "// &
     322              :                              "SCF%DIAGONALIZATION if "// &
     323              :                              "CORE_CORRECTION /= 0.0 and "// &
     324            0 :                              "SURFACE_DIPOLE_CORRECTION TRUE ")
     325           40 :             ELSE IF (dft_control%roks) THEN
     326              :                CALL cp_abort(__LOCATION__, &
     327              :                              "Combination of "// &
     328              :                              "CORE_CORRECTION /= 0.0 and "// &
     329              :                              "SURFACE_DIPOLE_CORRECTION TRUE "// &
     330            0 :                              "is not implemented with ROKS")
     331           40 :             ELSE IF (scf_control%diagonalization%mom) THEN
     332              :                CALL cp_abort(__LOCATION__, &
     333              :                              "Combination of "// &
     334              :                              "CORE_CORRECTION /= 0.0 and "// &
     335              :                              "SURFACE_DIPOLE_CORRECTION TRUE "// &
     336            0 :                              "is not implemented with SCF%MOM")
     337              :             END IF
     338              :          END IF
     339              :       END IF
     340              : 
     341       203883 :       SELECT CASE (scf_env%method)
     342              :       CASE DEFAULT
     343              :          CALL cp_abort(__LOCATION__, &
     344              :                        "unknown scf method: "// &
     345            0 :                        cp_to_string(scf_env%method))
     346              : 
     347              :          ! *************************************************************************
     348              :          ! Filter matrix diagonalisation: ugly implementation at this point of time
     349              :          ! *************************************************************************
     350              :       CASE (filter_matrix_diag_method_nr)
     351              : 
     352           80 :          IF (ABS(qs_env%total_zeff_corr) > 0.0_dp) THEN
     353              :             CALL cp_abort(__LOCATION__, &
     354              :                           "CORE_CORRECTION /= 0.0 plus SURFACE_DIPOLE_CORRECTION TRUE "// &
     355            0 :                           "requires SCF%DIAGONALIZATION: ALGORITHM STANDARD")
     356              :          END IF
     357              :          CALL fb_env_do_diag(scf_env%filter_matrix_env, qs_env, &
     358           80 :                              matrix_ks, matrix_s, scf_section, diis_step)
     359              : 
     360              :          ! Diagonlization in non orthonormal case
     361              :       CASE (general_diag_method_nr)
     362       104579 :          IF (dft_control%roks) THEN
     363              :             CALL do_roks_diag(scf_env, mos, matrix_ks, matrix_s, &
     364              :                               scf_control, scf_section, diis_step, &
     365          600 :                               has_unit_metric)
     366              :          ELSE
     367       103979 :             IF (scf_control%diagonalization%mom) THEN
     368              :                CALL do_mom_diag(scf_env, mos, matrix_ks, &
     369              :                                 matrix_s, scf_control, scf_section, &
     370          342 :                                 diis_step)
     371              :             ELSE
     372       103637 :                IF (dft_control%hairy_probes .EQV. .TRUE.) THEN
     373              :                   CALL do_general_diag(scf_env, mos, matrix_ks, &
     374              :                                        matrix_s, scf_control, scf_section, &
     375              :                                        diis_step, &
     376           14 :                                        probe)
     377              :                ELSE
     378              :                   CALL do_general_diag(scf_env, mos, matrix_ks, &
     379              :                                        matrix_s, scf_control, scf_section, &
     380       103623 :                                        diis_step)
     381              :                END IF
     382              :             END IF
     383       103979 :             IF (scf_control%do_diag_sub) THEN
     384              :                skip_diag_sub = (scf_env%subspace_env%eps_diag_sub > 0.0_dp) .AND. &
     385           10 :                                (scf_env%iter_count == 1 .OR. scf_env%iter_delta > scf_env%subspace_env%eps_diag_sub)
     386              :                IF (.NOT. skip_diag_sub) THEN
     387              :                   CALL do_scf_diag_subspace(qs_env, scf_env, scf_env%subspace_env, mos, rho, &
     388           10 :                                             ks_env, scf_section, scf_control)
     389              :                END IF
     390              :             END IF
     391              :          END IF
     392              :          ! Diagonlization in orthonormal case
     393              :       CASE (special_diag_method_nr)
     394        18398 :          IF (dft_control%roks) THEN
     395              :             CALL do_roks_diag(scf_env, mos, matrix_ks, matrix_s, &
     396              :                               scf_control, scf_section, diis_step, &
     397          522 :                               has_unit_metric)
     398              :          ELSE
     399              :             CALL do_special_diag(scf_env, mos, matrix_ks, &
     400              :                                  scf_control, scf_section, &
     401        17876 :                                  diis_step)
     402              :          END IF
     403              :          ! OT diagonalization
     404              :       CASE (ot_diag_method_nr)
     405              :          CALL do_ot_diag(scf_env, mos, matrix_ks, matrix_s, &
     406          202 :                          scf_control, scf_section, diis_step)
     407              :          ! Block Krylov diagonlization
     408              :       CASE (block_krylov_diag_method_nr)
     409          116 :          IF ((scf_env%krylov_settings%eps_std_diag > 0.0_dp) .AND. &
     410              :              (scf_env%iter_count == 1 .OR. scf_env%iter_delta > scf_env%krylov_settings%eps_std_diag)) THEN
     411            2 :             IF (scf_env%krylov_settings%always_check_conv) THEN
     412              :                CALL do_block_krylov_diag(scf_env, mos, matrix_ks, &
     413            0 :                                          scf_control, scf_section, check_moconv_only=.TRUE.)
     414              :             END IF
     415              :             CALL do_general_diag(scf_env, mos, matrix_ks, &
     416            2 :                                  matrix_s, scf_control, scf_section, diis_step)
     417              :          ELSE
     418              :             CALL do_block_krylov_diag(scf_env, mos, matrix_ks, &
     419          114 :                                       scf_control, scf_section)
     420              :          END IF
     421          116 :          IF (scf_control%do_diag_sub) THEN
     422              :             skip_diag_sub = (scf_env%subspace_env%eps_diag_sub > 0.0_dp) .AND. &
     423            0 :                             (scf_env%iter_count == 1 .OR. scf_env%iter_delta > scf_env%subspace_env%eps_diag_sub)
     424              :             IF (.NOT. skip_diag_sub) THEN
     425              :                CALL do_scf_diag_subspace(qs_env, scf_env, scf_env%subspace_env, mos, rho, &
     426            0 :                                          ks_env, scf_section, scf_control)
     427              :             END IF
     428              :          END IF
     429              :          ! Block Davidson diagonlization
     430              :       CASE (block_davidson_diag_method_nr)
     431              :          CALL do_block_davidson_diag(qs_env, scf_env, mos, matrix_ks, matrix_s, scf_control, &
     432           94 :                                      scf_section, .FALSE.)
     433              :          ! OT without diagonlization. Needs special treatment for SCP runs
     434              :       CASE (ot_method_nr)
     435              :          CALL qs_scf_loop_do_ot(qs_env, scf_env, scf_control%smear, mos, rho, &
     436              :                                 qs_env%mo_derivs, energy%total, &
     437       203883 :                                 matrix_s, energy_only=energy_only, has_unit_metric=has_unit_metric)
     438              :       END SELECT
     439       203883 :       IF (disable_diis) scf_control%eps_diis = saved_eps_diis
     440              : 
     441       203883 :       energy%kTS = 0.0_dp
     442       203883 :       energy%efermi = 0.0_dp
     443       203883 :       CALL get_qs_env(qs_env, mos=mos)
     444       444301 :       DO ispin = 1, SIZE(mos)
     445       240418 :          energy%kTS = energy%kTS + mos(ispin)%kTS
     446       444301 :          energy%efermi = energy%efermi + mos(ispin)%mu
     447              :       END DO
     448       203883 :       energy%efermi = energy%efermi/REAL(SIZE(mos), KIND=dp)
     449              : 
     450       203883 :       CALL timestop(handle)
     451              : 
     452       203883 :    END SUBROUTINE qs_scf_new_mos
     453              : 
     454              : ! **************************************************************************************************
     455              : !> \brief Updates MOs and density matrix using diagonalization
     456              : !>        Kpoint code
     457              : !> \param qs_env ...
     458              : !> \param scf_env ...
     459              : !> \param scf_control ...
     460              : !> \param diis_step ...
     461              : !> \param probe ...
     462              : !> \param ot_kp_subspace_refresh ...
     463              : !> \param allow_ot_kp_subspace_refresh ...
     464              : !> \param allow_ot_kp_exit_refresh ...
     465              : !> \param accepted_ot_kp_searches ...
     466              : !> \param added_mos_auto_grow ...
     467              : !> \param energy_only ...
     468              : ! **************************************************************************************************
     469        41578 :    SUBROUTINE qs_scf_new_mos_kp(qs_env, scf_env, scf_control, diis_step, probe, &
     470              :                                 ot_kp_subspace_refresh, allow_ot_kp_subspace_refresh, &
     471              :                                 allow_ot_kp_exit_refresh, accepted_ot_kp_searches, &
     472              :                                 added_mos_auto_grow, energy_only)
     473              :       TYPE(qs_environment_type), POINTER                 :: qs_env
     474              :       TYPE(qs_scf_env_type), POINTER                     :: scf_env
     475              :       TYPE(scf_control_type), POINTER                    :: scf_control
     476              :       LOGICAL                                            :: diis_step
     477              :       TYPE(hairy_probes_type), DIMENSION(:), OPTIONAL, &
     478              :          POINTER                                         :: probe
     479              :       LOGICAL, INTENT(OUT), OPTIONAL                     :: ot_kp_subspace_refresh
     480              :       LOGICAL, INTENT(IN), OPTIONAL                      :: allow_ot_kp_subspace_refresh, &
     481              :                                                             allow_ot_kp_exit_refresh
     482              :       INTEGER, INTENT(IN), OPTIONAL                      :: accepted_ot_kp_searches
     483              :       LOGICAL, INTENT(OUT), OPTIONAL                     :: added_mos_auto_grow, energy_only
     484              : 
     485              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'qs_scf_new_mos_kp'
     486              : 
     487              :       INTEGER                                            :: accepted_searches, handle, ispin, &
     488              :                                                             refresh_count
     489              :       LOGICAL :: allow_exit_refresh, allow_refresh, base_state, disable_diis, has_unit_metric, &
     490              :          my_added_mos_auto_grow, ot_energy_only, refresh
     491              :       REAL(dp)                                           :: diis_error, residual, saved_eps_diis
     492        41578 :       TYPE(dbcsr_p_type), DIMENSION(:, :), POINTER       :: matrix_ks, matrix_s, matrix_t
     493              :       TYPE(dft_control_type), POINTER                    :: dft_control
     494              :       TYPE(kpoint_type), POINTER                         :: kpoints
     495        41578 :       TYPE(mo_set_type), DIMENSION(:), POINTER           :: mos
     496              :       TYPE(mp_para_env_type), POINTER                    :: para_env
     497              :       TYPE(qs_energy_type), POINTER                      :: energy
     498              : 
     499        41578 :       CALL timeset(routineN, handle)
     500              : 
     501        41578 :       allow_refresh = .FALSE.
     502        41578 :       allow_exit_refresh = .FALSE.
     503        41578 :       accepted_searches = 0
     504        41578 :       my_added_mos_auto_grow = .FALSE.
     505        41578 :       refresh = .FALSE.
     506        41578 :       IF (PRESENT(allow_ot_kp_subspace_refresh)) allow_refresh = allow_ot_kp_subspace_refresh
     507        41578 :       IF (PRESENT(allow_ot_kp_exit_refresh)) allow_exit_refresh = allow_ot_kp_exit_refresh
     508        41578 :       IF (PRESENT(accepted_ot_kp_searches)) accepted_searches = accepted_ot_kp_searches
     509        41578 :       IF (PRESENT(ot_kp_subspace_refresh)) ot_kp_subspace_refresh = .FALSE.
     510        41578 :       IF (PRESENT(added_mos_auto_grow)) added_mos_auto_grow = .FALSE.
     511        41578 :       IF (PRESENT(energy_only)) energy_only = .FALSE.
     512              : 
     513        41578 :       NULLIFY (dft_control, energy, kpoints, matrix_ks, matrix_s, matrix_t, para_env)
     514              : 
     515        41578 :       CALL get_qs_env(qs_env=qs_env, dft_control=dft_control, energy=energy, kpoints=kpoints)
     516        41578 :       CALL get_kpoint_info(kpoints, para_env=para_env)
     517        41578 :       CPASSERT(ASSOCIATED(para_env))
     518        41578 :       scf_env%iter_param = 0.0_dp
     519              :       disable_diis = dft_control%qs_control%xtb_control%do_tblite .AND. &
     520        41578 :                      tb_native_scc_mixer_active(dft_control)
     521              :       IF (disable_diis) THEN
     522        10680 :          saved_eps_diis = scf_control%eps_diis
     523        10680 :          scf_control%eps_diis = 0.0_dp
     524              :       END IF
     525              : 
     526        41578 :       IF (dft_control%roks .AND. scf_env%method /= ot_method_nr) THEN
     527            0 :          CPABORT("KP code: ROKS method not available: ")
     528              :       END IF
     529              : 
     530        41578 :       SELECT CASE (scf_env%method)
     531              :       CASE DEFAULT
     532              :          CALL cp_abort(__LOCATION__, &
     533              :                        "KP code: Unknown scf method: "// &
     534            0 :                        cp_to_string(scf_env%method))
     535              :       CASE (general_diag_method_nr)
     536              :          ! Diagonlization in non orthonormal case
     537        36830 :          CALL get_qs_env(qs_env, matrix_ks_kp=matrix_ks, matrix_s_kp=matrix_s)
     538        36830 :          IF (scf_control%diagonalization%update_method == diag_update_method_adiis) THEN
     539           80 :             CPASSERT(ASSOCIATED(scf_env%scf_subspace_buffer))
     540           80 :             diis_error = scf_env%scf_subspace_buffer%last_old_fock_weight
     541              :          END IF
     542        36830 :          IF (dft_control%hairy_probes .EQV. .TRUE.) THEN
     543            0 :             scf_control%smear%do_smear = .FALSE.
     544              :             CALL do_general_diag_kp(matrix_ks, matrix_s, kpoints, scf_env, scf_control, .TRUE., &
     545            0 :                                     diis_step, diis_error, qs_env, probe)
     546              :          ELSE
     547              :             CALL do_general_diag_kp(matrix_ks, matrix_s, kpoints, scf_env, scf_control, .TRUE., &
     548              :                                     diis_step, diis_error, qs_env, &
     549        36830 :                                     added_mos_auto_grow=my_added_mos_auto_grow)
     550              :          END IF
     551        36830 :          IF (my_added_mos_auto_grow) THEN
     552            0 :             IF (PRESENT(added_mos_auto_grow)) added_mos_auto_grow = .TRUE.
     553            0 :             IF (disable_diis) scf_control%eps_diis = saved_eps_diis
     554            0 :             CALL timestop(handle)
     555           14 :             RETURN
     556              :          END IF
     557        36830 :          IF (scf_control%diagonalization%update_method == diag_update_method_adiis .AND. &
     558            0 :              .NOT. diis_step) THEN
     559           48 :             scf_env%iter_param = diis_error
     560           48 :             IF (scf_env%scf_subspace_buffer%last_restart) THEN
     561            0 :                scf_env%iter_method = "ADIIS/Rst."
     562              :             ELSE
     563           48 :                scf_env%iter_method = "ADIIS/Diag."
     564              :             END IF
     565        36782 :          ELSE IF (diis_step) THEN
     566        10660 :             scf_env%iter_param = diis_error
     567        10660 :             scf_env%iter_method = "DIIS/Diag."
     568              :          ELSE
     569        26122 :             IF (scf_env%mixing_method == 0) THEN
     570            0 :                scf_env%iter_method = "NoMix/Diag."
     571        26122 :             ELSE IF (scf_env%mixing_method == 1) THEN
     572        20260 :                scf_env%iter_param = scf_env%p_mix_alpha
     573        20260 :                scf_env%iter_method = "P_Mix/Diag."
     574         5862 :             ELSE IF (scf_env%mixing_method > 1) THEN
     575         5862 :                scf_env%iter_param = scf_env%mixing_store%alpha
     576         5862 :                scf_env%iter_method = TRIM(scf_env%mixing_store%iter_method)//"/Diag."
     577              :             END IF
     578              :          END IF
     579              :       CASE (special_diag_method_nr)
     580            0 :          CALL get_qs_env(qs_env=qs_env, has_unit_metric=has_unit_metric)
     581            0 :          CPASSERT(has_unit_metric)
     582              :          ! Diagonlization in orthonormal case
     583              :          CALL cp_abort(__LOCATION__, &
     584              :                        "KP code: Scf method not available: "// &
     585            0 :                        cp_to_string(scf_env%method))
     586              :       CASE (ot_diag_method_nr)
     587          100 :          CALL get_qs_env(qs_env, matrix_ks_kp=matrix_ks, matrix_s_kp=matrix_s, kinetic_kp=matrix_t)
     588              :          CALL do_ot_diag_kp(matrix_ks, matrix_s, matrix_t, kpoints, scf_env, scf_control, &
     589          100 :                             diis_step, my_added_mos_auto_grow)
     590          100 :          IF (my_added_mos_auto_grow) THEN
     591            0 :             IF (PRESENT(added_mos_auto_grow)) added_mos_auto_grow = .TRUE.
     592            0 :             IF (disable_diis) scf_control%eps_diis = saved_eps_diis
     593            0 :             CALL timestop(handle)
     594            0 :             RETURN
     595              :          END IF
     596              :       CASE (block_krylov_diag_method_nr)
     597          586 :          CALL get_qs_env(qs_env=qs_env, matrix_ks_kp=matrix_ks, matrix_s_kp=matrix_s)
     598          586 :          IF ((scf_env%krylov_settings%eps_std_diag > 0.0_dp) .AND. &
     599          910 :              (scf_env%iter_count == 1 .OR. scf_env%iter_delta > scf_env%krylov_settings%eps_std_diag)) THEN
     600            0 :             IF (scf_env%krylov_settings%always_check_conv) THEN
     601              :                CALL do_block_krylov_diag_kp(qs_env, scf_env, matrix_ks, matrix_s, kpoints, &
     602            0 :                                             scf_control, check_moconv_only=.TRUE.)
     603              :             END IF
     604              :             CALL do_general_diag_kp(matrix_ks, matrix_s, kpoints, scf_env, scf_control, .TRUE., &
     605              :                                     diis_step, diis_error, qs_env, &
     606            0 :                                     added_mos_auto_grow=my_added_mos_auto_grow)
     607            0 :             IF (my_added_mos_auto_grow) THEN
     608            0 :                IF (PRESENT(added_mos_auto_grow)) added_mos_auto_grow = .TRUE.
     609            0 :                IF (disable_diis) scf_control%eps_diis = saved_eps_diis
     610            0 :                CALL timestop(handle)
     611            0 :                RETURN
     612              :             END IF
     613              :          ELSE
     614              :             CALL do_block_krylov_diag_kp(qs_env, scf_env, matrix_ks, matrix_s, kpoints, &
     615          586 :                                          scf_control, added_mos_auto_grow=my_added_mos_auto_grow)
     616          586 :             IF (my_added_mos_auto_grow) THEN
     617            4 :                IF (PRESENT(added_mos_auto_grow)) added_mos_auto_grow = .TRUE.
     618            4 :                IF (disable_diis) scf_control%eps_diis = saved_eps_diis
     619            4 :                CALL timestop(handle)
     620            4 :                RETURN
     621              :             END IF
     622              :          END IF
     623              :       CASE (block_davidson_diag_method_nr)
     624          910 :          CALL get_qs_env(qs_env, matrix_ks_kp=matrix_ks, matrix_s_kp=matrix_s)
     625              :          CALL do_block_davidson_diag_kp(qs_env, scf_env, matrix_ks, matrix_s, kpoints, &
     626          910 :                                         scf_control, added_mos_auto_grow=my_added_mos_auto_grow)
     627          910 :          IF (my_added_mos_auto_grow) THEN
     628            4 :             IF (PRESENT(added_mos_auto_grow)) added_mos_auto_grow = .TRUE.
     629            4 :             IF (disable_diis) scf_control%eps_diis = saved_eps_diis
     630            4 :             CALL timestop(handle)
     631            4 :             RETURN
     632              :          END IF
     633              :       CASE (ot_method_nr)
     634         3152 :          CALL get_qs_env(qs_env, matrix_ks_kp=matrix_ks, matrix_s_kp=matrix_s)
     635              :          base_state = .NOT. scf_env%qs_ot_env(1)%energy_only .AND. &
     636              :                       (scf_env%qs_ot_env(1)%line_search_count == 0 .OR. &
     637         3152 :                        scf_env%qs_ot_env(1)%line_search_might_be_done)
     638         3152 :          residual = MAX(scf_env%iter_delta, scf_env%qs_ot_env(1)%delta)
     639              :          refresh = (allow_refresh .OR. allow_exit_refresh) .AND. &
     640              :                    scf_env%qs_ot_env(1)%settings%do_ener .AND. &
     641              :                    (scf_env%qs_ot_env(1)%settings%occupation_preconditioner .OR. &
     642              :                     scf_control%smear%method == smear_fermi_dirac) .AND. &
     643              :                    (dft_control%smear .OR. scf_control%smear%do_smear) .AND. &
     644              :                    qs_scf_kp_ref_refresh_ready(accepted_searches, residual, &
     645         3152 :                                                scf_control%eps_scf, base_state, allow_exit_refresh)
     646         3152 :          refresh_count = MERGE(1, 0, refresh)
     647         3152 :          CALL para_env%sum(refresh_count)
     648         3152 :          refresh = refresh_count > 0
     649         3152 :          IF (refresh) THEN
     650           16 :             IF (PRESENT(ot_kp_subspace_refresh)) ot_kp_subspace_refresh = .TRUE.
     651              :          ELSE
     652              :             CALL qs_scf_loop_do_ot_kp(qs_env, scf_env, matrix_ks, matrix_s, &
     653         3136 :                                       my_added_mos_auto_grow, ot_energy_only)
     654         3136 :             IF (PRESENT(energy_only)) energy_only = ot_energy_only
     655         3136 :             IF (my_added_mos_auto_grow) THEN
     656            6 :                IF (PRESENT(added_mos_auto_grow)) added_mos_auto_grow = .TRUE.
     657            6 :                IF (disable_diis) scf_control%eps_diis = saved_eps_diis
     658            6 :                CALL timestop(handle)
     659            6 :                RETURN
     660              :             END IF
     661         3130 :             IF (allow_exit_refresh .AND. scf_env%iter_delta <= scf_control%eps_scf) THEN
     662           14 :                base_state = qs_scf_kp_search_endpoint(scf_env%iter_method)
     663              :                refresh = qs_scf_kp_ref_refresh_ready( &
     664              :                          accepted_searches, scf_env%iter_delta, scf_control%eps_scf, &
     665           14 :                          base_state, allow_exit_window=.TRUE.)
     666           14 :                IF (refresh .AND. PRESENT(ot_kp_subspace_refresh)) THEN
     667            0 :                   ot_kp_subspace_refresh = .TRUE.
     668              :                END IF
     669              :             END IF
     670         3130 :             refresh_count = MERGE(1, 0, refresh)
     671         3130 :             CALL para_env%sum(refresh_count)
     672         3130 :             refresh = refresh_count > 0
     673         3130 :             IF (refresh .AND. PRESENT(ot_kp_subspace_refresh)) THEN
     674            0 :                ot_kp_subspace_refresh = .TRUE.
     675              :             END IF
     676              :          END IF
     677              :       CASE (smeagol_method_nr)
     678              :          ! SMEAGOL interface
     679            0 :          diis_step = .FALSE.
     680            0 :          IF (scf_env%mixing_method == 0) THEN
     681            0 :             scf_env%iter_method = "NoMix/SMGL"
     682            0 :          ELSE IF (scf_env%mixing_method == 1) THEN
     683            0 :             scf_env%iter_param = scf_env%p_mix_alpha
     684            0 :             scf_env%iter_method = "P_Mix/SMGL"
     685            0 :          ELSE IF (scf_env%mixing_method > 1) THEN
     686            0 :             scf_env%iter_param = scf_env%mixing_store%alpha
     687            0 :             scf_env%iter_method = TRIM(scf_env%mixing_store%iter_method)//"/SMGL"
     688              :          END IF
     689        42588 :          CALL run_smeagol_emtrans(qs_env, last=.FALSE., iter=scf_env%iter_count, rho_ao_kp=scf_env%p_mix_new)
     690              :       END SELECT
     691        41564 :       IF (disable_diis) scf_control%eps_diis = saved_eps_diis
     692              : 
     693        41564 :       CALL get_qs_env(qs_env=qs_env, energy=energy)
     694        41564 :       energy%kTS = 0.0_dp
     695        41564 :       energy%efermi = 0.0_dp
     696        41564 :       mos => kpoints%kp_env(1)%kpoint_env%mos
     697        86092 :       DO ispin = 1, SIZE(mos)
     698        44528 :          energy%kTS = energy%kTS + mos(ispin)%kTS
     699        86092 :          energy%efermi = energy%efermi + mos(ispin)%mu
     700              :       END DO
     701        41564 :       energy%efermi = energy%efermi/REAL(SIZE(mos), KIND=dp)
     702              : 
     703        41564 :       CALL timestop(handle)
     704              : 
     705        41578 :    END SUBROUTINE qs_scf_new_mos_kp
     706              : 
     707              : ! **************************************************************************************************
     708              : !> \brief K-point OT driver for local complex spin/k-point channels
     709              : !> \param qs_env ...
     710              : !> \param scf_env ...
     711              : !> \param matrix_ks ...
     712              : !> \param matrix_s ...
     713              : !> \param added_mos_auto_grow ...
     714              : !> \param energy_only ...
     715              : ! **************************************************************************************************
     716         3136 :    SUBROUTINE qs_scf_loop_do_ot_kp(qs_env, scf_env, matrix_ks, matrix_s, added_mos_auto_grow, energy_only)
     717              : 
     718              :       TYPE(qs_environment_type), POINTER                 :: qs_env
     719              :       TYPE(qs_scf_env_type), POINTER                     :: scf_env
     720              :       TYPE(dbcsr_p_type), DIMENSION(:, :), POINTER       :: matrix_ks, matrix_s
     721              :       LOGICAL, INTENT(OUT)                               :: added_mos_auto_grow, energy_only
     722              : 
     723              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'qs_scf_loop_do_ot_kp'
     724              : 
     725              :       INTEGER :: energy_spin, energy_start, first_channel, handle, homo, ikpoint, ispin, &
     726              :          local_channel, local_kpoint, nao, nkpoint, nlocal_channels, nmo, nspin_energy, nspin_ot
     727              :       INTEGER, DIMENSION(2)                              :: kp_range
     728              :       LOGICAL :: local_orbitals, need_gradient, need_mo_coeff, ot_gradient_prepared, &
     729              :          physical_base_state, restart_history, restricted_roks, use_real_wfn
     730              :       REAL(KIND=dp)                                      :: trial_kTS
     731         3136 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:)           :: orbital_scaling_factor, roks_occupation, &
     732         3136 :                                                             trial_mu
     733         3136 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :, :)     :: trial_eigenvalues, trial_occupation
     734         6272 :       REAL(KIND=dp), DIMENSION(:), POINTER               :: eigenvalues, occupation_numbers, wkp
     735         3136 :       TYPE(cp_cfm_p_type), ALLOCATABLE                   :: local_c(:)
     736              :       TYPE(cp_cfm_type)                                  :: active_mo_coeff_cfm, hc_cfm, physical_h
     737         3136 :       TYPE(cp_fm_p_type), ALLOCATABLE                    :: local_s(:, :)
     738              :       TYPE(cp_fm_struct_type), POINTER                   :: active_mo_struct, chc_struct
     739              :       TYPE(cp_fm_type)                                   :: active_mo_coeff, active_mo_coeff_im, &
     740              :                                                             chc_im, chc_re, mo_coeff, mo_coeff_im
     741         3136 :       TYPE(cp_fm_type), ALLOCATABLE, TARGET              :: local_hc(:, :, :)
     742         3136 :       TYPE(cp_fm_type), DIMENSION(:), POINTER            :: fmwork
     743              :       TYPE(cp_fm_type), POINTER                          :: hc_im, hc_re, hc_roks_im, hc_roks_re
     744        15680 :       TYPE(cp_fm_type), TARGET                           :: hc_roks_work(2), hc_work(2)
     745         3136 :       TYPE(dbcsr_p_type), DIMENSION(:), POINTER          :: matrix_hc, matrix_hc_im, &
     746         3136 :                                                             matrix_hc_physical, &
     747         3136 :                                                             matrix_hc_physical_im
     748         6272 :       TYPE(dbcsr_p_type), DIMENSION(:, :), POINTER       :: density_target, rho_ao_kp
     749              :       TYPE(dbcsr_type), POINTER                          :: matrix_k_im, matrix_k_re, matrix_s_im, &
     750              :                                                             matrix_s_re
     751              :       TYPE(dft_control_type), POINTER                    :: dft_control
     752              :       TYPE(kpoint_env_type), POINTER                     :: kp
     753              :       TYPE(kpoint_type), POINTER                         :: kpoints
     754              :       TYPE(mp_para_env_type), POINTER                    :: para_env_inter_kp
     755              :       TYPE(neighbor_list_set_p_type), DIMENSION(:), &
     756         3136 :          POINTER                                         :: sab_nl
     757              :       TYPE(qs_energy_type), POINTER                      :: energy
     758         3136 :       TYPE(qs_ot_type), DIMENSION(:), POINTER            :: local_ot_env
     759              :       TYPE(qs_rho_type), POINTER                         :: rho
     760              :       TYPE(scf_control_type), POINTER                    :: scf_control
     761              : 
     762         3136 :       CALL timeset(routineN, handle)
     763         3136 :       added_mos_auto_grow = .FALSE.
     764         3136 :       ot_gradient_prepared = .FALSE.
     765              : 
     766         3136 :       NULLIFY (active_mo_struct, chc_struct, density_target, dft_control, energy, fmwork, kpoints, &
     767         3136 :                local_ot_env, matrix_hc, matrix_hc_im, matrix_k_im, matrix_k_re, matrix_s_im, &
     768         3136 :                matrix_hc_physical, matrix_hc_physical_im, matrix_s_re, &
     769         3136 :                occupation_numbers, para_env_inter_kp, rho, &
     770         3136 :                rho_ao_kp, sab_nl, scf_control, wkp)
     771              : 
     772         3136 :       CPASSERT(ASSOCIATED(scf_env%qs_ot_env))
     773              :       CALL get_qs_env(qs_env=qs_env, dft_control=dft_control, energy=energy, kpoints=kpoints, rho=rho, &
     774         3136 :                       scf_control=scf_control)
     775              :       CALL get_kpoint_info(kpoints, nkp=nkpoint, wkp=wkp, use_real_wfn=use_real_wfn, &
     776              :                            kp_range=kp_range, para_env_inter_kp=para_env_inter_kp, &
     777         3136 :                            sab_nl=sab_nl)
     778         3136 :       fmwork => scf_env%scf_work1
     779         3136 :       CALL qs_rho_get(rho, rho_ao_kp=rho_ao_kp)
     780         3136 :       CPASSERT(ASSOCIATED(sab_nl))
     781         3136 :       CPASSERT(ASSOCIATED(matrix_ks))
     782         3136 :       CPASSERT(ASSOCIATED(matrix_s))
     783              : 
     784         3136 :       IF (use_real_wfn) THEN
     785              :          CALL cp_abort(__LOCATION__, &
     786            0 :                        "K-point OT driver currently supports complex k-point wavefunctions only.")
     787              :       END IF
     788         3136 :       IF (scf_env%qs_ot_env(1)%settings%ot_algorithm /= "TOD" .AND. &
     789              :           scf_env%qs_ot_env(1)%settings%ot_algorithm /= "REF") THEN
     790              :          CALL cp_abort(__LOCATION__, &
     791            0 :                        "K-point OT driver supports OT%ALGORITHM STRICT or IRAC.")
     792              :       END IF
     793         3136 :       kp => kpoints%kp_env(1)%kpoint_env
     794         3136 :       restricted_roks = dft_control%restricted
     795         3136 :       nspin_ot = MERGE(1, SIZE(kp%mos), restricted_roks)
     796         3136 :       nspin_energy = MERGE(SIZE(kp%mos), nspin_ot, restricted_roks)
     797              :       CALL qs_ot_check_channel_context(scf_env%qs_ot_env, nspin_ot, &
     798              :                                        nkpoint=nkpoint, &
     799              :                                        restricted=ANY(scf_env%qs_ot_env(:)%restricted), &
     800              :                                        require_kpoint=.TRUE., &
     801              :                                        kp_range=kp_range, &
     802              :                                        wkp=wkp, &
     803              :                                        require_local_state=.TRUE., &
     804        12354 :                                        require_complex_state=.TRUE.)
     805              : 
     806         3136 :       first_channel = qs_ot_channel_index(1, kp_range(1), nspin_ot)
     807         3136 :       nlocal_channels = SIZE(kpoints%kp_env)*nspin_ot
     808         3136 :       local_ot_env => scf_env%qs_ot_env(first_channel:first_channel + nlocal_channels - 1)
     809         3136 :       local_ot_env(1)%etotal = energy%total
     810              :       physical_base_state = local_ot_env(1)%settings%do_ener .AND. &
     811              :                             .NOT. local_ot_env(1)%energy_only .AND. &
     812              :                             (local_ot_env(1)%line_search_count == 0 .OR. &
     813         3136 :                              local_ot_env(1)%line_search_might_be_done)
     814              : 
     815         3136 :       CALL ot_mini_prepare(local_ot_env, restart_history, para_env_inter_kp)
     816         3136 :       need_gradient = .NOT. local_ot_env(1)%energy_only .OR. restart_history
     817              : 
     818              :       ! All k-point groups read H(k) from the cache, including a single distributed group.
     819              :       ! Fixed-occupation energy-only trials need no H(k) and can reuse the stored S(k).
     820              :       ! Initialization already stored H(k); rebuild_ks_matrix invalidates it.
     821         1252 :       IF (need_gradient .OR. local_ot_env(1)%settings%do_ener) THEN
     822         2690 :          IF (.NOT. scf_env%ot_ks_valid) THEN
     823         1600 :             CALL kpoint_operator_store(scf_env%ot_operator_ctx, matrix_ks, matrix_s)
     824         1600 :             scf_env%ot_ks_valid = .TRUE.
     825              :          END IF
     826              :       END IF
     827              : 
     828        15442 :       ALLOCATE (matrix_hc(nlocal_channels))
     829        12306 :       ALLOCATE (matrix_hc_im(nlocal_channels))
     830         3136 :       IF (need_gradient .AND. local_ot_env(1)%settings%occupation_preconditioner) THEN
     831         1818 :          ALLOCATE (matrix_hc_physical(nlocal_channels))
     832         1818 :          ALLOCATE (matrix_hc_physical_im(nlocal_channels))
     833              :       END IF
     834         9170 :       DO local_channel = 1, nlocal_channels
     835         6034 :          NULLIFY (matrix_hc(local_channel)%matrix)
     836         6034 :          NULLIFY (matrix_hc_im(local_channel)%matrix)
     837         6034 :          ALLOCATE (matrix_hc(local_channel)%matrix)
     838         6034 :          ALLOCATE (matrix_hc_im(local_channel)%matrix)
     839         6034 :          CALL dbcsr_copy(matrix_hc(local_channel)%matrix, local_ot_env(local_channel)%matrix_x, name="matrix_hc")
     840              :          CALL dbcsr_copy(matrix_hc_im(local_channel)%matrix, local_ot_env(local_channel)%matrix_x_im, &
     841         6034 :                          name="matrix_hc_im")
     842         6034 :          CALL dbcsr_set(matrix_hc(local_channel)%matrix, 0.0_dp)
     843         6034 :          CALL dbcsr_set(matrix_hc_im(local_channel)%matrix, 0.0_dp)
     844         9170 :          IF (ASSOCIATED(matrix_hc_physical)) THEN
     845          794 :             NULLIFY (matrix_hc_physical(local_channel)%matrix)
     846          794 :             NULLIFY (matrix_hc_physical_im(local_channel)%matrix)
     847          794 :             ALLOCATE (matrix_hc_physical(local_channel)%matrix)
     848          794 :             ALLOCATE (matrix_hc_physical_im(local_channel)%matrix)
     849              :             CALL dbcsr_copy(matrix_hc_physical(local_channel)%matrix, &
     850          794 :                             local_ot_env(local_channel)%matrix_x, name="matrix_hc_physical")
     851              :             CALL dbcsr_copy(matrix_hc_physical_im(local_channel)%matrix, &
     852          794 :                             local_ot_env(local_channel)%matrix_x_im, name="matrix_hc_physical_im")
     853          794 :             CALL dbcsr_set(matrix_hc_physical(local_channel)%matrix, 0.0_dp)
     854          794 :             CALL dbcsr_set(matrix_hc_physical_im(local_channel)%matrix, 0.0_dp)
     855              :          END IF
     856              :       END DO
     857              : 
     858         3136 :       IF (kpoints%para_env_kp%num_pe == 1 .AND. (need_gradient .OR. local_ot_env(1)%settings%do_ener)) THEN
     859         1456 :          CALL qs_scf_ot_kp_hc(kpoints, local_ot_env(1)%settings%do_ener, restricted_roks, local_hc)
     860              :       END IF
     861         3136 :       need_mo_coeff = .NOT. ALLOCATED(local_hc) .OR. local_ot_env(1)%settings%do_ener .OR. ALLOCATED(kpoints%lowdin_v)
     862              : 
     863         8364 :       DO local_kpoint = 1, SIZE(kpoints%kp_env)
     864              :          ! Mermin SD trials still use the auxiliary-energy gradient in take_step.
     865         5228 :          IF (.NOT. need_gradient .AND. .NOT. local_ot_env(1)%settings%do_ener) CYCLE
     866         4428 :          kp => kpoints%kp_env(local_kpoint)%kpoint_env
     867         4428 :          ikpoint = kp%nkpoint
     868         4428 :          CPASSERT(ASSOCIATED(kp%ot_hmat))
     869         4428 :          CPASSERT(SIZE(kp%ot_hmat, 1) >= 2)
     870        12734 :          DO ispin = 1, nspin_ot
     871         5170 :             local_channel = qs_ot_channel_index(ispin, ikpoint, nspin_ot) - first_channel + 1
     872         5170 :             IF (.NOT. ALLOCATED(local_hc)) THEN
     873              :                CALL kpoint_operator_get_local( &
     874              :                   matrix_ks, kpoints, kp, MIN(ispin, SIZE(matrix_ks, 1)), &
     875              :                   kp%ot_hmat(1, MIN(ispin, SIZE(kp%ot_hmat, 2))), &
     876         2172 :                   kp%ot_hmat(2, MIN(ispin, SIZE(kp%ot_hmat, 2))), matrix_k_re, matrix_k_im)
     877              :             END IF
     878              : 
     879              :             CALL get_mo_set(kp%mos(ispin), homo=homo, nao=nao, nmo=nmo, &
     880         5170 :                             occupation_numbers=occupation_numbers)
     881         5170 :             IF (local_ot_env(local_channel)%settings%do_ener) homo = nmo
     882         5170 :             CPASSERT(homo >= 1 .AND. homo <= nmo)
     883         5170 :             IF (.NOT. local_ot_env(local_channel)%settings%do_ener) THEN
     884        19003 :                IF (MAXVAL(ABS(occupation_numbers(1:homo) - occupation_numbers(1))) > &
     885              :                    100.0_dp*EPSILON(1.0_dp)) THEN
     886              :                   CALL cp_abort(__LOCATION__, &
     887            0 :                                 "Fixed-occupation K-point OT requires uniform occupations within each channel.")
     888              :                END IF
     889         2951 :                IF (occupation_numbers(1) <= 100.0_dp*EPSILON(1.0_dp)) THEN
     890              :                   CALL cp_abort(__LOCATION__, &
     891            0 :                                 "Fixed-occupation K-point OT encountered an empty active orbital block.")
     892              :                END IF
     893         2951 :                IF (homo < nmo) THEN
     894          204 :                   IF (MAXVAL(ABS(occupation_numbers(homo + 1:nmo))) > 100.0_dp*EPSILON(1.0_dp)) THEN
     895              :                      CALL cp_abort(__LOCATION__, &
     896            0 :                                    "Fixed-occupation K-point OT cannot optimize occupied padded MO columns.")
     897              :                   END IF
     898              :                END IF
     899              :             END IF
     900         5170 :             IF (need_mo_coeff) THEN
     901              :                CALL cp_fm_struct_create(active_mo_struct, template_fmstruct=kp%mos(ispin)%cmo_coeff%matrix_struct, &
     902         3517 :                                         ncol_global=homo)
     903         3517 :                CALL cp_fm_create(active_mo_coeff, active_mo_struct)
     904         3517 :                CALL cp_fm_create(active_mo_coeff_im, active_mo_struct)
     905         3517 :                IF (cp_fm_struct_equivalent(active_mo_struct, kp%mos(ispin)%cmo_coeff%matrix_struct)) THEN
     906         3469 :                   CALL cp_cfm_to_fm(kp%mos(ispin)%cmo_coeff, active_mo_coeff, active_mo_coeff_im)
     907              :                ELSE
     908           48 :                   CALL cp_fm_create(mo_coeff, kp%mos(ispin)%cmo_coeff%matrix_struct)
     909           48 :                   CALL cp_fm_create(mo_coeff_im, kp%mos(ispin)%cmo_coeff%matrix_struct)
     910           48 :                   CALL cp_cfm_to_fm(kp%mos(ispin)%cmo_coeff, mo_coeff, mo_coeff_im)
     911           48 :                   CALL cp_fm_to_fm(mo_coeff, active_mo_coeff, homo)
     912           48 :                   CALL cp_fm_to_fm(mo_coeff_im, active_mo_coeff_im, homo)
     913           48 :                   CALL cp_fm_release(mo_coeff)
     914           48 :                   CALL cp_fm_release(mo_coeff_im)
     915              :                END IF
     916              :             END IF
     917         5170 :             IF (ALLOCATED(local_hc)) THEN
     918         2998 :                hc_re => local_hc(1, ispin, local_kpoint)
     919         2998 :                hc_im => local_hc(2, ispin, local_kpoint)
     920              :             ELSE
     921         2172 :                hc_re => hc_work(1)
     922         2172 :                hc_im => hc_work(2)
     923         2172 :                CALL cp_fm_create(hc_re, active_mo_struct)
     924         2172 :                CALL cp_fm_create(hc_im, active_mo_struct)
     925         2172 :                CALL cp_dbcsr_sm_fm_multiply(matrix_k_re, active_mo_coeff, hc_re, homo)
     926              :                CALL cp_dbcsr_sm_fm_multiply(matrix_k_im, active_mo_coeff_im, hc_re, homo, &
     927         2172 :                                             alpha=-1.0_dp, beta=1.0_dp)
     928         2172 :                CALL cp_dbcsr_sm_fm_multiply(matrix_k_re, active_mo_coeff_im, hc_im, homo)
     929              :                CALL cp_dbcsr_sm_fm_multiply(matrix_k_im, active_mo_coeff, hc_im, homo, &
     930         2172 :                                             alpha=1.0_dp, beta=1.0_dp)
     931              :             END IF
     932         5170 :             IF (ALLOCATED(kpoints%lowdin_v)) THEN
     933          927 :                IF (ANY(kpoints%lowdin_v(:, ispin) /= 0.0_dp)) THEN
     934          927 :                   CALL cp_cfm_create(active_mo_coeff_cfm, active_mo_struct)
     935          927 :                   CALL cp_cfm_create(hc_cfm, active_mo_struct)
     936          927 :                   CALL cp_cfm_to_cfm(kp%mos(ispin)%cmo_coeff, active_mo_coeff_cfm, homo)
     937          927 :                   CALL cp_fm_to_cfm(hc_re, hc_im, hc_cfm)
     938          927 :                   CALL lowdin_kp_apply_mo(kp, kpoints%lowdin_v(:, ispin), active_mo_coeff_cfm, hc_cfm)
     939          927 :                   CALL cp_cfm_to_fm(hc_cfm, hc_re, hc_im)
     940          927 :                   CALL cp_cfm_release(hc_cfm)
     941          927 :                   CALL cp_cfm_release(active_mo_coeff_cfm)
     942              :                END IF
     943          927 :                IF (physical_base_state .AND. local_ot_env(local_channel)%settings%occupation_preconditioner) THEN
     944              :                   ! H*C already includes +U; the physical secant history needs the same full H.
     945          114 :                   CALL cp_cfm_create(physical_h, kp%ot_hmat(1, ispin)%matrix_struct)
     946          114 :                   CALL cp_fm_to_cfm(kp%ot_hmat(1, ispin), kp%ot_hmat(2, ispin), physical_h)
     947          114 :                   CALL lowdin_kp_apply(kp, kpoints%lowdin_v(:, ispin), cmat=physical_h)
     948          114 :                   CALL cp_cfm_to_fm(physical_h, kp%ot_hmat(1, ispin), kp%ot_hmat(2, ispin))
     949          114 :                   CALL cp_cfm_release(physical_h)
     950              :                END IF
     951              :             END IF
     952              : 
     953         5170 :             IF (local_ot_env(local_channel)%settings%do_ener) THEN
     954              :                ! Reuse the projected-Hamiltonian workspace for both ROKS spin channels.
     955              :                CALL cp_fm_struct_create(chc_struct, template_fmstruct=active_mo_struct, &
     956         2219 :                                         nrow_global=homo, ncol_global=homo)
     957         2219 :                CALL cp_fm_create(chc_re, chc_struct)
     958         2219 :                CALL cp_fm_create(chc_im, chc_struct)
     959              :             END IF
     960         5170 :             IF (restricted_roks) THEN
     961              :                ! ROKS has one complex orbital variable but two spin densities. Form the exact
     962              :                ! shared-orbital derivative before handing it to the one-channel OT minimizer.
     963           95 :                IF (local_ot_env(local_channel)%settings%do_ener) THEN
     964              :                   CALL multiply_complex_fm_adjoint( &
     965              :                      active_mo_coeff, active_mo_coeff_im, hc_re, hc_im, &
     966           50 :                      chc_re, chc_im, 1.0_dp, 0.0_dp)
     967           50 :                   CALL copy_fm_to_dbcsr(chc_re, local_ot_env(local_channel)%rot_mat_chc)
     968              :                   CALL dbcsr_get_diag(local_ot_env(local_channel)%rot_mat_chc, &
     969           50 :                                       local_ot_env(local_channel)%ener_rayleigh(1:homo))
     970              :                   CALL local_ot_env(local_channel)%para_env%sum( &
     971         1018 :                      local_ot_env(local_channel)%ener_rayleigh(1:homo))
     972              :                END IF
     973           95 :                CALL cp_fm_column_scale(hc_re, occupation_numbers(1:homo))
     974           95 :                CALL cp_fm_column_scale(hc_im, occupation_numbers(1:homo))
     975           95 :                IF (.NOT. ALLOCATED(local_hc)) THEN
     976           50 :                   CALL dbcsr_release_p(matrix_k_re)
     977           50 :                   CALL dbcsr_release_p(matrix_k_im)
     978              :                   CALL kpoint_operator_get_local( &
     979              :                      matrix_ks, kpoints, kp, 2, kp%ot_hmat(1, 2), kp%ot_hmat(2, 2), &
     980           50 :                      matrix_k_re, matrix_k_im)
     981              :                END IF
     982           95 :                CALL get_mo_set(kp%mos(2), occupation_numbers=occupation_numbers, nmo=nmo)
     983          285 :                ALLOCATE (roks_occupation(homo))
     984           95 :                roks_occupation(:) = 0.0_dp
     985          669 :                roks_occupation(1:MIN(homo, nmo)) = occupation_numbers(1:MIN(homo, nmo))
     986              : 
     987           95 :                IF (ALLOCATED(local_hc)) THEN
     988           45 :                   hc_roks_re => local_hc(1, 2, local_kpoint)
     989           45 :                   hc_roks_im => local_hc(2, 2, local_kpoint)
     990              :                ELSE
     991           50 :                   hc_roks_re => hc_roks_work(1)
     992           50 :                   hc_roks_im => hc_roks_work(2)
     993           50 :                   CALL cp_fm_create(hc_roks_re, active_mo_struct)
     994           50 :                   CALL cp_fm_create(hc_roks_im, active_mo_struct)
     995           50 :                   CALL cp_dbcsr_sm_fm_multiply(matrix_k_re, active_mo_coeff, hc_roks_re, homo)
     996              :                   CALL cp_dbcsr_sm_fm_multiply(matrix_k_im, active_mo_coeff_im, hc_roks_re, homo, &
     997           50 :                                                alpha=-1.0_dp, beta=1.0_dp)
     998           50 :                   CALL cp_dbcsr_sm_fm_multiply(matrix_k_re, active_mo_coeff_im, hc_roks_im, homo)
     999              :                   CALL cp_dbcsr_sm_fm_multiply(matrix_k_im, active_mo_coeff, hc_roks_im, homo, &
    1000           50 :                                                alpha=1.0_dp, beta=1.0_dp)
    1001              :                END IF
    1002           95 :                IF (local_ot_env(local_channel)%settings%do_ener) THEN
    1003              :                   CALL multiply_complex_fm_adjoint( &
    1004              :                      active_mo_coeff, active_mo_coeff_im, hc_roks_re, hc_roks_im, &
    1005           50 :                      chc_re, chc_im, 1.0_dp, 0.0_dp)
    1006           50 :                   CALL copy_fm_to_dbcsr(chc_re, local_ot_env(local_channel)%rot_mat_chc)
    1007              :                   CALL dbcsr_get_diag(local_ot_env(local_channel)%rot_mat_chc, &
    1008           50 :                                       local_ot_env(local_channel)%ener_rayleigh(homo + 1:2*homo))
    1009              :                   CALL local_ot_env(local_channel)%para_env%sum( &
    1010         1018 :                      local_ot_env(local_channel)%ener_rayleigh(homo + 1:2*homo))
    1011              :                END IF
    1012           95 :                CALL cp_fm_column_scale(hc_roks_re, roks_occupation)
    1013           95 :                CALL cp_fm_column_scale(hc_roks_im, roks_occupation)
    1014           95 :                CALL cp_fm_scale_and_add(1.0_dp, hc_re, 1.0_dp, hc_roks_re)
    1015           95 :                CALL cp_fm_scale_and_add(1.0_dp, hc_im, 1.0_dp, hc_roks_im)
    1016           95 :                CALL cp_fm_release(hc_roks_re)
    1017           95 :                CALL cp_fm_release(hc_roks_im)
    1018          190 :                DEALLOCATE (roks_occupation)
    1019              :             END IF
    1020              : 
    1021         5170 :             IF (local_ot_env(local_channel)%settings%do_ener) THEN
    1022              :                CALL multiply_complex_fm_adjoint( &
    1023              :                   active_mo_coeff, active_mo_coeff_im, hc_re, hc_im, &
    1024         2219 :                   chc_re, chc_im, 1.0_dp, 0.0_dp)
    1025         2219 :                CALL copy_fm_to_dbcsr(chc_re, local_ot_env(local_channel)%rot_mat_chc)
    1026         2219 :                CPASSERT(ASSOCIATED(local_ot_env(local_channel)%rot_mat_chc_im))
    1027         2219 :                CALL copy_fm_to_dbcsr(chc_im, local_ot_env(local_channel)%rot_mat_chc_im)
    1028         2219 :                IF (.NOT. restricted_roks) THEN
    1029              :                   CALL dbcsr_get_diag(local_ot_env(local_channel)%rot_mat_chc, &
    1030         2169 :                                       local_ot_env(local_channel)%ener_rayleigh)
    1031         2169 :                   CPASSERT(ASSOCIATED(local_ot_env(local_channel)%para_env))
    1032              :                   CALL local_ot_env(local_channel)%para_env%sum( &
    1033        31269 :                      local_ot_env(local_channel)%ener_rayleigh)
    1034              :                END IF
    1035         2219 :                CALL cp_fm_release(chc_im)
    1036         2219 :                CALL cp_fm_release(chc_re)
    1037         2219 :                CALL cp_fm_struct_release(chc_struct)
    1038              :             END IF
    1039              : 
    1040         5170 :             IF (need_gradient) THEN
    1041         3985 :                CALL copy_fm_to_dbcsr(hc_re, matrix_hc(local_channel)%matrix)
    1042         3985 :                CALL copy_fm_to_dbcsr(hc_im, matrix_hc_im(local_channel)%matrix)
    1043              :             END IF
    1044              : 
    1045         5170 :             IF (need_mo_coeff) THEN
    1046         3517 :                CALL cp_fm_release(active_mo_coeff)
    1047         3517 :                CALL cp_fm_release(active_mo_coeff_im)
    1048         3517 :                CALL cp_fm_struct_release(active_mo_struct)
    1049              :             END IF
    1050         5170 :             CALL cp_fm_release(hc_re)
    1051         5170 :             CALL cp_fm_release(hc_im)
    1052        15568 :             IF (.NOT. ALLOCATED(local_hc)) THEN
    1053         2172 :                CALL dbcsr_release_p(matrix_k_re)
    1054         2172 :                CALL dbcsr_release_p(matrix_k_im)
    1055              :             END IF
    1056              :          END DO
    1057              :       END DO
    1058              :       ! Each result was released by its consuming channel above.
    1059         3136 :       IF (ALLOCATED(local_hc)) DEALLOCATE (local_hc)
    1060              : 
    1061         3136 :       IF (local_ot_env(1)%settings%do_ener) THEN
    1062              :          CALL qs_scf_loop_collect_ot_kp_trial_smearing( &
    1063              :             kpoints, local_ot_env, first_channel, nspin_ot, nspin_energy, restricted_roks, &
    1064              :             kp_range, wkp, para_env_inter_kp, scf_control%smear, &
    1065         1470 :             trial_eigenvalues, trial_occupation, trial_mu, trial_kTS)
    1066              :       END IF
    1067              : 
    1068         8364 :       DO local_kpoint = 1, SIZE(kpoints%kp_env)
    1069         5228 :          IF (.NOT. need_gradient) CYCLE
    1070         3359 :          kp => kpoints%kp_env(local_kpoint)%kpoint_env
    1071         3359 :          ikpoint = kp%nkpoint
    1072        10480 :          DO ispin = 1, nspin_ot
    1073         3985 :             local_channel = qs_ot_channel_index(ispin, ikpoint, nspin_ot) - first_channel + 1
    1074              :             CALL get_mo_set(kp%mos(ispin), homo=homo, nmo=nmo, &
    1075         3985 :                             occupation_numbers=occupation_numbers)
    1076         3985 :             IF (local_ot_env(local_channel)%settings%do_ener) homo = nmo
    1077         3985 :             IF (physical_base_state .AND. &
    1078              :                 local_ot_env(local_channel)%settings%occupation_preconditioner) THEN
    1079          794 :                CALL cp_fm_create(mo_coeff, kp%mos(ispin)%cmo_coeff%matrix_struct)
    1080          794 :                CALL cp_fm_create(mo_coeff_im, kp%mos(ispin)%cmo_coeff%matrix_struct)
    1081          794 :                CALL cp_cfm_to_fm(kp%mos(ispin)%cmo_coeff, mo_coeff, mo_coeff_im)
    1082          794 :                IF (restricted_roks) THEN
    1083           22 :                   IF (.NOT. (nspin_energy <= SIZE(local_ot_env(local_channel)%mermin_physical))) THEN
    1084            0 :                      CALL cp_abort(__LOCATION__, "Missing Mermin physical spin state")
    1085              :                   END IF
    1086           66 :                   DO energy_spin = 1, nspin_energy
    1087              :                      CALL qs_scf_kp_roll_physical_secant( &
    1088              :                         local_ot_env(local_channel)%mermin_physical(energy_spin), &
    1089              :                         mo_coeff, mo_coeff_im, kp%ot_hmat(1, energy_spin), &
    1090              :                         kp%ot_hmat(2, energy_spin), &
    1091           66 :                         trial_occupation(:, ikpoint, energy_spin))
    1092              :                   END DO
    1093              :                ELSE
    1094              :                   CALL qs_scf_kp_roll_physical_secant( &
    1095              :                      local_ot_env(local_channel)%mermin_physical(1), mo_coeff, mo_coeff_im, &
    1096              :                      kp%ot_hmat(1, MIN(ispin, SIZE(kp%ot_hmat, 2))), &
    1097              :                      kp%ot_hmat(2, MIN(ispin, SIZE(kp%ot_hmat, 2))), &
    1098          772 :                      trial_occupation(:, ikpoint, ispin))
    1099              :                END IF
    1100          794 :                CALL cp_fm_release(mo_coeff)
    1101          794 :                CALL cp_fm_release(mo_coeff_im)
    1102              :             END IF
    1103        11955 :             ALLOCATE (orbital_scaling_factor(homo))
    1104         3985 :             IF (local_ot_env(local_channel)%settings%occupation_preconditioner) THEN
    1105              :                CALL dbcsr_copy(matrix_hc_physical(local_channel)%matrix, &
    1106          794 :                                matrix_hc(local_channel)%matrix)
    1107              :                CALL dbcsr_copy(matrix_hc_physical_im(local_channel)%matrix, &
    1108          794 :                                matrix_hc_im(local_channel)%matrix)
    1109          794 :                IF (restricted_roks) THEN
    1110          226 :                   orbital_scaling_factor(:) = 2.0_dp*wkp(ikpoint)
    1111              :                ELSE
    1112              :                   orbital_scaling_factor(:) = 2.0_dp*wkp(ikpoint)* &
    1113         5592 :                                               trial_occupation(1:homo, ikpoint, ispin)
    1114              :                END IF
    1115              :                CALL dbcsr_scale_by_vector(matrix_hc_physical(local_channel)%matrix, &
    1116          794 :                                           alpha=orbital_scaling_factor, side='right')
    1117              :                CALL dbcsr_scale_by_vector(matrix_hc_physical_im(local_channel)%matrix, &
    1118          794 :                                           alpha=orbital_scaling_factor, side='right')
    1119              :             END IF
    1120         3985 :             IF (local_ot_env(local_channel)%settings%occupation_preconditioner) THEN
    1121         5818 :                orbital_scaling_factor(:) = 2.0_dp*wkp(ikpoint)
    1122         3191 :             ELSE IF (restricted_roks) THEN
    1123          135 :                orbital_scaling_factor(:) = 2.0_dp*wkp(ikpoint)
    1124         3146 :             ELSE IF (local_ot_env(local_channel)%settings%do_ener) THEN
    1125              :                orbital_scaling_factor(:) = 2.0_dp*wkp(ikpoint)* &
    1126         2880 :                                            trial_occupation(1:homo, ikpoint, ispin)
    1127              :             ELSE
    1128        18868 :                orbital_scaling_factor(:) = 2.0_dp*wkp(ikpoint)*occupation_numbers(1:homo)
    1129              :             END IF
    1130              :             CALL dbcsr_scale_by_vector(matrix_hc(local_channel)%matrix, &
    1131         3985 :                                        alpha=orbital_scaling_factor, side='right')
    1132              :             CALL dbcsr_scale_by_vector(matrix_hc_im(local_channel)%matrix, &
    1133         3985 :                                        alpha=orbital_scaling_factor, side='right')
    1134        13198 :             DEALLOCATE (orbital_scaling_factor)
    1135              :          END DO
    1136              :       END DO
    1137              : 
    1138         3136 :       IF (local_ot_env(1)%settings%do_ener) THEN
    1139         1470 :          local_ot_env(1)%etotal = energy%total - energy%kTS + trial_kTS
    1140              :          CALL qs_scf_loop_prepare_ot_kp_energy_gradient( &
    1141              :             kpoints, local_ot_env, first_channel, nspin_ot, nspin_energy, restricted_roks, &
    1142              :             wkp, para_env_inter_kp, scf_control%smear, &
    1143         1470 :             trial_eigenvalues, trial_occupation, trial_mu)
    1144         1470 :          IF (need_gradient) THEN
    1145          664 :             IF (local_ot_env(1)%settings%occupation_preconditioner) THEN
    1146              :                CALL ot_mini_prepare_gradient( &
    1147              :                   local_ot_env, matrix_hc, matrix_hc_im=matrix_hc_im, &
    1148              :                   matrix_hc_physical=matrix_hc_physical, &
    1149              :                   matrix_hc_physical_im=matrix_hc_physical_im, &
    1150          512 :                   para_env_inter_kp=para_env_inter_kp, restart_history=restart_history)
    1151              :             ELSE
    1152              :                CALL ot_mini_prepare_gradient( &
    1153              :                   local_ot_env, matrix_hc, matrix_hc_im=matrix_hc_im, &
    1154          152 :                   para_env_inter_kp=para_env_inter_kp, restart_history=restart_history)
    1155              :             END IF
    1156          664 :             ot_gradient_prepared = .TRUE.
    1157          664 :             restart_history = .FALSE.
    1158              :          END IF
    1159              :          ! A coupled response direction is consumed only when the minimizer starts a new search.
    1160              :          ! Other line-search points do not need the dense finite-rotation Hessian.
    1161         1470 :          IF (physical_base_state) THEN
    1162              :             CALL qs_scf_loop_prepare_ot_kp_rotation_response( &
    1163              :                qs_env, kpoints, local_ot_env, first_channel, nspin_ot, restricted_roks, &
    1164              :                wkp, para_env_inter_kp, sab_nl, fmwork, rho_ao_kp, &
    1165          664 :                scf_control%smear, trial_eigenvalues, trial_occupation, trial_mu)
    1166              :          END IF
    1167              :          IF (physical_base_state .AND. &
    1168          664 :              local_ot_env(1)%settings%occupation_preconditioner .AND. &
    1169              :              (local_ot_env(1)%settings%ot_method == "CG" .OR. &
    1170              :               local_ot_env(1)%settings%ot_method == "LBFG")) THEN
    1171         1010 :             DO local_channel = 1, nlocal_channels
    1172         1270 :                CALL qs_scf_kp_store_mermin_gradient(local_ot_env(local_channel))
    1173              :             END DO
    1174              :          END IF
    1175              :       END IF
    1176         3136 :       IF (ASSOCIATED(matrix_hc_physical)) THEN
    1177              :          CALL ot_mini(local_ot_env, matrix_hc, matrix_hc_im=matrix_hc_im, &
    1178              :                       matrix_hc_physical=matrix_hc_physical, &
    1179              :                       matrix_hc_physical_im=matrix_hc_physical_im, &
    1180              :                       para_env_inter_kp=para_env_inter_kp, &
    1181          512 :                       gradient_prepared=ot_gradient_prepared, restart_history=restart_history)
    1182              :       ELSE
    1183              :          CALL ot_mini(local_ot_env, matrix_hc, matrix_hc_im=matrix_hc_im, &
    1184              :                       para_env_inter_kp=para_env_inter_kp, &
    1185         2624 :                       gradient_prepared=ot_gradient_prepared, restart_history=restart_history)
    1186              :       END IF
    1187         3136 :       scf_env%iter_delta = local_ot_env(1)%delta
    1188         3136 :       energy_only = local_ot_env(1)%energy_only
    1189              : 
    1190              :       ! Borrow cached overlaps and physical MO storage; no matrix ownership changes in workers.
    1191         3136 :       local_orbitals = kpoints%para_env_kp%num_pe == 1
    1192         3136 :       IF (local_orbitals) THEN
    1193        20304 :          ALLOCATE (local_s(2, nlocal_channels), local_c(nlocal_channels))
    1194         4518 :          DO local_kpoint = 1, SIZE(kpoints%kp_env)
    1195         2850 :             kp => kpoints%kp_env(local_kpoint)%kpoint_env
    1196         2850 :             CPASSERT(ASSOCIATED(kp%ot_smat))
    1197         2850 :             CPASSERT(SIZE(kp%ot_smat) >= 2)
    1198         7926 :             DO ispin = 1, nspin_ot
    1199         3408 :                local_channel = qs_ot_channel_index(ispin, kp%nkpoint, nspin_ot) - first_channel + 1
    1200         3408 :                local_s(1, local_channel)%matrix => kp%ot_smat(1)
    1201         3408 :                local_s(2, local_channel)%matrix => kp%ot_smat(2)
    1202         6258 :                local_c(local_channel)%matrix => kp%mos(ispin)%cmo_coeff
    1203              :             END DO
    1204              :          END DO
    1205         1668 :          CALL qs_ot_get_orbitals_local_batch(local_ot_env, local_s, local_c)
    1206              :       END IF
    1207              : 
    1208         8364 :       DO local_kpoint = 1, SIZE(kpoints%kp_env)
    1209         5228 :          kp => kpoints%kp_env(local_kpoint)%kpoint_env
    1210         5228 :          ikpoint = kp%nkpoint
    1211         5228 :          CPASSERT(ASSOCIATED(kp%ot_smat))
    1212         5228 :          CPASSERT(SIZE(kp%ot_smat) >= 2)
    1213         5228 :          IF (.NOT. local_orbitals) THEN
    1214              :             CALL kpoint_operator_get_local(matrix_s, kpoints, kp, 1, &
    1215              :                                            kp%ot_smat(1), kp%ot_smat(2), &
    1216         2378 :                                            matrix_s_re, matrix_s_im)
    1217              :          END IF
    1218        11262 :          DO ispin = 1, nspin_ot
    1219         6034 :             local_channel = qs_ot_channel_index(ispin, ikpoint, nspin_ot) - first_channel + 1
    1220              :             CALL get_mo_set(kp%mos(ispin), homo=homo, eigenvalues=eigenvalues, &
    1221         6034 :                             nao=nao, nmo=nmo)
    1222         6034 :             IF (local_ot_env(local_channel)%settings%do_ener) homo = nmo
    1223         6034 :             IF (.NOT. local_orbitals) THEN
    1224         1098 :                SELECT CASE (local_ot_env(local_channel)%settings%ot_algorithm)
    1225              :                CASE ("TOD")
    1226              :                   CALL qs_ot_get_orbitals_complex(matrix_hc(local_channel)%matrix, &
    1227              :                                                   matrix_hc_im(local_channel)%matrix, &
    1228              :                                                   matrix_s_re, matrix_s_im, &
    1229         1098 :                                                   local_ot_env(local_channel))
    1230              :                CASE ("REF")
    1231              :                   CALL qs_ot_get_orbitals_ref_complex(matrix_hc(local_channel)%matrix, &
    1232              :                                                       matrix_hc_im(local_channel)%matrix, &
    1233              :                                                       matrix_s_re, matrix_s_im, &
    1234         1528 :                                                       local_ot_env(local_channel), local_ot_env(1))
    1235              :                CASE DEFAULT
    1236         2626 :                   CPABORT("K-point OT orbital update requires ALGORITHM STRICT or IRAC")
    1237              :                END SELECT
    1238              :                CALL cp_fm_struct_create(active_mo_struct, template_fmstruct=kp%mos(ispin)%cmo_coeff%matrix_struct, &
    1239         2626 :                                         ncol_global=homo)
    1240         2626 :                CALL cp_fm_create(active_mo_coeff, active_mo_struct)
    1241         2626 :                CALL cp_fm_create(active_mo_coeff_im, active_mo_struct)
    1242         2626 :                CALL copy_dbcsr_to_fm(matrix_hc(local_channel)%matrix, active_mo_coeff)
    1243         2626 :                CALL copy_dbcsr_to_fm(matrix_hc_im(local_channel)%matrix, active_mo_coeff_im)
    1244         2626 :                IF (cp_fm_struct_equivalent(active_mo_struct, kp%mos(ispin)%cmo_coeff%matrix_struct)) THEN
    1245         2562 :                   CALL cp_fm_to_cfm(active_mo_coeff, active_mo_coeff_im, kp%mos(ispin)%cmo_coeff)
    1246              :                ELSE
    1247              :                   ! Preserve padded MO columns and handle different active/full matrix layouts.
    1248           64 :                   CALL cp_fm_create(mo_coeff, kp%mos(ispin)%cmo_coeff%matrix_struct)
    1249           64 :                   CALL cp_fm_create(mo_coeff_im, kp%mos(ispin)%cmo_coeff%matrix_struct)
    1250           64 :                   CALL cp_cfm_to_fm(kp%mos(ispin)%cmo_coeff, mo_coeff, mo_coeff_im)
    1251           64 :                   CALL cp_fm_to_fm(active_mo_coeff, mo_coeff, homo)
    1252           64 :                   CALL cp_fm_to_fm(active_mo_coeff_im, mo_coeff_im, homo)
    1253           64 :                   CALL cp_fm_to_cfm(mo_coeff, mo_coeff_im, kp%mos(ispin)%cmo_coeff)
    1254           64 :                   CALL cp_fm_release(mo_coeff)
    1255           64 :                   CALL cp_fm_release(mo_coeff_im)
    1256              :                END IF
    1257         2626 :                CALL cp_fm_release(active_mo_coeff)
    1258         2626 :                CALL cp_fm_release(active_mo_coeff_im)
    1259         2626 :                CALL cp_fm_struct_release(active_mo_struct)
    1260              :             END IF
    1261        17296 :             IF (local_ot_env(local_channel)%settings%do_ener .AND. .NOT. restricted_roks) THEN
    1262        16719 :                eigenvalues(1:homo) = local_ot_env(local_channel)%ener_x(:)
    1263              :             END IF
    1264              :          END DO
    1265         5228 :          IF (restricted_roks) THEN
    1266          137 :             CPASSERT(SIZE(kp%mos) == 2)
    1267          137 :             CALL cp_cfm_to_cfm(kp%mos(1)%cmo_coeff, kp%mos(2)%cmo_coeff)
    1268          137 :             IF (local_ot_env(local_channel)%settings%do_ener) THEN
    1269          150 :                DO energy_spin = 1, nspin_energy
    1270          100 :                   energy_start = (energy_spin - 1)*homo + 1
    1271              :                   kp%mos(energy_spin)%eigenvalues(1:homo) = &
    1272         2086 :                      local_ot_env(local_channel)%ener_x(energy_start:energy_start + homo - 1)
    1273              :                END DO
    1274              :             END IF
    1275              :          END IF
    1276         8364 :          IF (.NOT. local_orbitals) THEN
    1277         2378 :             CALL dbcsr_release_p(matrix_s_re)
    1278         2378 :             CALL dbcsr_release_p(matrix_s_im)
    1279              :          END IF
    1280              :       END DO
    1281              : 
    1282         3136 :       IF (local_ot_env(1)%settings%do_ener) THEN
    1283              :          CALL kpoint_set_mo_occupation(kpoints, scf_control%smear, &
    1284              :                                        added_mos_auto=scf_control%added_mos_auto, &
    1285              :                                        added_mos_auto_grow=added_mos_auto_grow, &
    1286         1470 :                                        separate_spin_occupations=restricted_roks)
    1287              :       END IF
    1288              : 
    1289         3136 :       IF (ALLOCATED(trial_eigenvalues)) DEALLOCATE (trial_eigenvalues)
    1290         3136 :       IF (ALLOCATED(trial_occupation)) DEALLOCATE (trial_occupation)
    1291         3136 :       IF (ALLOCATED(trial_mu)) DEALLOCATE (trial_mu)
    1292              : 
    1293         3136 :       IF (.NOT. added_mos_auto_grow) THEN
    1294         3130 :          fmwork => scf_env%scf_work1
    1295         3130 :          IF (ASSOCIATED(scf_env%p_mix_new)) THEN
    1296            0 :             density_target => scf_env%p_mix_new
    1297              :          ELSE
    1298         3130 :             CALL qs_rho_get(rho, rho_ao_kp=rho_ao_kp)
    1299         3130 :             density_target => rho_ao_kp
    1300              :          END IF
    1301         3130 :          CALL kpoint_density_matrices(kpoints)
    1302              :          CALL kpoint_density_transform(kpoints, density_target, .FALSE., &
    1303              :                                        matrix_s(1, 1)%matrix, sab_nl, fmwork, &
    1304         3130 :                                        overlap_rs=matrix_s)
    1305              :       END IF
    1306         3136 :       scf_env%iter_method = scf_env%qs_ot_env(first_channel)%OT_METHOD_FULL
    1307         3136 :       scf_env%iter_param = scf_env%qs_ot_env(first_channel)%ds_min
    1308         3136 :       qs_env%broyden_adaptive_sigma = scf_env%qs_ot_env(first_channel)%broyden_adaptive_sigma
    1309              : 
    1310         9170 :       DO local_channel = 1, nlocal_channels
    1311         6034 :          CALL dbcsr_release(matrix_hc(local_channel)%matrix)
    1312         6034 :          CALL dbcsr_release(matrix_hc_im(local_channel)%matrix)
    1313         6034 :          DEALLOCATE (matrix_hc(local_channel)%matrix)
    1314         6034 :          DEALLOCATE (matrix_hc_im(local_channel)%matrix)
    1315         9170 :          IF (ASSOCIATED(matrix_hc_physical)) THEN
    1316          794 :             CALL dbcsr_release(matrix_hc_physical(local_channel)%matrix)
    1317          794 :             CALL dbcsr_release(matrix_hc_physical_im(local_channel)%matrix)
    1318          794 :             DEALLOCATE (matrix_hc_physical(local_channel)%matrix)
    1319          794 :             DEALLOCATE (matrix_hc_physical_im(local_channel)%matrix)
    1320              :          END IF
    1321              :       END DO
    1322         3136 :       DEALLOCATE (matrix_hc, matrix_hc_im)
    1323         3136 :       IF (ASSOCIATED(matrix_hc_physical)) THEN
    1324          512 :          DEALLOCATE (matrix_hc_physical, matrix_hc_physical_im)
    1325              :       END IF
    1326              : 
    1327         3136 :       CALL timestop(handle)
    1328              : 
    1329        12544 :    END SUBROUTINE qs_scf_loop_do_ot_kp
    1330              : 
    1331              : ! **************************************************************************************************
    1332              : !> \brief Form H(k)C(k) for one-rank OT groups, without DBCSR conversions or communication.
    1333              : !> \param kpoints prepared Hamiltonians and current complex orbitals
    1334              : !> \param do_ener include all orbitals for variable occupations
    1335              : !> \param restricted_roks use the shared spin-up orbitals for both ROKS Hamiltonians
    1336              : !> \param hc real/imaginary products, released by the caller after each channel is consumed
    1337              : ! **************************************************************************************************
    1338         1456 :    SUBROUTINE qs_scf_ot_kp_hc(kpoints, do_ener, restricted_roks, hc)
    1339              :       TYPE(kpoint_type), POINTER                         :: kpoints
    1340              :       LOGICAL, INTENT(IN)                                :: do_ener, restricted_roks
    1341              :       TYPE(cp_fm_type), ALLOCATABLE, INTENT(OUT), TARGET :: hc(:, :, :)
    1342              : 
    1343              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'qs_scf_ot_kp_hc'
    1344              : 
    1345              :       INTEGER                                            :: handle, homo, ikp, ispin, kplocal, &
    1346              :                                                             max_nao, max_nmo, nao, nmo, nspin, &
    1347              :                                                             nworkers, spin, thread
    1348         1456 :       REAL(KIND=dp), ALLOCATABLE                         :: coeff(:, :, :, :)
    1349              :       TYPE(cp_fm_struct_type), POINTER                   :: active_mo_struct
    1350              :       TYPE(cp_fm_type), POINTER                          :: h_im, h_re, hc_im, hc_re
    1351              :       TYPE(kpoint_env_type), POINTER                     :: kp
    1352         1456 :       TYPE(local_gemm_ctxt_type), ALLOCATABLE            :: gemm_ctx(:)
    1353              : 
    1354         1456 :       CALL timeset(routineN, handle)
    1355         1456 :       CPASSERT(kpoints%para_env_kp%num_pe == 1)
    1356         1456 :       kplocal = SIZE(kpoints%kp_env)
    1357         1456 :       nspin = SIZE(kpoints%kp_env(1)%kpoint_env%mos)
    1358         1456 :       nworkers = 1
    1359         1456 : !$    nworkers = MIN(omp_get_max_threads(), kplocal*nspin)
    1360        21809 :       ALLOCATE (hc(2, nspin, kplocal), gemm_ctx(nworkers))
    1361         1456 :       max_nao = 0
    1362         1456 :       max_nmo = 0
    1363              :       ! Matrix structures retain communication contexts; create them before entering OpenMP.
    1364         3944 :       DO ikp = 1, kplocal
    1365         2488 :          kp => kpoints%kp_env(ikp)%kpoint_env
    1366         6987 :          DO ispin = 1, nspin
    1367         3043 :             spin = MERGE(1, ispin, restricted_roks)
    1368         3043 :             CALL get_mo_set(kp%mos(spin), homo=homo, nao=nao, nmo=nmo)
    1369         3043 :             IF (do_ener) homo = nmo
    1370         3043 :             CPASSERT(homo >= 1 .AND. homo <= nmo)
    1371              :             CALL cp_fm_struct_create(active_mo_struct, template_fmstruct=kp%mos(spin)%cmo_coeff%matrix_struct, &
    1372         3043 :                                      ncol_global=homo)
    1373         3043 :             CALL cp_fm_create(hc(1, ispin, ikp), active_mo_struct, set_zero=.TRUE.)
    1374         3043 :             CALL cp_fm_create(hc(2, ispin, ikp), active_mo_struct, set_zero=.TRUE.)
    1375         3043 :             CALL cp_fm_struct_release(active_mo_struct)
    1376         3043 :             max_nao = MAX(max_nao, nao)
    1377         8574 :             max_nmo = MAX(max_nmo, homo)
    1378              :          END DO
    1379              :       END DO
    1380         8736 :       ALLOCATE (coeff(max_nao, max_nmo, 2, nworkers))
    1381         2912 :       DO thread = 1, nworkers
    1382         2912 :          CALL gemm_ctx(thread)%create(LOCAL_GEMM_PU_GPU, timing=.FALSE.)
    1383              :       END DO
    1384              : 
    1385              : !$OMP PARALLEL DO COLLAPSE(2) DEFAULT(NONE) SCHEDULE(DYNAMIC, 1) NUM_THREADS(nworkers) IF(nworkers > 1) &
    1386              : !$OMP SHARED(kpoints,hc,coeff,gemm_ctx,kplocal,nspin,nworkers,max_nao,restricted_roks) &
    1387         1456 : !$OMP PRIVATE(ikp,ispin,spin,thread,kp,nao,homo,h_re,h_im,hc_re,hc_im)
    1388              :       DO ikp = 1, kplocal
    1389              :          DO ispin = 1, nspin
    1390              :             thread = 1
    1391              : !$          thread = omp_get_thread_num() + 1
    1392              :             kp => kpoints%kp_env(ikp)%kpoint_env
    1393              :             spin = MERGE(1, ispin, restricted_roks)
    1394              :             hc_re => hc(1, ispin, ikp)
    1395              :             hc_im => hc(2, ispin, ikp)
    1396              :             nao = hc_re%matrix_struct%nrow_global
    1397              :             homo = hc_re%matrix_struct%ncol_global
    1398              :             h_re => kp%ot_hmat(1, MIN(ispin, SIZE(kp%ot_hmat, 2)))
    1399              :             h_im => kp%ot_hmat(2, MIN(ispin, SIZE(kp%ot_hmat, 2)))
    1400              :             coeff(1:nao, 1:homo, 1, thread) = REAL(kp%mos(spin)%cmo_coeff%local_data(1:nao, 1:homo), KIND=dp)
    1401              :             coeff(1:nao, 1:homo, 2, thread) = AIMAG(kp%mos(spin)%cmo_coeff%local_data(1:nao, 1:homo))
    1402              :             ! Keep the four real products and their accumulation order.
    1403              :             CALL gemm_ctx(thread)%gemm("N", "N", nao, homo, nao, 1.0_dp, &
    1404              :                                        h_re%local_data, SIZE(h_re%local_data, 1), &
    1405              :                                        coeff(:, :, 1, thread), max_nao, 0.0_dp, &
    1406              :                                        hc_re%local_data, SIZE(hc_re%local_data, 1))
    1407              :             CALL gemm_ctx(thread)%gemm("N", "N", nao, homo, nao, -1.0_dp, &
    1408              :                                        h_im%local_data, SIZE(h_im%local_data, 1), &
    1409              :                                        coeff(:, :, 2, thread), max_nao, 1.0_dp, &
    1410              :                                        hc_re%local_data, SIZE(hc_re%local_data, 1))
    1411              :             CALL gemm_ctx(thread)%gemm("N", "N", nao, homo, nao, 1.0_dp, &
    1412              :                                        h_re%local_data, SIZE(h_re%local_data, 1), &
    1413              :                                        coeff(:, :, 2, thread), max_nao, 0.0_dp, &
    1414              :                                        hc_im%local_data, SIZE(hc_im%local_data, 1))
    1415              :             CALL gemm_ctx(thread)%gemm("N", "N", nao, homo, nao, 1.0_dp, &
    1416              :                                        h_im%local_data, SIZE(h_im%local_data, 1), &
    1417              :                                        coeff(:, :, 1, thread), max_nao, 1.0_dp, &
    1418              :                                        hc_im%local_data, SIZE(hc_im%local_data, 1))
    1419              :          END DO
    1420              :       END DO
    1421              : !$OMP END PARALLEL DO
    1422         2912 :       DO thread = 1, nworkers
    1423         2912 :          CALL gemm_ctx(thread)%destroy()
    1424              :       END DO
    1425         1456 :       CALL timestop(handle)
    1426         2912 :    END SUBROUTINE qs_scf_ot_kp_hc
    1427              : 
    1428              : ! **************************************************************************************************
    1429              : !> \brief roll one accepted physical K-point Mermin endpoint into a bounded response history
    1430              : !> \param history physical history for one spin density
    1431              : !> \param c_re current real orbital coefficients
    1432              : !> \param c_im current imaginary orbital coefficients
    1433              : !> \param h_re current real self-consistent Hamiltonian
    1434              : !> \param h_im current imaginary self-consistent Hamiltonian
    1435              : !> \param occupation current fixed-N occupations
    1436              : ! **************************************************************************************************
    1437          816 :    SUBROUTINE qs_scf_kp_roll_physical_secant(history, c_re, c_im, h_re, h_im, occupation)
    1438              :       TYPE(qs_ot_physical_secant_type), INTENT(INOUT)    :: history
    1439              :       TYPE(cp_fm_type), INTENT(IN), TARGET               :: c_re, c_im, h_re, h_im
    1440              :       REAL(KIND=dp), DIMENSION(:), INTENT(IN)            :: occupation
    1441              : 
    1442              :       INTEGER                                            :: nmo
    1443              :       LOGICAL                                            :: previous_valid
    1444              : 
    1445          816 :       nmo = SIZE(occupation)
    1446          816 :       CPASSERT(nmo > 0)
    1447              :       previous_valid = history%reference_valid .AND. &
    1448              :                        ASSOCIATED(history%c0) .AND. ASSOCIATED(history%c0_im) .AND. &
    1449              :                        ASSOCIATED(history%h0) .AND. ASSOCIATED(history%h0_im) .AND. &
    1450          816 :                        ALLOCATED(history%occupation0)
    1451          703 :       IF (previous_valid) previous_valid = SIZE(history%occupation0) == nmo
    1452          113 :       history%secant_valid = .FALSE.
    1453          703 :       IF (previous_valid) THEN
    1454          703 :          CALL store_physical_fm_matrix(history%c0, history%c_previous, "mermin_previous_c")
    1455          703 :          CALL store_physical_fm_matrix(history%c0_im, history%c_previous_im, "mermin_previous_c_im")
    1456          703 :          CALL store_physical_fm_matrix(h_re, history%y_previous, "mermin_previous_y")
    1457          703 :          CALL store_physical_fm_matrix(h_im, history%y_previous_im, "mermin_previous_y_im")
    1458              :          CALL cp_fm_scale_and_add( &
    1459          703 :             1.0_dp, history%y_previous, -1.0_dp, history%h0)
    1460              :          CALL cp_fm_scale_and_add( &
    1461          703 :             1.0_dp, history%y_previous_im, -1.0_dp, history%h0_im)
    1462          703 :          IF (ALLOCATED(history%occupation_previous)) THEN
    1463          618 :             IF (SIZE(history%occupation_previous) /= nmo) THEN
    1464            0 :                DEALLOCATE (history%occupation_previous)
    1465              :             END IF
    1466              :          END IF
    1467          703 :          IF (.NOT. ALLOCATED(history%occupation_previous)) THEN
    1468          255 :             ALLOCATE (history%occupation_previous(nmo))
    1469              :          END IF
    1470         5243 :          history%occupation_previous(:) = history%occupation0(:)
    1471          703 :          history%secant_valid = .TRUE.
    1472              :       END IF
    1473              : 
    1474          816 :       CALL store_physical_fm_matrix(c_re, history%c0, "mermin_c0")
    1475          816 :       CALL store_physical_fm_matrix(c_im, history%c0_im, "mermin_c0_im")
    1476          816 :       CALL store_physical_fm_matrix(h_re, history%h0, "mermin_h0")
    1477          816 :       CALL store_physical_fm_matrix(h_im, history%h0_im, "mermin_h0_im")
    1478          816 :       IF (ALLOCATED(history%occupation0)) THEN
    1479          703 :          IF (SIZE(history%occupation0) /= nmo) DEALLOCATE (history%occupation0)
    1480              :       END IF
    1481         1042 :       IF (.NOT. ALLOCATED(history%occupation0)) ALLOCATE (history%occupation0(nmo))
    1482         6044 :       history%occupation0(:) = occupation(:)
    1483          816 :       history%reference_valid = .TRUE.
    1484              : 
    1485          816 :    END SUBROUTINE qs_scf_kp_roll_physical_secant
    1486              : 
    1487              : ! **************************************************************************************************
    1488              : !> \brief store the raw physical Mermin gradient at one accepted K-point endpoint
    1489              : !> \param qs_ot_env local spin/K-point OT channel
    1490              : ! **************************************************************************************************
    1491          606 :    SUBROUTINE qs_scf_kp_store_mermin_gradient(qs_ot_env)
    1492              :       TYPE(qs_ot_type)                                   :: qs_ot_env
    1493              : 
    1494          606 :       CPASSERT(ASSOCIATED(qs_ot_env%matrix_mermin_g0))
    1495          606 :       CPASSERT(ASSOCIATED(qs_ot_env%matrix_mermin_g0_im))
    1496          606 :       CPASSERT(ASSOCIATED(qs_ot_env%rot_mat_mermin_g0))
    1497          606 :       CPASSERT(ASSOCIATED(qs_ot_env%rot_mat_mermin_g0_im))
    1498          606 :       CPASSERT(ALLOCATED(qs_ot_env%ener_mermin_g0))
    1499          606 :       CPASSERT(SIZE(qs_ot_env%ener_mermin_g0) == SIZE(qs_ot_env%ener_gx))
    1500              : 
    1501          606 :       CALL dbcsr_copy(qs_ot_env%matrix_mermin_g0, qs_ot_env%matrix_gx)
    1502          606 :       CALL dbcsr_copy(qs_ot_env%matrix_mermin_g0_im, qs_ot_env%matrix_gx_im)
    1503          606 :       CALL dbcsr_copy(qs_ot_env%rot_mat_mermin_g0, qs_ot_env%rot_mat_gx)
    1504          606 :       CALL dbcsr_copy(qs_ot_env%rot_mat_mermin_g0_im, qs_ot_env%rot_mat_gx_im)
    1505         4138 :       qs_ot_env%ener_mermin_g0(:) = qs_ot_env%ener_gx(:)
    1506          606 :       qs_ot_env%mermin_gradient_ref_valid = .TRUE.
    1507              : 
    1508          606 :    END SUBROUTINE qs_scf_kp_store_mermin_gradient
    1509              : 
    1510              : ! **************************************************************************************************
    1511              : !> \brief copy an owned physical full-matrix snapshot, reallocating on shape changes
    1512              : !> \param source transient or persistent source matrix
    1513              : !> \param snapshot owned response-history matrix
    1514              : !> \param name matrix name
    1515              : ! **************************************************************************************************
    1516         6076 :    SUBROUTINE store_physical_fm_matrix(source, snapshot, name)
    1517              :       TYPE(cp_fm_type), INTENT(IN), TARGET               :: source
    1518              :       TYPE(cp_fm_type), INTENT(INOUT), POINTER           :: snapshot
    1519              :       CHARACTER(LEN=*), INTENT(IN)                       :: name
    1520              : 
    1521              :       INTEGER                                            :: ncol_snapshot, ncol_source, &
    1522              :                                                             nrow_snapshot, nrow_source
    1523              :       LOGICAL                                            :: shape_changed
    1524              : 
    1525         6076 :       CALL cp_fm_get_info(source, nrow_global=nrow_source, ncol_global=ncol_source)
    1526         6076 :       shape_changed = .FALSE.
    1527         6076 :       IF (ASSOCIATED(snapshot)) THEN
    1528         5284 :          CALL cp_fm_get_info(snapshot, nrow_global=nrow_snapshot, ncol_global=ncol_snapshot)
    1529         5284 :          shape_changed = nrow_snapshot /= nrow_source .OR. ncol_snapshot /= ncol_source
    1530              :          IF (shape_changed) THEN
    1531            0 :             CALL cp_fm_release(snapshot)
    1532            0 :             DEALLOCATE (snapshot)
    1533              :          END IF
    1534              :       END IF
    1535         6076 :       IF (.NOT. ASSOCIATED(snapshot)) THEN
    1536          792 :          ALLOCATE (snapshot)
    1537          792 :          CALL cp_fm_create(snapshot, source%matrix_struct, name=name)
    1538              :       END IF
    1539         6076 :       CALL cp_fm_to_fm(source, snapshot)
    1540              : 
    1541         6076 :    END SUBROUTINE store_physical_fm_matrix
    1542              : 
    1543              : ! **************************************************************************************************
    1544              : !> \brief project one accepted physical Hxc secant onto current-orbital density tangents
    1545              : !> \param history accepted endpoint snapshots for one physical spin density
    1546              : !> \param overlap_re real part of the AO overlap matrix
    1547              : !> \param overlap_im imaginary part of the AO overlap matrix
    1548              : !> \param density_modes current-orbital density tangents including the K-point weight
    1549              : !> \param kpoint_weight irreducible K-point weight
    1550              : !> \param density_norm_sq physical density-step norm
    1551              : !> \param response_work density/Hamiltonian response work
    1552              : !> \param density_overlap projections of the density step onto density_modes
    1553              : !> \param response_overlap projections of the Hamiltonian step onto density_modes
    1554              : !> \param valid whether a finite accepted secant was available
    1555              : ! **************************************************************************************************
    1556          279 :    SUBROUTINE qs_scf_kp_physical_secant_overlaps( &
    1557          279 :       history, overlap_re, overlap_im, density_modes, kpoint_weight, density_norm_sq, &
    1558          279 :       response_work, density_overlap, response_overlap, valid)
    1559              : 
    1560              :       TYPE(qs_ot_physical_secant_type), INTENT(IN)       :: history
    1561              :       TYPE(cp_fm_type), INTENT(IN)                       :: overlap_re, overlap_im
    1562              :       COMPLEX(KIND=dp), DIMENSION(:, :, :), INTENT(IN)   :: density_modes
    1563              :       REAL(KIND=dp), INTENT(IN)                          :: kpoint_weight
    1564              :       REAL(KIND=dp), INTENT(OUT)                         :: density_norm_sq, response_work
    1565              :       REAL(KIND=dp), DIMENSION(:), INTENT(OUT)           :: density_overlap, response_overlap
    1566              :       LOGICAL, INTENT(OUT)                               :: valid
    1567              : 
    1568          279 :       COMPLEX(KIND=dp), ALLOCATABLE, DIMENSION(:, :)     :: hamiltonian_step_current, &
    1569          279 :                                                             hamiltonian_step_previous, &
    1570          279 :                                                             overlap_previous_current
    1571              :       INTEGER                                            :: nmo
    1572          279 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :)        :: dense_im, dense_re
    1573              :       TYPE(cp_fm_type)                                   :: action_im, action_re, cross_im, cross_re, &
    1574              :                                                             projection_im, projection_re
    1575              : 
    1576          279 :       nmo = SIZE(density_modes, 1)
    1577            0 :       CPASSERT(nmo > 0)
    1578          279 :       CPASSERT(SIZE(density_modes, 2) == nmo)
    1579          279 :       CPASSERT(SIZE(density_overlap) == SIZE(density_modes, 3))
    1580          279 :       CPASSERT(SIZE(response_overlap) == SIZE(density_modes, 3))
    1581              :       valid = history%secant_valid .AND. &
    1582              :               ASSOCIATED(history%c0) .AND. ASSOCIATED(history%c0_im) .AND. &
    1583              :               ASSOCIATED(history%c_previous) .AND. ASSOCIATED(history%c_previous_im) .AND. &
    1584              :               ASSOCIATED(history%y_previous) .AND. ASSOCIATED(history%y_previous_im) .AND. &
    1585          279 :               ALLOCATED(history%occupation0) .AND. ALLOCATED(history%occupation_previous)
    1586          279 :       density_norm_sq = 0.0_dp
    1587          279 :       response_work = 0.0_dp
    1588          837 :       density_overlap(:) = 0.0_dp
    1589          837 :       response_overlap(:) = 0.0_dp
    1590          279 :       IF (.NOT. valid) RETURN
    1591          279 :       CPASSERT(SIZE(history%occupation0) == nmo)
    1592          279 :       CPASSERT(SIZE(history%occupation_previous) == nmo)
    1593              : 
    1594              :       CALL cp_fm_create(action_re, history%c0%matrix_struct, &
    1595          279 :                         name="mermin_hxc_action_re", set_zero=.TRUE.)
    1596              :       CALL cp_fm_create(action_im, history%c0%matrix_struct, &
    1597          279 :                         name="mermin_hxc_action_im", set_zero=.TRUE.)
    1598              :       CALL cp_fm_create(cross_re, history%c0%matrix_struct, &
    1599          279 :                         name="mermin_hxc_cross_re", nrow=nmo, ncol=nmo, set_zero=.TRUE.)
    1600              :       CALL cp_fm_create(cross_im, history%c0%matrix_struct, &
    1601          279 :                         name="mermin_hxc_cross_im", nrow=nmo, ncol=nmo, set_zero=.TRUE.)
    1602              :       CALL cp_fm_create(projection_re, history%c0%matrix_struct, &
    1603          279 :                         name="mermin_hxc_projection_re", nrow=nmo, ncol=nmo, set_zero=.TRUE.)
    1604              :       CALL cp_fm_create(projection_im, history%c0%matrix_struct, &
    1605          279 :                         name="mermin_hxc_projection_im", nrow=nmo, ncol=nmo, set_zero=.TRUE.)
    1606              :       ALLOCATE (dense_re(nmo, nmo), dense_im(nmo, nmo), &
    1607              :                 hamiltonian_step_current(nmo, nmo), hamiltonian_step_previous(nmo, nmo), &
    1608         3627 :                 overlap_previous_current(nmo, nmo))
    1609              : 
    1610              :       CALL multiply_complex_fm_nn( &
    1611              :          overlap_re, overlap_im, history%c0, history%c0_im, &
    1612          279 :          action_re, action_im, 1.0_dp, 0.0_dp)
    1613              :       CALL multiply_complex_fm_adjoint( &
    1614              :          history%c_previous, history%c_previous_im, &
    1615          279 :          action_re, action_im, cross_re, cross_im, 1.0_dp, 0.0_dp)
    1616          279 :       CALL cp_fm_get_submatrix(cross_re, dense_re)
    1617          279 :       CALL cp_fm_get_submatrix(cross_im, dense_im)
    1618        13749 :       overlap_previous_current(:, :) = CMPLX(dense_re, dense_im, KIND=dp)
    1619              : 
    1620              :       CALL project_physical_response( &
    1621              :          history, history%c0, history%c0_im, &
    1622          279 :          action_re, action_im, projection_re, projection_im, hamiltonian_step_current)
    1623              :       CALL project_physical_response( &
    1624              :          history, history%c_previous, history%c_previous_im, &
    1625          279 :          action_re, action_im, projection_re, projection_im, hamiltonian_step_previous)
    1626              :       CALL qs_ot_density_secant_orbital_overlaps( &
    1627              :          overlap_previous_current, history%occupation_previous, history%occupation0, &
    1628              :          hamiltonian_step_previous, hamiltonian_step_current, &
    1629              :          density_modes, kpoint_weight, density_norm_sq, response_work, density_overlap, &
    1630          279 :          response_overlap, valid)
    1631              : 
    1632            0 :       DEALLOCATE (dense_re, dense_im, hamiltonian_step_current, &
    1633          279 :                   hamiltonian_step_previous, overlap_previous_current)
    1634          279 :       CALL cp_fm_release(action_re)
    1635          279 :       CALL cp_fm_release(action_im)
    1636          279 :       CALL cp_fm_release(cross_re)
    1637          279 :       CALL cp_fm_release(cross_im)
    1638          279 :       CALL cp_fm_release(projection_re)
    1639          558 :       CALL cp_fm_release(projection_im)
    1640              : 
    1641              :    CONTAINS
    1642              : 
    1643              : ! **************************************************************************************************
    1644              : !> \brief ...
    1645              : !> \param env ...
    1646              : !> \param c_re ...
    1647              : !> \param c_im ...
    1648              : !> \param action_re ...
    1649              : !> \param action_im ...
    1650              : !> \param projected_re ...
    1651              : !> \param projected_im ...
    1652              : !> \param projected ...
    1653              : ! **************************************************************************************************
    1654          558 :       SUBROUTINE project_physical_response( &
    1655          558 :          env, c_re, c_im, action_re, action_im, projected_re, projected_im, projected)
    1656              :       TYPE(qs_ot_physical_secant_type), INTENT(IN)       :: env
    1657              :       TYPE(cp_fm_type), INTENT(IN)                       :: c_re, c_im, action_re, action_im, &
    1658              :                                                             projected_re, projected_im
    1659              :       COMPLEX(KIND=dp), DIMENSION(:, :), INTENT(OUT)     :: projected
    1660              : 
    1661              :          CALL multiply_complex_fm_nn( &
    1662              :             env%y_previous, env%y_previous_im, c_re, c_im, &
    1663          558 :             action_re, action_im, 1.0_dp, 0.0_dp)
    1664              :          CALL multiply_complex_fm_adjoint( &
    1665          558 :             c_re, c_im, action_re, action_im, projected_re, projected_im, 1.0_dp, 0.0_dp)
    1666          558 :          CALL cp_fm_get_submatrix(projected_re, dense_re)
    1667          558 :          CALL cp_fm_get_submatrix(projected_im, dense_im)
    1668        27498 :          projected(:, :) = CMPLX(dense_re, dense_im, KIND=dp)
    1669        54996 :          projected(:, :) = 0.5_dp*(projected + CONJG(TRANSPOSE(projected)))
    1670          558 :       END SUBROUTINE project_physical_response
    1671              : 
    1672              :    END SUBROUTINE qs_scf_kp_physical_secant_overlaps
    1673              : 
    1674              : ! **************************************************************************************************
    1675              : !> \brief accumulate C=beta*C+alpha*A*B for split-complex distributed full matrices
    1676              : !> \param a_re ...
    1677              : !> \param a_im ...
    1678              : !> \param b_re ...
    1679              : !> \param b_im ...
    1680              : !> \param c_re ...
    1681              : !> \param c_im ...
    1682              : !> \param alpha ...
    1683              : !> \param beta ...
    1684              : ! **************************************************************************************************
    1685         3432 :    SUBROUTINE multiply_complex_fm_nn(a_re, a_im, b_re, b_im, c_re, c_im, alpha, beta)
    1686              :       TYPE(cp_fm_type), INTENT(IN)                       :: a_re, a_im, b_re, b_im, c_re, c_im
    1687              :       REAL(KIND=dp), INTENT(IN)                          :: alpha, beta
    1688              : 
    1689              :       INTEGER                                            :: k, k_b, m, m_c, n, n_c
    1690              : 
    1691         1144 :       CALL cp_fm_get_info(a_re, nrow_global=m, ncol_global=k)
    1692         1144 :       CALL cp_fm_get_info(b_re, nrow_global=k_b, ncol_global=n)
    1693         1144 :       CALL cp_fm_get_info(c_re, nrow_global=m_c, ncol_global=n_c)
    1694         1144 :       CPASSERT(k_b == k .AND. m_c == m .AND. n_c == n)
    1695         1144 :       CALL cp_complex_fm_gemm('N', 'N', m, n, k, alpha, a_re, a_im, b_re, b_im, beta, c_re, c_im)
    1696              : 
    1697         1144 :    END SUBROUTINE multiply_complex_fm_nn
    1698              : 
    1699              : ! **************************************************************************************************
    1700              : !> \brief accumulate C=beta*C+alpha*A^H*B for split-complex distributed full matrices
    1701              : !> \param a_re ...
    1702              : !> \param a_im ...
    1703              : !> \param b_re ...
    1704              : !> \param b_im ...
    1705              : !> \param c_re ...
    1706              : !> \param c_im ...
    1707              : !> \param alpha ...
    1708              : !> \param beta ...
    1709              : ! **************************************************************************************************
    1710        10389 :    SUBROUTINE multiply_complex_fm_adjoint(a_re, a_im, b_re, b_im, c_re, c_im, alpha, beta)
    1711              :       TYPE(cp_fm_type), INTENT(IN)                       :: a_re, a_im, b_re, b_im, c_re, c_im
    1712              :       REAL(KIND=dp), INTENT(IN)                          :: alpha, beta
    1713              : 
    1714              :       INTEGER                                            :: k, k_b, m, m_c, n, n_c
    1715              : 
    1716         3463 :       CALL cp_fm_get_info(a_re, nrow_global=k, ncol_global=m)
    1717         3463 :       CALL cp_fm_get_info(b_re, nrow_global=k_b, ncol_global=n)
    1718         3463 :       CALL cp_fm_get_info(c_re, nrow_global=m_c, ncol_global=n_c)
    1719         3463 :       CPASSERT(k_b == k .AND. m_c == m .AND. n_c == n)
    1720         3463 :       CALL cp_complex_fm_gemm('C', 'N', m, n, k, alpha, a_re, a_im, b_re, b_im, beta, c_re, c_im)
    1721              : 
    1722         3463 :    END SUBROUTINE multiply_complex_fm_adjoint
    1723              : 
    1724              : ! **************************************************************************************************
    1725              : !> \brief accumulate C=beta*C+alpha*A*B^H for split-complex distributed full matrices
    1726              : !> \param a_re real part of A
    1727              : !> \param a_im imaginary part of A
    1728              : !> \param b_re real part of B
    1729              : !> \param b_im imaginary part of B
    1730              : !> \param c_re real part of C
    1731              : !> \param c_im imaginary part of C
    1732              : !> \param alpha product scaling factor
    1733              : !> \param beta initial C scaling factor
    1734              : ! **************************************************************************************************
    1735          837 :    SUBROUTINE multiply_complex_fm_right_adjoint(a_re, a_im, b_re, b_im, c_re, c_im, alpha, beta)
    1736              :       TYPE(cp_fm_type), INTENT(IN)                       :: a_re, a_im, b_re, b_im, c_re, c_im
    1737              :       REAL(KIND=dp), INTENT(IN)                          :: alpha, beta
    1738              : 
    1739              :       INTEGER                                            :: k, k_b, m, m_c, n, n_c
    1740              : 
    1741          279 :       CALL cp_fm_get_info(a_re, nrow_global=m, ncol_global=k)
    1742          279 :       CALL cp_fm_get_info(b_re, nrow_global=n, ncol_global=k_b)
    1743          279 :       CALL cp_fm_get_info(c_re, nrow_global=m_c, ncol_global=n_c)
    1744          279 :       CPASSERT(k_b == k .AND. m_c == m .AND. n_c == n)
    1745          279 :       CALL cp_complex_fm_gemm('N', 'C', m, n, k, alpha, a_re, a_im, b_re, b_im, beta, c_re, c_im)
    1746              : 
    1747          279 :    END SUBROUTINE multiply_complex_fm_right_adjoint
    1748              : 
    1749              : ! **************************************************************************************************
    1750              : !> \brief Evaluate the GPW Hartree-XC and Lowdin +U curvature of a complex K-point density mode.
    1751              : !> \param qs_env ground-state QS environment defining the current density and XC kernel
    1752              : !> \param kpoints K-point environment and group distribution
    1753              : !> \param local_ot_env local spin/K-point OT channels
    1754              : !> \param first_channel global index of the first local channel
    1755              : !> \param nspin_ot number of physical spin channels
    1756              : !> \param wkp irreducible K-point weights
    1757              : !> \param para_env_inter_kp communicator between distributed K-point groups
    1758              : !> \param sab_nl real-space neighbor lists used by the K-point density transform
    1759              : !> \param fmwork full-matrix workspaces on the global communicator
    1760              : !> \param rho_ao_kp template AO density matrices for the real-space images
    1761              : !> \param channel_density_modes weighted current-orbital density modes per local channel
    1762              : !> \param number_of_modes number of populated modes to apply
    1763              : !> \param projected_hxc projected Hartree-XC Hessian in the supplied density-mode basis
    1764              : !> \param valid whether the projected block is finite and Hermitian within tolerance
    1765              : ! **************************************************************************************************
    1766          112 :    SUBROUTINE qs_scf_kp_exact_hxc_projected( &
    1767              :       qs_env, kpoints, local_ot_env, first_channel, nspin_ot, wkp, para_env_inter_kp, &
    1768          224 :       sab_nl, fmwork, rho_ao_kp, channel_density_modes, number_of_modes, &
    1769          112 :       projected_hxc, valid)
    1770              : 
    1771              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    1772              :       TYPE(kpoint_type), POINTER                         :: kpoints
    1773              :       TYPE(qs_ot_type), DIMENSION(:), POINTER            :: local_ot_env
    1774              :       INTEGER, INTENT(IN)                                :: first_channel, nspin_ot
    1775              :       REAL(KIND=dp), DIMENSION(:), POINTER               :: wkp
    1776              :       TYPE(mp_para_env_type), POINTER                    :: para_env_inter_kp
    1777              :       TYPE(neighbor_list_set_p_type), DIMENSION(:), &
    1778              :          POINTER                                         :: sab_nl
    1779              :       TYPE(cp_fm_type), DIMENSION(:), POINTER            :: fmwork
    1780              :       TYPE(dbcsr_p_type), DIMENSION(:, :), POINTER       :: rho_ao_kp
    1781              :       COMPLEX(KIND=dp), DIMENSION(:, :, :, :), &
    1782              :          INTENT(IN)                                      :: channel_density_modes
    1783              :       INTEGER, INTENT(IN)                                :: number_of_modes
    1784              :       REAL(KIND=dp), DIMENSION(:, :), INTENT(OUT)        :: projected_hxc
    1785              :       LOGICAL, INTENT(OUT)                               :: valid
    1786              : 
    1787          112 :       COMPLEX(KIND=dp), ALLOCATABLE, DIMENSION(:, :)     :: projected
    1788              :       INTEGER                                            :: ikpoint, ispin, local_channel, &
    1789              :                                                             local_kpoint, nao, nimages, &
    1790              :                                                             nlocal_kpoints, nmo, nmode, &
    1791              :                                                             response_mode, test_mode
    1792              :       LOGICAL                                            :: do_hfx
    1793              :       REAL(KIND=dp)                                      :: symmetry_error, symmetry_scale
    1794          112 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :)        :: dense_im, dense_re, lowdin_response
    1795              :       TYPE(cp_cfm_type)                                  :: action_cfm, coeff_cfm
    1796              :       TYPE(cp_fm_type)                                   :: action_im, action_re, density_im, &
    1797              :                                                             density_re, inactive_im, inactive_re, &
    1798              :                                                             projected_im, projected_re
    1799          112 :       TYPE(cp_fm_type), ALLOCATABLE, DIMENSION(:, :)     :: operator_im, operator_re
    1800          112 :       TYPE(cp_fm_type), ALLOCATABLE, DIMENSION(:, :, :)  :: density_kp
    1801          112 :       TYPE(dbcsr_p_type), DIMENSION(:, :), POINTER       :: density_rs, potential_rs
    1802              :       TYPE(dbcsr_type), POINTER                          :: matrix_k_im, matrix_k_re, template
    1803              :       TYPE(dft_control_type), POINTER                    :: dft_control
    1804              :       TYPE(kpoint_env_type), POINTER                     :: kp
    1805          112 :       TYPE(kpoint_operator_context_type)                 :: hxc_op_ctx
    1806              :       TYPE(qs_kpp1_env_type)                             :: kernel_env
    1807              :       TYPE(section_vals_type), POINTER                   :: hfx_section, input
    1808              : 
    1809          784 :       projected_hxc(:, :) = 0.0_dp
    1810          112 :       symmetry_error = 0.0_dp
    1811          112 :       valid = .FALSE.
    1812          112 :       NULLIFY (density_rs, dft_control, hfx_section, input, matrix_k_im, matrix_k_re, &
    1813          112 :                potential_rs, template)
    1814          112 :       CALL get_qs_env(qs_env, dft_control=dft_control, input=input)
    1815              :       IF (dft_control%qs_control%semi_empirical .OR. dft_control%qs_control%dftb .OR. &
    1816              :           dft_control%qs_control%xtb .OR. dft_control%qs_control%gapw .OR. &
    1817              :           dft_control%qs_control%gapw_xc .OR. dft_control%qs_control%lrigpw .OR. &
    1818          112 :           dft_control%qs_control%rigpw .OR. dft_control%do_admm) RETURN
    1819          102 :       hfx_section => section_vals_get_subs_vals(input, "DFT%XC%HF")
    1820          102 :       CALL section_vals_get(hfx_section, explicit=do_hfx)
    1821          102 :       IF (do_hfx) RETURN
    1822              : 
    1823          102 :       nlocal_kpoints = SIZE(kpoints%kp_env)
    1824          102 :       nmo = SIZE(channel_density_modes, 1)
    1825          102 :       nmode = number_of_modes
    1826          102 :       nimages = SIZE(rho_ao_kp, 2)
    1827          102 :       CPASSERT(nmo > 0)
    1828          102 :       CPASSERT(nmode > 0 .AND. nmode <= SIZE(channel_density_modes, 3))
    1829          102 :       CPASSERT(SIZE(channel_density_modes, 2) == nmo)
    1830          102 :       CPASSERT(SIZE(channel_density_modes, 4) == SIZE(local_ot_env))
    1831          102 :       IF (.NOT. (SIZE(projected_hxc, 1) >= nmode .AND. SIZE(projected_hxc, 2) >= nmode)) THEN
    1832            0 :          CALL cp_abort(__LOCATION__, "Projected HXC matrix is too small")
    1833              :       END IF
    1834          102 :       CPASSERT(SIZE(rho_ao_kp, 1) == nspin_ot)
    1835          102 :       CPASSERT(ASSOCIATED(fmwork))
    1836              : 
    1837          102 :       template => rho_ao_kp(1, 1)%matrix
    1838          102 :       CALL cp_fm_get_info(local_ot_env(1)%mermin_physical(1)%c0, nrow_global=nao)
    1839         1142 :       ALLOCATE (operator_re(nlocal_kpoints, nspin_ot), operator_im(nlocal_kpoints, nspin_ot))
    1840          265 :       DO local_kpoint = 1, nlocal_kpoints
    1841          428 :          DO ispin = 1, nspin_ot
    1842              :             local_channel = qs_ot_channel_index( &
    1843              :                             ispin, kpoints%kp_env(local_kpoint)%kpoint_env%nkpoint, nspin_ot) - &
    1844          163 :                             first_channel + 1
    1845              :             CALL cp_fm_create(operator_re(local_kpoint, ispin), &
    1846              :                               local_ot_env(local_channel)%mermin_physical(1)%c0%matrix_struct, &
    1847          163 :                               name="hxc_operator_k_re", nrow=nao, ncol=nao, set_zero=.TRUE.)
    1848              :             CALL cp_fm_create(operator_im(local_kpoint, ispin), &
    1849              :                               local_ot_env(local_channel)%mermin_physical(1)%c0%matrix_struct, &
    1850          326 :                               name="hxc_operator_k_im", nrow=nao, ncol=nao, set_zero=.TRUE.)
    1851              :          END DO
    1852              :       END DO
    1853          918 :       ALLOCATE (dense_re(nmo, nmo), dense_im(nmo, nmo), projected(nmo, nmo))
    1854              :       ! Prepare every response on the OT channel's group-local BLACS layout.
    1855              :       ! Reuse the context across density modes, which share the same AO layout.
    1856          102 :       CALL kpoint_operator_context_create(hxc_op_ctx, kpoints, fmwork(1), nspin_ot)
    1857          278 :       DO response_mode = 1, nmode
    1858         1790 :          ALLOCATE (density_kp(nlocal_kpoints, 2, nspin_ot))
    1859          455 :          DO local_kpoint = 1, nlocal_kpoints
    1860          279 :             kp => kpoints%kp_env(local_kpoint)%kpoint_env
    1861          279 :             ikpoint = kp%nkpoint
    1862          734 :             DO ispin = 1, nspin_ot
    1863          279 :                local_channel = qs_ot_channel_index(ispin, ikpoint, nspin_ot) - first_channel + 1
    1864          279 :                IF (.NOT. (ASSOCIATED(local_ot_env(local_channel)%mermin_physical(1)%c0))) THEN
    1865            0 :                   CALL cp_abort(__LOCATION__, "Missing physical OT coefficients")
    1866              :                END IF
    1867          279 :                IF (.NOT. (ASSOCIATED(local_ot_env(local_channel)%mermin_physical(1)%c0_im))) THEN
    1868            0 :                   CALL cp_abort(__LOCATION__, "Missing imaginary physical OT coefficients")
    1869              :                END IF
    1870              :                CALL cp_fm_create( &
    1871              :                   density_re, local_ot_env(local_channel)%mermin_physical(1)%c0%matrix_struct, &
    1872          279 :                   name="hxc_density_mode_re", nrow=nmo, ncol=nmo)
    1873              :                CALL cp_fm_create( &
    1874              :                   density_im, local_ot_env(local_channel)%mermin_physical(1)%c0%matrix_struct, &
    1875          279 :                   name="hxc_density_mode_im", nrow=nmo, ncol=nmo)
    1876              :                CALL cp_fm_set_submatrix( &
    1877              :                   density_re, REAL(channel_density_modes(:, :, response_mode, local_channel), &
    1878        11261 :                                    KIND=dp)/wkp(ikpoint))
    1879              :                CALL cp_fm_set_submatrix( &
    1880              :                   density_im, AIMAG(channel_density_modes(:, :, response_mode, local_channel))/ &
    1881        11261 :                   wkp(ikpoint))
    1882              :                CALL cp_fm_create( &
    1883              :                   action_re, local_ot_env(local_channel)%mermin_physical(1)%c0%matrix_struct, &
    1884          279 :                   name="hxc_density_action_re", set_zero=.TRUE.)
    1885              :                CALL cp_fm_create( &
    1886              :                   action_im, local_ot_env(local_channel)%mermin_physical(1)%c0%matrix_struct, &
    1887          279 :                   name="hxc_density_action_im", set_zero=.TRUE.)
    1888              :                CALL multiply_complex_fm_nn( &
    1889              :                   local_ot_env(local_channel)%mermin_physical(1)%c0, &
    1890              :                   local_ot_env(local_channel)%mermin_physical(1)%c0_im, density_re, density_im, &
    1891          279 :                   action_re, action_im, 1.0_dp, 0.0_dp)
    1892              :                ! The Lowdin response uses the AO density layout, not the rectangular MO layout.
    1893              :                CALL cp_fm_create(density_kp(local_kpoint, 1, ispin), &
    1894              :                                  kp%pmat(1, ispin)%matrix_struct, &
    1895          279 :                                  name="hxc_density_k_re", set_zero=.TRUE.)
    1896              :                CALL cp_fm_create(density_kp(local_kpoint, 2, ispin), &
    1897              :                                  kp%pmat(1, ispin)%matrix_struct, &
    1898          279 :                                  name="hxc_density_k_im", set_zero=.TRUE.)
    1899              :                CALL multiply_complex_fm_right_adjoint( &
    1900              :                   action_re, action_im, local_ot_env(local_channel)%mermin_physical(1)%c0, &
    1901              :                   local_ot_env(local_channel)%mermin_physical(1)%c0_im, &
    1902              :                   density_kp(local_kpoint, 1, ispin), density_kp(local_kpoint, 2, ispin), &
    1903          279 :                   1.0_dp, 0.0_dp)
    1904          279 :                CALL cp_fm_release(action_re)
    1905          279 :                CALL cp_fm_release(action_im)
    1906          279 :                CALL cp_fm_release(density_re)
    1907          837 :                CALL cp_fm_release(density_im)
    1908              :             END DO
    1909              :          END DO
    1910              : 
    1911          176 :          CALL dbcsr_allocate_matrix_set(density_rs, nspin_ot, nimages)
    1912          352 :          DO ispin = 1, nspin_ot
    1913        39246 :             DO local_kpoint = 1, nimages
    1914        38894 :                ALLOCATE (density_rs(ispin, local_kpoint)%matrix)
    1915              :                CALL dbcsr_copy(density_rs(ispin, local_kpoint)%matrix, &
    1916        38894 :                                rho_ao_kp(ispin, local_kpoint)%matrix, name="Hxc density response")
    1917        39070 :                CALL dbcsr_set(density_rs(ispin, local_kpoint)%matrix, 0.0_dp)
    1918              :             END DO
    1919              :          END DO
    1920              :          CALL kpoint_density_transform(kpoints, density_rs, .FALSE., template, sab_nl, fmwork, &
    1921          176 :                                        pmat_ext=density_kp)
    1922          176 :          IF (ALLOCATED(kpoints%lowdin_v)) CALL lowdin_kp_kernel(qs_env, density_kp, lowdin_response)
    1923          455 :          DO local_kpoint = 1, nlocal_kpoints
    1924          734 :             DO ispin = 1, nspin_ot
    1925          279 :                CALL cp_fm_release(density_kp(local_kpoint, 1, ispin))
    1926          558 :                CALL cp_fm_release(density_kp(local_kpoint, 2, ispin))
    1927              :             END DO
    1928              :          END DO
    1929          176 :          DEALLOCATE (density_kp)
    1930              : 
    1931          176 :          CALL apply_hxc_kernel_kp(qs_env, kernel_env, density_rs, potential_rs)
    1932              :          ! Refresh every response mode. The OT channel can use a different
    1933              :          ! group-local BLACS layout from the default AO/AO pool.
    1934          176 :          CALL kpoint_operator_prepare(hxc_op_ctx, potential_rs, kpoint_slot_ks, TARGET=operator_re(1, 1))
    1935          718 :          DO local_kpoint = 1, MAXVAL(kpoints%kp_dist(2, :) - kpoints%kp_dist(1, :) + 1)
    1936          792 :             DO ispin = 1, nspin_ot
    1937          616 :                IF (local_kpoint <= nlocal_kpoints) THEN
    1938              :                   CALL kpoint_operator_get(hxc_op_ctx, local_kpoint, ispin, potential_rs, &
    1939              :                                            fm_re=operator_re(local_kpoint, ispin), &
    1940          279 :                                            fm_im=operator_im(local_kpoint, ispin), matrix_row=ispin, slot=kpoint_slot_ks)
    1941              :                ELSE
    1942              :                   ! Participate in the global transfers without a local output in this round.
    1943              :                   CALL kpoint_operator_get(hxc_op_ctx, local_kpoint, ispin, potential_rs, &
    1944           29 :                                            fm_re=inactive_re, fm_im=inactive_im, matrix_row=ispin, slot=kpoint_slot_ks)
    1945              :                END IF
    1946              :             END DO
    1947              :          END DO
    1948          455 :          DO local_kpoint = 1, nlocal_kpoints
    1949          279 :             kp => kpoints%kp_env(local_kpoint)%kpoint_env
    1950          279 :             ikpoint = kp%nkpoint
    1951          734 :             DO ispin = 1, nspin_ot
    1952          279 :                local_channel = qs_ot_channel_index(ispin, ikpoint, nspin_ot) - first_channel + 1
    1953              :                CALL cp_fm_create( &
    1954              :                   action_re, local_ot_env(local_channel)%mermin_physical(1)%c0%matrix_struct, &
    1955          279 :                   name="hxc_potential_action_re", set_zero=.TRUE.)
    1956              :                CALL cp_fm_create( &
    1957              :                   action_im, local_ot_env(local_channel)%mermin_physical(1)%c0%matrix_struct, &
    1958          279 :                   name="hxc_potential_action_im", set_zero=.TRUE.)
    1959              :                CALL kpoint_operator_get_local( &
    1960              :                   potential_rs, kpoints, kp, ispin, operator_re(local_kpoint, ispin), &
    1961          279 :                   operator_im(local_kpoint, ispin), matrix_k_re, matrix_k_im)
    1962              :                CALL cp_dbcsr_sm_fm_multiply( &
    1963          279 :                   matrix_k_re, local_ot_env(local_channel)%mermin_physical(1)%c0, action_re, nmo)
    1964              :                CALL cp_dbcsr_sm_fm_multiply( &
    1965              :                   matrix_k_im, local_ot_env(local_channel)%mermin_physical(1)%c0_im, action_re, nmo, &
    1966          279 :                   alpha=-1.0_dp, beta=1.0_dp)
    1967              :                CALL cp_dbcsr_sm_fm_multiply( &
    1968          279 :                   matrix_k_re, local_ot_env(local_channel)%mermin_physical(1)%c0_im, action_im, nmo)
    1969              :                CALL cp_dbcsr_sm_fm_multiply( &
    1970              :                   matrix_k_im, local_ot_env(local_channel)%mermin_physical(1)%c0, action_im, nmo, &
    1971          279 :                   alpha=1.0_dp, beta=1.0_dp)
    1972          279 :                IF (ALLOCATED(lowdin_response)) THEN
    1973           87 :                   IF (ANY(lowdin_response(:, ispin) /= 0.0_dp)) THEN
    1974           87 :                      CALL cp_cfm_create(coeff_cfm, local_ot_env(local_channel)%mermin_physical(1)%c0%matrix_struct)
    1975           87 :                      CALL cp_cfm_create(action_cfm, action_re%matrix_struct)
    1976              :                      CALL cp_fm_to_cfm(local_ot_env(local_channel)%mermin_physical(1)%c0, &
    1977           87 :                                        local_ot_env(local_channel)%mermin_physical(1)%c0_im, coeff_cfm)
    1978           87 :                      CALL cp_fm_to_cfm(action_re, action_im, action_cfm)
    1979           87 :                      CALL lowdin_kp_apply_mo(kp, lowdin_response(:, ispin), coeff_cfm, action_cfm)
    1980           87 :                      CALL cp_cfm_to_fm(action_cfm, action_re, action_im)
    1981           87 :                      CALL cp_cfm_release(action_cfm)
    1982           87 :                      CALL cp_cfm_release(coeff_cfm)
    1983              :                   END IF
    1984              :                END IF
    1985              :                CALL cp_fm_create( &
    1986              :                   projected_re, local_ot_env(local_channel)%mermin_physical(1)%c0%matrix_struct, &
    1987          279 :                   name="hxc_projected_re", nrow=nmo, ncol=nmo, set_zero=.TRUE.)
    1988              :                CALL cp_fm_create( &
    1989              :                   projected_im, local_ot_env(local_channel)%mermin_physical(1)%c0%matrix_struct, &
    1990          279 :                   name="hxc_projected_im", nrow=nmo, ncol=nmo, set_zero=.TRUE.)
    1991              :                CALL multiply_complex_fm_adjoint( &
    1992              :                   local_ot_env(local_channel)%mermin_physical(1)%c0, &
    1993              :                   local_ot_env(local_channel)%mermin_physical(1)%c0_im, action_re, action_im, &
    1994          279 :                   projected_re, projected_im, 1.0_dp, 0.0_dp)
    1995          279 :                CALL cp_fm_get_submatrix(projected_re, dense_re)
    1996          279 :                CALL cp_fm_get_submatrix(projected_im, dense_im)
    1997        11261 :                projected(:, :) = CMPLX(dense_re, dense_im, KIND=dp)
    1998          790 :                DO test_mode = 1, nmode
    1999              :                   projected_hxc(test_mode, response_mode) = &
    2000              :                      projected_hxc(test_mode, response_mode) + REAL(SUM( &
    2001        21036 :                                                    CONJG(channel_density_modes(:, :, test_mode, local_channel))*projected), KIND=dp)
    2002              :                END DO
    2003          279 :                CALL cp_fm_release(projected_re)
    2004          279 :                CALL cp_fm_release(projected_im)
    2005          279 :                CALL cp_fm_release(action_re)
    2006          279 :                CALL cp_fm_release(action_im)
    2007          279 :                CALL dbcsr_release_p(matrix_k_re)
    2008          558 :                CALL dbcsr_release_p(matrix_k_im)
    2009              :             END DO
    2010              :          END DO
    2011          176 :          CALL dbcsr_deallocate_matrix_set(density_rs)
    2012          176 :          CALL dbcsr_deallocate_matrix_set(potential_rs)
    2013          278 :          NULLIFY (density_rs, potential_rs)
    2014              :       END DO
    2015          102 :       CALL kpoint_operator_context_release(hxc_op_ctx)
    2016              : 
    2017         1326 :       CALL para_env_inter_kp%sum(projected_hxc)
    2018              :       symmetry_error = MAXVAL(ABS( &
    2019              :                               projected_hxc(1:nmode, 1:nmode) - &
    2020          602 :                               TRANSPOSE(projected_hxc(1:nmode, 1:nmode))))
    2021              :       symmetry_scale = MAX(SQRT(EPSILON(1.0_dp)), &
    2022          602 :                            MAXVAL(ABS(projected_hxc(1:nmode, 1:nmode))))
    2023              :       projected_hxc(1:nmode, 1:nmode) = 0.5_dp*( &
    2024              :                                         projected_hxc(1:nmode, 1:nmode) + &
    2025         1102 :                                         TRANSPOSE(projected_hxc(1:nmode, 1:nmode)))
    2026              :       valid = ALL(ieee_is_finite(projected_hxc(1:nmode, 1:nmode))) .AND. &
    2027              :               ieee_is_finite(symmetry_error) .AND. &
    2028          602 :               symmetry_error <= 1.0E-10_dp*symmetry_scale
    2029              : 
    2030          102 :       DEALLOCATE (dense_re, dense_im, projected)
    2031          265 :       DO local_kpoint = 1, nlocal_kpoints
    2032          428 :          DO ispin = 1, nspin_ot
    2033          163 :             CALL cp_fm_release(operator_re(local_kpoint, ispin))
    2034          326 :             CALL cp_fm_release(operator_im(local_kpoint, ispin))
    2035              :          END DO
    2036              :       END DO
    2037          102 :       DEALLOCATE (operator_re, operator_im)
    2038          102 :       CALL kpp1_release(kernel_env)
    2039              : 
    2040          428 :    END SUBROUTINE qs_scf_kp_exact_hxc_projected
    2041              : 
    2042              : ! **************************************************************************************************
    2043              : !> \brief project a split-complex Hamiltonian into a complex orbital basis
    2044              : !> \param c_re real orbital coefficients
    2045              : !> \param c_im imaginary orbital coefficients
    2046              : !> \param h_re real Hamiltonian
    2047              : !> \param h_im imaginary Hamiltonian
    2048              : !> \param projected dense Hermitian projected Hamiltonian
    2049              : ! **************************************************************************************************
    2050           28 :    SUBROUTINE qs_scf_kp_project_hamiltonian(c_re, c_im, h_re, h_im, projected)
    2051              :       TYPE(cp_fm_type), INTENT(IN)                       :: c_re, c_im, h_re, h_im
    2052              :       COMPLEX(KIND=dp), DIMENSION(:, :), INTENT(OUT)     :: projected
    2053              : 
    2054              :       INTEGER                                            :: nmo
    2055              :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :)        :: dense_im, dense_re
    2056              :       TYPE(cp_fm_type)                                   :: action_im, action_re, projection_im, &
    2057              :                                                             projection_re
    2058              : 
    2059           28 :       nmo = SIZE(projected, 1)
    2060           28 :       CPASSERT(nmo > 0 .AND. SIZE(projected, 2) == nmo)
    2061           28 :       CALL cp_fm_create(action_re, c_re%matrix_struct, name="ot_response_hc_re", set_zero=.TRUE.)
    2062           28 :       CALL cp_fm_create(action_im, c_re%matrix_struct, name="ot_response_hc_im", set_zero=.TRUE.)
    2063              :       CALL cp_fm_create(projection_re, c_re%matrix_struct, name="ot_response_chc_re", &
    2064           28 :                         nrow=nmo, ncol=nmo, set_zero=.TRUE.)
    2065              :       CALL cp_fm_create(projection_im, c_re%matrix_struct, name="ot_response_chc_im", &
    2066           28 :                         nrow=nmo, ncol=nmo, set_zero=.TRUE.)
    2067          168 :       ALLOCATE (dense_re(nmo, nmo), dense_im(nmo, nmo))
    2068              : 
    2069              :       CALL multiply_complex_fm_nn( &
    2070           28 :          h_re, h_im, c_re, c_im, action_re, action_im, 1.0_dp, 0.0_dp)
    2071              :       CALL multiply_complex_fm_adjoint( &
    2072           28 :          c_re, c_im, action_re, action_im, projection_re, projection_im, 1.0_dp, 0.0_dp)
    2073           28 :       CALL cp_fm_get_submatrix(projection_re, dense_re)
    2074           28 :       CALL cp_fm_get_submatrix(projection_im, dense_im)
    2075         3108 :       projected(:, :) = CMPLX(dense_re, dense_im, KIND=dp)
    2076         6216 :       projected(:, :) = 0.5_dp*(projected + CONJG(TRANSPOSE(projected)))
    2077              : 
    2078           28 :       DEALLOCATE (dense_re, dense_im)
    2079           28 :       CALL cp_fm_release(action_re)
    2080           28 :       CALL cp_fm_release(action_im)
    2081           28 :       CALL cp_fm_release(projection_re)
    2082           28 :       CALL cp_fm_release(projection_im)
    2083              : 
    2084           28 :    END SUBROUTINE qs_scf_kp_project_hamiltonian
    2085              : 
    2086              : ! **************************************************************************************************
    2087              : !> \brief collect the global fixed-N trial smearing state used by k-point OT
    2088              : !> \param kpoints ...
    2089              : !> \param local_ot_env ...
    2090              : !> \param first_channel ...
    2091              : !> \param nspin_ot ...
    2092              : !> \param nspin_energy number of physical spin-resolved auxiliary-energy blocks
    2093              : !> \param restricted_roks whether both energy blocks share one orbital channel
    2094              : !> \param kp_range ...
    2095              : !> \param wkp ...
    2096              : !> \param para_env_inter_kp ...
    2097              : !> \param smear ...
    2098              : !> \param trial_eigenvalues ...
    2099              : !> \param trial_occupation ...
    2100              : !> \param trial_mu chemical potential for each spin channel
    2101              : !> \param trial_kTS ...
    2102              : ! **************************************************************************************************
    2103         1470 :    SUBROUTINE qs_scf_loop_collect_ot_kp_trial_smearing( &
    2104              :       kpoints, local_ot_env, first_channel, nspin_ot, nspin_energy, restricted_roks, &
    2105              :       kp_range, wkp, para_env_inter_kp, smear, trial_eigenvalues, trial_occupation, trial_mu, trial_kTS)
    2106              : 
    2107              :       TYPE(kpoint_type), POINTER                         :: kpoints
    2108              :       TYPE(qs_ot_type), DIMENSION(:), POINTER            :: local_ot_env
    2109              :       INTEGER, INTENT(IN)                                :: first_channel, nspin_ot, nspin_energy
    2110              :       LOGICAL, INTENT(IN)                                :: restricted_roks
    2111              :       INTEGER, DIMENSION(2), INTENT(IN)                  :: kp_range
    2112              :       REAL(KIND=dp), DIMENSION(:), POINTER               :: wkp
    2113              :       TYPE(mp_para_env_type), POINTER                    :: para_env_inter_kp
    2114              :       TYPE(smear_type), INTENT(IN)                       :: smear
    2115              :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :, :), &
    2116              :          INTENT(OUT)                                     :: trial_eigenvalues, trial_occupation
    2117              :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:), &
    2118              :          INTENT(OUT)                                     :: trial_mu
    2119              :       REAL(KIND=dp), INTENT(OUT)                         :: trial_kTS
    2120              : 
    2121              :       INTEGER                                            :: energy_start, ikpoint, ispin, &
    2122              :                                                             local_channel, local_kpoint, ne_a, &
    2123              :                                                             ne_b, nelectron, nkpoint, nmo
    2124              :       REAL(KIND=dp)                                      :: kTS, mu, nel, sigma
    2125              :       REAL(KIND=dp), DIMENSION(2)                        :: mus, spin_targets
    2126              :       TYPE(kpoint_env_type), POINTER                     :: kp
    2127              : 
    2128         1470 :       CPASSERT(smear%do_smear)
    2129         2790 :       SELECT CASE (smear%method)
    2130              :       CASE (smear_fermi_dirac)
    2131         1320 :          sigma = smear%electronic_temperature
    2132              :       CASE (smear_gaussian, smear_mp, smear_mv)
    2133          150 :          sigma = smear%smearing_width
    2134              :       CASE DEFAULT
    2135         1470 :          CPABORT("K-point Mermin OT does not support the selected smearing method")
    2136              :       END SELECT
    2137         1470 :       CPASSERT(sigma > EPSILON(sigma))
    2138         1470 :       CPASSERT(ASSOCIATED(para_env_inter_kp))
    2139         1470 :       CALL get_kpoint_info(kpoints, nkp=nkpoint)
    2140         1470 :       kp => kpoints%kp_env(1)%kpoint_env
    2141         1470 :       CALL get_mo_set(kp%mos(1), nelectron=nelectron, nmo=nmo)
    2142         1470 :       ne_a = nelectron
    2143         1470 :       ne_b = 0
    2144         1470 :       IF (nspin_energy == 2) CALL get_mo_set(kp%mos(2), nelectron=ne_b)
    2145         4410 :       spin_targets(:) = smearing_spin_targets([ne_a, ne_b], smear%fixed_mag_mom)
    2146              : 
    2147         7350 :       ALLOCATE (trial_eigenvalues(nmo, nkpoint, nspin_energy))
    2148         5880 :       ALLOCATE (trial_occupation(nmo, nkpoint, nspin_energy))
    2149         4410 :       ALLOCATE (trial_mu(nspin_energy))
    2150         1470 :       trial_eigenvalues(:, :, :) = 0.0_dp
    2151         1470 :       trial_occupation(:, :, :) = 0.0_dp
    2152         1470 :       mus(:) = 0.0_dp
    2153              : 
    2154         3505 :       DO local_kpoint = 1, SIZE(kpoints%kp_env)
    2155         2035 :          kp => kpoints%kp_env(local_kpoint)%kpoint_env
    2156         2035 :          ikpoint = kp%nkpoint
    2157         2035 :          CPASSERT(ikpoint >= kp_range(1) .AND. ikpoint <= kp_range(2))
    2158         5774 :          DO ispin = 1, nspin_energy
    2159              :             local_channel = qs_ot_channel_index(MERGE(1, ispin, restricted_roks), &
    2160         4438 :                                                 ikpoint, nspin_ot) - first_channel + 1
    2161         2269 :             energy_start = 1
    2162         2269 :             IF (restricted_roks) energy_start = (ispin - 1)*nmo + 1
    2163              :             trial_eigenvalues(1:nmo, ikpoint, ispin) = &
    2164        19822 :                local_ot_env(local_channel)%ener_x(energy_start:energy_start + nmo - 1)
    2165              :          END DO
    2166              :       END DO
    2167         1470 :       CALL para_env_inter_kp%sum(trial_eigenvalues)
    2168              : 
    2169         1470 :       IF (nspin_energy == 1) THEN
    2170         1236 :          nel = REAL(nelectron, KIND=dp)
    2171              :          CALL Smearkp(trial_occupation(:, :, 1), mus(1), trial_kTS, &
    2172         1236 :                       trial_eigenvalues(:, :, 1), nel, wkp, sigma, 2.0_dp, smear%method)
    2173          234 :       ELSE IF (restricted_roks .OR. smearing_separate_spin(smear%fixed_mag_mom)) THEN
    2174          180 :          nel = spin_targets(1)
    2175              :          CALL Smearkp(trial_occupation(:, :, 1), mus(1), kTS, &
    2176          180 :                       trial_eigenvalues(:, :, 1), nel, wkp, sigma, 1.0_dp, smear%method)
    2177          180 :          trial_kTS = kTS
    2178          180 :          nel = spin_targets(2)
    2179              :          CALL Smearkp(trial_occupation(:, :, 2), mus(2), kTS, &
    2180          180 :                       trial_eigenvalues(:, :, 2), nel, wkp, sigma, 1.0_dp, smear%method)
    2181          180 :          trial_kTS = trial_kTS + kTS
    2182              :       ELSE
    2183           54 :          nel = REAL(ne_a + ne_b, KIND=dp)
    2184              :          CALL Smearkp2(trial_occupation, mu, trial_kTS, trial_eigenvalues, nel, wkp, &
    2185           54 :                        sigma, smear%method)
    2186          162 :          mus(1:2) = mu
    2187              :       END IF
    2188         3174 :       trial_mu(:) = mus(1:nspin_energy)
    2189         1470 :    END SUBROUTINE qs_scf_loop_collect_ot_kp_trial_smearing
    2190              : 
    2191              : ! **************************************************************************************************
    2192              : !> \brief construct auxiliary-energy gradients on the global fixed-N Mermin surface
    2193              : !> \param kpoints ...
    2194              : !> \param local_ot_env ...
    2195              : !> \param first_channel ...
    2196              : !> \param nspin_ot ...
    2197              : !> \param nspin_energy ...
    2198              : !> \param restricted_roks ...
    2199              : !> \param wkp ...
    2200              : !> \param para_env_inter_kp ...
    2201              : !> \param smear ...
    2202              : !> \param trial_eigenvalues ...
    2203              : !> \param trial_occupation ...
    2204              : !> \param trial_mu ...
    2205              : ! **************************************************************************************************
    2206         1470 :    SUBROUTINE qs_scf_loop_prepare_ot_kp_energy_gradient( &
    2207              :       kpoints, local_ot_env, first_channel, nspin_ot, nspin_energy, restricted_roks, &
    2208         1470 :       wkp, para_env_inter_kp, smear, trial_eigenvalues, trial_occupation, trial_mu)
    2209              : 
    2210              :       TYPE(kpoint_type), POINTER                         :: kpoints
    2211              :       TYPE(qs_ot_type), DIMENSION(:), POINTER            :: local_ot_env
    2212              :       INTEGER, INTENT(IN)                                :: first_channel, nspin_ot, nspin_energy
    2213              :       LOGICAL, INTENT(IN)                                :: restricted_roks
    2214              :       REAL(KIND=dp), DIMENSION(:), POINTER               :: wkp
    2215              :       TYPE(mp_para_env_type), POINTER                    :: para_env_inter_kp
    2216              :       TYPE(smear_type), INTENT(IN)                       :: smear
    2217              :       REAL(KIND=dp), DIMENSION(:, :, :), INTENT(IN)      :: trial_eigenvalues, trial_occupation
    2218              :       REAL(KIND=dp), DIMENSION(:), INTENT(IN)            :: trial_mu
    2219              : 
    2220              :       INTEGER                                            :: energy_start, group, ikpoint, imo, &
    2221              :                                                             ispin, local_channel, local_kpoint, &
    2222              :                                                             ngroups, nmo
    2223              :       REAL(KIND=dp)                                      :: fixed_n_mean, maxocc, sigma
    2224         1470 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:)           :: fixed_n_residual, fixed_n_weight, &
    2225         1470 :                                                             preconditioner_count, &
    2226         1470 :                                                             preconditioner_shift, response_weight
    2227              :       TYPE(kpoint_env_type), POINTER                     :: kp
    2228              : 
    2229         1470 :       IF (.NOT. local_ot_env(1)%settings%do_ener) RETURN
    2230              : 
    2231         1470 :       CPASSERT(smear%do_smear)
    2232         1470 :       CPASSERT(ASSOCIATED(para_env_inter_kp))
    2233         2790 :       SELECT CASE (smear%method)
    2234              :       CASE (smear_fermi_dirac)
    2235         1320 :          sigma = smear%electronic_temperature
    2236              :       CASE (smear_gaussian, smear_mp, smear_mv)
    2237          150 :          sigma = smear%smearing_width
    2238              :       CASE DEFAULT
    2239         1470 :          CPABORT("K-point Mermin OT does not support the selected smearing method")
    2240              :       END SELECT
    2241         1470 :       CPASSERT(sigma > EPSILON(sigma))
    2242              : 
    2243         1470 :       ngroups = 1
    2244         1470 :       IF (restricted_roks .OR. &
    2245          180 :           (nspin_energy == 2 .AND. smearing_separate_spin(smear%fixed_mag_mom))) ngroups = 2
    2246         1470 :       nmo = SIZE(trial_eigenvalues, 1)
    2247              :       ALLOCATE (fixed_n_residual(ngroups), fixed_n_weight(ngroups), &
    2248              :                 preconditioner_count(ngroups), preconditioner_shift(ngroups), &
    2249        10290 :                 response_weight(nmo))
    2250         1470 :       fixed_n_residual(:) = 0.0_dp
    2251         1470 :       fixed_n_weight(:) = 0.0_dp
    2252         1470 :       preconditioner_count(:) = 0.0_dp
    2253         1470 :       preconditioner_shift(:) = 0.0_dp
    2254              : 
    2255         3505 :       DO local_kpoint = 1, SIZE(kpoints%kp_env)
    2256         2035 :          kp => kpoints%kp_env(local_kpoint)%kpoint_env
    2257         2035 :          ikpoint = kp%nkpoint
    2258         5774 :          DO ispin = 1, nspin_energy
    2259         2269 :             group = MERGE(ispin, 1, ngroups == nspin_energy)
    2260              :             local_channel = qs_ot_channel_index(MERGE(1, ispin, restricted_roks), &
    2261         4438 :                                                 ikpoint, nspin_ot) - first_channel + 1
    2262         2269 :             energy_start = 1
    2263         2269 :             IF (restricted_roks) energy_start = (ispin - 1)*nmo + 1
    2264         2269 :             CALL get_mo_set(kp%mos(ispin), maxocc=maxocc, nmo=nmo)
    2265         2269 :             CPASSERT(maxocc > EPSILON(maxocc))
    2266         2269 :             IF (.NOT. (energy_start + nmo - 1 <= SIZE(local_ot_env(local_channel)%ener_x))) THEN
    2267            0 :                CALL cp_abort(__LOCATION__, "OT energy slice exceeds channel storage")
    2268              :             END IF
    2269              :             CALL smearing_response_weight( &
    2270              :                response_weight, trial_occupation(:, ikpoint, ispin), &
    2271              :                trial_eigenvalues(:, ikpoint, ispin), trial_mu(ispin), sigma, maxocc, nmo, &
    2272         2269 :                smear%method)
    2273        17787 :             response_weight(:) = wkp(ikpoint)*response_weight
    2274        22091 :             DO imo = 1, nmo
    2275              :                fixed_n_weight(group) = fixed_n_weight(group) + &
    2276        15518 :                                        response_weight(imo)
    2277              :                fixed_n_residual(group) = fixed_n_residual(group) + &
    2278              :                                          response_weight(imo)* &
    2279              :                                          (local_ot_env(local_channel)%ener_rayleigh(energy_start + imo - 1) - &
    2280        17787 :                                           trial_eigenvalues(imo, ikpoint, ispin))
    2281              :             END DO
    2282              :          END DO
    2283              :       END DO
    2284         1470 :       CALL para_env_inter_kp%sum(fixed_n_weight)
    2285         1470 :       CALL para_env_inter_kp%sum(fixed_n_residual)
    2286              : 
    2287         1470 :       IF (local_ot_env(1)%settings%occupation_preconditioner) THEN
    2288         2993 :          DO local_kpoint = 1, SIZE(kpoints%kp_env)
    2289         1735 :             kp => kpoints%kp_env(local_kpoint)%kpoint_env
    2290         1735 :             ikpoint = kp%nkpoint
    2291         4962 :             DO ispin = 1, nspin_energy
    2292         1969 :                group = MERGE(ispin, 1, ngroups == nspin_energy)
    2293              :                local_channel = qs_ot_channel_index(MERGE(1, ispin, restricted_roks), &
    2294         3838 :                                                    ikpoint, nspin_ot) - first_channel + 1
    2295         1969 :                CALL get_mo_set(kp%mos(ispin), nmo=nmo)
    2296         1969 :                energy_start = 1
    2297         1969 :                IF (restricted_roks) energy_start = (ispin - 1)*nmo + 1
    2298         1969 :                fixed_n_mean = 0.0_dp
    2299         1969 :                IF (ABS(fixed_n_weight(group)) > EPSILON(fixed_n_weight(group))) THEN
    2300         1925 :                   fixed_n_mean = fixed_n_residual(group)/fixed_n_weight(group)
    2301              :                END IF
    2302              :                local_ot_env(local_channel)%ener_preconditioned_gx( &
    2303              :                   energy_start:energy_start + nmo - 1) = fixed_n_mean - &
    2304              :                                                       (local_ot_env(local_channel)%ener_rayleigh( &
    2305              :                                                        energy_start:energy_start + nmo - 1) - &
    2306        13527 :                                                        trial_eigenvalues(:, ikpoint, ispin))
    2307              :                preconditioner_shift(group) = preconditioner_shift(group) + &
    2308              :                                              SUM(local_ot_env(local_channel)%ener_preconditioned_gx( &
    2309        13527 :                                                  energy_start:energy_start + nmo - 1))
    2310         5673 :                preconditioner_count(group) = preconditioner_count(group) + REAL(nmo, KIND=dp)
    2311              :             END DO
    2312              :          END DO
    2313         1258 :          CALL para_env_inter_kp%sum(preconditioner_shift)
    2314         1258 :          CALL para_env_inter_kp%sum(preconditioner_count)
    2315              :       END IF
    2316              : 
    2317         3505 :       DO local_kpoint = 1, SIZE(kpoints%kp_env)
    2318         2035 :          kp => kpoints%kp_env(local_kpoint)%kpoint_env
    2319         2035 :          ikpoint = kp%nkpoint
    2320         5774 :          DO ispin = 1, nspin_energy
    2321         2269 :             group = MERGE(ispin, 1, ngroups == nspin_energy)
    2322              :             local_channel = qs_ot_channel_index(MERGE(1, ispin, restricted_roks), &
    2323         4438 :                                                 ikpoint, nspin_ot) - first_channel + 1
    2324         2269 :             CALL get_mo_set(kp%mos(ispin), maxocc=maxocc, nmo=nmo)
    2325         2269 :             energy_start = 1
    2326         2269 :             IF (restricted_roks) energy_start = (ispin - 1)*nmo + 1
    2327         2269 :             IF (local_ot_env(local_channel)%settings%occupation_preconditioner .AND. &
    2328              :                 preconditioner_count(group) > 0.0_dp) THEN
    2329              :                local_ot_env(local_channel)%ener_preconditioned_gx( &
    2330              :                   energy_start:energy_start + nmo - 1) = &
    2331              :                   local_ot_env(local_channel)%ener_preconditioned_gx( &
    2332              :                   energy_start:energy_start + nmo - 1) - &
    2333        13527 :                   preconditioner_shift(group)/preconditioner_count(group)
    2334              :             END IF
    2335              :             CALL smearing_response_weight( &
    2336              :                response_weight, trial_occupation(:, ikpoint, ispin), &
    2337              :                trial_eigenvalues(:, ikpoint, ispin), trial_mu(ispin), sigma, maxocc, nmo, &
    2338         2269 :                smear%method)
    2339        17787 :             response_weight(:) = wkp(ikpoint)*response_weight
    2340              :             CALL qs_ot_fixed_n_energy_gradient( &
    2341              :                local_ot_env(local_channel)%ener_rayleigh(energy_start:energy_start + nmo - 1), &
    2342              :                trial_eigenvalues(:, ikpoint, ispin), &
    2343              :                response_weight, fixed_n_weight(group), fixed_n_residual(group), &
    2344         6573 :                local_ot_env(local_channel)%ener_gx(energy_start:energy_start + nmo - 1))
    2345              :          END DO
    2346              :       END DO
    2347              : 
    2348            0 :       DEALLOCATE (fixed_n_residual, fixed_n_weight, preconditioner_count, preconditioner_shift, &
    2349         1470 :                   response_weight)
    2350              : 
    2351         1470 :    END SUBROUTINE qs_scf_loop_prepare_ot_kp_energy_gradient
    2352              : 
    2353              : ! **************************************************************************************************
    2354              : !> \brief build a coupled finite-complex rotation/energy preconditioner for K-point Mermin OT
    2355              : !> \param qs_env ground-state QS environment defining the current density and XC kernel
    2356              : !> \param kpoints K-point environment
    2357              : !> \param local_ot_env local spin/K-point OT channels
    2358              : !> \param first_channel global index of the first local channel
    2359              : !> \param nspin_ot number of spin channels
    2360              : !> \param restricted_roks whether two physical spin densities share each orbital channel
    2361              : !> \param wkp irreducible K-point weights
    2362              : !> \param para_env_inter_kp communicator between distributed K-point groups
    2363              : !> \param sab_nl real-space neighbor lists used by the K-point density transform
    2364              : !> \param fmwork full-matrix workspaces on the global communicator
    2365              : !> \param rho_ao_kp template AO density matrices for the real-space images
    2366              : !> \param smear smearing settings
    2367              : !> \param trial_eigenvalues current auxiliary band energies
    2368              : !> \param trial_occupation current fixed-N occupations
    2369              : !> \param trial_mu chemical potential for each spin channel
    2370              : ! **************************************************************************************************
    2371          664 :    SUBROUTINE qs_scf_loop_prepare_ot_kp_rotation_response( &
    2372              :       qs_env, kpoints, local_ot_env, first_channel, nspin_ot, restricted_roks, &
    2373              :       wkp, para_env_inter_kp, sab_nl, fmwork, rho_ao_kp, smear, &
    2374          664 :       trial_eigenvalues, trial_occupation, trial_mu)
    2375              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    2376              :       TYPE(kpoint_type), POINTER                         :: kpoints
    2377              :       TYPE(qs_ot_type), DIMENSION(:), POINTER            :: local_ot_env
    2378              :       INTEGER, INTENT(IN)                                :: first_channel, nspin_ot
    2379              :       LOGICAL, INTENT(IN)                                :: restricted_roks
    2380              :       REAL(KIND=dp), DIMENSION(:), POINTER               :: wkp
    2381              :       TYPE(mp_para_env_type), POINTER                    :: para_env_inter_kp
    2382              :       TYPE(neighbor_list_set_p_type), DIMENSION(:), &
    2383              :          POINTER                                         :: sab_nl
    2384              :       TYPE(cp_fm_type), DIMENSION(:), POINTER            :: fmwork
    2385              :       TYPE(dbcsr_p_type), DIMENSION(:, :), POINTER       :: rho_ao_kp
    2386              :       TYPE(smear_type), INTENT(IN)                       :: smear
    2387              :       REAL(KIND=dp), DIMENSION(:, :, :), INTENT(IN)      :: trial_eigenvalues, trial_occupation
    2388              :       REAL(KIND=dp), DIMENSION(:), INTENT(IN)            :: trial_mu
    2389              : 
    2390              :       INTEGER, PARAMETER :: finite_response_max_rotation = 800
    2391              :       REAL(KIND=dp), PARAMETER :: rotation_trust_rms = 0.25_dp, rotation_trust_spectral = 0.25_dp
    2392              : 
    2393          664 :       COMPLEX(KIND=dp), ALLOCATABLE, DIMENSION(:, :)     :: chc, generator
    2394          664 :       COMPLEX(KIND=dp), ALLOCATABLE, DIMENSION(:, :, :)  :: channel_generator, density_modes
    2395              :       COMPLEX(KIND=dp), ALLOCATABLE, &
    2396          664 :          DIMENSION(:, :, :, :)                           :: channel_density_modes
    2397              :       INTEGER :: energy_spin, energy_start, energy_stop, failure, gradient_secant_failure, group, &
    2398              :          i, ikpoint, ispin, j, local_channel, local_kpoint, nenergy, ngroups, nlocal_channels, &
    2399              :          nmo, nrotation, nrotation_groups, nspin_energy, physical_spin, r, rotation_group
    2400          664 :       INTEGER, ALLOCATABLE, DIMENSION(:, :)              :: channel_response_group
    2401              :       LOGICAL :: accepted_cross_valid, accepted_curvature_valid, exact_hxc_valid, &
    2402              :          hxc_channel_valid, hxc_valid, projected_update_valid, shadow_pending, solve_valid
    2403              :       REAL(KIND=dp) :: accepted_cross, accepted_curvature, denominator, hxc_density_norm_sq, &
    2404              :          hxc_density_norm_sq_channel, hxc_response_work, hxc_response_work_channel, maxocc, &
    2405              :          response_cross, response_curvature_total, response_scale, shadow_curvature_total, sigma, &
    2406              :          tmp, unscaled_rotation_norm
    2407          664 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:) :: curvature_sum, energy_count, energy_mean, &
    2408          664 :          energy_metric_step, energy_shift, energy_weighted_sum, rayleigh_step, response_weight, &
    2409          664 :          rotation_count, rotation_norm, rotation_scale, schur_rhs, shadow_energy_mean, &
    2410          664 :          shadow_energy_metric_step, shadow_energy_weighted_sum, shadow_rayleigh_step, &
    2411          664 :          spin_rotation_gradient, vy
    2412          664 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :) :: channel_response_weight, &
    2413          664 :          channel_rotation_gradient, chc_im, chc_re, coupling, dense_im, dense_re, fixed_n_matrix, &
    2414          664 :          fixed_n_rhs, fixed_n_solution, generator_im, generator_re, previous_rotation_step, &
    2415          664 :          rayleigh_response, rhs, rotation_gradient, rotation_hessian, rotation_step, rotation_y, &
    2416          664 :          schur_block, solution, spin_rayleigh_response, spin_rotation_hessian, vz
    2417          664 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :, :)     :: channel_rayleigh_response, &
    2418          664 :                                                             channel_rotation_hessian, rotation_z
    2419              :       REAL(KIND=dp), DIMENSION(2) :: hxc_density_overlap, hxc_density_overlap_channel, &
    2420              :          hxc_response_overlap, hxc_response_overlap_channel, projected_coefficients, &
    2421              :          projected_gradient
    2422              :       REAL(KIND=dp), DIMENSION(2, 2)                     :: exact_hxc_correction, hxc_correction, &
    2423              :                                                             projected_hessian
    2424              :       TYPE(cp_fm_type)                                   :: mo_coeff, mo_coeff_im
    2425              :       TYPE(kpoint_env_type), POINTER                     :: kp
    2426              : 
    2427          664 :       nlocal_channels = SIZE(local_ot_env)
    2428         1698 :       DO local_channel = 1, nlocal_channels
    2429         1034 :          local_ot_env(local_channel)%rotation_response_valid = .FALSE.
    2430         1034 :          IF (ASSOCIATED(local_ot_env(local_channel)%rot_mat_response_gx)) THEN
    2431          794 :             CALL dbcsr_set(local_ot_env(local_channel)%rot_mat_response_gx, 0.0_dp)
    2432              :          END IF
    2433         1034 :          IF (ASSOCIATED(local_ot_env(local_channel)%rot_mat_response_gx_im)) THEN
    2434          794 :             CALL dbcsr_set(local_ot_env(local_channel)%rot_mat_response_gx_im, 0.0_dp)
    2435              :          END IF
    2436         1034 :          IF (ASSOCIATED(local_ot_env(local_channel)%ener_response_gx)) THEN
    2437         6022 :             local_ot_env(local_channel)%ener_response_gx(:) = 0.0_dp
    2438              :          END IF
    2439         1034 :          IF (ASSOCIATED(local_ot_env(local_channel)%matrix_response_gx)) THEN
    2440          606 :             CALL dbcsr_set(local_ot_env(local_channel)%matrix_response_gx, 0.0_dp)
    2441              :          END IF
    2442         1698 :          IF (ASSOCIATED(local_ot_env(local_channel)%matrix_response_gx_im)) THEN
    2443          606 :             CALL dbcsr_set(local_ot_env(local_channel)%matrix_response_gx_im, 0.0_dp)
    2444              :          END IF
    2445              :       END DO
    2446          664 :       local_ot_env(1)%response_model_curvature = 0.0_dp
    2447          664 :       local_ot_env(1)%response_shadow_curvature = 0.0_dp
    2448          664 :       local_ot_env(1)%response_hxc_direction_valid = .FALSE.
    2449              :       IF (.NOT. local_ot_env(1)%settings%occupation_preconditioner .OR. &
    2450          664 :           .NOT. local_ot_env(1)%settings%do_rotation .OR. &
    2451              :           .NOT. local_ot_env(1)%settings%do_ener) RETURN
    2452              :       ! The dense candidate is accepted through a physical line search. DIIS and Broyden use the
    2453              :       ! cheaper fixed-N response in their history residuals, but have no comparable accepted-step
    2454              :       ! model and therefore must not pay for an unused finite-response construction.
    2455          512 :       IF (local_ot_env(1)%settings%ot_method /= "CG" .AND. &
    2456              :           local_ot_env(1)%settings%ot_method /= "LBFG") RETURN
    2457              :       ! ROKS has one orbital generator but two physical spin-density and fixed-N energy blocks.
    2458              :       ! Keep those blocks separate until their response metrics have been accumulated.
    2459          404 :       IF (.NOT. ot_mermin_response_preparation_needed( &
    2460              :           local_ot_env(1)%delta, local_ot_env(1)%response_candidate_directions, &
    2461              :           local_ot_env(1)%response_shadow_good_samples, &
    2462              :           local_ot_env(1)%response_candidate_good_samples, &
    2463              :           local_ot_env(1)%response_candidate_cooldown, &
    2464              :           local_ot_env(1)%response_shadow_pending)) RETURN
    2465          224 :       CPASSERT(smear%do_smear)
    2466          224 :       CPASSERT(ASSOCIATED(para_env_inter_kp))
    2467          412 :       SELECT CASE (smear%method)
    2468              :       CASE (smear_fermi_dirac)
    2469          188 :          sigma = smear%electronic_temperature
    2470              :       CASE (smear_gaussian, smear_mp, smear_mv)
    2471           36 :          sigma = smear%smearing_width
    2472              :       CASE DEFAULT
    2473          224 :          RETURN
    2474              :       END SELECT
    2475          224 :       CPASSERT(sigma > EPSILON(sigma))
    2476              : 
    2477          224 :       nmo = SIZE(trial_eigenvalues, 1)
    2478          224 :       nspin_energy = SIZE(trial_eigenvalues, 3)
    2479          224 :       nenergy = SIZE(local_ot_env(1)%ener_x)
    2480          224 :       CPASSERT(SIZE(trial_occupation, 1) == nmo)
    2481          224 :       CPASSERT(SIZE(trial_occupation, 3) == nspin_energy)
    2482          224 :       CPASSERT(nenergy == nmo*nspin_energy/nspin_ot)
    2483          224 :       nrotation = nmo*(nmo - 1)
    2484          224 :       IF (nrotation <= 0 .OR. nrotation > finite_response_max_rotation) RETURN
    2485          565 :       DO local_channel = 1, nlocal_channels
    2486          341 :          CPASSERT(local_ot_env(local_channel)%has_complex_kpoint_state)
    2487          341 :          CPASSERT(SIZE(local_ot_env(local_channel)%ener_x) == nenergy)
    2488          341 :          CPASSERT(ASSOCIATED(local_ot_env(local_channel)%rot_mat_response_gx))
    2489          341 :          CPASSERT(ASSOCIATED(local_ot_env(local_channel)%rot_mat_response_gx_im))
    2490          565 :          CPASSERT(ASSOCIATED(local_ot_env(local_channel)%ener_response_gx))
    2491              :       END DO
    2492              : 
    2493          224 :       ngroups = 1
    2494          224 :       IF (restricted_roks) THEN
    2495              :          ngroups = nspin_energy
    2496          210 :       ELSE IF (nspin_ot == 2 .AND. smearing_separate_spin(smear%fixed_mag_mom)) THEN
    2497           28 :          ngroups = 2
    2498              :       END IF
    2499          224 :       nrotation_groups = ngroups
    2500          224 :       IF (restricted_roks) nrotation_groups = 1
    2501          224 :       shadow_pending = local_ot_env(1)%response_shadow_pending
    2502              :       ALLOCATE (coupling(nrotation, ngroups), curvature_sum(ngroups), energy_count(ngroups), &
    2503              :                 energy_mean(ngroups), energy_metric_step(nenergy), energy_shift(ngroups), &
    2504              :                 energy_weighted_sum(ngroups), rayleigh_step(nenergy), response_weight(nmo), &
    2505              :                 rotation_count(nrotation_groups), rotation_norm(nrotation_groups), &
    2506              :                 rotation_scale(nrotation_groups), schur_rhs(nrotation), &
    2507              :                 shadow_energy_mean(ngroups), shadow_energy_metric_step(nenergy), &
    2508              :                 shadow_energy_weighted_sum(ngroups), shadow_rayleigh_step(nenergy), &
    2509              :                 vy(ngroups), vz(ngroups, ngroups), rayleigh_response(nenergy, nrotation), &
    2510              :                 rhs(nrotation, ngroups + 1), rotation_gradient(nrotation, 1), &
    2511              :                 rotation_hessian(nrotation, nrotation), &
    2512              :                 spin_rotation_gradient(nrotation), &
    2513              :                 spin_rayleigh_response(nmo, nrotation), &
    2514              :                 spin_rotation_hessian(nrotation, nrotation), &
    2515              :                 previous_rotation_step(nrotation, nlocal_channels), &
    2516              :                 rotation_step(nrotation, nlocal_channels), &
    2517              :                 rotation_y(nrotation, nlocal_channels), rotation_z(nrotation, nlocal_channels, ngroups), &
    2518              :                 schur_block(nrotation, nrotation), solution(nrotation, ngroups + 1), &
    2519              :                 fixed_n_matrix(ngroups, ngroups), fixed_n_rhs(ngroups, 1), &
    2520              :                 fixed_n_solution(ngroups, 1), &
    2521              :                 channel_rayleigh_response(nenergy, nrotation, nlocal_channels), &
    2522              :                 channel_rotation_hessian(nrotation, nrotation, nlocal_channels), &
    2523              :                 channel_rotation_gradient(nrotation, nlocal_channels), &
    2524              :                 channel_response_weight(nenergy, nlocal_channels), &
    2525              :                 channel_response_group(nenergy, nlocal_channels), &
    2526        19712 :                 channel_generator(nmo, nmo, nlocal_channels), density_modes(nmo, nmo, 2))
    2527         1120 :       ALLOCATE (channel_density_modes(nmo, nmo, 2, nlocal_channels))
    2528          224 :       curvature_sum(:) = 0.0_dp
    2529          224 :       vy(:) = 0.0_dp
    2530          224 :       vz(:, :) = 0.0_dp
    2531          224 :       rotation_y(:, :) = 0.0_dp
    2532          224 :       rotation_z(:, :, :) = 0.0_dp
    2533          224 :       previous_rotation_step(:, :) = 0.0_dp
    2534          224 :       channel_rayleigh_response(:, :, :) = 0.0_dp
    2535          224 :       channel_rotation_hessian(:, :, :) = 0.0_dp
    2536          224 :       channel_rotation_gradient(:, :) = 0.0_dp
    2537          224 :       channel_response_weight(:, :) = 0.0_dp
    2538          224 :       channel_response_group(:, :) = 0
    2539          224 :       channel_generator(:, :, :) = CMPLX(0.0_dp, 0.0_dp, KIND=dp)
    2540          224 :       channel_density_modes(:, :, :, :) = CMPLX(0.0_dp, 0.0_dp, KIND=dp)
    2541          224 :       failure = 0
    2542          224 :       response_cross = 0.0_dp
    2543              : 
    2544          531 :       DO local_kpoint = 1, SIZE(kpoints%kp_env)
    2545          307 :          kp => kpoints%kp_env(local_kpoint)%kpoint_env
    2546          307 :          ikpoint = kp%nkpoint
    2547          872 :          DO ispin = 1, nspin_ot
    2548          341 :             group = MERGE(ispin, 1, ngroups == nspin_ot)
    2549          341 :             local_channel = qs_ot_channel_index(ispin, ikpoint, nspin_ot) - first_channel + 1
    2550              :             CALL qs_scf_loop_ot_matrix_to_dense( &
    2551          341 :                local_ot_env(local_channel)%rot_mat_x, local_ot_env(local_channel), generator_re)
    2552              :             CALL qs_scf_loop_ot_matrix_to_dense( &
    2553          341 :                local_ot_env(local_channel)%rot_mat_x_im, local_ot_env(local_channel), generator_im)
    2554         1364 :             ALLOCATE (generator(nmo, nmo))
    2555        13335 :             generator(:, :) = CMPLX(generator_re, generator_im, KIND=dp)
    2556        13335 :             channel_generator(:, :, local_channel) = generator
    2557         9707 :             rotation_gradient(:, 1) = 0.0_dp
    2558          341 :             rotation_hessian(:, :) = 0.0_dp
    2559          341 :             rayleigh_response(:, :) = 0.0_dp
    2560              : 
    2561          341 :             IF (restricted_roks) THEN
    2562           14 :                IF (.NOT. (ASSOCIATED(kp%ot_hmat) .AND. SIZE(kp%ot_hmat, 2) >= nspin_energy)) THEN
    2563            0 :                   CALL cp_abort(__LOCATION__, "Missing OT Hamiltonian spin cache")
    2564              :                END IF
    2565           14 :                CALL cp_fm_create(mo_coeff, kp%mos(1)%cmo_coeff%matrix_struct)
    2566           14 :                CALL cp_fm_create(mo_coeff_im, kp%mos(1)%cmo_coeff%matrix_struct)
    2567           14 :                CALL cp_cfm_to_fm(kp%mos(1)%cmo_coeff, mo_coeff, mo_coeff_im)
    2568           42 :                DO energy_spin = 1, nspin_energy
    2569           28 :                   energy_start = (energy_spin - 1)*nmo + 1
    2570           28 :                   energy_stop = energy_start + nmo - 1
    2571           28 :                   group = energy_spin
    2572           28 :                   CALL get_mo_set(kp%mos(energy_spin), maxocc=maxocc)
    2573           28 :                   CPASSERT(maxocc > EPSILON(maxocc))
    2574              :                   CALL smearing_response_weight( &
    2575              :                      response_weight, trial_occupation(:, ikpoint, energy_spin), &
    2576              :                      trial_eigenvalues(:, ikpoint, energy_spin), trial_mu(energy_spin), &
    2577           28 :                      sigma, maxocc, nmo, smear%method)
    2578          308 :                   response_weight(:) = wkp(ikpoint)*response_weight
    2579          308 :                   curvature_sum(group) = curvature_sum(group) + SUM(response_weight)
    2580          308 :                   channel_response_weight(energy_start:energy_stop, local_channel) = response_weight
    2581          308 :                   channel_response_group(energy_start:energy_stop, local_channel) = group
    2582              : 
    2583           84 :                   ALLOCATE (chc(nmo, nmo))
    2584              :                   CALL qs_scf_kp_project_hamiltonian( &
    2585              :                      mo_coeff, mo_coeff_im, kp%ot_hmat(1, energy_spin), &
    2586           28 :                      kp%ot_hmat(2, energy_spin), chc)
    2587              :                   CALL qs_ot_finite_rotation_response( &
    2588              :                      chc, generator, trial_occupation(:, ikpoint, energy_spin), wkp(ikpoint), &
    2589           28 :                      spin_rotation_gradient, spin_rotation_hessian, spin_rayleigh_response)
    2590         2548 :                   rotation_gradient(:, 1) = rotation_gradient(:, 1) + spin_rotation_gradient
    2591       229348 :                   rotation_hessian(:, :) = rotation_hessian + spin_rotation_hessian
    2592        27748 :                   rayleigh_response(energy_start:energy_stop, :) = spin_rayleigh_response
    2593           70 :                   DEALLOCATE (chc)
    2594              :                END DO
    2595           14 :                CALL cp_fm_release(mo_coeff)
    2596           14 :                CALL cp_fm_release(mo_coeff_im)
    2597              :             ELSE
    2598          327 :                CALL get_mo_set(kp%mos(ispin), maxocc=maxocc)
    2599          327 :                CPASSERT(maxocc > EPSILON(maxocc))
    2600              :                CALL smearing_response_weight( &
    2601              :                   response_weight, trial_occupation(:, ikpoint, ispin), &
    2602              :                   trial_eigenvalues(:, ikpoint, ispin), trial_mu(ispin), sigma, maxocc, nmo, &
    2603          327 :                   smear%method)
    2604         2001 :                response_weight(:) = wkp(ikpoint)*response_weight
    2605         2001 :                curvature_sum(group) = curvature_sum(group) + SUM(response_weight)
    2606         2001 :                channel_response_weight(:, local_channel) = response_weight
    2607         2001 :                channel_response_group(:, local_channel) = group
    2608              :                CALL qs_scf_loop_ot_matrix_to_dense( &
    2609          327 :                   local_ot_env(local_channel)%rot_mat_chc, local_ot_env(local_channel), chc_re)
    2610              :                CALL qs_scf_loop_ot_matrix_to_dense( &
    2611          327 :                   local_ot_env(local_channel)%rot_mat_chc_im, local_ot_env(local_channel), chc_im)
    2612          981 :                ALLOCATE (chc(nmo, nmo))
    2613        11781 :                chc(:, :) = CMPLX(chc_re, chc_im, KIND=dp)
    2614              :                CALL qs_ot_finite_rotation_response( &
    2615              :                   chc, generator, trial_occupation(:, ikpoint, ispin), wkp(ikpoint), &
    2616          327 :                   rotation_gradient(:, 1), rotation_hessian, rayleigh_response)
    2617          654 :                DEALLOCATE (chc, chc_im, chc_re)
    2618              :             END IF
    2619         9707 :             channel_rotation_gradient(:, local_channel) = rotation_gradient(:, 1)
    2620       479663 :             channel_rotation_hessian(:, :, local_channel) = rotation_hessian
    2621              :             CALL qs_ot_fixed_n_multigroup_schur_block( &
    2622              :                rotation_hessian, rayleigh_response, channel_response_weight(:, local_channel), &
    2623              :                channel_response_group(:, local_channel), rotation_gradient(:, 1), &
    2624          341 :                local_ot_env(local_channel)%ener_gx, schur_block, coupling, schur_rhs)
    2625         9707 :             rhs(:, 1) = schur_rhs
    2626          752 :             DO group = 1, ngroups
    2627        12050 :                rhs(:, group + 1) = coupling(:, group)
    2628              :             END DO
    2629              :             CALL qs_ot_symmetric_abs_solve( &
    2630          341 :                schur_block, rhs, solution, solve_valid, relative_floor=1.0E-4_dp)
    2631          341 :             IF (solve_valid) THEN
    2632         9563 :                rotation_y(:, local_channel) = solution(:, 1)
    2633          704 :                DO group = 1, ngroups
    2634        11882 :                   rotation_z(:, local_channel, group) = solution(:, group + 1)
    2635              :                END DO
    2636        89315 :                channel_rayleigh_response(:, :, local_channel) = rayleigh_response
    2637          704 :                DO group = 1, ngroups
    2638        11565 :                   vy(group) = vy(group) + DOT_PRODUCT(coupling(:, group), solution(:, 1))
    2639         1231 :                   DO j = 1, ngroups
    2640              :                      vz(group, j) = vz(group, j) + &
    2641        15956 :                                     DOT_PRODUCT(coupling(:, group), solution(:, j + 1))
    2642              :                   END DO
    2643              :                END DO
    2644              :             ELSE
    2645           24 :                failure = 1
    2646              :             END IF
    2647          341 :             IF (shadow_pending .AND. local_ot_env(local_channel)%use_dx) THEN
    2648              :                CALL qs_scf_loop_ot_matrix_to_dense( &
    2649          194 :                   local_ot_env(local_channel)%rot_mat_dx, local_ot_env(local_channel), dense_re)
    2650              :                CALL qs_scf_loop_ot_matrix_to_dense( &
    2651          194 :                   local_ot_env(local_channel)%rot_mat_dx_im, local_ot_env(local_channel), dense_im)
    2652          194 :                r = 0
    2653         1164 :                DO i = 1, nmo - 1
    2654         4458 :                   DO j = i + 1, nmo
    2655         3294 :                      r = r + 1
    2656         3294 :                      previous_rotation_step(r, local_channel) = dense_re(i, j)
    2657         3294 :                      r = r + 1
    2658         4264 :                      previous_rotation_step(r, local_channel) = dense_im(i, j)
    2659              :                   END DO
    2660              :                END DO
    2661          194 :                CPASSERT(r == nrotation)
    2662          194 :                DEALLOCATE (dense_im, dense_re)
    2663              :             END IF
    2664          648 :             DEALLOCATE (generator, generator_im, generator_re)
    2665              :          END DO
    2666              :       END DO
    2667              : 
    2668          224 :       CALL para_env_inter_kp%sum(curvature_sum)
    2669          224 :       CALL para_env_inter_kp%sum(vy)
    2670          224 :       CALL para_env_inter_kp%sum(vz)
    2671          224 :       CALL para_env_inter_kp%sum(failure)
    2672          224 :       IF (failure /= 0) THEN
    2673            0 :          DEALLOCATE (coupling, curvature_sum, energy_count, energy_mean, energy_metric_step, &
    2674            0 :                      energy_shift, energy_weighted_sum, rayleigh_step, response_weight, &
    2675            0 :                      shadow_energy_mean, &
    2676            0 :                      shadow_energy_metric_step, shadow_energy_weighted_sum, shadow_rayleigh_step, &
    2677            0 :                      rotation_count, rotation_norm, rotation_scale, schur_rhs, vy, vz, &
    2678            0 :                      rayleigh_response, rhs, rotation_gradient, rotation_hessian, &
    2679            0 :                      spin_rotation_gradient, spin_rotation_hessian, spin_rayleigh_response, &
    2680            0 :                      previous_rotation_step, rotation_step, &
    2681            0 :                      rotation_y, rotation_z, schur_block, solution, channel_rayleigh_response, &
    2682            0 :                      channel_rotation_hessian, channel_rotation_gradient, channel_response_weight, &
    2683            0 :                      channel_density_modes, channel_response_group, channel_generator, &
    2684            0 :                      fixed_n_matrix, fixed_n_rhs, &
    2685            0 :                      fixed_n_solution, &
    2686           30 :                      density_modes)
    2687           30 :          RETURN
    2688              :       END IF
    2689              : 
    2690          750 :       fixed_n_matrix(:, :) = 0.5_dp*(vz + TRANSPOSE(vz))
    2691          430 :       DO group = 1, ngroups
    2692          430 :          fixed_n_matrix(group, group) = fixed_n_matrix(group, group) + curvature_sum(group)
    2693              :       END DO
    2694          430 :       fixed_n_rhs(:, 1) = vy
    2695          430 :       fixed_n_solution(:, 1) = 0.0_dp
    2696          194 :       solve_valid = .FALSE.
    2697          194 :       IF (ngroups == 1) THEN
    2698          152 :          denominator = fixed_n_matrix(1, 1)
    2699          152 :          solve_valid = ABS(denominator) > EPSILON(denominator)
    2700          152 :          IF (solve_valid) fixed_n_solution(1, 1) = fixed_n_rhs(1, 1)/denominator
    2701           42 :       ELSE IF (ngroups == 2) THEN
    2702              :          denominator = fixed_n_matrix(1, 1)*fixed_n_matrix(2, 2) - &
    2703           42 :                        fixed_n_matrix(1, 2)*fixed_n_matrix(2, 1)
    2704              :          solve_valid = ABS(denominator) > EPSILON(denominator)* &
    2705          294 :                        MAX(1.0_dp, MAXVAL(ABS(fixed_n_matrix))**2)
    2706           42 :          IF (solve_valid) THEN
    2707              :             fixed_n_solution(1, 1) = (fixed_n_matrix(2, 2)*fixed_n_rhs(1, 1) - &
    2708           28 :                                       fixed_n_matrix(1, 2)*fixed_n_rhs(2, 1))/denominator
    2709              :             fixed_n_solution(2, 1) = (fixed_n_matrix(1, 1)*fixed_n_rhs(2, 1) - &
    2710           28 :                                       fixed_n_matrix(2, 1)*fixed_n_rhs(1, 1))/denominator
    2711              :          END IF
    2712              :       END IF
    2713          624 :       IF (.NOT. solve_valid .OR. .NOT. ALL(fixed_n_solution == fixed_n_solution)) THEN
    2714            0 :          DEALLOCATE (coupling, curvature_sum, energy_count, energy_mean, energy_metric_step, &
    2715            0 :                      energy_shift, energy_weighted_sum, rayleigh_step, response_weight, &
    2716            0 :                      shadow_energy_mean, shadow_energy_metric_step, shadow_energy_weighted_sum, &
    2717            0 :                      shadow_rayleigh_step, rotation_count, rotation_norm, rotation_scale, &
    2718            0 :                      schur_rhs, vy, vz, rayleigh_response, rhs, rotation_gradient, rotation_hessian, &
    2719            0 :                      spin_rotation_gradient, spin_rotation_hessian, spin_rayleigh_response, &
    2720            0 :                      previous_rotation_step, rotation_step, rotation_y, rotation_z, schur_block, &
    2721            0 :                      solution, channel_rayleigh_response, channel_rotation_hessian, &
    2722            0 :                      channel_rotation_gradient, channel_response_weight, channel_response_group, &
    2723           14 :                      channel_generator, fixed_n_matrix, fixed_n_rhs, fixed_n_solution, density_modes)
    2724           14 :          RETURN
    2725              :       END IF
    2726              : 
    2727          180 :       rotation_norm(:) = 0.0_dp
    2728          180 :       rotation_count(:) = 0.0_dp
    2729          431 :       DO local_kpoint = 1, SIZE(kpoints%kp_env)
    2730          251 :          kp => kpoints%kp_env(local_kpoint)%kpoint_env
    2731          251 :          ikpoint = kp%nkpoint
    2732          696 :          DO ispin = 1, nspin_ot
    2733          265 :             rotation_group = MERGE(ispin, 1, nrotation_groups == nspin_ot)
    2734          265 :             local_channel = qs_ot_channel_index(ispin, ikpoint, nspin_ot) - first_channel + 1
    2735         9055 :             rotation_step(:, local_channel) = rotation_y(:, local_channel)
    2736          572 :             DO group = 1, ngroups
    2737              :                rotation_step(:, local_channel) = rotation_step(:, local_channel) - &
    2738              :                                                  rotation_z(:, local_channel, group)* &
    2739        10958 :                                                  fixed_n_solution(group, 1)
    2740              :             END DO
    2741              :             rotation_norm(rotation_group) = rotation_norm(rotation_group) + &
    2742              :                                             DOT_PRODUCT(rotation_step(:, local_channel), &
    2743         9055 :                                                         rotation_step(:, local_channel))
    2744          516 :             rotation_count(rotation_group) = rotation_count(rotation_group) + REAL(nrotation, KIND=dp)
    2745              :          END DO
    2746              :       END DO
    2747          180 :       CALL para_env_inter_kp%sum(rotation_norm)
    2748          180 :       CALL para_env_inter_kp%sum(rotation_count)
    2749          374 :       rotation_scale(:) = 1.0_dp
    2750          374 :       DO group = 1, nrotation_groups
    2751          374 :          IF (rotation_norm(group) > EPSILON(rotation_norm(group))) THEN
    2752              :             rotation_scale(group) = MIN( &
    2753          194 :                                     1.0_dp, rotation_trust_rms*SQRT(rotation_count(group)/rotation_norm(group)))
    2754              :          END IF
    2755              :       END DO
    2756              : 
    2757          180 :       energy_shift(:) = 0.0_dp
    2758          180 :       energy_count(:) = 0.0_dp
    2759          431 :       DO local_kpoint = 1, SIZE(kpoints%kp_env)
    2760          251 :          kp => kpoints%kp_env(local_kpoint)%kpoint_env
    2761          251 :          ikpoint = kp%nkpoint
    2762          696 :          DO ispin = 1, nspin_ot
    2763          265 :             rotation_group = MERGE(ispin, 1, nrotation_groups == nspin_ot)
    2764          265 :             local_channel = qs_ot_channel_index(ispin, ikpoint, nspin_ot) - first_channel + 1
    2765              :             rotation_step(:, local_channel) = &
    2766         9055 :                rotation_scale(rotation_group)*rotation_step(:, local_channel)
    2767              :             local_ot_env(local_channel)%ener_response_gx(:) = &
    2768              :                local_ot_env(local_channel)%ener_preconditioned_gx + &
    2769              :                MATMUL(channel_rayleigh_response(:, :, local_channel), &
    2770        90535 :                       rotation_step(:, local_channel))
    2771         1975 :             DO i = 1, nenergy
    2772         1710 :                group = channel_response_group(i, local_channel)
    2773              :                energy_shift(group) = energy_shift(group) + &
    2774         1710 :                                      local_ot_env(local_channel)%ener_response_gx(i)
    2775         1975 :                energy_count(group) = energy_count(group) + 1.0_dp
    2776              :             END DO
    2777              : 
    2778         1590 :             ALLOCATE (dense_re(nmo, nmo), dense_im(nmo, nmo))
    2779          265 :             dense_re(:, :) = 0.0_dp
    2780          265 :             dense_im(:, :) = 0.0_dp
    2781          265 :             r = 0
    2782         1570 :             DO i = 1, nmo - 1
    2783         5965 :                DO j = i + 1, nmo
    2784         4395 :                   r = r + 1
    2785         4395 :                   dense_re(i, j) = rotation_step(r, local_channel)
    2786         4395 :                   dense_re(j, i) = -rotation_step(r, local_channel)
    2787         4395 :                   r = r + 1
    2788         4395 :                   dense_im(i, j) = rotation_step(r, local_channel)
    2789         5700 :                   dense_im(j, i) = rotation_step(r, local_channel)
    2790              :                END DO
    2791              :             END DO
    2792          265 :             CPASSERT(r == nrotation)
    2793              :             CALL qs_scf_loop_ot_dense_to_matrix( &
    2794              :                dense_re, local_ot_env(local_channel), &
    2795          265 :                local_ot_env(local_channel)%rot_mat_response_gx)
    2796              :             CALL qs_scf_loop_ot_dense_to_matrix( &
    2797              :                dense_im, local_ot_env(local_channel), &
    2798          265 :                local_ot_env(local_channel)%rot_mat_response_gx_im)
    2799          265 :             local_ot_env(local_channel)%rotation_response_valid = .TRUE.
    2800          516 :             DEALLOCATE (dense_im, dense_re)
    2801              :          END DO
    2802              :       END DO
    2803          180 :       CALL para_env_inter_kp%sum(energy_shift)
    2804          180 :       CALL para_env_inter_kp%sum(energy_count)
    2805          431 :       DO local_kpoint = 1, SIZE(kpoints%kp_env)
    2806          251 :          kp => kpoints%kp_env(local_kpoint)%kpoint_env
    2807          251 :          ikpoint = kp%nkpoint
    2808          696 :          DO ispin = 1, nspin_ot
    2809          265 :             local_channel = qs_ot_channel_index(ispin, ikpoint, nspin_ot) - first_channel + 1
    2810         2226 :             DO i = 1, nenergy
    2811         1710 :                group = channel_response_group(i, local_channel)
    2812         1975 :                IF (energy_count(group) > 0.0_dp) THEN
    2813              :                   local_ot_env(local_channel)%ener_response_gx(i) = &
    2814              :                      local_ot_env(local_channel)%ener_response_gx(i) - &
    2815         1710 :                      energy_shift(group)/energy_count(group)
    2816              :                END IF
    2817              :             END DO
    2818              :          END DO
    2819              :       END DO
    2820              : 
    2821              :       ! The accepted gradient difference supplies the missing total cross curvature between the
    2822              :       ! finite rotation/energy candidate and the preceding accepted product direction.  Keep the
    2823              :       ! dedicated endpoint history separate from CG's preconditioned-gradient history.
    2824          180 :       accepted_cross = 0.0_dp
    2825          180 :       accepted_cross_valid = .FALSE.
    2826          180 :       gradient_secant_failure = 0
    2827          180 :       IF (shadow_pending .AND. ABS(local_ot_env(1)%ds_min) > SQRT(EPSILON(1.0_dp))) THEN
    2828          318 :          DO local_kpoint = 1, SIZE(kpoints%kp_env)
    2829          184 :             kp => kpoints%kp_env(local_kpoint)%kpoint_env
    2830          184 :             ikpoint = kp%nkpoint
    2831          512 :             DO ispin = 1, nspin_ot
    2832          194 :                local_channel = qs_ot_channel_index(ispin, ikpoint, nspin_ot) - first_channel + 1
    2833              :                IF (local_ot_env(local_channel)%mermin_gradient_ref_valid .AND. &
    2834              :                    ASSOCIATED(local_ot_env(local_channel)%rot_mat_mermin_g0) .AND. &
    2835          194 :                    ASSOCIATED(local_ot_env(local_channel)%rot_mat_mermin_g0_im) .AND. &
    2836          184 :                    ALLOCATED(local_ot_env(local_channel)%ener_mermin_g0)) THEN
    2837              :                   CALL dbcsr_dot(local_ot_env(local_channel)%rot_mat_gx, &
    2838          194 :                                  local_ot_env(local_channel)%rot_mat_response_gx, tmp)
    2839          194 :                   accepted_cross = accepted_cross + 0.5_dp*tmp
    2840              :                   CALL dbcsr_dot(local_ot_env(local_channel)%rot_mat_mermin_g0, &
    2841          194 :                                  local_ot_env(local_channel)%rot_mat_response_gx, tmp)
    2842          194 :                   accepted_cross = accepted_cross - 0.5_dp*tmp
    2843              :                   CALL dbcsr_dot(local_ot_env(local_channel)%rot_mat_gx_im, &
    2844          194 :                                  local_ot_env(local_channel)%rot_mat_response_gx_im, tmp)
    2845          194 :                   accepted_cross = accepted_cross + 0.5_dp*tmp
    2846              :                   CALL dbcsr_dot(local_ot_env(local_channel)%rot_mat_mermin_g0_im, &
    2847          194 :                                  local_ot_env(local_channel)%rot_mat_response_gx_im, tmp)
    2848          194 :                   accepted_cross = accepted_cross - 0.5_dp*tmp
    2849              :                   accepted_cross = accepted_cross + &
    2850              :                                    DOT_PRODUCT( &
    2851              :                                    local_ot_env(local_channel)%ener_gx - &
    2852              :                                    local_ot_env(local_channel)%ener_mermin_g0, &
    2853         1458 :                                    local_ot_env(local_channel)%ener_response_gx)
    2854              :                ELSE
    2855            0 :                   gradient_secant_failure = 1
    2856              :                END IF
    2857              :             END DO
    2858              :          END DO
    2859          134 :          CALL para_env_inter_kp%sum(accepted_cross)
    2860          134 :          CALL para_env_inter_kp%sum(gradient_secant_failure)
    2861          134 :          IF (gradient_secant_failure == 0) THEN
    2862          134 :             accepted_cross = accepted_cross/local_ot_env(1)%ds_min
    2863          134 :             accepted_cross_valid = ieee_is_finite(accepted_cross)
    2864              :          END IF
    2865              :       END IF
    2866              :       ! Evaluate the signed finite response in the same fixed-N tangent used to build the Schur
    2867              :       ! step. This is a prediction only; the minimizer calibrates it against accepted Mermin drops
    2868              :       ! before the candidate can be reused.
    2869          180 :       energy_weighted_sum(:) = 0.0_dp
    2870          431 :       DO local_kpoint = 1, SIZE(kpoints%kp_env)
    2871          251 :          kp => kpoints%kp_env(local_kpoint)%kpoint_env
    2872          251 :          ikpoint = kp%nkpoint
    2873          696 :          DO ispin = 1, nspin_ot
    2874          265 :             local_channel = qs_ot_channel_index(ispin, ikpoint, nspin_ot) - first_channel + 1
    2875         2226 :             DO i = 1, nenergy
    2876         1710 :                group = channel_response_group(i, local_channel)
    2877              :                energy_weighted_sum(group) = energy_weighted_sum(group) + &
    2878              :                                             channel_response_weight(i, local_channel)* &
    2879         1975 :                                             local_ot_env(local_channel)%ener_response_gx(i)
    2880              :             END DO
    2881              :          END DO
    2882              :       END DO
    2883          180 :       CALL para_env_inter_kp%sum(energy_weighted_sum)
    2884          180 :       energy_mean(:) = 0.0_dp
    2885          388 :       DO group = 1, ngroups
    2886          388 :          IF (ABS(curvature_sum(group)) > EPSILON(curvature_sum(group))) THEN
    2887          208 :             energy_mean(group) = energy_weighted_sum(group)/curvature_sum(group)
    2888              :          END IF
    2889              :       END DO
    2890              : 
    2891          180 :       response_curvature_total = 0.0_dp
    2892          431 :       DO local_kpoint = 1, SIZE(kpoints%kp_env)
    2893          251 :          kp => kpoints%kp_env(local_kpoint)%kpoint_env
    2894          251 :          ikpoint = kp%nkpoint
    2895          696 :          DO ispin = 1, nspin_ot
    2896          265 :             local_channel = qs_ot_channel_index(ispin, ikpoint, nspin_ot) - first_channel + 1
    2897         1975 :             DO i = 1, nenergy
    2898         1710 :                group = channel_response_group(i, local_channel)
    2899              :                energy_metric_step(i) = channel_response_weight(i, local_channel)* &
    2900              :                                        (local_ot_env(local_channel)%ener_response_gx(i) - &
    2901         1975 :                                         energy_mean(group))
    2902              :             END DO
    2903              :             rayleigh_step(:) = MATMUL(channel_rayleigh_response(:, :, local_channel), &
    2904        87115 :                                       rotation_step(:, local_channel))
    2905              :             response_curvature_total = response_curvature_total + &
    2906              :                                        DOT_PRODUCT(rotation_step(:, local_channel), &
    2907          795 :                                                    MATMUL(channel_rotation_hessian(:, :, local_channel), &
    2908              :                                                           rotation_step(:, local_channel))) - &
    2909              :                                        2.0_dp*DOT_PRODUCT(rayleigh_step, energy_metric_step) + &
    2910       486096 :                                        DOT_PRODUCT(local_ot_env(local_channel)%ener_response_gx, energy_metric_step)
    2911              :          END DO
    2912              :       END DO
    2913          180 :       CALL para_env_inter_kp%sum(response_curvature_total)
    2914          180 :       local_ot_env(1)%response_model_curvature = response_curvature_total
    2915              : 
    2916          180 :       IF (shadow_pending) THEN
    2917          134 :          shadow_energy_weighted_sum(:) = 0.0_dp
    2918          318 :          DO local_kpoint = 1, SIZE(kpoints%kp_env)
    2919          184 :             kp => kpoints%kp_env(local_kpoint)%kpoint_env
    2920          184 :             ikpoint = kp%nkpoint
    2921          512 :             DO ispin = 1, nspin_ot
    2922          194 :                local_channel = qs_ot_channel_index(ispin, ikpoint, nspin_ot) - first_channel + 1
    2923         1642 :                DO i = 1, nenergy
    2924         1264 :                   group = channel_response_group(i, local_channel)
    2925              :                   shadow_energy_weighted_sum(group) = shadow_energy_weighted_sum(group) + &
    2926              :                                                       channel_response_weight(i, local_channel)* &
    2927         1458 :                                                       local_ot_env(local_channel)%ener_dx(i)
    2928              :                END DO
    2929              :             END DO
    2930              :          END DO
    2931          134 :          CALL para_env_inter_kp%sum(shadow_energy_weighted_sum)
    2932          134 :          shadow_energy_mean(:) = 0.0_dp
    2933          288 :          DO group = 1, ngroups
    2934          288 :             IF (ABS(curvature_sum(group)) > EPSILON(curvature_sum(group))) THEN
    2935          154 :                shadow_energy_mean(group) = shadow_energy_weighted_sum(group)/curvature_sum(group)
    2936              :             END IF
    2937              :          END DO
    2938              : 
    2939          134 :          shadow_curvature_total = 0.0_dp
    2940          134 :          projected_gradient(:) = 0.0_dp
    2941          318 :          DO local_kpoint = 1, SIZE(kpoints%kp_env)
    2942          184 :             kp => kpoints%kp_env(local_kpoint)%kpoint_env
    2943          184 :             ikpoint = kp%nkpoint
    2944          512 :             DO ispin = 1, nspin_ot
    2945          194 :                local_channel = qs_ot_channel_index(ispin, ikpoint, nspin_ot) - first_channel + 1
    2946         1458 :                DO i = 1, nenergy
    2947         1264 :                   group = channel_response_group(i, local_channel)
    2948              :                   energy_metric_step(i) = channel_response_weight(i, local_channel)* &
    2949              :                                           (local_ot_env(local_channel)%ener_response_gx(i) - &
    2950         1264 :                                            energy_mean(group))
    2951              :                   shadow_energy_metric_step(i) = channel_response_weight(i, local_channel)* &
    2952              :                                                  (local_ot_env(local_channel)%ener_dx(i) - &
    2953         1458 :                                                   shadow_energy_mean(group))
    2954              :                END DO
    2955              :                rayleigh_step(:) = MATMUL(channel_rayleigh_response(:, :, local_channel), &
    2956        65054 :                                          rotation_step(:, local_channel))
    2957              :                shadow_rayleigh_step(:) = MATMUL( &
    2958              :                                          channel_rayleigh_response(:, :, local_channel), &
    2959        65054 :                                          previous_rotation_step(:, local_channel))
    2960              :                shadow_curvature_total = shadow_curvature_total + &
    2961              :                                         DOT_PRODUCT(previous_rotation_step(:, local_channel), &
    2962          582 :                                                     MATMUL(channel_rotation_hessian(:, :, local_channel), &
    2963              :                                                            previous_rotation_step(:, local_channel))) - &
    2964              :                                         2.0_dp*DOT_PRODUCT(shadow_rayleigh_step, &
    2965              :                                                            shadow_energy_metric_step) + &
    2966              :                                         DOT_PRODUCT(local_ot_env(local_channel)%ener_dx, &
    2967       366034 :                                                     shadow_energy_metric_step)
    2968              :                response_cross = response_cross + &
    2969              :                                 DOT_PRODUCT(rotation_step(:, local_channel), &
    2970          582 :                                             MATMUL(channel_rotation_hessian(:, :, local_channel), &
    2971              :                                                    previous_rotation_step(:, local_channel))) - &
    2972              :                                 DOT_PRODUCT(rayleigh_step, shadow_energy_metric_step) - &
    2973              :                                 DOT_PRODUCT(shadow_rayleigh_step, energy_metric_step) + &
    2974              :                                 0.5_dp*( &
    2975              :                                 DOT_PRODUCT(local_ot_env(local_channel)%ener_response_gx, &
    2976              :                                             shadow_energy_metric_step) + &
    2977       368562 :                                 DOT_PRODUCT(local_ot_env(local_channel)%ener_dx, energy_metric_step))
    2978              :                projected_gradient(1) = projected_gradient(1) + &
    2979              :                                        DOT_PRODUCT(channel_rotation_gradient(:, local_channel), &
    2980              :                                                    rotation_step(:, local_channel)) + &
    2981              :                                        DOT_PRODUCT(local_ot_env(local_channel)%ener_gx, &
    2982         8046 :                                                    local_ot_env(local_channel)%ener_response_gx)
    2983              :                CALL dbcsr_dot(local_ot_env(local_channel)%matrix_gx, &
    2984          194 :                               local_ot_env(local_channel)%matrix_dx, tmp)
    2985          194 :                projected_gradient(2) = projected_gradient(2) + tmp
    2986              :                CALL dbcsr_dot(local_ot_env(local_channel)%matrix_gx_im, &
    2987          194 :                               local_ot_env(local_channel)%matrix_dx_im, tmp)
    2988          194 :                projected_gradient(2) = projected_gradient(2) + tmp
    2989              :                projected_gradient(2) = projected_gradient(2) + &
    2990              :                                        DOT_PRODUCT(channel_rotation_gradient(:, local_channel), &
    2991              :                                                    previous_rotation_step(:, local_channel)) + &
    2992              :                                        DOT_PRODUCT(local_ot_env(local_channel)%ener_gx, &
    2993         8424 :                                                    local_ot_env(local_channel)%ener_dx)
    2994              :             END DO
    2995              :          END DO
    2996          134 :          CALL para_env_inter_kp%sum(shadow_curvature_total)
    2997          134 :          CALL para_env_inter_kp%sum(response_cross)
    2998          134 :          CALL para_env_inter_kp%sum(projected_gradient)
    2999          134 :          local_ot_env(1)%response_shadow_curvature = shadow_curvature_total
    3000              :       END IF
    3001              : 
    3002              :       ! The frozen-H finite response above omits the self-consistent Hxc density response. Project
    3003              :       ! the most recent accepted physical density/Hamiltonian secant onto both the candidate and
    3004              :       ! conventional accepted directions. All spin/K-point overlaps are accumulated before the
    3005              :       ! minimum-Frobenius secant is formed: this is the direct-sum spin response, including the Hxc
    3006              :       ! cross-spin coupling, and not a sum of independently fitted spin Hessians. The resulting
    3007              :       ! sign-aware rank-two response is calibrated against accepted Mermin drops before it can replace
    3008              :       ! the conventional search direction.
    3009          180 :       hxc_density_norm_sq = 0.0_dp
    3010          180 :       hxc_response_work = 0.0_dp
    3011          180 :       hxc_density_overlap(:) = 0.0_dp
    3012          180 :       hxc_response_overlap(:) = 0.0_dp
    3013          180 :       failure = 0
    3014          431 :       DO local_kpoint = 1, SIZE(kpoints%kp_env)
    3015          251 :          kp => kpoints%kp_env(local_kpoint)%kpoint_env
    3016          251 :          ikpoint = kp%nkpoint
    3017          251 :          CPASSERT(ASSOCIATED(kp%ot_smat))
    3018          251 :          CPASSERT(SIZE(kp%ot_smat) >= 2)
    3019          696 :          DO ispin = 1, nspin_ot
    3020          265 :             local_channel = qs_ot_channel_index(ispin, ikpoint, nspin_ot) - first_channel + 1
    3021         1046 :             DO energy_spin = 1, MERGE(nspin_energy, 1, restricted_roks)
    3022          279 :                physical_spin = MERGE(energy_spin, ispin, restricted_roks)
    3023          279 :                energy_start = MERGE((energy_spin - 1)*nmo + 1, 1, restricted_roks)
    3024          279 :                energy_stop = energy_start + nmo - 1
    3025          279 :                group = channel_response_group(energy_start, local_channel)
    3026              :                energy_metric_step(energy_start:energy_stop) = &
    3027              :                   -channel_response_weight(energy_start:energy_stop, local_channel)* &
    3028              :                   (local_ot_env(local_channel)%ener_response_gx(energy_start:energy_stop) - &
    3029         1989 :                    energy_mean(group))
    3030              :                CALL qs_ot_density_tangent( &
    3031              :                   channel_generator(:, :, local_channel), &
    3032              :                   trial_occupation(:, ikpoint, physical_spin), wkp(ikpoint), &
    3033              :                   rotation_step(:, local_channel), &
    3034          279 :                   energy_metric_step(energy_start:energy_stop), density_modes(:, :, 1))
    3035          279 :                IF (.NOT. restricted_roks) THEN
    3036        10641 :                   channel_density_modes(:, :, 1, local_channel) = density_modes(:, :, 1)
    3037              :                END IF
    3038        13749 :                density_modes(:, :, 2) = CMPLX(0.0_dp, 0.0_dp, KIND=dp)
    3039          279 :                IF (shadow_pending) THEN
    3040              :                   energy_metric_step(energy_start:energy_stop) = &
    3041              :                      -channel_response_weight(energy_start:energy_stop, local_channel)* &
    3042              :                      (local_ot_env(local_channel)%ener_dx(energy_start:energy_stop) - &
    3043         1468 :                       shadow_energy_mean(group))
    3044              :                   CALL qs_ot_density_tangent( &
    3045              :                      channel_generator(:, :, local_channel), &
    3046              :                      trial_occupation(:, ikpoint, physical_spin), wkp(ikpoint), &
    3047              :                      previous_rotation_step(:, local_channel), &
    3048          204 :                      energy_metric_step(energy_start:energy_stop), density_modes(:, :, 2))
    3049          204 :                   IF (.NOT. restricted_roks) THEN
    3050         8000 :                      channel_density_modes(:, :, 2, local_channel) = density_modes(:, :, 2)
    3051              :                   END IF
    3052              :                END IF
    3053              :                CALL qs_scf_kp_physical_secant_overlaps( &
    3054              :                   local_ot_env(local_channel)%mermin_physical(energy_spin), &
    3055              :                   kp%ot_smat(1), kp%ot_smat(2), density_modes, wkp(ikpoint), &
    3056              :                   hxc_density_norm_sq_channel, hxc_response_work_channel, &
    3057          279 :                   hxc_density_overlap_channel, hxc_response_overlap_channel, hxc_channel_valid)
    3058          544 :                IF (hxc_channel_valid) THEN
    3059          279 :                   hxc_density_norm_sq = hxc_density_norm_sq + hxc_density_norm_sq_channel
    3060          279 :                   hxc_response_work = hxc_response_work + hxc_response_work_channel
    3061          837 :                   hxc_density_overlap(:) = hxc_density_overlap + hxc_density_overlap_channel
    3062          837 :                   hxc_response_overlap(:) = hxc_response_overlap + hxc_response_overlap_channel
    3063              :                ELSE
    3064            0 :                   failure = 1
    3065              :                END IF
    3066              :             END DO
    3067              :          END DO
    3068              :       END DO
    3069          180 :       exact_hxc_correction(:, :) = 0.0_dp
    3070          180 :       exact_hxc_valid = .FALSE.
    3071          180 :       IF (local_ot_env(1)%settings%ot_method == "CG" .AND. .NOT. restricted_roks) THEN
    3072              :          CALL qs_scf_kp_exact_hxc_projected( &
    3073              :             qs_env, kpoints, local_ot_env, first_channel, nspin_ot, wkp, para_env_inter_kp, &
    3074              :             sab_nl, fmwork, rho_ao_kp, channel_density_modes, MERGE(2, 1, shadow_pending), &
    3075          142 :             exact_hxc_correction, exact_hxc_valid)
    3076              :       END IF
    3077          180 :       CALL para_env_inter_kp%sum(failure)
    3078          180 :       CALL para_env_inter_kp%sum(hxc_density_norm_sq)
    3079          180 :       CALL para_env_inter_kp%sum(hxc_response_work)
    3080          180 :       CALL para_env_inter_kp%sum(hxc_density_overlap)
    3081          180 :       CALL para_env_inter_kp%sum(hxc_response_overlap)
    3082          180 :       hxc_correction(:, :) = 0.0_dp
    3083          180 :       hxc_valid = .FALSE.
    3084          180 :       IF (failure == 0) THEN
    3085          180 :          IF (shadow_pending .AND. &
    3086              :              ABS(local_ot_env(1)%ds_min) > SQRT(EPSILON(1.0_dp))) THEN
    3087              :             CALL qs_ot_density_secant_projected_hessian( &
    3088              :                hxc_density_norm_sq, hxc_response_work, hxc_density_overlap, &
    3089              :                hxc_response_overlap, hxc_correction, hxc_valid, &
    3090          134 :                secant_mode=2, secant_position=local_ot_env(1)%ds_min)
    3091              :          ELSE
    3092              :             CALL qs_ot_density_secant_projected_hessian( &
    3093              :                hxc_density_norm_sq, hxc_response_work, hxc_density_overlap, &
    3094           46 :                hxc_response_overlap, hxc_correction, hxc_valid)
    3095              :          END IF
    3096              :       END IF
    3097          180 :       IF (exact_hxc_valid) THEN
    3098          102 :          hxc_correction(:, :) = exact_hxc_correction
    3099          102 :          hxc_valid = .TRUE.
    3100              :       END IF
    3101          180 :       IF (hxc_valid) THEN
    3102              :          local_ot_env(1)%response_model_curvature = &
    3103          180 :             local_ot_env(1)%response_model_curvature + hxc_correction(1, 1)
    3104          180 :          IF (shadow_pending) THEN
    3105              :             local_ot_env(1)%response_shadow_curvature = &
    3106          134 :                local_ot_env(1)%response_shadow_curvature + hxc_correction(2, 2)
    3107              :          END IF
    3108          134 :          IF (shadow_pending) THEN
    3109              :             CALL ot_mermin_secant_curvature( &
    3110              :                local_ot_env(1)%response_reference_energy, local_ot_env(1)%etotal, &
    3111              :                local_ot_env(1)%response_predicted_slope, local_ot_env(1)%ds_min, &
    3112          134 :                accepted_curvature, accepted_curvature_valid)
    3113          134 :             projected_hessian(1, 1) = response_curvature_total
    3114          134 :             projected_hessian(1, 2) = response_cross
    3115          134 :             projected_hessian(2, 1) = response_cross
    3116          134 :             projected_hessian(2, 2) = shadow_curvature_total
    3117          134 :             IF (accepted_cross_valid) THEN
    3118          134 :                projected_hessian(1, 2) = accepted_cross - hxc_correction(1, 2)
    3119          134 :                projected_hessian(2, 1) = projected_hessian(1, 2)
    3120              :             END IF
    3121          134 :             IF (accepted_curvature_valid) THEN
    3122          134 :                projected_hessian(2, 2) = accepted_curvature - hxc_correction(2, 2)
    3123          134 :                local_ot_env(1)%response_shadow_curvature = accepted_curvature
    3124              :             END IF
    3125              :             CALL qs_ot_projected_response_update( &
    3126              :                projected_hessian, hxc_correction, projected_coefficients, projected_update_valid, &
    3127          134 :                projected_gradient=projected_gradient)
    3128          134 :             IF (projected_update_valid) THEN
    3129          132 :                rotation_norm(:) = 0.0_dp
    3130          132 :                rotation_count(:) = 0.0_dp
    3131          314 :                DO local_kpoint = 1, SIZE(kpoints%kp_env)
    3132          182 :                   kp => kpoints%kp_env(local_kpoint)%kpoint_env
    3133          182 :                   ikpoint = kp%nkpoint
    3134          506 :                   DO ispin = 1, nspin_ot
    3135          192 :                      rotation_group = MERGE(ispin, 1, nrotation_groups == nspin_ot)
    3136              :                      local_channel = &
    3137          192 :                         qs_ot_channel_index(ispin, ikpoint, nspin_ot) - first_channel + 1
    3138              :                      rotation_step(:, local_channel) = &
    3139              :                         projected_coefficients(1)*rotation_step(:, local_channel) + &
    3140         6600 :                         projected_coefficients(2)*previous_rotation_step(:, local_channel)
    3141              :                      local_ot_env(local_channel)%ener_response_gx(:) = &
    3142              :                         projected_coefficients(1)* &
    3143              :                         local_ot_env(local_channel)%ener_response_gx + &
    3144         1416 :                         projected_coefficients(2)*local_ot_env(local_channel)%ener_dx
    3145              :                      rotation_norm(rotation_group) = rotation_norm(rotation_group) + &
    3146              :                                                      DOT_PRODUCT(rotation_step(:, local_channel), &
    3147         6600 :                                                                  rotation_step(:, local_channel))
    3148              :                      rotation_count(rotation_group) = &
    3149          374 :                         rotation_count(rotation_group) + REAL(nrotation, KIND=dp)
    3150              :                   END DO
    3151              :                END DO
    3152          132 :                CALL para_env_inter_kp%sum(rotation_norm)
    3153          132 :                CALL para_env_inter_kp%sum(rotation_count)
    3154          132 :                response_scale = 1.0_dp
    3155          274 :                IF (SUM(rotation_norm) > EPSILON(SUM(rotation_norm))) THEN
    3156              :                   response_scale = MIN( &
    3157              :                                    1.0_dp, rotation_trust_rms* &
    3158          416 :                                    SQRT(SUM(rotation_count)/SUM(rotation_norm)))
    3159              :                END IF
    3160          132 :                unscaled_rotation_norm = 0.0_dp
    3161          324 :                DO local_channel = 1, nlocal_channels
    3162         1152 :                   ALLOCATE (dense_re(nmo, nmo), dense_im(nmo, nmo))
    3163          192 :                   dense_re(:, :) = 0.0_dp
    3164          192 :                   dense_im(:, :) = 0.0_dp
    3165          192 :                   r = 0
    3166         1144 :                   DO i = 1, nmo - 1
    3167         4348 :                      DO j = i + 1, nmo
    3168         3204 :                         r = r + 1
    3169         3204 :                         dense_re(i, j) = rotation_step(r, local_channel)
    3170         3204 :                         dense_re(j, i) = -rotation_step(r, local_channel)
    3171         3204 :                         r = r + 1
    3172         3204 :                         dense_im(i, j) = rotation_step(r, local_channel)
    3173         4156 :                         dense_im(j, i) = rotation_step(r, local_channel)
    3174              :                      END DO
    3175              :                   END DO
    3176          192 :                   CPASSERT(r == nrotation)
    3177              :                   unscaled_rotation_norm = MAX( &
    3178              :                                            unscaled_rotation_norm, qs_ot_antihermitian_spectral_norm( &
    3179         8888 :                                            CMPLX(dense_re, dense_im, KIND=dp)))
    3180          324 :                   DEALLOCATE (dense_im, dense_re)
    3181              :                END DO
    3182          132 :                CALL para_env_inter_kp%max(unscaled_rotation_norm)
    3183          132 :                IF (unscaled_rotation_norm > EPSILON(unscaled_rotation_norm)) THEN
    3184              :                   response_scale = MIN( &
    3185              :                                    response_scale, &
    3186          132 :                                    rotation_trust_spectral/unscaled_rotation_norm)
    3187              :                END IF
    3188          314 :                DO local_kpoint = 1, SIZE(kpoints%kp_env)
    3189          182 :                   kp => kpoints%kp_env(local_kpoint)%kpoint_env
    3190          182 :                   ikpoint = kp%nkpoint
    3191          506 :                   DO ispin = 1, nspin_ot
    3192              :                      local_channel = &
    3193          192 :                         qs_ot_channel_index(ispin, ikpoint, nspin_ot) - first_channel + 1
    3194              :                      rotation_step(:, local_channel) = &
    3195         6600 :                         response_scale*rotation_step(:, local_channel)
    3196              :                      local_ot_env(local_channel)%ener_response_gx(:) = &
    3197         1416 :                         response_scale*local_ot_env(local_channel)%ener_response_gx
    3198          192 :                      IF (.NOT. (ASSOCIATED(local_ot_env(local_channel)%matrix_response_gx))) THEN
    3199            0 :                         CALL cp_abort(__LOCATION__, "Missing OT response gradient")
    3200              :                      END IF
    3201          192 :                      IF (.NOT. (ASSOCIATED(local_ot_env(local_channel)%matrix_response_gx_im))) THEN
    3202            0 :                         CALL cp_abort(__LOCATION__, "Missing imaginary OT response gradient")
    3203              :                      END IF
    3204              :                      CALL dbcsr_copy(local_ot_env(local_channel)%matrix_response_gx, &
    3205          192 :                                      local_ot_env(local_channel)%matrix_dx)
    3206              :                      CALL dbcsr_scale(local_ot_env(local_channel)%matrix_response_gx, &
    3207          192 :                                       response_scale*projected_coefficients(2))
    3208              :                      CALL dbcsr_copy(local_ot_env(local_channel)%matrix_response_gx_im, &
    3209          192 :                                      local_ot_env(local_channel)%matrix_dx_im)
    3210              :                      CALL dbcsr_scale(local_ot_env(local_channel)%matrix_response_gx_im, &
    3211          192 :                                       response_scale*projected_coefficients(2))
    3212         1152 :                      ALLOCATE (dense_re(nmo, nmo), dense_im(nmo, nmo))
    3213          192 :                      dense_re(:, :) = 0.0_dp
    3214          192 :                      dense_im(:, :) = 0.0_dp
    3215          192 :                      r = 0
    3216         1144 :                      DO i = 1, nmo - 1
    3217         4348 :                         DO j = i + 1, nmo
    3218         3204 :                            r = r + 1
    3219         3204 :                            dense_re(i, j) = rotation_step(r, local_channel)
    3220         3204 :                            dense_re(j, i) = -rotation_step(r, local_channel)
    3221         3204 :                            r = r + 1
    3222         3204 :                            dense_im(i, j) = rotation_step(r, local_channel)
    3223         4156 :                            dense_im(j, i) = rotation_step(r, local_channel)
    3224              :                         END DO
    3225              :                      END DO
    3226          192 :                      CPASSERT(r == nrotation)
    3227              :                      CALL qs_scf_loop_ot_dense_to_matrix( &
    3228              :                         dense_re, local_ot_env(local_channel), &
    3229          192 :                         local_ot_env(local_channel)%rot_mat_response_gx)
    3230              :                      CALL qs_scf_loop_ot_dense_to_matrix( &
    3231              :                         dense_im, local_ot_env(local_channel), &
    3232          192 :                         local_ot_env(local_channel)%rot_mat_response_gx_im)
    3233          374 :                      DEALLOCATE (dense_im, dense_re)
    3234              :                   END DO
    3235              :                END DO
    3236          132 :                local_ot_env(1)%response_hxc_direction_valid = .TRUE.
    3237              :                local_ot_env(1)%response_model_curvature = response_scale**2* &
    3238              :                                                           DOT_PRODUCT(projected_coefficients, &
    3239              :                                                                       MATMUL(projected_hessian + hxc_correction, &
    3240         1980 :                                                                              projected_coefficients))
    3241              :             END IF
    3242              :          END IF
    3243              :       END IF
    3244              : 
    3245            0 :       DEALLOCATE (coupling, curvature_sum, energy_count, energy_mean, energy_metric_step, &
    3246            0 :                   energy_shift, energy_weighted_sum, rayleigh_step, response_weight, shadow_energy_mean, &
    3247            0 :                   shadow_energy_metric_step, shadow_energy_weighted_sum, shadow_rayleigh_step, &
    3248            0 :                   rotation_count, rotation_norm, rotation_scale, schur_rhs, vy, vz, &
    3249            0 :                   rayleigh_response, rhs, rotation_gradient, rotation_hessian, &
    3250            0 :                   spin_rotation_gradient, spin_rotation_hessian, spin_rayleigh_response, &
    3251            0 :                   previous_rotation_step, rotation_step, &
    3252            0 :                   rotation_y, rotation_z, schur_block, solution, channel_rayleigh_response, &
    3253            0 :                   channel_rotation_hessian, channel_rotation_gradient, channel_response_weight, &
    3254            0 :                   channel_density_modes, channel_response_group, channel_generator, &
    3255            0 :                   fixed_n_matrix, fixed_n_rhs, &
    3256            0 :                   fixed_n_solution, &
    3257          180 :                   density_modes)
    3258              : 
    3259         1328 :    END SUBROUTINE qs_scf_loop_prepare_ot_kp_rotation_response
    3260              : 
    3261              : ! **************************************************************************************************
    3262              : !> \brief copy a distributed OT matrix to a replicated dense matrix
    3263              : !> \param matrix distributed matrix
    3264              : !> \param ot_env channel owning the matrix distribution
    3265              : !> \param dense replicated result
    3266              : ! **************************************************************************************************
    3267         1724 :    SUBROUTINE qs_scf_loop_ot_matrix_to_dense(matrix, ot_env, dense)
    3268              :       TYPE(dbcsr_type), INTENT(IN)                       :: matrix
    3269              :       TYPE(qs_ot_type), INTENT(IN)                       :: ot_env
    3270              :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :), &
    3271              :          INTENT(OUT)                                     :: dense
    3272              : 
    3273              :       INTEGER                                            :: ncol, nrow
    3274              :       TYPE(cp_fm_struct_type), POINTER                   :: fm_struct
    3275              :       TYPE(cp_fm_type)                                   :: fm
    3276              : 
    3277         1724 :       NULLIFY (fm_struct)
    3278            0 :       CPASSERT(ASSOCIATED(ot_env%blacs_env))
    3279         1724 :       CPASSERT(ASSOCIATED(ot_env%para_env))
    3280         1724 :       CALL dbcsr_get_info(matrix, nfullrows_total=nrow, nfullcols_total=ncol)
    3281         6896 :       ALLOCATE (dense(nrow, ncol))
    3282              :       CALL cp_fm_struct_create(fm_struct, context=ot_env%blacs_env, para_env=ot_env%para_env, &
    3283         1724 :                                nrow_global=nrow, ncol_global=ncol)
    3284         1724 :       CALL cp_fm_create(fm, fm_struct)
    3285         1724 :       CALL copy_dbcsr_to_fm(matrix, fm)
    3286         1724 :       CALL cp_fm_get_submatrix(fm, dense, n_rows=nrow, n_cols=ncol)
    3287         1724 :       CALL cp_fm_release(fm)
    3288         1724 :       CALL cp_fm_struct_release(fm_struct)
    3289              : 
    3290         5172 :    END SUBROUTINE qs_scf_loop_ot_matrix_to_dense
    3291              : 
    3292              : ! **************************************************************************************************
    3293              : !> \brief copy a replicated dense matrix into a distributed OT matrix
    3294              : !> \param dense replicated source
    3295              : !> \param ot_env channel owning the matrix distribution
    3296              : !> \param matrix distributed result
    3297              : ! **************************************************************************************************
    3298          914 :    SUBROUTINE qs_scf_loop_ot_dense_to_matrix(dense, ot_env, matrix)
    3299              :       REAL(KIND=dp), DIMENSION(:, :), INTENT(IN)         :: dense
    3300              :       TYPE(qs_ot_type), INTENT(IN)                       :: ot_env
    3301              :       TYPE(dbcsr_type), INTENT(INOUT)                    :: matrix
    3302              : 
    3303              :       TYPE(cp_fm_struct_type), POINTER                   :: fm_struct
    3304              :       TYPE(cp_fm_type)                                   :: fm
    3305              : 
    3306          914 :       NULLIFY (fm_struct)
    3307            0 :       CPASSERT(ASSOCIATED(ot_env%blacs_env))
    3308          914 :       CPASSERT(ASSOCIATED(ot_env%para_env))
    3309              :       CALL cp_fm_struct_create(fm_struct, context=ot_env%blacs_env, para_env=ot_env%para_env, &
    3310          914 :                                nrow_global=SIZE(dense, 1), ncol_global=SIZE(dense, 2))
    3311          914 :       CALL cp_fm_create(fm, fm_struct)
    3312          914 :       CALL cp_fm_set_submatrix(fm, dense)
    3313          914 :       CALL copy_fm_to_dbcsr(fm, matrix)
    3314          914 :       CALL cp_fm_release(fm)
    3315          914 :       CALL cp_fm_struct_release(fm_struct)
    3316              : 
    3317          914 :    END SUBROUTINE qs_scf_loop_ot_dense_to_matrix
    3318              : 
    3319              : ! **************************************************************************************************
    3320              : !> \brief the inner loop of scf, specific to using to the orbital transformation method
    3321              : !>       basically, in goes the ks matrix out goes a new p matrix
    3322              : !> \param qs_env ...
    3323              : !> \param scf_env ...
    3324              : !> \param smear ...
    3325              : !> \param mos ...
    3326              : !> \param rho ...
    3327              : !> \param mo_derivs ...
    3328              : !> \param total_energy ...
    3329              : !> \param matrix_s ...
    3330              : !> \param energy_only ...
    3331              : !> \param has_unit_metric ...
    3332              : !> \par History
    3333              : !>      03.2006 created [Joost VandeVondele]
    3334              : !>      2013    moved from qs_scf [Florian Schiffmann]
    3335              : ! **************************************************************************************************
    3336        80414 :    SUBROUTINE qs_scf_loop_do_ot(qs_env, scf_env, smear, mos, rho, mo_derivs, total_energy, &
    3337              :                                 matrix_s, energy_only, has_unit_metric)
    3338              : 
    3339              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    3340              :       TYPE(qs_scf_env_type), POINTER                     :: scf_env
    3341              :       TYPE(smear_type), POINTER                          :: smear
    3342              :       TYPE(mo_set_type), DIMENSION(:), INTENT(INOUT)     :: mos
    3343              :       TYPE(qs_rho_type), POINTER                         :: rho
    3344              :       TYPE(dbcsr_p_type), DIMENSION(:), POINTER          :: mo_derivs
    3345              :       REAL(KIND=dp), INTENT(IN)                          :: total_energy
    3346              :       TYPE(dbcsr_p_type), DIMENSION(:), POINTER          :: matrix_s
    3347              :       LOGICAL, INTENT(INOUT)                             :: energy_only
    3348              :       LOGICAL, INTENT(IN)                                :: has_unit_metric
    3349              : 
    3350              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'qs_scf_loop_do_ot'
    3351              : 
    3352              :       INTEGER                                            :: handle, ispin
    3353        80414 :       TYPE(dbcsr_p_type), DIMENSION(:), POINTER          :: rho_ao
    3354              :       TYPE(dbcsr_type), POINTER                          :: orthogonality_metric
    3355              : 
    3356        80414 :       CALL timeset(routineN, handle)
    3357        80414 :       NULLIFY (rho_ao)
    3358              : 
    3359        80414 :       CALL qs_rho_get(rho, rho_ao=rho_ao)
    3360              : 
    3361        80414 :       IF (has_unit_metric) THEN
    3362        18422 :          NULLIFY (orthogonality_metric)
    3363              :       ELSE
    3364        61992 :          orthogonality_metric => matrix_s(1)%matrix
    3365              :       END IF
    3366              : 
    3367              :       ! in case of LSD the first spin qs_ot_env will drive the minimization
    3368              :       ! in the case of a restricted calculation, it will make sure the spin orbitals are equal
    3369              : 
    3370              :       CALL ot_scf_mini(mos, mo_derivs, smear, orthogonality_metric, &
    3371              :                        total_energy, energy_only, scf_env%iter_delta, &
    3372        80414 :                        scf_env%qs_ot_env)
    3373              : 
    3374       176881 :       DO ispin = 1, SIZE(mos)
    3375       176881 :          CALL set_mo_occupation(mo_set=mos(ispin), smear=smear)
    3376              :       END DO
    3377              : 
    3378       176881 :       DO ispin = 1, SIZE(mos)
    3379              :          CALL calculate_density_matrix(mos(ispin), &
    3380              :                                        rho_ao(ispin)%matrix, &
    3381       176881 :                                        use_dbcsr=.TRUE.)
    3382              :       END DO
    3383              : 
    3384        80414 :       scf_env%iter_method = scf_env%qs_ot_env(1)%OT_METHOD_FULL
    3385        80414 :       scf_env%iter_param = scf_env%qs_ot_env(1)%ds_min
    3386        80414 :       qs_env%broyden_adaptive_sigma = scf_env%qs_ot_env(1)%broyden_adaptive_sigma
    3387              : 
    3388        80414 :       CALL timestop(handle)
    3389              : 
    3390        80414 :    END SUBROUTINE qs_scf_loop_do_ot
    3391              : 
    3392              : ! **************************************************************************************************
    3393              : !> \brief Measure the distance between the diagonalized candidate density and the current density.
    3394              : !> \param scf_env Holds SCF environment information.
    3395              : !> \param rho Current electron density.
    3396              : !> \param para_env Parallel environment.
    3397              : !> \param delta Maximum change of the density and any separately stored density coordinates.
    3398              : !> \param kpoints Optional Bloch densities for the Lowdin convergence check.
    3399              : ! **************************************************************************************************
    3400          152 :    SUBROUTINE qs_scf_candidate_density_delta(scf_env, rho, para_env, delta, kpoints)
    3401              :       TYPE(qs_scf_env_type), POINTER                     :: scf_env
    3402              :       TYPE(qs_rho_type), POINTER                         :: rho
    3403              :       TYPE(mp_para_env_type), POINTER                    :: para_env
    3404              :       REAL(KIND=dp), INTENT(OUT)                         :: delta
    3405              :       TYPE(kpoint_type), OPTIONAL, POINTER               :: kpoints
    3406              : 
    3407              :       INTEGER                                            :: ic, ispin
    3408              :       REAL(KIND=dp)                                      :: tmp
    3409          152 :       TYPE(dbcsr_p_type), DIMENSION(:, :), POINTER       :: rho_ao_kp
    3410              : 
    3411          152 :       NULLIFY (rho_ao_kp)
    3412          152 :       CALL qs_rho_get(rho, rho_ao_kp=rho_ao_kp)
    3413              : 
    3414          152 :       CPASSERT(ASSOCIATED(scf_env%p_mix_new))
    3415          152 :       delta = 0.0_dp
    3416         7918 :       DO ic = 1, SIZE(scf_env%p_mix_new, 2)
    3417        22658 :          DO ispin = 1, SIZE(scf_env%p_mix_new, 1)
    3418              :             ! p_mix=1 leaves the candidate unchanged while cp_sm_mix evaluates
    3419              :             ! the same max-element density difference used by direct mixing.
    3420              :             CALL cp_sm_mix(m1=scf_env%p_mix_new(ispin, ic)%matrix, &
    3421              :                            m2=rho_ao_kp(ispin, ic)%matrix, p_mix=1.0_dp, &
    3422        14740 :                            delta=tmp, para_env=para_env)
    3423        22506 :             delta = MAX(delta, tmp)
    3424              :          END DO
    3425              :       END DO
    3426              : 
    3427          152 :       CALL lowdin_kp_population(kpoints, delta=delta)
    3428          152 :    END SUBROUTINE qs_scf_candidate_density_delta
    3429              : 
    3430              : ! **************************************************************************************************
    3431              : !> \brief Commit the diagonalized candidate density without numerical mixing.
    3432              : !> \param scf_env Holds SCF environment information.
    3433              : !> \param rho Electron density to update.
    3434              : ! **************************************************************************************************
    3435          152 :    SUBROUTINE qs_scf_commit_density_candidate(scf_env, rho)
    3436              :       TYPE(qs_scf_env_type), POINTER                     :: scf_env
    3437              :       TYPE(qs_rho_type), POINTER                         :: rho
    3438              : 
    3439              :       CHARACTER(len=default_string_length)               :: name
    3440              :       INTEGER                                            :: ic, ispin
    3441          152 :       TYPE(dbcsr_p_type), DIMENSION(:, :), POINTER       :: rho_ao_kp
    3442              : 
    3443          152 :       NULLIFY (rho_ao_kp)
    3444          152 :       CALL qs_rho_get(rho, rho_ao_kp=rho_ao_kp)
    3445              : 
    3446          152 :       CPASSERT(ASSOCIATED(scf_env%p_mix_new))
    3447         7918 :       DO ic = 1, SIZE(scf_env%p_mix_new, 2)
    3448        22658 :          DO ispin = 1, SIZE(scf_env%p_mix_new, 1)
    3449        14740 :             CALL dbcsr_get_info(rho_ao_kp(ispin, ic)%matrix, name=name)
    3450        22506 :             CALL dbcsr_copy(rho_ao_kp(ispin, ic)%matrix, scf_env%p_mix_new(ispin, ic)%matrix, name=name)
    3451              :          END DO
    3452              :       END DO
    3453              : 
    3454          152 :    END SUBROUTINE qs_scf_commit_density_candidate
    3455              : 
    3456              : ! **************************************************************************************************
    3457              : !> \brief Performs the requested density mixing if any needed
    3458              : !> \param scf_env   Holds SCF environment information
    3459              : !> \param rho       All data for the electron density
    3460              : !> \param para_env  Parallel environment
    3461              : !> \param diis_step Did we do a DIIS step?
    3462              : !> \param kpoints Optional Bloch state with separate Lowdin density coordinates.
    3463              : ! **************************************************************************************************
    3464       242443 :    SUBROUTINE qs_scf_density_mixing(scf_env, rho, para_env, diis_step, kpoints)
    3465              :       TYPE(qs_scf_env_type), POINTER                     :: scf_env
    3466              :       TYPE(qs_rho_type), POINTER                         :: rho
    3467              :       TYPE(mp_para_env_type), POINTER                    :: para_env
    3468              :       LOGICAL                                            :: diis_step
    3469              :       TYPE(kpoint_type), OPTIONAL, POINTER               :: kpoints
    3470              : 
    3471              :       REAL(KIND=dp)                                      :: alpha
    3472       242443 :       TYPE(dbcsr_p_type), DIMENSION(:, :), POINTER       :: rho_ao_kp
    3473              : 
    3474       242443 :       NULLIFY (rho_ao_kp)
    3475              : 
    3476       242443 :       CALL qs_rho_get(rho, rho_ao_kp=rho_ao_kp)
    3477              : 
    3478       388372 :       SELECT CASE (scf_env%mixing_method)
    3479              :       CASE (direct_mixing_nr)
    3480              :          CALL scf_env_density_mixing(scf_env%p_mix_new, &
    3481              :                                      scf_env%mixing_store, rho_ao_kp, para_env, scf_env%iter_delta, scf_env%iter_count, &
    3482       145929 :                                      diis=diis_step)
    3483              :       CASE (gspace_mixing_nr, pulay_mixing_nr, broyden_mixing_nr, modified_broyden_mixing_nr, &
    3484              :             multisecant_mixing_nr, new_pulay_mixing_nr)
    3485              :          ! Compute the difference p_out-p_in
    3486              :          CALL self_consistency_check(rho_ao_kp, scf_env%p_delta, para_env, scf_env%p_mix_new, &
    3487        12970 :                                      delta=scf_env%iter_delta)
    3488              :       CASE (no_mixing_nr)
    3489              :       CASE DEFAULT
    3490              :          CALL cp_abort(__LOCATION__, &
    3491              :                        "unknown scf mixing method: "// &
    3492       242443 :                        cp_to_string(scf_env%mixing_method))
    3493              :       END SELECT
    3494              : 
    3495              :       ! Reciprocal-space mixing accepts the occupations later, together with the grid density.
    3496       242443 :       alpha = 0.0_dp
    3497       242443 :       IF (scf_env%mixing_method <= direct_mixing_nr) alpha = 1.0_dp
    3498       242443 :       IF (scf_env%mixing_method == direct_mixing_nr) THEN
    3499       145929 :          IF (.NOT. diis_step .AND. scf_env%iter_count >= scf_env%mixing_store%nskip_mixing) THEN
    3500        47940 :             alpha = scf_env%mixing_store%alpha
    3501              :          END IF
    3502              :       END IF
    3503       242443 :       CALL lowdin_kp_population(kpoints, delta=scf_env%iter_delta, alpha=alpha)
    3504              : 
    3505       242443 :    END SUBROUTINE qs_scf_density_mixing
    3506              : 
    3507              : ! **************************************************************************************************
    3508              : !> \brief checks whether exit conditions for outer loop are satisfied
    3509              : !> \param qs_env ...
    3510              : !> \param scf_env ...
    3511              : !> \param scf_control ...
    3512              : !> \param should_stop ...
    3513              : !> \param outer_loop_converged ...
    3514              : !> \param exit_outer_loop ...
    3515              : ! **************************************************************************************************
    3516        26627 :    SUBROUTINE qs_scf_check_outer_exit(qs_env, scf_env, scf_control, should_stop, &
    3517              :                                       outer_loop_converged, exit_outer_loop)
    3518              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    3519              :       TYPE(qs_scf_env_type), POINTER                     :: scf_env
    3520              :       TYPE(scf_control_type), POINTER                    :: scf_control
    3521              :       LOGICAL                                            :: should_stop, outer_loop_converged, &
    3522              :                                                             exit_outer_loop
    3523              : 
    3524              :       REAL(KIND=dp)                                      :: outer_loop_eps
    3525              : 
    3526        26627 :       outer_loop_converged = .TRUE.
    3527        26627 :       IF (scf_control%outer_scf%have_scf) THEN
    3528              :          ! We have an outer SCF loop...
    3529         6319 :          scf_env%outer_scf%iter_count = scf_env%outer_scf%iter_count + 1
    3530         6319 :          outer_loop_converged = .FALSE.
    3531              : 
    3532         6319 :          CALL outer_loop_gradient(qs_env, scf_env)
    3533              :          ! Multiple constraints: get largest deviation
    3534        12744 :          outer_loop_eps = SQRT(MAXVAL(scf_env%outer_scf%gradient(:, scf_env%outer_scf%iter_count)**2))
    3535              : 
    3536         6319 :          IF (outer_loop_eps < scf_control%outer_scf%eps_scf) outer_loop_converged = .TRUE.
    3537              :       END IF
    3538              : 
    3539              :       exit_outer_loop = should_stop .OR. outer_loop_converged .OR. &
    3540        26627 :                         scf_env%outer_scf%iter_count > scf_control%outer_scf%max_scf
    3541              : 
    3542        26627 :    END SUBROUTINE qs_scf_check_outer_exit
    3543              : 
    3544              : ! **************************************************************************************************
    3545              : !> \brief checks whether exit conditions for inner loop are satisfied
    3546              : !> \param qs_env ...
    3547              : !> \param scf_env ...
    3548              : !> \param scf_control ...
    3549              : !> \param should_stop ...
    3550              : !> \param just_energy ...
    3551              : !> \param exit_inner_loop ...
    3552              : !> \param inner_loop_converged ...
    3553              : !> \param output_unit ...
    3554              : !> \param u_changed Whether a Lowdin k-point U step requires restarting the SCF history.
    3555              : ! **************************************************************************************************
    3556       485190 :    SUBROUTINE qs_scf_check_inner_exit(qs_env, scf_env, scf_control, should_stop, just_energy, &
    3557              :                                       exit_inner_loop, inner_loop_converged, output_unit, u_changed)
    3558              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    3559              :       TYPE(qs_scf_env_type), POINTER                     :: scf_env
    3560              :       TYPE(scf_control_type), POINTER                    :: scf_control
    3561              :       LOGICAL                                            :: should_stop, just_energy, &
    3562              :                                                             exit_inner_loop, inner_loop_converged
    3563              :       INTEGER                                            :: output_unit
    3564              :       LOGICAL, INTENT(OUT)                               :: u_changed
    3565              : 
    3566              :       INTEGER                                            :: ikind
    3567              :       LOGICAL                                            :: davidson_tightening, u_pending, &
    3568              :                                                             update_validated
    3569              :       REAL(KIND=dp)                                      :: eps_u, ramp, target_u, u
    3570              :       TYPE(kpoint_type), POINTER                         :: kpoints
    3571       242595 :       TYPE(qs_kind_type), POINTER                        :: qs_kinds(:)
    3572              : 
    3573       242595 :       inner_loop_converged = .FALSE.
    3574       242595 :       exit_inner_loop = .FALSE.
    3575       242595 :       u_changed = .FALSE.
    3576       242595 :       u_pending = .FALSE.
    3577       242595 :       update_validated = scf_control%diagonalization%update_method /= diag_update_method_adiis
    3578       242595 :       IF (.NOT. update_validated) THEN
    3579          152 :          CPASSERT(ASSOCIATED(scf_env%scf_subspace_buffer))
    3580              :          update_validated = scf_env%adiis_validated .OR. &
    3581          152 :                             scf_env%scf_subspace_buffer%diis_weight >= 1.0_dp
    3582              :       END IF
    3583              : 
    3584              :       CALL external_control(should_stop, "SCF", target_time=qs_env%target_time, &
    3585       242595 :                             start_time=qs_env%start_time)
    3586       242595 :       CALL get_qs_env(qs_env, kpoints=kpoints, qs_kind_set=qs_kinds)
    3587       242595 :       IF (ASSOCIATED(kpoints)) THEN
    3588       242595 :          IF (ALLOCATED(kpoints%lowdin_q)) THEN
    3589         1976 :             DO ikind = 1, SIZE(qs_kinds)
    3590              :                CALL get_qs_kind(qs_kinds(ikind), u_minus_j=u, u_minus_j_target=target_u, &
    3591         1242 :                                 u_ramping=ramp, eps_u_ramping=eps_u)
    3592         1242 :                IF (ramp <= 0.0_dp .OR. u == target_u) CYCLE
    3593            0 :                u_pending = .TRUE.
    3594            0 :                IF (should_stop .OR. just_energy .OR. scf_env%iter_count >= scf_control%max_scf) CYCLE
    3595            0 :                IF (scf_control%use_ot .AND. .NOT. qs_scf_kp_search_endpoint(scf_env%iter_method)) CYCLE
    3596            0 :                IF (scf_env%iter_delta > eps_u .OR. .NOT. update_validated) CYCLE
    3597              :                ! Keep U fixed throughout trial energies and force evaluations.
    3598            0 :                u = MIN(u + ramp, target_u)
    3599            0 :                CALL set_qs_kind(qs_kinds(ikind), u_minus_j=u)
    3600            0 :                u_changed = .TRUE.
    3601            0 :                IF (output_unit > 0) WRITE (output_unit, '(T3,A,I0,A,F10.6,A)') &
    3602         1976 :                   "DFT+U ramping: kind ", ikind, ", U(eff) = ", u*evolt, " eV"
    3603              :             END DO
    3604              :          END IF
    3605              :       END IF
    3606       242595 :       IF (u_changed) RETURN
    3607       242595 :       IF (scf_env%iter_delta < scf_control%eps_scf .AND. update_validated .AND. .NOT. u_pending) THEN
    3608              :          ! nested IFs on purpose: a .AND. chain leaves the evaluation order
    3609              :          ! unspecified. On non-Davidson runs the env array has size zero
    3610              :          ! while the tightening test below indexes its first channel
    3611        22927 :          davidson_tightening = .FALSE.
    3612        22927 :          IF (scf_env%method == block_davidson_diag_method_nr) THEN
    3613           36 :             IF (SIZE(scf_env%block_davidson_env) > 0) THEN
    3614              :                davidson_tightening = scf_env%block_davidson_env(1)%eps_iter_used > &
    3615              :                                      scf_env%block_davidson_env(1)%eps_iter .AND. &
    3616           36 :                                      scf_env%iter_delta < scf_env%block_davidson_env(1)%eps_iter_used
    3617              :             END IF
    3618              :          END IF
    3619              :          IF (davidson_tightening) THEN
    3620              :             ! the adaptive inner tolerance of the Davidson solve that produced
    3621              :             ! this mixing delta was looser than the delta itself. The apparent
    3622              :             ! convergence may be nothing but the noise floor of the loose
    3623              :             ! solve. Tighten the ratchet one decade below what that solve used
    3624              :             ! and keep iterating until the delta survives a tighter solve.
    3625            0 :             IF (output_unit > 0) THEN
    3626              :                WRITE (UNIT=output_unit, FMT="(T3,A,ES9.2,A)") &
    3627            0 :                   "*** SCF delta below the loose Davidson tolerance ", &
    3628            0 :                   scf_env%block_davidson_env(1)%eps_iter_used, " - tightening and continuing ***"
    3629              :             END IF
    3630              :             scf_env%block_davidson_env(1)%eps_iter_prev = &
    3631              :                MIN(scf_env%block_davidson_env(1)%eps_iter_prev, &
    3632              :                    MAX(scf_env%block_davidson_env(1)%eps_iter, &
    3633            0 :                        0.1_dp*scf_env%block_davidson_env(1)%eps_iter_used))
    3634              :          ELSE
    3635        22927 :             IF (output_unit > 0) THEN
    3636              :                WRITE (UNIT=output_unit, FMT="(/,T3,A,I5,A/)") &
    3637        11627 :                   "*** SCF run converged in ", scf_env%iter_count, " steps ***"
    3638              :             END IF
    3639        22927 :             inner_loop_converged = .TRUE.
    3640        22927 :             exit_inner_loop = .TRUE.
    3641              :          END IF
    3642       219668 :       ELSE IF (should_stop .OR. scf_env%iter_count >= scf_control%max_scf) THEN
    3643         3904 :          inner_loop_converged = .FALSE.
    3644         3904 :          IF (just_energy) THEN
    3645          818 :             exit_inner_loop = .FALSE.
    3646              :          ELSE
    3647         3086 :             exit_inner_loop = .TRUE.
    3648         3086 :             IF (output_unit > 0) THEN
    3649              :                WRITE (UNIT=output_unit, FMT="(/,T3,A,I5,A/)") &
    3650         1544 :                   "Leaving inner SCF loop after reaching ", scf_env%iter_count, " steps."
    3651              :             END IF
    3652              :          END IF
    3653              :       END IF
    3654              : 
    3655       242595 :    END SUBROUTINE qs_scf_check_inner_exit
    3656              : 
    3657              : ! **************************************************************************************************
    3658              : !> \brief undoing density mixing. Important upon convergence
    3659              : !> \param scf_env ...
    3660              : !> \param rho ...
    3661              : !> \param dft_control ...
    3662              : !> \param para_env ...
    3663              : !> \param diis_step ...
    3664              : ! **************************************************************************************************
    3665        26013 :    SUBROUTINE qs_scf_undo_mixing(scf_env, rho, dft_control, para_env, diis_step)
    3666              :       TYPE(qs_scf_env_type), POINTER                     :: scf_env
    3667              :       TYPE(qs_rho_type), POINTER                         :: rho
    3668              :       TYPE(dft_control_type), POINTER                    :: dft_control
    3669              :       TYPE(mp_para_env_type), POINTER                    :: para_env
    3670              :       LOGICAL                                            :: diis_step
    3671              : 
    3672              :       CHARACTER(len=default_string_length)               :: name
    3673              :       INTEGER                                            :: ic, ispin, nc
    3674        26013 :       TYPE(dbcsr_p_type), DIMENSION(:, :), POINTER       :: rho_ao_kp
    3675              : 
    3676        26013 :       NULLIFY (rho_ao_kp)
    3677              : 
    3678        26013 :       IF (scf_env%mixing_method > 0) THEN
    3679        18242 :          CALL qs_rho_get(rho, rho_ao_kp=rho_ao_kp)
    3680        18242 :          nc = SIZE(scf_env%p_mix_new, 2)
    3681        35276 :          SELECT CASE (scf_env%mixing_method)
    3682              :          CASE (direct_mixing_nr)
    3683              :             CALL scf_env_density_mixing(scf_env%p_mix_new, scf_env%mixing_store, &
    3684              :                                         rho_ao_kp, para_env, scf_env%iter_delta, &
    3685              :                                         scf_env%iter_count, diis=diis_step, &
    3686        17034 :                                         invert=.TRUE.)
    3687       163206 :             DO ic = 1, nc
    3688       326884 :                DO ispin = 1, dft_control%nspins
    3689       163678 :                   CALL dbcsr_get_info(rho_ao_kp(ispin, ic)%matrix, name=name) ! keep the name
    3690       309850 :                   CALL dbcsr_copy(rho_ao_kp(ispin, ic)%matrix, scf_env%p_mix_new(ispin, ic)%matrix, name=name)
    3691              :                END DO
    3692              :             END DO
    3693              :          CASE (gspace_mixing_nr, pulay_mixing_nr, broyden_mixing_nr, modified_broyden_mixing_nr, &
    3694              :                multisecant_mixing_nr, new_pulay_mixing_nr)
    3695        94364 :             DO ic = 1, nc
    3696       161986 :                DO ispin = 1, dft_control%nspins
    3697        85864 :                   CALL dbcsr_get_info(rho_ao_kp(ispin, ic)%matrix, name=name) ! keep the name
    3698       160778 :                   CALL dbcsr_copy(rho_ao_kp(ispin, ic)%matrix, scf_env%p_mix_new(ispin, ic)%matrix, name=name)
    3699              :                END DO
    3700              :             END DO
    3701              :          END SELECT
    3702              :       END IF
    3703        26013 :    END SUBROUTINE qs_scf_undo_mixing
    3704              : 
    3705              : ! **************************************************************************************************
    3706              : !> \brief Performs the updates rho (takes care of mixing as well)
    3707              : !> \param rho ...
    3708              : !> \param qs_env ...
    3709              : !> \param scf_env ...
    3710              : !> \param ks_env ...
    3711              : !> \param mix_rho ...
    3712              : ! **************************************************************************************************
    3713       242595 :    SUBROUTINE qs_scf_rho_update(rho, qs_env, scf_env, ks_env, mix_rho)
    3714              :       TYPE(qs_rho_type), POINTER                         :: rho
    3715              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    3716              :       TYPE(qs_scf_env_type), POINTER                     :: scf_env
    3717              :       TYPE(qs_ks_env_type), POINTER                      :: ks_env
    3718              :       LOGICAL, INTENT(IN)                                :: mix_rho
    3719              : 
    3720       242595 :       REAL(KIND=dp), CONTIGUOUS, POINTER                 :: auxiliary(:, :)
    3721              :       TYPE(kpoint_type), POINTER                         :: kpoints
    3722              :       TYPE(mp_para_env_type), POINTER                    :: para_env
    3723              : 
    3724       242595 :       NULLIFY (para_env, auxiliary)
    3725       242595 :       CALL get_qs_env(qs_env, para_env=para_env, kpoints=kpoints)
    3726              :       ! ** update qs_env%rho
    3727       242595 :       CALL qs_rho_update_rho(rho, qs_env=qs_env)
    3728              :       ! ** Density mixing through density matrix or on the reciprocal space grid (exclusive)
    3729       242595 :       IF (mix_rho) THEN
    3730        11762 :          IF (ASSOCIATED(kpoints)) THEN
    3731        11762 :             IF (ALLOCATED(kpoints%lowdin_q)) THEN
    3732          218 :                CALL lowdin_kp_population(kpoints, alpha=1.0_dp)
    3733          218 :                auxiliary => kpoints%lowdin_q
    3734              :             END IF
    3735              :          END IF
    3736              :          CALL gspace_mixing(qs_env, scf_env%mixing_method, scf_env%mixing_store, rho, &
    3737        11762 :                             para_env, scf_env%iter_count, auxiliary=auxiliary)
    3738              : 
    3739              :       END IF
    3740       242595 :       CALL qs_ks_did_change(ks_env, rho_changed=.TRUE.)
    3741              : 
    3742       242595 :    END SUBROUTINE qs_scf_rho_update
    3743              : 
    3744              : ! **************************************************************************************************
    3745              : !> \brief Performs the necessary steps before leaving innner scf loop
    3746              : !> \param scf_env ...
    3747              : !> \param qs_env ...
    3748              : !> \param diis_step ...
    3749              : !> \param output_unit ...
    3750              : ! **************************************************************************************************
    3751        26013 :    SUBROUTINE qs_scf_inner_finalize(scf_env, qs_env, diis_step, output_unit)
    3752              :       TYPE(qs_scf_env_type), POINTER                     :: scf_env
    3753              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    3754              :       LOGICAL                                            :: diis_step
    3755              :       INTEGER, INTENT(IN)                                :: output_unit
    3756              : 
    3757              :       TYPE(dft_control_type), POINTER                    :: dft_control
    3758              :       TYPE(kpoint_type), POINTER                         :: kpoints
    3759              :       TYPE(mp_para_env_type), POINTER                    :: para_env
    3760              :       TYPE(qs_energy_type), POINTER                      :: energy
    3761              :       TYPE(qs_ks_env_type), POINTER                      :: ks_env
    3762              :       TYPE(qs_rho_type), POINTER                         :: rho
    3763              : 
    3764        26013 :       NULLIFY (energy, rho, dft_control, ks_env)
    3765              : 
    3766              :       CALL get_qs_env(qs_env=qs_env, energy=energy, ks_env=ks_env, &
    3767              :                       rho=rho, dft_control=dft_control, para_env=para_env, &
    3768        26013 :                       kpoints=kpoints)
    3769              : 
    3770        26013 :       CALL cleanup_scf_loop(scf_env)
    3771              : 
    3772              :       ! now, print out energies and charges corresponding to the obtained wfn
    3773              :       ! (this actually is not 100% consistent at this point)!
    3774        26013 :       CALL qs_scf_print_summary(output_unit, qs_env)
    3775              : 
    3776        26013 :       CALL qs_scf_undo_mixing(scf_env, rho, dft_control, para_env, diis_step)
    3777        26013 :       CALL lowdin_kp_population(kpoints, alpha=1.0_dp)
    3778              : 
    3779              :       !   *** update rspace rho since the mo changed
    3780              :       !   *** this might not always be needed (i.e. no post calculation / no forces )
    3781              :       !   *** but guarantees that rho and wfn are consistent at this point
    3782        26013 :       CALL qs_scf_rho_update(rho, qs_env, scf_env, ks_env, mix_rho=.FALSE.)
    3783              : 
    3784        26013 :    END SUBROUTINE qs_scf_inner_finalize
    3785              : 
    3786              : ! **************************************************************************************************
    3787              : !> \brief perform cleanup operations at the end of an scf loop
    3788              : !> \param scf_env ...
    3789              : !> \par History
    3790              : !>      03.2006 created [Joost VandeVondele]
    3791              : ! **************************************************************************************************
    3792        26013 :    SUBROUTINE cleanup_scf_loop(scf_env)
    3793              :       TYPE(qs_scf_env_type), INTENT(INOUT)               :: scf_env
    3794              : 
    3795              :       CHARACTER(len=*), PARAMETER                        :: routineN = 'cleanup_scf_loop'
    3796              : 
    3797              :       INTEGER                                            :: handle, ispin
    3798              : 
    3799        26013 :       CALL timeset(routineN, handle)
    3800              : 
    3801        26013 :       CALL scf_env_release_ot_operators(scf_env)
    3802        33772 :       SELECT CASE (scf_env%method)
    3803              :       CASE (ot_method_nr)
    3804        17749 :          DO ispin = 1, SIZE(scf_env%qs_ot_env)
    3805        17749 :             CALL ot_scf_destroy(scf_env%qs_ot_env(ispin))
    3806              :          END DO
    3807         7759 :          DEALLOCATE (scf_env%qs_ot_env)
    3808              :       CASE (ot_diag_method_nr)
    3809              :          !
    3810              :       CASE (general_diag_method_nr)
    3811              :          !
    3812              :       CASE (special_diag_method_nr)
    3813              :          !
    3814              :       CASE (block_krylov_diag_method_nr, block_davidson_diag_method_nr)
    3815              :          !
    3816              :       CASE (filter_matrix_diag_method_nr)
    3817              :          !
    3818              :       CASE (smeagol_method_nr)
    3819              :          !
    3820              :       CASE DEFAULT
    3821              :          CALL cp_abort(__LOCATION__, &
    3822              :                        "unknown scf method method:"// &
    3823        26013 :                        cp_to_string(scf_env%method))
    3824              :       END SELECT
    3825              : 
    3826        26013 :       CALL timestop(handle)
    3827              : 
    3828        26013 :    END SUBROUTINE cleanup_scf_loop
    3829              : 
    3830          653 : END MODULE qs_scf_loop_utils
        

Generated by: LCOV version 2.0-1