LCOV - code coverage report
Current view: top level - src/tb - tblite_interface.F (source / functions) Coverage Total Hit
Test: CP2K Regtests (git:1be8651) Lines: 97.2 % 980 953
Test Date: 2026-11-24 01:22:08 Functions: 100.0 % 31 31

            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 interface to tblite
      10              : !> \author JVP
      11              : !> \history creation 09.2024
      12              : ! **************************************************************************************************
      13              : 
      14              : MODULE tblite_interface
      15              : 
      16              : #if defined(__TBLITE)
      17              :    USE mctc_env, ONLY: error_type
      18              :    USE mctc_io, ONLY: new
      19              :    USE mctc_io_symbols, ONLY: symbol_to_number
      20              :    USE tblite_basis_type, ONLY: get_cutoff
      21              :    USE tblite_container_cache, ONLY: container_cache
      22              :    USE tblite_container_type, ONLY: container_type
      23              :    USE tblite_data_spin, ONLY: get_spin_constant
      24              :    USE tblite_integral_native_integrals, ONLY: multipole_cgto, multipole_grad_cgto, overlap_grad_cgto, msao
      25              :    USE tblite_partition, ONLY: work_partition, new_work_partition
      26              :    USE tblite_scf, ONLY: get_mixer_dimension
      27              :    USE tblite_scf_info, ONLY: scf_info, atom_resolved, shell_resolved
      28              :    USE tblite_scf_potential, ONLY: new_potential
      29              :    USE tblite_spin, ONLY: spin_polarization, new_spin_polarization
      30              :    USE tblite_wavefunction_type, ONLY: new_wavefunction
      31              :    USE tblite_xtb_calculator, ONLY: new_xtb_calculator
      32              :    USE tblite_xtb_gfn1, ONLY: new_gfn1_calculator
      33              :    USE tblite_xtb_gfn2, ONLY: new_gfn2_calculator
      34              :    USE tblite_xtb_h0, ONLY: get_selfenergy, get_occupation, tb_hamiltonian
      35              :    USE tblite_xtb_ipea1, ONLY: new_ipea1_calculator
      36              : #endif
      37              :    USE ai_contraction, ONLY: block_add, contraction
      38              :    USE ai_overlap, ONLY: overlap_ab
      39              :    USE atomic_kind_types, ONLY: atomic_kind_type, get_atomic_kind, get_atomic_kind_set
      40              :    USE atprop_types, ONLY: atprop_type
      41              :    USE basis_set_types, ONLY: gto_basis_set_type, gto_basis_set_p_type, allocate_gto_basis_set, &
      42              :                               process_gto_basis
      43              :    USE block_p_types, ONLY: block_p_type
      44              :    USE cell_types, ONLY: cell_type, get_cell
      45              :    USE cp_blacs_env, ONLY: cp_blacs_env_type
      46              :    USE cp_control_types, ONLY: dft_control_type
      47              :    USE cp_dbcsr_api, ONLY: dbcsr_p_type, dbcsr_create, dbcsr_add, dbcsr_copy, &
      48              :                            dbcsr_get_block_p, dbcsr_finalize, dbcsr_iterator_type, &
      49              :                            dbcsr_iterator_blocks_left, dbcsr_iterator_start, dbcsr_iterator_stop, &
      50              :                            dbcsr_iterator_next_block
      51              :    USE cp_dbcsr_contrib, ONLY: dbcsr_dot
      52              :    USE cp_dbcsr_cp2k_link, ONLY: cp_dbcsr_alloc_block_from_nbl
      53              :    USE cp_dbcsr_operations, ONLY: dbcsr_allocate_matrix_set, dbcsr_deallocate_matrix_set
      54              :    USE cp_log_handling, ONLY: cp_get_default_logger, cp_logger_type, cp_logger_get_default_io_unit
      55              :    USE cp_output_handling, ONLY: cp_print_key_should_output, cp_print_key_unit_nr, &
      56              :                                  cp_print_key_finished_output
      57              :    USE input_constants, ONLY: gfn1xtb, gfn2xtb, ipea1xtb, tblite_scc_mixer_auto, tblite_scc_mixer_cp2k, &
      58              :                               tblite_scc_mixer_none, tblite_scc_mixer_tblite, tblite_solver_gvd, &
      59              :                               tblite_solver_gvr
      60              :    USE input_section_types, ONLY: section_vals_val_get, section_vals_get_subs_vals, section_vals_type
      61              :    USE kinds, ONLY: default_string_length, dp, int_8
      62              :    USE kpoint_types, ONLY: get_kpoint_info, kpoint_type
      63              :    USE memory_utilities, ONLY: reallocate
      64              :    USE message_passing, ONLY: mp_para_env_type
      65              :    USE orbital_pointers, ONLY: ncoset
      66              :    USE particle_types, ONLY: particle_type
      67              :    USE qs_charge_mixing, ONLY: charge_mixing, tblite_scc_error_on_cp2k_scale, tblite_scc_pconv
      68              :    USE qs_condnum, ONLY: overlap_condnum
      69              :    USE qs_density_mixing_types, ONLY: modified_broyden_mixing_nr
      70              :    USE qs_energy_types, ONLY: qs_energy_type
      71              :    USE qs_environment_types, ONLY: get_qs_env, qs_environment_type
      72              :    USE qs_force_types, ONLY: qs_force_type
      73              :    USE qs_integral_utils, ONLY: basis_set_list_setup, get_memory_usage
      74              :    USE qs_kind_types, ONLY: get_qs_kind, qs_kind_type, get_qs_kind_set
      75              :    USE qs_ks_types, ONLY: get_ks_env, qs_ks_env_type, set_ks_env
      76              :    USE qs_neighbor_list_types, ONLY: neighbor_list_set_p_type
      77              :    USE qs_overlap, ONLY: create_sab_matrix
      78              :    USE qs_rho_types, ONLY: qs_rho_get, qs_rho_type
      79              :    USE qs_scf_types, ONLY: qs_scf_env_type
      80              :    USE scf_control_types, ONLY: scf_control_type
      81              :    USE string_utilities, ONLY: integer_to_string
      82              : #if defined(__TBLITE)
      83              :    USE tblite_scc_mixer, ONLY: new_cp2k_tblite_mixer
      84              : #endif
      85              :    USE tblite_types, ONLY: tblite_type, allocate_tblite_type
      86              :    USE virial_methods, ONLY: virial_pair_force
      87              :    USE virial_types, ONLY: virial_type
      88              :    USE xtb_types, ONLY: get_xtb_atom_param, xtb_atom_type
      89              : 
      90              : !$ USE OMP_LIB, ONLY: omp_destroy_lock, omp_init_lock, omp_set_lock, &
      91              : !$                    omp_unset_lock, omp_lock_kind
      92              : 
      93              : #include "../base/base_uses.f90"
      94              :    IMPLICIT NONE
      95              : 
      96              :    PRIVATE
      97              : 
      98              :    CHARACTER(len=*), PARAMETER, PRIVATE :: moduleN = 'tblite_interface'
      99              : 
     100              :    INTEGER, PARAMETER                                 :: dip_n = 3
     101              :    INTEGER, PARAMETER                                 :: quad_n = 6
     102              :    REAL(KIND=dp), PARAMETER                           :: same_atom = 0.00001_dp
     103              : 
     104              :    PUBLIC :: tb_set_calculator, tb_init_geometry, tb_init_wf
     105              :    PUBLIC :: tb_get_basis, tb_init_ham, build_tblite_matrices
     106              :    PUBLIC :: tb_get_energy, tb_update_charges, tb_ham_add_coulomb
     107              :    PUBLIC :: tb_native_scc_mixer_active
     108              :    PUBLIC :: tb_scf_mixer_error
     109              :    PUBLIC :: tb_get_multipole
     110              :    PUBLIC :: tb_derive_dH_off
     111              : 
     112              : CONTAINS
     113              : 
     114              : #if defined(__TBLITE)
     115              : ! **************************************************************************************************
     116              : !> \brief Project a tblite charge/magnetization quantity to a CP2K spin channel.
     117              : !> \param values ...
     118              : !> \param ispin ...
     119              : !> \return ...
     120              : ! **************************************************************************************************
     121      1936480 :    PURE FUNCTION tb_spin_project(values, ispin) RESULT(value)
     122              : 
     123              :       REAL(KIND=dp), DIMENSION(:), INTENT(IN)            :: values
     124              :       INTEGER, INTENT(IN)                                :: ispin
     125              :       REAL(KIND=dp)                                      :: value
     126              : 
     127      1936480 :       value = values(1)
     128      1936480 :       IF (SIZE(values) > 1) THEN
     129       256452 :          SELECT CASE (ispin)
     130              :          CASE (1)
     131        85484 :             value = values(1) + values(2)
     132              :          CASE (2)
     133        85484 :             value = values(1) - values(2)
     134              :          CASE DEFAULT
     135       170968 :             value = values(1)
     136              :          END SELECT
     137              :       END IF
     138              : 
     139      1936480 :    END FUNCTION tb_spin_project
     140              : 
     141              : ! **************************************************************************************************
     142              : !> \brief Preserve spin-resolved density before force assembly combines spin channels.
     143              : !> \param tb ...
     144              : !> \param matrix_p ...
     145              : ! **************************************************************************************************
     146           22 :    SUBROUTINE tb_store_density_ref(tb, matrix_p)
     147              : 
     148              :       TYPE(tblite_type), POINTER                         :: tb
     149              :       TYPE(dbcsr_p_type), DIMENSION(:, :), POINTER       :: matrix_p
     150              : 
     151              :       INTEGER                                            :: img, ispin, nimg, nspin
     152              : 
     153           22 :       nspin = SIZE(matrix_p, 1)
     154           22 :       nimg = SIZE(matrix_p, 2)
     155           22 :       IF (ASSOCIATED(tb%rho_ao_kp_ref)) THEN
     156            2 :          IF (SIZE(tb%rho_ao_kp_ref, 1) /= nspin .OR. SIZE(tb%rho_ao_kp_ref, 2) /= nimg) THEN
     157            0 :             CALL dbcsr_deallocate_matrix_set(tb%rho_ao_kp_ref)
     158              :          END IF
     159              :       END IF
     160           22 :       IF (.NOT. ASSOCIATED(tb%rho_ao_kp_ref)) THEN
     161           20 :          CALL dbcsr_allocate_matrix_set(tb%rho_ao_kp_ref, nspin, nimg)
     162           94 :          DO img = 1, nimg
     163          242 :             DO ispin = 1, nspin
     164          222 :                ALLOCATE (tb%rho_ao_kp_ref(ispin, img)%matrix)
     165              :             END DO
     166              :          END DO
     167              :       END IF
     168          152 :       DO img = 1, nimg
     169          412 :          DO ispin = 1, nspin
     170          390 :             CALL dbcsr_copy(tb%rho_ao_kp_ref(ispin, img)%matrix, matrix_p(ispin, img)%matrix)
     171              :          END DO
     172              :       END DO
     173              : 
     174           22 :    END SUBROUTINE tb_store_density_ref
     175              : #endif
     176              : 
     177              : ! **************************************************************************************************
     178              : !> \brief intialize geometry objects ...
     179              : !> \param qs_env ...
     180              : !> \param tb ...
     181              : ! **************************************************************************************************
     182          198 :    SUBROUTINE tb_init_geometry(qs_env, tb)
     183              : 
     184              :       TYPE(qs_environment_type), POINTER                 :: qs_env
     185              :       TYPE(tblite_type), POINTER                         :: tb
     186              : 
     187              : #if defined(__TBLITE)
     188              : 
     189              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'tblite_init_geometry'
     190              : 
     191              :       TYPE(cell_type), POINTER                           :: cell
     192          198 :       TYPE(particle_type), DIMENSION(:), POINTER         :: particle_set
     193          198 :       TYPE(qs_kind_type), DIMENSION(:), POINTER          :: qs_kind_set
     194              :       INTEGER                                            :: iatom, natom
     195              :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :)        :: xyz
     196              :       INTEGER                                            :: handle, ikind
     197              :       INTEGER, DIMENSION(3)                              :: periodic
     198              :       LOGICAL, DIMENSION(3)                              :: lperiod
     199              : 
     200          198 :       CALL timeset(routineN, handle)
     201              : 
     202              :       !get info from environment vaiarable
     203          198 :       CALL get_qs_env(qs_env=qs_env, particle_set=particle_set, cell=cell, qs_kind_set=qs_kind_set)
     204              : 
     205              :       !get information about particles
     206          198 :       natom = SIZE(particle_set)
     207          594 :       ALLOCATE (xyz(3, natom))
     208          198 :       CALL allocate_tblite_type(tb)
     209          594 :       ALLOCATE (tb%el_num(natom))
     210         1182 :       tb%el_num = -9
     211         1182 :       DO iatom = 1, natom
     212         3936 :          xyz(:, iatom) = particle_set(iatom)%r(:)
     213          984 :          CALL get_atomic_kind(particle_set(iatom)%atomic_kind, kind_number=ikind)
     214          984 :          CALL get_qs_kind(qs_kind_set(ikind), zatom=tb%el_num(iatom))
     215         2166 :          IF (tb%el_num(iatom) < 1 .OR. tb%el_num(iatom) > 85) THEN
     216            0 :             CPABORT("only elements 1-85 are supported by tblite")
     217              :          END IF
     218              :       END DO
     219              : 
     220              :       !get information about cell / lattice
     221          198 :       CALL get_cell(cell=cell, periodic=periodic)
     222          198 :       lperiod(1) = periodic(1) == 1
     223          198 :       lperiod(2) = periodic(2) == 1
     224          198 :       lperiod(3) = periodic(3) == 1
     225              : 
     226              :       !prepare for the call to the dispersion function
     227          198 :       CALL new(tb%mol, tb%el_num, xyz, lattice=cell%hmat, periodic=lperiod)
     228              : 
     229          198 :       DEALLOCATE (xyz)
     230              : 
     231          198 :       CALL timestop(handle)
     232              : 
     233              : #else
     234              :       MARK_USED(qs_env)
     235              :       MARK_USED(tb)
     236              :       CPABORT("Built without TBLITE")
     237              : #endif
     238              : 
     239          198 :    END SUBROUTINE tb_init_geometry
     240              : 
     241              : ! **************************************************************************************************
     242              : !> \brief updating coordinates...
     243              : !> \param qs_env ...
     244              : !> \param tb ...
     245              : ! **************************************************************************************************
     246         2616 :    SUBROUTINE tb_update_geometry(qs_env, tb)
     247              : 
     248              :       TYPE(qs_environment_type)                          :: qs_env
     249              :       TYPE(tblite_type)                                  :: tb
     250              : 
     251              : #if defined(__TBLITE)
     252              : 
     253              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'tblite_update_geometry'
     254              : 
     255              :       TYPE(cell_type), POINTER                           :: cell
     256         2616 :       TYPE(particle_type), DIMENSION(:), POINTER         :: particle_set
     257              :       INTEGER                                            :: iatom, natom
     258              :       INTEGER                                            :: handle
     259              : 
     260         2616 :       CALL timeset(routineN, handle)
     261              : 
     262              :       !get info from environment vaiarable
     263         2616 :       NULLIFY (cell)
     264         2616 :       CALL get_qs_env(qs_env=qs_env, particle_set=particle_set, cell=cell)
     265              : 
     266              :       !get information about particles
     267         2616 :       natom = SIZE(particle_set)
     268        13928 :       DO iatom = 1, natom
     269        47864 :          tb%mol%xyz(:, iatom) = particle_set(iatom)%r(:)
     270              :       END DO
     271        34008 :       tb%mol%lattice(:, :) = cell%hmat
     272              : 
     273         2616 :       CALL timestop(handle)
     274              : 
     275              : #else
     276              :       MARK_USED(qs_env)
     277              :       MARK_USED(tb)
     278              :       CPABORT("Built without TBLITE")
     279              : #endif
     280              : 
     281         2616 :    END SUBROUTINE tb_update_geometry
     282              : 
     283              : ! **************************************************************************************************
     284              : !> \brief initialize wavefunction ...
     285              : !> \param tb ...
     286              : !> \param dft_control ...
     287              : ! **************************************************************************************************
     288          198 :    SUBROUTINE tb_init_wf(tb, dft_control)
     289              : 
     290              :       TYPE(tblite_type), POINTER                         :: tb
     291              :       TYPE(dft_control_type), POINTER                    :: dft_control
     292              : 
     293              : #if defined(__TBLITE)
     294              : 
     295              :       INTEGER                                            :: nSpin
     296              : 
     297              :       TYPE(scf_info)                                     :: info
     298              : 
     299          198 :       nSpin = dft_control%nspins
     300            0 :       IF (nSpin /= 1 .AND. nSpin /= 2) CPABORT("tblite supports only one or two spin channels")
     301              : 
     302          198 :       tb%mol%charge = dft_control%charge
     303          198 :       tb%mol%uhf = MAX(0, dft_control%multiplicity - 1)
     304          198 :       IF (nSpin == 2) CALL tb_add_spin_polarization(tb)
     305              : 
     306          198 :       info = tb%calc%variable_info()
     307          198 :       IF (info%charge > shell_resolved) CPABORT("tblite: no support for orbital resolved charge")
     308          198 :       IF (info%dipole > atom_resolved) CPABORT("tblite: no support for shell resolved dipole moment")
     309          198 :       IF (info%quadrupole > atom_resolved) THEN
     310            0 :          CPABORT("tblite: no support shell resolved quadrupole moment")
     311              :       END IF
     312              : 
     313          198 :       CALL new_wavefunction(tb%wfn, tb%mol%nat, tb%calc%bas%nsh, tb%calc%bas%nao, nSpin, 0.0_dp)
     314          198 :       CALL get_occupation(tb%mol, tb%calc%bas, tb%calc%h0, tb%wfn%nocc, tb%wfn%n0at, tb%wfn%n0sh)
     315          198 :       CALL tb_reset_mixer(tb)
     316              : 
     317          198 :       CALL new_potential(tb%pot, tb%mol, tb%calc%bas, tb%wfn%nspin)
     318              : 
     319              :       !allocate quantities later required
     320         1386 :       ALLOCATE (tb%e_hal(tb%mol%nat), tb%e_rep(tb%mol%nat), tb%e_disp(tb%mol%nat))
     321         1386 :       ALLOCATE (tb%e_scd(tb%mol%nat), tb%e_es(tb%mol%nat), tb%e_int(tb%mol%nat))
     322          594 :       ALLOCATE (tb%selfenergy(tb%calc%bas%nsh))
     323          594 :       IF (ALLOCATED(tb%calc%ncoord)) ALLOCATE (tb%cn(tb%mol%nat))
     324              : 
     325              : #else
     326              :       MARK_USED(tb)
     327              :       MARK_USED(dft_control)
     328              :       CPABORT("Built without TBLITE")
     329              : #endif
     330              : 
     331          198 :    END SUBROUTINE tb_init_wf
     332              : 
     333              : #if defined(__TBLITE)
     334              : ! **************************************************************************************************
     335              : !> \brief Add tblite's on-site spin-polarization interaction.
     336              : !> \param tb ...
     337              : ! **************************************************************************************************
     338           30 :    SUBROUTINE tb_add_spin_polarization(tb)
     339              : 
     340              :       TYPE(tblite_type), POINTER                         :: tb
     341              : 
     342           30 :       CLASS(container_type), ALLOCATABLE                 :: cont
     343           30 :       TYPE(spin_polarization), ALLOCATABLE               :: spin
     344           30 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :, :)     :: wll
     345              : 
     346           30 :       ALLOCATE (spin)
     347           30 :       CALL tb_get_spin_constants(tb, wll)
     348           30 :       CALL new_spin_polarization(spin, tb%mol, wll, tb%calc%bas%nsh_id)
     349           30 :       CALL MOVE_ALLOC(spin, cont)
     350           30 :       CALL tb%calc%push_back(cont)
     351              : 
     352           30 :    END SUBROUTINE tb_add_spin_polarization
     353              : 
     354              : ! **************************************************************************************************
     355              : !> \brief Build tblite spin constants for the current basis.
     356              : !> \param tb ...
     357              : !> \param wll ...
     358              : ! **************************************************************************************************
     359           30 :    SUBROUTINE tb_get_spin_constants(tb, wll)
     360              : 
     361              :       TYPE(tblite_type), POINTER                         :: tb
     362              :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :, :), &
     363              :          INTENT(OUT)                                     :: wll
     364              : 
     365              :       INTEGER                                            :: il, ish, izp, jl, jsh, max_shell
     366              : 
     367           68 :       max_shell = MAXVAL(tb%calc%bas%nsh_id)
     368          150 :       ALLOCATE (wll(max_shell, max_shell, tb%mol%nid))
     369           30 :       wll = 0.0_dp
     370           68 :       DO izp = 1, tb%mol%nid
     371          144 :          DO ish = 1, tb%calc%bas%nsh_id(izp)
     372           76 :             il = tb%calc%bas%cgto(ish, izp)%ang
     373          270 :             DO jsh = 1, tb%calc%bas%nsh_id(izp)
     374          156 :                jl = tb%calc%bas%cgto(jsh, izp)%ang
     375          232 :                wll(jsh, ish, izp) = get_spin_constant(jl, il, tb%mol%num(izp))
     376              :             END DO
     377              :          END DO
     378              :       END DO
     379              : 
     380           30 :    END SUBROUTINE tb_get_spin_constants
     381              : #endif
     382              : 
     383              : ! **************************************************************************************************
     384              : !> \brief Reset tblite's internal SCC mixer for a new CP2K SCF cycle.
     385              : !> \param tb ...
     386              : ! **************************************************************************************************
     387         2656 :    SUBROUTINE tb_reset_mixer(tb)
     388              : 
     389              :       TYPE(tblite_type), POINTER                         :: tb
     390              : 
     391              : #if defined(__TBLITE)
     392              : 
     393              :       TYPE(scf_info)                                     :: info
     394              : 
     395         2656 :       info = tb%calc%variable_info()
     396         5114 :       IF (ALLOCATED(tb%mixer)) DEALLOCATE (tb%mixer)
     397              :       CALL new_cp2k_tblite_mixer(tb%mixer, tb%mixer_memory, &
     398              :                                  tb%wfn%nspin*get_mixer_dimension(tb%mol, tb%calc%bas, info), &
     399              :                                  tb%mixer_damping, tb%mixer_omega0, tb%mixer_min_weight, &
     400         2656 :                                  tb%mixer_max_weight, tb%mixer_weight_factor)
     401              : 
     402              : #else
     403              :       MARK_USED(tb)
     404              :       CPABORT("Built without TBLITE")
     405              : #endif
     406              : 
     407         2656 :    END SUBROUTINE tb_reset_mixer
     408              : 
     409              : ! **************************************************************************************************
     410              : !> \brief Configure tblite's internal SCC mixer from CP2K input.
     411              : !> \param tb ...
     412              : !> \param iterations ...
     413              : !> \param memory ...
     414              : !> \param damping ...
     415              : !> \param omega0 ...
     416              : !> \param min_weight ...
     417              : !> \param max_weight ...
     418              : !> \param weight_factor ...
     419              : !> \param solver ...
     420              : ! **************************************************************************************************
     421         2458 :    SUBROUTINE tb_configure_mixer(tb, iterations, memory, damping, omega0, min_weight, max_weight, &
     422              :                                  weight_factor, solver)
     423              : 
     424              :       TYPE(tblite_type), POINTER                         :: tb
     425              :       INTEGER, INTENT(IN)                                :: iterations, memory, solver
     426              :       REAL(KIND=dp), INTENT(IN)                          :: damping, max_weight, min_weight, omega0, &
     427              :                                                             weight_factor
     428              : 
     429              : #if defined(__TBLITE)
     430              : 
     431         2458 :       IF (iterations < 1) CPABORT("tblite SCC mixer ITERATIONS must be positive")
     432         2458 :       IF (memory < 1) CPABORT("tblite SCC mixer MEMORY must be positive")
     433         2458 :       IF (damping <= 0.0_dp) CPABORT("tblite SCC mixer damping must be positive")
     434         2458 :       IF (omega0 <= 0.0_dp) CPABORT("tblite SCC mixer OMEGA0 must be positive")
     435         2458 :       IF (min_weight <= 0.0_dp) CPABORT("tblite SCC mixer MIN_WEIGHT must be positive")
     436         2458 :       IF (max_weight <= 0.0_dp) CPABORT("tblite SCC mixer MAX_WEIGHT must be positive")
     437         2458 :       IF (max_weight < min_weight) THEN
     438            0 :          CPABORT("tblite SCC mixer MAX_WEIGHT must not be smaller than MIN_WEIGHT")
     439              :       END IF
     440         2458 :       IF (weight_factor <= 0.0_dp) CPABORT("tblite SCC mixer WEIGHT_FACTOR must be positive")
     441         2458 :       SELECT CASE (solver)
     442              :       CASE (tblite_solver_gvd, tblite_solver_gvr)
     443              :       CASE DEFAULT
     444         2458 :          CPABORT("Unknown tblite SCC mixer SOLVER")
     445              :       END SELECT
     446              : 
     447         2458 :       tb%calc%max_iter = iterations
     448         2458 :       tb%mixer_memory = memory
     449         2458 :       tb%mixer_damping = damping
     450         2458 :       tb%calc%mixer_input%damping = damping
     451         2458 :       tb%mixer_omega0 = omega0
     452         2458 :       tb%mixer_min_weight = min_weight
     453         2458 :       tb%mixer_max_weight = max_weight
     454         2458 :       tb%mixer_weight_factor = weight_factor
     455              : 
     456              : #else
     457              :       MARK_USED(tb)
     458              :       MARK_USED(iterations)
     459              :       MARK_USED(memory)
     460              :       MARK_USED(damping)
     461              :       MARK_USED(omega0)
     462              :       MARK_USED(min_weight)
     463              :       MARK_USED(max_weight)
     464              :       MARK_USED(weight_factor)
     465              :       MARK_USED(solver)
     466              :       CPABORT("Built without TBLITE")
     467              : #endif
     468              : 
     469         2458 :    END SUBROUTINE tb_configure_mixer
     470              : 
     471              : ! **************************************************************************************************
     472              : !> \brief Return whether the tblite native SCC mixer is active for this run.
     473              : !> \param dft_control ...
     474              : !> \return ...
     475              : ! **************************************************************************************************
     476        94654 :    FUNCTION tb_native_scc_mixer_active(dft_control) RESULT(use_native_mixer)
     477              : 
     478              :       TYPE(dft_control_type), POINTER                    :: dft_control
     479              :       LOGICAL                                            :: use_native_mixer
     480              : 
     481        94654 :       use_native_mixer = .FALSE.
     482        94654 :       IF (.NOT. ASSOCIATED(dft_control)) RETURN
     483        94654 :       IF (dft_control%qs_control%do_ls_scf) RETURN
     484              : 
     485        94654 :       SELECT CASE (dft_control%qs_control%xtb_control%tblite_scc_mixer)
     486              :       CASE (tblite_scc_mixer_auto)
     487              :          use_native_mixer = .TRUE.
     488              :       CASE (tblite_scc_mixer_tblite)
     489         5078 :          use_native_mixer = .TRUE.
     490              :       CASE (tblite_scc_mixer_cp2k, tblite_scc_mixer_none)
     491         5078 :          use_native_mixer = .FALSE.
     492              :       CASE DEFAULT
     493        94654 :          CPABORT("Unknown tblite SCC mixer")
     494              :       END SELECT
     495              : 
     496              :    END FUNCTION tb_native_scc_mixer_active
     497              : 
     498              : ! **************************************************************************************************
     499              : !> \brief Return the native tblite SCC mixer residual on the CP2K iter_delta scale.
     500              : !> \param dft_control ...
     501              : !> \param tb ...
     502              : !> \param eps_scf CP2K reporting scale for the native residual.
     503              : !> \return ...
     504              : ! **************************************************************************************************
     505        24780 :    FUNCTION tb_scf_mixer_error(dft_control, tb, eps_scf) RESULT(mixer_error)
     506              : 
     507              :       TYPE(dft_control_type), POINTER                    :: dft_control
     508              :       TYPE(tblite_type), POINTER                         :: tb
     509              :       REAL(KIND=dp), INTENT(IN)                          :: eps_scf
     510              :       REAL(KIND=dp)                                      :: mixer_error
     511              : 
     512              : #if defined(__TBLITE)
     513              :       REAL(KIND=dp)                                      :: raw_error
     514              : #endif
     515              : 
     516        24780 :       mixer_error = 0.0_dp
     517              : 
     518              : #if defined(__TBLITE)
     519        24780 :       IF (.NOT. ASSOCIATED(tb)) RETURN
     520        24780 :       IF (.NOT. tb_native_scc_mixer_active(dft_control)) RETURN
     521        22624 :       IF (ALLOCATED(tb%mixer)) THEN
     522        22624 :          raw_error = REAL(tb%mixer%get_error(), KIND=dp)
     523              :          mixer_error = tblite_scc_error_on_cp2k_scale( &
     524              :                        raw_error, eps_scf, &
     525        22624 :                        tblite_scc_pconv*dft_control%qs_control%xtb_control%tblite_accuracy)
     526              :       END IF
     527              : #else
     528              :       MARK_USED(dft_control)
     529              :       MARK_USED(tb)
     530              :       MARK_USED(eps_scf)
     531              : #endif
     532              : 
     533              :    END FUNCTION tb_scf_mixer_error
     534              : 
     535              : ! **************************************************************************************************
     536              : !> \brief ...
     537              : !> \param tb ...
     538              : !> \param typ ...
     539              : !> \param accuracy ...
     540              : !> \param param_file ...
     541              : ! **************************************************************************************************
     542          198 :    SUBROUTINE tb_set_calculator(tb, typ, accuracy, param_file)
     543              : 
     544              :       TYPE(tblite_type), POINTER                         :: tb
     545              :       INTEGER                                            :: typ
     546              :       REAL(KIND=dp), INTENT(IN)                          :: accuracy
     547              :       CHARACTER(LEN=*), INTENT(IN)                       :: param_file
     548              : 
     549              : #if defined(__TBLITE)
     550              : 
     551          198 :       TYPE(error_type), ALLOCATABLE                      :: error
     552              : 
     553          198 :       IF (ALLOCATED(tb%param)) DEALLOCATE (tb%param)
     554          198 :       IF (LEN_TRIM(param_file) > 0) THEN
     555            0 :          ALLOCATE (tb%param)
     556            0 :          CALL tb%param%load(TRIM(param_file), error)
     557            0 :          IF (ALLOCATED(error)) CPABORT("Could not load tblite PARAM file: "//TRIM(param_file))
     558            0 :          CALL new_xtb_calculator(tb%calc, tb%mol, tb%param, error)
     559              :       ELSE
     560          198 :          SELECT CASE (typ)
     561              :          CASE default
     562            0 :             CPABORT("Unknown xtb type")
     563              :          CASE (gfn1xtb)
     564           72 :             CALL new_gfn1_calculator(tb%calc, tb%mol, error)
     565              :          CASE (gfn2xtb)
     566          110 :             CALL new_gfn2_calculator(tb%calc, tb%mol, error)
     567              :          CASE (ipea1xtb)
     568          198 :             CALL new_ipea1_calculator(tb%calc, tb%mol, error)
     569              :          END SELECT
     570              :       END IF
     571          198 :       IF (ALLOCATED(error)) CPABORT("tblite calculator setup failed")
     572              : 
     573          198 :       tb%accuracy = accuracy
     574              : 
     575              : #else
     576              :       MARK_USED(tb)
     577              :       MARK_USED(typ)
     578              :       MARK_USED(accuracy)
     579              :       MARK_USED(param_file)
     580              :       CPABORT("Built without TBLITE")
     581              : #endif
     582              : 
     583          198 :    END SUBROUTINE tb_set_calculator
     584              : 
     585              : ! **************************************************************************************************
     586              : !> \brief Prepare geometry-dependent data once, before SCF, including requested core forces.
     587              : !> \param qs_env ...
     588              : !> \param calculate_forces ...
     589              : ! **************************************************************************************************
     590         2616 :    SUBROUTINE tb_init_ham(qs_env, calculate_forces)
     591              : 
     592              :       TYPE(qs_environment_type), POINTER                 :: qs_env
     593              :       LOGICAL, INTENT(IN)                                :: calculate_forces
     594              : 
     595              : #if defined(__TBLITE)
     596              : 
     597         2616 :       TYPE(container_cache)                              :: hcache, rcache
     598         2616 :       TYPE(error_type), ALLOCATABLE                      :: error
     599              :       TYPE(work_partition)                               :: partition
     600              :       TYPE(mp_para_env_type), POINTER                    :: para_env
     601              :       TYPE(tblite_type), POINTER                         :: tb
     602              :       INTEGER                                            :: handle
     603              : 
     604         2616 :       CALL timeset("tb_init_ham", handle)
     605         2616 :       CALL get_qs_env(qs_env=qs_env, tb_tblite=tb, para_env=para_env)
     606         2616 :       CALL tb_update_geometry(qs_env, tb)
     607              : 
     608         2616 :       IF (calculate_forces) THEN
     609          414 :          IF (.NOT. ALLOCATED(tb%grad)) ALLOCATE (tb%grad(3, tb%mol%nat))
     610          414 :          IF (.NOT. ALLOCATED(tb%dsedcn)) ALLOCATE (tb%dsedcn(tb%calc%bas%nsh))
     611          154 :          IF (ALLOCATED(tb%calc%ncoord)) THEN
     612          544 :             IF (.NOT. ALLOCATED(tb%dcndr)) ALLOCATE (tb%dcndr(3, tb%mol%nat, tb%mol%nat))
     613          414 :             IF (.NOT. ALLOCATED(tb%dcndL)) ALLOCATE (tb%dcndL(3, 3, tb%mol%nat))
     614              :          END IF
     615              :       ELSE
     616         2462 :          IF (ALLOCATED(tb%grad)) DEALLOCATE (tb%grad)
     617         2462 :          IF (ALLOCATED(tb%dsedcn)) DEALLOCATE (tb%dsedcn)
     618         2462 :          IF (ALLOCATED(tb%dcndr)) DEALLOCATE (tb%dcndr)
     619         2462 :          IF (ALLOCATED(tb%dcndL)) DEALLOCATE (tb%dcndL)
     620              :       END IF
     621              : 
     622              :       ! Containers return local contributions on the QS communicator.
     623         2616 :       CALL new_work_partition(error, partition, para_env%mepos, para_env%num_pe)
     624         2616 :       IF (ALLOCATED(error)) CPABORT(error%message)
     625         2616 :       CALL tb%calc%set_partition(partition)
     626              : 
     627        13928 :       tb%e_hal = 0.0_dp
     628        13928 :       tb%e_rep = 0.0_dp
     629        13928 :       tb%e_disp = 0.0_dp
     630        13928 :       tb%e_int = 0.0_dp
     631        34008 :       tb%sigma = 0.0_dp
     632              : 
     633         2616 :       IF (ALLOCATED(tb%calc%halogen)) THEN
     634         1302 :          CALL tb%calc%halogen%update(tb%mol, hcache)
     635         1302 :          IF (ALLOCATED(tb%grad)) THEN
     636         2662 :             tb%grad = 0.0_dp
     637              :             CALL tb%calc%halogen%get_engrad(tb%mol, hcache, tb%e_hal, &
     638           86 :             & tb%grad, tb%sigma)
     639           86 :             CALL tb_grad2force(qs_env, tb, para_env, 0, replicated=.FALSE.)
     640              :          ELSE
     641         1216 :             CALL tb%calc%halogen%get_engrad(tb%mol, hcache, tb%e_hal)
     642              :          END IF
     643              :       END IF
     644              : 
     645         2616 :       IF (ALLOCATED(tb%calc%repulsion)) THEN
     646         2616 :          CALL tb%calc%repulsion%update(tb%mol, rcache)
     647         2616 :          IF (ALLOCATED(tb%grad)) THEN
     648         3754 :             tb%grad = 0.0_dp
     649              :             CALL tb%calc%repulsion%get_engrad(tb%mol, rcache, tb%e_rep, &
     650          154 :             & tb%grad, tb%sigma)
     651          154 :             CALL tb_grad2force(qs_env, tb, para_env, 1, replicated=.FALSE.)
     652              :          ELSE
     653         2462 :             CALL tb%calc%repulsion%get_engrad(tb%mol, rcache, tb%e_rep)
     654              :          END IF
     655              :       END IF
     656              : 
     657         2616 :       IF (ALLOCATED(tb%calc%dispersion)) THEN
     658         2616 :          CALL tb%calc%dispersion%update(tb%mol, tb%dcache)
     659         2616 :          IF (ALLOCATED(tb%grad)) THEN
     660         3754 :             tb%grad = 0.0_dp
     661              :             CALL tb%calc%dispersion%get_engrad(tb%mol, tb%dcache, tb%e_disp, &
     662          154 :             & tb%grad, tb%sigma)
     663          154 :             CALL tb_grad2force(qs_env, tb, para_env, 2, replicated=.FALSE.)
     664              :          ELSE
     665         2462 :             CALL tb%calc%dispersion%get_engrad(tb%mol, tb%dcache, tb%e_disp)
     666              :          END IF
     667              :       END IF
     668              : 
     669         2616 :       IF (ALLOCATED(tb%calc%interactions)) THEN
     670          334 :          CALL tb%calc%interactions%update(tb%mol, tb%icache)
     671              :       END IF
     672              : 
     673         2616 :       IF (ALLOCATED(tb%calc%coulomb)) THEN
     674         2616 :          CALL tb%calc%coulomb%update(tb%mol, tb%cache)
     675              :       END IF
     676              : 
     677         2616 :       IF (ALLOCATED(tb%grad)) THEN
     678          154 :          IF (ALLOCATED(tb%calc%ncoord)) THEN
     679          154 :             CALL tb%calc%ncoord%get_cn(tb%mol, tb%cn, tb%dcndr, tb%dcndL)
     680              :          END IF
     681              :       ELSE
     682         2462 :          IF (ALLOCATED(tb%calc%ncoord)) THEN
     683         2462 :             CALL tb%calc%ncoord%get_cn(tb%mol, tb%cn)
     684              :          END IF
     685              :       END IF
     686              : 
     687              :       CALL get_selfenergy(tb%calc%h0, tb%mol%id, tb%calc%bas%ish_at, &
     688         2616 :                           tb%calc%bas%nsh_id, cn=tb%cn, selfenergy=tb%selfenergy, dsedcn=tb%dsedcn)
     689              : 
     690         2616 :       CALL timestop(handle)
     691              : 
     692              : #else
     693              :       MARK_USED(qs_env)
     694              :       MARK_USED(calculate_forces)
     695              :       CPABORT("Built without TBLITE")
     696              : #endif
     697              : 
     698         5232 :    END SUBROUTINE tb_init_ham
     699              : 
     700              : ! **************************************************************************************************
     701              : !> \brief ...
     702              : !> \param qs_env ...
     703              : !> \param tb ...
     704              : !> \param energy ...
     705              : ! **************************************************************************************************
     706        25700 :    SUBROUTINE tb_get_energy(qs_env, tb, energy)
     707              : 
     708              :       TYPE(qs_environment_type), POINTER                 :: qs_env
     709              :       TYPE(tblite_type), POINTER                         :: tb
     710              :       TYPE(qs_energy_type), POINTER                      :: energy
     711              : 
     712              : #if defined(__TBLITE)
     713              : 
     714              :       INTEGER                                            :: iounit
     715              :       TYPE(cp_logger_type), POINTER                      :: logger
     716              :       TYPE(mp_para_env_type), POINTER                    :: para_env
     717              :       TYPE(section_vals_type), POINTER                   :: scf_section
     718              :       REAL(KIND=dp)                                      :: xtb_inter
     719              :       REAL(KIND=dp), DIMENSION(6)                        :: contributions
     720        25700 :       NULLIFY (scf_section, logger)
     721              : 
     722        25700 :       logger => cp_get_default_logger()
     723        25700 :       iounit = cp_logger_get_default_io_unit(logger)
     724        25700 :       scf_section => section_vals_get_subs_vals(qs_env%input, "DFT%SCF")
     725              : 
     726              :       ! Keep the atom-resolved container arrays local between SCC evaluations.
     727        25700 :       CALL get_qs_env(qs_env=qs_env, para_env=para_env)
     728              :       contributions = [SUM(tb%e_rep), SUM(tb%e_es), SUM(tb%e_disp), &
     729       912680 :                        SUM(tb%e_scd), SUM(tb%e_hal), SUM(tb%e_int)]
     730        25700 :       CALL para_env%sum(contributions)
     731        25700 :       energy%repulsive = contributions(1)
     732        25700 :       energy%el_stat = contributions(2)
     733        25700 :       energy%dispersion = contributions(3)
     734        25700 :       energy%dispersion_sc = contributions(4)
     735        25700 :       energy%xtb_xb_inter = contributions(5)
     736        25700 :       xtb_inter = contributions(6)
     737              : 
     738              :       energy%total = energy%core + energy%repulsive + energy%el_stat + energy%dispersion &
     739              :                      + energy%dispersion_sc + energy%xtb_xb_inter + xtb_inter &
     740        25700 :                      + energy%kTS + energy%efield + energy%qmmm_el
     741              : 
     742              :       iounit = cp_print_key_unit_nr(logger, scf_section, "PRINT%DETAILED_ENERGY", &
     743        25700 :                                     extension=".scfLog")
     744        25700 :       IF (iounit > 0) THEN
     745              :          WRITE (UNIT=iounit, FMT="(/,(T9,A,T60,F20.10))") &
     746          179 :             "Repulsive pair potential energy:               ", energy%repulsive, &
     747          179 :             "Zeroth order Hamiltonian energy:               ", energy%core, &
     748          179 :             "Electrostatic energy:                          ", energy%el_stat, &
     749          179 :             "Self-consistent dispersion energy:             ", energy%dispersion_sc, &
     750          358 :             "Non-self consistent dispersion energy:         ", energy%dispersion
     751          179 :          IF (ABS(energy%xtb_xb_inter) > 1.e-9_dp) THEN
     752              :             WRITE (UNIT=iounit, FMT="(T9,A,T60,F20.10)") &
     753            0 :                "Correction for halogen bonding:                ", energy%xtb_xb_inter
     754              :          END IF
     755          179 :          IF (ABS(xtb_inter) > 1.e-9_dp) THEN
     756              :             WRITE (UNIT=iounit, FMT="(T9,A,T60,F20.10)") &
     757            0 :                "Additional interaction (e.g. spin):            ", xtb_inter
     758              :          END IF
     759          179 :          IF (ABS(energy%efield) > 1.e-9_dp) THEN
     760              :             WRITE (UNIT=iounit, FMT="(T9,A,T60,F20.10)") &
     761            0 :                "Electric field interaction energy:             ", energy%efield
     762              :          END IF
     763          179 :          IF (qs_env%qmmm) THEN
     764              :             WRITE (UNIT=iounit, FMT="(T9,A,T60,F20.10)") &
     765            0 :                "QM/MM Electrostatic energy:                    ", energy%qmmm_el
     766              :          END IF
     767              :       END IF
     768              :       CALL cp_print_key_finished_output(iounit, logger, scf_section, &
     769        25700 :                                         "PRINT%DETAILED_ENERGY")
     770              : 
     771              : #else
     772              :       MARK_USED(qs_env)
     773              :       MARK_USED(tb)
     774              :       MARK_USED(energy)
     775              :       CPABORT("Built without TBLITE")
     776              : #endif
     777              : 
     778        25700 :    END SUBROUTINE tb_get_energy
     779              : 
     780              : ! **************************************************************************************************
     781              : !> \brief ...
     782              : !> \param tb ...
     783              : !> \param gto_basis_set ...
     784              : !> \param element_symbol ...
     785              : !> \param param ...
     786              : !> \param occ ...
     787              : ! **************************************************************************************************
     788          334 :    SUBROUTINE tb_get_basis(tb, gto_basis_set, element_symbol, param, occ)
     789              : 
     790              :       TYPE(tblite_type), POINTER                         :: tb
     791              :       TYPE(gto_basis_set_type), POINTER                  :: gto_basis_set
     792              :       CHARACTER(len=2), INTENT(IN)                       :: element_symbol
     793              :       TYPE(xtb_atom_type), POINTER                       :: param
     794              :       INTEGER, DIMENSION(5), INTENT(out)                 :: occ
     795              : 
     796              : #if defined(__TBLITE)
     797              : 
     798              :       REAL(KIND=dp)                                      :: docc
     799              :       CHARACTER(LEN=default_string_length)               :: sng
     800              :       INTEGER                                            :: ang, i_type, id_atom, ind_ao, ipgf, iSH, &
     801              :                                                             ishell, ityp, maxl, mprim, natorb, &
     802              :                                                             nset, nshell
     803              :       LOGICAL                                            :: do_ortho
     804              : 
     805          334 :       CALL allocate_gto_basis_set(gto_basis_set)
     806              : 
     807              :       !identifying element in the bas data
     808          334 :       CALL symbol_to_number(i_type, element_symbol)
     809          684 :       DO id_atom = 1, tb%mol%nat
     810          684 :          IF (i_type == tb%el_num(id_atom)) EXIT
     811              :       END DO
     812          334 :       param%z = i_type
     813          334 :       param%symbol = element_symbol
     814          334 :       param%defined = .TRUE.
     815          334 :       ityp = tb%mol%id(id_atom)
     816              : 
     817              :       !getting size information
     818          334 :       nset = tb%calc%bas%nsh_id(ityp)
     819          334 :       nshell = 1
     820          334 :       mprim = 0
     821         1096 :       DO ishell = 1, nset
     822         1096 :          mprim = MAX(mprim, tb%calc%bas%cgto(ishell, ityp)%nprim)
     823              :       END DO
     824          334 :       param%nshell = nset
     825          334 :       natorb = 0
     826              : 
     827              :       !write basis set information
     828          334 :       CALL integer_to_string(mprim, sng)
     829          334 :       gto_basis_set%name = element_symbol//"_STO-"//TRIM(sng)//"G"
     830          334 :       gto_basis_set%nset = nset
     831          334 :       CALL reallocate(gto_basis_set%lmax, 1, nset)
     832          334 :       CALL reallocate(gto_basis_set%lmin, 1, nset)
     833          334 :       CALL reallocate(gto_basis_set%npgf, 1, nset)
     834          334 :       CALL reallocate(gto_basis_set%nshell, 1, nset)
     835          334 :       CALL reallocate(gto_basis_set%n, 1, 1, 1, nset)
     836          334 :       CALL reallocate(gto_basis_set%l, 1, 1, 1, nset)
     837          334 :       CALL reallocate(gto_basis_set%zet, 1, mprim, 1, nset)
     838          334 :       CALL reallocate(gto_basis_set%gcc, 1, mprim, 1, 1, 1, nset)
     839              : 
     840          334 :       ind_ao = 0
     841          334 :       maxl = 0
     842         1096 :       DO ishell = 1, nset
     843          762 :          ang = tb%calc%bas%cgto(ishell, ityp)%ang
     844          762 :          natorb = natorb + (2*ang + 1)
     845          762 :          param%lval(ishell) = ang
     846          762 :          maxl = MAX(ang, maxl)
     847          762 :          gto_basis_set%lmax(ishell) = ang
     848          762 :          gto_basis_set%lmin(ishell) = ang
     849          762 :          gto_basis_set%npgf(ishell) = tb%calc%bas%cgto(ishell, ityp)%nprim
     850          762 :          gto_basis_set%nshell(ishell) = nshell
     851          762 :          gto_basis_set%n(1, ishell) = ang + 1
     852          762 :          gto_basis_set%l(1, ishell) = ang
     853         4530 :          DO ipgf = 1, gto_basis_set%npgf(ishell)
     854         3768 :             gto_basis_set%gcc(ipgf, 1, ishell) = tb%calc%bas%cgto(ishell, ityp)%coeff(ipgf)
     855         4530 :             gto_basis_set%zet(ipgf, ishell) = tb%calc%bas%cgto(ishell, ityp)%alpha(ipgf)
     856              :          END DO
     857         2810 :          DO ipgf = 1, (2*ang + 1)
     858         1714 :             ind_ao = ind_ao + 1
     859         1714 :             param%lao(ind_ao) = ang
     860         2476 :             param%nao(ind_ao) = ishell
     861              :          END DO
     862              :       END DO
     863              : 
     864          334 :       do_ortho = .FALSE.
     865          334 :       CALL process_gto_basis(gto_basis_set, do_ortho, nset, maxl)
     866              : 
     867              :       !setting additional values in parameter
     868          334 :       param%rcut = get_cutoff(tb%calc%bas, tb%accuracy)
     869          334 :       param%natorb = natorb
     870          334 :       param%lmax = maxl !max angular momentum
     871              : 
     872              :       !getting occupation
     873          334 :       occ = 0
     874          334 :       docc = 0.0_dp
     875          334 :       IF (tb%calc%bas%nsh_at(id_atom) > 5) CPABORT("too many shells in tblite")
     876         1096 :       DO iSh = 1, tb%calc%bas%nsh_at(id_atom)
     877          762 :          occ(iSh) = NINT(tb%calc%h0%refocc(iSh, ityp) + docc)
     878          762 :          docc = docc + tb%calc%h0%refocc(iSh, ityp) - REAL(occ(iSh))
     879         1096 :          param%occupation(iSh) = occ(iSh)
     880              :       END DO
     881          334 :       IF (ABS(docc) > 0.1_dp) CPABORT("Getting occupation numbers from tblite fails")
     882         2004 :       param%zeff = SUM(occ) !effective core charge
     883              : 
     884              :       !set normalization process
     885          334 :       gto_basis_set%norm_type = 3
     886              : 
     887              : #else
     888              :       occ = 0
     889              :       MARK_USED(tb)
     890              :       MARK_USED(gto_basis_set)
     891              :       MARK_USED(element_symbol)
     892              :       MARK_USED(param)
     893              :       CPABORT("Built without TBLITE")
     894              : #endif
     895              : 
     896          334 :    END SUBROUTINE tb_get_basis
     897              : 
     898              : ! **************************************************************************************************
     899              : !> \brief ...
     900              : !> \param qs_env ...
     901              : !> \param calculate_forces ...
     902              : ! **************************************************************************************************
     903         2770 :    SUBROUTINE build_tblite_matrices(qs_env, calculate_forces)
     904              : 
     905              :       TYPE(qs_environment_type), POINTER                 :: qs_env
     906              :       LOGICAL, INTENT(IN)                                :: calculate_forces
     907              : 
     908              : #if defined(__TBLITE)
     909              : 
     910              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'build_tblite_matrices'
     911              : 
     912              :       INTEGER                                            :: handle, maxder, maxsgf, nderivatives, nimg, img, nkind, i, &
     913              :                                                             ic, iw, iatom, jatom, ikind, jkind, iset, jset, n1, n2, icol, &
     914              :                                                             irow, ia, ib, sgfa, sgfb, ldsab, nseta, nsetb, &
     915              :                                                             natorb_a, natorb_b, raw_iatom, raw_jatom, &
     916              :                                                             slot, idim, jdim
     917              :       LOGICAL                                            :: found, norml1, norml2, use_arnoldi
     918              :       REAL(KIND=dp)                                      :: dr, dshpoly, ff, hij_base, r2, rr
     919              :       REAL(KIND=dp)                                      :: native_dot_tmp, native_cn_icol, native_cn_irow, &
     920              :                                                             native_dot_weight
     921              :       INTEGER, DIMENSION(3)                              :: cell
     922              :       REAL(KIND=dp)                                      :: hij, shpoly
     923              :       REAL(KIND=dp), DIMENSION(2)                        :: condnum
     924              :       REAL(KIND=dp), DIMENSION(3)                        :: native_h0_overlap_force, native_radial_force, raw_rij, rij
     925              :       REAL(KIND=dp), DIMENSION(3)                        :: pulay_force
     926              :       REAL(KIND=dp), DIMENSION(3, 3)                     :: native_radial_dot, pulay_virial
     927         2770 :       INTEGER, ALLOCATABLE, DIMENSION(:)                 :: atom_of_kind, kind_of
     928         2770 :       INTEGER, DIMENSION(:, :, :), POINTER                :: cell_to_index
     929         2770 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :)        :: owork
     930         2770 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:)           :: native_cn_deriv_sum, local_cn_deriv
     931         2770 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :)        :: native_radial_force_sum, local_radial_force
     932         5540 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :, :)     :: oint, sint, hint
     933         2770 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :, :, :)  :: radial_hint
     934         2770 :       INTEGER, DIMENSION(:), POINTER                     :: la_max, la_min, lb_max, lb_min
     935         2770 :       INTEGER, DIMENSION(:), POINTER                     :: npgfa, npgfb, nsgfa, nsgfb
     936         2770 :       INTEGER, DIMENSION(:, :), POINTER                  :: first_sgfa, first_sgfb
     937         2770 :       REAL(KIND=dp), DIMENSION(:), POINTER               :: set_radius_a, set_radius_b
     938         2770 :       REAL(KIND=dp), DIMENSION(:, :), POINTER            :: rpgfa, rpgfb, zeta, zetb, scon_a, scon_b
     939         5540 :       REAL(KIND=dp), DIMENSION(:, :), POINTER            :: fblock, pblock, sblock, wblock
     940        36010 :       TYPE(block_p_type), DIMENSION(3, 3)                 :: radial_blocks
     941              : !$    INTEGER                                            :: hash, hash1, lock_num
     942              : !$    INTEGER(KIND=int_8)                                :: iatom8
     943         2770 : !$    INTEGER(kind=omp_lock_kind), ALLOCATABLE, DIMENSION(:) :: locks
     944              :       INTEGER, PARAMETER                                :: nlock = 501
     945              : 
     946         2770 :       TYPE(atomic_kind_type), DIMENSION(:), POINTER         :: atomic_kind_set
     947              :       TYPE(atprop_type), POINTER                            :: atprop
     948              :       TYPE(cp_blacs_env_type), POINTER                      :: blacs_env
     949              :       TYPE(cp_logger_type), POINTER                         :: logger
     950         2770 :       TYPE(dbcsr_p_type), DIMENSION(:, :), POINTER          :: matrix_dh_native, matrix_h, matrix_p, matrix_s, matrix_w
     951              :       TYPE(dft_control_type), POINTER                       :: dft_control
     952         2770 :       TYPE(qs_force_type), DIMENSION(:), POINTER            :: force
     953              :       TYPE(gto_basis_set_type), POINTER                     :: basis_set_a, basis_set_b
     954         2770 :       TYPE(gto_basis_set_p_type), DIMENSION(:), POINTER     :: basis_set_list
     955              :       TYPE(kpoint_type), POINTER                            :: kpoints
     956         2770 :       TYPE(neighbor_list_set_p_type), DIMENSION(:), POINTER :: sab_orb
     957         2770 :       TYPE(neighbor_list_set_p_type), DIMENSION(:), POINTER :: sab_kp
     958              :       TYPE(mp_para_env_type), POINTER                       :: para_env
     959              :       TYPE(qs_energy_type), POINTER                         :: energy
     960              :       TYPE(qs_ks_env_type), POINTER                         :: ks_env
     961         2770 :       TYPE(qs_kind_type), DIMENSION(:), POINTER             :: qs_kind_set
     962              :       TYPE(qs_rho_type), POINTER                            :: rho
     963              :       TYPE(tblite_type), POINTER                            :: tb
     964              :       TYPE(tb_hamiltonian), POINTER                         :: h0
     965              :       TYPE(virial_type), POINTER                            :: virial
     966              : 
     967         2770 :       CALL timeset(routineN, handle)
     968              : 
     969         2770 :       NULLIFY (ks_env, energy, atomic_kind_set, qs_kind_set)
     970         2770 :       NULLIFY (matrix_dh_native, matrix_h, matrix_s, matrix_w, atprop, dft_control)
     971         2770 :       NULLIFY (sab_orb, sab_kp, rho, tb, kpoints, cell_to_index)
     972              : 
     973              :       CALL get_qs_env(qs_env=qs_env, &
     974              :                       ks_env=ks_env, para_env=para_env, &
     975              :                       energy=energy, &
     976              :                       atomic_kind_set=atomic_kind_set, &
     977              :                       qs_kind_set=qs_kind_set, &
     978              :                       matrix_h_kp=matrix_h, &
     979              :                       matrix_s_kp=matrix_s, &
     980              :                       atprop=atprop, &
     981              :                       dft_control=dft_control, &
     982              :                       sab_orb=sab_orb, &
     983              :                       sab_kp=sab_kp, &
     984         2770 :                       rho=rho, tb_tblite=tb)
     985         2770 :       h0 => tb%calc%h0
     986              : 
     987         2770 :       nkind = SIZE(atomic_kind_set)
     988         2770 :       nderivatives = MERGE(1, 0, calculate_forces)
     989         2770 :       maxder = ncoset(nderivatives)
     990         2770 :       nimg = dft_control%nimages
     991         2770 :       IF (nimg > 1) THEN
     992         1296 :          IF (.NOT. ASSOCIATED(sab_kp)) CPABORT("Missing k-point neighbor list for tblite")
     993         1296 :          sab_orb => sab_kp
     994         1296 :          CALL get_ks_env(ks_env=ks_env, kpoints=kpoints)
     995         1296 :          CALL get_kpoint_info(kpoint=kpoints, cell_to_index=cell_to_index)
     996              :       END IF
     997              : 
     998              :       ! get density matrtix
     999         2770 :       CALL qs_rho_get(rho, rho_ao_kp=matrix_p)
    1000              : 
    1001              :       ! set up matrices for force calculations
    1002         2770 :       IF (calculate_forces) THEN
    1003          154 :          NULLIFY (force, matrix_w, virial)
    1004              :          CALL get_qs_env(qs_env=qs_env, &
    1005              :                          matrix_w_kp=matrix_w, &
    1006          154 :                          virial=virial, force=force)
    1007              : 
    1008          154 :          IF (SIZE(matrix_p, 1) == 2) THEN
    1009              :             ! SCF has restored the final density; preserve both spins before summation.
    1010           22 :             CALL tb_store_density_ref(tb, matrix_p)
    1011          152 :             DO img = 1, nimg
    1012              :                CALL dbcsr_add(matrix_p(1, img)%matrix, matrix_p(2, img)%matrix, &
    1013          130 :                               alpha_scalar=1.0_dp, beta_scalar=1.0_dp)
    1014              :                CALL dbcsr_add(matrix_w(1, img)%matrix, matrix_w(2, img)%matrix, &
    1015          152 :                               alpha_scalar=1.0_dp, beta_scalar=1.0_dp)
    1016              :             END DO
    1017              :          END IF
    1018          222 :          tb%use_virial = virial%pv_availability .AND. (.NOT. virial%pv_numer)
    1019              :       END IF
    1020              : 
    1021         2770 :       CALL get_atomic_kind_set(atomic_kind_set=atomic_kind_set, atom_of_kind=atom_of_kind, kind_of=kind_of)
    1022         2770 :       IF (calculate_forces) THEN
    1023          462 :          ALLOCATE (native_radial_force_sum(3, SIZE(atom_of_kind)))
    1024          462 :          ALLOCATE (native_cn_deriv_sum(SIZE(atom_of_kind)))
    1025          154 :          native_cn_deriv_sum = 0.0_dp
    1026          154 :          native_radial_force_sum = 0.0_dp
    1027              :       END IF
    1028              : 
    1029              :       ! set up basis set lists
    1030        12964 :       ALLOCATE (basis_set_list(nkind))
    1031         2770 :       CALL basis_set_list_setup(basis_set_list, "ORB", qs_kind_set)
    1032              : 
    1033              :       ! S and H0 are unchanged between SCF and the force calculation.
    1034         2770 :       IF (.NOT. calculate_forces) THEN
    1035         2616 :          CALL dbcsr_allocate_matrix_set(matrix_s, 1, nimg)
    1036              :          CALL create_sab_matrix(ks_env, matrix_s, "OVERLAP MATRIX", basis_set_list, basis_set_list, &
    1037         2616 :                                 sab_orb, .TRUE.)
    1038         2616 :          CALL set_ks_env(ks_env, matrix_s_kp=matrix_s)
    1039              : 
    1040         2616 :          CALL dbcsr_allocate_matrix_set(matrix_h, 1, nimg)
    1041        78520 :          DO img = 1, nimg
    1042        75904 :             ALLOCATE (matrix_h(1, img)%matrix)
    1043              :             CALL dbcsr_create(matrix_h(1, img)%matrix, template=matrix_s(1, img)%matrix, &
    1044        75904 :                               name="HAMILTONIAN MATRIX")
    1045        78520 :             CALL cp_dbcsr_alloc_block_from_nbl(matrix_h(1, img)%matrix, sab_orb)
    1046              :          END DO
    1047         2616 :          CALL set_ks_env(ks_env, matrix_h_kp=matrix_h)
    1048              :       END IF
    1049         2770 :       IF (calculate_forces .AND. nimg > 1) THEN
    1050           92 :          CALL dbcsr_allocate_matrix_set(matrix_dh_native, 9, nimg)
    1051         5100 :          DO img = 1, nimg
    1052        50172 :             DO idim = 1, 9
    1053        45072 :                ALLOCATE (matrix_dh_native(idim, img)%matrix)
    1054              :                CALL dbcsr_create(matrix_dh_native(idim, img)%matrix, template=matrix_s(1, img)%matrix, &
    1055        45072 :                                  name="TBLITE H0 STRAIN DERIVATIVE")
    1056        50080 :                CALL cp_dbcsr_alloc_block_from_nbl(matrix_dh_native(idim, img)%matrix, sab_orb)
    1057              :             END DO
    1058              :          END DO
    1059              :       END IF
    1060         2770 :       CALL get_qs_kind_set(qs_kind_set, maxsgf=maxsgf)
    1061         2770 :       ldsab = get_memory_usage(qs_kind_set, "ORB", "ORB")
    1062              : 
    1063         2770 :       native_radial_dot = 0.0_dp
    1064         2770 :       pulay_virial = 0.0_dp
    1065              : 
    1066              :       ! loop over all atom pairs with a non-zero overlap (sab_orb)
    1067              : !$OMP PARALLEL DEFAULT(NONE) &
    1068              : !$OMP SHARED (calculate_forces, basis_set_list, sab_orb, matrix_dh_native, matrix_s, matrix_h, matrix_p, matrix_w, &
    1069              : !$OMP        cell_to_index, nimg, atom_of_kind, qs_kind_set, tb, h0, ldsab, maxder, maxsgf, locks, &
    1070              : !$OMP        native_cn_deriv_sum, native_radial_force_sum, ncoset) &
    1071              : !$OMP PRIVATE (slot, hash, hash1, iatom8, lock_num, ikind, jkind, iatom, jatom, cell, rij, ic, irow, &
    1072              : !$OMP        icol, dr, dshpoly, ff, hij_base, r2, raw_iatom, raw_jatom, &
    1073              : !$OMP        raw_rij, native_cn_icol, native_cn_irow, native_dot_weight, native_h0_overlap_force, &
    1074              : !$OMP        native_radial_force, local_cn_deriv, local_radial_force, pulay_force, &
    1075              : !$OMP        n1, n2, ia, ib, i, idim, jdim, iset, jset, sgfa, sgfb, &
    1076              : !$OMP        nseta, nsetb, natorb_a, &
    1077              : !$OMP        natorb_b, found, zeta, first_sgfa, la_max, la_min, npgfa, nsgfa, rpgfa, set_radius_a, &
    1078              : !$OMP        scon_a, first_sgfb, lb_max, lb_min, npgfb, nsgfb, rpgfb, set_radius_b, scon_b, zetb, rr, hij, shpoly, &
    1079              : !$OMP        owork, oint, sint, hint, radial_hint, basis_set_a, basis_set_b, sblock, fblock, &
    1080              : !$OMP        pblock, wblock, radial_blocks) &
    1081         2770 : !$OMP REDUCTION (+ : native_radial_dot, pulay_virial)
    1082              : 
    1083              : !$OMP SINGLE
    1084              : !$    ALLOCATE (locks(nlock))
    1085              : !$OMP END SINGLE
    1086              : !$OMP DO
    1087              : !$    DO lock_num = 1, nlock
    1088              : !$       CALL omp_init_lock(locks(lock_num))
    1089              : !$    END DO
    1090              : !$OMP END DO
    1091              : 
    1092              :       ALLOCATE (oint(ldsab, ldsab, maxder), owork(ldsab, ldsab))
    1093              :       ALLOCATE (sint(maxsgf, maxsgf, maxder))
    1094              :       IF (.NOT. calculate_forces) ALLOCATE (hint(maxsgf, maxsgf, 1))
    1095              :       IF (calculate_forces) THEN
    1096              :          ALLOCATE (local_cn_deriv(SIZE(atom_of_kind)), local_radial_force(3, SIZE(atom_of_kind)))
    1097              :          local_cn_deriv = 0.0_dp
    1098              :          local_radial_force = 0.0_dp
    1099              :          IF (nimg > 1) ALLOCATE (radial_hint(maxsgf, maxsgf, 3, 3))
    1100              :       END IF
    1101              : 
    1102              : !$OMP DO SCHEDULE(GUIDED)
    1103              :       DO slot = 1, sab_orb(1)%nl_size
    1104              : 
    1105              :          ikind = sab_orb(1)%nlist_task(slot)%ikind
    1106              :          jkind = sab_orb(1)%nlist_task(slot)%jkind
    1107              :          iatom = sab_orb(1)%nlist_task(slot)%iatom
    1108              :          jatom = sab_orb(1)%nlist_task(slot)%jatom
    1109              :          cell(:) = sab_orb(1)%nlist_task(slot)%cell(:)
    1110              :          rij(1:3) = sab_orb(1)%nlist_task(slot)%r(1:3)
    1111              :          raw_iatom = iatom
    1112              :          raw_jatom = jatom
    1113              :          raw_rij = rij
    1114              :          native_cn_icol = 0.0_dp
    1115              :          native_cn_irow = 0.0_dp
    1116              :          native_h0_overlap_force = 0.0_dp
    1117              :          native_radial_force = 0.0_dp
    1118              : 
    1119              :          ! canonicalize pair ordering as in current serial flow
    1120              :          icol = MAX(iatom, jatom)
    1121              :          irow = MIN(iatom, jatom)
    1122              :          IF (iatom < jatom) THEN
    1123              :             rij = -rij
    1124              :             i = ikind
    1125              :             ikind = jkind
    1126              :             jkind = i
    1127              :          END IF
    1128              : 
    1129              :          dr = NORM2(rij(:))
    1130              :          r2 = dr*dr
    1131              : 
    1132              :          IF (nimg == 1) THEN
    1133              :             ic = 1
    1134              :          ELSE
    1135              :             ic = cell_to_index(cell(1), cell(2), cell(3))
    1136              :             CPASSERT(ic > 0)
    1137              :          END IF
    1138              : 
    1139              :          IF (calculate_forces) THEN
    1140              :             NULLIFY (pblock)
    1141              :             CALL dbcsr_get_block_p(matrix=matrix_p(1, ic)%matrix, &
    1142              :                                    row=irow, col=icol, BLOCK=pblock, found=found)
    1143              :             CPASSERT(found)
    1144              :             NULLIFY (wblock)
    1145              :             CALL dbcsr_get_block_p(matrix=matrix_w(1, ic)%matrix, &
    1146              :                                    row=irow, col=icol, BLOCK=wblock, found=found)
    1147              :             CPASSERT(found)
    1148              :             IF (nimg > 1) THEN
    1149              :                DO jdim = 1, 3
    1150              :                   DO idim = 1, 3
    1151              :                      NULLIFY (radial_blocks(idim, jdim)%block)
    1152              :                      CALL dbcsr_get_block_p(matrix=matrix_dh_native(idim + 3*(jdim - 1), ic)%matrix, &
    1153              :                                             row=irow, col=icol, BLOCK=radial_blocks(idim, jdim)%block, &
    1154              :                                             found=found)
    1155              :                      CPASSERT(found)
    1156              :                   END DO
    1157              :                END DO
    1158              :             END IF
    1159              :          END IF
    1160              : 
    1161              :          ! --------- Overlap
    1162              :          !get basis information
    1163              :          basis_set_a => basis_set_list(ikind)%gto_basis_set
    1164              :          IF (.NOT. ASSOCIATED(basis_set_a)) CYCLE
    1165              :          basis_set_b => basis_set_list(jkind)%gto_basis_set
    1166              :          IF (.NOT. ASSOCIATED(basis_set_b)) CYCLE
    1167              :          ! basis a
    1168              :          first_sgfa => basis_set_a%first_sgf
    1169              :          la_max => basis_set_a%lmax
    1170              :          la_min => basis_set_a%lmin
    1171              :          npgfa => basis_set_a%npgf
    1172              :          nseta = basis_set_a%nset
    1173              :          nsgfa => basis_set_a%nsgf_set
    1174              :          rpgfa => basis_set_a%pgf_radius
    1175              :          set_radius_a => basis_set_a%set_radius
    1176              :          scon_a => basis_set_a%scon
    1177              :          zeta => basis_set_a%zet
    1178              :          ! basis b
    1179              :          first_sgfb => basis_set_b%first_sgf
    1180              :          lb_max => basis_set_b%lmax
    1181              :          lb_min => basis_set_b%lmin
    1182              :          npgfb => basis_set_b%npgf
    1183              :          nsetb = basis_set_b%nset
    1184              :          nsgfb => basis_set_b%nsgf_set
    1185              :          rpgfb => basis_set_b%pgf_radius
    1186              :          set_radius_b => basis_set_b%set_radius
    1187              :          scon_b => basis_set_b%scon
    1188              :          zetb => basis_set_b%zet
    1189              : 
    1190              :          natorb_a = 0
    1191              :          DO iset = 1, nseta
    1192              :             natorb_a = natorb_a + (2*basis_set_a%l(1, iset) + 1)
    1193              :          END DO
    1194              :          natorb_b = 0
    1195              :          DO iset = 1, nsetb
    1196              :             natorb_b = natorb_b + (2*basis_set_b%l(1, iset) + 1)
    1197              :          END DO
    1198              :          sint(1:natorb_a, 1:natorb_b, :) = 0.0_dp
    1199              :          IF (.NOT. calculate_forces) hint(1:natorb_a, 1:natorb_b, :) = 0.0_dp
    1200              :          IF (calculate_forces .AND. nimg > 1) THEN
    1201              :             radial_hint(1:natorb_a, 1:natorb_b, :, :) = 0.0_dp
    1202              :          END IF
    1203              : 
    1204              :          !----------------- overlap integrals
    1205              :          DO iset = 1, nseta
    1206              :             n1 = npgfa(iset)*(ncoset(la_max(iset)) - ncoset(la_min(iset) - 1))
    1207              :             sgfa = first_sgfa(1, iset)
    1208              :             DO jset = 1, nsetb
    1209              :                IF (set_radius_a(iset) + set_radius_b(jset) < dr) CYCLE
    1210              :                n2 = npgfb(jset)*(ncoset(lb_max(jset)) - ncoset(lb_min(jset) - 1))
    1211              :                sgfb = first_sgfb(1, jset)
    1212              :                IF (calculate_forces) THEN
    1213              :                   CALL overlap_ab(la_max(iset), la_min(iset), npgfa(iset), rpgfa(:, iset), zeta(:, iset), &
    1214              :                                   lb_max(jset), lb_min(jset), npgfb(jset), rpgfb(:, jset), zetb(:, jset), &
    1215              :                                   rij, sab=oint(:, :, 1), dab=oint(:, :, 2:4))
    1216              :                ELSE
    1217              :                   CALL overlap_ab(la_max(iset), la_min(iset), npgfa(iset), rpgfa(:, iset), zeta(:, iset), &
    1218              :                                   lb_max(jset), lb_min(jset), npgfb(jset), rpgfb(:, jset), zetb(:, jset), &
    1219              :                                   rij, sab=oint(:, :, 1))
    1220              :                END IF
    1221              :                ! Contraction
    1222              :                CALL contraction(oint(:, :, 1), owork, ca=scon_a(:, sgfa:), na=n1, ma=nsgfa(iset), &
    1223              :                                 cb=scon_b(:, sgfb:), nb=n2, mb=nsgfb(jset), fscale=1.0_dp, trans=.FALSE.)
    1224              :                CALL block_add("IN", owork, nsgfa(iset), nsgfb(jset), sint(:, :, 1), sgfa, sgfb, trans=.FALSE.)
    1225              :                IF (calculate_forces) THEN
    1226              :                   DO i = 2, 4
    1227              :                      CALL contraction(oint(:, :, i), owork, ca=scon_a(:, sgfa:), na=n1, ma=nsgfa(iset), &
    1228              :                                       cb=scon_b(:, sgfb:), nb=n2, mb=nsgfb(jset), fscale=1.0_dp, trans=.FALSE.)
    1229              :                      CALL block_add("IN", owork, nsgfa(iset), nsgfb(jset), sint(:, :, i), sgfa, sgfb, trans=.FALSE.)
    1230              :                   END DO
    1231              :                END IF
    1232              :             END DO
    1233              :          END DO
    1234              : 
    1235              : !$       iatom8 = INT(irow - 1, int_8)*INT(SIZE(atom_of_kind), int_8) + INT(icol, int_8)
    1236              : !$       hash1 = INT(MOD(iatom8, INT(nlock, int_8)) + 1)
    1237              :          ! update S matrix
    1238              :          IF (.NOT. calculate_forces) THEN
    1239              :             CALL dbcsr_get_block_p(matrix_s(1, ic)%matrix, irow, icol, BLOCK=sblock, found=found)
    1240              :             CPASSERT(found)
    1241              : !$          hash = hash1
    1242              : !$          CALL omp_set_lock(locks(hash))
    1243              :             IF (icol <= irow) THEN
    1244              :                sblock(:, :) = sblock(:, :) + sint(1:natorb_a, 1:natorb_b, 1)
    1245              :             ELSE
    1246              :                sblock(:, :) = sblock(:, :) + TRANSPOSE(sint(1:natorb_a, 1:natorb_b, 1))
    1247              :             END IF
    1248              : !$          CALL omp_unset_lock(locks(hash))
    1249              :          END IF
    1250              : 
    1251              :          ! --------- Hamiltonian
    1252              :          IF (icol == irow .AND. dr < same_atom) THEN
    1253              :             !get diagonal F matrix from selfenergy
    1254              :             n1 = tb%calc%bas%ish_at(icol)
    1255              :             DO iset = 1, nseta
    1256              :                sgfa = first_sgfa(1, iset)
    1257              :                hij = tb%selfenergy(n1 + iset)
    1258              :                DO ia = sgfa, sgfa + nsgfa(iset) - 1
    1259              :                   IF (.NOT. calculate_forces) hint(ia, ia, 1) = hij
    1260              :                   IF (calculate_forces) THEN
    1261              :                      native_cn_icol = native_cn_icol + tb%dsedcn(n1 + iset)*pblock(ia, ia)
    1262              :                      DO jdim = 1, 3
    1263              :                         DO idim = 1, 3
    1264              :                            IF (nimg == 1) THEN
    1265              :                               native_radial_dot(idim, jdim) = native_radial_dot(idim, jdim) + &
    1266              :                                                               tb%dsedcn(n1 + iset)*tb%dcndL(idim, jdim, icol)*pblock(ia, ia)
    1267              :                            ELSE
    1268              :                               radial_hint(ia, ia, idim, jdim) = radial_hint(ia, ia, idim, jdim) + &
    1269              :                                                                 tb%dsedcn(n1 + iset)*tb%dcndL(idim, jdim, icol)
    1270              :                            END IF
    1271              :                         END DO
    1272              :                      END DO
    1273              :                   END IF
    1274              :                END DO
    1275              :             END DO
    1276              :          ELSE
    1277              :             !get off-diagonal F matrix
    1278              :             rr = SQRT(dr/(h0%rad(jkind) + h0%rad(ikind)))
    1279              :             n1 = tb%calc%bas%ish_at(icol)
    1280              :             DO iset = 1, nseta
    1281              :                sgfa = first_sgfa(1, iset)
    1282              :                n2 = tb%calc%bas%ish_at(irow)
    1283              :                DO jset = 1, nsetb
    1284              :                   sgfb = first_sgfb(1, jset)
    1285              :                   shpoly = (1.0_dp + h0%shpoly(iset, ikind)*rr) &
    1286              :                            *(1.0_dp + h0%shpoly(jset, jkind)*rr)
    1287              :                   dshpoly = ((1.0_dp + h0%shpoly(iset, ikind)*rr)*h0%shpoly(jset, jkind)*rr &
    1288              :                              + (1.0_dp + h0%shpoly(jset, jkind)*rr)*h0%shpoly(iset, ikind)*rr) &
    1289              :                             *0.5_dp/r2
    1290              :                   hij_base = 0.5_dp*(tb%selfenergy(n1 + iset) + tb%selfenergy(n2 + jset)) &
    1291              :                              *h0%hscale(iset, jset, ikind, jkind)
    1292              :                   hij = hij_base*shpoly
    1293              :                   DO ia = sgfa, sgfa + nsgfa(iset) - 1
    1294              :                      DO ib = sgfb, sgfb + nsgfb(jset) - 1
    1295              :                         IF (.NOT. calculate_forces) hint(ia, ib, 1) = hij*sint(ia, ib, 1)
    1296              :                         IF (calculate_forces) THEN
    1297              :                            native_dot_weight = 2.0_dp
    1298              :                            IF (icol == irow) native_dot_weight = 1.0_dp
    1299              :                            native_cn_icol = native_cn_icol + native_dot_weight*0.5_dp* &
    1300              :                                             h0%hscale(iset, jset, ikind, jkind)*shpoly* &
    1301              :                                             tb%dsedcn(n1 + iset)*pblock(ib, ia)*sint(ia, ib, 1)
    1302              :                            native_cn_irow = native_cn_irow + native_dot_weight*0.5_dp* &
    1303              :                                             h0%hscale(iset, jset, ikind, jkind)*shpoly* &
    1304              :                                             tb%dsedcn(n2 + jset)*pblock(ib, ia)*sint(ia, ib, 1)
    1305              :                            native_radial_force = native_radial_force + &
    1306              :                                                  hij_base*dshpoly*pblock(ib, ia)*sint(ia, ib, 1)*raw_rij
    1307              :                            native_h0_overlap_force = native_h0_overlap_force + &
    1308              :                                                      hij*pblock(ib, ia)*sint(ia, ib, 2:4)
    1309              :                            DO jdim = 1, 3
    1310              :                               DO idim = 1, 3
    1311              :                                  IF (nimg == 1) THEN
    1312              :                                     native_radial_dot(idim, jdim) = native_radial_dot(idim, jdim) + &
    1313              :                                                                     native_dot_weight*pblock(ib, ia)*( &
    1314              :                                                                     (-hij)*sint(ia, ib, idim + 1)*rij(jdim) + &
    1315              :                                                                     hij_base*dshpoly*sint(ia, ib, 1)*rij(idim)*rij(jdim) + &
    1316              :                                                                 0.5_dp*h0%hscale(iset, jset, ikind, jkind)*shpoly*sint(ia, ib, 1)* &
    1317              :                                                                     (tb%dsedcn(n1 + iset)*tb%dcndL(idim, jdim, icol) + &
    1318              :                                                                      tb%dsedcn(n2 + jset)*tb%dcndL(idim, jdim, irow)))
    1319              :                                  ELSE
    1320              :                                     radial_hint(ia, ib, idim, jdim) = radial_hint(ia, ib, idim, jdim) + &
    1321              :                                                                       (-hij)*sint(ia, ib, idim + 1)*rij(jdim) + &
    1322              :                                                                       hij_base*dshpoly*sint(ia, ib, 1)*rij(idim)*rij(jdim) + &
    1323              :                                                                 0.5_dp*h0%hscale(iset, jset, ikind, jkind)*shpoly*sint(ia, ib, 1)* &
    1324              :                                                                       (tb%dsedcn(n1 + iset)*tb%dcndL(idim, jdim, icol) + &
    1325              :                                                                        tb%dsedcn(n2 + jset)*tb%dcndL(idim, jdim, irow))
    1326              :                                  END IF
    1327              :                               END DO
    1328              :                            END DO
    1329              :                         END IF
    1330              :                      END DO
    1331              :                   END DO
    1332              :                END DO
    1333              :             END DO
    1334              :          END IF
    1335              : 
    1336              :          ! update F matrix
    1337              : !$       hash = hash1
    1338              : !$       CALL omp_set_lock(locks(hash))
    1339              :          IF (.NOT. calculate_forces) THEN
    1340              :             CALL dbcsr_get_block_p(matrix_h(1, ic)%matrix, irow, icol, BLOCK=fblock, found=found)
    1341              :             CPASSERT(found)
    1342              :          END IF
    1343              :          IF (icol <= irow) THEN
    1344              :             IF (.NOT. calculate_forces) fblock(:, :) = fblock(:, :) + hint(1:natorb_a, 1:natorb_b, 1)
    1345              :             IF (calculate_forces .AND. nimg > 1) THEN
    1346              :                DO jdim = 1, 3
    1347              :                   DO idim = 1, 3
    1348              :                      radial_blocks(idim, jdim)%block(:, :) = radial_blocks(idim, jdim)%block(:, :) + &
    1349              :                                                              radial_hint(1:natorb_a, 1:natorb_b, idim, jdim)
    1350              :                   END DO
    1351              :                END DO
    1352              :             END IF
    1353              :          ELSE
    1354              :             IF (.NOT. calculate_forces) fblock(:, :) = fblock(:, :) + TRANSPOSE(hint(1:natorb_a, 1:natorb_b, 1))
    1355              :             IF (calculate_forces .AND. nimg > 1) THEN
    1356              :                DO jdim = 1, 3
    1357              :                   DO idim = 1, 3
    1358              :                      radial_blocks(idim, jdim)%block(:, :) = radial_blocks(idim, jdim)%block(:, :) + &
    1359              :                                                              TRANSPOSE(radial_hint(1:natorb_a, 1:natorb_b, idim, jdim))
    1360              :                   END DO
    1361              :                END DO
    1362              :             END IF
    1363              :          END IF
    1364              : !$       CALL omp_unset_lock(locks(hash))
    1365              : 
    1366              :          IF (calculate_forces) THEN
    1367              :             ! Match the block orientation used to assemble S. Same-atom image
    1368              :             ! blocks need not be symmetric at nonzero lattice translations.
    1369              :             DO idim = 1, 3
    1370              :                IF (icol == irow) THEN
    1371              :                   pulay_force(idim) = SUM(wblock*sint(1:natorb_a, 1:natorb_b, idim + 1))
    1372              :                ELSE
    1373              :                   pulay_force(idim) = SUM(TRANSPOSE(wblock)*sint(1:natorb_a, 1:natorb_b, idim + 1))
    1374              :                END IF
    1375              :             END DO
    1376              :             local_radial_force(:, icol) = local_radial_force(:, icol) - 2.0_dp*pulay_force
    1377              :             local_radial_force(:, irow) = local_radial_force(:, irow) + 2.0_dp*pulay_force
    1378              :             IF (tb%use_virial) THEN
    1379              :                native_dot_weight = 2.0_dp
    1380              :                IF (icol == irow) native_dot_weight = 1.0_dp
    1381              :                CALL virial_pair_force(pulay_virial, -native_dot_weight, pulay_force, rij)
    1382              :             END IF
    1383              :             ff = 2.0_dp
    1384              :             local_radial_force(:, raw_iatom) = &
    1385              :                local_radial_force(:, raw_iatom) - ff*native_radial_force
    1386              :             local_radial_force(:, raw_jatom) = &
    1387              :                local_radial_force(:, raw_jatom) + ff*native_radial_force
    1388              :             local_radial_force(:, icol) = &
    1389              :                local_radial_force(:, icol) + ff*native_h0_overlap_force
    1390              :             local_radial_force(:, irow) = &
    1391              :                local_radial_force(:, irow) - ff*native_h0_overlap_force
    1392              :             local_cn_deriv(icol) = local_cn_deriv(icol) + native_cn_icol
    1393              :             local_cn_deriv(irow) = local_cn_deriv(irow) + native_cn_irow
    1394              :          END IF
    1395              : 
    1396              :       END DO
    1397              : !$OMP END DO
    1398              :       IF (calculate_forces) THEN
    1399              : !$OMP CRITICAL(tblite_native_radial_force)
    1400              :          native_radial_force_sum(:, :) = native_radial_force_sum(:, :) + local_radial_force(:, :)
    1401              :          native_cn_deriv_sum(:) = native_cn_deriv_sum(:) + local_cn_deriv(:)
    1402              : !$OMP END CRITICAL(tblite_native_radial_force)
    1403              :          DEALLOCATE (local_radial_force, local_cn_deriv)
    1404              :       END IF
    1405              :       DEALLOCATE (oint, owork, sint)
    1406              :       IF (ALLOCATED(hint)) DEALLOCATE (hint)
    1407              :       IF (ALLOCATED(radial_hint)) DEALLOCATE (radial_hint)
    1408              : !$OMP DO
    1409              : !$    DO lock_num = 1, nlock
    1410              : !$       CALL omp_destroy_lock(locks(lock_num))
    1411              : !$    END DO
    1412              : !$OMP END DO
    1413              : !$OMP SINGLE
    1414              : !$    DEALLOCATE (locks)
    1415              : !$OMP END SINGLE NOWAIT
    1416              : !$OMP END PARALLEL
    1417              : 
    1418         2770 :       IF (calculate_forces) THEN
    1419          154 :          IF (nimg > 1) THEN
    1420           92 :             native_radial_dot = 0.0_dp
    1421         5100 :             DO img = 1, nimg
    1422        20124 :                DO jdim = 1, 3
    1423        65104 :                   DO idim = 1, 3
    1424        45072 :                      CALL dbcsr_finalize(matrix_dh_native(idim + 3*(jdim - 1), img)%matrix)
    1425              :                      CALL dbcsr_dot(matrix_dh_native(idim + 3*(jdim - 1), img)%matrix, &
    1426        45072 :                                     matrix_p(1, img)%matrix, native_dot_tmp)
    1427        60096 :                      native_radial_dot(idim, jdim) = native_radial_dot(idim, jdim) + native_dot_tmp
    1428              :                   END DO
    1429              :                END DO
    1430              :             END DO
    1431           92 :             CALL dbcsr_deallocate_matrix_set(matrix_dh_native)
    1432              :          ELSE
    1433           62 :             CALL para_env%sum(native_radial_dot)
    1434              :          END IF
    1435          154 :          CALL para_env%sum(native_cn_deriv_sum)
    1436         3754 :          tb%grad = 0.0_dp
    1437          154 :          CALL tb_add_grad(tb%grad, tb%dcndr, native_cn_deriv_sum, tb%mol%nat)
    1438          154 :          CALL tb_grad2force(qs_env, tb, para_env, 4, replicated=.TRUE.)
    1439         1054 :          DO iatom = 1, SIZE(atom_of_kind)
    1440          900 :             ikind = kind_of(iatom)
    1441              :             force(ikind)%overlap(:, atom_of_kind(iatom)) = &
    1442         3754 :                force(ikind)%overlap(:, atom_of_kind(iatom)) + native_radial_force_sum(:, iatom)
    1443              :          END DO
    1444          154 :          IF (tb%use_virial) THEN
    1445         1118 :             virial%pv_overlap = virial%pv_overlap - native_radial_dot/para_env%num_pe + pulay_virial
    1446         1118 :             virial%pv_virial = virial%pv_virial - native_radial_dot/para_env%num_pe + pulay_virial
    1447              :          END IF
    1448              :       END IF
    1449              : 
    1450         2770 :       IF (.NOT. calculate_forces) THEN
    1451        78520 :          DO img = 1, nimg
    1452        75904 :             CALL dbcsr_finalize(matrix_s(1, img)%matrix)
    1453        78520 :             CALL dbcsr_finalize(matrix_h(1, img)%matrix)
    1454              :          END DO
    1455         2616 :          IF (dft_control%qs_control%xtb_control%tblite_method == gfn2xtb) THEN
    1456         1314 :             CALL tb_get_multipole(qs_env, tb)
    1457              :          END IF
    1458              :       END IF
    1459              : 
    1460              :       ! output overlap information
    1461         2770 :       NULLIFY (logger)
    1462         2770 :       logger => cp_get_default_logger()
    1463         2770 :       IF (.NOT. calculate_forces) THEN
    1464         2616 :          IF (cp_print_key_should_output(logger%iter_info, qs_env%input, &
    1465              :                                         "DFT%PRINT%OVERLAP_CONDITION") /= 0) THEN
    1466              :             iw = cp_print_key_unit_nr(logger, qs_env%input, "DFT%PRINT%OVERLAP_CONDITION", &
    1467            2 :                                       extension=".Log")
    1468            2 :             CALL section_vals_val_get(qs_env%input, "DFT%PRINT%OVERLAP_CONDITION%1-NORM", l_val=norml1)
    1469            2 :             CALL section_vals_val_get(qs_env%input, "DFT%PRINT%OVERLAP_CONDITION%DIAGONALIZATION", l_val=norml2)
    1470            2 :             CALL section_vals_val_get(qs_env%input, "DFT%PRINT%OVERLAP_CONDITION%ARNOLDI", l_val=use_arnoldi)
    1471            2 :             CALL get_qs_env(qs_env=qs_env, blacs_env=blacs_env)
    1472            2 :             CALL overlap_condnum(matrix_s, condnum, iw, norml1, norml2, use_arnoldi, blacs_env)
    1473              :          END IF
    1474              :       END IF
    1475              : 
    1476         2770 :       DEALLOCATE (basis_set_list)
    1477         2770 :       IF (ALLOCATED(native_cn_deriv_sum)) DEALLOCATE (native_cn_deriv_sum)
    1478         2770 :       IF (ALLOCATED(native_radial_force_sum)) DEALLOCATE (native_radial_force_sum)
    1479              : 
    1480         2770 :       CALL timestop(handle)
    1481              : 
    1482              : #else
    1483              :       MARK_USED(qs_env)
    1484              :       MARK_USED(calculate_forces)
    1485              :       CPABORT("Built without TBLITE")
    1486              : #endif
    1487              : 
    1488        11080 :    END SUBROUTINE build_tblite_matrices
    1489              : 
    1490              : ! **************************************************************************************************
    1491              : !> \brief ...
    1492              : !> \param qs_env ...
    1493              : !> \param dft_control ...
    1494              : !> \param tb ...
    1495              : !> \param calculate_forces ...
    1496              : !> \param use_rho ...
    1497              : ! **************************************************************************************************
    1498        53852 :    SUBROUTINE tb_update_charges(qs_env, dft_control, tb, calculate_forces, use_rho)
    1499              : 
    1500              :       TYPE(qs_environment_type), POINTER                                 :: qs_env
    1501              :       TYPE(dft_control_type), POINTER                                    :: dft_control
    1502              :       TYPE(tblite_type), POINTER                                         :: tb
    1503              :       LOGICAL, INTENT(IN)                                                :: calculate_forces
    1504              :       LOGICAL, INTENT(IN)                                                :: use_rho
    1505              : 
    1506              : #if defined(__TBLITE)
    1507              : 
    1508              :       INTEGER                                            :: iatom, ikind, is, ns, atom_a, im
    1509              :       INTEGER                                            :: ispin, nspin
    1510              :       INTEGER                                            :: nkind, nsgf, natorb, na
    1511              :       INTEGER                                            :: n_atom, max_orb, max_shell
    1512              :       LOGICAL                                            :: advance_native_mixer, do_dipole, do_quadrupole, &
    1513              :                                                             reuse_native_input, seed_native_from_rho, &
    1514              :                                                             use_native_mixer, use_no_mixer
    1515              :       REAL(KIND=dp)                                      :: native_seed_charge, norm, pao
    1516              :       INTEGER, DIMENSION(5)                              :: occ
    1517              :       INTEGER, DIMENSION(25)                             :: lao
    1518              :       INTEGER, DIMENSION(25)                             :: nao
    1519        53852 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :)        :: ch_atom
    1520        53852 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :)        :: aocg
    1521        53852 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :, :)     :: aocg_spin, ao_dip_spin, ao_quad_spin, &
    1522        53852 :                                                             ch_orb_spin, ch_shell_spin
    1523              : 
    1524        53852 :       TYPE(atomic_kind_type), DIMENSION(:), POINTER      :: atomic_kind_set
    1525        53852 :       TYPE(dbcsr_p_type), DIMENSION(:, :), POINTER       :: matrix_s, matrix_p
    1526        53852 :       TYPE(error_type), ALLOCATABLE                      :: error
    1527              :       TYPE(mp_para_env_type), POINTER                    :: para_env
    1528        53852 :       TYPE(particle_type), DIMENSION(:), POINTER         :: particle_set
    1529        53852 :       TYPE(qs_kind_type), DIMENSION(:), POINTER          :: qs_kind_set
    1530              :       TYPE(qs_rho_type), POINTER                         :: rho
    1531              :       TYPE(qs_scf_env_type), POINTER                     :: scf_env
    1532              :       TYPE(scf_control_type), POINTER                    :: scf_control
    1533              :       TYPE(xtb_atom_type), POINTER                       :: xtb_kind
    1534              : 
    1535              :       ! compute mulliken charges required for charge update
    1536        53852 :       NULLIFY (particle_set, qs_kind_set, atomic_kind_set, scf_control, scf_env)
    1537              :       CALL get_qs_env(qs_env=qs_env, scf_env=scf_env, particle_set=particle_set, qs_kind_set=qs_kind_set, &
    1538              :                       atomic_kind_set=atomic_kind_set, matrix_s_kp=matrix_s, rho=rho, para_env=para_env, &
    1539        53852 :                       scf_control=scf_control)
    1540              : 
    1541              :       ! also compute multipoles needed by GFN2
    1542        53852 :       do_dipole = .FALSE.
    1543        53852 :       do_quadrupole = .FALSE.
    1544        53852 :       IF (dft_control%qs_control%do_ls_scf .OR. scf_control%use_ot) THEN
    1545              :          use_native_mixer = .FALSE.
    1546              :          use_no_mixer = .TRUE.
    1547              :       ELSE
    1548        93746 :          SELECT CASE (dft_control%qs_control%xtb_control%tblite_scc_mixer)
    1549              :          CASE (tblite_scc_mixer_auto)
    1550        41662 :             use_native_mixer = tb_native_scc_mixer_active(dft_control)
    1551        41662 :             use_no_mixer = .FALSE.
    1552              :          CASE (tblite_scc_mixer_tblite)
    1553              :             use_native_mixer = .TRUE.
    1554              :             use_no_mixer = .FALSE.
    1555              :          CASE (tblite_scc_mixer_cp2k)
    1556              :             use_native_mixer = .FALSE.
    1557              :             use_no_mixer = .FALSE.
    1558              :          CASE (tblite_scc_mixer_none)
    1559              :             use_native_mixer = .FALSE.
    1560            0 :             use_no_mixer = .TRUE.
    1561              :          CASE DEFAULT
    1562        52084 :             CPABORT("Unknown tblite SCC mixer")
    1563              :          END SELECT
    1564              :       END IF
    1565        41662 :       IF (use_native_mixer) THEN
    1566        47628 :          IF (.NOT. ASSOCIATED(scf_env)) CPABORT("tblite SCC mixer requires a QS SCF environment")
    1567        47628 :          IF (use_rho .AND. (.NOT. calculate_forces)) THEN
    1568        24860 :             IF (scf_env%iter_count > dft_control%qs_control%xtb_control%tblite_mixer_iterations) THEN
    1569            0 :                CPABORT("tblite SCC mixer exceeded TBLITE_MIXER/ITERATIONS")
    1570              :             END IF
    1571        24860 :             IF (scf_env%iter_count == 1) THEN
    1572              :                CALL tb_configure_mixer(tb, dft_control%qs_control%xtb_control%tblite_mixer_iterations, &
    1573              :                                        dft_control%qs_control%xtb_control%tblite_mixer_memory, &
    1574              :                                        dft_control%qs_control%xtb_control%tblite_mixer_damping, &
    1575              :                                        dft_control%qs_control%xtb_control%tblite_mixer_omega0, &
    1576              :                                        dft_control%qs_control%xtb_control%tblite_mixer_min_weight, &
    1577              :                                        dft_control%qs_control%xtb_control%tblite_mixer_max_weight, &
    1578              :                                        dft_control%qs_control%xtb_control%tblite_mixer_weight_factor, &
    1579         2458 :                                        dft_control%qs_control%xtb_control%tblite_mixer_solver)
    1580         2458 :                CALL tb_reset_mixer(tb)
    1581              :             END IF
    1582              :          END IF
    1583              :       END IF
    1584        53852 :       nspin = dft_control%nspins
    1585        53852 :       IF (nspin /= tb%wfn%nspin) CPABORT("CP2K/tblite spin channel mismatch")
    1586              : 
    1587        53852 :       NULLIFY (matrix_p)
    1588        53852 :       IF (use_rho) THEN
    1589        29050 :          CALL qs_rho_get(rho, rho_ao_kp=matrix_p)
    1590        24802 :       ELSE IF (calculate_forces .AND. nspin > 1) THEN
    1591           22 :          IF (.NOT. ASSOCIATED(tb%rho_ao_kp_ref)) THEN
    1592            0 :             CPABORT("Missing converged tblite density for UKS/LSD forces")
    1593              :          END IF
    1594           22 :          matrix_p => tb%rho_ao_kp_ref
    1595              :       ELSE
    1596        24780 :          matrix_p => scf_env%p_mix_new
    1597              :       END IF
    1598        53852 :       IF (ASSOCIATED(tb%dipbra)) do_dipole = .TRUE.
    1599        53852 :       IF (ASSOCIATED(tb%quadbra)) do_quadrupole = .TRUE.
    1600        53852 :       reuse_native_input = .FALSE.
    1601        53852 :       IF (use_native_mixer) THEN
    1602        47628 :          IF (scf_env%iter_count == 1) THEN
    1603         8604 :             reuse_native_input = ANY(ABS(tb%wfn%qsh) > 1.0E-14_dp)
    1604         4916 :             IF (do_dipole) reuse_native_input = reuse_native_input .OR. &
    1605         5998 :                                                 ANY(ABS(tb%wfn%dpat) > 1.0E-14_dp)
    1606         4916 :             IF (do_quadrupole) reuse_native_input = reuse_native_input .OR. &
    1607         8620 :                                                     ANY(ABS(tb%wfn%qpat) > 1.0E-14_dp)
    1608              :          END IF
    1609              :       END IF
    1610        53852 :       n_atom = SIZE(particle_set)
    1611        53852 :       nkind = SIZE(atomic_kind_set)
    1612        53852 :       CALL get_qs_kind_set(qs_kind_set, maxsgf=nsgf)
    1613       215408 :       ALLOCATE (aocg(nsgf, n_atom))
    1614       269260 :       ALLOCATE (aocg_spin(nsgf, n_atom, nspin))
    1615        53852 :       aocg = 0.0_dp
    1616        53852 :       IF (do_dipole) THEN
    1617       145272 :          ALLOCATE (ao_dip_spin(n_atom, dip_n, nspin))
    1618              :       END IF
    1619        53852 :       IF (do_quadrupole) THEN
    1620       145272 :          ALLOCATE (ao_quad_spin(n_atom, quad_n, nspin))
    1621              :       END IF
    1622              :       max_orb = 0
    1623       136536 :       max_shell = 0
    1624       136536 :       DO ikind = 1, nkind
    1625        82684 :          CALL get_qs_kind(qs_kind_set(ikind), xtb_parameter=xtb_kind)
    1626        82684 :          CALL get_xtb_atom_param(xtb_kind, natorb=natorb)
    1627       136536 :          max_orb = MAX(max_orb, natorb)
    1628              :       END DO
    1629       308694 :       DO is = 1, n_atom
    1630       308694 :          max_shell = MAX(max_shell, tb%calc%bas%nsh_at(is))
    1631              :       END DO
    1632       215408 :       ALLOCATE (ch_atom(n_atom, nspin))
    1633       484668 :       ALLOCATE (ch_orb_spin(max_orb, n_atom, nspin), ch_shell_spin(n_atom, max_shell, nspin))
    1634        53852 :       ch_atom = 0.0_dp
    1635        53852 :       ch_orb_spin = 0.0_dp
    1636        53852 :       ch_shell_spin = 0.0_dp
    1637        53852 :       CALL tb_contract_population(tb, matrix_p, matrix_s, para_env, aocg_spin, ao_dip_spin, ao_quad_spin)
    1638        53852 :       IF (nspin == 1) THEN
    1639      2180920 :          aocg(:, :) = aocg_spin(:, :, 1)
    1640              :       ELSE
    1641        80170 :          aocg(:, :) = aocg_spin(:, :, 1) + aocg_spin(:, :, 2)
    1642         5498 :          IF (do_dipole) THEN
    1643        17024 :             DO im = 1, dip_n
    1644        49172 :                DO iatom = 1, n_atom
    1645        32148 :                   pao = ao_dip_spin(iatom, im, 1)
    1646        32148 :                   ao_dip_spin(iatom, im, 1) = pao + ao_dip_spin(iatom, im, 2)
    1647        44916 :                   ao_dip_spin(iatom, im, 2) = pao - ao_dip_spin(iatom, im, 2)
    1648              :                END DO
    1649              :             END DO
    1650              :          END IF
    1651         5498 :          IF (do_quadrupole) THEN
    1652        29792 :             DO im = 1, quad_n
    1653        94088 :                DO iatom = 1, n_atom
    1654        64296 :                   pao = ao_quad_spin(iatom, im, 1)
    1655        64296 :                   ao_quad_spin(iatom, im, 1) = pao + ao_quad_spin(iatom, im, 2)
    1656        89832 :                   ao_quad_spin(iatom, im, 2) = pao - ao_quad_spin(iatom, im, 2)
    1657              :                END DO
    1658              :             END DO
    1659              :          END IF
    1660              :       END IF
    1661        53852 :       NULLIFY (xtb_kind)
    1662       136536 :       DO ikind = 1, nkind
    1663        82684 :          CALL get_atomic_kind(atomic_kind_set(ikind), natom=na)
    1664        82684 :          CALL get_qs_kind(qs_kind_set(ikind), xtb_parameter=xtb_kind)
    1665        82684 :          CALL get_xtb_atom_param(xtb_kind, natorb=natorb, lao=lao, nao=nao, occupation=occ)
    1666       474062 :          DO iatom = 1, na
    1667       254842 :             atom_a = atomic_kind_set(ikind)%atom_list(iatom)
    1668      2072672 :             DO is = 1, natorb
    1669              :                ! Preserve tblite's native shell order, including repeated angular momenta.
    1670      1817830 :                ns = nao(is)
    1671      1817830 :                norm = 2*lao(is) + 1
    1672      1817830 :                ch_orb_spin(is, atom_a, 1) = aocg(is, atom_a) - tb%calc%h0%refocc(nao(is), ikind)/norm
    1673      1817830 :                IF (nspin == 2) ch_orb_spin(is, atom_a, 2) = &
    1674        49928 :                   aocg_spin(is, atom_a, 1) - aocg_spin(is, atom_a, 2)
    1675      3940430 :                DO ispin = 1, nspin
    1676              :                   ch_shell_spin(atom_a, ns, ispin) = ch_orb_spin(is, atom_a, ispin) + &
    1677      3685588 :                                                      ch_shell_spin(atom_a, ns, ispin)
    1678              :                END DO
    1679              :             END DO
    1680       607212 :             DO ispin = 1, nspin
    1681      2536752 :                ch_atom(atom_a, ispin) = SUM(ch_orb_spin(:, atom_a, ispin))
    1682              :             END DO
    1683              :          END DO
    1684              :       END DO
    1685       308694 :       native_seed_charge = -SUM(ch_atom(:, 1))
    1686              :       seed_native_from_rho = SUM(ABS(aocg_spin)) > 1.0E-10_dp .AND. &
    1687      2395112 :                              ABS(native_seed_charge - REAL(dft_control%charge, dp)) < 1.0E-5_dp
    1688        53852 :       DEALLOCATE (aocg, aocg_spin)
    1689              : 
    1690              :       ! Population arrays use CP2K electron-excess signs. The spin axis already
    1691              :       ! contains total charge and magnetization, as required by tblite.
    1692        53852 :       IF (use_native_mixer) THEN
    1693        47628 :          IF (.NOT. ALLOCATED(tb%mixer)) CPABORT("tblite mixer not initialized")
    1694        47628 :          advance_native_mixer = .FALSE.
    1695        47628 :          IF (use_rho .AND. (.NOT. calculate_forces)) THEN
    1696        24860 :             advance_native_mixer = scf_env%iter_count > 1
    1697              :          END IF
    1698        24860 :          IF (advance_native_mixer) THEN
    1699              :             ! Build the next Hamiltonian from the previous SCC residual.
    1700        22402 :             CALL tb%mixer%next(error)
    1701        22402 :             IF (ALLOCATED(error)) CPABORT("tblite native mixer failed: "//error%message)
    1702        22402 :             CALL tb%mixer%get(tb%wfn%qsh)
    1703        22402 :             CALL tb_sum_shell_charges(tb)
    1704        22402 :             IF (do_dipole) CALL tb%mixer%get(tb%wfn%dpat)
    1705        22402 :             IF (do_quadrupole) CALL tb%mixer%get(tb%wfn%qpat)
    1706        25226 :          ELSE IF (use_rho .AND. (.NOT. calculate_forces)) THEN
    1707         2458 :             IF (.NOT. reuse_native_input) THEN
    1708          158 :                IF (seed_native_from_rho) THEN
    1709              :                   ! SCF_GUESS/RESTART controls the initial SCC state.
    1710          140 :                   CALL tb_set_population(tb, ch_shell_spin, ao_dip_spin, ao_quad_spin)
    1711              :                ELSE
    1712          262 :                   tb%wfn%qsh(:, :) = 0.0_dp
    1713          114 :                   tb%wfn%qat(:, :) = 0.0_dp
    1714          280 :                   IF (do_dipole) tb%wfn%dpat(:, :, :) = 0.0_dp
    1715          466 :                   IF (do_quadrupole) tb%wfn%qpat(:, :, :) = 0.0_dp
    1716              :                END IF
    1717              :             END IF
    1718              :          ELSE
    1719              :             ! Record input/output pairs only after diagonalization, never for forces.
    1720        22768 :             IF (.NOT. calculate_forces) THEN
    1721        22624 :                CALL tb%mixer%set(tb%wfn%qsh)
    1722        22624 :                IF (do_dipole) CALL tb%mixer%set(tb%wfn%dpat)
    1723        22624 :                IF (do_quadrupole) CALL tb%mixer%set(tb%wfn%qpat)
    1724              :             END IF
    1725        22768 :             CALL tb_set_population(tb, ch_shell_spin, ao_dip_spin, ao_quad_spin)
    1726        22768 :             IF (.NOT. calculate_forces) THEN
    1727        22624 :                CALL tb%mixer%diff(tb%wfn%qsh)
    1728        22624 :                IF (do_dipole) CALL tb%mixer%diff(tb%wfn%dpat)
    1729        22624 :                IF (do_quadrupole) CALL tb%mixer%diff(tb%wfn%qpat)
    1730              :             END IF
    1731              :          END IF
    1732              :       ELSE
    1733         6224 :          IF (.NOT. (dft_control%qs_control%do_ls_scf .OR. scf_control%use_ot)) THEN
    1734         4456 :             IF (.NOT. ASSOCIATED(scf_env)) CPABORT("CP2K SCC mixer requires a QS SCF environment")
    1735         4456 :             IF (.NOT. (do_dipole .OR. do_quadrupole) .AND. &
    1736              :                 scf_env%mixing_method == modified_broyden_mixing_nr) THEN
    1737            0 :                CPABORT("MODIFIED_BROYDEN_MIXING with SCC_MIXER CP2K requires GFN2")
    1738              :             END IF
    1739              :          END IF
    1740         6224 :          IF (.NOT. use_no_mixer) THEN
    1741         4456 :             CALL tb_mix_population(scf_env, para_env, ch_shell_spin, ao_dip_spin, ao_quad_spin)
    1742              :          END IF
    1743         6224 :          CALL tb_set_population(tb, ch_shell_spin, ao_dip_spin, ao_quad_spin)
    1744         6224 :          IF (nspin == 1) THEN
    1745              :             IF (.NOT. (do_dipole .OR. do_quadrupole) .OR. &
    1746         4596 :                 dft_control%qs_control%do_ls_scf .OR. scf_control%use_ot) THEN
    1747              :                ! Preserve the existing atom-charge convention for shell-only mixing
    1748              :                ! and direct density optimization: qat comes from the unmixed density.
    1749        11890 :                tb%wfn%qat(:, 1) = -ch_atom(:, 1)
    1750              :             END IF
    1751              :          END IF
    1752              :       END IF
    1753              : 
    1754        53852 :       CALL tb_update_scf_potential(qs_env, tb, para_env, calculate_forces)
    1755              : 
    1756        53852 :       IF (ALLOCATED(ao_dip_spin)) DEALLOCATE (ao_dip_spin)
    1757        53852 :       IF (ALLOCATED(ao_quad_spin)) DEALLOCATE (ao_quad_spin)
    1758        53852 :       DEALLOCATE (ch_atom, ch_orb_spin, ch_shell_spin)
    1759              : 
    1760              : #else
    1761              :       MARK_USED(qs_env)
    1762              :       MARK_USED(tb)
    1763              :       MARK_USED(dft_control)
    1764              :       MARK_USED(calculate_forces)
    1765              :       MARK_USED(use_rho)
    1766              :       CPABORT("Built without TBLITE")
    1767              : #endif
    1768              : 
    1769       161556 :    END SUBROUTINE tb_update_charges
    1770              : 
    1771              : #if defined(__TBLITE)
    1772              : ! **************************************************************************************************
    1773              : !> \brief Convert CP2K shell/multipole populations to tblite charge/magnetization state.
    1774              : !> \param tb ...
    1775              : !> \param shell Electron excess per atom, shell and spin channel.
    1776              : !> \param dipole Electron dipoles, allocated only when required.
    1777              : !> \param quadrupole Electron quadrupoles, allocated only when required.
    1778              : ! **************************************************************************************************
    1779        29132 :    SUBROUTINE tb_set_population(tb, shell, dipole, quadrupole)
    1780              :       TYPE(tblite_type), INTENT(INOUT)                   :: tb
    1781              :       REAL(KIND=dp), DIMENSION(:, :, :), INTENT(IN)      :: shell
    1782              :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :, :), &
    1783              :          INTENT(IN)                                      :: dipole, quadrupole
    1784              : 
    1785              :       INTEGER                                            :: iatom, ii, is, ispin
    1786              : 
    1787       164024 :       DO iatom = 1, tb%mol%nat
    1788       134892 :          ii = tb%calc%bas%ish_at(iatom)
    1789       307676 :          DO ispin = 1, tb%wfn%nspin
    1790       511846 :             DO is = 1, tb%calc%bas%nsh_at(iatom)
    1791       511846 :                tb%wfn%qsh(ii + is, ispin) = -shell(iatom, is, ispin)
    1792              :             END DO
    1793       434250 :             IF (ALLOCATED(dipole)) tb%wfn%dpat(:, iatom, ispin) = -dipole(iatom, :, ispin)
    1794       859740 :             IF (ALLOCATED(quadrupole)) tb%wfn%qpat(:, iatom, ispin) = -quadrupole(iatom, :, ispin)
    1795              :          END DO
    1796              :       END DO
    1797        29132 :       CALL tb_sum_shell_charges(tb)
    1798              : 
    1799        29132 :    END SUBROUTINE tb_set_population
    1800              : 
    1801              : ! **************************************************************************************************
    1802              : !> \brief Reconstruct tblite atomic charges from its current shell charges.
    1803              : !> \param tb ...
    1804              : ! **************************************************************************************************
    1805        51534 :    SUBROUTINE tb_sum_shell_charges(tb)
    1806              :       TYPE(tblite_type), INTENT(INOUT)                   :: tb
    1807              : 
    1808              :       INTEGER                                            :: iatom, ii, ispin
    1809              : 
    1810       296270 :       DO iatom = 1, tb%mol%nat
    1811       244736 :          ii = tb%calc%bas%ish_at(iatom)
    1812       555146 :          DO ispin = 1, tb%wfn%nspin
    1813      1176452 :             tb%wfn%qat(iatom, ispin) = SUM(tb%wfn%qsh(ii + 1:ii + tb%calc%bas%nsh_at(iatom), ispin))
    1814              :          END DO
    1815              :       END DO
    1816              : 
    1817        51534 :    END SUBROUTINE tb_sum_shell_charges
    1818              : 
    1819              : ! **************************************************************************************************
    1820              : !> \brief Apply the CP2K mixer to shell and multipole populations for all spin channels.
    1821              : !> \param scf_env ...
    1822              : !> \param para_env ...
    1823              : !> \param shell ...
    1824              : !> \param dipole ...
    1825              : !> \param quadrupole ...
    1826              : ! **************************************************************************************************
    1827         4456 :    SUBROUTINE tb_mix_population(scf_env, para_env, shell, dipole, quadrupole)
    1828              :       TYPE(qs_scf_env_type), POINTER                     :: scf_env
    1829              :       TYPE(mp_para_env_type), POINTER                    :: para_env
    1830              :       REAL(KIND=dp), DIMENSION(:, :, :), INTENT(INOUT)   :: shell
    1831              :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :, :), &
    1832              :          INTENT(INOUT)                                   :: dipole, quadrupole
    1833              : 
    1834              :       INTEGER                                            :: ispin, ncols, nsh, nspin, offset
    1835              :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :)        :: mix_vars
    1836              : 
    1837         4456 :       nspin = SIZE(shell, 3)
    1838         4456 :       IF (nspin == 1 .AND. .NOT. ALLOCATED(dipole) .AND. .NOT. ALLOCATED(quadrupole)) THEN
    1839              :          ! Retain CP2K's electron-excess convention for single-spin shell-only mixing.
    1840              :          CALL charge_mixing(scf_env%mixing_method, scf_env%mixing_store, &
    1841            0 :                             shell(:, :, 1), para_env, scf_env%iter_count)
    1842              :          RETURN
    1843              :       END IF
    1844              : 
    1845         4456 :       nsh = SIZE(shell, 2)
    1846         4456 :       ncols = nspin*nsh
    1847         4456 :       IF (ALLOCATED(dipole)) ncols = ncols + nspin*dip_n
    1848         4456 :       IF (ALLOCATED(quadrupole)) ncols = ncols + nspin*quad_n
    1849        17824 :       ALLOCATE (mix_vars(SIZE(shell, 1), ncols))
    1850              : 
    1851              :       ! Preserve the mixer history layout: all shell channels, then dipoles, then quadrupoles.
    1852         4456 :       offset = 0
    1853        10482 :       DO ispin = 1, nspin
    1854        47838 :          mix_vars(:, offset + 1:offset + nsh) = -shell(:, :, ispin)
    1855        10482 :          offset = offset + nsh
    1856              :       END DO
    1857         4456 :       IF (ALLOCATED(dipole)) THEN
    1858        10482 :          DO ispin = 1, nspin
    1859        68744 :             mix_vars(:, offset + 1:offset + dip_n) = -dipole(:, :, ispin)
    1860        10482 :             offset = offset + dip_n
    1861              :          END DO
    1862              :       END IF
    1863         4456 :       IF (ALLOCATED(quadrupole)) THEN
    1864        10482 :          DO ispin = 1, nspin
    1865       131462 :             mix_vars(:, offset + 1:offset + quad_n) = -quadrupole(:, :, ispin)
    1866        10482 :             offset = offset + quad_n
    1867              :          END DO
    1868              :       END IF
    1869              :       CALL charge_mixing(scf_env%mixing_method, scf_env%mixing_store, &
    1870         4456 :                          mix_vars, para_env, scf_env%iter_count)
    1871         4456 :       offset = 0
    1872        10482 :       DO ispin = 1, nspin
    1873        47838 :          shell(:, :, ispin) = -mix_vars(:, offset + 1:offset + nsh)
    1874        10482 :          offset = offset + nsh
    1875              :       END DO
    1876         4456 :       IF (ALLOCATED(dipole)) THEN
    1877        10482 :          DO ispin = 1, nspin
    1878        68744 :             dipole(:, :, ispin) = -mix_vars(:, offset + 1:offset + dip_n)
    1879        10482 :             offset = offset + dip_n
    1880              :          END DO
    1881              :       END IF
    1882         4456 :       IF (ALLOCATED(quadrupole)) THEN
    1883        10482 :          DO ispin = 1, nspin
    1884       131462 :             quadrupole(:, :, ispin) = -mix_vars(:, offset + 1:offset + quad_n)
    1885        10482 :             offset = offset + quad_n
    1886              :          END DO
    1887              :       END IF
    1888              : 
    1889         4456 :    END SUBROUTINE tb_mix_population
    1890              : 
    1891              : ! **************************************************************************************************
    1892              : !> \brief Evaluate SCC potentials, energies and optional gradients for the current tblite state.
    1893              : !> \param qs_env ...
    1894              : !> \param tb ...
    1895              : !> \param para_env ...
    1896              : !> \param calculate_forces ...
    1897              : ! **************************************************************************************************
    1898        53852 :    SUBROUTINE tb_update_scf_potential(qs_env, tb, para_env, calculate_forces)
    1899              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    1900              :       TYPE(tblite_type), POINTER                         :: tb
    1901              :       TYPE(mp_para_env_type), POINTER                    :: para_env
    1902              :       LOGICAL, INTENT(IN)                                :: calculate_forces
    1903              : 
    1904        53852 :       CALL tb%pot%reset
    1905       308694 :       tb%e_es = 0.0_dp
    1906       308694 :       tb%e_scd = 0.0_dp
    1907       308694 :       tb%e_int = 0.0_dp
    1908        53852 :       IF (ALLOCATED(tb%calc%coulomb)) THEN
    1909        53852 :          CALL tb%calc%coulomb%get_potential(tb%mol, tb%cache, tb%wfn, tb%pot)
    1910        53852 :          CALL tb%calc%coulomb%get_energy(tb%mol, tb%cache, tb%wfn, tb%e_es)
    1911              :       END IF
    1912        53852 :       IF (ALLOCATED(tb%calc%dispersion)) THEN
    1913        53852 :          CALL tb%calc%dispersion%get_potential(tb%mol, tb%dcache, tb%wfn, tb%pot)
    1914        53852 :          CALL tb%calc%dispersion%get_energy(tb%mol, tb%dcache, tb%wfn, tb%e_scd)
    1915              :       END IF
    1916        53852 :       IF (ALLOCATED(tb%calc%interactions)) THEN
    1917         5498 :          CALL tb%calc%interactions%get_potential(tb%mol, tb%icache, tb%wfn, tb%pot)
    1918         5498 :          CALL tb%calc%interactions%get_energy(tb%mol, tb%icache, tb%wfn, tb%e_int)
    1919              :       END IF
    1920              : 
    1921              :       ! The Hamiltonian needs the complete potential in every spin channel.
    1922        53852 :       CALL para_env%sum(tb%pot%vat)
    1923        53852 :       CALL para_env%sum(tb%pot%vsh)
    1924        53852 :       CALL para_env%sum(tb%pot%vdp)
    1925        53852 :       CALL para_env%sum(tb%pot%vqp)
    1926              : 
    1927        53852 :       IF (calculate_forces) THEN
    1928          154 :          IF (ALLOCATED(tb%calc%coulomb)) THEN
    1929         3754 :             tb%grad = 0.0_dp
    1930          154 :             CALL tb%calc%coulomb%get_gradient(tb%mol, tb%cache, tb%wfn, tb%grad, tb%sigma)
    1931          154 :             CALL tb_grad2force(qs_env, tb, para_env, 3, replicated=.FALSE.)
    1932              :          END IF
    1933              : 
    1934          154 :          IF (ALLOCATED(tb%calc%dispersion)) THEN
    1935         3754 :             tb%grad = 0.0_dp
    1936          154 :             CALL tb%calc%dispersion%get_gradient(tb%mol, tb%dcache, tb%wfn, tb%grad, tb%sigma)
    1937          154 :             CALL tb_grad2force(qs_env, tb, para_env, 2, replicated=.FALSE.)
    1938              :          END IF
    1939              : 
    1940          154 :          IF (ALLOCATED(tb%calc%interactions)) THEN
    1941          230 :             tb%grad = 0.0_dp
    1942           22 :             CALL tb%calc%interactions%get_gradient(tb%mol, tb%icache, tb%wfn, tb%grad, tb%sigma)
    1943           22 :             CALL tb_grad2force(qs_env, tb, para_env, 3, replicated=.FALSE.)
    1944              :          END IF
    1945              :       END IF
    1946              : 
    1947        53852 :    END SUBROUTINE tb_update_scf_potential
    1948              : #endif
    1949              : 
    1950              : ! **************************************************************************************************
    1951              : !> \brief ...
    1952              : !> \param qs_env ...
    1953              : !> \param tb ...
    1954              : !> \param dft_control ...
    1955              : ! **************************************************************************************************
    1956        28232 :    SUBROUTINE tb_ham_add_coulomb(qs_env, tb, dft_control)
    1957              : 
    1958              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    1959              :       TYPE(tblite_type), POINTER                         :: tb
    1960              :       TYPE(dft_control_type), POINTER                    :: dft_control
    1961              : 
    1962              : #if defined(__TBLITE)
    1963              :       INTEGER                                           :: i, im, ispin, ikind, iatom, jatom, irow, icol, img, slot
    1964              :       INTEGER                                           :: nimg, nspin, nsgf, natorb, natom_kind, ndip, nquad
    1965              :       INTEGER, DIMENSION(3)                             :: cell
    1966              :       INTEGER, DIMENSION(25)                            :: nao
    1967        28232 :       INTEGER, DIMENSION(:, :, :), POINTER              :: cell_to_index
    1968              :       LOGICAL                                           :: found
    1969        28232 :       REAL(KIND=dp), DIMENSION(:, :), POINTER            :: sblock
    1970        28232 :       REAL(KIND=dp), DIMENSION(:, :), ALLOCATABLE        :: vat
    1971        28232 :       REAL(KIND=dp), DIMENSION(:, :, :), ALLOCATABLE     :: vsh, vmp
    1972        28232 :       TYPE(atomic_kind_type), DIMENSION(:), POINTER      :: atomic_kind_set
    1973              :       TYPE(dbcsr_iterator_type)                         :: iter
    1974        28232 :       TYPE(dbcsr_p_type), DIMENSION(:, :), POINTER       :: matrix_s, ks_matrix
    1975              :       TYPE(kpoint_type), POINTER                        :: kpoints
    1976        28232 :       TYPE(neighbor_list_set_p_type), DIMENSION(:), POINTER :: n_list
    1977        28232 :       TYPE(qs_kind_type), DIMENSION(:), POINTER          :: qs_kind_set
    1978              :       TYPE(xtb_atom_type), POINTER                      :: xtb_atom
    1979              : !$    INTEGER                                           :: hash, lock_num
    1980              : !$    INTEGER(KIND=int_8)                               :: pair_index
    1981        28232 : !$    INTEGER(KIND=omp_lock_kind), DIMENSION(:), ALLOCATABLE :: locks
    1982              :       INTEGER, PARAMETER                               :: nlock = 501
    1983              : 
    1984        28232 :       nimg = dft_control%nimages
    1985              :       CALL get_qs_env(qs_env=qs_env, atomic_kind_set=atomic_kind_set, qs_kind_set=qs_kind_set, &
    1986        28232 :                       matrix_s_kp=matrix_s, matrix_ks_kp=ks_matrix)
    1987        28232 :       nspin = SIZE(ks_matrix, 1)
    1988        28232 :       ndip = MERGE(dip_n, 0, ASSOCIATED(tb%dipbra))
    1989        28232 :       nquad = MERGE(quad_n, 0, ASSOCIATED(tb%quadbra))
    1990        28232 :       CALL get_qs_kind_set(qs_kind_set, maxsgf=nsgf)
    1991       329382 :       ALLOCATE (vsh(nsgf, tb%mol%nat, nspin), vat(tb%mol%nat, nspin), vmp(ndip + nquad, tb%mol%nat, nspin))
    1992              : 
    1993              :       ! Project each potential once per atom and spin, outside the matrix-block loop.
    1994        28232 :       vsh = 0.0_dp
    1995        71718 :       DO ikind = 1, SIZE(atomic_kind_set)
    1996        43486 :          CALL get_atomic_kind(atomic_kind_set(ikind), natom=natom_kind)
    1997        43486 :          CALL get_qs_kind(qs_kind_set(ikind), xtb_parameter=xtb_atom)
    1998        43486 :          CALL get_xtb_atom_param(xtb_atom, nao=nao, natorb=natorb)
    1999       248116 :          DO i = 1, natom_kind
    2000       132912 :             iatom = atomic_kind_set(ikind)%atom_list(i)
    2001       317194 :             DO ispin = 1, nspin
    2002      1112836 :                DO im = 1, natorb
    2003      1112836 :                   vsh(im, iatom, ispin) = tb_spin_project(tb%pot%vsh(nao(im) + tb%calc%bas%ish_at(iatom), :), ispin)
    2004              :                END DO
    2005       140796 :                vat(iatom, ispin) = tb_spin_project(tb%pot%vat(iatom, :), ispin)
    2006       415344 :                DO im = 1, ndip
    2007       415344 :                   vmp(im, iatom, ispin) = tb_spin_project(tb%pot%vdp(im, iatom, :), ispin)
    2008              :                END DO
    2009       822804 :                DO im = 1, nquad
    2010       689892 :                   vmp(ndip + im, iatom, ispin) = tb_spin_project(tb%pot%vqp(im, iatom, :), ispin)
    2011              :                END DO
    2012              :             END DO
    2013              :          END DO
    2014              :       END DO
    2015              : 
    2016        28232 :       IF (nimg == 1) THEN
    2017        15086 : !$OMP PARALLEL DEFAULT(NONE) SHARED(tb, matrix_s, ks_matrix, vsh, vat, vmp) PRIVATE(iter, irow, icol, sblock)
    2018              :          CALL dbcsr_iterator_start(iter, matrix_s(1, 1)%matrix)
    2019              :          DO WHILE (dbcsr_iterator_blocks_left(iter))
    2020              :             CALL dbcsr_iterator_next_block(iter, irow, icol, sblock)
    2021              :             CALL tb_ham_add_block(tb, ks_matrix, sblock, irow, icol, 1, vsh, vat, vmp)
    2022              :          END DO
    2023              :          CALL dbcsr_iterator_stop(iter)
    2024              : !$OMP END PARALLEL
    2025              :       ELSE
    2026        13146 :          CALL get_qs_env(qs_env=qs_env, sab_kp=n_list, kpoints=kpoints)
    2027        13146 :          IF (.NOT. ASSOCIATED(n_list)) THEN
    2028            0 :             CPABORT("Missing k-point neighbor list for tblite Hamiltonian")
    2029              :          END IF
    2030        13146 :          CALL get_kpoint_info(kpoint=kpoints, cell_to_index=cell_to_index)
    2031        13146 : !$       ALLOCATE (locks(nlock))
    2032      6599292 : !$       DO lock_num = 1, nlock
    2033      6599292 : !$          CALL omp_init_lock(locks(lock_num))
    2034              : !$       END DO
    2035              :          ! Preserve neighbor-list multiplicities when several lattice cells share a block.
    2036              : !$OMP PARALLEL DO DEFAULT(NONE) SCHEDULE(GUIDED) &
    2037              : !$OMP SHARED(tb, n_list, cell_to_index, matrix_s, ks_matrix, vsh, vat, vmp, locks) &
    2038        13146 : !$OMP PRIVATE(slot, iatom, jatom, irow, icol, cell, img, sblock, found, pair_index, hash)
    2039              :          DO slot = 1, n_list(1)%nl_size
    2040              :             iatom = n_list(1)%nlist_task(slot)%iatom
    2041              :             jatom = n_list(1)%nlist_task(slot)%jatom
    2042              :             cell(:) = n_list(1)%nlist_task(slot)%cell(:)
    2043              :             irow = MIN(iatom, jatom)
    2044              :             icol = MAX(iatom, jatom)
    2045              :             img = cell_to_index(cell(1), cell(2), cell(3))
    2046              :             CPASSERT(img > 0)
    2047              :             CALL dbcsr_get_block_p(matrix_s(1, img)%matrix, irow, icol, BLOCK=sblock, found=found)
    2048              :             CPASSERT(found)
    2049              : !$          pair_index = INT(irow - 1, int_8)*INT(tb%mol%nat, int_8) + INT(icol, int_8)
    2050              : !$          hash = INT(MOD(pair_index, INT(nlock, int_8))) + 1
    2051              : !$          CALL omp_set_lock(locks(hash))
    2052              :             CALL tb_ham_add_block(tb, ks_matrix, sblock, irow, icol, img, vsh, vat, vmp)
    2053              : !$          CALL omp_unset_lock(locks(hash))
    2054              :          END DO
    2055              : !$OMP END PARALLEL DO
    2056      6599292 : !$       DO lock_num = 1, nlock
    2057      6599292 : !$          CALL omp_destroy_lock(locks(lock_num))
    2058              : !$       END DO
    2059        13146 : !$       DEALLOCATE (locks)
    2060              :       END IF
    2061        28232 :       DEALLOCATE (vsh, vat, vmp)
    2062              : #else
    2063              :       MARK_USED(qs_env)
    2064              :       MARK_USED(tb)
    2065              :       MARK_USED(dft_control)
    2066              :       CPABORT("Built without TBLITE")
    2067              : #endif
    2068              : 
    2069        84696 :    END SUBROUTINE tb_ham_add_coulomb
    2070              : 
    2071              : #if defined(__TBLITE)
    2072              : ! **************************************************************************************************
    2073              : !> \brief Apply shell, atomic and multipole potentials to one matrix block.
    2074              : !> \param tb ...
    2075              : !> \param ks_matrix ...
    2076              : !> \param sblock ...
    2077              : !> \param irow ...
    2078              : !> \param icol ...
    2079              : !> \param img ...
    2080              : !> \param vsh ...
    2081              : !> \param vat ...
    2082              : !> \param vmp ...
    2083              : ! **************************************************************************************************
    2084      2903404 :    SUBROUTINE tb_ham_add_block(tb, ks_matrix, sblock, irow, icol, img, vsh, vat, vmp)
    2085              :       TYPE(tblite_type), POINTER                         :: tb
    2086              :       TYPE(dbcsr_p_type), DIMENSION(:, :), POINTER       :: ks_matrix
    2087              :       REAL(KIND=dp), DIMENSION(:, :), INTENT(IN)         :: sblock
    2088              :       INTEGER, INTENT(IN)                                :: irow, icol, img
    2089              :       REAL(KIND=dp), DIMENSION(:, :, :), INTENT(IN)      :: vsh
    2090              :       REAL(KIND=dp), DIMENSION(:, :), INTENT(IN)         :: vat
    2091              :       REAL(KIND=dp), DIMENSION(:, :, :), INTENT(IN)      :: vmp
    2092              : 
    2093              :       INTEGER                                            :: i, im, ispin, j
    2094              :       LOGICAL                                            :: found
    2095              :       REAL(KIND=dp)                                      :: vatom
    2096      2903404 :       REAL(KIND=dp), DIMENSION(:, :), POINTER            :: ksblock
    2097     58068080 :       TYPE(block_p_type), DIMENSION(dip_n+quad_n)        :: bra, ket
    2098              : 
    2099      2903404 :       CALL tb_get_multipole_blocks(tb, irow, icol, img, bra, ket)
    2100      5831545 :       DO ispin = 1, SIZE(ks_matrix, 1)
    2101      2928141 :          CALL dbcsr_get_block_p(ks_matrix(ispin, img)%matrix, irow, icol, BLOCK=ksblock, found=found)
    2102      2928141 :          CPASSERT(found)
    2103      2928141 :          vatom = vat(irow, ispin) + vat(icol, ispin)
    2104     23845084 :          DO j = 1, SIZE(sblock, 2)
    2105    198331395 :             DO i = 1, SIZE(sblock, 1)
    2106              :                ksblock(i, j) = ksblock(i, j) - 0.5_dp*(vsh(i, irow, ispin)*sblock(i, j) &
    2107    174486311 :                                                        + sblock(i, j)*vsh(j, icol, ispin))
    2108    195403254 :                ksblock(i, j) = ksblock(i, j) - 0.5_dp*vatom*sblock(i, j)
    2109              :             END DO
    2110              :          END DO
    2111     19961779 :          DO im = 1, SIZE(vmp, 1)
    2112              :             ksblock(:, :) = ksblock(:, :) - 0.5_dp*(ket(im)%block(:, :)*vmp(im, irow, ispin) &
    2113    862628688 :                                                     + bra(im)%block(:, :)*vmp(im, icol, ispin))
    2114              :          END DO
    2115              :       END DO
    2116      2903404 :    END SUBROUTINE tb_ham_add_block
    2117              : #endif
    2118              : 
    2119              : ! **************************************************************************************************
    2120              : !> \brief ...
    2121              : !> \param qs_env ...
    2122              : !> \param tb ...
    2123              : ! **************************************************************************************************
    2124         1314 :    SUBROUTINE tb_get_multipole(qs_env, tb)
    2125              : 
    2126              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    2127              :       TYPE(tblite_type), POINTER                         :: tb
    2128              : 
    2129              : #if defined(__TBLITE)
    2130              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'tb_get_multipole'
    2131              : 
    2132              :       INTEGER                                           :: handle, nimg, maxsgf, img, i, idx, slot, ic, im
    2133              :       INTEGER                                           :: ikind, jkind, iatom, jatom, irow, icol, ityp, jtyp
    2134              :       INTEGER                                           :: iset, jset, inda, indb, ia, ib, ij, ni, nj
    2135              :       INTEGER, DIMENSION(3)                              :: cell
    2136         1314 :       INTEGER, DIMENSION(:, :, :), POINTER               :: cell_to_index
    2137              :       REAL(KIND=dp)                                      :: r2
    2138              :       REAL(KIND=dp), DIMENSION(3)                         :: rij
    2139         1314 :       REAL(KIND=dp), DIMENSION(:), ALLOCATABLE             :: stmp
    2140         2628 :       REAL(KIND=dp), DIMENSION(:, :), ALLOCATABLE          :: dtmp, qtmp, dtmpj, qtmpj
    2141         1314 :       REAL(KIND=dp), DIMENSION(:, :, :, :), ALLOCATABLE    :: pair_multipole
    2142        26280 :       TYPE(block_p_type), DIMENSION(dip_n + quad_n)        :: bra, ket
    2143         1314 :       TYPE(dbcsr_p_type), DIMENSION(:, :), POINTER        :: matrix_s
    2144              :       TYPE(dft_control_type), POINTER                    :: dft_control
    2145              :       TYPE(gto_basis_set_type), POINTER                  :: basis_set_a, basis_set_b
    2146         1314 :       TYPE(gto_basis_set_p_type), DIMENSION(:), POINTER   :: basis_set_list
    2147              :       TYPE(kpoint_type), POINTER                         :: kpoints
    2148         1314 :       TYPE(neighbor_list_set_p_type), DIMENSION(:), POINTER :: sab_orb, sab_kp
    2149         1314 :       TYPE(qs_kind_type), DIMENSION(:), POINTER           :: qs_kind_set
    2150              : !$    INTEGER                                           :: hash, lock_num
    2151              : !$    INTEGER(KIND=int_8)                                :: pair_index
    2152         1314 : !$    INTEGER(KIND=omp_lock_kind), DIMENSION(:), ALLOCATABLE :: locks
    2153              :       INTEGER, PARAMETER                                :: nlock = 501
    2154              : 
    2155         1314 :       CALL timeset(routineN, handle)
    2156              :       CALL get_qs_env(qs_env=qs_env, qs_kind_set=qs_kind_set, sab_orb=sab_orb, sab_kp=sab_kp, &
    2157         1314 :                       dft_control=dft_control, kpoints=kpoints, matrix_s_kp=matrix_s)
    2158         1314 :       nimg = dft_control%nimages
    2159         1314 :       IF (nimg > 1) THEN
    2160          554 :          IF (.NOT. ASSOCIATED(sab_kp)) THEN
    2161            0 :             CPABORT("Missing k-point neighbor list for tblite multipoles")
    2162              :          END IF
    2163          554 :          sab_orb => sab_kp
    2164          554 :          CALL get_kpoint_info(kpoint=kpoints, cell_to_index=cell_to_index)
    2165              :       END IF
    2166         1314 :       CALL get_qs_kind_set(qs_kind_set, maxsgf=maxsgf)
    2167         5894 :       ALLOCATE (basis_set_list(SIZE(qs_kind_set)))
    2168         1314 :       CALL basis_set_list_setup(basis_set_list, "ORB", qs_kind_set)
    2169              : 
    2170              :       ! allocate dipole/quadrupole moment matrix elemnts
    2171         1314 :       CALL dbcsr_allocate_matrix_set(tb%dipbra, dip_n*nimg)
    2172         1314 :       CALL dbcsr_allocate_matrix_set(tb%dipket, dip_n*nimg)
    2173         1314 :       CALL dbcsr_allocate_matrix_set(tb%quadbra, quad_n*nimg)
    2174         1314 :       CALL dbcsr_allocate_matrix_set(tb%quadket, quad_n*nimg)
    2175        24990 :       DO img = 1, nimg
    2176        94704 :          DO i = 1, dip_n
    2177        71028 :             idx = i + dip_n*(img - 1)
    2178        71028 :             ALLOCATE (tb%dipbra(idx)%matrix)
    2179        71028 :             ALLOCATE (tb%dipket(idx)%matrix)
    2180              :             CALL dbcsr_create(tb%dipbra(idx)%matrix, template=matrix_s(1, img)%matrix, &
    2181        71028 :                               name="DIPOLE BRAMATRIX")
    2182              :             CALL dbcsr_create(tb%dipket(idx)%matrix, template=matrix_s(1, img)%matrix, &
    2183        71028 :                               name="DIPOLE KETMATRIX")
    2184        71028 :             CALL cp_dbcsr_alloc_block_from_nbl(tb%dipbra(idx)%matrix, sab_orb)
    2185        94704 :             CALL cp_dbcsr_alloc_block_from_nbl(tb%dipket(idx)%matrix, sab_orb)
    2186              :          END DO
    2187       167046 :          DO i = 1, quad_n
    2188       142056 :             idx = i + quad_n*(img - 1)
    2189       142056 :             ALLOCATE (tb%quadbra(idx)%matrix)
    2190       142056 :             ALLOCATE (tb%quadket(idx)%matrix)
    2191              :             CALL dbcsr_create(tb%quadbra(idx)%matrix, template=matrix_s(1, img)%matrix, &
    2192       142056 :                               name="QUADRUPOLE BRAMATRIX")
    2193              :             CALL dbcsr_create(tb%quadket(idx)%matrix, template=matrix_s(1, img)%matrix, &
    2194       142056 :                               name="QUADRUPOLE KETMATRIX")
    2195       142056 :             CALL cp_dbcsr_alloc_block_from_nbl(tb%quadbra(idx)%matrix, sab_orb)
    2196       165732 :             CALL cp_dbcsr_alloc_block_from_nbl(tb%quadket(idx)%matrix, sab_orb)
    2197              :          END DO
    2198              :       END DO
    2199              : 
    2200         1314 : !$    ALLOCATE (locks(nlock))
    2201       659628 : !$    DO lock_num = 1, nlock
    2202       659628 : !$       CALL omp_init_lock(locks(lock_num))
    2203              : !$    END DO
    2204              : 
    2205              : !$OMP PARALLEL DEFAULT(NONE) &
    2206              : !$OMP SHARED(tb, sab_orb, basis_set_list, nimg, cell_to_index, maxsgf, locks) &
    2207              : !$OMP PRIVATE(stmp, dtmp, qtmp, dtmpj, qtmpj, pair_multipole, slot, ikind, jkind, iatom, jatom, cell, rij, r2, &
    2208              : !$OMP         irow, icol, i, ic, ityp, jtyp, basis_set_a, basis_set_b, iset, jset, inda, indb, ia, ib, ij, &
    2209         1314 : !$OMP         bra, ket, im, ni, nj, pair_index, hash)
    2210              :       ALLOCATE (stmp(msao(tb%calc%bas%maxl)**2))
    2211              :       ALLOCATE (dtmp(dip_n, SIZE(stmp)), qtmp(quad_n, SIZE(stmp)))
    2212              :       ALLOCATE (dtmpj(dip_n, SIZE(stmp)), qtmpj(quad_n, SIZE(stmp)))
    2213              :       ALLOCATE (pair_multipole(maxsgf, maxsgf, dip_n + quad_n, 2))
    2214              : !$OMP DO SCHEDULE(GUIDED)
    2215              :       DO slot = 1, sab_orb(1)%nl_size
    2216              :          ikind = sab_orb(1)%nlist_task(slot)%ikind
    2217              :          jkind = sab_orb(1)%nlist_task(slot)%jkind
    2218              :          iatom = sab_orb(1)%nlist_task(slot)%iatom
    2219              :          jatom = sab_orb(1)%nlist_task(slot)%jatom
    2220              :          cell(:) = sab_orb(1)%nlist_task(slot)%cell(:)
    2221              :          rij(:) = sab_orb(1)%nlist_task(slot)%r(:)
    2222              :          r2 = NORM2(rij)**2
    2223              :          irow = MIN(iatom, jatom)
    2224              :          icol = MAX(iatom, jatom)
    2225              :          IF (iatom < jatom) THEN
    2226              :             rij = -rij
    2227              :             i = ikind
    2228              :             ikind = jkind
    2229              :             jkind = i
    2230              :          END IF
    2231              :          IF (nimg == 1) THEN
    2232              :             ic = 1
    2233              :          ELSE
    2234              :             ic = cell_to_index(cell(1), cell(2), cell(3))
    2235              :             CPASSERT(ic > 0)
    2236              :          END IF
    2237              :          ityp = tb%mol%id(icol)
    2238              :          jtyp = tb%mol%id(irow)
    2239              :          basis_set_a => basis_set_list(ikind)%gto_basis_set
    2240              :          IF (.NOT. ASSOCIATED(basis_set_a)) CYCLE
    2241              :          basis_set_b => basis_set_list(jkind)%gto_basis_set
    2242              :          IF (.NOT. ASSOCIATED(basis_set_b)) CYCLE
    2243              :          CALL tb_get_multipole_blocks(tb, irow, icol, ic, bra, ket)
    2244              :          ni = SIZE(bra(1)%block, 1)
    2245              :          nj = SIZE(bra(1)%block, 2)
    2246              :          pair_multipole(1:ni, 1:nj, :, :) = 0.0_dp
    2247              : 
    2248              :          DO iset = 1, basis_set_a%nset
    2249              :             DO jset = 1, basis_set_b%nset
    2250              :                CALL multipole_cgto(tb%calc%bas%cgto(jset, jtyp), tb%calc%bas%cgto(iset, ityp), &
    2251              :                                    r2, -rij, tb%calc%bas%intcut, stmp, dtmp, qtmp)
    2252              :                DO inda = 1, basis_set_a%nsgf_set(iset)
    2253              :                   ia = basis_set_a%first_sgf(1, iset) - basis_set_a%first_sgf(1, 1) + inda
    2254              :                   DO indb = 1, basis_set_b%nsgf_set(jset)
    2255              :                      ib = basis_set_b%first_sgf(1, jset) - basis_set_b%first_sgf(1, 1) + indb
    2256              :                      ij = indb + basis_set_b%nsgf_set(jset)*(inda - 1)
    2257              :                      ! Periodic self-images still require the shift to the other center.
    2258              :                      IF (icol == irow .AND. r2 < same_atom**2) THEN
    2259              :                         dtmpj(:, ij) = dtmp(:, ij)
    2260              :                         qtmpj(:, ij) = qtmp(:, ij)
    2261              :                      ELSE
    2262              :                         CALL tb_shift_multipole(-rij, stmp(ij), dtmp(:, ij), qtmp(:, ij), &
    2263              :                                                 dtmpj(:, ij), qtmpj(:, ij))
    2264              :                      END IF
    2265              :                      pair_multipole(ib, ia, 1:dip_n, 1) = pair_multipole(ib, ia, 1:dip_n, 1) + dtmp(:, ij)
    2266              :                      pair_multipole(ib, ia, dip_n + 1:, 1) = pair_multipole(ib, ia, dip_n + 1:, 1) + qtmp(:, ij)
    2267              :                      pair_multipole(ib, ia, 1:dip_n, 2) = pair_multipole(ib, ia, 1:dip_n, 2) + dtmpj(:, ij)
    2268              :                      pair_multipole(ib, ia, dip_n + 1:, 2) = pair_multipole(ib, ia, dip_n + 1:, 2) + qtmpj(:, ij)
    2269              :                   END DO
    2270              :                END DO
    2271              :             END DO
    2272              :          END DO
    2273              : 
    2274              :          ! Integrals are thread-local; lock only the accumulation into shared blocks.
    2275              : !$       pair_index = INT(irow - 1, int_8)*INT(tb%mol%nat, int_8) + INT(icol, int_8)
    2276              : !$       hash = INT(MOD(pair_index, INT(nlock, int_8))) + 1
    2277              : !$       CALL omp_set_lock(locks(hash))
    2278              :          DO im = 1, dip_n + quad_n
    2279              :             bra(im)%block(:, :) = bra(im)%block(:, :) + pair_multipole(1:ni, 1:nj, im, 1)
    2280              :             ket(im)%block(:, :) = ket(im)%block(:, :) + pair_multipole(1:ni, 1:nj, im, 2)
    2281              :          END DO
    2282              : !$       CALL omp_unset_lock(locks(hash))
    2283              :       END DO
    2284              : !$OMP END DO
    2285              :       DEALLOCATE (stmp, dtmp, qtmp, dtmpj, qtmpj, pair_multipole)
    2286              : !$OMP END PARALLEL
    2287       659628 : !$    DO lock_num = 1, nlock
    2288       659628 : !$       CALL omp_destroy_lock(locks(lock_num))
    2289              : !$    END DO
    2290         1314 : !$    DEALLOCATE (locks)
    2291              : 
    2292        72342 :       DO i = 1, SIZE(tb%dipbra)
    2293        71028 :          CALL dbcsr_finalize(tb%dipbra(i)%matrix)
    2294        72342 :          CALL dbcsr_finalize(tb%dipket(i)%matrix)
    2295              :       END DO
    2296       143370 :       DO i = 1, SIZE(tb%quadbra)
    2297       142056 :          CALL dbcsr_finalize(tb%quadbra(i)%matrix)
    2298       143370 :          CALL dbcsr_finalize(tb%quadket(i)%matrix)
    2299              :       END DO
    2300         1314 :       DEALLOCATE (basis_set_list)
    2301         1314 :       CALL timestop(handle)
    2302              : #else
    2303              :       MARK_USED(qs_env)
    2304              :       MARK_USED(tb)
    2305              :       CPABORT("Built without TBLITE")
    2306              : #endif
    2307              : 
    2308         6570 :    END SUBROUTINE tb_get_multipole
    2309              : 
    2310              : ! **************************************************************************************************
    2311              : !> \brief Shift a multipole operator from one center to the other.
    2312              : !> \param vec displacement vector between the two centers
    2313              : !> \param s overlap integral
    2314              : !> \param di dipole integral on the original center
    2315              : !> \param qi quadrupole integral on the original center
    2316              : !> \param dj dipole integral on the shifted center
    2317              : !> \param qj quadrupole integral on the shifted center
    2318              : ! **************************************************************************************************
    2319     19343334 :    PURE SUBROUTINE tb_shift_multipole(vec, s, di, qi, dj, qj)
    2320              : 
    2321              :       REAL(KIND=dp), DIMENSION(:), INTENT(IN)            :: vec
    2322              :       REAL(KIND=dp), INTENT(IN)                          :: s
    2323              :       REAL(KIND=dp), DIMENSION(:), INTENT(IN)            :: di, qi
    2324              :       REAL(KIND=dp), DIMENSION(:), INTENT(OUT)           :: dj, qj
    2325              : 
    2326              :       REAL(KIND=dp)                                      :: tr
    2327              : 
    2328     19343334 :       dj(1) = di(1) + vec(1)*s
    2329     19343334 :       dj(2) = di(2) + vec(2)*s
    2330     19343334 :       dj(3) = di(3) + vec(3)*s
    2331              : 
    2332     19343334 :       qj(1) = 2*vec(1)*di(1) + vec(1)**2*s
    2333     19343334 :       qj(3) = 2*vec(2)*di(2) + vec(2)**2*s
    2334     19343334 :       qj(6) = 2*vec(3)*di(3) + vec(3)**2*s
    2335     19343334 :       qj(2) = vec(1)*di(2) + vec(2)*di(1) + vec(1)*vec(2)*s
    2336     19343334 :       qj(4) = vec(1)*di(3) + vec(3)*di(1) + vec(1)*vec(3)*s
    2337     19343334 :       qj(5) = vec(2)*di(3) + vec(3)*di(2) + vec(2)*vec(3)*s
    2338     19343334 :       tr = 0.5_dp*(qj(1) + qj(3) + qj(6))
    2339              : 
    2340     19343334 :       qj(1) = qi(1) + 1.5_dp*qj(1) - tr
    2341     19343334 :       qj(2) = qi(2) + 1.5_dp*qj(2)
    2342     19343334 :       qj(3) = qi(3) + 1.5_dp*qj(3) - tr
    2343     19343334 :       qj(4) = qi(4) + 1.5_dp*qj(4)
    2344     19343334 :       qj(5) = qi(5) + 1.5_dp*qj(5)
    2345     19343334 :       qj(6) = qi(6) + 1.5_dp*qj(6) - tr
    2346              : 
    2347     19343334 :    END SUBROUTINE tb_shift_multipole
    2348              : 
    2349              : #if defined(__TBLITE)
    2350              : ! **************************************************************************************************
    2351              : !> \brief Fetch the multipole blocks in dipole, then quadrupole order.
    2352              : !> \param tb ...
    2353              : !> \param irow ...
    2354              : !> \param icol ...
    2355              : !> \param img ...
    2356              : !> \param bra ...
    2357              : !> \param ket ...
    2358              : ! **************************************************************************************************
    2359    332650820 :    SUBROUTINE tb_get_multipole_blocks(tb, irow, icol, img, bra, ket)
    2360              :       TYPE(tblite_type), POINTER                         :: tb
    2361              :       INTEGER, INTENT(IN)                                :: irow, icol, img
    2362              :       TYPE(block_p_type), DIMENSION(:), INTENT(OUT)      :: bra, ket
    2363              : 
    2364              :       INTEGER                                            :: idx, im, ndip
    2365              :       LOGICAL                                            :: found
    2366              : 
    2367     16632541 :       ndip = 0
    2368     16632541 :       IF (ASSOCIATED(tb%dipbra)) THEN
    2369     29701404 :          ndip = dip_n
    2370     29701404 :          DO im = 1, dip_n
    2371     22276053 :             idx = im + dip_n*(img - 1)
    2372     22276053 :             CALL dbcsr_get_block_p(tb%dipbra(idx)%matrix, irow, icol, BLOCK=bra(im)%block, found=found)
    2373     22276053 :             CPASSERT(found)
    2374     22276053 :             CALL dbcsr_get_block_p(tb%dipket(idx)%matrix, irow, icol, BLOCK=ket(im)%block, found=found)
    2375     51977457 :             CPASSERT(found)
    2376              :          END DO
    2377              :       END IF
    2378     16632541 :       IF (ASSOCIATED(tb%quadbra)) THEN
    2379     51977457 :          DO im = 1, quad_n
    2380     44552106 :             idx = im + quad_n*(img - 1)
    2381     44552106 :             CALL dbcsr_get_block_p(tb%quadbra(idx)%matrix, irow, icol, BLOCK=bra(ndip + im)%block, found=found)
    2382     44552106 :             CPASSERT(found)
    2383     44552106 :             CALL dbcsr_get_block_p(tb%quadket(idx)%matrix, irow, icol, BLOCK=ket(ndip + im)%block, found=found)
    2384     96529563 :             CPASSERT(found)
    2385              :          END DO
    2386              :       END IF
    2387     16632541 :    END SUBROUTINE tb_get_multipole_blocks
    2388              : 
    2389              : ! **************************************************************************************************
    2390              : !> \brief Contract all spin channels and multipoles, reducing all images together.
    2391              : !> \param tb ...
    2392              : !> \param matrix_p ...
    2393              : !> \param matrix_s ...
    2394              : !> \param para_env ...
    2395              : !> \param charges ...
    2396              : !> \param dipoles ...
    2397              : !> \param quadrupoles ...
    2398              : ! **************************************************************************************************
    2399        53852 :    SUBROUTINE tb_contract_population(tb, matrix_p, matrix_s, para_env, charges, dipoles, quadrupoles)
    2400              :       TYPE(tblite_type), POINTER                         :: tb
    2401              :       TYPE(dbcsr_p_type), DIMENSION(:, :), POINTER       :: matrix_p, matrix_s
    2402              :       TYPE(mp_para_env_type), POINTER                    :: para_env
    2403              :       REAL(KIND=dp), DIMENSION(:, :, :), INTENT(OUT)     :: charges
    2404              :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :, :), &
    2405              :          INTENT(INOUT)                                   :: dipoles, quadrupoles
    2406              : 
    2407              :       INTEGER                                            :: i, icol, im, img, irow, ispin, j, natom, &
    2408              :                                                             ndip, nquad, nsgf, nspin
    2409              :       LOGICAL                                            :: found
    2410              :       REAL(KIND=dp)                                      :: pcol, prow, ps
    2411        53852 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :, :)     :: local_population, population
    2412        53852 :       REAL(KIND=dp), DIMENSION(:, :), POINTER            :: pblock, sblock
    2413      1077040 :       TYPE(block_p_type), DIMENSION(dip_n+quad_n)        :: bra, ket
    2414              :       TYPE(dbcsr_iterator_type)                          :: iter
    2415              : 
    2416        53852 :       nsgf = SIZE(charges, 1)
    2417        53852 :       natom = SIZE(charges, 2)
    2418        53852 :       nspin = SIZE(charges, 3)
    2419        17534 :       ndip = MERGE(dip_n, 0, ALLOCATED(dipoles))
    2420        53852 :       nquad = MERGE(quad_n, 0, ALLOCATED(quadrupoles))
    2421       269260 :       ALLOCATE (population(nsgf + ndip + nquad, natom, nspin))
    2422        53852 :       population = 0.0_dp
    2423              : 
    2424              : !$OMP PARALLEL DEFAULT(NONE) &
    2425              : !$OMP SHARED(tb, matrix_p, matrix_s, population, nsgf, natom, nspin, ndip, nquad) &
    2426        53852 : !$OMP PRIVATE(local_population, iter, img, irow, icol, sblock, pblock, found, bra, ket, ispin, i, j, im, ps, prow, pcol)
    2427              :       ALLOCATE (local_population(nsgf + ndip + nquad, natom, nspin))
    2428              :       local_population = 0.0_dp
    2429              :       DO img = 1, SIZE(matrix_s, 2)
    2430              :          CALL dbcsr_iterator_start(iter, matrix_s(1, img)%matrix)
    2431              :          DO WHILE (dbcsr_iterator_blocks_left(iter))
    2432              :             CALL dbcsr_iterator_next_block(iter, irow, icol, sblock)
    2433              :             CALL tb_get_multipole_blocks(tb, irow, icol, img, bra, ket)
    2434              :             DO ispin = 1, nspin
    2435              :                CALL dbcsr_get_block_p(matrix_p(ispin, img)%matrix, irow, icol, BLOCK=pblock, found=found)
    2436              :                IF (.NOT. found) CYCLE
    2437              :                DO j = 1, SIZE(pblock, 2)
    2438              :                   DO i = 1, SIZE(pblock, 1)
    2439              :                      ps = pblock(i, j)*sblock(i, j)
    2440              :                      local_population(i, irow, ispin) = local_population(i, irow, ispin) + ps
    2441              :                      IF (irow /= icol) THEN
    2442              :                         local_population(j, icol, ispin) = local_population(j, icol, ispin) + ps
    2443              :                      END IF
    2444              :                   END DO
    2445              :                END DO
    2446              :                DO im = 1, ndip + nquad
    2447              :                   IF (irow == icol) THEN
    2448              :                      prow = SUM(pblock*bra(im)%block)
    2449              :                   ELSE
    2450              :                      prow = SUM(pblock*ket(im)%block)
    2451              :                      pcol = SUM(pblock*bra(im)%block)
    2452              :                      local_population(nsgf + im, icol, ispin) = local_population(nsgf + im, icol, ispin) + pcol
    2453              :                   END IF
    2454              :                   local_population(nsgf + im, irow, ispin) = local_population(nsgf + im, irow, ispin) + prow
    2455              :                END DO
    2456              :             END DO
    2457              :          END DO
    2458              :          CALL dbcsr_iterator_stop(iter)
    2459              :       END DO
    2460              : !$OMP CRITICAL(tblite_population)
    2461              :       population(:, :, :) = population(:, :, :) + local_population(:, :, :)
    2462              : !$OMP END CRITICAL(tblite_population)
    2463              :       DEALLOCATE (local_population)
    2464              : !$OMP END PARALLEL
    2465              : 
    2466              :       ! Real-space density images already contain the k-point weights.
    2467        53852 :       CALL para_env%sum(population)
    2468      2395112 :       charges(:, :, :) = population(1:nsgf, :, :)
    2469       113202 :       DO ispin = 1, nspin
    2470       181072 :          DO im = 1, ndip
    2471       712300 :             dipoles(:, im, ispin) = population(nsgf + im, :, ispin)
    2472              :          END DO
    2473       356646 :          DO im = 1, nquad
    2474      1365250 :             quadrupoles(:, im, ispin) = population(nsgf + ndip + im, :, ispin)
    2475              :          END DO
    2476              :       END DO
    2477        53852 :       DEALLOCATE (population)
    2478       107704 :    END SUBROUTINE tb_contract_population
    2479              : #endif
    2480              : 
    2481              : ! **************************************************************************************************
    2482              : !> \brief save gradient to force
    2483              : !> \param qs_env ...
    2484              : !> \param tb ...
    2485              : !> \param para_env ...
    2486              : !> \param ityp ...
    2487              : !> \param replicated Whether the gradient has already been summed over the QS communicator.
    2488              : ! **************************************************************************************************
    2489         1032 :    SUBROUTINE tb_grad2force(qs_env, tb, para_env, ityp, replicated)
    2490              : 
    2491              :       TYPE(qs_environment_type)                          :: qs_env
    2492              :       TYPE(tblite_type)                                  :: tb
    2493              :       TYPE(mp_para_env_type)                             :: para_env
    2494              :       INTEGER                                            :: ityp
    2495              :       LOGICAL, INTENT(IN)                                :: replicated
    2496              : 
    2497              :       CHARACTER(len=*), PARAMETER                        :: routineN = 'tb_grad2force'
    2498              : 
    2499              :       INTEGER                                            :: atoma, handle, iatom, ikind, natom
    2500         1032 :       INTEGER, ALLOCATABLE, DIMENSION(:)                 :: atom_of_kind, kind_of
    2501              :       REAL(KIND=dp)                                      :: scale
    2502         1032 :       TYPE(atomic_kind_type), DIMENSION(:), POINTER      :: atomic_kind_set
    2503         1032 :       TYPE(particle_type), DIMENSION(:), POINTER         :: particle_set
    2504         1032 :       TYPE(qs_force_type), DIMENSION(:), POINTER         :: force
    2505              : 
    2506         1032 :       CALL timeset(routineN, handle)
    2507              : 
    2508         1032 :       NULLIFY (force, atomic_kind_set)
    2509              :       CALL get_qs_env(qs_env=qs_env, force=force, particle_set=particle_set, &
    2510         1032 :                       atomic_kind_set=atomic_kind_set)
    2511              :       CALL get_atomic_kind_set(atomic_kind_set=atomic_kind_set, &
    2512         1032 :                                atom_of_kind=atom_of_kind, kind_of=kind_of)
    2513              : 
    2514         1032 :       natom = SIZE(particle_set)
    2515              : 
    2516              :       ! CP2K sums the force components after all local contributions are assembled.
    2517         1032 :       scale = 1.0_dp
    2518         1032 :       IF (replicated) scale = 1.0_dp/para_env%num_pe
    2519              : 
    2520         1032 :       SELECT CASE (ityp)
    2521              :       CASE DEFAULT
    2522            0 :          CPABORT("unknown force type")
    2523              :       CASE (0)
    2524          730 :          DO iatom = 1, natom
    2525          644 :             ikind = kind_of(iatom)
    2526          644 :             atoma = atom_of_kind(iatom)
    2527              :             force(ikind)%all_potential(:, atoma) = &
    2528         2662 :                force(ikind)%all_potential(:, atoma) + scale*tb%grad(:, iatom)
    2529              :          END DO
    2530              :       CASE (1)
    2531         1054 :          DO iatom = 1, natom
    2532          900 :             ikind = kind_of(iatom)
    2533          900 :             atoma = atom_of_kind(iatom)
    2534              :             force(ikind)%repulsive(:, atoma) = &
    2535         3754 :                force(ikind)%repulsive(:, atoma) + scale*tb%grad(:, iatom)
    2536              :          END DO
    2537              :       CASE (2)
    2538         2108 :          DO iatom = 1, natom
    2539         1800 :             ikind = kind_of(iatom)
    2540         1800 :             atoma = atom_of_kind(iatom)
    2541              :             force(ikind)%dispersion(:, atoma) = &
    2542         7508 :                force(ikind)%dispersion(:, atoma) + scale*tb%grad(:, iatom)
    2543              :          END DO
    2544              :       CASE (3)
    2545         1128 :          DO iatom = 1, natom
    2546          952 :             ikind = kind_of(iatom)
    2547          952 :             atoma = atom_of_kind(iatom)
    2548              :             force(ikind)%rho_elec(:, atoma) = &
    2549         3984 :                force(ikind)%rho_elec(:, atoma) + scale*tb%grad(:, iatom)
    2550              :          END DO
    2551              :       CASE (4)
    2552         2108 :          DO iatom = 1, natom
    2553         1800 :             ikind = kind_of(iatom)
    2554         1800 :             atoma = atom_of_kind(iatom)
    2555              :             force(ikind)%overlap(:, atoma) = &
    2556         7508 :                force(ikind)%overlap(:, atoma) + scale*tb%grad(:, iatom)
    2557              :          END DO
    2558              :       CASE (5)
    2559         1032 :          DO iatom = 1, natom
    2560            0 :             ikind = kind_of(iatom)
    2561            0 :             atoma = atom_of_kind(iatom)
    2562              :             force(ikind)%efield(:, atoma) = &
    2563            0 :                force(ikind)%efield(:, atoma) + scale*tb%grad(:, iatom)
    2564              :          END DO
    2565              :       END SELECT
    2566              : 
    2567         1032 :       CALL timestop(handle)
    2568              : 
    2569         2064 :    END SUBROUTINE tb_grad2force
    2570              : 
    2571              : ! **************************************************************************************************
    2572              : !> \brief Add SCC-overlap and direct multipole Hamiltonian derivatives.
    2573              : !> \param qs_env ...
    2574              : !> \param use_rho ...
    2575              : !> \param nimg ...
    2576              : ! **************************************************************************************************
    2577          154 :    SUBROUTINE tb_derive_dH_off(qs_env, use_rho, nimg)
    2578              : 
    2579              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    2580              :       LOGICAL, INTENT(IN)                                :: use_rho
    2581              :       INTEGER, INTENT(IN)                                :: nimg
    2582              : 
    2583              : #if defined(__TBLITE)
    2584              :       INTEGER                                            :: i, idim, ij, iatom, ic, icol, ikind, img, ispin, &
    2585              :                                                             jdim, ni, nj, nkind, nel, &
    2586              :                                                             ityp, jatom, jkind, jrow, jtyp, iset, jset, nseti, nsetj, &
    2587              :                                                             ia, ib, inda, indb, sampled_axes, sampled_even_axes, &
    2588              :                                                             sampled_gamma_axes, nspin, ikp_axis, slot, maxsgf, natorb_a, natorb_b
    2589              :       INTEGER, DIMENSION(3)                              :: cellind, nkp_cellind, nkp_grid
    2590          154 :       INTEGER, DIMENSION(:), POINTER                     :: nsgfa, nsgfb
    2591          154 :       INTEGER, DIMENSION(:, :), POINTER                  :: first_sgfa, first_sgfb
    2592          154 :       INTEGER, DIMENSION(:, :, :), POINTER               :: cell_to_index
    2593              :       LOGICAL                                            :: found, gamma_centered, gamma_sampled_image_pair, &
    2594              :                                                             has_multipole_response, sampled_image_pair, &
    2595              :                                                             use_matrix_scc_stress
    2596              :       LOGICAL, DIMENSION(3)                              :: mesh_has_gamma
    2597              :       REAL(KIND=dp)                                      :: r2, dr, i_a_shift, j_a_shift, i_a_shift_mag, j_a_shift_mag, &
    2598              :                                                             ishift, jshift, ishift_mag, jshift_mag, pij_charge, &
    2599              :                                                             pij_magnet, mp_pair_scale, kpoint_coordinate, native_dot_tmp
    2600              :       REAL(KIND=dp), DIMENSION(3)                        :: kp_shift
    2601              :       REAL(KIND=dp), DIMENSION(3)                        :: rij, dgrad, dhgrad_charge, dhgrad_magnet, &
    2602              :                                                             mpgrad_charge, mpgrad_magnet
    2603              :       REAL(KIND=dp), DIMENSION(3, 3)                     :: hsigma
    2604              :       REAL(KIND=dp), DIMENSION(dip_n)                    :: idip, jdip, idip_mag, jdip_mag
    2605              :       REAL(KIND=dp), DIMENSION(quad_n)                   :: iquad, jquad, iquad_mag, jquad_mag
    2606          154 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:)            :: t_ov
    2607          154 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :)         :: local_grad
    2608          154 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :)        :: t_dip, t_quad, t_d_ov
    2609          154 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :, :)     :: t_i_dip, t_i_quad, t_j_dip, t_j_quad
    2610          154 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :, :, :, :) :: scc_strain_hint
    2611          154 :       REAL(KIND=dp), DIMENSION(:, :), POINTER            :: pblock, pblock_beta
    2612         4158 :       TYPE(block_p_type), DIMENSION(3, 3, 2)             :: scc_strain_blocks
    2613              : 
    2614          154 :       TYPE(atomic_kind_type), DIMENSION(:), POINTER      :: atomic_kind_set
    2615          154 :       TYPE(dbcsr_p_type), DIMENSION(:, :), POINTER       :: matrix_dh_scc, matrix_p
    2616          154 :       TYPE(gto_basis_set_p_type), DIMENSION(:), POINTER  :: basis_set_list
    2617              :       TYPE(gto_basis_set_type), POINTER            :: basis_set_a, basis_set_b
    2618              :       TYPE(kpoint_type), POINTER                         :: kpoints
    2619              :       TYPE(mp_para_env_type), POINTER                    :: para_env
    2620              :       TYPE(neighbor_list_set_p_type), DIMENSION(:), &
    2621          154 :          POINTER                                         :: sab_orb
    2622              :       TYPE(neighbor_list_set_p_type), DIMENSION(:), &
    2623          154 :          POINTER                                         :: sab_kp
    2624          154 :       TYPE(qs_kind_type), DIMENSION(:), POINTER          :: qs_kind_set
    2625              :       TYPE(qs_rho_type), POINTER                         :: rho
    2626              :       TYPE(qs_scf_env_type), POINTER                     :: scf_env
    2627              :       TYPE(tblite_type), POINTER                         :: tb
    2628              :       TYPE(virial_type), POINTER                         :: virial
    2629              : 
    2630              : !$    INTEGER                                           :: hash, lock_num
    2631              : !$    INTEGER(KIND=int_8)                                :: pair_index
    2632          154 : !$    INTEGER(KIND=omp_lock_kind), DIMENSION(:), ALLOCATABLE :: locks
    2633              :       INTEGER, PARAMETER                                :: nlock = 501
    2634              : 
    2635              :       ! compute mulliken charges required for charge update
    2636          154 :       NULLIFY (scf_env, rho, tb, sab_orb, sab_kp, para_env, kpoints, matrix_dh_scc, virial)
    2637              :       CALL get_qs_env(qs_env=qs_env, &
    2638              :                       atomic_kind_set=atomic_kind_set, &
    2639              :                       scf_env=scf_env, &
    2640              :                       rho=rho, &
    2641              :                       tb_tblite=tb, &
    2642              :                       sab_orb=sab_orb, &
    2643              :                       sab_kp=sab_kp, &
    2644              :                       para_env=para_env, &
    2645              :                       qs_kind_set=qs_kind_set, &
    2646          154 :                       kpoints=kpoints)
    2647              : 
    2648          154 :       NULLIFY (cell_to_index)
    2649          154 :       IF (nimg > 1) THEN
    2650           92 :          IF (.NOT. ASSOCIATED(sab_kp)) CPABORT("Missing tblite k-point neighbor list")
    2651           92 :          sab_orb => sab_kp
    2652              :          CALL get_kpoint_info(kpoint=kpoints, cell_to_index=cell_to_index, nkp_grid=nkp_grid, &
    2653           92 :                               kp_shift=kp_shift, gamma_centered=gamma_centered)
    2654              :       ELSE
    2655          248 :          nkp_grid = 1
    2656           62 :          kp_shift = 0.0_dp
    2657           62 :          gamma_centered = .TRUE.
    2658              :       END IF
    2659          154 :       mesh_has_gamma = .FALSE.
    2660          616 :       DO i = 1, 3
    2661         1312 :          DO ikp_axis = 1, nkp_grid(i)
    2662          696 :             IF (gamma_centered .AND. MODULO(nkp_grid(i), 2) == 0) THEN
    2663              :                kpoint_coordinate = REAL(2*ikp_axis - nkp_grid(i), KIND=dp)/ &
    2664            0 :                                    REAL(2*nkp_grid(i), KIND=dp) + kp_shift(i)
    2665              :             ELSE
    2666              :                kpoint_coordinate = REAL(2*ikp_axis - nkp_grid(i) - 1, KIND=dp)/ &
    2667          696 :                                    REAL(2*nkp_grid(i), KIND=dp) + kp_shift(i)
    2668              :             END IF
    2669         1158 :             IF (ABS(kpoint_coordinate - ANINT(kpoint_coordinate)) < 1.0e-12_dp) THEN
    2670          330 :                mesh_has_gamma(i) = .TRUE.
    2671              :             END IF
    2672              :          END DO
    2673              :       END DO
    2674          154 :       has_multipole_response = ASSOCIATED(tb%dipbra) .OR. ASSOCIATED(tb%quadbra)
    2675              : 
    2676          154 :       NULLIFY (matrix_p)
    2677          154 :       IF (use_rho) THEN
    2678          132 :          CALL qs_rho_get(rho, rho_ao_kp=matrix_p)
    2679           22 :       ELSE IF (ASSOCIATED(tb%rho_ao_kp_ref)) THEN
    2680           22 :          matrix_p => tb%rho_ao_kp_ref
    2681              :       ELSE
    2682            0 :          matrix_p => scf_env%p_mix_new
    2683              :       END IF
    2684          154 :       nspin = SIZE(matrix_p, 1)
    2685          400 :       use_matrix_scc_stress = tb%use_virial .AND. nimg > 1 .AND. ALL(tb%mol%periodic)
    2686              : 
    2687              :       IF (use_matrix_scc_stress) THEN
    2688           50 :          CALL dbcsr_allocate_matrix_set(matrix_dh_scc, 9*nspin, nimg)
    2689         3994 :          DO img = 1, nimg
    2690         7994 :             DO ispin = 1, nspin
    2691        19944 :                DO jdim = 1, 3
    2692        52000 :                   DO idim = 1, 3
    2693        36000 :                      i = idim + 3*(jdim - 1) + 9*(ispin - 1)
    2694        36000 :                      ALLOCATE (matrix_dh_scc(i, img)%matrix)
    2695              :                      CALL dbcsr_create(matrix_dh_scc(i, img)%matrix, template=matrix_p(ispin, img)%matrix, &
    2696        36000 :                                        name="TBLITE SCC STRAIN DERIVATIVE")
    2697        48000 :                      CALL cp_dbcsr_alloc_block_from_nbl(matrix_dh_scc(i, img)%matrix, sab_orb)
    2698              :                   END DO
    2699              :                END DO
    2700              :             END DO
    2701              :          END DO
    2702              :       END IF
    2703              : 
    2704              :       ! set up basis set lists
    2705          154 :       nkind = SIZE(atomic_kind_set)
    2706          764 :       ALLOCATE (basis_set_list(nkind))
    2707          154 :       CALL basis_set_list_setup(basis_set_list, "ORB", qs_kind_set)
    2708              : 
    2709          154 :       nel = msao(tb%calc%bas%maxl)**2
    2710          154 :       CALL get_qs_kind_set(qs_kind_set, maxsgf=maxsgf)
    2711         3754 :       tb%grad = 0.0_dp
    2712          154 :       hsigma = 0.0_dp
    2713          154 : !$    ALLOCATE (locks(nlock))
    2714        77308 : !$    DO lock_num = 1, nlock
    2715        77308 : !$       CALL omp_init_lock(locks(lock_num))
    2716              : !$    END DO
    2717              : 
    2718              : !$OMP PARALLEL DEFAULT(NONE) &
    2719              : !$OMP SHARED(tb, sab_orb, basis_set_list, nimg, nspin, nel, maxsgf, cell_to_index, nkp_grid, mesh_has_gamma, &
    2720              : !$OMP        has_multipole_response, matrix_p, matrix_dh_scc, use_matrix_scc_stress, locks) &
    2721              : !$OMP PRIVATE(local_grad, t_ov, t_d_ov, t_dip, t_i_dip, t_j_dip, t_quad, t_i_quad, t_j_quad, &
    2722              : !$OMP         idip, jdip, idip_mag, jdip_mag, iquad, jquad, iquad_mag, jquad_mag, scc_strain_hint, &
    2723              : !$OMP         slot, i, idim, jdim, ij, iatom, jatom, ikind, jkind, icol, jrow, ityp, jtyp, cellind, rij, r2, dr, &
    2724              : !$OMP         basis_set_a, basis_set_b, first_sgfa, first_sgfb, nsgfa, nsgfb, nseti, nsetj, ic, nkp_cellind, &
    2725              : !$OMP         sampled_axes, sampled_even_axes, sampled_gamma_axes, sampled_image_pair, gamma_sampled_image_pair, &
    2726              : !$OMP         mp_pair_scale, pblock, pblock_beta, found, ispin, scc_strain_blocks, i_a_shift, j_a_shift, &
    2727              : !$OMP         i_a_shift_mag, j_a_shift_mag, ni, nj, iset, jset, ishift, jshift, ishift_mag, jshift_mag, &
    2728              : !$OMP         dgrad, inda, indb, ia, ib, pij_charge, pij_magnet, mpgrad_charge, mpgrad_magnet, &
    2729          154 : !$OMP         dhgrad_charge, dhgrad_magnet, natorb_a, natorb_b, pair_index, hash) REDUCTION(+:hsigma)
    2730              :       ALLOCATE (t_ov(nel), t_d_ov(3, nel), t_dip(dip_n, nel), t_quad(quad_n, nel))
    2731              :       ALLOCATE (t_i_dip(3, dip_n, nel), t_j_dip(3, dip_n, nel))
    2732              :       ALLOCATE (t_i_quad(3, quad_n, nel), t_j_quad(3, quad_n, nel))
    2733              :       ALLOCATE (local_grad(3, tb%mol%nat))
    2734              :       local_grad = 0.0_dp
    2735              :       IF (use_matrix_scc_stress) ALLOCATE (scc_strain_hint(maxsgf, maxsgf, 3, 3, nspin))
    2736              : !$OMP DO SCHEDULE(GUIDED)
    2737              :       DO slot = 1, sab_orb(1)%nl_size
    2738              :          ikind = sab_orb(1)%nlist_task(slot)%ikind
    2739              :          jkind = sab_orb(1)%nlist_task(slot)%jkind
    2740              :          iatom = sab_orb(1)%nlist_task(slot)%iatom
    2741              :          jatom = sab_orb(1)%nlist_task(slot)%jatom
    2742              :          cellind(:) = sab_orb(1)%nlist_task(slot)%cell(:)
    2743              :          rij(:) = sab_orb(1)%nlist_task(slot)%r(:)
    2744              : 
    2745              :          icol = MAX(iatom, jatom)
    2746              :          jrow = MIN(iatom, jatom)
    2747              : 
    2748              :          IF (iatom < jatom) THEN
    2749              :             rij = -rij
    2750              :             i = ikind
    2751              :             ikind = jkind
    2752              :             jkind = i
    2753              :          END IF
    2754              : 
    2755              :          ityp = tb%mol%id(icol)
    2756              :          jtyp = tb%mol%id(jrow)
    2757              : 
    2758              :          r2 = DOT_PRODUCT(rij, rij)
    2759              :          dr = SQRT(r2)
    2760              :          IF (icol == jrow .AND. dr < same_atom) CYCLE
    2761              : 
    2762              :          !get basis information
    2763              :          basis_set_a => basis_set_list(ikind)%gto_basis_set
    2764              :          IF (.NOT. ASSOCIATED(basis_set_a)) CYCLE
    2765              :          first_sgfa => basis_set_a%first_sgf
    2766              :          nsgfa => basis_set_a%nsgf_set
    2767              :          nseti = basis_set_a%nset
    2768              :          basis_set_b => basis_set_list(jkind)%gto_basis_set
    2769              :          IF (.NOT. ASSOCIATED(basis_set_b)) CYCLE
    2770              :          first_sgfb => basis_set_b%first_sgf
    2771              :          nsgfb => basis_set_b%nsgf_set
    2772              :          nsetj = basis_set_b%nset
    2773              : 
    2774              :          IF (nimg == 1) THEN
    2775              :             ic = 1
    2776              :          ELSE
    2777              :             ic = cell_to_index(cellind(1), cellind(2), cellind(3))
    2778              :             CPASSERT(ic > 0)
    2779              :          END IF
    2780              :          nkp_cellind = 0
    2781              :          DO i = 1, 3
    2782              :             IF (nkp_grid(i) > 1) THEN
    2783              :                nkp_cellind(i) = MODULO(cellind(i), nkp_grid(i))
    2784              :                IF (2*nkp_cellind(i) > nkp_grid(i)) nkp_cellind(i) = nkp_cellind(i) - nkp_grid(i)
    2785              :             END IF
    2786              :          END DO
    2787              :          sampled_axes = 0
    2788              :          IF (nkp_cellind(1) /= 0) sampled_axes = sampled_axes + 1
    2789              :          IF (nkp_cellind(2) /= 0) sampled_axes = sampled_axes + 1
    2790              :          IF (nkp_cellind(3) /= 0) sampled_axes = sampled_axes + 1
    2791              :          sampled_even_axes = 0
    2792              :          sampled_gamma_axes = 0
    2793              :          DO i = 1, 3
    2794              :             IF (nkp_grid(i) > 1 .AND. MODULO(nkp_grid(i), 2) == 0 .AND. &
    2795              :                 ABS(2*nkp_cellind(i)) == nkp_grid(i)) THEN
    2796              :                sampled_even_axes = sampled_even_axes + 1
    2797              :                IF (mesh_has_gamma(i)) sampled_gamma_axes = sampled_gamma_axes + 1
    2798              :             END IF
    2799              :          END DO
    2800              :          sampled_image_pair = sampled_axes > 0 .AND. sampled_even_axes > 0
    2801              :          gamma_sampled_image_pair = sampled_image_pair .AND. sampled_gamma_axes == sampled_even_axes
    2802              :          mp_pair_scale = 1.0_dp
    2803              :          IF (icol == jrow .AND. sampled_image_pair .AND. has_multipole_response .AND. &
    2804              :              .NOT. gamma_sampled_image_pair) mp_pair_scale = -1.0_dp
    2805              : 
    2806              :          NULLIFY (pblock, pblock_beta)
    2807              :          CALL dbcsr_get_block_p(matrix=matrix_p(1, ic)%matrix, &
    2808              :                                 row=jrow, col=icol, BLOCK=pblock, found=found)
    2809              :          IF (.NOT. found) CPABORT("pblock not found")
    2810              :          IF (nspin > 1) THEN
    2811              :             CALL dbcsr_get_block_p(matrix=matrix_p(2, ic)%matrix, &
    2812              :                                    row=jrow, col=icol, BLOCK=pblock_beta, found=found)
    2813              :             IF (.NOT. found) CPABORT("pblock beta not found")
    2814              :          END IF
    2815              :          IF (use_matrix_scc_stress) THEN
    2816              :             natorb_a = SIZE(pblock, 2)
    2817              :             natorb_b = SIZE(pblock, 1)
    2818              :             scc_strain_hint(1:natorb_a, 1:natorb_b, :, :, :) = 0.0_dp
    2819              :             DO ispin = 1, nspin
    2820              :                DO jdim = 1, 3
    2821              :                   DO idim = 1, 3
    2822              :                      NULLIFY (scc_strain_blocks(idim, jdim, ispin)%block)
    2823              :                      i = idim + 3*(jdim - 1) + 9*(ispin - 1)
    2824              :                      CALL dbcsr_get_block_p(matrix=matrix_dh_scc(i, ic)%matrix, &
    2825              :                                             row=jrow, col=icol, &
    2826              :                                             BLOCK=scc_strain_blocks(idim, jdim, ispin)%block, found=found)
    2827              :                      IF (.NOT. found) CPABORT("SCC strain derivative block not found")
    2828              :                   END DO
    2829              :                END DO
    2830              :             END DO
    2831              :          END IF
    2832              :          i_a_shift = tb%pot%vat(icol, 1)
    2833              :          j_a_shift = tb%pot%vat(jrow, 1)
    2834              :          i_a_shift_mag = 0.0_dp
    2835              :          j_a_shift_mag = 0.0_dp
    2836              :          IF (SIZE(tb%pot%vat, 2) > 1) THEN
    2837              :             i_a_shift_mag = tb%pot%vat(icol, 2)
    2838              :             j_a_shift_mag = tb%pot%vat(jrow, 2)
    2839              :          END IF
    2840              :          idip(:) = tb%pot%vdp(:, icol, 1)
    2841              :          jdip(:) = tb%pot%vdp(:, jrow, 1)
    2842              :          idip_mag(:) = 0.0_dp
    2843              :          jdip_mag(:) = 0.0_dp
    2844              :          IF (SIZE(tb%pot%vdp, 3) > 1) THEN
    2845              :             idip_mag(:) = tb%pot%vdp(:, icol, 2)
    2846              :             jdip_mag(:) = tb%pot%vdp(:, jrow, 2)
    2847              :          END IF
    2848              :          iquad(:) = tb%pot%vqp(:, icol, 1)
    2849              :          jquad(:) = tb%pot%vqp(:, jrow, 1)
    2850              :          iquad_mag(:) = 0.0_dp
    2851              :          jquad_mag(:) = 0.0_dp
    2852              :          IF (SIZE(tb%pot%vqp, 3) > 1) THEN
    2853              :             iquad_mag(:) = tb%pot%vqp(:, icol, 2)
    2854              :             jquad_mag(:) = tb%pot%vqp(:, jrow, 2)
    2855              :          END IF
    2856              :          ni = tb%calc%bas%ish_at(icol)
    2857              :          DO iset = 1, nseti
    2858              :             ishift = i_a_shift + tb%pot%vsh(ni + iset, 1)
    2859              :             ishift_mag = 0.0_dp
    2860              :             IF (SIZE(tb%pot%vsh, 2) > 1) ishift_mag = i_a_shift_mag + tb%pot%vsh(ni + iset, 2)
    2861              :             nj = tb%calc%bas%ish_at(jrow)
    2862              :             DO jset = 1, nsetj
    2863              :                jshift = j_a_shift + tb%pot%vsh(nj + jset, 1)
    2864              :                jshift_mag = 0.0_dp
    2865              :                IF (SIZE(tb%pot%vsh, 2) > 1) jshift_mag = j_a_shift_mag + tb%pot%vsh(nj + jset, 2)
    2866              : 
    2867              :                !get integrals and derivatives
    2868              :                IF (has_multipole_response) THEN
    2869              :                   CALL multipole_grad_cgto(tb%calc%bas%cgto(iset, ityp), tb%calc%bas%cgto(jset, jtyp), &
    2870              :                      & r2, rij, tb%calc%bas%intcut, t_ov, t_dip, t_quad, t_d_ov, t_i_dip, t_i_quad, &
    2871              :                      & t_j_dip, t_j_quad)
    2872              :                ELSE
    2873              :                   CALL overlap_grad_cgto(tb%calc%bas%cgto(iset, ityp), tb%calc%bas%cgto(jset, jtyp), &
    2874              :                                          r2, rij, tb%calc%bas%intcut, t_ov, t_d_ov)
    2875              :                END IF
    2876              : 
    2877              :                dgrad = 0.0_dp
    2878              :                DO inda = 1, nsgfa(iset)
    2879              :                   ia = first_sgfa(1, iset) - first_sgfa(1, 1) + inda
    2880              :                   DO indb = 1, nsgfb(jset)
    2881              :                      ib = first_sgfb(1, jset) - first_sgfb(1, 1) + indb
    2882              : 
    2883              :                      ij = inda + nsgfa(iset)*(indb - 1)
    2884              : 
    2885              :                      pij_charge = pblock(ib, ia)
    2886              :                      pij_magnet = 0.0_dp
    2887              :                      IF (nspin > 1) THEN
    2888              :                         pij_charge = pij_charge + pblock_beta(ib, ia)
    2889              :                         pij_magnet = pblock(ib, ia) - pblock_beta(ib, ia)
    2890              :                      END IF
    2891              :                      mpgrad_charge = 0.0_dp
    2892              :                      mpgrad_magnet = 0.0_dp
    2893              :                      IF (has_multipole_response) THEN
    2894              :                         mpgrad_charge = MATMUL(t_i_dip(:, :, ij), idip) &
    2895              :                                         + MATMUL(t_j_dip(:, :, ij), jdip) &
    2896              :                                         + MATMUL(t_i_quad(:, :, ij), iquad) &
    2897              :                                         + MATMUL(t_j_quad(:, :, ij), jquad)
    2898              :                         IF (nspin > 1) THEN
    2899              :                            mpgrad_magnet = MATMUL(t_i_dip(:, :, ij), idip_mag) &
    2900              :                                            + MATMUL(t_j_dip(:, :, ij), jdip_mag) &
    2901              :                                            + MATMUL(t_i_quad(:, :, ij), iquad_mag) &
    2902              :                                            + MATMUL(t_j_quad(:, :, ij), jquad_mag)
    2903              :                         END IF
    2904              :                      END IF
    2905              :                      dhgrad_charge = -(ishift + jshift)*t_d_ov(:, ij) - mp_pair_scale*mpgrad_charge
    2906              :                      dhgrad_magnet = -(ishift_mag + jshift_mag)*t_d_ov(:, ij) - mp_pair_scale*mpgrad_magnet
    2907              :                      dgrad(:) = dgrad(:) - &
    2908              :                                 ((ishift + jshift)*pij_charge + &
    2909              :                                  (ishift_mag + jshift_mag)*pij_magnet)*t_d_ov(:, ij) - &
    2910              :                                 mp_pair_scale*(pij_charge*mpgrad_charge + pij_magnet*mpgrad_magnet)
    2911              : 
    2912              :                      IF (use_matrix_scc_stress) THEN
    2913              :                         DO jdim = 1, 3
    2914              :                            DO idim = 1, 3
    2915              :                               scc_strain_hint(ia, ib, idim, jdim, 1) = &
    2916              :                                  scc_strain_hint(ia, ib, idim, jdim, 1) &
    2917              :                                  + (dhgrad_charge(idim) + MERGE(dhgrad_magnet(idim), 0.0_dp, nspin > 1))*rij(jdim)
    2918              :                               IF (nspin > 1) THEN
    2919              :                                  scc_strain_hint(ia, ib, idim, jdim, 2) = &
    2920              :                                     scc_strain_hint(ia, ib, idim, jdim, 2) &
    2921              :                                     + (dhgrad_charge(idim) - dhgrad_magnet(idim))*rij(jdim)
    2922              :                               END IF
    2923              :                            END DO
    2924              :                         END DO
    2925              :                      END IF
    2926              : 
    2927              :                   END DO
    2928              :                END DO
    2929              :                local_grad(:, icol) = local_grad(:, icol) - dgrad
    2930              :                local_grad(:, jrow) = local_grad(:, jrow) + dgrad
    2931              :                IF (tb%use_virial .AND. .NOT. use_matrix_scc_stress) THEN
    2932              :                   IF (icol == jrow) THEN
    2933              :                      DO ia = 1, 3
    2934              :                         DO ib = 1, 3
    2935              :                            IF (sampled_image_pair .AND. .NOT. gamma_sampled_image_pair) THEN
    2936              :                               hsigma(ia, ib) = hsigma(ia, ib) - 0.25_dp* &
    2937              :                                                (rij(ia)*dgrad(ib) + rij(ib)*dgrad(ia))
    2938              :                            ELSE
    2939              :                               hsigma(ia, ib) = hsigma(ia, ib) + 0.25_dp* &
    2940              :                                                (rij(ia)*dgrad(ib) + rij(ib)*dgrad(ia))
    2941              :                            END IF
    2942              :                         END DO
    2943              :                      END DO
    2944              :                   ELSE
    2945              :                      DO ia = 1, 3
    2946              :                         DO ib = 1, 3
    2947              :                            hsigma(ia, ib) = hsigma(ia, ib) + 0.50_dp*(rij(ia)*dgrad(ib) + rij(ib)*dgrad(ia))
    2948              :                         END DO
    2949              :                      END DO
    2950              :                   END IF
    2951              :                END IF
    2952              :             END DO
    2953              :          END DO
    2954              :          IF (use_matrix_scc_stress) THEN
    2955              : !$          pair_index = INT(jrow - 1, int_8)*INT(tb%mol%nat, int_8) + INT(icol, int_8)
    2956              : !$          hash = INT(MOD(pair_index, INT(nlock, int_8))) + 1
    2957              : !$          CALL omp_set_lock(locks(hash))
    2958              :             DO ispin = 1, nspin
    2959              :                DO jdim = 1, 3
    2960              :                   DO idim = 1, 3
    2961              :                      IF (icol <= jrow) THEN
    2962              :                         scc_strain_blocks(idim, jdim, ispin)%block(:, :) = &
    2963              :                            scc_strain_blocks(idim, jdim, ispin)%block(:, :) &
    2964              :                            + scc_strain_hint(1:natorb_a, 1:natorb_b, idim, jdim, ispin)
    2965              :                      ELSE
    2966              :                         scc_strain_blocks(idim, jdim, ispin)%block(:, :) = &
    2967              :                            scc_strain_blocks(idim, jdim, ispin)%block(:, :) &
    2968              :                            + TRANSPOSE(scc_strain_hint(1:natorb_a, 1:natorb_b, idim, jdim, ispin))
    2969              :                      END IF
    2970              :                   END DO
    2971              :                END DO
    2972              :             END DO
    2973              : !$          CALL omp_unset_lock(locks(hash))
    2974              :          END IF
    2975              :       END DO
    2976              : !$OMP END DO
    2977              : !$OMP CRITICAL(tblite_scc_gradient)
    2978              :       tb%grad(:, :) = tb%grad(:, :) + local_grad(:, :)
    2979              : !$OMP END CRITICAL(tblite_scc_gradient)
    2980              :       DEALLOCATE (local_grad, t_ov, t_d_ov, t_dip, t_quad, t_i_dip, t_j_dip, t_i_quad, t_j_quad)
    2981              :       IF (ALLOCATED(scc_strain_hint)) DEALLOCATE (scc_strain_hint)
    2982              : !$OMP END PARALLEL
    2983        77308 : !$    DO lock_num = 1, nlock
    2984        77308 : !$       CALL omp_destroy_lock(locks(lock_num))
    2985              : !$    END DO
    2986          154 : !$    DEALLOCATE (locks)
    2987              : 
    2988          154 :       IF (use_matrix_scc_stress) THEN
    2989           50 :          hsigma = 0.0_dp
    2990         3994 :          DO img = 1, nimg
    2991         7994 :             DO ispin = 1, nspin
    2992        19944 :                DO jdim = 1, 3
    2993        52000 :                   DO idim = 1, 3
    2994        36000 :                      i = idim + 3*(jdim - 1) + 9*(ispin - 1)
    2995        36000 :                      CALL dbcsr_finalize(matrix_dh_scc(i, img)%matrix)
    2996        36000 :                      CALL dbcsr_dot(matrix_dh_scc(i, img)%matrix, matrix_p(ispin, img)%matrix, native_dot_tmp)
    2997              :                      ! Symmetric DBCSR storage represents both orientations of each assembled pair.
    2998        48000 :                      hsigma(idim, jdim) = hsigma(idim, jdim) + 0.5_dp*native_dot_tmp
    2999              :                   END DO
    3000              :                END DO
    3001              :             END DO
    3002              :          END DO
    3003           50 :          CALL dbcsr_deallocate_matrix_set(matrix_dh_scc)
    3004              :       ELSE
    3005          104 :          CALL para_env%sum(hsigma)
    3006              :       END IF
    3007          154 :       CALL para_env%sum(tb%grad)
    3008          154 :       CALL tb_grad2force(qs_env, tb, para_env, 4, replicated=.TRUE.)
    3009              : 
    3010          154 :       DEALLOCATE (basis_set_list)
    3011              : 
    3012          154 :       IF (tb%use_virial) THEN
    3013           86 :          CALL tb_add_stress(qs_env, tb)
    3014           86 :          CALL get_qs_env(qs_env=qs_env, virial=virial)
    3015              :          ! Both the DBCSR contraction and the explicit sum above return a complete tensor.
    3016         1118 :          virial%pv_virial = virial%pv_virial - hsigma/para_env%num_pe
    3017              :       END IF
    3018              : 
    3019              : #else
    3020              :       MARK_USED(qs_env)
    3021              :       MARK_USED(use_rho)
    3022              :       MARK_USED(nimg)
    3023              :       CPABORT("Built without TBLITE")
    3024              : #endif
    3025              : 
    3026          462 :    END SUBROUTINE tb_derive_dH_off
    3027              : 
    3028              : ! **************************************************************************************************
    3029              : !> \brief Add the local container virial before CP2K's global reduction.
    3030              : !> \param qs_env ...
    3031              : !> \param tb ...
    3032              : ! **************************************************************************************************
    3033           86 :    SUBROUTINE tb_add_stress(qs_env, tb)
    3034              : 
    3035              :       TYPE(qs_environment_type)                          :: qs_env
    3036              :       TYPE(tblite_type)                                  :: tb
    3037              : 
    3038              :       INTEGER, DIMENSION(3)                              :: periodic
    3039              :       TYPE(cell_type), POINTER                           :: cell
    3040              :       TYPE(virial_type), POINTER                         :: virial
    3041              : 
    3042           86 :       NULLIFY (virial, cell)
    3043           86 :       CALL get_qs_env(qs_env=qs_env, virial=virial, cell=cell)
    3044           86 :       CALL get_cell(cell=cell, periodic=periodic)
    3045              : 
    3046          108 :       IF (ALL(periodic == 0)) THEN
    3047              :          CALL cp_warn(__LOCATION__, &
    3048              :                       "tblite stress tensor requested for an isolated system. "// &
    3049              :                       "The reported virial is useful for finite-difference checks, "// &
    3050            4 :                       "but it is not a physically meaningful bulk stress for an isolated molecule.")
    3051              :       END IF
    3052              : 
    3053         1118 :       virial%pv_virial = virial%pv_virial - tb%sigma
    3054              : 
    3055           86 :    END SUBROUTINE tb_add_stress
    3056              : 
    3057              : ! **************************************************************************************************
    3058              : !> \brief add contrib. to gradient
    3059              : !> \param grad ...
    3060              : !> \param deriv ...
    3061              : !> \param dE ...
    3062              : !> \param natom ...
    3063              : ! **************************************************************************************************
    3064          154 :    SUBROUTINE tb_add_grad(grad, deriv, dE, natom)
    3065              : 
    3066              :       REAL(KIND=dp), DIMENSION(:, :)                     :: grad
    3067              :       REAL(KIND=dp), DIMENSION(:, :, :)                  :: deriv
    3068              :       REAL(KIND=dp), DIMENSION(:)                        :: dE
    3069              :       INTEGER                                            :: natom
    3070              : 
    3071              :       INTEGER                                            :: i, j
    3072              : 
    3073         1054 :       DO i = 1, natom
    3074         9990 :          DO j = 1, natom
    3075        36644 :             grad(:, i) = grad(:, i) + deriv(:, i, j)*dE(j)
    3076              :          END DO
    3077              :       END DO
    3078              : 
    3079          154 :    END SUBROUTINE tb_add_grad
    3080              : 
    3081              : END MODULE tblite_interface
        

Generated by: LCOV version 2.0-1