LCOV - code coverage report
Current view: top level - src - qs_scf.F (source / functions) Hit Total Coverage
Test: CP2K Regtests (git:2fce0f8) Lines: 649 710 91.4 %
Date: 2024-12-21 06:28:57 Functions: 8 8 100.0 %

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

Generated by: LCOV version 1.15