LCOV - code coverage report
Current view: top level - src - qs_scf.F (source / functions) Coverage Total Hit
Test: CP2K Regtests (git:1be8651) Lines: 87.8 % 1480 1299
Test Date: 2026-11-24 01:22:08 Functions: 100.0 % 13 13

            Line data    Source code
       1              : !--------------------------------------------------------------------------------------------------!
       2              : !   CP2K: A general program to perform molecular dynamics simulations                              !
       3              : !   Copyright 2000-2026 CP2K developers group <https://cp2k.org>                                   !
       4              : !                                                                                                  !
       5              : !   SPDX-License-Identifier: GPL-2.0-or-later                                                      !
       6              : !--------------------------------------------------------------------------------------------------!
       7              : 
       8              : ! **************************************************************************************************
       9              : !> \brief Routines for the Quickstep SCF run.
      10              : !> \par History
      11              : !>      - Joost VandeVondele (02.2002)
      12              : !>           added code for: incremental (pab and gvg) update
      13              : !>                            initialisation (init_cube, l_info)
      14              : !>      - Joost VandeVondele (02.2002)
      15              : !>           called the poisson code of the classical part
      16              : !>           this takes into account the spherical cutoff and allows for
      17              : !>           isolated systems
      18              : !>      - Joost VandeVondele (02.2002)
      19              : !>           added multiple grid feature
      20              : !>           changed to spherical cutoff consistently (?)
      21              : !>           therefore removed the gradient correct functionals
      22              : !>      - updated with the new QS data structures (10.04.02,MK)
      23              : !>      - copy_matrix replaced by transfer_matrix (11.04.02,MK)
      24              : !>      - nrebuild_rho and nrebuild_gvg unified (12.04.02,MK)
      25              : !>      - set_mo_occupation for smearing of the MO occupation numbers
      26              : !>        (17.04.02,MK)
      27              : !>      - MO level shifting added (22.04.02,MK)
      28              : !>      - Usage of TYPE mo_set_p_type
      29              : !>      - Joost VandeVondele (05.2002)
      30              : !>            added cholesky based diagonalisation
      31              : !>      - 05.2002 added pao method [fawzi]
      32              : !>      - parallel FFT (JGH 22.05.2002)
      33              : !>      - 06.2002 moved KS matrix construction to qs_build_KS_matrix.F [fawzi]
      34              : !>      - started to include more LSD (01.2003,Joost VandeVondele)
      35              : !>      - 02.2003 scf_env [fawzi]
      36              : !>      - got rid of nrebuild (01.2004, Joost VandeVondele)
      37              : !>      - 10.2004 removed pao [fawzi]
      38              : !>      - 03.2006 large cleaning action [Joost VandeVondele]
      39              : !>      - High-spin ROKS added (05.04.06,MK)
      40              : !>      - Mandes (10.2013)
      41              : !>        intermediate energy communication with external communicator added
      42              : !>      - kpoints (08.2014, JGH)
      43              : !>      - unified k-point and gamma-point code (2014.11) [Ole Schuett]
      44              : !>      - added extra SCF loop for CDFT constraints (12.2015) [Nico Holmberg]
      45              : !> \author Matthias Krack (30.04.2001)
      46              : ! **************************************************************************************************
      47              : MODULE qs_scf
      48              :    USE atomic_kind_types,               ONLY: atomic_kind_type
      49              :    USE cc4s_export,                     ONLY: write_cc4s
      50              :    USE cp_blacs_env,                    ONLY: cp_blacs_env_type
      51              :    USE cp_cfm_types,                    ONLY: cp_cfm_create,&
      52              :                                               cp_cfm_p_type,&
      53              :                                               cp_cfm_release,&
      54              :                                               cp_cfm_to_fm,&
      55              :                                               cp_cfm_type,&
      56              :                                               cp_fm_to_cfm
      57              :    USE cp_control_types,                ONLY: dft_control_type
      58              :    USE cp_dbcsr_api,                    ONLY: &
      59              :         dbcsr_add, dbcsr_copy, dbcsr_create, dbcsr_deallocate_matrix, dbcsr_get_info, &
      60              :         dbcsr_init_p, dbcsr_p_type, dbcsr_release_p, dbcsr_set, dbcsr_type, dbcsr_type_no_symmetry
      61              :    USE cp_dbcsr_operations,             ONLY: copy_dbcsr_to_fm,&
      62              :                                               copy_fm_to_dbcsr,&
      63              :                                               copy_fm_to_dbcsr_bc,&
      64              :                                               cp_dbcsr_m_by_n_from_row_template,&
      65              :                                               dbcsr_deallocate_matrix_set
      66              :    USE cp_files,                        ONLY: close_file
      67              :    USE cp_fm_pool_types,                ONLY: cp_fm_pool_p_type
      68              :    USE cp_fm_struct,                    ONLY: cp_fm_struct_create,&
      69              :                                               cp_fm_struct_release,&
      70              :                                               cp_fm_struct_type
      71              :    USE cp_fm_types,                     ONLY: cp_fm_create,&
      72              :                                               cp_fm_init_random,&
      73              :                                               cp_fm_p_type,&
      74              :                                               cp_fm_release,&
      75              :                                               cp_fm_to_fm,&
      76              :                                               cp_fm_type
      77              :    USE cp_log_handling,                 ONLY: cp_add_default_logger,&
      78              :                                               cp_get_default_logger,&
      79              :                                               cp_logger_release,&
      80              :                                               cp_logger_type,&
      81              :                                               cp_rm_default_logger,&
      82              :                                               cp_to_string
      83              :    USE cp_output_handling,              ONLY: cp_add_iter_level,&
      84              :                                               cp_iterate,&
      85              :                                               cp_p_file,&
      86              :                                               cp_print_key_should_output,&
      87              :                                               cp_print_key_unit_nr,&
      88              :                                               cp_rm_iter_level
      89              :    USE cp_result_methods,               ONLY: get_results,&
      90              :                                               test_for_result
      91              :    USE cp_result_types,                 ONLY: cp_result_type
      92              :    USE dft_plus_u,                      ONLY: lowdin_kp_apply
      93              :    USE ec_env_types,                    ONLY: energy_correction_type
      94              :    USE input_constants,                 ONLY: &
      95              :         broyden_type_1, broyden_type_1_explicit, broyden_type_1_explicit_ls, broyden_type_1_ls, &
      96              :         broyden_type_2, broyden_type_2_explicit, broyden_type_2_explicit_ls, broyden_type_2_ls, &
      97              :         cdft2ot, cholesky_dbcsr, diag_update_method_adiis, history_guess, ot2cdft, &
      98              :         ot_precond_fermi_low_rank, ot_precond_full_all, ot_precond_full_all_covariant, &
      99              :         ot_precond_full_kinetic, ot_precond_full_single, ot_precond_full_single_inverse, &
     100              :         ot_precond_none, ot_precond_s_inverse, outer_scf_becke_constraint, &
     101              :         outer_scf_hirshfeld_constraint, outer_scf_optimizer_broyden, &
     102              :         outer_scf_optimizer_newton_ls, plus_u_lowdin, sic_eo, smear_fermi_dirac, smear_gaussian, &
     103              :         smear_mp, smear_mv, tblite_scc_mixer_tblite
     104              :    USE input_section_types,             ONLY: section_vals_get_subs_vals,&
     105              :                                               section_vals_type
     106              :    USE kinds,                           ONLY: default_path_length,&
     107              :                                               default_string_length,&
     108              :                                               dp
     109              :    USE kpoint_io,                       ONLY: write_kpoints_restart
     110              :    USE kpoint_methods,                  ONLY: kpoint_initialize_mo_set,&
     111              :                                               kpoint_initialize_mos
     112              :    USE kpoint_types,                    ONLY: get_kpoint_info,&
     113              :                                               kpoint_env_type,&
     114              :                                               kpoint_type
     115              :    USE machine,                         ONLY: m_flush,&
     116              :                                               m_walltime
     117              :    USE mathlib,                         ONLY: invert_matrix
     118              :    USE message_passing,                 ONLY: mp_comm_type,&
     119              :                                               mp_para_env_type
     120              :    USE particle_types,                  ONLY: particle_type
     121              :    USE physcon,                         ONLY: evolt
     122              :    USE preconditioner,                  ONLY: &
     123              :         make_preconditioner_complex_fermi_low_rank, make_preconditioner_complex_full_all, &
     124              :         make_preconditioner_complex_full_all_batch, &
     125              :         make_preconditioner_complex_full_all_covariant, make_preconditioner_complex_full_kinetic, &
     126              :         make_preconditioner_complex_full_s_inverse, make_preconditioner_complex_full_single, &
     127              :         make_preconditioner_complex_full_single_inverse, prepare_preconditioner, &
     128              :         restart_preconditioner
     129              :    USE preconditioner_types,            ONLY: destroy_preconditioner,&
     130              :                                               init_preconditioner
     131              :    USE pw_env_types,                    ONLY: pw_env_get,&
     132              :                                               pw_env_type
     133              :    USE pw_pool_types,                   ONLY: pw_pool_type
     134              :    USE qs_block_davidson_types,         ONLY: block_davidson_deallocate
     135              :    USE qs_cdft_scf_utils,               ONLY: build_diagonal_jacobian,&
     136              :                                               create_tmp_logger,&
     137              :                                               initialize_inverse_jacobian,&
     138              :                                               prepare_jacobian_stencil,&
     139              :                                               print_inverse_jacobian,&
     140              :                                               restart_inverse_jacobian
     141              :    USE qs_cdft_types,                   ONLY: cdft_control_type
     142              :    USE qs_charge_mixing,                ONLY: charge_mixing_scc_error
     143              :    USE qs_charges_types,                ONLY: qs_charges_type
     144              :    USE qs_density_matrices,             ONLY: calculate_density_matrix
     145              :    USE qs_density_mixing_types,         ONLY: gspace_mixing_nr
     146              :    USE qs_diis,                         ONLY: qs_diis_b_clear,&
     147              :                                               qs_diis_b_clear_kp,&
     148              :                                               qs_diis_b_create,&
     149              :                                               qs_diis_b_create_kp
     150              :    USE qs_energy_types,                 ONLY: qs_energy_type
     151              :    USE qs_environment_types,            ONLY: get_qs_env,&
     152              :                                               qs_environment_type,&
     153              :                                               set_qs_env
     154              :    USE qs_fod,                          ONLY: qs_fod_validate
     155              :    USE qs_integrate_potential,          ONLY: integrate_v_rspace
     156              :    USE qs_kind_types,                   ONLY: get_qs_kind,&
     157              :                                               qs_kind_type
     158              :    USE qs_kpoint_operators,             ONLY: kpoint_operator_context_create,&
     159              :                                               kpoint_operator_get_local,&
     160              :                                               kpoint_operator_store
     161              :    USE qs_kpoint_state,                 ONLY: qs_kpoint_copy_spin_mos,&
     162              :                                               qs_kpoint_mos_initialized,&
     163              :                                               qs_kpoint_set_fixed_occupations,&
     164              :                                               qs_kpoint_state_canonicalize_fixed,&
     165              :                                               qs_kpoint_state_commit,&
     166              :                                               qs_kpoint_state_prepare_fixed_density
     167              :    USE qs_ks_atom,                      ONLY: update_ks_atom
     168              :    USE qs_ks_methods,                   ONLY: evaluate_core_matrix_traces,&
     169              :                                               qs_ks_update_qs_env
     170              :    USE qs_ks_types,                     ONLY: get_ks_env,&
     171              :                                               qs_ks_did_change,&
     172              :                                               qs_ks_env_type
     173              :    USE qs_local_rho_types,              ONLY: local_rho_set_create,&
     174              :                                               local_rho_set_release,&
     175              :                                               local_rho_type
     176              :    USE qs_matrix_pools,                 ONLY: mpools_get,&
     177              :                                               mpools_rebuild_fm_pools,&
     178              :                                               mpools_release
     179              :    USE qs_mixing_utils,                 ONLY: mixing_init
     180              :    USE qs_mo_io,                        ONLY: write_mo_set_to_restart
     181              :    USE qs_mo_methods,                   ONLY: make_basis_simple,&
     182              :                                               make_basis_sm
     183              :    USE qs_mo_occupation,                ONLY: set_mo_occupation
     184              :    USE qs_mo_types,                     ONLY: allocate_mo_set,&
     185              :                                               deallocate_mo_set,&
     186              :                                               duplicate_mo_set,&
     187              :                                               get_mo_set,&
     188              :                                               init_mo_set,&
     189              :                                               mo_set_restrict,&
     190              :                                               mo_set_type,&
     191              :                                               reassign_allocated_mos
     192              :    USE qs_ot,                           ONLY: qs_ot_complex_multiply,&
     193              :                                               qs_ot_new_preconditioner
     194              :    USE qs_ot_kp,                        ONLY: qs_ot_get_orbitals_local_batch,&
     195              :                                               qs_ot_get_orbitals_ref_complex,&
     196              :                                               qs_ot_get_p_complex
     197              :    USE qs_ot_scf,                       ONLY: ot_scf_destroy,&
     198              :                                               ot_scf_init,&
     199              :                                               ot_scf_read_input
     200              :    USE qs_ot_types,                     ONLY: &
     201              :         qs_ot_allocate, qs_ot_allocate_complex_state, qs_ot_channel_index, &
     202              :         qs_ot_check_channel_context, qs_ot_init, qs_ot_kpoint_preconditioner_solver_supported, &
     203              :         qs_ot_kpoint_preconditioner_supported, qs_ot_number_of_channels, qs_ot_set_context
     204              :    USE qs_outer_scf,                    ONLY: outer_loop_gradient,&
     205              :                                               outer_loop_optimize,&
     206              :                                               outer_loop_purge_history,&
     207              :                                               outer_loop_switch,&
     208              :                                               outer_loop_update_qs_env
     209              :    USE qs_rho_atom_methods,             ONLY: allocate_rho_atom_internals
     210              :    USE qs_rho_atom_types,               ONLY: rho_atom_type,&
     211              :                                               zero_rho_atom_integrals
     212              :    USE qs_rho_methods,                  ONLY: qs_rho_update_rho
     213              :    USE qs_rho_types,                    ONLY: qs_rho_get,&
     214              :                                               qs_rho_type
     215              :    USE qs_scf_diagonalization,          ONLY: do_general_diag_kp
     216              :    USE qs_scf_initialization,           ONLY: qs_scf_env_initialize
     217              :    USE qs_scf_loop_utils,               ONLY: &
     218              :         qs_scf_candidate_density_delta, qs_scf_check_inner_exit, qs_scf_check_outer_exit, &
     219              :         qs_scf_commit_density_candidate, qs_scf_density_mixing, qs_scf_inner_finalize, &
     220              :         qs_scf_kp_search_endpoint, qs_scf_new_mos, qs_scf_new_mos_kp, qs_scf_rho_update, &
     221              :         qs_scf_set_loop_flags
     222              :    USE qs_scf_output,                   ONLY: qs_scf_cdft_info,&
     223              :                                               qs_scf_cdft_initial_info,&
     224              :                                               qs_scf_gce_info,&
     225              :                                               qs_scf_loop_info,&
     226              :                                               qs_scf_loop_print,&
     227              :                                               qs_scf_outer_loop_info,&
     228              :                                               qs_scf_write_mos
     229              :    USE qs_scf_post_scf,                 ONLY: qs_scf_compute_properties
     230              :    USE qs_scf_subspace,                 ONLY: qs_scf_subspace_build,&
     231              :                                               qs_scf_subspace_push,&
     232              :                                               qs_scf_subspace_restart,&
     233              :                                               qs_scf_subspace_update_shift
     234              :    USE qs_scf_subspace_types,           ONLY: qs_scf_subspace_buffer_clear,&
     235              :                                               qs_scf_subspace_buffer_create,&
     236              :                                               qs_scf_subspace_buffer_release
     237              :    USE qs_scf_types,                    ONLY: &
     238              :         block_davidson_diag_method_nr, block_krylov_diag_method_nr, filter_matrix_diag_method_nr, &
     239              :         general_diag_method_nr, ot_diag_method_nr, ot_method_nr, qs_scf_env_type, &
     240              :         scf_env_release_ot_operators, smeagol_method_nr, special_diag_method_nr
     241              :    USE qs_vxc_atom,                     ONLY: gapw_cdft_one_center
     242              :    USE qs_wf_history_methods,           ONLY: wfi_purge_history,&
     243              :                                               wfi_update
     244              :    USE scf_control_types,               ONLY: scf_control_type
     245              :    USE smeagol_interface,               ONLY: run_smeagol_bulktrans,&
     246              :                                               run_smeagol_emtrans
     247              :    USE tblite_interface,                ONLY: tb_get_energy,&
     248              :                                               tb_native_scc_mixer_active,&
     249              :                                               tb_scf_mixer_error,&
     250              :                                               tb_update_charges
     251              : #include "./base/base_uses.f90"
     252              : 
     253              :    IMPLICIT NONE
     254              : 
     255              :    PRIVATE
     256              : 
     257              :    CHARACTER(len=*), PARAMETER, PRIVATE :: moduleN = 'qs_scf'
     258              :    INTEGER, PARAMETER, PRIVATE          :: kp_ot_entry_initial = 1, &
     259              :                                            kp_ot_entry_reuse = 2, &
     260              :                                            kp_ot_entry_resized = 3, &
     261              :                                            kp_ot_entry_refresh = 4
     262              :    LOGICAL, PRIVATE                     :: reuse_precond = .FALSE.
     263              :    LOGICAL, PRIVATE                     :: used_history = .FALSE.
     264              : 
     265              :    PUBLIC :: scf, scf_env_cleanup, scf_env_do_scf, cdft_scf, init_scf_loop
     266              : 
     267              : CONTAINS
     268              : 
     269              : ! **************************************************************************************************
     270              : !> \brief perform an scf procedure in the given qs_env
     271              : !> \param qs_env the qs_environment where to perform the scf procedure
     272              : !> \param has_converged ...
     273              : !> \param total_scf_steps ...
     274              : !> \par History
     275              : !>      02.2003 introduced scf_env, moved real work to scf_env_do_scf [fawzi]
     276              : !> \author fawzi
     277              : !> \note
     278              : ! **************************************************************************************************
     279        25399 :    SUBROUTINE scf(qs_env, has_converged, total_scf_steps)
     280              :       TYPE(qs_environment_type), POINTER                 :: qs_env
     281              :       LOGICAL, INTENT(OUT), OPTIONAL                     :: has_converged
     282              :       INTEGER, INTENT(OUT), OPTIONAL                     :: total_scf_steps
     283              : 
     284              :       INTEGER                                            :: ihistory, max_scf_tmp, tsteps
     285              :       LOGICAL                                            :: converged, outer_scf_loop, should_stop
     286              :       LOGICAL, SAVE                                      :: first_step_flag = .TRUE.
     287        25399 :       REAL(KIND=dp), DIMENSION(:, :), POINTER            :: gradient_history, variable_history
     288              :       TYPE(cp_logger_type), POINTER                      :: logger
     289              :       TYPE(dft_control_type), POINTER                    :: dft_control
     290              :       TYPE(qs_scf_env_type), POINTER                     :: scf_env
     291              :       TYPE(scf_control_type), POINTER                    :: scf_control
     292              :       TYPE(section_vals_type), POINTER                   :: dft_section, input, scf_section
     293              : 
     294        25399 :       NULLIFY (scf_env)
     295        50798 :       logger => cp_get_default_logger()
     296        25399 :       CPASSERT(ASSOCIATED(qs_env))
     297        25399 :       IF (PRESENT(has_converged)) THEN
     298            0 :          has_converged = .FALSE.
     299              :       END IF
     300        25399 :       IF (PRESENT(total_scf_steps)) THEN
     301            0 :          total_scf_steps = 0
     302              :       END IF
     303              :       CALL get_qs_env(qs_env, scf_env=scf_env, input=input, &
     304        25399 :                       dft_control=dft_control, scf_control=scf_control)
     305        25399 :       CALL qs_fod_validate(input, logger, qs_env)
     306        25399 :       qs_env%scf_convergence_available = .FALSE.
     307        25399 :       qs_env%scf_converged = .FALSE.
     308        25399 :       IF (scf_control%max_scf > 0) THEN
     309              : 
     310        24757 :          dft_section => section_vals_get_subs_vals(input, "DFT")
     311        24757 :          scf_section => section_vals_get_subs_vals(dft_section, "SCF")
     312              : 
     313        24757 :          IF (.NOT. ASSOCIATED(scf_env)) THEN
     314         7431 :             CALL qs_scf_env_initialize(qs_env, scf_env)
     315              :             ! Moved here from qs_scf_env_initialize to be able to have more scf_env
     316         7431 :             CALL set_qs_env(qs_env, scf_env=scf_env)
     317              :          ELSE
     318        17326 :             CALL qs_scf_env_initialize(qs_env, scf_env)
     319              :          END IF
     320              : 
     321        24757 :          IF ((scf_control%density_guess == history_guess) .AND. (first_step_flag)) THEN
     322            4 :             max_scf_tmp = scf_control%max_scf
     323            4 :             scf_control%max_scf = 1
     324            4 :             outer_scf_loop = scf_control%outer_scf%have_scf
     325            4 :             scf_control%outer_scf%have_scf = .FALSE.
     326              :          END IF
     327              : 
     328        24757 :          IF (.NOT. dft_control%qs_control%cdft) THEN
     329              :             CALL scf_env_do_scf(scf_env=scf_env, scf_control=scf_control, qs_env=qs_env, &
     330        24395 :                                 converged=converged, should_stop=should_stop, total_scf_steps=tsteps)
     331              :          ELSE
     332              :             ! Third SCF loop needed for CDFT with OT to properly restart OT inner loop
     333              :             CALL cdft_scf(qs_env=qs_env, should_stop=should_stop, &
     334          362 :                           has_converged=converged, total_scf_steps=tsteps)
     335              :          END IF
     336              : 
     337        24757 :          qs_env%scf_convergence_available = .TRUE.
     338        24757 :          qs_env%scf_converged = converged
     339              : 
     340              :          ! If SCF has not converged, then we should not start MP2
     341        24757 :          IF (ASSOCIATED(qs_env%mp2_env)) qs_env%mp2_env%hf_fail = .NOT. converged
     342              : 
     343              :          ! CC4S export is performed only when enabled in the input section.
     344        24757 :          CALL write_cc4s(qs_env, converged)
     345              : 
     346              :          ! Add the converged outer_scf SCF gradient(s)/variable(s) to history
     347        24757 :          IF (scf_control%outer_scf%have_scf) THEN
     348         4451 :             ihistory = scf_env%outer_scf%iter_count
     349              :             CALL get_qs_env(qs_env, gradient_history=gradient_history, &
     350         4451 :                             variable_history=variable_history)
     351              :             ! We only store the latest two values
     352         8936 :             gradient_history(:, 1) = gradient_history(:, 2)
     353        17872 :             gradient_history(:, 2) = scf_env%outer_scf%gradient(:, ihistory)
     354         8936 :             variable_history(:, 1) = variable_history(:, 2)
     355        17872 :             variable_history(:, 2) = scf_env%outer_scf%variables(:, ihistory)
     356              :             ! Reset flag
     357         4451 :             IF (used_history) used_history = .FALSE.
     358              :             ! Update a counter and check if the Jacobian should be deallocated
     359         4451 :             IF (ASSOCIATED(scf_env%outer_scf%inv_jacobian)) THEN
     360           66 :                scf_control%outer_scf%cdft_opt_control%ijacobian(2) = scf_control%outer_scf%cdft_opt_control%ijacobian(2) + 1
     361              :                IF (scf_control%outer_scf%cdft_opt_control%ijacobian(2) >= &
     362           66 :                    scf_control%outer_scf%cdft_opt_control%jacobian_freq(2) .AND. &
     363              :                    scf_control%outer_scf%cdft_opt_control%jacobian_freq(2) > 0) THEN
     364           52 :                   scf_env%outer_scf%deallocate_jacobian = .TRUE.
     365              :                END IF
     366              :             END IF
     367              :          END IF
     368              :          !   *** add the converged wavefunction to the wavefunction history
     369        24757 :          IF ((ASSOCIATED(qs_env%wf_history)) .AND. &
     370              :              ((scf_control%density_guess /= history_guess) .OR. &
     371              :               (.NOT. first_step_flag))) THEN
     372        24753 :             IF (.NOT. dft_control%qs_control%cdft) THEN
     373              :                ! No next geometry step in a standalone single-point calculation.
     374        24391 :                IF (.NOT. qs_env%skip_wf_history) THEN
     375        21157 :                   CALL wfi_update(qs_env%wf_history, qs_env=qs_env, dt=1.0_dp)
     376              :                END IF
     377              :             ELSE
     378          362 :                IF (dft_control%qs_control%cdft_control%should_purge) THEN
     379            0 :                   CALL wfi_purge_history(qs_env)
     380            0 :                   CALL outer_loop_purge_history(qs_env)
     381            0 :                   dft_control%qs_control%cdft_control%should_purge = .FALSE.
     382              :                ELSE
     383          362 :                   CALL wfi_update(qs_env%wf_history, qs_env=qs_env, dt=1.0_dp)
     384              :                END IF
     385              :             END IF
     386            4 :          ELSE IF ((scf_control%density_guess == history_guess) .AND. &
     387              :                   (first_step_flag)) THEN
     388            4 :             scf_control%max_scf = max_scf_tmp
     389            4 :             scf_control%outer_scf%have_scf = outer_scf_loop
     390            4 :             first_step_flag = .FALSE.
     391              :          END IF
     392              : 
     393              :          ! *** compute properties that depend on the converged wavefunction
     394        24757 :          IF (.NOT. (should_stop)) CALL qs_scf_compute_properties(qs_env)
     395              : 
     396              :          ! *** SMEAGOL interface ***
     397        24757 :          IF (.NOT. (should_stop)) THEN
     398              :             ! compute properties that depend on the converged wavefunction ..
     399        24757 :             CALL run_smeagol_emtrans(qs_env, last=.TRUE., iter=0)
     400              :             ! .. or save matrices related to bulk leads
     401        24757 :             CALL run_smeagol_bulktrans(qs_env)
     402              :          END IF
     403              : 
     404              :          ! *** cleanup
     405        24757 :          CALL scf_env_cleanup(scf_env)
     406        24757 :          IF (dft_control%qs_control%cdft) THEN
     407          362 :             CALL cdft_control_cleanup(dft_control%qs_control%cdft_control)
     408              :          END IF
     409              : 
     410        24757 :          IF (PRESENT(has_converged)) THEN
     411            0 :             has_converged = converged
     412              :          END IF
     413        24757 :          IF (PRESENT(total_scf_steps)) THEN
     414            0 :             total_scf_steps = tsteps
     415              :          END IF
     416              : 
     417              :       END IF
     418              : 
     419        25399 :    END SUBROUTINE scf
     420              : 
     421              : ! **************************************************************************************************
     422              : !> \brief perform an scf loop
     423              : !> \param scf_env the scf_env where to perform the scf procedure
     424              : !> \param scf_control ...
     425              : !> \param qs_env the qs_env, the scf_env lives in
     426              : !> \param converged will be true / false if converged is reached
     427              : !> \param should_stop ...
     428              : !> \param total_scf_steps ...
     429              : !> \par History
     430              : !>      long history, see cvs and qs_scf module history
     431              : !>      02.2003 introduced scf_env [fawzi]
     432              : !>      09.2005 Frozen density approximation [TdK]
     433              : !>      06.2007 Check for SCF iteration count early [jgh]
     434              : !>      10.2019 switch_surf_dip [SGh]
     435              : !> \author Matthias Krack
     436              : !> \note
     437              : ! **************************************************************************************************
     438        25133 :    SUBROUTINE scf_env_do_scf(scf_env, scf_control, qs_env, converged, should_stop, total_scf_steps)
     439              : 
     440              :       TYPE(qs_scf_env_type), POINTER                     :: scf_env
     441              :       TYPE(scf_control_type), POINTER                    :: scf_control
     442              :       TYPE(qs_environment_type), POINTER                 :: qs_env
     443              :       LOGICAL, INTENT(OUT)                               :: converged, should_stop
     444              :       INTEGER, INTENT(OUT)                               :: total_scf_steps
     445              : 
     446              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'scf_env_do_scf'
     447              :       INTEGER, PARAMETER :: max_ot_kp_subspace_refreshes = 4
     448              :       REAL(KIND=dp), PARAMETER :: adiis_stagnation_ratio = 1.0E-2_dp
     449              : 
     450              :       CHARACTER(LEN=default_string_length)               :: description, name
     451              :       INTEGER :: accepted_ot_kp_searches, ext_master_id, handle, handle2, i_tmp, ic, ispin, &
     452              :          iter_count, kp_ot_entry_reason, ot_kp_subspace_refresh_count, &
     453              :          ot_kp_subspace_refresh_iter_count, output_unit, scf_energy_message_tag, total_steps
     454              :       LOGICAL :: added_mos_auto_grow, adiis_pushed, adiis_restarted, adiis_stagnated, &
     455              :          adiis_validation, density_full_step, diis_step, do_kpoints, energy_only, exit_inner_loop, &
     456              :          exit_outer_loop, inner_loop_converged, internal_tblite_density_full_step, &
     457              :          internal_tblite_mixer, just_energy, ot_kp_subspace_refresh, &
     458              :          ot_kp_subspace_refresh_pending, outer_loop_converged, tblite_native_mixer, u_changed
     459        25133 :       REAL(dp), POINTER                                  :: subspace_density(:, :), &
     460        25133 :                                                             subspace_fock(:, :)
     461              :       REAL(KIND=dp)                                      :: adiis_raw_delta, adiis_step_delta, t1, t2
     462              :       REAL(KIND=dp), DIMENSION(3)                        :: res_val_3
     463        25133 :       TYPE(atomic_kind_type), DIMENSION(:), POINTER      :: atomic_kind_set
     464              :       TYPE(cp_logger_type), POINTER                      :: logger
     465              :       TYPE(cp_result_type), POINTER                      :: results
     466        25133 :       TYPE(dbcsr_p_type), DIMENSION(:), POINTER          :: matrix_ks
     467        25133 :       TYPE(dbcsr_p_type), DIMENSION(:, :), POINTER       :: matrix_ks_kp, rho_ao_kp
     468              :       TYPE(dft_control_type), POINTER                    :: dft_control
     469              :       TYPE(energy_correction_type), POINTER              :: ec_env
     470              :       TYPE(kpoint_type), POINTER                         :: kpoints
     471        25133 :       TYPE(mo_set_type), DIMENSION(:), POINTER           :: mos, mos_last_converged
     472              :       TYPE(mp_comm_type)                                 :: external_comm
     473              :       TYPE(mp_para_env_type), POINTER                    :: para_env
     474        25133 :       TYPE(particle_type), DIMENSION(:), POINTER         :: particle_set
     475              :       TYPE(pw_env_type), POINTER                         :: pw_env
     476              :       TYPE(qs_charges_type), POINTER                     :: qs_charges
     477              :       TYPE(qs_energy_type), POINTER                      :: energy
     478        25133 :       TYPE(qs_kind_type), DIMENSION(:), POINTER          :: qs_kind_set
     479              :       TYPE(qs_ks_env_type), POINTER                      :: ks_env
     480              :       TYPE(qs_rho_type), POINTER                         :: rho
     481        25133 :       TYPE(rho_atom_type), POINTER                       :: rho_atom(:)
     482              :       TYPE(section_vals_type), POINTER                   :: dft_section, input, scf_section
     483              : 
     484              : ! Weak orbital metrics can need several bounded REF rebuilds to close the canonical density tail.
     485              : 
     486        25133 :       CALL timeset(routineN, handle)
     487              : 
     488        25133 :       NULLIFY (dft_control, rho, energy, &
     489        25133 :                logger, qs_charges, ks_env, mos, atomic_kind_set, qs_kind_set, &
     490        25133 :                particle_set, dft_section, input, &
     491        25133 :                scf_section, para_env, results, kpoints, pw_env, matrix_ks, &
     492        25133 :                matrix_ks_kp, rho_ao_kp, mos_last_converged)
     493              : 
     494        25133 :       CPASSERT(ASSOCIATED(scf_env))
     495        25133 :       CPASSERT(ASSOCIATED(qs_env))
     496              : 
     497        25133 :       logger => cp_get_default_logger()
     498        25133 :       t1 = m_walltime()
     499              : 
     500              :       CALL get_qs_env(qs_env=qs_env, &
     501              :                       energy=energy, &
     502              :                       particle_set=particle_set, &
     503              :                       qs_charges=qs_charges, &
     504              :                       ks_env=ks_env, &
     505              :                       atomic_kind_set=atomic_kind_set, &
     506              :                       qs_kind_set=qs_kind_set, &
     507              :                       rho=rho, &
     508              :                       mos=mos, &
     509              :                       matrix_ks_kp=matrix_ks_kp, &
     510              :                       input=input, &
     511              :                       dft_control=dft_control, &
     512              :                       do_kpoints=do_kpoints, &
     513              :                       kpoints=kpoints, &
     514              :                       results=results, &
     515              :                       pw_env=pw_env, &
     516        25133 :                       para_env=para_env)
     517              :       tblite_native_mixer = dft_control%qs_control%xtb_control%do_tblite .AND. &
     518              :                             scf_env%method /= ot_method_nr .AND. &
     519        25133 :                             tb_native_scc_mixer_active(dft_control)
     520              :       internal_tblite_mixer = (dft_control%qs_control%dftb .AND. &
     521              :                                dft_control%qs_control%dftb_control%tblite_scc_mixer == tblite_scc_mixer_tblite) .OR. &
     522              :                               (dft_control%qs_control%xtb .AND. &
     523              :                                .NOT. dft_control%qs_control%xtb_control%do_tblite .AND. &
     524        25133 :                                dft_control%qs_control%xtb_control%tblite_scc_mixer == tblite_scc_mixer_tblite)
     525              :       internal_tblite_density_full_step = dft_control%qs_control%xtb .AND. &
     526              :                                           .NOT. dft_control%qs_control%xtb_control%do_tblite .AND. &
     527        25133 :                                           dft_control%qs_control%xtb_control%tblite_scc_mixer == tblite_scc_mixer_tblite
     528              : 
     529        25133 :       CALL qs_rho_get(rho, rho_ao_kp=rho_ao_kp)
     530              : 
     531        25133 :       dft_section => section_vals_get_subs_vals(input, "DFT")
     532        25133 :       scf_section => section_vals_get_subs_vals(dft_section, "SCF")
     533              : 
     534              :       output_unit = cp_print_key_unit_nr(logger, scf_section, "PRINT%PROGRAM_RUN_INFO", &
     535        25133 :                                          extension=".scfLog")
     536              : 
     537        25133 :       IF (scf_control%gce%do_gce .AND. output_unit > 0) THEN
     538            4 :          WRITE (UNIT=output_unit, FMT="(/,T2,78('-'))")
     539              :          WRITE (UNIT=output_unit, FMT="(T31,A)") &
     540            4 :             "GRAND-CANONICAL SCF"
     541              :          WRITE (UNIT=output_unit, FMT="(T20,A,F12.6,A)") &
     542            4 :             "Target work function (TWF):", &
     543            8 :             evolt*scf_control%gce%target_workfunction, " eV"
     544            4 :          WRITE (UNIT=output_unit, FMT="(T2,78('-'))")
     545              :       END IF
     546              : 
     547        25133 :       IF (output_unit > 0) WRITE (UNIT=output_unit, FMT="(/,/,T2,A)") &
     548        12724 :          "SCF WAVEFUNCTION OPTIMIZATION"
     549              : 
     550              :       ! when switch_surf_dip is switched on, indicate storing mos from the last converged step
     551        25133 :       IF (dft_control%switch_surf_dip) THEN
     552            2 :          CALL get_qs_env(qs_env, mos_last_converged=mos_last_converged)
     553            4 :          DO ispin = 1, dft_control%nspins
     554            4 :             CALL reassign_allocated_mos(mos(ispin), mos_last_converged(ispin))
     555              :          END DO
     556            2 :          IF (output_unit > 0) WRITE (UNIT=output_unit, FMT="(/,/,T2,A)") &
     557            1 :             "COPIED mos_last_converged ---> mos"
     558              :       END IF
     559              : 
     560        25133 :       IF ((output_unit > 0) .AND. (.NOT. scf_control%use_ot)) THEN
     561              :          WRITE (UNIT=output_unit, &
     562              :                 FMT="(/,T3,A,T12,A,T31,A,T39,A,T59,A,T75,A,/,T3,A)") &
     563         9175 :             "Step", "Update method", "Time", "Convergence", "Total energy", "Change", &
     564        18350 :             REPEAT("-", 78)
     565              :       END IF
     566        25133 :       CALL cp_add_iter_level(logger, "QS_SCF")
     567              : 
     568              :       ! check for external communicator and if the intermediate energy should be sent
     569       100532 :       res_val_3(:) = -1.0_dp
     570        25133 :       description = "[EXT_SCF_ENER_COMM]"
     571        25133 :       IF (test_for_result(results, description=description)) THEN
     572              :          CALL get_results(results, description=description, &
     573            0 :                           values=res_val_3, n_entries=i_tmp)
     574            0 :          CPASSERT(i_tmp == 3)
     575            0 :          IF (ALL(res_val_3(:) <= 0.0_dp)) THEN
     576              :             CALL cp_abort(__LOCATION__, &
     577              :                           " Trying to access result ("//TRIM(description)// &
     578            0 :                           ") which is not correctly stored.")
     579              :          END IF
     580            0 :          CALL external_comm%set_handle(NINT(res_val_3(1)))
     581              :       END IF
     582        25133 :       ext_master_id = NINT(res_val_3(2))
     583        25133 :       scf_energy_message_tag = NINT(res_val_3(3))
     584              : 
     585              :       ! *** outer loop of the scf, can treat other variables,
     586              :       ! *** such as lagrangian multipliers
     587        25133 :       scf_env%outer_scf%iter_count = 0
     588        25133 :       accepted_ot_kp_searches = 0
     589        25133 :       iter_count = 0
     590        25133 :       kp_ot_entry_reason = kp_ot_entry_initial
     591        25133 :       ot_kp_subspace_refresh_count = 0
     592        25133 :       ot_kp_subspace_refresh_iter_count = 0
     593        25133 :       ot_kp_subspace_refresh_pending = .FALSE.
     594        25133 :       total_steps = 0
     595        25133 :       energy%tot_old = 0.0_dp
     596              : 
     597              :       scf_outer_loop: DO
     598              : 
     599              :          CALL init_scf_loop(scf_env=scf_env, qs_env=qs_env, &
     600              :                             scf_section=scf_section, &
     601        26043 :                             kp_ot_entry_reason=kp_ot_entry_reason)
     602        26043 :          kp_ot_entry_reason = kp_ot_entry_reuse
     603        26043 :          scf_env%adiis_shift = scf_control%diagonalization%adiis_shift
     604              : 
     605              :          CALL qs_scf_set_loop_flags(scf_env, diis_step, &
     606        26043 :                                     energy_only, just_energy, exit_inner_loop)
     607        26043 :          IF (ot_kp_subspace_refresh_pending) THEN
     608           16 :             scf_env%iter_count = ot_kp_subspace_refresh_iter_count
     609           16 :             ot_kp_subspace_refresh_pending = .FALSE.
     610              :          END IF
     611              : 
     612              :          ! decide whether to switch off dipole correction for convergence purposes
     613        26043 :          dft_control%surf_dip_correct_switch = dft_control%correct_surf_dip
     614        26043 :          IF ((dft_control%correct_surf_dip) .AND. (scf_control%outer_scf%have_scf) .AND. &
     615              :              (scf_env%outer_scf%iter_count > FLOOR(scf_control%outer_scf%max_scf/2.0_dp))) THEN
     616            0 :             IF (dft_control%switch_surf_dip) THEN
     617            0 :                dft_control%surf_dip_correct_switch = .FALSE.
     618            0 :                IF (output_unit > 0) WRITE (UNIT=output_unit, FMT="(/,/,T2,A)") &
     619            0 :                   "SURFACE DIPOLE CORRECTION switched off"
     620              :             END IF
     621              :          END IF
     622              : 
     623       485220 :          scf_loop: DO
     624              : 
     625       242625 :             CALL timeset(routineN//"_inner_loop", handle2)
     626              : 
     627       242625 :             IF (.NOT. just_energy) scf_env%iter_count = scf_env%iter_count + 1
     628       242625 :             iter_count = iter_count + 1
     629       242625 :             CALL cp_iterate(logger%iter_info, last=.FALSE., iter_nr=iter_count)
     630              : 
     631       242625 :             IF (output_unit > 0) CALL m_flush(output_unit)
     632              : 
     633       242625 :             total_steps = total_steps + 1
     634       242625 :             just_energy = energy_only
     635              : 
     636              :             CALL qs_ks_update_qs_env(qs_env, just_energy=just_energy, &
     637       242625 :                                      calculate_forces=.FALSE.)
     638              : 
     639       242625 :             scf_env%raw_map_delta = 0.0_dp
     640       242625 :             scf_env%raw_map_delta_valid = .FALSE.
     641              :             ! print 'heavy weight' or relatively expensive quantities
     642       242625 :             CALL qs_scf_loop_print(qs_env, scf_env, para_env)
     643              : 
     644       242625 :             added_mos_auto_grow = .FALSE.
     645       242625 :             ot_kp_subspace_refresh = .FALSE.
     646              :             adiis_validation = scf_control%diagonalization%update_method == diag_update_method_adiis .AND. &
     647       242625 :                                scf_env%adiis_check_next
     648       242625 :             adiis_step_delta = scf_env%step_norm
     649       242625 :             scf_env%adiis_validated = .FALSE.
     650              : 
     651       242625 :             IF (scf_control%diagonalization%update_method == diag_update_method_adiis) THEN
     652          152 :                NULLIFY (subspace_density, subspace_fock)
     653          152 :                IF (do_kpoints) THEN
     654           80 :                   IF (ALLOCATED(kpoints%lowdin_q)) THEN
     655            0 :                      subspace_density => kpoints%lowdin_q
     656            0 :                      subspace_fock => kpoints%lowdin_v
     657              :                   END IF
     658              :                END IF
     659              :                ! ADIIS is a Fock-space SCF method and never uses density mixing.  A small
     660              :                ! accelerated step is checked against the unmodified F[P] map before
     661              :                ! convergence is accepted. The check detects an artificial subspace zero;
     662              :                ! it is not a second, equally strict convergence criterion.
     663          152 :                CPASSERT(ASSOCIATED(scf_env%scf_subspace_buffer))
     664          152 :                scf_env%scf_subspace_buffer%last_restart = .FALSE.
     665          152 :                scf_env%scf_subspace_buffer%use_combined_fock = .FALSE.
     666          152 :                scf_env%scf_subspace_buffer%last_old_fock_weight = 0.0_dp
     667          152 :                IF (.NOT. adiis_validation .AND. scf_env%iter_count > 1) THEN
     668              :                   ! Only accepted densities whose raw F[P] has just been evaluated enter history.
     669              :                   ! The initial guess and raw-validation trial endpoint are deliberately excluded.
     670              :                   ! A shifted candidate needs a current ADIIS fallback even if CDIIS was
     671              :                   ! active last time: its acceptance is decided later, during diagonalization.
     672              :                   IF (scf_control%diagonalization%adiis_shift > 0.0_dp .OR. &
     673          140 :                       scf_env%scf_subspace_buffer%diis_weight < 1.0_dp .OR. &
     674              :                       scf_env%iter_delta >= scf_control%eps_diis) THEN
     675              :                      CALL qs_scf_subspace_push(scf_env%scf_subspace_buffer, matrix_ks_kp, rho_ao_kp, &
     676          110 :                                                energy%total, adiis_pushed, subspace_density, subspace_fock)
     677          110 :                      IF (.NOT. adiis_pushed) CPABORT("Failed to append the accepted ADIIS SCF state")
     678          110 :                      CALL qs_scf_subspace_build(scf_env%scf_subspace_buffer)
     679          110 :                      IF (scf_control%diagonalization%adiis_shift > 0.0_dp) THEN
     680           50 :                         CALL qs_scf_subspace_update_shift(scf_env%scf_subspace_buffer, scf_env%adiis_shift)
     681              :                      END IF
     682              :                   END IF
     683              :                END IF
     684          152 :                IF (do_kpoints) THEN
     685              :                   CALL qs_scf_new_mos_kp(qs_env, scf_env, scf_control, diis_step, &
     686           80 :                                          added_mos_auto_grow=added_mos_auto_grow)
     687              :                ELSE
     688           72 :                   CALL qs_scf_new_mos(qs_env, scf_env, scf_control, scf_section, diis_step, energy_only)
     689              :                END IF
     690              : 
     691          152 :                IF (adiis_validation) THEN
     692            0 :                   CALL qs_scf_candidate_density_delta(scf_env, rho, para_env, adiis_raw_delta, kpoints)
     693            0 :                   scf_env%raw_map_delta = adiis_raw_delta
     694            0 :                   scf_env%raw_map_delta_valid = .TRUE.
     695            0 :                   IF (adiis_raw_delta < scf_control%eps_scf) THEN
     696            0 :                      scf_env%iter_delta = adiis_raw_delta
     697            0 :                      scf_env%iter_param = 0.0_dp
     698            0 :                      scf_env%iter_method = "ADIIS/Chk."
     699            0 :                      scf_env%adiis_validated = .TRUE.
     700            0 :                      scf_env%adiis_check_next = .FALSE.
     701              :                   ELSE
     702            0 :                      adiis_stagnated = adiis_step_delta <= adiis_stagnation_ratio*adiis_raw_delta
     703            0 :                      IF (adiis_stagnated) THEN
     704              :                         ! A nearly vanishing ADIIS step can be a fixed point of the current
     705              :                         ! subspace without being a fixed point of the raw SCF map.  Discard
     706              :                         ! the stale subspace, retain the current paired P,F[P] state, and
     707              :                         ! accept the already computed raw candidate as the restart step.
     708              :                         ! This avoids duplicate history entries and a second diagonalization.
     709              :                         CALL qs_scf_subspace_restart(scf_env%scf_subspace_buffer, matrix_ks_kp, rho_ao_kp, &
     710            0 :                                                      energy%total, adiis_restarted, subspace_density, subspace_fock)
     711            0 :                         IF (.NOT. adiis_restarted) THEN
     712            0 :                            CPABORT("Failed to restart the ADIIS history from the current SCF state")
     713              :                         END IF
     714            0 :                         scf_env%iter_delta = adiis_raw_delta
     715            0 :                         scf_env%iter_param = 0.0_dp
     716            0 :                         scf_env%iter_method = "ADIIS/Rst."
     717            0 :                         scf_env%adiis_check_next = .FALSE.
     718              :                      ELSE
     719              :                         ! The raw map is not converged, but the accelerated step is not an
     720              :                         ! artificial subspace zero. Preserve the useful history, discard the
     721              :                         ! raw trial, and repeat the normal ADIIS step in this iteration.
     722              :                         CALL qs_scf_subspace_push(scf_env%scf_subspace_buffer, matrix_ks_kp, rho_ao_kp, &
     723            0 :                                                   energy%total, adiis_pushed, subspace_density, subspace_fock)
     724            0 :                         IF (.NOT. adiis_pushed) CPABORT("Failed to append the accepted ADIIS SCF state")
     725            0 :                         CALL qs_scf_subspace_build(scf_env%scf_subspace_buffer)
     726            0 :                         IF (do_kpoints) THEN
     727              :                            CALL qs_scf_new_mos_kp(qs_env, scf_env, scf_control, diis_step, &
     728            0 :                                                   added_mos_auto_grow=added_mos_auto_grow)
     729              :                         ELSE
     730            0 :                            CALL qs_scf_new_mos(qs_env, scf_env, scf_control, scf_section, diis_step, energy_only)
     731              :                         END IF
     732            0 :                         CALL qs_scf_candidate_density_delta(scf_env, rho, para_env, scf_env%iter_delta, kpoints)
     733            0 :                         scf_env%adiis_validated = scf_env%iter_delta < scf_control%eps_scf
     734            0 :                         IF (scf_env%adiis_validated .AND. .NOT. diis_step) THEN
     735            0 :                            scf_env%iter_param = 0.0_dp
     736            0 :                            scf_env%iter_method = "ADIIS/Chk."
     737              :                         END IF
     738              :                         ! A successful sanity check must not recursively demand another raw
     739              :                         ! endpoint check. A later, independently small step can trigger one.
     740            0 :                         scf_env%adiis_check_next = .FALSE.
     741              :                      END IF
     742              :                   END IF
     743              :                END IF
     744              : 
     745              :                IF (.NOT. adiis_validation) THEN
     746          152 :                   CALL qs_scf_candidate_density_delta(scf_env, rho, para_env, scf_env%iter_delta, kpoints)
     747              :                   scf_env%adiis_check_next = .NOT. diis_step .AND. &
     748          304 :                                              scf_env%iter_delta < scf_control%eps_scf
     749              :                END IF
     750              :             ELSE
     751              :                ! Keep the existing density-mixing SCF path unchanged.
     752       242473 :                IF (do_kpoints) THEN
     753              :                   ! kpoints
     754        40932 :                   IF (dft_control%hairy_probes .EQV. .TRUE.) THEN
     755            0 :                      scf_control%smear%do_smear = .FALSE.
     756              :                      CALL qs_scf_new_mos_kp(qs_env, scf_env, scf_control, diis_step, dft_control%probe, &
     757            0 :                                             energy_only=energy_only)
     758              :                   ELSE
     759              :                      CALL qs_scf_new_mos_kp( &
     760              :                         qs_env, scf_env, scf_control, diis_step, &
     761              :                         ot_kp_subspace_refresh=ot_kp_subspace_refresh, &
     762              :                         allow_ot_kp_subspace_refresh= &
     763              :                         ot_kp_subspace_refresh_count == 0, &
     764              :                         allow_ot_kp_exit_refresh= &
     765              :                         ot_kp_subspace_refresh_count > 0 .AND. &
     766              :                         ot_kp_subspace_refresh_count < max_ot_kp_subspace_refreshes, &
     767              :                         accepted_ot_kp_searches=accepted_ot_kp_searches, &
     768        40932 :                         added_mos_auto_grow=added_mos_auto_grow, energy_only=energy_only)
     769              :                   END IF
     770              :                ELSE
     771              :                   ! Gamma points only
     772       201541 :                   IF (dft_control%hairy_probes .EQV. .TRUE.) THEN
     773           14 :                      scf_control%smear%do_smear = .FALSE.
     774              :                      CALL qs_scf_new_mos(qs_env, scf_env, scf_control, scf_section, diis_step, energy_only, &
     775           14 :                                          dft_control%probe)
     776              :                   ELSE
     777       201527 :                      CALL qs_scf_new_mos(qs_env, scf_env, scf_control, scf_section, diis_step, energy_only)
     778              :                   END IF
     779              :                END IF
     780              :             END IF
     781              : 
     782       242625 :             IF (added_mos_auto_grow) THEN
     783           14 :                CALL qs_scf_grow_added_mos_auto_kp(qs_env, scf_env, scf_control, output_unit)
     784           14 :                kp_ot_entry_reason = kp_ot_entry_resized
     785           14 :                total_steps = MAX(0, total_steps - 1)
     786           14 :                iter_count = MAX(0, iter_count - 1)
     787           14 :                IF (.NOT. just_energy) scf_env%iter_count = MAX(0, scf_env%iter_count - 1)
     788           14 :                CALL timestop(handle2)
     789           14 :                CYCLE scf_outer_loop
     790              :             END IF
     791              : 
     792       242611 :             IF (ot_kp_subspace_refresh) THEN
     793           16 :                IF (output_unit > 0) THEN
     794              :                   WRITE (UNIT=output_unit, FMT="(T2,A)") &
     795            8 :                      "K-point OT: rebuilding physical virtual subspace by full KS diagonalization."
     796              :                END IF
     797           16 :                CALL qs_kpoint_state_commit(qs_env, update_occupations=.FALSE.)
     798           16 :                IF (ASSOCIATED(scf_env%qs_ot_env)) THEN
     799           50 :                   DO ispin = 1, SIZE(scf_env%qs_ot_env)
     800           50 :                      CALL ot_scf_destroy(scf_env%qs_ot_env(ispin))
     801              :                   END DO
     802           16 :                   DEALLOCATE (scf_env%qs_ot_env)
     803           16 :                   NULLIFY (scf_env%qs_ot_env)
     804              :                END IF
     805           16 :                IF (ASSOCIATED(kpoints%scf_diis_buffer)) THEN
     806            0 :                   CALL qs_diis_b_clear_kp(kpoints%scf_diis_buffer)
     807              :                END IF
     808           16 :                reuse_precond = .FALSE.
     809           16 :                accepted_ot_kp_searches = 0
     810           16 :                ot_kp_subspace_refresh_count = ot_kp_subspace_refresh_count + 1
     811           16 :                total_steps = MAX(0, total_steps - 1)
     812           16 :                iter_count = MAX(0, iter_count - 1)
     813           16 :                IF (.NOT. just_energy) scf_env%iter_count = MAX(0, scf_env%iter_count - 1)
     814           16 :                ot_kp_subspace_refresh_iter_count = scf_env%iter_count
     815           16 :                ot_kp_subspace_refresh_pending = .TRUE.
     816           16 :                kp_ot_entry_reason = kp_ot_entry_refresh
     817           16 :                CALL timestop(handle2)
     818           16 :                CYCLE scf_outer_loop
     819              :             END IF
     820              : 
     821       242595 :             IF (do_kpoints .AND. scf_env%method == ot_method_nr .AND. &
     822              :                 qs_scf_kp_search_endpoint(scf_env%iter_method)) THEN
     823         1854 :                accepted_ot_kp_searches = accepted_ot_kp_searches + 1
     824              :             END IF
     825              : 
     826              :             ! Print requested MO information (can be computationally expensive with OT)
     827       242595 :             CALL qs_scf_write_mos(qs_env, scf_env, final_mos=.FALSE.)
     828              : 
     829       242595 :             IF (dft_control%qs_control%xtb_control%do_tblite) THEN
     830        25620 :                IF (scf_env%method == ot_method_nr) THEN
     831          840 :                   CALL tb_update_charges(qs_env, dft_control, qs_env%tb_tblite, .FALSE., .TRUE.)
     832          840 :                   CALL evaluate_core_matrix_traces(qs_env)
     833              :                ELSE
     834        24780 :                   CPASSERT(scf_env%mixing_method > 0)
     835        24780 :                   CALL tb_update_charges(qs_env, dft_control, qs_env%tb_tblite, .FALSE., .FALSE.)
     836        24780 :                   CALL evaluate_core_matrix_traces(qs_env, rho_ao_ext=scf_env%p_mix_new)
     837              :                END IF
     838        25620 :                CALL tb_get_energy(qs_env, qs_env%tb_tblite, energy)
     839              :             END IF
     840              : 
     841       242595 :             IF (scf_control%diagonalization%update_method == diag_update_method_adiis) THEN
     842          152 :                CALL qs_scf_commit_density_candidate(scf_env, rho)
     843          152 :                density_full_step = .TRUE.
     844              :             ELSE
     845       242443 :                density_full_step = diis_step .OR. tblite_native_mixer .OR. internal_tblite_density_full_step
     846       242443 :                CALL qs_scf_density_mixing(scf_env, rho, para_env, density_full_step, kpoints)
     847              :             END IF
     848       242595 :             IF (dft_control%qs_control%xtb_control%do_tblite .AND. &
     849              :                 .NOT. (dft_control%qs_control%do_ls_scf .OR. scf_control%use_ot)) THEN
     850              :                scf_env%iter_delta = MAX(scf_env%iter_delta, &
     851              :                                         tb_scf_mixer_error(dft_control, qs_env%tb_tblite, &
     852        24780 :                                                            scf_control%eps_scf))
     853              :             END IF
     854       242595 :             IF (dft_control%qs_control%dftb .OR. &
     855              :                 (dft_control%qs_control%xtb .AND. .NOT. dft_control%qs_control%xtb_control%do_tblite)) THEN
     856              :                scf_env%iter_delta = MAX(scf_env%iter_delta, &
     857        57286 :                                         charge_mixing_scc_error(scf_env%mixing_store, scf_control%eps_scf))
     858              :             END IF
     859       242595 :             IF (tblite_native_mixer) THEN
     860        22624 :                scf_env%iter_param = dft_control%qs_control%xtb_control%tblite_mixer_damping
     861        22624 :                scf_env%iter_method = "TBLite/Diag"
     862       219971 :             ELSE IF (internal_tblite_mixer) THEN
     863           30 :                scf_env%iter_method = "TBLite/Diag"
     864           30 :                IF (dft_control%qs_control%dftb) THEN
     865           18 :                   scf_env%iter_param = dft_control%qs_control%dftb_control%tblite_mixer_damping
     866              :                ELSE
     867           12 :                   scf_env%iter_param = dft_control%qs_control%xtb_control%tblite_mixer_damping
     868              :                END IF
     869              :             END IF
     870       242595 :             scf_env%step_norm = scf_env%iter_delta
     871              : 
     872       242595 :             t2 = m_walltime()
     873              : 
     874       242595 :             CALL rebuild_xtb_total_energy(energy, dft_control)
     875              :             CALL qs_scf_loop_info(scf_env, output_unit, just_energy, t1, t2, energy, &
     876       242595 :                                   scf_control%diagonalization%adiis_verbose)
     877              : 
     878       242595 :             IF (scf_control%gce%do_gce) THEN
     879          384 :                CALL qs_scf_gce_info(output_unit, qs_env, just_energy)
     880              :             END IF
     881              : 
     882       242595 :             IF (.NOT. just_energy) energy%tot_old = energy%total
     883              : 
     884              :             ! check for external communicator and if the intermediate energy should be sent
     885       242595 :             IF (scf_energy_message_tag > 0) THEN
     886            0 :                CALL external_comm%send(energy%total, ext_master_id, scf_energy_message_tag)
     887              :             END IF
     888              : 
     889              :             CALL qs_scf_check_inner_exit(qs_env, scf_env, scf_control, should_stop, just_energy, &
     890       242595 :                                          exit_inner_loop, inner_loop_converged, output_unit, u_changed)
     891       242595 :             IF (u_changed) THEN
     892            0 :                CALL qs_scf_inner_finalize(scf_env, qs_env, density_full_step, 0)
     893            0 :                IF (scf_env%mixing_method > 1) THEN
     894            0 :                   CALL get_qs_env(qs_env, rho_atom_set=rho_atom)
     895              :                   CALL mixing_init(scf_env%mixing_method, rho, scf_env%mixing_store, para_env, &
     896            0 :                                    rho_atom=rho_atom, auxiliary=kpoints%lowdin_q)
     897              :                END IF
     898            0 :                CALL init_scf_loop(scf_env, qs_env, scf_section, kp_ot_entry_reuse)
     899            0 :                energy_only = .FALSE.
     900            0 :                just_energy = .FALSE.
     901            0 :                CALL timestop(handle2)
     902            0 :                CYCLE scf_loop
     903              :             END IF
     904              : 
     905              :             ! In case we decide to exit we perform few more check to see if this one
     906              :             ! is really the last SCF step
     907       242595 :             IF (exit_inner_loop) THEN
     908              : 
     909        26013 :                CALL qs_scf_inner_finalize(scf_env, qs_env, density_full_step, output_unit)
     910              : 
     911              :                CALL qs_scf_check_outer_exit(qs_env, scf_env, scf_control, should_stop, &
     912        26013 :                                             outer_loop_converged, exit_outer_loop)
     913              : 
     914              :                ! Let's tag the last SCF cycle so we can print informations only of the last step
     915        26013 :                IF (exit_outer_loop) CALL cp_iterate(logger%iter_info, last=.TRUE., iter_nr=iter_count)
     916              : 
     917              :             END IF
     918              : 
     919       242595 :             IF (do_kpoints) THEN
     920        40982 :                CALL write_kpoints_restart(rho_ao_kp, kpoints, scf_env, dft_section, particle_set, qs_kind_set)
     921              :             ELSE
     922       201613 :                IF (.NOT. dft_control%mtlr_dft_with_perturbation) THEN
     923              :                   ! Write wavefunction restart file
     924              :                   ! A low-spin ROKS state is not invariant under separate occupied-space
     925              :                   ! rotations of the two spins. Preserve its shared orbitals in GAPW restarts.
     926       199769 :                   IF (scf_env%method == ot_method_nr .AND. &
     927              :                       .NOT. (dft_control%low_spin_roks .AND. dft_control%qs_control%gapw)) THEN
     928              :                      ! With OT: provide the Kohn-Sham matrix for the calculation of the MO eigenvalues
     929        79058 :                      CALL get_ks_env(ks_env=ks_env, matrix_ks=matrix_ks)
     930              :                      CALL write_mo_set_to_restart(mos, particle_set, dft_section=dft_section, qs_kind_set=qs_kind_set, &
     931        79058 :                                                   matrix_ks=matrix_ks)
     932              :                   ELSE
     933       120711 :                      CALL write_mo_set_to_restart(mos, particle_set, dft_section=dft_section, qs_kind_set=qs_kind_set)
     934              :                   END IF
     935              :                END IF
     936              :             END IF
     937              : 
     938              :             ! Exit if we have finished with the SCF inner loop
     939       242595 :             IF (exit_inner_loop) THEN
     940        26013 :                CALL timestop(handle2)
     941              :                EXIT scf_loop
     942              :             END IF
     943              : 
     944       216582 :             IF (.NOT. BTEST(cp_print_key_should_output(logger%iter_info, &
     945              :                                                        scf_section, "PRINT%ITERATION_INFO/TIME_CUMUL"), cp_p_file)) THEN
     946       216582 :                t1 = m_walltime()
     947              :             END IF
     948              : 
     949              :             ! mixing methods have the new density matrix in p_mix_new
     950       216582 :             IF (scf_env%mixing_method > 0) THEN
     951      1826926 :                DO ic = 1, SIZE(rho_ao_kp, 2)
     952      3669111 :                   DO ispin = 1, dft_control%nspins
     953      1842185 :                      CALL dbcsr_get_info(rho_ao_kp(ispin, ic)%matrix, name=name) ! keep the name
     954      3528454 :                      CALL dbcsr_copy(rho_ao_kp(ispin, ic)%matrix, scf_env%p_mix_new(ispin, ic)%matrix, name=name)
     955              :                   END DO
     956              :                END DO
     957              :             END IF
     958              : 
     959              :             CALL qs_scf_rho_update(rho, qs_env, scf_env, ks_env, &
     960       216582 :                                    mix_rho=scf_env%mixing_method >= gspace_mixing_nr)
     961              : 
     962       216582 :             CALL timestop(handle2)
     963              : 
     964              :          END DO scf_loop
     965              : 
     966        26013 :          IF (.NOT. scf_control%outer_scf%have_scf) EXIT scf_outer_loop
     967              : 
     968              :          ! In case we use the OUTER SCF loop let's print some info..
     969              :          CALL qs_scf_outer_loop_info(output_unit, scf_control, scf_env, &
     970         5705 :                                      energy, total_steps, should_stop, outer_loop_converged)
     971              : 
     972              :          ! Save MOs to converged MOs if outer_loop_converged and surf_dip_correct_switch is true
     973         5705 :          IF (exit_outer_loop) THEN
     974         4825 :             IF ((dft_control%switch_surf_dip) .AND. (outer_loop_converged) .AND. &
     975              :                 (dft_control%surf_dip_correct_switch)) THEN
     976            4 :                DO ispin = 1, dft_control%nspins
     977            4 :                   CALL reassign_allocated_mos(mos_last_converged(ispin), mos(ispin))
     978              :                END DO
     979            2 :                IF (output_unit > 0) WRITE (UNIT=output_unit, FMT="(/,/,T2,A)") &
     980            1 :                   "COPIED mos ---> mos_last_converged"
     981              :             END IF
     982              :          END IF
     983              : 
     984         5705 :          IF (exit_outer_loop) EXIT scf_outer_loop
     985              : 
     986              :          !
     987          880 :          CALL outer_loop_optimize(scf_env, scf_control)
     988          880 :          CALL outer_loop_update_qs_env(qs_env, scf_env)
     989        26013 :          CALL qs_ks_did_change(ks_env, potential_changed=.TRUE.)
     990              : 
     991              :       END DO scf_outer_loop
     992              : 
     993        25133 :       converged = inner_loop_converged .AND. outer_loop_converged
     994        25133 :       total_scf_steps = total_steps
     995              : 
     996        25133 :       IF (dft_control%qs_control%cdft) THEN
     997              :          dft_control%qs_control%cdft_control%total_steps = &
     998          736 :             dft_control%qs_control%cdft_control%total_steps + total_steps
     999              :       END IF
    1000              : 
    1001        25133 :       IF (.NOT. converged) THEN
    1002         2248 :          IF (scf_control%ignore_convergence_failure .OR. should_stop) THEN
    1003         2248 :             CALL cp_warn(__LOCATION__, "SCF run NOT converged")
    1004              :          ELSE
    1005              :             CALL cp_abort(__LOCATION__, &
    1006              :                           "SCF run NOT converged. To continue the calculation "// &
    1007            0 :                           "regardless, please set the keyword IGNORE_CONVERGENCE_FAILURE.")
    1008              :          END IF
    1009              :       END IF
    1010              : 
    1011              :       ! Skip Harris functional calculation if ground-state is NOT converged
    1012        25133 :       IF (qs_env%energy_correction) THEN
    1013          698 :          CALL get_qs_env(qs_env, ec_env=ec_env)
    1014          698 :          ec_env%do_skip = .FALSE.
    1015          698 :          IF (ec_env%skip_ec .AND. .NOT. converged) ec_env%do_skip = .TRUE.
    1016              :       END IF
    1017              : 
    1018              :       ! if needed copy mo_coeff dbcsr->fm for later use in post_scf!fm->dbcsr
    1019        54234 :       DO ispin = 1, SIZE(mos) !fm -> dbcsr
    1020        54234 :          IF (mos(ispin)%use_mo_coeff_b) THEN !fm->dbcsr
    1021         8403 :             IF (.NOT. ASSOCIATED(mos(ispin)%mo_coeff_b)) THEN
    1022              :                !fm->dbcsr
    1023            0 :                CPABORT("mo_coeff_b is not allocated")
    1024              :             END IF !fm->dbcsr
    1025              :             CALL copy_dbcsr_to_fm(mos(ispin)%mo_coeff_b, & !fm->dbcsr
    1026         8403 :                                   mos(ispin)%mo_coeff) !fm -> dbcsr
    1027              :          END IF !fm->dbcsr
    1028              :       END DO !fm -> dbcsr
    1029              : 
    1030        25133 :       CALL cp_rm_iter_level(logger, level_name="QS_SCF")
    1031        25133 :       CALL timestop(handle)
    1032              : 
    1033        25133 :    END SUBROUTINE scf_env_do_scf
    1034              : 
    1035              : ! **************************************************************************************************
    1036              : !> \brief grow an automatic k-point smearing virtual space and rebuild dimensioned state
    1037              : !> \param qs_env ...
    1038              : !> \param scf_env ...
    1039              : !> \param scf_control ...
    1040              : !> \param output_unit ...
    1041              : ! **************************************************************************************************
    1042           14 :    SUBROUTINE qs_scf_grow_added_mos_auto_kp(qs_env, scf_env, scf_control, output_unit)
    1043              : 
    1044              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    1045              :       TYPE(qs_scf_env_type), POINTER                     :: scf_env
    1046              :       TYPE(scf_control_type), POINTER                    :: scf_control
    1047              :       INTEGER, INTENT(IN)                                :: output_unit
    1048              : 
    1049              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'qs_scf_grow_added_mos_auto_kp'
    1050              : 
    1051              :       INTEGER :: base_nmo, common_base_nmo, current_added, current_target_nmo, grow_by, handle, &
    1052              :          ic, ik, ispin, nmo_mat, nspins, old_nmo, target_nmo
    1053              :       INTEGER, DIMENSION(2)                              :: base_nmo_spin, new_added, new_nmo
    1054              :       LOGICAL                                            :: diag_step, has_unit_metric, need_resize, &
    1055              :                                                             shared_spin_auto
    1056              :       REAL(KIND=dp)                                      :: energy_step, flexible_electron_count, &
    1057              :                                                             maxocc, n_el_f
    1058           14 :       REAL(KIND=dp), DIMENSION(:), POINTER               :: eigenvalues, occupation_numbers, &
    1059           14 :                                                             old_eigenvalues, old_occupation_numbers
    1060              :       TYPE(cp_blacs_env_type), POINTER                   :: blacs_env
    1061           14 :       TYPE(cp_fm_pool_p_type), DIMENSION(:), POINTER     :: ao_mo_fm_pools
    1062              :       TYPE(cp_fm_type), POINTER                          :: mo_coeff
    1063           14 :       TYPE(dbcsr_p_type), DIMENSION(:), POINTER          :: mo_derivs
    1064           14 :       TYPE(dbcsr_p_type), DIMENSION(:, :), POINTER       :: matrix_ks, matrix_s
    1065              :       TYPE(dft_control_type), POINTER                    :: dft_control
    1066              :       TYPE(kpoint_env_type), POINTER                     :: kp
    1067              :       TYPE(kpoint_type), POINTER                         :: kpoints
    1068           14 :       TYPE(mo_set_type), ALLOCATABLE, DIMENSION(:)       :: old_mos
    1069           14 :       TYPE(mo_set_type), DIMENSION(:), POINTER           :: mos
    1070              :       TYPE(mp_para_env_type), POINTER                    :: para_env
    1071              : 
    1072           14 :       CALL timeset(routineN, handle)
    1073              : 
    1074           14 :       NULLIFY (ao_mo_fm_pools, blacs_env, dft_control, eigenvalues, kpoints, matrix_ks, matrix_s, &
    1075           14 :                mo_coeff, mo_derivs, mos, occupation_numbers, old_eigenvalues, &
    1076           14 :                old_occupation_numbers, para_env)
    1077              : 
    1078              :       CALL get_qs_env(qs_env=qs_env, blacs_env=blacs_env, dft_control=dft_control, &
    1079              :                       kpoints=kpoints, matrix_ks_kp=matrix_ks, matrix_s_kp=matrix_s, &
    1080              :                       mo_derivs=mo_derivs, mos=mos, para_env=para_env, &
    1081           14 :                       has_unit_metric=has_unit_metric)
    1082              : 
    1083           14 :       CPASSERT(ASSOCIATED(mos))
    1084           14 :       CPASSERT(ASSOCIATED(kpoints))
    1085           14 :       CPASSERT(ASSOCIATED(dft_control))
    1086           14 :       CPASSERT(ASSOCIATED(scf_control))
    1087           14 :       CPASSERT(ASSOCIATED(matrix_ks))
    1088           14 :       CPASSERT(ASSOCIATED(matrix_s))
    1089              : 
    1090           14 :       nspins = dft_control%nspins
    1091           14 :       CPASSERT(nspins >= 1 .AND. nspins <= SIZE(new_nmo))
    1092           42 :       new_added = scf_control%added_mos
    1093           14 :       new_nmo(:) = 0
    1094           14 :       need_resize = .FALSE.
    1095           42 :       shared_spin_auto = nspins == 2 .AND. ALL(scf_control%added_mos_auto(1:2))
    1096              : 
    1097           14 :       IF (shared_spin_auto) THEN
    1098           12 :          DO ispin = 1, nspins
    1099            8 :             current_added = MAX(0, scf_control%added_mos(ispin))
    1100           12 :             base_nmo_spin(ispin) = MAX(0, mos(ispin)%nmo - current_added)
    1101              :          END DO
    1102           12 :          common_base_nmo = MAXVAL(base_nmo_spin(1:nspins))
    1103           12 :          current_target_nmo = MAXVAL(mos(1:nspins)%nmo)
    1104            4 :          current_added = MAX(0, current_target_nmo - common_base_nmo)
    1105            4 :          grow_by = MAX(4, current_added)
    1106           12 :          target_nmo = MIN(MINVAL(mos(1:nspins)%nao), current_target_nmo + grow_by)
    1107           12 :          DO ispin = 1, nspins
    1108            8 :             new_nmo(ispin) = target_nmo
    1109            8 :             new_added(ispin) = target_nmo - base_nmo_spin(ispin)
    1110           12 :             need_resize = need_resize .OR. new_nmo(ispin) > mos(ispin)%nmo
    1111              :          END DO
    1112              :       ELSE
    1113           20 :          DO ispin = 1, nspins
    1114           10 :             old_nmo = mos(ispin)%nmo
    1115           10 :             new_nmo(ispin) = old_nmo
    1116           10 :             IF (.NOT. scf_control%added_mos_auto(ispin)) CYCLE
    1117           10 :             current_added = MAX(0, scf_control%added_mos(ispin))
    1118           10 :             base_nmo = MAX(0, old_nmo - current_added)
    1119           10 :             grow_by = MAX(4, current_added)
    1120           10 :             new_added(ispin) = MIN(mos(ispin)%nao - base_nmo, current_added + grow_by)
    1121           10 :             new_nmo(ispin) = base_nmo + new_added(ispin)
    1122           20 :             need_resize = need_resize .OR. new_nmo(ispin) > old_nmo
    1123              :          END DO
    1124              : 
    1125           10 :          IF (nspins == 2) THEN
    1126            0 :             target_nmo = MAXVAL(new_nmo(1:nspins))
    1127            0 :             DO ispin = 1, nspins
    1128            0 :                IF (target_nmo > mos(ispin)%nao) THEN
    1129              :                   CALL cp_abort(__LOCATION__, &
    1130            0 :                                 "K-point ADDED_MOS AUTO exhausted the AO basis while matching spin bands.")
    1131              :                END IF
    1132            0 :                IF (target_nmo > mos(ispin)%nmo .AND. .NOT. scf_control%added_mos_auto(ispin)) THEN
    1133              :                   CALL cp_abort(__LOCATION__, &
    1134            0 :                                 "K-point ADDED_MOS AUTO needs to grow a spin channel with explicit ADDED_MOS.")
    1135              :                END IF
    1136            0 :                base_nmo = MAX(0, mos(ispin)%nmo - MAX(0, scf_control%added_mos(ispin)))
    1137            0 :                new_nmo(ispin) = target_nmo
    1138            0 :                new_added(ispin) = target_nmo - base_nmo
    1139            0 :                need_resize = need_resize .OR. new_nmo(ispin) > mos(ispin)%nmo
    1140              :             END DO
    1141              :          END IF
    1142              :       END IF
    1143              : 
    1144           14 :       IF (.NOT. need_resize) THEN
    1145              :          CALL cp_abort(__LOCATION__, &
    1146            0 :                        "K-point ADDED_MOS AUTO cannot grow further although the highest band is still occupied.")
    1147              :       END IF
    1148              : 
    1149           32 :       scf_control%added_mos(1:nspins) = new_added(1:nspins)
    1150           14 :       IF (output_unit > 0) THEN
    1151            7 :          IF (nspins == 2) THEN
    1152              :             WRITE (UNIT=output_unit, FMT="(T2,A,2I5)") &
    1153            2 :                "K-point ADDED_MOS AUTO: growing virtual-space buffer to:", &
    1154            8 :                scf_control%added_mos(1:nspins)
    1155              :          ELSE
    1156              :             WRITE (UNIT=output_unit, FMT="(T2,A,I0)") &
    1157            5 :                "K-point ADDED_MOS AUTO: growing virtual-space buffer to: ", &
    1158           10 :                scf_control%added_mos(1)
    1159              :          END IF
    1160              :       END IF
    1161              : 
    1162           14 :       CALL scf_env_release_ot_operators(scf_env)
    1163           74 :       ALLOCATE (old_mos(nspins))
    1164           32 :       DO ispin = 1, nspins
    1165           18 :          CALL duplicate_mo_set(old_mos(ispin), mos(ispin))
    1166              :          CALL get_mo_set(old_mos(ispin), maxocc=maxocc, n_el_f=n_el_f, &
    1167           18 :                          flexible_electron_count=flexible_electron_count)
    1168           18 :          CALL deallocate_mo_set(mos(ispin))
    1169              :          CALL allocate_mo_set(mo_set=mos(ispin), nao=old_mos(ispin)%nao, nmo=new_nmo(ispin), &
    1170              :                               nelectron=old_mos(ispin)%nelectron, n_el_f=n_el_f, maxocc=maxocc, &
    1171           18 :                               flexible_electron_count=flexible_electron_count)
    1172           50 :          mos(ispin)%use_mo_coeff_b = old_mos(ispin)%use_mo_coeff_b
    1173              :       END DO
    1174              : 
    1175           14 :       CALL mpools_rebuild_fm_pools(qs_env%mpools, mos=mos, blacs_env=blacs_env, para_env=para_env)
    1176           14 :       CALL mpools_get(qs_env%mpools, ao_mo_fm_pools=ao_mo_fm_pools)
    1177              : 
    1178           32 :       DO ispin = 1, nspins
    1179              :          CALL init_mo_set(mos(ispin), fm_pool=ao_mo_fm_pools(ispin)%pool, &
    1180           18 :                           name="qs_env%mo"//TRIM(ADJUSTL(cp_to_string(ispin))))
    1181              :          CALL get_mo_set(mos(ispin), mo_coeff=mo_coeff, eigenvalues=eigenvalues, &
    1182           18 :                          occupation_numbers=occupation_numbers)
    1183              :          CALL get_mo_set(old_mos(ispin), eigenvalues=old_eigenvalues, &
    1184           18 :                          occupation_numbers=old_occupation_numbers)
    1185              : 
    1186           18 :          old_nmo = old_mos(ispin)%nmo
    1187           18 :          CALL cp_fm_init_random(mo_coeff, mos(ispin)%nmo)
    1188           18 :          IF (has_unit_metric) THEN
    1189            0 :             CALL make_basis_simple(mo_coeff, mos(ispin)%nmo)
    1190              :          ELSE
    1191           18 :             CALL make_basis_sm(mo_coeff, mos(ispin)%nmo, matrix_s(1, 1)%matrix)
    1192              :          END IF
    1193              : 
    1194          348 :          eigenvalues(1:old_nmo) = old_eigenvalues(1:old_nmo)
    1195          262 :          occupation_numbers(:) = 0.0_dp
    1196          348 :          occupation_numbers(1:old_nmo) = old_occupation_numbers(1:old_nmo)
    1197           18 :          IF (mos(ispin)%nmo > old_nmo) THEN
    1198           18 :             energy_step = MAX(scf_control%smear%electronic_temperature, 1.0E-3_dp)
    1199          106 :             DO ic = old_nmo + 1, mos(ispin)%nmo
    1200          106 :                eigenvalues(ic) = eigenvalues(old_nmo) + energy_step*REAL(ic - old_nmo, KIND=dp)
    1201              :             END DO
    1202              :          END IF
    1203           18 :          mos(ispin)%homo = old_mos(ispin)%homo
    1204           18 :          mos(ispin)%lfomo = old_mos(ispin)%lfomo
    1205           18 :          mos(ispin)%kTS = old_mos(ispin)%kTS
    1206           18 :          mos(ispin)%mu = old_mos(ispin)%mu
    1207           32 :          mos(ispin)%uniform_occupation = old_mos(ispin)%uniform_occupation
    1208              :       END DO
    1209              : 
    1210           14 :       IF (dft_control%restricted) CALL mo_set_restrict(mos)
    1211              : 
    1212           32 :       DO ispin = 1, nspins
    1213           18 :          IF (.NOT. mos(ispin)%use_mo_coeff_b) CYCLE
    1214           10 :          CALL get_mo_set(mos(ispin), mo_coeff=mo_coeff)
    1215           10 :          CALL dbcsr_init_p(mos(ispin)%mo_coeff_b)
    1216              :          CALL cp_dbcsr_m_by_n_from_row_template(mos(ispin)%mo_coeff_b, template=matrix_s(1, 1)%matrix, &
    1217           10 :                                                 n=mos(ispin)%nmo, sym=dbcsr_type_no_symmetry)
    1218           32 :          CALL copy_fm_to_dbcsr(mo_coeff, mos(ispin)%mo_coeff_b)
    1219              :       END DO
    1220              : 
    1221           14 :       IF (ASSOCIATED(mo_derivs)) THEN
    1222           12 :          DO ispin = 1, SIZE(mo_derivs)
    1223           12 :             IF (ASSOCIATED(mo_derivs(ispin)%matrix)) CALL dbcsr_release_p(mo_derivs(ispin)%matrix)
    1224              :          END DO
    1225            6 :          DEALLOCATE (mo_derivs)
    1226              :          NULLIFY (mo_derivs)
    1227            6 :          CALL set_qs_env(qs_env, mo_derivs=mo_derivs)
    1228              :       END IF
    1229           14 :       IF (qs_env%requires_mo_derivs) THEN
    1230            0 :          nmo_mat = MERGE(1, nspins, dft_control%restricted)
    1231            0 :          ALLOCATE (mo_derivs(nmo_mat))
    1232            0 :          DO ispin = 1, nmo_mat
    1233            0 :             NULLIFY (mo_derivs(ispin)%matrix)
    1234            0 :             CALL dbcsr_init_p(mo_derivs(ispin)%matrix)
    1235              :             CALL dbcsr_create(mo_derivs(ispin)%matrix, template=mos(ispin)%mo_coeff_b, &
    1236            0 :                               name="mo_derivs", matrix_type=dbcsr_type_no_symmetry)
    1237              :          END DO
    1238            0 :          CALL set_qs_env(qs_env, mo_derivs=mo_derivs)
    1239              :       END IF
    1240              : 
    1241           30 :       DO ik = 1, SIZE(kpoints%kp_env)
    1242           16 :          kp => kpoints%kp_env(ik)%kpoint_env
    1243           16 :          IF (ASSOCIATED(kp%mos)) THEN
    1244           36 :             DO ispin = 1, SIZE(kp%mos)
    1245           36 :                CALL deallocate_mo_set(kp%mos(ispin))
    1246              :             END DO
    1247           16 :             DEALLOCATE (kp%mos)
    1248              :             NULLIFY (kp%mos)
    1249              :          END IF
    1250           16 :          CALL cp_fm_release(kp%pmat)
    1251           30 :          CALL cp_fm_release(kp%wmat)
    1252              :       END DO
    1253           14 :       CALL mpools_release(kpoints%mpools)
    1254           14 :       CALL kpoint_initialize_mos(kpoints, mos)
    1255           14 :       CALL kpoint_initialize_mo_set(kpoints)
    1256              : 
    1257           14 :       diag_step = .FALSE.
    1258           14 :       CALL do_general_diag_kp(matrix_ks, matrix_s, kpoints, scf_env, scf_control, .FALSE., diag_step)
    1259           14 :       IF (dft_control%restricted) CALL qs_kpoint_copy_spin_mos(kpoints, nspins)
    1260              :       CALL qs_kpoint_state_commit( &
    1261              :          qs_env, update_occupations=.TRUE., &
    1262              :          separate_spin_occupations=dft_control%restricted, &
    1263           28 :          fixed_occupations=.NOT. (dft_control%smear .OR. scf_control%smear%do_smear))
    1264              : 
    1265           14 :       IF (ASSOCIATED(kpoints%scf_diis_buffer)) CALL qs_diis_b_clear_kp(kpoints%scf_diis_buffer)
    1266           14 :       IF (ASSOCIATED(scf_env%qs_ot_env)) THEN
    1267           14 :          DO ispin = 1, SIZE(scf_env%qs_ot_env)
    1268           14 :             CALL ot_scf_destroy(scf_env%qs_ot_env(ispin))
    1269              :          END DO
    1270            6 :          DEALLOCATE (scf_env%qs_ot_env)
    1271            6 :          NULLIFY (scf_env%qs_ot_env)
    1272              :       END IF
    1273           14 :       reuse_precond = .FALSE.
    1274              : 
    1275           32 :       DO ispin = 1, nspins
    1276           32 :          CALL deallocate_mo_set(old_mos(ispin))
    1277              :       END DO
    1278           14 :       DEALLOCATE (old_mos)
    1279              : 
    1280           14 :       CALL timestop(handle)
    1281              : 
    1282           14 :    END SUBROUTINE qs_scf_grow_added_mos_auto_kp
    1283              : 
    1284              : ! **************************************************************************************************
    1285              : !> \brief inits those objects needed if you want to restart the scf with, say
    1286              : !>        only a new initial guess, or different density functional or ...
    1287              : !>        this will happen just before the scf loop starts
    1288              : !> \param scf_env ...
    1289              : !> \param qs_env ...
    1290              : !> \param scf_section ...
    1291              : !> \param kp_ot_entry_reason reason for constructing a new k-point OT workspace
    1292              : !> \par History
    1293              : !>      03.2006 created [Joost VandeVondele]
    1294              : ! **************************************************************************************************
    1295        28879 :    SUBROUTINE init_scf_loop(scf_env, qs_env, scf_section, kp_ot_entry_reason)
    1296              : 
    1297              :       TYPE(qs_scf_env_type), POINTER                     :: scf_env
    1298              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    1299              :       TYPE(section_vals_type), POINTER                   :: scf_section
    1300              :       INTEGER, INTENT(IN), OPTIONAL                      :: kp_ot_entry_reason
    1301              : 
    1302              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'init_scf_loop'
    1303              : 
    1304              :       INTEGER                                            :: entry_reason, handle, ikind, ispin, &
    1305              :                                                             nkpoint, nmo, nspin_ot
    1306              :       INTEGER, DIMENSION(2)                              :: kp_range
    1307              :       LOGICAL :: do_adiis, do_kpoints, do_rotation, fixed_density_prepared, has_unit_metric, &
    1308              :          kp_diis_step, kpoint_mos_initialized
    1309              :       REAL(KIND=dp)                                      :: u_ramping
    1310        28879 :       REAL(KIND=dp), DIMENSION(:), POINTER               :: wkp
    1311              :       TYPE(cp_fm_type), POINTER                          :: mo_coeff
    1312        28879 :       TYPE(dbcsr_p_type), DIMENSION(:), POINTER          :: matrix_ks, matrix_s
    1313        28879 :       TYPE(dbcsr_p_type), DIMENSION(:, :), POINTER       :: matrix_ks_kp, matrix_s_kp, matrix_t_kp, &
    1314        28879 :                                                             rho_ao_kp
    1315              :       TYPE(dbcsr_type), POINTER                          :: orthogonality_metric
    1316              :       TYPE(dft_control_type), POINTER                    :: dft_control
    1317              :       TYPE(kpoint_type), POINTER                         :: kpoints
    1318        28879 :       TYPE(mo_set_type), DIMENSION(:), POINTER           :: mos
    1319        28879 :       TYPE(qs_kind_type), DIMENSION(:), POINTER          :: qs_kind_set
    1320              :       TYPE(qs_rho_type), POINTER                         :: rho
    1321              :       TYPE(scf_control_type), POINTER                    :: scf_control
    1322              : 
    1323        28879 :       CALL timeset(routineN, handle)
    1324              : 
    1325        28879 :       NULLIFY (scf_control, matrix_ks_kp, matrix_s, matrix_s_kp, matrix_t_kp, matrix_ks, &
    1326        28879 :                rho_ao_kp, dft_control, mos, mo_coeff, kpoints, qs_kind_set, rho, wkp)
    1327              : 
    1328        28879 :       CPASSERT(ASSOCIATED(scf_env))
    1329        28879 :       CPASSERT(ASSOCIATED(qs_env))
    1330        28879 :       entry_reason = kp_ot_entry_initial
    1331        28879 :       IF (PRESENT(kp_ot_entry_reason)) entry_reason = kp_ot_entry_reason
    1332        28879 :       fixed_density_prepared = .FALSE.
    1333              : 
    1334              :       CALL get_qs_env(qs_env=qs_env, &
    1335              :                       scf_control=scf_control, &
    1336              :                       dft_control=dft_control, &
    1337              :                       do_kpoints=do_kpoints, &
    1338              :                       kpoints=kpoints, &
    1339              :                       mos=mos, &
    1340              :                       rho=rho, &
    1341        28879 :                       qs_kind_set=qs_kind_set)
    1342              : 
    1343        28879 :       nkpoint = 1
    1344        28879 :       kp_range = 0
    1345        28879 :       nspin_ot = dft_control%nspins
    1346        28879 :       IF (dft_control%restricted) nspin_ot = 1
    1347        28879 :       IF (do_kpoints) THEN
    1348         4164 :          CALL get_kpoint_info(kpoints, nkp=nkpoint, kp_range=kp_range, wkp=wkp)
    1349              :       END IF
    1350              : 
    1351              :       ! if using mo_coeff_b then copy to fm
    1352        62305 :       DO ispin = 1, SIZE(mos) !fm->dbcsr
    1353        62305 :          IF (mos(1)%use_mo_coeff_b) THEN !fm->dbcsr
    1354         9512 :             CALL copy_dbcsr_to_fm(mos(ispin)%mo_coeff_b, mos(ispin)%mo_coeff) !fm->dbcsr
    1355              :          END IF !fm->dbcsr
    1356              :       END DO !fm->dbcsr
    1357              : 
    1358              :       ! this just guarantees that all mo_occupations match the eigenvalues, if smear
    1359        62305 :       DO ispin = 1, dft_control%nspins
    1360              :          ! do not reset mo_occupations if the maximum overlap method is in use
    1361        62305 :          IF (.NOT. scf_control%diagonalization%mom) THEN
    1362              :             !if the hair probes section is present, this sends hairy_probes to set_mo_occupation subroutine
    1363              :             !and switches off the standard smearing
    1364        33378 :             IF (dft_control%hairy_probes .EQV. .TRUE.) THEN
    1365            4 :                IF (scf_env%outer_scf%iter_count > 0) THEN
    1366            0 :                   scf_control%smear%do_smear = .FALSE.
    1367              :                   CALL set_mo_occupation(mo_set=mos(ispin), &
    1368              :                                          smear=scf_control%smear, &
    1369            0 :                                          probe=dft_control%probe)
    1370              :                END IF
    1371              :             ELSE
    1372        33374 :                IF (.NOT. scf_control%gce%do_gce) THEN
    1373              :                   CALL set_mo_occupation(mo_set=mos(ispin), &
    1374              :                                          smear=scf_control%smear, &
    1375        33362 :                                          emit_warnings=.NOT. do_kpoints)
    1376              :                ELSE
    1377              :                   CALL set_mo_occupation(mo_set=mos(ispin), &
    1378              :                                          smear=scf_control%smear, &
    1379              :                                          gce=scf_control%gce, &
    1380           12 :                                          emit_warnings=.NOT. do_kpoints)
    1381              :                END IF
    1382              :             END IF
    1383              :          END IF
    1384              :       END DO
    1385              : 
    1386        28879 :       do_adiis = scf_control%diagonalization%update_method == diag_update_method_adiis
    1387        28879 :       IF (do_adiis) THEN
    1388           12 :          IF (scf_env%method /= general_diag_method_nr) THEN
    1389            0 :             CPABORT("ADIIS currently requires SCF%DIAGONALIZATION ALGORITHM STANDARD")
    1390              :          END IF
    1391           12 :          IF (scf_env%cholesky_method == cholesky_dbcsr) THEN
    1392            0 :             CPABORT("ADIIS is not yet compatible with CHOLESKY INVERSE_DBCSR")
    1393              :          END IF
    1394           12 :          IF (dft_control%qs_control%dftb .OR. dft_control%qs_control%xtb .OR. &
    1395              :              dft_control%qs_control%semi_empirical) THEN
    1396            0 :             CPABORT("ADIIS currently requires a Quickstep DFT KS matrix")
    1397              :          END IF
    1398           12 :          IF (dft_control%do_admm_mo) THEN
    1399            0 :             CPABORT("ADIIS is not yet compatible with ADMM-MO")
    1400              :          END IF
    1401           12 :          IF (dft_control%sic_method_id == sic_eo) THEN
    1402            0 :             CPABORT("ADIIS is not yet compatible with explicit-orbital SIC")
    1403              :          END IF
    1404           12 :          IF (dft_control%apply_period_efield) THEN
    1405            0 :             CPABORT("ADIIS is not yet compatible with PERIODIC_EFIELD")
    1406              :          END IF
    1407           12 :          IF (dft_control%dft_plus_u) THEN
    1408            8 :             CPASSERT(ASSOCIATED(qs_kind_set))
    1409           24 :             DO ikind = 1, SIZE(qs_kind_set)
    1410           16 :                CALL get_qs_kind(qs_kind_set(ikind), u_ramping=u_ramping)
    1411           16 :                IF (u_ramping > 0.0_dp .AND. &
    1412           24 :                    (.NOT. do_kpoints .OR. dft_control%plus_u_method_id /= plus_u_lowdin)) THEN
    1413            0 :                   CPABORT("ADIIS is not yet compatible with DFT+U U_RAMPING")
    1414              :                END IF
    1415              :             END DO
    1416              :          END IF
    1417           12 :          IF (dft_control%smear .OR. scf_control%smear%do_smear) THEN
    1418            0 :             CPABORT("ADIIS finite-temperature smearing support is not implemented yet")
    1419              :          END IF
    1420              :          IF (dft_control%roks .OR. scf_control%diagonalization%mom .OR. &
    1421           12 :              dft_control%hairy_probes .OR. scf_control%gce%do_gce) THEN
    1422            0 :             CPABORT("ADIIS currently supports ordinary RKS/UKS occupations only")
    1423              :          END IF
    1424           12 :          IF (scf_control%do_diag_sub) THEN
    1425            0 :             CPABORT("ADIIS is not yet compatible with DIAG_SUB_SCF")
    1426              :          END IF
    1427           12 :          IF (scf_control%diagonalization%max_history < 1) THEN
    1428            0 :             CPABORT("ADIIS requires SCF%ADIIS%MAX_HISTORY >= 1")
    1429              :          END IF
    1430           12 :          IF (.NOT. ASSOCIATED(scf_env%scf_subspace_buffer)) THEN
    1431           12 :             ALLOCATE (scf_env%scf_subspace_buffer)
    1432              :             CALL qs_scf_subspace_buffer_create(scf_env%scf_subspace_buffer, &
    1433           12 :                                                scf_control%diagonalization%max_history)
    1434            0 :          ELSE IF (scf_env%scf_subspace_buffer%nbuffer /= scf_control%diagonalization%max_history) THEN
    1435            0 :             CALL qs_scf_subspace_buffer_release(scf_env%scf_subspace_buffer)
    1436              :             CALL qs_scf_subspace_buffer_create(scf_env%scf_subspace_buffer, &
    1437            0 :                                                scf_control%diagonalization%max_history)
    1438              :          END IF
    1439           12 :          CALL qs_scf_subspace_buffer_clear(scf_env%scf_subspace_buffer)
    1440              :       END IF
    1441              : 
    1442        28879 :       SELECT CASE (scf_env%method)
    1443              :       CASE DEFAULT
    1444              : 
    1445              :          CALL cp_abort(__LOCATION__, &
    1446            0 :                        "Unknown SCF method <"//TRIM(cp_to_string(scf_env%method))//"> found. Check the code!")
    1447              : 
    1448              :       CASE (filter_matrix_diag_method_nr)
    1449              : 
    1450           10 :          IF (.NOT. scf_env%skip_diis) THEN
    1451            0 :             IF (.NOT. ASSOCIATED(scf_env%scf_diis_buffer)) THEN
    1452            0 :                ALLOCATE (scf_env%scf_diis_buffer)
    1453            0 :                CALL qs_diis_b_create(scf_env%scf_diis_buffer, nbuffer=scf_control%max_diis)
    1454              :             END IF
    1455            0 :             CALL qs_diis_b_clear(scf_env%scf_diis_buffer)
    1456              :          END IF
    1457              : 
    1458              :       CASE (general_diag_method_nr, special_diag_method_nr, block_krylov_diag_method_nr, smeagol_method_nr)
    1459        21010 :          IF (.NOT. scf_env%skip_diis) THEN
    1460        19762 :             IF (do_kpoints) THEN
    1461         3206 :                IF (.NOT. ASSOCIATED(kpoints%scf_diis_buffer)) THEN
    1462         2534 :                   ALLOCATE (kpoints%scf_diis_buffer)
    1463         2534 :                   CALL qs_diis_b_create_kp(kpoints%scf_diis_buffer, nbuffer=scf_control%max_diis)
    1464              :                END IF
    1465         3206 :                CALL qs_diis_b_clear_kp(kpoints%scf_diis_buffer)
    1466              :             ELSE
    1467        16556 :                IF (.NOT. ASSOCIATED(scf_env%scf_diis_buffer)) THEN
    1468         4594 :                   ALLOCATE (scf_env%scf_diis_buffer)
    1469         4594 :                   CALL qs_diis_b_create(scf_env%scf_diis_buffer, nbuffer=scf_control%max_diis)
    1470              :                END IF
    1471        16556 :                CALL qs_diis_b_clear(scf_env%scf_diis_buffer)
    1472              :             END IF
    1473              :          END IF
    1474              : 
    1475              :       CASE (ot_diag_method_nr)
    1476              :          IF (scf_control%diagonalization%ot_settings%preconditioner_type == &
    1477           24 :              ot_precond_full_kinetic .AND. &
    1478              :              (dft_control%qs_control%dftb .OR. dft_control%qs_control%xtb .OR. &
    1479              :               dft_control%qs_control%semi_empirical)) THEN
    1480              :             CALL cp_warn(__LOCATION__, &
    1481              :                          "FULL_KINETIC is unavailable for semi-empirical DIAGONALIZATION%OT; "// &
    1482            4 :                          "falling back to FULL_S_INVERSE.")
    1483            4 :             scf_control%diagonalization%ot_settings%preconditioner_type = ot_precond_s_inverse
    1484            4 :             scf_control%diagonalization%ot_settings%preconditioner_name = "FULL_S_INVERSE"
    1485              :          END IF
    1486           24 :          IF (do_kpoints) THEN
    1487           10 :             IF (.NOT. scf_env%skip_diis) THEN
    1488            6 :                IF (.NOT. ASSOCIATED(kpoints%scf_diis_buffer)) THEN
    1489            6 :                   ALLOCATE (kpoints%scf_diis_buffer)
    1490            6 :                   CALL qs_diis_b_create_kp(kpoints%scf_diis_buffer, nbuffer=scf_control%max_diis)
    1491              :                END IF
    1492            6 :                CALL qs_diis_b_clear_kp(kpoints%scf_diis_buffer)
    1493              :             END IF
    1494           10 :             CALL timestop(handle)
    1495          294 :             RETURN
    1496              :          END IF
    1497           14 :          CALL get_qs_env(qs_env, matrix_ks=matrix_ks, matrix_s=matrix_s)
    1498              : 
    1499           14 :          IF (.NOT. scf_env%skip_diis) THEN
    1500           12 :             IF (.NOT. ASSOCIATED(scf_env%scf_diis_buffer)) THEN
    1501           12 :                ALLOCATE (scf_env%scf_diis_buffer)
    1502           12 :                CALL qs_diis_b_create(scf_env%scf_diis_buffer, nbuffer=scf_control%max_diis)
    1503              :             END IF
    1504           12 :             CALL qs_diis_b_clear(scf_env%scf_diis_buffer)
    1505              :          END IF
    1506              : 
    1507              :          ! if an old preconditioner is still around (i.e. outer SCF is active),
    1508              :          ! remove it if this could be worthwhile
    1509              :          CALL restart_preconditioner(qs_env, scf_env%ot_preconditioner, &
    1510              :                                      scf_control%diagonalization%ot_settings%preconditioner_type, &
    1511           14 :                                      dft_control%nspins)
    1512              : 
    1513              :          CALL prepare_preconditioner(qs_env, mos, matrix_ks, matrix_s, scf_env%ot_preconditioner, &
    1514              :                                      scf_control%diagonalization%ot_settings%preconditioner_type, &
    1515              :                                      scf_control%diagonalization%ot_settings%precond_solver_type, &
    1516              :                                      scf_control%diagonalization%ot_settings%energy_gap, dft_control%nspins, &
    1517              :                                      chebyshev_degree=scf_control%diagonalization%ot_settings%chebyshev_degree, &
    1518              :                                      low_rank_base=scf_control%diagonalization%ot_settings%low_rank_base, &
    1519              :                                      fermi_low_rank_max_rank= &
    1520              :                                      scf_control%diagonalization%ot_settings%fermi_low_rank_max_rank, &
    1521              :                                      lattice_fft=scf_control%diagonalization%ot_settings%lattice_fft, &
    1522              :                                      lattice_fft_local_cells= &
    1523           14 :                                      scf_control%diagonalization%ot_settings%lattice_fft_local_cells)
    1524              : 
    1525              :       CASE (block_davidson_diag_method_nr)
    1526              :          ! Preconditioner initialized within the loop, when required
    1527              :       CASE (ot_method_nr)
    1528         7781 :          IF (do_kpoints) THEN
    1529          284 :             IF (.NOT. ASSOCIATED(scf_env%qs_ot_env)) THEN
    1530              :                CALL get_qs_env(qs_env, matrix_s_kp=matrix_s_kp, &
    1531          284 :                                kinetic_kp=matrix_t_kp)
    1532          284 :                CPASSERT(ASSOCIATED(matrix_s_kp))
    1533              :                CALL allocate_qs_ot_envs(scf_env=scf_env, &
    1534              :                                         scf_control=scf_control, &
    1535              :                                         dft_control=dft_control, &
    1536              :                                         scf_section=scf_section, &
    1537              :                                         do_kpoints=do_kpoints, &
    1538              :                                         nkpoint=nkpoint, &
    1539              :                                         nspin_ot=nspin_ot, &
    1540              :                                         kp_range=kp_range, &
    1541          284 :                                         wkp=wkp)
    1542              : 
    1543          284 :                CALL scf_env_release_ot_operators(scf_env)
    1544          284 :                ALLOCATE (scf_env%ot_operator_ctx)
    1545              :                CALL kpoint_operator_context_create(scf_env%ot_operator_ctx, kpoints, &
    1546          284 :                                                    scf_env%scf_work1(1), dft_control%nspins)
    1547              : 
    1548              :                ! A previous zero-width filling may have changed the occupied rank at each k point.
    1549              :                ! Restore the fixed OT ranks before validating or reconstructing the active space.
    1550          284 :                IF (.NOT. scf_env%qs_ot_env(1)%settings%do_ener) THEN
    1551          202 :                   CALL qs_kpoint_set_fixed_occupations(kpoints)
    1552              :                END IF
    1553              :                kpoint_mos_initialized = qs_kpoint_mos_initialized( &
    1554          284 :                                         kpoints, require_full_space=scf_env%qs_ot_env(1)%settings%do_ener)
    1555          240 :                SELECT CASE (entry_reason)
    1556              :                CASE (kp_ot_entry_initial)
    1557          240 :                   IF (kpoint_mos_initialized) THEN
    1558          130 :                      IF (dft_control%restricted) THEN
    1559            0 :                         CALL qs_kpoint_copy_spin_mos(kpoints, dft_control%nspins)
    1560              :                      END IF
    1561              :                      CALL qs_kpoint_state_commit( &
    1562              :                         qs_env, update_occupations=.TRUE., &
    1563              :                         separate_spin_occupations=dft_control%restricted, &
    1564          136 :                         fixed_occupations=.NOT. (dft_control%smear .OR. scf_control%smear%do_smear))
    1565              :                   END IF
    1566              :                CASE (kp_ot_entry_reuse, kp_ot_entry_resized, kp_ot_entry_refresh)
    1567           44 :                   CPASSERT(kpoint_mos_initialized)
    1568              :                CASE DEFAULT
    1569          284 :                   CPABORT("Invalid k-point OT workspace entry reason.")
    1570              :                END SELECT
    1571              : 
    1572              :                ! For fixed occupations, reconstruct the occupied subspace directly from the
    1573              :                ! density-only guess. This preserves its physical content instead of replacing it
    1574              :                ! with the potentially remote ground-state projector of H[P].
    1575          284 :                IF (entry_reason == kp_ot_entry_initial .AND. .NOT. kpoint_mos_initialized .AND. &
    1576              :                    .NOT. scf_env%qs_ot_env(1)%settings%do_ener) THEN
    1577           58 :                   CPASSERT(ASSOCIATED(rho))
    1578           58 :                   CALL qs_rho_get(rho, rho_ao_kp=rho_ao_kp)
    1579           58 :                   CPASSERT(ASSOCIATED(rho_ao_kp))
    1580           58 :                   CALL kpoint_operator_store(scf_env%ot_operator_ctx, rho_ao_kp, matrix_s_kp)
    1581           58 :                   CALL qs_kpoint_state_prepare_fixed_density(kpoints)
    1582           58 :                   IF (SIZE(rho_ao_kp, 1) < nspin_ot) THEN
    1583            0 :                      CPASSERT(SIZE(rho_ao_kp, 1) == 1)
    1584            0 :                      CALL qs_kpoint_copy_spin_mos(kpoints, nspin_ot)
    1585              :                   END IF
    1586           58 :                   IF (dft_control%restricted) THEN
    1587            2 :                      CALL qs_kpoint_copy_spin_mos(kpoints, dft_control%nspins)
    1588              :                   END IF
    1589              :                   CALL qs_kpoint_state_commit( &
    1590              :                      qs_env, update_occupations=.TRUE., &
    1591           58 :                      separate_spin_occupations=dft_control%restricted, fixed_occupations=.TRUE.)
    1592              : 
    1593              :                   ! The reconstructed projector replaces the density-only input. Rebuild H and E
    1594              :                   ! so the first minimizer call sees one coherent physical electronic state.
    1595           58 :                   CALL qs_ks_update_qs_env(qs_env, just_energy=.FALSE., calculate_forces=.FALSE.)
    1596           58 :                   fixed_density_prepared = .TRUE.
    1597              : 
    1598              :                ELSE
    1599              :                   ! Build the physical Hamiltonian from the committed state or a Mermin
    1600              :                   ! density-only guess. Ordinary workspace re-entry only needs this rebuild.
    1601          226 :                   CALL qs_ks_update_qs_env(qs_env, just_energy=.FALSE., calculate_forces=.FALSE.)
    1602          226 :                   CALL get_qs_env(qs_env, matrix_ks_kp=matrix_ks_kp)
    1603          226 :                   CPASSERT(ASSOCIATED(matrix_ks_kp))
    1604              : 
    1605              :                   ! Mermin initialization and deliberate REF refreshes require a full orbital
    1606              :                   ! space, so use the physical Hamiltonian replacement for those cases only.
    1607          226 :                   IF ((entry_reason == kp_ot_entry_initial .AND. .NOT. kpoint_mos_initialized) .OR. &
    1608              :                       entry_reason == kp_ot_entry_refresh) THEN
    1609           68 :                      kp_diis_step = .FALSE.
    1610              :                      CALL do_general_diag_kp(matrix_ks_kp, matrix_s_kp, kpoints, scf_env, &
    1611           68 :                                              scf_control, .FALSE., kp_diis_step)
    1612           68 :                      IF (SIZE(matrix_ks_kp, 1) < nspin_ot) THEN
    1613            0 :                         CPASSERT(SIZE(matrix_ks_kp, 1) == 1)
    1614            0 :                         CALL qs_kpoint_copy_spin_mos(kpoints, nspin_ot)
    1615              :                      END IF
    1616           68 :                      IF (dft_control%restricted) THEN
    1617            4 :                         CALL qs_kpoint_copy_spin_mos(kpoints, dft_control%nspins)
    1618              :                      END IF
    1619              :                      CALL qs_kpoint_state_commit( &
    1620              :                         qs_env, update_occupations=.TRUE., &
    1621              :                         separate_spin_occupations=dft_control%restricted, &
    1622          136 :                         fixed_occupations=.NOT. (dft_control%smear .OR. scf_control%smear%do_smear))
    1623              : 
    1624              :                      ! The accepted projector replaced the density-only input. Rebuild H and E so
    1625              :                      ! the first minimizer call sees one coherent physical electronic state.
    1626              :                      CALL qs_ks_update_qs_env(qs_env, just_energy=.FALSE., &
    1627           68 :                                               calculate_forces=.FALSE.)
    1628              :                   END IF
    1629              :                END IF
    1630              : 
    1631          284 :                CALL get_qs_env(qs_env, matrix_ks_kp=matrix_ks_kp)
    1632          284 :                CPASSERT(ASSOCIATED(matrix_ks_kp))
    1633              : 
    1634              :                ! Redistribute the physical operators to their owning k-point groups.  OT must not
    1635              :                ! call the collective real-space transform independently with group-local k values.
    1636          284 :                IF (scf_env%qs_ot_env(1)%settings%preconditioner_type == ot_precond_full_kinetic) THEN
    1637          184 :                   CALL kpoint_operator_store(scf_env%ot_operator_ctx, matrix_ks_kp, matrix_s_kp, matrix_t_kp)
    1638              :                ELSE
    1639          100 :                   CALL kpoint_operator_store(scf_env%ot_operator_ctx, matrix_ks_kp, matrix_s_kp)
    1640              :                END IF
    1641          284 :                scf_env%ot_ks_valid = .TRUE.
    1642              : 
    1643              :                ! Natural orbitals define the fixed occupied projector but not its internal gauge.
    1644              :                ! Canonicalize that subspace with the matching physical Hamiltonian and populate
    1645              :                ! the MO energy labels before constructing H-dependent OT preconditioners.
    1646          284 :                IF (fixed_density_prepared) CALL qs_kpoint_state_canonicalize_fixed(kpoints)
    1647              : 
    1648              :                CALL allocate_qs_ot_kpoint_state(qs_env=qs_env, &
    1649              :                                                 scf_env=scf_env, &
    1650              :                                                 dft_control=dft_control, &
    1651              :                                                 kpoints=kpoints, &
    1652              :                                                 matrix_ks_kp=matrix_ks_kp, &
    1653              :                                                 matrix_s_kp=matrix_s_kp, &
    1654              :                                                 matrix_t_kp=matrix_t_kp, &
    1655          284 :                                                 nspin_ot=nspin_ot)
    1656              :             END IF
    1657              : 
    1658          284 :             CALL timestop(handle)
    1659          284 :             RETURN
    1660              :          END IF
    1661              : 
    1662              :          CALL get_qs_env(qs_env, &
    1663              :                          has_unit_metric=has_unit_metric, &
    1664              :                          matrix_s=matrix_s, &
    1665         7497 :                          matrix_ks=matrix_ks)
    1666              : 
    1667              :          ! reortho the wavefunctions if we are having an outer scf and
    1668              :          ! this is not the first iteration
    1669              :          ! this is useful to avoid the build-up of numerical noise
    1670              :          ! however, we can not play this trick if restricted (don't mix non-equivalent orbs)
    1671         7497 :          IF (scf_control%do_outer_scf_reortho) THEN
    1672         6911 :             IF (scf_control%outer_scf%have_scf .AND. .NOT. dft_control%restricted) THEN
    1673         4689 :                IF (scf_env%outer_scf%iter_count > 0) THEN
    1674         1853 :                   DO ispin = 1, dft_control%nspins
    1675         1015 :                      CALL get_mo_set(mo_set=mos(ispin), mo_coeff=mo_coeff, nmo=nmo)
    1676         1853 :                      IF (has_unit_metric) THEN
    1677          104 :                         CALL make_basis_simple(mo_coeff, nmo)
    1678              :                      ELSE
    1679          911 :                         CALL make_basis_sm(mo_coeff, nmo, matrix_s(1)%matrix)
    1680              :                      END IF
    1681              :                   END DO
    1682              :                END IF
    1683              :             END IF
    1684              :          ELSE
    1685              :             ! dont need any dirty trick for the numerically stable irac algorithm.
    1686              :          END IF
    1687              : 
    1688         7497 :          IF (.NOT. ASSOCIATED(scf_env%qs_ot_env)) THEN
    1689              : 
    1690              :             CALL allocate_qs_ot_envs(scf_env=scf_env, &
    1691              :                                      scf_control=scf_control, &
    1692              :                                      dft_control=dft_control, &
    1693              :                                      scf_section=scf_section, &
    1694              :                                      do_kpoints=do_kpoints, &
    1695              :                                      nkpoint=nkpoint, &
    1696              :                                      nspin_ot=nspin_ot, &
    1697              :                                      kp_range=kp_range, &
    1698         7497 :                                      wkp=wkp)
    1699              : 
    1700         7497 :             IF (scf_env%qs_ot_env(1)%settings%preconditioner_type == &
    1701              :                 ot_precond_full_all_covariant) THEN
    1702            0 :                IF (.NOT. do_kpoints) THEN
    1703            0 :                   DO ispin = 1, SIZE(mos)
    1704            0 :                      IF (.NOT. mos(ispin)%uniform_occupation) THEN
    1705              :                         CALL cp_abort(__LOCATION__, &
    1706            0 :                                       'PRECONDITIONER FULL_ALL_COVARIANT currently requires uniform occupations.')
    1707              :                      END IF
    1708              :                   END DO
    1709              :                END IF
    1710              :             END IF
    1711              : 
    1712              :             ! might need the KS matrix to init properly
    1713              :             CALL qs_ks_update_qs_env(qs_env, just_energy=.FALSE., &
    1714         7497 :                                      calculate_forces=.FALSE.)
    1715              : 
    1716              :             ! if an old preconditioner is still around (i.e. outer SCF is active),
    1717              :             ! remove it if this could be worthwhile
    1718         7497 :             IF (.NOT. reuse_precond) THEN
    1719              :                CALL restart_preconditioner(qs_env, scf_env%ot_preconditioner, &
    1720              :                                            scf_env%qs_ot_env(1)%settings%preconditioner_type, &
    1721         7497 :                                            dft_control%nspins)
    1722              :             END IF
    1723              : 
    1724              :             !
    1725              :             ! preconditioning still needs to be done correctly with has_unit_metric
    1726              :             ! notice that a big part of the preconditioning (S^-1) is fine anyhow
    1727              :             !
    1728         7497 :             IF (has_unit_metric) THEN
    1729         1148 :                NULLIFY (orthogonality_metric)
    1730              :             ELSE
    1731         6349 :                orthogonality_metric => matrix_s(1)%matrix
    1732              :             END IF
    1733              : 
    1734         7497 :             IF (.NOT. reuse_precond) THEN
    1735              :                CALL prepare_preconditioner(qs_env, mos, matrix_ks, matrix_s, scf_env%ot_preconditioner, &
    1736              :                                            scf_env%qs_ot_env(1)%settings%preconditioner_type, &
    1737              :                                            scf_env%qs_ot_env(1)%settings%precond_solver_type, &
    1738              :                                            scf_env%qs_ot_env(1)%settings%energy_gap, dft_control%nspins, &
    1739              :                                            has_unit_metric=has_unit_metric, &
    1740              :                                            chol_type=scf_env%qs_ot_env(1)%settings%cholesky_type, &
    1741              :                                            chebyshev_degree=scf_env%qs_ot_env(1)%settings%chebyshev_degree, &
    1742              :                                            low_rank_base=scf_env%qs_ot_env(1)%settings%low_rank_base, &
    1743              :                                            fermi_low_rank_max_rank= &
    1744              :                                            scf_env%qs_ot_env(1)%settings%fermi_low_rank_max_rank, &
    1745              :                                            lattice_fft=scf_env%qs_ot_env(1)%settings%lattice_fft, &
    1746              :                                            lattice_fft_local_cells= &
    1747         7497 :                                            scf_env%qs_ot_env(1)%settings%lattice_fft_local_cells)
    1748              :             END IF
    1749         7497 :             IF (reuse_precond) reuse_precond = .FALSE.
    1750              : 
    1751              :             CALL ot_scf_init(mo_array=mos, matrix_s=orthogonality_metric, &
    1752              :                              broyden_adaptive_sigma=qs_env%broyden_adaptive_sigma, &
    1753         7497 :                              qs_ot_env=scf_env%qs_ot_env, matrix_ks=matrix_ks(1)%matrix)
    1754              : 
    1755        13077 :             SELECT CASE (scf_env%qs_ot_env(1)%settings%preconditioner_type)
    1756              :             CASE (ot_precond_none)
    1757              :             CASE (ot_precond_full_all, ot_precond_fermi_low_rank, ot_precond_full_all_covariant, &
    1758              :                   ot_precond_full_single_inverse)
    1759        12391 :                DO ispin = 1, SIZE(scf_env%qs_ot_env)
    1760              :                   CALL qs_ot_new_preconditioner(scf_env%qs_ot_env(ispin), &
    1761        12391 :                                                 scf_env%ot_preconditioner(ispin)%preconditioner)
    1762              :                END DO
    1763              :             CASE (ot_precond_s_inverse, ot_precond_full_single)
    1764          156 :                DO ispin = 1, SIZE(scf_env%qs_ot_env)
    1765              :                   CALL qs_ot_new_preconditioner(scf_env%qs_ot_env(ispin), &
    1766          156 :                                                 scf_env%ot_preconditioner(1)%preconditioner)
    1767              :                END DO
    1768              :             CASE DEFAULT
    1769         8866 :                DO ispin = 1, SIZE(scf_env%qs_ot_env)
    1770              :                   CALL qs_ot_new_preconditioner(scf_env%qs_ot_env(ispin), &
    1771         2500 :                                                 scf_env%ot_preconditioner(1)%preconditioner)
    1772              :                END DO
    1773              :             END SELECT
    1774              :          END IF
    1775              : 
    1776              :          ! if we have non-uniform occupations we should be using rotation
    1777         7497 :          do_rotation = scf_env%qs_ot_env(1)%settings%do_rotation
    1778        45490 :          DO ispin = 1, SIZE(mos)
    1779        16611 :             IF (.NOT. mos(ispin)%uniform_occupation) THEN
    1780            0 :                CPASSERT(do_rotation)
    1781              :             END IF
    1782              :          END DO
    1783              :       END SELECT
    1784              : 
    1785              :       ! another safety check
    1786        28585 :       IF (dft_control%low_spin_roks) THEN
    1787           66 :          CPASSERT(scf_env%method == ot_method_nr)
    1788           66 :          do_rotation = scf_env%qs_ot_env(1)%settings%do_rotation
    1789           66 :          CPASSERT(do_rotation)
    1790              :       END IF
    1791              : 
    1792        28585 :       CALL timestop(handle)
    1793              : 
    1794        28879 :    END SUBROUTINE init_scf_loop
    1795              : 
    1796              : ! **************************************************************************************************
    1797              : !> \brief allocate OT environments and label their spin/k-point channel identity
    1798              : !> \param scf_env ...
    1799              : !> \param scf_control ...
    1800              : !> \param dft_control ...
    1801              : !> \param scf_section ...
    1802              : !> \param do_kpoints ...
    1803              : !> \param nkpoint ...
    1804              : !> \param nspin_ot ...
    1805              : !> \param kp_range ...
    1806              : !> \param wkp ...
    1807              : ! **************************************************************************************************
    1808         7781 :    SUBROUTINE allocate_qs_ot_envs(scf_env, scf_control, dft_control, scf_section, &
    1809              :                                   do_kpoints, nkpoint, nspin_ot, kp_range, wkp)
    1810              :       TYPE(qs_scf_env_type), POINTER                     :: scf_env
    1811              :       TYPE(scf_control_type), POINTER                    :: scf_control
    1812              :       TYPE(dft_control_type), POINTER                    :: dft_control
    1813              :       TYPE(section_vals_type), POINTER                   :: scf_section
    1814              :       LOGICAL, INTENT(IN)                                :: do_kpoints
    1815              :       INTEGER, INTENT(IN)                                :: nkpoint, nspin_ot
    1816              :       INTEGER, DIMENSION(2), INTENT(IN)                  :: kp_range
    1817              :       REAL(KIND=dp), DIMENSION(:), POINTER               :: wkp
    1818              : 
    1819              :       CHARACTER(len=*), PARAMETER :: kpoint_precond_error = &
    1820              :          "Complex K-point OT supports PRECONDITIONER NONE, FERMI_LOW_RANK, "// &
    1821              :          "FULL_S_INVERSE, FULL_KINETIC, FULL_SINGLE, FULL_SINGLE_INVERSE, FULL_ALL, or "// &
    1822              :          "FULL_ALL_COVARIANT.", kpoint_solver_error = &
    1823              :          "Complex K-point FERMI_LOW_RANK, FULL_SINGLE, FULL_ALL, and FULL_ALL_COVARIANT "// &
    1824              :          "support PRECOND_SOLVER DEFAULT; FULL_S_INVERSE, FULL_KINETIC, and "// &
    1825              :          "FULL_SINGLE_INVERSE support DEFAULT or INVERSE_CHOLESKY."
    1826              : 
    1827              :       INTEGER                                            :: ikpoint, ispin, local_kpoint, &
    1828              :                                                             number_of_OT_envs, ot_channel
    1829              :       LOGICAL                                            :: do_rotation, do_smear, is_full_all
    1830              :       REAL(KIND=dp)                                      :: kpoint_weight
    1831              : 
    1832         7781 :       CPASSERT(.NOT. ASSOCIATED(scf_env%qs_ot_env))
    1833              : 
    1834              :       ! Restricted calculations require just one set of OT orbitals per k-point.
    1835              :       number_of_OT_envs = qs_ot_number_of_channels(dft_control%nspins, &
    1836              :                                                    nkpoint=nkpoint, &
    1837         7781 :                                                    restricted=dft_control%restricted)
    1838              : 
    1839      1306180 :       ALLOCATE (scf_env%qs_ot_env(number_of_OT_envs))
    1840              : 
    1841              :       ! XXX Joost XXX should disentangle reading input from this part
    1842         7781 :       IF (scf_env%outer_scf%iter_count > 0) THEN
    1843          882 :          IF (scf_env%iter_delta < scf_control%eps_diis) THEN
    1844            0 :             scf_env%qs_ot_env(1)%settings%ot_state = 1
    1845              :          END IF
    1846              :       END IF
    1847              : 
    1848         7781 :       CALL ot_scf_read_input(scf_env%qs_ot_env, scf_section, do_kpoints)
    1849              : 
    1850         7781 :       IF (dft_control%restricted .AND. .NOT. do_kpoints .AND. &
    1851              :           scf_env%qs_ot_env(1)%settings%preconditioner_type == &
    1852              :           ot_precond_full_all_covariant) THEN
    1853            0 :          CPABORT('Gamma-point PRECONDITIONER FULL_ALL_COVARIANT does not currently support ROKS.')
    1854              :       END IF
    1855              : 
    1856         7781 :       IF (do_kpoints) THEN
    1857          284 :          do_smear = dft_control%smear .OR. scf_control%smear%do_smear
    1858              :          IF (do_smear) THEN
    1859           82 :             IF (.NOT. scf_env%qs_ot_env(1)%settings%do_ener) THEN
    1860            0 :                CPABORT("K-point OT smearing requires OT%ENERGIES and OT%ROTATION.")
    1861              :             END IF
    1862           82 :             IF (.NOT. scf_env%qs_ot_env(1)%settings%do_rotation) THEN
    1863            0 :                CPABORT("K-point OT smearing requires OT%ROTATION.")
    1864              :             END IF
    1865           82 :             SELECT CASE (scf_control%smear%method)
    1866              :             CASE (smear_fermi_dirac, smear_gaussian, smear_mp, smear_mv)
    1867            0 :                CONTINUE
    1868              :             CASE DEFAULT
    1869           82 :                CPABORT("K-point Mermin OT does not support the selected smearing method.")
    1870              :             END SELECT
    1871           82 :             IF (scf_env%qs_ot_env(1)%settings%ot_algorithm /= "TOD" .AND. &
    1872              :                 scf_env%qs_ot_env(1)%settings%ot_algorithm /= "REF") THEN
    1873            0 :                CPABORT("K-point Mermin OT currently supports OT%ALGORITHM STRICT or IRAC.")
    1874              :             END IF
    1875              :             IF (scf_env%qs_ot_env(1)%settings%OT_METHOD /= "CG" .AND. &
    1876              :                 scf_env%qs_ot_env(1)%settings%OT_METHOD /= "SD" .AND. &
    1877              :                 scf_env%qs_ot_env(1)%settings%OT_METHOD /= "DIIS" .AND. &
    1878           82 :                 scf_env%qs_ot_env(1)%settings%OT_METHOD /= "BROY" .AND. &
    1879              :                 scf_env%qs_ot_env(1)%settings%OT_METHOD /= "LBFG") THEN
    1880            0 :                CPABORT("K-point Mermin OT supports OT%MINIMIZER CG, SD, DIIS, BROYDEN, or LBFGS.")
    1881              :             END IF
    1882          202 :          ELSE IF (scf_env%qs_ot_env(1)%settings%do_ener) THEN
    1883            0 :             CPABORT("OT%ENERGIES requires smearing in the complex K-point path.")
    1884              :          END IF
    1885          284 :          IF (scf_env%qs_ot_env(1)%settings%ot_algorithm /= "TOD" .AND. &
    1886              :              scf_env%qs_ot_env(1)%settings%ot_algorithm /= "REF") THEN
    1887            0 :             CPABORT("K-point OT currently supports OT%ALGORITHM STRICT or IRAC.")
    1888              :          END IF
    1889              :          IF (scf_env%qs_ot_env(1)%settings%OT_METHOD /= "CG" .AND. &
    1890              :              scf_env%qs_ot_env(1)%settings%OT_METHOD /= "SD" .AND. &
    1891              :              scf_env%qs_ot_env(1)%settings%OT_METHOD /= "DIIS" .AND. &
    1892          284 :              scf_env%qs_ot_env(1)%settings%OT_METHOD /= "BROY" .AND. &
    1893              :              scf_env%qs_ot_env(1)%settings%OT_METHOD /= "LBFG") THEN
    1894            0 :             CPABORT("K-point OT currently supports OT%MINIMIZER CG, SD, DIIS, BROYDEN, or LBFGS.")
    1895              :          END IF
    1896          284 :          IF (.NOT. qs_ot_kpoint_preconditioner_supported( &
    1897              :              scf_env%qs_ot_env(1)%settings%preconditioner_type, .FALSE.)) THEN
    1898            0 :             CPABORT(kpoint_precond_error)
    1899              :          END IF
    1900          284 :          IF (scf_env%qs_ot_env(1)%settings%preconditioner_type == ot_precond_full_kinetic .AND. &
    1901              :              (dft_control%qs_control%semi_empirical .OR. dft_control%qs_control%dftb .OR. &
    1902              :               dft_control%qs_control%xtb)) THEN
    1903            0 :             CPABORT("FULL_KINETIC is unavailable for semi-empirical methods")
    1904              :          END IF
    1905          284 :          IF (.NOT. qs_ot_kpoint_preconditioner_solver_supported( &
    1906              :              scf_env%qs_ot_env(1)%settings%preconditioner_type, &
    1907              :              scf_env%qs_ot_env(1)%settings%precond_solver_type, .FALSE.)) THEN
    1908            0 :             CPABORT(kpoint_solver_error)
    1909              :          END IF
    1910          284 :          IF (scf_env%qs_ot_env(1)%settings%occupation_preconditioner .AND. .NOT. do_smear) THEN
    1911            0 :             CPABORT("K-point OCCUPATION_PRECONDITIONER requires smearing.")
    1912              :          END IF
    1913              :       END IF
    1914              : 
    1915         7781 :       IF (scf_env%outer_scf%iter_count > 0) THEN
    1916          882 :          IF (scf_env%qs_ot_env(1)%settings%ot_state == 1) THEN
    1917              :             scf_control%max_scf = MAX(scf_env%qs_ot_env(1)%settings%max_scf_diis, &
    1918            0 :                                       scf_control%max_scf)
    1919              :          END IF
    1920              :       END IF
    1921              : 
    1922              :       ! Keep a note that we are restricted.
    1923         7781 :       IF (dft_control%restricted) THEN
    1924          220 :          scf_env%qs_ot_env(:)%restricted = .TRUE.
    1925              :          ! requires rotation
    1926          108 :          IF (.NOT. scf_env%qs_ot_env(1)%settings%do_rotation) THEN
    1927              :             CALL cp_abort(__LOCATION__, &
    1928              :                           "Restricted calculation with OT requires orbital rotation. Please "// &
    1929            0 :                           "activate the OT%ROTATION keyword!")
    1930              :          END IF
    1931              :       ELSE
    1932        17593 :          scf_env%qs_ot_env(:)%restricted = .FALSE.
    1933              :       END IF
    1934              : 
    1935              :       ! This will rotate the MOs to be eigen states, which is not compatible with rotation.
    1936              :       ! e.g. mo_derivs here do not yet include potentially different occupation numbers.
    1937         7781 :       do_rotation = scf_env%qs_ot_env(1)%settings%do_rotation
    1938              :       ! Only full all needs rotation.
    1939         7781 :       is_full_all = scf_env%qs_ot_env(1)%settings%preconditioner_type == ot_precond_full_all
    1940         7781 :       IF (do_rotation .AND. is_full_all .AND. .NOT. do_kpoints) THEN
    1941            0 :          CPABORT('PRECONDITIONER FULL_ALL is not compatible with ROTATION.')
    1942              :       END IF
    1943              : 
    1944        16160 :       DO ikpoint = 1, nkpoint
    1945         8379 :          local_kpoint = 0
    1946         8379 :          IF (do_kpoints) THEN
    1947          882 :             IF (ikpoint >= kp_range(1) .AND. ikpoint <= kp_range(2)) THEN
    1948          528 :                local_kpoint = ikpoint - kp_range(1) + 1
    1949              :             END IF
    1950              :          END IF
    1951        26192 :          DO ispin = 1, nspin_ot
    1952        10032 :             ot_channel = qs_ot_channel_index(ispin, ikpoint, nspin_ot)
    1953        18411 :             IF (do_kpoints) THEN
    1954         1016 :                kpoint_weight = 1.0_dp
    1955         1016 :                IF (ASSOCIATED(wkp)) kpoint_weight = wkp(ikpoint)
    1956              :                CALL qs_ot_set_context(scf_env%qs_ot_env(ot_channel), &
    1957              :                                       spin_index=ispin, &
    1958              :                                       kpoint_index=ikpoint, &
    1959              :                                       local_kpoint_index=local_kpoint, &
    1960         1016 :                                       kpoint_weight=kpoint_weight)
    1961              :             ELSE
    1962         9016 :                CALL qs_ot_set_context(scf_env%qs_ot_env(ot_channel), spin_index=ispin)
    1963              :             END IF
    1964              :          END DO
    1965              :       END DO
    1966              : 
    1967              :       CALL qs_ot_check_channel_context(scf_env%qs_ot_env, dft_control%nspins, &
    1968              :                                        nkpoint=nkpoint, &
    1969              :                                        restricted=dft_control%restricted, &
    1970              :                                        require_kpoint=do_kpoints, &
    1971              :                                        kp_range=kp_range, &
    1972         7781 :                                        wkp=wkp)
    1973              : 
    1974         7781 :    END SUBROUTINE allocate_qs_ot_envs
    1975              : 
    1976              : ! **************************************************************************************************
    1977              : !> \brief allocate local k-point OT minimizer state for labelled spin/k-point channels
    1978              : !> \param qs_env ...
    1979              : !> \param scf_env ...
    1980              : !> \param dft_control ...
    1981              : !> \param kpoints ...
    1982              : !> \param matrix_ks_kp ...
    1983              : !> \param matrix_s_kp ...
    1984              : !> \param matrix_t_kp ...
    1985              : !> \param nspin_ot ...
    1986              : ! **************************************************************************************************
    1987          284 :    SUBROUTINE allocate_qs_ot_kpoint_state(qs_env, scf_env, dft_control, &
    1988              :                                           kpoints, matrix_ks_kp, matrix_s_kp, matrix_t_kp, nspin_ot)
    1989              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    1990              :       TYPE(qs_scf_env_type), POINTER                     :: scf_env
    1991              :       TYPE(dft_control_type), POINTER                    :: dft_control
    1992              :       TYPE(kpoint_type), POINTER                         :: kpoints
    1993              :       TYPE(dbcsr_p_type), DIMENSION(:, :), POINTER       :: matrix_ks_kp, matrix_s_kp, matrix_t_kp
    1994              :       INTEGER, INTENT(IN)                                :: nspin_ot
    1995              : 
    1996              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'allocate_qs_ot_kpoint_state'
    1997              : 
    1998              :       INTEGER :: energy_dimension, energy_spin, energy_start, first_channel, handle, ikpoint, &
    1999              :          ikpoint_local, ispin, local_channel, nao, nmo, nocc, ot_channel
    2000              :       LOGICAL                                            :: local_init, use_real_wfn
    2001          284 :       REAL(KIND=dp), DIMENSION(:), POINTER               :: eigenvalues
    2002          284 :       TYPE(cp_cfm_p_type), ALLOCATABLE                   :: local_c(:)
    2003          284 :       TYPE(cp_fm_p_type), ALLOCATABLE                    :: local_s(:, :)
    2004              :       TYPE(cp_fm_struct_type), POINTER                   :: active_mo_struct
    2005              :       TYPE(cp_fm_type)                                   :: active_mo_coeff, active_mo_coeff_im, &
    2006              :                                                             mo_coeff, mo_coeff_im
    2007              :       TYPE(dbcsr_type), POINTER                          :: matrix_sk_im, matrix_sk_re
    2008              :       TYPE(kpoint_env_type), POINTER                     :: kp
    2009              :       TYPE(mo_set_type), POINTER                         :: mo_set
    2010              : 
    2011          284 :       CALL timeset(routineN, handle)
    2012              : 
    2013          284 :       NULLIFY (active_mo_struct, eigenvalues, kp, matrix_sk_im, matrix_sk_re, mo_set)
    2014              : 
    2015          284 :       CPASSERT(ASSOCIATED(qs_env))
    2016          284 :       CPASSERT(ASSOCIATED(scf_env%qs_ot_env))
    2017          284 :       CPASSERT(ASSOCIATED(kpoints))
    2018          284 :       CPASSERT(ASSOCIATED(kpoints%kp_env))
    2019          284 :       CPASSERT(ASSOCIATED(matrix_ks_kp))
    2020          284 :       CPASSERT(ASSOCIATED(matrix_s_kp))
    2021          284 :       CPASSERT(ASSOCIATED(matrix_s_kp(1, 1)%matrix))
    2022          284 :       CPASSERT(.NOT. dft_control%restricted .OR. nspin_ot == 1)
    2023              : 
    2024          284 :       CALL get_kpoint_info(kpoints, use_real_wfn=use_real_wfn)
    2025          284 :       CPASSERT(.NOT. use_real_wfn)
    2026              : 
    2027          284 :       local_init = kpoints%para_env_kp%num_pe == 1
    2028          284 :       first_channel = qs_ot_channel_index(1, kpoints%kp_range(1), nspin_ot)
    2029         2668 :       IF (local_init) ALLOCATE (local_s(2, SIZE(kpoints%kp_env)*nspin_ot), local_c(SIZE(kpoints%kp_env)*nspin_ot))
    2030              : 
    2031          812 :       DO ikpoint_local = 1, SIZE(kpoints%kp_env)
    2032          528 :          kp => kpoints%kp_env(ikpoint_local)%kpoint_env
    2033          528 :          CPASSERT(ASSOCIATED(kp))
    2034          528 :          CPASSERT(ASSOCIATED(kp%mos))
    2035          528 :          CPASSERT(ASSOCIATED(kp%ot_smat))
    2036          528 :          CPASSERT(nspin_ot <= SIZE(kp%mos))
    2037          528 :          ikpoint = kp%nkpoint
    2038          528 :          CPASSERT(ikpoint >= 1)
    2039          528 :          CPASSERT(SIZE(kp%ot_smat) >= 2)
    2040              :          CALL kpoint_operator_get_local(matrix_s_kp, kpoints, kp, 1, &
    2041              :                                         kp%ot_smat(1), kp%ot_smat(2), &
    2042          528 :                                         matrix_sk_re, matrix_sk_im)
    2043         1136 :          DO ispin = 1, nspin_ot
    2044          608 :             ot_channel = qs_ot_channel_index(ispin, ikpoint, nspin_ot)
    2045          608 :             CPASSERT(.NOT. scf_env%qs_ot_env(ot_channel)%state_allocated)
    2046              : 
    2047          608 :             mo_set => kp%mos(ispin)
    2048              :             CALL get_mo_set(mo_set=mo_set, eigenvalues=eigenvalues, &
    2049          608 :                             homo=nocc, nao=nao, nmo=nmo)
    2050          608 :             CPASSERT(ASSOCIATED(mo_set%cmo_coeff))
    2051          608 :             CPASSERT(ASSOCIATED(eigenvalues))
    2052          608 :             CPASSERT(nao > 0)
    2053          608 :             CPASSERT(nmo > 0)
    2054          608 :             IF (scf_env%qs_ot_env(ot_channel)%settings%do_ener) nocc = nmo
    2055          608 :             IF (nocc < 1 .OR. nocc > nmo) THEN
    2056              :                CALL cp_abort(__LOCATION__, &
    2057            0 :                              "K-point OT requires at least one occupied orbital in every spin channel.")
    2058              :             END IF
    2059              : 
    2060              :             CALL cp_fm_struct_create(active_mo_struct, template_fmstruct=mo_set%cmo_coeff%matrix_struct, &
    2061          608 :                                      ncol_global=nocc)
    2062          608 :             energy_dimension = nocc
    2063          608 :             IF (dft_control%restricted .AND. &
    2064              :                 scf_env%qs_ot_env(ot_channel)%settings%do_ener) THEN
    2065            8 :                energy_dimension = nocc*SIZE(kp%mos)
    2066              :             END IF
    2067              :             CALL qs_ot_allocate(scf_env%qs_ot_env(ot_channel), &
    2068              :                                 matrix_sk_re, &
    2069          608 :                                 active_mo_struct, energy_dimension=energy_dimension)
    2070              : 
    2071          608 :             CALL qs_ot_allocate_complex_state(scf_env%qs_ot_env(ot_channel), matrix_sk_re)
    2072          608 :             IF (local_init) THEN
    2073          408 :                local_channel = ot_channel - first_channel + 1
    2074          408 :                local_s(1, local_channel)%matrix => kp%ot_smat(1)
    2075          408 :                local_s(2, local_channel)%matrix => kp%ot_smat(2)
    2076          408 :                local_c(local_channel)%matrix => mo_set%cmo_coeff
    2077              :             ELSE
    2078          200 :                CALL cp_fm_create(mo_coeff, mo_set%cmo_coeff%matrix_struct)
    2079          200 :                CALL cp_fm_create(mo_coeff_im, mo_set%cmo_coeff%matrix_struct)
    2080          200 :                CALL cp_cfm_to_fm(mo_set%cmo_coeff, mo_coeff, mo_coeff_im)
    2081          200 :                CALL cp_fm_create(active_mo_coeff, active_mo_struct)
    2082          200 :                CALL cp_fm_to_fm(mo_coeff, active_mo_coeff, nocc)
    2083          200 :                CALL dbcsr_set(scf_env%qs_ot_env(ot_channel)%matrix_c0, 0.0_dp)
    2084          200 :                CALL copy_fm_to_dbcsr(active_mo_coeff, scf_env%qs_ot_env(ot_channel)%matrix_c0)
    2085              : 
    2086          200 :                CALL cp_fm_create(active_mo_coeff_im, active_mo_struct)
    2087          200 :                CALL cp_fm_to_fm(mo_coeff_im, active_mo_coeff_im, nocc)
    2088          200 :                CALL dbcsr_set(scf_env%qs_ot_env(ot_channel)%matrix_c0_im, 0.0_dp)
    2089          200 :                CALL dbcsr_set(scf_env%qs_ot_env(ot_channel)%matrix_sc0_im, 0.0_dp)
    2090          200 :                CALL copy_fm_to_dbcsr(active_mo_coeff_im, scf_env%qs_ot_env(ot_channel)%matrix_c0_im)
    2091              :                CALL qs_ot_complex_multiply('N', 'N', matrix_sk_re, matrix_sk_im, &
    2092              :                                            scf_env%qs_ot_env(ot_channel)%matrix_c0, &
    2093              :                                            scf_env%qs_ot_env(ot_channel)%matrix_c0_im, &
    2094              :                                            scf_env%qs_ot_env(ot_channel)%matrix_sc0, &
    2095              :                                            scf_env%qs_ot_env(ot_channel)%matrix_sc0_im, &
    2096          200 :                                            scf_env%qs_ot_env(ot_channel)%matrix_x)
    2097              : 
    2098          200 :                CALL cp_fm_release(active_mo_coeff)
    2099          200 :                CALL cp_fm_release(active_mo_coeff_im)
    2100          200 :                CALL cp_fm_release(mo_coeff)
    2101          200 :                CALL cp_fm_release(mo_coeff_im)
    2102              :             END IF
    2103              : 
    2104          608 :             CALL qs_ot_init(scf_env%qs_ot_env(ot_channel))
    2105          608 :             IF (scf_env%qs_ot_env(ot_channel)%settings%do_ener) THEN
    2106          129 :                IF (dft_control%restricted) THEN
    2107           24 :                   DO energy_spin = 1, SIZE(kp%mos)
    2108           16 :                      CALL get_mo_set(kp%mos(energy_spin), eigenvalues=eigenvalues)
    2109           16 :                      energy_start = (energy_spin - 1)*nocc + 1
    2110              :                      scf_env%qs_ot_env(ot_channel)%ener_x(energy_start:energy_start + nocc - 1) = &
    2111          280 :                         eigenvalues(1:nocc)
    2112              :                   END DO
    2113              :                ELSE
    2114         1817 :                   scf_env%qs_ot_env(ot_channel)%ener_x(:) = eigenvalues(1:nocc)
    2115              :                END IF
    2116              :             END IF
    2117          608 :             scf_env%qs_ot_env(ot_channel)%broyden_adaptive_sigma = qs_env%broyden_adaptive_sigma
    2118              : 
    2119         1024 :             SELECT CASE (scf_env%qs_ot_env(ot_channel)%settings%ot_algorithm)
    2120              :             CASE ("TOD")
    2121          416 :                CALL dbcsr_set(scf_env%qs_ot_env(ot_channel)%matrix_x, 0.0_dp)
    2122          416 :                CALL dbcsr_set(scf_env%qs_ot_env(ot_channel)%matrix_sx, 0.0_dp)
    2123          416 :                CALL dbcsr_set(scf_env%qs_ot_env(ot_channel)%matrix_x_im, 0.0_dp)
    2124          416 :                CALL dbcsr_set(scf_env%qs_ot_env(ot_channel)%matrix_sx_im, 0.0_dp)
    2125              :                CALL qs_ot_get_p_complex(scf_env%qs_ot_env(ot_channel)%matrix_x, &
    2126              :                                         scf_env%qs_ot_env(ot_channel)%matrix_x_im, &
    2127              :                                         scf_env%qs_ot_env(ot_channel)%matrix_sx, &
    2128              :                                         scf_env%qs_ot_env(ot_channel)%matrix_sx_im, &
    2129          416 :                                         scf_env%qs_ot_env(ot_channel), zero_coordinates=.TRUE.)
    2130              :             CASE ("REF")
    2131          192 :                IF (.NOT. local_init) THEN
    2132              :                   CALL dbcsr_copy(scf_env%qs_ot_env(ot_channel)%matrix_x, &
    2133          118 :                                   scf_env%qs_ot_env(ot_channel)%matrix_c0)
    2134              :                   CALL dbcsr_copy(scf_env%qs_ot_env(ot_channel)%matrix_x_im, &
    2135          118 :                                   scf_env%qs_ot_env(ot_channel)%matrix_c0_im)
    2136              :                   CALL qs_ot_get_orbitals_ref_complex(scf_env%qs_ot_env(ot_channel)%matrix_c0, &
    2137              :                                                       scf_env%qs_ot_env(ot_channel)%matrix_c0_im, &
    2138              :                                                       matrix_sk_re, matrix_sk_im, &
    2139          118 :                                                       scf_env%qs_ot_env(ot_channel))
    2140              :                END IF
    2141              :             CASE DEFAULT
    2142          608 :                CPABORT("Algorithm not yet implemented")
    2143              :             END SELECT
    2144              : 
    2145          608 :             CPASSERT(scf_env%qs_ot_env(ot_channel)%state_allocated)
    2146          608 :             CPASSERT(scf_env%qs_ot_env(ot_channel)%has_complex_kpoint_state)
    2147         1744 :             CALL cp_fm_struct_release(active_mo_struct)
    2148              :          END DO
    2149          528 :          CALL dbcsr_release_p(matrix_sk_re)
    2150          812 :          CALL dbcsr_release_p(matrix_sk_im)
    2151              :       END DO
    2152              : 
    2153          284 :       IF (local_init) THEN
    2154              :          CALL qs_ot_get_orbitals_local_batch( &
    2155              :             scf_env%qs_ot_env(first_channel:first_channel + SIZE(local_c) - 1), &
    2156          188 :             local_s, local_c, initialize=.TRUE.)
    2157              :       END IF
    2158              : 
    2159              :       CALL qs_ot_check_channel_context(scf_env%qs_ot_env, dft_control%nspins, &
    2160              :                                        nkpoint=kpoints%nkp, &
    2161              :                                        restricted=ANY(scf_env%qs_ot_env(:)%restricted), &
    2162              :                                        require_kpoint=.TRUE., &
    2163              :                                        kp_range=kpoints%kp_range, &
    2164              :                                        require_local_state=.TRUE., &
    2165         1286 :                                        require_complex_state=.TRUE.)
    2166              : 
    2167              :       CALL prepare_qs_ot_kpoint_preconditioners(scf_env, kpoints, matrix_ks_kp, &
    2168          284 :                                                 matrix_s_kp, matrix_t_kp, nspin_ot)
    2169              : 
    2170          284 :       CALL timestop(handle)
    2171              : 
    2172          568 :    END SUBROUTINE allocate_qs_ot_kpoint_state
    2173              : 
    2174              : ! **************************************************************************************************
    2175              : !> \brief prepare and attach orbital preconditioners for complex k-point OT channels
    2176              : !> \param scf_env ...
    2177              : !> \param kpoints ...
    2178              : !> \param matrix_ks ...
    2179              : !> \param matrix_s ...
    2180              : !> \param matrix_t ...
    2181              : !> \param nspin_ot ...
    2182              : ! **************************************************************************************************
    2183          284 :    SUBROUTINE prepare_qs_ot_kpoint_preconditioners(scf_env, kpoints, matrix_ks, matrix_s, matrix_t, nspin_ot)
    2184              :       TYPE(qs_scf_env_type), POINTER                     :: scf_env
    2185              :       TYPE(kpoint_type), POINTER                         :: kpoints
    2186              :       TYPE(dbcsr_p_type), DIMENSION(:, :), POINTER       :: matrix_ks, matrix_s, matrix_t
    2187              :       INTEGER, INTENT(IN)                                :: nspin_ot
    2188              : 
    2189              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'prepare_qs_ot_kpoint_preconditioners'
    2190              : 
    2191              :       INTEGER :: first_channel, handle, ikpoint, ispin, ks_spin, local_channel, local_kpoint, &
    2192              :          n_ot_channels, nlocal, nocc, occupation_spin, ot_channel, prec_type, source_channel
    2193              :       LOGICAL                                            :: handled
    2194          284 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :)        :: occupation_signature
    2195          284 :       REAL(KIND=dp), DIMENSION(:), POINTER               :: occupation_numbers
    2196          284 :       TYPE(cp_fm_p_type), ALLOCATABLE                    :: local_h(:, :), local_s(:, :)
    2197          284 :       TYPE(dbcsr_p_type), ALLOCATABLE                    :: local_c(:, :)
    2198              :       TYPE(dbcsr_type), POINTER                          :: matrix_h_im, matrix_h_re, matrix_s_im, &
    2199              :                                                             matrix_s_re, matrix_t_im, matrix_t_re
    2200              :       TYPE(kpoint_env_type), POINTER                     :: kp
    2201              : 
    2202          284 :       CALL timeset(routineN, handle)
    2203              : 
    2204          284 :       NULLIFY (kp, matrix_h_im, matrix_h_re, matrix_s_im, matrix_s_re, matrix_t_im, matrix_t_re, &
    2205          284 :                occupation_numbers)
    2206          284 :       CPASSERT(ASSOCIATED(scf_env%qs_ot_env))
    2207          284 :       CPASSERT(ASSOCIATED(kpoints))
    2208          284 :       CPASSERT(ASSOCIATED(matrix_ks))
    2209          284 :       CPASSERT(ASSOCIATED(matrix_s))
    2210              : 
    2211          284 :       prec_type = scf_env%qs_ot_env(1)%settings%preconditioner_type
    2212          284 :       IF (prec_type == ot_precond_none) THEN
    2213            8 :          CALL timestop(handle)
    2214            8 :          RETURN
    2215              :       END IF
    2216            0 :       SELECT CASE (prec_type)
    2217              :       CASE (ot_precond_fermi_low_rank, ot_precond_full_all, ot_precond_full_all_covariant, &
    2218              :             ot_precond_full_single, ot_precond_full_single_inverse, &
    2219              :             ot_precond_full_kinetic, ot_precond_s_inverse)
    2220              :       CASE DEFAULT
    2221          276 :          CPABORT("Unsupported complex K-point OT preconditioner")
    2222              :       END SELECT
    2223          276 :       n_ot_channels = SIZE(scf_env%qs_ot_env)
    2224          276 :       IF (ASSOCIATED(scf_env%ot_preconditioner)) THEN
    2225          874 :          DO ot_channel = 1, SIZE(scf_env%ot_preconditioner)
    2226          874 :             IF (ASSOCIATED(scf_env%ot_preconditioner(ot_channel)%preconditioner)) THEN
    2227          364 :                CALL destroy_preconditioner(scf_env%ot_preconditioner(ot_channel)%preconditioner)
    2228          364 :                DEALLOCATE (scf_env%ot_preconditioner(ot_channel)%preconditioner)
    2229              :             END IF
    2230              :          END DO
    2231          174 :          DEALLOCATE (scf_env%ot_preconditioner)
    2232          174 :          NULLIFY (scf_env%ot_preconditioner)
    2233              :       END IF
    2234         1828 :       ALLOCATE (scf_env%ot_preconditioner(n_ot_channels))
    2235          796 :       DO local_kpoint = 1, SIZE(kpoints%kp_env)
    2236          520 :          kp => kpoints%kp_env(local_kpoint)%kpoint_env
    2237          520 :          ikpoint = kp%nkpoint
    2238         1388 :          DO ispin = 1, nspin_ot
    2239          592 :             ot_channel = qs_ot_channel_index(ispin, ikpoint, nspin_ot)
    2240          592 :             CPASSERT(scf_env%qs_ot_env(ot_channel)%state_allocated)
    2241         2368 :             ALLOCATE (scf_env%ot_preconditioner(ot_channel)%preconditioner)
    2242              :             CALL init_preconditioner(scf_env%ot_preconditioner(ot_channel)%preconditioner, &
    2243              :                                      para_env=scf_env%qs_ot_env(ot_channel)%para_env, &
    2244         1112 :                                      blacs_env=scf_env%qs_ot_env(ot_channel)%blacs_env)
    2245              :          END DO
    2246              :       END DO
    2247              : 
    2248          276 :       IF (prec_type == ot_precond_full_all .AND. .NOT. ALLOCATED(kpoints%lowdin_v)) THEN
    2249           56 :          first_channel = qs_ot_channel_index(1, kpoints%kp_range(1), nspin_ot)
    2250           56 :          nlocal = SIZE(kpoints%kp_env)*nspin_ot
    2251         1261 :          ALLOCATE (local_c(2, nlocal), local_h(2, nlocal), local_s(2, nlocal))
    2252          149 :          DO local_kpoint = 1, SIZE(kpoints%kp_env)
    2253           93 :             kp => kpoints%kp_env(local_kpoint)%kpoint_env
    2254          258 :             DO ispin = 1, nspin_ot
    2255          109 :                ot_channel = qs_ot_channel_index(ispin, kp%nkpoint, nspin_ot)
    2256          109 :                local_channel = ot_channel - first_channel + 1
    2257          109 :                ks_spin = MIN(ispin, SIZE(kp%ot_hmat, 2))
    2258          109 :                local_c(1, local_channel)%matrix => scf_env%qs_ot_env(ot_channel)%matrix_c0
    2259          109 :                local_c(2, local_channel)%matrix => scf_env%qs_ot_env(ot_channel)%matrix_c0_im
    2260          109 :                local_h(1, local_channel)%matrix => kp%ot_hmat(1, ks_spin)
    2261          109 :                local_h(2, local_channel)%matrix => kp%ot_hmat(2, ks_spin)
    2262          109 :                local_s(1, local_channel)%matrix => kp%ot_smat(1)
    2263          202 :                local_s(2, local_channel)%matrix => kp%ot_smat(2)
    2264              :             END DO
    2265              :          END DO
    2266              :          CALL make_preconditioner_complex_full_all_batch( &
    2267              :             scf_env%ot_preconditioner(first_channel:first_channel + nlocal - 1), local_c, local_h, local_s, &
    2268           56 :             scf_env%qs_ot_env(1)%settings%energy_gap, scf_env%qs_ot_env(1)%settings%precond_solver_type, handled)
    2269           56 :          IF (handled) THEN
    2270           95 :             DO ot_channel = first_channel, first_channel + nlocal - 1
    2271              :                CALL qs_ot_new_preconditioner(scf_env%qs_ot_env(ot_channel), &
    2272           95 :                                              scf_env%ot_preconditioner(ot_channel)%preconditioner)
    2273              :             END DO
    2274           32 :             CALL timestop(handle)
    2275           32 :             RETURN
    2276              :          END IF
    2277              :       END IF
    2278              : 
    2279          707 :       DO local_kpoint = 1, SIZE(kpoints%kp_env)
    2280          463 :          kp => kpoints%kp_env(local_kpoint)%kpoint_env
    2281          463 :          CPASSERT(ASSOCIATED(kp))
    2282          463 :          CPASSERT(ASSOCIATED(kp%ot_hmat))
    2283          463 :          CPASSERT(ASSOCIATED(kp%ot_smat))
    2284          463 :          CPASSERT(SIZE(kp%ot_smat) >= 2)
    2285          463 :          ikpoint = kp%nkpoint
    2286              :          CALL kpoint_operator_get_local(matrix_s, kpoints, kp, 1, &
    2287              :                                         kp%ot_smat(1), kp%ot_smat(2), &
    2288          463 :                                         matrix_s_re, matrix_s_im)
    2289          463 :          IF (prec_type == ot_precond_full_kinetic) THEN
    2290          345 :             CPASSERT(ASSOCIATED(matrix_t))
    2291          345 :             CPASSERT(ASSOCIATED(kp%ot_tmat))
    2292          345 :             CPASSERT(SIZE(kp%ot_tmat) >= 2)
    2293              :             CALL kpoint_operator_get_local(matrix_t, kpoints, kp, 1, &
    2294              :                                            kp%ot_tmat(1), kp%ot_tmat(2), &
    2295          345 :                                            matrix_t_re, matrix_t_im)
    2296              :          END IF
    2297          992 :          DO ispin = 1, nspin_ot
    2298          529 :             ot_channel = qs_ot_channel_index(ispin, ikpoint, nspin_ot)
    2299          529 :             IF (ispin > 1 .AND. &
    2300              :                 (prec_type == ot_precond_full_kinetic .OR. prec_type == ot_precond_s_inverse)) THEN
    2301           56 :                source_channel = qs_ot_channel_index(1, ikpoint, nspin_ot)
    2302           56 :                IF (.NOT. (ASSOCIATED(scf_env%ot_preconditioner(source_channel)%preconditioner%complex_fm))) THEN
    2303            0 :                   CALL cp_abort(__LOCATION__, "Missing shared complex OT preconditioner")
    2304              :                END IF
    2305              :                scf_env%ot_preconditioner(ot_channel)%preconditioner%complex_fm => &
    2306           56 :                   scf_env%ot_preconditioner(source_channel)%preconditioner%complex_fm
    2307           56 :                scf_env%ot_preconditioner(ot_channel)%preconditioner%owns_complex_fm = .FALSE.
    2308              :                scf_env%ot_preconditioner(ot_channel)%preconditioner%energy_gap = &
    2309           56 :                   scf_env%ot_preconditioner(source_channel)%preconditioner%energy_gap
    2310              :                scf_env%ot_preconditioner(ot_channel)%preconditioner%in_use = &
    2311           56 :                   scf_env%ot_preconditioner(source_channel)%preconditioner%in_use
    2312              :                scf_env%ot_preconditioner(ot_channel)%preconditioner%solver = &
    2313           56 :                   scf_env%ot_preconditioner(source_channel)%preconditioner%solver
    2314              :                CALL qs_ot_new_preconditioner(scf_env%qs_ot_env(ot_channel), &
    2315           56 :                                              scf_env%ot_preconditioner(ot_channel)%preconditioner)
    2316           56 :                CYCLE
    2317              :             END IF
    2318              :             IF (prec_type == ot_precond_fermi_low_rank .OR. &
    2319              :                 prec_type == ot_precond_full_all .OR. &
    2320              :                 prec_type == ot_precond_full_all_covariant .OR. &
    2321          473 :                 prec_type == ot_precond_full_single .OR. &
    2322              :                 prec_type == ot_precond_full_single_inverse) THEN
    2323           78 :                ks_spin = MIN(ispin, SIZE(kp%ot_hmat, 2))
    2324           78 :                CPASSERT(SIZE(kp%ot_hmat, 1) >= 2)
    2325           78 :                IF (ALLOCATED(kpoints%lowdin_v)) THEN
    2326            0 :                   BLOCK
    2327              :                      TYPE(cp_cfm_type) :: h
    2328              :                      TYPE(cp_fm_type) :: h_re, h_im
    2329              : 
    2330              :                      ! The physical +U operator need not share the real-space sparsity pattern.
    2331              :                      ! This full construction is only needed when preparing the preconditioner.
    2332            0 :                      CALL cp_cfm_create(h, kp%ot_hmat(1, ks_spin)%matrix_struct)
    2333            0 :                      CALL cp_fm_to_cfm(kp%ot_hmat(1, ks_spin), kp%ot_hmat(2, ks_spin), h)
    2334            0 :                      CALL lowdin_kp_apply(kp, kpoints%lowdin_v(:, ks_spin), cmat=h)
    2335            0 :                      CALL cp_fm_create(h_re, h%matrix_struct)
    2336            0 :                      CALL cp_fm_create(h_im, h%matrix_struct)
    2337            0 :                      CALL cp_cfm_to_fm(h, h_re, h_im)
    2338            0 :                      CALL dbcsr_init_p(matrix_h_re)
    2339            0 :                      CALL dbcsr_init_p(matrix_h_im)
    2340            0 :                      CALL copy_fm_to_dbcsr_bc(h_re, matrix_h_re)
    2341            0 :                      CALL copy_fm_to_dbcsr_bc(h_im, matrix_h_im)
    2342            0 :                      CALL cp_fm_release(h_re)
    2343            0 :                      CALL cp_fm_release(h_im)
    2344            0 :                      CALL cp_cfm_release(h)
    2345              :                   END BLOCK
    2346              :                ELSE
    2347              :                   CALL kpoint_operator_get_local(matrix_ks, kpoints, kp, ks_spin, &
    2348              :                                                  kp%ot_hmat(1, ks_spin), kp%ot_hmat(2, ks_spin), &
    2349           78 :                                                  matrix_h_re, matrix_h_im)
    2350              :                END IF
    2351              :             END IF
    2352           10 :             SELECT CASE (prec_type)
    2353              :             CASE (ot_precond_fermi_low_rank)
    2354              :                CALL make_preconditioner_complex_fermi_low_rank( &
    2355              :                   scf_env%ot_preconditioner(ot_channel)%preconditioner, &
    2356              :                   scf_env%qs_ot_env(ot_channel)%matrix_c0, &
    2357              :                   scf_env%qs_ot_env(ot_channel)%matrix_c0_im, &
    2358              :                   matrix_h_re, matrix_h_im, matrix_s_re, matrix_s_im, &
    2359              :                   scf_env%qs_ot_env(ot_channel)%settings%energy_gap, &
    2360              :                   scf_env%qs_ot_env(ot_channel)%settings%fermi_low_rank_max_rank, &
    2361           10 :                   scf_env%qs_ot_env(ot_channel)%settings%precond_solver_type)
    2362              :             CASE (ot_precond_full_all)
    2363              :                CALL make_preconditioner_complex_full_all( &
    2364              :                   scf_env%ot_preconditioner(ot_channel)%preconditioner, &
    2365              :                   scf_env%qs_ot_env(ot_channel)%matrix_c0, &
    2366              :                   scf_env%qs_ot_env(ot_channel)%matrix_c0_im, &
    2367              :                   matrix_h_re, matrix_h_im, matrix_s_re, matrix_s_im, &
    2368              :                   scf_env%qs_ot_env(ot_channel)%settings%energy_gap, &
    2369           46 :                   scf_env%qs_ot_env(ot_channel)%settings%precond_solver_type)
    2370              :             CASE (ot_precond_full_single)
    2371              :                CALL make_preconditioner_complex_full_single( &
    2372              :                   scf_env%ot_preconditioner(ot_channel)%preconditioner, &
    2373              :                   matrix_h_re, matrix_h_im, matrix_s_re, matrix_s_im, &
    2374              :                   kp%mos(ispin), &
    2375              :                   scf_env%qs_ot_env(ot_channel)%settings%energy_gap, &
    2376            8 :                   scf_env%qs_ot_env(ot_channel)%settings%precond_solver_type)
    2377              :             CASE (ot_precond_full_all_covariant)
    2378           10 :                IF (nspin_ot == 1 .AND. SIZE(kp%mos) > 1) THEN
    2379              :                   CALL dbcsr_get_info(scf_env%qs_ot_env(ot_channel)%matrix_c0, &
    2380            8 :                                       nfullcols_total=nocc)
    2381           32 :                   ALLOCATE (occupation_signature(nocc, SIZE(kp%mos)))
    2382           24 :                   DO occupation_spin = 1, SIZE(kp%mos)
    2383              :                      CALL get_mo_set(kp%mos(occupation_spin), &
    2384           16 :                                      occupation_numbers=occupation_numbers)
    2385           16 :                      CPASSERT(ASSOCIATED(occupation_numbers))
    2386           16 :                      CPASSERT(SIZE(occupation_numbers) >= nocc)
    2387          152 :                      occupation_signature(:, occupation_spin) = occupation_numbers(1:nocc)
    2388              :                   END DO
    2389              :                   CALL make_preconditioner_complex_full_all_covariant( &
    2390              :                      scf_env%ot_preconditioner(ot_channel)%preconditioner, &
    2391              :                      scf_env%qs_ot_env(ot_channel)%matrix_c0, &
    2392              :                      scf_env%qs_ot_env(ot_channel)%matrix_c0_im, &
    2393              :                      matrix_h_re, matrix_h_im, matrix_s_re, matrix_s_im, &
    2394              :                      scf_env%qs_ot_env(ot_channel)%settings%energy_gap, &
    2395              :                      scf_env%qs_ot_env(ot_channel)%settings%precond_solver_type, &
    2396            8 :                      occupation_signature)
    2397           16 :                   DEALLOCATE (occupation_signature)
    2398              :                ELSE
    2399              :                   CALL make_preconditioner_complex_full_all_covariant( &
    2400              :                      scf_env%ot_preconditioner(ot_channel)%preconditioner, &
    2401              :                      scf_env%qs_ot_env(ot_channel)%matrix_c0, &
    2402              :                      scf_env%qs_ot_env(ot_channel)%matrix_c0_im, &
    2403              :                      matrix_h_re, matrix_h_im, matrix_s_re, matrix_s_im, &
    2404              :                      scf_env%qs_ot_env(ot_channel)%settings%energy_gap, &
    2405            2 :                      scf_env%qs_ot_env(ot_channel)%settings%precond_solver_type)
    2406              :                END IF
    2407              :             CASE (ot_precond_full_single_inverse)
    2408              :                CALL make_preconditioner_complex_full_single_inverse( &
    2409              :                   scf_env%ot_preconditioner(ot_channel)%preconditioner, &
    2410              :                   scf_env%qs_ot_env(ot_channel)%matrix_c0, &
    2411              :                   scf_env%qs_ot_env(ot_channel)%matrix_c0_im, &
    2412              :                   matrix_h_re, matrix_h_im, matrix_s_re, matrix_s_im, &
    2413              :                   scf_env%qs_ot_env(ot_channel)%settings%energy_gap, &
    2414            4 :                   scf_env%qs_ot_env(ot_channel)%settings%precond_solver_type)
    2415              :             CASE (ot_precond_full_kinetic)
    2416              :                CALL make_preconditioner_complex_full_kinetic( &
    2417              :                   scf_env%ot_preconditioner(ot_channel)%preconditioner, &
    2418              :                   matrix_t_re, matrix_t_im, matrix_s_re, matrix_s_im, &
    2419              :                   scf_env%qs_ot_env(ot_channel)%settings%energy_gap, &
    2420          345 :                   scf_env%qs_ot_env(ot_channel)%settings%precond_solver_type)
    2421              :             CASE (ot_precond_s_inverse)
    2422              :                CALL make_preconditioner_complex_full_s_inverse( &
    2423              :                   scf_env%ot_preconditioner(ot_channel)%preconditioner, &
    2424              :                   matrix_s_re, matrix_s_im, &
    2425          473 :                   scf_env%qs_ot_env(ot_channel)%settings%precond_solver_type)
    2426              :             END SELECT
    2427              :             CALL qs_ot_new_preconditioner(scf_env%qs_ot_env(ot_channel), &
    2428          473 :                                           scf_env%ot_preconditioner(ot_channel)%preconditioner)
    2429          473 :             IF (ASSOCIATED(matrix_h_re)) CALL dbcsr_release_p(matrix_h_re)
    2430          936 :             IF (ASSOCIATED(matrix_h_im)) CALL dbcsr_release_p(matrix_h_im)
    2431              :          END DO
    2432          463 :          CALL dbcsr_release_p(matrix_s_re)
    2433          463 :          CALL dbcsr_release_p(matrix_s_im)
    2434          463 :          IF (ASSOCIATED(matrix_t_re)) CALL dbcsr_release_p(matrix_t_re)
    2435          707 :          IF (ASSOCIATED(matrix_t_im)) CALL dbcsr_release_p(matrix_t_im)
    2436              :       END DO
    2437              : 
    2438          244 :       CALL timestop(handle)
    2439              : 
    2440          568 :    END SUBROUTINE prepare_qs_ot_kpoint_preconditioners
    2441              : 
    2442              : ! **************************************************************************************************
    2443              : !> \brief perform cleanup operations (like releasing temporary storage)
    2444              : !>      at the end of the scf
    2445              : !> \param scf_env ...
    2446              : !> \par History
    2447              : !>      02.2003 created [fawzi]
    2448              : !> \author fawzi
    2449              : ! **************************************************************************************************
    2450        24807 :    SUBROUTINE scf_env_cleanup(scf_env)
    2451              :       TYPE(qs_scf_env_type), INTENT(INOUT)               :: scf_env
    2452              : 
    2453              :       CHARACTER(len=*), PARAMETER                        :: routineN = 'scf_env_cleanup'
    2454              : 
    2455              :       INTEGER                                            :: handle
    2456              : 
    2457        24807 :       CALL timeset(routineN, handle)
    2458              : 
    2459              :       ! Release SCF work storage
    2460        73265 :       IF (ALLOCATED(scf_env%fm_copy_plan)) DEALLOCATE (scf_env%fm_copy_plan)
    2461        24807 :       CALL cp_fm_release(scf_env%scf_work1)
    2462              : 
    2463        24807 :       IF (ASSOCIATED(scf_env%scf_work1_red)) THEN
    2464           62 :          CALL cp_fm_release(scf_env%scf_work1_red)
    2465              :       END IF
    2466        24807 :       IF (ASSOCIATED(scf_env%scf_work2)) THEN
    2467        18078 :          CALL cp_fm_release(scf_env%scf_work2)
    2468        18078 :          DEALLOCATE (scf_env%scf_work2)
    2469              :          NULLIFY (scf_env%scf_work2)
    2470              :       END IF
    2471        24807 :       IF (ASSOCIATED(scf_env%scf_work2_red)) THEN
    2472           62 :          CALL cp_fm_release(scf_env%scf_work2_red)
    2473           62 :          DEALLOCATE (scf_env%scf_work2_red)
    2474              :          NULLIFY (scf_env%scf_work2_red)
    2475              :       END IF
    2476        24807 :       IF (ASSOCIATED(scf_env%ortho)) THEN
    2477        15408 :          CALL cp_fm_release(scf_env%ortho)
    2478        15408 :          DEALLOCATE (scf_env%ortho)
    2479              :          NULLIFY (scf_env%ortho)
    2480              :       END IF
    2481        24807 :       IF (ASSOCIATED(scf_env%ortho_red)) THEN
    2482           62 :          CALL cp_fm_release(scf_env%ortho_red)
    2483           62 :          DEALLOCATE (scf_env%ortho_red)
    2484              :          NULLIFY (scf_env%ortho_red)
    2485              :       END IF
    2486        24807 :       IF (ASSOCIATED(scf_env%ortho_m1)) THEN
    2487           64 :          CALL cp_fm_release(scf_env%ortho_m1)
    2488           64 :          DEALLOCATE (scf_env%ortho_m1)
    2489              :          NULLIFY (scf_env%ortho_m1)
    2490              :       END IF
    2491        24807 :       IF (ASSOCIATED(scf_env%ortho_m1_red)) THEN
    2492            6 :          CALL cp_fm_release(scf_env%ortho_m1_red)
    2493            6 :          DEALLOCATE (scf_env%ortho_m1_red)
    2494              :          NULLIFY (scf_env%ortho_m1_red)
    2495              :       END IF
    2496              : 
    2497        24807 :       IF (ASSOCIATED(scf_env%ortho_dbcsr)) THEN
    2498           58 :          CALL dbcsr_deallocate_matrix(scf_env%ortho_dbcsr)
    2499              :       END IF
    2500        24807 :       IF (ASSOCIATED(scf_env%buf1_dbcsr)) THEN
    2501           58 :          CALL dbcsr_deallocate_matrix(scf_env%buf1_dbcsr)
    2502              :       END IF
    2503        24807 :       IF (ASSOCIATED(scf_env%buf2_dbcsr)) THEN
    2504           58 :          CALL dbcsr_deallocate_matrix(scf_env%buf2_dbcsr)
    2505              :       END IF
    2506              : 
    2507        24807 :       IF (ASSOCIATED(scf_env%p_mix_new)) THEN
    2508        18128 :          CALL dbcsr_deallocate_matrix_set(scf_env%p_mix_new)
    2509              :       END IF
    2510              : 
    2511        24807 :       IF (ASSOCIATED(scf_env%p_delta)) THEN
    2512         1210 :          CALL dbcsr_deallocate_matrix_set(scf_env%p_delta)
    2513              :       END IF
    2514              : 
    2515              :       ! Method dependent cleanup
    2516        24857 :       SELECT CASE (scf_env%method)
    2517              :       CASE (ot_method_nr)
    2518              :          !
    2519              :       CASE (ot_diag_method_nr)
    2520              :          !
    2521              :       CASE (general_diag_method_nr)
    2522              :          !
    2523              :       CASE (special_diag_method_nr)
    2524              :          !
    2525              :       CASE (block_krylov_diag_method_nr)
    2526              :       CASE (block_davidson_diag_method_nr)
    2527           50 :          CALL block_davidson_deallocate(scf_env%block_davidson_env)
    2528              :       CASE (filter_matrix_diag_method_nr)
    2529              :          !
    2530              :       CASE (smeagol_method_nr)
    2531              :          !
    2532              :       CASE DEFAULT
    2533        24807 :          CPABORT("unknown scf method method:"//cp_to_string(scf_env%method))
    2534              :       END SELECT
    2535              : 
    2536        24807 :       IF (ASSOCIATED(scf_env%outer_scf%variables)) THEN
    2537         4455 :          DEALLOCATE (scf_env%outer_scf%variables)
    2538              :       END IF
    2539        24807 :       IF (ASSOCIATED(scf_env%outer_scf%count)) THEN
    2540         4455 :          DEALLOCATE (scf_env%outer_scf%count)
    2541              :       END IF
    2542        24807 :       IF (ASSOCIATED(scf_env%outer_scf%gradient)) THEN
    2543         4455 :          DEALLOCATE (scf_env%outer_scf%gradient)
    2544              :       END IF
    2545        24807 :       IF (ASSOCIATED(scf_env%outer_scf%energy)) THEN
    2546         4455 :          DEALLOCATE (scf_env%outer_scf%energy)
    2547              :       END IF
    2548        24807 :       IF (ASSOCIATED(scf_env%outer_scf%inv_jacobian) .AND. &
    2549              :           scf_env%outer_scf%deallocate_jacobian) THEN
    2550           52 :          DEALLOCATE (scf_env%outer_scf%inv_jacobian)
    2551              :       END IF
    2552              : 
    2553        24807 :       CALL timestop(handle)
    2554              : 
    2555        24807 :    END SUBROUTINE scf_env_cleanup
    2556              : 
    2557              : ! **************************************************************************************************
    2558              : !> \brief perform a CDFT scf procedure in the given qs_env
    2559              : !> \param qs_env the qs_environment where to perform the scf procedure
    2560              : !> \param should_stop flag determining if calculation should stop
    2561              : !> \param has_converged both the electronic and constraint loops converged
    2562              : !> \param total_scf_steps number of electronic SCF steps over the constraint loop
    2563              : !> \par History
    2564              : !>      12.2015 Created
    2565              : !> \author Nico Holmberg
    2566              : ! **************************************************************************************************
    2567          362 :    SUBROUTINE cdft_scf(qs_env, should_stop, has_converged, total_scf_steps)
    2568              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    2569              :       LOGICAL, INTENT(OUT)                               :: should_stop, has_converged
    2570              :       INTEGER, INTENT(OUT)                               :: total_scf_steps
    2571              : 
    2572              :       CHARACTER(len=*), PARAMETER                        :: routineN = 'cdft_scf'
    2573              : 
    2574              :       INTEGER                                            :: handle, iatom, iimage, ispin, ivar, nmo, &
    2575              :                                                             nvar, output_unit, tsteps
    2576              :       LOGICAL                                            :: cdft_loop_converged, converged, &
    2577              :                                                             exit_cdft_loop, first_iteration, &
    2578              :                                                             my_uocc, uniform_occupation
    2579          362 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:)           :: gapw_cdft_values
    2580          362 :       REAL(KIND=dp), DIMENSION(:), POINTER               :: mo_occupations
    2581          362 :       TYPE(atomic_kind_type), DIMENSION(:), POINTER      :: atomic_kind_set
    2582              :       TYPE(cdft_control_type), POINTER                   :: cdft_control
    2583              :       TYPE(cp_logger_type), POINTER                      :: logger
    2584          362 :       TYPE(dbcsr_p_type), DIMENSION(:), POINTER          :: gapw_wmat, matrix_s, rho_ao
    2585              :       TYPE(dft_control_type), POINTER                    :: dft_control
    2586              :       TYPE(local_rho_type), POINTER                      :: gapw_operator_rho
    2587          362 :       TYPE(mo_set_type), DIMENSION(:), POINTER           :: mos
    2588              :       TYPE(mp_para_env_type), POINTER                    :: para_env
    2589              :       TYPE(pw_env_type), POINTER                         :: pw_env
    2590              :       TYPE(pw_pool_type), POINTER                        :: auxbas_pw_pool
    2591              :       TYPE(qs_energy_type), POINTER                      :: energy
    2592          362 :       TYPE(qs_kind_type), DIMENSION(:), POINTER          :: qs_kind_set
    2593              :       TYPE(qs_ks_env_type), POINTER                      :: ks_env
    2594              :       TYPE(qs_rho_type), POINTER                         :: rho
    2595              :       TYPE(qs_scf_env_type), POINTER                     :: scf_env
    2596              :       TYPE(scf_control_type), POINTER                    :: scf_control
    2597              :       TYPE(section_vals_type), POINTER                   :: dft_section, input, scf_section
    2598              : 
    2599          362 :       NULLIFY (atomic_kind_set, gapw_operator_rho, gapw_wmat, para_env, qs_kind_set, &
    2600          362 :                scf_env, ks_env, energy, rho, matrix_s, rho_ao, cdft_control, logger, &
    2601          362 :                dft_control, pw_env, auxbas_pw_pool, energy, ks_env, scf_env, dft_section, &
    2602          362 :                input, scf_section, scf_control, mos, mo_occupations)
    2603          724 :       logger => cp_get_default_logger()
    2604              : 
    2605          362 :       CPASSERT(ASSOCIATED(qs_env))
    2606              :       CALL get_qs_env(qs_env, scf_env=scf_env, energy=energy, &
    2607              :                       dft_control=dft_control, scf_control=scf_control, &
    2608          362 :                       ks_env=ks_env, input=input)
    2609              : 
    2610          362 :       CALL timeset(routineN//"_loop", handle)
    2611          362 :       dft_section => section_vals_get_subs_vals(input, "DFT")
    2612          362 :       scf_section => section_vals_get_subs_vals(dft_section, "SCF")
    2613              :       output_unit = cp_print_key_unit_nr(logger, scf_section, "PRINT%PROGRAM_RUN_INFO", &
    2614          362 :                                          extension=".scfLog")
    2615          362 :       first_iteration = .TRUE.
    2616              : 
    2617          362 :       cdft_control => dft_control%qs_control%cdft_control
    2618              : 
    2619          362 :       scf_env%outer_scf%iter_count = 0
    2620          362 :       cdft_control%total_steps = 0
    2621          362 :       total_scf_steps = 0
    2622              : 
    2623              :       ! Write some info about the CDFT calculation
    2624          362 :       IF (output_unit > 0) THEN
    2625              :          WRITE (UNIT=output_unit, FMT="(/,/,T2,A)") &
    2626          200 :             "CDFT EXTERNAL SCF WAVEFUNCTION OPTIMIZATION"
    2627          200 :          CALL qs_scf_cdft_initial_info(output_unit, cdft_control)
    2628              :       END IF
    2629          362 :       IF (cdft_control%reuse_precond) THEN
    2630            0 :          reuse_precond = .FALSE.
    2631            0 :          cdft_control%nreused = 0
    2632              :       END IF
    2633          614 :       cdft_outer_loop: DO
    2634              :          ! Change outer_scf settings to OT settings
    2635          614 :          CALL outer_loop_switch(scf_env, scf_control, cdft_control, cdft2ot)
    2636              :          ! Solve electronic structure with fixed value of constraint
    2637              :          CALL scf_env_do_scf(scf_env=scf_env, scf_control=scf_control, qs_env=qs_env, &
    2638          614 :                              converged=converged, should_stop=should_stop, total_scf_steps=tsteps)
    2639          614 :          total_scf_steps = total_scf_steps + tsteps
    2640              :          ! Decide whether to reuse the preconditioner on the next iteration
    2641          614 :          IF (cdft_control%reuse_precond) THEN
    2642              :             ! For convergence in exactly one step, the preconditioner is always reused (assuming max_reuse > 0)
    2643              :             ! usually this means that the electronic structure has already converged to the correct state
    2644              :             ! but the constraint optimizer keeps jumping over the optimal solution
    2645              :             IF (scf_env%outer_scf%iter_count == 1 .AND. scf_env%iter_count == 1 &
    2646            0 :                 .AND. cdft_control%total_steps /= 1) THEN
    2647            0 :                cdft_control%nreused = cdft_control%nreused - 1
    2648              :             END IF
    2649              :             ! SCF converged in less than precond_freq steps
    2650              :             IF (scf_env%outer_scf%iter_count == 1 .AND. scf_env%iter_count <= cdft_control%precond_freq .AND. &
    2651            0 :                 cdft_control%total_steps /= 1 .AND. cdft_control%nreused < cdft_control%max_reuse) THEN
    2652            0 :                reuse_precond = .TRUE.
    2653            0 :                cdft_control%nreused = cdft_control%nreused + 1
    2654              :             ELSE
    2655            0 :                reuse_precond = .FALSE.
    2656            0 :                cdft_control%nreused = 0
    2657              :             END IF
    2658              :          END IF
    2659              :          ! Update history purging counters
    2660          614 :          IF (first_iteration .AND. cdft_control%purge_history) THEN
    2661            0 :             cdft_control%istep = cdft_control%istep + 1
    2662            0 :             IF (scf_env%outer_scf%iter_count > 1) THEN
    2663            0 :                cdft_control%nbad_conv = cdft_control%nbad_conv + 1
    2664            0 :                IF (cdft_control%nbad_conv >= cdft_control%purge_freq .AND. &
    2665              :                    cdft_control%istep >= cdft_control%purge_offset) THEN
    2666            0 :                   cdft_control%nbad_conv = 0
    2667            0 :                   cdft_control%istep = 0
    2668            0 :                   cdft_control%should_purge = .TRUE.
    2669              :                END IF
    2670              :             END IF
    2671              :          END IF
    2672          614 :          first_iteration = .FALSE.
    2673              :          ! Change outer_scf settings to CDFT settings
    2674          614 :          CALL outer_loop_switch(scf_env, scf_control, cdft_control, ot2cdft)
    2675              :          CALL qs_scf_check_outer_exit(qs_env, scf_env, scf_control, should_stop, &
    2676          614 :                                       cdft_loop_converged, exit_cdft_loop)
    2677              :          CALL qs_scf_cdft_info(output_unit, scf_control, scf_env, cdft_control, &
    2678              :                                energy, cdft_control%total_steps, &
    2679          614 :                                should_stop, cdft_loop_converged, cdft_loop=.TRUE.)
    2680          614 :          IF (exit_cdft_loop) EXIT cdft_outer_loop
    2681              :          ! Check if the inverse Jacobian needs to be calculated
    2682          252 :          CALL qs_calculate_inverse_jacobian(qs_env)
    2683              :          ! Check if a line search should be performed to find an optimal step size for the optimizer
    2684          252 :          CALL qs_cdft_line_search(qs_env)
    2685              :          ! Optimize constraint
    2686          252 :          CALL outer_loop_optimize(scf_env, scf_control)
    2687          252 :          CALL outer_loop_update_qs_env(qs_env, scf_env)
    2688          614 :          CALL qs_ks_did_change(ks_env, potential_changed=.TRUE.)
    2689              :       END DO cdft_outer_loop
    2690              : 
    2691          362 :       has_converged = converged .AND. cdft_loop_converged
    2692          362 :       cdft_control%ienergy = cdft_control%ienergy + 1
    2693              : 
    2694              :       ! Store needed arrays for ET coupling calculation
    2695          362 :       IF (cdft_control%do_et) THEN
    2696          190 :          CALL get_qs_env(qs_env=qs_env, matrix_s=matrix_s, mos=mos)
    2697          190 :          nvar = SIZE(cdft_control%target)
    2698          190 :          IF (dft_control%qs_control%gapw) THEN
    2699            4 :             IF (dft_control%nimages /= 1) THEN
    2700              :                CALL cp_abort(__LOCATION__, &
    2701            0 :                              "GAPW CDFT-CI currently requires a Gamma-point calculation.")
    2702              :             END IF
    2703              :             CALL get_qs_env(qs_env, atomic_kind_set=atomic_kind_set, para_env=para_env, &
    2704            4 :                             qs_kind_set=qs_kind_set, rho=rho)
    2705            4 :             CALL qs_rho_get(rho, rho_ao=rho_ao)
    2706            4 :             CALL local_rho_set_create(gapw_operator_rho)
    2707              :             CALL allocate_rho_atom_internals(gapw_operator_rho%rho_atom_set, atomic_kind_set, &
    2708            4 :                                              qs_kind_set, dft_control, para_env)
    2709           24 :             ALLOCATE (gapw_cdft_values(nvar), gapw_wmat(dft_control%nspins*dft_control%nimages))
    2710            8 :             DO iimage = 1, dft_control%nimages
    2711           12 :                DO ispin = 1, dft_control%nspins
    2712            4 :                   CALL dbcsr_init_p(gapw_wmat(dft_control%nspins*(iimage - 1) + ispin)%matrix)
    2713              :                   CALL dbcsr_copy(gapw_wmat(dft_control%nspins*(iimage - 1) + ispin)%matrix, &
    2714            8 :                                   matrix_s(iimage)%matrix, name="GAPW CDFT WEIGHT MATRIX")
    2715              :                END DO
    2716              :             END DO
    2717              :          END IF
    2718              :          ! Matrix representation of weight function
    2719          764 :          ALLOCATE (cdft_control%wmat(nvar))
    2720          384 :          DO ivar = 1, nvar
    2721          194 :             CALL dbcsr_init_p(cdft_control%wmat(ivar)%matrix)
    2722              :             CALL dbcsr_copy(cdft_control%wmat(ivar)%matrix, matrix_s(1)%matrix, &
    2723          194 :                             name="ET_RESTRAINT_MATRIX")
    2724          194 :             CALL dbcsr_set(cdft_control%wmat(ivar)%matrix, 0.0_dp)
    2725              :             CALL integrate_v_rspace(cdft_control%group(ivar)%weight, &
    2726              :                                     hmat=cdft_control%wmat(ivar), qs_env=qs_env, &
    2727              :                                     calculate_forces=.FALSE., &
    2728          194 :                                     gapw=dft_control%qs_control%gapw)
    2729          384 :             IF (dft_control%qs_control%gapw) THEN
    2730            8 :                DO ispin = 1, SIZE(gapw_wmat)
    2731            8 :                   CALL dbcsr_set(gapw_wmat(ispin)%matrix, 0.0_dp)
    2732              :                END DO
    2733            4 :                CALL zero_rho_atom_integrals(gapw_operator_rho%rho_atom_set)
    2734              :                CALL gapw_cdft_one_center(qs_env, energy_only=.FALSE., calculate_forces=.FALSE., &
    2735              :                                          values=gapw_cdft_values, operator_group=ivar, &
    2736            4 :                                          rho_atom_operator_set=gapw_operator_rho%rho_atom_set)
    2737              :                CALL update_ks_atom(qs_env, gapw_wmat, rho_ao, forces=.FALSE., &
    2738            4 :                                    rho_atom_external=gapw_operator_rho%rho_atom_set)
    2739            4 :                CALL dbcsr_add(cdft_control%wmat(ivar)%matrix, gapw_wmat(1)%matrix, 1.0_dp, 1.0_dp)
    2740              :             END IF
    2741              :          END DO
    2742          190 :          IF (dft_control%qs_control%gapw) THEN
    2743            4 :             CALL dbcsr_deallocate_matrix_set(gapw_wmat)
    2744            4 :             CALL local_rho_set_release(gapw_operator_rho)
    2745            4 :             DEALLOCATE (gapw_cdft_values)
    2746              :          END IF
    2747              :          ! Overlap matrix
    2748          190 :          CALL dbcsr_init_p(cdft_control%matrix_s%matrix)
    2749              :          CALL dbcsr_copy(cdft_control%matrix_s%matrix, matrix_s(1)%matrix, &
    2750          190 :                          name="OVERLAP")
    2751              :          ! Molecular orbital coefficients
    2752          190 :          NULLIFY (cdft_control%mo_coeff)
    2753          936 :          ALLOCATE (cdft_control%mo_coeff(dft_control%nspins))
    2754          556 :          DO ispin = 1, dft_control%nspins
    2755              :             CALL cp_fm_create(matrix=cdft_control%mo_coeff(ispin), &
    2756              :                               matrix_struct=qs_env%mos(ispin)%mo_coeff%matrix_struct, &
    2757          366 :                               name="MO_COEFF_A"//TRIM(ADJUSTL(cp_to_string(ispin)))//"MATRIX")
    2758              :             CALL cp_fm_to_fm(qs_env%mos(ispin)%mo_coeff, &
    2759          556 :                              cdft_control%mo_coeff(ispin))
    2760              :          END DO
    2761              :          ! Density matrix
    2762          190 :          IF (cdft_control%calculate_metric) THEN
    2763           24 :             CALL get_qs_env(qs_env, rho=rho)
    2764           24 :             CALL qs_rho_get(rho, rho_ao=rho_ao)
    2765          120 :             ALLOCATE (cdft_control%matrix_p(dft_control%nspins))
    2766           72 :             DO ispin = 1, dft_control%nspins
    2767           48 :                NULLIFY (cdft_control%matrix_p(ispin)%matrix)
    2768           48 :                CALL dbcsr_init_p(cdft_control%matrix_p(ispin)%matrix)
    2769              :                CALL dbcsr_copy(cdft_control%matrix_p(ispin)%matrix, rho_ao(ispin)%matrix, &
    2770           72 :                                name="DENSITY MATRIX")
    2771              :             END DO
    2772              :          END IF
    2773              :          ! Copy occupation numbers if non-uniform occupation
    2774          190 :          uniform_occupation = .TRUE.
    2775          556 :          DO ispin = 1, dft_control%nspins
    2776          366 :             CALL get_mo_set(mo_set=mos(ispin), uniform_occupation=my_uocc)
    2777          612 :             uniform_occupation = uniform_occupation .AND. my_uocc
    2778              :          END DO
    2779          190 :          IF (.NOT. uniform_occupation) THEN
    2780          140 :             ALLOCATE (cdft_control%occupations(dft_control%nspins))
    2781           84 :             DO ispin = 1, dft_control%nspins
    2782              :                CALL get_mo_set(mo_set=mos(ispin), &
    2783              :                                nmo=nmo, &
    2784           56 :                                occupation_numbers=mo_occupations)
    2785          168 :                ALLOCATE (cdft_control%occupations(ispin)%array(nmo))
    2786          588 :                cdft_control%occupations(ispin)%array(1:nmo) = mo_occupations(1:nmo)
    2787              :             END DO
    2788              :          END IF
    2789              :       END IF
    2790              : 
    2791              :       ! Deallocate constraint storage if forces are not needed
    2792              :       ! In case of a simulation with multiple force_evals,
    2793              :       ! deallocate only if weight function should not be copied to different force_evals
    2794          362 :       IF (.NOT. (cdft_control%save_pot .OR. cdft_control%transfer_pot)) THEN
    2795          170 :          CALL get_qs_env(qs_env, pw_env=pw_env)
    2796          170 :          CALL pw_env_get(pw_env, auxbas_pw_pool=auxbas_pw_pool)
    2797          354 :          DO iatom = 1, SIZE(cdft_control%group)
    2798          184 :             CALL auxbas_pw_pool%give_back_pw(cdft_control%group(iatom)%weight)
    2799          354 :             DEALLOCATE (cdft_control%group(iatom)%weight)
    2800              :          END DO
    2801          170 :          IF (cdft_control%atomic_charges) THEN
    2802          266 :             DO iatom = 1, cdft_control%natoms
    2803          266 :                CALL auxbas_pw_pool%give_back_pw(cdft_control%charge(iatom))
    2804              :             END DO
    2805           88 :             DEALLOCATE (cdft_control%charge)
    2806              :          END IF
    2807          170 :          IF (cdft_control%type == outer_scf_becke_constraint .AND. &
    2808              :              cdft_control%becke_control%cavity_confine) THEN
    2809          124 :             IF (.NOT. ASSOCIATED(cdft_control%becke_control%cavity_mat)) THEN
    2810          114 :                CALL auxbas_pw_pool%give_back_pw(cdft_control%becke_control%cavity)
    2811              :             ELSE
    2812           10 :                DEALLOCATE (cdft_control%becke_control%cavity_mat)
    2813              :             END IF
    2814           46 :          ELSE IF (cdft_control%type == outer_scf_hirshfeld_constraint) THEN
    2815           22 :             IF (ASSOCIATED(cdft_control%hirshfeld_control%hirshfeld_env%fnorm)) THEN
    2816            0 :                CALL auxbas_pw_pool%give_back_pw(cdft_control%hirshfeld_control%hirshfeld_env%fnorm)
    2817              :             END IF
    2818              :          END IF
    2819          170 :          IF (ASSOCIATED(cdft_control%charges_fragment)) DEALLOCATE (cdft_control%charges_fragment)
    2820          170 :          cdft_control%need_pot = .TRUE.
    2821          170 :          cdft_control%external_control = .FALSE.
    2822              :       END IF
    2823              : 
    2824          362 :       CALL timestop(handle)
    2825              : 
    2826          724 :    END SUBROUTINE cdft_scf
    2827              : 
    2828              : ! **************************************************************************************************
    2829              : !> \brief perform cleanup operations for cdft_control
    2830              : !> \param cdft_control container for the external CDFT SCF loop variables
    2831              : !> \par History
    2832              : !>      12.2015 created [Nico Holmberg]
    2833              : !> \author Nico Holmberg
    2834              : ! **************************************************************************************************
    2835          362 :    SUBROUTINE cdft_control_cleanup(cdft_control)
    2836              :       TYPE(cdft_control_type), POINTER                   :: cdft_control
    2837              : 
    2838          362 :       IF (ASSOCIATED(cdft_control%constraint%variables)) THEN
    2839          362 :          DEALLOCATE (cdft_control%constraint%variables)
    2840              :       END IF
    2841          362 :       IF (ASSOCIATED(cdft_control%constraint%count)) THEN
    2842          362 :          DEALLOCATE (cdft_control%constraint%count)
    2843              :       END IF
    2844          362 :       IF (ASSOCIATED(cdft_control%constraint%gradient)) THEN
    2845          362 :          DEALLOCATE (cdft_control%constraint%gradient)
    2846              :       END IF
    2847          362 :       IF (ASSOCIATED(cdft_control%constraint%energy)) THEN
    2848          362 :          DEALLOCATE (cdft_control%constraint%energy)
    2849              :       END IF
    2850          362 :       IF (ASSOCIATED(cdft_control%constraint%inv_jacobian) .AND. &
    2851              :           cdft_control%constraint%deallocate_jacobian) THEN
    2852            4 :          DEALLOCATE (cdft_control%constraint%inv_jacobian)
    2853              :       END IF
    2854              : 
    2855          362 :    END SUBROUTINE cdft_control_cleanup
    2856              : 
    2857              : ! **************************************************************************************************
    2858              : !> \brief Calculates the finite difference inverse Jacobian
    2859              : !> \param qs_env the qs_environment_type where to compute the Jacobian
    2860              : !> \par History
    2861              : !>      01.2017 created [Nico Holmberg]
    2862              : ! **************************************************************************************************
    2863          252 :    SUBROUTINE qs_calculate_inverse_jacobian(qs_env)
    2864              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    2865              : 
    2866              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'qs_calculate_inverse_jacobian'
    2867              : 
    2868              :       CHARACTER(len=default_path_length)                 :: project_name
    2869              :       INTEGER                                            :: counter, handle, i, ispin, iter_count, &
    2870              :                                                             iwork, j, max_scf, nspins, nsteps, &
    2871              :                                                             nvar, nwork, output_unit, pwork, &
    2872              :                                                             tsteps, twork
    2873              :       LOGICAL                                            :: converged, explicit_jacobian, &
    2874              :                                                             should_build, should_stop, &
    2875              :                                                             use_md_history
    2876              :       REAL(KIND=dp)                                      :: inv_error, step_size
    2877          252 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:)           :: coeff, dh, step_multiplier
    2878          252 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :)        :: jacobian
    2879          252 :       REAL(KIND=dp), DIMENSION(:), POINTER               :: energy
    2880          252 :       REAL(KIND=dp), DIMENSION(:, :), POINTER            :: gradient, inv_jacobian
    2881              :       TYPE(cdft_control_type), POINTER                   :: cdft_control
    2882              :       TYPE(cp_logger_type), POINTER                      :: logger, tmp_logger
    2883          252 :       TYPE(dbcsr_p_type), DIMENSION(:), POINTER          :: p_rmpv
    2884          252 :       TYPE(dbcsr_p_type), DIMENSION(:, :), POINTER       :: rho_ao_kp
    2885              :       TYPE(dft_control_type), POINTER                    :: dft_control
    2886          252 :       TYPE(mo_set_type), ALLOCATABLE, DIMENSION(:)       :: mos_stashed
    2887          252 :       TYPE(mo_set_type), DIMENSION(:), POINTER           :: mos
    2888              :       TYPE(mp_para_env_type), POINTER                    :: para_env
    2889              :       TYPE(qs_energy_type), POINTER                      :: energy_qs
    2890              :       TYPE(qs_ks_env_type), POINTER                      :: ks_env
    2891              :       TYPE(qs_rho_type), POINTER                         :: rho
    2892              :       TYPE(qs_scf_env_type), POINTER                     :: scf_env
    2893              :       TYPE(scf_control_type), POINTER                    :: scf_control
    2894              : 
    2895          252 :       NULLIFY (energy, gradient, p_rmpv, rho_ao_kp, mos, rho, &
    2896          252 :                ks_env, scf_env, scf_control, dft_control, cdft_control, &
    2897          252 :                inv_jacobian, para_env, tmp_logger, energy_qs)
    2898          504 :       logger => cp_get_default_logger()
    2899              : 
    2900          252 :       CPASSERT(ASSOCIATED(qs_env))
    2901              :       CALL get_qs_env(qs_env, scf_env=scf_env, ks_env=ks_env, &
    2902              :                       scf_control=scf_control, mos=mos, rho=rho, &
    2903              :                       dft_control=dft_control, &
    2904          252 :                       para_env=para_env, energy=energy_qs)
    2905          252 :       explicit_jacobian = .FALSE.
    2906          252 :       should_build = .FALSE.
    2907          252 :       use_md_history = .FALSE.
    2908          252 :       iter_count = scf_env%outer_scf%iter_count
    2909              :       ! Quick exit if optimizer does not require Jacobian
    2910          252 :       IF (.NOT. ASSOCIATED(scf_control%outer_scf%cdft_opt_control)) RETURN
    2911              :       ! Check if Jacobian should be calculated and initialize
    2912          134 :       CALL timeset(routineN, handle)
    2913          134 :       CALL initialize_inverse_jacobian(scf_control, scf_env, explicit_jacobian, should_build, used_history)
    2914          134 :       IF (scf_control%outer_scf%cdft_opt_control%jacobian_restart) THEN
    2915              :          ! Restart from previously calculated inverse Jacobian
    2916            6 :          should_build = .FALSE.
    2917            6 :          CALL restart_inverse_jacobian(qs_env)
    2918              :       END IF
    2919          134 :       IF (should_build) THEN
    2920           86 :          scf_env%outer_scf%deallocate_jacobian = .FALSE.
    2921              :          ! Actually need to (re)build the Jacobian
    2922           86 :          IF (explicit_jacobian) THEN
    2923              :             ! Build Jacobian with finite differences
    2924           66 :             cdft_control => dft_control%qs_control%cdft_control
    2925           66 :             IF (.NOT. ASSOCIATED(cdft_control)) THEN
    2926              :                CALL cp_abort(__LOCATION__, &
    2927              :                              "Optimizers that need the explicit Jacobian can"// &
    2928            0 :                              " only be used together with a valid CDFT constraint.")
    2929              :             END IF
    2930              :             ! Redirect output from Jacobian calculation to a new file by creating a temporary logger
    2931           66 :             project_name = logger%iter_info%project_name
    2932           66 :             CALL create_tmp_logger(para_env, project_name, "-JacobianInfo.out", output_unit, tmp_logger)
    2933              :             ! Save last converged state so we can roll back to it (mo_coeff and some outer_loop variables)
    2934           66 :             nspins = dft_control%nspins
    2935          330 :             ALLOCATE (mos_stashed(nspins))
    2936          198 :             DO ispin = 1, nspins
    2937          198 :                CALL duplicate_mo_set(mos_stashed(ispin), mos(ispin))
    2938              :             END DO
    2939           66 :             CALL qs_rho_get(rho, rho_ao_kp=rho_ao_kp)
    2940           66 :             p_rmpv => rho_ao_kp(:, 1)
    2941              :             ! Allocate work
    2942           66 :             nvar = SIZE(scf_env%outer_scf%variables, 1)
    2943           66 :             max_scf = scf_control%outer_scf%max_scf + 1
    2944          264 :             ALLOCATE (gradient(nvar, max_scf))
    2945         1410 :             gradient = scf_env%outer_scf%gradient
    2946          198 :             ALLOCATE (energy(max_scf))
    2947          630 :             energy = scf_env%outer_scf%energy
    2948          264 :             ALLOCATE (jacobian(nvar, nvar))
    2949           66 :             jacobian = 0.0_dp
    2950           66 :             nsteps = cdft_control%total_steps
    2951              :             ! Setup finite difference scheme
    2952           66 :             CALL prepare_jacobian_stencil(qs_env, output_unit, nwork, pwork, coeff, step_multiplier, dh)
    2953           66 :             twork = pwork - nwork
    2954          160 :             DO i = 1, nvar
    2955          310 :                jacobian(i, :) = coeff(0)*scf_env%outer_scf%gradient(i, iter_count)
    2956              :             END DO
    2957              :             ! Calculate the Jacobian by perturbing each Lagrangian and recalculating the energy self-consistently
    2958           66 :             CALL cp_add_default_logger(tmp_logger)
    2959          160 :             DO i = 1, nvar
    2960           94 :                IF (output_unit > 0) THEN
    2961           47 :                   WRITE (output_unit, FMT="(A)") " "
    2962           47 :                   WRITE (output_unit, FMT="(A)") " #####################################"
    2963              :                   WRITE (output_unit, '(A,I3,A,I3,A)') &
    2964           47 :                      " ###  Constraint        ", i, " of ", nvar, " ###"
    2965           47 :                   WRITE (output_unit, FMT="(A)") " #####################################"
    2966              :                END IF
    2967           94 :                counter = 0
    2968          360 :                DO iwork = nwork, pwork
    2969          200 :                   IF (iwork == 0) CYCLE
    2970          106 :                   counter = counter + 1
    2971          106 :                   IF (output_unit > 0) THEN
    2972           53 :                      WRITE (output_unit, FMT="(A)") " #####################################"
    2973              :                      WRITE (output_unit, '(A,I3,A,I3,A)') &
    2974           53 :                         " ###  Energy evaluation ", counter, " of ", twork, " ###"
    2975           53 :                      WRITE (output_unit, FMT="(A)") " #####################################"
    2976              :                   END IF
    2977          106 :                   IF (SIZE(scf_control%outer_scf%cdft_opt_control%jacobian_step) == 1) THEN
    2978           98 :                      step_size = scf_control%outer_scf%cdft_opt_control%jacobian_step(1)
    2979              :                   ELSE
    2980            8 :                      step_size = scf_control%outer_scf%cdft_opt_control%jacobian_step(i)
    2981              :                   END IF
    2982          268 :                   scf_env%outer_scf%variables(:, iter_count + 1) = scf_env%outer_scf%variables(:, iter_count)
    2983              :                   scf_env%outer_scf%variables(i, iter_count + 1) = scf_env%outer_scf%variables(i, iter_count) + &
    2984          106 :                                                                    step_multiplier(iwork)*step_size
    2985          106 :                   CALL outer_loop_update_qs_env(qs_env, scf_env)
    2986          106 :                   CALL qs_ks_did_change(ks_env, potential_changed=.TRUE.)
    2987          106 :                   CALL outer_loop_switch(scf_env, scf_control, cdft_control, cdft2ot)
    2988              :                   CALL scf_env_do_scf(scf_env=scf_env, scf_control=scf_control, qs_env=qs_env, &
    2989          106 :                                       converged=converged, should_stop=should_stop, total_scf_steps=tsteps)
    2990          106 :                   CALL outer_loop_switch(scf_env, scf_control, cdft_control, ot2cdft)
    2991              :                   ! Update (iter_count + 1) element of gradient and print constraint info
    2992          106 :                   scf_env%outer_scf%iter_count = scf_env%outer_scf%iter_count + 1
    2993          106 :                   CALL outer_loop_gradient(qs_env, scf_env)
    2994              :                   CALL qs_scf_cdft_info(output_unit, scf_control, scf_env, cdft_control, &
    2995              :                                         energy_qs, cdft_control%total_steps, &
    2996          106 :                                         should_stop=.FALSE., outer_loop_converged=.FALSE., cdft_loop=.FALSE.)
    2997          106 :                   scf_env%outer_scf%iter_count = scf_env%outer_scf%iter_count - 1
    2998              :                   ! Update Jacobian
    2999          268 :                   DO j = 1, nvar
    3000          268 :                      jacobian(j, i) = jacobian(j, i) + coeff(iwork)*scf_env%outer_scf%gradient(j, iter_count + 1)
    3001              :                   END DO
    3002              :                   ! Reset everything to last converged state
    3003          268 :                   scf_env%outer_scf%variables(:, iter_count + 1) = 0.0_dp
    3004         2226 :                   scf_env%outer_scf%gradient = gradient
    3005          950 :                   scf_env%outer_scf%energy = energy
    3006          106 :                   cdft_control%total_steps = nsteps
    3007          318 :                   DO ispin = 1, nspins
    3008          212 :                      CALL deallocate_mo_set(mos(ispin))
    3009          212 :                      CALL duplicate_mo_set(mos(ispin), mos_stashed(ispin))
    3010              :                      CALL calculate_density_matrix(mos(ispin), &
    3011          318 :                                                    p_rmpv(ispin)%matrix)
    3012              :                   END DO
    3013          106 :                   CALL qs_rho_update_rho(rho, qs_env=qs_env)
    3014          400 :                   CALL qs_ks_did_change(qs_env%ks_env, rho_changed=.TRUE.)
    3015              :                END DO
    3016              :             END DO
    3017           66 :             CALL cp_rm_default_logger()
    3018           66 :             CALL cp_logger_release(tmp_logger)
    3019              :             ! Finalize and invert Jacobian
    3020          160 :             DO j = 1, nvar
    3021          310 :                DO i = 1, nvar
    3022          244 :                   jacobian(i, j) = jacobian(i, j)/dh(j)
    3023              :                END DO
    3024              :             END DO
    3025           66 :             IF (.NOT. ASSOCIATED(scf_env%outer_scf%inv_jacobian)) THEN
    3026          102 :                ALLOCATE (scf_env%outer_scf%inv_jacobian(nvar, nvar))
    3027              :             END IF
    3028           66 :             inv_jacobian => scf_env%outer_scf%inv_jacobian
    3029           66 :             CALL invert_matrix(jacobian, inv_jacobian, inv_error)
    3030           66 :             scf_control%outer_scf%cdft_opt_control%broyden_update = .FALSE.
    3031              :             ! Release temporary storage
    3032          198 :             DO ispin = 1, nspins
    3033          198 :                CALL deallocate_mo_set(mos_stashed(ispin))
    3034              :             END DO
    3035           66 :             DEALLOCATE (mos_stashed, jacobian, gradient, energy, coeff, step_multiplier, dh)
    3036          198 :             IF (output_unit > 0) THEN
    3037              :                WRITE (output_unit, FMT="(/,A)") &
    3038           33 :                   " ================================== JACOBIAN CALCULATED =================================="
    3039           33 :                CALL close_file(unit_number=output_unit)
    3040              :             END IF
    3041              :          ELSE
    3042              :             ! Build a strictly diagonal Jacobian from history and invert it
    3043           20 :             CALL build_diagonal_jacobian(qs_env, used_history)
    3044              :          END IF
    3045              :       END IF
    3046          134 :       IF (ASSOCIATED(scf_env%outer_scf%inv_jacobian) .AND. para_env%is_source()) THEN
    3047              :          ! Write restart file for inverse Jacobian
    3048           62 :          CALL print_inverse_jacobian(logger, scf_env%outer_scf%inv_jacobian, iter_count)
    3049              :       END IF
    3050              :       ! Update counter
    3051          134 :       scf_control%outer_scf%cdft_opt_control%ijacobian(1) = scf_control%outer_scf%cdft_opt_control%ijacobian(1) + 1
    3052          134 :       CALL timestop(handle)
    3053              : 
    3054          504 :    END SUBROUTINE qs_calculate_inverse_jacobian
    3055              : 
    3056              : ! **************************************************************************************************
    3057              : !> \brief Perform backtracking line search to find the optimal step size for the CDFT constraint
    3058              : !>        optimizer. Assumes that the CDFT gradient function is a smooth function of the constraint
    3059              : !>        variables.
    3060              : !> \param qs_env the qs_environment_type where to perform the line search
    3061              : !> \par History
    3062              : !>      02.2017 created [Nico Holmberg]
    3063              : ! **************************************************************************************************
    3064          252 :    SUBROUTINE qs_cdft_line_search(qs_env)
    3065              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    3066              : 
    3067              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'qs_cdft_line_search'
    3068              : 
    3069              :       CHARACTER(len=default_path_length)                 :: project_name
    3070              :       INTEGER                                            :: handle, i, ispin, iter_count, &
    3071              :                                                             max_linesearch, max_scf, nspins, &
    3072              :                                                             nsteps, nvar, output_unit, tsteps
    3073              :       LOGICAL :: continue_ls, continue_ls_exit, converged, do_linesearch, found_solution, &
    3074              :          reached_maxls, should_exit, should_stop, sign_changed
    3075          252 :       LOGICAL, ALLOCATABLE, DIMENSION(:)                 :: positive_sign
    3076              :       REAL(KIND=dp)                                      :: alpha, alpha_ls, factor, norm_ls
    3077          252 :       REAL(KIND=dp), DIMENSION(:), POINTER               :: energy
    3078          252 :       REAL(KIND=dp), DIMENSION(:, :), POINTER            :: gradient, inv_jacobian
    3079              :       REAL(KIND=dp), EXTERNAL                            :: dnrm2
    3080              :       TYPE(cdft_control_type), POINTER                   :: cdft_control
    3081              :       TYPE(cp_logger_type), POINTER                      :: logger, tmp_logger
    3082          252 :       TYPE(dbcsr_p_type), DIMENSION(:), POINTER          :: p_rmpv
    3083          252 :       TYPE(dbcsr_p_type), DIMENSION(:, :), POINTER       :: rho_ao_kp
    3084              :       TYPE(dft_control_type), POINTER                    :: dft_control
    3085          252 :       TYPE(mo_set_type), DIMENSION(:), POINTER           :: mos
    3086              :       TYPE(mp_para_env_type), POINTER                    :: para_env
    3087              :       TYPE(qs_energy_type), POINTER                      :: energy_qs
    3088              :       TYPE(qs_ks_env_type), POINTER                      :: ks_env
    3089              :       TYPE(qs_rho_type), POINTER                         :: rho
    3090              :       TYPE(qs_scf_env_type), POINTER                     :: scf_env
    3091              :       TYPE(scf_control_type), POINTER                    :: scf_control
    3092              : 
    3093          252 :       CALL timeset(routineN, handle)
    3094              : 
    3095          252 :       NULLIFY (energy, gradient, p_rmpv, rho_ao_kp, mos, rho, &
    3096          252 :                ks_env, scf_env, scf_control, dft_control, &
    3097          252 :                cdft_control, inv_jacobian, para_env, &
    3098          252 :                tmp_logger, energy_qs)
    3099          252 :       logger => cp_get_default_logger()
    3100              : 
    3101          252 :       CPASSERT(ASSOCIATED(qs_env))
    3102              :       CALL get_qs_env(qs_env, scf_env=scf_env, ks_env=ks_env, &
    3103              :                       scf_control=scf_control, mos=mos, rho=rho, &
    3104              :                       dft_control=dft_control, &
    3105          252 :                       para_env=para_env, energy=energy_qs)
    3106          252 :       do_linesearch = .FALSE.
    3107          252 :       SELECT CASE (scf_control%outer_scf%optimizer)
    3108              :       CASE DEFAULT
    3109              :          do_linesearch = .FALSE.
    3110              :       CASE (outer_scf_optimizer_newton_ls)
    3111           32 :          do_linesearch = .TRUE.
    3112              :       CASE (outer_scf_optimizer_broyden)
    3113          252 :          SELECT CASE (scf_control%outer_scf%cdft_opt_control%broyden_type)
    3114              :          CASE (broyden_type_1, broyden_type_2, broyden_type_1_explicit, broyden_type_2_explicit)
    3115            0 :             do_linesearch = .FALSE.
    3116              :          CASE (broyden_type_1_ls, broyden_type_1_explicit_ls, broyden_type_2_ls, broyden_type_2_explicit_ls)
    3117            0 :             cdft_control => dft_control%qs_control%cdft_control
    3118            0 :             IF (.NOT. ASSOCIATED(cdft_control)) THEN
    3119              :                CALL cp_abort(__LOCATION__, &
    3120              :                              "Optimizers that perform a line search can"// &
    3121            0 :                              " only be used together with a valid CDFT constraint")
    3122              :             END IF
    3123           32 :             IF (ASSOCIATED(scf_env%outer_scf%inv_jacobian)) THEN
    3124              :                do_linesearch = .TRUE.
    3125              :             END IF
    3126              :          END SELECT
    3127              :       END SELECT
    3128              :       IF (do_linesearch) THEN
    3129            8 :          BLOCK
    3130            8 :             TYPE(mo_set_type), DIMENSION(:), ALLOCATABLE :: mos_ls, mos_stashed
    3131            8 :             cdft_control => dft_control%qs_control%cdft_control
    3132            8 :             IF (.NOT. ASSOCIATED(cdft_control)) THEN
    3133              :                CALL cp_abort(__LOCATION__, &
    3134              :                              "Optimizers that perform a line search can"// &
    3135            0 :                              " only be used together with a valid CDFT constraint")
    3136              :             END IF
    3137            8 :             CPASSERT(ASSOCIATED(scf_env%outer_scf%inv_jacobian))
    3138            8 :             CPASSERT(ASSOCIATED(scf_control%outer_scf%cdft_opt_control))
    3139            8 :             alpha = scf_control%outer_scf%cdft_opt_control%newton_step_save
    3140            8 :             iter_count = scf_env%outer_scf%iter_count
    3141              :             ! Redirect output from line search procedure to a new file by creating a temporary logger
    3142            8 :             project_name = logger%iter_info%project_name
    3143            8 :             CALL create_tmp_logger(para_env, project_name, "-LineSearch.out", output_unit, tmp_logger)
    3144              :             ! Save last converged state so we can roll back to it (mo_coeff and some outer_loop variables)
    3145            8 :             nspins = dft_control%nspins
    3146           40 :             ALLOCATE (mos_stashed(nspins))
    3147           24 :             DO ispin = 1, nspins
    3148           24 :                CALL duplicate_mo_set(mos_stashed(ispin), mos(ispin))
    3149              :             END DO
    3150            8 :             CALL qs_rho_get(rho, rho_ao_kp=rho_ao_kp)
    3151            8 :             p_rmpv => rho_ao_kp(:, 1)
    3152            8 :             nsteps = cdft_control%total_steps
    3153              :             ! Allocate work
    3154            8 :             nvar = SIZE(scf_env%outer_scf%variables, 1)
    3155            8 :             max_scf = scf_control%outer_scf%max_scf + 1
    3156            8 :             max_linesearch = scf_control%outer_scf%cdft_opt_control%max_ls
    3157            8 :             continue_ls = scf_control%outer_scf%cdft_opt_control%continue_ls
    3158            8 :             factor = scf_control%outer_scf%cdft_opt_control%factor_ls
    3159            8 :             continue_ls_exit = .FALSE.
    3160            8 :             found_solution = .FALSE.
    3161           32 :             ALLOCATE (gradient(nvar, max_scf))
    3162          104 :             gradient = scf_env%outer_scf%gradient
    3163           24 :             ALLOCATE (energy(max_scf))
    3164           56 :             energy = scf_env%outer_scf%energy
    3165            8 :             reached_maxls = .FALSE.
    3166              :             ! Broyden optimizers: perform update of inv_jacobian if necessary
    3167            8 :             IF (scf_control%outer_scf%cdft_opt_control%broyden_update) THEN
    3168            0 :                CALL outer_loop_optimize(scf_env, scf_control)
    3169              :                ! Reset the variables and prevent a reupdate of inv_jacobian
    3170            0 :                scf_env%outer_scf%variables(:, iter_count + 1) = 0
    3171            0 :                scf_control%outer_scf%cdft_opt_control%broyden_update = .FALSE.
    3172              :             END IF
    3173              :             ! Print some info
    3174            8 :             IF (output_unit > 0) THEN
    3175              :                WRITE (output_unit, FMT="(/,A)") &
    3176            4 :                   " ================================== LINE SEARCH STARTED  =================================="
    3177              :                WRITE (output_unit, FMT="(A,I5,A)") &
    3178            4 :                   " Evaluating optimal step size for optimizer using a maximum of", max_linesearch, " steps"
    3179            4 :                IF (continue_ls) THEN
    3180              :                   WRITE (output_unit, FMT="(A)") &
    3181            2 :                      " Line search continues until best step size is found or max steps are reached"
    3182              :                END IF
    3183              :                WRITE (output_unit, '(/,A,F5.3)') &
    3184            4 :                   " Initial step size: ", alpha
    3185              :                WRITE (output_unit, '(/,A,F5.3)') &
    3186            4 :                   " Step size update factor: ", factor
    3187              :                WRITE (output_unit, '(/,A,I10,A,I10)') &
    3188            4 :                   " Energy evaluation: ", cdft_control%ienergy, ", CDFT SCF iteration: ", iter_count
    3189              :             END IF
    3190              :             ! Perform backtracking line search
    3191            8 :             CALL cp_add_default_logger(tmp_logger)
    3192           16 :             DO i = 1, max_linesearch
    3193           16 :                IF (output_unit > 0) THEN
    3194            8 :                   WRITE (output_unit, FMT="(A)") " "
    3195            8 :                   WRITE (output_unit, FMT="(A)") " #####################################"
    3196              :                   WRITE (output_unit, '(A,I10,A)') &
    3197            8 :                      " ###  Line search step: ", i, " ###"
    3198            8 :                   WRITE (output_unit, FMT="(A)") " #####################################"
    3199              :                END IF
    3200           16 :                inv_jacobian => scf_env%outer_scf%inv_jacobian
    3201              :                ! Newton update of CDFT variables with a step size of alpha
    3202              :                scf_env%outer_scf%variables(:, iter_count + 1) = scf_env%outer_scf%variables(:, iter_count) - alpha* &
    3203          128 :                                                                 MATMUL(inv_jacobian, scf_env%outer_scf%gradient(:, iter_count))
    3204              :                ! With updated CDFT variables, perform SCF
    3205           16 :                CALL outer_loop_update_qs_env(qs_env, scf_env)
    3206           16 :                CALL qs_ks_did_change(ks_env, potential_changed=.TRUE.)
    3207           16 :                CALL outer_loop_switch(scf_env, scf_control, cdft_control, cdft2ot)
    3208              :                CALL scf_env_do_scf(scf_env=scf_env, scf_control=scf_control, qs_env=qs_env, &
    3209           16 :                                    converged=converged, should_stop=should_stop, total_scf_steps=tsteps)
    3210           16 :                CALL outer_loop_switch(scf_env, scf_control, cdft_control, ot2cdft)
    3211              :                ! Update (iter_count + 1) element of gradient and print constraint info
    3212           16 :                scf_env%outer_scf%iter_count = scf_env%outer_scf%iter_count + 1
    3213           16 :                CALL outer_loop_gradient(qs_env, scf_env)
    3214              :                CALL qs_scf_cdft_info(output_unit, scf_control, scf_env, cdft_control, &
    3215              :                                      energy_qs, cdft_control%total_steps, &
    3216           16 :                                      should_stop=.FALSE., outer_loop_converged=.FALSE., cdft_loop=.FALSE.)
    3217           16 :                scf_env%outer_scf%iter_count = scf_env%outer_scf%iter_count - 1
    3218              :                ! Store sign of initial gradient for each variable for continue_ls
    3219           16 :                IF (continue_ls .AND. .NOT. ALLOCATED(positive_sign)) THEN
    3220           12 :                   ALLOCATE (positive_sign(nvar))
    3221            8 :                   DO ispin = 1, nvar
    3222            8 :                      positive_sign(ispin) = scf_env%outer_scf%gradient(ispin, iter_count + 1) >= 0.0_dp
    3223              :                   END DO
    3224              :                END IF
    3225              :                ! Check if the L2 norm of the gradient decreased
    3226           16 :                inv_jacobian => scf_env%outer_scf%inv_jacobian
    3227           16 :                IF (dnrm2(nvar, scf_env%outer_scf%gradient(:, iter_count + 1), 1) < &
    3228              :                    dnrm2(nvar, scf_env%outer_scf%gradient(:, iter_count), 1)) THEN
    3229              :                   ! Optimal step size found
    3230           14 :                   IF (.NOT. continue_ls) THEN
    3231              :                      should_exit = .TRUE.
    3232              :                   ELSE
    3233              :                      ! But line search continues for at least one more iteration in an attempt to find a better solution
    3234              :                      ! if max number of steps is not exceeded
    3235           10 :                      IF (found_solution) THEN
    3236              :                         ! Check if the norm also decreased w.r.t. to previously found solution
    3237            6 :                         IF (dnrm2(nvar, scf_env%outer_scf%gradient(:, iter_count + 1), 1) > norm_ls) THEN
    3238              :                            ! Norm increased => accept previous solution and exit
    3239              :                            continue_ls_exit = .TRUE.
    3240              :                         END IF
    3241              :                      END IF
    3242              :                      ! Store current state and the value of alpha
    3243           10 :                      IF (.NOT. continue_ls_exit) THEN
    3244           10 :                         should_exit = .FALSE.
    3245           10 :                         alpha_ls = alpha
    3246           10 :                         found_solution = .TRUE.
    3247           10 :                         norm_ls = dnrm2(nvar, scf_env%outer_scf%gradient(:, iter_count + 1), 1)
    3248              :                         ! Check if the sign of the gradient has changed for all variables (w.r.t initial gradient)
    3249              :                         ! In this case we should exit because further line search steps will just increase the norm
    3250           10 :                         sign_changed = .TRUE.
    3251           20 :                         DO ispin = 1, nvar
    3252              :                            sign_changed = sign_changed .AND. (positive_sign(ispin) .NEQV. &
    3253           28 :                                                               scf_env%outer_scf%gradient(ispin, iter_count + 1) >= 0.0_dp)
    3254              :                         END DO
    3255           10 :                         IF (.NOT. ALLOCATED(mos_ls)) THEN
    3256           16 :                            ALLOCATE (mos_ls(nspins))
    3257              :                         ELSE
    3258           18 :                            DO ispin = 1, nspins
    3259           18 :                               CALL deallocate_mo_set(mos_ls(ispin))
    3260              :                            END DO
    3261              :                         END IF
    3262           30 :                         DO ispin = 1, nspins
    3263           30 :                            CALL duplicate_mo_set(mos_ls(ispin), mos(ispin))
    3264              :                         END DO
    3265           10 :                         alpha = alpha*factor
    3266              :                         ! Exit on last iteration
    3267           10 :                         IF (i == max_linesearch) continue_ls_exit = .TRUE.
    3268              :                         ! Exit if constraint target is satisfied to requested tolerance
    3269           20 :                         IF (SQRT(MAXVAL(scf_env%outer_scf%gradient(:, scf_env%outer_scf%iter_count + 1)**2)) < &
    3270              :                             scf_control%outer_scf%eps_scf) THEN
    3271            2 :                            continue_ls_exit = .TRUE.
    3272              :                         END IF
    3273              :                         ! Exit if line search jumped over the optimal step length
    3274           10 :                         IF (sign_changed) continue_ls_exit = .TRUE.
    3275              :                      END IF
    3276              :                   END IF
    3277              :                ELSE
    3278              :                   ! Gradient increased => alpha is too large (if the gradient function is smooth)
    3279            2 :                   should_exit = .FALSE.
    3280              :                   ! Update alpha using Armijo's scheme
    3281            2 :                   alpha = alpha*factor
    3282              :                END IF
    3283           14 :                IF (continue_ls_exit) THEN
    3284              :                   ! Continuation of line search did not yield a better alpha, use previously located solution and exit
    3285            4 :                   alpha = alpha_ls
    3286           12 :                   DO ispin = 1, nspins
    3287            8 :                      CALL deallocate_mo_set(mos(ispin))
    3288            8 :                      CALL duplicate_mo_set(mos(ispin), mos_ls(ispin))
    3289              :                      CALL calculate_density_matrix(mos(ispin), &
    3290            8 :                                                    p_rmpv(ispin)%matrix)
    3291           12 :                      CALL deallocate_mo_set(mos_ls(ispin))
    3292              :                   END DO
    3293            4 :                   CALL qs_rho_update_rho(rho, qs_env=qs_env)
    3294            4 :                   CALL qs_ks_did_change(qs_env%ks_env, rho_changed=.TRUE.)
    3295            4 :                   DEALLOCATE (mos_ls)
    3296              :                   should_exit = .TRUE.
    3297              :                END IF
    3298              :                ! Reached max steps and SCF converged: continue with last iterated step size
    3299           12 :                IF (.NOT. should_exit .AND. &
    3300              :                    (i == max_linesearch .AND. converged .AND. .NOT. found_solution)) THEN
    3301            0 :                   should_exit = .TRUE.
    3302            0 :                   reached_maxls = .TRUE.
    3303            0 :                   alpha = alpha*(1.0_dp/factor)
    3304              :                END IF
    3305              :                ! Reset outer SCF environment to last converged state
    3306           32 :                scf_env%outer_scf%variables(:, iter_count + 1) = 0.0_dp
    3307          208 :                scf_env%outer_scf%gradient = gradient
    3308          112 :                scf_env%outer_scf%energy = energy
    3309              :                ! Exit line search if a suitable step size was found
    3310           16 :                IF (should_exit) EXIT
    3311              :                ! Reset the electronic structure
    3312            8 :                cdft_control%total_steps = nsteps
    3313           24 :                DO ispin = 1, nspins
    3314           16 :                   CALL deallocate_mo_set(mos(ispin))
    3315           16 :                   CALL duplicate_mo_set(mos(ispin), mos_stashed(ispin))
    3316              :                   CALL calculate_density_matrix(mos(ispin), &
    3317           24 :                                                 p_rmpv(ispin)%matrix)
    3318              :                END DO
    3319            8 :                CALL qs_rho_update_rho(rho, qs_env=qs_env)
    3320           24 :                CALL qs_ks_did_change(qs_env%ks_env, rho_changed=.TRUE.)
    3321              :             END DO
    3322            8 :             scf_control%outer_scf%cdft_opt_control%newton_step = alpha
    3323            8 :             IF (.NOT. should_exit) THEN
    3324              :                CALL cp_warn(__LOCATION__, &
    3325            0 :                             "Line search did not converge. CDFT SCF proceeds with fixed step size.")
    3326            0 :                scf_control%outer_scf%cdft_opt_control%newton_step = scf_control%outer_scf%cdft_opt_control%newton_step_save
    3327              :             END IF
    3328            8 :             IF (reached_maxls) THEN
    3329              :                CALL cp_warn(__LOCATION__, &
    3330            0 :                             "Line search did not converge. CDFT SCF proceeds with lasted iterated step size.")
    3331              :             END IF
    3332            8 :             CALL cp_rm_default_logger()
    3333            8 :             CALL cp_logger_release(tmp_logger)
    3334              :             ! Release temporary storage
    3335           24 :             DO ispin = 1, nspins
    3336           24 :                CALL deallocate_mo_set(mos_stashed(ispin))
    3337              :             END DO
    3338            8 :             DEALLOCATE (mos_stashed, gradient, energy)
    3339            8 :             IF (ALLOCATED(positive_sign)) DEALLOCATE (positive_sign)
    3340           20 :             IF (output_unit > 0) THEN
    3341              :                WRITE (output_unit, FMT="(/,A)") &
    3342            4 :                   " ================================== LINE SEARCH COMPLETE =================================="
    3343            4 :                CALL close_file(unit_number=output_unit)
    3344              :             END IF
    3345              :          END BLOCK
    3346              :       END IF
    3347              : 
    3348          252 :       CALL timestop(handle)
    3349              : 
    3350          252 :    END SUBROUTINE qs_cdft_line_search
    3351              : 
    3352              : ! **************************************************************************************************
    3353              : !> \brief Rebuild the native xTB total energy from its components using the current
    3354              : !>        electronic entropy. The SCF matrix construction sees the entropy from the
    3355              : !>        previous iteration (or zero on the first/only one), so recompute it here
    3356              : !>        before the energy is reported or used.
    3357              : !> \param energy ...
    3358              : !> \param dft_control ...
    3359              : ! **************************************************************************************************
    3360       242595 :    SUBROUTINE rebuild_xtb_total_energy(energy, dft_control)
    3361              :       TYPE(qs_energy_type), POINTER                      :: energy
    3362              :       TYPE(dft_control_type), POINTER                    :: dft_control
    3363              : 
    3364       242595 :       IF (.NOT. dft_control%qs_control%xtb) RETURN
    3365        56340 :       IF (dft_control%qs_control%xtb_control%do_tblite) RETURN
    3366              : 
    3367        30720 :       SELECT CASE (dft_control%qs_control%xtb_control%gfn_type)
    3368              :       CASE (0)
    3369              :          energy%total = energy%core + energy%eeq + energy%efield + energy%qmmm_el + &
    3370            0 :                         energy%repulsive + energy%dispersion + energy%kTS
    3371              :       CASE (1)
    3372              :          energy%total = energy%core + energy%repulsive + energy%hartree + &
    3373              :                         energy%xtb_spinpol + energy%efield + energy%qmmm_el + &
    3374        30720 :                         energy%dispersion + energy%dftb3 + energy%kTS
    3375              :       END SELECT
    3376              : 
    3377              :    END SUBROUTINE rebuild_xtb_total_energy
    3378              : 
    3379           16 : END MODULE qs_scf
        

Generated by: LCOV version 2.0-1