LCOV - code coverage report
Current view: top level - src - qs_scf.F (source / functions) Coverage Total Hit
Test: CP2K Regtests (git:c24029e) Lines: 91.6 % 776 711
Test Date: 2026-07-04 06:36:57 Functions: 100.0 % 8 8

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

Generated by: LCOV version 2.0-1