LCOV - code coverage report
Current view: top level - src - kpoint_unfolding.F (source / functions) Coverage Total Hit
Test: CP2K Regtests (git:1be8651) Lines: 93.0 % 430 400
Test Date: 2026-11-24 01:22:08 Functions: 83.3 % 12 10

            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 Band structure unfolding onto a primitive cell for k-point supercell runs
      10              : !>        (Quan, Rybin, Scheffler, Carbogno, Phys. Rev. B 113, 085112 (2026)).
      11              : !>        Closed-form orbit-Fourier weights
      12              : !>        W^k_KN = sum_channels | 1/sqrt(m) sum_{mu in channel} exp(-2 pi i f_k.n_mu) C'_muN |^2
      13              : !>        with C' = S(K)^{1/2} C(K) (Loewdin) and displacement-integer labels n_mu, which
      14              : !>        live in the L = 0 gauge (no supercell wrap phase needed). The per-band sum rule
      15              : !>        sum_q W^{k_q}_KN = C_N^T S(K) C_N = 1 holds strictly for any distortion or defect.
      16              : !>        Gauge: atoms are wrapped with the convention of the k-point neighbor
      17              : !>        lists. CP2K uses pbc_stable when the SCF ran with k-point symmetry, and
      18              : !>        plain pbc otherwise. This matches the rskp_transform anchoring.
      19              : ! **************************************************************************************************
      20              : MODULE kpoint_unfolding
      21              : 
      22              :    USE basis_set_types,                 ONLY: get_gto_basis_set,&
      23              :                                               gto_basis_set_type
      24              :    USE bibliography,                    ONLY: Quan2026
      25              :    USE cell_types,                      ONLY: cell_type,&
      26              :                                               pbc,&
      27              :                                               pbc_stable,&
      28              :                                               real_to_scaled
      29              :    USE cp_cfm_types,                    ONLY: cp_cfm_create,&
      30              :                                               cp_cfm_get_info,&
      31              :                                               cp_cfm_release,&
      32              :                                               cp_cfm_type
      33              :    USE cp_dbcsr_api,                    ONLY: dbcsr_p_type
      34              :    USE input_section_types,             ONLY: section_vals_type,&
      35              :                                               section_vals_val_get
      36              :    USE kinds,                           ONLY: default_string_length,&
      37              :                                               dp
      38              :    USE kpoint_methods,                  ONLY: lowdin_kp_mo_coeff
      39              :    USE kpoint_types,                    ONLY: get_kpoint_info,&
      40              :                                               kpoint_env_type,&
      41              :                                               kpoint_type
      42              :    USE mathconstants,                   ONLY: twopi
      43              :    USE mathlib,                         ONLY: det_3x3,&
      44              :                                               inv_3x3,&
      45              :                                               vector_product
      46              :    USE message_passing,                 ONLY: mp_para_env_type
      47              :    USE particle_methods,                ONLY: get_particle_set
      48              :    USE particle_types,                  ONLY: particle_type
      49              :    USE physcon,                         ONLY: angstrom,&
      50              :                                               evolt
      51              :    USE qs_environment_types,            ONLY: get_qs_env,&
      52              :                                               qs_environment_type
      53              :    USE qs_kind_types,                   ONLY: get_qs_kind,&
      54              :                                               qs_kind_type
      55              :    USE qs_mo_types,                     ONLY: get_mo_set,&
      56              :                                               mo_set_type
      57              :    USE qs_scf_diagonalization,          ONLY: diag_kp_smat
      58              :    USE qs_scf_types,                    ONLY: qs_scf_env_type
      59              :    USE reference_manager,               ONLY: cite_reference
      60              : #include "./base/base_uses.f90"
      61              : 
      62              :    IMPLICIT NONE
      63              :    PRIVATE
      64              : 
      65              :    CHARACTER(len=*), PARAMETER, PRIVATE :: moduleN = 'kpoint_unfolding'
      66              :    INTEGER, PARAMETER, PRIVATE :: msg_length = 256
      67              :    ! tolerance for identifying k-points that differ by a reciprocal lattice vector
      68              :    REAL(KIND=dp), PARAMETER :: kdifftol = 1.0E-6_dp
      69              :    ! bound-inclusion tolerance for unfolded f = M^-T (K + p): coordinates on the
      70              :    ! unit-cell edge reach 0 or 1 only within roundoff
      71              :    REAL(KIND=dp), PARAMETER :: unit_tol = 1.0E-9_dp
      72              :    ! full-atom-selection Loewdin populations equal 1 to the k-point MO orthonormality
      73              :    ! accuracy (set by the diagonalization threshold, EPS_DEFAULT-level); violations
      74              :    ! indicate an inconsistent S(k) or MO set, well above this guard
      75              :    REAL(KIND=dp), PARAMETER :: mo_orthonorm_tol = 1.0E-8_dp
      76              :    ! MO block width bounding per-rank channel-reduction scratch in unfolding_kp_weights
      77              :    INTEGER, PARAMETER :: unfolding_mo_block = 256
      78              : 
      79              :    !> Transformation matrix, derived primitive cell, and the per-AO orbit map
      80              :    TYPE :: unfolding_env_type
      81              :       INTEGER, DIMENSION(3, 3) :: transmat = 0             ! hmat_SC = hmat_PC . M (column convention)
      82              :       INTEGER :: m = 0                                      ! |det(M)|
      83              :       REAL(KIND=dp) :: symm_tol = 0.5_dp/angstrom         ! default 0.5 Angstrom in internal Bohr
      84              :       REAL(KIND=dp), DIMENSION(3, 3) :: h_pc = 0.0_dp       ! derived primitive lattice (columns)
      85              :       INTEGER :: n_sets = 0                                 ! atomic equivalent-site sets
      86              :       INTEGER :: n_channels = 0                             ! per-AO equivalence channels
      87              :       INTEGER, DIMENSION(:), ALLOCATABLE :: channel_of_ao   ! (nao)
      88              :       INTEGER, DIMENSION(:, :), ALLOCATABLE :: n_of_ao      ! (3, nao) primitive translation labels
      89              :       INTEGER :: n_incomplete = 0                           ! equivalent-site sets with fewer than m atoms
      90              :       INTEGER :: n_groups = 1                               ! atom groups (independent clustering)
      91              :       INTEGER, DIMENSION(:), ALLOCATABLE :: channel_group   ! group of each channel (upper bound nao)
      92              :       LOGICAL :: full_selection = .TRUE.                    ! no atom screened: Loewdin populations are 1
      93              :       LOGICAL :: lowdin_proj = .FALSE.                      ! S(K)^{1/2} prebuilt by the DFT+U projection
      94              :    END TYPE unfolding_env_type
      95              : 
      96              :    PUBLIC :: unfolding_env_type, unfolding_setup, unfolding_fold_kpath, &
      97              :              unfolding_process_batch, unfolding_finish_set, unfolding_env_release
      98              : 
      99              : CONTAINS
     100              : 
     101              : ! **************************************************************************************************
     102              : !> \brief Set up band structure unfolding from the UNFOLDING section: primitive cell of
     103              : !>        TRANSFORMATION_MATRIX, ATOMS groups, and the supercell-to-primitive orbit map. The
     104              : !>        setup is summarized on the output unit and in the header of the band structure file
     105              : !> \param uf unfolding environment
     106              : !> \param qs_env ...
     107              : !> \param u_input UNFOLDING section
     108              : !> \param unit_nr default output unit
     109              : !> \param bs_data_unit band structure data unit
     110              : ! **************************************************************************************************
     111          108 :    SUBROUTINE unfolding_setup(uf, qs_env, u_input, unit_nr, bs_data_unit)
     112              :       TYPE(unfolding_env_type), INTENT(OUT)              :: uf
     113              :       TYPE(qs_environment_type), POINTER                 :: qs_env
     114              :       TYPE(section_vals_type), POINTER                   :: u_input
     115              :       INTEGER, INTENT(IN)                                :: unit_nr, bs_data_unit
     116              : 
     117              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'unfolding_setup'
     118              : 
     119              :       INTEGER                                            :: g, handle, i, ia, ia_first, ia_last, j, &
     120              :                                                             n_atom_groups, natom
     121              :       INTEGER, ALLOCATABLE, DIMENSION(:)                 :: group_of_atom
     122              :       INTEGER, DIMENSION(3, 3)                           :: transmat
     123            4 :       INTEGER, DIMENSION(:), POINTER                     :: atom_vals, mvals
     124              :       LOGICAL                                            :: stable_images
     125              :       REAL(KIND=dp)                                      :: symm_tol
     126              :       REAL(KIND=dp), DIMENSION(3, 3)                     :: cart_hmat
     127              :       TYPE(cell_type), POINTER                           :: cell
     128              :       TYPE(kpoint_type), POINTER                         :: kpoints
     129            4 :       TYPE(particle_type), DIMENSION(:), POINTER         :: particle_set
     130            4 :       TYPE(qs_kind_type), DIMENSION(:), POINTER          :: qs_kind_set
     131              : 
     132            4 :       CALL timeset(routineN, handle)
     133              : 
     134            4 :       CALL cite_reference(Quan2026)
     135            4 :       NULLIFY (cell, kpoints, particle_set, qs_kind_set)
     136            4 :       CALL get_qs_env(qs_env, cell=cell, kpoints=kpoints, particle_set=particle_set, qs_kind_set=qs_kind_set)
     137              : 
     138            4 :       NULLIFY (mvals)
     139            4 :       CALL section_vals_val_get(u_input, "TRANSFORMATION_MATRIX", i_vals=mvals)
     140              :       ! input lists the three matrix rows; RESHAPE fills columns first
     141            4 :       transmat = RESHAPE(mvals, [3, 3], ORDER=[2, 1])
     142            4 :       NULLIFY (mvals)  ! aliases section storage, must not be deallocated
     143            4 :       CALL section_vals_val_get(u_input, "SYMM_TOL", r_val=symm_tol)
     144           52 :       cart_hmat(:, :) = cell%hmat(:, :)
     145            4 :       IF (cell%input_cell_canonicalized) cart_hmat(:, :) = cell%input_hmat(:, :)
     146            4 :       CALL unfolding_env_create(uf, transmat, symm_tol, cart_hmat)
     147              : 
     148            4 :       natom = SIZE(particle_set)
     149           12 :       ALLOCATE (group_of_atom(natom))
     150            4 :       group_of_atom = 0
     151            4 :       CALL section_vals_val_get(u_input, "ATOMS", n_rep_val=n_atom_groups)
     152            8 :       DO g = 1, n_atom_groups
     153            4 :          NULLIFY (atom_vals)
     154            4 :          CALL section_vals_val_get(u_input, "ATOMS", i_rep_val=g, i_vals=atom_vals)
     155           16 :          DO j = 1, SIZE(atom_vals)
     156           12 :             ia = atom_vals(j)
     157           12 :             IF (ia < 1 .OR. ia > natom) THEN
     158            0 :                CPABORT("UNFOLD_BAND| ATOMS index outside 1..natom")
     159              :             END IF
     160           12 :             IF (group_of_atom(ia) /= 0) THEN
     161            0 :                CPABORT("UNFOLD_BAND| ATOMS groups must be disjoint")
     162              :             END IF
     163           16 :             group_of_atom(ia) = g
     164              :          END DO
     165            8 :          NULLIFY (atom_vals)
     166              :       END DO
     167              :       ! no ATOMS keyword: all atoms form a single implicit group
     168           22 :       IF (n_atom_groups == 0) group_of_atom = 1
     169           26 :       uf%full_selection = ALL(group_of_atom /= 0)
     170            4 :       IF (n_atom_groups > 1 .AND. unit_nr > 0) THEN
     171            1 :          WRITE (unit_nr, FMT="(T2,A,I0,A)") "UNFOLD_BAND| atom groups: ", n_atom_groups, &
     172            2 :             " (weights per group; column 4 = total)"
     173            3 :          DO g = 1, n_atom_groups
     174            2 :             ia_first = 0
     175            2 :             ia_last = 0
     176           18 :             DO j = 1, natom
     177           18 :                IF (group_of_atom(j) == g) THEN
     178            6 :                   IF (ia_first == 0) ia_first = j
     179            6 :                   ia_last = j
     180              :                END IF
     181              :             END DO
     182            2 :             WRITE (unit_nr, FMT="(T2,A,I0,A,I0,A,I0,A,I0,A)") "UNFOLD_BAND| group ", g, ": ", &
     183           21 :                COUNT(group_of_atom == g), " atoms (first ", ia_first, ", last ", ia_last, ")"
     184              :          END DO
     185              :       END IF
     186            4 :       IF (n_atom_groups >= 1 .AND. unit_nr > 0) THEN
     187            1 :          WRITE (unit_nr, FMT="(T2,A,I0)") "UNFOLD_BAND| screened atoms (excluded): ", &
     188           10 :             COUNT(group_of_atom == 0)
     189              :       END IF
     190            4 :       IF (unit_nr > 0) THEN
     191           26 :          WRITE (unit_nr, FMT="(T2,A,9(1X,I3))") "UNFOLD_BAND| M (rows) =", TRANSPOSE(uf%transmat)
     192            2 :          WRITE (unit_nr, FMT="(T2,A,I0,A,F8.4)") "UNFOLD_BAND| m = |det M| = ", uf%m, &
     193            4 :             " ; site tolerance [angstrom] = ", uf%symm_tol*angstrom
     194            8 :          DO i = 1, 3
     195            6 :             WRITE (unit_nr, FMT="(T2,A,I0,A,3F12.6)") "UNFOLD_BAND| primitive cell vector ", i, &
     196           14 :                " [Bohr] =", uf%h_pc(1:3, i)
     197              :          END DO
     198              :       END IF
     199              :       ! mirror the neighbor-list anchoring convention (qs_neighbor_lists):
     200              :       ! stable images when the SCF ran k-points with symmetry, plain pbc otherwise
     201            4 :       stable_images = .FALSE.
     202            8 :       IF (ASSOCIATED(kpoints)) stable_images = kpoints%nkp > 0 .AND. kpoints%symmetry
     203              :       CALL unfolding_env_build_map(uf, cell, particle_set, qs_kind_set, group_of_atom, &
     204            4 :                                    stable_images, unit_nr)
     205              : 
     206            4 :       IF (bs_data_unit > 0 .AND. bs_data_unit /= unit_nr) THEN
     207           26 :          WRITE (UNIT=bs_data_unit, FMT="(A,9(1X,I3))") "# UNFOLD_BAND| M (rows) =", TRANSPOSE(uf%transmat)
     208            2 :          WRITE (UNIT=bs_data_unit, FMT="(A,I0,A,F8.4)") "# UNFOLD_BAND| m = |det M| = ", uf%m, &
     209            4 :             " ; site tolerance [angstrom] = ", uf%symm_tol*angstrom
     210            8 :          DO i = 1, 3
     211            6 :             WRITE (UNIT=bs_data_unit, FMT="(A,I0,A,3F14.8)") "# UNFOLD_BAND| primitive cell vector ", i, &
     212           14 :                " [Bohr] =", uf%h_pc(1:3, i)
     213              :          END DO
     214            2 :          WRITE (UNIT=bs_data_unit, FMT="(A,I0,A,I0)") "# UNFOLD_BAND| equivalent-site sets: ", &
     215            4 :             uf%n_sets, "; incomplete sets: ", uf%n_incomplete
     216            2 :          WRITE (UNIT=bs_data_unit, FMT="(A,I0,A,I0)") "# UNFOLD_BAND| atom groups: ", uf%n_groups, &
     217           20 :             " ; screened atoms: ", COUNT(group_of_atom == 0)
     218              :       END IF
     219              :       ! DFT+U inputs (nonzero lowdin_v) build S(K)^{1/2} inside the band structure
     220              :       ! diagonalization; rebuilding it for the weights would repeat the eigensolver
     221            4 :       IF (ASSOCIATED(kpoints)) THEN
     222            4 :          IF (ALLOCATED(kpoints%lowdin_v)) uf%lowdin_proj = ANY(kpoints%lowdin_v /= 0.0_dp)
     223              :       END IF
     224              : 
     225            4 :       DEALLOCATE (group_of_atom)
     226            4 :       CALL timestop(handle)
     227           16 :    END SUBROUTINE unfolding_setup
     228              : 
     229              : ! **************************************************************************************************
     230              : !> \brief Initialize the unfolding environment from the integer transformation matrix
     231              : !> \param uf unfolding environment
     232              : !> \param transmat 3x3 integer matrix, hmat_SC = hmat_PC . transmat
     233              : !> \param symm_tol site-assignment Cartesian tolerance in Bohr (internal units; the
     234              : !>        SYMM_TOL input is given in Angstrom), below half the smallest
     235              : !>        primitive-cell lattice plane distance
     236              : !> \param cart_hmat supercell cartesian lattice in Bohr (columns are the lattice vectors),
     237              : !>        already accounting for input-cell canonicalization
     238              : ! **************************************************************************************************
     239          104 :    SUBROUTINE unfolding_env_create(uf, transmat, symm_tol, cart_hmat)
     240              :       TYPE(unfolding_env_type), INTENT(OUT)              :: uf
     241              :       INTEGER, DIMENSION(3, 3), INTENT(IN)               :: transmat
     242              :       REAL(KIND=dp), INTENT(IN)                          :: symm_tol
     243              :       REAL(KIND=dp), DIMENSION(3, 3), INTENT(IN)         :: cart_hmat
     244              : 
     245              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'unfolding_env_create'
     246              : 
     247              :       CHARACTER(LEN=msg_length)                          :: msgstr
     248              :       INTEGER                                            :: handle, i
     249              :       REAL(KIND=dp)                                      :: plane_d_min
     250              :       REAL(KIND=dp), DIMENSION(3)                        :: plane_distance
     251              :       REAL(KIND=dp), DIMENSION(3, 3)                     :: m_dp, minv
     252              : 
     253            4 :       CALL timeset(routineN, handle)
     254              : 
     255           52 :       uf%transmat = transmat
     256            4 :       uf%symm_tol = symm_tol
     257           52 :       m_dp = REAL(transmat, KIND=dp)
     258            4 :       uf%m = ABS(NINT(det_3x3(m_dp)))
     259            4 :       IF (uf%m == 0) CPABORT("UNFOLD_BAND| TRANSFORMATION_MATRIX is singular")
     260              : 
     261            4 :       minv = inv_3x3(m_dp)
     262           16 :       DO i = 1, 3
     263          196 :          uf%h_pc(1:3, i) = MATMUL(cart_hmat(1:3, 1:3), minv(1:3, i))
     264              :       END DO
     265              : 
     266              :       ! plane distance of each cyclic pair of primitive lattice-vector columns:
     267              :       ! cell volume divided by the cross-product area
     268            4 :       plane_distance(1) = plane_dist_of(uf%h_pc, 2, 3)
     269            4 :       plane_distance(2) = plane_dist_of(uf%h_pc, 3, 1)
     270            4 :       plane_distance(3) = plane_dist_of(uf%h_pc, 1, 2)
     271              : 
     272              :       ! a tolerance below half the smallest primitive plane distance guarantees
     273              :       ! that componentwise rounding of ds recovers the nearest ideal site. It
     274              :       ! also rules out two ideal sites within tol of one atom
     275            4 :       IF (symm_tol <= 0.0_dp) THEN
     276            0 :          CPABORT("UNFOLD_BAND| SYMM_TOL must be positive")
     277              :       END IF
     278            4 :       plane_d_min = MIN(plane_distance(1), plane_distance(2), plane_distance(3))
     279            4 :       IF (symm_tol >= 0.5_dp*plane_d_min) THEN
     280              :          WRITE (UNIT=msgstr, FMT="(A,F8.3,A)") &
     281            0 :             "UNFOLD_BAND| SYMM_TOL must be smaller than ", &
     282            0 :             0.5_dp*plane_d_min*angstrom, " angstrom (half the smallest primitive plane distance)"
     283            0 :          CPABORT(TRIM(msgstr))
     284              :       END IF
     285              : 
     286            4 :       CALL timestop(handle)
     287            4 :    END SUBROUTINE unfolding_env_create
     288              : 
     289              : ! **************************************************************************************************
     290              : !> \brief Release the unfolding environment
     291              : !> \param uf ...
     292              : ! **************************************************************************************************
     293            4 :    SUBROUTINE unfolding_env_release(uf)
     294              :       TYPE(unfolding_env_type), INTENT(INOUT)            :: uf
     295              : 
     296            4 :       IF (ALLOCATED(uf%channel_of_ao)) DEALLOCATE (uf%channel_of_ao)
     297            4 :       IF (ALLOCATED(uf%n_of_ao)) DEALLOCATE (uf%n_of_ao)
     298            4 :       IF (ALLOCATED(uf%channel_group)) DEALLOCATE (uf%channel_group)
     299            4 :       uf%n_sets = 0
     300            4 :       uf%n_channels = 0
     301            4 :       uf%n_incomplete = 0
     302            4 :       uf%m = 0
     303            4 :    END SUBROUTINE unfolding_env_release
     304              : 
     305              : ! **************************************************************************************************
     306              : !> \brief Cluster supercell atoms into primitive-translation orbits (per-AO channels).
     307              : !>        Candidates are matched by element (atomic number; GHOST kinds equal their
     308              : !>        base element), and inside an orbit the basis set must be identical (nsgf
     309              : !>        and the flattened set->shell l sequence) - violations abort. Each atom
     310              : !>        joins the same-group, same-kind orbit whose ideal site lies within SYMM_TOL
     311              : !>        (Cartesian distance); a vacancy is a missing member (incomplete channel), any
     312              : !>        further primitive-cell basis atom or interstitial opens its own orbit. Slots
     313              : !>        are translation cosets (n = n' mod M Z^3); a slot claimed twice, or an atom
     314              : !>        matching two orbits, aborts - the partition is then atom-order dependent.
     315              : !>        Coordinates are wrapped with the convention of the k-point neighbor lists:
     316              : !>        pbc_stable when the SCF ran with k-point symmetry, plain pbc otherwise.
     317              : !> \param uf unfolding environment
     318              : !> \param cell supercell
     319              : !> \param particle_set supercell atoms
     320              : !> \param qs_kind_set kinds
     321              : !> \param group_of_atom (natom) 0 = fully screened, >= 1 = clustering group
     322              : !> \param stable_images wrap atoms with pbc_stable (SCF k-point symmetry anchoring)
     323              : !> \param unit_nr summary output unit (<= 0 suppresses)
     324              : ! **************************************************************************************************
     325            4 :    SUBROUTINE unfolding_env_build_map(uf, cell, particle_set, qs_kind_set, group_of_atom, &
     326              :                                       stable_images, unit_nr)
     327              :       TYPE(unfolding_env_type), INTENT(INOUT)            :: uf
     328              :       TYPE(cell_type), POINTER                           :: cell
     329              :       TYPE(particle_type), DIMENSION(:), POINTER         :: particle_set
     330              :       TYPE(qs_kind_type), DIMENSION(:), POINTER          :: qs_kind_set
     331              :       INTEGER, DIMENSION(:), INTENT(IN)                  :: group_of_atom
     332              :       LOGICAL, INTENT(IN)                                :: stable_images
     333              :       INTEGER, INTENT(IN)                                :: unit_nr
     334              : 
     335              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'unfolding_env_build_map'
     336              : 
     337              :       CHARACTER(LEN=default_string_length)               :: name_i, name_ref
     338              :       CHARACTER(LEN=msg_length)                          :: msgstr
     339              :       INTEGER :: handle, iao, iatom, idet, ikind, iset, ishell, j, jatom, kind_i, kind_r, &
     340              :          local_ao, lpos, lstore_max, nao, natom, nkind, nmemb, nref, nset, refj, z_i
     341            4 :       INTEGER, ALLOCATABLE, DIMENSION(:)                 :: channel_size, first_sgf, kind_lcount, &
     342            4 :                                                             kind_nsgf, kind_z, last_sgf, ref_atom, &
     343            4 :                                                             ref_base, slot_count
     344            4 :       INTEGER, ALLOCATABLE, DIMENSION(:, :)              :: kind_lseq, slot_atom
     345            4 :       INTEGER, ALLOCATABLE, DIMENSION(:, :, :)           :: slot_n
     346              :       INTEGER, DIMENSION(3)                              :: coset_test, dn, n_cand, n_int
     347              :       INTEGER, DIMENSION(3, 3)                           :: adj
     348            4 :       INTEGER, DIMENSION(:), POINTER                     :: nshell
     349            4 :       INTEGER, DIMENSION(:, :), POINTER                  :: lshell
     350              :       REAL(KIND=dp)                                      :: max_res, res, res_cand
     351            4 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :)        :: s_pbc
     352              :       REAL(KIND=dp), DIMENSION(3)                        :: dcart, ds, r_pbc
     353              :       REAL(KIND=dp), DIMENSION(3, 3)                     :: m_dp
     354              :       TYPE(gto_basis_set_type), POINTER                  :: basis_set
     355              : 
     356            4 :       CALL timeset(routineN, handle)
     357              : 
     358            4 :       natom = SIZE(particle_set)
     359           16 :       ALLOCATE (first_sgf(natom), last_sgf(natom))
     360            4 :       CALL get_particle_set(particle_set, qs_kind_set, first_sgf=first_sgf, last_sgf=last_sgf)
     361            4 :       nao = last_sgf(natom)
     362           20 :       ALLOCATE (uf%channel_of_ao(nao), uf%n_of_ao(3, nao))
     363          132 :       uf%channel_of_ao = 0
     364            8 :       ALLOCATE (uf%channel_group(nao))
     365          132 :       uf%channel_group = 0
     366              : 
     367              :       ! orbit candidates are matched by element (GHOST kinds carry their base
     368              :       ! element); within an orbit the basis must agree, so cache per kind the
     369              :       ! atomic number, nsgf, and the flattened set->shell l sequence (m = -l..l
     370              :       ! within a shell, hence the sequence pins every spherical function)
     371            4 :       nkind = SIZE(qs_kind_set)
     372           20 :       ALLOCATE (kind_z(nkind), kind_nsgf(nkind), kind_lcount(nkind))
     373           10 :       lstore_max = 0
     374           10 :       DO ikind = 1, nkind
     375            6 :          CALL get_qs_kind(qs_kind_set(ikind), zatom=kind_z(ikind))
     376            6 :          NULLIFY (basis_set)
     377            6 :          CALL get_qs_kind(qs_kind_set(ikind), basis_set=basis_set)
     378            6 :          IF (ASSOCIATED(basis_set)) THEN
     379            6 :             NULLIFY (nshell, lshell)
     380            6 :             CALL get_gto_basis_set(basis_set, nset=nset, nshell=nshell, l=lshell, nsgf=kind_nsgf(ikind))
     381           12 :             kind_lcount(ikind) = SUM(nshell(1:nset))
     382              :          ELSE
     383            0 :             kind_nsgf(ikind) = 0
     384            0 :             kind_lcount(ikind) = 0
     385              :          END IF
     386           10 :          lstore_max = MAX(lstore_max, kind_lcount(ikind))
     387              :       END DO
     388           16 :       ALLOCATE (kind_lseq(lstore_max, nkind))
     389            4 :       kind_lseq = 0
     390           10 :       DO ikind = 1, nkind
     391            6 :          IF (kind_lcount(ikind) == 0) CYCLE
     392            6 :          NULLIFY (basis_set, nshell, lshell)
     393            6 :          CALL get_qs_kind(qs_kind_set(ikind), basis_set=basis_set)
     394            6 :          CALL get_gto_basis_set(basis_set, nset=nset, nshell=nshell, l=lshell)
     395            6 :          lpos = 0
     396           12 :          DO iset = 1, nset
     397           24 :             DO ishell = 1, nshell(iset)
     398           12 :                lpos = lpos + 1
     399           18 :                kind_lseq(lpos, ikind) = lshell(ishell, iset)
     400              :             END DO
     401              :          END DO
     402           16 :          CPASSERT(lpos == kind_lcount(ikind))
     403              :       END DO
     404              : 
     405           12 :       ALLOCATE (s_pbc(3, natom))
     406           36 :       DO iatom = 1, natom
     407           32 :          IF (stable_images) THEN
     408            0 :             r_pbc(1:3) = pbc_stable(particle_set(iatom)%r(1:3), cell)
     409              :          ELSE
     410           32 :             r_pbc(1:3) = pbc(particle_set(iatom)%r(1:3), cell)
     411              :          END IF
     412           36 :          CALL real_to_scaled(s_pbc(1:3, iatom), r_pbc(1:3), cell)
     413              :       END DO
     414              : 
     415           12 :       ALLOCATE (ref_atom(natom), ref_base(natom))
     416           32 :       ALLOCATE (slot_n(3, uf%m, natom), slot_atom(uf%m, natom), slot_count(natom))
     417            4 :       slot_count = 0
     418            4 :       max_res = 0.0_dp
     419              :       ! integer adjugate and determinant: two translations n, n' belong to the same
     420              :       ! coset of the primitive lattice iff adj . (n - n') is divisible by det(M)
     421           52 :       m_dp = REAL(uf%transmat, KIND=dp)
     422           16 :       adj(1, 1:3) = NINT(vector_product(m_dp(1:3, 2), m_dp(1:3, 3)))
     423           16 :       adj(2, 1:3) = NINT(vector_product(m_dp(1:3, 3), m_dp(1:3, 1)))
     424           16 :       adj(3, 1:3) = NINT(vector_product(m_dp(1:3, 1), m_dp(1:3, 2)))
     425            4 :       idet = NINT(det_3x3(m_dp))
     426            4 :       nref = 0
     427            4 :       uf%n_sets = 0
     428            4 :       uf%n_channels = 0
     429            4 :       uf%n_incomplete = 0
     430           36 :       uf%n_groups = MAXVAL(group_of_atom(1:natom))
     431              : 
     432           36 :       DO iatom = 1, natom
     433           32 :          IF (group_of_atom(iatom) == 0) CYCLE
     434           28 :          kind_i = particle_set(iatom)%atomic_kind%kind_number
     435           28 :          z_i = kind_z(kind_i)
     436              : 
     437              :          ! the residual norm is frame-free (h_PC may sit in the input frame).
     438              :          ! The plane-distance validation rules out two sites within tol. A second
     439              :          ! matching orbit or a taken slot gives an atom-order-dependent partition
     440              :          ! and aborts
     441           28 :          refj = 0
     442           62 :          DO j = 1, nref
     443           34 :             jatom = ref_atom(j)
     444           34 :             IF (group_of_atom(jatom) /= group_of_atom(iatom)) CYCLE
     445           28 :             IF (kind_z(particle_set(jatom)%atomic_kind%kind_number) /= z_i) CYCLE
     446              :             ds(1:3) = MATMUL(REAL(uf%transmat(1:3, 1:3), KIND=dp), &
     447          784 :                              s_pbc(1:3, iatom) - s_pbc(1:3, jatom))
     448          112 :             n_int(1:3) = NINT(ds(1:3))
     449          448 :             dcart(1:3) = MATMUL(uf%h_pc(1:3, 1:3), ds(1:3) - REAL(n_int(1:3), KIND=dp))
     450          112 :             res = NORM2(dcart(1:3))
     451           28 :             IF (res >= uf%symm_tol) CYCLE
     452           56 :             DO nmemb = 1, slot_count(j)
     453          144 :                dn(1:3) = n_int(1:3) - slot_n(1:3, nmemb, j)
     454          468 :                coset_test(1:3) = MATMUL(adj(1:3, 1:3), dn(1:3))
     455           68 :                IF (ALL(MOD(coset_test(1:3), idet) == 0)) THEN
     456            0 :                   WRITE (UNIT=msgstr, FMT="(A,I0,A,I0,A)") "UNFOLD_BAND| assignment conflict: atoms ", &
     457            0 :                      iatom, " and ", slot_atom(nmemb, j), &
     458            0 :                      " map to the same equivalent-site slot. Set a smaller SYMM_TOL."
     459            0 :                   CPABORT(TRIM(msgstr))
     460              :                END IF
     461              :             END DO
     462           20 :             IF (refj /= 0) THEN
     463            0 :                WRITE (UNIT=msgstr, FMT="(A,I0,A)") "UNFOLD_BAND| ambiguous site for atom ", iatom, &
     464            0 :                   ": it matches several equivalent-site sets. Set a smaller SYMM_TOL or use ATOMS groups."
     465            0 :                CPABORT(TRIM(msgstr))
     466              :             END IF
     467           20 :             refj = j
     468           20 :             n_cand(1:3) = n_int(1:3)
     469           48 :             res_cand = res
     470              :          END DO
     471              : 
     472           28 :          IF (refj /= 0) THEN
     473              :             ! basis-set consistency inside the orbit: same element with a
     474              :             ! different basis must be excluded from this orbit (put such atoms
     475              :             ! in a separate ATOMS group to unfold them independently)
     476           20 :             kind_r = particle_set(ref_atom(refj))%atomic_kind%kind_number
     477              :             IF (kind_nsgf(kind_i) /= kind_nsgf(kind_r) .OR. &
     478           60 :                 kind_lcount(kind_i) /= kind_lcount(kind_r) .OR. &
     479              :                 ANY(kind_lseq(1:kind_lcount(kind_i), kind_i) /= kind_lseq(1:kind_lcount(kind_r), kind_r))) THEN
     480            0 :                CALL get_qs_kind(qs_kind_set(kind_i), name=name_i)
     481            0 :                CALL get_qs_kind(qs_kind_set(kind_r), name=name_ref)
     482              :                WRITE (UNIT=msgstr, FMT="(A,I0,A,I0,A,A,A,A,A)") &
     483            0 :                   "UNFOLD_BAND| atoms ", iatom, " and ", ref_atom(refj), &
     484            0 :                   " (kinds ", TRIM(name_i), " / ", TRIM(name_ref), &
     485            0 :                   ") differ in basis set. Put them in separate ATOMS groups."
     486            0 :                CPABORT(TRIM(msgstr))
     487              :             END IF
     488              :          END IF
     489              : 
     490              :          IF (refj == 0) THEN
     491            8 :             nref = nref + 1
     492            8 :             refj = nref
     493            8 :             ref_atom(refj) = iatom
     494            8 :             ref_base(refj) = uf%n_channels + 1
     495            8 :             uf%n_channels = uf%n_channels + (last_sgf(iatom) - first_sgf(iatom) + 1)
     496           40 :             uf%channel_group(ref_base(refj):uf%n_channels) = group_of_atom(iatom)
     497            8 :             n_cand(1:3) = 0
     498            8 :             res_cand = 0.0_dp
     499              :          END IF
     500              : 
     501           28 :          slot_count(refj) = slot_count(refj) + 1
     502          112 :          slot_n(1:3, slot_count(refj), refj) = n_cand(1:3)
     503           28 :          slot_atom(slot_count(refj), refj) = iatom
     504           28 :          max_res = MAX(max_res, res_cand)
     505              : 
     506          144 :          DO local_ao = first_sgf(iatom), last_sgf(iatom)
     507          112 :             uf%channel_of_ao(local_ao) = ref_base(refj) + (local_ao - first_sgf(iatom))
     508          480 :             uf%n_of_ao(1:3, local_ao) = n_cand(1:3)
     509              :          END DO
     510              :       END DO
     511              : 
     512              :       ! each coset hosts at most one atom, so channel_size equals the member count
     513           12 :       ALLOCATE (channel_size(uf%n_channels))
     514            4 :       channel_size = 0
     515          132 :       DO iao = 1, nao
     516          132 :          IF (uf%channel_of_ao(iao) > 0) THEN
     517          112 :             channel_size(uf%channel_of_ao(iao)) = channel_size(uf%channel_of_ao(iao)) + 1
     518              :          END IF
     519              :       END DO
     520           36 :       IF (ANY(channel_size > uf%m)) THEN
     521            0 :          CPABORT("UNFOLD_BAND| equivalent-site channel overflow: check TRANSFORMATION_MATRIX/SYMM_TOL")
     522              :       END IF
     523            4 :       uf%n_sets = nref
     524           12 :       uf%n_incomplete = COUNT(slot_count(1:nref) < uf%m)
     525              : 
     526            4 :       IF (unit_nr > 0) THEN
     527            2 :          WRITE (UNIT=unit_nr, FMT="(T2,A,I0,A,I0,A,I0)") "UNFOLD_BAND| equivalent-site sets: ", &
     528            2 :             uf%n_sets, " (", uf%n_channels, " AO channels); incomplete sets (vacancies): ", &
     529            4 :             uf%n_incomplete
     530            2 :          WRITE (UNIT=unit_nr, FMT="(T2,A,F12.6)") "UNFOLD_BAND| max assignment residual [angstrom] = ", &
     531            4 :             max_res*angstrom
     532              :       END IF
     533              : 
     534            0 :       DEALLOCATE (channel_size, first_sgf, last_sgf, kind_lcount, kind_lseq, kind_nsgf, kind_z, ref_atom, &
     535            4 :                   ref_base, slot_n, slot_atom, slot_count, s_pbc)
     536            4 :       CALL timestop(handle)
     537            4 :    END SUBROUTINE unfolding_env_build_map
     538              : 
     539              : ! **************************************************************************************************
     540              : !> \brief Fold primitive-cell k-points onto deduplicated supercell K-points
     541              : !> \param uf unfolding environment
     542              : !> \param kppath (3, npoints) primitive fractional k-points
     543              : !> \param kpfolded (3, nfold) unique supercell K in [-0.5, 0.5)
     544              : !> \param path2K (npoints) folded-K index of each path point
     545              : !> \param nfold number of unique supercell K-points
     546              : ! **************************************************************************************************
     547            4 :    SUBROUTINE unfolding_fold_kpath(uf, kppath, kpfolded, path2K, nfold)
     548              :       TYPE(unfolding_env_type), INTENT(IN)               :: uf
     549              :       REAL(KIND=dp), DIMENSION(:, :), INTENT(IN)         :: kppath
     550              :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :), &
     551              :          INTENT(OUT)                                     :: kpfolded
     552              :       INTEGER, ALLOCATABLE, DIMENSION(:), INTENT(OUT)    :: path2K
     553              :       INTEGER, INTENT(OUT)                               :: nfold
     554              : 
     555              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'unfolding_fold_kpath'
     556              : 
     557              :       INTEGER                                            :: handle, ik, jk, npoints
     558              :       REAL(KIND=dp), DIMENSION(3)                        :: dvec, ffold
     559              : 
     560            4 :       CALL timeset(routineN, handle)
     561              : 
     562            4 :       npoints = SIZE(kppath, 2)
     563           20 :       ALLOCATE (kpfolded(3, npoints), path2K(npoints))
     564            4 :       path2K = 0
     565            4 :       nfold = 0
     566           18 :       DO ik = 1, npoints
     567              :          ! F = M^T f (paper row convention f.M); wrap into [-0.5, 0.5)
     568          350 :          ffold(1:3) = MATMUL(TRANSPOSE(REAL(uf%transmat(1:3, 1:3), KIND=dp)), kppath(1:3, ik))
     569           56 :          ffold(1:3) = ffold(1:3) - ANINT(ffold(1:3))
     570           22 :          DO jk = 1, nfold
     571           48 :             dvec(1:3) = ffold(1:3) - kpfolded(1:3, jk)
     572           48 :             dvec(1:3) = dvec(1:3) - ANINT(dvec(1:3))
     573           58 :             IF (MAXVAL(ABS(dvec(1:3))) < kdifftol) THEN
     574            4 :                path2K(ik) = jk
     575            4 :                EXIT
     576              :             END IF
     577              :          END DO
     578           18 :          IF (path2K(ik) == 0) THEN
     579           10 :             nfold = nfold + 1
     580           40 :             kpfolded(1:3, nfold) = ffold(1:3)
     581           10 :             path2K(ik) = nfold
     582              :          END IF
     583              :       END DO
     584            4 :       CALL timestop(handle)
     585            4 :    END SUBROUTINE unfolding_fold_kpath
     586              : 
     587              : ! **************************************************************************************************
     588              : !> \brief Accumulate unfolding weights, eigenvalues, and occupations for one batch of unique
     589              : !>        supercell K-points into the full-set arrays. Releases per-K MO coefficients and
     590              : !>        S(K)^{1/2} progressively as each K-point is processed.
     591              : !> \param uf unfolding environment
     592              : !> \param qs_env ...
     593              : !> \param kpoint batch of unique supercell K-points with their MOs
     594              : !> \param kpgeneral (3, npoints) primitive-cell path points
     595              : !> \param path2K (npoints) global supercell K-point index of each path point
     596              : !> \param k_offset global index offset preceding this batch (first batch has k_offset = 0)
     597              : !> \param wall (npoints, nmo, 0:n_groups, nspins) accumulated unfolding weights (slice 0 = total)
     598              : !> \param eigval_all (nmo, nfold, nspins) accumulated band eigenvalues
     599              : !> \param occnum_all (nmo, nfold, nspins) accumulated band occupations
     600              : !> \param sumdev running maximum deviation from the subspace sum rule across batches
     601              : ! **************************************************************************************************
     602            4 :    SUBROUTINE unfolding_process_batch(uf, qs_env, kpoint, kpgeneral, path2K, k_offset, &
     603            4 :                                       wall, eigval_all, occnum_all, sumdev)
     604              :       TYPE(unfolding_env_type), INTENT(IN)               :: uf
     605              :       TYPE(qs_environment_type), POINTER                 :: qs_env
     606              :       TYPE(kpoint_type), POINTER                         :: kpoint
     607              :       REAL(KIND=dp), DIMENSION(:, :), INTENT(IN)         :: kpgeneral
     608              :       INTEGER, DIMENSION(:), INTENT(IN)                  :: path2K
     609              :       INTEGER, INTENT(IN)                                :: k_offset
     610              :       REAL(KIND=dp), DIMENSION(:, :, 0:, :), &
     611              :          INTENT(INOUT)                                   :: wall
     612              :       REAL(KIND=dp), DIMENSION(:, :, :), INTENT(INOUT)   :: eigval_all, occnum_all
     613              :       REAL(KIND=dp), INTENT(INOUT)                       :: sumdev
     614              : 
     615              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'unfolding_process_batch'
     616              : 
     617              :       INTEGER                                            :: handle, ik, ik_glob, ikpgr, iq, iqc, &
     618              :                                                             ispin, jpath, nfold_b, nmo, npoints, &
     619              :                                                             nspins
     620              :       INTEGER, DIMENSION(2)                              :: kp_range
     621              :       LOGICAL                                            :: is_kp_source
     622              :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:)           :: psub
     623            4 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :)        :: fqs
     624              :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :, :)     :: wmat
     625              :       REAL(KIND=dp), DIMENSION(3)                        :: dvec
     626            4 :       REAL(KIND=dp), DIMENSION(:), POINTER               :: eigenvalues, occupation_numbers
     627            4 :       REAL(KIND=dp), DIMENSION(:, :), POINTER            :: xkp
     628            4 :       TYPE(dbcsr_p_type), DIMENSION(:, :), POINTER       :: matrix_s
     629              :       TYPE(kpoint_env_type), POINTER                     :: kp
     630              :       TYPE(qs_scf_env_type), POINTER                     :: scf_env
     631              : 
     632            4 :       CALL timeset(routineN, handle)
     633              : 
     634            4 :       NULLIFY (matrix_s, scf_env)
     635            4 :       CALL get_qs_env(qs_env, matrix_s_kp=matrix_s, scf_env=scf_env)
     636            4 :       npoints = SIZE(path2K)
     637            4 :       nmo = SIZE(wall, 2)
     638            4 :       nspins = SIZE(wall, 4)
     639              : 
     640              :       ! S(k)^{1/2} of the batch's local K-points, reused across spins and path points
     641            4 :       IF (.NOT. uf%lowdin_proj) CALL diag_kp_smat(matrix_s, kpoint, scf_env%scf_work1)
     642            4 :       CALL get_kpoint_info(kpoint, nkp=nfold_b, kp_range=kp_range, xkp=xkp)
     643            4 :       is_kp_source = kpoint%para_env_kp%is_source()
     644              : 
     645           28 :       ALLOCATE (wmat(uf%m, nmo, 0:uf%n_groups), psub(nmo))
     646           14 :       DO ik = 1, nfold_b
     647           10 :          IF (ik < kp_range(1) .OR. ik > kp_range(2)) CYCLE
     648            5 :          ik_glob = k_offset + ik
     649            5 :          ikpgr = ik - kp_range(1) + 1
     650            5 :          kp => kpoint%kp_env(ikpgr)%kpoint_env
     651            5 :          CALL unfolding_unfolded_kspace(uf, xkp(1:3, ik), fqs)
     652           10 :          DO ispin = 1, nspins
     653            5 :             CALL unfolding_kp_weights(uf, kp, ispin, fqs, wmat, psub)
     654              :             ! generalized subspace sum rule: holds for screened selections too
     655          505 :             sumdev = MAX(sumdev, MAXVAL(ABS(SUM(wmat(:, 1:nmo, 0), 1) - psub(1:nmo))))
     656              :             ! with all atoms selected the Loewdin populations are the MO
     657              :             ! S-orthonormality row sums and must equal 1
     658          105 :             IF (uf%full_selection .AND. MAXVAL(ABS(psub(1:nmo) - 1.0_dp)) > mo_orthonorm_tol) THEN
     659            0 :                CPABORT("UNFOLD_BAND| the full-selection Loewdin population deviates from 1")
     660              :             END IF
     661              :             ! Only the source rank of the owning k-point group records each K-point's
     662              :             ! entries so a single world para_env%sum works even if group sizes vary across batches.
     663            5 :             IF (is_kp_source) THEN
     664            5 :                CALL get_mo_set(kp%mos(ispin), eigenvalues=eigenvalues, occupation_numbers=occupation_numbers)
     665          105 :                eigval_all(1:nmo, ik_glob, ispin) = eigenvalues(1:nmo)
     666          105 :                occnum_all(1:nmo, ik_glob, ispin) = occupation_numbers(1:nmo)
     667              :             END IF
     668           23 :             DO jpath = 1, npoints
     669           18 :                IF (path2K(jpath) /= ik_glob) CYCLE
     670            7 :                iq = 0
     671           11 :                DO iqc = 1, SIZE(fqs, 2)
     672           44 :                   dvec(1:3) = fqs(1:3, iqc) - kpgeneral(1:3, jpath)
     673           44 :                   dvec(1:3) = dvec(1:3) - ANINT(dvec(1:3))
     674           44 :                   IF (MAXVAL(ABS(dvec(1:3))) < kdifftol) THEN
     675              :                      iq = iqc
     676              :                      EXIT
     677              :                   END IF
     678              :                END DO
     679            7 :                IF (iq == 0) THEN
     680            0 :                   CPABORT("UNFOLD_BAND| path point not in unfolded set")
     681              :                END IF
     682           12 :                IF (is_kp_source) THEN
     683          385 :                   wall(jpath, 1:nmo, 0:uf%n_groups, ispin) = wmat(iq, 1:nmo, 0:uf%n_groups)
     684              :                END IF
     685              :             END DO
     686           10 :             IF (ASSOCIATED(kp%mos(ispin)%cmo_coeff)) THEN
     687            5 :                CALL cp_cfm_release(kp%mos(ispin)%cmo_coeff)
     688            5 :                DEALLOCATE (kp%mos(ispin)%cmo_coeff)
     689            5 :                NULLIFY (kp%mos(ispin)%cmo_coeff)
     690              :             END IF
     691              :          END DO
     692            5 :          CALL cp_cfm_release(kp%cshalf)
     693           14 :          DEALLOCATE (fqs)
     694              :       END DO
     695            4 :       DEALLOCATE (wmat, psub)
     696              : 
     697            4 :       CALL timestop(handle)
     698            8 :    END SUBROUTINE unfolding_process_batch
     699              : 
     700              : ! **************************************************************************************************
     701              : !> \brief Reduce accumulated unfolding results across MPI ranks and write the unfolded band
     702              : !>        structure set and sum-rule check
     703              : !> \param para_env global MPI communicator
     704              : !> \param kpfolded (3, nfold) unique supercell K-points
     705              : !> \param kpgeneral (3, npoints) primitive-cell path points
     706              : !> \param path2K (npoints) supercell K-point index of each path point
     707              : !> \param eigval_all (nmo, nfold, nspins) band eigenvalues (reduced in place)
     708              : !> \param occnum_all (nmo, nfold, nspins) band occupations (reduced in place)
     709              : !> \param wall (npoints, nmo, 0:n_groups, nspins) unfolding weights (reduced in place)
     710              : !> \param sumdev maximum subspace sum-rule deviation (reduced in place)
     711              : !> \param unit_nr default output unit
     712              : !> \param bs_data_unit band structure data unit
     713              : ! **************************************************************************************************
     714            4 :    SUBROUTINE unfolding_finish_set(para_env, kpfolded, kpgeneral, path2K, eigval_all, occnum_all, &
     715            4 :                                    wall, sumdev, unit_nr, bs_data_unit)
     716              :       TYPE(mp_para_env_type), INTENT(IN)                 :: para_env
     717              :       REAL(KIND=dp), DIMENSION(:, :), INTENT(IN)         :: kpfolded, kpgeneral
     718              :       INTEGER, DIMENSION(:), INTENT(IN)                  :: path2K
     719              :       REAL(KIND=dp), DIMENSION(:, :, :), INTENT(INOUT)   :: eigval_all, occnum_all
     720              :       REAL(KIND=dp), DIMENSION(:, :, 0:, :), &
     721              :          INTENT(INOUT)                                   :: wall
     722              :       REAL(KIND=dp), INTENT(INOUT)                       :: sumdev
     723              :       INTEGER, INTENT(IN)                                :: unit_nr, bs_data_unit
     724              : 
     725              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'unfolding_finish_set'
     726              : 
     727              :       INTEGER                                            :: g, handle, ik, ikmap, imo, ispin, &
     728              :                                                             n_groups, ngrp_out, nmo, npoints, &
     729              :                                                             nspins
     730              :       REAL(KIND=dp)                                      :: path_weight
     731              : 
     732            4 :       CALL timeset(routineN, handle)
     733              : 
     734         1872 :       CALL para_env%sum(wall)
     735          432 :       CALL para_env%sum(eigval_all)
     736          432 :       CALL para_env%sum(occnum_all)
     737            4 :       CALL para_env%max(sumdev)
     738              : 
     739            4 :       IF (bs_data_unit > 0) THEN
     740            2 :          npoints = SIZE(wall, 1)
     741            2 :          nmo = SIZE(wall, 2)
     742            2 :          n_groups = UBOUND(wall, 3)  ! group axis of wall runs 0:n_groups (0 = total)
     743            2 :          nspins = SIZE(wall, 4)
     744            2 :          path_weight = 1.0_dp/REAL(npoints, KIND=dp)
     745              :          ! per-group weight columns only for two or more groups: a single group equals the total
     746            2 :          ngrp_out = MERGE(n_groups, 0, n_groups >= 2)
     747              : 
     748            9 :          DO ik = 1, npoints
     749            7 :             ikmap = path2K(ik)
     750           16 :             DO ispin = 1, nspins
     751              :                WRITE (UNIT=bs_data_unit, FMT="(A,I0,A,I0,A,3(1X,F14.8))") &
     752            7 :                   "# UNFOLD_BAND| path point ", ik, " -> SC K #", ikmap, " :", kpfolded(1:3, ikmap)
     753              :                WRITE (UNIT=bs_data_unit, FMT="(A,I0,T15,A,I0,A,T24,3(1X,F14.8),3X,F14.8)") &
     754            7 :                   "#  Point ", ik, "  Spin ", ispin, ":", kpgeneral(1:3, ik), path_weight
     755              :                WRITE (UNIT=bs_data_unit, FMT="(A)", ADVANCE="NO") &
     756            7 :                   "#   Band    Energy [eV]     Occupation   Unfold_Weight"
     757           15 :                DO g = 1, ngrp_out
     758           15 :                   WRITE (UNIT=bs_data_unit, FMT="(A,I0)", ADVANCE="NO") "   W_grp", g
     759              :                END DO
     760            7 :                WRITE (UNIT=bs_data_unit, FMT="(A)") ""
     761          154 :                DO imo = 1, nmo
     762          140 :                   WRITE (UNIT=bs_data_unit, FMT="(T2,I7,*(1X,F14.8))") imo, &
     763          140 :                      eigval_all(imo, ikmap, ispin)*evolt, occnum_all(imo, ikmap, ispin), &
     764          287 :                      (wall(ik, imo, g, ispin), g=0, ngrp_out)
     765              :                END DO
     766              :             END DO
     767              :          END DO
     768              :       END IF
     769              : 
     770            4 :       IF (unit_nr > 0) THEN
     771              :          WRITE (unit_nr, FMT="(T2,A,ES9.2)") &
     772            2 :             "UNFOLD_BAND| Set check max|sum_q W - Loewdin population| = ", sumdev
     773              :       END IF
     774              : 
     775            4 :       CALL timestop(handle)
     776            4 :    END SUBROUTINE unfolding_finish_set
     777              : 
     778              : ! **************************************************************************************************
     779              : !> \brief The m primitive k-points f (in [0,1)) with M^T f = K (mod 1)
     780              : !> \param uf unfolding environment
     781              : !> \param K supercell fractional k-point
     782              : !> \param fqs (3, m) unfolded primitive k-points
     783              : ! **************************************************************************************************
     784            5 :    SUBROUTINE unfolding_unfolded_kspace(uf, K, fqs)
     785              :       TYPE(unfolding_env_type), INTENT(IN)               :: uf
     786              :       REAL(KIND=dp), DIMENSION(3), INTENT(IN)            :: K
     787              :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :), &
     788              :          INTENT(OUT)                                     :: fqs
     789              : 
     790              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'unfolding_unfolded_kspace'
     791              : 
     792              :       INTEGER                                            :: handle, nfound, px, py, pz, r
     793              :       INTEGER, DIMENSION(3)                              :: phi, plo
     794              :       REAL(KIND=dp), DIMENSION(3)                        :: f, pshift
     795              :       REAL(KIND=dp), DIMENSION(3, 3)                     :: minvt
     796              : 
     797            5 :       CALL timeset(routineN, handle)
     798              : 
     799              :       ! p = M^T f - K with f in [0,1): component r of M^T f lies between the sums of
     800              :       ! the negative and positive entries of column r of M; shifting by the K range
     801              :       ! [-0.5, 0.5) keeps these integer bounds exact (no slack needed)
     802          130 :       minvt = TRANSPOSE(inv_3x3(REAL(uf%transmat, KIND=dp)))
     803           20 :       DO r = 1, 3
     804           60 :          plo(r) = SUM(MIN(uf%transmat(1:3, r), 0))
     805           65 :          phi(r) = SUM(MAX(uf%transmat(1:3, r), 0))
     806              :       END DO
     807              : 
     808           15 :       ALLOCATE (fqs(3, uf%m))
     809            5 :       nfound = 0
     810           25 :       DO px = plo(1), phi(1)
     811          105 :          DO py = plo(2), phi(2)
     812          420 :             DO pz = plo(3), phi(3)
     813         1280 :                pshift(1:3) = REAL([px, py, pz], KIND=dp)
     814         5120 :                f(1:3) = MATMUL(minvt(1:3, 1:3), K(1:3) + pshift(1:3))
     815         1853 :                IF (ALL(f(1:3) >= -unit_tol) .AND. ALL(f(1:3) < 1.0_dp - unit_tol)) THEN
     816           20 :                   nfound = nfound + 1
     817           20 :                   IF (nfound > uf%m) CPABORT("UNFOLD_BAND| unfolded k set larger than m")
     818           80 :                   fqs(1:3, nfound) = MAX(f(1:3), 0.0_dp)
     819              :                END IF
     820              :             END DO
     821              :          END DO
     822              :       END DO
     823            5 :       IF (nfound /= uf%m) THEN
     824            0 :          CPABORT("UNFOLD_BAND| unfolded k set incomplete. Check TRANSFORMATION_MATRIX.")
     825              :       END IF
     826            5 :       CALL timestop(handle)
     827            5 :    END SUBROUTINE unfolding_unfolded_kspace
     828              : 
     829              : ! **************************************************************************************************
     830              : !> \brief Unfolding weights for one local k-point environment (complex wavefunctions).
     831              : !>        Requires kp%cshalf, i.e. diag_kp_smat must have run for this kpoint object.
     832              : !>        Per atom group the weights obey the generalized subspace sum rule
     833              : !>        sum_q W^k_q_KN(group) = sum_{mu in group} |C'_muN|^2 (Loewdin population);
     834              : !>        slice 0 carries the total over all selected atoms (= 1 for a full selection).
     835              : !> \param uf unfolding environment with orbit map
     836              : !> \param kp k-point environment (one local K)
     837              : !> \param ispin spin index
     838              : !> \param fqs (3, nq) unfolded primitive k-points of this K
     839              : !> \param weights (nq, nmo, 0:n_groups) spectral weights; slice 0 = total
     840              : !> \param psubspace (nmo) Loewdin population of the selected atoms per band
     841              : ! **************************************************************************************************
     842            5 :    SUBROUTINE unfolding_kp_weights(uf, kp, ispin, fqs, weights, psubspace)
     843              :       TYPE(unfolding_env_type), INTENT(IN)               :: uf
     844              :       TYPE(kpoint_env_type), POINTER                     :: kp
     845              :       INTEGER, INTENT(IN)                                :: ispin
     846              :       REAL(KIND=dp), DIMENSION(:, :), INTENT(IN)         :: fqs
     847              :       REAL(KIND=dp), DIMENSION(:, :, 0:), INTENT(OUT)    :: weights
     848              :       REAL(KIND=dp), DIMENSION(:), INTENT(OUT)           :: psubspace
     849              : 
     850              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'unfolding_kp_weights'
     851              : 
     852            5 :       COMPLEX(KIND=dp), ALLOCATABLE, DIMENSION(:)        :: phase_loc
     853            5 :       COMPLEX(KIND=dp), ALLOCATABLE, DIMENSION(:, :)     :: tsum
     854              :       COMPLEX(KIND=dp), CONTIGUOUS, DIMENSION(:, :), &
     855            5 :          POINTER                                         :: local_data
     856              :       INTEGER                                            :: g, handle, iao, ich, icol, imo, iq, &
     857              :                                                             irow, j1, j2, jloc, mo_blk, nao, nb, &
     858              :                                                             ncol_local, nmo, nq, nrow_local
     859            5 :       INTEGER, DIMENSION(:), POINTER                     :: col_indices, row_indices
     860              :       REAL(KIND=dp)                                      :: arg
     861              :       TYPE(cp_cfm_type)                                  :: cwork
     862              :       TYPE(mo_set_type), POINTER                         :: mo_set
     863              :       TYPE(mp_para_env_type), POINTER                    :: para_env_kp
     864              : 
     865            5 :       CALL timeset(routineN, handle)
     866              : 
     867            5 :       NULLIFY (mo_set, local_data, row_indices, col_indices, para_env_kp)
     868            5 :       mo_set => kp%mos(ispin)
     869            5 :       CALL get_mo_set(mo_set, nao=nao, nmo=nmo)
     870            5 :       IF (.NOT. ASSOCIATED(mo_set%cmo_coeff)) THEN
     871            0 :          CPABORT("UNFOLD_BAND| complex MO coefficients expected (band structure k-points)")
     872              :       END IF
     873            5 :       IF (.NOT. ASSOCIATED(kp%cshalf%matrix_struct)) THEN
     874            0 :          CPABORT("UNFOLD_BAND| kp%cshalf is missing. diag_kp_smat must run before unfolding.")
     875              :       END IF
     876              : 
     877            5 :       nq = SIZE(fqs, 2)
     878            5 :       CALL cp_cfm_create(cwork, mo_set%cmo_coeff%matrix_struct)
     879            5 :       CALL lowdin_kp_mo_coeff(kp, ispin, .FALSE., cshalfc=cwork)
     880              :       CALL cp_cfm_get_info(cwork, nrow_local=nrow_local, ncol_local=ncol_local, &
     881              :                            row_indices=row_indices, col_indices=col_indices, &
     882            5 :                            local_data=local_data, para_env=para_env_kp)
     883              : 
     884              :       ! Loewdin population of the selected atoms: the generalized sum-rule reference
     885          105 :       psubspace(1:nmo) = 0.0_dp
     886          105 :       DO icol = 1, ncol_local
     887          100 :          imo = col_indices(icol)
     888         3305 :          DO irow = 1, nrow_local
     889         3200 :             iao = row_indices(irow)
     890         3300 :             IF (uf%channel_of_ao(iao) > 0) THEN
     891         2720 :                psubspace(imo) = psubspace(imo) + ABS(local_data(irow, icol))**2
     892              :             END IF
     893              :          END DO
     894              :       END DO
     895            5 :       IF (para_env_kp%num_pe > 1) CALL para_env_kp%sum(psubspace(1:nmo))
     896              : 
     897            5 :       mo_blk = MAX(1, MIN(nmo, unfolding_mo_block))
     898           30 :       ALLOCATE (phase_loc(nrow_local), tsum(uf%n_channels, mo_blk))
     899         1318 :       weights = 0.0_dp
     900           25 :       DO iq = 1, nq
     901          660 :          DO irow = 1, nrow_local
     902          640 :             iao = row_indices(irow)
     903          640 :             IF (uf%channel_of_ao(iao) == 0) CYCLE
     904         2176 :             arg = -twopi*DOT_PRODUCT(fqs(1:3, iq), REAL(uf%n_of_ao(1:3, iao), KIND=dp))
     905          660 :             phase_loc(irow) = EXP(CMPLX(0.0_dp, arg, KIND=dp))
     906              :          END DO
     907           45 :          DO j1 = 1, nmo, mo_blk
     908           20 :             j2 = MIN(nmo, j1 + mo_blk - 1)
     909           20 :             nb = j2 - j1 + 1
     910         3620 :             tsum(1:uf%n_channels, 1:nb) = (0.0_dp, 0.0_dp)
     911          420 :             DO icol = 1, ncol_local
     912          400 :                imo = col_indices(icol)
     913          400 :                IF (imo < j1 .OR. imo > j2) CYCLE
     914          400 :                jloc = imo - j1 + 1
     915        13220 :                DO irow = 1, nrow_local
     916        12800 :                   iao = row_indices(irow)
     917        12800 :                   ich = uf%channel_of_ao(iao)
     918        12800 :                   IF (ich == 0) CYCLE
     919        13200 :                   tsum(ich, jloc) = tsum(ich, jloc) + phase_loc(irow)*local_data(irow, icol)
     920              :                END DO
     921              :             END DO
     922           20 :             IF (para_env_kp%num_pe > 1) CALL para_env_kp%sum(tsum(1:uf%n_channels, 1:nb))
     923          440 :             DO jloc = 1, nb
     924          400 :                imo = j1 + jloc - 1
     925         3620 :                DO ich = 1, uf%n_channels
     926         3200 :                   g = uf%channel_group(ich)
     927         3600 :                   weights(iq, imo, g) = weights(iq, imo, g) + ABS(tsum(ich, jloc))**2
     928              :                END DO
     929              :             END DO
     930              :          END DO
     931              :       END DO
     932            5 :       CALL cp_cfm_release(cwork)
     933         1318 :       weights(1:nq, 1:nmo, 0:uf%n_groups) = weights(1:nq, 1:nmo, 0:uf%n_groups)/REAL(uf%m, KIND=dp)
     934           13 :       DO g = 1, uf%n_groups
     935          813 :          weights(1:nq, 1:nmo, 0) = weights(1:nq, 1:nmo, 0) + weights(1:nq, 1:nmo, g)
     936              :       END DO
     937              : 
     938            5 :       DEALLOCATE (phase_loc, tsum)
     939            5 :       CALL timestop(handle)
     940           15 :    END SUBROUTINE unfolding_kp_weights
     941              : 
     942              : ! **************************************************************************************************
     943              : !> \brief Plane distance of lattice-vector columns j and k of a cell (columns)
     944              : !> \param h ...
     945              : !> \param j ...
     946              : !> \param k ...
     947              : !> \return ...
     948              : ! **************************************************************************************************
     949           12 :    PURE FUNCTION plane_dist_of(h, j, k) RESULT(d)
     950              :       REAL(KIND=dp), DIMENSION(3, 3), INTENT(IN)         :: h
     951              :       INTEGER, INTENT(IN)                                :: j, k
     952              :       REAL(KIND=dp)                                      :: d
     953              : 
     954           48 :       d = ABS(det_3x3(h))/NORM2(vector_product(h(1:3, j), h(1:3, k)))
     955           12 :    END FUNCTION plane_dist_of
     956              : 
     957            0 : END MODULE kpoint_unfolding
        

Generated by: LCOV version 2.0-1