LCOV - code coverage report
Current view: top level - src - qs_scf.F (source / functions) Hit Total Coverage
Test: CP2K Regtests (git:e5b1968) Lines: 677 742 91.2 %
Date: 2025-06-05 07:00:53 Functions: 8 8 100.0 %

          Line data    Source code
       1             : !--------------------------------------------------------------------------------------------------!
       2             : !   CP2K: A general program to perform molecular dynamics simulations                              !
       3             : !   Copyright 2000-2025 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 cp_control_types,                ONLY: dft_control_type
      50             :    USE cp_dbcsr_api,                    ONLY: dbcsr_copy,&
      51             :                                               dbcsr_deallocate_matrix,&
      52             :                                               dbcsr_get_info,&
      53             :                                               dbcsr_init_p,&
      54             :                                               dbcsr_p_type,&
      55             :                                               dbcsr_set,&
      56             :                                               dbcsr_type
      57             :    USE cp_dbcsr_operations,             ONLY: copy_dbcsr_to_fm,&
      58             :                                               dbcsr_deallocate_matrix_set
      59             :    USE cp_files,                        ONLY: close_file
      60             :    USE cp_fm_types,                     ONLY: cp_fm_create,&
      61             :                                               cp_fm_release,&
      62             :                                               cp_fm_to_fm,&
      63             :                                               cp_fm_type
      64             :    USE cp_log_handling,                 ONLY: cp_add_default_logger,&
      65             :                                               cp_get_default_logger,&
      66             :                                               cp_logger_release,&
      67             :                                               cp_logger_type,&
      68             :                                               cp_rm_default_logger,&
      69             :                                               cp_to_string
      70             :    USE cp_output_handling,              ONLY: cp_add_iter_level,&
      71             :                                               cp_iterate,&
      72             :                                               cp_p_file,&
      73             :                                               cp_print_key_should_output,&
      74             :                                               cp_print_key_unit_nr,&
      75             :                                               cp_rm_iter_level
      76             :    USE cp_result_methods,               ONLY: get_results,&
      77             :                                               test_for_result
      78             :    USE cp_result_types,                 ONLY: cp_result_type
      79             :    USE ec_env_types,                    ONLY: energy_correction_type
      80             :    USE input_constants,                 ONLY: &
      81             :         broyden_type_1, broyden_type_1_explicit, broyden_type_1_explicit_ls, broyden_type_1_ls, &
      82             :         broyden_type_2, broyden_type_2_explicit, broyden_type_2_explicit_ls, broyden_type_2_ls, &
      83             :         cdft2ot, history_guess, ot2cdft, ot_precond_full_all, ot_precond_full_single, &
      84             :         ot_precond_full_single_inverse, ot_precond_none, ot_precond_s_inverse, &
      85             :         outer_scf_becke_constraint, outer_scf_hirshfeld_constraint, outer_scf_optimizer_broyden, &
      86             :         outer_scf_optimizer_newton_ls
      87             :    USE input_section_types,             ONLY: section_vals_get_subs_vals,&
      88             :                                               section_vals_type
      89             :    USE kinds,                           ONLY: default_path_length,&
      90             :                                               default_string_length,&
      91             :                                               dp
      92             :    USE kpoint_io,                       ONLY: write_kpoints_restart
      93             :    USE kpoint_types,                    ONLY: kpoint_type
      94             :    USE machine,                         ONLY: m_flush,&
      95             :                                               m_walltime
      96             :    USE mathlib,                         ONLY: invert_matrix
      97             :    USE message_passing,                 ONLY: mp_comm_type,&
      98             :                                               mp_para_env_type
      99             :    USE particle_types,                  ONLY: particle_type
     100             :    USE preconditioner,                  ONLY: prepare_preconditioner,&
     101             :                                               restart_preconditioner
     102             :    USE pw_env_types,                    ONLY: pw_env_get,&
     103             :                                               pw_env_type
     104             :    USE pw_pool_types,                   ONLY: pw_pool_type
     105             :    USE qs_block_davidson_types,         ONLY: block_davidson_deallocate
     106             :    USE qs_cdft_scf_utils,               ONLY: build_diagonal_jacobian,&
     107             :                                               create_tmp_logger,&
     108             :                                               initialize_inverse_jacobian,&
     109             :                                               prepare_jacobian_stencil,&
     110             :                                               print_inverse_jacobian,&
     111             :                                               restart_inverse_jacobian
     112             :    USE qs_cdft_types,                   ONLY: cdft_control_type
     113             :    USE qs_charges_types,                ONLY: qs_charges_type
     114             :    USE qs_density_matrices,             ONLY: calculate_density_matrix
     115             :    USE qs_density_mixing_types,         ONLY: gspace_mixing_nr
     116             :    USE qs_diis,                         ONLY: qs_diis_b_clear,&
     117             :                                               qs_diis_b_clear_kp,&
     118             :                                               qs_diis_b_create,&
     119             :                                               qs_diis_b_create_kp
     120             :    USE qs_energy_types,                 ONLY: qs_energy_type
     121             :    USE qs_environment_types,            ONLY: get_qs_env,&
     122             :                                               qs_environment_type,&
     123             :                                               set_qs_env
     124             :    USE qs_integrate_potential,          ONLY: integrate_v_rspace
     125             :    USE qs_kind_types,                   ONLY: qs_kind_type
     126             :    USE qs_ks_methods,                   ONLY: evaluate_core_matrix_p_mix_new,&
     127             :                                               qs_ks_update_qs_env
     128             :    USE qs_ks_types,                     ONLY: qs_ks_did_change,&
     129             :                                               qs_ks_env_type
     130             :    USE qs_mo_io,                        ONLY: write_mo_set_to_restart
     131             :    USE qs_mo_methods,                   ONLY: make_basis_simple,&
     132             :                                               make_basis_sm
     133             :    USE qs_mo_occupation,                ONLY: set_mo_occupation
     134             :    USE qs_mo_types,                     ONLY: deallocate_mo_set,&
     135             :                                               duplicate_mo_set,&
     136             :                                               get_mo_set,&
     137             :                                               mo_set_type,&
     138             :                                               reassign_allocated_mos
     139             :    USE qs_ot,                           ONLY: qs_ot_new_preconditioner
     140             :    USE qs_ot_scf,                       ONLY: ot_scf_init,&
     141             :                                               ot_scf_read_input
     142             :    USE qs_outer_scf,                    ONLY: outer_loop_gradient,&
     143             :                                               outer_loop_optimize,&
     144             :                                               outer_loop_purge_history,&
     145             :                                               outer_loop_switch,&
     146             :                                               outer_loop_update_qs_env
     147             :    USE qs_rho_methods,                  ONLY: qs_rho_update_rho
     148             :    USE qs_rho_types,                    ONLY: qs_rho_get,&
     149             :                                               qs_rho_type
     150             :    USE qs_scf_initialization,           ONLY: qs_scf_env_initialize
     151             :    USE qs_scf_loop_utils,               ONLY: qs_scf_check_inner_exit,&
     152             :                                               qs_scf_check_outer_exit,&
     153             :                                               qs_scf_density_mixing,&
     154             :                                               qs_scf_inner_finalize,&
     155             :                                               qs_scf_new_mos,&
     156             :                                               qs_scf_new_mos_kp,&
     157             :                                               qs_scf_rho_update,&
     158             :                                               qs_scf_set_loop_flags
     159             :    USE qs_scf_output,                   ONLY: qs_scf_cdft_info,&
     160             :                                               qs_scf_cdft_initial_info,&
     161             :                                               qs_scf_loop_info,&
     162             :                                               qs_scf_loop_print,&
     163             :                                               qs_scf_outer_loop_info,&
     164             :                                               qs_scf_write_mos
     165             :    USE qs_scf_post_scf,                 ONLY: qs_scf_compute_properties
     166             :    USE qs_scf_types,                    ONLY: &
     167             :         block_davidson_diag_method_nr, block_krylov_diag_method_nr, filter_matrix_diag_method_nr, &
     168             :         general_diag_method_nr, ot_diag_method_nr, ot_method_nr, qs_scf_env_type, &
     169             :         smeagol_method_nr, special_diag_method_nr
     170             :    USE qs_wf_history_methods,           ONLY: wfi_purge_history,&
     171             :                                               wfi_update
     172             :    USE scf_control_types,               ONLY: scf_control_type
     173             :    USE smeagol_interface,               ONLY: run_smeagol_bulktrans,&
     174             :                                               run_smeagol_emtrans
     175             :    USE tblite_interface,                ONLY: tb_get_energy,&
     176             :                                               tb_update_charges
     177             : #include "./base/base_uses.f90"
     178             : 
     179             :    IMPLICIT NONE
     180             : 
     181             :    PRIVATE
     182             : 
     183             :    CHARACTER(len=*), PARAMETER, PRIVATE :: moduleN = 'qs_scf'
     184             :    LOGICAL, PRIVATE                     :: reuse_precond = .FALSE.
     185             :    LOGICAL, PRIVATE                     :: used_history = .FALSE.
     186             : 
     187             :    PUBLIC :: scf, scf_env_cleanup, scf_env_do_scf, cdft_scf, init_scf_loop
     188             : 
     189             : CONTAINS
     190             : 
     191             : ! **************************************************************************************************
     192             : !> \brief perform an scf procedure in the given qs_env
     193             : !> \param qs_env the qs_environment where to perform the scf procedure
     194             : !> \param has_converged ...
     195             : !> \param total_scf_steps ...
     196             : !> \par History
     197             : !>      02.2003 introduced scf_env, moved real work to scf_env_do_scf [fawzi]
     198             : !> \author fawzi
     199             : !> \note
     200             : ! **************************************************************************************************
     201       17947 :    SUBROUTINE scf(qs_env, has_converged, total_scf_steps)
     202             :       TYPE(qs_environment_type), POINTER                 :: qs_env
     203             :       LOGICAL, INTENT(OUT), OPTIONAL                     :: has_converged
     204             :       INTEGER, INTENT(OUT), OPTIONAL                     :: total_scf_steps
     205             : 
     206             :       INTEGER                                            :: ihistory, max_scf_tmp, tsteps
     207             :       LOGICAL                                            :: converged, outer_scf_loop, should_stop
     208             :       LOGICAL, SAVE                                      :: first_step_flag = .TRUE.
     209       17947 :       REAL(KIND=dp), DIMENSION(:, :), POINTER            :: gradient_history, variable_history
     210             :       TYPE(cp_logger_type), POINTER                      :: logger
     211             :       TYPE(dft_control_type), POINTER                    :: dft_control
     212             :       TYPE(qs_scf_env_type), POINTER                     :: scf_env
     213             :       TYPE(scf_control_type), POINTER                    :: scf_control
     214             :       TYPE(section_vals_type), POINTER                   :: dft_section, input, scf_section
     215             : 
     216       17947 :       NULLIFY (scf_env)
     217       17947 :       logger => cp_get_default_logger()
     218       17947 :       CPASSERT(ASSOCIATED(qs_env))
     219       17947 :       IF (PRESENT(has_converged)) THEN
     220           0 :          has_converged = .FALSE.
     221             :       END IF
     222       17947 :       IF (PRESENT(total_scf_steps)) THEN
     223           0 :          total_scf_steps = 0
     224             :       END IF
     225             :       CALL get_qs_env(qs_env, scf_env=scf_env, input=input, &
     226       17947 :                       dft_control=dft_control, scf_control=scf_control)
     227       17947 :       IF (scf_control%max_scf > 0) THEN
     228             : 
     229       17305 :          dft_section => section_vals_get_subs_vals(input, "DFT")
     230       17305 :          scf_section => section_vals_get_subs_vals(dft_section, "SCF")
     231             : 
     232       17305 :          IF (.NOT. ASSOCIATED(scf_env)) THEN
     233        5435 :             CALL qs_scf_env_initialize(qs_env, scf_env)
     234             :             ! Moved here from qs_scf_env_initialize to be able to have more scf_env
     235        5435 :             CALL set_qs_env(qs_env, scf_env=scf_env)
     236             :          ELSE
     237       11870 :             CALL qs_scf_env_initialize(qs_env, scf_env)
     238             :          END IF
     239             : 
     240       17305 :          IF ((scf_control%density_guess .EQ. history_guess) .AND. (first_step_flag)) THEN
     241           2 :             max_scf_tmp = scf_control%max_scf
     242           2 :             scf_control%max_scf = 1
     243           2 :             outer_scf_loop = scf_control%outer_scf%have_scf
     244           2 :             scf_control%outer_scf%have_scf = .FALSE.
     245             :          END IF
     246             : 
     247       17305 :          IF (.NOT. dft_control%qs_control%cdft) THEN
     248             :             CALL scf_env_do_scf(scf_env=scf_env, scf_control=scf_control, qs_env=qs_env, &
     249       16979 :                                 converged=converged, should_stop=should_stop, total_scf_steps=tsteps)
     250             :          ELSE
     251             :             ! Third SCF loop needed for CDFT with OT to properly restart OT inner loop
     252         326 :             CALL cdft_scf(qs_env=qs_env, should_stop=should_stop)
     253             :          END IF
     254             : 
     255             :          ! If SCF has not converged, then we should not start MP2
     256       17305 :          IF (ASSOCIATED(qs_env%mp2_env)) qs_env%mp2_env%hf_fail = .NOT. converged
     257             : 
     258             :          ! Add the converged outer_scf SCF gradient(s)/variable(s) to history
     259       17305 :          IF (scf_control%outer_scf%have_scf) THEN
     260        3841 :             ihistory = scf_env%outer_scf%iter_count
     261             :             CALL get_qs_env(qs_env, gradient_history=gradient_history, &
     262        3841 :                             variable_history=variable_history)
     263             :             ! We only store the latest two values
     264        7712 :             gradient_history(:, 1) = gradient_history(:, 2)
     265       15424 :             gradient_history(:, 2) = scf_env%outer_scf%gradient(:, ihistory)
     266        7712 :             variable_history(:, 1) = variable_history(:, 2)
     267       15424 :             variable_history(:, 2) = scf_env%outer_scf%variables(:, ihistory)
     268             :             ! Reset flag
     269        3841 :             IF (used_history) used_history = .FALSE.
     270             :             ! Update a counter and check if the Jacobian should be deallocated
     271        3841 :             IF (ASSOCIATED(scf_env%outer_scf%inv_jacobian)) THEN
     272          64 :                scf_control%outer_scf%cdft_opt_control%ijacobian(2) = scf_control%outer_scf%cdft_opt_control%ijacobian(2) + 1
     273             :                IF (scf_control%outer_scf%cdft_opt_control%ijacobian(2) .GE. &
     274          64 :                    scf_control%outer_scf%cdft_opt_control%jacobian_freq(2) .AND. &
     275             :                    scf_control%outer_scf%cdft_opt_control%jacobian_freq(2) > 0) &
     276          50 :                   scf_env%outer_scf%deallocate_jacobian = .TRUE.
     277             :             END IF
     278             :          END IF
     279             :          !   *** add the converged wavefunction to the wavefunction history
     280       17305 :          IF ((ASSOCIATED(qs_env%wf_history)) .AND. &
     281             :              ((scf_control%density_guess .NE. history_guess) .OR. &
     282             :               (.NOT. first_step_flag))) THEN
     283       17303 :             IF (.NOT. dft_control%qs_control%cdft) THEN
     284       16977 :                CALL wfi_update(qs_env%wf_history, qs_env=qs_env, dt=1.0_dp)
     285             :             ELSE
     286         326 :                IF (dft_control%qs_control%cdft_control%should_purge) THEN
     287           0 :                   CALL wfi_purge_history(qs_env)
     288           0 :                   CALL outer_loop_purge_history(qs_env)
     289           0 :                   dft_control%qs_control%cdft_control%should_purge = .FALSE.
     290             :                ELSE
     291         326 :                   CALL wfi_update(qs_env%wf_history, qs_env=qs_env, dt=1.0_dp)
     292             :                END IF
     293             :             END IF
     294           2 :          ELSE IF ((scf_control%density_guess .EQ. history_guess) .AND. &
     295             :                   (first_step_flag)) THEN
     296           2 :             scf_control%max_scf = max_scf_tmp
     297           2 :             scf_control%outer_scf%have_scf = outer_scf_loop
     298           2 :             first_step_flag = .FALSE.
     299             :          END IF
     300             : 
     301             :          ! *** compute properties that depend on the converged wavefunction
     302       17305 :          IF (.NOT. (should_stop)) CALL qs_scf_compute_properties(qs_env)
     303             : 
     304             :          ! *** SMEAGOL interface ***
     305       17305 :          IF (.NOT. (should_stop)) THEN
     306             :             ! compute properties that depend on the converged wavefunction ..
     307       17305 :             CALL run_smeagol_emtrans(qs_env, last=.TRUE., iter=0)
     308             :             ! .. or save matrices related to bulk leads
     309       17305 :             CALL run_smeagol_bulktrans(qs_env)
     310             :          END IF
     311             : 
     312             :          ! *** cleanup
     313       17305 :          CALL scf_env_cleanup(scf_env)
     314       17305 :          IF (dft_control%qs_control%cdft) &
     315         326 :             CALL cdft_control_cleanup(dft_control%qs_control%cdft_control)
     316             : 
     317       17305 :          IF (PRESENT(has_converged)) THEN
     318           0 :             has_converged = converged
     319             :          END IF
     320       17305 :          IF (PRESENT(total_scf_steps)) THEN
     321           0 :             total_scf_steps = tsteps
     322             :          END IF
     323             : 
     324             :       END IF
     325             : 
     326       17947 :    END SUBROUTINE scf
     327             : 
     328             : ! **************************************************************************************************
     329             : !> \brief perform an scf loop
     330             : !> \param scf_env the scf_env where to perform the scf procedure
     331             : !> \param scf_control ...
     332             : !> \param qs_env the qs_env, the scf_env lives in
     333             : !> \param converged will be true / false if converged is reached
     334             : !> \param should_stop ...
     335             : !> \param total_scf_steps ...
     336             : !> \par History
     337             : !>      long history, see cvs and qs_scf module history
     338             : !>      02.2003 introduced scf_env [fawzi]
     339             : !>      09.2005 Frozen density approximation [TdK]
     340             : !>      06.2007 Check for SCF iteration count early [jgh]
     341             : !>      10.2019 switch_surf_dip [SGh]
     342             : !> \author Matthias Krack
     343             : !> \note
     344             : ! **************************************************************************************************
     345       17607 :    SUBROUTINE scf_env_do_scf(scf_env, scf_control, qs_env, converged, should_stop, total_scf_steps)
     346             : 
     347             :       TYPE(qs_scf_env_type), POINTER                     :: scf_env
     348             :       TYPE(scf_control_type), POINTER                    :: scf_control
     349             :       TYPE(qs_environment_type), POINTER                 :: qs_env
     350             :       LOGICAL, INTENT(OUT)                               :: converged, should_stop
     351             :       INTEGER, INTENT(OUT)                               :: total_scf_steps
     352             : 
     353             :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'scf_env_do_scf'
     354             : 
     355             :       CHARACTER(LEN=default_string_length)               :: description, name
     356             :       INTEGER                                            :: ext_master_id, handle, handle2, i_tmp, &
     357             :                                                             ic, ispin, iter_count, output_unit, &
     358             :                                                             scf_energy_message_tag, total_steps
     359             :       LOGICAL :: diis_step, do_kpoints, energy_only, exit_inner_loop, exit_outer_loop, &
     360             :          inner_loop_converged, just_energy, outer_loop_converged
     361             :       REAL(KIND=dp)                                      :: t1, t2
     362             :       REAL(KIND=dp), DIMENSION(3)                        :: res_val_3
     363       17607 :       TYPE(atomic_kind_type), DIMENSION(:), POINTER      :: atomic_kind_set
     364             :       TYPE(cp_logger_type), POINTER                      :: logger
     365             :       TYPE(cp_result_type), POINTER                      :: results
     366       17607 :       TYPE(dbcsr_p_type), DIMENSION(:, :), POINTER       :: rho_ao_kp
     367             :       TYPE(dft_control_type), POINTER                    :: dft_control
     368             :       TYPE(energy_correction_type), POINTER              :: ec_env
     369             :       TYPE(kpoint_type), POINTER                         :: kpoints
     370       17607 :       TYPE(mo_set_type), DIMENSION(:), POINTER           :: mos, mos_last_converged
     371             :       TYPE(mp_comm_type)                                 :: external_comm
     372             :       TYPE(mp_para_env_type), POINTER                    :: para_env
     373       17607 :       TYPE(particle_type), DIMENSION(:), POINTER         :: particle_set
     374             :       TYPE(pw_env_type), POINTER                         :: pw_env
     375             :       TYPE(qs_charges_type), POINTER                     :: qs_charges
     376             :       TYPE(qs_energy_type), POINTER                      :: energy
     377       17607 :       TYPE(qs_kind_type), DIMENSION(:), POINTER          :: qs_kind_set
     378             :       TYPE(qs_ks_env_type), POINTER                      :: ks_env
     379             :       TYPE(qs_rho_type), POINTER                         :: rho
     380             :       TYPE(section_vals_type), POINTER                   :: dft_section, input, scf_section
     381             : 
     382       17607 :       CALL timeset(routineN, handle)
     383             : 
     384       17607 :       NULLIFY (dft_control, rho, energy, &
     385       17607 :                logger, qs_charges, ks_env, mos, atomic_kind_set, qs_kind_set, &
     386       17607 :                particle_set, dft_section, input, &
     387       17607 :                scf_section, para_env, results, kpoints, pw_env, rho_ao_kp, mos_last_converged)
     388             : 
     389       17607 :       CPASSERT(ASSOCIATED(scf_env))
     390       17607 :       CPASSERT(ASSOCIATED(qs_env))
     391             : 
     392       17607 :       logger => cp_get_default_logger()
     393       17607 :       t1 = m_walltime()
     394             : 
     395             :       CALL get_qs_env(qs_env=qs_env, &
     396             :                       energy=energy, &
     397             :                       particle_set=particle_set, &
     398             :                       qs_charges=qs_charges, &
     399             :                       ks_env=ks_env, &
     400             :                       atomic_kind_set=atomic_kind_set, &
     401             :                       qs_kind_set=qs_kind_set, &
     402             :                       rho=rho, &
     403             :                       mos=mos, &
     404             :                       input=input, &
     405             :                       dft_control=dft_control, &
     406             :                       do_kpoints=do_kpoints, &
     407             :                       kpoints=kpoints, &
     408             :                       results=results, &
     409             :                       pw_env=pw_env, &
     410       17607 :                       para_env=para_env)
     411             : 
     412       17607 :       CALL qs_rho_get(rho, rho_ao_kp=rho_ao_kp)
     413             : 
     414       17607 :       dft_section => section_vals_get_subs_vals(input, "DFT")
     415       17607 :       scf_section => section_vals_get_subs_vals(dft_section, "SCF")
     416             : 
     417             :       output_unit = cp_print_key_unit_nr(logger, scf_section, "PRINT%PROGRAM_RUN_INFO", &
     418       17607 :                                          extension=".scfLog")
     419             : 
     420       17607 :       IF (output_unit > 0) WRITE (UNIT=output_unit, FMT="(/,/,T2,A)") &
     421        8986 :          "SCF WAVEFUNCTION OPTIMIZATION"
     422             : 
     423             :       ! when switch_surf_dip is switched on, indicate storing mos from the last converged step
     424       17607 :       IF (dft_control%switch_surf_dip) THEN
     425           2 :          CALL get_qs_env(qs_env, mos_last_converged=mos_last_converged)
     426           4 :          DO ispin = 1, dft_control%nspins
     427           4 :             CALL reassign_allocated_mos(mos(ispin), mos_last_converged(ispin))
     428             :          END DO
     429           2 :          IF (output_unit > 0) WRITE (UNIT=output_unit, FMT="(/,/,T2,A)") &
     430           1 :             "COPIED mos_last_converged ---> mos"
     431             :       END IF
     432             : 
     433       17607 :       IF ((output_unit > 0) .AND. (.NOT. scf_control%use_ot)) THEN
     434             :          WRITE (UNIT=output_unit, &
     435             :                 FMT="(/,T3,A,T12,A,T31,A,T39,A,T59,A,T75,A,/,T3,A)") &
     436        5975 :             "Step", "Update method", "Time", "Convergence", "Total energy", "Change", &
     437       11950 :             REPEAT("-", 78)
     438             :       END IF
     439       17607 :       CALL cp_add_iter_level(logger%iter_info, "QS_SCF")
     440             : 
     441             :       ! check for external communicator and if the intermediate energy should be sent
     442       70428 :       res_val_3(:) = -1.0_dp
     443       17607 :       description = "[EXT_SCF_ENER_COMM]"
     444       17607 :       IF (test_for_result(results, description=description)) THEN
     445             :          CALL get_results(results, description=description, &
     446           0 :                           values=res_val_3, n_entries=i_tmp)
     447           0 :          CPASSERT(i_tmp .EQ. 3)
     448           0 :          IF (ALL(res_val_3(:) .LE. 0.0)) &
     449             :             CALL cp_abort(__LOCATION__, &
     450             :                           " Trying to access result ("//TRIM(description)// &
     451           0 :                           ") which is not correctly stored.")
     452           0 :          CALL external_comm%set_handle(NINT(res_val_3(1)))
     453             :       END IF
     454       17607 :       ext_master_id = NINT(res_val_3(2))
     455       17607 :       scf_energy_message_tag = NINT(res_val_3(3))
     456             : 
     457             :       ! *** outer loop of the scf, can treat other variables,
     458             :       ! *** such as lagrangian multipliers
     459       17607 :       scf_env%outer_scf%iter_count = 0
     460       17607 :       iter_count = 0
     461       17607 :       total_steps = 0
     462       17607 :       energy%tot_old = 0.0_dp
     463             : 
     464         772 :       scf_outer_loop: DO
     465             : 
     466             :          CALL init_scf_loop(scf_env=scf_env, qs_env=qs_env, &
     467       18379 :                             scf_section=scf_section)
     468             : 
     469             :          CALL qs_scf_set_loop_flags(scf_env, diis_step, &
     470       18379 :                                     energy_only, just_energy, exit_inner_loop)
     471             : 
     472             :          ! decide whether to switch off dipole correction for convergence purposes
     473       18379 :          dft_control%surf_dip_correct_switch = dft_control%correct_surf_dip
     474       18379 :          IF ((dft_control%correct_surf_dip) .AND. (scf_control%outer_scf%have_scf) .AND. &
     475             :              (scf_env%outer_scf%iter_count > FLOOR(scf_control%outer_scf%max_scf/2.0_dp))) THEN
     476           0 :             IF (dft_control%switch_surf_dip) THEN
     477           0 :                dft_control%surf_dip_correct_switch = .FALSE.
     478           0 :                IF (output_unit > 0) WRITE (UNIT=output_unit, FMT="(/,/,T2,A)") &
     479           0 :                   "SURFACE DIPOLE CORRECTION switched off"
     480             :             END IF
     481             :          END IF
     482             : 
     483      156579 :          scf_loop: DO
     484             : 
     485      156579 :             CALL timeset(routineN//"_inner_loop", handle2)
     486             : 
     487      156579 :             IF (.NOT. just_energy) scf_env%iter_count = scf_env%iter_count + 1
     488      156579 :             iter_count = iter_count + 1
     489      156579 :             CALL cp_iterate(logger%iter_info, last=.FALSE., iter_nr=iter_count)
     490             : 
     491      156579 :             IF (output_unit > 0) CALL m_flush(output_unit)
     492             : 
     493      156579 :             total_steps = total_steps + 1
     494      156579 :             just_energy = energy_only
     495             : 
     496             :             CALL qs_ks_update_qs_env(qs_env, just_energy=just_energy, &
     497      156579 :                                      calculate_forces=.FALSE.)
     498             : 
     499             :             ! print 'heavy weight' or relatively expensive quantities
     500      156579 :             CALL qs_scf_loop_print(qs_env, scf_env, para_env)
     501             : 
     502      156579 :             IF (do_kpoints) THEN
     503             :                ! kpoints
     504        5226 :                IF (dft_control%hairy_probes .EQV. .TRUE.) THEN
     505           0 :                   scf_control%smear%do_smear = .FALSE.
     506           0 :                   CALL qs_scf_new_mos_kp(qs_env, scf_env, scf_control, diis_step, dft_control%probe)
     507             :                ELSE
     508        5226 :                   CALL qs_scf_new_mos_kp(qs_env, scf_env, scf_control, diis_step)
     509             :                END IF
     510             :             ELSE
     511             :                ! Gamma points only
     512      151353 :                IF (dft_control%hairy_probes .EQV. .TRUE.) THEN
     513          14 :                   scf_control%smear%do_smear = .FALSE.
     514             :                   CALL qs_scf_new_mos(qs_env, scf_env, scf_control, scf_section, diis_step, energy_only, &
     515          14 :                                       dft_control%probe)
     516             :                ELSE
     517      151339 :                   CALL qs_scf_new_mos(qs_env, scf_env, scf_control, scf_section, diis_step, energy_only)
     518             :                END IF
     519             :             END IF
     520             : 
     521             :             ! Print requested MO information (can be computationally expensive with OT)
     522      156579 :             CALL qs_scf_write_mos(qs_env, scf_env, final_mos=.FALSE.)
     523             : 
     524      156579 :             IF (dft_control%qs_control%xtb_control%do_tblite) THEN
     525         596 :                CALL tb_update_charges(qs_env, dft_control, qs_env%tb_tblite, .FALSE., .FALSE.)
     526         596 :                CALL evaluate_core_matrix_p_mix_new(qs_env)
     527         596 :                CALL tb_get_energy(qs_env, qs_env%tb_tblite, energy)
     528             :             END IF
     529             : 
     530      156579 :             CALL qs_scf_density_mixing(scf_env, rho, para_env, diis_step)
     531             : 
     532      156579 :             t2 = m_walltime()
     533             : 
     534      156579 :             CALL qs_scf_loop_info(scf_env, output_unit, just_energy, t1, t2, energy)
     535             : 
     536      156579 :             IF (.NOT. just_energy) energy%tot_old = energy%total
     537             : 
     538             :             ! check for external communicator and if the intermediate energy should be sent
     539      156579 :             IF (scf_energy_message_tag .GT. 0) THEN
     540           0 :                CALL external_comm%send(energy%total, ext_master_id, scf_energy_message_tag)
     541             :             END IF
     542             : 
     543             :             CALL qs_scf_check_inner_exit(qs_env, scf_env, scf_control, should_stop, just_energy, &
     544      156579 :                                          exit_inner_loop, inner_loop_converged, output_unit)
     545             : 
     546             :             ! In case we decide to exit we perform few more check to see if this one
     547             :             ! is really the last SCF step
     548      156579 :             IF (exit_inner_loop) THEN
     549             : 
     550       18379 :                CALL qs_scf_inner_finalize(scf_env, qs_env, diis_step, output_unit)
     551             : 
     552             :                CALL qs_scf_check_outer_exit(qs_env, scf_env, scf_control, should_stop, &
     553       18379 :                                             outer_loop_converged, exit_outer_loop)
     554             : 
     555             :                ! Let's tag the last SCF cycle so we can print informations only of the last step
     556       18379 :                IF (exit_outer_loop) CALL cp_iterate(logger%iter_info, last=.TRUE., iter_nr=iter_count)
     557             : 
     558             :             END IF
     559             : 
     560      156579 :             IF (do_kpoints) THEN
     561        5226 :                CALL write_kpoints_restart(rho_ao_kp, kpoints, scf_env, dft_section, particle_set, qs_kind_set)
     562             :             ELSE
     563             :                ! Write Wavefunction restart file
     564      151353 :                CALL write_mo_set_to_restart(mos, particle_set, dft_section=dft_section, qs_kind_set=qs_kind_set)
     565             :             END IF
     566             : 
     567             :             ! Exit if we have finished with the SCF inner loop
     568      156579 :             IF (exit_inner_loop) THEN
     569       18379 :                CALL timestop(handle2)
     570             :                EXIT scf_loop
     571             :             END IF
     572             : 
     573      138200 :             IF (.NOT. BTEST(cp_print_key_should_output(logger%iter_info, &
     574             :                                                        scf_section, "PRINT%ITERATION_INFO/TIME_CUMUL"), cp_p_file)) &
     575      138200 :                t1 = m_walltime()
     576             : 
     577             :             ! mixing methods have the new density matrix in p_mix_new
     578      138200 :             IF (scf_env%mixing_method > 0) THEN
     579      496938 :                DO ic = 1, SIZE(rho_ao_kp, 2)
     580      968575 :                   DO ispin = 1, dft_control%nspins
     581      471637 :                      CALL dbcsr_get_info(rho_ao_kp(ispin, ic)%matrix, name=name) ! keep the name
     582      892916 :                      CALL dbcsr_copy(rho_ao_kp(ispin, ic)%matrix, scf_env%p_mix_new(ispin, ic)%matrix, name=name)
     583             :                   END DO
     584             :                END DO
     585             :             END IF
     586             : 
     587             :             CALL qs_scf_rho_update(rho, qs_env, scf_env, ks_env, &
     588      138200 :                                    mix_rho=scf_env%mixing_method >= gspace_mixing_nr)
     589             : 
     590      138200 :             CALL timestop(handle2)
     591             : 
     592             :          END DO scf_loop
     593             : 
     594       18379 :          IF (.NOT. scf_control%outer_scf%have_scf) EXIT scf_outer_loop
     595             : 
     596             :          ! In case we use the OUTER SCF loop let's print some info..
     597             :          CALL qs_scf_outer_loop_info(output_unit, scf_control, scf_env, &
     598        4913 :                                      energy, total_steps, should_stop, outer_loop_converged)
     599             : 
     600             : !  save mos to converged mos if outer_loop_converged and surf_dip_correct_switch is true
     601        4913 :          IF (exit_outer_loop) THEN
     602        4141 :             IF ((dft_control%switch_surf_dip) .AND. (outer_loop_converged) .AND. &
     603             :                 (dft_control%surf_dip_correct_switch)) THEN
     604           4 :                DO ispin = 1, dft_control%nspins
     605           4 :                   CALL reassign_allocated_mos(mos_last_converged(ispin), mos(ispin))
     606             :                END DO
     607           2 :                IF (output_unit > 0) WRITE (UNIT=output_unit, FMT="(/,/,T2,A)") &
     608           1 :                   "COPIED mos ---> mos_last_converged"
     609             :             END IF
     610             :          END IF
     611             : 
     612        4913 :          IF (exit_outer_loop) EXIT scf_outer_loop
     613             : 
     614             :          !
     615         772 :          CALL outer_loop_optimize(scf_env, scf_control)
     616         772 :          CALL outer_loop_update_qs_env(qs_env, scf_env)
     617       18379 :          CALL qs_ks_did_change(ks_env, potential_changed=.TRUE.)
     618             : 
     619             :       END DO scf_outer_loop
     620             : 
     621       17607 :       converged = inner_loop_converged .AND. outer_loop_converged
     622       17607 :       total_scf_steps = total_steps
     623             : 
     624       17607 :       IF (dft_control%qs_control%cdft) &
     625             :          dft_control%qs_control%cdft_control%total_steps = &
     626         626 :          dft_control%qs_control%cdft_control%total_steps + total_steps
     627             : 
     628       17607 :       IF (.NOT. converged) THEN
     629        2142 :          IF (scf_control%ignore_convergence_failure .OR. should_stop) THEN
     630        2142 :             CALL cp_warn(__LOCATION__, "SCF run NOT converged")
     631             :          ELSE
     632             :             CALL cp_abort(__LOCATION__, &
     633             :                           "SCF run NOT converged. To continue the calculation "// &
     634           0 :                           "regardless, please set the keyword IGNORE_CONVERGENCE_FAILURE.")
     635             :          END IF
     636             :       END IF
     637             : 
     638             :       ! Skip Harris functional calculation if ground-state is NOT converged
     639       17607 :       IF (qs_env%energy_correction) THEN
     640         510 :          CALL get_qs_env(qs_env, ec_env=ec_env)
     641         510 :          ec_env%do_skip = .FALSE.
     642         510 :          IF (ec_env%skip_ec .AND. .NOT. converged) ec_env%do_skip = .TRUE.
     643             :       END IF
     644             : 
     645             :       ! if needed copy mo_coeff dbcsr->fm for later use in post_scf!fm->dbcsr
     646       37720 :       DO ispin = 1, SIZE(mos) !fm -> dbcsr
     647       37720 :          IF (mos(ispin)%use_mo_coeff_b) THEN !fm->dbcsr
     648        6983 :             IF (.NOT. ASSOCIATED(mos(ispin)%mo_coeff_b)) & !fm->dbcsr
     649           0 :                CPABORT("mo_coeff_b is not allocated") !fm->dbcsr
     650             :             CALL copy_dbcsr_to_fm(mos(ispin)%mo_coeff_b, & !fm->dbcsr
     651        6983 :                                   mos(ispin)%mo_coeff) !fm -> dbcsr
     652             :          END IF !fm->dbcsr
     653             :       END DO !fm -> dbcsr
     654             : 
     655       17607 :       CALL cp_rm_iter_level(logger%iter_info, level_name="QS_SCF")
     656       17607 :       CALL timestop(handle)
     657             : 
     658       17607 :    END SUBROUTINE scf_env_do_scf
     659             : 
     660             : ! **************************************************************************************************
     661             : !> \brief inits those objects needed if you want to restart the scf with, say
     662             : !>        only a new initial guess, or different density functional or ...
     663             : !>        this will happen just before the scf loop starts
     664             : !> \param scf_env ...
     665             : !> \param qs_env ...
     666             : !> \param scf_section ...
     667             : !> \par History
     668             : !>      03.2006 created [Joost VandeVondele]
     669             : ! **************************************************************************************************
     670       20519 :    SUBROUTINE init_scf_loop(scf_env, qs_env, scf_section)
     671             : 
     672             :       TYPE(qs_scf_env_type), POINTER                     :: scf_env
     673             :       TYPE(qs_environment_type), POINTER                 :: qs_env
     674             :       TYPE(section_vals_type), POINTER                   :: scf_section
     675             : 
     676             :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'init_scf_loop'
     677             : 
     678             :       INTEGER                                            :: handle, ispin, nmo, number_of_OT_envs
     679             :       LOGICAL                                            :: do_kpoints, do_rotation, &
     680             :                                                             has_unit_metric, is_full_all
     681             :       TYPE(cp_fm_type), POINTER                          :: mo_coeff
     682       20519 :       TYPE(dbcsr_p_type), DIMENSION(:), POINTER          :: matrix_ks, matrix_s
     683             :       TYPE(dbcsr_type), POINTER                          :: orthogonality_metric
     684             :       TYPE(dft_control_type), POINTER                    :: dft_control
     685             :       TYPE(kpoint_type), POINTER                         :: kpoints
     686       20519 :       TYPE(mo_set_type), DIMENSION(:), POINTER           :: mos
     687             :       TYPE(scf_control_type), POINTER                    :: scf_control
     688             : 
     689       20519 :       CALL timeset(routineN, handle)
     690             : 
     691       20519 :       NULLIFY (scf_control, matrix_s, matrix_ks, dft_control, mos, mo_coeff, kpoints)
     692             : 
     693       20519 :       CPASSERT(ASSOCIATED(scf_env))
     694       20519 :       CPASSERT(ASSOCIATED(qs_env))
     695             : 
     696             :       CALL get_qs_env(qs_env=qs_env, &
     697             :                       scf_control=scf_control, &
     698             :                       dft_control=dft_control, &
     699             :                       do_kpoints=do_kpoints, &
     700             :                       kpoints=kpoints, &
     701       20519 :                       mos=mos)
     702             : 
     703             :       ! if using mo_coeff_b then copy to fm
     704       43939 :       DO ispin = 1, SIZE(mos) !fm->dbcsr
     705       43939 :          IF (mos(1)%use_mo_coeff_b) THEN !fm->dbcsr
     706        7922 :             CALL copy_dbcsr_to_fm(mos(ispin)%mo_coeff_b, mos(ispin)%mo_coeff) !fm->dbcsr
     707             :          END IF !fm->dbcsr
     708             :       END DO !fm->dbcsr
     709             : 
     710             :       ! this just guarantees that all mo_occupations match the eigenvalues, if smear
     711       43939 :       DO ispin = 1, dft_control%nspins
     712             :          ! do not reset mo_occupations if the maximum overlap method is in use
     713       43939 :          IF (.NOT. scf_control%diagonalization%mom) THEN
     714             :             !if the hair probes section is present, this sends hairy_probes to set_mo_occupation subroutine
     715             :             !and switches off the standard smearing
     716       23376 :             IF (dft_control%hairy_probes .EQV. .TRUE.) THEN
     717           4 :                IF (scf_env%outer_scf%iter_count > 0) THEN
     718           0 :                   scf_control%smear%do_smear = .FALSE.
     719             :                   CALL set_mo_occupation(mo_set=mos(ispin), &
     720             :                                          smear=scf_control%smear, &
     721           0 :                                          probe=dft_control%probe)
     722             :                END IF
     723             :             ELSE
     724             :                CALL set_mo_occupation(mo_set=mos(ispin), &
     725       23372 :                                       smear=scf_control%smear)
     726             :             END IF
     727             :          END IF
     728             :       END DO
     729             : 
     730       20519 :       SELECT CASE (scf_env%method)
     731             :       CASE DEFAULT
     732             : 
     733           0 :          CPABORT("unknown scf method method:"//cp_to_string(scf_env%method))
     734             : 
     735             :       CASE (filter_matrix_diag_method_nr)
     736             : 
     737          10 :          IF (.NOT. scf_env%skip_diis) THEN
     738           0 :             IF (.NOT. ASSOCIATED(scf_env%scf_diis_buffer)) THEN
     739           0 :                ALLOCATE (scf_env%scf_diis_buffer)
     740           0 :                CALL qs_diis_b_create(scf_env%scf_diis_buffer, nbuffer=scf_control%max_diis)
     741             :             END IF
     742           0 :             CALL qs_diis_b_clear(scf_env%scf_diis_buffer)
     743             :          END IF
     744             : 
     745             :       CASE (general_diag_method_nr, special_diag_method_nr, block_krylov_diag_method_nr, smeagol_method_nr)
     746       13910 :          IF (.NOT. scf_env%skip_diis) THEN
     747       13658 :             IF (do_kpoints) THEN
     748         862 :                IF (.NOT. ASSOCIATED(kpoints%scf_diis_buffer)) THEN
     749         134 :                   ALLOCATE (kpoints%scf_diis_buffer)
     750         134 :                   CALL qs_diis_b_create_kp(kpoints%scf_diis_buffer, nbuffer=scf_control%max_diis)
     751             :                END IF
     752         862 :                CALL qs_diis_b_clear_kp(kpoints%scf_diis_buffer)
     753             :             ELSE
     754       12796 :                IF (.NOT. ASSOCIATED(scf_env%scf_diis_buffer)) THEN
     755        3836 :                   ALLOCATE (scf_env%scf_diis_buffer)
     756        3836 :                   CALL qs_diis_b_create(scf_env%scf_diis_buffer, nbuffer=scf_control%max_diis)
     757             :                END IF
     758       12796 :                CALL qs_diis_b_clear(scf_env%scf_diis_buffer)
     759             :             END IF
     760             :          END IF
     761             : 
     762             :       CASE (ot_diag_method_nr)
     763           8 :          CALL get_qs_env(qs_env, matrix_ks=matrix_ks, matrix_s=matrix_s)
     764             : 
     765           8 :          IF (.NOT. scf_env%skip_diis) THEN
     766           6 :             IF (.NOT. ASSOCIATED(scf_env%scf_diis_buffer)) THEN
     767           6 :                ALLOCATE (scf_env%scf_diis_buffer)
     768           6 :                CALL qs_diis_b_create(scf_env%scf_diis_buffer, nbuffer=scf_control%max_diis)
     769             :             END IF
     770           6 :             CALL qs_diis_b_clear(scf_env%scf_diis_buffer)
     771             :          END IF
     772             : 
     773             :          ! disable DFTB and SE for now
     774             :          IF (dft_control%qs_control%dftb .OR. &
     775           8 :              dft_control%qs_control%xtb .OR. &
     776             :              dft_control%qs_control%semi_empirical) THEN
     777           0 :             CPABORT("DFTB and SE not available with OT/DIAG")
     778             :          END IF
     779             : 
     780             :          ! if an old preconditioner is still around (i.e. outer SCF is active),
     781             :          ! remove it if this could be worthwhile
     782             :          CALL restart_preconditioner(qs_env, scf_env%ot_preconditioner, &
     783             :                                      scf_control%diagonalization%ot_settings%preconditioner_type, &
     784           8 :                                      dft_control%nspins)
     785             : 
     786             :          CALL prepare_preconditioner(qs_env, mos, matrix_ks, matrix_s, scf_env%ot_preconditioner, &
     787             :                                      scf_control%diagonalization%ot_settings%preconditioner_type, &
     788             :                                      scf_control%diagonalization%ot_settings%precond_solver_type, &
     789           8 :                                      scf_control%diagonalization%ot_settings%energy_gap, dft_control%nspins)
     790             : 
     791             :       CASE (block_davidson_diag_method_nr)
     792             :          ! Preconditioner initialized within the loop, when required
     793             :       CASE (ot_method_nr)
     794             :          CALL get_qs_env(qs_env, &
     795             :                          has_unit_metric=has_unit_metric, &
     796             :                          matrix_s=matrix_s, &
     797        6575 :                          matrix_ks=matrix_ks)
     798             : 
     799             :          ! reortho the wavefunctions if we are having an outer scf and
     800             :          ! this is not the first iteration
     801             :          ! this is useful to avoid the build-up of numerical noise
     802             :          ! however, we can not play this trick if restricted (don't mix non-equivalent orbs)
     803        6575 :          IF (scf_control%do_outer_scf_reortho) THEN
     804        6005 :             IF (scf_control%outer_scf%have_scf .AND. .NOT. dft_control%restricted) THEN
     805        4163 :                IF (scf_env%outer_scf%iter_count > 0) THEN
     806        1653 :                   DO ispin = 1, dft_control%nspins
     807         901 :                      CALL get_mo_set(mo_set=mos(ispin), mo_coeff=mo_coeff, nmo=nmo)
     808        1653 :                      IF (has_unit_metric) THEN
     809         110 :                         CALL make_basis_simple(mo_coeff, nmo)
     810             :                      ELSE
     811         791 :                         CALL make_basis_sm(mo_coeff, nmo, matrix_s(1)%matrix)
     812             :                      END IF
     813             :                   END DO
     814             :                END IF
     815             :             END IF
     816             :          ELSE
     817             :             ! dont need any dirty trick for the numerically stable irac algorithm.
     818             :          END IF
     819             : 
     820        6575 :          IF (.NOT. ASSOCIATED(scf_env%qs_ot_env)) THEN
     821             : 
     822             :             ! restricted calculations require just one set of OT orbitals
     823        6575 :             number_of_OT_envs = dft_control%nspins
     824        6575 :             IF (dft_control%restricted) number_of_OT_envs = 1
     825             : 
     826     1086100 :             ALLOCATE (scf_env%qs_ot_env(number_of_OT_envs))
     827             : 
     828             :             ! XXX Joost XXX should disentangle reading input from this part
     829        6575 :             IF (scf_env%outer_scf%iter_count > 0) THEN
     830         772 :                IF (scf_env%iter_delta < scf_control%eps_diis) THEN
     831           4 :                   scf_env%qs_ot_env(1)%settings%ot_state = 1
     832             :                END IF
     833             :             END IF
     834             :             !
     835        6575 :             CALL ot_scf_read_input(scf_env%qs_ot_env, scf_section)
     836             :             !
     837        6575 :             IF (scf_env%outer_scf%iter_count > 0) THEN
     838         772 :                IF (scf_env%qs_ot_env(1)%settings%ot_state == 1) THEN
     839             :                   scf_control%max_scf = MAX(scf_env%qs_ot_env(1)%settings%max_scf_diis, &
     840           4 :                                             scf_control%max_scf)
     841             :                END IF
     842             :             END IF
     843             : 
     844             :             ! keep a note that we are restricted
     845        6575 :             IF (dft_control%restricted) THEN
     846          92 :                scf_env%qs_ot_env(1)%restricted = .TRUE.
     847             :                ! requires rotation
     848          92 :                IF (.NOT. scf_env%qs_ot_env(1)%settings%do_rotation) &
     849             :                   CALL cp_abort(__LOCATION__, &
     850             :                                 "Restricted calculation with OT requires orbital rotation. Please "// &
     851           0 :                                 "activate the OT%ROTATION keyword!")
     852             :             ELSE
     853       14191 :                scf_env%qs_ot_env(:)%restricted = .FALSE.
     854             :             END IF
     855             : 
     856             :             ! this will rotate the MOs to be eigen states, which is not compatible with rotation
     857             :             ! e.g. mo_derivs here do not yet include potentially different occupations numbers
     858        6575 :             do_rotation = scf_env%qs_ot_env(1)%settings%do_rotation
     859             :             ! only full all needs rotation
     860        6575 :             is_full_all = scf_env%qs_ot_env(1)%settings%preconditioner_type == ot_precond_full_all
     861        6575 :             IF (do_rotation .AND. is_full_all) &
     862           0 :                CPABORT('PRECONDITIONER FULL_ALL is not compatible with ROTATION.')
     863             : 
     864             :             ! might need the KS matrix to init properly
     865             :             CALL qs_ks_update_qs_env(qs_env, just_energy=.FALSE., &
     866        6575 :                                      calculate_forces=.FALSE.)
     867             : 
     868             :             ! if an old preconditioner is still around (i.e. outer SCF is active),
     869             :             ! remove it if this could be worthwhile
     870        6575 :             IF (.NOT. reuse_precond) &
     871             :                CALL restart_preconditioner(qs_env, scf_env%ot_preconditioner, &
     872             :                                            scf_env%qs_ot_env(1)%settings%preconditioner_type, &
     873        6575 :                                            dft_control%nspins)
     874             : 
     875             :             !
     876             :             ! preconditioning still needs to be done correctly with has_unit_metric
     877             :             ! notice that a big part of the preconditioning (S^-1) is fine anyhow
     878             :             !
     879        6575 :             IF (has_unit_metric) THEN
     880        1134 :                NULLIFY (orthogonality_metric)
     881             :             ELSE
     882        5441 :                orthogonality_metric => matrix_s(1)%matrix
     883             :             END IF
     884             : 
     885        6575 :             IF (.NOT. reuse_precond) &
     886             :                CALL prepare_preconditioner(qs_env, mos, matrix_ks, matrix_s, scf_env%ot_preconditioner, &
     887             :                                            scf_env%qs_ot_env(1)%settings%preconditioner_type, &
     888             :                                            scf_env%qs_ot_env(1)%settings%precond_solver_type, &
     889             :                                            scf_env%qs_ot_env(1)%settings%energy_gap, dft_control%nspins, &
     890             :                                            has_unit_metric=has_unit_metric, &
     891        6575 :                                            chol_type=scf_env%qs_ot_env(1)%settings%cholesky_type)
     892        6575 :             IF (reuse_precond) reuse_precond = .FALSE.
     893             : 
     894             :             CALL ot_scf_init(mo_array=mos, matrix_s=orthogonality_metric, &
     895             :                              broyden_adaptive_sigma=qs_env%broyden_adaptive_sigma, &
     896        6575 :                              qs_ot_env=scf_env%qs_ot_env, matrix_ks=matrix_ks(1)%matrix)
     897             : 
     898       11169 :             SELECT CASE (scf_env%qs_ot_env(1)%settings%preconditioner_type)
     899             :             CASE (ot_precond_none)
     900             :             CASE (ot_precond_full_all, ot_precond_full_single_inverse)
     901       10129 :                DO ispin = 1, SIZE(scf_env%qs_ot_env)
     902             :                   CALL qs_ot_new_preconditioner(scf_env%qs_ot_env(ispin), &
     903       10129 :                                                 scf_env%ot_preconditioner(ispin)%preconditioner)
     904             :                END DO
     905             :             CASE (ot_precond_s_inverse, ot_precond_full_single)
     906         152 :                DO ispin = 1, SIZE(scf_env%qs_ot_env)
     907             :                   CALL qs_ot_new_preconditioner(scf_env%qs_ot_env(ispin), &
     908         152 :                                                 scf_env%ot_preconditioner(1)%preconditioner)
     909             :                END DO
     910             :             CASE DEFAULT
     911        8022 :                DO ispin = 1, SIZE(scf_env%qs_ot_env)
     912             :                   CALL qs_ot_new_preconditioner(scf_env%qs_ot_env(ispin), &
     913        2660 :                                                 scf_env%ot_preconditioner(1)%preconditioner)
     914             :                END DO
     915             :             END SELECT
     916             :          END IF
     917             : 
     918             :          ! if we have non-uniform occupations we should be using rotation
     919        6575 :          do_rotation = scf_env%qs_ot_env(1)%settings%do_rotation
     920       34986 :          DO ispin = 1, SIZE(mos)
     921       14467 :             IF (.NOT. mos(ispin)%uniform_occupation) THEN
     922           0 :                CPASSERT(do_rotation)
     923             :             END IF
     924             :          END DO
     925             :       END SELECT
     926             : 
     927             :       ! another safety check
     928       20519 :       IF (dft_control%low_spin_roks) THEN
     929          24 :          CPASSERT(scf_env%method == ot_method_nr)
     930          24 :          do_rotation = scf_env%qs_ot_env(1)%settings%do_rotation
     931          24 :          CPASSERT(do_rotation)
     932             :       END IF
     933             : 
     934       20519 :       CALL timestop(handle)
     935             : 
     936       20519 :    END SUBROUTINE init_scf_loop
     937             : 
     938             : ! **************************************************************************************************
     939             : !> \brief perform cleanup operations (like releasing temporary storage)
     940             : !>      at the end of the scf
     941             : !> \param scf_env ...
     942             : !> \par History
     943             : !>      02.2003 created [fawzi]
     944             : !> \author fawzi
     945             : ! **************************************************************************************************
     946       17351 :    SUBROUTINE scf_env_cleanup(scf_env)
     947             :       TYPE(qs_scf_env_type), INTENT(INOUT)               :: scf_env
     948             : 
     949             :       CHARACTER(len=*), PARAMETER                        :: routineN = 'scf_env_cleanup'
     950             : 
     951             :       INTEGER                                            :: handle
     952             : 
     953       17351 :       CALL timeset(routineN, handle)
     954             : 
     955             :       ! Release SCF work storage
     956       17351 :       CALL cp_fm_release(scf_env%scf_work1)
     957             : 
     958       17351 :       IF (ASSOCIATED(scf_env%scf_work1_red)) THEN
     959          38 :          CALL cp_fm_release(scf_env%scf_work1_red)
     960             :       END IF
     961       17351 :       IF (ASSOCIATED(scf_env%scf_work2)) THEN
     962       11728 :          CALL cp_fm_release(scf_env%scf_work2)
     963       11728 :          DEALLOCATE (scf_env%scf_work2)
     964             :          NULLIFY (scf_env%scf_work2)
     965             :       END IF
     966       17351 :       IF (ASSOCIATED(scf_env%scf_work2_red)) THEN
     967          38 :          CALL cp_fm_release(scf_env%scf_work2_red)
     968          38 :          DEALLOCATE (scf_env%scf_work2_red)
     969             :          NULLIFY (scf_env%scf_work2_red)
     970             :       END IF
     971       17351 :       IF (ASSOCIATED(scf_env%ortho)) THEN
     972        9060 :          CALL cp_fm_release(scf_env%ortho)
     973        9060 :          DEALLOCATE (scf_env%ortho)
     974             :          NULLIFY (scf_env%ortho)
     975             :       END IF
     976       17351 :       IF (ASSOCIATED(scf_env%ortho_red)) THEN
     977          38 :          CALL cp_fm_release(scf_env%ortho_red)
     978          38 :          DEALLOCATE (scf_env%ortho_red)
     979             :          NULLIFY (scf_env%ortho_red)
     980             :       END IF
     981       17351 :       IF (ASSOCIATED(scf_env%ortho_m1)) THEN
     982          48 :          CALL cp_fm_release(scf_env%ortho_m1)
     983          48 :          DEALLOCATE (scf_env%ortho_m1)
     984             :          NULLIFY (scf_env%ortho_m1)
     985             :       END IF
     986       17351 :       IF (ASSOCIATED(scf_env%ortho_m1_red)) THEN
     987           6 :          CALL cp_fm_release(scf_env%ortho_m1_red)
     988           6 :          DEALLOCATE (scf_env%ortho_m1_red)
     989             :          NULLIFY (scf_env%ortho_m1_red)
     990             :       END IF
     991             : 
     992       17351 :       IF (ASSOCIATED(scf_env%ortho_dbcsr)) THEN
     993          58 :          CALL dbcsr_deallocate_matrix(scf_env%ortho_dbcsr)
     994             :       END IF
     995       17351 :       IF (ASSOCIATED(scf_env%buf1_dbcsr)) THEN
     996          58 :          CALL dbcsr_deallocate_matrix(scf_env%buf1_dbcsr)
     997             :       END IF
     998       17351 :       IF (ASSOCIATED(scf_env%buf2_dbcsr)) THEN
     999          58 :          CALL dbcsr_deallocate_matrix(scf_env%buf2_dbcsr)
    1000             :       END IF
    1001             : 
    1002       17351 :       IF (ASSOCIATED(scf_env%p_mix_new)) THEN
    1003       11740 :          CALL dbcsr_deallocate_matrix_set(scf_env%p_mix_new)
    1004             :       END IF
    1005             : 
    1006       17351 :       IF (ASSOCIATED(scf_env%p_delta)) THEN
    1007         246 :          CALL dbcsr_deallocate_matrix_set(scf_env%p_delta)
    1008             :       END IF
    1009             : 
    1010             :       ! Method dependent cleanup
    1011       17367 :       SELECT CASE (scf_env%method)
    1012             :       CASE (ot_method_nr)
    1013             :          !
    1014             :       CASE (ot_diag_method_nr)
    1015             :          !
    1016             :       CASE (general_diag_method_nr)
    1017             :          !
    1018             :       CASE (special_diag_method_nr)
    1019             :          !
    1020             :       CASE (block_krylov_diag_method_nr)
    1021             :       CASE (block_davidson_diag_method_nr)
    1022          16 :          CALL block_davidson_deallocate(scf_env%block_davidson_env)
    1023             :       CASE (filter_matrix_diag_method_nr)
    1024             :          !
    1025             :       CASE (smeagol_method_nr)
    1026             :          !
    1027             :       CASE DEFAULT
    1028       17351 :          CPABORT("unknown scf method method:"//cp_to_string(scf_env%method))
    1029             :       END SELECT
    1030             : 
    1031       17351 :       IF (ASSOCIATED(scf_env%outer_scf%variables)) THEN
    1032        3845 :          DEALLOCATE (scf_env%outer_scf%variables)
    1033             :       END IF
    1034       17351 :       IF (ASSOCIATED(scf_env%outer_scf%count)) THEN
    1035        3845 :          DEALLOCATE (scf_env%outer_scf%count)
    1036             :       END IF
    1037       17351 :       IF (ASSOCIATED(scf_env%outer_scf%gradient)) THEN
    1038        3845 :          DEALLOCATE (scf_env%outer_scf%gradient)
    1039             :       END IF
    1040       17351 :       IF (ASSOCIATED(scf_env%outer_scf%energy)) THEN
    1041        3845 :          DEALLOCATE (scf_env%outer_scf%energy)
    1042             :       END IF
    1043       17351 :       IF (ASSOCIATED(scf_env%outer_scf%inv_jacobian) .AND. &
    1044             :           scf_env%outer_scf%deallocate_jacobian) THEN
    1045          50 :          DEALLOCATE (scf_env%outer_scf%inv_jacobian)
    1046             :       END IF
    1047             : 
    1048       17351 :       CALL timestop(handle)
    1049             : 
    1050       17351 :    END SUBROUTINE scf_env_cleanup
    1051             : 
    1052             : ! **************************************************************************************************
    1053             : !> \brief perform a CDFT scf procedure in the given qs_env
    1054             : !> \param qs_env the qs_environment where to perform the scf procedure
    1055             : !> \param should_stop flag determining if calculation should stop
    1056             : !> \par History
    1057             : !>      12.2015 Created
    1058             : !> \author Nico Holmberg
    1059             : ! **************************************************************************************************
    1060         652 :    SUBROUTINE cdft_scf(qs_env, should_stop)
    1061             :       TYPE(qs_environment_type), POINTER                 :: qs_env
    1062             :       LOGICAL, INTENT(OUT)                               :: should_stop
    1063             : 
    1064             :       CHARACTER(len=*), PARAMETER                        :: routineN = 'cdft_scf'
    1065             : 
    1066             :       INTEGER                                            :: handle, iatom, ispin, ivar, nmo, nvar, &
    1067             :                                                             output_unit, tsteps
    1068             :       LOGICAL                                            :: cdft_loop_converged, converged, &
    1069             :                                                             exit_cdft_loop, first_iteration, &
    1070             :                                                             my_uocc, uniform_occupation
    1071         326 :       REAL(KIND=dp), DIMENSION(:), POINTER               :: mo_occupations
    1072             :       TYPE(cdft_control_type), POINTER                   :: cdft_control
    1073             :       TYPE(cp_logger_type), POINTER                      :: logger
    1074         326 :       TYPE(dbcsr_p_type), DIMENSION(:), POINTER          :: matrix_s, rho_ao
    1075             :       TYPE(dft_control_type), POINTER                    :: dft_control
    1076         326 :       TYPE(mo_set_type), DIMENSION(:), POINTER           :: mos
    1077             :       TYPE(pw_env_type), POINTER                         :: pw_env
    1078             :       TYPE(pw_pool_type), POINTER                        :: auxbas_pw_pool
    1079             :       TYPE(qs_energy_type), POINTER                      :: energy
    1080             :       TYPE(qs_ks_env_type), POINTER                      :: ks_env
    1081             :       TYPE(qs_rho_type), POINTER                         :: rho
    1082             :       TYPE(qs_scf_env_type), POINTER                     :: scf_env
    1083             :       TYPE(scf_control_type), POINTER                    :: scf_control
    1084             :       TYPE(section_vals_type), POINTER                   :: dft_section, input, scf_section
    1085             : 
    1086         326 :       NULLIFY (scf_env, ks_env, energy, rho, matrix_s, rho_ao, cdft_control, logger, &
    1087         326 :                dft_control, pw_env, auxbas_pw_pool, energy, ks_env, scf_env, dft_section, &
    1088         326 :                input, scf_section, scf_control, mos, mo_occupations)
    1089         652 :       logger => cp_get_default_logger()
    1090             : 
    1091         326 :       CPASSERT(ASSOCIATED(qs_env))
    1092             :       CALL get_qs_env(qs_env, scf_env=scf_env, energy=energy, &
    1093             :                       dft_control=dft_control, scf_control=scf_control, &
    1094         326 :                       ks_env=ks_env, input=input)
    1095             : 
    1096         326 :       CALL timeset(routineN//"_loop", handle)
    1097         326 :       dft_section => section_vals_get_subs_vals(input, "DFT")
    1098         326 :       scf_section => section_vals_get_subs_vals(dft_section, "SCF")
    1099             :       output_unit = cp_print_key_unit_nr(logger, scf_section, "PRINT%PROGRAM_RUN_INFO", &
    1100         326 :                                          extension=".scfLog")
    1101         326 :       first_iteration = .TRUE.
    1102             : 
    1103         326 :       cdft_control => dft_control%qs_control%cdft_control
    1104             : 
    1105         326 :       scf_env%outer_scf%iter_count = 0
    1106         326 :       cdft_control%total_steps = 0
    1107             : 
    1108             :       ! Write some info about the CDFT calculation
    1109         326 :       IF (output_unit > 0) THEN
    1110             :          WRITE (UNIT=output_unit, FMT="(/,/,T2,A)") &
    1111         181 :             "CDFT EXTERNAL SCF WAVEFUNCTION OPTIMIZATION"
    1112         181 :          CALL qs_scf_cdft_initial_info(output_unit, cdft_control)
    1113             :       END IF
    1114         326 :       IF (cdft_control%reuse_precond) THEN
    1115           0 :          reuse_precond = .FALSE.
    1116           0 :          cdft_control%nreused = 0
    1117             :       END IF
    1118         512 :       cdft_outer_loop: DO
    1119             :          ! Change outer_scf settings to OT settings
    1120         512 :          CALL outer_loop_switch(scf_env, scf_control, cdft_control, cdft2ot)
    1121             :          ! Solve electronic structure with fixed value of constraint
    1122             :          CALL scf_env_do_scf(scf_env=scf_env, scf_control=scf_control, qs_env=qs_env, &
    1123         512 :                              converged=converged, should_stop=should_stop, total_scf_steps=tsteps)
    1124             :          ! Decide whether to reuse the preconditioner on the next iteration
    1125         512 :          IF (cdft_control%reuse_precond) THEN
    1126             :             ! For convergence in exactly one step, the preconditioner is always reused (assuming max_reuse > 0)
    1127             :             ! usually this means that the electronic structure has already converged to the correct state
    1128             :             ! but the constraint optimizer keeps jumping over the optimal solution
    1129             :             IF (scf_env%outer_scf%iter_count == 1 .AND. scf_env%iter_count == 1 &
    1130           0 :                 .AND. cdft_control%total_steps /= 1) &
    1131           0 :                cdft_control%nreused = cdft_control%nreused - 1
    1132             :             ! SCF converged in less than precond_freq steps
    1133             :             IF (scf_env%outer_scf%iter_count == 1 .AND. scf_env%iter_count .LE. cdft_control%precond_freq .AND. &
    1134           0 :                 cdft_control%total_steps /= 1 .AND. cdft_control%nreused .LT. cdft_control%max_reuse) THEN
    1135           0 :                reuse_precond = .TRUE.
    1136           0 :                cdft_control%nreused = cdft_control%nreused + 1
    1137             :             ELSE
    1138           0 :                reuse_precond = .FALSE.
    1139           0 :                cdft_control%nreused = 0
    1140             :             END IF
    1141             :          END IF
    1142             :          ! Update history purging counters
    1143         512 :          IF (first_iteration .AND. cdft_control%purge_history) THEN
    1144           0 :             cdft_control%istep = cdft_control%istep + 1
    1145           0 :             IF (scf_env%outer_scf%iter_count .GT. 1) THEN
    1146           0 :                cdft_control%nbad_conv = cdft_control%nbad_conv + 1
    1147           0 :                IF (cdft_control%nbad_conv .GE. cdft_control%purge_freq .AND. &
    1148             :                    cdft_control%istep .GE. cdft_control%purge_offset) THEN
    1149           0 :                   cdft_control%nbad_conv = 0
    1150           0 :                   cdft_control%istep = 0
    1151           0 :                   cdft_control%should_purge = .TRUE.
    1152             :                END IF
    1153             :             END IF
    1154             :          END IF
    1155         512 :          first_iteration = .FALSE.
    1156             :          ! Change outer_scf settings to CDFT settings
    1157         512 :          CALL outer_loop_switch(scf_env, scf_control, cdft_control, ot2cdft)
    1158             :          CALL qs_scf_check_outer_exit(qs_env, scf_env, scf_control, should_stop, &
    1159         512 :                                       cdft_loop_converged, exit_cdft_loop)
    1160             :          CALL qs_scf_cdft_info(output_unit, scf_control, scf_env, cdft_control, &
    1161             :                                energy, cdft_control%total_steps, &
    1162         512 :                                should_stop, cdft_loop_converged, cdft_loop=.TRUE.)
    1163         512 :          IF (exit_cdft_loop) EXIT cdft_outer_loop
    1164             :          ! Check if the inverse Jacobian needs to be calculated
    1165         186 :          CALL qs_calculate_inverse_jacobian(qs_env)
    1166             :          ! Check if a line search should be performed to find an optimal step size for the optimizer
    1167         186 :          CALL qs_cdft_line_search(qs_env)
    1168             :          ! Optimize constraint
    1169         186 :          CALL outer_loop_optimize(scf_env, scf_control)
    1170         186 :          CALL outer_loop_update_qs_env(qs_env, scf_env)
    1171         512 :          CALL qs_ks_did_change(ks_env, potential_changed=.TRUE.)
    1172             :       END DO cdft_outer_loop
    1173             : 
    1174         326 :       cdft_control%ienergy = cdft_control%ienergy + 1
    1175             : 
    1176             :       ! Store needed arrays for ET coupling calculation
    1177         326 :       IF (cdft_control%do_et) THEN
    1178         176 :          CALL get_qs_env(qs_env=qs_env, matrix_s=matrix_s, mos=mos)
    1179         176 :          nvar = SIZE(cdft_control%target)
    1180             :          ! Matrix representation of weight function
    1181         708 :          ALLOCATE (cdft_control%wmat(nvar))
    1182         356 :          DO ivar = 1, nvar
    1183         180 :             CALL dbcsr_init_p(cdft_control%wmat(ivar)%matrix)
    1184             :             CALL dbcsr_copy(cdft_control%wmat(ivar)%matrix, matrix_s(1)%matrix, &
    1185         180 :                             name="ET_RESTRAINT_MATRIX")
    1186         180 :             CALL dbcsr_set(cdft_control%wmat(ivar)%matrix, 0.0_dp)
    1187             :             CALL integrate_v_rspace(cdft_control%group(ivar)%weight, &
    1188             :                                     hmat=cdft_control%wmat(ivar), qs_env=qs_env, &
    1189             :                                     calculate_forces=.FALSE., &
    1190         356 :                                     gapw=dft_control%qs_control%gapw)
    1191             :          END DO
    1192             :          ! Overlap matrix
    1193         176 :          CALL dbcsr_init_p(cdft_control%matrix_s%matrix)
    1194             :          CALL dbcsr_copy(cdft_control%matrix_s%matrix, matrix_s(1)%matrix, &
    1195         176 :                          name="OVERLAP")
    1196             :          ! Molecular orbital coefficients
    1197         176 :          NULLIFY (cdft_control%mo_coeff)
    1198         880 :          ALLOCATE (cdft_control%mo_coeff(dft_control%nspins))
    1199         528 :          DO ispin = 1, dft_control%nspins
    1200             :             CALL cp_fm_create(matrix=cdft_control%mo_coeff(ispin), &
    1201             :                               matrix_struct=qs_env%mos(ispin)%mo_coeff%matrix_struct, &
    1202         352 :                               name="MO_COEFF_A"//TRIM(ADJUSTL(cp_to_string(ispin)))//"MATRIX")
    1203             :             CALL cp_fm_to_fm(qs_env%mos(ispin)%mo_coeff, &
    1204         528 :                              cdft_control%mo_coeff(ispin))
    1205             :          END DO
    1206             :          ! Density matrix
    1207         176 :          IF (cdft_control%calculate_metric) THEN
    1208          24 :             CALL get_qs_env(qs_env, rho=rho)
    1209          24 :             CALL qs_rho_get(rho, rho_ao=rho_ao)
    1210         120 :             ALLOCATE (cdft_control%matrix_p(dft_control%nspins))
    1211          72 :             DO ispin = 1, dft_control%nspins
    1212          48 :                NULLIFY (cdft_control%matrix_p(ispin)%matrix)
    1213          48 :                CALL dbcsr_init_p(cdft_control%matrix_p(ispin)%matrix)
    1214             :                CALL dbcsr_copy(cdft_control%matrix_p(ispin)%matrix, rho_ao(ispin)%matrix, &
    1215          72 :                                name="DENSITY MATRIX")
    1216             :             END DO
    1217             :          END IF
    1218             :          ! Copy occupation numbers if non-uniform occupation
    1219         176 :          uniform_occupation = .TRUE.
    1220         528 :          DO ispin = 1, dft_control%nspins
    1221         352 :             CALL get_mo_set(mo_set=mos(ispin), uniform_occupation=my_uocc)
    1222         584 :             uniform_occupation = uniform_occupation .AND. my_uocc
    1223             :          END DO
    1224         176 :          IF (.NOT. uniform_occupation) THEN
    1225         140 :             ALLOCATE (cdft_control%occupations(dft_control%nspins))
    1226          84 :             DO ispin = 1, dft_control%nspins
    1227             :                CALL get_mo_set(mo_set=mos(ispin), &
    1228             :                                nmo=nmo, &
    1229          56 :                                occupation_numbers=mo_occupations)
    1230         168 :                ALLOCATE (cdft_control%occupations(ispin)%array(nmo))
    1231         588 :                cdft_control%occupations(ispin)%array(1:nmo) = mo_occupations(1:nmo)
    1232             :             END DO
    1233             :          END IF
    1234             :       END IF
    1235             : 
    1236             :       ! Deallocate constraint storage if forces are not needed
    1237             :       ! In case of a simulation with multiple force_evals,
    1238             :       ! deallocate only if weight function should not be copied to different force_evals
    1239         326 :       IF (.NOT. (cdft_control%save_pot .OR. cdft_control%transfer_pot)) THEN
    1240         148 :          CALL get_qs_env(qs_env, pw_env=pw_env)
    1241         148 :          CALL pw_env_get(pw_env, auxbas_pw_pool=auxbas_pw_pool)
    1242         308 :          DO iatom = 1, SIZE(cdft_control%group)
    1243         160 :             CALL auxbas_pw_pool%give_back_pw(cdft_control%group(iatom)%weight)
    1244         308 :             DEALLOCATE (cdft_control%group(iatom)%weight)
    1245             :          END DO
    1246         148 :          IF (cdft_control%atomic_charges) THEN
    1247         256 :             DO iatom = 1, cdft_control%natoms
    1248         256 :                CALL auxbas_pw_pool%give_back_pw(cdft_control%charge(iatom))
    1249             :             END DO
    1250          84 :             DEALLOCATE (cdft_control%charge)
    1251             :          END IF
    1252         148 :          IF (cdft_control%type == outer_scf_becke_constraint .AND. &
    1253             :              cdft_control%becke_control%cavity_confine) THEN
    1254         120 :             IF (.NOT. ASSOCIATED(cdft_control%becke_control%cavity_mat)) THEN
    1255         110 :                CALL auxbas_pw_pool%give_back_pw(cdft_control%becke_control%cavity)
    1256             :             ELSE
    1257          10 :                DEALLOCATE (cdft_control%becke_control%cavity_mat)
    1258             :             END IF
    1259          28 :          ELSE IF (cdft_control%type == outer_scf_hirshfeld_constraint) THEN
    1260          20 :             IF (ASSOCIATED(cdft_control%hirshfeld_control%hirshfeld_env%fnorm)) THEN
    1261           0 :                CALL auxbas_pw_pool%give_back_pw(cdft_control%hirshfeld_control%hirshfeld_env%fnorm)
    1262             :             END IF
    1263             :          END IF
    1264         148 :          IF (ASSOCIATED(cdft_control%charges_fragment)) DEALLOCATE (cdft_control%charges_fragment)
    1265         148 :          cdft_control%need_pot = .TRUE.
    1266         148 :          cdft_control%external_control = .FALSE.
    1267             :       END IF
    1268             : 
    1269         326 :       CALL timestop(handle)
    1270             : 
    1271         326 :    END SUBROUTINE cdft_scf
    1272             : 
    1273             : ! **************************************************************************************************
    1274             : !> \brief perform cleanup operations for cdft_control
    1275             : !> \param cdft_control container for the external CDFT SCF loop variables
    1276             : !> \par History
    1277             : !>      12.2015 created [Nico Holmberg]
    1278             : !> \author Nico Holmberg
    1279             : ! **************************************************************************************************
    1280         326 :    SUBROUTINE cdft_control_cleanup(cdft_control)
    1281             :       TYPE(cdft_control_type), POINTER                   :: cdft_control
    1282             : 
    1283         326 :       IF (ASSOCIATED(cdft_control%constraint%variables)) &
    1284         326 :          DEALLOCATE (cdft_control%constraint%variables)
    1285         326 :       IF (ASSOCIATED(cdft_control%constraint%count)) &
    1286         326 :          DEALLOCATE (cdft_control%constraint%count)
    1287         326 :       IF (ASSOCIATED(cdft_control%constraint%gradient)) &
    1288         326 :          DEALLOCATE (cdft_control%constraint%gradient)
    1289         326 :       IF (ASSOCIATED(cdft_control%constraint%energy)) &
    1290         326 :          DEALLOCATE (cdft_control%constraint%energy)
    1291         326 :       IF (ASSOCIATED(cdft_control%constraint%inv_jacobian) .AND. &
    1292             :           cdft_control%constraint%deallocate_jacobian) &
    1293           4 :          DEALLOCATE (cdft_control%constraint%inv_jacobian)
    1294             : 
    1295         326 :    END SUBROUTINE cdft_control_cleanup
    1296             : 
    1297             : ! **************************************************************************************************
    1298             : !> \brief Calculates the finite difference inverse Jacobian
    1299             : !> \param qs_env the qs_environment_type where to compute the Jacobian
    1300             : !> \par History
    1301             : !>      01.2017 created [Nico Holmberg]
    1302             : ! **************************************************************************************************
    1303         186 :    SUBROUTINE qs_calculate_inverse_jacobian(qs_env)
    1304             :       TYPE(qs_environment_type), POINTER                 :: qs_env
    1305             : 
    1306             :       CHARACTER(LEN=*), PARAMETER :: routineN = 'qs_calculate_inverse_jacobian'
    1307             : 
    1308             :       CHARACTER(len=default_path_length)                 :: project_name
    1309             :       INTEGER                                            :: counter, handle, i, ispin, iter_count, &
    1310             :                                                             iwork, j, max_scf, nspins, nsteps, &
    1311             :                                                             nvar, nwork, output_unit, pwork, &
    1312             :                                                             tsteps, twork
    1313             :       LOGICAL                                            :: converged, explicit_jacobian, &
    1314             :                                                             should_build, should_stop, &
    1315             :                                                             use_md_history
    1316             :       REAL(KIND=dp)                                      :: inv_error, step_size
    1317         186 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:)           :: coeff, dh, step_multiplier
    1318         186 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :)        :: jacobian
    1319         186 :       REAL(KIND=dp), DIMENSION(:), POINTER               :: energy
    1320         186 :       REAL(KIND=dp), DIMENSION(:, :), POINTER            :: gradient, inv_jacobian
    1321             :       TYPE(cdft_control_type), POINTER                   :: cdft_control
    1322             :       TYPE(cp_logger_type), POINTER                      :: logger, tmp_logger
    1323         186 :       TYPE(dbcsr_p_type), DIMENSION(:), POINTER          :: p_rmpv
    1324         186 :       TYPE(dbcsr_p_type), DIMENSION(:, :), POINTER       :: rho_ao_kp
    1325             :       TYPE(dft_control_type), POINTER                    :: dft_control
    1326         186 :       TYPE(mo_set_type), ALLOCATABLE, DIMENSION(:)       :: mos_stashed
    1327         186 :       TYPE(mo_set_type), DIMENSION(:), POINTER           :: mos
    1328             :       TYPE(mp_para_env_type), POINTER                    :: para_env
    1329             :       TYPE(qs_energy_type), POINTER                      :: energy_qs
    1330             :       TYPE(qs_ks_env_type), POINTER                      :: ks_env
    1331             :       TYPE(qs_rho_type), POINTER                         :: rho
    1332             :       TYPE(qs_scf_env_type), POINTER                     :: scf_env
    1333             :       TYPE(scf_control_type), POINTER                    :: scf_control
    1334             : 
    1335         186 :       NULLIFY (energy, gradient, p_rmpv, rho_ao_kp, mos, rho, &
    1336         186 :                ks_env, scf_env, scf_control, dft_control, cdft_control, &
    1337         186 :                inv_jacobian, para_env, tmp_logger, energy_qs)
    1338         372 :       logger => cp_get_default_logger()
    1339             : 
    1340         186 :       CPASSERT(ASSOCIATED(qs_env))
    1341             :       CALL get_qs_env(qs_env, scf_env=scf_env, ks_env=ks_env, &
    1342             :                       scf_control=scf_control, mos=mos, rho=rho, &
    1343             :                       dft_control=dft_control, &
    1344         186 :                       para_env=para_env, energy=energy_qs)
    1345         186 :       explicit_jacobian = .FALSE.
    1346         186 :       should_build = .FALSE.
    1347         186 :       use_md_history = .FALSE.
    1348         186 :       iter_count = scf_env%outer_scf%iter_count
    1349             :       ! Quick exit if optimizer does not require Jacobian
    1350         186 :       IF (.NOT. ASSOCIATED(scf_control%outer_scf%cdft_opt_control)) RETURN
    1351             :       ! Check if Jacobian should be calculated and initialize
    1352         118 :       CALL timeset(routineN, handle)
    1353         118 :       CALL initialize_inverse_jacobian(scf_control, scf_env, explicit_jacobian, should_build, used_history)
    1354         118 :       IF (scf_control%outer_scf%cdft_opt_control%jacobian_restart) THEN
    1355             :          ! Restart from previously calculated inverse Jacobian
    1356           6 :          should_build = .FALSE.
    1357           6 :          CALL restart_inverse_jacobian(qs_env)
    1358             :       END IF
    1359         118 :       IF (should_build) THEN
    1360          78 :          scf_env%outer_scf%deallocate_jacobian = .FALSE.
    1361             :          ! Actually need to (re)build the Jacobian
    1362          78 :          IF (explicit_jacobian) THEN
    1363             :             ! Build Jacobian with finite differences
    1364          62 :             cdft_control => dft_control%qs_control%cdft_control
    1365          62 :             IF (.NOT. ASSOCIATED(cdft_control)) &
    1366             :                CALL cp_abort(__LOCATION__, &
    1367             :                              "Optimizers that need the explicit Jacobian can"// &
    1368           0 :                              " only be used together with a valid CDFT constraint.")
    1369             :             ! Redirect output from Jacobian calculation to a new file by creating a temporary logger
    1370          62 :             project_name = logger%iter_info%project_name
    1371          62 :             CALL create_tmp_logger(para_env, project_name, "-JacobianInfo.out", output_unit, tmp_logger)
    1372             :             ! Save last converged state so we can roll back to it (mo_coeff and some outer_loop variables)
    1373          62 :             nspins = dft_control%nspins
    1374         310 :             ALLOCATE (mos_stashed(nspins))
    1375         186 :             DO ispin = 1, nspins
    1376         186 :                CALL duplicate_mo_set(mos_stashed(ispin), mos(ispin))
    1377             :             END DO
    1378          62 :             CALL qs_rho_get(rho, rho_ao_kp=rho_ao_kp)
    1379          62 :             p_rmpv => rho_ao_kp(:, 1)
    1380             :             ! Allocate work
    1381          62 :             nvar = SIZE(scf_env%outer_scf%variables, 1)
    1382          62 :             max_scf = scf_control%outer_scf%max_scf + 1
    1383         248 :             ALLOCATE (gradient(nvar, max_scf))
    1384        1310 :             gradient = scf_env%outer_scf%gradient
    1385         186 :             ALLOCATE (energy(max_scf))
    1386         594 :             energy = scf_env%outer_scf%energy
    1387         248 :             ALLOCATE (jacobian(nvar, nvar))
    1388         282 :             jacobian = 0.0_dp
    1389          62 :             nsteps = cdft_control%total_steps
    1390             :             ! Setup finite difference scheme
    1391          62 :             CALL prepare_jacobian_stencil(qs_env, output_unit, nwork, pwork, coeff, step_multiplier, dh)
    1392          62 :             twork = pwork - nwork
    1393         148 :             DO i = 1, nvar
    1394         282 :                jacobian(i, :) = coeff(0)*scf_env%outer_scf%gradient(i, iter_count)
    1395             :             END DO
    1396             :             ! Calculate the Jacobian by perturbing each Lagrangian and recalculating the energy self-consistently
    1397          62 :             CALL cp_add_default_logger(tmp_logger)
    1398         148 :             DO i = 1, nvar
    1399          86 :                IF (output_unit > 0) THEN
    1400          43 :                   WRITE (output_unit, FMT="(A)") " "
    1401          43 :                   WRITE (output_unit, FMT="(A)") " #####################################"
    1402             :                   WRITE (output_unit, '(A,I3,A,I3,A)') &
    1403          43 :                      " ###  Constraint        ", i, " of ", nvar, " ###"
    1404          43 :                   WRITE (output_unit, FMT="(A)") " #####################################"
    1405             :                END IF
    1406          86 :                counter = 0
    1407         332 :                DO iwork = nwork, pwork
    1408         184 :                   IF (iwork == 0) CYCLE
    1409          98 :                   counter = counter + 1
    1410          98 :                   IF (output_unit > 0) THEN
    1411          49 :                      WRITE (output_unit, FMT="(A)") " #####################################"
    1412             :                      WRITE (output_unit, '(A,I3,A,I3,A)') &
    1413          49 :                         " ###  Energy evaluation ", counter, " of ", twork, " ###"
    1414          49 :                      WRITE (output_unit, FMT="(A)") " #####################################"
    1415             :                   END IF
    1416          98 :                   IF (SIZE(scf_control%outer_scf%cdft_opt_control%jacobian_step) == 1) THEN
    1417          90 :                      step_size = scf_control%outer_scf%cdft_opt_control%jacobian_step(1)
    1418             :                   ELSE
    1419           8 :                      step_size = scf_control%outer_scf%cdft_opt_control%jacobian_step(i)
    1420             :                   END IF
    1421         244 :                   scf_env%outer_scf%variables(:, iter_count + 1) = scf_env%outer_scf%variables(:, iter_count)
    1422             :                   scf_env%outer_scf%variables(i, iter_count + 1) = scf_env%outer_scf%variables(i, iter_count) + &
    1423          98 :                                                                    step_multiplier(iwork)*step_size
    1424          98 :                   CALL outer_loop_update_qs_env(qs_env, scf_env)
    1425          98 :                   CALL qs_ks_did_change(ks_env, potential_changed=.TRUE.)
    1426          98 :                   CALL outer_loop_switch(scf_env, scf_control, cdft_control, cdft2ot)
    1427             :                   CALL scf_env_do_scf(scf_env=scf_env, scf_control=scf_control, qs_env=qs_env, &
    1428          98 :                                       converged=converged, should_stop=should_stop, total_scf_steps=tsteps)
    1429          98 :                   CALL outer_loop_switch(scf_env, scf_control, cdft_control, ot2cdft)
    1430             :                   ! Update (iter_count + 1) element of gradient and print constraint info
    1431          98 :                   scf_env%outer_scf%iter_count = scf_env%outer_scf%iter_count + 1
    1432          98 :                   CALL outer_loop_gradient(qs_env, scf_env)
    1433             :                   CALL qs_scf_cdft_info(output_unit, scf_control, scf_env, cdft_control, &
    1434             :                                         energy_qs, cdft_control%total_steps, &
    1435          98 :                                         should_stop=.FALSE., outer_loop_converged=.FALSE., cdft_loop=.FALSE.)
    1436          98 :                   scf_env%outer_scf%iter_count = scf_env%outer_scf%iter_count - 1
    1437             :                   ! Update Jacobian
    1438         244 :                   DO j = 1, nvar
    1439         244 :                      jacobian(j, i) = jacobian(j, i) + coeff(iwork)*scf_env%outer_scf%gradient(j, iter_count + 1)
    1440             :                   END DO
    1441             :                   ! Reset everything to last converged state
    1442         244 :                   scf_env%outer_scf%variables(:, iter_count + 1) = 0.0_dp
    1443        2026 :                   scf_env%outer_scf%gradient = gradient
    1444         878 :                   scf_env%outer_scf%energy = energy
    1445          98 :                   cdft_control%total_steps = nsteps
    1446         294 :                   DO ispin = 1, nspins
    1447         196 :                      CALL deallocate_mo_set(mos(ispin))
    1448         196 :                      CALL duplicate_mo_set(mos(ispin), mos_stashed(ispin))
    1449             :                      CALL calculate_density_matrix(mos(ispin), &
    1450         294 :                                                    p_rmpv(ispin)%matrix)
    1451             :                   END DO
    1452          98 :                   CALL qs_rho_update_rho(rho, qs_env=qs_env)
    1453         368 :                   CALL qs_ks_did_change(qs_env%ks_env, rho_changed=.TRUE.)
    1454             :                END DO
    1455             :             END DO
    1456          62 :             CALL cp_rm_default_logger()
    1457          62 :             CALL cp_logger_release(tmp_logger)
    1458             :             ! Finalize and invert Jacobian
    1459         148 :             DO j = 1, nvar
    1460         282 :                DO i = 1, nvar
    1461         220 :                   jacobian(i, j) = jacobian(i, j)/dh(j)
    1462             :                END DO
    1463             :             END DO
    1464          62 :             IF (.NOT. ASSOCIATED(scf_env%outer_scf%inv_jacobian)) &
    1465         102 :                ALLOCATE (scf_env%outer_scf%inv_jacobian(nvar, nvar))
    1466          62 :             inv_jacobian => scf_env%outer_scf%inv_jacobian
    1467          62 :             CALL invert_matrix(jacobian, inv_jacobian, inv_error)
    1468          62 :             scf_control%outer_scf%cdft_opt_control%broyden_update = .FALSE.
    1469             :             ! Release temporary storage
    1470         186 :             DO ispin = 1, nspins
    1471         186 :                CALL deallocate_mo_set(mos_stashed(ispin))
    1472             :             END DO
    1473          62 :             DEALLOCATE (mos_stashed, jacobian, gradient, energy, coeff, step_multiplier, dh)
    1474         186 :             IF (output_unit > 0) THEN
    1475             :                WRITE (output_unit, FMT="(/,A)") &
    1476          31 :                   " ================================== JACOBIAN CALCULATED =================================="
    1477          31 :                CALL close_file(unit_number=output_unit)
    1478             :             END IF
    1479             :          ELSE
    1480             :             ! Build a strictly diagonal Jacobian from history and invert it
    1481          16 :             CALL build_diagonal_jacobian(qs_env, used_history)
    1482             :          END IF
    1483             :       END IF
    1484         118 :       IF (ASSOCIATED(scf_env%outer_scf%inv_jacobian) .AND. para_env%is_source()) THEN
    1485             :          ! Write restart file for inverse Jacobian
    1486          55 :          CALL print_inverse_jacobian(logger, scf_env%outer_scf%inv_jacobian, iter_count)
    1487             :       END IF
    1488             :       ! Update counter
    1489         118 :       scf_control%outer_scf%cdft_opt_control%ijacobian(1) = scf_control%outer_scf%cdft_opt_control%ijacobian(1) + 1
    1490         118 :       CALL timestop(handle)
    1491             : 
    1492         372 :    END SUBROUTINE qs_calculate_inverse_jacobian
    1493             : 
    1494             : ! **************************************************************************************************
    1495             : !> \brief Perform backtracking line search to find the optimal step size for the CDFT constraint
    1496             : !>        optimizer. Assumes that the CDFT gradient function is a smooth function of the constraint
    1497             : !>        variables.
    1498             : !> \param qs_env the qs_environment_type where to perform the line search
    1499             : !> \par History
    1500             : !>      02.2017 created [Nico Holmberg]
    1501             : ! **************************************************************************************************
    1502         186 :    SUBROUTINE qs_cdft_line_search(qs_env)
    1503             :       TYPE(qs_environment_type), POINTER                 :: qs_env
    1504             : 
    1505             :       CHARACTER(LEN=*), PARAMETER :: routineN = 'qs_cdft_line_search'
    1506             : 
    1507             :       CHARACTER(len=default_path_length)                 :: project_name
    1508             :       INTEGER                                            :: handle, i, ispin, iter_count, &
    1509             :                                                             max_linesearch, max_scf, nspins, &
    1510             :                                                             nsteps, nvar, output_unit, tsteps
    1511             :       LOGICAL :: continue_ls, continue_ls_exit, converged, do_linesearch, found_solution, &
    1512             :          reached_maxls, should_exit, should_stop, sign_changed
    1513         186 :       LOGICAL, ALLOCATABLE, DIMENSION(:)                 :: positive_sign
    1514             :       REAL(KIND=dp)                                      :: alpha, alpha_ls, factor, norm_ls
    1515         186 :       REAL(KIND=dp), DIMENSION(:), POINTER               :: energy
    1516         186 :       REAL(KIND=dp), DIMENSION(:, :), POINTER            :: gradient, inv_jacobian
    1517             :       REAL(KIND=dp), EXTERNAL                            :: dnrm2
    1518             :       TYPE(cdft_control_type), POINTER                   :: cdft_control
    1519             :       TYPE(cp_logger_type), POINTER                      :: logger, tmp_logger
    1520         186 :       TYPE(dbcsr_p_type), DIMENSION(:), POINTER          :: p_rmpv
    1521         186 :       TYPE(dbcsr_p_type), DIMENSION(:, :), POINTER       :: rho_ao_kp
    1522             :       TYPE(dft_control_type), POINTER                    :: dft_control
    1523         186 :       TYPE(mo_set_type), DIMENSION(:), POINTER           :: mos
    1524             :       TYPE(mp_para_env_type), POINTER                    :: para_env
    1525             :       TYPE(qs_energy_type), POINTER                      :: energy_qs
    1526             :       TYPE(qs_ks_env_type), POINTER                      :: ks_env
    1527             :       TYPE(qs_rho_type), POINTER                         :: rho
    1528             :       TYPE(qs_scf_env_type), POINTER                     :: scf_env
    1529             :       TYPE(scf_control_type), POINTER                    :: scf_control
    1530             : 
    1531         186 :       CALL timeset(routineN, handle)
    1532             : 
    1533         186 :       NULLIFY (energy, gradient, p_rmpv, rho_ao_kp, mos, rho, &
    1534         186 :                ks_env, scf_env, scf_control, dft_control, &
    1535         186 :                cdft_control, inv_jacobian, para_env, &
    1536         186 :                tmp_logger, energy_qs)
    1537         186 :       logger => cp_get_default_logger()
    1538             : 
    1539         186 :       CPASSERT(ASSOCIATED(qs_env))
    1540             :       CALL get_qs_env(qs_env, scf_env=scf_env, ks_env=ks_env, &
    1541             :                       scf_control=scf_control, mos=mos, rho=rho, &
    1542             :                       dft_control=dft_control, &
    1543         186 :                       para_env=para_env, energy=energy_qs)
    1544         186 :       do_linesearch = .FALSE.
    1545         186 :       SELECT CASE (scf_control%outer_scf%optimizer)
    1546             :       CASE DEFAULT
    1547             :          do_linesearch = .FALSE.
    1548             :       CASE (outer_scf_optimizer_newton_ls)
    1549          24 :          do_linesearch = .TRUE.
    1550             :       CASE (outer_scf_optimizer_broyden)
    1551         186 :          SELECT CASE (scf_control%outer_scf%cdft_opt_control%broyden_type)
    1552             :          CASE (broyden_type_1, broyden_type_2, broyden_type_1_explicit, broyden_type_2_explicit)
    1553           0 :             do_linesearch = .FALSE.
    1554             :          CASE (broyden_type_1_ls, broyden_type_1_explicit_ls, broyden_type_2_ls, broyden_type_2_explicit_ls)
    1555           0 :             cdft_control => dft_control%qs_control%cdft_control
    1556           0 :             IF (.NOT. ASSOCIATED(cdft_control)) &
    1557             :                CALL cp_abort(__LOCATION__, &
    1558             :                              "Optimizers that perform a line search can"// &
    1559           0 :                              " only be used together with a valid CDFT constraint")
    1560           0 :             IF (ASSOCIATED(scf_env%outer_scf%inv_jacobian)) &
    1561          24 :                do_linesearch = .TRUE.
    1562             :          END SELECT
    1563             :       END SELECT
    1564             :       IF (do_linesearch) THEN
    1565           8 :          BLOCK
    1566           8 :             TYPE(mo_set_type), DIMENSION(:), ALLOCATABLE :: mos_ls, mos_stashed
    1567           8 :             cdft_control => dft_control%qs_control%cdft_control
    1568           8 :             IF (.NOT. ASSOCIATED(cdft_control)) &
    1569             :                CALL cp_abort(__LOCATION__, &
    1570             :                              "Optimizers that perform a line search can"// &
    1571           0 :                              " only be used together with a valid CDFT constraint")
    1572           8 :             CPASSERT(ASSOCIATED(scf_env%outer_scf%inv_jacobian))
    1573           8 :             CPASSERT(ASSOCIATED(scf_control%outer_scf%cdft_opt_control))
    1574           8 :             alpha = scf_control%outer_scf%cdft_opt_control%newton_step_save
    1575           8 :             iter_count = scf_env%outer_scf%iter_count
    1576             :             ! Redirect output from line search procedure to a new file by creating a temporary logger
    1577           8 :             project_name = logger%iter_info%project_name
    1578           8 :             CALL create_tmp_logger(para_env, project_name, "-LineSearch.out", output_unit, tmp_logger)
    1579             :             ! Save last converged state so we can roll back to it (mo_coeff and some outer_loop variables)
    1580           8 :             nspins = dft_control%nspins
    1581          40 :             ALLOCATE (mos_stashed(nspins))
    1582          24 :             DO ispin = 1, nspins
    1583          24 :                CALL duplicate_mo_set(mos_stashed(ispin), mos(ispin))
    1584             :             END DO
    1585           8 :             CALL qs_rho_get(rho, rho_ao_kp=rho_ao_kp)
    1586           8 :             p_rmpv => rho_ao_kp(:, 1)
    1587           8 :             nsteps = cdft_control%total_steps
    1588             :             ! Allocate work
    1589           8 :             nvar = SIZE(scf_env%outer_scf%variables, 1)
    1590           8 :             max_scf = scf_control%outer_scf%max_scf + 1
    1591           8 :             max_linesearch = scf_control%outer_scf%cdft_opt_control%max_ls
    1592           8 :             continue_ls = scf_control%outer_scf%cdft_opt_control%continue_ls
    1593           8 :             factor = scf_control%outer_scf%cdft_opt_control%factor_ls
    1594           8 :             continue_ls_exit = .FALSE.
    1595           8 :             found_solution = .FALSE.
    1596          32 :             ALLOCATE (gradient(nvar, max_scf))
    1597         104 :             gradient = scf_env%outer_scf%gradient
    1598          24 :             ALLOCATE (energy(max_scf))
    1599          56 :             energy = scf_env%outer_scf%energy
    1600           8 :             reached_maxls = .FALSE.
    1601             :             ! Broyden optimizers: perform update of inv_jacobian if necessary
    1602           8 :             IF (scf_control%outer_scf%cdft_opt_control%broyden_update) THEN
    1603           0 :                CALL outer_loop_optimize(scf_env, scf_control)
    1604             :                ! Reset the variables and prevent a reupdate of inv_jacobian
    1605           0 :                scf_env%outer_scf%variables(:, iter_count + 1) = 0
    1606           0 :                scf_control%outer_scf%cdft_opt_control%broyden_update = .FALSE.
    1607             :             END IF
    1608             :             ! Print some info
    1609           8 :             IF (output_unit > 0) THEN
    1610             :                WRITE (output_unit, FMT="(/,A)") &
    1611           4 :                   " ================================== LINE SEARCH STARTED  =================================="
    1612             :                WRITE (output_unit, FMT="(A,I5,A)") &
    1613           4 :                   " Evaluating optimal step size for optimizer using a maximum of", max_linesearch, " steps"
    1614           4 :                IF (continue_ls) THEN
    1615             :                   WRITE (output_unit, FMT="(A)") &
    1616           2 :                      " Line search continues until best step size is found or max steps are reached"
    1617             :                END IF
    1618             :                WRITE (output_unit, '(/,A,F5.3)') &
    1619           4 :                   " Initial step size: ", alpha
    1620             :                WRITE (output_unit, '(/,A,F5.3)') &
    1621           4 :                   " Step size update factor: ", factor
    1622             :                WRITE (output_unit, '(/,A,I10,A,I10)') &
    1623           4 :                   " Energy evaluation: ", cdft_control%ienergy, ", CDFT SCF iteration: ", iter_count
    1624             :             END IF
    1625             :             ! Perform backtracking line search
    1626           8 :             CALL cp_add_default_logger(tmp_logger)
    1627          16 :             DO i = 1, max_linesearch
    1628          16 :                IF (output_unit > 0) THEN
    1629           8 :                   WRITE (output_unit, FMT="(A)") " "
    1630           8 :                   WRITE (output_unit, FMT="(A)") " #####################################"
    1631             :                   WRITE (output_unit, '(A,I10,A)') &
    1632           8 :                      " ###  Line search step: ", i, " ###"
    1633           8 :                   WRITE (output_unit, FMT="(A)") " #####################################"
    1634             :                END IF
    1635          16 :                inv_jacobian => scf_env%outer_scf%inv_jacobian
    1636             :                ! Newton update of CDFT variables with a step size of alpha
    1637             :                scf_env%outer_scf%variables(:, iter_count + 1) = scf_env%outer_scf%variables(:, iter_count) - alpha* &
    1638         144 :                                                                 MATMUL(inv_jacobian, scf_env%outer_scf%gradient(:, iter_count))
    1639             :                ! With updated CDFT variables, perform SCF
    1640          16 :                CALL outer_loop_update_qs_env(qs_env, scf_env)
    1641          16 :                CALL qs_ks_did_change(ks_env, potential_changed=.TRUE.)
    1642          16 :                CALL outer_loop_switch(scf_env, scf_control, cdft_control, cdft2ot)
    1643             :                CALL scf_env_do_scf(scf_env=scf_env, scf_control=scf_control, qs_env=qs_env, &
    1644          16 :                                    converged=converged, should_stop=should_stop, total_scf_steps=tsteps)
    1645          16 :                CALL outer_loop_switch(scf_env, scf_control, cdft_control, ot2cdft)
    1646             :                ! Update (iter_count + 1) element of gradient and print constraint info
    1647          16 :                scf_env%outer_scf%iter_count = scf_env%outer_scf%iter_count + 1
    1648          16 :                CALL outer_loop_gradient(qs_env, scf_env)
    1649             :                CALL qs_scf_cdft_info(output_unit, scf_control, scf_env, cdft_control, &
    1650             :                                      energy_qs, cdft_control%total_steps, &
    1651          16 :                                      should_stop=.FALSE., outer_loop_converged=.FALSE., cdft_loop=.FALSE.)
    1652          16 :                scf_env%outer_scf%iter_count = scf_env%outer_scf%iter_count - 1
    1653             :                ! Store sign of initial gradient for each variable for continue_ls
    1654          16 :                IF (continue_ls .AND. .NOT. ALLOCATED(positive_sign)) THEN
    1655          12 :                   ALLOCATE (positive_sign(nvar))
    1656           8 :                   DO ispin = 1, nvar
    1657           8 :                      positive_sign(ispin) = scf_env%outer_scf%gradient(ispin, iter_count + 1) .GE. 0.0_dp
    1658             :                   END DO
    1659             :                END IF
    1660             :                ! Check if the L2 norm of the gradient decreased
    1661          16 :                inv_jacobian => scf_env%outer_scf%inv_jacobian
    1662          16 :                IF (dnrm2(nvar, scf_env%outer_scf%gradient(:, iter_count + 1), 1) .LT. &
    1663             :                    dnrm2(nvar, scf_env%outer_scf%gradient(:, iter_count), 1)) THEN
    1664             :                   ! Optimal step size found
    1665          14 :                   IF (.NOT. continue_ls) THEN
    1666             :                      should_exit = .TRUE.
    1667             :                   ELSE
    1668             :                      ! But line search continues for at least one more iteration in an attempt to find a better solution
    1669             :                      ! if max number of steps is not exceeded
    1670          10 :                      IF (found_solution) THEN
    1671             :                         ! Check if the norm also decreased w.r.t. to previously found solution
    1672           6 :                         IF (dnrm2(nvar, scf_env%outer_scf%gradient(:, iter_count + 1), 1) .GT. norm_ls) THEN
    1673             :                            ! Norm increased => accept previous solution and exit
    1674             :                            continue_ls_exit = .TRUE.
    1675             :                         END IF
    1676             :                      END IF
    1677             :                      ! Store current state and the value of alpha
    1678          10 :                      IF (.NOT. continue_ls_exit) THEN
    1679          10 :                         should_exit = .FALSE.
    1680          10 :                         alpha_ls = alpha
    1681          10 :                         found_solution = .TRUE.
    1682          10 :                         norm_ls = dnrm2(nvar, scf_env%outer_scf%gradient(:, iter_count + 1), 1)
    1683             :                         ! Check if the sign of the gradient has changed for all variables (w.r.t initial gradient)
    1684             :                         ! In this case we should exit because further line search steps will just increase the norm
    1685          10 :                         sign_changed = .TRUE.
    1686          20 :                         DO ispin = 1, nvar
    1687             :                            sign_changed = sign_changed .AND. (positive_sign(ispin) .NEQV. &
    1688          28 :                                                               scf_env%outer_scf%gradient(ispin, iter_count + 1) .GE. 0.0_dp)
    1689             :                         END DO
    1690          10 :                         IF (.NOT. ALLOCATED(mos_ls)) THEN
    1691          16 :                            ALLOCATE (mos_ls(nspins))
    1692             :                         ELSE
    1693          18 :                            DO ispin = 1, nspins
    1694          18 :                               CALL deallocate_mo_set(mos_ls(ispin))
    1695             :                            END DO
    1696             :                         END IF
    1697          30 :                         DO ispin = 1, nspins
    1698          30 :                            CALL duplicate_mo_set(mos_ls(ispin), mos(ispin))
    1699             :                         END DO
    1700          10 :                         alpha = alpha*factor
    1701             :                         ! Exit on last iteration
    1702          10 :                         IF (i == max_linesearch) continue_ls_exit = .TRUE.
    1703             :                         ! Exit if constraint target is satisfied to requested tolerance
    1704          30 :                         IF (SQRT(MAXVAL(scf_env%outer_scf%gradient(:, scf_env%outer_scf%iter_count + 1)**2)) .LT. &
    1705             :                             scf_control%outer_scf%eps_scf) &
    1706           2 :                            continue_ls_exit = .TRUE.
    1707             :                         ! Exit if line search jumped over the optimal step length
    1708          10 :                         IF (sign_changed) continue_ls_exit = .TRUE.
    1709             :                      END IF
    1710             :                   END IF
    1711             :                ELSE
    1712             :                   ! Gradient increased => alpha is too large (if the gradient function is smooth)
    1713           2 :                   should_exit = .FALSE.
    1714             :                   ! Update alpha using Armijo's scheme
    1715           2 :                   alpha = alpha*factor
    1716             :                END IF
    1717          16 :                IF (continue_ls_exit) THEN
    1718             :                   ! Continuation of line search did not yield a better alpha, use previously located solution and exit
    1719           4 :                   alpha = alpha_ls
    1720          12 :                   DO ispin = 1, nspins
    1721           8 :                      CALL deallocate_mo_set(mos(ispin))
    1722           8 :                      CALL duplicate_mo_set(mos(ispin), mos_ls(ispin))
    1723             :                      CALL calculate_density_matrix(mos(ispin), &
    1724           8 :                                                    p_rmpv(ispin)%matrix)
    1725          12 :                      CALL deallocate_mo_set(mos_ls(ispin))
    1726             :                   END DO
    1727           4 :                   CALL qs_rho_update_rho(rho, qs_env=qs_env)
    1728           4 :                   CALL qs_ks_did_change(qs_env%ks_env, rho_changed=.TRUE.)
    1729           4 :                   DEALLOCATE (mos_ls)
    1730             :                   should_exit = .TRUE.
    1731             :                END IF
    1732             :                ! Reached max steps and SCF converged: continue with last iterated step size
    1733          12 :                IF (.NOT. should_exit .AND. &
    1734             :                    (i == max_linesearch .AND. converged .AND. .NOT. found_solution)) THEN
    1735           0 :                   should_exit = .TRUE.
    1736           0 :                   reached_maxls = .TRUE.
    1737           0 :                   alpha = alpha*(1.0_dp/factor)
    1738             :                END IF
    1739             :                ! Reset outer SCF environment to last converged state
    1740          32 :                scf_env%outer_scf%variables(:, iter_count + 1) = 0.0_dp
    1741         208 :                scf_env%outer_scf%gradient = gradient
    1742         112 :                scf_env%outer_scf%energy = energy
    1743             :                ! Exit line search if a suitable step size was found
    1744          16 :                IF (should_exit) EXIT
    1745             :                ! Reset the electronic structure
    1746           8 :                cdft_control%total_steps = nsteps
    1747          24 :                DO ispin = 1, nspins
    1748          16 :                   CALL deallocate_mo_set(mos(ispin))
    1749          16 :                   CALL duplicate_mo_set(mos(ispin), mos_stashed(ispin))
    1750             :                   CALL calculate_density_matrix(mos(ispin), &
    1751          24 :                                                 p_rmpv(ispin)%matrix)
    1752             :                END DO
    1753           8 :                CALL qs_rho_update_rho(rho, qs_env=qs_env)
    1754          24 :                CALL qs_ks_did_change(qs_env%ks_env, rho_changed=.TRUE.)
    1755             :             END DO
    1756           8 :             scf_control%outer_scf%cdft_opt_control%newton_step = alpha
    1757           8 :             IF (.NOT. should_exit) THEN
    1758             :                CALL cp_warn(__LOCATION__, &
    1759           0 :                             "Line search did not converge. CDFT SCF proceeds with fixed step size.")
    1760           0 :                scf_control%outer_scf%cdft_opt_control%newton_step = scf_control%outer_scf%cdft_opt_control%newton_step_save
    1761             :             END IF
    1762           8 :             IF (reached_maxls) &
    1763             :                CALL cp_warn(__LOCATION__, &
    1764           0 :                             "Line search did not converge. CDFT SCF proceeds with lasted iterated step size.")
    1765           8 :             CALL cp_rm_default_logger()
    1766           8 :             CALL cp_logger_release(tmp_logger)
    1767             :             ! Release temporary storage
    1768          24 :             DO ispin = 1, nspins
    1769          24 :                CALL deallocate_mo_set(mos_stashed(ispin))
    1770             :             END DO
    1771           8 :             DEALLOCATE (mos_stashed, gradient, energy)
    1772           8 :             IF (ALLOCATED(positive_sign)) DEALLOCATE (positive_sign)
    1773          20 :             IF (output_unit > 0) THEN
    1774             :                WRITE (output_unit, FMT="(/,A)") &
    1775           4 :                   " ================================== LINE SEARCH COMPLETE =================================="
    1776           4 :                CALL close_file(unit_number=output_unit)
    1777             :             END IF
    1778             :          END BLOCK
    1779             :       END IF
    1780             : 
    1781         186 :       CALL timestop(handle)
    1782             : 
    1783         186 :    END SUBROUTINE qs_cdft_line_search
    1784             : 
    1785          16 : END MODULE qs_scf

Generated by: LCOV version 1.15