LCOV - code coverage report
Current view: top level - src - qs_vxc_atom.F (source / functions) Coverage Total Hit
Test: CP2K Regtests (git:1be8651) Lines: 89.6 % 1684 1509
Test Date: 2026-11-24 01:22:08 Functions: 100.0 % 21 21

            Line data    Source code
       1              : !--------------------------------------------------------------------------------------------------!
       2              : !   CP2K: A general program to perform molecular dynamics simulations                              !
       3              : !   Copyright 2000-2026 CP2K developers group <https://cp2k.org>                                   !
       4              : !                                                                                                  !
       5              : !   SPDX-License-Identifier: GPL-2.0-or-later                                                      !
       6              : !--------------------------------------------------------------------------------------------------!
       7              : 
       8              : ! **************************************************************************************************
       9              : !> \brief routines that build the integrals of the Vxc potential calculated
      10              : !>      for the atomic density in the basis set of spherical primitives
      11              : ! **************************************************************************************************
      12              : MODULE qs_vxc_atom
      13              :    USE atomic_kind_types,               ONLY: atomic_kind_type,&
      14              :                                               get_atomic_kind
      15              :    USE basis_set_types,                 ONLY: gto_basis_set_type
      16              :    USE cell_types,                      ONLY: cell_type
      17              :    USE cp_array_utils,                  ONLY: cp_3d_r_cp_type
      18              :    USE cp_control_types,                ONLY: dft_control_type
      19              :    USE cp_log_handling,                 ONLY: cp_logger_get_default_io_unit
      20              :    USE external_potential_types,        ONLY: gth_potential_type,&
      21              :                                               sgp_potential_type
      22              :    USE input_constants,                 ONLY: cdft_alpha_constraint,&
      23              :                                               cdft_beta_constraint,&
      24              :                                               cdft_charge_constraint,&
      25              :                                               cdft_magnetization_constraint,&
      26              :                                               xc_none
      27              :    USE input_section_types,             ONLY: section_get_rval,&
      28              :                                               section_vals_get_subs_vals,&
      29              :                                               section_vals_type,&
      30              :                                               section_vals_val_get
      31              :    USE kinds,                           ONLY: dp,&
      32              :                                               int_8
      33              :    USE lebedev,                         ONLY: deallocate_lebedev_grids,&
      34              :                                               get_number_of_lebedev_grid,&
      35              :                                               init_lebedev_grids,&
      36              :                                               lebedev_grid
      37              :    USE memory_utilities,                ONLY: reallocate
      38              :    USE message_passing,                 ONLY: mp_para_env_type
      39              :    USE orbital_pointers,                ONLY: indco,&
      40              :                                               indso,&
      41              :                                               nco,&
      42              :                                               ncoset,&
      43              :                                               nsoset
      44              :    USE orbital_transformation_matrices, ONLY: orbtramat
      45              :    USE particle_types,                  ONLY: particle_type
      46              :    USE pw_env_types,                    ONLY: pw_env_get,&
      47              :                                               pw_env_type
      48              :    USE pw_grid_types,                   ONLY: pw_grid_type
      49              :    USE pw_methods,                      ONLY: pw_axpy
      50              :    USE pw_pool_types,                   ONLY: pw_pool_type
      51              :    USE pw_types,                        ONLY: pw_c1d_gs_type,&
      52              :                                               pw_r3d_rs_type
      53              :    USE qs_cdft_grid,                    ONLY: cdft_point_context_create,&
      54              :                                               cdft_point_context_release,&
      55              :                                               cdft_point_context_type,&
      56              :                                               cdft_point_weights
      57              :    USE qs_cdft_types,                   ONLY: cdft_control_type
      58              :    USE qs_environment_types,            ONLY: get_qs_env,&
      59              :                                               qs_environment_type
      60              :    USE qs_force_types,                  ONLY: qs_force_type
      61              :    USE qs_grid_atom,                    ONLY: allocate_grid_atom,&
      62              :                                               create_grid_atom,&
      63              :                                               grid_atom_type
      64              :    USE qs_harmonics_atom,               ONLY: harmonics_atom_type
      65              :    USE qs_kind_types,                   ONLY: get_qs_kind,&
      66              :                                               has_nlcc,&
      67              :                                               qs_kind_type
      68              :    USE qs_linres_types,                 ONLY: nablavks_atom_type
      69              :    USE qs_native_grid_cache,            ONLY: fetch_native_grid_stencil,&
      70              :                                               native_grid_interp_npts,&
      71              :                                               native_grid_interp_offset_max,&
      72              :                                               native_grid_interp_offset_min,&
      73              :                                               native_grid_interpolation_stencil_type,&
      74              :                                               prepare_native_grid_cache,&
      75              :                                               store_native_grid_stencil
      76              :    USE qs_rho_atom_methods,             ONLY: replicate_rho_atom_radial
      77              :    USE qs_rho_atom_types,               ONLY: get_rho_atom,&
      78              :                                               rho_atom_coeff,&
      79              :                                               rho_atom_type
      80              :    USE qs_rho_types,                    ONLY: qs_rho_get,&
      81              :                                               qs_rho_type
      82              :    USE qs_vxc_atom_utils,               ONLY: &
      83              :         calc_rho_angular, calc_rho_nlcc, calc_tau_atom, calc_weight_function, &
      84              :         create_tau_basis_cache, dgaVtaudgb, evaluate_nlcc_primitive_fields, gaVxcgb_GC, &
      85              :         gaVxcgb_noGC, gapw_atom_grid_support_radius, release_tau_basis_cache, tau_basis_cache_type
      86              :    USE skala_gpw_features,              ONLY: build_periodic_atom_image_layout,&
      87              :                                               periodic_atom_image_partition_from_layout,&
      88              :                                               skala_gpw_smooth_partition_derivatives,&
      89              :                                               skala_periodic_partition_type,&
      90              :                                               smooth_atom_partition
      91              :    USE skala_gpw_functional,            ONLY: &
      92              :         build_vxc_from_feature_grads, get_gauxc_section, get_skala_native_section, &
      93              :         native_skala_gapw_density_partition, skala_gapw_atom_composite_energy, &
      94              :         skala_gapw_atom_vxc_of_r, skala_gapw_density_partition_hard_minus_soft, &
      95              :         skala_gapw_density_partition_hard_only, skala_gapw_density_partition_none, &
      96              :         skala_gapw_density_partition_soft_only, xc_section_uses_gauxc_model, &
      97              :         xc_section_uses_native_skala_evaluator
      98              :    USE spherical_harmonics,             ONLY: y_lm
      99              :    USE util,                            ONLY: get_limit
     100              :    USE virial_types,                    ONLY: virial_type
     101              :    USE xc_atom,                         ONLY: fill_rho_set,&
     102              :                                               vxc_of_r_epr,&
     103              :                                               vxc_of_r_new,&
     104              :                                               xc_rho_set_atom_update
     105              :    USE xc_derivative_set_types,         ONLY: xc_derivative_set_type,&
     106              :                                               xc_dset_create,&
     107              :                                               xc_dset_release,&
     108              :                                               xc_dset_zero_all
     109              :    USE xc_derivatives,                  ONLY: xc_functionals_get_needs
     110              :    USE xc_input_constants,              ONLY: skala_gapw_cp2k_default,&
     111              :                                               skala_gapw_direct_valence,&
     112              :                                               skala_gapw_paw_one_center,&
     113              :                                               skala_gapw_paw_one_center_split
     114              :    USE xc_rho_cflags_types,             ONLY: xc_rho_cflags_type
     115              :    USE xc_rho_set_types,                ONLY: xc_rho_set_create,&
     116              :                                               xc_rho_set_get,&
     117              :                                               xc_rho_set_release,&
     118              :                                               xc_rho_set_type,&
     119              :                                               xc_rho_set_update
     120              : #include "./base/base_uses.f90"
     121              : 
     122              :    IMPLICIT NONE
     123              : 
     124              :    PRIVATE
     125              : 
     126              :    CHARACTER(len=*), PARAMETER, PRIVATE :: moduleN = 'qs_vxc_atom'
     127              : 
     128              :    ! A wrapped stencil can touch both end tiles and one adjacent interior tile when the final
     129              :    ! tile is shorter than the stencil. Three tiles per direction are therefore sufficient.
     130              :    INTEGER, PARAMETER, PRIVATE :: native_grid_adjoint_tile_edge = 64, &
     131              :                                   native_grid_adjoint_max_tiles_per_direction = 3, &
     132              :                                   native_grid_adjoint_max_bins_per_row = &
     133              :                                   native_grid_adjoint_max_tiles_per_direction**3
     134              : 
     135              :    PUBLIC :: add_gapw_atom_grid_interpolation_adjoint, &
     136              :              atom_grid_image_bounds, &
     137              :              interpolate_gapw_atom_grid_fields, &
     138              :              calculate_vxc_atom, &
     139              :              calculate_vxc_atom_epr, &
     140              :              gapw_cdft_one_center
     141              : 
     142              : ! **************************************************************************************************
     143              : 
     144              : CONTAINS
     145              : 
     146              : ! **************************************************************************************************
     147              : !> \brief Initialize atom-centered quadrature for native Skala layouts.
     148              : !> \param kind_set quantum kinds
     149              : !> \param dft_control DFT controls supplying the radial quadrature
     150              : ! **************************************************************************************************
     151          254 :    SUBROUTINE ensure_native_skala_atom_grids(kind_set, dft_control)
     152              :       TYPE(qs_kind_type), DIMENSION(:), POINTER          :: kind_set
     153              :       TYPE(dft_control_type), POINTER                    :: dft_control
     154              : 
     155              :       INTEGER                                            :: ikind, ll, na, nr, quadrature
     156              :       TYPE(grid_atom_type), POINTER                      :: grid_atom
     157              : 
     158          254 :       quadrature = dft_control%qs_control%gapw_control%quadrature
     159          254 :       CALL init_lebedev_grids()
     160          554 :       DO ikind = 1, SIZE(kind_set)
     161          300 :          NULLIFY (grid_atom)
     162          300 :          CALL get_qs_kind(kind_set(ikind), grid_atom=grid_atom, ngrid_ang=na, ngrid_rad=nr)
     163          300 :          IF (ASSOCIATED(grid_atom)) THEN
     164          280 :             IF (ASSOCIATED(grid_atom%weight) .AND. grid_atom%nr == nr) CYCLE
     165              :          ELSE
     166           20 :             CALL allocate_grid_atom(kind_set(ikind)%grid_atom)
     167           20 :             grid_atom => kind_set(ikind)%grid_atom
     168              :          END IF
     169           20 :          ll = get_number_of_lebedev_grid(n=na)
     170           20 :          na = lebedev_grid(ll)%n
     171           20 :          grid_atom%ng_sphere = na
     172           20 :          grid_atom%nr = nr
     173          574 :          CALL create_grid_atom(grid_atom, nr, na, 0, ll, quadrature)
     174              :       END DO
     175          254 :       CALL deallocate_lebedev_grids()
     176              : 
     177          254 :    END SUBROUTINE ensure_native_skala_atom_grids
     178              : 
     179              : ! **************************************************************************************************
     180              : !> \brief Decide whether a kind contributes hard-minus-soft primitive fields.
     181              : !> \param paw_atom whether CP2K constructed a one-center representation for the kind
     182              : !> \param gapw_representation requested Skala pseudopotential GAPW representation
     183              : !> \param has_pseudopotential whether the kind uses a GTH or semi-global pseudopotential
     184              : !> \param zeff valence charge of the potential
     185              : !> \param zatom atomic number
     186              : !> \return true when hard-minus-soft fields contribute for this kind
     187              : ! **************************************************************************************************
     188          564 :    PURE FUNCTION native_skala_uses_one_center_kind( &
     189              :       paw_atom, gapw_representation, has_pseudopotential, zeff, zatom) RESULT(use_one_center)
     190              :       LOGICAL, INTENT(IN)                                :: paw_atom
     191              :       INTEGER, INTENT(IN)                                :: gapw_representation
     192              :       LOGICAL, INTENT(IN)                                :: has_pseudopotential
     193              :       REAL(dp), INTENT(IN)                               :: zeff
     194              :       INTEGER, INTENT(IN)                                :: zatom
     195              :       LOGICAL                                            :: use_one_center
     196              : 
     197          564 :       use_one_center = paw_atom
     198          564 :       IF (.NOT. use_one_center) RETURN
     199              : 
     200          620 :       SELECT CASE (gapw_representation)
     201              :       CASE (skala_gapw_direct_valence)
     202           70 :          use_one_center = .NOT. has_pseudopotential
     203              :       CASE (skala_gapw_paw_one_center, skala_gapw_paw_one_center_split)
     204           16 :          CONTINUE
     205              :       CASE (skala_gapw_cp2k_default)
     206           16 :          IF (has_pseudopotential .AND. &
     207          566 :              ABS(zeff - REAL(zatom, dp)) <= 1.0E-10_dp) use_one_center = .FALSE.
     208              :       END SELECT
     209              : 
     210              :    END FUNCTION native_skala_uses_one_center_kind
     211              : 
     212              : ! **************************************************************************************************
     213              : !> \brief ...
     214              : !> \param qs_env ...
     215              : !> \param energy_only ...
     216              : !> \param exc1 the on-body ex energy contribution
     217              : !> \param adiabatic_rescale_factor ...
     218              : !> \param kind_set_external provides a non-default kind_set to use
     219              : !> \param rho_atom_set_external provides a non-default atomic density set to use
     220              : !> \param xc_section_external provides an external non-default XC
     221              : !> \param calculate_forces ...
     222              : !> \param composite_vxc_rho ...
     223              : !> \param composite_vxc_tau ...
     224              : !> \param composite_reference_active ...
     225              : !> \param direct_valence_atom_grid evaluate the smooth valence fields on atom-centered grids
     226              : !> \param atom_composite_grid evaluate GAPW primitive fields on atom-centered composite grids
     227              : ! **************************************************************************************************
     228        35460 :    SUBROUTINE calculate_vxc_atom(qs_env, energy_only, exc1, &
     229              :                                  adiabatic_rescale_factor, kind_set_external, &
     230              :                                  rho_atom_set_external, xc_section_external, calculate_forces, &
     231              :                                  composite_vxc_rho, composite_vxc_tau, composite_reference_active, &
     232              :                                  direct_valence_atom_grid, atom_composite_grid)
     233              : 
     234              :       TYPE(qs_environment_type), POINTER                 :: qs_env
     235              :       LOGICAL, INTENT(IN)                                :: energy_only
     236              :       REAL(dp), INTENT(INOUT)                            :: exc1
     237              :       REAL(dp), INTENT(IN), OPTIONAL                     :: adiabatic_rescale_factor
     238              :       TYPE(qs_kind_type), DIMENSION(:), OPTIONAL, &
     239              :          POINTER                                         :: kind_set_external
     240              :       TYPE(rho_atom_type), DIMENSION(:), OPTIONAL, &
     241              :          POINTER                                         :: rho_atom_set_external
     242              :       TYPE(section_vals_type), OPTIONAL, POINTER         :: xc_section_external
     243              :       LOGICAL, INTENT(IN), OPTIONAL                      :: calculate_forces
     244              :       TYPE(pw_r3d_rs_type), DIMENSION(:), OPTIONAL, &
     245              :          POINTER                                         :: composite_vxc_rho, composite_vxc_tau
     246              :       LOGICAL, INTENT(OUT), OPTIONAL                     :: composite_reference_active
     247              :       LOGICAL, INTENT(IN), OPTIONAL                      :: direct_valence_atom_grid, &
     248              :                                                             atom_composite_grid
     249              : 
     250              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'calculate_vxc_atom'
     251              : 
     252              :       INTEGER :: adjoint_bin, adjoint_entry, adjoint_nbins, adjoint_nchannels, &
     253              :          adjoint_tile_count(3), adjoint_tile_lower(3), adjoint_tile_upper(3), &
     254              :          atom_composite_components, bo(2), composite_image_periodicity(3), composite_local_atom, &
     255              :          composite_local_natom, composite_nflat, composite_partition_target_image, &
     256              :          composite_pw_nflat, composite_row, gapw_density_partition, gapw_representation, handle, &
     257              :          ia, iat, iatom, icomponent, idir, ikind, image_i1, image_i2, image_i3, image_lower(3), &
     258              :          image_shell(3), image_shift(3), image_upper(3), ir, ispin, iw, jdir, myfun, na, natom, &
     259              :          nr, nspins, num_pe, on
     260              :       INTEGER :: source_atom, target_atom, xc_deriv_method_id, xc_rho_smooth_id, zatom
     261        35460 :       INTEGER(KIND=int_8), ALLOCATABLE, DIMENSION(:)     :: composite_atomic_grid_sizes, &
     262        35460 :                                                             composite_local_grid_sizes
     263        35460 :       INTEGER, ALLOCATABLE, DIMENSION(:) :: adjoint_bin_offsets, adjoint_bin_rows, &
     264        35460 :          composite_atom_end, composite_atom_kind, composite_atom_kind_index, composite_atom_start, &
     265        35460 :          composite_grid_atom, composite_local_atoms
     266              :       INTEGER, DIMENSION(2, 3)                           :: bounds
     267        35460 :       INTEGER, DIMENSION(:), POINTER                     :: atom_list
     268              :       LOGICAL :: accint, atom_composite_active, atom_composite_diagnostic, &
     269              :          atom_composite_reference, direct_valence_atom_composite, donlcc, evaluate_hard, &
     270              :          evaluate_soft, gradient_f, image_partition_atom_composite, lsd, my_calculate_forces, &
     271              :          native_grid_diagnostics, nlcc, one_center_kind, paw_atom, paw_pseudopotentials, &
     272              :          requested_atom_composite_grid, rho_g_valid, skala_atom_grid, source_matrix_local, tau_f, &
     273              :          tau_r_valid, use_atom_composite_density, use_atom_composite_gradient, &
     274              :          use_atom_composite_tau, use_virial
     275        35460 :       LOGICAL, ALLOCATABLE, DIMENSION(:)                 :: composite_partition_included
     276              :       REAL(dp) :: agr, alpha, atom_composite_exc, atom_composite_nelec, &
     277              :          composite_cross_cutoff_max, composite_cross_density_max, composite_cross_grad_max, &
     278              :          composite_cross_kin_max, composite_density_max, composite_density_min, &
     279              :          composite_grad_max, composite_kin_max, composite_kin_min, composite_tau_integral, &
     280              :          cross_cutoff, density_cut, exc_h, exc_s, feature_vxc_analytic, feature_vxc_fd, &
     281              :          feature_vxc_minus, feature_vxc_plus, feature_vxc_step, gradient_cut, &
     282              :          local_partition_weight, my_adiabatic_rescale_factor, nlcc_density, nlcc_spin_factor, &
     283              :          one_center_density_field_contraction
     284              :       REAL(dp) :: one_center_density_matrix_contraction, one_center_field_contraction, &
     285              :          one_center_gradient_field_contraction, one_center_gradient_matrix_contraction, &
     286              :          one_center_matrix_contraction, one_center_rho_grad_field_contraction, &
     287              :          one_center_rho_grad_matrix_contraction, one_center_tau_field_contraction, &
     288              :          one_center_tau_matrix_contraction, one_center_tensor_contraction, partition_adjoint, &
     289              :          partition_weight, smooth_grid_contraction, smooth_input_contraction, &
     290              :          target_partition_adjoint, tau_cut, zeff
     291        35460 :       REAL(dp), ALLOCATABLE, DIMENSION(:) :: composite_atomic_grid_weight_grad, &
     292        35460 :          composite_atomic_grid_weights, composite_base_grid_weights, composite_distances, &
     293       106380 :          composite_grid_weight_grad, composite_grid_weights, composite_partition_weights, fw
     294        35460 :       REAL(dp), ALLOCATABLE, DIMENSION(:, :) :: composite_atom_coord_grad, composite_atom_coords, &
     295        35460 :          composite_cross_density, composite_cross_force, composite_cross_force_local, &
     296        35460 :          composite_cross_kin, composite_density, composite_density_grad, composite_explicit_force, &
     297        35460 :          composite_grid_coord_force, composite_grid_coord_grad, composite_grid_coords, &
     298        35460 :          composite_kin, composite_kin_grad, composite_local_atom_coords, &
     299        35460 :          composite_model_atom_force, composite_moving_smooth_force, composite_nlcc_center_force, &
     300        35460 :          composite_nlcc_center_force_local, composite_nlcc_target_force, &
     301        35460 :          composite_partition_atom_coords
     302        35460 :       REAL(dp), ALLOCATABLE, DIMENSION(:, :) :: composite_partition_force, &
     303        70920 :          composite_partition_force_local, composite_smooth_density_cache, &
     304        70920 :          composite_smooth_kin_cache, local_partition_datom
     305        35460 :       REAL(dp), ALLOCATABLE, DIMENSION(:, :), TARGET     :: smooth_density_adjoint_storage, &
     306        35460 :                                                             smooth_kin_adjoint_storage
     307        35460 :       REAL(dp), ALLOCATABLE, DIMENSION(:, :, :) :: composite_cross_grad, composite_grad, &
     308        35460 :          composite_grad_grad, composite_int_h, composite_int_s, composite_partition_datom, &
     309       106380 :          composite_partition_dstrain, composite_smooth_gradient_cache, vtau_h_local, vtau_s_local, &
     310        35460 :          vxc_h_local, vxc_s_local
     311        35460 :       REAL(dp), ALLOCATABLE, DIMENSION(:, :, :), TARGET  :: smooth_grad_adjoint_storage
     312        35460 :       REAL(dp), ALLOCATABLE, DIMENSION(:, :, :, :)       :: vxg_h_local, vxg_s_local
     313              :       REAL(dp), DIMENSION(1, 1, 1)                       :: tau_d
     314              :       REAL(dp), DIMENSION(1, 1, 1, 1)                    :: rho_d
     315              :       REAL(dp), DIMENSION(2) :: composite_smooth_density_adjoint_value, &
     316              :          composite_smooth_density_value, composite_smooth_kin_adjoint_value, &
     317              :          composite_smooth_kin_value, cross_density, cross_density_adjoint, cross_kin, &
     318              :          cross_kin_adjoint
     319              :       REAL(dp), DIMENSION(3) :: composite_point, cross_displacement, cross_spatial_derivative, &
     320              :          fractional, image_translation, nlcc_gradient, nlcc_spatial_derivative, &
     321              :          skala_atom_force_h, skala_atom_force_s, spatial_derivative
     322              :       REAL(dp), DIMENSION(3, 2) :: composite_smooth_gradient_adjoint_value, &
     323              :          composite_smooth_gradient_value, cross_density_spatial, cross_grad, cross_grad_adjoint, &
     324              :          cross_kin_spatial
     325              :       REAL(dp), DIMENSION(3, 3) :: composite_cross_image_virial, &
     326              :          composite_cross_image_virial_local, composite_explicit_virial, composite_feature_virial, &
     327              :          composite_interpolation_virial, composite_partition_strain_virial, &
     328              :          local_partition_dstrain, nlcc_hessian, skala_atom_virial, skala_atom_virial_h, &
     329              :          skala_atom_virial_s
     330              :       REAL(dp), DIMENSION(3, 3, 2)                       :: cross_grad_spatial
     331              :       REAL(dp), DIMENSION(4)                             :: feature_component_analytic, &
     332              :                                                             feature_component_fd
     333        70920 :       REAL(dp), DIMENSION(:, :), POINTER                 :: rho_nlcc, smooth_density_adjoint, &
     334        70920 :                                                             smooth_kin_adjoint, weight_h, weight_s
     335        35460 :       REAL(dp), DIMENSION(:, :, :), POINTER :: composite_smooth_rho, composite_smooth_rhoa, &
     336        35460 :          composite_smooth_rhob, composite_smooth_tau, composite_smooth_tau_a, &
     337       141840 :          composite_smooth_tau_b, rho_h, rho_s, smooth_grad_adjoint, smooth_rho, smooth_rhoa, &
     338        35460 :          smooth_rhob, smooth_tau, smooth_tau_a, smooth_tau_b, tau_h, tau_s, vtau_h, vtau_s, vxc_h, &
     339        35460 :          vxc_s
     340        70920 :       REAL(dp), DIMENSION(:, :, :, :), POINTER           :: drho_h, drho_s, vxg_h, vxg_s
     341        35460 :       TYPE(atomic_kind_type), DIMENSION(:), POINTER      :: atomic_kind_set
     342              :       TYPE(cell_type), POINTER                           :: cell
     343       248220 :       TYPE(cp_3d_r_cp_type), DIMENSION(3) :: composite_smooth_drho, composite_smooth_drhoa, &
     344       496440 :          composite_smooth_drhob, smooth_drho, smooth_drhoa, smooth_drhob
     345              :       TYPE(dft_control_type), POINTER                    :: dft_control
     346              :       TYPE(grid_atom_type), POINTER                      :: grid_atom
     347              :       TYPE(gth_potential_type), POINTER                  :: gth_potential
     348              :       TYPE(gto_basis_set_type), POINTER                  :: basis_1c
     349              :       TYPE(harmonics_atom_type), POINTER                 :: harmonics
     350              :       TYPE(mp_para_env_type), POINTER                    :: para_env
     351              :       TYPE(native_grid_interpolation_stencil_type)       :: interpolation_stencil
     352        35460 :       TYPE(particle_type), DIMENSION(:), POINTER         :: particle_set
     353        35460 :       TYPE(pw_c1d_gs_type), DIMENSION(:), POINTER        :: smooth_rho_g
     354              :       TYPE(pw_env_type), POINTER                         :: pw_env
     355              :       TYPE(pw_pool_type), POINTER                        :: auxbas_pw_pool
     356        70920 :       TYPE(pw_r3d_rs_type), DIMENSION(:), POINTER        :: smooth_rho_r, smooth_tau_r, &
     357        35460 :                                                             smooth_vxc_rho, smooth_vxc_tau
     358        35460 :       TYPE(qs_force_type), DIMENSION(:), POINTER         :: force
     359        35460 :       TYPE(qs_kind_type), DIMENSION(:), POINTER          :: my_kind_set
     360              :       TYPE(qs_rho_type), POINTER                         :: rho_struct
     361        35460 :       TYPE(rho_atom_coeff), DIMENSION(:), POINTER        :: cpc_h, cpc_s, dr_h, dr_s, int_hh, &
     362        70920 :                                                             int_ss, r_h, r_s
     363        35460 :       TYPE(rho_atom_coeff), DIMENSION(:, :), POINTER     :: r_h_d, r_s_d
     364        35460 :       TYPE(rho_atom_type), DIMENSION(:), POINTER         :: my_rho_atom_set
     365              :       TYPE(rho_atom_type), POINTER                       :: rho_atom
     366              :       TYPE(section_vals_type), POINTER                   :: input, model_section, my_xc_section, &
     367              :                                                             native_section, xc_fun_section
     368              :       TYPE(sgp_potential_type), POINTER                  :: sgp_potential
     369       992880 :       TYPE(skala_periodic_partition_type) :: composite_partition_image_coords
     370        35460 :       TYPE(tau_basis_cache_type)                         :: tau_basis_cache
     371              :       TYPE(virial_type), POINTER                         :: virial
     372              :       TYPE(xc_derivative_set_type)                       :: deriv_set
     373              :       TYPE(xc_rho_cflags_type)                           :: needs
     374              :       TYPE(xc_rho_set_type)                              :: rho_set_h, rho_set_s, smooth_rho_set
     375              : 
     376              : ! -------------------------------------------------------------------------
     377              : 
     378        35460 :       CALL timeset(routineN, handle)
     379              : 
     380        35460 :       NULLIFY (atom_list)
     381        35460 :       NULLIFY (auxbas_pw_pool)
     382        35460 :       NULLIFY (my_kind_set)
     383        35460 :       NULLIFY (atomic_kind_set)
     384        35460 :       NULLIFY (cell)
     385        35460 :       NULLIFY (grid_atom)
     386        35460 :       NULLIFY (gth_potential)
     387        35460 :       NULLIFY (force)
     388        35460 :       NULLIFY (harmonics)
     389        35460 :       NULLIFY (input)
     390        35460 :       NULLIFY (para_env)
     391        35460 :       NULLIFY (particle_set)
     392        35460 :       NULLIFY (pw_env)
     393        35460 :       NULLIFY (rho_atom)
     394        35460 :       NULLIFY (rho_struct)
     395        35460 :       NULLIFY (my_rho_atom_set)
     396        35460 :       NULLIFY (rho_nlcc)
     397        35460 :       NULLIFY (smooth_rho, smooth_rhoa, smooth_rhob, smooth_tau, smooth_tau_a, smooth_tau_b)
     398        35460 :       NULLIFY (composite_smooth_rho, composite_smooth_rhoa, composite_smooth_rhob, &
     399        35460 :                composite_smooth_tau, composite_smooth_tau_a, composite_smooth_tau_b)
     400        35460 :       NULLIFY (smooth_rho_g, smooth_rho_r, smooth_tau_r)
     401        35460 :       NULLIFY (smooth_vxc_rho, smooth_vxc_tau)
     402       141840 :       DO idir = 1, 3
     403       106380 :          NULLIFY (smooth_drho(idir)%array, smooth_drhoa(idir)%array, smooth_drhob(idir)%array)
     404              :          NULLIFY (composite_smooth_drho(idir)%array, &
     405       106380 :                   composite_smooth_drhoa(idir)%array, &
     406       141840 :                   composite_smooth_drhob(idir)%array)
     407              :       END DO
     408        35460 :       NULLIFY (sgp_potential)
     409        35460 :       NULLIFY (virial)
     410        35460 :       my_calculate_forces = .FALSE.
     411        35460 :       IF (PRESENT(calculate_forces)) my_calculate_forces = calculate_forces
     412        35460 :       IF (PRESENT(composite_reference_active)) composite_reference_active = .FALSE.
     413        35460 :       direct_valence_atom_composite = .FALSE.
     414        35460 :       IF (PRESENT(direct_valence_atom_grid)) THEN
     415          126 :          direct_valence_atom_composite = direct_valence_atom_grid
     416              :       END IF
     417        35460 :       requested_atom_composite_grid = .FALSE.
     418        35460 :       IF (PRESENT(atom_composite_grid)) requested_atom_composite_grid = atom_composite_grid
     419              : 
     420        35460 :       IF (PRESENT(adiabatic_rescale_factor)) THEN
     421           44 :          my_adiabatic_rescale_factor = adiabatic_rescale_factor
     422              :       ELSE
     423        35416 :          my_adiabatic_rescale_factor = 1.0_dp
     424              :       END IF
     425              : 
     426              :       CALL get_qs_env(qs_env=qs_env, &
     427              :                       dft_control=dft_control, &
     428              :                       cell=cell, &
     429              :                       para_env=para_env, &
     430              :                       atomic_kind_set=atomic_kind_set, &
     431              :                       qs_kind_set=my_kind_set, &
     432              :                       input=input, &
     433              :                       particle_set=particle_set, &
     434              :                       pw_env=pw_env, &
     435              :                       virial=virial, &
     436              :                       rho_atom_set=my_rho_atom_set, &
     437        35460 :                       force=force)
     438              : 
     439        35460 :       IF (dft_control%qs_control%gapw_xc) THEN
     440         5570 :          CALL get_qs_env(qs_env=qs_env, rho_xc=rho_struct)
     441              :       ELSE
     442        29890 :          CALL get_qs_env(qs_env=qs_env, rho=rho_struct)
     443              :       END IF
     444              : 
     445        35460 :       IF (PRESENT(kind_set_external)) my_kind_set => kind_set_external
     446        35460 :       IF (PRESENT(rho_atom_set_external)) my_rho_atom_set => rho_atom_set_external
     447              : 
     448        35460 :       nlcc = has_nlcc(my_kind_set)
     449        35460 :       accint = dft_control%qs_control%gapw_control%accurate_xcint
     450              : 
     451        35460 :       my_xc_section => section_vals_get_subs_vals(input, "DFT%XC")
     452              : 
     453        35460 :       IF (PRESENT(xc_section_external)) my_xc_section => xc_section_external
     454              : 
     455        35460 :       xc_fun_section => section_vals_get_subs_vals(my_xc_section, "XC_FUNCTIONAL")
     456              :       CALL section_vals_val_get(xc_fun_section, "_SECTION_PARAMETERS_", &
     457        35460 :                                 i_val=myfun)
     458        35460 :       skala_atom_grid = xc_section_uses_gauxc_model(my_xc_section)
     459        35460 :       gapw_representation = skala_gapw_cp2k_default
     460        35460 :       atom_composite_diagnostic = .FALSE.
     461        35460 :       atom_composite_reference = .FALSE.
     462        35460 :       paw_pseudopotentials = .FALSE.
     463        35460 :       native_grid_diagnostics = .FALSE.
     464        35460 :       atom_composite_components = 1
     465        35460 :       feature_vxc_step = 3.0E-3_dp
     466        35460 :       IF (skala_atom_grid) THEN
     467          272 :          native_section => get_skala_native_section(my_xc_section)
     468          272 :          model_section => native_section
     469          272 :          IF (.NOT. ASSOCIATED(model_section)) model_section => get_gauxc_section(my_xc_section)
     470            2 :          CPASSERT(ASSOCIATED(model_section))
     471              :          CALL section_vals_val_get(model_section, "PSEUDOPOTENTIAL_GAPW_REPRESENTATION", &
     472          272 :                                    i_val=gapw_representation)
     473          272 :          IF (ASSOCIATED(native_section)) THEN
     474              :             CALL section_vals_val_get(native_section, "DIAGNOSTICS", &
     475          270 :                                       l_val=native_grid_diagnostics)
     476              :          END IF
     477              :       END IF
     478              :       IF (skala_atom_grid) THEN
     479          590 :          DO ikind = 1, SIZE(my_kind_set)
     480          318 :             NULLIFY (gth_potential, sgp_potential)
     481              :             CALL get_qs_kind(my_kind_set(ikind), paw_atom=paw_atom, &
     482          318 :                              gth_potential=gth_potential, sgp_potential=sgp_potential)
     483              :             paw_pseudopotentials = paw_pseudopotentials .OR. &
     484              :                                    (paw_atom .AND. (ASSOCIATED(gth_potential) .OR. &
     485          754 :                                                     ASSOCIATED(sgp_potential)))
     486              :          END DO
     487              :       END IF
     488          272 :       IF (skala_atom_grid .AND. xc_section_uses_native_skala_evaluator(my_xc_section)) THEN
     489          270 :          native_section => get_skala_native_section(my_xc_section)
     490          270 :          CPASSERT(ASSOCIATED(native_section))
     491              :          CALL section_vals_val_get(native_section, &
     492              :                                    "GAPW_ATOM_COMPOSITE_DIAGNOSTIC", &
     493          270 :                                    l_val=atom_composite_diagnostic)
     494              :          CALL section_vals_val_get(native_section, &
     495              :                                    "GAPW_ATOM_COMPOSITE_REFERENCE", &
     496          270 :                                    l_val=atom_composite_reference)
     497              :          CALL section_vals_val_get(native_section, &
     498              :                                    "GAPW_ATOM_COMPOSITE_COMPONENTS", &
     499          270 :                                    i_val=atom_composite_components)
     500              :          CALL section_vals_val_get(native_section, &
     501              :                                    "GAPW_ATOM_COMPOSITE_FD_STEP", &
     502          270 :                                    r_val=feature_vxc_step)
     503              :       END IF
     504              :       atom_composite_reference = atom_composite_reference .OR. &
     505              :                                  (gapw_representation == skala_gapw_paw_one_center .AND. &
     506        35460 :                                   paw_pseudopotentials)
     507        35460 :       atom_composite_reference = atom_composite_reference .OR. requested_atom_composite_grid
     508        35460 :       atom_composite_reference = atom_composite_reference .OR. direct_valence_atom_composite
     509        35460 :       atom_composite_active = atom_composite_diagnostic .OR. atom_composite_reference
     510        35460 :       use_atom_composite_density = atom_composite_components <= 2
     511        35460 :       use_atom_composite_gradient = atom_composite_components <= 2
     512              :       use_atom_composite_tau = atom_composite_components == 1 .OR. &
     513        35460 :                                atom_composite_components == 3
     514        35460 :       IF (atom_composite_active) THEN
     515          254 :          CALL ensure_native_skala_atom_grids(my_kind_set, dft_control)
     516              :       END IF
     517        35460 :       IF (direct_valence_atom_composite) THEN
     518          126 :          use_atom_composite_density = .FALSE.
     519          126 :          use_atom_composite_gradient = .FALSE.
     520          126 :          use_atom_composite_tau = .FALSE.
     521              :       END IF
     522              :       ! CP2K's auxiliary PW fields are represented on one index-periodic cell even
     523              :       ! when the physical Poisson problem is isolated or partially periodic.
     524        35460 :       image_partition_atom_composite = atom_composite_active
     525       141840 :       composite_image_periodicity = 1
     526        35460 :       IF (PRESENT(composite_reference_active)) composite_reference_active = atom_composite_reference
     527        35460 :       gapw_density_partition = skala_gapw_density_partition_hard_minus_soft
     528        35460 :       IF (skala_atom_grid) THEN
     529          272 :          gapw_density_partition = native_skala_gapw_density_partition(my_xc_section)
     530              :       END IF
     531        35460 :       use_virial = ASSOCIATED(virial)
     532        35460 :       IF (use_virial) use_virial = my_calculate_forces .AND. &
     533        35460 :                                    virial%pv_calculate .AND. (.NOT. virial%pv_numer)
     534              : 
     535        35460 :       IF (myfun == xc_none) THEN
     536         4500 :          exc1 = 0.0_dp
     537        17664 :          my_rho_atom_set(:)%exc_h = 0.0_dp
     538        17664 :          my_rho_atom_set(:)%exc_s = 0.0_dp
     539              :       ELSE
     540              :          CALL section_vals_val_get(my_xc_section, "DENSITY_CUTOFF", &
     541        30960 :                                    r_val=density_cut)
     542              :          CALL section_vals_val_get(my_xc_section, "GRADIENT_CUTOFF", &
     543        30960 :                                    r_val=gradient_cut)
     544              :          CALL section_vals_val_get(my_xc_section, "TAU_CUTOFF", &
     545        30960 :                                    r_val=tau_cut)
     546              : 
     547        30960 :          lsd = dft_control%lsd
     548        30960 :          nspins = dft_control%nspins
     549              :          needs = xc_functionals_get_needs(xc_fun_section, &
     550              :                                           lsd=lsd, &
     551        30960 :                                           calc_potential=.TRUE.)
     552              : 
     553        30960 :          gradient_f = (needs%drho .OR. needs%drho_spin) .OR. skala_atom_grid
     554        30960 :          tau_f = (needs%tau .OR. needs%tau_spin) .OR. skala_atom_grid
     555              : 
     556        30960 :          IF (atom_composite_active) THEN
     557          254 :             IF (lsd) THEN
     558           38 :                needs%rho_spin = .TRUE.
     559           38 :                needs%drho_spin = .TRUE.
     560           38 :                needs%tau_spin = .TRUE.
     561              :             ELSE
     562          216 :                needs%rho = .TRUE.
     563          216 :                needs%drho = .TRUE.
     564          216 :                needs%tau = .TRUE.
     565              :             END IF
     566              : 
     567              :             ALLOCATE (composite_atomic_grid_sizes(SIZE(particle_set)), &
     568            0 :                       composite_atom_kind(SIZE(particle_set)), &
     569              :                       composite_atom_kind_index(SIZE(particle_set)), &
     570            0 :                       composite_atom_start(SIZE(particle_set)), &
     571            0 :                       composite_atom_end(SIZE(particle_set)), &
     572            0 :                       composite_atom_coords(3, SIZE(particle_set)), &
     573            0 :                       composite_partition_weights(SIZE(particle_set)), &
     574            0 :                       composite_partition_atom_coords(3, SIZE(particle_set)), &
     575         3302 :                       composite_distances(SIZE(particle_set)))
     576          254 :             composite_atomic_grid_sizes = 0_int_8
     577          254 :             composite_atom_kind = 0
     578          254 :             composite_atom_kind_index = 0
     579          254 :             composite_atom_start = 0
     580          254 :             composite_atom_end = 0
     581          764 :             DO iatom = 1, SIZE(particle_set)
     582         2294 :                composite_atom_coords(:, iatom) = particle_set(iatom)%r
     583              :             END DO
     584          554 :             DO ikind = 1, SIZE(atomic_kind_set)
     585          300 :                CALL get_atomic_kind(atomic_kind_set(ikind), atom_list=atom_list, natom=natom)
     586          300 :                NULLIFY (gth_potential, sgp_potential)
     587              :                CALL get_qs_kind(my_kind_set(ikind), paw_atom=paw_atom, &
     588              :                                 gth_potential=gth_potential, grid_atom=grid_atom, &
     589          300 :                                 sgp_potential=sgp_potential, zatom=zatom, zeff=zeff)
     590         1064 :                DO iat = 1, natom
     591          510 :                   iatom = atom_list(iat)
     592          510 :                   composite_atomic_grid_sizes(iatom) = INT(grid_atom%nr*grid_atom%ng_sphere, KIND=int_8)
     593          510 :                   composite_atom_kind(iatom) = ikind
     594          810 :                   composite_atom_kind_index(iatom) = iat
     595              :                END DO
     596              :             END DO
     597          764 :             IF (ANY(composite_atomic_grid_sizes <= 0_int_8)) THEN
     598              :                CALL cp_abort(__LOCATION__, &
     599            0 :                              "The atom-composite diagnostic requires a GAPW one-center grid for every atom.")
     600              :             END IF
     601              : 
     602          254 :             composite_local_natom = 0
     603          554 :             DO ikind = 1, SIZE(atomic_kind_set)
     604          300 :                CALL get_atomic_kind(atomic_kind_set(ikind), atom_list=atom_list, natom=natom)
     605          300 :                NULLIFY (gth_potential, sgp_potential)
     606              :                CALL get_qs_kind(my_kind_set(ikind), paw_atom=paw_atom, &
     607              :                                 gth_potential=gth_potential, sgp_potential=sgp_potential, &
     608          300 :                                 zatom=zatom, zeff=zeff)
     609          300 :                bo = get_limit(natom, para_env%num_pe, para_env%mepos)
     610          854 :                composite_local_natom = composite_local_natom + MAX(0, bo(2) - bo(1) + 1)
     611              :             END DO
     612            0 :             ALLOCATE (composite_local_atoms(composite_local_natom), &
     613            0 :                       composite_local_grid_sizes(composite_local_natom), &
     614         1712 :                       composite_local_atom_coords(3, composite_local_natom))
     615          254 :             composite_local_atom = 0
     616          254 :             composite_nflat = 0
     617          554 :             DO ikind = 1, SIZE(atomic_kind_set)
     618          300 :                CALL get_atomic_kind(atomic_kind_set(ikind), atom_list=atom_list, natom=natom)
     619          300 :                NULLIFY (gth_potential, sgp_potential)
     620              :                CALL get_qs_kind(my_kind_set(ikind), paw_atom=paw_atom, &
     621              :                                 gth_potential=gth_potential, sgp_potential=sgp_potential, &
     622          300 :                                 zatom=zatom, zeff=zeff)
     623          300 :                bo = get_limit(natom, para_env%num_pe, para_env%mepos)
     624         1109 :                DO iat = bo(1), bo(2)
     625          255 :                   iatom = atom_list(iat)
     626          255 :                   composite_local_atom = composite_local_atom + 1
     627          255 :                   composite_local_atoms(composite_local_atom) = iatom
     628              :                   composite_local_grid_sizes(composite_local_atom) = &
     629          255 :                      composite_atomic_grid_sizes(iatom)
     630              :                   composite_local_atom_coords(:, composite_local_atom) = &
     631         1020 :                      composite_atom_coords(:, iatom)
     632          255 :                   composite_atom_start(iatom) = composite_nflat + 1
     633          255 :                   composite_nflat = composite_nflat + INT(composite_atomic_grid_sizes(iatom))
     634          555 :                   composite_atom_end(iatom) = composite_nflat
     635              :                END DO
     636              :             END DO
     637          254 :             CPASSERT(composite_local_atom == composite_local_natom)
     638            0 :             ALLOCATE (composite_density(composite_nflat, 2), &
     639            0 :                       composite_grad(composite_nflat, 3, 2), &
     640            0 :                       composite_kin(composite_nflat, 2), &
     641            0 :                       composite_grid_atom(composite_nflat), &
     642            0 :                       composite_smooth_density_cache(composite_nflat, 2), &
     643            0 :                       composite_smooth_gradient_cache(composite_nflat, 3, 2), &
     644            0 :                       composite_smooth_kin_cache(composite_nflat, 2), &
     645            0 :                       composite_grid_coords(3, composite_nflat), &
     646            0 :                       composite_grid_weights(composite_nflat), &
     647            0 :                       composite_base_grid_weights(composite_nflat), &
     648         4330 :                       composite_atomic_grid_weights(composite_nflat))
     649          254 :             composite_density = 0.0_dp
     650          254 :             composite_grad = 0.0_dp
     651          254 :             composite_kin = 0.0_dp
     652          509 :             DO composite_local_atom = 1, composite_local_natom
     653          255 :                iatom = composite_local_atoms(composite_local_atom)
     654       276185 :                composite_grid_atom(composite_atom_start(iatom):composite_atom_end(iatom)) = iatom
     655              :             END DO
     656          254 :             composite_smooth_density_cache = 0.0_dp
     657          254 :             composite_smooth_gradient_cache = 0.0_dp
     658          254 :             composite_smooth_kin_cache = 0.0_dp
     659          254 :             composite_grid_coords = 0.0_dp
     660          254 :             composite_grid_weights = 0.0_dp
     661          254 :             composite_base_grid_weights = 0.0_dp
     662          254 :             composite_atomic_grid_weights = 0.0_dp
     663              : 
     664              :             CALL qs_rho_get(rho_struct, rho_r=smooth_rho_r, rho_g=smooth_rho_g, &
     665              :                             tau_r=smooth_tau_r, rho_g_valid=rho_g_valid, &
     666          254 :                             tau_r_valid=tau_r_valid)
     667          254 :             CPASSERT(rho_g_valid)
     668          254 :             CPASSERT(tau_r_valid)
     669          254 :             CPASSERT(ASSOCIATED(smooth_rho_r))
     670          254 :             CPASSERT(ASSOCIATED(smooth_rho_g))
     671          254 :             CPASSERT(ASSOCIATED(smooth_tau_r))
     672              :             CALL prepare_native_grid_cache(qs_env%native_grid_cache, smooth_rho_r(1)%pw_grid, &
     673          254 :                                            cell, composite_nflat, image_partition_atom_composite)
     674          254 :             CALL pw_env_get(pw_env, auxbas_pw_pool=auxbas_pw_pool)
     675              :             CALL section_vals_val_get(my_xc_section, "XC_GRID%XC_DERIV", &
     676          254 :                                       i_val=xc_deriv_method_id)
     677              :             CALL section_vals_val_get(my_xc_section, "XC_GRID%XC_SMOOTH_RHO", &
     678          254 :                                       i_val=xc_rho_smooth_id)
     679              :             CALL xc_rho_set_create(smooth_rho_set, smooth_rho_r(1)%pw_grid%bounds_local, &
     680              :                                    rho_cutoff=section_get_rval(my_xc_section, "density_cutoff"), &
     681              :                                    drho_cutoff=section_get_rval(my_xc_section, "gradient_cutoff"), &
     682          254 :                                    tau_cutoff=section_get_rval(my_xc_section, "tau_cutoff"))
     683              :             CALL xc_rho_set_update(smooth_rho_set, smooth_rho_r, smooth_rho_g, smooth_tau_r, needs, &
     684          254 :                                    xc_deriv_method_id, xc_rho_smooth_id, auxbas_pw_pool)
     685          762 :             IF (lsd) THEN
     686              :                CALL xc_rho_set_get(smooth_rho_set, rhoa=smooth_rhoa, rhob=smooth_rhob, &
     687              :                                    drhoa=smooth_drhoa, drhob=smooth_drhob, &
     688           38 :                                    tau_a=smooth_tau_a, tau_b=smooth_tau_b)
     689              :                CALL gather_native_grid_field(smooth_rhoa, smooth_rho_r(1)%pw_grid, para_env, &
     690           38 :                                              composite_smooth_rhoa)
     691              :                CALL gather_native_grid_field(smooth_rhob, smooth_rho_r(1)%pw_grid, para_env, &
     692           38 :                                              composite_smooth_rhob)
     693              :                CALL gather_native_grid_field(smooth_tau_a, smooth_rho_r(1)%pw_grid, para_env, &
     694           38 :                                              composite_smooth_tau_a)
     695              :                CALL gather_native_grid_field(smooth_tau_b, smooth_rho_r(1)%pw_grid, para_env, &
     696           38 :                                              composite_smooth_tau_b)
     697          152 :                DO idir = 1, 3
     698              :                   CALL gather_native_grid_field(smooth_drhoa(idir)%array, &
     699              :                                                 smooth_rho_r(1)%pw_grid, para_env, &
     700          114 :                                                 composite_smooth_drhoa(idir)%array)
     701              :                   CALL gather_native_grid_field(smooth_drhob(idir)%array, &
     702              :                                                 smooth_rho_r(1)%pw_grid, para_env, &
     703          152 :                                                 composite_smooth_drhob(idir)%array)
     704              :                END DO
     705              :             ELSE
     706              :                CALL xc_rho_set_get(smooth_rho_set, rho=smooth_rho, drho=smooth_drho, &
     707          216 :                                    tau=smooth_tau)
     708              :                CALL gather_native_grid_field(smooth_rho, smooth_rho_r(1)%pw_grid, para_env, &
     709          216 :                                              composite_smooth_rho)
     710              :                CALL gather_native_grid_field(smooth_tau, smooth_rho_r(1)%pw_grid, para_env, &
     711          216 :                                              composite_smooth_tau)
     712          864 :                DO idir = 1, 3
     713              :                   CALL gather_native_grid_field(smooth_drho(idir)%array, &
     714              :                                                 smooth_rho_r(1)%pw_grid, para_env, &
     715          864 :                                                 composite_smooth_drho(idir)%array)
     716              :                END DO
     717              :             END IF
     718              :          END IF
     719              : 
     720              :          ! Initialize energy contribution from the one center XC terms to zero
     721        30960 :          exc1 = 0.0_dp
     722              : 
     723              :          ! Nullify some pointers for work-arrays
     724        30960 :          NULLIFY (rho_h, drho_h, rho_s, drho_s, weight_h, weight_s)
     725        30960 :          NULLIFY (vxc_h, vxc_s, vxg_h, vxg_s)
     726        30960 :          NULLIFY (tau_h, tau_s)
     727        30960 :          NULLIFY (vtau_h, vtau_s)
     728              : 
     729              :          ! Here starts the loop over all the atoms
     730              : 
     731        89470 :          DO ikind = 1, SIZE(atomic_kind_set)
     732        58510 :             CALL get_atomic_kind(atomic_kind_set(ikind), atom_list=atom_list, natom=natom)
     733        58510 :             NULLIFY (gth_potential, sgp_potential)
     734              :             CALL get_qs_kind(my_kind_set(ikind), paw_atom=paw_atom, &
     735              :                              gth_potential=gth_potential, harmonics=harmonics, &
     736              :                              grid_atom=grid_atom, sgp_potential=sgp_potential, &
     737        58510 :                              zatom=zatom, zeff=zeff)
     738        58510 :             one_center_kind = .NOT. direct_valence_atom_composite
     739        58510 :             IF (one_center_kind) THEN
     740        58374 :                CALL get_qs_kind(my_kind_set(ikind), basis_set=basis_1c, basis_type="GAPW_1C")
     741        58374 :                one_center_kind = paw_atom
     742        58374 :                IF (skala_atom_grid) THEN
     743              :                   one_center_kind = native_skala_uses_one_center_kind( &
     744              :                                     paw_atom, gapw_representation, &
     745              :                                     ASSOCIATED(gth_potential) .OR. ASSOCIATED(sgp_potential), &
     746          206 :                                     zeff, zatom)
     747              :                END IF
     748              :             END IF
     749        58510 :             IF (.NOT. one_center_kind .AND. .NOT. atom_composite_active) CYCLE
     750              : 
     751        52750 :             nr = grid_atom%nr
     752        52750 :             na = grid_atom%ng_sphere
     753              : 
     754        52750 :             IF (one_center_kind) THEN
     755              :                ! Prepare the structures needed to calculate and store the one-center XC derivatives.
     756              : 
     757              :                ! Array dimension: here anly one dimensional arrays are used,
     758              :                ! i.e. only the first column of deriv_data is read.
     759              :                ! The other to dimensions  are set to size equal 1
     760       526100 :                bounds(1:2, 1:3) = 1
     761        52610 :                bounds(2, 1) = na
     762        52610 :                bounds(2, 2) = nr
     763              : 
     764              :                ! set integration weights
     765        52610 :                weight_h => grid_atom%weight
     766        52610 :                weight_s => grid_atom%weight
     767        52610 :                IF (accint) THEN
     768        14786 :                   on = dft_control%qs_control%gapw_control%oweights
     769        14786 :                   alpha = dft_control%qs_control%gapw_control%aw(ikind)
     770        14786 :                   IF (ASSOCIATED(grid_atom%gapw_weight_s)) THEN
     771        14254 :                      IF (grid_atom%gapw_weight_alpha /= alpha) DEALLOCATE (grid_atom%gapw_weight_s)
     772              :                   END IF
     773        14786 :                   IF (.NOT. ASSOCIATED(grid_atom%gapw_weight_s)) THEN
     774         2128 :                      ALLOCATE (grid_atom%gapw_weight_s(na, nr))
     775         1596 :                      ALLOCATE (fw(nr))
     776          532 :                      CALL calc_weight_function(fw, grid_atom%rad2, on, alpha)
     777        26952 :                      DO ir = 1, nr
     778        26420 :                         agr = 1.0_dp - fw(ir)
     779      1343632 :                         grid_atom%gapw_weight_s(:, ir) = agr*grid_atom%weight(:, ir)
     780              :                      END DO
     781          532 :                      DEALLOCATE (fw)
     782          532 :                      grid_atom%gapw_weight_alpha = alpha
     783              :                   END IF
     784        14786 :                   weight_s => grid_atom%gapw_weight_s
     785              :                END IF
     786              : 
     787              :                ! create a place where to put the derivatives
     788        52610 :                CALL xc_dset_create(deriv_set, local_bounds=bounds)
     789              :                ! create the place where to store the argument for the functionals
     790              :                CALL xc_rho_set_create(rho_set_h, bounds, rho_cutoff=density_cut, &
     791        52610 :                                       drho_cutoff=gradient_cut, tau_cutoff=tau_cut)
     792              :                CALL xc_rho_set_create(rho_set_s, bounds, rho_cutoff=density_cut, &
     793        52610 :                                       drho_cutoff=gradient_cut, tau_cutoff=tau_cut)
     794              : 
     795              :                ! allocate the required 3d arrays where to store rho and drho
     796        52610 :                CALL xc_rho_set_atom_update(rho_set_h, needs, nspins, bounds)
     797        52610 :                CALL xc_rho_set_atom_update(rho_set_s, needs, nspins, bounds)
     798              : 
     799        52610 :                CALL reallocate(rho_h, 1, na, 1, nr, 1, nspins)
     800        52610 :                CALL reallocate(rho_s, 1, na, 1, nr, 1, nspins)
     801        52610 :                CALL reallocate(vxc_h, 1, na, 1, nr, 1, nspins)
     802        52610 :                CALL reallocate(vxc_s, 1, na, 1, nr, 1, nspins)
     803              :                !
     804        52610 :                IF (gradient_f) THEN
     805        35736 :                   CALL reallocate(drho_h, 1, 4, 1, na, 1, nr, 1, nspins)
     806        35736 :                   CALL reallocate(drho_s, 1, 4, 1, na, 1, nr, 1, nspins)
     807        35736 :                   CALL reallocate(vxg_h, 1, 3, 1, na, 1, nr, 1, nspins)
     808        35736 :                   CALL reallocate(vxg_s, 1, 3, 1, na, 1, nr, 1, nspins)
     809              :                END IF
     810              : 
     811        52610 :                IF (tau_f) THEN
     812         1570 :                   CALL create_tau_basis_cache(tau_basis_cache, grid_atom, basis_1c, harmonics)
     813         1570 :                   CALL reallocate(tau_h, 1, na, 1, nr, 1, nspins)
     814         1570 :                   CALL reallocate(tau_s, 1, na, 1, nr, 1, nspins)
     815         1570 :                   CALL reallocate(vtau_h, 1, na, 1, nr, 1, nspins)
     816         1570 :                   CALL reallocate(vtau_s, 1, na, 1, nr, 1, nspins)
     817              :                END IF
     818              : 
     819              :                ! NLCC for separate hard and soft one-center densities.
     820        52610 :                donlcc = .FALSE.
     821        52610 :                IF (nlcc) THEN
     822         1922 :                   NULLIFY (rho_nlcc)
     823         1922 :                   rho_nlcc => my_kind_set(ikind)%nlcc_pot
     824         1922 :                   IF (ASSOCIATED(rho_nlcc)) donlcc = .TRUE.
     825              :                END IF
     826              :             END IF
     827              : 
     828              :             ! Distribute the atoms of this kind
     829              : 
     830        52750 :             num_pe = para_env%num_pe
     831        52750 :             bo = get_limit(natom, para_env%num_pe, para_env%mepos)
     832              : 
     833        93798 :             DO iat = bo(1), bo(2)
     834        41048 :                iatom = atom_list(iat)
     835              : 
     836        41048 :                IF (one_center_kind) THEN
     837        40919 :                   my_rho_atom_set(iatom)%exc_h = 0.0_dp
     838        40919 :                   my_rho_atom_set(iatom)%exc_s = 0.0_dp
     839              : 
     840        40919 :                   rho_atom => my_rho_atom_set(iatom)
     841    140165551 :                   rho_h = 0.0_dp
     842    140165551 :                   rho_s = 0.0_dp
     843        40919 :                   IF (gradient_f) THEN
     844        27182 :                      NULLIFY (r_h, r_s, dr_h, dr_s, r_h_d, r_s_d)
     845              :                      CALL get_rho_atom(rho_atom=rho_atom, rho_rad_h=r_h, &
     846              :                                        rho_rad_s=r_s, drho_rad_h=dr_h, &
     847              :                                        drho_rad_s=dr_s, rho_rad_h_d=r_h_d, &
     848        27182 :                                        rho_rad_s_d=r_s_d)
     849    439913133 :                      drho_h = 0.0_dp
     850    439913133 :                      drho_s = 0.0_dp
     851              :                   ELSE
     852        13737 :                      NULLIFY (r_h, r_s)
     853        13737 :                      CALL get_rho_atom(rho_atom=rho_atom, rho_rad_h=r_h, rho_rad_s=r_s)
     854        13737 :                      rho_d = 0.0_dp
     855              :                   END IF
     856        40919 :                   IF (tau_f) THEN
     857         1187 :                      CALL calc_tau_atom(tau_h, tau_s, rho_atom, tau_basis_cache, nspins)
     858              :                   ELSE
     859        39732 :                      tau_d = 0.0_dp
     860              :                   END IF
     861              : 
     862      2265459 :                   DO ir = 1, nr
     863              :                      CALL calc_rho_angular(grid_atom, harmonics, nspins, gradient_f, &
     864              :                                            ir, r_h, r_s, rho_h, rho_s, dr_h, dr_s, &
     865      2224540 :                                            r_h_d, r_s_d, drho_h, drho_s)
     866      2265459 :                      IF (donlcc) THEN
     867              :                         CALL calc_rho_nlcc(grid_atom, nspins, gradient_f, &
     868              :                                            ir, rho_nlcc(:, 1), rho_h, rho_s, &
     869        30950 :                                            rho_nlcc(:, 2), drho_h, drho_s)
     870              :                      END IF
     871              :                   END DO
     872              :                END IF
     873              : 
     874        41048 :                IF (atom_composite_active) THEN
     875          255 :                   IF (image_partition_atom_composite) THEN
     876              :                      CALL build_periodic_atom_image_layout( &
     877              :                         composite_atom_coords, cell, iatom, composite_image_periodicity, &
     878          255 :                         composite_partition_image_coords, composite_partition_target_image)
     879              :                   END IF
     880              : !$OMP PARALLEL DO COLLAPSE(2) IF (image_partition_atom_composite) SCHEDULE(STATIC) DEFAULT(NONE) &
     881              : !$OMP PRIVATE(composite_row, composite_point, composite_smooth_density_value, &
     882              : !$OMP         composite_smooth_gradient_value, composite_smooth_kin_value, &
     883              : !$OMP         idir, ispin, &
     884              : !$OMP         gth_potential, nlcc_density, nlcc_gradient, nlcc_hessian, nlcc_spin_factor, &
     885              : !$OMP         interpolation_stencil, partition_weight, sgp_potential, source_atom) &
     886              : !$OMP SHARED(atom_composite_reference, cell, composite_atom_coords, composite_atom_kind, &
     887              : !$OMP        composite_atom_start, composite_atomic_grid_weights, composite_base_grid_weights, &
     888              : !$OMP        composite_density, composite_distances, composite_grad, &
     889              : !$OMP        composite_grid_coords, composite_grid_weights, composite_kin, &
     890              : !$OMP        composite_partition_atom_coords, composite_partition_image_coords, &
     891              : !$OMP        composite_partition_target_image, composite_partition_weights, &
     892              : !$OMP        composite_smooth_density_cache, composite_smooth_drho, composite_smooth_drhoa, &
     893              : !$OMP        composite_smooth_drhob, composite_smooth_gradient_cache, &
     894              : !$OMP        composite_smooth_kin_cache, composite_smooth_rho, composite_smooth_rhoa, &
     895              : !$OMP        composite_smooth_rhob, composite_smooth_tau, composite_smooth_tau_a, &
     896              : !$OMP        composite_smooth_tau_b, drho_h, drho_s, grid_atom, iatom, &
     897              : !$OMP        image_partition_atom_composite, lsd, my_kind_set, na, nlcc, nr, one_center_kind, &
     898              : !$OMP        particle_set, qs_env, rho_h, rho_s, smooth_rho_r, tau_h, tau_s, &
     899          255 : !$OMP        use_atom_composite_density, use_atom_composite_gradient, use_atom_composite_tau)
     900              :                   DO ir = 1, nr
     901              :                      DO ia = 1, na
     902              :                         composite_row = composite_atom_start(iatom) + (ir - 1)*na + ia - 1
     903              :                         composite_point(1) = particle_set(iatom)%r(1) + grid_atom%rad(ir)* &
     904              :                                              grid_atom%sin_pol(ia)*grid_atom%cos_azi(ia)
     905              :                         composite_point(2) = particle_set(iatom)%r(2) + grid_atom%rad(ir)* &
     906              :                                              grid_atom%sin_pol(ia)*grid_atom%sin_azi(ia)
     907              :                         composite_point(3) = particle_set(iatom)%r(3) + &
     908              :                                              grid_atom%rad(ir)*grid_atom%cos_pol(ia)
     909              :                         composite_grid_coords(:, composite_row) = composite_point
     910              :                         IF (image_partition_atom_composite) THEN
     911              :                            CALL periodic_atom_image_partition_from_layout( &
     912              :                               composite_point, composite_partition_image_coords, &
     913              :                               composite_partition_target_image, partition_weight)
     914              :                         ELSE
     915              :                            CALL smooth_atom_partition( &
     916              :                               composite_point, composite_atom_coords, cell, &
     917              :                               composite_partition_weights, composite_partition_atom_coords, &
     918              :                               composite_distances)
     919              :                            partition_weight = composite_partition_weights(iatom)
     920              :                         END IF
     921              :                         composite_base_grid_weights(composite_row) = grid_atom%weight(ia, ir)
     922              :                         composite_atomic_grid_weights(composite_row) = &
     923              :                            composite_base_grid_weights(composite_row)
     924              :                         composite_grid_weights(composite_row) = &
     925              :                            composite_base_grid_weights(composite_row)* &
     926              :                            partition_weight
     927              :                         IF (.NOT. fetch_native_grid_stencil(qs_env%native_grid_cache, composite_row, &
     928              :                                                             composite_point, interpolation_stencil)) THEN
     929              :                            CALL create_native_grid_interpolation_stencil( &
     930              :                               interpolation_stencil, smooth_rho_r(1)%pw_grid, cell, composite_point, &
     931              :                               image_partition_atom_composite)
     932              :                            CALL store_native_grid_stencil(qs_env%native_grid_cache, composite_row, &
     933              :                                                           composite_point, interpolation_stencil)
     934              :                         END IF
     935              :                         IF (lsd) THEN
     936              :                            CALL interpolate_native_grid_fields( &
     937              :                               composite_smooth_rhoa, composite_smooth_drhoa(1)%array, &
     938              :                               composite_smooth_drhoa(2)%array, composite_smooth_drhoa(3)%array, &
     939              :                               composite_smooth_tau_a, interpolation_stencil, &
     940              :                               composite_smooth_density_value(1), &
     941              :                               composite_smooth_gradient_value(:, 1), &
     942              :                               composite_smooth_kin_value(1))
     943              :                            CALL interpolate_native_grid_fields( &
     944              :                               composite_smooth_rhob, composite_smooth_drhob(1)%array, &
     945              :                               composite_smooth_drhob(2)%array, composite_smooth_drhob(3)%array, &
     946              :                               composite_smooth_tau_b, interpolation_stencil, &
     947              :                               composite_smooth_density_value(2), &
     948              :                               composite_smooth_gradient_value(:, 2), &
     949              :                               composite_smooth_kin_value(2))
     950              :                            composite_smooth_density_cache(composite_row, :) = &
     951              :                               composite_smooth_density_value
     952              :                            composite_smooth_gradient_cache(composite_row, :, :) = &
     953              :                               composite_smooth_gradient_value
     954              :                            composite_smooth_kin_cache(composite_row, :) = &
     955              :                               composite_smooth_kin_value
     956              :                            DO ispin = 1, 2
     957              :                               composite_density(composite_row, ispin) = &
     958              :                                  composite_smooth_density_value(ispin)
     959              :                               composite_grad(composite_row, :, ispin) = &
     960              :                                  composite_smooth_gradient_value(:, ispin)
     961              :                               composite_kin(composite_row, ispin) = &
     962              :                                  composite_smooth_kin_value(ispin)
     963              :                               IF (one_center_kind .AND. use_atom_composite_density) THEN
     964              :                                  composite_density(composite_row, ispin) = &
     965              :                                     composite_density(composite_row, ispin) + &
     966              :                                     rho_h(ia, ir, ispin) - rho_s(ia, ir, ispin)
     967              :                               END IF
     968              :                               IF (one_center_kind .AND. use_atom_composite_gradient) THEN
     969              :                                  DO idir = 1, 3
     970              :                                     composite_grad(composite_row, idir, ispin) = &
     971              :                                        composite_grad(composite_row, idir, ispin) + &
     972              :                                        drho_h(idir, ia, ir, ispin) - drho_s(idir, ia, ir, ispin)
     973              :                                  END DO
     974              :                               END IF
     975              :                               IF (one_center_kind .AND. use_atom_composite_tau) THEN
     976              :                                  composite_kin(composite_row, ispin) = &
     977              :                                     composite_kin(composite_row, ispin) + &
     978              :                                     tau_h(ia, ir, ispin) - tau_s(ia, ir, ispin)
     979              :                               END IF
     980              :                            END DO
     981              :                         ELSE
     982              :                            CALL interpolate_native_grid_fields( &
     983              :                               composite_smooth_rho, composite_smooth_drho(1)%array, &
     984              :                               composite_smooth_drho(2)%array, composite_smooth_drho(3)%array, &
     985              :                               composite_smooth_tau, interpolation_stencil, &
     986              :                               composite_smooth_density_value(1), &
     987              :                               composite_smooth_gradient_value(:, 1), &
     988              :                               composite_smooth_kin_value(1))
     989              :                            composite_smooth_density_cache(composite_row, 1) = &
     990              :                               composite_smooth_density_value(1)
     991              :                            composite_smooth_gradient_cache(composite_row, :, 1) = &
     992              :                               composite_smooth_gradient_value(:, 1)
     993              :                            composite_smooth_kin_cache(composite_row, 1) = &
     994              :                               composite_smooth_kin_value(1)
     995              :                            composite_density(composite_row, :) = &
     996              :                               0.5_dp*composite_smooth_density_value(1)
     997              :                            DO idir = 1, 3
     998              :                               composite_grad(composite_row, idir, :) = &
     999              :                                  0.5_dp*composite_smooth_gradient_value(idir, 1)
    1000              :                            END DO
    1001              :                            composite_kin(composite_row, :) = &
    1002              :                               0.5_dp*composite_smooth_kin_value(1)
    1003              :                            IF (one_center_kind .AND. use_atom_composite_density) THEN
    1004              :                               composite_density(composite_row, :) = &
    1005              :                                  composite_density(composite_row, :) + &
    1006              :                                  0.5_dp*(rho_h(ia, ir, 1) - rho_s(ia, ir, 1))
    1007              :                            END IF
    1008              :                            IF (one_center_kind .AND. use_atom_composite_gradient) THEN
    1009              :                               DO idir = 1, 3
    1010              :                                  composite_grad(composite_row, idir, :) = &
    1011              :                                     composite_grad(composite_row, idir, :) + &
    1012              :                                     0.5_dp*(drho_h(idir, ia, ir, 1) - &
    1013              :                                             drho_s(idir, ia, ir, 1))
    1014              :                               END DO
    1015              :                            END IF
    1016              :                            IF (one_center_kind .AND. use_atom_composite_tau) THEN
    1017              :                               composite_kin(composite_row, :) = composite_kin(composite_row, :) + &
    1018              :                                                                 0.5_dp*(tau_h(ia, ir, 1) - &
    1019              :                                                                         tau_s(ia, ir, 1))
    1020              :                            END IF
    1021              :                         END IF
    1022              :                         IF (atom_composite_reference .AND. nlcc) THEN
    1023              :                            nlcc_spin_factor = MERGE(1.0_dp, 0.5_dp, lsd)
    1024              :                            DO source_atom = 1, SIZE(particle_set)
    1025              :                               NULLIFY (gth_potential, sgp_potential)
    1026              :                               CALL get_qs_kind(my_kind_set(composite_atom_kind(source_atom)), &
    1027              :                                                gth_potential=gth_potential, &
    1028              :                                                sgp_potential=sgp_potential)
    1029              :                               CALL evaluate_nlcc_primitive_fields( &
    1030              :                                  composite_point, particle_set(source_atom)%r, &
    1031              :                                  gth_potential, sgp_potential, nlcc_density, &
    1032              :                                  nlcc_gradient, nlcc_hessian)
    1033              :                               composite_density(composite_row, :) = &
    1034              :                                  composite_density(composite_row, :) + &
    1035              :                                  nlcc_spin_factor*nlcc_density
    1036              :                               DO idir = 1, 3
    1037              :                                  composite_grad(composite_row, idir, :) = &
    1038              :                                     composite_grad(composite_row, idir, :) + &
    1039              :                                     nlcc_spin_factor*nlcc_gradient(idir)
    1040              :                               END DO
    1041              :                            END DO
    1042              :                         END IF
    1043              :                      END DO
    1044              :                   END DO
    1045              : !$OMP END PARALLEL DO
    1046          255 :                   CPASSERT(nr*na == composite_atom_end(iatom) - composite_atom_start(iatom) + 1)
    1047              :                END IF
    1048              : 
    1049        41048 :                IF (.NOT. one_center_kind) CYCLE
    1050              : 
    1051      2265459 :                DO ir = 1, nr
    1052      2265459 :                   IF (tau_f) THEN
    1053        59150 :                      CALL fill_rho_set(rho_set_h, lsd, nspins, needs, rho_h, drho_h, tau_h, na, ir)
    1054        59150 :                      CALL fill_rho_set(rho_set_s, lsd, nspins, needs, rho_s, drho_s, tau_s, na, ir)
    1055      2165390 :                   ELSE IF (gradient_f) THEN
    1056      1325140 :                      CALL fill_rho_set(rho_set_h, lsd, nspins, needs, rho_h, drho_h, tau_d, na, ir)
    1057      1325140 :                      CALL fill_rho_set(rho_set_s, lsd, nspins, needs, rho_s, drho_s, tau_d, na, ir)
    1058              :                   ELSE
    1059       840250 :                      CALL fill_rho_set(rho_set_h, lsd, nspins, needs, rho_h, rho_d, tau_d, na, ir)
    1060       840250 :                      CALL fill_rho_set(rho_set_s, lsd, nspins, needs, rho_s, rho_d, tau_d, na, ir)
    1061              :                   END IF
    1062              :                END DO
    1063              : 
    1064        40919 :                evaluate_hard = .TRUE.
    1065        40919 :                evaluate_soft = .TRUE.
    1066        40919 :                skala_atom_force_h = 0.0_dp
    1067        40919 :                skala_atom_force_s = 0.0_dp
    1068        40919 :                skala_atom_virial_h = 0.0_dp
    1069        40919 :                skala_atom_virial_s = 0.0_dp
    1070        40919 :                IF (skala_atom_grid) THEN
    1071              :                   SELECT CASE (gapw_density_partition)
    1072              :                   CASE (skala_gapw_density_partition_hard_minus_soft)
    1073            0 :                      CONTINUE
    1074              :                   CASE (skala_gapw_density_partition_hard_only)
    1075            0 :                      evaluate_soft = .FALSE.
    1076              :                   CASE (skala_gapw_density_partition_soft_only)
    1077            0 :                      evaluate_hard = .FALSE.
    1078              :                   CASE (skala_gapw_density_partition_none)
    1079            0 :                      evaluate_hard = .FALSE.
    1080            0 :                      evaluate_soft = .FALSE.
    1081              :                   CASE DEFAULT
    1082              :                      CALL cp_abort(__LOCATION__, &
    1083          128 :                                    "Unknown SKALA_NATIVE%GAPW_DENSITY_PARTITION value.")
    1084              :                   END SELECT
    1085              :                END IF
    1086        40919 :                IF (atom_composite_reference) THEN
    1087          126 :                   evaluate_hard = .FALSE.
    1088          126 :                   evaluate_soft = .FALSE.
    1089              :                END IF
    1090              : 
    1091              :                !-------------------!
    1092              :                ! hard atom density !
    1093              :                !-------------------!
    1094        40919 :                CALL xc_dset_zero_all(deriv_set)
    1095        40919 :                IF (.NOT. evaluate_hard) THEN
    1096          126 :                   exc_h = 0.0_dp
    1097          126 :                   IF (.NOT. energy_only) THEN
    1098       119052 :                      vxc_h = 0.0_dp
    1099       464652 :                      IF (ASSOCIATED(vxg_h)) vxg_h = 0.0_dp
    1100       119052 :                      IF (ASSOCIATED(vtau_h)) vtau_h = 0.0_dp
    1101              :                   END IF
    1102        40793 :                ELSE IF (skala_atom_grid) THEN
    1103              :                   CALL skala_gapw_atom_vxc_of_r( &
    1104              :                      my_xc_section, grid_atom, para_env, particle_set(iatom)%r, &
    1105              :                      rho_h, drho_h, tau_h, weight_h, lsd, nspins, na, nr, &
    1106              :                      exc_h, vxc_h, vxg_h, vtau_h, energy_only=energy_only, &
    1107            2 :                      atom_force=skala_atom_force_h, atom_virial=skala_atom_virial_h)
    1108              :                ELSE
    1109              :                   CALL vxc_of_r_new(xc_fun_section, rho_set_h, deriv_set, 1, needs, weight_h, &
    1110              :                                     lsd, na, nr, exc_h, vxc_h, vxg_h, vtau_h, energy_only=energy_only, &
    1111        40791 :                                     adiabatic_rescale_factor=my_adiabatic_rescale_factor)
    1112              :                END IF
    1113        40919 :                rho_atom%exc_h = rho_atom%exc_h + exc_h
    1114              : 
    1115              :                !-------------------!
    1116              :                ! soft atom density !
    1117              :                !-------------------!
    1118        40919 :                CALL xc_dset_zero_all(deriv_set)
    1119        40919 :                IF (.NOT. evaluate_soft) THEN
    1120          126 :                   exc_s = 0.0_dp
    1121          126 :                   IF (.NOT. energy_only) THEN
    1122       119052 :                      vxc_s = 0.0_dp
    1123       464652 :                      IF (ASSOCIATED(vxg_s)) vxg_s = 0.0_dp
    1124       119052 :                      IF (ASSOCIATED(vtau_s)) vtau_s = 0.0_dp
    1125              :                   END IF
    1126        40793 :                ELSE IF (skala_atom_grid) THEN
    1127              :                   CALL skala_gapw_atom_vxc_of_r( &
    1128              :                      my_xc_section, grid_atom, para_env, particle_set(iatom)%r, &
    1129              :                      rho_s, drho_s, tau_s, weight_s, lsd, nspins, na, nr, &
    1130              :                      exc_s, vxc_s, vxg_s, vtau_s, energy_only=energy_only, &
    1131            2 :                      atom_force=skala_atom_force_s, atom_virial=skala_atom_virial_s)
    1132              :                ELSE
    1133              :                   CALL vxc_of_r_new(xc_fun_section, rho_set_s, deriv_set, 1, needs, weight_s, &
    1134              :                                     lsd, na, nr, exc_s, vxc_s, vxg_s, vtau_s, energy_only=energy_only, &
    1135        40791 :                                     adiabatic_rescale_factor=my_adiabatic_rescale_factor)
    1136              :                END IF
    1137        40919 :                rho_atom%exc_s = rho_atom%exc_s + exc_s
    1138              : 
    1139              :                ! Add contributions to the exc energy
    1140              : 
    1141        40919 :                exc1 = exc1 + rho_atom%exc_h - rho_atom%exc_s
    1142        40919 :                IF (skala_atom_grid .AND. my_calculate_forces .AND. ASSOCIATED(force)) THEN
    1143              :                   force(ikind)%rho_elec(:, iat) = force(ikind)%rho_elec(:, iat) + &
    1144          140 :                                                   skala_atom_force_h - skala_atom_force_s
    1145              :                END IF
    1146        40919 :                IF (skala_atom_grid .AND. use_virial) THEN
    1147          403 :                   skala_atom_virial = skala_atom_virial_h - skala_atom_virial_s
    1148          124 :                   DO idir = 1, 3
    1149          403 :                      DO jdir = 1, 3
    1150              :                         virial%pv_gapw(idir, jdir) = virial%pv_gapw(idir, jdir) + &
    1151          279 :                                                      skala_atom_virial(idir, jdir)
    1152              :                         virial%pv_virial(idir, jdir) = virial%pv_virial(idir, jdir) + &
    1153          372 :                                                        skala_atom_virial(idir, jdir)
    1154              :                      END DO
    1155              :                   END DO
    1156              :                END IF
    1157              : 
    1158              :                ! Integration to get the matrix elements relative to the vxc_atom
    1159              :                ! here the products with the primitives is done: gaVxcgb
    1160              :                ! internal transformation to get the integral in cartesian Gaussians
    1161              : 
    1162        40919 :                IF (.NOT. energy_only) THEN
    1163        38953 :                   NULLIFY (int_hh, int_ss)
    1164        38953 :                   CALL get_rho_atom(rho_atom=rho_atom, ga_Vlocal_gb_h=int_hh, ga_Vlocal_gb_s=int_ss)
    1165        38953 :                   IF (gradient_f) THEN
    1166              :                      CALL gaVxcgb_GC(vxc_h, vxc_s, vxg_h, vxg_s, int_hh, int_ss, &
    1167        25392 :                                      grid_atom, basis_1c, harmonics, nspins)
    1168              :                   ELSE
    1169              :                      CALL gaVxcgb_noGC(vxc_h, vxc_s, int_hh, int_ss, &
    1170        13561 :                                        grid_atom, basis_1c, harmonics, nspins)
    1171              :                   END IF
    1172        38953 :                   IF (tau_f) THEN
    1173         1139 :                      CALL dgaVtaudgb(vtau_h, vtau_s, int_hh, int_ss, tau_basis_cache, nspins)
    1174              :                   END IF
    1175              :                END IF ! energy_only
    1176        93798 :                NULLIFY (r_h, r_s, dr_h, dr_s)
    1177              :             END DO ! iat
    1178              : 
    1179       142220 :             IF (one_center_kind) THEN
    1180        52610 :                IF (tau_f) CALL release_tau_basis_cache(tau_basis_cache)
    1181              : 
    1182        52610 :                CALL xc_dset_release(deriv_set)
    1183        52610 :                CALL xc_rho_set_release(rho_set_h)
    1184        52610 :                CALL xc_rho_set_release(rho_set_s)
    1185              :             END IF
    1186              :          END DO ! ikind
    1187              : 
    1188        30960 :          IF (atom_composite_active) THEN
    1189            0 :             ALLOCATE (composite_cross_density(composite_nflat, 2), &
    1190            0 :                       composite_cross_grad(composite_nflat, 3, 2), &
    1191         1712 :                       composite_cross_kin(composite_nflat, 2))
    1192          254 :             composite_cross_density = 0.0_dp
    1193          254 :             composite_cross_grad = 0.0_dp
    1194          254 :             composite_cross_kin = 0.0_dp
    1195          254 :             composite_cross_cutoff_max = 0.0_dp
    1196          254 :             IF (.NOT. direct_valence_atom_composite) THEN
    1197          292 :                DO ikind = 1, SIZE(atomic_kind_set)
    1198          164 :                   CALL get_atomic_kind(atomic_kind_set(ikind), atom_list=atom_list, natom=natom)
    1199          164 :                   NULLIFY (gth_potential, sgp_potential)
    1200              :                   CALL get_qs_kind(my_kind_set(ikind), paw_atom=paw_atom, &
    1201              :                                    gth_potential=gth_potential, harmonics=harmonics, &
    1202              :                                    grid_atom=grid_atom, sgp_potential=sgp_potential, &
    1203          164 :                                    zatom=zatom, zeff=zeff)
    1204          164 :                   CALL get_qs_kind(my_kind_set(ikind), basis_set=basis_1c, basis_type="GAPW_1C")
    1205          188 :                   IF (.NOT. native_skala_uses_one_center_kind( &
    1206              :                       paw_atom, gapw_representation, &
    1207              :                       ASSOCIATED(gth_potential) .OR. ASSOCIATED(sgp_potential), &
    1208              :                       zeff, zatom)) CYCLE
    1209              : 
    1210              :                   CALL replicate_rho_atom_radial( &
    1211          160 :                      para_env, my_rho_atom_set, my_kind_set(ikind), atom_list, natom, nspins)
    1212          160 :                   nr = grid_atom%nr
    1213          160 :                   na = grid_atom%ng_sphere
    1214          160 :                   CALL create_tau_basis_cache(tau_basis_cache, grid_atom, basis_1c, harmonics)
    1215          160 :                   CALL reallocate(rho_h, 1, na, 1, nr, 1, nspins)
    1216          160 :                   CALL reallocate(rho_s, 1, na, 1, nr, 1, nspins)
    1217          160 :                   CALL reallocate(drho_h, 1, 4, 1, na, 1, nr, 1, nspins)
    1218          160 :                   CALL reallocate(drho_s, 1, 4, 1, na, 1, nr, 1, nspins)
    1219          160 :                   CALL reallocate(tau_h, 1, na, 1, nr, 1, nspins)
    1220          160 :                   CALL reallocate(tau_s, 1, na, 1, nr, 1, nspins)
    1221              : 
    1222              :                   ! The one-center density matrices are already globally reduced. Distribute the
    1223              :                   ! overlap work by target atom so that every rank constructs only its model rows.
    1224          412 :                   DO iat = 1, natom
    1225          252 :                      source_atom = atom_list(iat)
    1226          252 :                      rho_atom => my_rho_atom_set(source_atom)
    1227          252 :                      NULLIFY (r_h, r_s, dr_h, dr_s, r_h_d, r_s_d)
    1228              :                      CALL get_rho_atom(rho_atom=rho_atom, rho_rad_h=r_h, rho_rad_s=r_s, &
    1229              :                                        drho_rad_h=dr_h, drho_rad_s=dr_s, &
    1230          252 :                                        rho_rad_h_d=r_h_d, rho_rad_s_d=r_s_d)
    1231       238104 :                      rho_h = 0.0_dp
    1232       238104 :                      rho_s = 0.0_dp
    1233      1159704 :                      drho_h = 0.0_dp
    1234      1159704 :                      drho_s = 0.0_dp
    1235          252 :                      CALL calc_tau_atom(tau_h, tau_s, rho_atom, tau_basis_cache, nspins)
    1236         7452 :                      DO ir = 1, nr
    1237              :                         CALL calc_rho_angular(grid_atom, harmonics, nspins, .TRUE., &
    1238              :                                               ir, r_h, r_s, rho_h, rho_s, dr_h, dr_s, &
    1239         7452 :                                               r_h_d, r_s_d, drho_h, drho_s)
    1240              :                      END DO
    1241              : 
    1242              :                      cross_cutoff = gapw_atom_grid_support_radius( &
    1243          252 :                                     grid_atom, rho_h, rho_s, drho_h, drho_s, tau_h, tau_s)
    1244          252 :                      IF (cross_cutoff <= 0.0_dp) CYCLE
    1245          228 :                      composite_cross_cutoff_max = MAX(composite_cross_cutoff_max, cross_cutoff)
    1246          228 :                      image_shell = 0
    1247          912 :                      DO idir = 1, 3
    1248          912 :                         IF (cell%perd(idir) == 1) THEN
    1249              :                            image_shell(idir) = CEILING( &
    1250         2544 :                                                cross_cutoff*SQRT(SUM(cell%h_inv(idir, :)**2))) + 1
    1251              :                         END IF
    1252              :                      END DO
    1253              : 
    1254              : !$OMP PARALLEL DO DEFAULT(NONE) SCHEDULE(STATIC) &
    1255              : !$OMP PRIVATE(image_lower, image_upper, composite_row, cross_density, cross_density_spatial, &
    1256              : !$OMP         cross_displacement, cross_grad, cross_grad_spatial, cross_kin, &
    1257              : !$OMP         cross_kin_spatial, fractional, idir, image_i1, image_i2, image_i3, jdir, &
    1258              : !$OMP         image_shift, image_translation, target_atom) &
    1259              : !$OMP SHARED(cell, composite_cross_density, composite_cross_grad, composite_cross_kin, &
    1260              : !$OMP        composite_grid_atom, composite_grid_coords, composite_nflat, cross_cutoff, &
    1261              : !$OMP        drho_h, drho_s, grid_atom, harmonics, image_shell, lsd, nspins, &
    1262              : !$OMP        particle_set, rho_h, rho_s, source_atom, tau_h, tau_s, &
    1263          412 : !$OMP        use_atom_composite_density, use_atom_composite_gradient, use_atom_composite_tau)
    1264              :                      DO composite_row = 1, composite_nflat
    1265              :                         target_atom = composite_grid_atom(composite_row)
    1266              :                         fractional = 0.0_dp
    1267              :                         DO idir = 1, 3
    1268              :                            DO jdir = 1, 3
    1269              :                               fractional(idir) = fractional(idir) + cell%h_inv(idir, jdir)* &
    1270              :                                                  (composite_grid_coords(jdir, composite_row) - &
    1271              :                                                   particle_set(source_atom)%r(jdir))
    1272              :                            END DO
    1273              :                         END DO
    1274              :                         CALL atom_grid_image_bounds(cell, fractional, cross_cutoff, image_shell, &
    1275              :                                                     image_lower, image_upper)
    1276              :                         DO image_i3 = image_lower(3), image_upper(3)
    1277              :                            DO image_i2 = image_lower(2), image_upper(2)
    1278              :                               DO image_i1 = image_lower(1), image_upper(1)
    1279              :                                  image_shift = [image_i1, image_i2, image_i3]
    1280              :                                  IF (target_atom == source_atom .AND. &
    1281              :                                      ALL(image_shift == 0)) CYCLE
    1282              :                                  image_translation = MATMUL( &
    1283              :                                                      cell%hmat, REAL(image_shift, dp))
    1284              :                                  cross_displacement = composite_grid_coords(:, composite_row) - &
    1285              :                                                       particle_set(source_atom)%r - &
    1286              :                                                       image_translation
    1287              :                                  IF (SQRT(SUM(cross_displacement**2)) > cross_cutoff) CYCLE
    1288              :                                  CALL interpolate_gapw_atom_grid_fields( &
    1289              :                                     grid_atom, harmonics, cross_displacement, cross_cutoff, nspins, &
    1290              :                                     rho_h, rho_s, drho_h, drho_s, tau_h, tau_s, &
    1291              :                                     cross_density, cross_grad, cross_kin, cross_density_spatial, &
    1292              :                                     cross_grad_spatial, cross_kin_spatial, calculate_spatial=.FALSE.)
    1293              :                                  IF (lsd) THEN
    1294              :                                     IF (use_atom_composite_density) THEN
    1295              :                                        composite_cross_density(composite_row, 1:2) = &
    1296              :                                           composite_cross_density(composite_row, 1:2) + &
    1297              :                                           cross_density(1:2)
    1298              :                                     END IF
    1299              :                                     IF (use_atom_composite_gradient) THEN
    1300              :                                        composite_cross_grad(composite_row, :, 1:2) = &
    1301              :                                           composite_cross_grad(composite_row, :, 1:2) + &
    1302              :                                           cross_grad(:, 1:2)
    1303              :                                     END IF
    1304              :                                     IF (use_atom_composite_tau) THEN
    1305              :                                        composite_cross_kin(composite_row, 1:2) = &
    1306              :                                           composite_cross_kin(composite_row, 1:2) + cross_kin(1:2)
    1307              :                                     END IF
    1308              :                                  ELSE
    1309              :                                     IF (use_atom_composite_density) THEN
    1310              :                                        composite_cross_density(composite_row, :) = &
    1311              :                                           composite_cross_density(composite_row, :) + &
    1312              :                                           0.5_dp*cross_density(1)
    1313              :                                     END IF
    1314              :                                     IF (use_atom_composite_gradient) THEN
    1315              :                                        DO idir = 1, 3
    1316              :                                           composite_cross_grad(composite_row, idir, :) = &
    1317              :                                              composite_cross_grad(composite_row, idir, :) + &
    1318              :                                              0.5_dp*cross_grad(idir, 1)
    1319              :                                        END DO
    1320              :                                     END IF
    1321              :                                     IF (use_atom_composite_tau) THEN
    1322              :                                        composite_cross_kin(composite_row, :) = &
    1323              :                                           composite_cross_kin(composite_row, :) + &
    1324              :                                           0.5_dp*cross_kin(1)
    1325              :                                     END IF
    1326              :                                  END IF
    1327              :                               END DO
    1328              :                            END DO
    1329              :                         END DO
    1330              :                      END DO
    1331              : !$OMP END PARALLEL DO
    1332              :                   END DO
    1333              : 
    1334          452 :                   CALL release_tau_basis_cache(tau_basis_cache)
    1335              :                END DO
    1336              :             END IF
    1337              : 
    1338          254 :             IF (native_grid_diagnostics) THEN
    1339       119570 :                composite_cross_density_max = MAXVAL(ABS(composite_cross_density))
    1340       358710 :                composite_cross_grad_max = MAXVAL(ABS(composite_cross_grad))
    1341       119570 :                composite_cross_kin_max = MAXVAL(ABS(composite_cross_kin))
    1342           30 :                CALL para_env%max(composite_cross_cutoff_max)
    1343           30 :                CALL para_env%max(composite_cross_density_max)
    1344           30 :                CALL para_env%max(composite_cross_grad_max)
    1345           30 :                CALL para_env%max(composite_cross_kin_max)
    1346           30 :                iw = cp_logger_get_default_io_unit()
    1347           30 :                IF (iw > 0) THEN
    1348              :                   WRITE (UNIT=iw, FMT="(T2,A,4(1X,ES20.12))") &
    1349           15 :                      "SKALA_GPW| Atom-composite cross support/maxima", &
    1350           15 :                      composite_cross_cutoff_max, composite_cross_density_max, &
    1351           30 :                      composite_cross_grad_max, composite_cross_kin_max
    1352              :                END IF
    1353              :             END IF
    1354       552114 :             composite_density(:, :) = composite_density(:, :) + composite_cross_density(:, :)
    1355      1656342 :             composite_grad(:, :, :) = composite_grad(:, :, :) + composite_cross_grad(:, :, :)
    1356       552114 :             composite_kin(:, :) = composite_kin(:, :) + composite_cross_kin(:, :)
    1357          254 :             DEALLOCATE (composite_cross_density, composite_cross_grad, composite_cross_kin)
    1358              : 
    1359       275930 :             CPASSERT(ALL(composite_grid_weights >= 0.0_dp))
    1360              :             atom_composite_nelec = SUM(composite_grid_weights* &
    1361       275930 :                                        (composite_density(:, 1) + composite_density(:, 2)))
    1362          254 :             CALL para_env%sum(atom_composite_nelec)
    1363          254 :             IF (atom_composite_reference .AND. my_calculate_forces) THEN
    1364              :                CALL skala_gapw_atom_composite_energy( &
    1365              :                   my_xc_section, para_env, composite_density, composite_grad, composite_kin, &
    1366              :                   composite_grid_coords, composite_grid_weights, composite_atomic_grid_weights, &
    1367              :                   composite_local_grid_sizes, composite_local_atom_coords, atom_composite_exc, &
    1368              :                   composite_density_grad, composite_grad_grad, composite_kin_grad, &
    1369              :                   composite_grid_coord_grad, composite_grid_weight_grad, &
    1370           58 :                   composite_atomic_grid_weight_grad, composite_atom_coord_grad)
    1371            0 :                ALLOCATE (composite_cross_force(3, SIZE(particle_set)), &
    1372            0 :                          composite_explicit_force(3, SIZE(particle_set)), &
    1373            0 :                          composite_grid_coord_force(3, SIZE(particle_set)), &
    1374            0 :                          composite_model_atom_force(3, SIZE(particle_set)), &
    1375            0 :                          composite_moving_smooth_force(3, SIZE(particle_set)), &
    1376            0 :                          composite_nlcc_center_force(3, SIZE(particle_set)), &
    1377            0 :                          composite_nlcc_target_force(3, SIZE(particle_set)), &
    1378            0 :                          composite_partition_force(3, SIZE(particle_set)), &
    1379            0 :                          composite_partition_included(SIZE(particle_set)), &
    1380            0 :                          composite_partition_datom(3, SIZE(particle_set), SIZE(particle_set)), &
    1381          986 :                          composite_partition_dstrain(3, 3, SIZE(particle_set)))
    1382           58 :                composite_cross_force = 0.0_dp
    1383           58 :                composite_cross_image_virial = 0.0_dp
    1384           58 :                composite_model_atom_force = 0.0_dp
    1385           58 :                composite_grid_coord_force = 0.0_dp
    1386           58 :                composite_moving_smooth_force = 0.0_dp
    1387           58 :                composite_nlcc_center_force = 0.0_dp
    1388           58 :                composite_nlcc_target_force = 0.0_dp
    1389           58 :                composite_partition_force = 0.0_dp
    1390           58 :                composite_explicit_virial = 0.0_dp
    1391           58 :                composite_feature_virial = 0.0_dp
    1392           58 :                composite_interpolation_virial = 0.0_dp
    1393           58 :                composite_partition_strain_virial = 0.0_dp
    1394              : !$OMP PARALLEL DO IF (image_partition_atom_composite) SCHEDULE(STATIC) DEFAULT(NONE) &
    1395              : !$OMP PRIVATE(composite_local_atom, composite_row, composite_smooth_gradient_value, &
    1396              : !$OMP         iatom, idir, ispin, jdir) &
    1397              : !$OMP SHARED(cell, composite_atom_end, composite_atom_start, composite_grad_grad, &
    1398              : !$OMP        composite_grid_coords, composite_local_atoms, composite_local_natom, &
    1399              : !$OMP        composite_smooth_drho, composite_smooth_drhoa, composite_smooth_drhob, &
    1400              : !$OMP        image_partition_atom_composite, lsd, smooth_rho_r) &
    1401           58 : !$OMP REDUCTION(+:composite_feature_virial)
    1402              :                DO composite_local_atom = 1, composite_local_natom
    1403              :                   iatom = composite_local_atoms(composite_local_atom)
    1404              :                   DO composite_row = composite_atom_start(iatom), composite_atom_end(iatom)
    1405              :                      IF (lsd) THEN
    1406              :                         DO jdir = 1, 3
    1407              :                            composite_smooth_gradient_value(jdir, 1) = &
    1408              :                               interpolate_native_grid( &
    1409              :                               composite_smooth_drhoa(jdir)%array, smooth_rho_r(1)%pw_grid, &
    1410              :                               cell, composite_grid_coords(:, composite_row), &
    1411              :                               image_partition_atom_composite)
    1412              :                            composite_smooth_gradient_value(jdir, 2) = &
    1413              :                               interpolate_native_grid( &
    1414              :                               composite_smooth_drhob(jdir)%array, smooth_rho_r(1)%pw_grid, &
    1415              :                               cell, composite_grid_coords(:, composite_row), &
    1416              :                               image_partition_atom_composite)
    1417              :                         END DO
    1418              :                      ELSE
    1419              :                         DO jdir = 1, 3
    1420              :                            composite_smooth_gradient_value(jdir, :) = 0.5_dp* &
    1421              :                                                                       interpolate_native_grid( &
    1422              :                                                                       composite_smooth_drho(jdir)%array, smooth_rho_r(1)%pw_grid, &
    1423              :                                                                       cell, composite_grid_coords(:, composite_row), &
    1424              :                                                                       image_partition_atom_composite)
    1425              :                         END DO
    1426              :                      END IF
    1427              :                      DO ispin = 1, 2
    1428              :                         DO idir = 1, 3
    1429              :                            DO jdir = 1, 3
    1430              :                               composite_feature_virial(jdir, idir) = &
    1431              :                                  composite_feature_virial(jdir, idir) - &
    1432              :                                  composite_grad_grad(composite_row, idir, ispin)* &
    1433              :                                  composite_smooth_gradient_value(jdir, ispin)
    1434              :                            END DO
    1435              :                         END DO
    1436              :                      END DO
    1437              :                   END DO
    1438              :                END DO
    1439              : !$OMP END PARALLEL DO
    1440              : !$OMP PARALLEL IF (image_partition_atom_composite) DEFAULT(NONE) &
    1441              : !$OMP PRIVATE(composite_local_atom, composite_row, gth_potential, iatom, idir, ispin, jdir, &
    1442              : !$OMP         nlcc_density, nlcc_gradient, nlcc_hessian, nlcc_spatial_derivative, &
    1443              : !$OMP         nlcc_spin_factor, partition_adjoint, composite_nlcc_center_force_local, &
    1444              : !$OMP         composite_partition_force_local, local_partition_datom, local_partition_dstrain, &
    1445              : !$OMP         local_partition_weight, sgp_potential, source_atom, &
    1446              : !$OMP         composite_partition_image_coords, composite_partition_target_image, &
    1447              : !$OMP         spatial_derivative, target_atom, target_partition_adjoint) &
    1448              : !$OMP REDUCTION(+:composite_interpolation_virial, composite_partition_strain_virial) &
    1449              : !$OMP SHARED(cell, composite_atom_coord_grad, composite_atom_coords, composite_atom_end, &
    1450              : !$OMP        composite_atom_kind, composite_atom_start, composite_atomic_grid_weight_grad, &
    1451              : !$OMP        composite_atomic_grid_weights, composite_base_grid_weights, composite_density_grad, &
    1452              : !$OMP        composite_grad_grad, composite_grid_coord_force, composite_grid_coord_grad, &
    1453              : !$OMP        composite_grid_coords, composite_grid_weight_grad, composite_image_periodicity, &
    1454              : !$OMP        composite_kin_grad, composite_local_atoms, composite_local_natom, &
    1455              : !$OMP        composite_model_atom_force, composite_moving_smooth_force, &
    1456              : !$OMP        composite_nlcc_center_force, composite_nlcc_target_force, composite_partition_datom, &
    1457              : !$OMP        composite_partition_dstrain, composite_partition_force, composite_partition_included, &
    1458              : !$OMP        composite_partition_weights, composite_smooth_drho, composite_smooth_drhoa, &
    1459              : !$OMP        composite_smooth_drhob, composite_smooth_rho, composite_smooth_rhoa, &
    1460              : !$OMP        composite_smooth_rhob, composite_smooth_tau, composite_smooth_tau_a, &
    1461              : !$OMP        composite_smooth_tau_b, image_partition_atom_composite, lsd, my_kind_set, nlcc, &
    1462           58 : !$OMP        particle_set, smooth_rho_r)
    1463              :                ALLOCATE (composite_nlcc_center_force_local(3, SIZE(particle_set)), &
    1464              :                          composite_partition_force_local(3, SIZE(particle_set)), &
    1465              :                          local_partition_datom(3, SIZE(particle_set)))
    1466              :                composite_nlcc_center_force_local = 0.0_dp
    1467              :                composite_partition_force_local = 0.0_dp
    1468              : !$OMP DO SCHEDULE(DYNAMIC)
    1469              :                DO composite_local_atom = 1, composite_local_natom
    1470              :                   iatom = composite_local_atoms(composite_local_atom)
    1471              :                   composite_model_atom_force(:, iatom) = &
    1472              :                      composite_atom_coord_grad(:, composite_local_atom)
    1473              :                   IF (image_partition_atom_composite) THEN
    1474              :                      CALL build_periodic_atom_image_layout( &
    1475              :                         composite_atom_coords, cell, iatom, composite_image_periodicity, &
    1476              :                         composite_partition_image_coords, composite_partition_target_image)
    1477              :                   END IF
    1478              :                   DO composite_row = composite_atom_start(iatom), composite_atom_end(iatom)
    1479              :                      composite_grid_coord_force(:, iatom) = &
    1480              :                         composite_grid_coord_force(:, iatom) + &
    1481              :                         composite_grid_coord_grad(:, composite_row)
    1482              :                      IF (lsd) THEN
    1483              :                         spatial_derivative = &
    1484              :                            composite_density_grad(composite_row, 1)* &
    1485              :                            interpolate_native_grid_gradient( &
    1486              :                            composite_smooth_rhoa, smooth_rho_r(1)%pw_grid, cell, &
    1487              :                            composite_grid_coords(:, composite_row), &
    1488              :                            image_partition_atom_composite) + &
    1489              :                            composite_density_grad(composite_row, 2)* &
    1490              :                            interpolate_native_grid_gradient( &
    1491              :                            composite_smooth_rhob, smooth_rho_r(1)%pw_grid, cell, &
    1492              :                            composite_grid_coords(:, composite_row), &
    1493              :                            image_partition_atom_composite) + &
    1494              :                            composite_kin_grad(composite_row, 1)* &
    1495              :                            interpolate_native_grid_gradient( &
    1496              :                            composite_smooth_tau_a, smooth_rho_r(1)%pw_grid, cell, &
    1497              :                            composite_grid_coords(:, composite_row), &
    1498              :                            image_partition_atom_composite) + &
    1499              :                            composite_kin_grad(composite_row, 2)* &
    1500              :                            interpolate_native_grid_gradient( &
    1501              :                            composite_smooth_tau_b, smooth_rho_r(1)%pw_grid, cell, &
    1502              :                            composite_grid_coords(:, composite_row), &
    1503              :                            image_partition_atom_composite)
    1504              :                         DO idir = 1, 3
    1505              :                            spatial_derivative = spatial_derivative + &
    1506              :                                                 composite_grad_grad(composite_row, idir, 1)* &
    1507              :                                                 interpolate_native_grid_gradient( &
    1508              :                                                 composite_smooth_drhoa(idir)%array, &
    1509              :                                                 smooth_rho_r(1)%pw_grid, cell, &
    1510              :                                                 composite_grid_coords(:, composite_row), &
    1511              :                                                 image_partition_atom_composite) + &
    1512              :                                                 composite_grad_grad(composite_row, idir, 2)* &
    1513              :                                                 interpolate_native_grid_gradient( &
    1514              :                                                 composite_smooth_drhob(idir)%array, &
    1515              :                                                 smooth_rho_r(1)%pw_grid, cell, &
    1516              :                                                 composite_grid_coords(:, composite_row), &
    1517              :                                                 image_partition_atom_composite)
    1518              :                         END DO
    1519              :                      ELSE
    1520              :                         spatial_derivative = 0.5_dp*SUM( &
    1521              :                                              composite_density_grad(composite_row, :))* &
    1522              :                                              interpolate_native_grid_gradient( &
    1523              :                                              composite_smooth_rho, smooth_rho_r(1)%pw_grid, cell, &
    1524              :                                              composite_grid_coords(:, composite_row), &
    1525              :                                              image_partition_atom_composite) + &
    1526              :                                              0.5_dp*SUM(composite_kin_grad(composite_row, :))* &
    1527              :                                              interpolate_native_grid_gradient( &
    1528              :                                              composite_smooth_tau, smooth_rho_r(1)%pw_grid, cell, &
    1529              :                                              composite_grid_coords(:, composite_row), &
    1530              :                                              image_partition_atom_composite)
    1531              :                         DO idir = 1, 3
    1532              :                            spatial_derivative = spatial_derivative + 0.5_dp*SUM( &
    1533              :                                                 composite_grad_grad(composite_row, idir, :))* &
    1534              :                                                 interpolate_native_grid_gradient( &
    1535              :                                                 composite_smooth_drho(idir)%array, &
    1536              :                                                 smooth_rho_r(1)%pw_grid, &
    1537              :                                                 cell, composite_grid_coords(:, composite_row), &
    1538              :                                                 image_partition_atom_composite)
    1539              :                         END DO
    1540              :                      END IF
    1541              :                      DO idir = 1, 3
    1542              :                         DO jdir = 1, 3
    1543              :                            composite_interpolation_virial(idir, jdir) = &
    1544              :                               composite_interpolation_virial(idir, jdir) + &
    1545              :                               spatial_derivative(idir)*( &
    1546              :                               composite_grid_coords(jdir, composite_row) - &
    1547              :                               particle_set(iatom)%r(jdir))
    1548              :                         END DO
    1549              :                      END DO
    1550              :                      composite_moving_smooth_force(:, iatom) = &
    1551              :                         composite_moving_smooth_force(:, iatom) + spatial_derivative
    1552              :                      IF (nlcc) THEN
    1553              :                         nlcc_spin_factor = MERGE(1.0_dp, 0.5_dp, lsd)
    1554              :                         DO source_atom = 1, SIZE(particle_set)
    1555              :                            NULLIFY (gth_potential, sgp_potential)
    1556              :                            CALL get_qs_kind(my_kind_set(composite_atom_kind(source_atom)), &
    1557              :                                             gth_potential=gth_potential, &
    1558              :                                             sgp_potential=sgp_potential)
    1559              :                            CALL evaluate_nlcc_primitive_fields( &
    1560              :                               composite_grid_coords(:, composite_row), &
    1561              :                               particle_set(source_atom)%r, gth_potential, sgp_potential, &
    1562              :                               nlcc_density, nlcc_gradient, nlcc_hessian)
    1563              :                            nlcc_spatial_derivative = 0.0_dp
    1564              :                            DO ispin = 1, 2
    1565              :                               nlcc_spatial_derivative = nlcc_spatial_derivative + &
    1566              :                                                         nlcc_spin_factor*composite_density_grad(composite_row, ispin)* &
    1567              :                                                         nlcc_gradient
    1568              :                               DO idir = 1, 3
    1569              :                                  DO jdir = 1, 3
    1570              :                                     nlcc_spatial_derivative(jdir) = &
    1571              :                                        nlcc_spatial_derivative(jdir) + nlcc_spin_factor* &
    1572              :                                        composite_grad_grad(composite_row, idir, ispin)* &
    1573              :                                        nlcc_hessian(idir, jdir)
    1574              :                                  END DO
    1575              :                               END DO
    1576              :                            END DO
    1577              :                            composite_nlcc_target_force(:, iatom) = &
    1578              :                               composite_nlcc_target_force(:, iatom) + nlcc_spatial_derivative
    1579              :                            composite_nlcc_center_force_local(:, source_atom) = &
    1580              :                               composite_nlcc_center_force_local(:, source_atom) - nlcc_spatial_derivative
    1581              :                         END DO
    1582              :                      END IF
    1583              :                      IF (image_partition_atom_composite) THEN
    1584              :                         CALL periodic_atom_image_partition_from_layout( &
    1585              :                            composite_grid_coords(:, composite_row), composite_partition_image_coords, &
    1586              :                            composite_partition_target_image, local_partition_weight, local_partition_datom, &
    1587              :                            local_partition_dstrain)
    1588              :                         target_partition_adjoint = composite_base_grid_weights(composite_row)* &
    1589              :                                                    composite_grid_weight_grad(composite_row)
    1590              :                         DO target_atom = 1, SIZE(particle_set)
    1591              :                            composite_partition_force_local(:, target_atom) = &
    1592              :                               composite_partition_force_local(:, target_atom) + &
    1593              :                               target_partition_adjoint*local_partition_datom(:, target_atom)
    1594              :                         END DO
    1595              :                         composite_partition_force_local(:, iatom) = &
    1596              :                            composite_partition_force_local(:, iatom) - target_partition_adjoint* &
    1597              :                            SUM(local_partition_datom, DIM=2)
    1598              :                         composite_partition_strain_virial = &
    1599              :                            composite_partition_strain_virial - target_partition_adjoint* &
    1600              :                            local_partition_dstrain
    1601              :                      ELSE
    1602              :                         CALL skala_gpw_smooth_partition_derivatives( &
    1603              :                            composite_grid_coords(:, composite_row), composite_atom_coords, cell, &
    1604              :                            composite_partition_weights, composite_partition_included, &
    1605              :                            composite_partition_datom, composite_partition_dstrain)
    1606              :                         partition_adjoint = composite_grid_weight_grad(composite_row)* &
    1607              :                                             composite_atomic_grid_weights(composite_row)
    1608              :                         DO target_atom = 1, SIZE(particle_set)
    1609              :                            composite_partition_force_local(:, target_atom) = &
    1610              :                               composite_partition_force_local(:, target_atom) + &
    1611              :                               partition_adjoint* &
    1612              :                               composite_partition_datom(:, target_atom, iatom)
    1613              :                         END DO
    1614              :                         composite_partition_force_local(:, iatom) = &
    1615              :                            composite_partition_force_local(:, iatom) - partition_adjoint* &
    1616              :                            SUM(composite_partition_datom(:, :, iatom), DIM=2)
    1617              :                      END IF
    1618              :                   END DO
    1619              :                END DO
    1620              : !$OMP END DO
    1621              : !$OMP CRITICAL(skala_atom_composite_force_reduction)
    1622              :                composite_nlcc_center_force(:, :) = composite_nlcc_center_force(:, :) + &
    1623              :                                                    composite_nlcc_center_force_local
    1624              :                composite_partition_force(:, :) = composite_partition_force(:, :) + &
    1625              :                                                  composite_partition_force_local
    1626              : !$OMP END CRITICAL(skala_atom_composite_force_reduction)
    1627              :                DEALLOCATE (composite_nlcc_center_force_local, composite_partition_force_local, &
    1628           58 :                            local_partition_datom)
    1629              : !$OMP END PARALLEL
    1630              :                ! The target atom grids can overlap augmentation regions of other atoms
    1631              :                ! and periodic images. Differentiate the same discrete interpolation used
    1632              :                ! in the forward composite fields, including the explicit image strain.
    1633           58 :                IF (.NOT. direct_valence_atom_composite) THEN
    1634           90 :                   DO ikind = 1, SIZE(atomic_kind_set)
    1635           54 :                      CALL get_atomic_kind(atomic_kind_set(ikind), atom_list=atom_list, natom=natom)
    1636           54 :                      NULLIFY (gth_potential, sgp_potential)
    1637              :                      CALL get_qs_kind(my_kind_set(ikind), paw_atom=paw_atom, &
    1638              :                                       gth_potential=gth_potential, harmonics=harmonics, &
    1639              :                                       grid_atom=grid_atom, sgp_potential=sgp_potential, &
    1640           54 :                                       zatom=zatom, zeff=zeff)
    1641           54 :                      CALL get_qs_kind(my_kind_set(ikind), basis_set=basis_1c, basis_type="GAPW_1C")
    1642           66 :                      IF (.NOT. native_skala_uses_one_center_kind( &
    1643              :                          paw_atom, gapw_representation, &
    1644              :                          ASSOCIATED(gth_potential) .OR. ASSOCIATED(sgp_potential), &
    1645              :                          zeff, zatom)) CYCLE
    1646              : 
    1647           52 :                      nr = grid_atom%nr
    1648           52 :                      na = grid_atom%ng_sphere
    1649           52 :                      CALL create_tau_basis_cache(tau_basis_cache, grid_atom, basis_1c, harmonics)
    1650           52 :                      CALL reallocate(rho_h, 1, na, 1, nr, 1, nspins)
    1651           52 :                      CALL reallocate(rho_s, 1, na, 1, nr, 1, nspins)
    1652           52 :                      CALL reallocate(drho_h, 1, 4, 1, na, 1, nr, 1, nspins)
    1653           52 :                      CALL reallocate(drho_s, 1, 4, 1, na, 1, nr, 1, nspins)
    1654           52 :                      CALL reallocate(tau_h, 1, na, 1, nr, 1, nspins)
    1655           52 :                      CALL reallocate(tau_s, 1, na, 1, nr, 1, nspins)
    1656              : 
    1657          122 :                      DO iat = 1, natom
    1658           70 :                         source_atom = atom_list(iat)
    1659           70 :                         rho_atom => my_rho_atom_set(source_atom)
    1660           70 :                         NULLIFY (r_h, r_s, dr_h, dr_s, r_h_d, r_s_d)
    1661              :                         CALL get_rho_atom(rho_atom=rho_atom, rho_rad_h=r_h, rho_rad_s=r_s, &
    1662              :                                           drho_rad_h=dr_h, drho_rad_s=dr_s, &
    1663           70 :                                           rho_rad_h_d=r_h_d, rho_rad_s_d=r_s_d)
    1664       102140 :                         rho_h = 0.0_dp
    1665       102140 :                         rho_s = 0.0_dp
    1666       500220 :                         drho_h = 0.0_dp
    1667       500220 :                         drho_s = 0.0_dp
    1668           70 :                         CALL calc_tau_atom(tau_h, tau_s, rho_atom, tau_basis_cache, nspins)
    1669         2550 :                         DO ir = 1, nr
    1670              :                            CALL calc_rho_angular(grid_atom, harmonics, nspins, .TRUE., &
    1671              :                                                  ir, r_h, r_s, rho_h, rho_s, dr_h, dr_s, &
    1672         2550 :                                                  r_h_d, r_s_d, drho_h, drho_s)
    1673              :                         END DO
    1674              : 
    1675              :                         cross_cutoff = gapw_atom_grid_support_radius( &
    1676           70 :                                        grid_atom, rho_h, rho_s, drho_h, drho_s, tau_h, tau_s)
    1677           70 :                         IF (cross_cutoff <= 0.0_dp) CYCLE
    1678           58 :                         image_shell = 0
    1679          232 :                         DO idir = 1, 3
    1680          232 :                            IF (cell%perd(idir) == 1) THEN
    1681              :                               image_shell(idir) = CEILING( &
    1682          600 :                                                   cross_cutoff*SQRT(SUM(cell%h_inv(idir, :)**2))) + 1
    1683              :                            END IF
    1684              :                         END DO
    1685              : 
    1686              : !$OMP PARALLEL DEFAULT(NONE) &
    1687              : !$OMP PRIVATE(image_lower, image_upper, composite_cross_force_local, composite_cross_image_virial_local, &
    1688              : !$OMP         composite_row, cross_density, cross_density_adjoint, cross_density_spatial, &
    1689              : !$OMP         cross_displacement, cross_grad, cross_grad_adjoint, cross_grad_spatial, &
    1690              : !$OMP         cross_kin, cross_kin_adjoint, cross_kin_spatial, cross_spatial_derivative, &
    1691              : !$OMP         fractional, idir, image_i1, image_i2, image_i3, image_shift, image_translation, &
    1692              : !$OMP         ispin, jdir, target_atom) &
    1693              : !$OMP SHARED(cell, composite_cross_force, composite_cross_image_virial, &
    1694              : !$OMP        composite_density_grad, composite_grad_grad, composite_grid_atom, &
    1695              : !$OMP        composite_grid_coords, composite_kin_grad, composite_nflat, cross_cutoff, &
    1696              : !$OMP        drho_h, drho_s, grid_atom, harmonics, image_shell, lsd, nspins, &
    1697              : !$OMP        particle_set, rho_h, rho_s, source_atom, tau_h, tau_s, &
    1698          122 : !$OMP        use_atom_composite_density, use_atom_composite_gradient, use_atom_composite_tau)
    1699              :                         ALLOCATE (composite_cross_force_local(3, SIZE(particle_set)))
    1700              :                         composite_cross_force_local = 0.0_dp
    1701              :                         composite_cross_image_virial_local = 0.0_dp
    1702              : !$OMP DO SCHEDULE(STATIC)
    1703              :                         DO composite_row = 1, composite_nflat
    1704              :                            target_atom = composite_grid_atom(composite_row)
    1705              :                            IF (lsd) THEN
    1706              :                               cross_density_adjoint = 0.0_dp
    1707              :                               cross_grad_adjoint = 0.0_dp
    1708              :                               cross_kin_adjoint = 0.0_dp
    1709              :                               IF (use_atom_composite_density) THEN
    1710              :                                  cross_density_adjoint(1:2) = &
    1711              :                                     composite_density_grad(composite_row, 1:2)
    1712              :                               END IF
    1713              :                               IF (use_atom_composite_gradient) THEN
    1714              :                                  cross_grad_adjoint(:, 1:2) = &
    1715              :                                     composite_grad_grad(composite_row, :, 1:2)
    1716              :                               END IF
    1717              :                               IF (use_atom_composite_tau) THEN
    1718              :                                  cross_kin_adjoint(1:2) = &
    1719              :                                     composite_kin_grad(composite_row, 1:2)
    1720              :                               END IF
    1721              :                            ELSE
    1722              :                               cross_density_adjoint = 0.0_dp
    1723              :                               cross_grad_adjoint = 0.0_dp
    1724              :                               cross_kin_adjoint = 0.0_dp
    1725              :                               IF (use_atom_composite_density) THEN
    1726              :                                  cross_density_adjoint(1) = 0.5_dp* &
    1727              :                                                             SUM(composite_density_grad(composite_row, :))
    1728              :                               END IF
    1729              :                               IF (use_atom_composite_gradient) THEN
    1730              :                                  DO idir = 1, 3
    1731              :                                     cross_grad_adjoint(idir, 1) = 0.5_dp* &
    1732              :                                                                   SUM(composite_grad_grad(composite_row, idir, :))
    1733              :                                  END DO
    1734              :                               END IF
    1735              :                               IF (use_atom_composite_tau) THEN
    1736              :                                  cross_kin_adjoint(1) = 0.5_dp* &
    1737              :                                                         SUM(composite_kin_grad(composite_row, :))
    1738              :                               END IF
    1739              :                            END IF
    1740              : 
    1741              :                            fractional = 0.0_dp
    1742              :                            DO idir = 1, 3
    1743              :                               DO jdir = 1, 3
    1744              :                                  fractional(idir) = fractional(idir) + cell%h_inv(idir, jdir)* &
    1745              :                                                     (composite_grid_coords(jdir, composite_row) - &
    1746              :                                                      particle_set(source_atom)%r(jdir))
    1747              :                               END DO
    1748              :                            END DO
    1749              :                            CALL atom_grid_image_bounds(cell, fractional, cross_cutoff, image_shell, &
    1750              :                                                        image_lower, image_upper)
    1751              :                            DO image_i3 = image_lower(3), image_upper(3)
    1752              :                               DO image_i2 = image_lower(2), image_upper(2)
    1753              :                                  DO image_i1 = image_lower(1), image_upper(1)
    1754              :                                     image_shift = [image_i1, image_i2, image_i3]
    1755              :                                     IF (target_atom == source_atom .AND. &
    1756              :                                         ALL(image_shift == 0)) CYCLE
    1757              :                                     image_translation = MATMUL( &
    1758              :                                                         cell%hmat, REAL(image_shift, dp))
    1759              :                                     cross_displacement = &
    1760              :                                        composite_grid_coords(:, composite_row) - &
    1761              :                                        particle_set(source_atom)%r - image_translation
    1762              :                                     IF (SQRT(SUM(cross_displacement**2)) > cross_cutoff) CYCLE
    1763              :                                     CALL interpolate_gapw_atom_grid_fields( &
    1764              :                                        grid_atom, harmonics, cross_displacement, cross_cutoff, &
    1765              :                                        nspins, rho_h, rho_s, drho_h, drho_s, tau_h, tau_s, &
    1766              :                                        cross_density, cross_grad, cross_kin, cross_density_spatial, &
    1767              :                                        cross_grad_spatial, cross_kin_spatial)
    1768              :                                     cross_spatial_derivative = 0.0_dp
    1769              :                                     DO ispin = 1, nspins
    1770              :                                        DO idir = 1, 3
    1771              :                                           cross_spatial_derivative(idir) = &
    1772              :                                              cross_spatial_derivative(idir) + &
    1773              :                                              cross_density_adjoint(ispin)* &
    1774              :                                              cross_density_spatial(idir, ispin) + &
    1775              :                                              cross_kin_adjoint(ispin)* &
    1776              :                                              cross_kin_spatial(idir, ispin)
    1777              :                                           DO jdir = 1, 3
    1778              :                                              cross_spatial_derivative(idir) = &
    1779              :                                                 cross_spatial_derivative(idir) + &
    1780              :                                                 cross_grad_adjoint(jdir, ispin)* &
    1781              :                                                 cross_grad_spatial(jdir, idir, ispin)
    1782              :                                           END DO
    1783              :                                        END DO
    1784              :                                     END DO
    1785              :                                     composite_cross_force_local(:, target_atom) = &
    1786              :                                        composite_cross_force_local(:, target_atom) + &
    1787              :                                        cross_spatial_derivative
    1788              :                                     composite_cross_force_local(:, source_atom) = &
    1789              :                                        composite_cross_force_local(:, source_atom) - &
    1790              :                                        cross_spatial_derivative
    1791              :                                     DO idir = 1, 3
    1792              :                                        DO jdir = 1, 3
    1793              :                                           composite_cross_image_virial_local(idir, jdir) = &
    1794              :                                              composite_cross_image_virial_local(idir, jdir) + &
    1795              :                                              cross_spatial_derivative(idir)*image_translation(jdir)
    1796              :                                        END DO
    1797              :                                     END DO
    1798              :                                  END DO
    1799              :                               END DO
    1800              :                            END DO
    1801              :                         END DO
    1802              : !$OMP END DO
    1803              : !$OMP CRITICAL(skala_atom_composite_cross_reduction)
    1804              :                         composite_cross_force(:, :) = &
    1805              :                            composite_cross_force(:, :) + composite_cross_force_local(:, :)
    1806              :                         composite_cross_image_virial = composite_cross_image_virial + &
    1807              :                                                        composite_cross_image_virial_local
    1808              : !$OMP END CRITICAL(skala_atom_composite_cross_reduction)
    1809              :                         DEALLOCATE (composite_cross_force_local)
    1810              : !$OMP END PARALLEL
    1811              :                      END DO
    1812          142 :                      CALL release_tau_basis_cache(tau_basis_cache)
    1813              :                   END DO
    1814              :                END IF
    1815              : 
    1816              :                composite_explicit_force(:, :) = composite_model_atom_force(:, :) + &
    1817              :                                                 composite_grid_coord_force(:, :) + &
    1818              :                                                 composite_moving_smooth_force(:, :) + &
    1819              :                                                 composite_cross_force(:, :) + &
    1820              :                                                 composite_nlcc_center_force(:, :) + &
    1821              :                                                 composite_nlcc_target_force(:, :) + &
    1822          522 :                                                 composite_partition_force(:, :)
    1823              :                ! CP2K stores +dE/dR in the electronic force components, while the
    1824              :                ! virial is -dE/dstrain. Model coordinates, atom-grid centers,
    1825              :                ! NLCC centers, and partition centers move affinely with their atoms.
    1826              :                ! The smooth-field interpolation force is excluded here: its affine
    1827              :                ! response is already in the PW stress and its non-affine local-grid
    1828              :                ! correction is composite_interpolation_virial.
    1829          174 :                DO iatom = 1, SIZE(particle_set)
    1830          522 :                   DO idir = 1, 3
    1831         1508 :                      DO jdir = 1, 3
    1832              :                         composite_explicit_virial(idir, jdir) = &
    1833              :                            composite_explicit_virial(idir, jdir) - ( &
    1834              :                            composite_model_atom_force(idir, iatom) + &
    1835              :                            composite_grid_coord_force(idir, iatom) + &
    1836              :                            composite_cross_force(idir, iatom) + &
    1837              :                            composite_nlcc_center_force(idir, iatom) + &
    1838              :                            composite_nlcc_target_force(idir, iatom) + &
    1839         1392 :                            composite_partition_force(idir, iatom))*particle_set(iatom)%r(jdir)
    1840              :                      END DO
    1841              :                   END DO
    1842              :                END DO
    1843              :                composite_explicit_virial = composite_explicit_virial + &
    1844              :                                            composite_partition_strain_virial + &
    1845          754 :                                            composite_cross_image_virial
    1846           58 :                IF (ASSOCIATED(force)) THEN
    1847          174 :                   DO iatom = 1, SIZE(particle_set)
    1848          116 :                      ikind = composite_atom_kind(iatom)
    1849          116 :                      iat = composite_atom_kind_index(iatom)
    1850          116 :                      CPASSERT(ikind > 0 .AND. iat > 0)
    1851              :                      force(ikind)%rho_elec(:, iat) = force(ikind)%rho_elec(:, iat) + &
    1852          522 :                                                      composite_explicit_force(:, iatom)
    1853              :                   END DO
    1854              :                END IF
    1855           58 :                IF (use_virial) THEN
    1856              :                   ! The local radial vectors of the atom-centered quadrature do not
    1857              :                   ! deform with the periodic cell. Correct the standard PW response,
    1858              :                   ! which follows fixed fractional coordinates, by the corresponding
    1859              :                   ! non-affine interpolation derivative.
    1860          624 :                   virial%pv_xc = composite_feature_virial - composite_interpolation_virial
    1861          624 :                   virial%pv_gapw = virial%pv_gapw + composite_explicit_virial
    1862          624 :                   virial%pv_virial = virial%pv_virial + composite_explicit_virial
    1863              :                END IF
    1864           58 :                IF (native_grid_diagnostics) THEN
    1865           14 :                   CALL para_env%sum(composite_cross_force)
    1866           14 :                   CALL para_env%sum(composite_cross_image_virial)
    1867           14 :                   CALL para_env%sum(composite_model_atom_force)
    1868           14 :                   CALL para_env%sum(composite_grid_coord_force)
    1869           14 :                   CALL para_env%sum(composite_moving_smooth_force)
    1870           14 :                   CALL para_env%sum(composite_nlcc_center_force)
    1871           14 :                   CALL para_env%sum(composite_nlcc_target_force)
    1872           14 :                   CALL para_env%sum(composite_partition_force)
    1873           14 :                   CALL para_env%sum(composite_explicit_force)
    1874           14 :                   CALL para_env%sum(composite_explicit_virial)
    1875           14 :                   CALL para_env%sum(composite_feature_virial)
    1876           14 :                   CALL para_env%sum(composite_interpolation_virial)
    1877           14 :                   iw = cp_logger_get_default_io_unit()
    1878           14 :                   IF (iw > 0) THEN
    1879           21 :                      DO iatom = 1, SIZE(particle_set)
    1880              :                         WRITE (UNIT=iw, FMT="(T2,A,1X,I0,3(1X,ES20.12))") &
    1881           14 :                            "SKALA_GPW| Atom-composite model-atom force", iatom, &
    1882           28 :                            composite_model_atom_force(:, iatom)
    1883              :                         WRITE (UNIT=iw, FMT="(T2,A,1X,I0,3(1X,ES20.12))") &
    1884           14 :                            "SKALA_GPW| Atom-composite grid-coordinate force", iatom, &
    1885           28 :                            composite_grid_coord_force(:, iatom)
    1886              :                         WRITE (UNIT=iw, FMT="(T2,A,1X,I0,3(1X,ES20.12))") &
    1887           14 :                            "SKALA_GPW| Atom-composite moving-smooth force", iatom, &
    1888           28 :                            composite_moving_smooth_force(:, iatom)
    1889              :                         WRITE (UNIT=iw, FMT="(T2,A,1X,I0,3(1X,ES20.12))") &
    1890           14 :                            "SKALA_GPW| Atom-composite cross-region force", iatom, &
    1891           28 :                            composite_cross_force(:, iatom)
    1892              :                         WRITE (UNIT=iw, FMT="(T2,A,1X,I0,3(1X,ES20.12))") &
    1893           14 :                            "SKALA_GPW| Atom-composite NLCC-center force", iatom, &
    1894           28 :                            composite_nlcc_center_force(:, iatom)
    1895              :                         WRITE (UNIT=iw, FMT="(T2,A,1X,I0,3(1X,ES20.12))") &
    1896           14 :                            "SKALA_GPW| Atom-composite NLCC-target force", iatom, &
    1897           28 :                            composite_nlcc_target_force(:, iatom)
    1898              :                         WRITE (UNIT=iw, FMT="(T2,A,1X,I0,3(1X,ES20.12))") &
    1899           14 :                            "SKALA_GPW| Atom-composite partition force", iatom, &
    1900           28 :                            composite_partition_force(:, iatom)
    1901              :                         WRITE (UNIT=iw, FMT="(T2,A,1X,I0,3(1X,ES20.12))") &
    1902           14 :                            "SKALA_GPW| Atom-composite explicit force", iatom, &
    1903           35 :                            composite_explicit_force(:, iatom)
    1904              :                      END DO
    1905              :                      WRITE (UNIT=iw, FMT="(T2,A)") &
    1906            7 :                         "SKALA_GPW| Atom-composite explicit virial"
    1907           28 :                      DO idir = 1, 3
    1908              :                         WRITE (UNIT=iw, FMT="(T2,A,1X,3ES20.10)") &
    1909           28 :                            "SKALA_GPW|", composite_explicit_virial(idir, :)
    1910              :                      END DO
    1911              :                      WRITE (UNIT=iw, FMT="(T2,A)") &
    1912            7 :                         "SKALA_GPW| Atom-composite cross-image virial"
    1913           28 :                      DO idir = 1, 3
    1914              :                         WRITE (UNIT=iw, FMT="(T2,A,1X,3ES20.10)") &
    1915           28 :                            "SKALA_GPW|", composite_cross_image_virial(idir, :)
    1916              :                      END DO
    1917              :                      WRITE (UNIT=iw, FMT="(T2,A)") &
    1918            7 :                         "SKALA_GPW| Atom-composite feature virial"
    1919           28 :                      DO idir = 1, 3
    1920              :                         WRITE (UNIT=iw, FMT="(T2,A,1X,3ES20.10)") &
    1921           28 :                            "SKALA_GPW|", composite_feature_virial(idir, :)
    1922              :                      END DO
    1923              :                      WRITE (UNIT=iw, FMT="(T2,A)") &
    1924            7 :                         "SKALA_GPW| Atom-composite interpolation virial"
    1925           28 :                      DO idir = 1, 3
    1926              :                         WRITE (UNIT=iw, FMT="(T2,A,1X,3ES20.10)") &
    1927           28 :                            "SKALA_GPW|", composite_interpolation_virial(idir, :)
    1928              :                      END DO
    1929              :                   END IF
    1930              :                END IF
    1931            0 :                DEALLOCATE (composite_atom_coord_grad, composite_atomic_grid_weight_grad, &
    1932            0 :                            composite_cross_force, &
    1933            0 :                            composite_explicit_force, composite_grid_coord_force, &
    1934            0 :                            composite_grid_coord_grad, composite_grid_weight_grad, &
    1935            0 :                            composite_model_atom_force, composite_moving_smooth_force, &
    1936            0 :                            composite_nlcc_center_force, &
    1937            0 :                            composite_nlcc_target_force, &
    1938            0 :                            composite_partition_datom, composite_partition_dstrain, &
    1939           58 :                            composite_partition_force, composite_partition_included)
    1940              :             ELSE
    1941              :                CALL skala_gapw_atom_composite_energy( &
    1942              :                   my_xc_section, para_env, composite_density, composite_grad, composite_kin, &
    1943              :                   composite_grid_coords, composite_grid_weights, composite_atomic_grid_weights, &
    1944              :                   composite_local_grid_sizes, composite_local_atom_coords, atom_composite_exc, &
    1945          196 :                   composite_density_grad, composite_grad_grad, composite_kin_grad)
    1946              :             END IF
    1947         1016 :             composite_pw_nflat = PRODUCT(smooth_rho_r(1)%pw_grid%npts)
    1948          254 :             adjoint_nchannels = MERGE(2, 1, lsd)
    1949            0 :             ALLOCATE (smooth_density_adjoint_storage(composite_pw_nflat, adjoint_nchannels), &
    1950            0 :                       smooth_grad_adjoint_storage(composite_pw_nflat, 3, adjoint_nchannels), &
    1951         2286 :                       smooth_kin_adjoint_storage(composite_pw_nflat, adjoint_nchannels))
    1952          254 :             smooth_density_adjoint_storage = 0.0_dp
    1953          254 :             smooth_grad_adjoint_storage = 0.0_dp
    1954          254 :             smooth_kin_adjoint_storage = 0.0_dp
    1955              :             CALL build_native_grid_adjoint_bins( &
    1956              :                smooth_rho_r(1)%pw_grid, cell, composite_grid_coords, &
    1957              :                image_partition_atom_composite, adjoint_tile_count, adjoint_bin_offsets, &
    1958          254 :                adjoint_bin_rows)
    1959          254 :             adjoint_nbins = SIZE(adjoint_bin_offsets) - 1
    1960              : !$OMP PARALLEL DO SCHEDULE(DYNAMIC) DEFAULT(NONE) &
    1961              : !$OMP PRIVATE(adjoint_entry, composite_row, composite_smooth_density_adjoint_value, &
    1962              : !$OMP         composite_smooth_gradient_adjoint_value, composite_smooth_kin_adjoint_value, &
    1963              : !$OMP         adjoint_tile_lower, adjoint_tile_upper, interpolation_stencil) &
    1964              : !$OMP SHARED(adjoint_bin_offsets, adjoint_bin_rows, adjoint_nbins, adjoint_nchannels, &
    1965              : !$OMP        adjoint_tile_count, cell, composite_density_grad, composite_grad_grad, &
    1966              : !$OMP        composite_grid_coords, composite_kin_grad, image_partition_atom_composite, lsd, &
    1967              : !$OMP        smooth_density_adjoint_storage, smooth_grad_adjoint_storage, &
    1968          254 : !$OMP        smooth_kin_adjoint_storage, smooth_rho_r, qs_env)
    1969              :             DO adjoint_bin = 1, adjoint_nbins
    1970              :                CALL native_grid_adjoint_tile_bounds( &
    1971              :                   smooth_rho_r(1)%pw_grid, adjoint_bin, adjoint_tile_count, &
    1972              :                   adjoint_tile_lower, adjoint_tile_upper)
    1973              :                DO adjoint_entry = adjoint_bin_offsets(adjoint_bin), &
    1974              :                   adjoint_bin_offsets(adjoint_bin + 1) - 1
    1975              :                   composite_row = adjoint_bin_rows(adjoint_entry)
    1976              :                   IF (.NOT. fetch_native_grid_stencil(qs_env%native_grid_cache, composite_row, &
    1977              :                                                       composite_grid_coords(:, composite_row), interpolation_stencil)) THEN
    1978              :                      CALL create_native_grid_interpolation_stencil( &
    1979              :                         interpolation_stencil, smooth_rho_r(1)%pw_grid, cell, &
    1980              :                         composite_grid_coords(:, composite_row), image_partition_atom_composite)
    1981              :                   END IF
    1982              :                   IF (lsd) THEN
    1983              :                      composite_smooth_density_adjoint_value = &
    1984              :                         composite_density_grad(composite_row, :)
    1985              :                      composite_smooth_gradient_adjoint_value = &
    1986              :                         composite_grad_grad(composite_row, :, :)
    1987              :                      composite_smooth_kin_adjoint_value = composite_kin_grad(composite_row, :)
    1988              :                   ELSE
    1989              :                      composite_smooth_density_adjoint_value = 0.0_dp
    1990              :                      composite_smooth_gradient_adjoint_value = 0.0_dp
    1991              :                      composite_smooth_kin_adjoint_value = 0.0_dp
    1992              :                      composite_smooth_density_adjoint_value(1) = &
    1993              :                         SUM(composite_density_grad(composite_row, :))
    1994              :                      composite_smooth_gradient_adjoint_value(:, 1) = &
    1995              :                         SUM(composite_grad_grad(composite_row, :, :), DIM=2)
    1996              :                      composite_smooth_kin_adjoint_value(1) = &
    1997              :                         SUM(composite_kin_grad(composite_row, :))
    1998              :                   END IF
    1999              :                   CALL add_native_grid_fields_adjoint_tile( &
    2000              :                      smooth_density_adjoint_storage, smooth_grad_adjoint_storage, &
    2001              :                      smooth_kin_adjoint_storage, smooth_rho_r(1)%pw_grid, interpolation_stencil, &
    2002              :                      composite_smooth_density_adjoint_value, &
    2003              :                      composite_smooth_gradient_adjoint_value, &
    2004              :                      composite_smooth_kin_adjoint_value, adjoint_nchannels, &
    2005              :                      adjoint_tile_lower, adjoint_tile_upper)
    2006              :                END DO
    2007              :             END DO
    2008              : !$OMP END PARALLEL DO
    2009          254 :             DEALLOCATE (adjoint_bin_offsets, adjoint_bin_rows)
    2010              :             smooth_input_contraction = 0.0_dp
    2011              : !$OMP PARALLEL DO SCHEDULE(STATIC) REDUCTION(+:smooth_input_contraction) DEFAULT(NONE) &
    2012              : !$OMP PRIVATE(composite_smooth_density_value, composite_smooth_gradient_value, &
    2013              : !$OMP         composite_smooth_kin_value, idir, ispin) &
    2014              : !$OMP SHARED(composite_density_grad, composite_grad_grad, composite_kin_grad, composite_nflat, &
    2015              : !$OMP        composite_smooth_density_cache, composite_smooth_gradient_cache, &
    2016          254 : !$OMP        composite_smooth_kin_cache, lsd)
    2017              :             DO composite_row = 1, composite_nflat
    2018              :                composite_smooth_density_value = composite_smooth_density_cache(composite_row, :)
    2019              :                composite_smooth_gradient_value = &
    2020              :                   composite_smooth_gradient_cache(composite_row, :, :)
    2021              :                composite_smooth_kin_value = composite_smooth_kin_cache(composite_row, :)
    2022              :                DO ispin = 1, 2
    2023              :                   IF (lsd) THEN
    2024              :                      smooth_input_contraction = smooth_input_contraction + &
    2025              :                                                 composite_density_grad(composite_row, ispin)* &
    2026              :                                                 composite_smooth_density_value(ispin) + &
    2027              :                                                 composite_kin_grad(composite_row, ispin)* &
    2028              :                                                 composite_smooth_kin_value(ispin)
    2029              :                      DO idir = 1, 3
    2030              :                         smooth_input_contraction = smooth_input_contraction + &
    2031              :                                                    composite_grad_grad(composite_row, idir, ispin)* &
    2032              :                                                    composite_smooth_gradient_value(idir, ispin)
    2033              :                      END DO
    2034              :                   ELSE
    2035              :                      smooth_input_contraction = smooth_input_contraction + 0.5_dp*( &
    2036              :                                                 composite_density_grad(composite_row, ispin)* &
    2037              :                                                 composite_smooth_density_value(1) + &
    2038              :                                                 composite_kin_grad(composite_row, ispin)* &
    2039              :                                                 composite_smooth_kin_value(1))
    2040              :                      DO idir = 1, 3
    2041              :                         smooth_input_contraction = smooth_input_contraction + 0.5_dp* &
    2042              :                                                    composite_grad_grad(composite_row, idir, ispin)* &
    2043              :                                                    composite_smooth_gradient_value(idir, 1)
    2044              :                      END DO
    2045              :                   END IF
    2046              :                END DO
    2047              :             END DO
    2048              : !$OMP END PARALLEL DO
    2049          254 :             smooth_density_adjoint => smooth_density_adjoint_storage
    2050          254 :             smooth_grad_adjoint => smooth_grad_adjoint_storage
    2051          254 :             smooth_kin_adjoint => smooth_kin_adjoint_storage
    2052              :             ! The interpolation transpose still uses CP2K's global FFT-grid layout. Reduce only
    2053              :             ! this PW adjoint; atom-grid feature rows and their model derivatives stay rank-local.
    2054      4640470 :             CALL para_env%sum(smooth_density_adjoint)
    2055     13921486 :             CALL para_env%sum(smooth_grad_adjoint)
    2056      4640470 :             CALL para_env%sum(smooth_kin_adjoint)
    2057          254 :             CALL para_env%sum(smooth_input_contraction)
    2058              :             CALL build_vxc_from_feature_grads( &
    2059              :                smooth_vxc_rho, smooth_vxc_tau, smooth_rho_r, auxbas_pw_pool, &
    2060              :                smooth_density_adjoint, smooth_grad_adjoint, smooth_kin_adjoint, &
    2061          254 :                xc_deriv_method_id, global_grid_layout=.TRUE.)
    2062          254 :             NULLIFY (smooth_density_adjoint, smooth_grad_adjoint, smooth_kin_adjoint)
    2063            0 :             DEALLOCATE (smooth_density_adjoint_storage, smooth_grad_adjoint_storage, &
    2064          254 :                         smooth_kin_adjoint_storage)
    2065          254 :             smooth_grid_contraction = 0.0_dp
    2066          546 :             DO ispin = 1, nspins
    2067              :                smooth_grid_contraction = smooth_grid_contraction + smooth_rho_r(1)%pw_grid%dvol* &
    2068              :                                          (SUM(smooth_vxc_rho(ispin)%array* &
    2069              :                                               smooth_rho_r(ispin)%array) + &
    2070              :                                           SUM(smooth_vxc_tau(ispin)%array* &
    2071      2543044 :                                               smooth_tau_r(ispin)%array))
    2072          292 :                IF (atom_composite_reference) THEN
    2073          292 :                   CPASSERT(PRESENT(composite_vxc_rho))
    2074          292 :                   CPASSERT(PRESENT(composite_vxc_tau))
    2075          292 :                   CPASSERT(ASSOCIATED(composite_vxc_rho))
    2076          292 :                   CPASSERT(ASSOCIATED(composite_vxc_tau))
    2077          292 :                   CPASSERT(SIZE(composite_vxc_rho) == nspins)
    2078          292 :                   CPASSERT(SIZE(composite_vxc_tau) == nspins)
    2079          292 :                   CALL pw_axpy(smooth_vxc_rho(ispin), composite_vxc_rho(ispin), 1.0_dp)
    2080          292 :                   CALL pw_axpy(smooth_vxc_tau(ispin), composite_vxc_tau(ispin), 1.0_dp)
    2081              :                END IF
    2082          292 :                CALL auxbas_pw_pool%give_back_pw(smooth_vxc_rho(ispin))
    2083          546 :                CALL auxbas_pw_pool%give_back_pw(smooth_vxc_tau(ispin))
    2084              :             END DO
    2085          254 :             CALL para_env%sum(smooth_grid_contraction)
    2086          254 :             DEALLOCATE (smooth_vxc_rho, smooth_vxc_tau)
    2087              : 
    2088          254 :             one_center_field_contraction = 0.0_dp
    2089          254 :             one_center_matrix_contraction = 0.0_dp
    2090          254 :             one_center_density_field_contraction = 0.0_dp
    2091          254 :             one_center_density_matrix_contraction = 0.0_dp
    2092          254 :             one_center_gradient_field_contraction = 0.0_dp
    2093          254 :             one_center_gradient_matrix_contraction = 0.0_dp
    2094          254 :             one_center_rho_grad_field_contraction = 0.0_dp
    2095          254 :             one_center_rho_grad_matrix_contraction = 0.0_dp
    2096          254 :             one_center_tau_field_contraction = 0.0_dp
    2097          254 :             one_center_tau_matrix_contraction = 0.0_dp
    2098          254 :             IF (.NOT. direct_valence_atom_composite) THEN
    2099          292 :                DO ikind = 1, SIZE(atomic_kind_set)
    2100          164 :                   CALL get_atomic_kind(atomic_kind_set(ikind), atom_list=atom_list, natom=natom)
    2101          164 :                   NULLIFY (gth_potential, sgp_potential)
    2102              :                   CALL get_qs_kind(my_kind_set(ikind), paw_atom=paw_atom, &
    2103              :                                    gth_potential=gth_potential, harmonics=harmonics, &
    2104              :                                    grid_atom=grid_atom, sgp_potential=sgp_potential, &
    2105          164 :                                    zatom=zatom, zeff=zeff)
    2106          164 :                   CALL get_qs_kind(my_kind_set(ikind), basis_set=basis_1c, basis_type="GAPW_1C")
    2107          188 :                   IF (.NOT. native_skala_uses_one_center_kind( &
    2108              :                       paw_atom, gapw_representation, &
    2109              :                       ASSOCIATED(gth_potential) .OR. ASSOCIATED(sgp_potential), &
    2110              :                       zeff, zatom)) CYCLE
    2111              : 
    2112          160 :                   nr = grid_atom%nr
    2113          160 :                   na = grid_atom%ng_sphere
    2114          160 :                   CALL reallocate(rho_h, 1, na, 1, nr, 1, nspins)
    2115          160 :                   CALL reallocate(rho_s, 1, na, 1, nr, 1, nspins)
    2116          160 :                   CALL reallocate(vxc_h, 1, na, 1, nr, 1, nspins)
    2117          160 :                   CALL reallocate(vxc_s, 1, na, 1, nr, 1, nspins)
    2118          160 :                   CALL reallocate(drho_h, 1, 4, 1, na, 1, nr, 1, nspins)
    2119          160 :                   CALL reallocate(drho_s, 1, 4, 1, na, 1, nr, 1, nspins)
    2120          160 :                   CALL reallocate(vxg_h, 1, 3, 1, na, 1, nr, 1, nspins)
    2121          160 :                   CALL reallocate(vxg_s, 1, 3, 1, na, 1, nr, 1, nspins)
    2122          160 :                   CALL reallocate(tau_h, 1, na, 1, nr, 1, nspins)
    2123          160 :                   CALL reallocate(tau_s, 1, na, 1, nr, 1, nspins)
    2124          160 :                   CALL reallocate(vtau_h, 1, na, 1, nr, 1, nspins)
    2125          160 :                   CALL reallocate(vtau_s, 1, na, 1, nr, 1, nspins)
    2126          160 :                   CALL create_tau_basis_cache(tau_basis_cache, grid_atom, basis_1c, harmonics)
    2127              : 
    2128          160 :                   bo = get_limit(natom, para_env%num_pe, para_env%mepos)
    2129          412 :                   DO iat = 1, natom
    2130          252 :                      iatom = atom_list(iat)
    2131          252 :                      source_matrix_local = iat >= bo(1) .AND. iat <= bo(2)
    2132          252 :                      rho_atom => my_rho_atom_set(iatom)
    2133          252 :                      NULLIFY (cpc_h, cpc_s, r_h, r_s, dr_h, dr_s, r_h_d, r_s_d, int_hh, int_ss)
    2134              :                      CALL get_rho_atom(rho_atom=rho_atom, cpc_h=cpc_h, cpc_s=cpc_s, &
    2135              :                                        rho_rad_h=r_h, rho_rad_s=r_s, drho_rad_h=dr_h, &
    2136              :                                        drho_rad_s=dr_s, rho_rad_h_d=r_h_d, rho_rad_s_d=r_s_d, &
    2137          252 :                                        ga_Vlocal_gb_h=int_hh, ga_Vlocal_gb_s=int_ss)
    2138       238104 :                      rho_h = 0.0_dp
    2139       238104 :                      rho_s = 0.0_dp
    2140      1159704 :                      drho_h = 0.0_dp
    2141      1159704 :                      drho_s = 0.0_dp
    2142          252 :                      CALL calc_tau_atom(tau_h, tau_s, rho_atom, tau_basis_cache, nspins)
    2143         7452 :                      DO ir = 1, nr
    2144              :                         CALL calc_rho_angular(grid_atom, harmonics, nspins, .TRUE., &
    2145              :                                               ir, r_h, r_s, rho_h, rho_s, dr_h, dr_s, &
    2146         7452 :                                               r_h_d, r_s_d, drho_h, drho_s)
    2147              :                      END DO
    2148              : 
    2149       238104 :                      vxc_h = 0.0_dp
    2150       238104 :                      vxc_s = 0.0_dp
    2151       929304 :                      vxg_h = 0.0_dp
    2152       929304 :                      vxg_s = 0.0_dp
    2153       238104 :                      vtau_h = 0.0_dp
    2154       238104 :                      vtau_s = 0.0_dp
    2155          252 :                      IF (source_matrix_local) THEN
    2156          126 :                         composite_row = composite_atom_start(iatom) - 1
    2157         3726 :                         DO ir = 1, nr
    2158       118926 :                            DO ia = 1, na
    2159       115200 :                               composite_row = composite_row + 1
    2160       118800 :                               IF (lsd) THEN
    2161            0 :                                  IF (use_atom_composite_density) THEN
    2162            0 :                                     vxc_h(ia, ir, 1:2) = composite_density_grad(composite_row, 1:2)
    2163            0 :                                     vxc_s(ia, ir, 1:2) = composite_density_grad(composite_row, 1:2)
    2164              :                                  END IF
    2165            0 :                                  IF (use_atom_composite_gradient) THEN
    2166            0 :                                     DO idir = 1, 3
    2167              :                                        vxg_h(idir, ia, ir, 1:2) = &
    2168            0 :                                           composite_grad_grad(composite_row, idir, 1:2)
    2169              :                                        vxg_s(idir, ia, ir, 1:2) = &
    2170            0 :                                           composite_grad_grad(composite_row, idir, 1:2)
    2171              :                                     END DO
    2172              :                                  END IF
    2173            0 :                                  IF (use_atom_composite_tau) THEN
    2174            0 :                                     vtau_h(ia, ir, 1:2) = composite_kin_grad(composite_row, 1:2)
    2175            0 :                                     vtau_s(ia, ir, 1:2) = composite_kin_grad(composite_row, 1:2)
    2176              :                                  END IF
    2177              :                               ELSE
    2178       115200 :                                  IF (use_atom_composite_density) THEN
    2179              :                                     vxc_h(ia, ir, 1) = 0.5_dp* &
    2180       345600 :                                                        SUM(composite_density_grad(composite_row, :))
    2181       115200 :                                     vxc_s(ia, ir, 1) = vxc_h(ia, ir, 1)
    2182              :                                  END IF
    2183       115200 :                                  IF (use_atom_composite_gradient) THEN
    2184       460800 :                                     DO idir = 1, 3
    2185              :                                        vxg_h(idir, ia, ir, 1) = 0.5_dp* &
    2186              :                                                                 SUM(composite_grad_grad( &
    2187      1036800 :                                                                     composite_row, idir, :))
    2188       460800 :                                        vxg_s(idir, ia, ir, 1) = vxg_h(idir, ia, ir, 1)
    2189              :                                     END DO
    2190              :                                  END IF
    2191       115200 :                                  IF (use_atom_composite_tau) THEN
    2192              :                                     vtau_h(ia, ir, 1) = 0.5_dp* &
    2193       345600 :                                                         SUM(composite_kin_grad(composite_row, :))
    2194       115200 :                                     vtau_s(ia, ir, 1) = vtau_h(ia, ir, 1)
    2195              :                                  END IF
    2196              :                               END IF
    2197              :                            END DO
    2198              :                         END DO
    2199          126 :                         CPASSERT(composite_row == composite_atom_end(iatom))
    2200              :                      END IF
    2201              : 
    2202              :                      cross_cutoff = gapw_atom_grid_support_radius( &
    2203          252 :                                     grid_atom, rho_h, rho_s, drho_h, drho_s, tau_h, tau_s)
    2204          252 :                      IF (cross_cutoff > 0.0_dp) THEN
    2205          228 :                         image_shell = 0
    2206          912 :                         DO idir = 1, 3
    2207          912 :                            IF (cell%perd(idir) == 1) THEN
    2208              :                               image_shell(idir) = CEILING( &
    2209         2544 :                                                   cross_cutoff*SQRT(SUM(cell%h_inv(idir, :)**2))) + 1
    2210              :                            END IF
    2211              :                         END DO
    2212              :                         ! Each thread accumulates its own one-center potentials; combine them
    2213              :                         ! before the existing MPI reduction over target-atom owners.
    2214              : !$OMP PARALLEL DEFAULT(NONE) &
    2215              : !$OMP PRIVATE(image_lower, image_upper, composite_row, cross_density_adjoint, cross_displacement, &
    2216              : !$OMP         cross_grad_adjoint, cross_kin_adjoint, fractional, idir, image_i1, &
    2217              : !$OMP         image_i2, image_i3, image_shift, image_translation, jdir, target_atom, &
    2218              : !$OMP         vxc_h_local, vxc_s_local, vxg_h_local, vxg_s_local, vtau_h_local, vtau_s_local) &
    2219              : !$OMP SHARED(cell, composite_density_grad, composite_grad_grad, composite_grid_atom, &
    2220              : !$OMP        composite_grid_coords, composite_kin_grad, composite_nflat, cross_cutoff, &
    2221              : !$OMP        grid_atom, harmonics, iatom, image_shell, lsd, nspins, particle_set, &
    2222              : !$OMP        use_atom_composite_density, use_atom_composite_gradient, use_atom_composite_tau, &
    2223          228 : !$OMP        vxc_h, vxc_s, vxg_h, vxg_s, vtau_h, vtau_s)
    2224              :                         ALLOCATE (vxc_h_local, MOLD=vxc_h)
    2225              :                         ALLOCATE (vxc_s_local, MOLD=vxc_s)
    2226              :                         ALLOCATE (vxg_h_local, MOLD=vxg_h)
    2227              :                         ALLOCATE (vxg_s_local, MOLD=vxg_s)
    2228              :                         ALLOCATE (vtau_h_local, MOLD=vtau_h)
    2229              :                         ALLOCATE (vtau_s_local, MOLD=vtau_s)
    2230              :                         vxc_h_local = 0.0_dp
    2231              :                         vxc_s_local = 0.0_dp
    2232              :                         vxg_h_local = 0.0_dp
    2233              :                         vxg_s_local = 0.0_dp
    2234              :                         vtau_h_local = 0.0_dp
    2235              :                         vtau_s_local = 0.0_dp
    2236              : !$OMP DO SCHEDULE(STATIC)
    2237              :                         DO composite_row = 1, composite_nflat
    2238              :                            target_atom = composite_grid_atom(composite_row)
    2239              :                            cross_density_adjoint = 0.0_dp
    2240              :                            cross_grad_adjoint = 0.0_dp
    2241              :                            cross_kin_adjoint = 0.0_dp
    2242              :                            IF (lsd) THEN
    2243              :                               IF (use_atom_composite_density) THEN
    2244              :                                  cross_density_adjoint(1:2) = &
    2245              :                                     composite_density_grad(composite_row, 1:2)
    2246              :                               END IF
    2247              :                               IF (use_atom_composite_gradient) THEN
    2248              :                                  cross_grad_adjoint(:, 1:2) = &
    2249              :                                     composite_grad_grad(composite_row, :, 1:2)
    2250              :                               END IF
    2251              :                               IF (use_atom_composite_tau) THEN
    2252              :                                  cross_kin_adjoint(1:2) = &
    2253              :                                     composite_kin_grad(composite_row, 1:2)
    2254              :                               END IF
    2255              :                            ELSE
    2256              :                               IF (use_atom_composite_density) THEN
    2257              :                                  cross_density_adjoint(1) = 0.5_dp* &
    2258              :                                                             SUM(composite_density_grad(composite_row, :))
    2259              :                               END IF
    2260              :                               IF (use_atom_composite_gradient) THEN
    2261              :                                  DO idir = 1, 3
    2262              :                                     cross_grad_adjoint(idir, 1) = 0.5_dp* &
    2263              :                                                                   SUM(composite_grad_grad(composite_row, idir, :))
    2264              :                                  END DO
    2265              :                               END IF
    2266              :                               IF (use_atom_composite_tau) THEN
    2267              :                                  cross_kin_adjoint(1) = 0.5_dp* &
    2268              :                                                         SUM(composite_kin_grad(composite_row, :))
    2269              :                               END IF
    2270              :                            END IF
    2271              :                            fractional = 0.0_dp
    2272              :                            DO idir = 1, 3
    2273              :                               DO jdir = 1, 3
    2274              :                                  fractional(idir) = fractional(idir) + cell%h_inv(idir, jdir)* &
    2275              :                                                     (composite_grid_coords(jdir, composite_row) - &
    2276              :                                                      particle_set(iatom)%r(jdir))
    2277              :                               END DO
    2278              :                            END DO
    2279              :                            CALL atom_grid_image_bounds(cell, fractional, cross_cutoff, image_shell, &
    2280              :                                                        image_lower, image_upper)
    2281              :                            DO image_i3 = image_lower(3), image_upper(3)
    2282              :                               DO image_i2 = image_lower(2), image_upper(2)
    2283              :                                  DO image_i1 = image_lower(1), image_upper(1)
    2284              :                                     image_shift = [image_i1, image_i2, image_i3]
    2285              :                                     IF (target_atom == iatom .AND. ALL(image_shift == 0)) CYCLE
    2286              :                                     image_translation = MATMUL( &
    2287              :                                                         cell%hmat, REAL(image_shift, dp))
    2288              :                                     cross_displacement = &
    2289              :                                        composite_grid_coords(:, composite_row) - &
    2290              :                                        particle_set(iatom)%r - image_translation
    2291              :                                     ! Reject inactive images before allocating interpolation scratch.
    2292              :                                     IF (SQRT(SUM(cross_displacement**2)) > cross_cutoff) CYCLE
    2293              :                                     CALL add_gapw_atom_grid_interpolation_adjoint( &
    2294              :                                        grid_atom, harmonics, cross_displacement, cross_cutoff, &
    2295              :                                        nspins, cross_density_adjoint, cross_grad_adjoint, &
    2296              :                                        cross_kin_adjoint, vxc_h_local, vxc_s_local, vxg_h_local, vxg_s_local, &
    2297              :                                        vtau_h_local, vtau_s_local)
    2298              :                                  END DO
    2299              :                               END DO
    2300              :                            END DO
    2301              :                         END DO
    2302              : !$OMP END DO
    2303              : !$OMP CRITICAL(skala_atom_composite_adjoint_reduction)
    2304              :                         vxc_h = vxc_h + vxc_h_local
    2305              :                         vxc_s = vxc_s + vxc_s_local
    2306              :                         vxg_h = vxg_h + vxg_h_local
    2307              :                         vxg_s = vxg_s + vxg_s_local
    2308              :                         vtau_h = vtau_h + vtau_h_local
    2309              :                         vtau_s = vtau_s + vtau_s_local
    2310              : !$OMP END CRITICAL(skala_atom_composite_adjoint_reduction)
    2311              :                         DEALLOCATE (vxc_h_local, vxc_s_local, vxg_h_local, vxg_s_local, vtau_h_local, vtau_s_local)
    2312              : !$OMP END PARALLEL
    2313              :                      END IF
    2314              : 
    2315              :                      ! Model rows are distributed by target atom, while CP2K stores each
    2316              :                      ! one-center matrix on the rank owning its source atom. Sum the exact
    2317              :                      ! interpolation transpose before forming that matrix.
    2318       475956 :                      CALL para_env%sum(vxc_h)
    2319       475956 :                      CALL para_env%sum(vxc_s)
    2320      1858356 :                      CALL para_env%sum(vxg_h)
    2321      1858356 :                      CALL para_env%sum(vxg_s)
    2322       475956 :                      CALL para_env%sum(vtau_h)
    2323       475956 :                      CALL para_env%sum(vtau_s)
    2324          252 :                      IF (.NOT. source_matrix_local) CYCLE
    2325              : 
    2326              :                      one_center_rho_grad_field_contraction = &
    2327              :                         one_center_rho_grad_field_contraction + SUM(vxc_h*(rho_h - rho_s)) + &
    2328       583578 :                         SUM(vxg_h*(drho_h(1:3, :, :, :) - drho_s(1:3, :, :, :)))
    2329              :                      one_center_density_field_contraction = one_center_density_field_contraction + &
    2330       119052 :                                                             SUM(vxc_h*(rho_h - rho_s))
    2331              :                      one_center_gradient_field_contraction = one_center_gradient_field_contraction + &
    2332              :                                                              SUM(vxg_h*(drho_h(1:3, :, :, :) - &
    2333       464652 :                                                                         drho_s(1:3, :, :, :)))
    2334              :                      one_center_tau_field_contraction = one_center_tau_field_contraction + &
    2335       119052 :                                                         SUM(vtau_h*(tau_h - tau_s))
    2336              : 
    2337            0 :                      ALLOCATE (composite_int_h(SIZE(int_hh(1)%r_coef, 1), &
    2338              :                                                SIZE(int_hh(1)%r_coef, 2), nspins), &
    2339            0 :                                composite_int_s(SIZE(int_ss(1)%r_coef, 1), &
    2340         1134 :                                                SIZE(int_ss(1)%r_coef, 2), nspins))
    2341          252 :                      DO ispin = 1, nspins
    2342        29358 :                         composite_int_h(:, :, ispin) = int_hh(ispin)%r_coef
    2343        29358 :                         composite_int_s(:, :, ispin) = int_ss(ispin)%r_coef
    2344        29358 :                         int_hh(ispin)%r_coef = 0.0_dp
    2345        29484 :                         int_ss(ispin)%r_coef = 0.0_dp
    2346              :                      END DO
    2347              :                      CALL gaVxcgb_noGC(vxc_h, vxc_s, int_hh, int_ss, &
    2348          126 :                                        grid_atom, basis_1c, harmonics, nspins)
    2349          252 :                      DO ispin = 1, nspins
    2350              :                         one_center_density_matrix_contraction = &
    2351              :                            one_center_density_matrix_contraction + &
    2352              :                            contract_one_center_matrix(cpc_h(ispin)%r_coef, &
    2353              :                                                       int_hh(ispin)%r_coef, &
    2354              :                                                       tau_basis_cache%n2oindex) - &
    2355              :                            contract_one_center_matrix(cpc_s(ispin)%r_coef, &
    2356              :                                                       int_ss(ispin)%r_coef, &
    2357          126 :                                                       tau_basis_cache%n2oindex)
    2358        29358 :                         int_hh(ispin)%r_coef = 0.0_dp
    2359        29484 :                         int_ss(ispin)%r_coef = 0.0_dp
    2360              :                      END DO
    2361              :                      CALL gaVxcgb_GC(vxc_h, vxc_s, vxg_h, vxg_s, int_hh, int_ss, &
    2362          126 :                                      grid_atom, basis_1c, harmonics, nspins)
    2363          252 :                      DO ispin = 1, nspins
    2364              :                         one_center_rho_grad_matrix_contraction = &
    2365              :                            one_center_rho_grad_matrix_contraction + &
    2366              :                            contract_one_center_matrix(cpc_h(ispin)%r_coef, &
    2367              :                                                       int_hh(ispin)%r_coef, &
    2368              :                                                       tau_basis_cache%n2oindex) - &
    2369              :                            contract_one_center_matrix(cpc_s(ispin)%r_coef, &
    2370              :                                                       int_ss(ispin)%r_coef, &
    2371          252 :                                                       tau_basis_cache%n2oindex)
    2372              :                      END DO
    2373          126 :                      CALL dgaVtaudgb(vtau_h, vtau_s, int_hh, int_ss, tau_basis_cache, nspins)
    2374          252 :                      DO ispin = 1, nspins
    2375              :                         one_center_matrix_contraction = one_center_matrix_contraction + &
    2376              :                                                         contract_one_center_matrix(cpc_h(ispin)%r_coef, &
    2377              :                                                                                    int_hh(ispin)%r_coef, &
    2378              :                                                                                    tau_basis_cache%n2oindex) - &
    2379              :                                                         contract_one_center_matrix(cpc_s(ispin)%r_coef, &
    2380              :                                                                                    int_ss(ispin)%r_coef, &
    2381          126 :                                                                                    tau_basis_cache%n2oindex)
    2382          252 :                         IF (.NOT. atom_composite_reference) THEN
    2383            0 :                            int_hh(ispin)%r_coef = composite_int_h(:, :, ispin)
    2384            0 :                            int_ss(ispin)%r_coef = composite_int_s(:, :, ispin)
    2385              :                         END IF
    2386              :                      END DO
    2387          412 :                      DEALLOCATE (composite_int_h, composite_int_s)
    2388              :                   END DO
    2389          452 :                   CALL release_tau_basis_cache(tau_basis_cache)
    2390              :                END DO
    2391              :             END IF
    2392          254 :             CALL para_env%sum(one_center_density_field_contraction)
    2393          254 :             CALL para_env%sum(one_center_density_matrix_contraction)
    2394          254 :             CALL para_env%sum(one_center_gradient_field_contraction)
    2395          254 :             CALL para_env%sum(one_center_matrix_contraction)
    2396          254 :             CALL para_env%sum(one_center_rho_grad_field_contraction)
    2397          254 :             CALL para_env%sum(one_center_rho_grad_matrix_contraction)
    2398          254 :             CALL para_env%sum(one_center_tau_field_contraction)
    2399              :             one_center_field_contraction = one_center_rho_grad_field_contraction + &
    2400          254 :                                            one_center_tau_field_contraction
    2401              :             one_center_gradient_matrix_contraction = one_center_rho_grad_matrix_contraction - &
    2402          254 :                                                      one_center_density_matrix_contraction
    2403              :             one_center_tau_matrix_contraction = one_center_matrix_contraction - &
    2404          254 :                                                 one_center_rho_grad_matrix_contraction
    2405       552114 :             feature_component_analytic(1) = SUM(composite_density_grad*composite_density)
    2406      1656342 :             feature_component_analytic(2) = SUM(composite_grad_grad*composite_grad)
    2407       552114 :             feature_component_analytic(3) = SUM(composite_kin_grad*composite_kin)
    2408         1016 :             feature_component_analytic(4) = SUM(feature_component_analytic(1:3))
    2409          254 :             CALL para_env%sum(feature_component_analytic)
    2410              :             one_center_tensor_contraction = feature_component_analytic(4) - &
    2411          254 :                                             smooth_input_contraction
    2412          254 :             IF (atom_composite_diagnostic) THEN
    2413            0 :                DO icomponent = 1, 4
    2414            0 :                   SELECT CASE (icomponent)
    2415              :                   CASE (1)
    2416            0 :                      composite_density = (1.0_dp + feature_vxc_step)*composite_density
    2417              :                   CASE (2)
    2418            0 :                      composite_grad = (1.0_dp + feature_vxc_step)*composite_grad
    2419              :                   CASE (3)
    2420            0 :                      composite_kin = (1.0_dp + feature_vxc_step)*composite_kin
    2421              :                   CASE (4)
    2422            0 :                      composite_density = (1.0_dp + feature_vxc_step)*composite_density
    2423            0 :                      composite_grad = (1.0_dp + feature_vxc_step)*composite_grad
    2424            0 :                      composite_kin = (1.0_dp + feature_vxc_step)*composite_kin
    2425              :                   END SELECT
    2426              :                   CALL skala_gapw_atom_composite_energy( &
    2427              :                      my_xc_section, para_env, composite_density, composite_grad, composite_kin, &
    2428              :                      composite_grid_coords, composite_grid_weights, composite_atomic_grid_weights, &
    2429            0 :                      composite_local_grid_sizes, composite_local_atom_coords, feature_vxc_plus)
    2430            0 :                   SELECT CASE (icomponent)
    2431              :                   CASE (1)
    2432              :                      composite_density = ((1.0_dp - feature_vxc_step)/ &
    2433            0 :                                           (1.0_dp + feature_vxc_step))*composite_density
    2434              :                   CASE (2)
    2435              :                      composite_grad = ((1.0_dp - feature_vxc_step)/ &
    2436            0 :                                        (1.0_dp + feature_vxc_step))*composite_grad
    2437              :                   CASE (3)
    2438              :                      composite_kin = ((1.0_dp - feature_vxc_step)/ &
    2439            0 :                                       (1.0_dp + feature_vxc_step))*composite_kin
    2440              :                   CASE (4)
    2441              :                      composite_density = ((1.0_dp - feature_vxc_step)/ &
    2442            0 :                                           (1.0_dp + feature_vxc_step))*composite_density
    2443              :                      composite_grad = ((1.0_dp - feature_vxc_step)/ &
    2444            0 :                                        (1.0_dp + feature_vxc_step))*composite_grad
    2445              :                      composite_kin = ((1.0_dp - feature_vxc_step)/ &
    2446            0 :                                       (1.0_dp + feature_vxc_step))*composite_kin
    2447              :                   END SELECT
    2448              :                   CALL skala_gapw_atom_composite_energy( &
    2449              :                      my_xc_section, para_env, composite_density, composite_grad, composite_kin, &
    2450              :                      composite_grid_coords, composite_grid_weights, composite_atomic_grid_weights, &
    2451            0 :                      composite_local_grid_sizes, composite_local_atom_coords, feature_vxc_minus)
    2452            0 :                   SELECT CASE (icomponent)
    2453              :                   CASE (1)
    2454            0 :                      composite_density = composite_density/(1.0_dp - feature_vxc_step)
    2455              :                   CASE (2)
    2456            0 :                      composite_grad = composite_grad/(1.0_dp - feature_vxc_step)
    2457              :                   CASE (3)
    2458            0 :                      composite_kin = composite_kin/(1.0_dp - feature_vxc_step)
    2459              :                   CASE (4)
    2460            0 :                      composite_density = composite_density/(1.0_dp - feature_vxc_step)
    2461            0 :                      composite_grad = composite_grad/(1.0_dp - feature_vxc_step)
    2462            0 :                      composite_kin = composite_kin/(1.0_dp - feature_vxc_step)
    2463              :                   END SELECT
    2464              :                   feature_component_fd(icomponent) = &
    2465            0 :                      (feature_vxc_plus - feature_vxc_minus)/(2.0_dp*feature_vxc_step)
    2466              :                END DO
    2467            0 :                feature_vxc_analytic = feature_component_analytic(4)
    2468            0 :                feature_vxc_fd = feature_component_fd(4)
    2469            0 :                iw = cp_logger_get_default_io_unit()
    2470            0 :                IF (iw > 0) THEN
    2471              :                   WRITE (UNIT=iw, FMT="(T2,A,1X,I0)") &
    2472            0 :                      "SKALA_GPW| Atom-composite reference components", atom_composite_components
    2473              :                   WRITE (UNIT=iw, FMT="(T2,A,1X,ES24.16)") &
    2474            0 :                      "SKALA_GPW| Atom-composite reference electrons", atom_composite_nelec
    2475              :                   WRITE (UNIT=iw, FMT="(T2,A,1X,ES24.16)") &
    2476            0 :                      "SKALA_GPW| Atom-composite reference XC energy", atom_composite_exc
    2477              :                   WRITE (UNIT=iw, FMT="(T2,A,1X,ES24.16)") &
    2478            0 :                      "SKALA_GPW| Atom-composite feature VXC contraction", feature_vxc_analytic
    2479              :                   WRITE (UNIT=iw, FMT="(T2,A,1X,ES24.16)") &
    2480            0 :                      "SKALA_GPW| Atom-composite feature finite difference", feature_vxc_fd
    2481              :                   WRITE (UNIT=iw, FMT="(T2,A,1X,ES24.16)") &
    2482            0 :                      "SKALA_GPW| Atom-composite feature VXC error", &
    2483            0 :                      feature_vxc_analytic - feature_vxc_fd
    2484              :                   WRITE (UNIT=iw, FMT="(T2,A,3(1X,ES24.16))") &
    2485            0 :                      "SKALA_GPW| Atom-composite smooth PW adjoint", smooth_input_contraction, &
    2486            0 :                      smooth_grid_contraction, smooth_grid_contraction - smooth_input_contraction
    2487              :                   WRITE (UNIT=iw, FMT="(T2,A,4(1X,ES24.16))") &
    2488            0 :                      "SKALA_GPW| Atom-composite one-center adjoint", one_center_tensor_contraction, &
    2489            0 :                      one_center_field_contraction, one_center_matrix_contraction, &
    2490            0 :                      one_center_matrix_contraction - one_center_tensor_contraction
    2491              :                   WRITE (UNIT=iw, FMT="(T2,A,4(1X,ES24.16))") &
    2492            0 :                      "SKALA_GPW| Atom-composite one-center channels", &
    2493            0 :                      one_center_rho_grad_field_contraction, one_center_rho_grad_matrix_contraction, &
    2494            0 :                      one_center_tau_field_contraction, one_center_tau_matrix_contraction
    2495              :                   WRITE (UNIT=iw, FMT="(T2,A,4(1X,ES24.16))") &
    2496            0 :                      "SKALA_GPW| Atom-composite one-center rho-gradient", &
    2497            0 :                      one_center_density_field_contraction, one_center_density_matrix_contraction, &
    2498            0 :                      one_center_gradient_field_contraction, one_center_gradient_matrix_contraction
    2499            0 :                   DO icomponent = 1, 3
    2500              :                      WRITE (UNIT=iw, FMT="(T2,A,1X,I0,3(1X,ES24.16))") &
    2501            0 :                         "SKALA_GPW| Atom-composite component VXC", icomponent, &
    2502            0 :                         feature_component_analytic(icomponent), feature_component_fd(icomponent), &
    2503            0 :                         feature_component_analytic(icomponent) - feature_component_fd(icomponent)
    2504              :                   END DO
    2505              :                END IF
    2506              :             END IF
    2507          254 :             IF (atom_composite_reference) THEN
    2508          254 :                exc1 = atom_composite_exc
    2509          254 :                IF (native_grid_diagnostics) THEN
    2510           30 :                   IF (composite_nflat > 0) THEN
    2511       119540 :                      composite_density_min = MINVAL(composite_density)
    2512       119540 :                      composite_density_max = MAXVAL(composite_density)
    2513       119540 :                      composite_kin_min = MINVAL(composite_kin)
    2514       119540 :                      composite_kin_max = MAXVAL(composite_kin)
    2515       358620 :                      composite_grad_max = MAXVAL(ABS(composite_grad))
    2516              :                   ELSE
    2517           10 :                      composite_density_min = HUGE(1.0_dp)
    2518           10 :                      composite_density_max = -HUGE(1.0_dp)
    2519           10 :                      composite_kin_min = HUGE(1.0_dp)
    2520           10 :                      composite_kin_max = -HUGE(1.0_dp)
    2521           10 :                      composite_grad_max = 0.0_dp
    2522              :                   END IF
    2523              :                   composite_tau_integral = &
    2524       179250 :                      SUM(composite_grid_weights*SUM(composite_kin, DIM=2))
    2525           30 :                   CALL para_env%min(composite_density_min)
    2526           30 :                   CALL para_env%max(composite_density_max)
    2527           30 :                   CALL para_env%min(composite_kin_min)
    2528           30 :                   CALL para_env%max(composite_kin_max)
    2529           30 :                   CALL para_env%max(composite_grad_max)
    2530           30 :                   CALL para_env%sum(composite_tau_integral)
    2531              :                END IF
    2532          254 :                iw = cp_logger_get_default_io_unit()
    2533          254 :                IF (iw > 0) THEN
    2534              :                   WRITE (UNIT=iw, FMT="(T2,A,1X,ES24.16)") &
    2535          127 :                      "SKALA_GPW| Active atom-composite XC energy", atom_composite_exc
    2536          127 :                   IF (native_grid_diagnostics) THEN
    2537              :                      WRITE (UNIT=iw, FMT="(T2,A,1X,ES24.16)") &
    2538           15 :                         "SKALA_GPW| Active atom-composite electrons", atom_composite_nelec
    2539              :                      WRITE (UNIT=iw, FMT="(T2,A,2(1X,ES24.16))") &
    2540           15 :                         "SKALA_GPW| Active atom-composite density range", &
    2541           30 :                         composite_density_min, composite_density_max
    2542              :                      WRITE (UNIT=iw, FMT="(T2,A,2(1X,ES24.16))") &
    2543           15 :                         "SKALA_GPW| Active atom-composite tau range", &
    2544           30 :                         composite_kin_min, composite_kin_max
    2545              :                      WRITE (UNIT=iw, FMT="(T2,A,1X,ES24.16)") &
    2546           15 :                         "SKALA_GPW| Active atom-composite tau integral", &
    2547           30 :                         composite_tau_integral
    2548              :                      WRITE (UNIT=iw, FMT="(T2,A,1X,ES24.16)") &
    2549           15 :                         "SKALA_GPW| Active atom-composite max gradient", &
    2550           30 :                         composite_grad_max
    2551              :                   END IF
    2552              :                END IF
    2553              :             END IF
    2554          254 :             CALL xc_rho_set_release(smooth_rho_set, pw_pool=auxbas_pw_pool)
    2555            0 :             DEALLOCATE (composite_atomic_grid_sizes, composite_atom_kind, &
    2556            0 :                         composite_atom_kind_index, composite_atom_start, composite_atom_end, &
    2557            0 :                         composite_atom_coords, composite_local_atoms, composite_local_grid_sizes, &
    2558            0 :                         composite_local_atom_coords, composite_grid_atom, &
    2559            0 :                         composite_partition_weights, composite_partition_atom_coords, &
    2560            0 :                         composite_distances, composite_density, composite_grad, composite_kin, &
    2561            0 :                         composite_smooth_density_cache, composite_smooth_gradient_cache, &
    2562            0 :                         composite_smooth_kin_cache, &
    2563            0 :                         composite_density_grad, composite_grad_grad, composite_kin_grad, &
    2564            0 :                         composite_grid_coords, composite_grid_weights, &
    2565          254 :                         composite_base_grid_weights, composite_atomic_grid_weights)
    2566          254 :             IF (lsd) THEN
    2567            0 :                DEALLOCATE (composite_smooth_rhoa, composite_smooth_rhob, &
    2568           38 :                            composite_smooth_tau_a, composite_smooth_tau_b)
    2569          152 :                DO idir = 1, 3
    2570            0 :                   DEALLOCATE (composite_smooth_drhoa(idir)%array, &
    2571          152 :                               composite_smooth_drhob(idir)%array)
    2572              :                END DO
    2573              :             ELSE
    2574          216 :                DEALLOCATE (composite_smooth_rho, composite_smooth_tau)
    2575          864 :                DO idir = 1, 3
    2576          864 :                   DEALLOCATE (composite_smooth_drho(idir)%array)
    2577              :                END DO
    2578              :             END IF
    2579              :          END IF
    2580              : 
    2581        30960 :          IF (.NOT. atom_composite_reference) CALL para_env%sum(exc1)
    2582              : 
    2583        30960 :          IF (ASSOCIATED(rho_h)) DEALLOCATE (rho_h)
    2584        30960 :          IF (ASSOCIATED(rho_s)) DEALLOCATE (rho_s)
    2585        30960 :          IF (ASSOCIATED(vxc_h)) DEALLOCATE (vxc_h)
    2586        30960 :          IF (ASSOCIATED(vxc_s)) DEALLOCATE (vxc_s)
    2587              : 
    2588        30960 :          IF (gradient_f) THEN
    2589        21734 :             IF (ASSOCIATED(drho_h)) DEALLOCATE (drho_h)
    2590        21734 :             IF (ASSOCIATED(drho_s)) DEALLOCATE (drho_s)
    2591        21734 :             IF (ASSOCIATED(vxg_h)) DEALLOCATE (vxg_h)
    2592        21734 :             IF (ASSOCIATED(vxg_s)) DEALLOCATE (vxg_s)
    2593              :          END IF
    2594              : 
    2595        30960 :          IF (tau_f) THEN
    2596         1166 :             IF (ASSOCIATED(tau_h)) DEALLOCATE (tau_h)
    2597         1166 :             IF (ASSOCIATED(tau_s)) DEALLOCATE (tau_s)
    2598         1166 :             IF (ASSOCIATED(vtau_h)) DEALLOCATE (vtau_h)
    2599         1166 :             IF (ASSOCIATED(vtau_s)) DEALLOCATE (vtau_s)
    2600              :          END IF
    2601              : 
    2602              :       END IF !xc_none
    2603              : 
    2604        35460 :       CALL timestop(handle)
    2605              : 
    2606      6205500 :    END SUBROUTINE calculate_vxc_atom
    2607              : 
    2608              : ! **************************************************************************************************
    2609              : !> \brief Add the GAPW one-center correction to CDFT values and operators.
    2610              : !> \param qs_env Quickstep environment
    2611              : !> \param energy_only skip construction of the CDFT one-center operator
    2612              : !> \param calculate_forces evaluate explicit derivatives of the partition weights
    2613              : !> \param values constraint values from the hard-minus-soft one-center densities
    2614              : !> \param electronic_charge optional one-center corrections to atomic populations
    2615              : !> \param operator_group optional group for which to build the unscaled weight operator
    2616              : !> \param rho_atom_operator_set optional destination for the one-center operator integrals
    2617              : ! **************************************************************************************************
    2618          464 :    SUBROUTINE gapw_cdft_one_center(qs_env, energy_only, calculate_forces, values, &
    2619          464 :                                    electronic_charge, operator_group, rho_atom_operator_set)
    2620              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    2621              :       LOGICAL, INTENT(IN)                                :: energy_only, calculate_forces
    2622              :       REAL(KIND=dp), DIMENSION(:), INTENT(OUT)           :: values
    2623              :       REAL(KIND=dp), DIMENSION(:, :), INTENT(OUT), &
    2624              :          OPTIONAL                                        :: electronic_charge
    2625              :       INTEGER, INTENT(IN), OPTIONAL                      :: operator_group
    2626              :       TYPE(rho_atom_type), DIMENSION(:), POINTER, &
    2627              :          OPTIONAL                                        :: rho_atom_operator_set
    2628              : 
    2629              :       INTEGER                                            :: atom, channel, ia, iat, igroup, ikind, &
    2630              :                                                             ir, natom, natom_kind, nspins
    2631              :       INTEGER, DIMENSION(2)                              :: atom_bounds
    2632          464 :       INTEGER, DIMENSION(:), POINTER                     :: atom_list
    2633              :       LOGICAL                                            :: lsd, paw_atom
    2634              :       REAL(KIND=dp)                                      :: delta_density, point_factor, spin_factor
    2635          464 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:)           :: atomic_weights, group_weights
    2636          464 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :)        :: explicit_derivative, &
    2637          464 :                                                             group_point_derivative
    2638          464 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :, :)     :: group_atom_derivative
    2639              :       REAL(KIND=dp), DIMENSION(3)                        :: point
    2640          464 :       REAL(KIND=dp), DIMENSION(:, :, :), POINTER         :: rho_h, rho_s
    2641          464 :       REAL(KIND=dp), DIMENSION(:, :, :, :), POINTER      :: drho_h, drho_s
    2642          464 :       REAL(KIND=dp), DIMENSION(:, :, :), POINTER         :: vlocal_h, vlocal_s
    2643          464 :       TYPE(atomic_kind_type), DIMENSION(:), POINTER      :: atomic_kind_set
    2644              :       TYPE(cdft_control_type), POINTER                   :: cdft_control
    2645          464 :       TYPE(cdft_point_context_type)                      :: context
    2646              :       TYPE(dft_control_type), POINTER                    :: dft_control
    2647              :       TYPE(grid_atom_type), POINTER                      :: grid_atom
    2648              :       TYPE(gto_basis_set_type), POINTER                  :: basis_1c
    2649              :       TYPE(harmonics_atom_type), POINTER                 :: harmonics
    2650              :       TYPE(mp_para_env_type), POINTER                    :: para_env
    2651          464 :       TYPE(particle_type), DIMENSION(:), POINTER         :: particle_set
    2652          464 :       TYPE(qs_force_type), DIMENSION(:), POINTER         :: force
    2653          464 :       TYPE(qs_kind_type), DIMENSION(:), POINTER          :: qs_kind_set
    2654          464 :       TYPE(rho_atom_coeff), DIMENSION(:), POINTER        :: dr_h, dr_s, int_hh, int_ss, r_h, r_s
    2655          464 :       TYPE(rho_atom_coeff), DIMENSION(:, :), POINTER     :: r_h_d, r_s_d
    2656          464 :       TYPE(rho_atom_type), DIMENSION(:), POINTER         :: operator_atom_set, rho_atom_set
    2657              :       TYPE(rho_atom_type), POINTER                       :: operator_atom, rho_atom
    2658              : 
    2659          464 :       NULLIFY (atom_list, atomic_kind_set, basis_1c, cdft_control, dft_control, force, &
    2660          464 :                grid_atom, harmonics, int_hh, int_ss, para_env, particle_set, r_h, r_s, &
    2661          464 :                dr_h, dr_s, r_h_d, r_s_d, rho_h, rho_s, drho_h, drho_s, &
    2662          464 :                operator_atom, operator_atom_set, rho_atom, rho_atom_set, qs_kind_set, &
    2663          464 :                vlocal_h, vlocal_s)
    2664              :       CALL get_qs_env(qs_env, atomic_kind_set=atomic_kind_set, dft_control=dft_control, &
    2665              :                       force=force, natom=natom, para_env=para_env, particle_set=particle_set, &
    2666          464 :                       qs_kind_set=qs_kind_set, rho_atom_set=rho_atom_set)
    2667          464 :       CPASSERT(ASSOCIATED(atomic_kind_set))
    2668          464 :       CPASSERT(ASSOCIATED(dft_control))
    2669          464 :       CPASSERT(ASSOCIATED(para_env))
    2670          464 :       CPASSERT(ASSOCIATED(particle_set))
    2671          464 :       CPASSERT(ASSOCIATED(qs_kind_set))
    2672          464 :       CPASSERT(ASSOCIATED(rho_atom_set))
    2673          464 :       operator_atom_set => rho_atom_set
    2674          464 :       IF (PRESENT(rho_atom_operator_set)) operator_atom_set => rho_atom_operator_set
    2675          464 :       CPASSERT(ASSOCIATED(operator_atom_set))
    2676          464 :       cdft_control => dft_control%qs_control%cdft_control
    2677          464 :       CPASSERT(ASSOCIATED(cdft_control))
    2678          464 :       nspins = dft_control%nspins
    2679          464 :       lsd = dft_control%lsd
    2680          464 :       CPASSERT(SIZE(values) == SIZE(cdft_control%group))
    2681          464 :       IF (PRESENT(operator_group)) THEN
    2682            4 :          CPASSERT(operator_group >= 1 .AND. operator_group <= SIZE(cdft_control%group))
    2683              :       END IF
    2684          464 :       IF (PRESENT(electronic_charge)) THEN
    2685           76 :          CPASSERT(SIZE(electronic_charge, 1) == natom)
    2686           76 :          CPASSERT(SIZE(electronic_charge, 2) == nspins)
    2687              :       END IF
    2688              : 
    2689          464 :       CALL cdft_point_context_create(qs_env, context, calculate_forces)
    2690              :       ALLOCATE (group_weights(context%ngroup), group_point_derivative(3, context%ngroup), &
    2691              :                 group_atom_derivative(3, natom, context%ngroup), &
    2692         4640 :                 explicit_derivative(3, natom))
    2693          616 :       IF (PRESENT(electronic_charge)) ALLOCATE (atomic_weights(natom))
    2694         1004 :       values = 0.0_dp
    2695          464 :       explicit_derivative = 0.0_dp
    2696         1012 :       IF (PRESENT(electronic_charge)) electronic_charge = 0.0_dp
    2697              : 
    2698         1104 :       DO ikind = 1, SIZE(atomic_kind_set)
    2699          640 :          CALL get_atomic_kind(atomic_kind_set(ikind), atom_list=atom_list, natom=natom_kind)
    2700              :          CALL get_qs_kind(qs_kind_set(ikind), paw_atom=paw_atom, grid_atom=grid_atom, &
    2701          640 :                           harmonics=harmonics)
    2702          640 :          IF (.NOT. paw_atom) CYCLE
    2703          640 :          CALL get_qs_kind(qs_kind_set(ikind), basis_set=basis_1c, basis_type="GAPW_1C")
    2704          640 :          CPASSERT(ASSOCIATED(grid_atom))
    2705          640 :          CPASSERT(ASSOCIATED(harmonics))
    2706          640 :          CPASSERT(ASSOCIATED(basis_1c))
    2707              :          ALLOCATE (vlocal_h(grid_atom%ng_sphere, grid_atom%nr, nspins), &
    2708         5760 :                    vlocal_s(grid_atom%ng_sphere, grid_atom%nr, nspins))
    2709              : 
    2710          640 :          atom_bounds = get_limit(natom_kind, para_env%num_pe, para_env%mepos)
    2711         1177 :          DO iat = atom_bounds(1), atom_bounds(2)
    2712          537 :             atom = atom_list(iat)
    2713          537 :             rho_atom => rho_atom_set(atom)
    2714          537 :             NULLIFY (r_h, r_s)
    2715          537 :             CALL get_rho_atom(rho_atom=rho_atom, rho_rad_h=r_h, rho_rad_s=r_s)
    2716          537 :             CALL reallocate(rho_h, 1, grid_atom%ng_sphere, 1, grid_atom%nr, 1, nspins)
    2717          537 :             CALL reallocate(rho_s, 1, grid_atom%ng_sphere, 1, grid_atom%nr, 1, nspins)
    2718      1827053 :             rho_h = 0.0_dp
    2719      1827053 :             rho_s = 0.0_dp
    2720        27387 :             DO ir = 1, grid_atom%nr
    2721              :                CALL calc_rho_angular(grid_atom, harmonics, nspins, .FALSE., ir, r_h, r_s, &
    2722        27387 :                                      rho_h, rho_s, dr_h, dr_s, r_h_d, r_s_d, drho_h, drho_s)
    2723              :             END DO
    2724      1827053 :             vlocal_h = 0.0_dp
    2725      1827053 :             vlocal_s = 0.0_dp
    2726              : 
    2727        27387 :             DO ir = 1, grid_atom%nr
    2728      1369887 :                DO ia = 1, grid_atom%ng_sphere
    2729              :                   point(1) = particle_set(atom)%r(1) + grid_atom%rad(ir)* &
    2730      1342500 :                              grid_atom%sin_pol(ia)*grid_atom%cos_azi(ia)
    2731              :                   point(2) = particle_set(atom)%r(2) + grid_atom%rad(ir)* &
    2732      1342500 :                              grid_atom%sin_pol(ia)*grid_atom%sin_azi(ia)
    2733      1342500 :                   point(3) = particle_set(atom)%r(3) + grid_atom%rad(ir)*grid_atom%cos_pol(ia)
    2734      1342500 :                   IF (PRESENT(electronic_charge)) THEN
    2735              :                      CALL cdft_point_weights(context, point, group_weights, &
    2736              :                                              group_point_derivative, group_atom_derivative, &
    2737       247500 :                                              atomic_weights)
    2738              :                   ELSE
    2739              :                      CALL cdft_point_weights(context, point, group_weights, &
    2740      1095000 :                                              group_point_derivative, group_atom_derivative)
    2741              :                   END IF
    2742      3159350 :                   DO channel = 1, nspins
    2743      1790000 :                      delta_density = rho_h(ia, ir, channel) - rho_s(ia, ir, channel)
    2744      1790000 :                      IF (PRESENT(electronic_charge)) THEN
    2745              :                         electronic_charge(:, channel) = electronic_charge(:, channel) + &
    2746              :                                                         grid_atom%weight(ia, ir)*atomic_weights* &
    2747      1830000 :                                                         delta_density
    2748              :                      END IF
    2749      1790000 :                      point_factor = 0.0_dp
    2750      3960000 :                      DO igroup = 1, context%ngroup
    2751              :                         spin_factor = cdft_spin_factor( &
    2752      2170000 :                                       cdft_control%group(igroup)%constraint_type, channel, lsd)
    2753      2170000 :                         IF (PRESENT(operator_group)) THEN
    2754        10000 :                            IF (igroup == operator_group) THEN
    2755        10000 :                               point_factor = point_factor + group_weights(igroup)
    2756              :                            END IF
    2757              :                         ELSE
    2758              :                            point_factor = point_factor + cdft_control%strength(igroup)* &
    2759      2160000 :                                           group_weights(igroup)*spin_factor
    2760              :                         END IF
    2761              :                         values(igroup) = values(igroup) + grid_atom%weight(ia, ir)* &
    2762      2170000 :                                          group_weights(igroup)*delta_density*spin_factor
    2763      3960000 :                         IF (calculate_forces) THEN
    2764              :                            explicit_derivative(:, :) = &
    2765              :                               explicit_derivative + grid_atom%weight(ia, ir)* &
    2766              :                               cdft_control%strength(igroup)*delta_density* &
    2767       367500 :                               spin_factor*group_atom_derivative(:, :, igroup)
    2768              :                            explicit_derivative(:, atom) = explicit_derivative(:, atom) + &
    2769              :                                                           grid_atom%weight(ia, ir)* &
    2770              :                                                           cdft_control%strength(igroup)*delta_density* &
    2771       150000 :                                                           spin_factor*group_point_derivative(:, igroup)
    2772              :                         END IF
    2773              :                      END DO
    2774      1790000 :                      vlocal_h(ia, ir, channel) = grid_atom%weight(ia, ir)*point_factor
    2775      3132500 :                      vlocal_s(ia, ir, channel) = vlocal_h(ia, ir, channel)
    2776              :                   END DO
    2777              :                END DO
    2778              :             END DO
    2779              : 
    2780         1177 :             IF (.NOT. energy_only) THEN
    2781          389 :                NULLIFY (int_hh, int_ss)
    2782          389 :                operator_atom => operator_atom_set(atom)
    2783          389 :                CALL get_rho_atom(rho_atom=operator_atom, ga_Vlocal_gb_h=int_hh, ga_Vlocal_gb_s=int_ss)
    2784              :                CALL gaVxcgb_noGC(vlocal_h, vlocal_s, int_hh, int_ss, grid_atom, &
    2785          389 :                                  basis_1c, harmonics, nspins)
    2786              :             END IF
    2787              :          END DO
    2788         1744 :          DEALLOCATE (vlocal_h, vlocal_s)
    2789              :       END DO
    2790              : 
    2791         1544 :       CALL para_env%sum(values)
    2792          464 :       CALL para_env%sum(explicit_derivative)
    2793         1560 :       IF (PRESENT(electronic_charge)) CALL para_env%sum(electronic_charge)
    2794          464 :       IF (calculate_forces .AND. ASSOCIATED(force) .AND. para_env%is_source()) THEN
    2795            9 :          DO ikind = 1, SIZE(atomic_kind_set)
    2796            5 :             CALL get_atomic_kind(atomic_kind_set(ikind), atom_list=atom_list, natom=natom_kind)
    2797           18 :             DO iat = 1, natom_kind
    2798            9 :                atom = atom_list(iat)
    2799              :                force(ikind)%rho_elec(:, iat) = force(ikind)%rho_elec(:, iat) + &
    2800           41 :                                                explicit_derivative(:, atom)
    2801              :             END DO
    2802              :          END DO
    2803              :       END IF
    2804              : 
    2805          464 :       IF (ASSOCIATED(rho_h)) DEALLOCATE (rho_h)
    2806          464 :       IF (ASSOCIATED(rho_s)) DEALLOCATE (rho_s)
    2807          464 :       IF (ALLOCATED(atomic_weights)) DEALLOCATE (atomic_weights)
    2808          464 :       DEALLOCATE (explicit_derivative, group_atom_derivative, group_point_derivative, group_weights)
    2809          928 :       CALL cdft_point_context_release(context)
    2810              : 
    2811              :    CONTAINS
    2812              : 
    2813              : ! **************************************************************************************************
    2814              : !> \brief ...
    2815              : !> \param constraint_type ...
    2816              : !> \param channel ...
    2817              : !> \param lsd ...
    2818              : !> \return ...
    2819              : ! **************************************************************************************************
    2820      2170000 :       FUNCTION cdft_spin_factor(constraint_type, channel, lsd) RESULT(factor)
    2821              :       INTEGER, INTENT(IN)                                :: constraint_type, channel
    2822              :       LOGICAL, INTENT(IN)                                :: lsd
    2823              :       REAL(KIND=dp)                                      :: factor
    2824              : 
    2825      2170000 :          SELECT CASE (constraint_type)
    2826              :          CASE (cdft_charge_constraint)
    2827            0 :             factor = 1.0_dp
    2828              :          CASE (cdft_magnetization_constraint)
    2829            0 :             CPASSERT(lsd)
    2830            0 :             factor = MERGE(1.0_dp, -1.0_dp, channel == 1)
    2831              :          CASE (cdft_alpha_constraint)
    2832       380000 :             CPASSERT(lsd)
    2833       380000 :             factor = MERGE(1.0_dp, 0.0_dp, channel == 1)
    2834              :          CASE (cdft_beta_constraint)
    2835       380000 :             CPASSERT(lsd)
    2836       380000 :             factor = MERGE(1.0_dp, 0.0_dp, channel == 2)
    2837              :          CASE DEFAULT
    2838      2170000 :             CPABORT("Unknown CDFT constraint type.")
    2839              :          END SELECT
    2840      2170000 :       END FUNCTION cdft_spin_factor
    2841              : 
    2842              :    END SUBROUTINE gapw_cdft_one_center
    2843              : 
    2844              : ! **************************************************************************************************
    2845              : !> \brief Contract a compact one-center density matrix with an integral in the padded old basis.
    2846              : !> \param density_matrix ...
    2847              : !> \param integral_matrix ...
    2848              : !> \param new_to_old ...
    2849              : !> \return ...
    2850              : ! **************************************************************************************************
    2851          756 :    FUNCTION contract_one_center_matrix(density_matrix, integral_matrix, new_to_old) RESULT(value)
    2852              :       REAL(KIND=dp), DIMENSION(:, :), INTENT(IN)         :: density_matrix, integral_matrix
    2853              :       INTEGER, DIMENSION(:), INTENT(IN)                  :: new_to_old
    2854              :       REAL(KIND=dp)                                      :: value
    2855              : 
    2856              :       INTEGER                                            :: ibas, jbas, nbas
    2857              : 
    2858          756 :       nbas = SIZE(density_matrix, 1)
    2859          756 :       CPASSERT(SIZE(density_matrix, 2) == nbas)
    2860          756 :       CPASSERT(SIZE(new_to_old) >= nbas)
    2861         6108 :       CPASSERT(MINVAL(new_to_old(1:nbas)) >= 1)
    2862         6108 :       CPASSERT(MAXVAL(new_to_old(1:nbas)) <= SIZE(integral_matrix, 1))
    2863         6108 :       CPASSERT(MAXVAL(new_to_old(1:nbas)) <= SIZE(integral_matrix, 2))
    2864              : 
    2865          756 :       value = 0.0_dp
    2866         6108 :       DO jbas = 1, nbas
    2867        80364 :          DO ibas = 1, nbas
    2868              :             value = value + density_matrix(ibas, jbas)* &
    2869        79608 :                     integral_matrix(new_to_old(ibas), new_to_old(jbas))
    2870              :          END DO
    2871              :       END DO
    2872              : 
    2873          756 :    END FUNCTION contract_one_center_matrix
    2874              : 
    2875              : ! **************************************************************************************************
    2876              : !> \brief Replicate a distributed real-space field for atom-grid interpolation.
    2877              : !> \param local_values ...
    2878              : !> \param pw_grid ...
    2879              : !> \param group ...
    2880              : !> \param global_values ...
    2881              : ! **************************************************************************************************
    2882         1460 :    SUBROUTINE gather_native_grid_field(local_values, pw_grid, group, global_values)
    2883              :       REAL(KIND=dp), DIMENSION(:, :, :), INTENT(IN), &
    2884              :          POINTER                                         :: local_values
    2885              :       TYPE(pw_grid_type), INTENT(IN), POINTER            :: pw_grid
    2886              :       TYPE(mp_para_env_type), INTENT(IN)                 :: group
    2887              :       REAL(KIND=dp), DIMENSION(:, :, :), INTENT(OUT), &
    2888              :          POINTER                                         :: global_values
    2889              : 
    2890              :       INTEGER, DIMENSION(2, 3)                           :: bo
    2891              : 
    2892         1460 :       CPASSERT(ASSOCIATED(local_values))
    2893         1460 :       CPASSERT(ASSOCIATED(pw_grid))
    2894         1460 :       CPASSERT(.NOT. ASSOCIATED(global_values))
    2895        14600 :       bo = pw_grid%bounds_local
    2896              :       ALLOCATE (global_values(pw_grid%bounds(1, 1):pw_grid%bounds(2, 1), &
    2897              :                               pw_grid%bounds(1, 2):pw_grid%bounds(2, 2), &
    2898         7300 :                               pw_grid%bounds(1, 3):pw_grid%bounds(2, 3)))
    2899     12157880 :       global_values = 0.0_dp
    2900              :       global_values(bo(1, 1):bo(2, 1), bo(1, 2):bo(2, 2), bo(1, 3):bo(2, 3)) = &
    2901     12716680 :          local_values
    2902     24314300 :       CALL group%sum(global_values)
    2903              : 
    2904         1460 :    END SUBROUTINE gather_native_grid_field
    2905              : 
    2906              : ! **************************************************************************************************
    2907              : !> \brief Build the tensor-product interpolation stencil for one Cartesian point.
    2908              : !> \param stencil ...
    2909              : !> \param pw_grid ...
    2910              : !> \param cell ...
    2911              : !> \param point ...
    2912              : !> \param wrap_auxiliary_cell wrap all auxiliary-grid directions
    2913              : !> \param indices_only skip interpolation weights when only grid indices are needed
    2914              : ! **************************************************************************************************
    2915     46733664 :    SUBROUTINE create_native_grid_interpolation_stencil(stencil, pw_grid, cell, point, &
    2916              :                                                        wrap_auxiliary_cell, indices_only)
    2917              :       TYPE(native_grid_interpolation_stencil_type), &
    2918              :          INTENT(OUT)                                     :: stencil
    2919              :       TYPE(pw_grid_type), INTENT(IN), POINTER            :: pw_grid
    2920              :       TYPE(cell_type), INTENT(IN), POINTER               :: cell
    2921              :       REAL(KIND=dp), DIMENSION(3), INTENT(IN)            :: point
    2922              :       LOGICAL, INTENT(IN), OPTIONAL                      :: wrap_auxiliary_cell, indices_only
    2923              : 
    2924              :       INTEGER                                            :: idir, inode, relative_index
    2925              :       INTEGER, DIMENSION(3)                              :: base
    2926              :       LOGICAL                                            :: build_weights, wrap_grid
    2927              :       REAL(KIND=dp), DIMENSION(3)                        :: fraction, relative
    2928              : 
    2929       396048 :       CPASSERT(ASSOCIATED(pw_grid))
    2930       396048 :       CPASSERT(ASSOCIATED(cell))
    2931       396048 :       stencil%active = .FALSE.
    2932     15841920 :       stencil%valid = .FALSE.
    2933     15841920 :       stencil%weight = 0.0_dp
    2934       396048 :       build_weights = .TRUE.
    2935       396048 :       IF (PRESENT(indices_only)) build_weights = .NOT. indices_only
    2936      1449192 :       wrap_grid = ANY(cell%perd == 0)
    2937       396048 :       IF (PRESENT(wrap_auxiliary_cell)) wrap_grid = wrap_auxiliary_cell
    2938      5148624 :       relative = MATMUL(pw_grid%dh_inv, point)
    2939      1584192 :       DO idir = 1, 3
    2940      1188144 :          IF (cell%perd(idir) == 1 .OR. wrap_grid) THEN
    2941      1188144 :             relative(idir) = MODULO(relative(idir), REAL(pw_grid%npts(idir), KIND=dp))
    2942            0 :          ELSE IF (relative(idir) <= -REAL(native_grid_interp_offset_max, dp) .OR. &
    2943              :                   relative(idir) >= REAL(pw_grid%npts(idir) - &
    2944              :                                          native_grid_interp_offset_min, KIND=dp)) THEN
    2945            0 :             RETURN
    2946              :          END IF
    2947      1188144 :          base(idir) = FLOOR(relative(idir))
    2948      1188144 :          FRACTION(idir) = relative(idir) - REAL(base(idir), KIND=dp)
    2949      1188144 :          IF (build_weights) THEN
    2950       361116 :             CALL native_grid_lagrange_weights(FRACTION(idir), stencil%weight(:, idir))
    2951              :          END IF
    2952     15841920 :          DO inode = 1, native_grid_interp_npts
    2953     14257728 :             relative_index = base(idir) + native_grid_interp_offset_min + inode - 1
    2954     14257728 :             IF (cell%perd(idir) == 1 .OR. wrap_grid) THEN
    2955     14257728 :                relative_index = MODULO(relative_index, pw_grid%npts(idir))
    2956     14257728 :                stencil%valid(inode, idir) = .TRUE.
    2957            0 :             ELSE IF (relative_index >= 0 .AND. relative_index < pw_grid%npts(idir)) THEN
    2958            0 :                stencil%valid(inode, idir) = .TRUE.
    2959              :             END IF
    2960     15445872 :             stencil%relative_index(inode, idir) = relative_index
    2961              :          END DO
    2962              :       END DO
    2963       396048 :       stencil%active = .TRUE.
    2964              : 
    2965              :    END SUBROUTINE create_native_grid_interpolation_stencil
    2966              : 
    2967              : ! **************************************************************************************************
    2968              : !> \brief Interpolate density, gradient, and kinetic-density fields in one stencil traversal.
    2969              : !> \param density ...
    2970              : !> \param grad_x ...
    2971              : !> \param grad_y ...
    2972              : !> \param grad_z ...
    2973              : !> \param kin ...
    2974              : !> \param stencil ...
    2975              : !> \param density_value ...
    2976              : !> \param grad_value ...
    2977              : !> \param kin_value ...
    2978              : ! **************************************************************************************************
    2979       299388 :    SUBROUTINE interpolate_native_grid_fields(density, grad_x, grad_y, grad_z, kin, stencil, &
    2980              :                                              density_value, grad_value, kin_value)
    2981              :       REAL(KIND=dp), DIMENSION(:, :, :), INTENT(IN)      :: density, grad_x, grad_y, grad_z, kin
    2982              :       TYPE(native_grid_interpolation_stencil_type), &
    2983              :          INTENT(IN)                                      :: stencil
    2984              :       REAL(KIND=dp), INTENT(OUT)                         :: density_value
    2985              :       REAL(KIND=dp), DIMENSION(3), INTENT(OUT)           :: grad_value
    2986              :       REAL(KIND=dp), INTENT(OUT)                         :: kin_value
    2987              : 
    2988              :       INTEGER                                            :: inode_x, inode_y, inode_z
    2989              :       INTEGER, DIMENSION(3)                              :: index, lower_bound
    2990              :       REAL(KIND=dp)                                      :: coefficient
    2991              : 
    2992      1197552 :       CPASSERT(ALL(SHAPE(grad_x) == SHAPE(density)))
    2993      1197552 :       CPASSERT(ALL(SHAPE(grad_y) == SHAPE(density)))
    2994      1197552 :       CPASSERT(ALL(SHAPE(grad_z) == SHAPE(density)))
    2995      1197552 :       CPASSERT(ALL(SHAPE(kin) == SHAPE(density)))
    2996       299388 :       density_value = 0.0_dp
    2997       299388 :       grad_value = 0.0_dp
    2998       299388 :       kin_value = 0.0_dp
    2999       299388 :       IF (.NOT. stencil%active) RETURN
    3000              :       lower_bound = LBOUND(density)
    3001      3892044 :       DO inode_z = 1, native_grid_interp_npts
    3002      3592656 :          IF (.NOT. stencil%valid(inode_z, 3)) CYCLE
    3003      3592656 :          INDEX(3) = lower_bound(3) + stencil%relative_index(inode_z, 3)
    3004     47003916 :          DO inode_y = 1, native_grid_interp_npts
    3005     43111872 :             IF (.NOT. stencil%valid(inode_y, 2)) CYCLE
    3006     43111872 :             INDEX(2) = lower_bound(2) + stencil%relative_index(inode_y, 2)
    3007    564046992 :             DO inode_x = 1, native_grid_interp_npts
    3008    517342464 :                IF (.NOT. stencil%valid(inode_x, 1)) CYCLE
    3009    517342464 :                INDEX(1) = lower_bound(1) + stencil%relative_index(inode_x, 1)
    3010              :                coefficient = stencil%weight(inode_x, 1)* &
    3011              :                              stencil%weight(inode_y, 2)* &
    3012    517342464 :                              stencil%weight(inode_z, 3)
    3013    517342464 :                density_value = density_value + coefficient*density(INDEX(1), INDEX(2), INDEX(3))
    3014    517342464 :                grad_value(1) = grad_value(1) + coefficient*grad_x(INDEX(1), INDEX(2), INDEX(3))
    3015    517342464 :                grad_value(2) = grad_value(2) + coefficient*grad_y(INDEX(1), INDEX(2), INDEX(3))
    3016    517342464 :                grad_value(3) = grad_value(3) + coefficient*grad_z(INDEX(1), INDEX(2), INDEX(3))
    3017    560454336 :                kin_value = kin_value + coefficient*kin(INDEX(1), INDEX(2), INDEX(3))
    3018              :             END DO
    3019              :          END DO
    3020              :       END DO
    3021              : 
    3022              :    END SUBROUTINE interpolate_native_grid_fields
    3023              : 
    3024              : ! **************************************************************************************************
    3025              : !> \brief Group atom-grid rows by the disjoint PW tiles touched by their interpolation stencils.
    3026              : !> \param pw_grid ...
    3027              : !> \param cell ...
    3028              : !> \param points atom-grid coordinates
    3029              : !> \param wrap_auxiliary_cell wrap all auxiliary-grid directions
    3030              : !> \param tile_count number of tiles along each PW-grid direction
    3031              : !> \param bin_offsets CSR offsets into bin_rows
    3032              : !> \param bin_rows atom-grid rows touching each tile
    3033              : ! **************************************************************************************************
    3034          254 :    SUBROUTINE build_native_grid_adjoint_bins(pw_grid, cell, points, wrap_auxiliary_cell, &
    3035              :                                              tile_count, bin_offsets, bin_rows)
    3036              :       TYPE(pw_grid_type), INTENT(IN), POINTER            :: pw_grid
    3037              :       TYPE(cell_type), INTENT(IN), POINTER               :: cell
    3038              :       REAL(KIND=dp), DIMENSION(:, :), INTENT(IN)         :: points
    3039              :       LOGICAL, INTENT(IN)                                :: wrap_auxiliary_cell
    3040              :       INTEGER, DIMENSION(3), INTENT(OUT)                 :: tile_count
    3041              :       INTEGER, ALLOCATABLE, DIMENSION(:), INTENT(OUT)    :: bin_offsets, bin_rows
    3042              : 
    3043              :       INTEGER                                            :: candidate, ibin, idir, inode, irow, ix, &
    3044              :                                                             iy, iz, nbin, ntouched, position
    3045          254 :       INTEGER, ALLOCATABLE, DIMENSION(:)                 :: bin_counts, bin_cursor, row_bin_count
    3046          254 :       INTEGER, ALLOCATABLE, DIMENSION(:, :)              :: row_bins
    3047              :       INTEGER, DIMENSION(3)                              :: touched_count
    3048              :       INTEGER, DIMENSION(&
    3049              :          native_grid_adjoint_max_tiles_per_direction, 3) :: touched_tiles
    3050              :       TYPE(native_grid_interpolation_stencil_type)       :: stencil
    3051              : 
    3052            0 :       CPASSERT(ASSOCIATED(pw_grid))
    3053          254 :       CPASSERT(ASSOCIATED(cell))
    3054          254 :       CPASSERT(SIZE(points, 1) == 3)
    3055              :       tile_count = (pw_grid%npts + native_grid_adjoint_tile_edge - 1)/ &
    3056         1016 :                    native_grid_adjoint_tile_edge
    3057         1016 :       nbin = PRODUCT(tile_count)
    3058            0 :       ALLOCATE (row_bin_count(SIZE(points, 2)), &
    3059         1226 :                 row_bins(native_grid_adjoint_max_bins_per_row, SIZE(points, 2)))
    3060          254 :       row_bin_count = 0
    3061          254 :       row_bins = 0
    3062              : !$OMP PARALLEL DO SCHEDULE(STATIC) DEFAULT(NONE) &
    3063              : !$OMP PRIVATE(candidate, idir, inode, ix, iy, iz, ntouched, stencil, &
    3064              : !$OMP         touched_count, touched_tiles) &
    3065          254 : !$OMP SHARED(cell, points, pw_grid, row_bin_count, row_bins, tile_count, wrap_auxiliary_cell)
    3066              :       DO irow = 1, SIZE(points, 2)
    3067              :          CALL create_native_grid_interpolation_stencil( &
    3068              :             stencil, pw_grid, cell, points(:, irow), wrap_auxiliary_cell, indices_only=.TRUE.)
    3069              :          IF (.NOT. stencil%active) CYCLE
    3070              :          touched_count = 0
    3071              :          touched_tiles = 0
    3072              :          DO idir = 1, 3
    3073              :             DO inode = 1, native_grid_interp_npts
    3074              :                IF (.NOT. stencil%valid(inode, idir)) CYCLE
    3075              :                candidate = stencil%relative_index(inode, idir)/native_grid_adjoint_tile_edge + 1
    3076              :                IF (ALL(touched_tiles(1:touched_count(idir), idir) /= candidate)) THEN
    3077              :                   touched_count(idir) = touched_count(idir) + 1
    3078              :                   CPASSERT(touched_count(idir) <= SIZE(touched_tiles, 1))
    3079              :                   touched_tiles(touched_count(idir), idir) = candidate
    3080              :                END IF
    3081              :             END DO
    3082              :          END DO
    3083              :          ntouched = 0
    3084              :          DO iz = 1, touched_count(3)
    3085              :             DO iy = 1, touched_count(2)
    3086              :                DO ix = 1, touched_count(1)
    3087              :                   ntouched = ntouched + 1
    3088              :                   CPASSERT(ntouched <= native_grid_adjoint_max_bins_per_row)
    3089              :                   row_bins(ntouched, irow) = 1 + touched_tiles(ix, 1) - 1 + tile_count(1)*( &
    3090              :                                              touched_tiles(iy, 2) - 1 + tile_count(2)*( &
    3091              :                                              touched_tiles(iz, 3) - 1))
    3092              :                END DO
    3093              :             END DO
    3094              :          END DO
    3095              :          row_bin_count(irow) = ntouched
    3096              :       END DO
    3097              : !$OMP END PARALLEL DO
    3098              : 
    3099         1524 :       ALLOCATE (bin_counts(nbin), bin_cursor(nbin), bin_offsets(nbin + 1))
    3100          254 :       bin_counts = 0
    3101       275930 :       DO irow = 1, SIZE(points, 2)
    3102       551606 :          DO ibin = 1, row_bin_count(irow)
    3103       551352 :             bin_counts(row_bins(ibin, irow)) = bin_counts(row_bins(ibin, irow)) + 1
    3104              :          END DO
    3105              :       END DO
    3106          254 :       bin_offsets(1) = 1
    3107          508 :       DO ibin = 1, nbin
    3108          508 :          bin_offsets(ibin + 1) = bin_offsets(ibin) + bin_counts(ibin)
    3109              :       END DO
    3110          740 :       ALLOCATE (bin_rows(bin_offsets(nbin + 1) - 1))
    3111          508 :       bin_cursor(:) = bin_offsets(1:nbin)
    3112       275930 :       DO irow = 1, SIZE(points, 2)
    3113       551606 :          DO ibin = 1, row_bin_count(irow)
    3114       275676 :             candidate = row_bins(ibin, irow)
    3115       275676 :             position = bin_cursor(candidate)
    3116       275676 :             bin_rows(position) = irow
    3117       551352 :             bin_cursor(candidate) = position + 1
    3118              :          END DO
    3119              :       END DO
    3120          254 :       DEALLOCATE (bin_counts, bin_cursor, row_bin_count, row_bins)
    3121              : 
    3122        30734 :    END SUBROUTINE build_native_grid_adjoint_bins
    3123              : 
    3124              : ! **************************************************************************************************
    3125              : !> \brief Return the inclusive PW-grid bounds owned by one linear tile index.
    3126              : !> \param pw_grid ...
    3127              : !> \param tile_index linear tile index
    3128              : !> \param tile_count number of tiles along each PW-grid direction
    3129              : !> \param tile_lower zero-based lower grid index
    3130              : !> \param tile_upper zero-based upper grid index
    3131              : ! **************************************************************************************************
    3132          254 :    SUBROUTINE native_grid_adjoint_tile_bounds(pw_grid, tile_index, tile_count, &
    3133              :                                               tile_lower, tile_upper)
    3134              :       TYPE(pw_grid_type), INTENT(IN), POINTER            :: pw_grid
    3135              :       INTEGER, INTENT(IN)                                :: tile_index
    3136              :       INTEGER, DIMENSION(3), INTENT(IN)                  :: tile_count
    3137              :       INTEGER, DIMENSION(3), INTENT(OUT)                 :: tile_lower, tile_upper
    3138              : 
    3139              :       INTEGER                                            :: linear_tile
    3140              :       INTEGER, DIMENSION(3)                              :: expected_tile_count, tile_coord
    3141              : 
    3142          254 :       CPASSERT(ASSOCIATED(pw_grid))
    3143              :       expected_tile_count = (pw_grid%npts + native_grid_adjoint_tile_edge - 1)/ &
    3144         1016 :                             native_grid_adjoint_tile_edge
    3145         1016 :       CPASSERT(ALL(tile_count == expected_tile_count))
    3146         1016 :       CPASSERT(tile_index >= 1 .AND. tile_index <= PRODUCT(tile_count))
    3147          254 :       linear_tile = tile_index - 1
    3148          254 :       tile_coord(1) = MOD(linear_tile, tile_count(1))
    3149          254 :       linear_tile = linear_tile/tile_count(1)
    3150          254 :       tile_coord(2) = MOD(linear_tile, tile_count(2))
    3151          254 :       tile_coord(3) = linear_tile/tile_count(2)
    3152         1016 :       tile_lower = tile_coord*native_grid_adjoint_tile_edge
    3153         1016 :       tile_upper = MIN(tile_lower + native_grid_adjoint_tile_edge - 1, pw_grid%npts - 1)
    3154              : 
    3155          254 :    END SUBROUTINE native_grid_adjoint_tile_bounds
    3156              : 
    3157              : ! **************************************************************************************************
    3158              : !> \brief Apply the primitive-field interpolation transpose inside one disjoint PW tile.
    3159              : !> \param density ...
    3160              : !> \param grad ...
    3161              : !> \param kin ...
    3162              : !> \param pw_grid ...
    3163              : !> \param stencil ...
    3164              : !> \param density_value ...
    3165              : !> \param grad_value ...
    3166              : !> \param kin_value ...
    3167              : !> \param nchannels number of spin channels accumulated by the adjoint
    3168              : !> \param tile_lower zero-based lower grid index owned by this call
    3169              : !> \param tile_upper zero-based upper grid index owned by this call
    3170              : ! **************************************************************************************************
    3171       275676 :    SUBROUTINE add_native_grid_fields_adjoint_tile( &
    3172       275676 :       density, grad, kin, pw_grid, stencil, density_value, grad_value, kin_value, nchannels, &
    3173              :       tile_lower, tile_upper)
    3174              :       REAL(KIND=dp), DIMENSION(:, :), INTENT(INOUT)      :: density
    3175              :       REAL(KIND=dp), DIMENSION(:, :, :), INTENT(INOUT)   :: grad
    3176              :       REAL(KIND=dp), DIMENSION(:, :), INTENT(INOUT)      :: kin
    3177              :       TYPE(pw_grid_type), INTENT(IN), POINTER            :: pw_grid
    3178              :       TYPE(native_grid_interpolation_stencil_type), &
    3179              :          INTENT(IN)                                      :: stencil
    3180              :       REAL(KIND=dp), DIMENSION(:), INTENT(IN)            :: density_value
    3181              :       REAL(KIND=dp), DIMENSION(:, :), INTENT(IN)         :: grad_value
    3182              :       REAL(KIND=dp), DIMENSION(:), INTENT(IN)            :: kin_value
    3183              :       INTEGER, INTENT(IN)                                :: nchannels
    3184              :       INTEGER, DIMENSION(3), INTENT(IN)                  :: tile_lower, tile_upper
    3185              : 
    3186              :       INTEGER                                            :: idir, inode_x, inode_y, inode_z, ipt, &
    3187              :                                                             ispin
    3188              :       INTEGER, DIMENSION(3)                              :: relative_index
    3189              :       REAL(KIND=dp)                                      :: coefficient
    3190              : 
    3191       275676 :       CPASSERT(ASSOCIATED(pw_grid))
    3192      1102704 :       CPASSERT(SIZE(density, 1) == PRODUCT(pw_grid%npts))
    3193       275676 :       CPASSERT(SIZE(density, 2) == nchannels)
    3194      1102704 :       CPASSERT(SIZE(grad, 1) == PRODUCT(pw_grid%npts))
    3195       275676 :       CPASSERT(SIZE(grad, 2) == 3)
    3196       275676 :       CPASSERT(SIZE(grad, 3) == nchannels)
    3197      1102704 :       CPASSERT(SIZE(kin, 1) == PRODUCT(pw_grid%npts))
    3198       275676 :       CPASSERT(SIZE(kin, 2) == nchannels)
    3199       275676 :       CPASSERT(SIZE(density_value) == 2)
    3200       827028 :       CPASSERT(ALL(SHAPE(grad_value) == [3, 2]))
    3201       275676 :       CPASSERT(SIZE(kin_value) == 2)
    3202       275676 :       CPASSERT(nchannels >= 1 .AND. nchannels <= 2)
    3203      1102704 :       CPASSERT(ALL(tile_lower >= 0))
    3204      1102704 :       CPASSERT(ALL(tile_upper >= tile_lower))
    3205      1102704 :       CPASSERT(ALL(tile_upper < pw_grid%npts))
    3206       275676 :       IF (.NOT. stencil%active) RETURN
    3207      3583788 :       DO inode_z = 1, native_grid_interp_npts
    3208      3308112 :          IF (.NOT. stencil%valid(inode_z, 3)) CYCLE
    3209      3308112 :          relative_index(3) = stencil%relative_index(inode_z, 3)
    3210      3308112 :          IF (relative_index(3) < tile_lower(3) .OR. relative_index(3) > tile_upper(3)) CYCLE
    3211     43281132 :          DO inode_y = 1, native_grid_interp_npts
    3212     39697344 :             IF (.NOT. stencil%valid(inode_y, 2)) CYCLE
    3213     39697344 :             relative_index(2) = stencil%relative_index(inode_y, 2)
    3214     39697344 :             IF (relative_index(2) < tile_lower(2) .OR. relative_index(2) > tile_upper(2)) CYCLE
    3215    519373584 :             DO inode_x = 1, native_grid_interp_npts
    3216    476368128 :                IF (.NOT. stencil%valid(inode_x, 1)) CYCLE
    3217    476368128 :                relative_index(1) = stencil%relative_index(inode_x, 1)
    3218    476368128 :                IF (relative_index(1) < tile_lower(1) .OR. relative_index(1) > tile_upper(1)) CYCLE
    3219              :                ipt = 1 + relative_index(1) + pw_grid%npts(1)*( &
    3220    476368128 :                      relative_index(2) + pw_grid%npts(2)*relative_index(3))
    3221              :                coefficient = stencil%weight(inode_x, 1)* &
    3222              :                              stencil%weight(inode_y, 2)* &
    3223    476368128 :                              stencil%weight(inode_z, 3)
    3224   1033407936 :                DO ispin = 1, nchannels
    3225    517342464 :                   density(ipt, ispin) = density(ipt, ispin) + coefficient*density_value(ispin)
    3226   2069369856 :                   DO idir = 1, 3
    3227              :                      grad(ipt, idir, ispin) = grad(ipt, idir, ispin) + &
    3228   2069369856 :                                               coefficient*grad_value(idir, ispin)
    3229              :                   END DO
    3230    993710592 :                   kin(ipt, ispin) = kin(ipt, ispin) + coefficient*kin_value(ispin)
    3231              :                END DO
    3232              :             END DO
    3233              :          END DO
    3234              :       END DO
    3235              : 
    3236              :    END SUBROUTINE add_native_grid_fields_adjoint_tile
    3237              : 
    3238              : ! **************************************************************************************************
    3239              : !> \brief Interpolate a replicated native-grid field at a Cartesian point.
    3240              : !> \param values ...
    3241              : !> \param pw_grid ...
    3242              : !> \param cell ...
    3243              : !> \param point ...
    3244              : !> \param wrap_auxiliary_cell wrap all auxiliary-grid directions
    3245              : !> \return ...
    3246              : ! **************************************************************************************************
    3247       296352 :    FUNCTION interpolate_native_grid(values, pw_grid, cell, point, wrap_auxiliary_cell) RESULT(value)
    3248              :       REAL(KIND=dp), DIMENSION(:, :, :), INTENT(IN)      :: values
    3249              :       TYPE(pw_grid_type), INTENT(IN), POINTER            :: pw_grid
    3250              :       TYPE(cell_type), INTENT(IN), POINTER               :: cell
    3251              :       REAL(KIND=dp), DIMENSION(3), INTENT(IN)            :: point
    3252              :       LOGICAL, INTENT(IN), OPTIONAL                      :: wrap_auxiliary_cell
    3253              :       REAL(KIND=dp)                                      :: value
    3254              : 
    3255              :       INTEGER                                            :: corner_x, corner_y, corner_z, idir
    3256              :       INTEGER, DIMENSION(3)                              :: base, index, relative_index
    3257              :       LOGICAL                                            :: wrap_grid
    3258              :       REAL(KIND=dp)                                      :: coefficient
    3259              :       REAL(KIND=dp), DIMENSION(3)                        :: fraction, relative
    3260              :       REAL(KIND=dp), &
    3261              :          DIMENSION(native_grid_interp_npts, 3)           :: weights
    3262              : 
    3263       296352 :       CPASSERT(ASSOCIATED(pw_grid))
    3264       296352 :       CPASSERT(ASSOCIATED(cell))
    3265      1185408 :       DO idir = 1, 3
    3266      1185408 :          CPASSERT(SIZE(values, idir) == pw_grid%npts(idir))
    3267              :       END DO
    3268              : 
    3269      1050408 :       wrap_grid = ANY(cell%perd == 0)
    3270       296352 :       IF (PRESENT(wrap_auxiliary_cell)) wrap_grid = wrap_auxiliary_cell
    3271      3852576 :       relative = MATMUL(pw_grid%dh_inv, point)
    3272      1185408 :       DO idir = 1, 3
    3273       889056 :          IF (cell%perd(idir) == 1 .OR. wrap_grid) THEN
    3274       889056 :             relative(idir) = MODULO(relative(idir), REAL(pw_grid%npts(idir), KIND=dp))
    3275            0 :          ELSE IF (relative(idir) <= -REAL(native_grid_interp_offset_max, dp) .OR. &
    3276              :                   relative(idir) >= REAL(pw_grid%npts(idir) - &
    3277              :                                          native_grid_interp_offset_min, KIND=dp)) THEN
    3278       296352 :             value = 0.0_dp
    3279              :             RETURN
    3280              :          END IF
    3281       889056 :          base(idir) = FLOOR(relative(idir))
    3282       889056 :          FRACTION(idir) = relative(idir) - REAL(base(idir), KIND=dp)
    3283      1185408 :          CALL native_grid_lagrange_weights(FRACTION(idir), weights(:, idir))
    3284              :       END DO
    3285              : 
    3286              :       value = 0.0_dp
    3287      3852576 :       DO corner_z = native_grid_interp_offset_min, native_grid_interp_offset_max
    3288     46527264 :          DO corner_y = native_grid_interp_offset_min, native_grid_interp_offset_max
    3289    558327168 :             DO corner_x = native_grid_interp_offset_min, native_grid_interp_offset_max
    3290   2048385024 :                relative_index = base + [corner_x, corner_y, corner_z]
    3291              :                coefficient = weights(corner_x - native_grid_interp_offset_min + 1, 1)* &
    3292              :                              weights(corner_y - native_grid_interp_offset_min + 1, 2)* &
    3293    512096256 :                              weights(corner_z - native_grid_interp_offset_min + 1, 3)
    3294   2048385024 :                DO idir = 1, 3
    3295   2048385024 :                   IF (cell%perd(idir) == 1 .OR. wrap_grid) THEN
    3296   1536288768 :                      relative_index(idir) = MODULO(relative_index(idir), pw_grid%npts(idir))
    3297            0 :                   ELSE IF (relative_index(idir) < 0 .OR. &
    3298              :                            relative_index(idir) >= pw_grid%npts(idir)) THEN
    3299            0 :                      coefficient = 0.0_dp
    3300              :                   END IF
    3301              :                END DO
    3302    512096256 :                IF (coefficient == 0.0_dp) CYCLE
    3303   1750038624 :                index = LBOUND(values) + relative_index
    3304    554770944 :                value = value + coefficient*values(INDEX(1), INDEX(2), INDEX(3))
    3305              :             END DO
    3306              :          END DO
    3307              :       END DO
    3308              : 
    3309              :    END FUNCTION interpolate_native_grid
    3310              : 
    3311              : ! **************************************************************************************************
    3312              : !> \brief Return the Cartesian gradient of native-grid interpolation at one point.
    3313              : !> \param values ...
    3314              : !> \param pw_grid ...
    3315              : !> \param cell ...
    3316              : !> \param point ...
    3317              : !> \param wrap_auxiliary_cell wrap all auxiliary-grid directions
    3318              : !> \return ...
    3319              : ! **************************************************************************************************
    3320       493920 :    FUNCTION interpolate_native_grid_gradient(values, pw_grid, cell, point, &
    3321       493920 :                                              wrap_auxiliary_cell) RESULT(gradient)
    3322              :       REAL(KIND=dp), DIMENSION(:, :, :), INTENT(IN)      :: values
    3323              :       TYPE(pw_grid_type), INTENT(IN), POINTER            :: pw_grid
    3324              :       TYPE(cell_type), INTENT(IN), POINTER               :: cell
    3325              :       REAL(KIND=dp), DIMENSION(3), INTENT(IN)            :: point
    3326              :       LOGICAL, INTENT(IN), OPTIONAL                      :: wrap_auxiliary_cell
    3327              :       REAL(KIND=dp), DIMENSION(3)                        :: gradient
    3328              : 
    3329              :       INTEGER                                            :: corner_x, corner_y, corner_z, idir, jdir
    3330              :       INTEGER, DIMENSION(3)                              :: base, corner_index, index, relative_index
    3331              :       LOGICAL                                            :: wrap_grid
    3332              :       REAL(KIND=dp)                                      :: coefficient
    3333              :       REAL(KIND=dp), DIMENSION(3)                        :: fraction, gradient_relative, relative
    3334              :       REAL(KIND=dp), &
    3335              :          DIMENSION(native_grid_interp_npts, 3)           :: derivative_weights, weights
    3336              : 
    3337       493920 :       CPASSERT(ASSOCIATED(pw_grid))
    3338       493920 :       CPASSERT(ASSOCIATED(cell))
    3339      1975680 :       DO idir = 1, 3
    3340      1975680 :          CPASSERT(SIZE(values, idir) == pw_grid%npts(idir))
    3341              :       END DO
    3342              : 
    3343      1750680 :       wrap_grid = ANY(cell%perd == 0)
    3344       493920 :       IF (PRESENT(wrap_auxiliary_cell)) wrap_grid = wrap_auxiliary_cell
    3345      6420960 :       relative = MATMUL(pw_grid%dh_inv, point)
    3346      1975680 :       DO idir = 1, 3
    3347      1481760 :          IF (cell%perd(idir) == 1 .OR. wrap_grid) THEN
    3348      1481760 :             relative(idir) = MODULO(relative(idir), REAL(pw_grid%npts(idir), KIND=dp))
    3349            0 :          ELSE IF (relative(idir) <= -REAL(native_grid_interp_offset_max, dp) .OR. &
    3350              :                   relative(idir) >= REAL(pw_grid%npts(idir) - &
    3351              :                                          native_grid_interp_offset_min, KIND=dp)) THEN
    3352            0 :             gradient = 0.0_dp
    3353            0 :             RETURN
    3354              :          END IF
    3355      1481760 :          base(idir) = FLOOR(relative(idir))
    3356      1481760 :          FRACTION(idir) = relative(idir) - REAL(base(idir), KIND=dp)
    3357              :          CALL native_grid_lagrange_weights( &
    3358      1975680 :             FRACTION(idir), weights(:, idir), derivative_weights(:, idir))
    3359              :       END DO
    3360              : 
    3361       493920 :       gradient_relative = 0.0_dp
    3362      6420960 :       DO corner_z = native_grid_interp_offset_min, native_grid_interp_offset_max
    3363     77545440 :          DO corner_y = native_grid_interp_offset_min, native_grid_interp_offset_max
    3364    930545280 :             DO corner_x = native_grid_interp_offset_min, native_grid_interp_offset_max
    3365   3413975040 :                relative_index = base + [corner_x, corner_y, corner_z]
    3366              :                corner_index = [corner_x, corner_y, corner_z] - &
    3367   3413975040 :                               native_grid_interp_offset_min + 1
    3368   3413975040 :                DO idir = 1, 3
    3369   3413975040 :                   IF (cell%perd(idir) == 1 .OR. wrap_grid) THEN
    3370   2560481280 :                      relative_index(idir) = MODULO(relative_index(idir), pw_grid%npts(idir))
    3371            0 :                   ELSE IF (relative_index(idir) < 0 .OR. &
    3372              :                            relative_index(idir) >= pw_grid%npts(idir)) THEN
    3373              :                      EXIT
    3374              :                   END IF
    3375              :                END DO
    3376    853493760 :                IF (idir <= 3) CYCLE
    3377   3413975040 :                index = LBOUND(values) + relative_index
    3378   3485099520 :                DO idir = 1, 3
    3379              :                   coefficient = 1.0_dp
    3380  10241925120 :                   DO jdir = 1, 3
    3381  10241925120 :                      IF (jdir == idir) THEN
    3382              :                         coefficient = coefficient*derivative_weights( &
    3383   2560481280 :                                       corner_index(jdir), jdir)
    3384              :                      ELSE
    3385              :                         coefficient = coefficient*weights( &
    3386   5120962560 :                                       corner_index(jdir), jdir)
    3387              :                      END IF
    3388              :                   END DO
    3389              :                   gradient_relative(idir) = gradient_relative(idir) + &
    3390   3413975040 :                                             coefficient*values(INDEX(1), INDEX(2), INDEX(3))
    3391              :                END DO
    3392              :             END DO
    3393              :          END DO
    3394              :       END DO
    3395       493920 :       gradient = MATMUL(TRANSPOSE(pw_grid%dh_inv), gradient_relative)
    3396              : 
    3397              :    END FUNCTION interpolate_native_grid_gradient
    3398              : 
    3399              : ! **************************************************************************************************
    3400              : !> \brief Build the value and optional derivative weights for the native-grid interpolation.
    3401              : !> \param fraction fractional coordinate between two grid points
    3402              : !> \param weights interpolation weights
    3403              : !> \param derivative_weights optional derivatives with respect to fraction
    3404              : ! **************************************************************************************************
    3405      2731932 :    SUBROUTINE native_grid_lagrange_weights(fraction, weights, derivative_weights)
    3406              :       REAL(KIND=dp), INTENT(IN)                          :: fraction
    3407              :       REAL(KIND=dp), DIMENSION(:), INTENT(OUT)           :: weights
    3408              :       REAL(KIND=dp), DIMENSION(:), INTENT(OUT), OPTIONAL :: derivative_weights
    3409              : 
    3410              :       INTEGER                                            :: inode, jnode, knode, npoints
    3411              :       REAL(KIND=dp)                                      :: denominator, derivative, numerator
    3412      5463864 :       REAL(KIND=dp), DIMENSION(SIZE(weights))            :: nodes
    3413              : 
    3414      2731932 :       npoints = SIZE(weights)
    3415      2731932 :       IF (PRESENT(derivative_weights)) THEN
    3416      1481760 :          CPASSERT(SIZE(derivative_weights) == npoints)
    3417              :       END IF
    3418     35515116 :       DO inode = 1, npoints
    3419     35515116 :          nodes(inode) = REAL(native_grid_interp_offset_min + inode - 1, dp)
    3420              :       END DO
    3421     35515116 :       DO inode = 1, npoints
    3422              :          denominator = 1.0_dp
    3423              :          numerator = 1.0_dp
    3424    426181392 :          DO jnode = 1, npoints
    3425    393398208 :             IF (jnode == inode) CYCLE
    3426    360615024 :             denominator = denominator*(nodes(inode) - nodes(jnode))
    3427    426181392 :             numerator = numerator*(fraction - nodes(jnode))
    3428              :          END DO
    3429     32783184 :          weights(inode) = numerator/denominator
    3430     35515116 :          IF (PRESENT(derivative_weights)) THEN
    3431              :             derivative = 0.0_dp
    3432    231154560 :             DO knode = 1, npoints
    3433    213373440 :                IF (knode == inode) CYCLE
    3434              :                numerator = 1.0_dp
    3435   2542700160 :                DO jnode = 1, npoints
    3436   2347107840 :                   IF (jnode == inode .OR. jnode == knode) CYCLE
    3437   2542700160 :                   numerator = numerator*(fraction - nodes(jnode))
    3438              :                END DO
    3439    231154560 :                derivative = derivative + numerator/denominator
    3440              :             END DO
    3441     17781120 :             derivative_weights(inode) = derivative
    3442              :          END IF
    3443              :       END DO
    3444              : 
    3445      2731932 :    END SUBROUTINE native_grid_lagrange_weights
    3446              : 
    3447              : ! **************************************************************************************************
    3448              : !> \brief Conservatively bound periodic images that can intersect a Cartesian support sphere.
    3449              : !> \param cell current cell and periodicity
    3450              : !> \param fractional target-minus-source displacement in lattice coordinates
    3451              : !> \param cutoff current, density-dependent Cartesian support radius
    3452              : !> \param image_shell original enclosing image shell
    3453              : !> \param lower inclusive lower image indices
    3454              : !> \param upper inclusive upper image indices (may be smaller than lower)
    3455              : ! **************************************************************************************************
    3456       543538 :    SUBROUTINE atom_grid_image_bounds(cell, fractional, cutoff, image_shell, lower, upper)
    3457              :       TYPE(cell_type), INTENT(IN), POINTER               :: cell
    3458              :       REAL(dp), INTENT(IN)                               :: fractional(3), cutoff
    3459              :       INTEGER, INTENT(IN)                                :: image_shell(3)
    3460              :       INTEGER, INTENT(OUT)                               :: lower(3), upper(3)
    3461              : 
    3462              :       INTEGER                                            :: center, idir
    3463              :       REAL(dp)                                           :: condition_bound, padding, radius
    3464              : 
    3465              :       ! |(H^-1 d)_i| <= cutoff ||(H^-1)_i|| also holds for triclinic cells.
    3466              :       ! Inflate the bounds for cancellation in fractional coordinates and the inverse cell.
    3467     13588450 :       condition_bound = MAX(1.0_dp, SUM(ABS(cell%hmat))*SUM(ABS(cell%h_inv)))
    3468       543538 :       lower = 0
    3469       543538 :       upper = 0
    3470      2174152 :       DO idir = 1, 3
    3471      1630614 :          IF (cell%perd(idir) == 0) CYCLE
    3472      1330590 :          center = NINT(fractional(idir))
    3473      5322360 :          radius = cutoff*SQRT(SUM(cell%h_inv(idir, :)**2))
    3474              :          padding = 128.0_dp*EPSILON(1.0_dp)*condition_bound* &
    3475      5322360 :                    MAX(1.0_dp, MAXVAL(ABS(fractional)), radius)
    3476      1330590 :          lower(idir) = MAX(center - image_shell(idir), CEILING(fractional(idir) - radius - padding))
    3477      2174152 :          upper(idir) = MIN(center + image_shell(idir), FLOOR(fractional(idir) + radius + padding))
    3478              :       END DO
    3479       543538 :    END SUBROUTINE atom_grid_image_bounds
    3480              : 
    3481              : ! **************************************************************************************************
    3482              : !> \brief Express one radial node's first and second derivatives as linear combinations of the
    3483              : !>        local node values used by the C2-continuous quintic Hermite interpolant.
    3484              : !> \param grid_atom radial source grid
    3485              : !> \param descending whether radial nodes are stored in descending order
    3486              : !> \param node logical index of the node whose derivatives are required
    3487              : !> \param logical_start first logical index represented by the coefficient arrays
    3488              : !> \param slope coefficients of the first derivative
    3489              : !> \param curvature coefficients of the second derivative
    3490              : ! **************************************************************************************************
    3491       357566 :    SUBROUTINE radial_node_derivative_coefficients( &
    3492              :       grid_atom, descending, node, logical_start, slope, curvature)
    3493              :       TYPE(grid_atom_type), POINTER                      :: grid_atom
    3494              :       LOGICAL, INTENT(IN)                                :: descending
    3495              :       INTEGER, INTENT(IN)                                :: node, logical_start
    3496              :       REAL(dp), DIMENSION(4), INTENT(OUT)                :: slope, curvature
    3497              : 
    3498              :       INTEGER                                            :: center, hi, lo, n
    3499              :       REAL(dp)                                           :: h_hi, h_lo, x_center, x_hi, x_lo
    3500              : 
    3501       357566 :       n = grid_atom%nr
    3502       357566 :       slope = 0.0_dp
    3503       357566 :       curvature = 0.0_dp
    3504       357566 :       IF (node == 1) THEN
    3505              :          lo = 1
    3506              :          hi = 2
    3507       357550 :       ELSE IF (node == n) THEN
    3508           16 :          lo = n - 1
    3509           16 :          hi = n
    3510              :       ELSE
    3511       357534 :          lo = node - 1
    3512       357534 :          hi = node + 1
    3513              :       END IF
    3514       357566 :       x_lo = grid_atom%rad(MERGE(n + 1 - lo, lo, descending))
    3515       357566 :       x_hi = grid_atom%rad(MERGE(n + 1 - hi, hi, descending))
    3516       357566 :       slope(lo - logical_start + 1) = -1.0_dp/(x_hi - x_lo)
    3517       357566 :       slope(hi - logical_start + 1) = 1.0_dp/(x_hi - x_lo)
    3518              : 
    3519       357566 :       IF (n < 3) RETURN
    3520       357566 :       center = MIN(MAX(node, 2), n - 1)
    3521       357566 :       lo = center - 1
    3522       357566 :       hi = center + 1
    3523       357566 :       x_lo = grid_atom%rad(MERGE(n + 1 - lo, lo, descending))
    3524       357566 :       x_center = grid_atom%rad(MERGE(n + 1 - center, center, descending))
    3525       357566 :       x_hi = grid_atom%rad(MERGE(n + 1 - hi, hi, descending))
    3526       357566 :       h_lo = x_center - x_lo
    3527       357566 :       h_hi = x_hi - x_center
    3528       357566 :       curvature(lo - logical_start + 1) = 2.0_dp/(h_lo*(h_lo + h_hi))
    3529              :       curvature(center - logical_start + 1) = &
    3530       357566 :          -2.0_dp*(1.0_dp/h_lo + 1.0_dp/h_hi)/(h_lo + h_hi)
    3531       357566 :       curvature(hi - logical_start + 1) = 2.0_dp/(h_hi*(h_lo + h_hi))
    3532              : 
    3533              :    END SUBROUTINE radial_node_derivative_coefficients
    3534              : 
    3535              : ! **************************************************************************************************
    3536              : !> \brief Build mutually consistent value and Cartesian-derivative weights for interpolation from
    3537              : !>        a GAPW radial/Lebedev atom grid to one arbitrary local displacement.
    3538              : !> \param grid_atom source atom grid
    3539              : !> \param harmonics source spherical harmonics
    3540              : !> \param displacement point minus source-image coordinate
    3541              : !> \param cutoff compact support radius
    3542              : !> \param radial_indices active radial nodes
    3543              : !> \param radial_weights interpolation weights on the active radial nodes
    3544              : !> \param radial_derivative_weights optional radial derivatives of the interpolation weights
    3545              : !> \param nradial number of active radial nodes
    3546              : !> \param angular_weights angular interpolation weights
    3547              : !> \param angular_derivative_weights optional Cartesian derivatives of the angular weights
    3548              : !> \param active whether the point lies inside the compact support
    3549              : ! **************************************************************************************************
    3550       178815 :    SUBROUTINE atom_grid_interpolation_weights( &
    3551              :       grid_atom, harmonics, displacement, cutoff, radial_indices, radial_weights, &
    3552       178815 :       radial_derivative_weights, nradial, angular_weights, angular_derivative_weights, active)
    3553              :       TYPE(grid_atom_type), POINTER                      :: grid_atom
    3554              :       TYPE(harmonics_atom_type), POINTER                 :: harmonics
    3555              :       REAL(dp), DIMENSION(3), INTENT(IN)                 :: displacement
    3556              :       REAL(dp), INTENT(IN)                               :: cutoff
    3557              :       INTEGER, DIMENSION(4), INTENT(OUT)                 :: radial_indices
    3558              :       REAL(dp), DIMENSION(4), INTENT(OUT)                :: radial_weights
    3559              :       REAL(dp), DIMENSION(4), INTENT(OUT), OPTIONAL      :: radial_derivative_weights
    3560              :       INTEGER, INTENT(OUT)                               :: nradial
    3561              :       REAL(dp), DIMENSION(:), INTENT(OUT)                :: angular_weights
    3562              :       REAL(dp), DIMENSION(:, :), INTENT(OUT), OPTIONAL   :: angular_derivative_weights
    3563              :       LOGICAL, INTENT(OUT)                               :: active
    3564              : 
    3565              :       INTEGER                                            :: ia, ic, inode, iso, l, left, left_pos, &
    3566              :                                                             logical_end, logical_start, lx, ly, &
    3567              :                                                             lz, n, right_pos, shell_index
    3568              :       LOGICAL                                            :: descending
    3569              :       REAL(dp)                                           :: dh00, dh01, dh10, dh11, dh20, dh21, h00, &
    3570              :                                                             h01, h10, h11, h20, h21, h_interval, &
    3571              :                                                             monomial, radius, solid_derivative, t, &
    3572              :                                                             x1, x2
    3573              :       REAL(dp), DIMENSION(3)                             :: direction
    3574       357630 :       REAL(dp), DIMENSION(harmonics%max_s_harm)          :: angular_values
    3575              :       REAL(dp), DIMENSION(4)                             :: curvature_left, curvature_right, &
    3576              :                                                             slope_left, slope_right
    3577           32 :       REAL(dp), DIMENSION(3, harmonics%max_s_harm)       :: angular_value_derivatives
    3578              : 
    3579       178815 :       CPASSERT(ASSOCIATED(grid_atom))
    3580       178815 :       CPASSERT(ASSOCIATED(harmonics))
    3581       178815 :       CPASSERT(SIZE(angular_weights) == grid_atom%ng_sphere)
    3582       178815 :       IF (PRESENT(angular_derivative_weights)) THEN
    3583        29955 :          CPASSERT(SIZE(angular_derivative_weights, 1) == 3)
    3584        29955 :          CPASSERT(SIZE(angular_derivative_weights, 2) == grid_atom%ng_sphere)
    3585              :       END IF
    3586              : 
    3587       178815 :       radial_indices = 0
    3588       178815 :       radial_weights = 0.0_dp
    3589       178815 :       IF (PRESENT(radial_derivative_weights)) radial_derivative_weights = 0.0_dp
    3590      7709481 :       angular_weights = 0.0_dp
    3591      5854599 :       IF (PRESENT(angular_derivative_weights)) angular_derivative_weights = 0.0_dp
    3592       178815 :       nradial = 0
    3593       178815 :       active = .FALSE.
    3594       178815 :       n = grid_atom%nr
    3595       178815 :       descending = grid_atom%rad(1) > grid_atom%rad(n)
    3596       715260 :       radius = SQRT(SUM(displacement**2))
    3597       178847 :       IF (radius > cutoff .OR. &
    3598              :           radius > grid_atom%rad(MERGE(1, n, descending))) RETURN
    3599       178799 :       IF (radius <= 1.0E-12_dp) RETURN
    3600       715132 :       direction = displacement/radius
    3601              : 
    3602       178783 :       CPASSERT(n >= 2)
    3603       178783 :       left = n - 1
    3604       357542 :       IF (radius <= grid_atom%rad(MERGE(n, 1, descending))) THEN
    3605            0 :          left = 1
    3606              :       ELSE
    3607      4338443 :          DO inode = 1, n - 1
    3608      4338531 :             IF (radius <= grid_atom%rad(MERGE(n - inode, inode + 1, descending))) THEN
    3609       178783 :                left = inode
    3610       178783 :                EXIT
    3611              :             END IF
    3612              :          END DO
    3613              :       END IF
    3614              : 
    3615       178783 :       logical_start = MAX(1, left - 1)
    3616       178783 :       logical_end = MIN(n, left + 2)
    3617       178783 :       nradial = logical_end - logical_start + 1
    3618       893883 :       DO inode = 1, nradial
    3619              :          radial_indices(inode) = MERGE(n + 2 - logical_start - inode, &
    3620       893963 :                                        logical_start + inode - 1, descending)
    3621              :       END DO
    3622       178783 :       left_pos = left - logical_start + 1
    3623       178783 :       right_pos = left_pos + 1
    3624       178783 :       x1 = grid_atom%rad(radial_indices(left_pos))
    3625       178783 :       x2 = grid_atom%rad(radial_indices(right_pos))
    3626       178783 :       h_interval = x2 - x1
    3627       178783 :       t = (radius - x1)/h_interval
    3628              : 
    3629       178783 :       h00 = 1.0_dp - 10.0_dp*t**3 + 15.0_dp*t**4 - 6.0_dp*t**5
    3630       178783 :       h10 = t - 6.0_dp*t**3 + 8.0_dp*t**4 - 3.0_dp*t**5
    3631       178783 :       h20 = 0.5_dp*(t**2 - 3.0_dp*t**3 + 3.0_dp*t**4 - t**5)
    3632       178783 :       h01 = 10.0_dp*t**3 - 15.0_dp*t**4 + 6.0_dp*t**5
    3633       178783 :       h11 = -4.0_dp*t**3 + 7.0_dp*t**4 - 3.0_dp*t**5
    3634       178783 :       h21 = 0.5_dp*(t**3 - 2.0_dp*t**4 + t**5)
    3635              : 
    3636              :       CALL radial_node_derivative_coefficients( &
    3637       178783 :          grid_atom, descending, left, logical_start, slope_left, curvature_left)
    3638              :       CALL radial_node_derivative_coefficients( &
    3639       178783 :          grid_atom, descending, left + 1, logical_start, slope_right, curvature_right)
    3640       178783 :       radial_weights(left_pos) = radial_weights(left_pos) + h00
    3641       178783 :       radial_weights(right_pos) = radial_weights(right_pos) + h01
    3642              :       radial_weights(1:nradial) = radial_weights(1:nradial) + &
    3643              :                                   h_interval*(h10*slope_left(1:nradial) + &
    3644              :                                               h11*slope_right(1:nradial)) + &
    3645              :                                   h_interval**2*(h20*curvature_left(1:nradial) + &
    3646       893883 :                                                  h21*curvature_right(1:nradial))
    3647       178783 :       IF (PRESENT(radial_derivative_weights)) THEN
    3648        29955 :          dh00 = -30.0_dp*t**2 + 60.0_dp*t**3 - 30.0_dp*t**4
    3649        29955 :          dh10 = 1.0_dp - 18.0_dp*t**2 + 32.0_dp*t**3 - 15.0_dp*t**4
    3650        29955 :          dh20 = 0.5_dp*(2.0_dp*t - 9.0_dp*t**2 + 12.0_dp*t**3 - 5.0_dp*t**4)
    3651        29955 :          dh01 = 30.0_dp*t**2 - 60.0_dp*t**3 + 30.0_dp*t**4
    3652        29955 :          dh11 = -12.0_dp*t**2 + 28.0_dp*t**3 - 15.0_dp*t**4
    3653        29955 :          dh21 = 0.5_dp*(3.0_dp*t**2 - 8.0_dp*t**3 + 5.0_dp*t**4)
    3654              :          radial_derivative_weights(left_pos) = &
    3655        29955 :             radial_derivative_weights(left_pos) + dh00/h_interval
    3656              :          radial_derivative_weights(right_pos) = &
    3657        29955 :             radial_derivative_weights(right_pos) + dh01/h_interval
    3658              :          radial_derivative_weights(1:nradial) = radial_derivative_weights(1:nradial) + &
    3659              :                                                 dh10*slope_left(1:nradial) + &
    3660              :                                                 dh11*slope_right(1:nradial) + &
    3661              :                                                 h_interval*(dh20*curvature_left(1:nradial) + &
    3662       149775 :                                                             dh21*curvature_right(1:nradial))
    3663              :       END IF
    3664              : 
    3665      1067526 :       angular_values = 0.0_dp
    3666       860939 :       IF (PRESENT(angular_derivative_weights)) angular_value_derivatives = 0.0_dp
    3667      1067526 :       DO iso = 1, harmonics%max_s_harm
    3668       888743 :          l = indso(1, iso)
    3669       888743 :          CALL y_lm(direction, angular_values(iso), l, indso(2, iso))
    3670       888743 :          IF (l == 0 .OR. .NOT. PRESENT(angular_derivative_weights)) CYCLE
    3671       140584 :          shell_index = iso - nsoset(l - 1)
    3672       968806 :          DO ic = 1, nco(l)
    3673       828222 :             lx = indco(1, ic + ncoset(l - 1))
    3674       828222 :             ly = indco(2, ic + ncoset(l - 1))
    3675       828222 :             lz = indco(3, ic + ncoset(l - 1))
    3676       828222 :             IF (lx > 0) THEN
    3677              :                monomial = REAL(lx, dp)*direction(1)**(lx - 1)* &
    3678       424314 :                           direction(2)**ly*direction(3)**lz
    3679              :                angular_value_derivatives(1, iso) = angular_value_derivatives(1, iso) + &
    3680       424314 :                                                    orbtramat(l)%slm(shell_index, ic)*monomial
    3681              :             END IF
    3682       828222 :             IF (ly > 0) THEN
    3683              :                monomial = direction(1)**lx*REAL(ly, dp)*direction(2)**(ly - 1)* &
    3684       424314 :                           direction(3)**lz
    3685              :                angular_value_derivatives(2, iso) = angular_value_derivatives(2, iso) + &
    3686       424314 :                                                    orbtramat(l)%slm(shell_index, ic)*monomial
    3687              :             END IF
    3688       968806 :             IF (lz > 0) THEN
    3689              :                monomial = direction(1)**lx*direction(2)**ly* &
    3690       424314 :                           REAL(lz, dp)*direction(3)**(lz - 1)
    3691              :                angular_value_derivatives(3, iso) = angular_value_derivatives(3, iso) + &
    3692       424314 :                                                    orbtramat(l)%slm(shell_index, ic)*monomial
    3693              :             END IF
    3694              :          END DO
    3695       741119 :          DO inode = 1, 3
    3696       421752 :             solid_derivative = angular_value_derivatives(inode, iso)
    3697              :             angular_value_derivatives(inode, iso) = (solid_derivative - &
    3698              :                                                      REAL(l, dp)*angular_values(iso)* &
    3699      1310495 :                                                      direction(inode))/radius
    3700              :          END DO
    3701              :       END DO
    3702              : 
    3703      7707849 :       DO ia = 1, grid_atom%ng_sphere
    3704              :          angular_weights(ia) = grid_atom%wa(ia)* &
    3705              :                                DOT_PRODUCT(harmonics%slm(ia, 1:harmonics%max_s_harm), &
    3706     45615492 :                                            angular_values)
    3707      7707849 :          IF (PRESENT(angular_derivative_weights)) THEN
    3708      5675784 :             DO inode = 1, 3
    3709              :                angular_derivative_weights(inode, ia) = grid_atom%wa(ia)* &
    3710              :                                                        DOT_PRODUCT(harmonics%slm(ia, 1:harmonics%max_s_harm), &
    3711     28055838 :                                                                    angular_value_derivatives(inode, :))
    3712              :             END DO
    3713              :          END IF
    3714              :       END DO
    3715       178783 :       active = .TRUE.
    3716              : 
    3717              :    END SUBROUTINE atom_grid_interpolation_weights
    3718              : 
    3719              : ! **************************************************************************************************
    3720              : !> \brief Interpolate hard-minus-soft primitive fields and their spatial derivatives from one
    3721              : !>        GAPW atom grid.
    3722              : !> \param grid_atom radial and angular source grid
    3723              : !> \param harmonics spherical-harmonic representation of the source grid
    3724              : !> \param displacement target point relative to the source-atom image
    3725              : !> \param cutoff compact support radius of the source fields
    3726              : !> \param nspins number of spin channels
    3727              : !> \param rho_h hard one-center density values
    3728              : !> \param rho_s soft one-center density values
    3729              : !> \param drho_h hard one-center density-gradient values
    3730              : !> \param drho_s soft one-center density-gradient values
    3731              : !> \param tau_h hard one-center kinetic-energy-density values
    3732              : !> \param tau_s soft one-center kinetic-energy-density values
    3733              : !> \param density interpolated hard-minus-soft density
    3734              : !> \param gradient interpolated hard-minus-soft density gradient
    3735              : !> \param kin interpolated hard-minus-soft kinetic-energy density
    3736              : !> \param density_spatial Cartesian derivatives of density
    3737              : !> \param gradient_spatial Cartesian derivatives of the density gradient
    3738              : !> \param kin_spatial Cartesian derivatives of the kinetic-energy density
    3739              : !> \param calculate_spatial evaluate spatial derivatives (default true), otherwise return zeros
    3740              : ! **************************************************************************************************
    3741       104385 :    SUBROUTINE interpolate_gapw_atom_grid_fields( &
    3742       208770 :       grid_atom, harmonics, displacement, cutoff, nspins, rho_h, rho_s, drho_h, drho_s, &
    3743       104385 :       tau_h, tau_s, density, gradient, kin, density_spatial, gradient_spatial, kin_spatial, calculate_spatial)
    3744              :       TYPE(grid_atom_type), POINTER                      :: grid_atom
    3745              :       TYPE(harmonics_atom_type), POINTER                 :: harmonics
    3746              :       REAL(dp), DIMENSION(3), INTENT(IN)                 :: displacement
    3747              :       REAL(dp), INTENT(IN)                               :: cutoff
    3748              :       INTEGER, INTENT(IN)                                :: nspins
    3749              :       REAL(dp), DIMENSION(:, :, :), INTENT(IN)           :: rho_h, rho_s
    3750              :       REAL(dp), DIMENSION(:, :, :, :), INTENT(IN)        :: drho_h, drho_s
    3751              :       REAL(dp), DIMENSION(:, :, :), INTENT(IN)           :: tau_h, tau_s
    3752              :       REAL(dp), DIMENSION(2), INTENT(OUT)                :: density
    3753              :       REAL(dp), DIMENSION(3, 2), INTENT(OUT)             :: gradient
    3754              :       REAL(dp), DIMENSION(2), INTENT(OUT)                :: kin
    3755              :       REAL(dp), DIMENSION(3, 2), INTENT(OUT)             :: density_spatial
    3756              :       REAL(dp), DIMENSION(3, 3, 2), INTENT(OUT)          :: gradient_spatial
    3757              :       REAL(dp), DIMENSION(3, 2), INTENT(OUT)             :: kin_spatial
    3758              :       LOGICAL, INTENT(IN), OPTIONAL                      :: calculate_spatial
    3759              : 
    3760              :       INTEGER                                            :: ia, idir, inode, ir, ispin, jdir, nradial
    3761              :       INTEGER, DIMENSION(4)                              :: radial_indices
    3762              :       LOGICAL                                            :: active, need_spatial
    3763              :       REAL(dp)                                           :: derivative_weight, weight
    3764       208770 :       REAL(dp), DIMENSION(grid_atom%ng_sphere)           :: angular_weights
    3765              :       REAL(dp), DIMENSION(4)                             :: radial_derivative_weights, radial_weights
    3766       208770 :       REAL(dp), DIMENSION(3, grid_atom%ng_sphere)        :: angular_derivative_weights
    3767              : 
    3768       104385 :       density = 0.0_dp
    3769       104385 :       gradient = 0.0_dp
    3770       104385 :       kin = 0.0_dp
    3771       104385 :       density_spatial = 0.0_dp
    3772       104385 :       gradient_spatial = 0.0_dp
    3773       104385 :       kin_spatial = 0.0_dp
    3774       104385 :       need_spatial = .TRUE.
    3775       104385 :       IF (PRESENT(calculate_spatial)) need_spatial = calculate_spatial
    3776        74430 :       IF (need_spatial) THEN
    3777              :          CALL atom_grid_interpolation_weights( &
    3778              :             grid_atom, harmonics, displacement, cutoff, radial_indices, radial_weights, &
    3779        29955 :             radial_derivative_weights, nradial, angular_weights, angular_derivative_weights, active)
    3780              :       ELSE
    3781              :          CALL atom_grid_interpolation_weights( &
    3782              :             grid_atom, harmonics, displacement, cutoff, radial_indices, radial_weights, &
    3783        74430 :             nradial=nradial, angular_weights=angular_weights, active=active)
    3784              :       END IF
    3785       104385 :       IF (active) THEN
    3786       521829 :          DO inode = 1, nradial
    3787       417460 :             ir = radial_indices(inode)
    3788     18417053 :             DO ia = 1, grid_atom%ng_sphere
    3789     17895224 :                weight = radial_weights(inode)*angular_weights(ia)
    3790     36209908 :                DO ispin = 1, nspins
    3791              :                   density(ispin) = density(ispin) + &
    3792     17897224 :                                    weight*(rho_h(ia, ir, ispin) - rho_s(ia, ir, ispin))
    3793              :                   kin(ispin) = kin(ispin) + &
    3794     17897224 :                                weight*(tau_h(ia, ir, ispin) - tau_s(ia, ir, ispin))
    3795     89484120 :                   DO idir = 1, 3
    3796              :                      gradient(idir, ispin) = gradient(idir, ispin) + &
    3797              :                                              weight*(drho_h(idir, ia, ir, ispin) - &
    3798     53691672 :                                                      drho_s(idir, ia, ir, ispin))
    3799     53691672 :                      IF (.NOT. need_spatial) CYCLE
    3800              :                      derivative_weight = radial_derivative_weights(inode)* &
    3801              :                                          displacement(idir)/SQRT(SUM(displacement**2))* &
    3802              :                                          angular_weights(ia) + radial_weights(inode)* &
    3803     68109408 :                                          angular_derivative_weights(idir, ia)
    3804              :                      density_spatial(idir, ispin) = density_spatial(idir, ispin) + &
    3805     17027352 :                                                     derivative_weight*(rho_h(ia, ir, ispin) - rho_s(ia, ir, ispin))
    3806              :                      kin_spatial(idir, ispin) = kin_spatial(idir, ispin) + &
    3807     17027352 :                                                 derivative_weight*(tau_h(ia, ir, ispin) - tau_s(ia, ir, ispin))
    3808     86006632 :                      DO jdir = 1, 3
    3809              :                         gradient_spatial(jdir, idir, ispin) = &
    3810              :                            gradient_spatial(jdir, idir, ispin) + derivative_weight*( &
    3811    104773728 :                            drho_h(jdir, ia, ir, ispin) - drho_s(jdir, ia, ir, ispin))
    3812              :                      END DO
    3813              :                   END DO
    3814              :                END DO
    3815              :             END DO
    3816              :          END DO
    3817              :       END IF
    3818       104385 :    END SUBROUTINE interpolate_gapw_atom_grid_fields
    3819              : 
    3820              : ! **************************************************************************************************
    3821              : !> \brief Apply the exact transpose of interpolate_gapw_atom_grid_fields to one-center potentials.
    3822              : !> \param grid_atom radial and angular source grid
    3823              : !> \param harmonics spherical-harmonic representation of the source grid
    3824              : !> \param displacement target point relative to the source-atom image
    3825              : !> \param cutoff compact support radius of the source fields
    3826              : !> \param nspins number of spin channels
    3827              : !> \param density_adjoint model derivative with respect to density
    3828              : !> \param gradient_adjoint model derivative with respect to the density gradient
    3829              : !> \param kin_adjoint model derivative with respect to kinetic-energy density
    3830              : !> \param vxc_h accumulated hard one-center density potential
    3831              : !> \param vxc_s accumulated soft one-center density potential
    3832              : !> \param vxg_h accumulated hard one-center density-gradient potential
    3833              : !> \param vxg_s accumulated soft one-center density-gradient potential
    3834              : !> \param vtau_h accumulated hard one-center kinetic-energy-density potential
    3835              : !> \param vtau_s accumulated soft one-center kinetic-energy-density potential
    3836              : ! **************************************************************************************************
    3837        74430 :    SUBROUTINE add_gapw_atom_grid_interpolation_adjoint( &
    3838              :       grid_atom, harmonics, displacement, cutoff, nspins, density_adjoint, gradient_adjoint, &
    3839        74430 :       kin_adjoint, vxc_h, vxc_s, vxg_h, vxg_s, vtau_h, vtau_s)
    3840              :       TYPE(grid_atom_type), POINTER                      :: grid_atom
    3841              :       TYPE(harmonics_atom_type), POINTER                 :: harmonics
    3842              :       REAL(dp), DIMENSION(3), INTENT(IN)                 :: displacement
    3843              :       REAL(dp), INTENT(IN)                               :: cutoff
    3844              :       INTEGER, INTENT(IN)                                :: nspins
    3845              :       REAL(dp), DIMENSION(2), INTENT(IN)                 :: density_adjoint
    3846              :       REAL(dp), DIMENSION(3, 2), INTENT(IN)              :: gradient_adjoint
    3847              :       REAL(dp), DIMENSION(2), INTENT(IN)                 :: kin_adjoint
    3848              :       REAL(dp), DIMENSION(:, :, :), INTENT(INOUT)        :: vxc_h, vxc_s
    3849              :       REAL(dp), DIMENSION(:, :, :, :), INTENT(INOUT)     :: vxg_h, vxg_s
    3850              :       REAL(dp), DIMENSION(:, :, :), INTENT(INOUT)        :: vtau_h, vtau_s
    3851              : 
    3852              :       INTEGER                                            :: ia, idir, inode, ir, ispin, nradial
    3853              :       INTEGER, DIMENSION(4)                              :: radial_indices
    3854              :       LOGICAL                                            :: active
    3855              :       REAL(dp)                                           :: value
    3856              :       REAL(dp), DIMENSION(4)                             :: radial_weights
    3857       148860 :       REAL(dp), DIMENSION(grid_atom%ng_sphere)           :: angular_weights
    3858              : 
    3859              :       CALL atom_grid_interpolation_weights( &
    3860              :          grid_atom, harmonics, displacement, cutoff, radial_indices, radial_weights, &
    3861        74430 :          nradial=nradial, angular_weights=angular_weights, active=active)
    3862        74430 :       IF (active) THEN
    3863       372054 :          DO inode = 1, nradial
    3864       297640 :             ir = radial_indices(inode)
    3865     12591494 :             DO ia = 1, grid_atom%ng_sphere
    3866     12219440 :                value = radial_weights(inode)*angular_weights(ia)
    3867     24738520 :                DO ispin = 1, nspins
    3868              :                   ! CP2K applies the hard-minus-soft sign when the two one-center
    3869              :                   ! matrices are assembled, so both stored potentials carry the
    3870              :                   ! same transpose-interpolation coefficient.
    3871     12221440 :                   vxc_h(ia, ir, ispin) = vxc_h(ia, ir, ispin) + value*density_adjoint(ispin)
    3872     12221440 :                   vxc_s(ia, ir, ispin) = vxc_s(ia, ir, ispin) + value*density_adjoint(ispin)
    3873     12221440 :                   vtau_h(ia, ir, ispin) = vtau_h(ia, ir, ispin) + value*kin_adjoint(ispin)
    3874     12221440 :                   vtau_s(ia, ir, ispin) = vtau_s(ia, ir, ispin) + value*kin_adjoint(ispin)
    3875     61105200 :                   DO idir = 1, 3
    3876              :                      vxg_h(idir, ia, ir, ispin) = vxg_h(idir, ia, ir, ispin) + &
    3877     36664320 :                                                   value*gradient_adjoint(idir, ispin)
    3878              :                      vxg_s(idir, ia, ir, ispin) = vxg_s(idir, ia, ir, ispin) + &
    3879     48885760 :                                                   value*gradient_adjoint(idir, ispin)
    3880              :                   END DO
    3881              :                END DO
    3882              :             END DO
    3883              :          END DO
    3884              :       END IF
    3885        74430 :    END SUBROUTINE add_gapw_atom_grid_interpolation_adjoint
    3886              : 
    3887              : ! **************************************************************************************************
    3888              : !> \brief ...
    3889              : !> \param qs_env ...
    3890              : !> \param exc1 the on-body ex energy contribution
    3891              : !> \param gradient_atom_set ...
    3892              : ! **************************************************************************************************
    3893           10 :    SUBROUTINE calculate_vxc_atom_epr(qs_env, exc1, gradient_atom_set)
    3894              : 
    3895              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    3896              :       REAL(dp), INTENT(INOUT)                            :: exc1
    3897              :       TYPE(nablavks_atom_type), DIMENSION(:), POINTER    :: gradient_atom_set
    3898              : 
    3899              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'calculate_vxc_atom_epr'
    3900              : 
    3901              :       INTEGER                                            :: bo(2), handle, ia, iat, iatom, idir, &
    3902              :                                                             ikind, ir, ispin, myfun, na, natom, &
    3903              :                                                             nr, nspins, num_pe, on
    3904              :       INTEGER, DIMENSION(2, 3)                           :: bounds
    3905           10 :       INTEGER, DIMENSION(:), POINTER                     :: atom_list
    3906              :       LOGICAL                                            :: accint, donlcc, gradient_f, lsd, nlcc, &
    3907              :                                                             paw_atom, tau_f
    3908              :       REAL(dp)                                           :: agr, alpha, density_cut, exc_h, exc_s, &
    3909              :                                                             gradient_cut, tau_cut
    3910           10 :       REAL(dp), ALLOCATABLE, DIMENSION(:)                :: fw
    3911              :       REAL(dp), DIMENSION(1, 1, 1)                       :: tau_d
    3912              :       REAL(dp), DIMENSION(1, 1, 1, 1)                    :: rho_d
    3913           10 :       REAL(dp), DIMENSION(:, :), POINTER                 :: rho_nlcc, weight_h, weight_s
    3914           20 :       REAL(dp), DIMENSION(:, :, :), POINTER              :: rho_h, rho_s, tau_h, tau_s, vtau_h, &
    3915           10 :                                                             vtau_s, vxc_h, vxc_s
    3916           20 :       REAL(dp), DIMENSION(:, :, :, :), POINTER           :: drho_h, drho_s, vxg_h, vxg_s
    3917           10 :       TYPE(atomic_kind_type), DIMENSION(:), POINTER      :: atomic_kind_set
    3918              :       TYPE(dft_control_type), POINTER                    :: dft_control
    3919              :       TYPE(grid_atom_type), POINTER                      :: grid_atom
    3920              :       TYPE(gto_basis_set_type), POINTER                  :: basis_1c
    3921              :       TYPE(harmonics_atom_type), POINTER                 :: harmonics
    3922              :       TYPE(mp_para_env_type), POINTER                    :: para_env
    3923           10 :       TYPE(qs_kind_type), DIMENSION(:), POINTER          :: my_kind_set
    3924           10 :       TYPE(rho_atom_coeff), DIMENSION(:), POINTER        :: dr_h, dr_s, int_hh, int_ss, r_h, r_s
    3925           10 :       TYPE(rho_atom_coeff), DIMENSION(:, :), POINTER     :: r_h_d, r_s_d
    3926           10 :       TYPE(rho_atom_type), DIMENSION(:), POINTER         :: my_rho_atom_set
    3927              :       TYPE(rho_atom_type), POINTER                       :: rho_atom
    3928              :       TYPE(section_vals_type), POINTER                   :: input, my_xc_section, xc_fun_section
    3929           10 :       TYPE(tau_basis_cache_type)                         :: tau_basis_cache
    3930              :       TYPE(xc_derivative_set_type)                       :: deriv_set
    3931              :       TYPE(xc_rho_cflags_type)                           :: needs
    3932              :       TYPE(xc_rho_set_type)                              :: rho_set_h, rho_set_s
    3933              : 
    3934              : ! -------------------------------------------------------------------------
    3935              : 
    3936           10 :       CALL timeset(routineN, handle)
    3937              : 
    3938           10 :       NULLIFY (atom_list)
    3939           10 :       NULLIFY (my_kind_set)
    3940           10 :       NULLIFY (atomic_kind_set)
    3941           10 :       NULLIFY (grid_atom)
    3942           10 :       NULLIFY (harmonics)
    3943           10 :       NULLIFY (input)
    3944           10 :       NULLIFY (para_env)
    3945           10 :       NULLIFY (rho_atom)
    3946           10 :       NULLIFY (my_rho_atom_set)
    3947           10 :       NULLIFY (rho_nlcc)
    3948              : 
    3949              :       CALL get_qs_env(qs_env=qs_env, &
    3950              :                       dft_control=dft_control, &
    3951              :                       para_env=para_env, &
    3952              :                       atomic_kind_set=atomic_kind_set, &
    3953              :                       qs_kind_set=my_kind_set, &
    3954              :                       input=input, &
    3955           10 :                       rho_atom_set=my_rho_atom_set)
    3956              : 
    3957           10 :       nlcc = has_nlcc(my_kind_set)
    3958           10 :       accint = dft_control%qs_control%gapw_control%accurate_xcint
    3959              : 
    3960              :       my_xc_section => section_vals_get_subs_vals(input, &
    3961           10 :                                                   "PROPERTIES%LINRES%EPR%PRINT%G_TENSOR%XC")
    3962           10 :       xc_fun_section => section_vals_get_subs_vals(my_xc_section, "XC_FUNCTIONAL")
    3963              :       CALL section_vals_val_get(xc_fun_section, "_SECTION_PARAMETERS_", &
    3964           10 :                                 i_val=myfun)
    3965              : 
    3966           10 :       IF (myfun == xc_none) THEN
    3967            0 :          exc1 = 0.0_dp
    3968            0 :          my_rho_atom_set(:)%exc_h = 0.0_dp
    3969            0 :          my_rho_atom_set(:)%exc_s = 0.0_dp
    3970              :       ELSE
    3971              :          CALL section_vals_val_get(my_xc_section, "DENSITY_CUTOFF", &
    3972           10 :                                    r_val=density_cut)
    3973              :          CALL section_vals_val_get(my_xc_section, "GRADIENT_CUTOFF", &
    3974           10 :                                    r_val=gradient_cut)
    3975              :          CALL section_vals_val_get(my_xc_section, "TAU_CUTOFF", &
    3976           10 :                                    r_val=tau_cut)
    3977              : 
    3978           10 :          lsd = dft_control%lsd
    3979           10 :          nspins = dft_control%nspins
    3980              :          needs = xc_functionals_get_needs(xc_fun_section, &
    3981              :                                           lsd=lsd, &
    3982           10 :                                           calc_potential=.TRUE.)
    3983              : 
    3984              :          ! whatever the xc, if epr_xc, drho_spin is needed
    3985           10 :          needs%drho_spin = .TRUE.
    3986              : 
    3987           10 :          gradient_f = (needs%drho .OR. needs%drho_spin)
    3988           10 :          tau_f = (needs%tau .OR. needs%tau_spin)
    3989              : 
    3990              :          ! Initialize energy contribution from the one center XC terms to zero
    3991           10 :          exc1 = 0.0_dp
    3992              : 
    3993              :          ! Nullify some pointers for work-arrays
    3994           10 :          NULLIFY (rho_h, drho_h, rho_s, drho_s, weight_h, weight_s)
    3995           10 :          NULLIFY (vxc_h, vxc_s, vxg_h, vxg_s)
    3996           10 :          NULLIFY (tau_h, tau_s)
    3997           10 :          NULLIFY (vtau_h, vtau_s)
    3998              : 
    3999              :          ! Here starts the loop over all the atoms
    4000              : 
    4001           30 :          DO ikind = 1, SIZE(atomic_kind_set)
    4002           20 :             CALL get_atomic_kind(atomic_kind_set(ikind), atom_list=atom_list, natom=natom)
    4003              :             CALL get_qs_kind(my_kind_set(ikind), paw_atom=paw_atom, &
    4004           20 :                              harmonics=harmonics, grid_atom=grid_atom)
    4005           20 :             CALL get_qs_kind(my_kind_set(ikind), basis_set=basis_1c, basis_type="GAPW_1C")
    4006              : 
    4007           20 :             IF (.NOT. paw_atom) CYCLE
    4008              : 
    4009           20 :             nr = grid_atom%nr
    4010           20 :             na = grid_atom%ng_sphere
    4011              : 
    4012              :             ! Prepare the structures needed to calculate and store the xc derivatives
    4013              : 
    4014              :             ! Array dimension: here anly one dimensional arrays are used,
    4015              :             ! i.e. only the first column of deriv_data is read.
    4016              :             ! The other to dimensions  are set to size equal 1
    4017          200 :             bounds(1:2, 1:3) = 1
    4018           20 :             bounds(2, 1) = na
    4019           20 :             bounds(2, 2) = nr
    4020              : 
    4021              :             ! set integration weights
    4022           20 :             weight_h => grid_atom%weight
    4023           20 :             weight_s => grid_atom%weight
    4024           20 :             IF (accint) THEN
    4025            0 :                on = dft_control%qs_control%gapw_control%oweights
    4026            0 :                alpha = dft_control%qs_control%gapw_control%aw(ikind)
    4027            0 :                IF (ASSOCIATED(grid_atom%gapw_weight_s)) THEN
    4028            0 :                   IF (grid_atom%gapw_weight_alpha /= alpha) DEALLOCATE (grid_atom%gapw_weight_s)
    4029              :                END IF
    4030            0 :                IF (.NOT. ASSOCIATED(grid_atom%gapw_weight_s)) THEN
    4031            0 :                   ALLOCATE (grid_atom%gapw_weight_s(na, nr))
    4032            0 :                   ALLOCATE (fw(nr))
    4033            0 :                   CALL calc_weight_function(fw, grid_atom%rad2, on, alpha)
    4034            0 :                   DO ir = 1, nr
    4035            0 :                      agr = 1.0_dp - fw(ir)
    4036            0 :                      grid_atom%gapw_weight_s(:, ir) = agr*grid_atom%weight(:, ir)
    4037              :                   END DO
    4038            0 :                   DEALLOCATE (fw)
    4039            0 :                   grid_atom%gapw_weight_alpha = alpha
    4040              :                END IF
    4041            0 :                weight_s => grid_atom%gapw_weight_s
    4042              :             END IF
    4043              : 
    4044              :             ! create a place where to put the derivatives
    4045           20 :             CALL xc_dset_create(deriv_set, local_bounds=bounds)
    4046              :             ! create the place where to store the argument for the functionals
    4047              :             CALL xc_rho_set_create(rho_set_h, bounds, rho_cutoff=density_cut, &
    4048           20 :                                    drho_cutoff=gradient_cut, tau_cutoff=tau_cut)
    4049              :             CALL xc_rho_set_create(rho_set_s, bounds, rho_cutoff=density_cut, &
    4050           20 :                                    drho_cutoff=gradient_cut, tau_cutoff=tau_cut)
    4051              : 
    4052              :             ! allocate the required 3d arrays where to store rho and drho
    4053           20 :             CALL xc_rho_set_atom_update(rho_set_h, needs, nspins, bounds)
    4054           20 :             CALL xc_rho_set_atom_update(rho_set_s, needs, nspins, bounds)
    4055              : 
    4056           20 :             CALL reallocate(rho_h, 1, na, 1, nr, 1, nspins)
    4057           20 :             CALL reallocate(rho_s, 1, na, 1, nr, 1, nspins)
    4058           20 :             CALL reallocate(vxc_h, 1, na, 1, nr, 1, nspins)
    4059           20 :             CALL reallocate(vxc_s, 1, na, 1, nr, 1, nspins)
    4060              :             !
    4061              :             IF (gradient_f) THEN
    4062           20 :                CALL reallocate(drho_h, 1, 4, 1, na, 1, nr, 1, nspins)
    4063           20 :                CALL reallocate(drho_s, 1, 4, 1, na, 1, nr, 1, nspins)
    4064           20 :                CALL reallocate(vxg_h, 1, 3, 1, na, 1, nr, 1, nspins)
    4065           20 :                CALL reallocate(vxg_s, 1, 3, 1, na, 1, nr, 1, nspins)
    4066              :             END IF
    4067              : 
    4068           20 :             IF (tau_f) THEN
    4069            0 :                CALL create_tau_basis_cache(tau_basis_cache, grid_atom, basis_1c, harmonics)
    4070            0 :                CALL reallocate(tau_h, 1, na, 1, nr, 1, nspins)
    4071            0 :                CALL reallocate(tau_s, 1, na, 1, nr, 1, nspins)
    4072            0 :                CALL reallocate(vtau_h, 1, na, 1, nr, 1, nspins)
    4073            0 :                CALL reallocate(vtau_s, 1, na, 1, nr, 1, nspins)
    4074              :             END IF
    4075              : 
    4076              :             ! NLCC: prepare rho and drho of the core charge for this KIND
    4077           20 :             donlcc = .FALSE.
    4078           20 :             IF (nlcc) THEN
    4079            0 :                NULLIFY (rho_nlcc)
    4080            0 :                rho_nlcc => my_kind_set(ikind)%nlcc_pot
    4081            0 :                IF (ASSOCIATED(rho_nlcc)) donlcc = .TRUE.
    4082              :             END IF
    4083              : 
    4084              :             ! Distribute the atoms of this kind
    4085              : 
    4086           20 :             num_pe = para_env%num_pe
    4087           20 :             bo = get_limit(natom, para_env%num_pe, para_env%mepos)
    4088              : 
    4089           35 :             DO iat = bo(1), bo(2)
    4090           15 :                iatom = atom_list(iat)
    4091              : 
    4092           15 :                my_rho_atom_set(iatom)%exc_h = 0.0_dp
    4093           15 :                my_rho_atom_set(iatom)%exc_s = 0.0_dp
    4094              : 
    4095           15 :                rho_atom => my_rho_atom_set(iatom)
    4096        76545 :                rho_h = 0.0_dp
    4097        76545 :                rho_s = 0.0_dp
    4098              :                IF (gradient_f) THEN
    4099           15 :                   NULLIFY (r_h, r_s, dr_h, dr_s, r_h_d, r_s_d)
    4100              :                   CALL get_rho_atom(rho_atom=rho_atom, rho_rad_h=r_h, &
    4101              :                                     rho_rad_s=r_s, drho_rad_h=dr_h, &
    4102              :                                     drho_rad_s=dr_s, rho_rad_h_d=r_h_d, &
    4103           15 :                                     rho_rad_s_d=r_s_d)
    4104       376545 :                   drho_h = 0.0_dp
    4105       376545 :                   drho_s = 0.0_dp
    4106              :                ELSE
    4107              :                   NULLIFY (r_h, r_s)
    4108              :                   CALL get_rho_atom(rho_atom=rho_atom, rho_rad_h=r_h, rho_rad_s=r_s)
    4109              :                   rho_d = 0.0_dp
    4110              :                END IF
    4111           15 :                IF (tau_f) THEN
    4112              :                   !compute tau on the grid all at once
    4113            0 :                   CALL calc_tau_atom(tau_h, tau_s, rho_atom, tau_basis_cache, nspins)
    4114              :                ELSE
    4115           15 :                   tau_d = 0.0_dp
    4116              :                END IF
    4117              : 
    4118          765 :                DO ir = 1, nr
    4119              :                   CALL calc_rho_angular(grid_atom, harmonics, nspins, gradient_f, &
    4120              :                                         ir, r_h, r_s, rho_h, rho_s, dr_h, dr_s, &
    4121          750 :                                         r_h_d, r_s_d, drho_h, drho_s)
    4122          765 :                   IF (donlcc) THEN
    4123              :                      CALL calc_rho_nlcc(grid_atom, nspins, gradient_f, &
    4124            0 :                                         ir, rho_nlcc(:, 1), rho_h, rho_s, rho_nlcc(:, 2), drho_h, drho_s)
    4125              :                   END IF
    4126              :                END DO
    4127          765 :                DO ir = 1, nr
    4128          765 :                   IF (tau_f) THEN
    4129            0 :                      CALL fill_rho_set(rho_set_h, lsd, nspins, needs, rho_h, drho_h, tau_h, na, ir)
    4130            0 :                      CALL fill_rho_set(rho_set_s, lsd, nspins, needs, rho_s, drho_s, tau_s, na, ir)
    4131              :                   ELSE IF (gradient_f) THEN
    4132          750 :                      CALL fill_rho_set(rho_set_h, lsd, nspins, needs, rho_h, drho_h, tau_d, na, ir)
    4133          750 :                      CALL fill_rho_set(rho_set_s, lsd, nspins, needs, rho_s, drho_s, tau_d, na, ir)
    4134              :                   ELSE
    4135              :                      CALL fill_rho_set(rho_set_h, lsd, nspins, needs, rho_h, rho_d, tau_d, na, ir)
    4136              :                      CALL fill_rho_set(rho_set_s, lsd, nspins, needs, rho_s, rho_d, tau_d, na, ir)
    4137              :                   END IF
    4138              :                END DO
    4139              : 
    4140              :                !-------------------!
    4141              :                ! hard atom density !
    4142              :                !-------------------!
    4143           15 :                CALL xc_dset_zero_all(deriv_set)
    4144              :                CALL vxc_of_r_epr(xc_fun_section, rho_set_h, deriv_set, needs, weight_h, &
    4145           15 :                                  lsd, na, nr, exc_h, vxc_h, vxg_h, vtau_h)
    4146           15 :                rho_atom%exc_h = rho_atom%exc_h + exc_h
    4147              : 
    4148              :                !-------------------!
    4149              :                ! soft atom density !
    4150              :                !-------------------!
    4151           15 :                CALL xc_dset_zero_all(deriv_set)
    4152              :                CALL vxc_of_r_epr(xc_fun_section, rho_set_s, deriv_set, needs, weight_s, &
    4153           15 :                                  lsd, na, nr, exc_s, vxc_s, vxg_s, vtau_s)
    4154           15 :                rho_atom%exc_s = rho_atom%exc_s + exc_s
    4155              : 
    4156           45 :                DO ispin = 1, nspins
    4157          135 :                   DO idir = 1, 3
    4158         4620 :                      DO ir = 1, nr
    4159       229590 :                         DO ia = 1, na
    4160              :                            gradient_atom_set(iatom)%nablavks_vec_rad_h(idir, ispin)%r_coef(ir, ia) = &
    4161              :                               gradient_atom_set(iatom)%nablavks_vec_rad_h(idir, ispin)%r_coef(ir, ia) &
    4162       225000 :                               + vxg_h(idir, ia, ir, ispin)
    4163              :                            gradient_atom_set(iatom)%nablavks_vec_rad_s(idir, ispin)%r_coef(ir, ia) = &
    4164              :                               gradient_atom_set(iatom)%nablavks_vec_rad_s(idir, ispin)%r_coef(ir, ia) &
    4165       229500 :                               + vxg_s(idir, ia, ir, ispin)
    4166              :                         END DO ! ia
    4167              :                      END DO ! ir
    4168              :                   END DO ! idir
    4169              :                END DO ! ispin
    4170              : 
    4171              :                ! Add contributions to the exc energy
    4172              : 
    4173           15 :                exc1 = exc1 + rho_atom%exc_h - rho_atom%exc_s
    4174              : 
    4175              :                ! Integration to get the matrix elements relative to the vxc_atom
    4176              :                ! here the products with the primitives is done: gaVxcgb
    4177              :                ! internal transformation to get the integral in cartesian Gaussians
    4178              : 
    4179           15 :                NULLIFY (int_hh, int_ss)
    4180           15 :                CALL get_rho_atom(rho_atom=rho_atom, ga_Vlocal_gb_h=int_hh, ga_Vlocal_gb_s=int_ss)
    4181              :                IF (gradient_f) THEN
    4182              :                   CALL gaVxcgb_GC(vxc_h, vxc_s, vxg_h, vxg_s, int_hh, int_ss, &
    4183           15 :                                   grid_atom, basis_1c, harmonics, nspins)
    4184              :                ELSE
    4185              :                   CALL gaVxcgb_noGC(vxc_h, vxc_s, int_hh, int_ss, &
    4186              :                                     grid_atom, basis_1c, harmonics, nspins)
    4187              :                END IF
    4188           15 :                IF (tau_f) THEN
    4189              :                   CALL dgaVtaudgb(vtau_h, vtau_s, int_hh, int_ss, &
    4190            0 :                                   tau_basis_cache, nspins)
    4191              :                END IF
    4192           35 :                NULLIFY (r_h, r_s, dr_h, dr_s)
    4193              :             END DO ! iat
    4194              : 
    4195           20 :             IF (tau_f) CALL release_tau_basis_cache(tau_basis_cache)
    4196              : 
    4197              :             ! Release the xc structure used to store the xc derivatives
    4198           20 :             CALL xc_dset_release(deriv_set)
    4199           20 :             CALL xc_rho_set_release(rho_set_h)
    4200           70 :             CALL xc_rho_set_release(rho_set_s)
    4201              :          END DO ! ikind
    4202              : 
    4203           10 :          CALL para_env%sum(exc1)
    4204              : 
    4205           10 :          IF (ASSOCIATED(rho_h)) DEALLOCATE (rho_h)
    4206           10 :          IF (ASSOCIATED(rho_s)) DEALLOCATE (rho_s)
    4207           10 :          IF (ASSOCIATED(vxc_h)) DEALLOCATE (vxc_h)
    4208           10 :          IF (ASSOCIATED(vxc_s)) DEALLOCATE (vxc_s)
    4209              : 
    4210              :          IF (gradient_f) THEN
    4211           10 :             IF (ASSOCIATED(drho_h)) DEALLOCATE (drho_h)
    4212           10 :             IF (ASSOCIATED(drho_s)) DEALLOCATE (drho_s)
    4213           10 :             IF (ASSOCIATED(vxg_h)) DEALLOCATE (vxg_h)
    4214           10 :             IF (ASSOCIATED(vxg_s)) DEALLOCATE (vxg_s)
    4215              :          END IF
    4216              : 
    4217           10 :          IF (tau_f) THEN
    4218            0 :             IF (ASSOCIATED(tau_h)) DEALLOCATE (tau_h)
    4219            0 :             IF (ASSOCIATED(tau_s)) DEALLOCATE (tau_s)
    4220            0 :             IF (ASSOCIATED(vtau_h)) DEALLOCATE (vtau_h)
    4221            0 :             IF (ASSOCIATED(vtau_s)) DEALLOCATE (vtau_s)
    4222              :          END IF
    4223              : 
    4224              :       END IF !xc_none
    4225              : 
    4226           10 :       CALL timestop(handle)
    4227              : 
    4228          440 :    END SUBROUTINE calculate_vxc_atom_epr
    4229              : 
    4230              : END MODULE qs_vxc_atom
        

Generated by: LCOV version 2.0-1