LCOV - code coverage report
Current view: top level - src - qs_ks_methods.F (source / functions) Coverage Total Hit
Test: CP2K Regtests (git:24d69ee) Lines: 92.9 % 759 705
Test Date: 2026-09-03 07:32:15 Functions: 100.0 % 7 7

            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 that build the Kohn-Sham matrix (i.e calculate the coulomb
      10              : !>        and xc parts
      11              : !> \author Fawzi Mohamed
      12              : !> \par History
      13              : !>      - 05.2002 moved from qs_scf (see there the history) [fawzi]
      14              : !>      - JGH [30.08.02] multi-grid arrays independent from density and potential
      15              : !>      - 10.2002 introduced pools, uses updated rho as input,
      16              : !>                removed most temporary variables, renamed may vars,
      17              : !>                began conversion to LSD [fawzi]
      18              : !>      - 10.2004 moved calculate_w_matrix here [Joost VandeVondele]
      19              : !>                introduced energy derivative wrt MOs [Joost VandeVondele]
      20              : !>      - SCCS implementation (16.10.2013,MK)
      21              : ! **************************************************************************************************
      22              : MODULE qs_ks_methods
      23              :    USE accint_weights_forces,           ONLY: accint_weight_force
      24              :    USE admm_dm_methods,                 ONLY: admm_dm_calc_rho_aux,&
      25              :                                               admm_dm_merge_ks_matrix
      26              :    USE admm_methods,                    ONLY: admm_mo_calc_rho_aux,&
      27              :                                               admm_mo_calc_rho_aux_kp,&
      28              :                                               admm_mo_merge_ks_matrix,&
      29              :                                               admm_update_ks_atom,&
      30              :                                               calc_admm_mo_derivatives,&
      31              :                                               calc_admm_ovlp_forces,&
      32              :                                               calc_admm_ovlp_forces_kp
      33              :    USE admm_types,                      ONLY: admm_type,&
      34              :                                               get_admm_env
      35              :    USE atomic_kind_types,               ONLY: atomic_kind_type,&
      36              :                                               get_atomic_kind_set
      37              :    USE cell_types,                      ONLY: cell_type
      38              :    USE cp_control_types,                ONLY: dft_control_type
      39              :    USE cp_dbcsr_api,                    ONLY: &
      40              :         dbcsr_add, dbcsr_copy, dbcsr_create, dbcsr_filter, dbcsr_get_info, dbcsr_multiply, &
      41              :         dbcsr_p_type, dbcsr_release, dbcsr_set, dbcsr_type, dbcsr_type_antisymmetric, &
      42              :         dbcsr_type_symmetric
      43              :    USE cp_dbcsr_cp2k_link,              ONLY: cp_dbcsr_alloc_block_from_nbl
      44              :    USE cp_dbcsr_operations,             ONLY: dbcsr_allocate_matrix_set,&
      45              :                                               dbcsr_copy_columns_hack
      46              :    USE cp_ddapc,                        ONLY: qs_ks_ddapc
      47              :    USE cp_fm_types,                     ONLY: cp_fm_type
      48              :    USE cp_log_handling,                 ONLY: cp_get_default_logger,&
      49              :                                               cp_logger_get_default_io_unit,&
      50              :                                               cp_logger_type
      51              :    USE cp_output_handling,              ONLY: cp_p_file,&
      52              :                                               cp_print_key_should_output
      53              :    USE dft_plus_u,                      ONLY: plus_u
      54              :    USE gapw_gspace_reconstruction,      ONLY: integrate_gapw_composite_vxc_gspace
      55              :    USE gce_methods,                     ONLY: planar_averaged_v_hartree_3d,&
      56              :                                               planar_counter_charge
      57              :    USE hartree_local_methods,           ONLY: Vh_1c_gg_integrals
      58              :    USE hartree_local_types,             ONLY: ecoul_1center_type
      59              :    USE hfx_ace_methods,                 ONLY: hfx_ace_ks_matrix
      60              :    USE hfx_admm_utils,                  ONLY: hfx_admm_init,&
      61              :                                               hfx_ks_matrix,&
      62              :                                               hfx_ks_matrix_kp
      63              :    USE input_constants,                 ONLY: do_ppl_grid,&
      64              :                                               outer_scf_becke_constraint,&
      65              :                                               outer_scf_hirshfeld_constraint,&
      66              :                                               smeagol_runtype_emtransport
      67              :    USE input_section_types,             ONLY: section_vals_get,&
      68              :                                               section_vals_get_subs_vals,&
      69              :                                               section_vals_type,&
      70              :                                               section_vals_val_get
      71              :    USE kg_correction,                   ONLY: kg_ekin_subset
      72              :    USE kinds,                           ONLY: default_string_length,&
      73              :                                               dp
      74              :    USE kpoint_types,                    ONLY: get_kpoint_info,&
      75              :                                               kpoint_type
      76              :    USE lri_environment_methods,         ONLY: v_int_ppl_energy
      77              :    USE lri_environment_types,           ONLY: lri_density_type,&
      78              :                                               lri_environment_type,&
      79              :                                               lri_kind_type
      80              :    USE mathlib,                         ONLY: abnormal_value
      81              :    USE message_passing,                 ONLY: mp_para_env_type
      82              :    USE particle_types,                  ONLY: particle_type
      83              :    USE pw_env_types,                    ONLY: pw_env_get,&
      84              :                                               pw_env_type
      85              :    USE pw_methods,                      ONLY: pw_axpy,&
      86              :                                               pw_copy,&
      87              :                                               pw_integral_ab,&
      88              :                                               pw_integrate_function,&
      89              :                                               pw_scale,&
      90              :                                               pw_transfer,&
      91              :                                               pw_zero
      92              :    USE pw_poisson_methods,              ONLY: pw_poisson_solve
      93              :    USE pw_poisson_types,                ONLY: pw_poisson_implicit,&
      94              :                                               pw_poisson_type
      95              :    USE pw_pool_types,                   ONLY: pw_pool_type
      96              :    USE pw_types,                        ONLY: pw_c1d_gs_type,&
      97              :                                               pw_r3d_rs_type
      98              :    USE qmmm_image_charge,               ONLY: add_image_pot_to_hartree_pot,&
      99              :                                               calculate_image_pot,&
     100              :                                               integrate_potential_devga_rspace
     101              :    USE qs_cdft_types,                   ONLY: cdft_control_type
     102              :    USE qs_cdft_utils,                   ONLY: cdft_constraint_print
     103              :    USE qs_charges_types,                ONLY: qs_charges_type
     104              :    USE qs_core_energies,                ONLY: calculate_ptrace
     105              :    USE qs_dftb_matrices,                ONLY: build_dftb_ks_matrix
     106              :    USE qs_efield_berry,                 ONLY: qs_efield_berry_phase
     107              :    USE qs_efield_local,                 ONLY: qs_efield_local_operator
     108              :    USE qs_energy_types,                 ONLY: qs_energy_type
     109              :    USE qs_environment_types,            ONLY: get_qs_env,&
     110              :                                               qs_environment_type
     111              :    USE qs_force_types,                  ONLY: qs_force_type
     112              :    USE qs_gapw_densities,               ONLY: prepare_gapw_den
     113              :    USE qs_harris_types,                 ONLY: harris_type
     114              :    USE qs_harris_utils,                 ONLY: harris_set_potentials
     115              :    USE qs_integrate_potential,          ONLY: integrate_ppl_rspace,&
     116              :                                               integrate_rho_nlcc,&
     117              :                                               integrate_v_core_rspace,&
     118              :                                               integrate_v_rspace
     119              :    USE qs_kind_types,                   ONLY: qs_kind_type
     120              :    USE qs_ks_apply_restraints,          ONLY: qs_ks_cdft_constraint,&
     121              :                                               qs_ks_mulliken_restraint,&
     122              :                                               qs_ks_s2_restraint
     123              :    USE qs_ks_atom,                      ONLY: update_ks_atom
     124              :    USE qs_ks_qmmm_methods,              ONLY: qmmm_calculate_energy,&
     125              :                                               qmmm_modify_hartree_pot
     126              :    USE qs_ks_types,                     ONLY: qs_ks_env_type,&
     127              :                                               set_ks_env
     128              :    USE qs_ks_utils,                     ONLY: &
     129              :         calc_v_sic_rspace, calculate_zmp_potential, compute_matrix_vxc, compute_matrix_vxc_kp, &
     130              :         get_embed_potential_energy, low_spin_roks, print_densities, print_detailed_energy, &
     131              :         sic_explicit_orbitals, sum_up_and_integrate
     132              :    USE qs_local_rho_types,              ONLY: local_rho_type
     133              :    USE qs_mo_types,                     ONLY: get_mo_set,&
     134              :                                               mo_set_type
     135              :    USE qs_neighbor_list_types,          ONLY: neighbor_list_set_p_type
     136              :    USE qs_rho0_ggrid,                   ONLY: integrate_vhg0_rspace
     137              :    USE qs_rho_types,                    ONLY: qs_rho_get,&
     138              :                                               qs_rho_type
     139              :    USE qs_sccs,                         ONLY: sccs
     140              :    USE qs_vxc,                          ONLY: qs_vxc_create
     141              :    USE qs_vxc_atom,                     ONLY: calculate_vxc_atom,&
     142              :                                               gapw_cdft_one_center
     143              :    USE rtp_admm_methods,                ONLY: rtp_admm_calc_rho_aux,&
     144              :                                               rtp_admm_merge_ks_matrix
     145              :    USE se_fock_matrix,                  ONLY: build_se_fock_matrix
     146              :    USE skala_gpw_functional,            ONLY: &
     147              :         ensure_native_skala_grid_scope, get_gauxc_section, &
     148              :         native_skala_gapw_atom_composite_requested, native_skala_gapw_composite_direct_ao, &
     149              :         native_skala_gapw_composite_reference, native_skala_uses_atom_composite_grid, &
     150              :         skala_gapw_representation, xc_section_uses_gauxc_model, xc_section_uses_native_skala_grid
     151              :    USE smeagol_interface,               ONLY: smeagol_shift_v_hartree
     152              :    USE string_utilities,                ONLY: uppercase
     153              :    USE surface_dipole,                  ONLY: calc_dipsurf_potential
     154              :    USE tblite_ks_matrix,                ONLY: build_tblite_ks_matrix
     155              :    USE virial_types,                    ONLY: virial_type
     156              :    USE xc_gauxc_functional,             ONLY: apply_gauxc,&
     157              :                                               gauxc_gapw_all_all_electron,&
     158              :                                               gauxc_gapw_all_pseudopotentials,&
     159              :                                               gauxc_gapw_has_paw_pseudopotentials
     160              :    USE xc_input_constants,              ONLY: skala_gapw_direct_valence,&
     161              :                                               skala_gapw_paw_one_center
     162              :    USE xtb_ks_matrix,                   ONLY: build_xtb_ks_matrix
     163              : #include "./base/base_uses.f90"
     164              : 
     165              :    IMPLICIT NONE
     166              : 
     167              :    PRIVATE
     168              : 
     169              :    LOGICAL, PARAMETER :: debug_this_module = .TRUE.
     170              :    CHARACTER(len=*), PARAMETER, PRIVATE :: moduleN = 'qs_ks_methods'
     171              : 
     172              :    PUBLIC :: calc_rho_tot_gspace, qs_ks_update_qs_env, qs_ks_build_kohn_sham_matrix, &
     173              :              qs_ks_allocate_basics, evaluate_core_matrix_traces, rebuild_ks_matrix
     174              : 
     175              : CONTAINS
     176              : 
     177              : ! **************************************************************************************************
     178              : !> \brief routine where the real calculations are made: the
     179              : !>      KS matrix is calculated
     180              : !> \param qs_env the qs_env to update
     181              : !> \param calculate_forces if true calculate the quantities needed
     182              : !>        to calculate the forces. Defaults to false.
     183              : !> \param just_energy if true updates the energies but not the
     184              : !>        ks matrix. Defaults to false
     185              : !> \param print_active ...
     186              : !> \param ext_ks_matrix ...
     187              : !> \param ext_xc_section ...
     188              : !> \par History
     189              : !>      06.2002 moved from qs_scf to qs_ks_methods, use of ks_env
     190              : !>              new did_change scheme [fawzi]
     191              : !>      10.2002 introduced pools, uses updated rho as input, LSD [fawzi]
     192              : !>      10.2004 build_kohn_sham matrix now also computes the derivatives
     193              : !>              of the total energy wrt to the MO coefs, if instructed to
     194              : !>              do so. This appears useful for orbital dependent functionals
     195              : !>              where the KS matrix alone (however this might be defined)
     196              : !>               does not contain the info to construct this derivative.
     197              : !> \author Matthias Krack
     198              : !> \note
     199              : !>      make rho, energy and qs_charges optional, defaulting
     200              : !>      to qs_env components?
     201              : ! **************************************************************************************************
     202       128729 :    SUBROUTINE qs_ks_build_kohn_sham_matrix(qs_env, calculate_forces, just_energy, &
     203              :                                            print_active, ext_ks_matrix, ext_xc_section)
     204              :       TYPE(qs_environment_type), POINTER                 :: qs_env
     205              :       LOGICAL, INTENT(in)                                :: calculate_forces, just_energy
     206              :       LOGICAL, INTENT(IN), OPTIONAL                      :: print_active
     207              :       TYPE(dbcsr_p_type), DIMENSION(:), OPTIONAL, &
     208              :          POINTER                                         :: ext_ks_matrix
     209              :       TYPE(section_vals_type), OPTIONAL, POINTER         :: ext_xc_section
     210              : 
     211              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'qs_ks_build_kohn_sham_matrix'
     212              : 
     213              :       CHARACTER(len=default_string_length)               :: gauxc_model_name, name
     214              :       INTEGER :: ace_rebuild_frequency, atom_a, gapw_representation, handle, iatom, ikind, img, &
     215              :          ispin, natom, nimages, nspins, output_unit
     216       128729 :       INTEGER, ALLOCATABLE, DIMENSION(:)                 :: atom_of_kind, kind_of
     217              :       LOGICAL :: ace_active, do_adiabatic_rescaling, do_ddapc, do_hfx, do_kpoints, do_ppl, dokp, &
     218              :          gapw, gapw_all_all_electron, gapw_all_pseudopotentials, gapw_mixed_core_representations, &
     219              :          gapw_xc, gauxc_model_none, just_energy_xc, lrigpw, my_print, &
     220              :          native_direct_valence_atom_composite, native_gapw_all_electron_atom_composite, &
     221              :          native_gapw_atom_composite_reference, native_gapw_atom_composite_requested, &
     222              :          native_gapw_composite_direct_ao, native_gapw_composite_reference, &
     223              :          native_gapw_periodic_atom_composite, native_grid_diagnostics, native_grid_use_cuda, &
     224              :          native_skala_evaluator, native_skala_restore_exc
     225              :       LOGICAL :: paw_composite_representation, rigpw, use_gauxc_matrix, use_virial
     226              :       LOGICAL, SAVE :: native_grid_cpu_kpoints_warned = .FALSE.
     227              :       REAL(KIND=dp) :: ecore_ppl, edisp, ee_ener, ekin_mol, mulliken_order_p, &
     228              :          native_skala_composite_contraction, native_skala_composite_rho_contraction, &
     229              :          native_skala_composite_tau_contraction, native_skala_exc_scf, native_skala_total_scf, &
     230              :          vscale
     231       128729 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:)           :: cdft_gapw_values
     232       128729 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :)        :: cdft_charge_correction, &
     233       128729 :                                                             cdft_electronic_charge, &
     234       128729 :                                                             native_skala_atom_force
     235              :       REAL(KIND=dp), DIMENSION(3, 3)                     :: h_stress, native_skala_composite_virial, &
     236              :                                                             pv_loc
     237              :       TYPE(admm_type), POINTER                           :: admm_env
     238       128729 :       TYPE(atomic_kind_type), DIMENSION(:), POINTER      :: atomic_kind_set
     239              :       TYPE(cdft_control_type), POINTER                   :: cdft_control
     240              :       TYPE(cell_type), POINTER                           :: cell
     241              :       TYPE(cp_logger_type), POINTER                      :: logger
     242       128729 :       TYPE(dbcsr_p_type), DIMENSION(:), POINTER          :: ksmat, matrix_vhxc, matrix_vxc, mo_derivs
     243       128729 :       TYPE(dbcsr_p_type), DIMENSION(:, :), POINTER       :: ks_matrix, ks_matrix_im, matrix_h, &
     244       128729 :                                                             matrix_h_im, matrix_s, matrix_vxc_kp, &
     245       128729 :                                                             my_rho, rho_ao
     246              :       TYPE(dft_control_type), POINTER                    :: dft_control
     247       128729 :       TYPE(ecoul_1center_type), DIMENSION(:), POINTER    :: ecoul_1c
     248              :       TYPE(harris_type), POINTER                         :: harris_env
     249              :       TYPE(kpoint_type), POINTER                         :: kpoints
     250              :       TYPE(local_rho_type), POINTER                      :: local_rho_set
     251              :       TYPE(lri_density_type), POINTER                    :: lri_density
     252              :       TYPE(lri_environment_type), POINTER                :: lri_env
     253       128729 :       TYPE(lri_kind_type), DIMENSION(:), POINTER         :: lri_v_int
     254              :       TYPE(mp_para_env_type), POINTER                    :: para_env
     255              :       TYPE(neighbor_list_set_p_type), DIMENSION(:), &
     256       128729 :          POINTER                                         :: sab_orb
     257       128729 :       TYPE(particle_type), DIMENSION(:), POINTER         :: particle_set
     258              :       TYPE(pw_c1d_gs_type)                               :: rho_tot_gspace, v_hartree_gspace
     259              :       TYPE(pw_c1d_gs_type), POINTER                      :: rho_core
     260              :       TYPE(pw_env_type), POINTER                         :: pw_env
     261              :       TYPE(pw_poisson_type), POINTER                     :: poisson_env
     262              :       TYPE(pw_pool_type), POINTER                        :: auxbas_pw_pool
     263       386187 :       TYPE(pw_r3d_rs_type), DIMENSION(2)                 :: v_hxc_rspace
     264       257458 :       TYPE(pw_r3d_rs_type), DIMENSION(:), POINTER        :: rho_r, v_rspace_embed, v_rspace_new, &
     265       128729 :                                                             v_rspace_new_aux_fit, v_tau_rspace, &
     266       128729 :                                                             v_tau_rspace_aux_fit
     267              :       TYPE(pw_r3d_rs_type), POINTER :: rho0_s_rs, rho_nlcc, rhoz_cneo_s_rs, v_hartree_rspace, &
     268              :          v_sccs_rspace, v_sic_rspace, v_spin_ddapc_rest_r, vee, vppl_rspace
     269              :       TYPE(qs_energy_type), POINTER                      :: energy
     270       128729 :       TYPE(qs_force_type), DIMENSION(:), POINTER         :: force
     271       128729 :       TYPE(qs_kind_type), DIMENSION(:), POINTER          :: qs_kind_set
     272              :       TYPE(qs_ks_env_type), POINTER                      :: ks_env
     273              :       TYPE(qs_rho_type), POINTER                         :: rho, rho1, rho_struct, rho_xc
     274              :       TYPE(section_vals_type), POINTER                   :: ace_section, &
     275              :                                                             adiabatic_rescaling_section, &
     276              :                                                             gauxc_section, hfx_sections, input, &
     277              :                                                             scf_section, xc_section
     278              :       TYPE(virial_type), POINTER                         :: virial
     279              : 
     280       128729 :       CALL timeset(routineN, handle)
     281       128729 :       NULLIFY (admm_env, atomic_kind_set, cell, dft_control, force, logger, mo_derivs, my_rho, &
     282       128729 :                rho_struct, para_env, pw_env, virial, vppl_rspace, &
     283       128729 :                ace_section, &
     284       128729 :                adiabatic_rescaling_section, hfx_sections, input, scf_section, &
     285       128729 :                xc_section, gauxc_section, matrix_h, matrix_h_im, matrix_s, auxbas_pw_pool, poisson_env, &
     286       128729 :                v_rspace_new, v_rspace_new_aux_fit, v_tau_rspace, v_tau_rspace_aux_fit, matrix_vxc, &
     287       128729 :                matrix_vxc_kp, matrix_vhxc, &
     288       128729 :                vee, rho_nlcc, ks_env, ks_matrix, ks_matrix_im, rho, energy, rho_xc, rho_r, rho_ao, &
     289       128729 :                rho_core, sab_orb, particle_set, qs_kind_set, kpoints)
     290              : 
     291       128729 :       CPASSERT(ASSOCIATED(qs_env))
     292              : 
     293       128729 :       logger => cp_get_default_logger()
     294       128729 :       my_print = .TRUE.
     295       128729 :       IF (PRESENT(print_active)) my_print = print_active
     296       128729 :       use_gauxc_matrix = .FALSE.
     297       128729 :       native_gapw_atom_composite_reference = .FALSE.
     298       128729 :       native_gapw_atom_composite_requested = .FALSE.
     299       128729 :       native_gapw_all_electron_atom_composite = .FALSE.
     300       128729 :       native_direct_valence_atom_composite = .FALSE.
     301       128729 :       gapw_all_all_electron = .FALSE.
     302       128729 :       gapw_all_pseudopotentials = .FALSE.
     303       128729 :       gapw_mixed_core_representations = .FALSE.
     304       128729 :       native_gapw_composite_direct_ao = .FALSE.
     305       128729 :       native_gapw_composite_reference = .FALSE.
     306       128729 :       native_gapw_periodic_atom_composite = .FALSE.
     307       128729 :       native_grid_diagnostics = .FALSE.
     308       128729 :       native_skala_composite_contraction = 0.0_dp
     309       128729 :       native_skala_composite_rho_contraction = 0.0_dp
     310       128729 :       native_skala_composite_tau_contraction = 0.0_dp
     311       128729 :       native_skala_restore_exc = .FALSE.
     312              : 
     313              :       CALL get_qs_env(qs_env, &
     314              :                       ks_env=ks_env, &
     315              :                       dft_control=dft_control, &
     316              :                       matrix_h_kp=matrix_h, &
     317              :                       matrix_h_im_kp=matrix_h_im, &
     318              :                       matrix_s_kp=matrix_s, &
     319              :                       matrix_ks_kp=ks_matrix, &
     320              :                       matrix_ks_im_kp=ks_matrix_im, &
     321              :                       matrix_vxc=matrix_vxc, &
     322              :                       matrix_vhxc=matrix_vhxc, &
     323              :                       matrix_vxc_kp=matrix_vxc_kp, &
     324              :                       pw_env=pw_env, &
     325              :                       cell=cell, &
     326              :                       atomic_kind_set=atomic_kind_set, &
     327              :                       para_env=para_env, &
     328              :                       input=input, &
     329              :                       virial=virial, &
     330              :                       v_hartree_rspace=v_hartree_rspace, &
     331              :                       vee=vee, &
     332              :                       rho_nlcc=rho_nlcc, &
     333              :                       rho=rho, &
     334              :                       rho_core=rho_core, &
     335              :                       rho_xc=rho_xc, &
     336              :                       sab_orb=sab_orb, &
     337              :                       energy=energy, &
     338              :                       force=force, &
     339              :                       kpoints=kpoints, &
     340              :                       do_kpoints=do_kpoints, &
     341              :                       particle_set=particle_set, &
     342              :                       qs_kind_set=qs_kind_set, &
     343       128729 :                       natom=natom)
     344              : 
     345       128729 :       CALL qs_rho_get(rho, rho_r=rho_r, rho_ao_kp=rho_ao)
     346              : 
     347       128729 :       nimages = dft_control%nimages
     348       128729 :       nspins = dft_control%nspins
     349              : 
     350              :       ! remap pointer to allow for non-kpoint external ks matrix
     351       128729 :       IF (PRESENT(ext_ks_matrix)) ks_matrix(1:nspins, 1:1) => ext_ks_matrix(1:nspins)
     352              : 
     353       128729 :       use_virial = virial%pv_availability .AND. (.NOT. virial%pv_numer)
     354              : 
     355       128729 :       adiabatic_rescaling_section => section_vals_get_subs_vals(input, "DFT%XC%ADIABATIC_RESCALING")
     356       128729 :       CALL section_vals_get(adiabatic_rescaling_section, explicit=do_adiabatic_rescaling)
     357       128729 :       just_energy_xc = just_energy
     358       128729 :       IF (do_adiabatic_rescaling) THEN
     359              :          !! If we perform adiabatic rescaling, the xc potential has to be scaled by the xc- and
     360              :          !! HFX-energy. Thus, let us first calculate the energy
     361           44 :          just_energy_xc = .TRUE.
     362              :       END IF
     363              : 
     364       128729 :       CPASSERT(ASSOCIATED(matrix_h))
     365       128729 :       CPASSERT(ASSOCIATED(matrix_s))
     366       128729 :       CPASSERT(ASSOCIATED(rho))
     367       128729 :       CPASSERT(ASSOCIATED(pw_env))
     368       128729 :       CPASSERT(SIZE(ks_matrix, 1) > 0)
     369       128729 :       dokp = (nimages > 1)
     370              : 
     371              :       ! Setup the possible usage of DDAPC charges
     372              :       do_ddapc = dft_control%qs_control%ddapc_restraint .OR. &
     373              :                  qs_env%cp_ddapc_ewald%do_decoupling .OR. &
     374              :                  qs_env%cp_ddapc_ewald%do_qmmm_periodic_decpl .OR. &
     375       128729 :                  qs_env%cp_ddapc_ewald%do_solvation
     376              : 
     377              :       ! Check if LRIGPW is used
     378       128729 :       lrigpw = dft_control%qs_control%lrigpw
     379       128729 :       rigpw = dft_control%qs_control%rigpw
     380       128729 :       IF (rigpw) THEN
     381           26 :          CPASSERT(nimages == 1)
     382              :       END IF
     383           26 :       IF (lrigpw .AND. rigpw) THEN
     384            0 :          CPABORT(" LRI and RI are not compatible")
     385              :       END IF
     386              : 
     387              :       ! Check for GAPW method : additional terms for local densities
     388       128729 :       gapw = dft_control%qs_control%gapw
     389       128729 :       gapw_xc = dft_control%qs_control%gapw_xc
     390       128729 :       IF (gapw_xc .AND. gapw) THEN
     391            0 :          CPABORT(" GAPW and GAPW_XC are not compatible")
     392              :       END IF
     393       128729 :       IF ((gapw .AND. lrigpw) .OR. (gapw_xc .AND. lrigpw)) THEN
     394            0 :          CPABORT(" GAPW/GAPW_XC and LRIGPW are not compatible")
     395              :       END IF
     396       128729 :       IF ((gapw .AND. rigpw) .OR. (gapw_xc .AND. rigpw)) THEN
     397            0 :          CPABORT(" GAPW/GAPW_XC and RIGPW are not compatible")
     398              :       END IF
     399              : 
     400       128729 :       do_ppl = dft_control%qs_control%do_ppl_method == do_ppl_grid
     401       128729 :       IF (do_ppl) THEN
     402           60 :          CPASSERT(.NOT. gapw)
     403           60 :          CALL get_qs_env(qs_env=qs_env, vppl=vppl_rspace)
     404              :       END IF
     405              : 
     406       128729 :       IF (gapw_xc) THEN
     407         4304 :          CPASSERT(ASSOCIATED(rho_xc))
     408              :       END IF
     409              : 
     410              :       ! gets the tmp grids
     411       128729 :       CALL pw_env_get(pw_env, auxbas_pw_pool=auxbas_pw_pool, poisson_env=poisson_env)
     412              : 
     413       128729 :       IF (gapw .AND. (poisson_env%parameters%solver == pw_poisson_implicit)) THEN
     414            0 :          CPABORT("The implicit Poisson solver cannot be used in conjunction with GAPW.")
     415              :       END IF
     416              : 
     417              :       ! ***  Prepare densities for gapw ***
     418       128729 :       IF (gapw .OR. gapw_xc) THEN
     419        27230 :          CALL prepare_gapw_den(qs_env, do_rho0=(.NOT. gapw_xc))
     420              :       END IF
     421              : 
     422              :       ! Calculate the Hartree potential
     423       128729 :       CALL auxbas_pw_pool%create_pw(v_hartree_gspace)
     424       128729 :       CALL auxbas_pw_pool%create_pw(rho_tot_gspace)
     425              : 
     426       128729 :       scf_section => section_vals_get_subs_vals(input, "DFT%SCF")
     427              :       IF (BTEST(cp_print_key_should_output(logger%iter_info, scf_section, &
     428              :                                            "PRINT%DETAILED_ENERGY"), &
     429              :                 cp_p_file) .AND. &
     430       128729 :           (.NOT. gapw) .AND. (.NOT. gapw_xc) .AND. &
     431              :           (.NOT. (poisson_env%parameters%solver == pw_poisson_implicit))) THEN
     432          946 :          CALL pw_zero(rho_tot_gspace)
     433          946 :          CALL calc_rho_tot_gspace(rho_tot_gspace, qs_env, rho, skip_nuclear_density=.TRUE.)
     434              :          CALL pw_poisson_solve(poisson_env, rho_tot_gspace, energy%e_hartree, &
     435          946 :                                v_hartree_gspace)
     436          946 :          CALL pw_zero(rho_tot_gspace)
     437          946 :          CALL pw_zero(v_hartree_gspace)
     438              :       END IF
     439              : 
     440              :       ! Get the total density in g-space [ions + electrons]
     441       128729 :       CALL calc_rho_tot_gspace(rho_tot_gspace, qs_env, rho)
     442              : 
     443       128729 :       IF (qs_env%scf_control%gce%do_gce .AND. .NOT. dft_control%do_pcc) THEN
     444            0 :          CPABORT("GCE requires DFT%PLANAR_COUNTER_CHARGE to define the countercharge plane.")
     445              :       END IF
     446              : 
     447              :       ! Add the planar counter charge density
     448       128729 :       IF (dft_control%do_pcc) THEN
     449          114 :          CALL planar_counter_charge(rho_tot_gspace, dft_control%pcc_control, auxbas_pw_pool)
     450              :       END IF
     451              : 
     452       128729 :       IF (my_print) THEN
     453       128637 :          CALL print_densities(qs_env, rho)
     454              :       END IF
     455              : 
     456       128729 :       IF (dft_control%do_sccs) THEN
     457              :          ! Self-consistent continuum solvation (SCCS) model
     458              :          NULLIFY (v_sccs_rspace)
     459          160 :          ALLOCATE (v_sccs_rspace)
     460          160 :          CALL auxbas_pw_pool%create_pw(v_sccs_rspace)
     461              : 
     462          160 :          IF (poisson_env%parameters%solver == pw_poisson_implicit) THEN
     463            0 :             CPABORT("The implicit Poisson solver cannot be used together with SCCS.")
     464              :          END IF
     465              : 
     466          160 :          IF (use_virial .AND. calculate_forces) THEN
     467              :             CALL sccs(qs_env, rho_tot_gspace, v_hartree_gspace, v_sccs_rspace, &
     468            0 :                       h_stress=h_stress)
     469            0 :             virial%pv_ehartree = virial%pv_ehartree + h_stress/REAL(para_env%num_pe, dp)
     470            0 :             virial%pv_virial = virial%pv_virial + h_stress/REAL(para_env%num_pe, dp)
     471              :          ELSE
     472          160 :             CALL sccs(qs_env, rho_tot_gspace, v_hartree_gspace, v_sccs_rspace)
     473              :          END IF
     474              :       ELSE
     475              :          ! Getting the Hartree energy and Hartree potential.  Also getting the stress tensor
     476              :          ! from the Hartree term if needed.  No nuclear force information here
     477       128569 :          IF (use_virial .AND. calculate_forces) THEN
     478          510 :             h_stress(:, :) = 0.0_dp
     479              :             CALL pw_poisson_solve(poisson_env, rho_tot_gspace, energy%hartree, &
     480              :                                   v_hartree_gspace, h_stress=h_stress, &
     481          510 :                                   rho_core=rho_core)
     482         6630 :             virial%pv_ehartree = virial%pv_ehartree + h_stress/REAL(para_env%num_pe, dp)
     483         6630 :             virial%pv_virial = virial%pv_virial + h_stress/REAL(para_env%num_pe, dp)
     484              :          ELSE
     485              :             CALL pw_poisson_solve(poisson_env, rho_tot_gspace, energy%hartree, &
     486       128059 :                                   v_hartree_gspace, rho_core=rho_core)
     487              :          END IF
     488              :       END IF
     489              : 
     490       128729 :       IF (dft_control%do_paep .OR. qs_env%scf_control%gce%do_gce) THEN
     491           86 :          CALL pw_transfer(v_hartree_gspace, v_hartree_rspace)
     492              :          CALL planar_averaged_v_hartree_3d(v_hartree_rspace, dft_control, qs_env%scf_control%gce%do_gce, &
     493           86 :                                            qs_env%scf_control%gce%ref_esp, para_env)
     494              :       END IF
     495              : 
     496              :       ! In case decouple periodic images and/or apply restraints to charges
     497       128729 :       IF (do_ddapc) THEN
     498              :          CALL qs_ks_ddapc(qs_env, auxbas_pw_pool, rho_tot_gspace, v_hartree_gspace, &
     499              :                           v_spin_ddapc_rest_r, energy, calculate_forces, ks_matrix, &
     500         2152 :                           just_energy)
     501              :       ELSE
     502       126577 :          dft_control%qs_control%ddapc_explicit_potential = .FALSE.
     503       126577 :          dft_control%qs_control%ddapc_restraint_is_spin = .FALSE.
     504       126577 :          IF (.NOT. just_energy) THEN
     505       115925 :             CALL pw_transfer(v_hartree_gspace, v_hartree_rspace)
     506       115925 :             CALL pw_scale(v_hartree_rspace, v_hartree_rspace%pw_grid%dvol)
     507              :          END IF
     508              :       END IF
     509       128729 :       CALL auxbas_pw_pool%give_back_pw(v_hartree_gspace)
     510              : 
     511       128729 :       IF (dft_control%correct_surf_dip) THEN
     512          110 :          IF (dft_control%surf_dip_correct_switch) THEN
     513          110 :             CALL calc_dipsurf_potential(qs_env, energy)
     514          110 :             energy%hartree = energy%hartree + energy%surf_dipole
     515              :          END IF
     516              :       END IF
     517              : 
     518              :       ! SIC
     519              :       CALL calc_v_sic_rspace(v_sic_rspace, energy, qs_env, dft_control, rho, poisson_env, &
     520       128729 :                              just_energy, calculate_forces, auxbas_pw_pool)
     521              : 
     522              :       ! Check if CDFT constraint is needed
     523       128729 :       CALL qs_ks_cdft_constraint(qs_env, auxbas_pw_pool, calculate_forces, cdft_control)
     524              : 
     525              :       ! Adds the External Potential if requested
     526       128729 :       IF (dft_control%apply_external_potential) THEN
     527              :          ! Compute the energy due to the external potential
     528              :          ee_ener = 0.0_dp
     529          728 :          DO ispin = 1, nspins
     530          728 :             ee_ener = ee_ener + pw_integral_ab(rho_r(ispin), vee)
     531              :          END DO
     532          364 :          IF (.NOT. just_energy) THEN
     533          364 :             IF (gapw) THEN
     534              :                CALL get_qs_env(qs_env=qs_env, &
     535              :                                rho0_s_rs=rho0_s_rs, &
     536           42 :                                rhoz_cneo_s_rs=rhoz_cneo_s_rs)
     537           42 :                CPASSERT(ASSOCIATED(rho0_s_rs))
     538           42 :                IF (ASSOCIATED(rhoz_cneo_s_rs)) THEN
     539            0 :                   CALL pw_axpy(rhoz_cneo_s_rs, rho0_s_rs)
     540              :                END IF
     541           42 :                ee_ener = ee_ener + pw_integral_ab(rho0_s_rs, vee)
     542           42 :                IF (ASSOCIATED(rhoz_cneo_s_rs)) THEN
     543            0 :                   CALL pw_axpy(rhoz_cneo_s_rs, rho0_s_rs, -1.0_dp)
     544              :                END IF
     545              :             END IF
     546              :          END IF
     547              :          ! the sign accounts for the charge of the electrons
     548          364 :          energy%ee = -ee_ener
     549              :       END IF
     550              : 
     551              :       ! Adds the QM/MM potential
     552       128729 :       IF (qs_env%qmmm) THEN
     553              :          CALL qmmm_calculate_energy(qs_env=qs_env, &
     554              :                                     rho=rho_r, &
     555              :                                     v_qmmm=qs_env%ks_qmmm_env%v_qmmm_rspace, &
     556         6318 :                                     qmmm_energy=energy%qmmm_el)
     557         6318 :          IF (qs_env%qmmm_env_qm%image_charge) THEN
     558              :             CALL calculate_image_pot(v_hartree_rspace=v_hartree_rspace, &
     559              :                                      rho_hartree_gspace=rho_tot_gspace, &
     560              :                                      energy=energy, &
     561              :                                      qmmm_env=qs_env%qmmm_env_qm, &
     562           60 :                                      qs_env=qs_env)
     563           60 :             IF (.NOT. just_energy) THEN
     564              :                CALL add_image_pot_to_hartree_pot(v_hartree=v_hartree_rspace, &
     565              :                                                  v_metal=qs_env%ks_qmmm_env%v_metal_rspace, &
     566           60 :                                                  qs_env=qs_env)
     567           60 :                IF (calculate_forces) THEN
     568              :                   CALL integrate_potential_devga_rspace( &
     569              :                      potential=v_hartree_rspace, coeff=qs_env%image_coeff, &
     570              :                      forces=qs_env%qmmm_env_qm%image_charge_pot%image_forcesMM, &
     571           20 :                      qmmm_env=qs_env%qmmm_env_qm, qs_env=qs_env)
     572              :                END IF
     573              :             END IF
     574           60 :             CALL qs_env%ks_qmmm_env%v_metal_rspace%release()
     575           60 :             DEALLOCATE (qs_env%ks_qmmm_env%v_metal_rspace)
     576              :          END IF
     577         6318 :          IF (.NOT. just_energy) THEN
     578              :             CALL qmmm_modify_hartree_pot(v_hartree=v_hartree_rspace, &
     579         6228 :                                          v_qmmm=qs_env%ks_qmmm_env%v_qmmm_rspace, scale=1.0_dp)
     580              :          END IF
     581              :       END IF
     582       128729 :       CALL auxbas_pw_pool%give_back_pw(rho_tot_gspace)
     583              : 
     584              :       ! SMEAGOL interface
     585       128729 :       IF (dft_control%smeagol_control%smeagol_enabled .AND. &
     586              :           dft_control%smeagol_control%run_type == smeagol_runtype_emtransport) THEN
     587            0 :          CPASSERT(ASSOCIATED(dft_control%smeagol_control%aux))
     588              :          CALL smeagol_shift_v_hartree(v_hartree_rspace, cell, &
     589              :                                       dft_control%smeagol_control%aux%HartreeLeadsLeft, &
     590              :                                       dft_control%smeagol_control%aux%HartreeLeadsRight, &
     591              :                                       dft_control%smeagol_control%aux%HartreeLeadsBottom, &
     592              :                                       dft_control%smeagol_control%aux%VBias, &
     593              :                                       dft_control%smeagol_control%aux%minL, &
     594              :                                       dft_control%smeagol_control%aux%maxR, &
     595              :                                       dft_control%smeagol_control%aux%isexplicit_maxR, &
     596            0 :                                       dft_control%smeagol_control%aux%isexplicit_HartreeLeadsBottom)
     597              :       END IF
     598              : 
     599              :       ! calculate the density matrix for the fitted mo_coeffs
     600       128729 :       IF (dft_control%do_admm) THEN
     601        13366 :          IF (PRESENT(ext_xc_section)) THEN
     602            0 :             CALL hfx_admm_init(qs_env, calculate_forces, ext_xc_section)
     603              :          ELSE
     604        13366 :             CALL hfx_admm_init(qs_env, calculate_forces)
     605              :          END IF
     606              : 
     607        13366 :          IF (dft_control%do_admm_mo) THEN
     608        13152 :             IF (qs_env%run_rtp) THEN
     609          114 :                CALL rtp_admm_calc_rho_aux(qs_env)
     610              :             ELSE
     611        13038 :                IF (dokp) THEN
     612          156 :                   CALL admm_mo_calc_rho_aux_kp(qs_env)
     613              :                ELSE
     614        12882 :                   CALL admm_mo_calc_rho_aux(qs_env)
     615              :                END IF
     616              :             END IF
     617          214 :          ELSE IF (dft_control%do_admm_dm) THEN
     618          214 :             CALL admm_dm_calc_rho_aux(qs_env)
     619              :          END IF
     620              :       END IF
     621              : 
     622              :       ! only activate stress calculation if
     623       128729 :       IF (use_virial .AND. calculate_forces) virial%pv_calculate = .TRUE.
     624              : 
     625              :       ! *** calculate the xc potential on the pw density ***
     626              :       ! *** associates v_rspace_new if the xc potential needs to be computed.
     627              :       ! If we do wavefunction fitting, we need the vxc_potential in the auxiliary basis set
     628       128729 :       IF (dft_control%do_admm) THEN
     629        13366 :          CALL get_qs_env(qs_env, admm_env=admm_env)
     630        13366 :          xc_section => admm_env%xc_section_aux
     631        13366 :          CALL get_admm_env(admm_env, rho_aux_fit=rho_struct)
     632              : 
     633              :          ! here we ignore a possible vdW section in admm_env%xc_section_aux
     634              :          CALL qs_vxc_create(ks_env=ks_env, rho_struct=rho_struct, xc_section=xc_section, &
     635              :                             vxc_rho=v_rspace_new_aux_fit, vxc_tau=v_tau_rspace_aux_fit, exc=energy%exc_aux_fit, &
     636        13366 :                             just_energy=just_energy_xc)
     637              : 
     638        13366 :          IF (admm_env%do_gapw) THEN
     639              :             !compute the potential due to atomic densities
     640              :             CALL calculate_vxc_atom(qs_env, energy_only=just_energy_xc, exc1=energy%exc1_aux_fit, &
     641              :                                     kind_set_external=admm_env%admm_gapw_env%admm_kind_set, &
     642              :                                     xc_section_external=xc_section, &
     643              :                                     rho_atom_set_external=admm_env%admm_gapw_env%local_rho_set%rho_atom_set, &
     644         4720 :                                     calculate_forces=calculate_forces)
     645              : 
     646              :          END IF
     647              : 
     648        13366 :          NULLIFY (rho_struct)
     649              : 
     650        13366 :          IF (use_virial .AND. calculate_forces) THEN
     651           20 :             vscale = 1.0_dp
     652              :             !Note: ADMMS and ADMMP stress tensor only for closed-shell calculations
     653           20 :             IF (admm_env%do_admms) vscale = admm_env%gsi(1)**(2.0_dp/3.0_dp)
     654           20 :             IF (admm_env%do_admmp) vscale = admm_env%gsi(1)**2
     655          260 :             virial%pv_exc = virial%pv_exc - vscale*virial%pv_xc
     656          260 :             virial%pv_virial = virial%pv_virial - vscale*virial%pv_xc
     657              :             ! virial%pv_xc will be zeroed in the xc routines
     658              :          END IF
     659        13366 :          xc_section => admm_env%xc_section_primary
     660              :       ELSE
     661       115363 :          xc_section => section_vals_get_subs_vals(input, "DFT%XC")
     662              :          ! build ks matrix with an xc section potentially different from the one defined in input
     663       115363 :          IF (PRESENT(ext_xc_section)) xc_section => ext_xc_section
     664              :       END IF
     665              : 
     666       128729 :       IF (gapw_xc) THEN
     667         4304 :          CALL get_qs_env(qs_env=qs_env, rho_xc=rho_struct)
     668              :       ELSE
     669       124425 :          CALL get_qs_env(qs_env=qs_env, rho=rho_struct)
     670              :       END IF
     671              : 
     672              :       ! zmp
     673       128729 :       IF (dft_control%apply_external_density .OR. dft_control%apply_external_vxc) THEN
     674          106 :          energy%exc = 0.0_dp
     675          106 :          CALL calculate_zmp_potential(qs_env, v_rspace_new, rho, exc=energy%exc)
     676              :       ELSE
     677              :          ! Embedding potential (runs regardless of XC method)
     678       128623 :          IF (dft_control%apply_embed_pot) THEN
     679          868 :             NULLIFY (v_rspace_embed)
     680          868 :             energy%embed_corr = 0.0_dp
     681              :             CALL get_embed_potential_energy(qs_env, rho, v_rspace_embed, dft_control, &
     682          868 :                                             energy%embed_corr, just_energy)
     683              :          END IF
     684              : 
     685              :          ! Everything else, either via GauXC or manual XC computation
     686       128623 :          native_skala_evaluator = xc_section_uses_native_skala_grid(xc_section)
     687       128623 :          paw_composite_representation = .FALSE.
     688       128623 :          IF (dft_control%use_gauxc .AND. (gapw .OR. gapw_xc)) THEN
     689              :             paw_composite_representation = xc_section_uses_gauxc_model(xc_section) .AND. &
     690              :                                            skala_gapw_representation(xc_section) == skala_gapw_paw_one_center .AND. &
     691          278 :                                            gauxc_gapw_has_paw_pseudopotentials(qs_kind_set)
     692              :             native_skala_evaluator = native_skala_evaluator .OR. &
     693          278 :                                      paw_composite_representation
     694              :          END IF
     695       128623 :          IF (dft_control%use_gauxc) THEN
     696          790 :             IF (native_skala_evaluator) THEN
     697          312 :                CALL ensure_native_skala_grid_scope(xc_section)
     698          312 :                gapw_representation = skala_gapw_representation(xc_section)
     699          312 :                IF (gapw .OR. gapw_xc) THEN
     700          168 :                   gapw_all_all_electron = gauxc_gapw_all_all_electron(qs_kind_set)
     701          168 :                   gapw_all_pseudopotentials = gauxc_gapw_all_pseudopotentials(qs_kind_set)
     702              :                   gapw_mixed_core_representations = &
     703          168 :                      .NOT. gapw_all_all_electron .AND. .NOT. gapw_all_pseudopotentials
     704              :                END IF
     705              :                native_direct_valence_atom_composite = &
     706              :                   xc_section_uses_native_skala_grid(xc_section) .AND. &
     707              :                   native_skala_uses_atom_composite_grid(xc_section) .AND. &
     708              :                   ((.NOT. gapw .AND. .NOT. gapw_xc) .OR. &
     709              :                    (gapw_representation == skala_gapw_direct_valence .AND. &
     710          312 :                     gapw_all_pseudopotentials))
     711              :                native_gapw_composite_reference = &
     712          312 :                   native_skala_gapw_composite_reference(xc_section) .AND. (gapw .OR. gapw_xc)
     713              :                native_gapw_atom_composite_requested = &
     714              :                   native_skala_gapw_atom_composite_requested(xc_section) .AND. &
     715          312 :                   (gapw .OR. gapw_xc)
     716              :                native_gapw_atom_composite_reference = &
     717          312 :                   native_gapw_atom_composite_requested .OR. paw_composite_representation
     718              :                native_gapw_periodic_atom_composite = &
     719          312 :                   native_skala_uses_atom_composite_grid(xc_section)
     720          312 :                IF (gapw_mixed_core_representations .AND. &
     721              :                    .NOT. native_gapw_periodic_atom_composite) THEN
     722              :                   CALL cp_abort(__LOCATION__, &
     723              :                                 "Mixed all-electron and pseudopotential GAPW kinds require "// &
     724              :                                 "NATIVE_GRID_LAYOUT ATOM_COMPOSITE so that their primitive "// &
     725            0 :                                 "fields are combined before Skala feature construction.")
     726              :                END IF
     727              :                native_gapw_atom_composite_reference = &
     728              :                   native_gapw_atom_composite_reference .OR. &
     729              :                   (gapw_mixed_core_representations .AND. &
     730          312 :                    native_gapw_periodic_atom_composite)
     731              :                native_gapw_all_electron_atom_composite = &
     732              :                   (gapw .OR. gapw_xc) .AND. &
     733              :                   gapw_all_all_electron .AND. &
     734              :                   (.NOT. native_gapw_composite_reference) .AND. &
     735          312 :                   native_gapw_periodic_atom_composite
     736              :                native_gapw_atom_composite_reference = &
     737              :                   native_gapw_atom_composite_reference .OR. &
     738          312 :                   native_gapw_all_electron_atom_composite
     739          312 :                IF (paw_composite_representation) THEN
     740          136 :                   IF (ANY(cell%perd /= 0)) THEN
     741              :                      native_gapw_composite_reference = &
     742          104 :                         .NOT. native_gapw_periodic_atom_composite
     743              :                      native_gapw_atom_composite_reference = &
     744          104 :                         native_gapw_periodic_atom_composite
     745              :                   ELSE
     746            8 :                      native_gapw_composite_reference = .FALSE.
     747            8 :                      native_gapw_atom_composite_reference = .TRUE.
     748              :                   END IF
     749              :                END IF
     750          312 :                IF (native_gapw_composite_reference .AND. native_gapw_atom_composite_reference) THEN
     751              :                   CALL cp_abort(__LOCATION__, &
     752            0 :                                 "Select only one native-grid GAPW composite reference route.")
     753              :                END IF
     754              :                native_gapw_composite_direct_ao = native_gapw_composite_reference .AND. &
     755          312 :                                                  native_skala_gapw_composite_direct_ao(xc_section)
     756          312 :                gauxc_section => get_gauxc_section(xc_section)
     757          312 :                IF (ASSOCIATED(gauxc_section)) THEN
     758              :                   CALL section_vals_val_get(gauxc_section, "NATIVE_GRID_DIAGNOSTICS", &
     759          312 :                                             l_val=native_grid_diagnostics)
     760              :                END IF
     761          312 :                IF ((.NOT. do_kpoints) .AND. nimages /= 1) THEN
     762              :                   CALL cp_abort(__LOCATION__, &
     763              :                                 "Native SKALA grid evaluation supports multiple images only "// &
     764            0 :                                 "for k-point calculations.")
     765              :                END IF
     766          312 :                IF (do_kpoints) THEN
     767           48 :                   CPASSERT(ASSOCIATED(kpoints))
     768           48 :                   gauxc_section => get_gauxc_section(xc_section)
     769           48 :                   CPASSERT(ASSOCIATED(gauxc_section))
     770           48 :                   CALL section_vals_val_get(gauxc_section, "NATIVE_GRID_USE_CUDA", l_val=native_grid_use_cuda)
     771           48 :                   IF (.NOT. native_grid_use_cuda) THEN
     772           48 :                      IF (para_env%mepos == 0 .AND. .NOT. native_grid_cpu_kpoints_warned) THEN
     773              :                         CALL cp_warn(__LOCATION__, &
     774              :                                      "Native SKALA grid evaluation with k-points is using the CPU TorchScript "// &
     775              :                                      "path. Use a mutually compatible BLAS, ScaLAPACK, OpenMP, and LibTorch "// &
     776           12 :                                      "runtime stack, or select NATIVE_GRID_USE_CUDA T.")
     777           12 :                         native_grid_cpu_kpoints_warned = .TRUE.
     778              :                      END IF
     779              :                   END IF
     780              :                END IF
     781          312 :                IF (dft_control%roks) THEN
     782            0 :                   CPABORT("Native SKALA grid evaluation does not support ROKS.")
     783              :                END IF
     784          312 :                IF (dft_control%do_admm) THEN
     785            0 :                   CPABORT("Native SKALA grid evaluation does not support ADMM.")
     786              :                END IF
     787              :                ! Force and stress rebuilds re-enter this path for derivatives and VXC only. The
     788              :                ! autograd virial already contains the rebuilt XC volume term when qs_vxc_create
     789              :                ! returns, so the externally reported energy must be restored to its SCF value.
     790          312 :                native_skala_restore_exc = calculate_forces
     791          312 :                IF (native_skala_restore_exc) THEN
     792           72 :                   native_skala_exc_scf = energy%exc
     793           72 :                   native_skala_total_scf = energy%total
     794              :                END IF
     795          312 :                IF (calculate_forces) THEN
     796          216 :                   ALLOCATE (native_skala_atom_force(3, natom))
     797           72 :                   native_skala_atom_force = 0.0_dp
     798           72 :                   IF (native_gapw_atom_composite_reference .OR. &
     799              :                       native_direct_valence_atom_composite) THEN
     800              :                      CALL qs_vxc_create(ks_env=ks_env, rho_struct=rho_struct, xc_section=xc_section, &
     801              :                                         vxc_rho=v_rspace_new, vxc_tau=v_tau_rspace, exc=energy%exc, &
     802              :                                         edisp=edisp, dispersion_env=qs_env%dispersion_env, &
     803              :                                         just_energy=just_energy_xc, qs_env_external=qs_env, &
     804              :                                         native_gapw_composite_override=native_gapw_composite_reference, &
     805           64 :                                         native_skala_defer_to_atom_composite=.TRUE.)
     806              :                   ELSE
     807              :                      CALL qs_vxc_create(ks_env=ks_env, rho_struct=rho_struct, xc_section=xc_section, &
     808              :                                         vxc_rho=v_rspace_new, vxc_tau=v_tau_rspace, exc=energy%exc, &
     809              :                                         edisp=edisp, dispersion_env=qs_env%dispersion_env, &
     810              :                                         just_energy=just_energy_xc, &
     811              :                                         native_skala_atom_force=native_skala_atom_force, &
     812              :                                         qs_env_external=qs_env, &
     813            8 :                                         native_gapw_composite_override=native_gapw_composite_reference)
     814              :                   END IF
     815              :                   IF (native_gapw_composite_reference .AND. .NOT. native_gapw_composite_direct_ao .AND. &
     816           72 :                       ASSOCIATED(v_rspace_new) .AND. ASSOCIATED(v_tau_rspace)) THEN
     817            2 :                      IF (native_grid_diagnostics .AND. para_env%mepos == 0) THEN
     818            0 :                         output_unit = cp_logger_get_default_io_unit()
     819            0 :                         IF (output_unit > 0) THEN
     820            0 :                            DO iatom = 1, natom
     821              :                               WRITE (UNIT=output_unit, FMT="(T2,A,1X,I0,3(1X,ES20.12))") &
     822            0 :                                  "SKALA_GPW| Native regular-grid atom force", iatom, &
     823            0 :                                  native_skala_atom_force(:, iatom)
     824              :                            END DO
     825              :                         END IF
     826              :                      END IF
     827            2 :                      IF (use_virial) THEN
     828            2 :                         native_skala_composite_virial = 0.0_dp
     829              :                         CALL integrate_gapw_composite_vxc_gspace( &
     830              :                            qs_env, auxbas_pw_pool, v_rspace_new, v_tau_rspace, &
     831              :                            atom_force=native_skala_atom_force, &
     832              :                            strain_virial=native_skala_composite_virial, &
     833              :                            one_center_contraction=native_skala_composite_contraction, &
     834              :                            one_center_rho_contraction=native_skala_composite_rho_contraction, &
     835            2 :                            one_center_tau_contraction=native_skala_composite_tau_contraction)
     836            2 :                         IF (native_grid_diagnostics .AND. para_env%mepos == 0) THEN
     837            0 :                            output_unit = cp_logger_get_default_io_unit()
     838            0 :                            IF (output_unit > 0) THEN
     839              :                               WRITE (UNIT=output_unit, FMT="(T2,A)") &
     840            0 :                                  "SKALA_GPW| Composite-direction one-center virial"
     841            0 :                               DO iatom = 1, 3
     842              :                                  WRITE (UNIT=output_unit, FMT="(T2,A,1X,3ES20.10)") &
     843            0 :                                     "SKALA_GPW|", native_skala_composite_virial(iatom, :)
     844              :                               END DO
     845              :                            END IF
     846              :                         END IF
     847           26 :                         virial%pv_xc = virial%pv_xc + native_skala_composite_virial
     848              :                      ELSE
     849              :                         CALL integrate_gapw_composite_vxc_gspace( &
     850              :                            qs_env, auxbas_pw_pool, v_rspace_new, v_tau_rspace, &
     851              :                            atom_force=native_skala_atom_force, &
     852              :                            one_center_contraction=native_skala_composite_contraction, &
     853              :                            one_center_rho_contraction=native_skala_composite_rho_contraction, &
     854            0 :                            one_center_tau_contraction=native_skala_composite_tau_contraction)
     855              :                      END IF
     856              :                   END IF
     857           72 :                   IF (native_grid_diagnostics .AND. para_env%mepos == 0) THEN
     858            7 :                      output_unit = cp_logger_get_default_io_unit()
     859            7 :                      IF (output_unit > 0) THEN
     860              :                         WRITE (UNIT=output_unit, FMT="(T2,A,1X,ES20.10)") &
     861            7 :                            "SKALA_GPW| Composite-direction one-center VXC contraction", &
     862           14 :                            native_skala_composite_contraction
     863              :                         WRITE (UNIT=output_unit, FMT="(T2,A,1X,ES20.10)") &
     864            7 :                            "SKALA_GPW| Composite-direction one-center rho contraction", &
     865           14 :                            native_skala_composite_rho_contraction
     866              :                         WRITE (UNIT=output_unit, FMT="(T2,A,1X,ES20.10)") &
     867            7 :                            "SKALA_GPW| Composite-direction one-center tau contraction", &
     868           14 :                            native_skala_composite_tau_contraction
     869           21 :                         DO iatom = 1, natom
     870              :                            WRITE (UNIT=output_unit, FMT="(T2,A,1X,I0,3(1X,ES20.12))") &
     871           21 :                               "SKALA_GPW| Native atom force", iatom, native_skala_atom_force(:, iatom)
     872              :                         END DO
     873              :                      END IF
     874              :                   END IF
     875           72 :                   CPASSERT(ASSOCIATED(force))
     876           72 :                   CPASSERT(ASSOCIATED(atomic_kind_set))
     877           72 :                   CALL get_atomic_kind_set(atomic_kind_set, atom_of_kind=atom_of_kind, kind_of=kind_of)
     878          216 :                   DO iatom = 1, natom
     879          144 :                      ikind = kind_of(iatom)
     880          144 :                      atom_a = atom_of_kind(iatom)
     881              :                      force(ikind)%rho_elec(:, atom_a) = force(ikind)%rho_elec(:, atom_a) + &
     882          648 :                                                         native_skala_atom_force(:, iatom)
     883              :                   END DO
     884           72 :                   DEALLOCATE (atom_of_kind, kind_of, native_skala_atom_force)
     885              :                ELSE
     886              :                   CALL qs_vxc_create(ks_env=ks_env, rho_struct=rho_struct, xc_section=xc_section, &
     887              :                                      vxc_rho=v_rspace_new, vxc_tau=v_tau_rspace, exc=energy%exc, &
     888              :                                      edisp=edisp, dispersion_env=qs_env%dispersion_env, &
     889              :                                      just_energy=just_energy_xc, qs_env_external=qs_env, &
     890              :                                      native_gapw_composite_override=native_gapw_composite_reference, &
     891              :                                      native_skala_defer_to_atom_composite= &
     892              :                                      (native_gapw_atom_composite_reference .OR. &
     893          240 :                                       native_direct_valence_atom_composite))
     894              :                   IF (native_gapw_composite_reference .AND. .NOT. native_gapw_composite_direct_ao .AND. &
     895          240 :                       ASSOCIATED(v_rspace_new) .AND. ASSOCIATED(v_tau_rspace)) THEN
     896              :                      CALL integrate_gapw_composite_vxc_gspace( &
     897              :                         qs_env, auxbas_pw_pool, v_rspace_new, v_tau_rspace, &
     898              :                         one_center_contraction=native_skala_composite_contraction, &
     899              :                         one_center_rho_contraction=native_skala_composite_rho_contraction, &
     900            2 :                         one_center_tau_contraction=native_skala_composite_tau_contraction)
     901            2 :                      IF (native_grid_diagnostics .AND. para_env%mepos == 0) THEN
     902            0 :                         output_unit = cp_logger_get_default_io_unit()
     903            0 :                         IF (output_unit > 0) THEN
     904              :                            WRITE (UNIT=output_unit, FMT="(T2,A,1X,ES20.10)") &
     905            0 :                               "SKALA_GPW| Composite-direction one-center VXC contraction", &
     906            0 :                               native_skala_composite_contraction
     907              :                            WRITE (UNIT=output_unit, FMT="(T2,A,1X,ES20.10)") &
     908            0 :                               "SKALA_GPW| Composite-direction one-center rho contraction", &
     909            0 :                               native_skala_composite_rho_contraction
     910              :                            WRITE (UNIT=output_unit, FMT="(T2,A,1X,ES20.10)") &
     911            0 :                               "SKALA_GPW| Composite-direction one-center tau contraction", &
     912            0 :                               native_skala_composite_tau_contraction
     913              :                         END IF
     914              :                      END IF
     915              :                   END IF
     916              :                END IF
     917          312 :                IF (native_skala_restore_exc) energy%exc = native_skala_exc_scf
     918          312 :                IF (native_direct_valence_atom_composite) THEN
     919          136 :                   CPASSERT(ASSOCIATED(v_rspace_new))
     920          136 :                   CPASSERT(ASSOCIATED(v_tau_rspace))
     921              :                   CALL calculate_vxc_atom( &
     922              :                      qs_env, just_energy_xc, energy%exc1, xc_section_external=xc_section, &
     923              :                      calculate_forces=calculate_forces, composite_vxc_rho=v_rspace_new, &
     924          136 :                      composite_vxc_tau=v_tau_rspace, direct_valence_atom_grid=.TRUE.)
     925          136 :                   energy%exc = 0.0_dp
     926          176 :                ELSE IF ((gapw .OR. gapw_xc) .AND. .NOT. native_gapw_composite_reference) THEN
     927          144 :                   IF (native_gapw_atom_composite_reference) THEN
     928          128 :                      CPASSERT(ASSOCIATED(v_rspace_new))
     929          128 :                      CPASSERT(ASSOCIATED(v_tau_rspace))
     930              :                      CALL calculate_vxc_atom( &
     931              :                         qs_env, just_energy_xc, energy%exc1, xc_section_external=xc_section, &
     932              :                         calculate_forces=calculate_forces, composite_vxc_rho=v_rspace_new, &
     933          128 :                         composite_vxc_tau=v_tau_rspace, atom_composite_grid=.TRUE.)
     934          128 :                      energy%exc = 0.0_dp
     935              :                   ELSE
     936              :                      CALL calculate_vxc_atom(qs_env, just_energy_xc, energy%exc1, &
     937              :                                              xc_section_external=xc_section, &
     938           16 :                                              calculate_forces=calculate_forces)
     939              :                   END IF
     940              :                END IF
     941          312 :                IF (edisp /= 0.0_dp) energy%dispersion = edisp
     942          312 :                IF (qs_env%requires_matrix_vxc .AND. ASSOCIATED(v_rspace_new)) THEN
     943            0 :                   IF (do_kpoints) THEN
     944              :                      CALL compute_matrix_vxc_kp(qs_env=qs_env, v_rspace=v_rspace_new, &
     945              :                                                 matrix_vxc_kp=matrix_vxc_kp, &
     946            0 :                                                 gapw_full_basis=native_gapw_composite_direct_ao)
     947            0 :                      CALL set_ks_env(ks_env, matrix_vxc_kp=matrix_vxc_kp)
     948              :                   ELSE
     949              :                      CALL compute_matrix_vxc(qs_env=qs_env, v_rspace=v_rspace_new, &
     950              :                                              matrix_vxc=matrix_vxc, &
     951            0 :                                              gapw_full_basis=native_gapw_composite_direct_ao)
     952            0 :                      CALL set_ks_env(ks_env, matrix_vxc=matrix_vxc)
     953              :                   END IF
     954              :                END IF
     955              :             ELSE
     956          478 :                use_gauxc_matrix = .TRUE.
     957          478 :                CALL apply_gauxc(qs_env, xc_section, calculate_forces)
     958          478 :                IF (gapw_xc .OR. (gapw .AND. gauxc_gapw_has_paw_pseudopotentials(qs_kind_set))) THEN
     959              :                   CALL calculate_vxc_atom(qs_env, just_energy_xc, energy%exc1, &
     960              :                                           xc_section_external=xc_section, &
     961            2 :                                           calculate_forces=calculate_forces)
     962              :                END IF
     963              :             END IF
     964              :          ELSE
     965              :             CALL qs_vxc_create(ks_env=ks_env, rho_struct=rho_struct, xc_section=xc_section, &
     966              :                                vxc_rho=v_rspace_new, vxc_tau=v_tau_rspace, exc=energy%exc, &
     967              :                                edisp=edisp, dispersion_env=qs_env%dispersion_env, &
     968       127833 :                                just_energy=just_energy_xc)
     969       127833 :             IF (edisp /= 0.0_dp) energy%dispersion = edisp
     970       127833 :             IF (qs_env%requires_matrix_vxc .AND. ASSOCIATED(v_rspace_new)) THEN
     971            2 :                CALL compute_matrix_vxc(qs_env=qs_env, v_rspace=v_rspace_new, matrix_vxc=matrix_vxc)
     972            2 :                CALL set_ks_env(ks_env, matrix_vxc=matrix_vxc)
     973              :             END IF
     974              : 
     975       127833 :             IF (gapw .OR. gapw_xc) THEN
     976              :                CALL calculate_vxc_atom(qs_env, just_energy_xc, energy%exc1, &
     977              :                                        xc_section_external=xc_section, &
     978        26952 :                                        calculate_forces=calculate_forces)
     979              :             END IF
     980              :          END IF
     981              :       END IF
     982              : 
     983        27480 :       IF (gapw .AND. dft_control%qs_control%cdft) THEN
     984         1308 :          ALLOCATE (cdft_gapw_values(SIZE(cdft_control%group)))
     985          436 :          IF (cdft_control%atomic_charges) THEN
     986              :             ALLOCATE (cdft_charge_correction(natom, nspins), &
     987          532 :                       cdft_electronic_charge(cdft_control%natoms, nspins))
     988              :             CALL gapw_cdft_one_center(qs_env, just_energy, calculate_forces, &
     989           76 :                                       cdft_gapw_values, cdft_charge_correction)
     990          228 :             DO ispin = 1, nspins
     991          624 :                DO iatom = 1, cdft_control%natoms
     992              :                   cdft_electronic_charge(iatom, ispin) = &
     993          548 :                      pw_integral_ab(cdft_control%charge(iatom), rho_r(ispin), local_only=.TRUE.)
     994              :                END DO
     995              :             END DO
     996           76 :             CALL para_env%sum(cdft_electronic_charge)
     997          228 :             DO ispin = 1, nspins
     998          624 :                DO iatom = 1, cdft_control%natoms
     999              :                   cdft_electronic_charge(iatom, ispin) = &
    1000              :                      cdft_electronic_charge(iatom, ispin) + &
    1001          548 :                      cdft_charge_correction(cdft_control%atoms(iatom), ispin)
    1002              :                END DO
    1003              :             END DO
    1004              :          ELSE
    1005          360 :             CALL gapw_cdft_one_center(qs_env, just_energy, calculate_forces, cdft_gapw_values)
    1006              :          END IF
    1007          944 :          cdft_control%value = cdft_control%value + cdft_gapw_values
    1008          944 :          energy%cdft = energy%cdft + DOT_PRODUCT(cdft_control%strength, cdft_gapw_values)
    1009          436 :          IF (cdft_control%atomic_charges) THEN
    1010           76 :             CALL cdft_constraint_print(qs_env, cdft_electronic_charge)
    1011           76 :             DEALLOCATE (cdft_charge_correction, cdft_electronic_charge)
    1012              :          ELSE
    1013          360 :             CALL cdft_constraint_print(qs_env, cdft_electronic_charge)
    1014              :          END IF
    1015          436 :          DEALLOCATE (cdft_gapw_values)
    1016              :       END IF
    1017              : 
    1018       128729 :       IF (dft_control%mtlr_dft_with_perturbation .AND. .NOT. just_energy) THEN
    1019          420 :          IF (do_adiabatic_rescaling .OR. use_gauxc_matrix) THEN
    1020            0 :             CPABORT("MTLR requires an XC potential on the real-space grid.")
    1021              :          END IF
    1022          420 :          IF (.NOT. ASSOCIATED(matrix_vhxc)) THEN
    1023           20 :             ALLOCATE (matrix_vhxc(nspins))
    1024           12 :             DO ispin = 1, nspins
    1025            8 :                NULLIFY (matrix_vhxc(ispin)%matrix)
    1026            8 :                ALLOCATE (matrix_vhxc(ispin)%matrix)
    1027              :                CALL dbcsr_create(matrix_vhxc(ispin)%matrix, &
    1028            8 :                                  template=ks_matrix(1, 1)%matrix)
    1029            8 :                CALL cp_dbcsr_alloc_block_from_nbl(matrix_vhxc(ispin)%matrix, sab_orb)
    1030           12 :                CALL dbcsr_set(matrix_vhxc(ispin)%matrix, 0.0_dp)
    1031              :             END DO
    1032            4 :             CALL set_ks_env(ks_env, matrix_vhxc=matrix_vhxc)
    1033              :          ELSE
    1034          416 :             CPASSERT(SIZE(matrix_vhxc) == nspins)
    1035         1248 :             DO ispin = 1, nspins
    1036         1248 :                CPASSERT(ASSOCIATED(matrix_vhxc(ispin)%matrix))
    1037              :             END DO
    1038              :          END IF
    1039         1260 :          DO ispin = 1, nspins
    1040          840 :             CALL auxbas_pw_pool%create_pw(v_hxc_rspace(ispin))
    1041          840 :             CALL pw_zero(v_hxc_rspace(ispin))
    1042          840 :             CALL pw_axpy(v_hartree_rspace, v_hxc_rspace(ispin))
    1043          840 :             IF (ASSOCIATED(v_rspace_new)) THEN
    1044              :                CALL pw_axpy(v_rspace_new(ispin), &
    1045              :                             v_hxc_rspace(ispin), &
    1046          840 :                             v_rspace_new(ispin)%pw_grid%dvol)
    1047              :             END IF
    1048          840 :             CALL dbcsr_set(matrix_vhxc(ispin)%matrix, 0.0_dp)
    1049              :             CALL integrate_v_rspace(v_hxc_rspace(ispin), &
    1050              :                                     hmat=matrix_vhxc(ispin), &
    1051              :                                     qs_env=qs_env, &
    1052          840 :                                     calculate_forces=.FALSE.)
    1053         1260 :             CALL auxbas_pw_pool%give_back_pw(v_hxc_rspace(ispin))
    1054              :          END DO
    1055              :       END IF
    1056              : 
    1057              :       ! set hartree and xc potentials for use in Harris method
    1058       128729 :       IF (qs_env%harris_method) THEN
    1059          116 :          CALL get_qs_env(qs_env, harris_env=harris_env)
    1060          116 :          CALL harris_set_potentials(harris_env, v_hartree_rspace, v_rspace_new)
    1061              :       END IF
    1062              : 
    1063       128729 :       NULLIFY (rho_struct)
    1064       128729 :       IF (use_virial .AND. calculate_forces) THEN
    1065         6630 :          virial%pv_exc = virial%pv_exc - virial%pv_xc
    1066         6630 :          virial%pv_virial = virial%pv_virial - virial%pv_xc
    1067              :       END IF
    1068              : 
    1069              :       ! *** Add Hartree-Fock contribution if required ***
    1070       128729 :       hfx_sections => section_vals_get_subs_vals(xc_section, "HF")
    1071       128729 :       CALL section_vals_get(hfx_sections, explicit=do_hfx)
    1072              : 
    1073       128729 :       ace_active = .FALSE.
    1074       128729 :       ace_rebuild_frequency = 1
    1075              : 
    1076       128729 :       IF (do_hfx) THEN
    1077        30108 :          ace_section => section_vals_get_subs_vals(hfx_sections, "ACE")
    1078        30108 :          IF (ASSOCIATED(ace_section)) THEN
    1079        30108 :             CALL section_vals_val_get(ace_section, "ACTIVE", l_val=ace_active)
    1080        30108 :             CALL section_vals_val_get(ace_section, "REBUILD_FREQUENCY", i_val=ace_rebuild_frequency)
    1081              :          END IF
    1082              :       END IF
    1083              : 
    1084       128729 :       IF (do_hfx) THEN
    1085        30108 :          IF (dokp) THEN
    1086          274 :             IF (ace_active) THEN
    1087            0 :                CPABORT("ACE-HFX for k-points is not implemented yet")
    1088              :             ELSE
    1089          274 :                CALL hfx_ks_matrix_kp(qs_env, ks_matrix, energy, calculate_forces)
    1090              :             END IF
    1091              : 
    1092              :          ELSE
    1093              :             ! ext_xc_section may contain a hfx section
    1094        29834 :             IF (ace_active) THEN
    1095              :                CALL hfx_ace_ks_matrix(qs_env, ks_matrix, rho, energy, calculate_forces, &
    1096              :                                       just_energy, v_rspace_new, v_tau_rspace, &
    1097           48 :                                       ace_rebuild_frequency, ext_xc_section=xc_section)
    1098              :             ELSE
    1099              :                CALL hfx_ks_matrix(qs_env, ks_matrix, rho, energy, calculate_forces, &
    1100        29786 :                                   just_energy, v_rspace_new, v_tau_rspace, ext_xc_section=xc_section)
    1101              :             END IF
    1102              :          END IF
    1103              :       END IF !do_hfx
    1104              : 
    1105       128729 :       IF (do_ppl .AND. calculate_forces) THEN
    1106           12 :          CPASSERT(.NOT. gapw)
    1107           26 :          DO ispin = 1, nspins
    1108           26 :             CALL integrate_ppl_rspace(rho_r(ispin), qs_env)
    1109              :          END DO
    1110              :       END IF
    1111              : 
    1112              :       ! The atom-composite evaluator differentiates its atom-centered NLCC field directly.
    1113              :       IF (ASSOCIATED(rho_nlcc) .AND. calculate_forces .AND. &
    1114       128729 :           .NOT. native_gapw_atom_composite_reference .AND. &
    1115              :           .NOT. native_direct_valence_atom_composite) THEN
    1116           72 :          DO ispin = 1, nspins
    1117           36 :             CALL integrate_rho_nlcc(v_rspace_new(ispin), qs_env)
    1118           72 :             IF (dft_control%do_admm) CALL integrate_rho_nlcc(v_rspace_new_aux_fit(ispin), qs_env)
    1119              :          END DO
    1120              :       END IF
    1121              : 
    1122              :       ! calculate KG correction
    1123       128729 :       IF (dft_control%qs_control%do_kg .AND. just_energy) THEN
    1124              : 
    1125           12 :          CPASSERT(nimages == 1)
    1126           12 :          ksmat => ks_matrix(:, 1)
    1127           12 :          CALL kg_ekin_subset(qs_env, ksmat, ekin_mol, calculate_forces, do_kernel=.FALSE.)
    1128              : 
    1129              :          ! subtract kg corr from the total energy
    1130           12 :          energy%exc = energy%exc - ekin_mol
    1131              : 
    1132              :       END IF
    1133              : 
    1134              :       ! ***  Single atom contributions ***
    1135       128729 :       IF (.NOT. just_energy) THEN
    1136       117687 :          IF (calculate_forces) THEN
    1137              :             ! Getting nuclear force contribution from the core charge density
    1138         5991 :             IF ((poisson_env%parameters%solver == pw_poisson_implicit) .AND. &
    1139              :                 (poisson_env%parameters%dielectric_params%dielec_core_correction)) THEN
    1140           28 :                BLOCK
    1141              :                   TYPE(pw_r3d_rs_type) :: v_minus_veps
    1142           28 :                   CALL auxbas_pw_pool%create_pw(v_minus_veps)
    1143           28 :                   CALL pw_copy(v_hartree_rspace, v_minus_veps)
    1144           28 :                   CALL pw_axpy(poisson_env%implicit_env%v_eps, v_minus_veps, -v_hartree_rspace%pw_grid%dvol)
    1145           28 :                   CALL integrate_v_core_rspace(v_minus_veps, qs_env)
    1146           28 :                   CALL auxbas_pw_pool%give_back_pw(v_minus_veps)
    1147              :                END BLOCK
    1148              :             ELSE
    1149         5963 :                CALL integrate_v_core_rspace(v_hartree_rspace, qs_env)
    1150              :             END IF
    1151              :          END IF
    1152              : 
    1153       117687 :          IF (.NOT. do_hfx) THEN
    1154              :             ! Initialize the Kohn-Sham matrix with the core Hamiltonian matrix
    1155              :             ! (sets ks sparsity equal to matrix_h sparsity)
    1156       196427 :             DO ispin = 1, nspins
    1157      1033105 :                DO img = 1, nimages
    1158       836678 :                   CALL dbcsr_get_info(ks_matrix(ispin, img)%matrix, name=name) ! keep the name
    1159       943176 :                   CALL dbcsr_copy(ks_matrix(ispin, img)%matrix, matrix_h(1, img)%matrix, name=name)
    1160              :                END DO
    1161              :             END DO
    1162              :             ! imaginary part if required
    1163        89929 :             IF (qs_env%run_rtp) THEN
    1164         2088 :                IF (dft_control%rtp_control%velocity_gauge) THEN
    1165          182 :                   CPASSERT(ASSOCIATED(matrix_h_im))
    1166          182 :                   CPASSERT(ASSOCIATED(ks_matrix_im))
    1167          364 :                   DO ispin = 1, nspins
    1168          546 :                      DO img = 1, nimages
    1169          182 :                         CALL dbcsr_get_info(ks_matrix_im(ispin, img)%matrix, name=name) ! keep the name
    1170          364 :                         CALL dbcsr_copy(ks_matrix_im(ispin, img)%matrix, matrix_h_im(1, img)%matrix, name=name)
    1171              :                      END DO
    1172              :                   END DO
    1173              :                END IF
    1174              :             END IF
    1175              :          END IF
    1176              : 
    1177       117687 :          IF (use_virial .AND. calculate_forces) THEN
    1178         6630 :             pv_loc = virial%pv_virial
    1179              :          END IF
    1180              :          ! sum up potentials and integrate
    1181              :          ! Pointing my_rho to the density matrix rho_ao
    1182       117687 :          my_rho => rho_ao
    1183              : 
    1184              :          CALL sum_up_and_integrate(qs_env, ks_matrix, rho, my_rho, vppl_rspace, &
    1185              :                                    v_rspace_new, v_rspace_new_aux_fit, v_tau_rspace, v_tau_rspace_aux_fit, &
    1186              :                                    v_sic_rspace, v_spin_ddapc_rest_r, v_sccs_rspace, v_rspace_embed, &
    1187       117687 :                                    cdft_control, calculate_forces)
    1188              : 
    1189       117687 :          IF (use_gauxc_matrix) THEN
    1190          478 :             IF (dokp) THEN
    1191            0 :                CALL get_qs_env(qs_env=qs_env, matrix_vxc_kp=matrix_vxc_kp)
    1192            0 :                CPASSERT(ASSOCIATED(matrix_vxc_kp))
    1193            0 :                DO ispin = 1, nspins
    1194            0 :                   DO img = 1, nimages
    1195              :                      CALL dbcsr_add(ks_matrix(ispin, img)%matrix, matrix_vxc_kp(ispin, img)%matrix, &
    1196            0 :                                     1.0_dp, 1.0_dp)
    1197              :                   END DO
    1198              :                END DO
    1199              :             ELSE
    1200          478 :                CALL get_qs_env(qs_env=qs_env, matrix_vxc=matrix_vxc)
    1201          478 :                CPASSERT(ASSOCIATED(matrix_vxc))
    1202          478 :                CPASSERT(nimages == 1)
    1203          978 :                DO ispin = 1, nspins
    1204          978 :                   CALL dbcsr_add(ks_matrix(ispin, 1)%matrix, matrix_vxc(ispin)%matrix, 1.0_dp, 1.0_dp)
    1205              :                END DO
    1206              :             END IF
    1207              :          END IF
    1208              : 
    1209       117687 :          IF (gapw .OR. gapw_xc) THEN
    1210        26326 :             IF (calculate_forces) THEN
    1211          774 :                IF (gapw_xc) THEN
    1212          122 :                   CALL get_qs_env(qs_env=qs_env, rho_xc=rho_struct)
    1213              :                ELSE
    1214          652 :                   CALL get_qs_env(qs_env=qs_env, rho=rho_struct)
    1215              :                END IF
    1216          774 :                NULLIFY (rho1)
    1217          774 :                IF (dft_control%use_gauxc .AND. (gapw .OR. gapw_xc) .AND. &
    1218              :                    .NOT. native_skala_evaluator) THEN
    1219            2 :                   gauxc_model_none = .FALSE.
    1220            2 :                   gauxc_section => get_gauxc_section(xc_section)
    1221            2 :                   IF (ASSOCIATED(gauxc_section)) THEN
    1222            2 :                      CALL section_vals_val_get(gauxc_section, "MODEL", c_val=gauxc_model_name)
    1223            2 :                      gauxc_model_name = ADJUSTL(gauxc_model_name)
    1224            2 :                      CALL uppercase(gauxc_model_name)
    1225              :                      gauxc_model_none = (TRIM(gauxc_model_name) == "" .OR. &
    1226            2 :                                          TRIM(gauxc_model_name) == "NONE")
    1227              :                   END IF
    1228            2 :                   IF (gauxc_model_none .AND. &
    1229              :                       (gapw_xc .OR. gauxc_gapw_has_paw_pseudopotentials(qs_kind_set))) THEN
    1230            0 :                      CALL accint_weight_force(qs_env, rho_struct, rho1, 0, xc_section)
    1231              :                   END IF
    1232              :                ELSE
    1233          772 :                   CALL accint_weight_force(qs_env, rho_struct, rho1, 0, xc_section)
    1234              :                END IF
    1235              :                !
    1236          774 :                IF (dft_control%do_admm) THEN
    1237           90 :                   CALL get_qs_env(qs_env, admm_env=admm_env)
    1238           90 :                   xc_section => admm_env%xc_section_aux
    1239           90 :                   CALL get_admm_env(admm_env, rho_aux_fit=rho_struct)
    1240           90 :                   vscale = 1.0_dp
    1241           90 :                   IF (admm_env%do_admmp) THEN
    1242            8 :                      vscale = admm_env%gsi(1)**2
    1243           82 :                   ELSE IF (admm_env%do_admms) THEN
    1244            6 :                      vscale = admm_env%gsi(1)**(2.0_dp/3.0_dp)
    1245              :                   END IF
    1246           90 :                   CALL accint_weight_force(qs_env, rho_struct, rho1, 0, xc_section, force_scale=vscale)
    1247              :                END IF
    1248              :             END IF
    1249              :          END IF
    1250              : 
    1251       117687 :          IF (use_virial .AND. calculate_forces) THEN
    1252         6630 :             virial%pv_ehartree = virial%pv_ehartree + (virial%pv_virial - pv_loc)
    1253              :          END IF
    1254       117687 :          IF (dft_control%qs_control%do_kg) THEN
    1255          900 :             CPASSERT(nimages == 1)
    1256          900 :             ksmat => ks_matrix(:, 1)
    1257              : 
    1258          900 :             IF (use_virial .AND. calculate_forces) THEN
    1259          208 :                pv_loc = virial%pv_virial
    1260              :             END IF
    1261              : 
    1262          900 :             CALL kg_ekin_subset(qs_env, ksmat, ekin_mol, calculate_forces, do_kernel=.FALSE.)
    1263              :             ! subtract kg corr from the total energy
    1264          900 :             energy%exc = energy%exc - ekin_mol
    1265              : 
    1266              :             ! virial corrections
    1267          900 :             IF (use_virial .AND. calculate_forces) THEN
    1268              : 
    1269              :                ! Integral contribution
    1270          208 :                virial%pv_ehartree = virial%pv_ehartree + (virial%pv_virial - pv_loc)
    1271              : 
    1272              :                ! GGA contribution
    1273          208 :                virial%pv_exc = virial%pv_exc + virial%pv_xc
    1274          208 :                virial%pv_virial = virial%pv_virial + virial%pv_xc
    1275          208 :                virial%pv_xc = 0.0_dp
    1276              :             END IF
    1277              :          END IF
    1278              : 
    1279              :       ELSE
    1280              :          IF (do_hfx) THEN
    1281              :             IF (.FALSE.) THEN
    1282              :                CPWARN("KS matrix no longer correct. Check possible problems with property calculations!")
    1283              :             END IF
    1284              :          END IF
    1285              :       END IF ! .NOT. just energy
    1286       128729 :       IF (dft_control%qs_control%ddapc_explicit_potential) THEN
    1287          164 :          CALL auxbas_pw_pool%give_back_pw(v_spin_ddapc_rest_r)
    1288          164 :          DEALLOCATE (v_spin_ddapc_rest_r)
    1289              :       END IF
    1290              : 
    1291       128729 :       IF (calculate_forces .AND. dft_control%qs_control%cdft) THEN
    1292          126 :          IF (.NOT. cdft_control%transfer_pot) THEN
    1293          230 :             DO iatom = 1, SIZE(cdft_control%group)
    1294          124 :                CALL auxbas_pw_pool%give_back_pw(cdft_control%group(iatom)%weight)
    1295          230 :                DEALLOCATE (cdft_control%group(iatom)%weight)
    1296              :             END DO
    1297          106 :             IF (cdft_control%atomic_charges) THEN
    1298           78 :                DO iatom = 1, cdft_control%natoms
    1299           78 :                   CALL auxbas_pw_pool%give_back_pw(cdft_control%charge(iatom))
    1300              :                END DO
    1301           26 :                DEALLOCATE (cdft_control%charge)
    1302              :             END IF
    1303          106 :             IF (cdft_control%type == outer_scf_becke_constraint .AND. &
    1304              :                 cdft_control%becke_control%cavity_confine) THEN
    1305           88 :                IF (.NOT. ASSOCIATED(cdft_control%becke_control%cavity_mat)) THEN
    1306           64 :                   CALL auxbas_pw_pool%give_back_pw(cdft_control%becke_control%cavity)
    1307              :                ELSE
    1308           24 :                   DEALLOCATE (cdft_control%becke_control%cavity_mat)
    1309              :                END IF
    1310           18 :             ELSE IF (cdft_control%type == outer_scf_hirshfeld_constraint) THEN
    1311            6 :                IF (ASSOCIATED(cdft_control%hirshfeld_control%hirshfeld_env%fnorm)) THEN
    1312            0 :                   CALL auxbas_pw_pool%give_back_pw(cdft_control%hirshfeld_control%hirshfeld_env%fnorm)
    1313              :                END IF
    1314              :             END IF
    1315          106 :             IF (ASSOCIATED(cdft_control%charges_fragment)) DEALLOCATE (cdft_control%charges_fragment)
    1316          106 :             cdft_control%save_pot = .FALSE.
    1317          106 :             cdft_control%need_pot = .TRUE.
    1318          106 :             cdft_control%external_control = .FALSE.
    1319              :          END IF
    1320              :       END IF
    1321              : 
    1322       128729 :       IF (dft_control%do_sccs) THEN
    1323          160 :          CALL auxbas_pw_pool%give_back_pw(v_sccs_rspace)
    1324          160 :          DEALLOCATE (v_sccs_rspace)
    1325              :       END IF
    1326              : 
    1327       128729 :       IF (gapw) THEN
    1328        22926 :          IF (dft_control%apply_external_potential) THEN
    1329              :             ! Integrals of the Hartree potential with g0_soft
    1330              :             CALL qmmm_modify_hartree_pot(v_hartree=v_hartree_rspace, &
    1331           42 :                                          v_qmmm=vee, scale=-1.0_dp)
    1332              :          END IF
    1333        22926 :          CALL integrate_vhg0_rspace(qs_env, v_hartree_rspace, para_env, calculate_forces)
    1334              :          ! Place Vh_1c_gg_integrals after integrate_vhg0_rspace for CNEO calculations
    1335              :          ! because vhg0 integral is needed to build the complete nuclear equation
    1336        22926 :          CALL get_qs_env(qs_env, ecoul_1c=ecoul_1c, local_rho_set=local_rho_set)
    1337              :          CALL Vh_1c_gg_integrals(qs_env, energy%hartree_1c, ecoul_1c, local_rho_set, para_env, tddft=.FALSE., &
    1338        22926 :                                  core_2nd=.FALSE.)
    1339              :          ! CNEO quantum nuclear core energy (kinetic + Z*erfc(r)/r potential from classical nuclei)
    1340        22926 :          energy%core_cneo = 0.0_dp
    1341        22926 :          IF (ASSOCIATED(local_rho_set%rhoz_cneo_set)) THEN
    1342          184 :             DO iatom = 1, SIZE(local_rho_set%rhoz_cneo_set)
    1343          184 :                energy%core_cneo = energy%core_cneo + local_rho_set%rhoz_cneo_set(iatom)%e_core
    1344              :             END DO
    1345              :          END IF
    1346              :       END IF
    1347              : 
    1348       128729 :       IF (gapw .OR. gapw_xc) THEN
    1349              :          ! Single atom contributions in the KS matrix ***
    1350        27230 :          CALL update_ks_atom(qs_env, ks_matrix, rho_ao, calculate_forces)
    1351        27230 :          IF (dft_control%do_admm) THEN
    1352              :             !Single atom contribution to the AUX matrices
    1353              :             !Note: also update ks_aux_fit matrix in case of rtp
    1354         4720 :             CALL admm_update_ks_atom(qs_env, calculate_forces)
    1355              :          END IF
    1356              :       END IF
    1357              : 
    1358              :       !Calculation of Mulliken restraint, if requested
    1359              :       CALL qs_ks_mulliken_restraint(energy, dft_control, just_energy, para_env, &
    1360       128729 :                                     ks_matrix, matrix_s, rho, mulliken_order_p)
    1361              : 
    1362              :       ! Add DFT+U contribution, if requested
    1363       128729 :       IF (dft_control%dft_plus_u) THEN
    1364         2734 :          IF (just_energy) THEN
    1365          746 :             CALL plus_u(qs_env=qs_env)
    1366              :          ELSE
    1367         1988 :             CALL plus_u(qs_env=qs_env, matrix_h=ks_matrix)
    1368              :          END IF
    1369              :       ELSE
    1370       125995 :          energy%dft_plus_u = 0.0_dp
    1371              :       END IF
    1372              : 
    1373              :       ! At this point the ks matrix should be up to date, filter it if requested
    1374       283481 :       DO ispin = 1, nspins
    1375      1370537 :          DO img = 1, nimages
    1376              :             CALL dbcsr_filter(ks_matrix(ispin, img)%matrix, &
    1377      1241808 :                               dft_control%qs_control%eps_filter_matrix)
    1378              :          END DO
    1379              :       END DO
    1380              : 
    1381              :       !** merge the auxiliary KS matrix and the primary one
    1382       128729 :       IF (dft_control%do_admm_mo) THEN
    1383        13152 :          IF (qs_env%run_rtp) THEN
    1384          114 :             CALL rtp_admm_merge_ks_matrix(qs_env)
    1385              :          ELSE
    1386        13038 :             CALL admm_mo_merge_ks_matrix(qs_env)
    1387              :          END IF
    1388       115577 :       ELSE IF (dft_control%do_admm_dm) THEN
    1389          214 :          CALL admm_dm_merge_ks_matrix(qs_env)
    1390              :       END IF
    1391              : 
    1392              :       ! External field (nonperiodic case)
    1393       128729 :       CALL qs_efield_local_operator(qs_env, just_energy, calculate_forces)
    1394              : 
    1395              :       ! Right now we can compute the orbital derivative here, as it depends currently only on the available
    1396              :       ! Kohn-Sham matrix. This might change in the future, in which case more pieces might need to be assembled
    1397              :       ! from this routine, notice that this part of the calculation in not linear scaling
    1398              :       ! right now this operation is only non-trivial because of occupation numbers and the restricted keyword
    1399       128729 :       IF (qs_env%requires_mo_derivs .AND. .NOT. just_energy .AND. .NOT. qs_env%run_rtp) THEN
    1400        44955 :          CALL get_qs_env(qs_env, mo_derivs=mo_derivs)
    1401        44955 :          CPASSERT(nimages == 1)
    1402        44955 :          ksmat => ks_matrix(:, 1)
    1403        44955 :          CALL calc_mo_derivatives(qs_env, ksmat, mo_derivs)
    1404              :       END IF
    1405              : 
    1406              :       ! ADMM overlap forces
    1407       128729 :       IF (calculate_forces .AND. dft_control%do_admm) THEN
    1408          316 :          IF (dokp) THEN
    1409           30 :             CALL calc_admm_ovlp_forces_kp(qs_env)
    1410              :          ELSE
    1411          286 :             CALL calc_admm_ovlp_forces(qs_env)
    1412              :          END IF
    1413              :       END IF
    1414              : 
    1415              :       ! deal with low spin roks
    1416              :       CALL low_spin_roks(energy, qs_env, dft_control, do_hfx, just_energy, &
    1417       128729 :                          calculate_forces, auxbas_pw_pool)
    1418              : 
    1419              :       ! deal with sic on explicit orbitals
    1420              :       CALL sic_explicit_orbitals(energy, qs_env, dft_control, poisson_env, just_energy, &
    1421       128729 :                                  calculate_forces, auxbas_pw_pool)
    1422              : 
    1423              :       ! Periodic external field
    1424       128729 :       CALL qs_efield_berry_phase(qs_env, just_energy, calculate_forces)
    1425              : 
    1426              :       ! adds s2_restraint energy and orbital derivatives
    1427              :       CALL qs_ks_s2_restraint(dft_control, qs_env, matrix_s, &
    1428       128729 :                               energy, calculate_forces, just_energy)
    1429              : 
    1430       128729 :       IF (do_ppl) THEN
    1431              :          ! update core energy for grid based local pseudopotential
    1432           60 :          ecore_ppl = 0._dp
    1433          126 :          DO ispin = 1, nspins
    1434          126 :             ecore_ppl = ecore_ppl + pw_integral_ab(vppl_rspace, rho_r(ispin))
    1435              :          END DO
    1436           60 :          energy%core = energy%core + ecore_ppl
    1437              :       END IF
    1438              : 
    1439       128729 :       IF (lrigpw) THEN
    1440              :          ! update core energy for ppl_ri method
    1441          496 :          CALL get_qs_env(qs_env, lri_env=lri_env, lri_density=lri_density)
    1442          496 :          IF (lri_env%ppl_ri) THEN
    1443            8 :             ecore_ppl = 0._dp
    1444           16 :             DO ispin = 1, nspins
    1445            8 :                lri_v_int => lri_density%lri_coefs(ispin)%lri_kinds
    1446           16 :                CALL v_int_ppl_energy(qs_env, lri_v_int, ecore_ppl)
    1447              :             END DO
    1448            8 :             energy%core = energy%core + ecore_ppl
    1449              :          END IF
    1450              :       END IF
    1451              : 
    1452              :       ! Sum all energy terms to obtain the total energy
    1453              :       energy%total = energy%core_overlap + energy%core_self + energy%core_cneo + energy%core + &
    1454              :                      energy%hartree + energy%hartree_1c + energy%exc + energy%exc1 + energy%ex + &
    1455              :                      energy%dispersion + energy%gcp + energy%qmmm_el + energy%mulliken + &
    1456              :                      SUM(energy%ddapc_restraint) + energy%s2_restraint + &
    1457              :                      energy%dft_plus_u + energy%kTS + &
    1458              :                      energy%efield + energy%efield_core + energy%ee + &
    1459              :                      energy%ee_core + energy%exc_aux_fit + energy%image_charge + &
    1460       257562 :                      energy%sccs_pol + energy%cdft + energy%exc1_aux_fit
    1461              : 
    1462       128729 :       IF (dft_control%apply_embed_pot) energy%total = energy%total + energy%embed_corr
    1463              : 
    1464       128729 :       IF (native_skala_restore_exc) energy%total = native_skala_total_scf
    1465              : 
    1466       128729 :       IF (abnormal_value(energy%total)) THEN
    1467            0 :          CPABORT("KS energy is an abnormal value (NaN/Inf).")
    1468              :       END IF
    1469              : 
    1470              :       ! Print detailed energy
    1471       128729 :       IF (my_print) THEN
    1472       128637 :          CALL print_detailed_energy(qs_env, dft_control, input, energy, mulliken_order_p)
    1473              :       END IF
    1474              : 
    1475       128729 :       CALL timestop(handle)
    1476              : 
    1477       386187 :    END SUBROUTINE qs_ks_build_kohn_sham_matrix
    1478              : 
    1479              : ! **************************************************************************************************
    1480              : !> \brief ...
    1481              : !> \param rho_tot_gspace ...
    1482              : !> \param qs_env ...
    1483              : !> \param rho ...
    1484              : !> \param skip_nuclear_density ...
    1485              : ! **************************************************************************************************
    1486       132487 :    SUBROUTINE calc_rho_tot_gspace(rho_tot_gspace, qs_env, rho, skip_nuclear_density)
    1487              :       TYPE(pw_c1d_gs_type), INTENT(INOUT)                :: rho_tot_gspace
    1488              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    1489              :       TYPE(qs_rho_type), POINTER                         :: rho
    1490              :       LOGICAL, INTENT(IN), OPTIONAL                      :: skip_nuclear_density
    1491              : 
    1492              :       INTEGER                                            :: ispin
    1493              :       LOGICAL                                            :: my_skip
    1494              :       TYPE(dft_control_type), POINTER                    :: dft_control
    1495       132487 :       TYPE(pw_c1d_gs_type), DIMENSION(:), POINTER        :: rho_g
    1496              :       TYPE(pw_c1d_gs_type), POINTER                      :: rho0_s_gs, rho_core, rhoz_cneo_s_gs
    1497              :       TYPE(qs_charges_type), POINTER                     :: qs_charges
    1498              : 
    1499       132487 :       my_skip = .FALSE.
    1500          960 :       IF (PRESENT(skip_nuclear_density)) my_skip = skip_nuclear_density
    1501              : 
    1502       132487 :       CALL qs_rho_get(rho, rho_g=rho_g)
    1503       132487 :       CALL get_qs_env(qs_env=qs_env, dft_control=dft_control)
    1504              : 
    1505       132487 :       IF (.NOT. my_skip) THEN
    1506       131537 :          NULLIFY (rho_core)
    1507       131537 :          CALL get_qs_env(qs_env=qs_env, rho_core=rho_core)
    1508       131537 :          IF (dft_control%qs_control%gapw) THEN
    1509        23246 :             NULLIFY (rho0_s_gs, rhoz_cneo_s_gs)
    1510        23246 :             CALL get_qs_env(qs_env=qs_env, rho0_s_gs=rho0_s_gs, rhoz_cneo_s_gs=rhoz_cneo_s_gs)
    1511        23246 :             CPASSERT(ASSOCIATED(rho0_s_gs))
    1512        23246 :             CALL pw_copy(rho0_s_gs, rho_tot_gspace)
    1513        23246 :             IF (ASSOCIATED(rhoz_cneo_s_gs)) THEN
    1514           48 :                CALL pw_axpy(rhoz_cneo_s_gs, rho_tot_gspace)
    1515              :             END IF
    1516        23246 :             IF (dft_control%qs_control%gapw_control%nopaw_as_gpw) THEN
    1517         2828 :                CALL pw_axpy(rho_core, rho_tot_gspace)
    1518              :             END IF
    1519              :          ELSE
    1520       108291 :             CALL pw_copy(rho_core, rho_tot_gspace)
    1521              :          END IF
    1522       289407 :          DO ispin = 1, dft_control%nspins
    1523       289407 :             CALL pw_axpy(rho_g(ispin), rho_tot_gspace)
    1524              :          END DO
    1525       131537 :          CALL get_qs_env(qs_env=qs_env, qs_charges=qs_charges)
    1526       131537 :          qs_charges%total_rho_gspace = pw_integrate_function(rho_tot_gspace, isign=-1)
    1527              :       ELSE
    1528         1904 :          DO ispin = 1, dft_control%nspins
    1529         1904 :             CALL pw_axpy(rho_g(ispin), rho_tot_gspace)
    1530              :          END DO
    1531              :       END IF
    1532              : 
    1533       132487 :    END SUBROUTINE calc_rho_tot_gspace
    1534              : 
    1535              : ! **************************************************************************************************
    1536              : !> \brief compute MO derivatives
    1537              : !> \param qs_env the qs_env to update
    1538              : !> \param ks_matrix ...
    1539              : !> \param mo_derivs ...
    1540              : !> \par History
    1541              : !>      01.2014 created, transferred from qs_ks_build_kohn_sham_matrix in
    1542              : !>      separate subroutine
    1543              : !> \author Dorothea Golze
    1544              : ! **************************************************************************************************
    1545        44955 :    SUBROUTINE calc_mo_derivatives(qs_env, ks_matrix, mo_derivs)
    1546              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    1547              :       TYPE(dbcsr_p_type), DIMENSION(:), POINTER          :: ks_matrix, mo_derivs
    1548              : 
    1549              :       INTEGER                                            :: ispin
    1550              :       LOGICAL                                            :: uniform_occupation
    1551        44955 :       REAL(KIND=dp), DIMENSION(:), POINTER               :: occupation_numbers
    1552              :       TYPE(cp_fm_type), POINTER                          :: mo_coeff
    1553              :       TYPE(dbcsr_type)                                   :: mo_derivs2_tmp1, mo_derivs2_tmp2
    1554              :       TYPE(dbcsr_type), POINTER                          :: mo_coeff_b
    1555              :       TYPE(dft_control_type), POINTER                    :: dft_control
    1556        44955 :       TYPE(mo_set_type), DIMENSION(:), POINTER           :: mo_array
    1557              : 
    1558        44955 :       NULLIFY (dft_control, mo_array, mo_coeff, mo_coeff_b, occupation_numbers)
    1559              : 
    1560              :       CALL get_qs_env(qs_env, &
    1561              :                       dft_control=dft_control, &
    1562        44955 :                       mos=mo_array)
    1563              : 
    1564        98821 :       DO ispin = 1, SIZE(mo_derivs)
    1565              : 
    1566              :          CALL get_mo_set(mo_set=mo_array(ispin), mo_coeff=mo_coeff, &
    1567        53866 :                          mo_coeff_b=mo_coeff_b, occupation_numbers=occupation_numbers)
    1568              :          CALL dbcsr_multiply('n', 'n', 1.0_dp, ks_matrix(ispin)%matrix, mo_coeff_b, &
    1569        53866 :                              0.0_dp, mo_derivs(ispin)%matrix)
    1570              : 
    1571        98821 :          IF (dft_control%restricted) THEN
    1572              :             ! only the first mo_set are actual variables, but we still need both
    1573          636 :             CPASSERT(ispin == 1)
    1574          636 :             CPASSERT(SIZE(mo_array) == 2)
    1575              :             ! use a temporary array with the same size as the first spin for the second spin
    1576              : 
    1577              :             ! uniform_occupation is needed for this case, otherwise we can not
    1578              :             ! reconstruct things in ot, since we irreversibly sum
    1579          636 :             CALL get_mo_set(mo_set=mo_array(1), uniform_occupation=uniform_occupation)
    1580          636 :             CPASSERT(uniform_occupation)
    1581          636 :             CALL get_mo_set(mo_set=mo_array(2), uniform_occupation=uniform_occupation)
    1582          636 :             CPASSERT(uniform_occupation)
    1583              : 
    1584              :             ! The beta-spin might have fewer orbitals than alpa-spin...
    1585              :             ! create temporary matrices with beta_nmo columns
    1586          636 :             CALL get_mo_set(mo_set=mo_array(2), mo_coeff_b=mo_coeff_b)
    1587          636 :             CALL dbcsr_create(mo_derivs2_tmp1, template=mo_coeff_b)
    1588              : 
    1589              :             ! calculate beta derivatives
    1590          636 :             CALL dbcsr_multiply('n', 'n', 1.0_dp, ks_matrix(2)%matrix, mo_coeff_b, 0.0_dp, mo_derivs2_tmp1)
    1591              : 
    1592              :             ! create larger matrix with alpha_nmo columns
    1593          636 :             CALL dbcsr_create(mo_derivs2_tmp2, template=mo_derivs(1)%matrix)
    1594          636 :             CALL dbcsr_set(mo_derivs2_tmp2, 0.0_dp)
    1595              : 
    1596              :             ! copy into larger matrix, fills the first beta_nmo columns
    1597              :             CALL dbcsr_copy_columns_hack(mo_derivs2_tmp2, mo_derivs2_tmp1, &
    1598              :                                          mo_array(2)%nmo, 1, 1, &
    1599              :                                          para_env=mo_array(1)%mo_coeff%matrix_struct%para_env, &
    1600          636 :                                          blacs_env=mo_array(1)%mo_coeff%matrix_struct%context)
    1601              : 
    1602              :             ! add beta contribution to alpa mo_derivs
    1603          636 :             CALL dbcsr_add(mo_derivs(1)%matrix, mo_derivs2_tmp2, 1.0_dp, 1.0_dp)
    1604          636 :             CALL dbcsr_release(mo_derivs2_tmp1)
    1605          636 :             CALL dbcsr_release(mo_derivs2_tmp2)
    1606              :          END IF
    1607              :       END DO
    1608              : 
    1609        44955 :       IF (dft_control%do_admm_mo) THEN
    1610         6802 :          CALL calc_admm_mo_derivatives(qs_env, mo_derivs)
    1611              :       END IF
    1612              : 
    1613        44955 :    END SUBROUTINE calc_mo_derivatives
    1614              : 
    1615              : ! **************************************************************************************************
    1616              : !> \brief updates the Kohn Sham matrix of the given qs_env (facility method)
    1617              : !> \param qs_env the qs_env to update
    1618              : !> \param calculate_forces if true calculate the quantities needed
    1619              : !>        to calculate the forces. Defaults to false.
    1620              : !> \param just_energy if true updates the energies but not the
    1621              : !>        ks matrix. Defaults to false
    1622              : !> \param print_active ...
    1623              : !> \par History
    1624              : !>      4.2002 created [fawzi]
    1625              : !>      8.2014 kpoints [JGH]
    1626              : !>     10.2014 refractored [Ole Schuett]
    1627              : !> \author Fawzi Mohamed
    1628              : ! **************************************************************************************************
    1629       274544 :    SUBROUTINE qs_ks_update_qs_env(qs_env, calculate_forces, just_energy, &
    1630              :                                   print_active)
    1631              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    1632              :       LOGICAL, INTENT(IN), OPTIONAL                      :: calculate_forces, just_energy, &
    1633              :                                                             print_active
    1634              : 
    1635              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'qs_ks_update_qs_env'
    1636              : 
    1637              :       INTEGER                                            :: handle, unit_nr
    1638              :       LOGICAL                                            :: c_forces, do_rebuild, energy_only, &
    1639              :                                                             forces_up_to_date, potential_changed, &
    1640              :                                                             rho_changed, s_mstruct_changed
    1641              :       TYPE(qs_ks_env_type), POINTER                      :: ks_env
    1642              : 
    1643       274544 :       NULLIFY (ks_env)
    1644       274544 :       unit_nr = cp_logger_get_default_io_unit()
    1645              : 
    1646       274544 :       c_forces = .FALSE.
    1647       274544 :       energy_only = .FALSE.
    1648       274544 :       IF (PRESENT(just_energy)) energy_only = just_energy
    1649       274544 :       IF (PRESENT(calculate_forces)) c_forces = calculate_forces
    1650              : 
    1651       274544 :       IF (c_forces) THEN
    1652        10581 :          CALL timeset(routineN//'_forces', handle)
    1653              :       ELSE
    1654       263963 :          CALL timeset(routineN, handle)
    1655              :       END IF
    1656              : 
    1657       274544 :       CPASSERT(ASSOCIATED(qs_env))
    1658              : 
    1659              :       CALL get_qs_env(qs_env, &
    1660              :                       ks_env=ks_env, &
    1661              :                       rho_changed=rho_changed, &
    1662              :                       s_mstruct_changed=s_mstruct_changed, &
    1663              :                       potential_changed=potential_changed, &
    1664       274544 :                       forces_up_to_date=forces_up_to_date)
    1665              : 
    1666       274544 :       do_rebuild = .FALSE.
    1667       274544 :       do_rebuild = do_rebuild .OR. rho_changed
    1668         8879 :       do_rebuild = do_rebuild .OR. s_mstruct_changed
    1669         8879 :       do_rebuild = do_rebuild .OR. potential_changed
    1670         8879 :       do_rebuild = do_rebuild .OR. (c_forces .AND. .NOT. forces_up_to_date)
    1671              : 
    1672              :       IF (do_rebuild) THEN
    1673       266045 :          CALL evaluate_core_matrix_traces(qs_env)
    1674              : 
    1675              :          ! the ks matrix will be rebuilt so this is fine now
    1676       266045 :          CALL set_ks_env(ks_env, potential_changed=.FALSE.)
    1677              : 
    1678              :          CALL rebuild_ks_matrix(qs_env, &
    1679              :                                 calculate_forces=c_forces, &
    1680              :                                 just_energy=energy_only, &
    1681       266045 :                                 print_active=print_active)
    1682              : 
    1683       266045 :          IF (.NOT. energy_only) THEN
    1684              :             CALL set_ks_env(ks_env, &
    1685              :                             rho_changed=.FALSE., &
    1686              :                             s_mstruct_changed=.FALSE., &
    1687       488457 :                             forces_up_to_date=forces_up_to_date .OR. c_forces)
    1688              :          END IF
    1689              :       END IF
    1690              : 
    1691       274544 :       CALL timestop(handle)
    1692              : 
    1693       274544 :    END SUBROUTINE qs_ks_update_qs_env
    1694              : 
    1695              : ! **************************************************************************************************
    1696              : !> \brief Calculates the traces of the core matrices and the density matrix.
    1697              : !> \param qs_env ...
    1698              : !> \param rho_ao_ext ...
    1699              : !> \author Ole Schuett
    1700              : ! **************************************************************************************************
    1701       291357 :    SUBROUTINE evaluate_core_matrix_traces(qs_env, rho_ao_ext)
    1702              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    1703              :       TYPE(dbcsr_p_type), DIMENSION(:, :), OPTIONAL, &
    1704              :          POINTER                                         :: rho_ao_ext
    1705              : 
    1706              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'evaluate_core_matrix_traces'
    1707              : 
    1708              :       INTEGER                                            :: handle
    1709              :       REAL(KIND=dp)                                      :: energy_core_im
    1710       291357 :       TYPE(dbcsr_p_type), DIMENSION(:, :), POINTER       :: matrixkp_h, matrixkp_t, rho_ao_kp
    1711              :       TYPE(dft_control_type), POINTER                    :: dft_control
    1712              :       TYPE(qs_energy_type), POINTER                      :: energy
    1713              :       TYPE(qs_rho_type), POINTER                         :: rho
    1714              : 
    1715       291357 :       CALL timeset(routineN, handle)
    1716       291357 :       NULLIFY (energy, rho, dft_control, rho_ao_kp, matrixkp_t, matrixkp_h)
    1717              : 
    1718              :       CALL get_qs_env(qs_env, &
    1719              :                       rho=rho, &
    1720              :                       energy=energy, &
    1721              :                       dft_control=dft_control, &
    1722              :                       kinetic_kp=matrixkp_t, &
    1723       291357 :                       matrix_h_kp=matrixkp_h)
    1724              : 
    1725       291357 :       IF (PRESENT(rho_ao_ext)) THEN
    1726        24596 :          rho_ao_kp => rho_ao_ext
    1727              :       ELSE
    1728       266761 :          CALL qs_rho_get(rho, rho_ao_kp=rho_ao_kp)
    1729              :       END IF
    1730              : 
    1731       291357 :       CALL calculate_ptrace(matrixkp_h, rho_ao_kp, energy%core, dft_control%nspins)
    1732              : 
    1733              :       ! Add the imaginary part in the RTP case
    1734       291357 :       IF (qs_env%run_rtp) THEN
    1735         3350 :          IF (dft_control%rtp_control%velocity_gauge) THEN
    1736          182 :             CALL get_qs_env(qs_env, matrix_h_im_kp=matrixkp_h)
    1737          182 :             CALL qs_rho_get(rho, rho_ao_im_kp=rho_ao_kp)
    1738          182 :             CALL calculate_ptrace(matrixkp_h, rho_ao_kp, energy_core_im, dft_control%nspins)
    1739          182 :             energy%core = energy%core - energy_core_im
    1740              :          END IF
    1741              :       END IF
    1742              : 
    1743              :       ! kinetic energy
    1744       291357 :       IF (ASSOCIATED(matrixkp_t)) THEN
    1745       128403 :          CALL calculate_ptrace(matrixkp_t, rho_ao_kp, energy%kinetic, dft_control%nspins)
    1746              :       END IF
    1747              : 
    1748       291357 :       CALL timestop(handle)
    1749       291357 :    END SUBROUTINE evaluate_core_matrix_traces
    1750              : 
    1751              : ! **************************************************************************************************
    1752              : !> \brief Constructs a new Khon-Sham matrix
    1753              : !> \param qs_env ...
    1754              : !> \param calculate_forces ...
    1755              : !> \param just_energy ...
    1756              : !> \param print_active ...
    1757              : !> \author Ole Schuett
    1758              : ! **************************************************************************************************
    1759       266065 :    SUBROUTINE rebuild_ks_matrix(qs_env, calculate_forces, just_energy, print_active)
    1760              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    1761              :       LOGICAL, INTENT(IN)                                :: calculate_forces, just_energy
    1762              :       LOGICAL, INTENT(IN), OPTIONAL                      :: print_active
    1763              : 
    1764              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'rebuild_ks_matrix'
    1765              : 
    1766              :       INTEGER                                            :: handle
    1767              :       TYPE(dft_control_type), POINTER                    :: dft_control
    1768              : 
    1769       266065 :       CALL timeset(routineN, handle)
    1770       266065 :       NULLIFY (dft_control)
    1771              : 
    1772       266065 :       CALL get_qs_env(qs_env, dft_control=dft_control)
    1773              : 
    1774       266065 :       IF (dft_control%qs_control%semi_empirical) THEN
    1775              :          CALL build_se_fock_matrix(qs_env, &
    1776              :                                    calculate_forces=calculate_forces, &
    1777        41348 :                                    just_energy=just_energy)
    1778              : 
    1779       224717 :       ELSE IF (dft_control%qs_control%dftb) THEN
    1780              :          CALL build_dftb_ks_matrix(qs_env, &
    1781              :                                    calculate_forces=calculate_forces, &
    1782        30460 :                                    just_energy=just_energy)
    1783              : 
    1784       194257 :       ELSE IF (dft_control%qs_control%xtb) THEN
    1785        65842 :          IF (dft_control%qs_control%xtb_control%do_tblite) THEN
    1786              :             CALL build_tblite_ks_matrix(qs_env, &
    1787              :                                         calculate_forces=calculate_forces, &
    1788        27900 :                                         just_energy=just_energy)
    1789              :          ELSE
    1790              :             CALL build_xtb_ks_matrix(qs_env, &
    1791              :                                      calculate_forces=calculate_forces, &
    1792        37942 :                                      just_energy=just_energy)
    1793              :          END IF
    1794              :       ELSE
    1795              :          CALL qs_ks_build_kohn_sham_matrix(qs_env, &
    1796              :                                            calculate_forces=calculate_forces, &
    1797              :                                            just_energy=just_energy, &
    1798       128415 :                                            print_active=print_active)
    1799              :       END IF
    1800              : 
    1801       266065 :       CALL timestop(handle)
    1802              : 
    1803       266065 :    END SUBROUTINE rebuild_ks_matrix
    1804              : 
    1805              : ! **************************************************************************************************
    1806              : !> \brief Allocate ks_matrix if necessary, take current overlap matrix as template
    1807              : !> \param qs_env ...
    1808              : !> \param is_complex ...
    1809              : !> \par History
    1810              : !>    refactoring 04.03.2011 [MI]
    1811              : !> \author
    1812              : ! **************************************************************************************************
    1813              : 
    1814        28920 :    SUBROUTINE qs_ks_allocate_basics(qs_env, is_complex)
    1815              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    1816              :       LOGICAL, INTENT(in)                                :: is_complex
    1817              : 
    1818              :       CHARACTER(LEN=default_string_length)               :: headline
    1819              :       INTEGER                                            :: ic, ispin, nimages, nspins
    1820              :       LOGICAL                                            :: do_kpoints
    1821        28920 :       TYPE(dbcsr_p_type), DIMENSION(:, :), POINTER       :: matrix_s_kp, matrixkp_im_ks, matrixkp_ks
    1822              :       TYPE(dbcsr_type), POINTER                          :: refmatrix
    1823              :       TYPE(dft_control_type), POINTER                    :: dft_control
    1824              :       TYPE(kpoint_type), POINTER                         :: kpoints
    1825              :       TYPE(neighbor_list_set_p_type), DIMENSION(:), &
    1826        28920 :          POINTER                                         :: sab_orb
    1827              :       TYPE(qs_ks_env_type), POINTER                      :: ks_env
    1828              : 
    1829        28920 :       NULLIFY (dft_control, ks_env, matrix_s_kp, sab_orb, matrixkp_ks, refmatrix, matrixkp_im_ks, kpoints)
    1830              : 
    1831              :       CALL get_qs_env(qs_env, &
    1832              :                       dft_control=dft_control, &
    1833              :                       matrix_s_kp=matrix_s_kp, &
    1834              :                       ks_env=ks_env, &
    1835              :                       kpoints=kpoints, &
    1836              :                       do_kpoints=do_kpoints, &
    1837              :                       matrix_ks_kp=matrixkp_ks, &
    1838        28920 :                       matrix_ks_im_kp=matrixkp_im_ks)
    1839              : 
    1840        28920 :       IF (do_kpoints) THEN
    1841         3620 :          CALL get_kpoint_info(kpoints, sab_nl=sab_orb)
    1842              :       ELSE
    1843        25300 :          CALL get_qs_env(qs_env, sab_orb=sab_orb)
    1844              :       END IF
    1845              : 
    1846        28920 :       nspins = dft_control%nspins
    1847        28920 :       nimages = dft_control%nimages
    1848              : 
    1849        28920 :       IF (.NOT. ASSOCIATED(matrixkp_ks)) THEN
    1850        28870 :          CALL dbcsr_allocate_matrix_set(matrixkp_ks, nspins, nimages)
    1851        28870 :          refmatrix => matrix_s_kp(1, 1)%matrix
    1852        61640 :          DO ispin = 1, nspins
    1853       345282 :             DO ic = 1, nimages
    1854       283642 :                IF (nspins > 1) THEN
    1855        50064 :                   IF (ispin == 1) THEN
    1856        25032 :                      headline = "KOHN-SHAM MATRIX FOR ALPHA SPIN"
    1857              :                   ELSE
    1858        25032 :                      headline = "KOHN-SHAM MATRIX FOR BETA SPIN"
    1859              :                   END IF
    1860              :                ELSE
    1861       233578 :                   headline = "KOHN-SHAM MATRIX"
    1862              :                END IF
    1863       283642 :                ALLOCATE (matrixkp_ks(ispin, ic)%matrix)
    1864              :                CALL dbcsr_create(matrix=matrixkp_ks(ispin, ic)%matrix, template=refmatrix, &
    1865       283642 :                                  name=TRIM(headline), matrix_type=dbcsr_type_symmetric)
    1866       283642 :                CALL cp_dbcsr_alloc_block_from_nbl(matrixkp_ks(ispin, ic)%matrix, sab_orb)
    1867       316412 :                CALL dbcsr_set(matrixkp_ks(ispin, ic)%matrix, 0.0_dp)
    1868              :             END DO
    1869              :          END DO
    1870        28870 :          CALL set_ks_env(ks_env, matrix_ks_kp=matrixkp_ks)
    1871              :       END IF
    1872              : 
    1873        28920 :       IF (is_complex) THEN
    1874          174 :          IF (.NOT. ASSOCIATED(matrixkp_im_ks)) THEN
    1875          174 :             CPASSERT(nspins == SIZE(matrixkp_ks, 1))
    1876          174 :             CPASSERT(nimages == SIZE(matrixkp_ks, 2))
    1877          174 :             CALL dbcsr_allocate_matrix_set(matrixkp_im_ks, nspins, nimages)
    1878          372 :             DO ispin = 1, nspins
    1879          570 :                DO ic = 1, nimages
    1880          198 :                   IF (nspins > 1) THEN
    1881           48 :                      IF (ispin == 1) THEN
    1882           24 :                         headline = "IMAGINARY KOHN-SHAM MATRIX FOR ALPHA SPIN"
    1883              :                      ELSE
    1884           24 :                         headline = "IMAGINARY KOHN-SHAM MATRIX FOR BETA SPIN"
    1885              :                      END IF
    1886              :                   ELSE
    1887          150 :                      headline = "IMAGINARY KOHN-SHAM MATRIX"
    1888              :                   END IF
    1889          198 :                   ALLOCATE (matrixkp_im_ks(ispin, ic)%matrix)
    1890          198 :                   refmatrix => matrixkp_ks(ispin, ic)%matrix  ! base on real part, but anti-symmetric
    1891              :                   CALL dbcsr_create(matrix=matrixkp_im_ks(ispin, ic)%matrix, template=refmatrix, &
    1892          198 :                                     name=TRIM(headline), matrix_type=dbcsr_type_antisymmetric)
    1893          198 :                   CALL cp_dbcsr_alloc_block_from_nbl(matrixkp_im_ks(ispin, ic)%matrix, sab_orb)
    1894          396 :                   CALL dbcsr_set(matrixkp_im_ks(ispin, ic)%matrix, 0.0_dp)
    1895              :                END DO
    1896              :             END DO
    1897          174 :             CALL set_ks_env(ks_env, matrix_ks_im_kp=matrixkp_im_ks)
    1898              :          END IF
    1899              :       END IF
    1900              : 
    1901        28920 :    END SUBROUTINE qs_ks_allocate_basics
    1902              : 
    1903              : END MODULE qs_ks_methods
        

Generated by: LCOV version 2.0-1