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

            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 Calculates the moment integrals <a|r^m|b> and <a|r x d/dr|b>
      10              : !> \par History
      11              : !>      added angular moments (JGH 11.2012)
      12              : !> \author JGH (20.07.2006)
      13              : ! **************************************************************************************************
      14              : MODULE qs_moments
      15              :    USE ai_angmom, ONLY: angmom
      16              :    USE ai_moments, ONLY: contract_expikr, &
      17              :                          diff_momop, &
      18              :                          expikr, &
      19              :                          moment
      20              :    USE atomic_kind_types, ONLY: atomic_kind_type, &
      21              :                                 get_atomic_kind
      22              :    USE basis_set_types, ONLY: gto_basis_set_p_type, &
      23              :                               gto_basis_set_type
      24              :    USE bibliography, ONLY: Mattiat2019, &
      25              :                            cite_reference
      26              :    USE block_p_types, ONLY: block_p_type
      27              :    USE cell_types, ONLY: cell_type, &
      28              :                          pbc, &
      29              :                          pbc_stable, &
      30              :                          get_cell
      31              :    USE commutator_rpnl, ONLY: build_com_mom_nl
      32              :    USE cp_blacs_env, ONLY: cp_blacs_env_type
      33              :    USE cp_cfm_basic_linalg, ONLY: cp_cfm_det
      34              :    USE cp_cfm_types, ONLY: cp_cfm_copy_general, &
      35              :                            cp_cfm_create, &
      36              :                            cp_cfm_get_element, &
      37              :                            cp_cfm_get_info, &
      38              :                            cp_cfm_release, &
      39              :                            cp_cfm_to_fm, &
      40              :                            cp_fm_to_cfm, &
      41              :                            cp_cfm_type
      42              :    USE cp_control_types, ONLY: dft_control_type
      43              :    USE cp_dbcsr_api, ONLY: &
      44              :       dbcsr_copy, dbcsr_create, dbcsr_deallocate_matrix, dbcsr_distribution_type, &
      45              :       dbcsr_get_block_p, dbcsr_get_info, dbcsr_get_matrix_type, dbcsr_init_p, dbcsr_multiply, dbcsr_p_type, &
      46              :       dbcsr_set, dbcsr_type, dbcsr_type_antisymmetric, dbcsr_type_no_symmetry, dbcsr_type_symmetric
      47              :    USE cp_dbcsr_contrib, ONLY: dbcsr_dot, &
      48              :                                dbcsr_trace
      49              :    USE cp_dbcsr_cp2k_link, ONLY: cp_dbcsr_alloc_block_from_nbl
      50              :    USE cp_dbcsr_operations, ONLY: copy_dbcsr_to_fm, &
      51              :                                   cp_dbcsr_sm_fm_multiply, &
      52              :                                   dbcsr_allocate_matrix_set, &
      53              :                                   dbcsr_deallocate_matrix_set
      54              :    USE cp_files, ONLY: close_file, &
      55              :                        open_file
      56              :    USE cp_fm_struct, ONLY: cp_fm_struct_create, &
      57              :                            cp_fm_struct_double, &
      58              :                            cp_fm_struct_release, &
      59              :                            cp_fm_struct_type
      60              :    USE cp_fm_types, ONLY: cp_fm_copy_general, &
      61              :                           cp_fm_create, &
      62              :                           cp_fm_get_info, &
      63              :                           cp_fm_release, &
      64              :                           cp_fm_set_all, &
      65              :                           cp_fm_type
      66              :    USE cp_result_methods, ONLY: cp_results_erase, &
      67              :                                 put_results
      68              :    USE cp_result_types, ONLY: cp_result_type
      69              :    USE cp_units, ONLY: cp_ukind_dipole, &
      70              :                        cp_unit_create, &
      71              :                        cp_unit_from_cp2k, &
      72              :                        cp_unit_from_cp2k1, &
      73              :                        cp_unit_release, &
      74              :                        cp_unit_type, &
      75              :                        cp_units_au, &
      76              :                        cp_units_c_m, &
      77              :                        cp_units_debye, &
      78              :                        cp_units_e_angstrom
      79              :    USE distribution_1d_types, ONLY: distribution_1d_type
      80              :    USE input_constants, ONLY: use_mom_ref_coac
      81              :    USE kinds, ONLY: default_string_length, &
      82              :                     dp, &
      83              :                     max_line_length
      84              :    USE kpoint_k_r_trafo_simple, ONLY: replicate_rs_matrices, &
      85              :                                       rs_to_kp
      86              :    USE kpoint_methods, ONLY: kpoint_init_cell_index, &
      87              :                              kpoint_initialize
      88              :    USE kpoint_types, ONLY: get_kpoint_info, &
      89              :                            kpoint_env_p_type, &
      90              :                            kpoint_env_type, &
      91              :                            kpoint_type, &
      92              :                            kpoint_create, &
      93              :                            kpoint_release, &
      94              :                            read_kpoint_section
      95              :    USE mathconstants, ONLY: pi, &
      96              :                             twopi, &
      97              :                             gaussi, &
      98              :                             z_one, &
      99              :                             z_zero
     100              :    USE message_passing, ONLY: mp_para_env_type
     101              :    USE parallel_gemm_api, ONLY: parallel_gemm
     102              :    USE moments_utils, ONLY: get_reference_point
     103              :    USE orbital_pointers, ONLY: current_maxl, &
     104              :                                indco, &
     105              :                                ncoset
     106              :    USE particle_methods, ONLY: get_particle_set
     107              :    USE particle_types, ONLY: particle_type
     108              :    USE physcon, ONLY: angstrom
     109              :    USE qs_environment_types, ONLY: get_qs_env, &
     110              :                                    qs_environment_type
     111              :    USE qs_kind_types, ONLY: get_qs_kind, &
     112              :                             get_qs_kind_set, &
     113              :                             qs_kind_type
     114              :    USE kpoint_transform, ONLY: rskp_prepared_transform_type, &
     115              :                                rskp_transform_evaluate, &
     116              :                                rskp_transform_prepare, &
     117              :                                rskp_transform_release
     118              :    USE qs_ks_types, ONLY: get_ks_env, &
     119              :                           qs_ks_env_type
     120              :    USE qs_mo_types, ONLY: get_mo_set, &
     121              :                           mo_set_type
     122              :    USE qs_neighbor_list_types, ONLY: get_iterator_info, &
     123              :                                      neighbor_list_iterate, &
     124              :                                      neighbor_list_iterator_create, &
     125              :                                      neighbor_list_iterator_p_type, &
     126              :                                      neighbor_list_iterator_release, &
     127              :                                      neighbor_list_set_p_type
     128              :    USE qs_operators_ao, ONLY: build_exp_ikr_matrix, &
     129              :                               build_lin_mom_matrix
     130              :    USE qs_overlap, ONLY: build_overlap_matrix
     131              :    USE qs_rho_types, ONLY: qs_rho_get, &
     132              :                            qs_rho_type
     133              :    USE rt_propagation_types, ONLY: get_rtp, &
     134              :                                    rt_prop_type
     135              :    USE soc_pseudopotential_methods, ONLY: V_SOC_xyz_from_pseudopotential
     136              :    USE cp_parser_methods, ONLY: read_float_object
     137              :    USE input_section_types, ONLY: section_vals_get, &
     138              :                                   section_vals_get_subs_vals, &
     139              :                                   section_vals_type, &
     140              :                                   section_vals_val_get
     141              :    USE mathlib, ONLY: geeig_right, &
     142              :                       gemm_square
     143              :    USE string_utilities, ONLY: uppercase
     144              : 
     145              : #include "./base/base_uses.f90"
     146              : 
     147              :    IMPLICIT NONE
     148              : 
     149              :    PRIVATE
     150              : 
     151              :    CHARACTER(len=*), PARAMETER, PRIVATE :: moduleN = 'qs_moments'
     152              : 
     153              :    ! Public subroutines
     154              :    PUBLIC :: build_berry_moment_matrix, build_local_moment_matrix, get_multipoles_ao
     155              :    PUBLIC :: build_berry_kpoint_matrix, build_local_magmom_matrix
     156              :    PUBLIC :: qs_moment_berry_phase, qs_moment_locop
     157              :    PUBLIC :: qs_moment_kpoints, build_local_moment_matrix_rs_img
     158              :    PUBLIC :: qs_moment_kpoints_deep, qs_moment_kpoints_deep_soc
     159              :    PUBLIC :: qs_moment_kpoints_scf_mos
     160              :    PUBLIC :: build_local_moments_der_matrix
     161              :    PUBLIC :: calculate_commutator_nl_terms, op_orbbas, op_orbbas_rtp, &
     162              :              print_moments, print_moments_nl, set_label
     163              : 
     164              : CONTAINS
     165              : 
     166              : ! **************************************************************************************************
     167              : !> \brief ...
     168              : !> \param qs_env ...
     169              : !> \param moments ...
     170              : !> \param nmoments ...
     171              : !> \param ref_point ...
     172              : !> \param ref_points ...
     173              : !> \param basis_type ...
     174              : !> \param all_images accumulate all neighbor images belonging to one atom pair
     175              : !> \param minimum_image apply the half-cell image filter
     176              : !> \param neighbor_image preserve the neighbor-list image geometry
     177              : !> \param first_component first Cartesian moment component to write
     178              : ! **************************************************************************************************
     179         3712 :    SUBROUTINE build_local_moment_matrix(qs_env, moments, nmoments, ref_point, ref_points, basis_type, &
     180              :                                         all_images, minimum_image, neighbor_image, first_component)
     181              : 
     182              :       TYPE(qs_environment_type), POINTER                 :: qs_env
     183              :       TYPE(dbcsr_p_type), DIMENSION(:), POINTER          :: moments
     184              :       INTEGER, INTENT(IN)                                :: nmoments
     185              :       REAL(KIND=dp), DIMENSION(:), INTENT(IN), OPTIONAL  :: ref_point
     186              :       REAL(KIND=dp), DIMENSION(:, :), INTENT(IN), &
     187              :          OPTIONAL                                        :: ref_points
     188              :       CHARACTER(len=*), OPTIONAL                         :: basis_type
     189              :       LOGICAL, OPTIONAL                                   :: all_images, minimum_image, neighbor_image
     190              :       INTEGER, OPTIONAL                                   :: first_component
     191              : 
     192              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'build_local_moment_matrix'
     193              : 
     194              :       INTEGER :: component_start, handle, i, iatom, icol, ikind, inode, irow, iset, jatom, jkind, jset, &
     195              :                  last_jatom, maxco, maxsgf, ncoa, ncob, nkind, nm, nseta, nsetb, sgfa, sgfb
     196              :       LOGICAL                                            :: found, my_all_images, my_minimum_image, &
     197              :                                                             my_neighbor_image, new_atom_pair
     198              :       REAL(KIND=dp)                                      :: dab
     199              :       REAL(KIND=dp), DIMENSION(3)                        :: half_cell
     200         3712 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :)        :: work
     201         3712 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :, :)     :: mab
     202              :       REAL(KIND=dp), DIMENSION(3)                        :: ra, rab, rac, rb, rbc, rc
     203         3712 :       TYPE(block_p_type), ALLOCATABLE, DIMENSION(:)      :: mint
     204              :       TYPE(cell_type), POINTER                           :: cell
     205         3712 :       TYPE(gto_basis_set_p_type), DIMENSION(:), POINTER  :: basis_set_list
     206              :       TYPE(gto_basis_set_type), POINTER                  :: basis_set_a, basis_set_b
     207              :       TYPE(neighbor_list_iterator_p_type), &
     208         3712 :          DIMENSION(:), POINTER                           :: nl_iterator
     209              :       TYPE(neighbor_list_set_p_type), DIMENSION(:), &
     210         3712 :          POINTER                                         :: sab_orb
     211         3712 :       TYPE(particle_type), DIMENSION(:), POINTER         :: particle_set
     212         3712 :       TYPE(qs_kind_type), DIMENSION(:), POINTER          :: qs_kind_set
     213              :       TYPE(qs_kind_type), POINTER                        :: qs_kind
     214              : 
     215         3712 :       IF (nmoments < 1) RETURN
     216              : 
     217         3712 :       CALL timeset(routineN, handle)
     218              : 
     219         3712 :       my_all_images = .FALSE.
     220         3712 :       IF (PRESENT(all_images)) my_all_images = all_images
     221         3712 :       my_minimum_image = .FALSE.
     222         3712 :       IF (PRESENT(minimum_image)) my_minimum_image = minimum_image
     223         3712 :       my_neighbor_image = .FALSE.
     224         3712 :       IF (PRESENT(neighbor_image)) my_neighbor_image = neighbor_image
     225              : 
     226         3712 :       nm = (6 + 11*nmoments + 6*nmoments**2 + nmoments**3)/6 - 1
     227         3712 :       CPASSERT(SIZE(moments) >= nm)
     228         3712 :       component_start = 1
     229         3712 :       IF (PRESENT(first_component)) component_start = first_component
     230         3712 :       CPASSERT(component_start >= 1 .AND. component_start <= nm)
     231              : 
     232         3712 :       NULLIFY (qs_kind_set, particle_set, sab_orb, cell)
     233              :       CALL get_qs_env(qs_env=qs_env, &
     234              :                       qs_kind_set=qs_kind_set, &
     235              :                       particle_set=particle_set, cell=cell, &
     236         3712 :                       sab_orb=sab_orb)
     237              : 
     238         3712 :       IF (my_minimum_image) THEN
     239          150 :          half_cell = 0.5_dp*NORM2(cell%hmat, DIM=1)
     240              :       END IF
     241              : 
     242         3712 :       nkind = SIZE(qs_kind_set)
     243              :       ! Allocate work storage
     244              :       CALL get_qs_kind_set(qs_kind_set=qs_kind_set, &
     245              :                            maxco=maxco, maxsgf=maxsgf, &
     246         7318 :                            basis_type=basis_type)
     247              : 
     248        18560 :       ALLOCATE (mab(maxco, maxco, nm))
     249         3712 :       mab(:, :, :) = 0.0_dp
     250              : 
     251        14848 :       ALLOCATE (work(maxco, maxsgf))
     252         3712 :       work(:, :) = 0.0_dp
     253              : 
     254        22442 :       ALLOCATE (mint(nm))
     255        15018 :       DO i = component_start, nm
     256        15018 :          NULLIFY (mint(i)%block)
     257              :       END DO
     258              : 
     259        18528 :       ALLOCATE (basis_set_list(nkind))
     260        11104 :       DO ikind = 1, nkind
     261         7392 :          qs_kind => qs_kind_set(ikind)
     262         7392 :          CALL get_qs_kind(qs_kind=qs_kind, basis_set=basis_set_a, basis_type=basis_type)
     263        11104 :          IF (ASSOCIATED(basis_set_a)) THEN
     264         7392 :             basis_set_list(ikind)%gto_basis_set => basis_set_a
     265              :          ELSE
     266            0 :             NULLIFY (basis_set_list(ikind)%gto_basis_set)
     267              :          END IF
     268              :       END DO
     269         3712 :       CALL neighbor_list_iterator_create(nl_iterator, sab_orb)
     270        40989 :       DO WHILE (neighbor_list_iterate(nl_iterator) == 0)
     271              :          CALL get_iterator_info(nl_iterator, ikind=ikind, jkind=jkind, inode=inode, &
     272        37277 :                                 iatom=iatom, jatom=jatom, r=rab)
     273        37277 :          basis_set_a => basis_set_list(ikind)%gto_basis_set
     274        37277 :          IF (.NOT. ASSOCIATED(basis_set_a)) CYCLE
     275        37277 :          basis_set_b => basis_set_list(jkind)%gto_basis_set
     276        37277 :          IF (.NOT. ASSOCIATED(basis_set_b)) CYCLE
     277              :          ASSOCIATE ( &
     278              :             ! basis ikind
     279              :             first_sgfa => basis_set_a%first_sgf, &
     280              :             la_max => basis_set_a%lmax, &
     281              :             la_min => basis_set_a%lmin, &
     282              :             npgfa => basis_set_a%npgf, &
     283              :             nsgfa => basis_set_a%nsgf_set, &
     284              :             rpgfa => basis_set_a%pgf_radius, &
     285              :             set_radius_a => basis_set_a%set_radius, &
     286              :             sphi_a => basis_set_a%sphi, &
     287              :             zeta => basis_set_a%zet, &
     288              :             ! basis jkind, &
     289              :             first_sgfb => basis_set_b%first_sgf, &
     290              :             lb_max => basis_set_b%lmax, &
     291              :             lb_min => basis_set_b%lmin, &
     292              :             npgfb => basis_set_b%npgf, &
     293              :             nsgfb => basis_set_b%nsgf_set, &
     294              :             rpgfb => basis_set_b%pgf_radius, &
     295              :             set_radius_b => basis_set_b%set_radius, &
     296              :             sphi_b => basis_set_b%sphi, &
     297              :             zetb => basis_set_b%zet)
     298              : 
     299        37277 :             nseta = basis_set_a%nset
     300        37277 :             nsetb = basis_set_b%nset
     301              : 
     302        10131 :             IF (inode == 1) last_jatom = 0
     303              : 
     304        37277 :             IF (my_minimum_image) THEN
     305          482 :                IF (ANY(ABS(rab(:)) > half_cell(:))) CYCLE
     306              :             END IF
     307              : 
     308        37275 :             new_atom_pair = jatom /= last_jatom
     309        37275 :             IF (.NOT. my_all_images .AND. .NOT. new_atom_pair) THEN
     310              :                CYCLE
     311              :             END IF
     312              : 
     313        14795 :             IF (new_atom_pair) THEN
     314        14128 :                last_jatom = jatom
     315              : 
     316        14128 :                IF (iatom <= jatom) THEN
     317         8831 :                   irow = iatom
     318         8831 :                   icol = jatom
     319              :                ELSE
     320         5297 :                   irow = jatom
     321         5297 :                   icol = iatom
     322              :                END IF
     323              : 
     324        57382 :                DO i = component_start, nm
     325        43254 :                   NULLIFY (mint(i)%block)
     326              :                   CALL dbcsr_get_block_p(matrix=moments(i)%matrix, &
     327        43254 :                                          row=irow, col=icol, BLOCK=mint(i)%block, found=found)
     328        43254 :                   CPASSERT(found .AND. ASSOCIATED(mint(i)%block))
     329      2188517 :                   mint(i)%block = 0._dp
     330              :                END DO
     331              :             END IF
     332              : 
     333              :             ! Reference point and image geometry.
     334        14795 :             IF (PRESENT(ref_points)) THEN
     335            0 :                rc(:) = 0.5_dp*(ref_points(:, iatom) + ref_points(:, jatom))
     336        14795 :             ELSE IF (PRESENT(ref_point)) THEN
     337        54108 :                rc(:) = ref_point(:)
     338              :             ELSE
     339         1268 :                rc(:) = 0._dp
     340              :             END IF
     341              : 
     342        14795 :             IF (my_all_images) THEN
     343              :                ! Keep the image represented by the current neighbor-list node.
     344          830 :                ra(:) = pbc(particle_set(iatom)%r(:), cell)
     345         3320 :                rb(:) = ra(:) + rab(:)
     346          830 :                rac(:) = pbc(rc, ra, cell)
     347          830 :                IF (my_neighbor_image) THEN
     348         1720 :                   rbc(:) = rac(:) + rab(:)
     349              :                ELSE
     350          400 :                   rbc(:) = pbc(rc, rb, cell)
     351              :                END IF
     352         3320 :                dab = NORM2(rab)
     353        13965 :             ELSE IF (my_neighbor_image) THEN
     354              :                ! Keep the neighbor-list image while selecting one atom-pair representative.
     355           72 :                ra(:) = particle_set(iatom)%r(:)
     356           72 :                rb(:) = ra(:) + rab(:)
     357           18 :                rac(:) = pbc(rc, ra, cell)
     358           72 :                rbc(:) = rac(:) + rab(:)
     359           72 :                dab = NORM2(rab)
     360              :             ELSE
     361              :                ! Fold atomic positions around the reference point.
     362       111576 :                ra(:) = pbc(particle_set(iatom)%r(:) - rc, cell) + rc
     363       111576 :                rb(:) = pbc(particle_set(jatom)%r(:) - rc, cell) + rc
     364        55788 :                rab(:) = ra(:) - rb(:)
     365        55788 :                rac(:) = ra(:) - rc(:)
     366        55788 :                rbc(:) = rb(:) - rc(:)
     367        55788 :                dab = NORM2(rab)
     368              :             END IF
     369              : 
     370        75129 :             DO iset = 1, nseta
     371              : 
     372        23057 :                ncoa = npgfa(iset)*ncoset(la_max(iset))
     373        23057 :                sgfa = first_sgfa(1, iset)
     374              : 
     375        81260 :                DO jset = 1, nsetb
     376              : 
     377        43408 :                   IF (set_radius_a(iset) + set_radius_b(jset) < dab) CYCLE
     378              : 
     379        42526 :                   ncob = npgfb(jset)*ncoset(lb_max(jset))
     380        42526 :                   sgfb = first_sgfb(1, jset)
     381              : 
     382              :                   ! Calculate the primitive integrals
     383              :                   CALL moment(la_max(iset), npgfa(iset), zeta(:, iset), &
     384              :                               rpgfa(:, iset), la_min(iset), &
     385              :                               lb_max(jset), npgfb(jset), zetb(:, jset), &
     386        42526 :                               rpgfb(:, jset), nmoments, rac, rbc, mab)
     387              : 
     388              :                   ! Contraction step
     389       198591 :                   DO i = component_start, nm
     390              : 
     391              :                      CALL dgemm("N", "N", ncoa, nsgfb(jset), ncob, &
     392              :                                 1.0_dp, mab(1, 1, i), SIZE(mab, 1), &
     393              :                                 sphi_b(1, sgfb), SIZE(sphi_b, 1), &
     394       133008 :                                 0.0_dp, work(1, 1), SIZE(work, 1))
     395              : 
     396       176416 :                      IF (iatom <= jatom) THEN
     397              : 
     398              :                         CALL dgemm("T", "N", nsgfa(iset), nsgfb(jset), ncoa, &
     399              :                                    1.0_dp, sphi_a(1, sgfa), SIZE(sphi_a, 1), &
     400              :                                    work(1, 1), SIZE(work, 1), &
     401              :                                    1.0_dp, mint(i)%block(sgfa, sgfb), &
     402        86926 :                                    SIZE(mint(i)%block, 1))
     403              : 
     404              :                      ELSE
     405              : 
     406              :                         CALL dgemm("T", "N", nsgfb(jset), nsgfa(iset), ncoa, &
     407              :                                    1.0_dp, work(1, 1), SIZE(work, 1), &
     408              :                                    sphi_a(1, sgfa), SIZE(sphi_a, 1), &
     409              :                                    1.0_dp, mint(i)%block(sgfb, sgfa), &
     410        46082 :                                    SIZE(mint(i)%block, 1))
     411              : 
     412              :                      END IF
     413              : 
     414              :                   END DO
     415              : 
     416              :                END DO
     417              :             END DO
     418              :          END ASSOCIATE
     419              : 
     420              :       END DO
     421         3712 :       CALL neighbor_list_iterator_release(nl_iterator)
     422              : 
     423              :       ! Release work storage
     424         3712 :       DEALLOCATE (mab, basis_set_list)
     425         3712 :       DEALLOCATE (work)
     426        15018 :       DO i = component_start, nm
     427        15018 :          NULLIFY (mint(i)%block)
     428              :       END DO
     429         3712 :       DEALLOCATE (mint)
     430              : 
     431         3712 :       CALL timestop(handle)
     432              : 
     433         7424 :    END SUBROUTINE build_local_moment_matrix
     434              : 
     435              : ! **************************************************************************************************
     436              : !> \brief The AO multipoles M^k_µν = <φ_µ|(r - r_0)^k|φ_ν> of every order up to n_moments, on the
     437              : !>        block pattern of the overlap, about r_0, the centre of atomic charges;
     438              : !>        k = x, y, z for order 1, then xx, xy, xz, yy, yz, zz for order 2
     439              : !> \param qs_env source of the basis, the geometry and the overlap's block pattern
     440              : !> \param n_moments highest order, 1 for dipoles, 2 adds quadrupoles
     441              : !> \param matrix_multipole M^k_µν, one entry per component k, allocated here; the caller releases it
     442              : !> \param rpoint r_0
     443              : ! **************************************************************************************************
     444           70 :    SUBROUTINE get_multipoles_ao(qs_env, n_moments, matrix_multipole, rpoint)
     445              : 
     446              :       TYPE(qs_environment_type), POINTER                 :: qs_env
     447              :       INTEGER, INTENT(IN)                                :: n_moments
     448              :       TYPE(dbcsr_p_type), DIMENSION(:), POINTER          :: matrix_multipole
     449              :       REAL(KIND=dp), DIMENSION(3), INTENT(OUT)           :: rpoint
     450              : 
     451              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'get_multipoles_ao'
     452              : 
     453              :       INTEGER                                            :: handle, idir, n_multipole
     454           70 :       REAL(KIND=dp), DIMENSION(:), POINTER               :: ref_point
     455           70 :       TYPE(dbcsr_p_type), DIMENSION(:), POINTER          :: matrix_s
     456              :       TYPE(neighbor_list_set_p_type), DIMENSION(:), &
     457           70 :          POINTER                                         :: sab_orb
     458              : 
     459           70 :       CALL timeset(routineN, handle)
     460              : 
     461           70 :       NULLIFY (matrix_s, sab_orb, ref_point)
     462           70 :       CALL get_qs_env(qs_env, matrix_s=matrix_s, sab_orb=sab_orb)
     463              : 
     464              :       ! components of every order up to n_moments: 3 dipoles, then 6 quadrupoles
     465           70 :       n_multipole = (6 + 11*n_moments + 6*n_moments**2 + n_moments**3)/6 - 1
     466           70 :       NULLIFY (matrix_multipole)
     467           70 :       CALL dbcsr_allocate_matrix_set(matrix_multipole, n_multipole)
     468          316 :       DO idir = 1, n_multipole
     469          246 :          CALL dbcsr_init_p(matrix_multipole(idir)%matrix)
     470              :          CALL dbcsr_create(matrix_multipole(idir)%matrix, name="ao_multipole", &
     471          246 :                            template=matrix_s(1)%matrix, matrix_type=dbcsr_type_symmetric)
     472          246 :          CALL cp_dbcsr_alloc_block_from_nbl(matrix_multipole(idir)%matrix, sab_orb)
     473          316 :          CALL dbcsr_set(matrix_multipole(idir)%matrix, 0._dp)
     474              :       END DO
     475              : 
     476           70 :       CALL get_reference_point(rpoint, qs_env=qs_env, reference=use_mom_ref_coac, ref_point=ref_point)
     477           70 :       CALL build_local_moment_matrix(qs_env, matrix_multipole, n_moments, ref_point=rpoint)
     478              : 
     479           70 :       CALL timestop(handle)
     480              : 
     481           70 :    END SUBROUTINE get_multipoles_ao
     482              : 
     483              : ! **************************************************************************************************
     484              : !> \brief Calculate right-hand sided derivatives of multipole moments, e. g. < a | xy d/dz | b >
     485              : !>        Optionally stores the multipole moments themselves for free.
     486              : !>        Note that the multipole moments are symmetric while their derivatives are anti-symmetric
     487              : !>        Only first derivatives are performed, e. g. x d/dy
     488              : !> \param qs_env ...
     489              : !> \param moments_der will contain the derivatives of the multipole moments
     490              : !> \param nmoments_der order of the moments with derivatives
     491              : !> \param nmoments order of the multipole moments (no derivatives, same output as
     492              : !>        build_local_moment_matrix, needs moments as arguments to store results)
     493              : !> \param ref_point ...
     494              : !> \param moments contains the multipole moments, optionally for free, up to order nmoments
     495              : !> \param basis_type basis set used for the integral evaluation
     496              : !> \param minimum_image apply the half-cell image filter
     497              : !> \param ordered use ordered neighbor blocks and, for ordinary derivatives, the full neighbor list
     498              : !> \param lambda optional atom selector for the right-hand derivative
     499              : !> \param deltaR optional weights for left and right nuclear-coordinate derivatives
     500              : !> \param neighbor_image use the neighbor-list image for coordinate construction
     501              : ! **************************************************************************************************
     502         4134 :    SUBROUTINE build_local_moments_der_matrix(qs_env, moments_der, nmoments_der, nmoments, &
     503         4134 :                                              ref_point, moments, basis_type, minimum_image, ordered, lambda, &
     504              :                                              deltaR, neighbor_image)
     505              :       TYPE(qs_environment_type), POINTER                 :: qs_env
     506              :       TYPE(dbcsr_p_type), DIMENSION(:, :), &
     507              :          INTENT(INOUT), POINTER                          :: moments_der
     508              :       INTEGER, INTENT(IN)                                :: nmoments_der, nmoments
     509              :       REAL(KIND=dp), DIMENSION(:), INTENT(IN), OPTIONAL  :: ref_point
     510              :       TYPE(dbcsr_p_type), DIMENSION(:), INTENT(INOUT), &
     511              :          OPTIONAL, POINTER                               :: moments
     512              :       CHARACTER(len=*), OPTIONAL                         :: basis_type
     513              :       LOGICAL, OPTIONAL                                   :: minimum_image, ordered
     514              :       INTEGER, OPTIONAL                                   :: lambda
     515              :       REAL(KIND=dp), DIMENSION(:, :), OPTIONAL, POINTER  :: deltaR
     516              :       LOGICAL, OPTIONAL                                   :: neighbor_image
     517              : 
     518              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'build_local_moments_der_matrix'
     519              : 
     520              :       INTEGER :: dimders, handle, i, iatom, icol, ider, ii, ikind, inode, ipgf, irow, iset, j, &
     521              :                  jatom, jkind, jpgf, jset, last_jatom, lda_min, M_dim, maxco, maxsgf, na, nb, ncoa, ncob, nda, ndb, &
     522              :                  nders, nkind, nm, nmom_build, nseta, nsetb, sgfa, sgfb
     523              :       LOGICAL                                            :: accumulate_images, found, my_minimum_image, my_neighbor_image, &
     524              :                                                             my_ordered, new_atom_pair
     525              :       REAL(KIND=dp)                                      :: dab, derivative_sign
     526              :       REAL(KIND=dp), DIMENSION(3)                        :: half_cell
     527         4134 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :)        :: work
     528         4134 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :, :)     :: mab
     529         4134 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :, :, :)  :: difmab
     530              :       REAL(KIND=dp), DIMENSION(3)                        :: ra, rab, rac, rb, rbc, rc
     531         4134 :       REAL(KIND=dp), DIMENSION(:, :, :), POINTER         :: mab_tmp
     532         4134 :       TYPE(block_p_type), ALLOCATABLE, DIMENSION(:)      :: mom_block
     533         4134 :       TYPE(block_p_type), ALLOCATABLE, DIMENSION(:, :)   :: mom_block_der
     534              :       TYPE(cell_type), POINTER                           :: cell
     535         4134 :       TYPE(gto_basis_set_p_type), DIMENSION(:), POINTER  :: basis_set_list
     536              :       TYPE(gto_basis_set_type), POINTER                  :: basis_set_a, basis_set_b
     537              :       TYPE(neighbor_list_iterator_p_type), &
     538         4134 :          DIMENSION(:), POINTER                           :: nl_iterator
     539              :       TYPE(neighbor_list_set_p_type), DIMENSION(:), &
     540         4134 :          POINTER                                         :: sab_all, sab_orb
     541         4134 :       TYPE(particle_type), DIMENSION(:), POINTER         :: particle_set
     542         4134 :       TYPE(qs_kind_type), DIMENSION(:), POINTER          :: qs_kind_set
     543              :       TYPE(qs_kind_type), POINTER                        :: qs_kind
     544              : 
     545         4134 :       nmom_build = MAX(nmoments, nmoments_der)      ! build moments up to order nmom_buiod
     546         4134 :       IF (nmom_build < 1) RETURN
     547              : 
     548         4134 :       CALL timeset(routineN, handle)
     549              : 
     550         4134 :       nders = 1                                    ! only first order derivatives
     551         4134 :       dimders = ncoset(nders) - 1
     552              : 
     553         4134 :       my_minimum_image = .FALSE.
     554         4134 :       IF (PRESENT(minimum_image)) my_minimum_image = minimum_image
     555         4134 :       my_ordered = .FALSE.
     556         4134 :       IF (PRESENT(ordered)) my_ordered = ordered
     557         4134 :       my_neighbor_image = my_ordered
     558         4134 :       IF (PRESENT(neighbor_image)) my_neighbor_image = neighbor_image
     559         4134 :       CPASSERT(.NOT. (PRESENT(deltaR) .AND. PRESENT(lambda)))
     560         4134 :       IF (PRESENT(lambda) .OR. PRESENT(deltaR)) THEN
     561          510 :          CPASSERT(my_ordered)
     562              :       END IF
     563         4134 :       accumulate_images = my_ordered .AND. my_neighbor_image
     564         4134 :       IF (PRESENT(deltaR) .OR. PRESENT(lambda)) accumulate_images = .FALSE.
     565         4134 :       derivative_sign = 1._dp
     566              :       ! diff_momop returns the right nuclear-center derivative. The former
     567              :       ! rRc_xyz_der_ao interface exposed the corresponding electronic derivative
     568              :       ! on the ordinary ordered path.
     569         4134 :       IF (my_ordered .AND. .NOT. PRESENT(deltaR) .AND. .NOT. PRESENT(lambda)) THEN
     570         3582 :          derivative_sign = -1._dp
     571              :       END IF
     572              : 
     573         4134 :       NULLIFY (qs_kind_set, particle_set, sab_all, sab_orb, cell)
     574              :       CALL get_qs_env(qs_env=qs_env, &
     575              :                       qs_kind_set=qs_kind_set, &
     576              :                       particle_set=particle_set, &
     577              :                       cell=cell, &
     578              :                       sab_orb=sab_orb, &
     579         4134 :                       sab_all=sab_all)
     580              : 
     581         4134 :       IF (my_ordered) THEN
     582         4092 :          CPASSERT(nmoments_der > 0)
     583         4092 :          CPASSERT(dbcsr_get_matrix_type(moments_der(1, 1)%matrix) == dbcsr_type_no_symmetry)
     584         4092 :          IF (nmoments > 0) THEN
     585         3582 :             CPASSERT(PRESENT(moments))
     586         3582 :             CPASSERT(dbcsr_get_matrix_type(moments(1)%matrix) == dbcsr_type_no_symmetry)
     587              :          END IF
     588              :       END IF
     589              : 
     590         4134 :       IF (my_minimum_image) THEN
     591            0 :          half_cell = 0.5_dp*NORM2(cell%hmat, DIM=1)
     592              :       END IF
     593              : 
     594         4134 :       nkind = SIZE(qs_kind_set)
     595              : 
     596              :       ! Work storage
     597              :       CALL get_qs_kind_set(qs_kind_set=qs_kind_set, &
     598              :                            maxco=maxco, maxsgf=maxsgf, &
     599         4680 :                            basis_type=basis_type)
     600              : 
     601         4134 :       IF (nmoments > 0) THEN
     602         3622 :          nm = (6 + 11*nmoments + 6*nmoments**2 + nmoments**3)/6 - 1
     603         3622 :          CPASSERT(SIZE(moments) == nm)
     604              :          ! storage for integrals
     605        18098 :          ALLOCATE (mab(maxco, maxco, nm))
     606              :          ! blocks
     607         3622 :          mab(:, :, :) = 0.0_dp
     608        43464 :          ALLOCATE (mom_block(nm))
     609        36220 :          DO i = 1, nm
     610        36220 :             NULLIFY (mom_block(i)%block)
     611              :          END DO
     612              :       END IF
     613              : 
     614         4134 :       IF (nmoments_der > 0) THEN
     615         4134 :          M_dim = ncoset(nmoments_der) - 1
     616         4134 :          CPASSERT(SIZE(moments_der, dim=1) == M_dim)
     617         4134 :          CPASSERT(SIZE(moments_der, dim=2) == dimders)
     618              :          ! storage for integrals
     619        24792 :          ALLOCATE (difmab(maxco, maxco, M_dim, dimders))
     620         4134 :          difmab(:, :, :, :) = 0.0_dp
     621              :          ! blocks
     622       130656 :          ALLOCATE (mom_block_der(M_dim, dimders))
     623        38040 :          DO i = 1, M_dim
     624       139758 :             DO ider = 1, dimders
     625       135624 :                NULLIFY (mom_block_der(i, ider)%block)
     626              :             END DO
     627              :          END DO
     628              :       END IF
     629              : 
     630        16530 :       ALLOCATE (work(maxco, maxsgf))
     631         4134 :       work(:, :) = 0.0_dp
     632              : 
     633         4134 :       NULLIFY (basis_set_a, basis_set_b, basis_set_list)
     634         4134 :       NULLIFY (qs_kind)
     635        19370 :       ALLOCATE (basis_set_list(nkind))
     636        11102 :       DO ikind = 1, nkind
     637         6968 :          qs_kind => qs_kind_set(ikind)
     638         6968 :          CALL get_qs_kind(qs_kind=qs_kind, basis_set=basis_set_a, basis_type=basis_type)
     639        11102 :          IF (ASSOCIATED(basis_set_a)) THEN
     640         6968 :             basis_set_list(ikind)%gto_basis_set => basis_set_a
     641              :          ELSE
     642            0 :             NULLIFY (basis_set_list(ikind)%gto_basis_set)
     643              :          END IF
     644              :       END DO
     645              : 
     646              :       ! Calculate derivatives looping over neighbour list
     647         4134 :       NULLIFY (nl_iterator)
     648         4134 :       IF (my_ordered) THEN
     649         4092 :          CALL neighbor_list_iterator_create(nl_iterator, sab_all)
     650              :       ELSE
     651           42 :          CALL neighbor_list_iterator_create(nl_iterator, sab_orb)
     652              :       END IF
     653       295200 :       DO WHILE (neighbor_list_iterate(nl_iterator) == 0)
     654              :          CALL get_iterator_info(nl_iterator, ikind=ikind, jkind=jkind, inode=inode, &
     655       291066 :                                 iatom=iatom, jatom=jatom, r=rab)
     656       291066 :          basis_set_a => basis_set_list(ikind)%gto_basis_set
     657       291066 :          IF (.NOT. ASSOCIATED(basis_set_a)) CYCLE
     658       291066 :          basis_set_b => basis_set_list(jkind)%gto_basis_set
     659       291066 :          IF (.NOT. ASSOCIATED(basis_set_b)) CYCLE
     660              :          ASSOCIATE ( &
     661              :             ! basis ikind
     662              :             first_sgfa => basis_set_a%first_sgf, &
     663              :             la_max => basis_set_a%lmax, &
     664              :             la_min => basis_set_a%lmin, &
     665              :             npgfa => basis_set_a%npgf, &
     666              :             nsgfa => basis_set_a%nsgf_set, &
     667              :             rpgfa => basis_set_a%pgf_radius, &
     668              :             set_radius_a => basis_set_a%set_radius, &
     669              :             sphi_a => basis_set_a%sphi, &
     670              :             zeta => basis_set_a%zet, &
     671              :             ! basis jkind, &
     672              :             first_sgfb => basis_set_b%first_sgf, &
     673              :             lb_max => basis_set_b%lmax, &
     674              :             lb_min => basis_set_b%lmin, &
     675              :             npgfb => basis_set_b%npgf, &
     676              :             nsgfb => basis_set_b%nsgf_set, &
     677              :             rpgfb => basis_set_b%pgf_radius, &
     678              :             set_radius_b => basis_set_b%set_radius, &
     679              :             sphi_b => basis_set_b%sphi, &
     680              :             zetb => basis_set_b%zet)
     681              : 
     682       291066 :             IF (SIZE(sphi_a, 1) == 0) CYCLE
     683       291045 :             IF (SIZE(sphi_b, 1) == 0) CYCLE
     684              : 
     685       291045 :             nseta = basis_set_a%nset
     686       291045 :             nsetb = basis_set_b%nset
     687              : 
     688       291045 :             IF (inode == 1) last_jatom = 0
     689              : 
     690       291045 :             IF (my_minimum_image) THEN
     691            0 :                IF (ANY(ABS(rab(:)) > half_cell(:))) CYCLE
     692              :             END IF
     693              : 
     694       291045 :             new_atom_pair = jatom /= last_jatom
     695              :             ! The ordinary ordered neighbor-image path accumulates all images for one atom pair.
     696              :             ! Specialized derivative paths select one representative image, as in the former builders.
     697       291045 :             IF (.NOT. accumulate_images .AND. .NOT. new_atom_pair) CYCLE
     698              : 
     699       272163 :             IF (new_atom_pair) THEN
     700        21021 :                last_jatom = jatom
     701              : 
     702              :                ! get blocks
     703        21021 :                IF (my_ordered) THEN
     704        19677 :                   irow = iatom
     705        19677 :                   icol = jatom
     706         1344 :                ELSE IF (iatom <= jatom) THEN
     707          710 :                   irow = iatom
     708          710 :                   icol = jatom
     709              :                ELSE
     710          634 :                   irow = jatom
     711          634 :                   icol = iatom
     712              :                END IF
     713              : 
     714        21021 :                IF (nmoments > 0) THEN
     715       187200 :                   DO i = 1, nm
     716       168480 :                      NULLIFY (mom_block(i)%block)
     717              :                      ! get block from pre calculated overlap matrix
     718              :                      CALL dbcsr_get_block_p(matrix=moments(i)%matrix, &
     719       168480 :                                             row=irow, col=icol, BLOCK=mom_block(i)%block, found=found)
     720       168480 :                      CPASSERT(found .AND. ASSOCIATED(mom_block(i)%block))
     721     13060368 :                      mom_block(i)%block = 0._dp
     722              :                   END DO
     723              :                END IF
     724        21021 :                IF (nmoments_der > 0) THEN
     725       188412 :                   DO i = 1, M_dim
     726       690585 :                      DO ider = 1, dimders
     727       502173 :                         NULLIFY (mom_block_der(i, ider)%block)
     728              :                         CALL dbcsr_get_block_p(matrix=moments_der(i, ider)%matrix, &
     729              :                                                row=irow, col=icol, &
     730              :                                                block=mom_block_der(i, ider)%block, &
     731       502173 :                                                found=found)
     732       502173 :                         CPASSERT(found .AND. ASSOCIATED(mom_block_der(i, ider)%block))
     733     39136707 :                         mom_block_der(i, ider)%block = 0._dp
     734              :                      END DO
     735              :                   END DO
     736              :                END IF
     737              :             END IF
     738              : 
     739              :             ! reference point
     740       272163 :             IF (PRESENT(ref_point)) THEN
     741      1088652 :                rc(:) = ref_point(:)
     742              :             ELSE
     743            0 :                rc(:) = 0._dp
     744              :             END IF
     745              :             ! using PBC here might screw a molecule that fits the box (but e.g. hasn't been shifted by center_molecule)
     746              :             ! by folding around the center, such screwing can be avoided for a proper choice of center.
     747       272163 :             IF (my_neighbor_image) THEN
     748       268551 :                ra(:) = pbc(particle_set(iatom)%r(:), cell)
     749      1074204 :                rb(:) = ra(:) + rab(:)
     750       268551 :                rac(:) = pbc(rc, ra, cell)
     751      1074204 :                rbc(:) = rac(:) + rab(:)
     752         3612 :             ELSE IF (my_ordered) THEN
     753         9072 :                ra(:) = particle_set(iatom)%r(:)
     754         9072 :                rb(:) = particle_set(jatom)%r(:)
     755         2268 :                rab(:) = pbc(rb, ra, cell)
     756         9072 :                rac(:) = pbc(ra - rc, cell)
     757         9072 :                rbc(:) = pbc(rb - rc, cell)
     758              :             ELSE
     759        10752 :                ra(:) = pbc(particle_set(iatom)%r(:) - rc, cell) + rc
     760        10752 :                rb(:) = pbc(particle_set(jatom)%r(:) - rc, cell) + rc
     761              :                ! we dont use PBC at this point
     762         5376 :                rab(:) = ra(:) - rb(:)
     763         5376 :                rac(:) = ra(:) - rc(:)
     764         5376 :                rbc(:) = rb(:) - rc(:)
     765              :             END IF
     766      1088652 :             dab = NORM2(rab)
     767              : 
     768      1192773 :             DO iset = 1, nseta
     769              : 
     770       629544 :                ncoa = npgfa(iset)*ncoset(la_max(iset))
     771       629544 :                sgfa = first_sgfa(1, iset)
     772              : 
     773      2434161 :                DO jset = 1, nsetb
     774              : 
     775      1532454 :                   IF (set_radius_a(iset) + set_radius_b(jset) < dab) CYCLE
     776              : 
     777       575127 :                   ncob = npgfb(jset)*ncoset(lb_max(jset))
     778       575127 :                   sgfb = first_sgfb(1, jset)
     779              : 
     780       575127 :                   NULLIFY (mab_tmp)
     781              :                   ALLOCATE (mab_tmp(npgfa(iset)*ncoset(la_max(iset) + 1), &
     782      2848803 :                                     npgfb(jset)*ncoset(lb_max(jset) + 1), ncoset(nmom_build) - 1))
     783              : 
     784              :                   ! Calculate the primitive integrals (need l+1 for derivatives)
     785       575127 :                   lda_min = MAX(0, la_min(iset) - 1)
     786              :                   CALL moment(la_max(iset) + 1, npgfa(iset), zeta(:, iset), &
     787              :                               rpgfa(:, iset), lda_min, &
     788              :                               lb_max(jset) + 1, npgfb(jset), zetb(:, jset), &
     789       575127 :                               rpgfb(:, jset), nmom_build, rac, rbc, mab_tmp)
     790              : 
     791       575127 :                   IF (nmoments_der > 0) THEN
     792              :                      CALL diff_momop(la_max(iset), npgfa(iset), zeta(:, iset), &
     793              :                                      rpgfa(:, iset), la_min(iset), &
     794              :                                      lb_max(jset), npgfb(jset), zetb(:, jset), &
     795              :                                      rpgfb(:, jset), lb_min(jset), &
     796              :                                      nmoments_der, rac, rbc, difmab, mab_ext=mab_tmp, &
     797       575127 :                                      lambda=lambda, deltaR=deltaR, iatom=iatom, jatom=jatom)
     798              :                   END IF
     799              : 
     800       575127 :                   IF (nmoments > 0) THEN
     801              :                      ! copy subset of mab_tmp (l+1) to mab (l)
     802       572826 :                      mab = 0.0_dp
     803      5728260 :                      DO ii = 1, nm
     804      5155434 :                         na = 0
     805      5155434 :                         nda = 0
     806     16768722 :                         DO ipgf = 1, npgfa(iset)
     807     11040462 :                            nb = 0
     808     11040462 :                            ndb = 0
     809     40123782 :                            DO jpgf = 1, npgfb(jset)
     810    119211723 :                               DO j = 1, ncoset(lb_max(jset))
     811    454485897 :                                  DO i = 1, ncoset(la_max(iset))
     812    425402577 :                                     mab(i + na, j + nb, ii) = mab_tmp(i + nda, j + ndb, ii)
     813              :                                  END DO ! i
     814              :                               END DO ! j
     815     29083320 :                               nb = nb + ncoset(lb_max(jset))
     816     40123782 :                               ndb = ndb + ncoset(lb_max(jset) + 1)
     817              :                            END DO ! jpgf
     818     11040462 :                            na = na + ncoset(la_max(iset))
     819     16195896 :                            nda = nda + ncoset(la_max(iset) + 1)
     820              :                         END DO ! ipgf
     821              :                      END DO
     822              :                      ! Contraction step
     823      5728260 :                      DO i = 1, nm
     824              : 
     825              :                         CALL dgemm("N", "N", ncoa, nsgfb(jset), ncob, &
     826              :                                    1.0_dp, mab(1, 1, i), SIZE(mab, 1), &
     827              :                                    sphi_b(1, sgfb), SIZE(sphi_b, 1), &
     828      5155434 :                                    0.0_dp, work(1, 1), SIZE(work, 1))
     829              : 
     830      5728260 :                         IF (my_ordered .OR. iatom <= jatom) THEN
     831              :                            CALL dgemm("T", "N", nsgfa(iset), nsgfb(jset), ncoa, &
     832              :                                       1.0_dp, sphi_a(1, sgfa), SIZE(sphi_a, 1), &
     833              :                                       work(1, 1), SIZE(work, 1), &
     834              :                                       1.0_dp, mom_block(i)%block(sgfa, sgfb), &
     835      5151717 :                                       SIZE(mom_block(i)%block, 1))
     836              :                         ELSE
     837              :                            CALL dgemm("T", "N", nsgfb(jset), nsgfa(iset), ncoa, &
     838              :                                       1.0_dp, work(1, 1), SIZE(work, 1), &
     839              :                                       sphi_a(1, sgfa), SIZE(sphi_a, 1), &
     840              :                                       1.0_dp, mom_block(i)%block(sgfb, sgfa), &
     841         3717 :                                       SIZE(mom_block(i)%block, 1))
     842              :                         END IF
     843              :                      END DO
     844              :                   END IF
     845              : 
     846       575127 :                   IF (nmoments_der > 0) THEN
     847      5731812 :                      DO i = 1, M_dim
     848     21201867 :                         DO ider = 1, dimders
     849              :                            CALL dgemm("N", "N", ncoa, nsgfb(jset), ncob, &
     850              :                                       derivative_sign, difmab(1, 1, i, ider), SIZE(difmab, 1), &
     851              :                                       sphi_b(1, sgfb), SIZE(sphi_b, 1), &
     852     15470055 :                                       0._dp, work(1, 1), SIZE(work, 1))
     853              : 
     854     20626740 :                            IF (my_ordered .OR. iatom <= jatom) THEN
     855              :                               CALL dgemm("T", "N", nsgfa(iset), nsgfb(jset), ncoa, &
     856              :                                          1.0_dp, sphi_a(1, sgfa), SIZE(sphi_a, 1), &
     857              :                                          work(1, 1), SIZE(work, 1), &
     858              :                                          1.0_dp, mom_block_der(i, ider)%block(sgfa, sgfb), &
     859     15466284 :                                          SIZE(mom_block_der(i, ider)%block, 1))
     860              :                            ELSE
     861              :                               CALL dgemm("T", "N", nsgfb(jset), nsgfa(iset), ncoa, &
     862              :                                          -1.0_dp, work(1, 1), SIZE(work, 1), &
     863              :                                          sphi_a(1, sgfa), SIZE(sphi_a, 1), &
     864              :                                          1.0_dp, mom_block_der(i, ider)%block(sgfb, sgfa), &
     865         3771 :                                          SIZE(mom_block_der(i, ider)%block, 1))
     866              :                            END IF
     867              :                         END DO
     868              :                      END DO
     869              :                   END IF
     870      2161998 :                   DEALLOCATE (mab_tmp)
     871              :                END DO
     872              :             END DO
     873              :          END ASSOCIATE
     874              :       END DO
     875         4134 :       CALL neighbor_list_iterator_release(nl_iterator)
     876              : 
     877              :       ! deallocations
     878         4134 :       DEALLOCATE (basis_set_list)
     879         4134 :       DEALLOCATE (work)
     880         4134 :       IF (nmoments > 0) THEN
     881         3622 :          DEALLOCATE (mab)
     882        36220 :          DO i = 1, nm
     883        36220 :             NULLIFY (mom_block(i)%block)
     884              :          END DO
     885         3622 :          DEALLOCATE (mom_block)
     886              :       END IF
     887         4134 :       IF (nmoments_der > 0) THEN
     888         4134 :          DEALLOCATE (difmab)
     889        38040 :          DO i = 1, M_dim
     890       139758 :             DO ider = 1, dimders
     891       135624 :                NULLIFY (mom_block_der(i, ider)%block)
     892              :             END DO
     893              :          END DO
     894         4134 :          DEALLOCATE (mom_block_der)
     895              :       END IF
     896              : 
     897         4134 :       CALL timestop(handle)
     898              : 
     899         8268 :    END SUBROUTINE build_local_moments_der_matrix
     900              : 
     901              : ! **************************************************************************************************
     902              : !> \brief ...
     903              : !> \param qs_env ...
     904              : !> \param magmom ...
     905              : !> \param nmoments ...
     906              : !> \param ref_point ...
     907              : !> \param ref_points ...
     908              : !> \param basis_type ...
     909              : ! **************************************************************************************************
     910           64 :    SUBROUTINE build_local_magmom_matrix(qs_env, magmom, nmoments, ref_point, ref_points, basis_type)
     911              : 
     912              :       TYPE(qs_environment_type), POINTER                 :: qs_env
     913              :       TYPE(dbcsr_p_type), DIMENSION(:), POINTER          :: magmom
     914              :       INTEGER, INTENT(IN)                                :: nmoments
     915              :       REAL(KIND=dp), DIMENSION(:), INTENT(IN), OPTIONAL  :: ref_point
     916              :       REAL(KIND=dp), DIMENSION(:, :), INTENT(IN), &
     917              :          OPTIONAL                                        :: ref_points
     918              :       CHARACTER(len=*), OPTIONAL                         :: basis_type
     919              : 
     920              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'build_local_magmom_matrix'
     921              : 
     922              :       INTEGER :: handle, i, iatom, icol, ikind, inode, irow, iset, jatom, jkind, jset, maxco, &
     923              :                  maxsgf, ncoa, ncob, nkind, nm, nseta, nsetb, sgfa, sgfb
     924              :       LOGICAL                                            :: found
     925              :       REAL(KIND=dp)                                      :: dab
     926           64 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :)        :: work
     927           64 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :, :)     :: mab
     928              :       REAL(KIND=dp), DIMENSION(3)                        :: ra, rab, rac, rb, rbc, rc
     929           64 :       TYPE(block_p_type), ALLOCATABLE, DIMENSION(:)      :: mint
     930              :       TYPE(cell_type), POINTER                           :: cell
     931           64 :       TYPE(gto_basis_set_p_type), DIMENSION(:), POINTER  :: basis_set_list
     932              :       TYPE(gto_basis_set_type), POINTER                  :: basis_set_a, basis_set_b
     933              :       TYPE(neighbor_list_iterator_p_type), &
     934           64 :          DIMENSION(:), POINTER                           :: nl_iterator
     935              :       TYPE(neighbor_list_set_p_type), DIMENSION(:), &
     936           64 :          POINTER                                         :: sab_orb
     937           64 :       TYPE(particle_type), DIMENSION(:), POINTER         :: particle_set
     938           64 :       TYPE(qs_kind_type), DIMENSION(:), POINTER          :: qs_kind_set
     939              :       TYPE(qs_kind_type), POINTER                        :: qs_kind
     940              : 
     941           64 :       IF (nmoments < 1) RETURN
     942              : 
     943           64 :       CALL timeset(routineN, handle)
     944              : 
     945              :       ! magnetic dipoles/angular moments only
     946           64 :       nm = 3
     947              : 
     948           64 :       NULLIFY (qs_kind_set, particle_set, sab_orb, cell)
     949              :       CALL get_qs_env(qs_env=qs_env, &
     950              :                       qs_kind_set=qs_kind_set, &
     951              :                       particle_set=particle_set, cell=cell, &
     952           64 :                       sab_orb=sab_orb)
     953              : 
     954           64 :       nkind = SIZE(qs_kind_set)
     955              : 
     956              :       ! Allocate work storage
     957              :       CALL get_qs_kind_set(qs_kind_set=qs_kind_set, &
     958           64 :                            maxco=maxco, maxsgf=maxsgf)
     959              : 
     960          320 :       ALLOCATE (mab(maxco, maxco, nm))
     961           64 :       mab(:, :, :) = 0.0_dp
     962              : 
     963          256 :       ALLOCATE (work(maxco, maxsgf))
     964           64 :       work(:, :) = 0.0_dp
     965              : 
     966          256 :       ALLOCATE (mint(nm))
     967          256 :       DO i = 1, nm
     968          256 :          NULLIFY (mint(i)%block)
     969              :       END DO
     970              : 
     971          356 :       ALLOCATE (basis_set_list(nkind))
     972          228 :       DO ikind = 1, nkind
     973          164 :          qs_kind => qs_kind_set(ikind)
     974          328 :          CALL get_qs_kind(qs_kind=qs_kind, basis_set=basis_set_a, basis_type=basis_type)
     975          228 :          IF (ASSOCIATED(basis_set_a)) THEN
     976          164 :             basis_set_list(ikind)%gto_basis_set => basis_set_a
     977              :          ELSE
     978            0 :             NULLIFY (basis_set_list(ikind)%gto_basis_set)
     979              :          END IF
     980              :       END DO
     981           64 :       CALL neighbor_list_iterator_create(nl_iterator, sab_orb)
     982         7696 :       DO WHILE (neighbor_list_iterate(nl_iterator) == 0)
     983              :          CALL get_iterator_info(nl_iterator, ikind=ikind, jkind=jkind, inode=inode, &
     984         7632 :                                 iatom=iatom, jatom=jatom, r=rab)
     985         7632 :          basis_set_a => basis_set_list(ikind)%gto_basis_set
     986         7632 :          IF (.NOT. ASSOCIATED(basis_set_a)) CYCLE
     987         7632 :          basis_set_b => basis_set_list(jkind)%gto_basis_set
     988         7632 :          IF (.NOT. ASSOCIATED(basis_set_b)) CYCLE
     989              :          ASSOCIATE ( &
     990              :             ! basis ikind
     991              :             first_sgfa => basis_set_a%first_sgf, &
     992              :             la_max => basis_set_a%lmax, &
     993              :             la_min => basis_set_a%lmin, &
     994              :             npgfa => basis_set_a%npgf, &
     995              :             nsgfa => basis_set_a%nsgf_set, &
     996              :             rpgfa => basis_set_a%pgf_radius, &
     997              :             set_radius_a => basis_set_a%set_radius, &
     998              :             sphi_a => basis_set_a%sphi, &
     999              :             zeta => basis_set_a%zet, &
    1000              :             ! basis jkind, &
    1001              :             first_sgfb => basis_set_b%first_sgf, &
    1002              :             lb_max => basis_set_b%lmax, &
    1003              :             lb_min => basis_set_b%lmin, &
    1004              :             npgfb => basis_set_b%npgf, &
    1005              :             nsgfb => basis_set_b%nsgf_set, &
    1006              :             rpgfb => basis_set_b%pgf_radius, &
    1007              :             set_radius_b => basis_set_b%set_radius, &
    1008              :             sphi_b => basis_set_b%sphi, &
    1009              :             zetb => basis_set_b%zet)
    1010              : 
    1011         7632 :             nseta = basis_set_a%nset
    1012         7632 :             nsetb = basis_set_b%nset
    1013              : 
    1014         7632 :             IF (iatom <= jatom) THEN
    1015         4216 :                irow = iatom
    1016         4216 :                icol = jatom
    1017              :             ELSE
    1018         3416 :                irow = jatom
    1019         3416 :                icol = iatom
    1020              :             END IF
    1021              : 
    1022        30528 :             DO i = 1, nm
    1023        22896 :                NULLIFY (mint(i)%block)
    1024              :                CALL dbcsr_get_block_p(matrix=magmom(i)%matrix, &
    1025        22896 :                                       row=irow, col=icol, BLOCK=mint(i)%block, found=found)
    1026        22896 :                CPASSERT(found .AND. ASSOCIATED(mint(i)%block))
    1027       384762 :                mint(i)%block = 0._dp
    1028              :             END DO
    1029              : 
    1030              :             ! fold atomic position back into unit cell
    1031         7632 :             IF (PRESENT(ref_points)) THEN
    1032            0 :                rc(:) = 0.5_dp*(ref_points(:, iatom) + ref_points(:, jatom))
    1033         7632 :             ELSE IF (PRESENT(ref_point)) THEN
    1034        30528 :                rc(:) = ref_point(:)
    1035              :             ELSE
    1036            0 :                rc(:) = 0._dp
    1037              :             END IF
    1038              :             ! using PBC here might screw a molecule that fits the box (but e.g. hasn't been shifted by center_molecule)
    1039              :             ! by folding around the center, such screwing can be avoided for a proper choice of center.
    1040        61056 :             ra(:) = pbc(particle_set(iatom)%r(:) - rc, cell) + rc
    1041        61056 :             rb(:) = pbc(particle_set(jatom)%r(:) - rc, cell) + rc
    1042              :             ! we dont use PBC at this point
    1043        30528 :             rab(:) = ra(:) - rb(:)
    1044        30528 :             rac(:) = ra(:) - rc(:)
    1045        30528 :             rbc(:) = rb(:) - rc(:)
    1046        30528 :             dab = NORM2(rab)
    1047              : 
    1048        23013 :             DO iset = 1, nseta
    1049              : 
    1050         7749 :                ncoa = npgfa(iset)*ncoset(la_max(iset))
    1051         7749 :                sgfa = first_sgfa(1, iset)
    1052              : 
    1053        23364 :                DO jset = 1, nsetb
    1054              : 
    1055         7983 :                   IF (set_radius_a(iset) + set_radius_b(jset) < dab) CYCLE
    1056              : 
    1057         6990 :                   ncob = npgfb(jset)*ncoset(lb_max(jset))
    1058         6990 :                   sgfb = first_sgfb(1, jset)
    1059              : 
    1060              :                   ! Calculate the primitive integrals
    1061              :                   CALL angmom(la_max(iset), npgfa(iset), zeta(:, iset), &
    1062              :                               rpgfa(:, iset), la_min(iset), &
    1063              :                               lb_max(jset), npgfb(jset), zetb(:, jset), &
    1064         6990 :                               rpgfb(:, jset), rac, rbc, mab)
    1065              : 
    1066              :                   ! Contraction step
    1067        35709 :                   DO i = 1, nm
    1068              :                      CALL dgemm("N", "N", ncoa, nsgfb(jset), ncob, &
    1069              :                                 1.0_dp, mab(1, 1, i), SIZE(mab, 1), &
    1070              :                                 sphi_b(1, sgfb), SIZE(sphi_b, 1), &
    1071        20970 :                                 0.0_dp, work(1, 1), SIZE(work, 1))
    1072              : 
    1073        28953 :                      IF (iatom <= jatom) THEN
    1074              :                         CALL dgemm("T", "N", nsgfa(iset), nsgfb(jset), ncoa, &
    1075              :                                    1.0_dp, sphi_a(1, sgfa), SIZE(sphi_a, 1), &
    1076              :                                    work(1, 1), SIZE(work, 1), &
    1077              :                                    1.0_dp, mint(i)%block(sgfa, sgfb), &
    1078        11901 :                                    SIZE(mint(i)%block, 1))
    1079              :                      ELSE
    1080              :                         CALL dgemm("T", "N", nsgfb(jset), nsgfa(iset), ncoa, &
    1081              :                                    -1.0_dp, work(1, 1), SIZE(work, 1), &
    1082              :                                    sphi_a(1, sgfa), SIZE(sphi_a, 1), &
    1083              :                                    1.0_dp, mint(i)%block(sgfb, sgfa), &
    1084         9069 :                                    SIZE(mint(i)%block, 1))
    1085              :                      END IF
    1086              : 
    1087              :                   END DO
    1088              : 
    1089              :                END DO
    1090              :             END DO
    1091              :          END ASSOCIATE
    1092              :       END DO
    1093           64 :       CALL neighbor_list_iterator_release(nl_iterator)
    1094              : 
    1095              :       ! Release work storage
    1096           64 :       DEALLOCATE (mab, basis_set_list)
    1097           64 :       DEALLOCATE (work)
    1098          256 :       DO i = 1, nm
    1099          256 :          NULLIFY (mint(i)%block)
    1100              :       END DO
    1101           64 :       DEALLOCATE (mint)
    1102              : 
    1103           64 :       CALL timestop(handle)
    1104              : 
    1105          192 :    END SUBROUTINE build_local_magmom_matrix
    1106              : 
    1107              : ! **************************************************************************************************
    1108              : !> \brief ...
    1109              : !> \param qs_env ...
    1110              : !> \param cosmat ...
    1111              : !> \param sinmat ...
    1112              : !> \param kvec ...
    1113              : !> \param sab_orb_external ...
    1114              : !> \param basis_type ...
    1115              : ! **************************************************************************************************
    1116        13250 :    SUBROUTINE build_berry_moment_matrix(qs_env, cosmat, sinmat, kvec, sab_orb_external, basis_type)
    1117              : 
    1118              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    1119              :       TYPE(dbcsr_type), POINTER                          :: cosmat, sinmat
    1120              :       REAL(KIND=dp), DIMENSION(3), INTENT(IN)            :: kvec
    1121              :       TYPE(neighbor_list_set_p_type), DIMENSION(:), &
    1122              :          OPTIONAL, POINTER                               :: sab_orb_external
    1123              :       CHARACTER(len=*), OPTIONAL                         :: basis_type
    1124              : 
    1125              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'build_berry_moment_matrix'
    1126              : 
    1127              :       INTEGER                                            :: handle
    1128        53000 :       TYPE(dbcsr_p_type), DIMENSION(2, 1)                :: op_sm_set
    1129              :       REAL(KIND=dp), DIMENSION(3, 1)                     :: kvec_batch
    1130              : 
    1131        13250 :       CALL timeset(routineN, handle)
    1132              : 
    1133        13250 :       op_sm_set(1, 1)%matrix => cosmat
    1134        13250 :       op_sm_set(2, 1)%matrix => sinmat
    1135        13250 :       kvec_batch(:, 1) = kvec(:)
    1136              : 
    1137              :       CALL build_exp_ikr_matrix(qs_env, op_sm_set, kvec_batch, &
    1138        15340 :                                 sab_orb_external=sab_orb_external, basis_type=basis_type)
    1139              : 
    1140        13250 :       CALL timestop(handle)
    1141              : 
    1142        13250 :    END SUBROUTINE build_berry_moment_matrix
    1143              : 
    1144              : ! **************************************************************************************************
    1145              : !> \brief ...
    1146              : !> \param qs_env ...
    1147              : !> \param cosmat ...
    1148              : !> \param sinmat ...
    1149              : !> \param kvec ...
    1150              : !> \param basis_type ...
    1151              : !> \param ordered use all ordered atom pairs for a non-Hermitian cross-k overlap
    1152              : !> \param ordered_kpoints image-cell mapping for the ordered neighbour list
    1153              : ! **************************************************************************************************
    1154          198 :    SUBROUTINE build_berry_kpoint_matrix(qs_env, cosmat, sinmat, kvec, basis_type, ordered, ordered_kpoints)
    1155              : 
    1156              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    1157              :       TYPE(dbcsr_p_type), DIMENSION(:, :), POINTER       :: cosmat, sinmat
    1158              :       REAL(KIND=dp), DIMENSION(3), INTENT(IN)            :: kvec
    1159              :       CHARACTER(len=*), OPTIONAL                         :: basis_type
    1160              :       LOGICAL, INTENT(IN), OPTIONAL                      :: ordered
    1161              :       TYPE(kpoint_type), POINTER, OPTIONAL               :: ordered_kpoints
    1162              : 
    1163              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'build_berry_kpoint_matrix'
    1164              : 
    1165              :       CHARACTER                                          :: matrix_symmetry
    1166          198 :       COMPLEX(dp), ALLOCATABLE                           :: expab(:, :)
    1167              :       INTEGER :: handle, i, iatom, ic, icol, ikind, inode, irow, iset, jatom, jkind, jset, &
    1168              :                  ldsa, ldsb, ldwork, natom, ncoa, ncob, nimg, nkind, nseta, nsetb, sgfa, sgfb
    1169              :       INTEGER, DIMENSION(3)                              :: icell
    1170          198 :       INTEGER, DIMENSION(:), CONTIGUOUS, POINTER                     :: row_blk_sizes
    1171          198 :       INTEGER, DIMENSION(:, :, :), POINTER               :: cell_to_index
    1172              :       LOGICAL                                            :: found, full_pairs, stable_images, use_cell_mapping
    1173          198 :       REAL(dp), DIMENSION(:, :), POINTER                 :: cblock, sblock, work
    1174              :       REAL(KIND=dp)                                      :: dab
    1175              :       REAL(KIND=dp), DIMENSION(3)                        :: ra, rab, rb
    1176              :       TYPE(cell_type), POINTER                           :: cell
    1177              :       TYPE(dbcsr_distribution_type), POINTER             :: dbcsr_dist
    1178              :       TYPE(dft_control_type), POINTER                    :: dft_control
    1179          198 :       TYPE(gto_basis_set_p_type), DIMENSION(:), POINTER  :: basis_set_list
    1180              :       TYPE(gto_basis_set_type), POINTER                  :: basis_set, basis_set_a, basis_set_b
    1181              :       TYPE(kpoint_type), POINTER                         :: kpoints
    1182              :       TYPE(neighbor_list_iterator_p_type), &
    1183          198 :          DIMENSION(:), POINTER                           :: nl_iterator
    1184              :       TYPE(neighbor_list_set_p_type), DIMENSION(:), &
    1185          198 :          POINTER                                         :: sab_orb
    1186          198 :       TYPE(particle_type), DIMENSION(:), POINTER         :: particle_set
    1187          198 :       TYPE(qs_kind_type), DIMENSION(:), POINTER          :: qs_kind_set
    1188              :       TYPE(qs_kind_type), POINTER                        :: qs_kind
    1189              :       TYPE(qs_ks_env_type), POINTER                      :: ks_env
    1190              : 
    1191          198 :       CALL timeset(routineN, handle)
    1192              : 
    1193          198 :       full_pairs = .FALSE.
    1194          198 :       IF (PRESENT(ordered)) full_pairs = ordered
    1195          198 :       matrix_symmetry = dbcsr_type_symmetric
    1196          198 :       IF (full_pairs) matrix_symmetry = dbcsr_type_no_symmetry
    1197              : 
    1198              :       CALL get_qs_env(qs_env, &
    1199              :                       ks_env=ks_env, &
    1200          198 :                       dft_control=dft_control)
    1201          198 :       CALL get_ks_env(ks_env=ks_env, kpoints=kpoints)
    1202          198 :       stable_images = kpoints%nkp > 0 .AND. kpoints%symmetry
    1203          198 :       nimg = dft_control%nimages
    1204          198 :       IF (nimg > 1) THEN
    1205          198 :          CALL get_kpoint_info(kpoint=kpoints, cell_to_index=cell_to_index)
    1206          198 :          use_cell_mapping = .TRUE.
    1207              :       ELSE
    1208              :          use_cell_mapping = .FALSE.
    1209              :       END IF
    1210              : 
    1211              :       CALL get_qs_env(qs_env=qs_env, &
    1212              :                       qs_kind_set=qs_kind_set, &
    1213              :                       particle_set=particle_set, cell=cell, &
    1214          198 :                       sab_orb=sab_orb)
    1215              : 
    1216          198 :       IF (full_pairs) THEN
    1217           60 :          CALL get_qs_env(qs_env, sab_all=sab_orb)
    1218           60 :          IF (.NOT. ASSOCIATED(sab_orb)) CPABORT("Ordered Berry integrals require k-point neighbour lists.")
    1219           60 :          CPASSERT(PRESENT(ordered_kpoints))
    1220           60 :          CALL get_kpoint_info(ordered_kpoints, cell_to_index=cell_to_index)
    1221           60 :          nimg = SIZE(ordered_kpoints%index_to_cell, 2)
    1222           60 :          use_cell_mapping = .TRUE.
    1223              :       END IF
    1224              : 
    1225          198 :       nkind = SIZE(qs_kind_set)
    1226          198 :       natom = SIZE(particle_set)
    1227          800 :       ALLOCATE (basis_set_list(nkind))
    1228          404 :       DO ikind = 1, nkind
    1229          206 :          qs_kind => qs_kind_set(ikind)
    1230          412 :          CALL get_qs_kind(qs_kind=qs_kind, basis_set=basis_set, basis_type=basis_type)
    1231          404 :          IF (ASSOCIATED(basis_set)) THEN
    1232          206 :             basis_set_list(ikind)%gto_basis_set => basis_set
    1233              :          ELSE
    1234            0 :             NULLIFY (basis_set_list(ikind)%gto_basis_set)
    1235              :          END IF
    1236              :       END DO
    1237              : 
    1238          594 :       ALLOCATE (row_blk_sizes(natom))
    1239              :       CALL get_particle_set(particle_set, qs_kind_set, nsgf=row_blk_sizes, &
    1240          198 :                             basis=basis_set_list)
    1241          198 :       CALL get_ks_env(ks_env, dbcsr_dist=dbcsr_dist)
    1242              :       ! (re)allocate matrix sets
    1243          198 :       CALL dbcsr_allocate_matrix_set(sinmat, 1, nimg)
    1244          198 :       CALL dbcsr_allocate_matrix_set(cosmat, 1, nimg)
    1245        29474 :       DO i = 1, nimg
    1246              :          ! sin
    1247        29276 :          ALLOCATE (sinmat(1, i)%matrix)
    1248              :          CALL dbcsr_create(matrix=sinmat(1, i)%matrix, &
    1249              :                            name="SINMAT", &
    1250              :                            dist=dbcsr_dist, matrix_type=matrix_symmetry, &
    1251        29276 :                            row_blk_size=row_blk_sizes, col_blk_size=row_blk_sizes)
    1252        29276 :          CALL cp_dbcsr_alloc_block_from_nbl(sinmat(1, i)%matrix, sab_orb)
    1253        29276 :          CALL dbcsr_set(sinmat(1, i)%matrix, 0.0_dp)
    1254              :          ! cos
    1255        29276 :          ALLOCATE (cosmat(1, i)%matrix)
    1256              :          CALL dbcsr_create(matrix=cosmat(1, i)%matrix, &
    1257              :                            name="COSMAT", &
    1258              :                            dist=dbcsr_dist, matrix_type=matrix_symmetry, &
    1259        29276 :                            row_blk_size=row_blk_sizes, col_blk_size=row_blk_sizes)
    1260        29276 :          CALL cp_dbcsr_alloc_block_from_nbl(cosmat(1, i)%matrix, sab_orb)
    1261        29474 :          CALL dbcsr_set(cosmat(1, i)%matrix, 0.0_dp)
    1262              :       END DO
    1263              : 
    1264          198 :       CALL get_qs_kind_set(qs_kind_set=qs_kind_set, maxco=ldwork)
    1265          792 :       ALLOCATE (expab(ldwork, ldwork))
    1266          792 :       ALLOCATE (work(ldwork, ldwork))
    1267              : 
    1268          198 :       CALL neighbor_list_iterator_create(nl_iterator, sab_orb)
    1269       117619 :       DO WHILE (neighbor_list_iterate(nl_iterator) == 0)
    1270              :          CALL get_iterator_info(nl_iterator, ikind=ikind, jkind=jkind, inode=inode, &
    1271       117421 :                                 iatom=iatom, jatom=jatom, r=rab, cell=icell)
    1272       117421 :          basis_set_a => basis_set_list(ikind)%gto_basis_set
    1273       117421 :          IF (.NOT. ASSOCIATED(basis_set_a)) CYCLE
    1274       117421 :          basis_set_b => basis_set_list(jkind)%gto_basis_set
    1275       117421 :          IF (.NOT. ASSOCIATED(basis_set_b)) CYCLE
    1276              :          ASSOCIATE ( &
    1277              :             ! basis ikind
    1278              :             first_sgfa => basis_set_a%first_sgf, &
    1279              :             la_max => basis_set_a%lmax, &
    1280              :             la_min => basis_set_a%lmin, &
    1281              :             npgfa => basis_set_a%npgf, &
    1282              :             nsgfa => basis_set_a%nsgf_set, &
    1283              :             rpgfa => basis_set_a%pgf_radius, &
    1284              :             set_radius_a => basis_set_a%set_radius, &
    1285              :             sphi_a => basis_set_a%sphi, &
    1286              :             zeta => basis_set_a%zet, &
    1287              :             ! basis jkind, &
    1288              :             first_sgfb => basis_set_b%first_sgf, &
    1289              :             lb_max => basis_set_b%lmax, &
    1290              :             lb_min => basis_set_b%lmin, &
    1291              :             npgfb => basis_set_b%npgf, &
    1292              :             nsgfb => basis_set_b%nsgf_set, &
    1293              :             rpgfb => basis_set_b%pgf_radius, &
    1294              :             set_radius_b => basis_set_b%set_radius, &
    1295              :             sphi_b => basis_set_b%sphi, &
    1296       234842 :             zetb => basis_set_b%zet)
    1297              : 
    1298       117421 :             nseta = basis_set_a%nset
    1299       117421 :             nsetb = basis_set_b%nset
    1300              : 
    1301       117421 :             ldsa = SIZE(sphi_a, 1)
    1302       117421 :             ldsb = SIZE(sphi_b, 1)
    1303              : 
    1304        48618 :             IF (iatom <= jatom .OR. full_pairs) THEN
    1305        69469 :                irow = iatom
    1306        69469 :                icol = jatom
    1307              :             ELSE
    1308        47952 :                irow = jatom
    1309        47952 :                icol = iatom
    1310              :             END IF
    1311              : 
    1312       117421 :             IF (use_cell_mapping) THEN
    1313       117421 :                ic = cell_to_index(icell(1), icell(2), icell(3))
    1314       117421 :                CPASSERT(ic > 0)
    1315              :             ELSE
    1316              :                ic = 1
    1317              :             END IF
    1318              : 
    1319       117421 :             NULLIFY (sblock)
    1320              :             CALL dbcsr_get_block_p(matrix=sinmat(1, ic)%matrix, &
    1321       117421 :                                    row=irow, col=icol, BLOCK=sblock, found=found)
    1322       117421 :             CPASSERT(found)
    1323       117421 :             NULLIFY (cblock)
    1324              :             CALL dbcsr_get_block_p(matrix=cosmat(1, ic)%matrix, &
    1325       117421 :                                    row=irow, col=icol, BLOCK=cblock, found=found)
    1326       117421 :             CPASSERT(found)
    1327              : 
    1328              :             ! Absolute phases must use the same atom images as the orbital neighbour list.
    1329       117421 :             IF (stable_images) THEN
    1330        95871 :                ra(:) = pbc_stable(particle_set(iatom)%r(:), cell)
    1331              :             ELSE
    1332        21550 :                ra(:) = pbc(particle_set(iatom)%r(:), cell)
    1333              :             END IF
    1334       469684 :             rb(:) = ra + rab
    1335       117421 :             dab = SQRT(rab(1)*rab(1) + rab(2)*rab(2) + rab(3)*rab(3))
    1336              : 
    1337       359024 :             DO iset = 1, nseta
    1338              : 
    1339       124182 :                ncoa = npgfa(iset)*ncoset(la_max(iset))
    1340       124182 :                sgfa = first_sgfa(1, iset)
    1341              : 
    1342       379307 :                DO jset = 1, nsetb
    1343              : 
    1344       137704 :                   IF (set_radius_a(iset) + set_radius_b(jset) < dab) CYCLE
    1345              : 
    1346       132984 :                   ncob = npgfb(jset)*ncoset(lb_max(jset))
    1347       132984 :                   sgfb = first_sgfb(1, jset)
    1348              : 
    1349              :                   ! Calculate the primitive integrals
    1350              :                   CALL expikr(la_max(iset), npgfa(iset), zeta(:, iset), rpgfa(:, iset), la_min(iset), &
    1351              :                               lb_max(jset), npgfb(jset), zetb(:, jset), rpgfb(:, jset), lb_min(jset), &
    1352       132984 :                               ra, rb, kvec, expab)
    1353              :                   CALL contract_expikr(cblock, sblock, &
    1354              :                                        iatom, ncoa, nsgfa(iset), sgfa, sphi_a, ldsa, &
    1355              :                                        jatom, ncob, nsgfb(jset), sgfb, sphi_b, ldsb, &
    1356       261886 :                                        expab, work, ldwork, ordered=full_pairs)
    1357              : 
    1358              :                END DO
    1359              :             END DO
    1360              :          END ASSOCIATE
    1361              :       END DO
    1362          198 :       CALL neighbor_list_iterator_release(nl_iterator)
    1363              : 
    1364          198 :       DEALLOCATE (expab)
    1365          198 :       DEALLOCATE (work)
    1366          198 :       DEALLOCATE (basis_set_list)
    1367          198 :       DEALLOCATE (row_blk_sizes)
    1368              : 
    1369          198 :       CALL timestop(handle)
    1370              : 
    1371          396 :    END SUBROUTINE build_berry_kpoint_matrix
    1372              : 
    1373              : ! **************************************************************************************************
    1374              : !> \brief ...
    1375              : !> \param qs_env ...
    1376              : !> \param magnetic ...
    1377              : !> \param nmoments ...
    1378              : !> \param reference ...
    1379              : !> \param ref_point ...
    1380              : !> \param unit_number ...
    1381              : !> \param unit_str unit of the printed moments (dipole unit of cp_units), default debye
    1382              : ! **************************************************************************************************
    1383          436 :    SUBROUTINE qs_moment_berry_phase(qs_env, magnetic, nmoments, reference, ref_point, unit_number, unit_str)
    1384              : 
    1385              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    1386              :       LOGICAL, INTENT(IN)                                :: magnetic
    1387              :       INTEGER, INTENT(IN)                                :: nmoments, reference
    1388              :       REAL(dp), DIMENSION(:), POINTER                    :: ref_point
    1389              :       INTEGER, INTENT(IN)                                :: unit_number
    1390              :       CHARACTER(LEN=*), INTENT(IN), OPTIONAL             :: unit_str
    1391              : 
    1392              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'qs_moment_berry_phase'
    1393              :       REAL(dp), PARAMETER                                :: eps_occ = 1.0E-6_dp
    1394              : 
    1395          436 :       CHARACTER(LEN=8), ALLOCATABLE, DIMENSION(:)        :: rlab
    1396              :       CHARACTER(LEN=default_string_length)               :: description
    1397              :       COMPLEX(dp)                                        :: xphase(3), zdet, zdeta, zi(3), &
    1398              :                                                             zij(3, 3), zijk(3, 3, 3), &
    1399              :                                                             zijkl(3, 3, 3, 3), zphase(3), zz
    1400              :       INTEGER                                            :: handle, i, ia, idim, ikind, ispin, ix, &
    1401              :                                                             iy, iz, j, k, l, nao, nm, nmo, nmo_max, &
    1402              :                                                             nmom, tmp_dim
    1403              :       LOGICAL                                            :: floating, fractional, ghost
    1404          436 :       LOGICAL, ALLOCATABLE, DIMENSION(:)                 :: all_occupied
    1405          436 :       LOGICAL, ALLOCATABLE, DIMENSION(:, :)              :: mo_occupied
    1406              :       REAL(dp)                                           :: charge, ci(3), cij(3, 3), dd, nel_det, &
    1407              :                                                             occ, trace
    1408          436 :       REAL(dp), ALLOCATABLE, DIMENSION(:)                :: mmom
    1409          436 :       REAL(dp), ALLOCATABLE, DIMENSION(:, :)             :: rmom
    1410              :       REAL(dp), DIMENSION(3)                             :: kvec, qq, rcc, ria
    1411          436 :       REAL(dp), DIMENSION(:), POINTER                    :: occupation_numbers
    1412              :       TYPE(atomic_kind_type), POINTER                    :: atomic_kind
    1413              :       TYPE(cell_type), POINTER                           :: cell
    1414          436 :       TYPE(cp_cfm_type), ALLOCATABLE, DIMENSION(:)       :: eigrmat
    1415              :       TYPE(cp_fm_struct_type), POINTER                   :: tmp_fm_struct
    1416          436 :       TYPE(cp_fm_type), ALLOCATABLE, DIMENSION(:)        :: opvec
    1417          436 :       TYPE(cp_fm_type), ALLOCATABLE, DIMENSION(:, :)     :: op_fm_set
    1418          436 :       TYPE(cp_fm_type), DIMENSION(:), POINTER            :: mos_new
    1419              :       TYPE(cp_fm_type), POINTER                          :: mo_coeff
    1420              :       TYPE(cp_result_type), POINTER                      :: results
    1421          436 :       TYPE(dbcsr_p_type), DIMENSION(:), POINTER          :: matrix_s, rho_ao
    1422              :       TYPE(dbcsr_type), POINTER                          :: cosmat, sinmat
    1423              :       TYPE(dft_control_type), POINTER                    :: dft_control
    1424              :       TYPE(distribution_1d_type), POINTER                :: local_particles
    1425          436 :       TYPE(mo_set_type), DIMENSION(:), POINTER           :: mos
    1426              :       TYPE(mp_para_env_type), POINTER                    :: para_env
    1427          436 :       TYPE(particle_type), DIMENSION(:), POINTER         :: particle_set
    1428          436 :       TYPE(qs_kind_type), DIMENSION(:), POINTER          :: qs_kind_set
    1429              :       TYPE(qs_rho_type), POINTER                         :: rho
    1430              :       TYPE(rt_prop_type), POINTER                        :: rtp
    1431              : 
    1432            0 :       CPASSERT(ASSOCIATED(qs_env))
    1433              : 
    1434          436 :       IF (ASSOCIATED(qs_env%ls_scf_env)) THEN
    1435            0 :          IF (unit_number > 0) WRITE (unit_number, *) "Periodic moment calculation not implemented in linear scaling code"
    1436            0 :          RETURN
    1437              :       END IF
    1438              : 
    1439          436 :       CALL timeset(routineN, handle)
    1440              : 
    1441              :       ! restrict maximum moment available
    1442          436 :       nmom = MIN(nmoments, 2)
    1443              : 
    1444          436 :       nm = (6 + 11*nmom + 6*nmom**2 + nmom**3)/6 - 1
    1445              :       ! rmom(:,1)=electronic
    1446              :       ! rmom(:,2)=nuclear
    1447              :       ! rmom(:,1)=total
    1448         2180 :       ALLOCATE (rmom(nm + 1, 3))
    1449         1308 :       ALLOCATE (rlab(nm + 1))
    1450          436 :       rmom = 0.0_dp
    1451         2180 :       rlab = ""
    1452          436 :       IF (magnetic) THEN
    1453            0 :          nm = 3
    1454            0 :          ALLOCATE (mmom(nm))
    1455            0 :          mmom = 0._dp
    1456              :       END IF
    1457              : 
    1458          436 :       NULLIFY (dft_control, rho, cell, particle_set, results, para_env, &
    1459          436 :                local_particles, matrix_s, mos, rho_ao)
    1460              : 
    1461              :       CALL get_qs_env(qs_env, &
    1462              :                       dft_control=dft_control, &
    1463              :                       rho=rho, &
    1464              :                       cell=cell, &
    1465              :                       results=results, &
    1466              :                       particle_set=particle_set, &
    1467              :                       qs_kind_set=qs_kind_set, &
    1468              :                       para_env=para_env, &
    1469              :                       local_particles=local_particles, &
    1470              :                       matrix_s=matrix_s, &
    1471          436 :                       mos=mos)
    1472              : 
    1473          436 :       CALL qs_rho_get(rho, rho_ao=rho_ao)
    1474              : 
    1475          436 :       NULLIFY (cosmat, sinmat)
    1476          436 :       ALLOCATE (cosmat, sinmat)
    1477          436 :       CALL dbcsr_copy(cosmat, matrix_s(1)%matrix, 'COS MOM')
    1478          436 :       CALL dbcsr_copy(sinmat, matrix_s(1)%matrix, 'SIN MOM')
    1479              : 
    1480         2700 :       ALLOCATE (op_fm_set(2, dft_control%nspins))
    1481         1772 :       ALLOCATE (opvec(dft_control%nspins))
    1482         1772 :       ALLOCATE (eigrmat(dft_control%nspins))
    1483          436 :       nmo_max = 0
    1484          900 :       DO ispin = 1, dft_control%nspins
    1485          464 :          NULLIFY (tmp_fm_struct, mo_coeff)
    1486          464 :          CALL get_mo_set(mo_set=mos(ispin), mo_coeff=mo_coeff, nao=nao, nmo=nmo)
    1487          464 :          nmo_max = MAX(nmo_max, nmo)
    1488          464 :          CALL cp_fm_create(opvec(ispin), mo_coeff%matrix_struct)
    1489              :          CALL cp_fm_struct_create(tmp_fm_struct, nrow_global=nmo, &
    1490          464 :                                   ncol_global=nmo, para_env=para_env, context=mo_coeff%matrix_struct%context)
    1491         1392 :          DO i = 1, SIZE(op_fm_set, 1)
    1492         1392 :             CALL cp_fm_create(op_fm_set(i, ispin), tmp_fm_struct)
    1493              :          END DO
    1494          464 :          CALL cp_cfm_create(eigrmat(ispin), op_fm_set(1, ispin)%matrix_struct)
    1495         1364 :          CALL cp_fm_struct_release(tmp_fm_struct)
    1496              :       END DO
    1497              : 
    1498              :       ! occupation
    1499         2616 :       ALLOCATE (mo_occupied(nmo_max, dft_control%nspins), all_occupied(dft_control%nspins))
    1500          436 :       mo_occupied = .FALSE.
    1501          436 :       fractional = .FALSE.
    1502          436 :       nel_det = 0.0_dp
    1503          900 :       DO ispin = 1, dft_control%nspins
    1504          464 :          NULLIFY (occupation_numbers)
    1505          464 :          CALL get_mo_set(mo_set=mos(ispin), maxocc=occ, nmo=nmo, occupation_numbers=occupation_numbers)
    1506         2634 :          DO i = 1, nmo
    1507         2634 :             IF (occupation_numbers(i) > eps_occ) THEN
    1508         2130 :                mo_occupied(i, ispin) = .TRUE.
    1509         2130 :                nel_det = nel_det + occ
    1510         2130 :                IF (ABS(occupation_numbers(i) - occ) > eps_occ) fractional = .TRUE.
    1511              :             END IF
    1512              :          END DO
    1513         3492 :          all_occupied(ispin) = ALL(mo_occupied(1:nmo, ispin))
    1514              :       END DO
    1515          436 :       IF (fractional) THEN
    1516            0 :          CPWARN("Berry phase moments for fractional MOs' occupation numbers not implemented")
    1517              :       END IF
    1518              : 
    1519              :       ! reference point
    1520          436 :       CALL get_reference_point(rcc, qs_env=qs_env, reference=reference, ref_point=ref_point)
    1521         1744 :       rcc = pbc(rcc, cell)
    1522              : 
    1523              :       ! label
    1524         1744 :       DO l = 1, nm
    1525         1308 :          ix = indco(1, l + 1)
    1526         1308 :          iy = indco(2, l + 1)
    1527         1308 :          iz = indco(3, l + 1)
    1528         1744 :          CALL set_label(rlab(l + 1), ix, iy, iz)
    1529              :       END DO
    1530              : 
    1531              :       ! nuclear contribution
    1532         1764 :       DO ia = 1, SIZE(particle_set)
    1533         1328 :          atomic_kind => particle_set(ia)%atomic_kind
    1534         1328 :          CALL get_atomic_kind(atomic_kind, kind_number=ikind)
    1535         1328 :          CALL get_qs_kind(qs_kind_set(ikind), core_charge=charge, ghost=ghost, floating=floating)
    1536         1764 :          IF (.NOT. ghost .AND. .NOT. floating) THEN
    1537         1328 :             rmom(1, 2) = rmom(1, 2) - charge
    1538              :          END IF
    1539              :       END DO
    1540         6976 :       ria = twopi*MATMUL(cell%h_inv, rcc)
    1541         1744 :       zphase = CMPLX(COS(ria), SIN(ria), dp)**rmom(1, 2)
    1542              : 
    1543          436 :       zi = 0._dp
    1544          436 :       zij = 0._dp
    1545              :       zijk = 0._dp
    1546              :       zijkl = 0._dp
    1547              : 
    1548          872 :       DO l = 1, nmom
    1549          436 :          SELECT CASE (l)
    1550              :          CASE (1)
    1551              :             ! Dipole
    1552         1744 :             zi(:) = CMPLX(1._dp, 0._dp, dp)
    1553         1764 :             DO ia = 1, SIZE(particle_set)
    1554         1328 :                atomic_kind => particle_set(ia)%atomic_kind
    1555         1328 :                CALL get_atomic_kind(atomic_kind, kind_number=ikind)
    1556         1328 :                CALL get_qs_kind(qs_kind_set(ikind), core_charge=charge, ghost=ghost, floating=floating)
    1557         1764 :                IF (.NOT. ghost .AND. .NOT. floating) THEN
    1558         5312 :                   ria = particle_set(ia)%r
    1559         5312 :                   ria = pbc(ria, cell)
    1560         5312 :                   DO i = 1, 3
    1561        15936 :                      kvec(:) = twopi*cell%h_inv(i, :)
    1562        15936 :                      dd = SUM(kvec(:)*ria(:))
    1563         3984 :                      zdeta = CMPLX(COS(dd), SIN(dd), KIND=dp)**charge
    1564         5312 :                      zi(i) = zi(i)*zdeta
    1565              :                   END DO
    1566              :                END IF
    1567              :             END DO
    1568         1744 :             zi = zi*zphase
    1569         1744 :             ci = AIMAG(LOG(zi))/twopi
    1570         1744 :             qq = AIMAG(LOG(zi))
    1571         6976 :             rmom(2:4, 2) = MATMUL(cell%hmat, ci)
    1572              :          CASE (2)
    1573              :             ! Quadrupole
    1574            0 :             CPABORT("Berry phase moments bigger than 1 not implemented")
    1575            0 :             zij(:, :) = CMPLX(1._dp, 0._dp, dp)
    1576            0 :             DO ia = 1, SIZE(particle_set)
    1577            0 :                atomic_kind => particle_set(ia)%atomic_kind
    1578            0 :                CALL get_atomic_kind(atomic_kind, kind_number=ikind)
    1579            0 :                CALL get_qs_kind(qs_kind_set(ikind), core_charge=charge)
    1580            0 :                ria = particle_set(ia)%r
    1581            0 :                ria = pbc(ria, cell)
    1582            0 :                DO i = 1, 3
    1583            0 :                   DO j = i, 3
    1584            0 :                      kvec(:) = twopi*(cell%h_inv(i, :) + cell%h_inv(j, :))
    1585            0 :                      dd = SUM(kvec(:)*ria(:))
    1586            0 :                      zdeta = CMPLX(COS(dd), SIN(dd), KIND=dp)**charge
    1587            0 :                      zij(i, j) = zij(i, j)*zdeta
    1588            0 :                      zij(j, i) = zij(i, j)
    1589              :                   END DO
    1590              :                END DO
    1591              :             END DO
    1592            0 :             DO i = 1, 3
    1593            0 :                DO j = 1, 3
    1594            0 :                   zij(i, j) = zij(i, j)*zphase(i)*zphase(j)
    1595            0 :                   zz = zij(i, j)/zi(i)/zi(j)
    1596            0 :                   cij(i, j) = AIMAG(LOG(zz))/twopi
    1597              :                END DO
    1598              :             END DO
    1599            0 :             cij = 0.5_dp*cij/twopi/twopi
    1600            0 :             cij = MATMUL(MATMUL(cell%hmat, cij), TRANSPOSE(cell%hmat))
    1601            0 :             DO k = 4, 9
    1602            0 :                ix = indco(1, k + 1)
    1603            0 :                iy = indco(2, k + 1)
    1604            0 :                iz = indco(3, k + 1)
    1605            0 :                IF (ix == 0) THEN
    1606            0 :                   rmom(k + 1, 2) = cij(iy, iz)
    1607            0 :                ELSE IF (iy == 0) THEN
    1608            0 :                   rmom(k + 1, 2) = cij(ix, iz)
    1609            0 :                ELSE IF (iz == 0) THEN
    1610            0 :                   rmom(k + 1, 2) = cij(ix, iy)
    1611              :                END IF
    1612              :             END DO
    1613              :          CASE (3)
    1614              :             ! Octapole
    1615            0 :             CPABORT("Berry phase moments bigger than 2 not implemented")
    1616              :          CASE (4)
    1617              :             ! Hexadecapole
    1618            0 :             CPABORT("Berry phase moments bigger than 3 not implemented")
    1619              :          CASE DEFAULT
    1620          436 :             CPABORT("Berry phase moments bigger than 4 not implemented")
    1621              :          END SELECT
    1622              :       END DO
    1623              : 
    1624              :       ! electronic contribution
    1625              : 
    1626         6976 :       ria = twopi*nel_det*MATMUL(cell%h_inv, rcc)
    1627         1744 :       xphase = CMPLX(COS(ria), SIN(ria), dp)
    1628              : 
    1629              :       ! charge
    1630          436 :       trace = 0.0_dp
    1631          900 :       DO ispin = 1, dft_control%nspins
    1632          464 :          CALL dbcsr_dot(rho_ao(ispin)%matrix, matrix_s(1)%matrix, trace)
    1633          900 :          rmom(1, 1) = rmom(1, 1) + trace
    1634              :       END DO
    1635              : 
    1636          436 :       zi = 0._dp
    1637          436 :       zij = 0._dp
    1638              :       zijk = 0._dp
    1639              :       zijkl = 0._dp
    1640              : 
    1641          872 :       DO l = 1, nmom
    1642          436 :          SELECT CASE (l)
    1643              :          CASE (1)
    1644              :             ! Dipole
    1645         1744 :             DO i = 1, 3
    1646         5232 :                kvec(:) = twopi*cell%h_inv(i, :)
    1647         1308 :                CALL build_berry_moment_matrix(qs_env, cosmat, sinmat, kvec)
    1648         1308 :                IF (qs_env%run_rtp) THEN
    1649           48 :                   CALL get_qs_env(qs_env, rtp=rtp)
    1650           48 :                   CALL get_rtp(rtp, mos_new=mos_new)
    1651           48 :                   CALL op_orbbas_rtp(cosmat, sinmat, mos, op_fm_set, mos_new)
    1652              :                ELSE
    1653         1260 :                   CALL op_orbbas(cosmat, sinmat, mos, op_fm_set, opvec)
    1654              :                END IF
    1655         1308 :                zdet = CMPLX(1._dp, 0._dp, dp)
    1656         2700 :                DO ispin = 1, dft_control%nspins
    1657         1392 :                   CALL cp_cfm_get_info(eigrmat(ispin), ncol_local=tmp_dim)
    1658         7902 :                   DO idim = 1, tmp_dim
    1659              :                      eigrmat(ispin)%local_data(:, idim) = &
    1660              :                         CMPLX(op_fm_set(1, ispin)%local_data(:, idim), &
    1661        43464 :                               -op_fm_set(2, ispin)%local_data(:, idim), dp)
    1662              :                   END DO
    1663         1392 :                   IF (.NOT. all_occupied(ispin)) THEN
    1664           24 :                      CALL berry_phase_remove_unocc(eigrmat(ispin), mo_occupied(:, ispin))
    1665              :                   END IF
    1666              :                   ! CALL cp_cfm_lu_decompose(eigrmat(ispin), zdeta)
    1667         1392 :                   CALL cp_cfm_det(eigrmat(ispin), zdeta)
    1668         1392 :                   zdet = zdet*zdeta
    1669         4092 :                   IF (dft_control%nspins == 1) THEN
    1670         1224 :                      zdet = zdet*zdeta
    1671              :                   END IF
    1672              :                END DO
    1673         1744 :                zi(i) = zdet
    1674              :             END DO
    1675         1744 :             zi = zi*xphase
    1676              :          CASE (2)
    1677              :             ! Quadrupole
    1678            0 :             CPABORT("Berry phase moments bigger than 1 not implemented")
    1679            0 :             DO i = 1, 3
    1680            0 :                DO j = i, 3
    1681            0 :                   kvec(:) = twopi*(cell%h_inv(i, :) + cell%h_inv(j, :))
    1682            0 :                   CALL build_berry_moment_matrix(qs_env, cosmat, sinmat, kvec)
    1683            0 :                   IF (qs_env%run_rtp) THEN
    1684            0 :                      CALL get_qs_env(qs_env, rtp=rtp)
    1685            0 :                      CALL get_rtp(rtp, mos_new=mos_new)
    1686            0 :                      CALL op_orbbas_rtp(cosmat, sinmat, mos, op_fm_set, mos_new)
    1687              :                   ELSE
    1688            0 :                      CALL op_orbbas(cosmat, sinmat, mos, op_fm_set, opvec)
    1689              :                   END IF
    1690            0 :                   zdet = CMPLX(1._dp, 0._dp, dp)
    1691            0 :                   DO ispin = 1, dft_control%nspins
    1692            0 :                      CALL cp_cfm_get_info(eigrmat(ispin), ncol_local=tmp_dim)
    1693            0 :                      DO idim = 1, tmp_dim
    1694              :                         eigrmat(ispin)%local_data(:, idim) = &
    1695              :                            CMPLX(op_fm_set(1, ispin)%local_data(:, idim), &
    1696            0 :                                  -op_fm_set(2, ispin)%local_data(:, idim), dp)
    1697              :                      END DO
    1698            0 :                      IF (.NOT. all_occupied(ispin)) THEN
    1699            0 :                         CALL berry_phase_remove_unocc(eigrmat(ispin), mo_occupied(:, ispin))
    1700              :                      END IF
    1701              :                      ! CALL cp_cfm_lu_decompose(eigrmat(ispin), zdeta)
    1702            0 :                      CALL cp_cfm_det(eigrmat(ispin), zdeta)
    1703            0 :                      zdet = zdet*zdeta
    1704            0 :                      IF (dft_control%nspins == 1) THEN
    1705            0 :                         zdet = zdet*zdeta
    1706              :                      END IF
    1707              :                   END DO
    1708            0 :                   zij(i, j) = zdet*xphase(i)*xphase(j)
    1709            0 :                   zij(j, i) = zdet*xphase(i)*xphase(j)
    1710              :                END DO
    1711              :             END DO
    1712              :          CASE (3)
    1713              :             ! Octapole
    1714            0 :             CPABORT("Berry phase moments bigger than 2 not implemented")
    1715              :          CASE (4)
    1716              :             ! Hexadecapole
    1717            0 :             CPABORT("Berry phase moments bigger than 3 not implemented")
    1718              :          CASE DEFAULT
    1719          436 :             CPABORT("Berry phase moments bigger than 4 not implemented")
    1720              :          END SELECT
    1721              :       END DO
    1722          872 :       DO l = 1, nmom
    1723          436 :          SELECT CASE (l)
    1724              :          CASE (1)
    1725              :             ! Dipole (apply periodic (2 Pi) boundary conditions)
    1726         1744 :             ci = AIMAG(LOG(zi))
    1727         1744 :             DO i = 1, 3
    1728         1308 :                IF (qq(i) + ci(i) > pi) ci(i) = ci(i) - twopi
    1729         1744 :                IF (qq(i) + ci(i) < -pi) ci(i) = ci(i) + twopi
    1730              :             END DO
    1731         8284 :             rmom(2:4, 1) = MATMUL(cell%hmat, ci)/twopi
    1732              :          CASE (2)
    1733              :             ! Quadrupole
    1734            0 :             CPABORT("Berry phase moments bigger than 1 not implemented")
    1735            0 :             DO i = 1, 3
    1736            0 :                DO j = 1, 3
    1737            0 :                   zz = zij(i, j)/zi(i)/zi(j)
    1738            0 :                   cij(i, j) = AIMAG(LOG(zz))/twopi
    1739              :                END DO
    1740              :             END DO
    1741            0 :             cij = 0.5_dp*cij/twopi/twopi
    1742            0 :             cij = MATMUL(MATMUL(cell%hmat, cij), TRANSPOSE(cell%hmat))
    1743            0 :             DO k = 4, 9
    1744            0 :                ix = indco(1, k + 1)
    1745            0 :                iy = indco(2, k + 1)
    1746            0 :                iz = indco(3, k + 1)
    1747            0 :                IF (ix == 0) THEN
    1748            0 :                   rmom(k + 1, 1) = cij(iy, iz)
    1749            0 :                ELSE IF (iy == 0) THEN
    1750            0 :                   rmom(k + 1, 1) = cij(ix, iz)
    1751            0 :                ELSE IF (iz == 0) THEN
    1752            0 :                   rmom(k + 1, 1) = cij(ix, iy)
    1753              :                END IF
    1754              :             END DO
    1755              :          CASE (3)
    1756              :             ! Octapole
    1757            0 :             CPABORT("Berry phase moments bigger than 2 not implemented")
    1758              :          CASE (4)
    1759              :             ! Hexadecapole
    1760            0 :             CPABORT("Berry phase moments bigger than 3 not implemented")
    1761              :          CASE DEFAULT
    1762          436 :             CPABORT("Berry phase moments bigger than 4 not implemented")
    1763              :          END SELECT
    1764              :       END DO
    1765              : 
    1766         2180 :       rmom(:, 3) = rmom(:, 1) + rmom(:, 2)
    1767          436 :       description = "[DIPOLE]"
    1768          436 :       CALL cp_results_erase(results=results, description=description)
    1769              :       CALL put_results(results=results, description=description, &
    1770          436 :                        values=rmom(2:4, 3))
    1771          436 :       IF (magnetic) THEN
    1772              :          CALL print_moments(unit_number, nmom, rmom, rlab, rcc, cell, periodic=.TRUE., mmom=mmom, &
    1773            0 :                             unit_str=unit_str)
    1774              :       ELSE
    1775          436 :          CALL print_moments(unit_number, nmom, rmom, rlab, rcc, cell, periodic=.TRUE., unit_str=unit_str)
    1776              :       END IF
    1777              : 
    1778          436 :       DEALLOCATE (rmom)
    1779          436 :       DEALLOCATE (rlab)
    1780          436 :       IF (magnetic) THEN
    1781            0 :          DEALLOCATE (mmom)
    1782              :       END IF
    1783              : 
    1784          436 :       CALL dbcsr_deallocate_matrix(cosmat)
    1785          436 :       CALL dbcsr_deallocate_matrix(sinmat)
    1786              : 
    1787          436 :       CALL cp_fm_release(opvec)
    1788          436 :       CALL cp_fm_release(op_fm_set)
    1789          900 :       DO ispin = 1, dft_control%nspins
    1790          900 :          CALL cp_cfm_release(eigrmat(ispin))
    1791              :       END DO
    1792          436 :       DEALLOCATE (eigrmat)
    1793          436 :       DEALLOCATE (mo_occupied, all_occupied)
    1794              : 
    1795          436 :       CALL timestop(handle)
    1796              : 
    1797         1308 :    END SUBROUTINE qs_moment_berry_phase
    1798              : 
    1799              : ! **************************************************************************************************
    1800              : !> \brief Removes unoccupied MOs from the Berry phase matrix Z_ij = <psi_i|exp(i k.r)|psi_j> by
    1801              : !>        replacing their rows and columns with those of the unit matrix. The determinant of the
    1802              : !>        result equals the determinant of Z.
    1803              : !> \param zmat        nmo x nmo Berry phase matrix of one spin channel, modified on output
    1804              : !> \param mo_occupied .TRUE. for the MOs that are part of the Slater determinant
    1805              : ! **************************************************************************************************
    1806           24 :    SUBROUTINE berry_phase_remove_unocc(zmat, mo_occupied)
    1807              : 
    1808              :       TYPE(cp_cfm_type), INTENT(IN)                      :: zmat
    1809              :       LOGICAL, DIMENSION(:), INTENT(IN)                  :: mo_occupied
    1810              : 
    1811              :       INTEGER                                            :: icol, irow, ncol_local, nrow_local
    1812           24 :       INTEGER, DIMENSION(:), POINTER                     :: col_indices, row_indices
    1813              : 
    1814           24 :       NULLIFY (col_indices, row_indices)
    1815              :       CALL cp_cfm_get_info(zmat, nrow_local=nrow_local, ncol_local=ncol_local, &
    1816           24 :                            row_indices=row_indices, col_indices=col_indices)
    1817          240 :       DO icol = 1, ncol_local
    1818         1212 :          DO irow = 1, nrow_local
    1819          972 :             IF (mo_occupied(row_indices(irow)) .AND. mo_occupied(col_indices(icol))) CYCLE
    1820          996 :             IF (row_indices(irow) == col_indices(icol)) THEN
    1821           60 :                zmat%local_data(irow, icol) = z_one
    1822              :             ELSE
    1823          720 :                zmat%local_data(irow, icol) = z_zero
    1824              :             END IF
    1825              :          END DO
    1826              :       END DO
    1827              : 
    1828           24 :    END SUBROUTINE berry_phase_remove_unocc
    1829              : 
    1830              : ! **************************************************************************************************
    1831              : !> \brief ...
    1832              : !> \param cosmat ...
    1833              : !> \param sinmat ...
    1834              : !> \param mos ...
    1835              : !> \param op_fm_set ...
    1836              : !> \param opvec ...
    1837              : ! **************************************************************************************************
    1838         1260 :    SUBROUTINE op_orbbas(cosmat, sinmat, mos, op_fm_set, opvec)
    1839              : 
    1840              :       TYPE(dbcsr_type), POINTER                          :: cosmat, sinmat
    1841              :       TYPE(mo_set_type), DIMENSION(:), INTENT(IN)        :: mos
    1842              :       TYPE(cp_fm_type), DIMENSION(:, :), INTENT(IN)      :: op_fm_set
    1843              :       TYPE(cp_fm_type), DIMENSION(:), INTENT(INOUT)      :: opvec
    1844              : 
    1845              :       INTEGER                                            :: i, nao, nmo
    1846              :       TYPE(cp_fm_type), POINTER                          :: mo_coeff
    1847              : 
    1848         2580 :       DO i = 1, SIZE(op_fm_set, 2) ! spin
    1849         1320 :          CALL get_mo_set(mo_set=mos(i), nao=nao, mo_coeff=mo_coeff, nmo=nmo)
    1850         1320 :          CALL cp_dbcsr_sm_fm_multiply(cosmat, mo_coeff, opvec(i), ncol=nmo)
    1851              :          CALL parallel_gemm("T", "N", nmo, nmo, nao, 1.0_dp, mo_coeff, opvec(i), 0.0_dp, &
    1852         1320 :                             op_fm_set(1, i))
    1853         1320 :          CALL cp_dbcsr_sm_fm_multiply(sinmat, mo_coeff, opvec(i), ncol=nmo)
    1854              :          CALL parallel_gemm("T", "N", nmo, nmo, nao, 1.0_dp, mo_coeff, opvec(i), 0.0_dp, &
    1855         3900 :                             op_fm_set(2, i))
    1856              :       END DO
    1857              : 
    1858         1260 :    END SUBROUTINE op_orbbas
    1859              : 
    1860              : ! **************************************************************************************************
    1861              : !> \brief ...
    1862              : !> \param cosmat ...
    1863              : !> \param sinmat ...
    1864              : !> \param mos ...
    1865              : !> \param op_fm_set ...
    1866              : !> \param mos_new ...
    1867              : ! **************************************************************************************************
    1868           48 :    SUBROUTINE op_orbbas_rtp(cosmat, sinmat, mos, op_fm_set, mos_new)
    1869              : 
    1870              :       TYPE(dbcsr_type), POINTER                          :: cosmat, sinmat
    1871              :       TYPE(mo_set_type), DIMENSION(:), INTENT(IN)        :: mos
    1872              :       TYPE(cp_fm_type), DIMENSION(:, :), INTENT(IN)      :: op_fm_set
    1873              :       TYPE(cp_fm_type), DIMENSION(:), POINTER            :: mos_new
    1874              : 
    1875              :       INTEGER                                            :: i, icol, lcol, nao, newdim, nmo
    1876              :       LOGICAL                                            :: double_col, double_row
    1877              :       TYPE(cp_fm_struct_type), POINTER                   :: newstruct, newstruct1
    1878              :       TYPE(cp_fm_type)                                   :: work, work1, work2
    1879              :       TYPE(cp_fm_type), POINTER                          :: mo_coeff
    1880              : 
    1881          120 :       DO i = 1, SIZE(op_fm_set, 2) ! spin
    1882           72 :          CALL get_mo_set(mo_set=mos(i), nao=nao, mo_coeff=mo_coeff, nmo=nmo)
    1883           72 :          CALL cp_fm_get_info(mos_new(2*i), ncol_local=lcol, ncol_global=nmo)
    1884           72 :          double_col = .TRUE.
    1885           72 :          double_row = .FALSE.
    1886              :          CALL cp_fm_struct_double(newstruct, &
    1887              :                                   mos_new(2*i)%matrix_struct, &
    1888              :                                   mos_new(2*i)%matrix_struct%context, &
    1889              :                                   double_col, &
    1890           72 :                                   double_row)
    1891              : 
    1892           72 :          CALL cp_fm_create(work, matrix_struct=newstruct)
    1893           72 :          CALL cp_fm_create(work1, matrix_struct=newstruct)
    1894           72 :          CALL cp_fm_create(work2, matrix_struct=newstruct)
    1895           72 :          CALL cp_fm_get_info(work, ncol_global=newdim)
    1896              : 
    1897           72 :          CALL cp_fm_set_all(work, 0.0_dp, 0.0_dp)
    1898          336 :          DO icol = 1, lcol
    1899         3300 :             work%local_data(:, icol) = mos_new(2*i - 1)%local_data(:, icol)
    1900         3372 :             work%local_data(:, icol + lcol) = mos_new(2*i)%local_data(:, icol)
    1901              :          END DO
    1902              : 
    1903           72 :          CALL cp_dbcsr_sm_fm_multiply(cosmat, work, work1, ncol=newdim)
    1904           72 :          CALL cp_dbcsr_sm_fm_multiply(sinmat, work, work2, ncol=newdim)
    1905              : 
    1906          336 :          DO icol = 1, lcol
    1907         3300 :             work%local_data(:, icol) = work1%local_data(:, icol) - work2%local_data(:, icol + lcol)
    1908         3372 :             work%local_data(:, icol + lcol) = work1%local_data(:, icol + lcol) + work2%local_data(:, icol)
    1909              :          END DO
    1910              : 
    1911           72 :          CALL cp_fm_release(work1)
    1912           72 :          CALL cp_fm_release(work2)
    1913              : 
    1914              :          CALL cp_fm_struct_double(newstruct1, &
    1915              :                                   op_fm_set(1, i)%matrix_struct, &
    1916              :                                   op_fm_set(1, i)%matrix_struct%context, &
    1917              :                                   double_col, &
    1918           72 :                                   double_row)
    1919              : 
    1920           72 :          CALL cp_fm_create(work1, matrix_struct=newstruct1)
    1921              : 
    1922              :          CALL parallel_gemm("T", "N", nmo, newdim, nao, 1.0_dp, mos_new(2*i - 1), &
    1923           72 :                             work, 0.0_dp, work1)
    1924              : 
    1925          336 :          DO icol = 1, lcol
    1926          756 :             op_fm_set(1, i)%local_data(:, icol) = work1%local_data(:, icol)
    1927          828 :             op_fm_set(2, i)%local_data(:, icol) = work1%local_data(:, icol + lcol)
    1928              :          END DO
    1929              : 
    1930              :          CALL parallel_gemm("T", "N", nmo, newdim, nao, 1.0_dp, mos_new(2*i), &
    1931           72 :                             work, 0.0_dp, work1)
    1932              : 
    1933          336 :          DO icol = 1, lcol
    1934              :             op_fm_set(1, i)%local_data(:, icol) = &
    1935          756 :                op_fm_set(1, i)%local_data(:, icol) + work1%local_data(:, icol + lcol)
    1936              :             op_fm_set(2, i)%local_data(:, icol) = &
    1937          828 :                op_fm_set(2, i)%local_data(:, icol) - work1%local_data(:, icol)
    1938              :          END DO
    1939              : 
    1940           72 :          CALL cp_fm_release(work)
    1941           72 :          CALL cp_fm_release(work1)
    1942           72 :          CALL cp_fm_struct_release(newstruct)
    1943          336 :          CALL cp_fm_struct_release(newstruct1)
    1944              : 
    1945              :       END DO
    1946              : 
    1947           48 :    END SUBROUTINE op_orbbas_rtp
    1948              : 
    1949              : ! **************************************************************************************************
    1950              : !> \brief ...
    1951              : !> \param qs_env ...
    1952              : !> \param magnetic ...
    1953              : !> \param nmoments ...
    1954              : !> \param reference ...
    1955              : !> \param ref_point ...
    1956              : !> \param unit_number ...
    1957              : !> \param vel_reprs ...
    1958              : !> \param com_nl ...
    1959              : !> \param unit_str unit of the printed moments (dipole unit of cp_units), default debye
    1960              : ! **************************************************************************************************
    1961         1122 :    SUBROUTINE qs_moment_locop(qs_env, magnetic, nmoments, reference, ref_point, unit_number, vel_reprs, com_nl, &
    1962              :                               unit_str)
    1963              : 
    1964              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    1965              :       LOGICAL, INTENT(IN)                                :: magnetic
    1966              :       INTEGER, INTENT(IN)                                :: nmoments, reference
    1967              :       REAL(dp), DIMENSION(:), INTENT(IN), POINTER        :: ref_point
    1968              :       INTEGER, INTENT(IN)                                :: unit_number
    1969              :       LOGICAL, INTENT(IN), OPTIONAL                      :: vel_reprs, com_nl
    1970              :       CHARACTER(LEN=*), INTENT(IN), OPTIONAL             :: unit_str
    1971              : 
    1972              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'qs_moment_locop'
    1973              : 
    1974         1122 :       CHARACTER(LEN=8), ALLOCATABLE, DIMENSION(:)        :: rlab
    1975              :       CHARACTER(LEN=default_string_length)               :: description
    1976              :       INTEGER                                            :: akind, handle, i, ia, iatom, idir, &
    1977              :                                                             ikind, ispin, ix, iy, iz, l, nm, nmom, &
    1978              :                                                             order
    1979              :       LOGICAL                                            :: my_com_nl, my_velreprs, use_periodic_images
    1980              :       REAL(dp)                                           :: charge, dd, strace, trace
    1981         1122 :       REAL(dp), ALLOCATABLE, DIMENSION(:)                :: mmom, nlcom_rrv, nlcom_rrv_vrr, &
    1982         1122 :                                                             nlcom_rv, nlcom_rvr, nlcom_rxrv, &
    1983         1122 :                                                             qupole_der, rmom_vel
    1984         1122 :       REAL(dp), ALLOCATABLE, DIMENSION(:, :)             :: rmom
    1985              :       REAL(dp), DIMENSION(3)                             :: rcc, ria
    1986              :       TYPE(atomic_kind_type), POINTER                    :: atomic_kind
    1987              :       TYPE(cell_type), POINTER                           :: cell
    1988              :       TYPE(cp_result_type), POINTER                      :: results
    1989         1122 :       TYPE(dbcsr_p_type), DIMENSION(:), POINTER          :: magmom, matrix_s, moments, momentum, &
    1990         1122 :                                                             rho_ao
    1991         1122 :       TYPE(dbcsr_p_type), DIMENSION(:, :), POINTER       :: moments_der
    1992              :       TYPE(dbcsr_type), POINTER                          :: tmp_ao
    1993              :       TYPE(dft_control_type), POINTER                    :: dft_control
    1994              :       TYPE(distribution_1d_type), POINTER                :: local_particles
    1995              :       TYPE(mp_para_env_type), POINTER                    :: para_env
    1996              :       TYPE(neighbor_list_set_p_type), DIMENSION(:), &
    1997         1122 :          POINTER                                         :: sab_all, sab_orb
    1998         1122 :       TYPE(particle_type), DIMENSION(:), POINTER         :: particle_set
    1999         1122 :       TYPE(qs_kind_type), DIMENSION(:), POINTER          :: qs_kind_set
    2000              :       TYPE(qs_rho_type), POINTER                         :: rho
    2001              : 
    2002            0 :       CPASSERT(ASSOCIATED(qs_env))
    2003              : 
    2004         1122 :       CALL timeset(routineN, handle)
    2005              : 
    2006         1122 :       my_velreprs = .FALSE.
    2007         1122 :       IF (PRESENT(vel_reprs)) my_velreprs = vel_reprs
    2008         1122 :       IF (PRESENT(com_nl)) my_com_nl = com_nl
    2009         1122 :       IF (my_velreprs) CALL cite_reference(Mattiat2019)
    2010              : 
    2011              :       ! reference point
    2012         1122 :       CALL get_reference_point(rcc, qs_env=qs_env, reference=reference, ref_point=ref_point)
    2013              : 
    2014              :       ! only allow for moments up to maxl set by basis
    2015         1122 :       nmom = MIN(nmoments, current_maxl)
    2016              :       ! electronic contribution
    2017         1122 :       NULLIFY (dft_control, rho, cell, particle_set, qs_kind_set, results, para_env, matrix_s, rho_ao, sab_all, sab_orb)
    2018              :       CALL get_qs_env(qs_env, &
    2019              :                       dft_control=dft_control, &
    2020              :                       rho=rho, &
    2021              :                       cell=cell, &
    2022              :                       results=results, &
    2023              :                       particle_set=particle_set, &
    2024              :                       qs_kind_set=qs_kind_set, &
    2025              :                       para_env=para_env, &
    2026              :                       matrix_s=matrix_s, &
    2027              :                       sab_all=sab_all, &
    2028         1122 :                       sab_orb=sab_orb)
    2029              : 
    2030         1122 :       IF (my_com_nl) THEN
    2031           40 :          IF ((nmom >= 1) .AND. my_velreprs) THEN
    2032           40 :             ALLOCATE (nlcom_rv(3))
    2033           40 :             nlcom_rv(:) = 0._dp
    2034              :          END IF
    2035           40 :          IF ((nmom >= 2) .AND. my_velreprs) THEN
    2036           40 :             ALLOCATE (nlcom_rrv(6))
    2037           40 :             nlcom_rrv(:) = 0._dp
    2038           40 :             ALLOCATE (nlcom_rvr(6))
    2039           40 :             nlcom_rvr(:) = 0._dp
    2040           40 :             ALLOCATE (nlcom_rrv_vrr(6))
    2041           40 :             nlcom_rrv_vrr(:) = 0._dp
    2042              :          END IF
    2043           40 :          IF (magnetic) THEN
    2044           18 :             ALLOCATE (nlcom_rxrv(3))
    2045           18 :             nlcom_rxrv = 0._dp
    2046              :          END IF
    2047              :          ! Calculate non local correction terms
    2048           40 :          CALL calculate_commutator_nl_terms(qs_env, nlcom_rv, nlcom_rxrv, nlcom_rrv, nlcom_rvr, nlcom_rrv_vrr, rcc)
    2049              :       END IF
    2050              : 
    2051         1122 :       NULLIFY (moments)
    2052         1122 :       nm = (6 + 11*nmom + 6*nmom**2 + nmom**3)/6 - 1
    2053         1122 :       CALL dbcsr_allocate_matrix_set(moments, nm)
    2054         4790 :       DO i = 1, nm
    2055         3668 :          ALLOCATE (moments(i)%matrix)
    2056         3668 :          IF (my_velreprs .AND. (nmom >= 2)) THEN
    2057              :             CALL dbcsr_create(moments(i)%matrix, template=matrix_s(1)%matrix, &
    2058          360 :                               matrix_type=dbcsr_type_symmetric)
    2059          360 :             CALL cp_dbcsr_alloc_block_from_nbl(moments(i)%matrix, sab_orb)
    2060              :          ELSE
    2061         3308 :             CALL dbcsr_copy(moments(i)%matrix, matrix_s(1)%matrix, "Moments")
    2062              :          END IF
    2063         4790 :          CALL dbcsr_set(moments(i)%matrix, 0.0_dp)
    2064              :       END DO
    2065              : 
    2066              :       ! calculate derivatives if quadrupole in vel. reprs. is requested
    2067         1122 :       IF (my_velreprs .AND. (nmom >= 2)) THEN
    2068           40 :          NULLIFY (moments_der)
    2069           40 :          CALL dbcsr_allocate_matrix_set(moments_der, 3, 3)
    2070          160 :          DO i = 1, 3 ! x, y, z
    2071          520 :             DO idir = 1, 3 ! d/dx, d/dy, d/dz
    2072          360 :                CALL dbcsr_init_p(moments_der(i, idir)%matrix)
    2073              :                CALL dbcsr_create(moments_der(i, idir)%matrix, template=matrix_s(1)%matrix, &
    2074          360 :                                  matrix_type=dbcsr_type_antisymmetric)
    2075          360 :                CALL cp_dbcsr_alloc_block_from_nbl(moments_der(i, idir)%matrix, sab_orb)
    2076          480 :                CALL dbcsr_set(moments_der(i, idir)%matrix, 0.0_dp)
    2077              :             END DO
    2078              :          END DO
    2079           40 :          CALL build_local_moments_der_matrix(qs_env, moments_der, 1, 2, ref_point=rcc, moments=moments)
    2080              :       ELSE
    2081              :          ! In non-periodic directions the moment must include the same images as the overlap.
    2082         5406 :          use_periodic_images = ANY(cell%perd /= 0) .AND. ANY(cell%perd == 0)
    2083              :          CALL build_local_moment_matrix(qs_env, moments, nmom, ref_point=rcc, &
    2084         1082 :                                         all_images=use_periodic_images, neighbor_image=use_periodic_images)
    2085              :       END IF
    2086              : 
    2087         1122 :       CALL qs_rho_get(rho, rho_ao=rho_ao)
    2088              : 
    2089         4488 :       ALLOCATE (rmom(nm + 1, 3))
    2090         3366 :       ALLOCATE (rlab(nm + 1))
    2091         1122 :       rmom = 0.0_dp
    2092         5912 :       rlab = ""
    2093              : 
    2094         1122 :       IF ((my_velreprs .AND. (nmoments >= 1)) .OR. magnetic) THEN
    2095              :          ! Allocate matrix to store the matrix product to be traced (dbcsr_dot only works for products of
    2096              :          ! symmetric matrices)
    2097           42 :          NULLIFY (tmp_ao)
    2098           42 :          CALL dbcsr_init_p(tmp_ao)
    2099           42 :          CALL dbcsr_create(tmp_ao, template=matrix_s(1)%matrix, matrix_type=dbcsr_type_no_symmetry, name="tmp")
    2100           42 :          CALL cp_dbcsr_alloc_block_from_nbl(tmp_ao, sab_all)
    2101           42 :          CALL dbcsr_set(tmp_ao, 0.0_dp)
    2102              :       END IF
    2103              : 
    2104         1122 :       trace = 0.0_dp
    2105         2322 :       DO ispin = 1, dft_control%nspins
    2106         1200 :          CALL dbcsr_dot(rho_ao(ispin)%matrix, matrix_s(1)%matrix, trace)
    2107         2322 :          rmom(1, 1) = rmom(1, 1) + trace
    2108              :       END DO
    2109              : 
    2110         4790 :       DO i = 1, SIZE(moments)
    2111         3668 :          strace = 0._dp
    2112         7570 :          DO ispin = 1, dft_control%nspins
    2113         3902 :             IF (my_velreprs .AND. nmoments >= 2) THEN
    2114              :                CALL dbcsr_multiply("T", "N", 1.0_dp, rho_ao(ispin)%matrix, moments(i)%matrix, &
    2115          360 :                                    0.0_dp, tmp_ao)
    2116          360 :                CALL dbcsr_trace(tmp_ao, trace)
    2117              :             ELSE
    2118         3542 :                CALL dbcsr_dot(rho_ao(ispin)%matrix, moments(i)%matrix, trace)
    2119              :             END IF
    2120         7570 :             strace = strace + trace
    2121              :          END DO
    2122         4790 :          rmom(i + 1, 1) = strace
    2123              :       END DO
    2124              : 
    2125         1122 :       CALL dbcsr_deallocate_matrix_set(moments)
    2126              : 
    2127              :       ! nuclear contribution
    2128              :       CALL get_qs_env(qs_env=qs_env, &
    2129         1122 :                       local_particles=local_particles)
    2130         3510 :       DO ikind = 1, SIZE(local_particles%n_el)
    2131         5343 :          DO ia = 1, local_particles%n_el(ikind)
    2132         1833 :             iatom = local_particles%list(ikind)%array(ia)
    2133              :             ! fold atomic positions back into unit cell
    2134        14664 :             ria = pbc(particle_set(iatom)%r - rcc, cell) + rcc
    2135         7332 :             ria = ria - rcc
    2136         1833 :             atomic_kind => particle_set(iatom)%atomic_kind
    2137         1833 :             CALL get_atomic_kind(atomic_kind, kind_number=akind)
    2138         1833 :             CALL get_qs_kind(qs_kind_set(akind), core_charge=charge)
    2139         1833 :             rmom(1, 2) = rmom(1, 2) - charge
    2140        10683 :             DO l = 1, nm
    2141         6462 :                ix = indco(1, l + 1)
    2142         6462 :                iy = indco(2, l + 1)
    2143         6462 :                iz = indco(3, l + 1)
    2144         6462 :                dd = 1._dp
    2145         6462 :                IF (ix > 0) dd = dd*ria(1)**ix
    2146         6462 :                IF (iy > 0) dd = dd*ria(2)**iy
    2147         6462 :                IF (iz > 0) dd = dd*ria(3)**iz
    2148         6462 :                rmom(l + 1, 2) = rmom(l + 1, 2) - charge*dd
    2149         8295 :                CALL set_label(rlab(l + 1), ix, iy, iz)
    2150              :             END DO
    2151              :          END DO
    2152              :       END DO
    2153         1122 :       CALL para_env%sum(rmom(:, 2))
    2154        18858 :       rmom(:, :) = -rmom(:, :)
    2155         5912 :       rmom(:, 3) = rmom(:, 1) + rmom(:, 2)
    2156              : 
    2157              :       ! magnetic moments
    2158         1122 :       IF (magnetic) THEN
    2159           20 :          NULLIFY (magmom)
    2160           20 :          CALL dbcsr_allocate_matrix_set(magmom, 3)
    2161           80 :          DO i = 1, SIZE(magmom)
    2162           60 :             CALL dbcsr_init_p(magmom(i)%matrix)
    2163              :             CALL dbcsr_create(magmom(i)%matrix, template=matrix_s(1)%matrix, &
    2164           60 :                               matrix_type=dbcsr_type_antisymmetric)
    2165           60 :             CALL cp_dbcsr_alloc_block_from_nbl(magmom(i)%matrix, sab_orb)
    2166           80 :             CALL dbcsr_set(magmom(i)%matrix, 0.0_dp)
    2167              :          END DO
    2168              : 
    2169           20 :          CALL build_local_magmom_matrix(qs_env, magmom, nmom, ref_point=rcc)
    2170              : 
    2171           60 :          ALLOCATE (mmom(SIZE(magmom)))
    2172           20 :          mmom(:) = 0.0_dp
    2173           20 :          IF (qs_env%run_rtp) THEN
    2174              :             ! get imaginary part of the density in rho_ao (the real part is not needed since the trace of the product
    2175              :             ! of a symmetric (REAL(rho_ao)) and an anti-symmetric (L_AO) matrix is zero)
    2176              :             ! There may be other cases, where the imaginary part of the density is relevant
    2177           12 :             NULLIFY (rho_ao)
    2178           12 :             CALL qs_rho_get(rho, rho_ao_im=rho_ao)
    2179              :          END IF
    2180              :          ! if the density is purely real this is an expensive way to calculate zero
    2181           80 :          DO i = 1, SIZE(magmom)
    2182           60 :             strace = 0._dp
    2183          120 :             DO ispin = 1, dft_control%nspins
    2184           60 :                CALL dbcsr_set(tmp_ao, 0.0_dp)
    2185              :                CALL dbcsr_multiply("T", "N", 1.0_dp, rho_ao(ispin)%matrix, magmom(i)%matrix, &
    2186           60 :                                    0.0_dp, tmp_ao)
    2187           60 :                CALL dbcsr_trace(tmp_ao, trace)
    2188          120 :                strace = strace + trace
    2189              :             END DO
    2190           80 :             mmom(i) = strace
    2191              :          END DO
    2192              : 
    2193           20 :          CALL dbcsr_deallocate_matrix_set(magmom)
    2194              :       END IF
    2195              : 
    2196              :       ! velocity representations
    2197         1122 :       IF (my_velreprs) THEN
    2198          120 :          ALLOCATE (rmom_vel(nm))
    2199           40 :          rmom_vel = 0.0_dp
    2200              : 
    2201          120 :          DO order = 1, nmom
    2202           40 :             SELECT CASE (order)
    2203              : 
    2204              :             CASE (1) ! expectation value of momentum
    2205           40 :                NULLIFY (momentum)
    2206           40 :                CALL dbcsr_allocate_matrix_set(momentum, 3)
    2207          160 :                DO i = 1, 3
    2208          120 :                   CALL dbcsr_init_p(momentum(i)%matrix)
    2209              :                   CALL dbcsr_create(momentum(i)%matrix, template=matrix_s(1)%matrix, &
    2210          120 :                                     matrix_type=dbcsr_type_antisymmetric)
    2211          120 :                   CALL cp_dbcsr_alloc_block_from_nbl(momentum(i)%matrix, sab_orb)
    2212          160 :                   CALL dbcsr_set(momentum(i)%matrix, 0.0_dp)
    2213              :                END DO
    2214           40 :                CALL build_lin_mom_matrix(qs_env, momentum)
    2215              : 
    2216              :                ! imaginary part of the density for RTP, real part gives 0 since momentum is antisymmetric
    2217           40 :                IF (qs_env%run_rtp) THEN
    2218           30 :                   NULLIFY (rho_ao)
    2219           30 :                   CALL qs_rho_get(rho, rho_ao_im=rho_ao)
    2220          120 :                   DO idir = 1, SIZE(momentum)
    2221           90 :                      strace = 0._dp
    2222          180 :                      DO ispin = 1, dft_control%nspins
    2223           90 :                         CALL dbcsr_set(tmp_ao, 0.0_dp)
    2224              :                         CALL dbcsr_multiply("T", "N", 1.0_dp, rho_ao(ispin)%matrix, momentum(idir)%matrix, &
    2225           90 :                                             0.0_dp, tmp_ao)
    2226           90 :                         CALL dbcsr_trace(tmp_ao, trace)
    2227          180 :                         strace = strace + trace
    2228              :                      END DO
    2229          120 :                      rmom_vel(idir) = rmom_vel(idir) + strace
    2230              :                   END DO
    2231              :                END IF
    2232              : 
    2233           40 :                CALL dbcsr_deallocate_matrix_set(momentum)
    2234              : 
    2235              :             CASE (2) ! expectation value of quadrupole moment in vel. reprs.
    2236           40 :                ALLOCATE (qupole_der(9)) ! will contain the expectation values of r_\alpha * d/d r_\beta
    2237           40 :                qupole_der = 0._dp
    2238              : 
    2239           40 :                NULLIFY (rho_ao)
    2240           40 :                CALL qs_rho_get(rho, rho_ao=rho_ao)
    2241              : 
    2242              :                ! Calculate expectation value over real part
    2243           40 :                trace = 0._dp
    2244          160 :                DO i = 1, 3
    2245          520 :                   DO idir = 1, 3
    2246          360 :                      strace = 0._dp
    2247          720 :                      DO ispin = 1, dft_control%nspins
    2248          360 :                         CALL dbcsr_set(tmp_ao, 0._dp)
    2249          360 :                         CALL dbcsr_multiply("T", "N", 1._dp, rho_ao(ispin)%matrix, moments_der(i, idir)%matrix, 0._dp, tmp_ao)
    2250          360 :                         CALL dbcsr_trace(tmp_ao, trace)
    2251          720 :                         strace = strace + trace
    2252              :                      END DO
    2253          480 :                      qupole_der((i - 1)*3 + idir) = qupole_der((i - 1)*3 + idir) + strace
    2254              :                   END DO
    2255              :                END DO
    2256              : 
    2257           40 :                IF (qs_env%run_rtp) THEN
    2258           30 :                   NULLIFY (rho_ao)
    2259           30 :                   CALL qs_rho_get(rho, rho_ao_im=rho_ao)
    2260              : 
    2261              :                   ! Calculate expectation value over imaginary part
    2262           30 :                   trace = 0._dp
    2263          120 :                   DO i = 1, 3
    2264          390 :                      DO idir = 1, 3
    2265          270 :                         strace = 0._dp
    2266          540 :                         DO ispin = 1, dft_control%nspins
    2267          270 :                            CALL dbcsr_set(tmp_ao, 0._dp)
    2268          270 :                            CALL dbcsr_multiply("T", "N", 1._dp, rho_ao(ispin)%matrix, moments_der(i, idir)%matrix, 0._dp, tmp_ao)
    2269          270 :                            CALL dbcsr_trace(tmp_ao, trace)
    2270          540 :                            strace = strace + trace
    2271              :                         END DO
    2272          360 :                         qupole_der((i - 1)*3 + idir) = qupole_der((i - 1)*3 + idir) + strace
    2273              :                      END DO
    2274              :                   END DO
    2275              :                END IF
    2276              : 
    2277              :                ! calculate vel. reprs. of quadrupole moment from derivatives
    2278           40 :                rmom_vel(4) = -2*qupole_der(1) - rmom(1, 1)
    2279           40 :                rmom_vel(5) = -qupole_der(2) - qupole_der(4)
    2280           40 :                rmom_vel(6) = -qupole_der(3) - qupole_der(7)
    2281           40 :                rmom_vel(7) = -2*qupole_der(5) - rmom(1, 1)
    2282           40 :                rmom_vel(8) = -qupole_der(6) - qupole_der(8)
    2283           40 :                rmom_vel(9) = -2*qupole_der(9) - rmom(1, 1)
    2284              : 
    2285          120 :                DEALLOCATE (qupole_der)
    2286              :             CASE DEFAULT
    2287              :             END SELECT
    2288              :          END DO
    2289              :       END IF
    2290              : 
    2291         1122 :       IF ((my_velreprs .AND. (nmoments >= 1)) .OR. magnetic) THEN
    2292           42 :          CALL dbcsr_deallocate_matrix(tmp_ao)
    2293              :       END IF
    2294         1122 :       IF (my_velreprs .AND. (nmoments >= 2)) THEN
    2295           40 :          CALL dbcsr_deallocate_matrix_set(moments_der)
    2296              :       END IF
    2297              : 
    2298         1122 :       description = "[DIPOLE]"
    2299         1122 :       CALL cp_results_erase(results=results, description=description)
    2300              :       CALL put_results(results=results, description=description, &
    2301         1122 :                        values=rmom(2:4, 3))
    2302              : 
    2303         5606 :       IF (unit_number > 0 .AND. ANY(cell%perd /= 0) .AND. ANY(cell%perd == 0)) THEN
    2304              :          WRITE (unit_number, "(T3,A)") &
    2305            2 :             "Only dipole components perpendicular to the periodic lattice vectors are well-defined."
    2306              :       END IF
    2307              : 
    2308         1122 :       IF (magnetic .AND. my_velreprs) THEN
    2309              :          CALL print_moments(unit_number, nmom, rmom, rlab, rcc, cell, periodic=.FALSE., mmom=mmom, rmom_vel=rmom_vel, &
    2310           18 :                             unit_str=unit_str)
    2311         1104 :       ELSE IF (magnetic .AND. .NOT. my_velreprs) THEN
    2312              :          CALL print_moments(unit_number, nmom, rmom, rlab, rcc, cell, periodic=.FALSE., mmom=mmom, &
    2313            2 :                             unit_str=unit_str)
    2314         1102 :       ELSE IF (my_velreprs .AND. .NOT. magnetic) THEN
    2315              :          CALL print_moments(unit_number, nmom, rmom, rlab, rcc, cell, periodic=.FALSE., rmom_vel=rmom_vel, &
    2316           22 :                             unit_str=unit_str)
    2317              :       ELSE
    2318         1080 :          CALL print_moments(unit_number, nmom, rmom, rlab, rcc, cell, periodic=.FALSE., unit_str=unit_str)
    2319              :       END IF
    2320              : 
    2321         1122 :       IF (my_com_nl) THEN
    2322           40 :          IF (magnetic) THEN
    2323           72 :             mmom(:) = nlcom_rxrv(:)
    2324              :          END IF
    2325           40 :          IF (my_velreprs .AND. (nmom >= 1)) THEN
    2326           40 :             DEALLOCATE (rmom_vel)
    2327           40 :             ALLOCATE (rmom_vel(21))
    2328          160 :             rmom_vel(1:3) = nlcom_rv
    2329              :          END IF
    2330           40 :          IF (my_velreprs .AND. (nmom >= 2)) THEN
    2331          280 :             rmom_vel(4:9) = nlcom_rrv
    2332          280 :             rmom_vel(10:15) = nlcom_rvr
    2333          280 :             rmom_vel(16:21) = nlcom_rrv_vrr
    2334              :          END IF
    2335           40 :          IF (magnetic .AND. .NOT. my_velreprs) THEN
    2336            0 :             CALL print_moments_nl(unit_number, nmom, rlab, mmom=mmom)
    2337           40 :          ELSE IF (my_velreprs .AND. .NOT. magnetic) THEN
    2338           22 :             CALL print_moments_nl(unit_number, nmom, rlab, rmom_vel=rmom_vel)
    2339           18 :          ELSE IF (my_velreprs .AND. magnetic) THEN
    2340           18 :             CALL print_moments_nl(unit_number, nmom, rlab, mmom=mmom, rmom_vel=rmom_vel)
    2341              :          END IF
    2342              : 
    2343              :       END IF
    2344              : 
    2345              :       IF (my_com_nl) THEN
    2346           40 :          IF (nmom >= 1 .AND. my_velreprs) DEALLOCATE (nlcom_rv)
    2347           40 :          IF (nmom >= 2 .AND. my_velreprs) THEN
    2348           40 :             DEALLOCATE (nlcom_rrv)
    2349           40 :             DEALLOCATE (nlcom_rvr)
    2350           40 :             DEALLOCATE (nlcom_rrv_vrr)
    2351              :          END IF
    2352           40 :          IF (magnetic) DEALLOCATE (nlcom_rxrv)
    2353              :       END IF
    2354              : 
    2355         1122 :       DEALLOCATE (rmom)
    2356         1122 :       DEALLOCATE (rlab)
    2357         1122 :       IF (magnetic) THEN
    2358           20 :          DEALLOCATE (mmom)
    2359              :       END IF
    2360         1122 :       IF (my_velreprs) THEN
    2361           40 :          DEALLOCATE (rmom_vel)
    2362              :       END IF
    2363              : 
    2364         1122 :       CALL timestop(handle)
    2365              : 
    2366         2244 :    END SUBROUTINE qs_moment_locop
    2367              : 
    2368              : ! **************************************************************************************************
    2369              : !> \brief ...
    2370              : !> \param label ...
    2371              : !> \param ix ...
    2372              : !> \param iy ...
    2373              : !> \param iz ...
    2374              : ! **************************************************************************************************
    2375         8454 :    SUBROUTINE set_label(label, ix, iy, iz)
    2376              :       CHARACTER(LEN=*), INTENT(OUT)                      :: label
    2377              :       INTEGER, INTENT(IN)                                :: ix, iy, iz
    2378              : 
    2379              :       INTEGER                                            :: i
    2380              : 
    2381         8454 :       label = ""
    2382        11633 :       DO i = 1, ix
    2383        11633 :          WRITE (label(i:), "(A1)") "X"
    2384              :       END DO
    2385        11633 :       DO i = ix + 1, ix + iy
    2386        11633 :          WRITE (label(i:), "(A1)") "Y"
    2387              :       END DO
    2388        11633 :       DO i = ix + iy + 1, ix + iy + iz
    2389        11633 :          WRITE (label(i:), "(A1)") "Z"
    2390              :       END DO
    2391              : 
    2392         8454 :    END SUBROUTINE set_label
    2393              : 
    2394              : ! **************************************************************************************************
    2395              : !> \brief ...
    2396              : !> \param unit_number ...
    2397              : !> \param nmom ...
    2398              : !> \param rmom ...
    2399              : !> \param rlab ...
    2400              : !> \param rcc ...
    2401              : !> \param cell ...
    2402              : !> \param periodic ...
    2403              : !> \param mmom ...
    2404              : !> \param rmom_vel ...
    2405              : !> \param unit_str unit of the printed electric moments (a dipole unit of cp_units), default debye
    2406              : ! **************************************************************************************************
    2407         1576 :    SUBROUTINE print_moments(unit_number, nmom, rmom, rlab, rcc, cell, periodic, mmom, rmom_vel, unit_str)
    2408              :       INTEGER, INTENT(IN)                                :: unit_number, nmom
    2409              :       REAL(dp), DIMENSION(:, :), INTENT(IN)              :: rmom
    2410              :       CHARACTER(LEN=8), DIMENSION(:)                     :: rlab
    2411              :       REAL(dp), DIMENSION(3), INTENT(IN)                 :: rcc
    2412              :       TYPE(cell_type), POINTER                           :: cell
    2413              :       LOGICAL                                            :: periodic
    2414              :       REAL(dp), DIMENSION(:), INTENT(IN), OPTIONAL       :: mmom, rmom_vel
    2415              :       CHARACTER(LEN=*), INTENT(IN), OPTIONAL             :: unit_str
    2416              : 
    2417              :       CHARACTER(LEN=16)                                  :: dip_label, fnum, ftot, len_label
    2418              :       INTEGER                                            :: i, i0, i1, j, l
    2419              :       LOGICAL                                            :: use_sci
    2420              :       REAL(dp)                                           :: dd, dip_fac, len_fac
    2421              : 
    2422         1576 :       IF (unit_number > 0) THEN
    2423          801 :          IF (PRESENT(unit_str)) THEN
    2424          783 :             CALL get_moment_print_units(unit_str, dip_fac, len_fac, dip_label, len_label, use_sci)
    2425              :          ELSE
    2426           18 :             CALL get_moment_print_units("debye", dip_fac, len_fac, dip_label, len_label, use_sci)
    2427              :          END IF
    2428              :          ! fixed-point fields would print SI values (~1e-30) as zero
    2429          801 :          fnum = "F14.8"
    2430          801 :          ftot = "F13.7"
    2431          801 :          IF (use_sci) THEN
    2432            0 :             fnum = "ES14.6"
    2433            0 :             ftot = "ES13.5"
    2434              :          END IF
    2435         2426 :          DO l = 0, nmom
    2436          801 :             SELECT CASE (l)
    2437              :             CASE (0)
    2438          801 :                WRITE (unit_number, "(T3,A,T33,3F16.8)") "Reference Point [Bohr]", rcc
    2439          801 :                WRITE (unit_number, "(T3,A)") "Charges"
    2440              :                WRITE (unit_number, "(T5,A,T18,F14.8,T36,A,T42,F14.8,T60,A,T67,F14.8)") &
    2441          801 :                   "Electronic=", rmom(1, 1), "Core=", rmom(1, 2), "Total=", rmom(1, 3)
    2442              :             CASE (1)
    2443          801 :                IF (periodic) THEN
    2444          222 :                   WRITE (unit_number, "(T3,A)") "Dipole vectors are based on the periodic (Berry phase) operator."
    2445              :                   WRITE (unit_number, "(T3,A)") "They are defined modulo integer multiples of the cell matrix ["// &
    2446          222 :                      TRIM(dip_label)//"]."
    2447          888 :                   WRITE (unit_number, "(T3,A,3("//TRIM(fnum)//",1X),A)") "[X] [", cell%hmat(1, :)*dip_fac, "] [i]"
    2448          888 :                   WRITE (unit_number, "(T3,A,3("//TRIM(fnum)//",1X),A)") "[Y]=[", cell%hmat(2, :)*dip_fac, "]*[j]"
    2449          888 :                   WRITE (unit_number, "(T3,A,3("//TRIM(fnum)//",1X),A)") "[Z] [", cell%hmat(3, :)*dip_fac, "] [k]"
    2450              :                ELSE
    2451          579 :                   WRITE (unit_number, "(T3,A)") "Dipoles are based on the traditional operator."
    2452              :                END IF
    2453         3204 :                dd = SQRT(SUM(rmom(2:4, 3)**2))*dip_fac
    2454          801 :                WRITE (unit_number, "(T3,A)") "Dipole moment ["//TRIM(dip_label)//"]"
    2455              :                WRITE (unit_number, "(T5,3(A,A,E15.7,1X),T60,A,T68,"//TRIM(ftot)//")") &
    2456         3204 :                   (TRIM(rlab(i)), "=", rmom(i, 3)*dip_fac, i=2, 4), "Total=", dd
    2457              :             CASE (2)
    2458           21 :                dd = dip_fac*len_fac
    2459           21 :                WRITE (unit_number, "(T3,A)") "Quadrupole moment ["//TRIM(dip_label)//"*"//TRIM(len_label)//"]"
    2460              :                WRITE (unit_number, "(T17,3(A,A,E16.8,9X))") &
    2461           84 :                   (TRIM(rlab(i)), "=", rmom(i, 3)*dd, i=5, 7)
    2462              :                WRITE (unit_number, "(T17,3(A,A,E16.8,9X))") &
    2463           84 :                   (TRIM(rlab(i)), "=", rmom(i, 3)*dd, i=8, 10)
    2464              :             CASE (3)
    2465            1 :                dd = dip_fac*len_fac**2
    2466            1 :                WRITE (unit_number, "(T3,A)") "Octapole moment ["//TRIM(dip_label)//"*"//TRIM(len_label)//"**2]"
    2467              :                WRITE (unit_number, "(T7,4(A,A,"//TRIM(fnum)//",3X))") &
    2468            5 :                   (TRIM(rlab(i)), "=", rmom(i, 3)*dd, i=11, 14)
    2469              :                WRITE (unit_number, "(T7,4(A,A,"//TRIM(fnum)//",3X))") &
    2470            5 :                   (TRIM(rlab(i)), "=", rmom(i, 3)*dd, i=15, 18)
    2471              :                WRITE (unit_number, "(T7,4(A,A,"//TRIM(fnum)//",3X))") &
    2472            3 :                   (TRIM(rlab(i)), "=", rmom(i, 3)*dd, i=19, 20)
    2473              :             CASE (4)
    2474            1 :                dd = dip_fac*len_fac**3
    2475            1 :                WRITE (unit_number, "(T3,A)") "Hexadecapole moment ["//TRIM(dip_label)//"*"//TRIM(len_label)//"**3]"
    2476              :                WRITE (unit_number, "(T6,4(A,A,"//TRIM(fnum)//",2X))") &
    2477            5 :                   (TRIM(rlab(i)), "=", rmom(i, 3)*dd, i=21, 24)
    2478              :                WRITE (unit_number, "(T6,4(A,A,"//TRIM(fnum)//",2X))") &
    2479            5 :                   (TRIM(rlab(i)), "=", rmom(i, 3)*dd, i=25, 28)
    2480              :                WRITE (unit_number, "(T6,4(A,A,"//TRIM(fnum)//",2X))") &
    2481            5 :                   (TRIM(rlab(i)), "=", rmom(i, 3)*dd, i=29, 32)
    2482              :                WRITE (unit_number, "(T6,4(A,A,"//TRIM(fnum)//",2X))") &
    2483            5 :                   (TRIM(rlab(i)), "=", rmom(i, 3)*dd, i=32, 35)
    2484              :             CASE DEFAULT
    2485              :                WRITE (unit_number, "(T3,A,A,I2)") "Higher moment ["//TRIM(dip_label)//"*"//TRIM(len_label)// &
    2486            0 :                   "**(L-1)]", "  L=", l
    2487            0 :                i0 = (6 + 11*(l - 1) + 6*(l - 1)**2 + (l - 1)**3)/6
    2488            0 :                i1 = (6 + 11*l + 6*l**2 + l**3)/6 - 1
    2489            0 :                dd = dip_fac*len_fac**(l - 1)
    2490         1625 :                DO i = i0, i1, 3
    2491              :                   WRITE (unit_number, "(T18,3(A,A,"//TRIM(fnum)//",4X))") &
    2492            0 :                      (TRIM(rlab(j + 1)), "=", rmom(j + 1, 3)*dd, j=i, MIN(i1, i + 2))
    2493              :                END DO
    2494              :             END SELECT
    2495              :          END DO
    2496          801 :          IF (PRESENT(mmom)) THEN
    2497           28 :             IF (nmom >= 1) THEN
    2498          112 :                dd = SQRT(SUM(mmom(1:3)**2))
    2499           28 :                WRITE (unit_number, "(T3,A)") "Orbital angular momentum [a. u.]"
    2500              :                WRITE (unit_number, "(T5,3(A,A,E16.8,1X),T64,A,T71,F14.8)") &
    2501          112 :                   (TRIM(rlab(i + 1)), "=", mmom(i), i=1, 3), "Total=", dd
    2502              :             END IF
    2503              :          END IF
    2504          801 :          IF (PRESENT(rmom_vel)) THEN
    2505           96 :             DO l = 1, nmom
    2506           38 :                SELECT CASE (l)
    2507              :                CASE (1)
    2508          152 :                   dd = SQRT(SUM(rmom_vel(1:3)**2))
    2509           38 :                   WRITE (unit_number, "(T3,A)") "Expectation value of momentum operator [a. u.]"
    2510              :                   WRITE (unit_number, "(T5,3(A,A,E16.8,1X),T64,A,T71,F14.8)") &
    2511          152 :                      (TRIM(rlab(i + 1)), "=", rmom_vel(i), i=1, 3), "Total=", dd
    2512              :                CASE (2)
    2513           20 :                   WRITE (unit_number, "(T3,A)") "Expectation value of quadrupole operator in vel. repr. [a. u.]"
    2514              :                   WRITE (unit_number, "(T17,3(A,A,E16.8,9X))") &
    2515           80 :                      (TRIM(rlab(i + 1)), "=", rmom_vel(i), i=4, 6)
    2516              :                   WRITE (unit_number, "(T17,3(A,A,E16.8,9X))") &
    2517          138 :                      (TRIM(rlab(i + 1)), "=", rmom_vel(i), i=7, 9)
    2518              :                CASE DEFAULT
    2519              :                END SELECT
    2520              :             END DO
    2521              :          END IF
    2522              :       END IF
    2523              : 
    2524         1576 :    END SUBROUTINE print_moments
    2525              : 
    2526              : ! **************************************************************************************************
    2527              : !> \brief Conversion factors and labels for printing electric moments in a chosen dipole unit.
    2528              : !>        Multipoles of order L are printed in (dipole unit)*(length unit)^(L-1), where the length
    2529              : !>        unit is paired with the dipole unit (debye, e_angstrom -> angstrom; au_dip -> bohr;
    2530              : !>        C_m -> m).
    2531              : !> \param unit_str dipole unit understood by cp_units (debye, e_angstrom, au_dip, C_m)
    2532              : !> \param dip_fac factor converting a dipole from a.u. (e*bohr) to unit_str
    2533              : !> \param len_fac factor converting a length from bohr to the paired length unit
    2534              : !> \param dip_label label of the dipole unit for the output headers
    2535              : !> \param len_label label of the paired length unit for the output headers
    2536              : !> \param use_sci .TRUE. if the values are too small for fixed-point output (SI units)
    2537              : ! **************************************************************************************************
    2538         1626 :    SUBROUTINE get_moment_print_units(unit_str, dip_fac, len_fac, dip_label, len_label, use_sci)
    2539              :       CHARACTER(LEN=*), INTENT(IN)                       :: unit_str
    2540              :       REAL(dp), INTENT(OUT)                              :: dip_fac, len_fac
    2541              :       CHARACTER(LEN=*), INTENT(OUT)                      :: dip_label, len_label
    2542              :       LOGICAL, INTENT(OUT)                               :: use_sci
    2543              : 
    2544              :       CHARACTER(LEN=16)                                  :: len_unit
    2545              :       TYPE(cp_unit_type)                                 :: unit
    2546              : 
    2547          813 :       CALL cp_unit_create(unit, unit_str)
    2548          813 :       IF (unit%n_kinds /= 1 .OR. unit%kind_id(1) /= cp_ukind_dipole .OR. unit%power(1) /= 1) THEN
    2549              :          CALL cp_abort(__LOCATION__, "MOMENTS%UNIT must be a dipole moment unit "// &
    2550            0 :                        "(debye, e_angstrom, au_dip or C_m), got: "//TRIM(unit_str))
    2551              :       END IF
    2552          813 :       use_sci = .FALSE.
    2553         1616 :       SELECT CASE (unit%unit_id(1))
    2554              :       CASE (cp_units_debye)
    2555          803 :          dip_label = "Debye"
    2556          803 :          len_label = "Angstrom"
    2557          803 :          len_unit = "angstrom"
    2558              :       CASE (cp_units_e_angstrom)
    2559            0 :          dip_label = "e*Angstrom"
    2560            0 :          len_label = "Angstrom"
    2561            0 :          len_unit = "angstrom"
    2562              :       CASE (cp_units_au)
    2563           10 :          dip_label = "a.u."
    2564           10 :          len_label = "Bohr"
    2565           10 :          len_unit = "bohr"
    2566              :       CASE (cp_units_c_m)
    2567            0 :          dip_label = "C*m"
    2568            0 :          len_label = "m"
    2569            0 :          len_unit = "m"
    2570            0 :          use_sci = .TRUE.
    2571              :       CASE DEFAULT
    2572          813 :          CALL cp_abort(__LOCATION__, "MOMENTS%UNIT: dipole unit not fully specified: "//TRIM(unit_str))
    2573              :       END SELECT
    2574          813 :       dip_fac = cp_unit_from_cp2k1(1.0_dp, unit)
    2575          813 :       len_fac = cp_unit_from_cp2k(1.0_dp, TRIM(len_unit))
    2576          813 :       CALL cp_unit_release(unit)
    2577              : 
    2578        20325 :    END SUBROUTINE get_moment_print_units
    2579              : 
    2580              : ! **************************************************************************************************
    2581              : !> \brief ...
    2582              : !> \param unit_number ...
    2583              : !> \param nmom ...
    2584              : !> \param rlab ...
    2585              : !> \param mmom ...
    2586              : !> \param rmom_vel ...
    2587              : ! **************************************************************************************************
    2588           58 :    SUBROUTINE print_moments_nl(unit_number, nmom, rlab, mmom, rmom_vel)
    2589              :       INTEGER, INTENT(IN)                                :: unit_number, nmom
    2590              :       CHARACTER(LEN=8), DIMENSION(:)                     :: rlab
    2591              :       REAL(dp), DIMENSION(:), INTENT(IN), OPTIONAL       :: mmom, rmom_vel
    2592              : 
    2593              :       INTEGER                                            :: i, l
    2594              :       REAL(dp)                                           :: dd
    2595              : 
    2596           58 :       IF (unit_number > 0) THEN
    2597           38 :          IF (PRESENT(mmom)) THEN
    2598           27 :             IF (nmom >= 1) THEN
    2599          108 :                dd = SQRT(SUM(mmom(1:3)**2))
    2600           27 :                WRITE (unit_number, "(T3,A)") "Expectation value of rx[r,V_nl] [a. u.]"
    2601              :                WRITE (unit_number, "(T5,3(A,A,E16.8,1X),T64,A,T71,F14.8)") &
    2602          108 :                   (TRIM(rlab(i + 1)), "=", mmom(i), i=1, 3), "Total=", dd
    2603              :             END IF
    2604              :          END IF
    2605           38 :          IF (PRESENT(rmom_vel)) THEN
    2606           96 :             DO l = 1, nmom
    2607           38 :                SELECT CASE (l)
    2608              :                CASE (1)
    2609          152 :                   dd = SQRT(SUM(rmom_vel(1:3)**2))
    2610           38 :                   WRITE (unit_number, "(T3,A)") "Expectation value of [r,V_nl] [a. u.]"
    2611              :                   WRITE (unit_number, "(T5,3(A,A,E16.8,1X),T64,A,T71,F14.8)") &
    2612          152 :                      (TRIM(rlab(i + 1)), "=", rmom_vel(i), i=1, 3), "Total=", dd
    2613              :                CASE (2)
    2614           20 :                   WRITE (unit_number, "(T3,A)") "Expectation value of [rr,V_nl] [a. u.]"
    2615              :                   WRITE (unit_number, "(T17,3(A,A,E16.8,9X))") &
    2616           80 :                      (TRIM(rlab(i + 1)), "=", rmom_vel(i), i=4, 6)
    2617              :                   WRITE (unit_number, "(T17,3(A,A,E16.8,9X))") &
    2618           80 :                      (TRIM(rlab(i + 1)), "=", rmom_vel(i), i=7, 9)
    2619           20 :                   WRITE (unit_number, "(T3,A)") "Expectation value of r x V_nl x r [a. u.]"
    2620              :                   WRITE (unit_number, "(T17,3(A,A,E16.8,9X))") &
    2621           80 :                      (TRIM(rlab(i + 1 - 6)), "=", rmom_vel(i), i=10, 12)
    2622              :                   WRITE (unit_number, "(T17,3(A,A,E16.8,9X))") &
    2623           80 :                      (TRIM(rlab(i + 1 - 6)), "=", rmom_vel(i), i=13, 15)
    2624           20 :                   WRITE (unit_number, "(T3,A)") "Expectation value of r x r x V_nl + V_nl x r x r [a. u.]"
    2625              :                   WRITE (unit_number, "(T17,3(A,A,E16.8,9X))") &
    2626           80 :                      (TRIM(rlab(i + 1 - 12)), "=", rmom_vel(i), i=16, 18)
    2627              :                   WRITE (unit_number, "(T17,3(A,A,E16.8,9X))") &
    2628          138 :                      (TRIM(rlab(i + 1 - 12)), "=", rmom_vel(i), i=19, 21)
    2629              :                CASE DEFAULT
    2630              :                END SELECT
    2631              :             END DO
    2632              :          END IF
    2633              :       END IF
    2634              : 
    2635           58 :    END SUBROUTINE print_moments_nl
    2636              : 
    2637              : ! **************************************************************************************************
    2638              : !> \brief Calculate the expectation value of operators related to non-local potential:
    2639              : !>        [r, Vnl], noted rv
    2640              : !>        r x [r,Vnl], noted rxrv
    2641              : !>        [rr,Vnl], noted rrv
    2642              : !>        r x Vnl x r, noted rvr
    2643              : !>        r x r x Vnl + Vnl x r x r, noted rrv_vrr
    2644              : !>        Note that the 3 first operator are commutator while the 2 last
    2645              : !>        are not. For reading clarity the same notation is used for all 5
    2646              : !>        operators.
    2647              : !> \param qs_env ...
    2648              : !> \param nlcom_rv ...
    2649              : !> \param nlcom_rxrv ...
    2650              : !> \param nlcom_rrv ...
    2651              : !> \param nlcom_rvr ...
    2652              : !> \param nlcom_rrv_vrr ...
    2653              : !> \param ref_point ...
    2654              : ! **************************************************************************************************
    2655           76 :    SUBROUTINE calculate_commutator_nl_terms(qs_env, nlcom_rv, nlcom_rxrv, nlcom_rrv, nlcom_rvr, &
    2656              :                                             nlcom_rrv_vrr, ref_point)
    2657              : 
    2658              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    2659              :       REAL(dp), ALLOCATABLE, DIMENSION(:), OPTIONAL      :: nlcom_rv, nlcom_rxrv, nlcom_rrv, &
    2660              :                                                             nlcom_rvr, nlcom_rrv_vrr
    2661              :       REAL(dp), DIMENSION(3)                             :: ref_point
    2662              : 
    2663              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'calculate_commutator_nl_terms'
    2664              : 
    2665              :       INTEGER                                            :: handle, ind, ispin
    2666              :       LOGICAL                                            :: calc_rrv, calc_rrv_vrr, calc_rv, &
    2667              :                                                             calc_rvr, calc_rxrv
    2668              :       REAL(dp)                                           :: eps_ppnl, strace, trace
    2669              :       TYPE(cell_type), POINTER                           :: cell
    2670           76 :       TYPE(dbcsr_p_type), DIMENSION(:), POINTER          :: matrix_rrv, matrix_rrv_vrr, matrix_rv, &
    2671           76 :                                                             matrix_rvr, matrix_rxrv, matrix_s, &
    2672           76 :                                                             rho_ao
    2673              :       TYPE(dbcsr_type), POINTER                          :: tmp_ao
    2674              :       TYPE(dft_control_type), POINTER                    :: dft_control
    2675              :       TYPE(neighbor_list_set_p_type), DIMENSION(:), &
    2676           76 :          POINTER                                         :: sab_all, sab_orb, sap_ppnl
    2677           76 :       TYPE(particle_type), DIMENSION(:), POINTER         :: particle_set
    2678           76 :       TYPE(qs_kind_type), DIMENSION(:), POINTER          :: qs_kind_set
    2679              :       TYPE(qs_rho_type), POINTER                         :: rho
    2680              : 
    2681           76 :       CALL timeset(routineN, handle)
    2682              : 
    2683           76 :       calc_rv = .FALSE.
    2684           76 :       calc_rxrv = .FALSE.
    2685           76 :       calc_rrv = .FALSE.
    2686           76 :       calc_rvr = .FALSE.
    2687           76 :       calc_rrv_vrr = .FALSE.
    2688              : 
    2689              :       ! rv, rxrv and rrv are commutator matrices: anti-symmetric.
    2690              :       ! The real part of the density matrix rho_ao is symmetric so that
    2691              :       ! the expectation value of real density matrix is zero. Hence, if
    2692              :       ! the density matrix is real, no need to compute these quantities.
    2693              :       ! This is not the case for rvr and rrv_vrr which are symmetric.
    2694              : 
    2695           76 :       IF (ALLOCATED(nlcom_rv)) THEN
    2696           76 :          nlcom_rv(:) = 0._dp
    2697           76 :          IF (qs_env%run_rtp) calc_rv = .TRUE.
    2698              :       END IF
    2699           76 :       IF (ALLOCATED(nlcom_rxrv)) THEN
    2700           54 :          nlcom_rxrv(:) = 0._dp
    2701           54 :          IF (qs_env%run_rtp) calc_rxrv = .TRUE.
    2702              :       END IF
    2703           76 :       IF (ALLOCATED(nlcom_rrv)) THEN
    2704           40 :          nlcom_rrv(:) = 0._dp
    2705           40 :          IF (qs_env%run_rtp) calc_rrv = .TRUE.
    2706              :       END IF
    2707           76 :       IF (ALLOCATED(nlcom_rvr)) THEN
    2708           40 :          nlcom_rvr(:) = 0._dp
    2709           40 :          calc_rvr = .TRUE.
    2710              :       END IF
    2711           76 :       IF (ALLOCATED(nlcom_rrv_vrr)) THEN
    2712           40 :          nlcom_rrv_vrr(:) = 0._dp
    2713           40 :          calc_rrv_vrr = .TRUE.
    2714              :       END IF
    2715              : 
    2716           76 :       IF (.NOT. (calc_rv .OR. calc_rrv .OR. calc_rxrv .OR. calc_rvr .OR. calc_rrv_vrr)) THEN
    2717           12 :          CALL timestop(handle)
    2718           12 :          RETURN
    2719              :       END IF
    2720              : 
    2721           64 :       NULLIFY (cell, matrix_s, particle_set, qs_kind_set, rho, sab_all, sab_orb, sap_ppnl)
    2722              :       CALL get_qs_env(qs_env, &
    2723              :                       cell=cell, &
    2724              :                       dft_control=dft_control, &
    2725              :                       matrix_s=matrix_s, &
    2726              :                       particle_set=particle_set, &
    2727              :                       qs_kind_set=qs_kind_set, &
    2728              :                       rho=rho, &
    2729              :                       sab_orb=sab_orb, &
    2730              :                       sab_all=sab_all, &
    2731           64 :                       sap_ppnl=sap_ppnl)
    2732              : 
    2733           64 :       eps_ppnl = dft_control%qs_control%eps_ppnl
    2734              : 
    2735              :       ! Allocate storage
    2736           64 :       NULLIFY (matrix_rv, matrix_rxrv, matrix_rrv, matrix_rvr, matrix_rrv_vrr)
    2737           64 :       IF (calc_rv) THEN
    2738           54 :          CALL dbcsr_allocate_matrix_set(matrix_rv, 3)
    2739          216 :          DO ind = 1, 3
    2740          162 :             CALL dbcsr_init_p(matrix_rv(ind)%matrix)
    2741              :             CALL dbcsr_create(matrix_rv(ind)%matrix, template=matrix_s(1)%matrix, &
    2742          162 :                               matrix_type=dbcsr_type_antisymmetric)
    2743          162 :             CALL cp_dbcsr_alloc_block_from_nbl(matrix_rv(ind)%matrix, sab_orb)
    2744          216 :             CALL dbcsr_set(matrix_rv(ind)%matrix, 0._dp)
    2745              :          END DO
    2746              :       END IF
    2747              : 
    2748           64 :       IF (calc_rxrv) THEN
    2749           36 :          CALL dbcsr_allocate_matrix_set(matrix_rxrv, 3)
    2750          144 :          DO ind = 1, 3
    2751          108 :             CALL dbcsr_init_p(matrix_rxrv(ind)%matrix)
    2752              :             CALL dbcsr_create(matrix_rxrv(ind)%matrix, template=matrix_s(1)%matrix, &
    2753          108 :                               matrix_type=dbcsr_type_antisymmetric)
    2754          108 :             CALL cp_dbcsr_alloc_block_from_nbl(matrix_rxrv(ind)%matrix, sab_orb)
    2755          144 :             CALL dbcsr_set(matrix_rxrv(ind)%matrix, 0._dp)
    2756              :          END DO
    2757              :       END IF
    2758              : 
    2759           64 :       IF (calc_rrv) THEN
    2760           30 :          CALL dbcsr_allocate_matrix_set(matrix_rrv, 6)
    2761          210 :          DO ind = 1, 6
    2762          180 :             CALL dbcsr_init_p(matrix_rrv(ind)%matrix)
    2763              :             CALL dbcsr_create(matrix_rrv(ind)%matrix, template=matrix_s(1)%matrix, &
    2764          180 :                               matrix_type=dbcsr_type_antisymmetric)
    2765          180 :             CALL cp_dbcsr_alloc_block_from_nbl(matrix_rrv(ind)%matrix, sab_orb)
    2766          210 :             CALL dbcsr_set(matrix_rrv(ind)%matrix, 0._dp)
    2767              :          END DO
    2768              :       END IF
    2769              : 
    2770           64 :       IF (calc_rvr) THEN
    2771           40 :          CALL dbcsr_allocate_matrix_set(matrix_rvr, 6)
    2772          280 :          DO ind = 1, 6
    2773          240 :             CALL dbcsr_init_p(matrix_rvr(ind)%matrix)
    2774              :             CALL dbcsr_create(matrix_rvr(ind)%matrix, template=matrix_s(1)%matrix, &
    2775          240 :                               matrix_type=dbcsr_type_symmetric)
    2776          240 :             CALL cp_dbcsr_alloc_block_from_nbl(matrix_rvr(ind)%matrix, sab_orb)
    2777          280 :             CALL dbcsr_set(matrix_rvr(ind)%matrix, 0._dp)
    2778              :          END DO
    2779              :       END IF
    2780           64 :       IF (calc_rrv_vrr) THEN
    2781           40 :          CALL dbcsr_allocate_matrix_set(matrix_rrv_vrr, 6)
    2782          280 :          DO ind = 1, 6
    2783          240 :             CALL dbcsr_init_p(matrix_rrv_vrr(ind)%matrix)
    2784              :             CALL dbcsr_create(matrix_rrv_vrr(ind)%matrix, template=matrix_s(1)%matrix, &
    2785          240 :                               matrix_type=dbcsr_type_symmetric)
    2786          240 :             CALL cp_dbcsr_alloc_block_from_nbl(matrix_rrv_vrr(ind)%matrix, sab_orb)
    2787          280 :             CALL dbcsr_set(matrix_rrv_vrr(ind)%matrix, 0._dp)
    2788              :          END DO
    2789              :       END IF
    2790              : 
    2791              :       ! calculate evaluation of operators in AO basis set
    2792              :       CALL build_com_mom_nl(qs_kind_set, sab_orb, sap_ppnl, eps_ppnl, particle_set, cell, matrix_rv=matrix_rv, &
    2793              :                             matrix_rxrv=matrix_rxrv, matrix_rrv=matrix_rrv, matrix_rvr=matrix_rvr, &
    2794           64 :                             matrix_rrv_vrr=matrix_rrv_vrr, ref_point=ref_point)
    2795              : 
    2796              :       ! Calculate expectation values
    2797              :       ! Real part
    2798           64 :       NULLIFY (tmp_ao)
    2799           64 :       CALL dbcsr_init_p(tmp_ao)
    2800           64 :       CALL dbcsr_create(tmp_ao, template=matrix_s(1)%matrix, matrix_type=dbcsr_type_no_symmetry, name="tmp")
    2801           64 :       CALL cp_dbcsr_alloc_block_from_nbl(tmp_ao, sab_all)
    2802           64 :       CALL dbcsr_set(tmp_ao, 0.0_dp)
    2803              : 
    2804           64 :       IF (calc_rvr .OR. calc_rrv_vrr) THEN
    2805           40 :          NULLIFY (rho_ao)
    2806           40 :          CALL qs_rho_get(rho, rho_ao=rho_ao)
    2807              : 
    2808           40 :          IF (calc_rvr) THEN
    2809              :             trace = 0._dp
    2810          280 :             DO ind = 1, SIZE(matrix_rvr)
    2811          240 :                strace = 0._dp
    2812          480 :                DO ispin = 1, dft_control%nspins
    2813          240 :                   CALL dbcsr_set(tmp_ao, 0.0_dp)
    2814              :                   CALL dbcsr_multiply("T", "N", 1.0_dp, rho_ao(ispin)%matrix, matrix_rvr(ind)%matrix, &
    2815          240 :                                       0.0_dp, tmp_ao)
    2816          240 :                   CALL dbcsr_trace(tmp_ao, trace)
    2817          480 :                   strace = strace + trace
    2818              :                END DO
    2819          280 :                nlcom_rvr(ind) = nlcom_rvr(ind) + strace
    2820              :             END DO
    2821              :          END IF
    2822              : 
    2823           40 :          IF (calc_rrv_vrr) THEN
    2824              :             trace = 0._dp
    2825          280 :             DO ind = 1, SIZE(matrix_rrv_vrr)
    2826          240 :                strace = 0._dp
    2827          480 :                DO ispin = 1, dft_control%nspins
    2828          240 :                   CALL dbcsr_set(tmp_ao, 0.0_dp)
    2829              :                   CALL dbcsr_multiply("T", "N", 1.0_dp, rho_ao(ispin)%matrix, matrix_rrv_vrr(ind)%matrix, &
    2830          240 :                                       0.0_dp, tmp_ao)
    2831          240 :                   CALL dbcsr_trace(tmp_ao, trace)
    2832          480 :                   strace = strace + trace
    2833              :                END DO
    2834          280 :                nlcom_rrv_vrr(ind) = nlcom_rrv_vrr(ind) + strace
    2835              :             END DO
    2836              :          END IF
    2837              :       END IF
    2838              : 
    2839              :       ! imagninary part of the density matrix
    2840           64 :       NULLIFY (rho_ao)
    2841           64 :       CALL qs_rho_get(rho, rho_ao_im=rho_ao)
    2842              : 
    2843           64 :       IF (calc_rv) THEN
    2844              :          trace = 0._dp
    2845          216 :          DO ind = 1, SIZE(matrix_rv)
    2846          162 :             strace = 0._dp
    2847          324 :             DO ispin = 1, dft_control%nspins
    2848          162 :                CALL dbcsr_set(tmp_ao, 0.0_dp)
    2849              :                CALL dbcsr_multiply("T", "N", 1.0_dp, rho_ao(ispin)%matrix, matrix_rv(ind)%matrix, &
    2850          162 :                                    0.0_dp, tmp_ao)
    2851          162 :                CALL dbcsr_trace(tmp_ao, trace)
    2852          324 :                strace = strace + trace
    2853              :             END DO
    2854          216 :             nlcom_rv(ind) = nlcom_rv(ind) + strace
    2855              :          END DO
    2856              :       END IF
    2857              : 
    2858           64 :       IF (calc_rrv) THEN
    2859              :          trace = 0._dp
    2860          210 :          DO ind = 1, SIZE(matrix_rrv)
    2861          180 :             strace = 0._dp
    2862          360 :             DO ispin = 1, dft_control%nspins
    2863          180 :                CALL dbcsr_set(tmp_ao, 0.0_dp)
    2864              :                CALL dbcsr_multiply("T", "N", 1.0_dp, rho_ao(ispin)%matrix, matrix_rrv(ind)%matrix, &
    2865          180 :                                    0.0_dp, tmp_ao)
    2866          180 :                CALL dbcsr_trace(tmp_ao, trace)
    2867          360 :                strace = strace + trace
    2868              :             END DO
    2869          210 :             nlcom_rrv(ind) = nlcom_rrv(ind) + strace
    2870              :          END DO
    2871              :       END IF
    2872              : 
    2873           64 :       IF (calc_rxrv) THEN
    2874              :          trace = 0._dp
    2875          144 :          DO ind = 1, SIZE(matrix_rxrv)
    2876          108 :             strace = 0._dp
    2877          216 :             DO ispin = 1, dft_control%nspins
    2878          108 :                CALL dbcsr_set(tmp_ao, 0.0_dp)
    2879              :                CALL dbcsr_multiply("T", "N", 1.0_dp, rho_ao(ispin)%matrix, matrix_rxrv(ind)%matrix, &
    2880          108 :                                    0.0_dp, tmp_ao)
    2881          108 :                CALL dbcsr_trace(tmp_ao, trace)
    2882          216 :                strace = strace + trace
    2883              :             END DO
    2884          144 :             nlcom_rxrv(ind) = nlcom_rxrv(ind) + strace
    2885              :          END DO
    2886              :       END IF
    2887           64 :       CALL dbcsr_deallocate_matrix(tmp_ao)
    2888           64 :       IF (calc_rv) CALL dbcsr_deallocate_matrix_set(matrix_rv)
    2889           64 :       IF (calc_rxrv) CALL dbcsr_deallocate_matrix_set(matrix_rxrv)
    2890           64 :       IF (calc_rrv) CALL dbcsr_deallocate_matrix_set(matrix_rrv)
    2891           64 :       IF (calc_rvr) CALL dbcsr_deallocate_matrix_set(matrix_rvr)
    2892           64 :       IF (calc_rrv_vrr) CALL dbcsr_deallocate_matrix_set(matrix_rrv_vrr)
    2893              : 
    2894           64 :       CALL timestop(handle)
    2895           76 :    END SUBROUTINE calculate_commutator_nl_terms
    2896              : 
    2897              : ! **************************************************************************************************
    2898              : !> \brief Get list of kpoints from input to compute dipole moment elements
    2899              : !> \param qs_env ...
    2900              : !> \param xkp ...
    2901              : !> \param special_pnts ...
    2902              : !> \author Shridhar Shanbhag
    2903              : ! **************************************************************************************************
    2904           12 :    SUBROUTINE get_xkp_for_dipole_calc(qs_env, xkp, special_pnts)
    2905              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    2906              :       TYPE(section_vals_type), POINTER                   :: kpnts, kpset
    2907              :       REAL(KIND=dp), DIMENSION(3, 3)                     :: cart_hmat, hmat
    2908              : 
    2909              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'get_xkp_for_dipole_calc'
    2910              : 
    2911              :       CHARACTER(LEN=default_string_length)               :: ustr
    2912              :       TYPE(kpoint_type), POINTER                         :: kpoint_work
    2913              :       TYPE(cell_type), POINTER                           :: cell
    2914              :       CHARACTER(LEN=default_string_length), &
    2915           12 :          DIMENSION(:), POINTER                           :: strptr
    2916              :       CHARACTER(LEN=default_string_length), &
    2917           12 :          DIMENSION(:), POINTER                           :: special_pnts, spname
    2918              :       CHARACTER(LEN=max_line_length)                     :: error_message
    2919              :       INTEGER                                            :: handle, i, ik, ikk, ip, &
    2920              :                                                             n_ptr, npline, nkp
    2921              :       LOGICAL                                            :: explicit_kpnts, explicit_kpset
    2922           12 :       REAL(kind=dp), ALLOCATABLE, DIMENSION(:, :)        :: kspecial, xkp
    2923              :       REAL(KIND=dp), DIMENSION(3)                        :: kpptr
    2924           12 :       TYPE(particle_type), DIMENSION(:), POINTER         :: particle_set
    2925              : 
    2926           12 :       CALL timeset(routineN, handle)
    2927           12 :       kpset => section_vals_get_subs_vals(qs_env%input, "DFT%PRINT%MOMENTS%KPOINT_SET")
    2928           12 :       kpnts => section_vals_get_subs_vals(qs_env%input, "DFT%PRINT%MOMENTS%KPOINTS")
    2929           12 :       CALL section_vals_get(kpset, explicit=explicit_kpset)
    2930           12 :       CALL section_vals_get(kpnts, explicit=explicit_kpnts)
    2931           12 :       IF (explicit_kpset .AND. explicit_kpnts) then
    2932            0 :          CPABORT("Both KPOINT_SET and KPOINTS present in MOMENTS section")
    2933              :       end if
    2934              : 
    2935           12 :       IF (explicit_kpset) THEN
    2936            6 :          CALL get_qs_env(qs_env, cell=cell)
    2937            6 :          CALL get_cell(cell, h=hmat)
    2938            6 :          cart_hmat(:, :) = hmat(:, :)
    2939            6 :          IF (cell%input_cell_canonicalized) cart_hmat(:, :) = cell%input_hmat(:, :)
    2940            6 :          CALL section_vals_val_get(kpset, "NPOINTS", i_val=npline)
    2941            6 :          CALL section_vals_val_get(kpset, "UNITS", c_val=ustr)
    2942            6 :          CALL uppercase(ustr)
    2943            6 :          CALL section_vals_val_get(kpset, "SPECIAL_POINT", n_rep_val=n_ptr)
    2944            6 :          CPASSERT(n_ptr > 0)
    2945           18 :          ALLOCATE (kspecial(3, n_ptr))
    2946           18 :          ALLOCATE (spname(n_ptr))
    2947           12 :          DO ip = 1, n_ptr
    2948            6 :             CALL section_vals_val_get(kpset, "SPECIAL_POINT", i_rep_val=ip, c_vals=strptr)
    2949            6 :             IF (SIZE(strptr(:), 1) == 4) THEN
    2950            2 :                spname(ip) = strptr(1)
    2951            8 :                DO i = 1, 3
    2952            6 :                   CALL read_float_object(strptr(i + 1), kpptr(i), error_message)
    2953            8 :                   IF (LEN_TRIM(error_message) > 0) CPABORT(TRIM(error_message))
    2954              :                END DO
    2955            4 :             ELSE IF (SIZE(strptr(:), 1) == 3) THEN
    2956            4 :                spname(ip) = "not specified"
    2957           16 :                DO i = 1, 3
    2958           12 :                   CALL read_float_object(strptr(i), kpptr(i), error_message)
    2959           16 :                   IF (LEN_TRIM(error_message) > 0) CPABORT(TRIM(error_message))
    2960              :                END DO
    2961              :             ELSE
    2962            0 :                CPABORT("Input SPECIAL_POINT invalid")
    2963              :             END IF
    2964            6 :             SELECT CASE (ustr)
    2965              :             CASE ("B_VECTOR")
    2966           24 :                kspecial(1:3, ip) = kpptr(1:3)
    2967              :             CASE ("CART_ANGSTROM")
    2968              :                kspecial(1:3, ip) = (kpptr(1)*cart_hmat(1, 1:3) + &
    2969              :                                     kpptr(2)*cart_hmat(2, 1:3) + &
    2970            0 :                                     kpptr(3)*cart_hmat(3, 1:3))/twopi*angstrom
    2971              :             CASE ("CART_BOHR")
    2972              :                kspecial(1:3, ip) = (kpptr(1)*cart_hmat(1, 1:3) + &
    2973              :                                     kpptr(2)*cart_hmat(2, 1:3) + &
    2974            0 :                                     kpptr(3)*cart_hmat(3, 1:3))/twopi
    2975              :             CASE DEFAULT
    2976            6 :                CPABORT("Unknown unit <"//TRIM(ustr)//"> specified for k-point definition")
    2977              :             END SELECT
    2978              :          END DO
    2979            6 :          nkp = (n_ptr - 1)*npline + 1
    2980            6 :          CPASSERT(nkp >= 1)
    2981              : 
    2982              :          ! Initialize environment and calculate MOs
    2983           18 :          ALLOCATE (xkp(3, nkp))
    2984           18 :          ALLOCATE (special_pnts(nkp))
    2985           12 :          special_pnts(:) = ""
    2986           24 :          xkp(1:3, 1) = kspecial(1:3, 1)
    2987            6 :          ikk = 1
    2988            6 :          special_pnts(ikk) = spname(1)
    2989            6 :          DO ik = 2, n_ptr
    2990            0 :             DO ip = 1, npline
    2991            0 :                ikk = ikk + 1
    2992              :                xkp(1:3, ikk) = kspecial(1:3, ik - 1) + &
    2993              :                                REAL(ip, KIND=dp)/REAL(npline, KIND=dp)* &
    2994            0 :                                (kspecial(1:3, ik) - kspecial(1:3, ik - 1))
    2995              :             END DO
    2996            6 :             special_pnts(ikk) = spname(ik)
    2997              :          END DO
    2998           18 :          DEALLOCATE (spname, kspecial)
    2999            6 :       ELSE IF (explicit_kpnts) THEN
    3000            2 :          CALL get_qs_env(qs_env, particle_set=particle_set, cell=cell)
    3001            2 :          CALL get_cell(cell, h=hmat)
    3002            2 :          NULLIFY (kpoint_work)
    3003            2 :          CALL kpoint_create(kpoint_work)
    3004            2 :          CALL read_kpoint_section(kpoint_work, kpnts, hmat, cell)
    3005            2 :          CALL kpoint_initialize(kpoint_work, particle_set, cell)
    3006            2 :          nkp = kpoint_work%nkp
    3007            6 :          ALLOCATE (xkp(3, nkp))
    3008            6 :          ALLOCATE (special_pnts(nkp))
    3009            4 :          special_pnts(:) = ""
    3010           10 :          xkp(1:3, :) = kpoint_work%xkp(1:3, :)
    3011            2 :          CALL kpoint_release(kpoint_work)
    3012              :       ELSE
    3013              :          ! use k-point mesh from DFT calculation
    3014            4 :          CALL get_qs_env(qs_env, kpoints=kpoint_work)
    3015            4 :          nkp = kpoint_work%nkp
    3016            4 :          nkp = kpoint_work%nkp
    3017           12 :          ALLOCATE (xkp(3, nkp))
    3018           12 :          ALLOCATE (special_pnts(nkp))
    3019          252 :          special_pnts(:) = ""
    3020          996 :          xkp(1:3, :) = kpoint_work%xkp(1:3, :)
    3021              :       END IF
    3022           12 :       CALL timestop(handle)
    3023              : 
    3024           12 :    END SUBROUTINE get_xkp_for_dipole_calc
    3025              : ! **************************************************************************************************
    3026              : !> \brief Calculate local moment matrix for a periodic system for all image cells
    3027              : !> \param qs_env ...
    3028              : !> \param moments_rs_img ...
    3029              : !> \param rcc ...
    3030              : !> \author Shridhar Shanbhag
    3031              : ! **************************************************************************************************
    3032           60 :    SUBROUTINE build_local_moment_matrix_rs_img(qs_env, moments_rs_img, rcc)
    3033              : 
    3034              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    3035              :       TYPE(dbcsr_p_type), DIMENSION(:, :), POINTER       :: moments_rs_img
    3036              :       REAL(KIND=dp), DIMENSION(3), OPTIONAL              :: rcc
    3037              : 
    3038              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'build_local_moment_matrix_rs_img'
    3039              : 
    3040              :       INTEGER :: handle, i_dir, iatom, ic, ikind, iset, j, jatom, jkind, jset, &
    3041              :                  ldsa, ldsb, ldwork, ncoa, ncob, nimg, nkind, nseta, nsetb, nsize, sgfa, sgfb
    3042              :       INTEGER, DIMENSION(3)                              :: icell
    3043           60 :       INTEGER, DIMENSION(:, :), POINTER                  :: index_to_cell
    3044           60 :       INTEGER, DIMENSION(:, :, :), POINTER               :: cell_to_index
    3045              :       LOGICAL                                            :: found
    3046              :       REAL(dp), DIMENSION(3)                             :: ra, rab, rac, rb, rbc, rc
    3047           60 :       REAL(dp), DIMENSION(:, :), POINTER                 :: dblock, work
    3048           60 :       REAL(dp), DIMENSION(:, :, :), POINTER              :: dipab
    3049              :       REAL(KIND=dp)                                      :: dab
    3050              :       TYPE(cell_type), POINTER                           :: cell
    3051           60 :       TYPE(dbcsr_p_type), DIMENSION(:, :), POINTER       :: matrix_ks_kp
    3052              :       TYPE(dft_control_type), POINTER                    :: dft_control
    3053           60 :       TYPE(gto_basis_set_p_type), DIMENSION(:), POINTER  :: basis_set_list
    3054              :       TYPE(gto_basis_set_type), POINTER                  :: basis_set, basis_set_a, basis_set_b
    3055              :       TYPE(kpoint_type), POINTER                         :: kpoints_all
    3056              :       TYPE(mp_para_env_type), POINTER                    :: para_env
    3057              :       TYPE(neighbor_list_iterator_p_type), &
    3058           60 :          DIMENSION(:), POINTER                           :: nl_iterator
    3059              :       TYPE(neighbor_list_set_p_type), DIMENSION(:), &
    3060           60 :          POINTER                                         :: sab_all
    3061           60 :       TYPE(particle_type), DIMENSION(:), POINTER         :: particle_set
    3062           60 :       TYPE(qs_kind_type), DIMENSION(:), POINTER          :: qs_kind_set
    3063              :       TYPE(qs_kind_type), POINTER                        :: qs_kind
    3064              : 
    3065           60 :       CALL timeset(routineN, handle)
    3066              : 
    3067              :       CALL get_qs_env(qs_env=qs_env, &
    3068              :                       dft_control=dft_control, &
    3069              :                       qs_kind_set=qs_kind_set, &
    3070              :                       matrix_ks_kp=matrix_ks_kp, &
    3071              :                       particle_set=particle_set, &
    3072              :                       cell=cell, &
    3073              :                       para_env=para_env, &
    3074           60 :                       sab_all=sab_all)
    3075              : 
    3076           60 :       NULLIFY (kpoints_all)
    3077           60 :       CALL kpoint_create(kpoints_all)
    3078           60 :       CALL kpoint_init_cell_index(kpoints_all, sab_all, para_env, nimg)
    3079              : 
    3080           60 :       nkind = SIZE(qs_kind_set)
    3081          262 :       ALLOCATE (basis_set_list(nkind))
    3082          142 :       DO ikind = 1, nkind
    3083           82 :          qs_kind => qs_kind_set(ikind)
    3084           82 :          CALL get_qs_kind(qs_kind=qs_kind, basis_set=basis_set)
    3085          142 :          IF (ASSOCIATED(basis_set)) THEN
    3086           82 :             basis_set_list(ikind)%gto_basis_set => basis_set
    3087              :          ELSE
    3088            0 :             NULLIFY (basis_set_list(ikind)%gto_basis_set)
    3089              :          END IF
    3090              :       END DO
    3091              : 
    3092           60 :       rc(:) = 0._dp
    3093           60 :       IF (PRESENT(rcc)) rc(:) = rcc(:)
    3094              : 
    3095           60 :       CALL get_particle_set(particle_set, qs_kind_set, basis=basis_set_list)
    3096           60 :       CALL get_kpoint_info(kpoints_all, cell_to_index=cell_to_index, index_to_cell=index_to_cell)
    3097           60 :       nsize = SIZE(index_to_cell, 2)
    3098           60 :       CPASSERT(SIZE(moments_rs_img, 2) == nsize)
    3099          240 :       DO i_dir = 1, 3
    3100         8460 :          DO j = 1, nsize
    3101         8220 :             ALLOCATE (moments_rs_img(i_dir, j)%matrix)
    3102              :             CALL dbcsr_create(matrix=moments_rs_img(i_dir, j)%matrix, &
    3103              :                               template=matrix_ks_kp(1, 1)%matrix, &
    3104              :                               matrix_type=dbcsr_type_no_symmetry, &
    3105         8220 :                               name="DIPMAT")
    3106         8220 :             CALL cp_dbcsr_alloc_block_from_nbl(moments_rs_img(i_dir, j)%matrix, sab_all)
    3107         8400 :             CALL dbcsr_set(moments_rs_img(i_dir, j)%matrix, 0.0_dp)
    3108              :          END DO
    3109              :       END DO
    3110              : 
    3111           60 :       CALL get_qs_kind_set(qs_kind_set=qs_kind_set, maxco=ldwork)
    3112          300 :       ALLOCATE (dipab(ldwork, ldwork, 3))
    3113          240 :       ALLOCATE (work(ldwork, ldwork))
    3114              : 
    3115           60 :       CALL neighbor_list_iterator_create(nl_iterator, sab_all)
    3116         4883 :       DO WHILE (neighbor_list_iterate(nl_iterator) == 0)
    3117              :          CALL get_iterator_info(nl_iterator, ikind=ikind, jkind=jkind, &
    3118         4823 :                                 iatom=iatom, jatom=jatom, r=rab, cell=icell)
    3119              : 
    3120         4823 :          basis_set_a => basis_set_list(ikind)%gto_basis_set
    3121         4823 :          IF (.NOT. ASSOCIATED(basis_set_a)) CYCLE
    3122         4823 :          basis_set_b => basis_set_list(jkind)%gto_basis_set
    3123         4823 :          IF (.NOT. ASSOCIATED(basis_set_b)) CYCLE
    3124              :          ASSOCIATE ( &
    3125              :             ! basis ikind
    3126              :             first_sgfa => basis_set_a%first_sgf, &
    3127              :             la_max => basis_set_a%lmax, &
    3128              :             la_min => basis_set_a%lmin, &
    3129              :             npgfa => basis_set_a%npgf, &
    3130              :             nsgfa => basis_set_a%nsgf_set, &
    3131              :             rpgfa => basis_set_a%pgf_radius, &
    3132              :             set_radius_a => basis_set_a%set_radius, &
    3133              :             sphi_a => basis_set_a%sphi, &
    3134              :             zeta => basis_set_a%zet, &
    3135              :             ! basis jkind, &
    3136              :             first_sgfb => basis_set_b%first_sgf, &
    3137              :             lb_max => basis_set_b%lmax, &
    3138              :             lb_min => basis_set_b%lmin, &
    3139              :             npgfb => basis_set_b%npgf, &
    3140              :             nsgfb => basis_set_b%nsgf_set, &
    3141              :             rpgfb => basis_set_b%pgf_radius, &
    3142              :             set_radius_b => basis_set_b%set_radius, &
    3143              :             sphi_b => basis_set_b%sphi, &
    3144              :             zetb => basis_set_b%zet)
    3145              : 
    3146         4823 :             nseta = basis_set_a%nset
    3147         4823 :             nsetb = basis_set_b%nset
    3148              : 
    3149         4823 :             ldsa = SIZE(sphi_a, 1)
    3150         4823 :             ldsb = SIZE(sphi_b, 1)
    3151              : 
    3152         4823 :             NULLIFY (dblock)
    3153              : 
    3154         4823 :             ra = pbc(particle_set(iatom)%r(:), cell)
    3155        19292 :             rb(:) = ra(:) + rab(:)
    3156        19292 :             rac = ra - rc
    3157        19292 :             rbc = rb - rc
    3158        19292 :             dab = norm2(rab)
    3159              : 
    3160         4823 :             ic = cell_to_index(icell(1), icell(2), icell(3))
    3161              : 
    3162        14544 :             DO iset = 1, nseta
    3163              : 
    3164         4898 :                ncoa = npgfa(iset)*ncoset(la_max(iset))
    3165         4898 :                sgfa = first_sgfa(1, iset)
    3166              : 
    3167        14769 :                DO jset = 1, nsetb
    3168              : 
    3169         5048 :                   IF (set_radius_a(iset) + set_radius_b(jset) < dab) CYCLE
    3170              : 
    3171         4114 :                   ncob = npgfb(jset)*ncoset(lb_max(jset))
    3172         4114 :                   sgfb = first_sgfb(1, jset)
    3173              : 
    3174              :                   CALL moment(la_max(iset), npgfa(iset), zeta(:, iset), rpgfa(:, iset), la_min(iset), &
    3175              :                               lb_max(jset), npgfb(jset), zetb(:, jset), rpgfb(:, jset), 1, &
    3176         4114 :                               rac, rbc, dipab)
    3177        21354 :                   DO i_dir = 1, 3
    3178              :                      CALL dbcsr_get_block_p(matrix=moments_rs_img(i_dir, ic)%matrix, &
    3179        12342 :                                             row=iatom, col=jatom, BLOCK=dblock, found=found)
    3180        12342 :                      CPASSERT(found)
    3181              :                      CALL dgemm("N", "N", ncoa, nsgfb(jset), ncob, &
    3182              :                                 1.0_dp, dipab(1, 1, i_dir), ldwork, &
    3183        12342 :                                 sphi_b(1, sgfb), ldsb, 0.0_dp, work(1, 1), ldwork)
    3184              : 
    3185              :                      CALL dgemm("T", "N", nsgfa(iset), nsgfb(jset), ncoa, &
    3186              :                                 1.0_dp, sphi_a(1, sgfa), ldsa, &
    3187        29732 :                                 work(1, 1), ldwork, 1.0_dp, dblock(sgfa, sgfb), SIZE(dblock, 1))
    3188              :                   END DO
    3189              :                END DO
    3190              :             END DO
    3191              :          END ASSOCIATE
    3192              :       END DO
    3193           60 :       CALL neighbor_list_iterator_release(nl_iterator)
    3194           60 :       CALL kpoint_release(kpoints_all)
    3195           60 :       DEALLOCATE (dipab, work, basis_set_list)
    3196           60 :       CALL timestop(handle)
    3197              : 
    3198          180 :    END SUBROUTINE build_local_moment_matrix_rs_img
    3199              : 
    3200              : ! **************************************************************************************************
    3201              : !> \brief Image-cell index covering the images of two kpoint environments and their mirrors -R.
    3202              : !>        Needed when the SCF neighbor list reaches further than sab_all (e.g. with HFX), so
    3203              : !>        that real-space matrices of both kinds can be replicated into one set of arrays.
    3204              : !> \param kp_a first kpoint environment (cell index initialised)
    3205              : !> \param kp_b second kpoint environment (cell index initialised)
    3206              : !> \param index_to_cell union image list, dim (3, n_images); allocated here, caller deallocates
    3207              : !> \param cell_to_index mapping of cell coordinates to the union image index (0 = not present);
    3208              : !>        allocated here, caller deallocates
    3209              : !> \author Shridhar Shanbhag
    3210              : ! **************************************************************************************************
    3211           10 :    SUBROUTINE get_cell_index_union(kp_a, kp_b, index_to_cell, cell_to_index)
    3212              :       TYPE(kpoint_type), POINTER                         :: kp_a, kp_b
    3213              :       INTEGER, DIMENSION(:, :), POINTER                  :: index_to_cell
    3214              :       INTEGER, DIMENSION(:, :, :), POINTER               :: cell_to_index
    3215              : 
    3216              :       INTEGER                                            :: i, ic, isgn, n
    3217              :       INTEGER, DIMENSION(3)                              :: cell, itm
    3218           10 :       INTEGER, DIMENSION(:, :), ALLOCATABLE              :: list
    3219           10 :       INTEGER, DIMENSION(:, :), POINTER                  :: itc_a, itc_b
    3220              : 
    3221           10 :       NULLIFY (itc_a, itc_b)
    3222           10 :       CALL get_kpoint_info(kp_a, index_to_cell=itc_a)
    3223           10 :       CALL get_kpoint_info(kp_b, index_to_cell=itc_b)
    3224           10 :       CPASSERT(ASSOCIATED(itc_a))
    3225           10 :       CPASSERT(ASSOCIATED(itc_b))
    3226              : 
    3227           40 :       DO i = 1, 3
    3228         5464 :          itm(i) = MAX(MAXVAL(ABS(itc_a(i, :))), MAXVAL(ABS(itc_b(i, :))))
    3229              :       END DO
    3230           50 :       ALLOCATE (cell_to_index(-itm(1):itm(1), -itm(2):itm(2), -itm(3):itm(3)))
    3231         1564 :       cell_to_index(:, :, :) = 0
    3232           30 :       ALLOCATE (list(3, 2*(SIZE(itc_a, 2) + SIZE(itc_b, 2))))
    3233              : 
    3234              :       ! the images of kp_a keep their order, so index i of kp_a is index i of the union
    3235           20 :       n = 0
    3236           20 :       DO isgn = 1, -1, -2
    3237         1922 :          DO ic = 1, SIZE(itc_a, 2)
    3238         7568 :             cell(:) = isgn*itc_a(:, ic)
    3239         1892 :             IF (cell_to_index(cell(1), cell(2), cell(3)) /= 0) CYCLE
    3240          946 :             n = n + 1
    3241          946 :             cell_to_index(cell(1), cell(2), cell(3)) = n
    3242         3804 :             list(:, n) = cell(:)
    3243              :          END DO
    3244              :       END DO
    3245           20 :       DO isgn = 1, -1, -2
    3246         1754 :          DO ic = 1, SIZE(itc_b, 2)
    3247         6896 :             cell(:) = isgn*itc_b(:, ic)
    3248         1724 :             IF (cell_to_index(cell(1), cell(2), cell(3)) /= 0) CYCLE
    3249            0 :             n = n + 1
    3250            0 :             cell_to_index(cell(1), cell(2), cell(3)) = n
    3251           20 :             list(:, n) = cell(:)
    3252              :          END DO
    3253              :       END DO
    3254              : 
    3255           30 :       ALLOCATE (index_to_cell(3, n))
    3256         3794 :       index_to_cell(:, :) = list(:, 1:n)
    3257           10 :       DEALLOCATE (list)
    3258              : 
    3259           10 :    END SUBROUTINE get_cell_index_union
    3260              : 
    3261              : ! **************************************************************************************************
    3262              : !> \brief Calculate interband k-point dipole moments d_nm(k) = i<u_n|∇_k|u_m>, Berry curvature,
    3263              : !>        momentum and band energies for a periodic system for k-points
    3264              : !> \param qs_env ...
    3265              : !> \param xkp list of kpoints
    3266              : !> \param dipole ...
    3267              : !> \param rcc coordinates about which to calculate the dipole
    3268              : !> \param berry_c berry curvature calculated using Ω^γ_n = -Σ_{m≠n} 2*Im[d^α_nm d^β_mn]
    3269              : !> \param momentum ...
    3270              : !> \param energy ...
    3271              : !> \param do_parallel option to distribute the result in dipole across different MPI ranks
    3272              : !> \author Shridhar Shanbhag
    3273              : ! **************************************************************************************************
    3274            8 :    SUBROUTINE qs_moment_kpoints_deep(qs_env, xkp, dipole, rcc, berry_c, momentum, energy, do_parallel)
    3275              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    3276              :       LOGICAL, OPTIONAL                                  :: do_parallel
    3277              :       LOGICAL                                            :: my_do_parallel, calc_dipole, calc_bc, &
    3278              :                                                             calc_momentum, calc_energy
    3279              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'qs_moment_kpoints_deep'
    3280              :       COMPLEX(KIND=dp)                                   :: phase, tmp_max
    3281            8 :       COMPLEX(KIND=dp), DIMENSION(:, :), ALLOCATABLE     :: C_k, H_k, S_k, D_k, CDC, C_dH_C, &
    3282            8 :                                                             C_dS_C, dH_dk_i, dS_dk_i
    3283            8 :       COMPLEX(KIND=dp), DIMENSION(:, :, :), ALLOCATABLE  :: dip, mom
    3284              :       COMPLEX(KIND=dp), DIMENSION(:, :, :, :, :), &
    3285              :          ALLOCATABLE, OPTIONAL                           :: dipole, momentum
    3286              :       INTEGER                                            :: handle, i_dir, ikp, nkp, &
    3287              :                                                             n_img_scf, n_img_all, n_img_mom, nao, &
    3288              :                                                             num_pe, num_copy, mepos, n, m, mu, &
    3289              :                                                             ispin, nspin
    3290              :       INTEGER, DIMENSION(3)                              :: periodic
    3291            8 :       INTEGER, DIMENSION(:, :), POINTER                  :: index_to_cell_all, index_to_cell_mom
    3292            8 :       INTEGER, DIMENSION(:, :, :), POINTER               :: cell_to_index_all
    3293              :       REAL(KIND=dp), PARAMETER                           :: eps_degenerate = 1.0E-10_dp
    3294              :       REAL(KIND=dp), DIMENSION(3), OPTIONAL              :: rcc
    3295              :       REAL(KIND=dp), DIMENSION(3)                        :: my_rcc
    3296              :       REAL(KIND=dp), DIMENSION(3, 3)                     :: hmat
    3297            8 :       REAL(KIND=dp), DIMENSION(:), ALLOCATABLE           :: eigenvals
    3298            8 :       REAL(KIND=dp), DIMENSION(:, :), ALLOCATABLE        :: bc, xkp
    3299              :       REAL(KIND=dp), DIMENSION(:, :, :, :), &
    3300              :          ALLOCATABLE, OPTIONAL                           :: berry_c
    3301              :       REAL(KIND=dp), DIMENSION(:, :, :), &
    3302              :          ALLOCATABLE, OPTIONAL                           :: energy
    3303              :       REAL(KIND=dp), DIMENSION(:, :, :, :), &
    3304            8 :          ALLOCATABLE                                     :: D_rs, H_rs, S_rs
    3305              :       TYPE(cell_type), POINTER                           :: cell
    3306            8 :       TYPE(dbcsr_p_type), DIMENSION(:, :), POINTER       :: moments_rs_img, matrix_ks_kp, &
    3307            8 :                                                             matrix_s_kp
    3308              :       TYPE(dft_control_type), POINTER                    :: dft_control
    3309              :       TYPE(kpoint_type), POINTER                         :: kpoints_all, kpoints_scf
    3310            8 :       TYPE(mo_set_type), DIMENSION(:), POINTER           :: mos
    3311              :       TYPE(mp_para_env_type), POINTER                    :: para_env
    3312              :       TYPE(neighbor_list_set_p_type), DIMENSION(:), &
    3313            8 :          POINTER                                         :: sab_all
    3314              : 
    3315            8 :       CALL timeset(routineN, handle)
    3316            8 :       calc_dipole = PRESENT(dipole)
    3317            8 :       calc_bc = PRESENT(berry_c)
    3318            8 :       calc_momentum = PRESENT(momentum)
    3319            8 :       calc_energy = PRESENT(energy)
    3320            8 :       my_do_parallel = .FALSE.
    3321            8 :       my_rcc = 0.0_dp
    3322            8 :       IF (PRESENT(do_parallel)) my_do_parallel = do_parallel
    3323            8 :       IF (PRESENT(rcc)) my_rcc = rcc
    3324              : 
    3325              :       CALL get_qs_env(qs_env, &
    3326              :                       matrix_ks_kp=matrix_ks_kp, &
    3327              :                       matrix_s_kp=matrix_s_kp, &
    3328              :                       sab_all=sab_all, &
    3329              :                       cell=cell, &
    3330              :                       kpoints=kpoints_scf, &
    3331              :                       para_env=para_env, &
    3332              :                       dft_control=dft_control, &
    3333            8 :                       mos=mos)
    3334              : 
    3335            8 :       CALL get_mo_set(mo_set=mos(1), nao=nao)
    3336            8 :       CALL get_cell(cell=cell, h=hmat, periodic=periodic)
    3337            8 :       nspin = SIZE(matrix_ks_kp, 1)
    3338            8 :       nkp = SIZE(xkp, 2)
    3339              : 
    3340              :       ! create kpoint environment kpoints_all which contains all neighbor cells R of sab_all
    3341              :       ! (the images of the dipole operator) without considering any lattice symmetry
    3342            8 :       NULLIFY (kpoints_all, index_to_cell_mom)
    3343            8 :       CALL kpoint_create(kpoints_all)
    3344            8 :       CALL kpoint_init_cell_index(kpoints_all, sab_all, para_env, n_img_scf)
    3345            8 :       CALL get_kpoint_info(kpoints_all, index_to_cell=index_to_cell_mom)
    3346            8 :       n_img_mom = SIZE(index_to_cell_mom, 2)
    3347              : 
    3348              :       ! The SCF neighbor list (e.g. extended for HFX) can contain images not in sab_all, so the
    3349              :       ! arrays S_rs, H_rs, D_rs are indexed by the union of both image sets (incl. mirrors -R)
    3350            8 :       CALL get_cell_index_union(kpoints_all, kpoints_scf, index_to_cell_all, cell_to_index_all)
    3351            8 :       n_img_all = SIZE(index_to_cell_all, 2)
    3352              : 
    3353            8 :       NULLIFY (moments_rs_img)
    3354            8 :       CALL dbcsr_allocate_matrix_set(moments_rs_img, 3, n_img_mom)
    3355              :       ! D_μ,ν = <φ_μ|r|φ_ν>
    3356            8 :       CALL build_local_moment_matrix_rs_img(qs_env, moments_rs_img, rcc=my_rcc)
    3357              : 
    3358           80 :       ALLOCATE (S_rs(1, nao, nao, n_img_all), H_rs(nspin, nao, nao, n_img_all), source=0.0_dp)
    3359           40 :       ALLOCATE (D_rs(3, nao, nao, n_img_all), source=0.0_dp)
    3360              : 
    3361              :       ! Convert real-space dbcsr matrices into arrays
    3362            8 :       CALL replicate_rs_matrices(matrix_s_kp, kpoints_scf, S_rs, cell_to_index_all)
    3363            8 :       CALL replicate_rs_matrices(matrix_ks_kp, kpoints_scf, H_rs, cell_to_index_all)
    3364            8 :       CALL replicate_rs_matrices(moments_rs_img, kpoints_all, D_rs, cell_to_index_all)
    3365              : 
    3366            8 :       mepos = 0
    3367            8 :       num_pe = 1
    3368            8 :       num_copy = nkp
    3369            8 :       IF (my_do_parallel) THEN
    3370            8 :          mepos = para_env%mepos
    3371            8 :          num_pe = para_env%num_pe
    3372            8 :          num_copy = CEILING(REAL(nkp)/num_pe)
    3373              :       END IF
    3374              : 
    3375           44 :       IF (calc_dipole) ALLOCATE (dipole(nspin, num_copy, 3, nao, nao), source=z_zero)
    3376           38 :       IF (calc_bc) ALLOCATE (berry_c(nspin, num_copy, 3, nao), source=0.0_dp)
    3377           20 :       IF (calc_momentum) ALLOCATE (momentum(nspin, num_copy, 3, nao, nao), source=z_zero)
    3378           16 :       IF (calc_energy) ALLOCATE (energy(nspin, num_copy, nao), source=0.0_dp)
    3379              : 
    3380              : !$OMP PARALLEL DEFAULT(NONE) PRIVATE(ikp, S_k, H_k, eigenvals, C_k, ispin, n, m, &
    3381              : !$OMP i_dir, dS_dk_i, dH_dk_i, D_k, dip, bc, mom, C_dS_C, C_dH_C, CDC, tmp_max, phase) &
    3382              : !$OMP SHARED(num_pe, mepos, dipole, berry_c, momentum, energy, nao, nspin, periodic, nkp, &
    3383            8 : !$OMP xkp, S_rs, H_rs, D_rs, index_to_cell_all, hmat, calc_dipole, calc_bc, calc_momentum, calc_energy)
    3384              :       ALLOCATE (dS_dk_i(nao, nao), C_dS_C(nao, nao), dH_dk_i(nao, nao), C_dH_C(nao, nao), source=z_zero)
    3385              :       ALLOCATE (CDC(nao, nao), S_k(nao, nao), H_k(nao, nao), source=z_zero)
    3386              :       ALLOCATE (C_k(nao, nao), D_k(nao, nao), source=z_zero)
    3387              :       ALLOCATE (eigenvals(nao), source=0.0_dp)
    3388              :       IF (calc_dipole .OR. calc_bc) ALLOCATE (dip(3, nao, nao), source=z_zero)
    3389              :       IF (calc_bc) ALLOCATE (bc(3, nao), source=0.0_dp)
    3390              :       IF (calc_momentum) ALLOCATE (mom(3, nao, nao), source=z_zero)
    3391              : !$OMP DO COLLAPSE(2)
    3392              :       DO ispin = 1, nspin
    3393              :          DO ikp = 1, nkp
    3394              :             IF (MOD(ikp - 1, num_pe) /= mepos) CYCLE
    3395              : 
    3396              :             ! S^R -> S(k), H^R -> H(k)
    3397              :             S_k = 0
    3398              :             H_k = 0
    3399              :             CALL rs_to_kp(S_rs(1, :, :, :), S_k, index_to_cell_all, xkp(:, ikp))
    3400              :             CALL rs_to_kp(H_rs(ispin, :, :, :), H_k, index_to_cell_all, xkp(:, ikp))
    3401              : 
    3402              :             ! Diagonalize H(k)C(k) = S(k)C(k)ε(k)
    3403              :             CALL geeig_right(H_k, S_k, eigenvals, C_k)
    3404              : 
    3405              :             ! To have a smooth complex phase of C(k) as function of k, for every n, we force
    3406              :             ! the largest C_μ,n(k) to be real.
    3407              :             ! This is important to have a continuous dipole moment d_nm(k) as a function of k
    3408              :             DO n = 1, nao
    3409              :                tmp_max = C_k(1, n)
    3410              :                DO mu = 1, nao
    3411              :                   IF (ABS(C_k(mu, n)) < ABS(tmp_max)) CYCLE
    3412              :                   tmp_max = C_k(mu, n)
    3413              :                END DO
    3414              :                phase = tmp_max/ABS(tmp_max)
    3415              :                C_k(:, n) = C_k(:, n)/phase
    3416              :             END DO
    3417              : 
    3418              :             ! reset per k-point/spin: degenerate pairs are skipped below and must not keep
    3419              :             ! values from a previous iteration
    3420              :             IF (calc_dipole .OR. calc_bc) dip = z_zero
    3421              :             IF (calc_momentum) mom = z_zero
    3422              : 
    3423              :             DO i_dir = 1, 3 ! d^x, d^y, d^z
    3424              : 
    3425              :                IF (periodic(i_dir) == 0) CYCLE
    3426              :                ! ∇ S(k) = Σ_R iR S^R e^(ikR), ∇ H(k) = Σ_R iR H^R e^(ikR)
    3427              :                CALL rs_to_kp(S_rs(1, :, :, :), dS_dk_i, index_to_cell_all, xkp(:, ikp), i_dir, hmat)
    3428              :                CALL rs_to_kp(H_rs(ispin, :, :, :), dH_dk_i, index_to_cell_all, xkp(:, ikp), i_dir, hmat)
    3429              : 
    3430              :                ! Σ_R D^R e^(ikR) = D(k), D_μ,ν = <φ_μ|r|φ_ν>
    3431              :                CALL rs_to_kp(D_rs(i_dir, :, :, :), D_k(:, :), index_to_cell_all, xkp(:, ikp))
    3432              : 
    3433              :                ! Basis transform to Kohn-Sham basis: (C^H) ∇ S C, (C^H) ∇ H C, (C^H) D C
    3434              :                CALL gemm_square(C_k, 'C', dS_dk_i, 'N', C_k, 'N', C_dS_C)
    3435              :                CALL gemm_square(C_k, 'C', dH_dk_i, 'N', C_k, 'N', C_dH_C)
    3436              :                CALL gemm_square(C_k, 'C', D_k, 'N', C_k, 'N', CDC)
    3437              : 
    3438              :                ! Compute the dipole (n ≠ m)
    3439              :                !    d_nm (k) = - i/(ε_n - ε_m) [ C^† dH(k)/dk C ]_nm
    3440              :                !               + i ε_n/(ε_n - ε_m) [ C^† dS(k)/dk C ]_nm + [ C^†D(k)C ]_nm
    3441              :                ! and the momentum
    3442              :                !    p_nm = <ψ_n|-iħ∇_r|ψ_m> = <u_n|(ħk - iħ∇_r)|u_m>
    3443              :                !         = i d_nm (ε_n - ε_m) + ∇_k ε_n δ_nm
    3444              :                !         = [ C^† dH(k)/dk C ]_nm - ε_n [ C^† dS(k)/dk C ]_nm
    3445              :                !           + i (ε_n - ε_m) [ (C^H)D(k)C ]_nm
    3446              :                DO n = 1, nao
    3447              :                   DO m = 1, nao
    3448              :                      IF (n == m) THEN
    3449              :                         ! diagonal elements of the dipole would need to be computed from
    3450              :                         ! a numerical k-derivative which is not implemented
    3451              :                         IF (calc_momentum) THEN
    3452              :                            mom(i_dir, n, n) = DBLE(C_dH_C(n, n)) - DBLE(eigenvals(n)*C_dS_C(n, n))
    3453              :                         END IF
    3454              :                      ELSE
    3455              :                         IF ((calc_dipole .OR. calc_bc) .AND. (ABS(eigenvals(n) - eigenvals(m)) >= eps_degenerate)) THEN
    3456              :                            dip(i_dir, n, m) = -gaussi*C_dH_C(n, m)/(eigenvals(n) - eigenvals(m)) &
    3457              :                                               + gaussi*eigenvals(n)*C_dS_C(n, m)/(eigenvals(n) - eigenvals(m)) &
    3458              :                                               + CDC(n, m)
    3459              :                         END IF
    3460              :                         IF (calc_momentum) THEN
    3461              :                            mom(i_dir, n, m) = C_dH_C(n, m) - eigenvals(n)*C_dS_C(n, m) &
    3462              :                                               + gaussi*CDC(n, m)*(eigenvals(n) - eigenvals(m))
    3463              :                         END IF
    3464              :                      END IF
    3465              :                   END DO
    3466              :                END DO
    3467              :             END DO
    3468              :             ! Compute the Berry curvature from the dipoles
    3469              :             ! Ω^γ_n = -Σ_{m≠n} 2*Im[d^α_nm d^β_mn], where (α, β, γ) are cyclic in {x, y, z}
    3470              :             IF (calc_bc) THEN
    3471              :                bc = 0.0_dp
    3472              :                DO i_dir = 1, 3
    3473              :                   DO n = 1, nao
    3474              :                      DO m = 1, nao
    3475              :                         IF (n == m) CYCLE
    3476              :                         bc(i_dir, n) = bc(i_dir, n) &
    3477              :                                        - 2*AIMAG(dip(1 + MOD(i_dir, 3), n, m)*dip(1 + MOD(i_dir + 1, 3), m, n))
    3478              :                      END DO
    3479              :                   END DO
    3480              :                END DO
    3481              :             END IF
    3482              :             ! Store the dipoles, momentum, berry curvature and energies for each MPI rank
    3483              :             IF (calc_dipole) dipole(ispin, CEILING(REAL(ikp)/num_pe), :, :, :) = dip(:, :, :)
    3484              :             IF (calc_momentum) momentum(ispin, CEILING(REAL(ikp)/num_pe), :, :, :) = mom(:, :, :)
    3485              :             IF (calc_bc) berry_c(ispin, CEILING(REAL(ikp)/num_pe), :, :) = bc(:, :)
    3486              :             IF (calc_energy) energy(ispin, CEILING(REAL(ikp)/num_pe), :) = eigenvals(:)
    3487              :          END DO
    3488              :       END DO
    3489              : !$OMP END DO
    3490              :       DEALLOCATE (dS_dk_i, C_dS_C, dH_dk_i, C_dH_C, CDC, S_k, H_k, C_k, D_k, eigenvals)
    3491              :       IF (calc_dipole .OR. calc_bc) DEALLOCATE (dip)
    3492              :       IF (calc_bc) DEALLOCATE (bc)
    3493              :       IF (calc_momentum) DEALLOCATE (mom)
    3494              : !$OMP END PARALLEL
    3495            8 :       DEALLOCATE (S_rs, H_rs, D_rs)
    3496            8 :       DEALLOCATE (index_to_cell_all, cell_to_index_all)
    3497            8 :       CALL dbcsr_deallocate_matrix_set(moments_rs_img)
    3498            8 :       CALL kpoint_release(kpoints_all)
    3499            8 :       CALL timestop(handle)
    3500           32 :    END SUBROUTINE qs_moment_kpoints_deep
    3501              : 
    3502              : ! **************************************************************************************************
    3503              : !> \brief Add the spin-orbit coupling operator V^SOC(k) = sigma . V(k) (or its k-derivative) to a
    3504              : !>        2*nao spinor matrix. The real-space components VSOC_rs store V^SOC without the imaginary
    3505              : !>        unit (real, antisymmetric), so the physical Hermitian component is W_c = i*V_c(k). The
    3506              : !>        Pauli placement mirrors H_KS_spinor_kp in post_scf_bandstructure_utils.F:
    3507              : !>        uu += W_z ; dd += -W_z ; ud += W_x + i*W_y ; du += W_x - i*W_y.
    3508              : !> \param mat_spinor 2*nao spinor matrix to be updated in place
    3509              : !> \param VSOC_rs real-space SOC images, dim (3=xyz, nao, nao, n_img)
    3510              : !> \param index_to_cell image-cell coordinates
    3511              : !> \param xkp k-point
    3512              : !> \param nao number of atomic orbitals (block size)
    3513              : !> \param deriv_direction optional cartesian direction for the k-derivative of V^SOC
    3514              : !> \param hmat cell matrix, required for the derivative
    3515              : !> \author Shridhar Shanbhag
    3516              : ! **************************************************************************************************
    3517            4 :    SUBROUTINE add_VSOC_to_spinor(mat_spinor, VSOC_rs, index_to_cell, xkp, nao, &
    3518              :                                  deriv_direction, hmat)
    3519              :       COMPLEX(KIND=dp), DIMENSION(:, :), INTENT(INOUT)   :: mat_spinor
    3520              :       REAL(KIND=dp), DIMENSION(:, :, :, :), INTENT(IN)   :: VSOC_rs
    3521              :       INTEGER, DIMENSION(:, :), POINTER                  :: index_to_cell
    3522              :       REAL(KIND=dp), DIMENSION(3), INTENT(IN)            :: xkp
    3523              :       INTEGER, INTENT(IN)                                :: nao
    3524              :       INTEGER, INTENT(IN), OPTIONAL                      :: deriv_direction
    3525              :       REAL(KIND=dp), DIMENSION(3, 3), INTENT(IN), &
    3526              :          OPTIONAL                                        :: hmat
    3527              : 
    3528            4 :       COMPLEX(KIND=dp), DIMENSION(:, :), ALLOCATABLE     :: Vx, Vy, Vz
    3529              :       INTEGER                                            :: s
    3530              : 
    3531            4 :       s = nao + 1
    3532           32 :       ALLOCATE (Vx(nao, nao), Vy(nao, nao), Vz(nao, nao), source=z_zero)
    3533              : 
    3534            4 :       IF (PRESENT(deriv_direction)) THEN
    3535            3 :          CALL rs_to_kp(VSOC_rs(1, :, :, :), Vx, index_to_cell, xkp, deriv_direction, hmat)
    3536            3 :          CALL rs_to_kp(VSOC_rs(2, :, :, :), Vy, index_to_cell, xkp, deriv_direction, hmat)
    3537            3 :          CALL rs_to_kp(VSOC_rs(3, :, :, :), Vz, index_to_cell, xkp, deriv_direction, hmat)
    3538              :       ELSE
    3539            1 :          CALL rs_to_kp(VSOC_rs(1, :, :, :), Vx, index_to_cell, xkp)
    3540            1 :          CALL rs_to_kp(VSOC_rs(2, :, :, :), Vy, index_to_cell, xkp)
    3541            1 :          CALL rs_to_kp(VSOC_rs(3, :, :, :), Vz, index_to_cell, xkp)
    3542              :       END IF
    3543              : 
    3544              :       ! physical component operators W_c = i * V_c (VSOC_rs stores V without the imaginary unit)
    3545          292 :       Vx(:, :) = gaussi*Vx(:, :)
    3546          292 :       Vy(:, :) = gaussi*Vy(:, :)
    3547          292 :       Vz(:, :) = gaussi*Vz(:, :)
    3548              : 
    3549          292 :       mat_spinor(1:nao, 1:nao) = mat_spinor(1:nao, 1:nao) + Vz(:, :)
    3550          292 :       mat_spinor(s:2*nao, s:2*nao) = mat_spinor(s:2*nao, s:2*nao) - Vz(:, :)
    3551          292 :       mat_spinor(1:nao, s:2*nao) = mat_spinor(1:nao, s:2*nao) + Vx(:, :) + gaussi*Vy(:, :)
    3552          292 :       mat_spinor(s:2*nao, 1:nao) = mat_spinor(s:2*nao, 1:nao) + Vx(:, :) - gaussi*Vy(:, :)
    3553              : 
    3554            4 :       DEALLOCATE (Vx, Vy, Vz)
    3555              : 
    3556            4 :    END SUBROUTINE add_VSOC_to_spinor
    3557              : 
    3558              : ! **************************************************************************************************
    3559              : !> \brief Calculate interband k-point dipole moments d_nm(k) = i<u_n|∇_k|u_m>, Berry curvature,
    3560              : !>        momentum and band energies for a periodic system for k-points with spin-orbit coupling
    3561              : !>        (SOC) in the 2*nao spinor basis, via the length-gauge sum rule.
    3562              : !>        SOC enters both the Hamiltonian and the velocity operator (the k-derivative of V^SOC is
    3563              : !>        included). Mirrors qs_moment_kpoints_deep but promoted to spinor space; the two spin
    3564              : !>        channels are merged into 2*nao spinor bands (returned with spin dimension 1).
    3565              : !> \param qs_env ...
    3566              : !> \param xkp k-points at which the dipoles are evaluated
    3567              : !> \param dipole optional output dipoles, dim (1, k copy, 3, 2*nao, 2*nao)
    3568              : !> \param rcc reference point for the local dipole operator (interband dipoles are origin-independent)
    3569              : !> \param berry_c optional SOC Berry curvature, dim (1, k copy, 3, 2*nao)
    3570              : !> \param momentum optional SOC momentum matrix elements p_nm, dim (1, k copy, 3, 2*nao, 2*nao)
    3571              : !> \param energy optional spinor band energies, dim (1, k copy, 2*nao)
    3572              : !> \param do_parallel distribute k-points over MPI ranks
    3573              : !> \author Shridhar Shanbhag
    3574              : ! **************************************************************************************************
    3575            2 :    SUBROUTINE qs_moment_kpoints_deep_soc(qs_env, xkp, dipole, rcc, berry_c, momentum, energy, do_parallel)
    3576              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    3577              :       REAL(KIND=dp), DIMENSION(:, :), ALLOCATABLE        :: xkp
    3578              :       COMPLEX(KIND=dp), DIMENSION(:, :, :, :, :), &
    3579              :          ALLOCATABLE, OPTIONAL                           :: dipole
    3580              :       REAL(KIND=dp), DIMENSION(3), OPTIONAL              :: rcc
    3581              :       REAL(KIND=dp), DIMENSION(:, :, :, :), &
    3582              :          ALLOCATABLE, OPTIONAL                           :: berry_c
    3583              :       COMPLEX(KIND=dp), DIMENSION(:, :, :, :, :), &
    3584              :          ALLOCATABLE, OPTIONAL                           :: momentum
    3585              :       REAL(KIND=dp), DIMENSION(:, :, :), &
    3586              :          ALLOCATABLE, OPTIONAL                           :: energy
    3587              :       LOGICAL, OPTIONAL                                  :: do_parallel
    3588              : 
    3589              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'qs_moment_kpoints_deep_soc'
    3590              :       REAL(KIND=dp), PARAMETER                           :: eps_degenerate = 1.0E-10_dp
    3591              : 
    3592              :       COMPLEX(KIND=dp)                                   :: phase, tmp_max
    3593            2 :       COMPLEX(KIND=dp), DIMENSION(:, :), ALLOCATABLE     :: D_k, dHd_k, dHu_k, dS_k, Hd_k, Hu_k, &
    3594            2 :                                                             S_k, D2, dH2, dS2, H2, S2, W, WD2W, &
    3595            2 :                                                             WdH2W, WdS2W
    3596            2 :       COMPLEX(KIND=dp), DIMENSION(:, :, :), ALLOCATABLE  :: dip, mom
    3597              :       INTEGER                                            :: handle, i_dir, ikp, mepos, mu, m, n, &
    3598              :                                                             n_img_all, n_img_mom, nao, nao2, nimg, nkp, &
    3599              :                                                             nspin, num_copy, num_pe, s
    3600              :       INTEGER, DIMENSION(3)                              :: periodic
    3601            2 :       INTEGER, DIMENSION(:, :), POINTER                  :: index_to_cell_all, index_to_cell_mom
    3602            2 :       INTEGER, DIMENSION(:, :, :), POINTER               :: cell_to_index_all
    3603              :       LOGICAL                                            :: calc_bc, calc_dipole, calc_energy, &
    3604              :                                                             calc_momentum, my_do_parallel
    3605              :       REAL(KIND=dp), DIMENSION(3)                        :: my_rcc
    3606              :       REAL(KIND=dp), DIMENSION(3, 3)                     :: hmat
    3607            2 :       REAL(KIND=dp), DIMENSION(:), ALLOCATABLE           :: eigenvals
    3608            2 :       REAL(KIND=dp), DIMENSION(:, :), ALLOCATABLE        :: bc
    3609            2 :       REAL(KIND=dp), DIMENSION(:, :, :, :), ALLOCATABLE  :: D_rs, H_rs, S_rs, VSOC_rs
    3610              :       TYPE(cell_type), POINTER                           :: cell
    3611            2 :       TYPE(dbcsr_p_type), DIMENSION(:, :), POINTER       :: mat_V_SOC_xyz, matrix_ks_kp, &
    3612            2 :                                                             matrix_s_kp, moments_rs_img
    3613              :       TYPE(dft_control_type), POINTER                    :: dft_control
    3614              :       TYPE(kpoint_type), POINTER                         :: kpoints_all, kpoints_scf
    3615            2 :       TYPE(mo_set_type), DIMENSION(:), POINTER           :: mos
    3616              :       TYPE(mp_para_env_type), POINTER                    :: para_env
    3617              :       TYPE(neighbor_list_set_p_type), DIMENSION(:), &
    3618            2 :          POINTER                                         :: sab_all
    3619              : 
    3620            2 :       CALL timeset(routineN, handle)
    3621            2 :       calc_dipole = PRESENT(dipole)
    3622            2 :       calc_bc = PRESENT(berry_c)
    3623            2 :       calc_momentum = PRESENT(momentum)
    3624            2 :       calc_energy = PRESENT(energy)
    3625            2 :       my_do_parallel = .FALSE.
    3626            2 :       my_rcc = 0.0_dp
    3627            2 :       IF (PRESENT(do_parallel)) my_do_parallel = do_parallel
    3628            2 :       IF (PRESENT(rcc)) my_rcc = rcc
    3629              : 
    3630            2 :       NULLIFY (cell, cell_to_index_all, dft_control, index_to_cell_all, index_to_cell_mom, kpoints_all, &
    3631            2 :                kpoints_scf, mat_V_SOC_xyz, matrix_ks_kp, matrix_s_kp, moments_rs_img, mos, &
    3632            2 :                para_env, sab_all)
    3633              : 
    3634              :       CALL get_qs_env(qs_env, &
    3635              :                       matrix_ks_kp=matrix_ks_kp, &
    3636              :                       matrix_s_kp=matrix_s_kp, &
    3637              :                       sab_all=sab_all, &
    3638              :                       cell=cell, &
    3639              :                       kpoints=kpoints_scf, &
    3640              :                       para_env=para_env, &
    3641              :                       dft_control=dft_control, &
    3642            2 :                       mos=mos)
    3643              : 
    3644            2 :       CALL get_mo_set(mo_set=mos(1), nao=nao)
    3645            2 :       CALL get_cell(cell=cell, h=hmat, periodic=periodic)
    3646            2 :       nspin = SIZE(matrix_ks_kp, 1)
    3647            2 :       nkp = SIZE(xkp, 2)
    3648            2 :       nao2 = 2*nao
    3649            2 :       s = nao + 1
    3650              : 
    3651              :       ! create kpoint environment kpoints_all which contains all neighbor cells R of sab_all
    3652              :       ! (the images of the dipole operator)
    3653            2 :       CALL kpoint_create(kpoints_all)
    3654            2 :       CALL kpoint_init_cell_index(kpoints_all, sab_all, para_env, nimg)
    3655            2 :       CALL get_kpoint_info(kpoints_all, index_to_cell=index_to_cell_mom)
    3656            2 :       n_img_mom = SIZE(index_to_cell_mom, 2)
    3657              : 
    3658              :       ! The SCF neighbor list (e.g. extended for HFX) can contain images not in sab_all, so the
    3659              :       ! arrays S_rs, H_rs, D_rs, VSOC_rs are indexed by the union of both image sets (incl. -R)
    3660            2 :       CALL get_cell_index_union(kpoints_all, kpoints_scf, index_to_cell_all, cell_to_index_all)
    3661            2 :       n_img_all = SIZE(index_to_cell_all, 2)
    3662              : 
    3663            2 :       NULLIFY (moments_rs_img)
    3664            2 :       CALL dbcsr_allocate_matrix_set(moments_rs_img, 3, n_img_mom)
    3665              :       ! D_mu,nu = <phi_mu|r|phi_nu>
    3666            2 :       CALL build_local_moment_matrix_rs_img(qs_env, moments_rs_img, rcc=my_rcc)
    3667              : 
    3668              :       ! Real-space SOC operator V^SOC_c^R (c=x,y,z), stored real and antisymmetric on sab_orb.
    3669              :       ! Aborts inside if the atoms carry no pseudopotential SOC parameters.
    3670            2 :       CALL V_SOC_xyz_from_pseudopotential(qs_env, mat_V_SOC_xyz)
    3671              : 
    3672           20 :       ALLOCATE (S_rs(1, nao, nao, n_img_all), H_rs(nspin, nao, nao, n_img_all), source=0.0_dp)
    3673           16 :       ALLOCATE (D_rs(3, nao, nao, n_img_all), VSOC_rs(3, nao, nao, n_img_all), source=0.0_dp)
    3674              : 
    3675              :       ! Convert real-space dbcsr matrices into arrays (S/H on the SCF kpoints, D on kpoints_all)
    3676            2 :       CALL replicate_rs_matrices(matrix_s_kp, kpoints_scf, S_rs, cell_to_index_all)
    3677            2 :       CALL replicate_rs_matrices(matrix_ks_kp, kpoints_scf, H_rs, cell_to_index_all)
    3678            2 :       CALL replicate_rs_matrices(moments_rs_img, kpoints_all, D_rs, cell_to_index_all)
    3679            2 :       CALL replicate_rs_matrices(mat_V_SOC_xyz, kpoints_scf, VSOC_rs, cell_to_index_all)
    3680              : 
    3681            2 :       mepos = 0
    3682            2 :       num_pe = 1
    3683            2 :       num_copy = nkp
    3684            2 :       IF (my_do_parallel) THEN
    3685            2 :          mepos = para_env%mepos
    3686            2 :          num_pe = para_env%num_pe
    3687            2 :          num_copy = CEILING(REAL(nkp)/num_pe)
    3688              :       END IF
    3689              : 
    3690           10 :       IF (calc_dipole) ALLOCATE (dipole(1, num_copy, 3, nao2, nao2), source=z_zero)
    3691            8 :       IF (calc_bc) ALLOCATE (berry_c(1, num_copy, 3, nao2), source=0.0_dp)
    3692            2 :       IF (calc_momentum) ALLOCATE (momentum(1, num_copy, 3, nao2, nao2), source=z_zero)
    3693            2 :       IF (calc_energy) ALLOCATE (energy(1, num_copy, nao2), source=0.0_dp)
    3694              : 
    3695              : !$OMP PARALLEL DEFAULT(NONE) PRIVATE(ikp, i_dir, n, m, mu, tmp_max, phase, eigenvals, &
    3696              : !$OMP S_k, Hu_k, Hd_k, D_k, dS_k, dHu_k, dHd_k, S2, H2, D2, dS2, dH2, W, &
    3697              : !$OMP WdH2W, WdS2W, WD2W, dip, bc, mom) &
    3698              : !$OMP SHARED(num_pe, mepos, dipole, berry_c, momentum, energy, nao, nao2, s, nspin, periodic, &
    3699              : !$OMP nkp, xkp, S_rs, H_rs, D_rs, VSOC_rs, index_to_cell_all, hmat, calc_dipole, calc_bc, &
    3700            2 : !$OMP calc_momentum, calc_energy)
    3701              :       ALLOCATE (S_k(nao, nao), Hu_k(nao, nao), Hd_k(nao, nao), D_k(nao, nao), source=z_zero)
    3702              :       ALLOCATE (dS_k(nao, nao), dHu_k(nao, nao), dHd_k(nao, nao), source=z_zero)
    3703              :       ALLOCATE (S2(nao2, nao2), H2(nao2, nao2), D2(nao2, nao2), dS2(nao2, nao2), &
    3704              :                 dH2(nao2, nao2), W(nao2, nao2), source=z_zero)
    3705              :       ALLOCATE (WdH2W(nao2, nao2), WdS2W(nao2, nao2), WD2W(nao2, nao2), source=z_zero)
    3706              :       ALLOCATE (eigenvals(nao2), source=0.0_dp)
    3707              :       IF (calc_dipole .OR. calc_bc) ALLOCATE (dip(3, nao2, nao2), source=z_zero)
    3708              :       IF (calc_bc) ALLOCATE (bc(3, nao2), source=0.0_dp)
    3709              :       IF (calc_momentum) ALLOCATE (mom(3, nao2, nao2), source=z_zero)
    3710              : !$OMP DO
    3711              :       DO ikp = 1, nkp
    3712              :          IF (MOD(ikp - 1, num_pe) /= mepos) CYCLE
    3713              : 
    3714              :          ! S(k), H_up(k), H_dn(k)
    3715              :          CALL rs_to_kp(S_rs(1, :, :, :), S_k, index_to_cell_all, xkp(:, ikp))
    3716              :          CALL rs_to_kp(H_rs(1, :, :, :), Hu_k, index_to_cell_all, xkp(:, ikp))
    3717              :          CALL rs_to_kp(H_rs(nspin, :, :, :), Hd_k, index_to_cell_all, xkp(:, ikp))
    3718              : 
    3719              :          ! spinor overlap S2 = blockdiag(S, S)
    3720              :          S2 = z_zero
    3721              :          S2(1:nao, 1:nao) = S_k(:, :)
    3722              :          S2(s:nao2, s:nao2) = S_k(:, :)
    3723              : 
    3724              :          ! spinor Hamiltonian H2 = blockdiag(H_up, H_dn) + V^SOC(k)
    3725              :          H2 = z_zero
    3726              :          H2(1:nao, 1:nao) = Hu_k(:, :)
    3727              :          H2(s:nao2, s:nao2) = Hd_k(:, :)
    3728              :          CALL add_VSOC_to_spinor(H2, VSOC_rs, index_to_cell_all, xkp(:, ikp), nao)
    3729              : 
    3730              :          ! Diagonalize H2 W = S2 W E  ->  spinor bands and AO-spinor eigenvectors
    3731              :          CALL geeig_right(H2, S2, eigenvals, W)
    3732              : 
    3733              :          ! To have a smooth complex phase of C(k) as function of k, for every n, we force
    3734              :          ! the largest C_μ,n(k) to be real.
    3735              :          ! This is important to have a continuous dipole moment d_nm(k) as a function of k
    3736              :          DO n = 1, nao2
    3737              :             tmp_max = W(1, n)
    3738              :             DO mu = 1, nao2
    3739              :                IF (ABS(W(mu, n)) < ABS(tmp_max)) CYCLE
    3740              :                tmp_max = W(mu, n)
    3741              :             END DO
    3742              :             phase = tmp_max/ABS(tmp_max)
    3743              :             W(:, n) = W(:, n)/phase
    3744              :          END DO
    3745              : 
    3746              :          IF (calc_dipole .OR. calc_bc) dip = z_zero
    3747              :          IF (calc_momentum) mom = z_zero
    3748              :          DO i_dir = 1, 3 ! d^x, d^y, d^z
    3749              : 
    3750              :             IF (periodic(i_dir) == 0) CYCLE
    3751              : 
    3752              :             ! spinor overlap derivative dS2 = blockdiag(grad S, grad S)
    3753              :             CALL rs_to_kp(S_rs(1, :, :, :), dS_k, index_to_cell_all, xkp(:, ikp), i_dir, hmat)
    3754              :             dS2 = z_zero
    3755              :             dS2(1:nao, 1:nao) = dS_k(:, :)
    3756              :             dS2(s:nao2, s:nao2) = dS_k(:, :)
    3757              : 
    3758              :             ! spinor Hamiltonian derivative dH2 = blockdiag(grad H_up, grad H_dn) + grad V^SOC
    3759              :             CALL rs_to_kp(H_rs(1, :, :, :), dHu_k, index_to_cell_all, xkp(:, ikp), i_dir, hmat)
    3760              :             CALL rs_to_kp(H_rs(nspin, :, :, :), dHd_k, index_to_cell_all, xkp(:, ikp), i_dir, hmat)
    3761              :             dH2 = z_zero
    3762              :             dH2(1:nao, 1:nao) = dHu_k(:, :)
    3763              :             dH2(s:nao2, s:nao2) = dHd_k(:, :)
    3764              :             CALL add_VSOC_to_spinor(dH2, VSOC_rs, index_to_cell_all, xkp(:, ikp), nao, i_dir, hmat)
    3765              : 
    3766              :             ! spinor dipole operator D2 = blockdiag(D(k), D(k))
    3767              :             CALL rs_to_kp(D_rs(i_dir, :, :, :), D_k, index_to_cell_all, xkp(:, ikp))
    3768              :             D2 = z_zero
    3769              :             D2(1:nao, 1:nao) = D_k(:, :)
    3770              :             D2(s:nao2, s:nao2) = D_k(:, :)
    3771              : 
    3772              :             ! Basis transform to the spinor eigenbasis: W^H (grad S) W, W^H (grad H) W, W^H D W
    3773              :             CALL gemm_square(W, 'C', dH2, 'N', W, 'N', WdH2W)
    3774              :             CALL gemm_square(W, 'C', dS2, 'N', W, 'N', WdS2W)
    3775              :             CALL gemm_square(W, 'C', D2, 'N', W, 'N', WD2W)
    3776              : 
    3777              :             ! d_nm(k) = -i/(E_n-E_m)[W^H grad H W]_nm + i E_n/(E_n-E_m)[W^H grad S W]_nm + [W^H D W]_nm
    3778              :             ! Degenerate spinor pairs (|E_n-E_m| < eps_degenerate, e.g. Kramers) are skipped for the
    3779              :             ! dipole (and hence the Berry curvature): the length-gauge sum rule needs degenerate
    3780              :             ! perturbation theory there. The momentum below is well defined and is still computed.
    3781              :             ! Momentum (grad H includes grad V^SOC, i.e. the SOC part of the velocity):
    3782              :             !    p_nm = i d_nm (E_n - E_m) + grad_k E_n delta_nm
    3783              :             !         = [W^H grad H W]_nm - E_n [W^H grad S W]_nm + i (E_n - E_m) [W^H D W]_nm
    3784              :             DO n = 1, nao2
    3785              :                DO m = 1, nao2
    3786              :                   IF (n == m) THEN
    3787              :                      ! diagonal elements of the dipole would need to be computed from
    3788              :                      ! a numerical k-derivative which is not implemented
    3789              :                      IF (calc_momentum) THEN
    3790              :                         mom(i_dir, n, n) = DBLE(WdH2W(n, n)) - DBLE(eigenvals(n)*WdS2W(n, n))
    3791              :                      END IF
    3792              :                   ELSE
    3793              :                      IF ((calc_dipole .OR. calc_bc) .AND. (ABS(eigenvals(n) - eigenvals(m)) >= eps_degenerate)) THEN
    3794              :                         dip(i_dir, n, m) = -gaussi*WdH2W(n, m)/(eigenvals(n) - eigenvals(m)) &
    3795              :                                            + gaussi*eigenvals(n)*WdS2W(n, m)/(eigenvals(n) - eigenvals(m)) &
    3796              :                                            + WD2W(n, m)
    3797              :                      END IF
    3798              :                      IF (calc_momentum) THEN
    3799              :                         mom(i_dir, n, m) = WdH2W(n, m) - eigenvals(n)*WdS2W(n, m) &
    3800              :                                            + gaussi*WD2W(n, m)*(eigenvals(n) - eigenvals(m))
    3801              :                      END IF
    3802              :                   END IF
    3803              :                END DO
    3804              :             END DO
    3805              :          END DO
    3806              : 
    3807              :          ! Berry curvature Omega^gamma_n = -Sum_{m/=n} 2*Im[d^alpha_nm d^beta_mn], (alpha,beta,gamma) cyclic
    3808              :          IF (calc_bc) THEN
    3809              :             bc = 0.0_dp
    3810              :             DO i_dir = 1, 3
    3811              :                DO n = 1, nao2
    3812              :                   DO m = 1, nao2
    3813              :                      IF (n == m) CYCLE
    3814              :                      bc(i_dir, n) = bc(i_dir, n) &
    3815              :                                     - 2*AIMAG(dip(1 + MOD(i_dir, 3), n, m)*dip(1 + MOD(i_dir + 1, 3), m, n))
    3816              :                   END DO
    3817              :                END DO
    3818              :             END DO
    3819              :          END IF
    3820              : 
    3821              :          ! Store the dipoles, momentum, berry curvature and energies for each MPI rank
    3822              :          IF (calc_dipole) dipole(1, CEILING(REAL(ikp)/num_pe), :, :, :) = dip(:, :, :)
    3823              :          IF (calc_momentum) momentum(1, CEILING(REAL(ikp)/num_pe), :, :, :) = mom(:, :, :)
    3824              :          IF (calc_bc) berry_c(1, CEILING(REAL(ikp)/num_pe), :, :) = bc(:, :)
    3825              :          IF (calc_energy) energy(1, CEILING(REAL(ikp)/num_pe), :) = eigenvals(:)
    3826              :       END DO
    3827              : !$OMP END DO
    3828              :       DEALLOCATE (S_k, Hu_k, Hd_k, D_k, dS_k, dHu_k, dHd_k, S2, H2, D2, dS2, dH2, W, &
    3829              :                   WdH2W, WdS2W, WD2W, eigenvals)
    3830              :       IF (calc_dipole .OR. calc_bc) DEALLOCATE (dip)
    3831              :       IF (calc_bc) DEALLOCATE (bc)
    3832              :       IF (calc_momentum) DEALLOCATE (mom)
    3833              : !$OMP END PARALLEL
    3834            2 :       DEALLOCATE (S_rs, H_rs, D_rs, VSOC_rs)
    3835            2 :       DEALLOCATE (index_to_cell_all, cell_to_index_all)
    3836            2 :       CALL dbcsr_deallocate_matrix_set(moments_rs_img)
    3837            2 :       CALL dbcsr_deallocate_matrix_set(mat_V_SOC_xyz)
    3838            2 :       CALL kpoint_release(kpoints_all)
    3839            2 :       CALL timestop(handle)
    3840            8 :    END SUBROUTINE qs_moment_kpoints_deep_soc
    3841              : 
    3842              : ! **************************************************************************************************
    3843              : !> \brief Calculates interband k-point dipoles in the existing SCF MO basis.
    3844              : !> \param qs_env ...
    3845              : !> \param dipole ...
    3846              : !> \param rcc retained for interface compatibility; interband dipoles are origin independent
    3847              : !> \param nmo_spin_out number of SCF MOs available for each spin
    3848              : ! **************************************************************************************************
    3849            6 :    SUBROUTINE qs_moment_kpoints_scf_mos(qs_env, dipole, rcc, nmo_spin_out)
    3850              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    3851              :       COMPLEX(KIND=dp), DIMENSION(:, :, :, :, :), &
    3852              :          ALLOCATABLE                                     :: dipole
    3853              :       REAL(KIND=dp), DIMENSION(3), OPTIONAL              :: rcc
    3854              :       INTEGER, DIMENSION(:), ALLOCATABLE, INTENT(OUT), &
    3855              :          OPTIONAL                                        :: nmo_spin_out
    3856              : 
    3857              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'qs_moment_kpoints_scf_mos'
    3858              :       INTEGER                                            :: handle, i_dir, ikp, ikp_local, ispin, &
    3859              :                                                             m, n, nao, nkp, nmo, nspin
    3860            6 :       INTEGER, DIMENSION(:), ALLOCATABLE                 :: nmo_spin
    3861              :       INTEGER, DIMENSION(2)                              :: kp_range
    3862              :       LOGICAL                                            :: my_kpgrp
    3863              :       REAL(KIND=dp), PARAMETER                           :: eps_degenerate = 1.0E-10_dp
    3864              :       COMPLEX(KIND=dp)                                   :: moment_element
    3865              :       REAL(KIND=dp)                                      :: energy_diff
    3866            6 :       REAL(KIND=dp), DIMENSION(:), ALLOCATABLE           :: eigenvalues_kp
    3867            6 :       REAL(KIND=dp), DIMENSION(:), POINTER               :: eigenvals
    3868              :       TYPE(cp_blacs_env_type), POINTER                   :: blacs_env_all
    3869              :       TYPE(cp_fm_struct_type), POINTER                   :: fm_struct
    3870              :       TYPE(cp_cfm_type)                                  :: cfm_empty, cfm_mo_coeff_global, &
    3871              :                                                             cfm_moment, cfm_operator, cfm_work
    3872              :       TYPE(cp_fm_type)                                   :: fm_dummy, fm_mo_coeff_global
    3873              :       TYPE(cp_fm_type)                                   :: fm_operator_imag, fm_operator_real
    3874            6 :       TYPE(dbcsr_p_type), DIMENSION(:, :), POINTER       :: overlap_deriv
    3875            6 :       TYPE(dbcsr_p_type), DIMENSION(:, :), POINTER       :: overlap_deriv_xyz
    3876              :       TYPE(dft_control_type), POINTER                    :: dft_control
    3877            6 :       TYPE(kpoint_env_p_type), DIMENSION(:), POINTER     :: kp_env
    3878              :       TYPE(kpoint_env_type), POINTER                     :: kp
    3879              :       TYPE(kpoint_type), POINTER                         :: kpoints_scf
    3880           24 :       TYPE(rskp_prepared_transform_type)                 :: transform
    3881            6 :       TYPE(mo_set_type), DIMENSION(:), POINTER           :: mos_kp
    3882              :       TYPE(cp_cfm_type), POINTER                         :: cmo_coeff_source
    3883              :       TYPE(cp_fm_type), POINTER                          :: fm_mo_coeff_source
    3884              :       TYPE(mp_para_env_type), POINTER                    :: para_env, para_env_inter_kp, para_env_kp
    3885              :       TYPE(neighbor_list_set_p_type), DIMENSION(:), &
    3886            6 :          POINTER                                         :: sab_kp, sab_orb
    3887              :       TYPE(qs_ks_env_type), POINTER                      :: ks_env
    3888              : 
    3889            6 :       CALL timeset(routineN, handle)
    3890              : 
    3891            6 :       NULLIFY (blacs_env_all, cmo_coeff_source, dft_control, eigenvals, &
    3892            6 :                fm_mo_coeff_source, &
    3893            6 :                fm_struct, kp, kp_env, kpoints_scf, ks_env, mos_kp, &
    3894            6 :                overlap_deriv, overlap_deriv_xyz, para_env, para_env_inter_kp, para_env_kp, sab_kp, sab_orb)
    3895              :       IF (PRESENT(rcc)) THEN
    3896              :          MARK_USED(rcc)
    3897              :       END IF
    3898              : 
    3899              :       CALL get_qs_env(qs_env, dft_control=dft_control, kpoints=kpoints_scf, ks_env=ks_env, &
    3900            6 :                       para_env=para_env, sab_orb=sab_orb)
    3901            6 :       CPASSERT(ASSOCIATED(dft_control))
    3902            6 :       CPASSERT(ASSOCIATED(kpoints_scf))
    3903            6 :       CPASSERT(ASSOCIATED(ks_env))
    3904            6 :       CPASSERT(ASSOCIATED(para_env))
    3905            6 :       CPASSERT(ASSOCIATED(sab_orb))
    3906              : 
    3907              :       CALL get_kpoint_info(kpoints_scf, nkp=nkp, kp_range=kp_range, kp_env=kp_env, &
    3908              :                            para_env_kp=para_env_kp, para_env_inter_kp=para_env_inter_kp, &
    3909            6 :                            blacs_env_all=blacs_env_all, sab_nl=sab_kp)
    3910            6 :       IF (kp_range(2) >= kp_range(1)) THEN
    3911            6 :          CPASSERT(ASSOCIATED(kp_env))
    3912              :       END IF
    3913            6 :       CPASSERT(ASSOCIATED(para_env_kp))
    3914            6 :       CPASSERT(ASSOCIATED(para_env_inter_kp))
    3915            6 :       CPASSERT(ASSOCIATED(blacs_env_all))
    3916            6 :       CPASSERT(ASSOCIATED(sab_kp))
    3917              : 
    3918              :       CALL build_overlap_matrix(ks_env, matrixkp_s=overlap_deriv, nderivative=1, &
    3919              :                                 basis_type_a="ORB", basis_type_b="ORB", sab_nl=sab_orb, &
    3920            6 :                                 ext_kpoints=kpoints_scf)
    3921              : 
    3922            6 :       nspin = dft_control%nspins
    3923            6 :       CALL dbcsr_get_info(overlap_deriv(1, 1)%matrix, nfullrows_total=nao)
    3924           18 :       ALLOCATE (nmo_spin(nspin), source=0)
    3925            6 :       IF (kp_range(2) >= kp_range(1)) THEN
    3926            6 :          kp => kp_env(1)%kpoint_env
    3927            6 :          mos_kp => kp%mos
    3928            6 :          CPASSERT(ASSOCIATED(mos_kp))
    3929           12 :          DO ispin = 1, nspin
    3930           12 :             CALL get_mo_set(mos_kp(ispin), nmo=nmo_spin(ispin))
    3931              :          END DO
    3932              :       END IF
    3933            6 :       CALL para_env%max(nmo_spin)
    3934           48 :       ALLOCATE (dipole(nspin, nkp, 3, MAXVAL(nmo_spin), MAXVAL(nmo_spin)), source=z_zero)
    3935            6 :       IF (PRESENT(nmo_spin_out)) THEN
    3936            8 :          ALLOCATE (nmo_spin_out(nspin))
    3937            8 :          nmo_spin_out(:) = nmo_spin(:)
    3938              :       END IF
    3939              : 
    3940            6 :       CPASSERT(SIZE(overlap_deriv, 1) >= 4)
    3941            6 :       overlap_deriv_xyz => overlap_deriv(2:4, :)
    3942              :       CALL cp_fm_struct_create(fm_struct, nrow_global=nao, ncol_global=nao, &
    3943            6 :                                para_env=para_env, context=blacs_env_all)
    3944              :       CALL rskp_transform_prepare(transform, overlap_deriv_xyz, [1, 2, 3], sab_kp, &
    3945              :                                   kpoints_scf%cell_to_index, fm_struct, para_env, para_env_kp, &
    3946              :                                   para_env_inter_kp, kpoints_scf%rskp_transform, kpoints_scf%xkp, &
    3947            6 :                                   kpoints_scf%nkp_grid, kpoints_scf%kp_dist, mirror_sign=-1)
    3948            6 :       CALL cp_fm_struct_release(fm_struct)
    3949              : 
    3950          258 :       DO ikp = 1, nkp
    3951          252 :          my_kpgrp = (ikp >= kp_range(1) .AND. ikp <= kp_range(2))
    3952              :          IF (my_kpgrp) THEN
    3953          234 :             ikp_local = ikp - kp_range(1) + 1
    3954          234 :             kp => kp_env(ikp_local)%kpoint_env
    3955          234 :             mos_kp => kp%mos
    3956              :          ELSE
    3957          252 :             NULLIFY (kp, mos_kp)
    3958              :          END IF
    3959          510 :          DO ispin = 1, nspin
    3960          252 :             nmo = nmo_spin(ispin)
    3961          756 :             ALLOCATE (eigenvalues_kp(nmo), source=0.0_dp)
    3962              : 
    3963              :             CALL cp_fm_struct_create(fm_struct, nrow_global=nao, ncol_global=nmo, &
    3964          252 :                                      para_env=para_env, context=blacs_env_all)
    3965          252 :             CALL cp_cfm_create(cfm_mo_coeff_global, fm_struct)
    3966          252 :             CALL cp_cfm_create(cfm_work, fm_struct)
    3967          252 :             CALL cp_fm_struct_release(fm_struct)
    3968              :             CALL cp_fm_struct_create(fm_struct, nrow_global=nmo, ncol_global=nmo, &
    3969          252 :                                      para_env=para_env, context=blacs_env_all)
    3970          252 :             CALL cp_cfm_create(cfm_moment, fm_struct)
    3971          252 :             CALL cp_fm_struct_release(fm_struct)
    3972              :             CALL cp_fm_struct_create(fm_struct, nrow_global=nao, ncol_global=nao, &
    3973          252 :                                      para_env=para_env, context=blacs_env_all)
    3974          252 :             CALL cp_cfm_create(cfm_operator, fm_struct)
    3975          252 :             CALL cp_fm_create(fm_operator_real, fm_struct)
    3976          252 :             CALL cp_fm_create(fm_operator_imag, fm_struct)
    3977          252 :             CALL cp_fm_struct_release(fm_struct)
    3978              : 
    3979          252 :             IF (my_kpgrp) THEN
    3980          234 :                CALL get_mo_set(mos_kp(ispin), eigenvalues=eigenvals)
    3981          234 :                CPASSERT(ASSOCIATED(eigenvals))
    3982          234 :                IF (kpoints_scf%use_real_wfn) THEN
    3983            0 :                   NULLIFY (cmo_coeff_source)
    3984            0 :                   fm_mo_coeff_source => mos_kp(ispin)%mo_coeff
    3985              :                ELSE
    3986          234 :                   NULLIFY (fm_mo_coeff_source)
    3987          234 :                   cmo_coeff_source => mos_kp(ispin)%cmo_coeff
    3988              :                END IF
    3989          772 :                IF (para_env_kp%is_source()) eigenvalues_kp(1:nmo) = eigenvals(1:nmo)
    3990              :             ELSE
    3991              :                NULLIFY (cmo_coeff_source)
    3992              :                NULLIFY (fm_mo_coeff_source)
    3993              :             END IF
    3994          252 :             IF (kpoints_scf%use_real_wfn) THEN
    3995            0 :                CALL cp_fm_create(fm_mo_coeff_global, cfm_mo_coeff_global%matrix_struct)
    3996            0 :                IF (ASSOCIATED(fm_mo_coeff_source)) THEN
    3997            0 :                   CALL cp_fm_copy_general(fm_mo_coeff_source, fm_mo_coeff_global, para_env)
    3998              :                ELSE
    3999            0 :                   CALL cp_fm_copy_general(fm_dummy, fm_mo_coeff_global, para_env)
    4000              :                END IF
    4001            0 :                CALL cp_fm_to_cfm(msourcer=fm_mo_coeff_global, mtarget=cfm_mo_coeff_global)
    4002            0 :                CALL cp_fm_release(fm_mo_coeff_global)
    4003              :             ELSE
    4004          252 :                IF (ASSOCIATED(cmo_coeff_source)) THEN
    4005          234 :                   CALL cp_cfm_copy_general(cmo_coeff_source, cfm_mo_coeff_global, para_env)
    4006              :                ELSE
    4007           18 :                   CALL cp_cfm_copy_general(cfm_empty, cfm_mo_coeff_global, para_env)
    4008              :                END IF
    4009              :             END IF
    4010          252 :             CALL para_env%sum(eigenvalues_kp)
    4011              : 
    4012         1008 :             DO i_dir = 1, 3
    4013              :                ! The derivative transforms are anti-Hermitian at each k point.
    4014              :                CALL rskp_transform_evaluate(transform, i_dir, ikp, kpoints_scf%xkp, &
    4015          756 :                                             fm_operator_real, fm_operator_imag)
    4016          756 :                CALL cp_fm_to_cfm(fm_operator_real, fm_operator_imag, cfm_operator)
    4017              :                CALL parallel_gemm("N", "N", nao, nmo, nao, z_one, cfm_operator, &
    4018          756 :                                   cfm_mo_coeff_global, z_zero, cfm_work)
    4019              :                CALL parallel_gemm("C", "N", nmo, nmo, nao, z_one, cfm_mo_coeff_global, &
    4020          756 :                                   cfm_work, z_zero, cfm_moment)
    4021              : 
    4022         4236 :                DO n = 1, nmo
    4023        18108 :                   DO m = 1, nmo
    4024        14124 :                      IF (n == m) CYCLE
    4025        10896 :                      energy_diff = eigenvalues_kp(m) - eigenvalues_kp(n)
    4026        10896 :                      IF (ABS(energy_diff) <= eps_degenerate) CYCLE
    4027        10872 :                      CALL cp_cfm_get_element(cfm_moment, m, n, moment_element)
    4028        14100 :                      IF (para_env%is_source()) THEN
    4029         8688 :                         dipole(ispin, ikp, i_dir, n, m) = moment_element/energy_diff
    4030              :                      END IF
    4031              :                   END DO
    4032              :                END DO
    4033              :             END DO
    4034          252 :             CALL cp_cfm_release(cfm_mo_coeff_global)
    4035          252 :             CALL cp_cfm_release(cfm_work)
    4036          252 :             CALL cp_cfm_release(cfm_moment)
    4037          252 :             CALL cp_cfm_release(cfm_operator)
    4038          252 :             CALL cp_fm_release(fm_operator_real)
    4039          252 :             CALL cp_fm_release(fm_operator_imag)
    4040         1260 :             DEALLOCATE (eigenvalues_kp)
    4041              :          END DO
    4042              :       END DO
    4043              : 
    4044           12 :       DO ispin = 1, nspin
    4045          264 :          DO ikp = 1, nkp
    4046         1014 :             DO i_dir = 1, 3
    4047        35712 :                CALL para_env%sum(dipole(ispin, ikp, i_dir, :, :))
    4048              :             END DO
    4049              :          END DO
    4050              :       END DO
    4051              : 
    4052            6 :       CALL rskp_transform_release(transform)
    4053            6 :       CALL dbcsr_deallocate_matrix_set(overlap_deriv)
    4054            6 :       DEALLOCATE (nmo_spin)
    4055            6 :       CALL timestop(handle)
    4056              : 
    4057           24 :    END SUBROUTINE qs_moment_kpoints_scf_mos
    4058              : 
    4059              : ! **************************************************************************************************
    4060              : !> \brief Calculate and print dipole moment elements d_nm(k) = i<u_n|∇_k|u_m> for k-point
    4061              : !>        calculations
    4062              : !> \param qs_env ...
    4063              : !> \param nmoments ...
    4064              : !> \param reference ...
    4065              : !> \param ref_point ...
    4066              : !> \param max_nmo ...
    4067              : !> \param unit_number ...
    4068              : !> \param do_soc include spin-orbit coupling (spinor sum-rule; requires an explicit KPOINT set)
    4069              : !> \param unit_str unit of the printed dipoles (dipole unit of cp_units), default debye; the Berry
    4070              : !>        curvature is printed in the paired length unit squared
    4071              : !> \param dip_file if present and non-empty, the dipole matrix elements are written to this file
    4072              : !>        instead of being printed to unit_number
    4073              : !> \param bc_file if present and non-empty, the Berry curvature is written to this file instead of
    4074              : !>        being printed to unit_number
    4075              : !> \author Shridhar Shanbhag
    4076              : ! **************************************************************************************************
    4077           12 :    SUBROUTINE qs_moment_kpoints(qs_env, nmoments, reference, ref_point, max_nmo, unit_number, do_soc, &
    4078              :                                 unit_str, dip_file, bc_file)
    4079              :       TYPE(qs_environment_type), POINTER                 :: qs_env
    4080              :       INTEGER, INTENT(IN)                                :: nmoments, reference, max_nmo
    4081              :       REAL(dp), DIMENSION(:), INTENT(IN), POINTER        :: ref_point
    4082              :       INTEGER, INTENT(IN)                                :: unit_number
    4083              :       LOGICAL, INTENT(IN)                                :: do_soc
    4084              :       CHARACTER(LEN=*), INTENT(IN), OPTIONAL             :: unit_str, dip_file, bc_file
    4085              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'qs_moment_kpoints'
    4086              :       CHARACTER(LEN=16)                                  :: dip_label, len_label
    4087              :       INTEGER                                            :: bc_unit, dip_unit, iu
    4088              :       INTEGER, DIMENSION(3)                              :: out_units
    4089              :       LOGICAL                                            :: use_sci
    4090              :       LOGICAL                                            :: to_bc_file, to_dip_file
    4091              :       LOGICAL, DIMENSION(3)                              :: print_bc, print_dip
    4092              :       REAL(KIND=dp)                                      :: dip_fac, len_fac
    4093           12 :       TYPE(dbcsr_p_type), DIMENSION(:, :), POINTER       :: matrix_ks_kp
    4094           12 :       COMPLEX(KIND=dp), DIMENSION(:, :, :), ALLOCATABLE  :: dipole_to_print
    4095              :       COMPLEX(KIND=dp), DIMENSION(:, :, :, :, :), &
    4096           12 :          ALLOCATABLE                                     :: dipole
    4097              :       INTEGER                                            :: handle, i_dir, ikp, nmo_dim, nkp, nao, &
    4098              :                                                             num_pe, mepos, n, m, &
    4099              :                                                             ispin, nspin, nspin_dip, nmin, nmax, homo
    4100           12 :       INTEGER, DIMENSION(:), ALLOCATABLE                 :: nmo_spin_scf
    4101              :       LOGICAL                                            :: explicit_kpnts, explicit_kpset, use_scf_mos
    4102              :       REAL(KIND=dp), DIMENSION(3)                        :: rcc
    4103           12 :       REAL(KIND=dp), DIMENSION(:, :), ALLOCATABLE        :: xkp
    4104           12 :       REAL(KIND=dp), DIMENSION(:, :), ALLOCATABLE        :: bc_to_print
    4105           12 :       REAL(KIND=dp), DIMENSION(:, :, :, :), ALLOCATABLE  :: berry_c
    4106           12 :       TYPE(mo_set_type), DIMENSION(:), POINTER           :: mos
    4107              :       TYPE(mp_para_env_type), POINTER                    :: para_env
    4108              :       TYPE(section_vals_type), POINTER                   :: kpnts, kpset
    4109              :       CHARACTER(LEN=default_string_length), &
    4110           12 :          DIMENSION(:), POINTER                           :: special_pnts
    4111              : 
    4112           12 :       CALL timeset(routineN, handle)
    4113              : 
    4114           12 :       IF (nmoments > 1) CPABORT("KPOINT quadrupole and higher moments not implemented.")
    4115           12 :       IF (max_nmo < 0) CPABORT("Negative maximum number of molecular orbitals max_nmo provided.")
    4116              : 
    4117              :       CALL get_qs_env(qs_env, &
    4118              :                       para_env=para_env, &
    4119              :                       matrix_ks_kp=matrix_ks_kp, &
    4120           12 :                       mos=mos)
    4121              : 
    4122           12 :       CALL get_mo_set(mo_set=mos(1), nao=nao)
    4123           12 :       CALL get_xkp_for_dipole_calc(qs_env, xkp, special_pnts)
    4124           12 :       CALL get_reference_point(rcc, qs_env=qs_env, reference=reference, ref_point=ref_point)
    4125           12 :       nspin = SIZE(matrix_ks_kp, 1)
    4126           12 :       nkp = SIZE(xkp, 2)
    4127              : 
    4128           12 :       kpset => section_vals_get_subs_vals(qs_env%input, "DFT%PRINT%MOMENTS%KPOINT_SET")
    4129           12 :       kpnts => section_vals_get_subs_vals(qs_env%input, "DFT%PRINT%MOMENTS%KPOINTS")
    4130           12 :       CALL section_vals_get(kpset, explicit=explicit_kpset)
    4131           12 :       CALL section_vals_get(kpnts, explicit=explicit_kpnts)
    4132           12 :       use_scf_mos = .NOT. explicit_kpset .AND. .NOT. explicit_kpnts
    4133              : 
    4134           12 :       IF (do_soc .AND. use_scf_mos) THEN
    4135              :          CALL cp_abort(__LOCATION__, "MOMENTS with SOC requires an explicit KPOINT_SET or "// &
    4136            0 :                        "KPOINTS section (the interband sum-rule / deep path).")
    4137              :       END IF
    4138              : 
    4139              :       ! output units: d_nm in the dipole unit, Berry curvature in the paired length unit squared
    4140           12 :       IF (PRESENT(unit_str)) THEN
    4141           12 :          CALL get_moment_print_units(unit_str, dip_fac, len_fac, dip_label, len_label, use_sci)
    4142              :       ELSE
    4143            0 :          CALL get_moment_print_units("debye", dip_fac, len_fac, dip_label, len_label, use_sci)
    4144              :       END IF
    4145              :       MARK_USED(use_sci)
    4146              : 
    4147           12 :       IF (unit_number > 0) WRITE (unit_number, FMT="(/,T2,A)") &
    4148            6 :          '!-----------------------------------------------------------------------------!'
    4149           12 :       IF (unit_number > 0) WRITE (unit_number, "(T22,A)") "Periodic Dipole Matrix Elements ["// &
    4150            6 :          TRIM(dip_label)//"]"
    4151           12 :       IF (unit_number > 0 .AND. do_soc) WRITE (unit_number, "(T20,A)") &
    4152            1 :          "with Spin-Orbit Coupling (spinor bands)"
    4153              : 
    4154              :       ! optional separate files, written by the I/O rank only; data written to a file is not
    4155              :       ! repeated in the main MOMENTS output
    4156           12 :       to_dip_file = .FALSE.
    4157           12 :       to_bc_file = .FALSE.
    4158           12 :       IF (PRESENT(dip_file)) to_dip_file = (LEN_TRIM(dip_file) > 0)
    4159           12 :       IF (PRESENT(bc_file)) to_bc_file = (LEN_TRIM(bc_file) > 0)
    4160           12 :       IF (unit_number > 0 .AND. to_dip_file) WRITE (unit_number, "(/,T3,A)") &
    4161            1 :          "Dipole matrix elements written to file: "//TRIM(dip_file)
    4162           12 :       IF (unit_number > 0 .AND. to_bc_file) WRITE (unit_number, "(/,T3,A)") &
    4163            1 :          "Berry curvature written to file: "//TRIM(bc_file)
    4164           12 :       dip_unit = -1
    4165           12 :       bc_unit = -1
    4166           12 :       IF (para_env%is_source()) THEN
    4167            6 :          IF (to_dip_file) THEN
    4168              :             CALL open_file(file_name=TRIM(dip_file), file_status="REPLACE", file_action="WRITE", &
    4169            1 :                            unit_number=dip_unit)
    4170              :             WRITE (dip_unit, FMT="(/,T2,A)") &
    4171            1 :                '!-----------------------------------------------------------------------------!'
    4172            1 :             WRITE (dip_unit, "(T22,A)") "Periodic Dipole Matrix Elements ["//TRIM(dip_label)//"]"
    4173            1 :             IF (do_soc) WRITE (dip_unit, "(T20,A)") "with Spin-Orbit Coupling (spinor bands)"
    4174              :          END IF
    4175            6 :          IF (to_bc_file) THEN
    4176              :             CALL open_file(file_name=TRIM(bc_file), file_status="REPLACE", file_action="WRITE", &
    4177            1 :                            unit_number=bc_unit)
    4178              :             WRITE (bc_unit, FMT="(/,T2,A)") &
    4179            1 :                '!-----------------------------------------------------------------------------!'
    4180            1 :             WRITE (bc_unit, "(T22,A)") "Berry Curvature ["//TRIM(len_label)//"^2]"
    4181            1 :             IF (do_soc) WRITE (bc_unit, "(T20,A)") "with Spin-Orbit Coupling (spinor bands)"
    4182              :          END IF
    4183              :       END IF
    4184              :       ! output targets: main output, dipole file, Berry curvature file; each table goes
    4185              :       ! to its file if one is given, otherwise to the main output
    4186           48 :       out_units = [unit_number, dip_unit, bc_unit]
    4187           48 :       print_dip = [.NOT. to_dip_file, to_dip_file, .FALSE.]
    4188           48 :       print_bc = [.NOT. to_bc_file, .FALSE., to_bc_file]
    4189           12 :       IF (to_dip_file .AND. to_bc_file) out_units(1) = -1
    4190              : 
    4191           12 :       nspin_dip = nspin
    4192           12 :       IF (do_soc) THEN
    4193              :          ! spinor sum-rule: SOC merges the two spin channels into 2*nao spinor bands
    4194              :          CALL qs_moment_kpoints_deep_soc(qs_env, &
    4195              :                                          xkp, &
    4196              :                                          dipole, &
    4197              :                                          rcc, &
    4198              :                                          berry_c, &
    4199            2 :                                          do_parallel=.TRUE.)
    4200            2 :          nmo_dim = 2*nao
    4201            2 :          nspin_dip = 1
    4202           10 :       ELSE IF (use_scf_mos) THEN
    4203            4 :          CALL qs_moment_kpoints_scf_mos(qs_env, dipole, rcc, nmo_spin_scf)
    4204            4 :          nmo_dim = SIZE(dipole, 4)
    4205           24 :          ALLOCATE (berry_c(nspin, nkp, 3, nmo_dim), source=0.0_dp)
    4206            8 :          DO ispin = 1, nspin
    4207          256 :             DO ikp = 1, nkp
    4208          996 :                DO i_dir = 1, 3
    4209         4160 :                   DO n = 1, nmo_dim
    4210        17736 :                      DO m = 1, nmo_dim
    4211        13824 :                         IF (n == m) CYCLE
    4212              :                         berry_c(ispin, ikp, i_dir, n) = berry_c(ispin, ikp, i_dir, n) &
    4213              :                                                         + 2*AIMAG(dipole(ispin, ikp, 1 + MOD(i_dir, 3), n, m)* &
    4214        16992 :                                                                   dipole(ispin, ikp, 1 + MOD(i_dir + 1, 3), m, n))
    4215              :                      END DO
    4216              :                   END DO
    4217              :                END DO
    4218              :             END DO
    4219              :          END DO
    4220              :       ELSE
    4221              :          CALL qs_moment_kpoints_deep(qs_env, &
    4222              :                                      xkp, &
    4223              :                                      dipole, &
    4224              :                                      rcc, &
    4225              :                                      berry_c, &
    4226            6 :                                      do_parallel=.TRUE.)
    4227            6 :          nmo_dim = nao
    4228              :       END IF
    4229              : 
    4230           48 :       ALLOCATE (dipole_to_print(3, nmo_dim, nmo_dim), source=z_zero)
    4231           36 :       ALLOCATE (bc_to_print(3, nmo_dim), source=0.0_dp)
    4232              : 
    4233           12 :       mepos = para_env%mepos
    4234           12 :       num_pe = para_env%num_pe
    4235              : 
    4236          268 :       DO ikp = 1, nkp
    4237          526 :          DO ispin = 1, nspin_dip
    4238          258 :             IF (do_soc) THEN
    4239              :                ! spinor HOMO = number of occupied spin-up + spin-down states (mirrors SOC_ev)
    4240            2 :                CALL get_mo_set(mo_set=mos(1), homo=homo)
    4241            2 :                CALL get_mo_set(mo_set=mos(nspin), homo=n)
    4242            2 :                homo = homo + n
    4243              :             ELSE
    4244          256 :                CALL get_mo_set(mo_set=mos(ispin), homo=homo)
    4245              :             END IF
    4246          258 :             nmin = max(1, homo - (max_nmo - 1)/2)
    4247          258 :             nmax = min(nmo_dim, homo + max_nmo/2)
    4248          258 :             IF (max_nmo == 0) THEN
    4249            0 :                nmin = 1
    4250            0 :                nmax = nmo_dim
    4251              :             END IF
    4252          258 :             IF (use_scf_mos) THEN
    4253          248 :                nmax = min(nmax, nmo_spin_scf(ispin))
    4254              :             END IF
    4255          258 :             dipole_to_print = 0.0_dp
    4256          258 :             bc_to_print = 0.0_dp
    4257          258 :             IF (use_scf_mos) THEN
    4258        19736 :                dipole_to_print(:, :, :) = dipole(ispin, ikp, :, :, :)
    4259         4472 :                bc_to_print(:, :) = berry_c(ispin, ikp, :, :)
    4260           10 :             ELSE IF (mod(ikp - 1, num_pe) == mepos) THEN
    4261        88309 :                dipole_to_print(:, :, :) = dipole(ispin, CEILING(REAL(ikp)/num_pe), :, :, :)
    4262          965 :                bc_to_print(:, :) = berry_c(ispin, CEILING(REAL(ikp)/num_pe), :, :)
    4263              :             END IF
    4264          258 :             IF (.NOT. use_scf_mos) THEN
    4265           10 :                CALL para_env%sum(dipole_to_print)
    4266           10 :                CALL para_env%sum(bc_to_print)
    4267              :             END IF
    4268         1288 :             DO iu = 1, SIZE(out_units)
    4269          774 :                IF (out_units(iu) <= 0) CYCLE
    4270          130 :                IF (special_pnts(ikp) /= "") WRITE (out_units(iu), "(/,2X,A,A)") &
    4271            5 :                   "Special point: ", ADJUSTL(TRIM(special_pnts(ikp)))
    4272              :                WRITE (out_units(iu), "(/,1X,A,I3,1X,3(A,1F12.6))") &
    4273          130 :                   "Kpoint:", ikp, ", kx:", xkp(1, ikp), ", ky:", xkp(2, ikp), ", kz:", xkp(3, ikp)
    4274          130 :                IF (nspin > 1 .AND. .NOT. do_soc) WRITE (out_units(iu), "(/,2X,A,I2)") &
    4275            2 :                   "Open Shell System. Spin:", ispin
    4276          130 :                IF (print_dip(iu)) THEN
    4277              :                   WRITE (out_units(iu), "(2X,A)") "  kp   n   m  Re(dx_nm)  Im(dx_nm) &
    4278          129 :                   & Re(dy_nm)  Im(dy_nm)  Re(dz_nm)  Im(dz_nm)"
    4279          681 :                   DO n = nmin, nmax
    4280         3137 :                      DO m = nmin, nmax
    4281         2456 :                         IF (n == m) CYCLE
    4282         8720 :                         WRITE (out_units(iu), "(2X,I4,2I4,6(G11.3))") ikp, n, m, dipole_to_print(1:3, n, m)*dip_fac
    4283              :                      END DO
    4284              :                   END DO
    4285              :                END IF
    4286          388 :                IF (print_bc(iu)) THEN
    4287          129 :                   WRITE (out_units(iu), "(/,1X,A)") "Berry Curvature ["//TRIM(len_label)//"^2]"
    4288          129 :                   WRITE (out_units(iu), "(2X,A)") "   kp    n      YZ          ZX          XY"
    4289          681 :                   DO n = nmin, nmax
    4290              :                      WRITE (out_units(iu), "(2X,2I5,3(1X,G11.3))") &
    4291         2337 :                         ikp, n, bc_to_print(1:3, n)*len_fac**2
    4292              :                   END DO
    4293              :                END IF
    4294              :             END DO
    4295              :          END DO
    4296              :       END DO
    4297           12 :       IF (dip_unit > 0) CALL close_file(unit_number=dip_unit)
    4298           12 :       IF (bc_unit > 0) CALL close_file(unit_number=bc_unit)
    4299           12 :       DEALLOCATE (dipole_to_print, bc_to_print, berry_c, dipole)
    4300           12 :       IF (ALLOCATED(nmo_spin_scf)) DEALLOCATE (nmo_spin_scf)
    4301           12 :       DEALLOCATE (special_pnts, xkp)
    4302              : 
    4303           12 :       CALL timestop(handle)
    4304              : 
    4305           48 :    END SUBROUTINE qs_moment_kpoints
    4306              : 
    4307              : END MODULE qs_moments
        

Generated by: LCOV version 2.0-1