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

            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 Builds the shared RI-RS grid, AO collocation and fitting representation.
      10              : !> \par History
      11              : !>      09.2026 created Jan Wilhelm
      12              : !>      09.2026 moved code by Ritaj Tyagi from gw_ri_rs_non_periodic.F
      13              : !>      09.2026 added routine to compute Z_lP for automatic RI optimization
      14              : ! **************************************************************************************************
      15              : MODULE ri_rs_setup
      16              :    USE atomic_kind_types,               ONLY: atomic_kind_type
      17              :    USE cell_types,                      ONLY: cell_type,&
      18              :                                               pbc
      19              :    USE cp_blacs_env,                    ONLY: cp_blacs_env_create,&
      20              :                                               cp_blacs_env_release,&
      21              :                                               cp_blacs_env_type
      22              :    USE cp_dbcsr_api,                    ONLY: &
      23              :         dbcsr_create, dbcsr_distribution_get, dbcsr_distribution_new, dbcsr_distribution_release, &
      24              :         dbcsr_distribution_type, dbcsr_finalize, dbcsr_get_info, dbcsr_type, dbcsr_type_no_symmetry
      25              :    USE cp_dbcsr_io,                     ONLY: dbcsr_binary_read,&
      26              :                                               dbcsr_binary_write
      27              :    USE cp_log_handling,                 ONLY: cp_get_default_logger,&
      28              :                                               cp_logger_type
      29              :    USE cp_output_handling,              ONLY: cp_p_file,&
      30              :                                               cp_print_key_should_output
      31              :    USE gw_auto_ri_types,                ONLY: auto_ri_type
      32              :    USE gw_utils_compute_integrals,      ONLY: build_3c_integral_block_ctx,&
      33              :                                               gw_3c_ctx_create,&
      34              :                                               gw_3c_ctx_release,&
      35              :                                               gw_3c_ctx_type,&
      36              :                                               gw_3c_ws_create,&
      37              :                                               gw_3c_ws_release,&
      38              :                                               gw_3c_ws_type
      39              :    USE input_section_types,             ONLY: section_vals_type
      40              :    USE kinds,                           ONLY: dp,&
      41              :                                               max_line_length
      42              :    USE machine,                         ONLY: m_flush,&
      43              :                                               m_walltime
      44              :    USE message_passing,                 ONLY: mp_mem_avail_per_rank_GB,&
      45              :                                               mp_para_env_type
      46              :    USE particle_types,                  ONLY: particle_type
      47              :    USE physcon,                         ONLY: angstrom
      48              :    USE post_scf_bandstructure_types,    ONLY: post_scf_bandstructure_type
      49              :    USE qs_environment_types,            ONLY: get_qs_env,&
      50              :                                               qs_environment_type
      51              :    USE qs_kind_types,                   ONLY: qs_kind_type
      52              :    USE ri_rs_fitting,                   ONLY: solve_ri_rs_fit,&
      53              :                                               store_Z_lP_columns
      54              :    USE ri_rs_grid_setup,                ONLY: setup_ri_rs_grid
      55              :    USE ri_rs_matrices,                  ONLY: atomic_basis_at_grid_point,&
      56              :                                               print_matrix_occupation
      57              :    USE ri_rs_types,                     ONLY: ri_rs_env
      58              :    USE ri_rs_utils,                     ONLY: evaluate_ao_basis_on_points,&
      59              :                                               evaluate_ao_on_points,&
      60              :                                               precompute_ri_rs_radii
      61              :    USE util,                            ONLY: sort
      62              : #include "./base/base_uses.f90"
      63              : 
      64              :    IMPLICIT NONE
      65              :    PRIVATE
      66              : 
      67              :    CHARACTER(len=*), PARAMETER, PRIVATE :: moduleN = 'ri_rs_setup'
      68              : 
      69              :    PUBLIC :: compute_Z_lP, ensure_ri_rs_representation
      70              : 
      71              : CONTAINS
      72              : 
      73              : ! **************************************************************************************************
      74              : !> \brief Populate the RI-RS grid, AO collocation and auxiliary fitting coefficients once.
      75              : !>        Periodic systems use the same neighbouring-image convention for phi and Z.
      76              : !> \param qs_env electronic-structure environment
      77              : !> \param bs_env geometry, RI-RS settings and owned output matrices
      78              : ! **************************************************************************************************
      79           86 :    SUBROUTINE ensure_ri_rs_representation(qs_env, bs_env)
      80              :       TYPE(qs_environment_type), POINTER                 :: qs_env
      81              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
      82              : 
      83              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'ensure_ri_rs_representation'
      84              : 
      85              :       INTEGER                                            :: handle
      86              :       REAL(KIND=dp)                                      :: build_start
      87              : 
      88           86 :       CALL timeset(routineN, handle)
      89           86 :       IF (.NOT. bs_env%ri_rs%grid_built) THEN
      90           50 :          build_start = m_walltime()
      91              :          CALL get_qs_env(qs_env, atomic_kind_set=bs_env%ri_rs%atomic_kind_set, &
      92           50 :                          cell=bs_env%ri_rs%cell, particle_set=bs_env%ri_rs%particle_set)
      93              :          ! AO/RI support radii determine which atoms and grid points enter each local fit.
      94           50 :          IF (.NOT. ALLOCATED(bs_env%ri_rs%radius_ao_per_atom)) THEN
      95              :             CALL precompute_ri_rs_radii(bs_env%ri_rs, bs_env%basis_set_AO, bs_env%basis_set_RI, &
      96           50 :                                         bs_env%eps_filter, bs_env%unit_nr)
      97              :          END IF
      98              :          ! Place atom-centered RI-RS grids at r_l = R_A + r_l^(A), then flatten them into one grid.
      99           50 :          CALL setup_ri_rs_grid(bs_env, bs_env%ri_rs%grid_points)
     100              :          ! Collocation matrix ϕ_μl = ϕ_μ(r_l), including neighbouring AO images for Gamma.
     101              :          CALL atomic_basis_at_grid_point(bs_env%ri_rs, bs_env%basis_set_AO, &
     102              :                                          bs_env%mat_ao_ao%matrix, bs_env%para_env, bs_env%eps_filter, &
     103              :                                          bs_env%dbcsr_msg_elem_limit, bs_env%unit_nr, &
     104           50 :                                          periodic_images=bs_env%do_periodic)
     105              :          CALL print_matrix_occupation(bs_env%ri_rs%mat_phi_mu_l, 'ϕ_μ(r_l)', &
     106           50 :                                       bs_env%para_env, bs_env%unit_nr, bs_env%dbcsr_msg_elem_limit)
     107              :          ! Fit Z_lP using the integration domains and RI basis described in compute_Z_lP below.
     108              :          CALL compute_Z_lP(qs_env, bs_env, bs_env%ri_rs%grid_points, &
     109              :                            bs_env%ri_rs%mat_phi_mu_l, bs_env%ri_rs%mat_Z_lP, &
     110           50 :                            periodic_images=bs_env%do_periodic)
     111           50 :          bs_env%ri_rs%grid_built = .TRUE.
     112           50 :          IF (bs_env%unit_nr > 0) THEN
     113              :             WRITE (bs_env%unit_nr, '(T2,A,T58,A,F7.1,A)') &
     114           25 :                'Built RI-RS representation,', ' Execution time', m_walltime() - build_start, ' s'
     115           25 :             WRITE (bs_env%unit_nr, '(A)') ' '
     116              :          END IF
     117              :       END IF
     118           86 :       CALL timestop(handle)
     119           86 :    END SUBROUTINE ensure_ri_rs_representation
     120              : 
     121              : ! **************************************************************************************************
     122              : !> \brief Computes the RI-RS fitting coefficients Z_lP by solving, independently for every RI
     123              : !>        atom P, a Jacobi-conditioned, Tikhonov-regularized linear system restricted to the
     124              : !>        grid points r_l inside P's integration sphere |r_l - R_P| <= cutoff_ri(P):
     125              : !>
     126              : !>        1.  D_ll'  = [ Σ_μ ϕ_μ(r_l) ϕ_μ(r_l') ]²
     127              : !>        2.  d_l    = 1 / sqrt(max(D_ll, jacobi_floor)) (Jacobi conditioning vector)
     128              : !>        3.  D'_ll' = d_l D_ll' d_l' + λ δ_ll'         (λ = TIKHONOV regularization)
     129              : !>        4.  d_lP   = Σ_μν ϕ_μ(r_l) ϕ_ν(r_l) (μν|P)
     130              : !>        5.  Σ_l' D'_ll' Z'_l'P = d_l d_lP             (solve linear system for Z'_lP)
     131              : !>        6.  Z_lP   = d_l Z'_lP                        (undo the conditioning)
     132              : !>
     133              : !>        With AUTO_RI, the optimized functions of atom P are φ_p = Σ_{P∈A} U_Pp φ_P, so step 4
     134              : !>        uses the reference functions of P and d_lp = Σ_P d_lP U_Pp.
     135              : !>
     136              : !>        See Duchemin and Blase, arXiv:1902.00066, Sec. II.3 for the least-squares construction
     137              : !>        and balancing, and solve_ri_rs_fit for the common floor and regularization convention.
     138              : !>
     139              : !>        The Gamma path uses image-summed AO values and three-center integrals, with RI
     140              : !>        atom P fixed in the reference cell. Molecular and Gamma sphere cutoffs are retained.
     141              : !>
     142              : !>        Work is distributed over atoms in two phases (planned by classify_z_lp_atoms and
     143              : !>        lpt_assign_atoms): Phase A solves "small" atoms with single-rank LAPACK
     144              : !>        (dpotrf/dpotrs); Phase B solves "big" atoms, whose dense matrix D'_ll' would exceed one
     145              : !>        rank's memory, with ScaLAPACK (pdpotrf/pdpotrs) over rank subgroups of size G.
     146              : !>        The solved Z columns are scattered into the sparse global mat_Z_lP.
     147              : !>        If a Z_lP restart file exists, it is read instead and the solve is skipped entirely.
     148              : !> \param qs_env ...
     149              : !> \param bs_env ...
     150              : !> \param ri_rs_grid_points ...
     151              : !> \param mat_phi_mu_l ...
     152              : !> \param mat_Z_lP ...
     153              : !> \param periodic_images use Gamma image sums and minimum-image integration spheres
     154              : ! **************************************************************************************************
     155           50 :    SUBROUTINE compute_Z_lP(qs_env, bs_env, ri_rs_grid_points, mat_phi_mu_l, mat_Z_lP, periodic_images)
     156              : 
     157              :       TYPE(qs_environment_type), POINTER                 :: qs_env
     158              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
     159              :       REAL(KIND=dp), INTENT(IN)                          :: ri_rs_grid_points(:, :)
     160              :       TYPE(dbcsr_type), INTENT(INOUT)                    :: mat_phi_mu_l
     161              :       TYPE(dbcsr_type), INTENT(OUT)                      :: mat_Z_lP
     162              :       LOGICAL, INTENT(IN)                                :: periodic_images
     163              : 
     164              :       CHARACTER(LEN=*), PARAMETER :: key = 'PROPERTIES%BANDSTRUCTURE%GW%PRINT%RESTART', &
     165              :          routineN = 'compute_Z_lP'
     166              : 
     167              :       INTEGER :: atom_j_mepos, atom_j_stride, atom_P, G, handle, i_blk, iatom, idx, iphase, j, &
     168              :          max_ao_size, my_group, n_big, n_done, n_groups, n_loc_ri, n_local_grid, n_my_atoms, &
     169              :          n_ref_ri, n_small, natom, npcol_phi, num_grid_chunks, phase_hi
     170          100 :       INTEGER, ALLOCATABLE, DIMENSION(:) :: ao_atoms, ao_col_start, big_list, local_grid_idx, &
     171           50 :          my_atoms_A, my_atoms_B, n_local_grid_atom, ref_blk_sizes, row_offset, small_list
     172          100 :       INTEGER, CONTIGUOUS, DIMENSION(:), POINTER         :: col_dist_ri, r_blk_sizes, ri_blk_sizes, &
     173           50 :                                                             row_dist_grid
     174              :       LOGICAL                                            :: do_scatter, use_dist
     175           50 :       LOGICAL, ALLOCATABLE                               :: ao_nonzero(:, :)
     176              :       REAL(KIND=dp)                                      :: cutoff_ri, item_start_time, r_c, t1
     177           50 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:)           :: cutoff_ri_per_atom
     178           50 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :)        :: d_lp_local, d_lp_opt, phi_local, U_Pp
     179              :       TYPE(cell_type), POINTER                           :: cell
     180              :       TYPE(cp_blacs_env_type), POINTER                   :: blacs_env_sub
     181              :       TYPE(cp_logger_type), POINTER                      :: logger
     182              :       TYPE(dbcsr_distribution_type)                      :: dist_phi, dist_Z
     183          650 :       TYPE(gw_3c_ctx_type)                               :: ctx_3c
     184              :       TYPE(mp_para_env_type), POINTER                    :: para_env, para_env_sub
     185           50 :       TYPE(particle_type), DIMENSION(:), POINTER         :: particle_set
     186           50 :       TYPE(qs_kind_type), DIMENSION(:), POINTER          :: qs_kind_set
     187              :       TYPE(section_vals_type), POINTER                   :: input
     188              : 
     189           50 :       CALL timeset(routineN, handle)
     190              : 
     191           50 :       t1 = m_walltime()
     192              : 
     193              :       CALL get_qs_env(qs_env, para_env=para_env, particle_set=particle_set, input=input, &
     194           50 :                       qs_kind_set=qs_kind_set, cell=cell)
     195              : 
     196           50 :       NULLIFY (para_env_sub, blacs_env_sub)
     197              : 
     198           50 :       natom = bs_env%n_atom
     199           50 :       bs_env%ri_rs%fit_max_grid = 0
     200           50 :       bs_env%ri_rs%fit_peak_bytes = 0.0_dp
     201              : 
     202              :       ! =========================================================================
     203              :       ! 1. SETUP DBCSR TOPOLOGY & EXACT OFFSETS
     204              :       !    mat_Z_lP inherits the grid row blocking (and row distribution) of
     205              :       !    mat_phi_mu_l; its columns are one block per RI atom.
     206              :       ! =========================================================================
     207           50 :       CALL dbcsr_get_info(mat_phi_mu_l, row_blk_size=r_blk_sizes, distribution=dist_phi)
     208           50 :       CALL dbcsr_distribution_get(dist_phi, row_dist=row_dist_grid, npcols=npcol_phi)
     209              : 
     210           50 :       num_grid_chunks = SIZE(r_blk_sizes)
     211              : 
     212          150 :       ALLOCATE (row_offset(num_grid_chunks))
     213           50 :       row_offset(1) = 0
     214          656 :       DO i_blk = 2, num_grid_chunks
     215          656 :          row_offset(i_blk) = row_offset(i_blk - 1) + r_blk_sizes(i_blk - 1)
     216              :       END DO
     217              : 
     218          200 :       ALLOCATE (ri_blk_sizes(natom), col_dist_ri(natom))
     219          174 :       DO iatom = 1, natom
     220              :          ri_blk_sizes(iatom) = &
     221          124 :             bs_env%i_RI_end_from_atom(iatom) - bs_env%i_RI_start_from_atom(iatom) + 1
     222          174 :          col_dist_ri(iatom) = MOD(iatom - 1, npcol_phi)
     223              :       END DO
     224              :       ! (μν|P) and d_lP use the reference RI functions; AUTO_RI contracts them to ri_blk_sizes.
     225          100 :       ALLOCATE (ref_blk_sizes(natom))
     226          174 :       ref_blk_sizes(:) = ri_blk_sizes
     227           62 :       IF (bs_env%auto_ri%enabled) ref_blk_sizes(:) = bs_env%auto_ri%sizes_ref_RI
     228              : 
     229              :       CALL dbcsr_distribution_new(dist_Z, template=dist_phi, &
     230           50 :                                   row_dist=row_dist_grid, col_dist=col_dist_ri)
     231              : 
     232           50 :       IF (bs_env%ri_rs%Z_lP_exists) THEN
     233              :          CALL dbcsr_binary_read(filepath=TRIM(bs_env%prefix)//"Z_lP.matrix", &
     234              :                                 distribution=dist_Z, &
     235            2 :                                 matrix_new=mat_Z_lP)
     236            2 :          IF (bs_env%unit_nr > 0) THEN
     237              :             WRITE (bs_env%unit_nr, '(T2,A,T57,A,F7.1,A)') &
     238            1 :                'Read Z_lP from file ', ' Execution time', m_walltime() - t1, ' s'
     239              :             ! The grid rows use Morton order (spatial_atom_order). A Z_lP.matrix
     240              :             ! written with another grid ordering would be silently read into
     241              :             ! the current row order. Delete stale Z_lP.matrix files and recompute if in doubt.
     242              :             WRITE (bs_env%unit_nr, '(T2,A)') &
     243            1 :                '*** NOTE: Z_lP restart must match the current (spatial) grid row ordering ***'
     244            1 :             WRITE (bs_env%unit_nr, '(A)') ' '
     245              :          END IF
     246              :       ELSE
     247              : 
     248           48 :          IF (bs_env%unit_nr > 0) THEN
     249           24 :             WRITE (bs_env%unit_nr, '(A)') ' '
     250           24 :             WRITE (bs_env%unit_nr, '(T2,A)') 'Started computing Z_lP'
     251           24 :             CALL m_flush(bs_env%unit_nr)
     252              :          END IF
     253              :          CALL dbcsr_create(mat_Z_lP, name="mat_Z_lP", dist=dist_Z, &
     254              :                            matrix_type=dbcsr_type_no_symmetry, &
     255           48 :                            row_blk_size=r_blk_sizes, col_blk_size=ri_blk_sizes)
     256              : 
     257              :          ! Largest per-atom AO block, needed to size the 3c-integral work buffers.
     258           48 :          max_ao_size = 0
     259          166 :          DO j = 1, bs_env%n_atom
     260              :             max_ao_size = MAX(max_ao_size, &
     261              :                               bs_env%i_ao_end_from_atom(j) - &
     262          166 :                               bs_env%i_ao_start_from_atom(j) + 1)
     263              :          END DO
     264              : 
     265              :          ! Keep each path's integration domain: r_c + r_RI(P) for molecules,
     266              :          ! r_c + r_AO(P) for the Gamma image-summed approximation.
     267          144 :          ALLOCATE (cutoff_ri_per_atom(natom))
     268              : 
     269           48 :          r_c = bs_env%ri_metric%cutoff_radius
     270          166 :          DO iatom = 1, natom
     271          166 :             IF (periodic_images) THEN
     272            0 :                cutoff_ri_per_atom(iatom) = r_c + bs_env%ri_rs%radius_ao_per_atom(iatom)
     273              :             ELSE
     274          118 :                cutoff_ri_per_atom(iatom) = r_c + bs_env%ri_rs%radius_ri_per_atom(iatom)
     275              :             END IF
     276              :          END DO
     277              : 
     278           48 :          CALL print_sphere_cutoff_table(bs_env, cutoff_ri_per_atom)
     279              : 
     280              :          ! =========================================================================
     281              :          ! 2. PER-ATOM SOLVER CLASSIFICATION
     282              :          !    Split the atoms into "small" (single-rank LAPACK, Phase A) and "big"
     283              :          !    (distributed ScaLAPACK over subgroups of G ranks, Phase B) by comparing
     284              :          !    each atom's estimated solve peak memory against the measured budget.
     285              :          ! =========================================================================
     286              :          CALL classify_z_lp_atoms(bs_env, ri_rs_grid_points, cutoff_ri_per_atom, ref_blk_sizes, &
     287           48 :                                   n_local_grid_atom, small_list, n_small, big_list, n_big, G, periodic_images)
     288              : 
     289              :          ! LPT scheduling: sort the atoms of each phase by estimated solve cost
     290              :          ! (n_local_grid^3, Cholesky-dominated) and greedily assign to the least-loaded
     291              :          ! rank (Phase A) / subgroup (Phase B).
     292              :          CALL lpt_assign_atoms(small_list, n_small, n_local_grid_atom, para_env%num_pe, &
     293           48 :                                para_env%mepos, my_atoms_A)
     294           48 :          IF (n_big > 0) THEN
     295            0 :             n_groups = para_env%num_pe/G
     296            0 :             my_group = MIN(para_env%mepos/G, n_groups - 1)
     297              :             CALL lpt_assign_atoms(big_list, n_big, n_local_grid_atom, n_groups, my_group, &
     298            0 :                                   my_atoms_B)
     299              :          ELSE
     300           48 :             ALLOCATE (my_atoms_B(0))
     301              :          END IF
     302              : 
     303              :          ! Atoms this rank will process across both phases for rank-0 progress
     304           48 :          n_my_atoms = SIZE(my_atoms_A) + SIZE(my_atoms_B)
     305           48 :          n_done = 0
     306              : 
     307              :          ! Shared context for the three-center integrals (μν|P) of the RHS build
     308              :          CALL gw_3c_ctx_create(ctx_3c, bs_env, bs_env%ri_metric, &
     309              :                                basis_j=bs_env%basis_set_AO, basis_k=bs_env%basis_set_AO, &
     310           48 :                                basis_i=bs_env%basis_set_RI)
     311              : 
     312              :          ! =========================================================================
     313              :          ! 3. TWO-PHASE LOOP OVER ATOMS
     314              :          !    Phase A processes the "small" atoms with the single-rank BLAS path
     315              :          !    Phase B processes the "big" atoms with the distributed ScaLAPACK path
     316              :          !    over rank subgroups of size G. phi_local for each atom's cutoff sphere
     317              :          !    is built on the fly to avoid replicating a global grid x AO matrix.
     318              :          ! =========================================================================
     319          144 :          DO iphase = 1, 2
     320           96 :             IF (iphase == 1) THEN
     321           48 :                use_dist = .FALSE.
     322           48 :                atom_j_mepos = 0
     323           48 :                atom_j_stride = 1
     324           48 :                phase_hi = SIZE(my_atoms_A)
     325              :             ELSE
     326           48 :                IF (n_big == 0) CYCLE
     327            0 :                use_dist = .TRUE.
     328            0 :                n_groups = para_env%num_pe/G
     329            0 :                my_group = MIN(para_env%mepos/G, n_groups - 1)
     330            0 :                ALLOCATE (para_env_sub)
     331            0 :                CALL para_env_sub%from_split(para_env, my_group)
     332            0 :                CALL cp_blacs_env_create(blacs_env=blacs_env_sub, para_env=para_env_sub)
     333            0 :                atom_j_mepos = para_env_sub%mepos
     334            0 :                atom_j_stride = para_env_sub%num_pe
     335              :                ! All ranks of a subgroup share my_group, hence the identical my_atoms_B list
     336              :                ! (the per-atom ScaLAPACK solve is collective over the subgroup).
     337            0 :                phase_hi = SIZE(my_atoms_B)
     338              :             END IF
     339              : 
     340          107 :             DO idx = 1, phase_hi
     341           59 :                item_start_time = m_walltime()
     342           59 :                IF (iphase == 1) THEN
     343           59 :                   atom_P = my_atoms_A(idx)
     344              :                ELSE
     345            0 :                   atom_P = my_atoms_B(idx)
     346              :                END IF
     347              : 
     348           59 :                n_loc_ri = ri_blk_sizes(atom_P)
     349           59 :                IF (n_loc_ri == 0) CYCLE
     350           59 :                n_ref_ri = ref_blk_sizes(atom_P)
     351           59 :                cutoff_ri = cutoff_ri_per_atom(atom_P)
     352              : 
     353              :                ! ---------------------------------------------------------------------
     354              :                ! A. Sphere-local AO matrix ϕ_μ(r_l): select the grid points with
     355              :                !    |r_l - R_P| <= cutoff_ri(P), using minimum-image distances for Gamma.
     356              :                !    The molecular path drops rows below EPS_FILTER; Gamma keeps all sphere rows.
     357              :                ! ---------------------------------------------------------------------
     358              :                CALL build_phi_on_sphere(bs_env, qs_kind_set, &
     359              :                                         ri_rs_grid_points, atom_P, cutoff_ri, &
     360              :                                         local_grid_idx, n_local_grid, phi_local, &
     361           59 :                                         ao_atoms, ao_col_start, periodic_images=periodic_images, ao_nonzero=ao_nonzero)
     362              : 
     363              :                ! ---------------------------------------------------------------------
     364              :                ! B. Right-hand side  d_lP = Σ_μν ϕ_μ(r_l) ϕ_ν(r_l) (μν|P)
     365              :                ! ---------------------------------------------------------------------
     366          236 :                ALLOCATE (d_lp_local(n_local_grid, n_ref_ri))
     367           59 :                d_lp_local = 0.0_dp
     368              : 
     369              :                CALL compute_d_lp(bs_env, ctx_3c, phi_local, ao_atoms, ao_col_start, ao_nonzero, d_lp_local, n_local_grid, &
     370           59 :                                  n_ref_ri, atom_P, max_ao_size, atom_j_mepos, atom_j_stride, periodic_images)
     371              : 
     372           59 :                DEALLOCATE (ao_atoms, ao_col_start, ao_nonzero)
     373              : 
     374              :                ! Reduce per-subgroup-rank partials into the replicated d_lp_local.
     375              :                ! Skipped for BLAS path: each rank has the full sum locally.
     376           59 :                IF (use_dist) THEN
     377            0 :                   CALL para_env_sub%sum(d_lp_local)
     378              :                END IF
     379           59 :                IF (bs_env%auto_ri%enabled) THEN
     380            6 :                   CALL get_U_Pp_AA(bs_env%auto_ri, atom_P, U_Pp)
     381           24 :                   ALLOCATE (d_lp_opt(n_local_grid, n_loc_ri))
     382              :                   CALL dgemm('N', 'N', n_local_grid, n_loc_ri, n_ref_ri, 1.0_dp, d_lp_local, &
     383            6 :                              n_local_grid, U_Pp, n_ref_ri, 0.0_dp, d_lp_opt, n_local_grid)
     384            6 :                   CALL MOVE_ALLOC(d_lp_opt, d_lp_local)
     385            6 :                   DEALLOCATE (U_Pp)
     386              :                END IF
     387              : 
     388              :                ! ---------------------------------------------------------------------
     389              :                ! C. Solve the Jacobi-scaled, regularized fit with LAPACK or ScaLAPACK.
     390              :                ! ---------------------------------------------------------------------
     391           59 :                IF (use_dist) THEN
     392              :                   CALL solve_ri_rs_fit(phi_local, d_lp_local, bs_env%ri_rs%tikhonov, &
     393            0 :                                        para_env_sub, blacs_env_sub)
     394              :                ELSE
     395           59 :                   CALL solve_ri_rs_fit(phi_local, d_lp_local, bs_env%ri_rs%tikhonov)
     396              :                END IF
     397              : 
     398              :                ! ---------------------------------------------------------------------
     399              :                ! D. Scatter the solved Z columns back into the global sparse mat_Z_lP.
     400              :                ! ---------------------------------------------------------------------
     401           59 :                do_scatter = .TRUE.
     402           59 :                IF (use_dist) do_scatter = (para_env_sub%mepos == 0)
     403            0 :                IF (do_scatter) THEN
     404              :                   CALL store_Z_lP_columns(mat_Z_lP, d_lp_local, local_grid_idx, n_local_grid, &
     405              :                                           n_loc_ri, atom_P, r_blk_sizes, row_offset, &
     406           59 :                                           bs_env%eps_filter)
     407              :                END IF
     408              : 
     409           59 :                DEALLOCATE (d_lp_local)
     410           59 :                DEALLOCATE (local_grid_idx, phi_local)
     411              : 
     412              :                ! Report each atom completed by the printing rank. No inter-rank communication is
     413              :                ! needed; the final message below is printed only after the global synchronization.
     414           59 :                n_done = n_done + 1
     415              :                CALL print_Z_lP_progress(bs_env, n_done, n_my_atoms, &
     416          107 :                                         m_walltime() - item_start_time)
     417              :             END DO   ! idx: atoms of this phase owned by this rank / subgroup
     418              : 
     419              :             ! Tear down the Phase-B subgroup (all ranks created it collectively).
     420           96 :             IF (iphase == 2) THEN
     421            0 :                CALL cp_blacs_env_release(blacs_env_sub)
     422            0 :                CALL para_env_sub%free()
     423            0 :                DEALLOCATE (para_env_sub)
     424              :             END IF
     425              :          END DO   ! iphase
     426              : 
     427           48 :          DEALLOCATE (cutoff_ri_per_atom)
     428           48 :          DEALLOCATE (small_list, big_list)
     429              : 
     430           48 :          CALL gw_3c_ctx_release(ctx_3c)
     431              : 
     432           48 :          CALL dbcsr_finalize(mat_Z_lP)
     433              : 
     434           48 :          CALL para_env%sync()
     435              :          CALL print_Z_lP_progress(bs_env, natom, natom, m_walltime() - t1, &
     436           48 :                                   all_mpi_ranks=.TRUE.)
     437              : 
     438           48 :          logger => cp_get_default_logger()
     439              : 
     440           48 :          IF (BTEST(cp_print_key_should_output(logger%iter_info, input, key), cp_p_file)) THEN
     441            4 :             CALL dbcsr_binary_write(matrix=mat_Z_lP, filepath=TRIM(bs_env%prefix)//"Z_lP.matrix")
     442              :          END IF
     443              : 
     444              :       END IF
     445              : 
     446           50 :       DEALLOCATE (row_offset, ri_blk_sizes, ref_blk_sizes, col_dist_ri)
     447           50 :       CALL dbcsr_distribution_release(dist_Z)
     448              : 
     449           50 :       CALL timestop(handle)
     450              : 
     451          250 :    END SUBROUTINE compute_Z_lP
     452              : 
     453              : ! **************************************************************************************************
     454              : !> \brief Prints the per-kind maximum RI-RS integration-sphere cutoff table.
     455              : !> \param bs_env ...
     456              : !> \param cutoff_ri_per_atom ...
     457              : ! **************************************************************************************************
     458           48 :    SUBROUTINE print_sphere_cutoff_table(bs_env, cutoff_ri_per_atom)
     459              : 
     460              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
     461              :       REAL(KIND=dp), DIMENSION(:), INTENT(IN)            :: cutoff_ri_per_atom
     462              : 
     463              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'print_sphere_cutoff_table'
     464              : 
     465              :       INTEGER                                            :: handle, iatom, ikind, nkind
     466           48 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:)           :: cutoff_ri_per_kind
     467           48 :       TYPE(atomic_kind_type), DIMENSION(:), POINTER      :: atomic_kind_set
     468           48 :       TYPE(particle_type), DIMENSION(:), POINTER         :: particle_set
     469              : 
     470           48 :       CALL timeset(routineN, handle)
     471              : 
     472           48 :       atomic_kind_set => bs_env%ri_rs%atomic_kind_set
     473           48 :       particle_set => bs_env%ri_rs%particle_set
     474              : 
     475           48 :       IF (bs_env%unit_nr <= 0) THEN
     476           24 :          CALL timestop(handle)
     477              :          RETURN
     478              :       END IF
     479              : 
     480           24 :       nkind = SIZE(atomic_kind_set)
     481           72 :       ALLOCATE (cutoff_ri_per_kind(nkind))
     482           24 :       cutoff_ri_per_kind(:) = 0.0_dp
     483              : 
     484           83 :       DO iatom = 1, bs_env%n_atom
     485           59 :          ikind = particle_set(iatom)%atomic_kind%kind_number
     486           83 :          cutoff_ri_per_kind(ikind) = MAX(cutoff_ri_per_kind(ikind), cutoff_ri_per_atom(iatom))
     487              :       END DO
     488              : 
     489           24 :       WRITE (bs_env%unit_nr, '(T2,A)') 'Per-kind maximum RI-RS sphere cutoff (Å):'
     490           24 :       WRITE (bs_env%unit_nr, '(T4,A4,A14)') 'Kind', 'cutoff (Å)'
     491           59 :       DO ikind = 1, nkind
     492              :          WRITE (bs_env%unit_nr, '(T4,A4,F14.4)') &
     493           35 :             atomic_kind_set(ikind)%element_symbol, &
     494           94 :             cutoff_ri_per_kind(ikind)*angstrom
     495              :       END DO
     496           24 :       WRITE (bs_env%unit_nr, '(A)') ' '
     497              : 
     498           24 :       DEALLOCATE (cutoff_ri_per_kind)
     499              : 
     500           24 :       CALL timestop(handle)
     501              : 
     502           48 :    END SUBROUTINE print_sphere_cutoff_table
     503              : 
     504              : ! **************************************************************************************************
     505              : !> \brief LPT (longest-processing-time) assignment of the Z_lP atoms to workers (MPI ranks in
     506              : !>        Phase A, rank subgroups in Phase B): sort by estimated solve cost n_local_grid^3
     507              : !>        (the per-atom Cholesky dominates; the n^2 assembly terms order the atoms the same
     508              : !>        way) and greedily give each atom to the least-loaded worker.
     509              : !> \param atom_list ...
     510              : !> \param n_atoms ...
     511              : !> \param n_local_grid_atom ...
     512              : !> \param n_workers ...
     513              : !> \param my_worker ...
     514              : !> \param my_atoms ...
     515              : ! **************************************************************************************************
     516           48 :    SUBROUTINE lpt_assign_atoms(atom_list, n_atoms, n_local_grid_atom, n_workers, my_worker, &
     517              :                                my_atoms)
     518              : 
     519              :       INTEGER, DIMENSION(:), INTENT(IN)                  :: atom_list
     520              :       INTEGER, INTENT(IN)                                :: n_atoms
     521              :       INTEGER, DIMENSION(:), INTENT(IN)                  :: n_local_grid_atom
     522              :       INTEGER, INTENT(IN)                                :: n_workers, my_worker
     523              :       INTEGER, ALLOCATABLE, DIMENSION(:), INTENT(OUT)    :: my_atoms
     524              : 
     525              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'lpt_assign_atoms'
     526              : 
     527              :       INTEGER                                            :: handle, i, iw, n_mine, w_min
     528           48 :       INTEGER, ALLOCATABLE, DIMENSION(:)                 :: mine_tmp, perm
     529           48 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:)           :: cost, load
     530              : 
     531           48 :       CALL timeset(routineN, handle)
     532              : 
     533           48 :       IF (n_atoms <= 0) THEN
     534            0 :          ALLOCATE (my_atoms(0))
     535            0 :          CALL timestop(handle)
     536            0 :          RETURN
     537              :       END IF
     538              : 
     539          384 :       ALLOCATE (cost(n_atoms), perm(n_atoms), mine_tmp(n_atoms), load(n_workers))
     540          166 :       DO i = 1, n_atoms
     541          166 :          cost(i) = REAL(n_local_grid_atom(atom_list(i)), dp)**3
     542              :       END DO
     543           48 :       CALL sort(cost, n_atoms, perm)   ! ascending; walk backwards for largest-first
     544              : 
     545           48 :       load(:) = 0.0_dp
     546           48 :       n_mine = 0
     547          166 :       DO i = n_atoms, 1, -1
     548              :          w_min = 1
     549          236 :          DO iw = 2, n_workers
     550          236 :             IF (load(iw) < load(w_min)) w_min = iw
     551              :          END DO
     552          118 :          load(w_min) = load(w_min) + cost(i)
     553          166 :          IF (w_min - 1 == my_worker) THEN
     554           59 :             n_mine = n_mine + 1
     555           59 :             mine_tmp(n_mine) = atom_list(perm(i))
     556              :          END IF
     557              :       END DO
     558              : 
     559          144 :       ALLOCATE (my_atoms(n_mine))
     560          107 :       my_atoms(:) = mine_tmp(1:n_mine)
     561              : 
     562           48 :       CALL timestop(handle)
     563              : 
     564           96 :    END SUBROUTINE lpt_assign_atoms
     565              : 
     566              : ! **************************************************************************************************
     567              : !> \brief Computes the dense localized right-hand side for one RI atom P,
     568              : !>
     569              : !>          d_lP = Σ_μν ϕ_μ(r_l) ϕ_ν(r_l) (μν|P).
     570              : !>
     571              : !>        OMP-threaded over unordered AO-atom pairs: build (mu nu|P) in the reference cell,
     572              : !>        or sum (mu_R nu_S|P_0) over nearest images for Gamma. Contract grid-chunked pair
     573              : !>        densities into a thread-private d_lp partial, then reduce the partials into d_lp.
     574              : !>        The shared integral context caches Libint/spherical-transform tables; each thread
     575              : !>        owns its integral workspace. The kind-radius triangle screen in
     576              : !>        build_3c_integral_block_ctx skips negligible image triples via the screened output.
     577              : !> \param bs_env ...
     578              : !> \param ctx shared three-center integral context
     579              : !> \param phi_val AO values on local-sphere grid rows and compact active-AO columns
     580              : !> \param ao_atoms global indices of the active AO atoms
     581              : !> \param ao_col_start local phi column starts, including the terminal column offset
     582              : !> \param ao_nonzero exact nonzero AO support on the retained grid rows
     583              : !> \param d_lp RHS (n_grid_total × n_loc_ri), zeroed by the caller and accumulated here
     584              : !> \param n_grid_total number of retained local-sphere grid rows
     585              : !> \param n_loc_ri number of RI functions on atom_P
     586              : !> \param atom_P RI atom fixed in the reference cell (0,0,0)
     587              : !> \param max_ao_size ...
     588              : !> \param atom_j_mepos ...
     589              : !> \param atom_j_stride ...
     590              : !> \param periodic_images sum nearest AO images with RI atom P fixed in the reference cell
     591              : ! **************************************************************************************************
     592           59 :    SUBROUTINE compute_d_lp(bs_env, ctx, phi_val, ao_atoms, ao_col_start, ao_nonzero, d_lp, n_grid_total, n_loc_ri, atom_P, &
     593              :                            max_ao_size, atom_j_mepos, atom_j_stride, periodic_images)
     594              : 
     595              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
     596              :       TYPE(gw_3c_ctx_type), INTENT(IN)                   :: ctx
     597              :       REAL(KIND=dp), DIMENSION(:, :), INTENT(IN)         :: phi_val
     598              :       INTEGER, DIMENSION(:), INTENT(IN)                  :: ao_atoms, ao_col_start
     599              :       LOGICAL, DIMENSION(:, :), INTENT(IN)               :: ao_nonzero
     600              :       INTEGER, INTENT(IN)                                :: n_grid_total, n_loc_ri
     601              :       REAL(KIND=dp), INTENT(INOUT)                       :: d_lp(n_grid_total, n_loc_ri)
     602              :       INTEGER, INTENT(IN)                                :: atom_P, max_ao_size, atom_j_mepos, &
     603              :                                                             atom_j_stride
     604              :       LOGICAL, INTENT(IN)                                :: periodic_images
     605              : 
     606              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'compute_d_lp'
     607              :       INTEGER, PARAMETER                                 :: grid_chunk = 1024
     608              : 
     609              :       INTEGER :: atom_j, atom_k, c, cell_R_vec(3), cell_S_vec(3), handle, handle2, &
     610              :          image_extent(3), ix_R, ix_S, iy_R, iy_S, iz_R, iz_S, j, jj, jk_idx, jsize, jstart, k, kk, &
     611              :          ksize, kstart, l, l0, n_grid_pair, point, ri
     612           59 :       INTEGER, ALLOCATABLE                               :: grid_index(:)
     613              :       LOGICAL                                            :: any_kept, screened
     614              :       REAL(KIND=dp)                                      :: pair_factor
     615           59 :       REAL(KIND=dp), ALLOCATABLE                         :: grid_result(:, :), int_3c_prv(:, :, :)
     616           59 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :)        :: d_lp_prv, int_2d_prv, rho_chunk
     617           59 :       TYPE(gw_3c_ws_type)                                :: ws
     618              : 
     619           59 :       CALL timeset(routineN, handle)
     620           59 :       image_extent = 0
     621           59 :       IF (periodic_images) image_extent = bs_env%ri_rs%cell%perd
     622              : 
     623              :       !$OMP PARALLEL DEFAULT(NONE) &
     624              :       !$OMP SHARED(bs_env, ctx, phi_val, ao_atoms, ao_col_start, ao_nonzero, d_lp, &
     625              :       !$OMP        n_grid_total, n_loc_ri, atom_P, max_ao_size, &
     626              :       !$OMP        atom_j_mepos, atom_j_stride, image_extent) &
     627              :       !$OMP PRIVATE(grid_index, grid_result, n_grid_pair, point, pair_factor, &
     628              :       !$OMP         jj, kk, atom_j, atom_k, c, handle2, j, jk_idx, jsize, jstart, k, ksize, kstart, &
     629              :       !$OMP         l, l0, ri, screened, d_lp_prv, int_2d_prv, rho_chunk, int_3c_prv, ws, &
     630           59 :       !$OMP         any_kept, ix_R, iy_R, iz_R, ix_S, iy_S, iz_S, cell_R_vec, cell_S_vec)
     631              : 
     632              :       ! The integral context is shared; all scratch arrays and the accumulating RHS are thread-private.
     633              :       CALL gw_3c_ws_create(ws, ctx)
     634              :       ALLOCATE (int_3c_prv(max_ao_size, max_ao_size, n_loc_ri))
     635              :       ALLOCATE (int_2d_prv(max_ao_size*max_ao_size, n_loc_ri))
     636              :       ALLOCATE (rho_chunk(grid_chunk, max_ao_size*max_ao_size))
     637              :       ALLOCATE (d_lp_prv(n_grid_total, n_loc_ri))
     638              :       ALLOCATE (grid_index(n_grid_total), grid_result(grid_chunk, n_loc_ri))
     639              :       d_lp_prv(:, :) = 0.0_dp
     640              : 
     641              :       ! MPI assigns each unordered pair through its first atom; OpenMP divides those atoms.
     642              :       ! Skip only exact-zero pair-grid support, without a new screening threshold.
     643              :       !$OMP DO SCHEDULE(DYNAMIC)
     644              :       DO jj = 1, SIZE(ao_atoms)
     645              :          atom_j = ao_atoms(jj)
     646              :          IF (MOD(atom_j - 1, atom_j_stride) /= atom_j_mepos) CYCLE
     647              :          DO kk = jj, SIZE(ao_atoms)
     648              :             atom_k = ao_atoms(kk)
     649              :             jstart = ao_col_start(jj)
     650              :             kstart = ao_col_start(kk)
     651              :             jsize = ao_col_start(jj + 1) - jstart
     652              :             ksize = ao_col_start(kk + 1) - kstart
     653              : 
     654              :             n_grid_pair = 0
     655              :             DO point = 1, n_grid_total
     656              :                IF (.NOT. (ao_nonzero(point, jj) .AND. ao_nonzero(point, kk))) CYCLE
     657              :                n_grid_pair = n_grid_pair + 1
     658              :                grid_index(n_grid_pair) = point
     659              :             END DO
     660              :             IF (n_grid_pair == 0) CYCLE
     661              :             ! (μν|P) = (νμ|P): distinct atom pairs contribute twice.
     662              :             pair_factor = 1.0_dp
     663              :             IF (atom_j /= atom_k) pair_factor = 2.0_dp
     664              : 
     665              :             ! For Gamma, sum (mu_R nu_S|P_0); the molecular path has only R=S=0.
     666              :             ! AO exchange symmetry applies to the complete image sum, so the same
     667              :             ! unordered atom pairs and pair_factor are used in both paths.
     668              :             ! The integral builder accumulates in place, including across image triples.
     669              :             ! Its kind-radius triangle screen rejects image triples beyond the integral cutoff.
     670              :             int_3c_prv(1:jsize, 1:ksize, 1:n_loc_ri) = 0.0_dp
     671              :             any_kept = .FALSE.
     672              :             DO ix_R = -image_extent(1), image_extent(1)
     673              :             DO iy_R = -image_extent(2), image_extent(2)
     674              :             DO iz_R = -image_extent(3), image_extent(3)
     675              :                cell_R_vec = [ix_R, iy_R, iz_R]
     676              :                DO ix_S = -image_extent(1), image_extent(1)
     677              :                DO iy_S = -image_extent(2), image_extent(2)
     678              :                DO iz_S = -image_extent(3), image_extent(3)
     679              :                   cell_S_vec = [ix_S, iy_S, iz_S]
     680              :                   CALL build_3c_integral_block_ctx(int_3c_prv(1:jsize, 1:ksize, 1:n_loc_ri), &
     681              :                                                    ctx, ws, atom_j=atom_j, atom_k=atom_k, atom_i=atom_P, &
     682              :                                                    cell_j=cell_R_vec, cell_k=cell_S_vec, screened=screened)
     683              :                   IF (screened) CYCLE
     684              :                   any_kept = .TRUE.
     685              :                END DO
     686              :                END DO
     687              :                END DO
     688              :             END DO
     689              :             END DO
     690              :             END DO
     691              :             IF (.NOT. any_kept) CYCLE
     692              : 
     693              :             ! Flatten (μν|P) to a matrix with combined AO index (ν-1)*jsize + μ for BLAS.
     694              :             DO ri = 1, n_loc_ri
     695              :                DO k = 1, ksize
     696              :                   DO j = 1, jsize
     697              :                      jk_idx = (k - 1)*jsize + j
     698              :                      int_2d_prv(jk_idx, ri) = int_3c_prv(j, k, ri)
     699              :                   END DO
     700              :                END DO
     701              :             END DO
     702              : 
     703              :             ! Pair density ρ(l, μν) = ϕ_μ(r_l) ϕ_ν(r_l) in grid chunks, contracted on the fly:
     704              :             ! d_lP += Σ_μν ρ(l, μν) (μν|P), with the atom-pair multiplicity included in pair_factor.
     705              :             DO l0 = 1, n_grid_pair, grid_chunk
     706              :                c = MIN(grid_chunk, n_grid_pair - l0 + 1)
     707              :                DO k = 1, ksize
     708              :                   DO j = 1, jsize
     709              :                      jk_idx = (k - 1)*jsize + j
     710              :                      DO l = 1, c
     711              :                         point = grid_index(l0 + l - 1)
     712              :                         rho_chunk(l, jk_idx) = phi_val(point, jstart + j - 1)* &
     713              :                                                phi_val(point, kstart + k - 1)
     714              :                      END DO
     715              :                   END DO
     716              :                END DO
     717              :                CALL timeset(routineN//"_dgemm", handle2)
     718              :                CALL dgemm("N", "N", c, n_loc_ri, jsize*ksize, &
     719              :                           pair_factor, rho_chunk, grid_chunk, &
     720              :                           int_2d_prv, max_ao_size*max_ao_size, &
     721              :                           0.0_dp, grid_result, grid_chunk)
     722              :                DO ri = 1, n_loc_ri
     723              :                   DO l = 1, c
     724              :                      point = grid_index(l0 + l - 1)
     725              :                      d_lp_prv(point, ri) = d_lp_prv(point, ri) + grid_result(l, ri)
     726              :                   END DO
     727              :                END DO
     728              :                CALL timestop(handle2)
     729              :             END DO
     730              :          END DO
     731              :       END DO
     732              :       !$OMP END DO
     733              : 
     734              :       ! Reduce once per thread; distributed fits subsequently sum the rank partials in the subgroup.
     735              :       !$OMP CRITICAL (compute_d_lp_reduce)
     736              :       d_lp(1:n_grid_total, 1:n_loc_ri) = d_lp(1:n_grid_total, 1:n_loc_ri) + &
     737              :                                          d_lp_prv(1:n_grid_total, 1:n_loc_ri)
     738              :       !$OMP END CRITICAL (compute_d_lp_reduce)
     739              : 
     740              :       DEALLOCATE (int_3c_prv, int_2d_prv, rho_chunk, d_lp_prv, grid_index, grid_result)
     741              :       CALL gw_3c_ws_release(ws)
     742              : 
     743              :       !$OMP END PARALLEL
     744              : 
     745           59 :       CALL timestop(handle)
     746              : 
     747           59 :    END SUBROUTINE compute_d_lp
     748              : 
     749              : ! **************************************************************************************************
     750              : !> \brief Prints completed Z_lP atoms and execution time from the printing rank.
     751              : !> \param bs_env ...
     752              : !> \param n_done Number of atoms completed by the printing rank.
     753              : !> \param n_total Total number of atoms assigned to the printing rank.
     754              : !> \param execution_time Wall-clock time used for the reported work.
     755              : !> \param all_mpi_ranks Whether all MPI ranks have completed the calculation.
     756              : ! **************************************************************************************************
     757          107 :    SUBROUTINE print_Z_lP_progress(bs_env, n_done, n_total, execution_time, all_mpi_ranks)
     758              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
     759              :       INTEGER, INTENT(IN)                                :: n_done, n_total
     760              :       REAL(KIND=dp), INTENT(IN)                          :: execution_time
     761              :       LOGICAL, INTENT(IN), OPTIONAL                      :: all_mpi_ranks
     762              : 
     763              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'print_Z_lP_progress'
     764              : 
     765              :       INTEGER                                            :: handle
     766              :       LOGICAL                                            :: completed
     767              : 
     768          107 :       CALL timeset(routineN, handle)
     769              : 
     770          107 :       IF (bs_env%unit_nr > 0) THEN
     771           59 :          completed = .FALSE.
     772           59 :          IF (PRESENT(all_mpi_ranks)) completed = all_mpi_ranks
     773           24 :          IF (completed) THEN
     774              :             WRITE (bs_env%unit_nr, '(T2,A,T58,A,F7.1,A,/)') &
     775           24 :                'Computed Z_lP (all MPI ranks) for all atoms,', &
     776           48 :                'Execution time', execution_time, ' s'
     777              :          ELSE
     778              :             WRITE (bs_env%unit_nr, '(T2,A,I11,A,I3,A,F7.1,A)') &
     779           35 :                'Computed Z_lP (MPI rank 0) for atom', n_done, ' /', n_total, &
     780           70 :                ',    Execution time', execution_time, ' s'
     781              :          END IF
     782           59 :          CALL m_flush(bs_env%unit_nr)
     783              :       END IF
     784              : 
     785          107 :       CALL timestop(handle)
     786              : 
     787          107 :    END SUBROUTINE print_Z_lP_progress
     788              : 
     789              : ! **************************************************************************************************
     790              : !> \brief Unpacks the AA contraction matrix of one atom.
     791              : !> \param auto_ri ...
     792              : !> \param atom ...
     793              : !> \param U_Pp ...
     794              : ! **************************************************************************************************
     795            6 :    SUBROUTINE get_U_Pp_AA(auto_ri, atom, U_Pp)
     796              :       TYPE(auto_ri_type), INTENT(IN)                     :: auto_ri
     797              :       INTEGER, INTENT(IN)                                :: atom
     798              :       REAL(KIND=dp), ALLOCATABLE, INTENT(OUT)            :: U_Pp(:, :)
     799              : 
     800              :       INTEGER                                            :: first, ncolumn, nrow
     801              : 
     802            6 :       nrow = auto_ri%sizes_ref_RI(atom)
     803            6 :       ncolumn = auto_ri%sizes_opt_RI(atom)
     804            6 :       first = auto_ri%U_Pp_atom_offset(atom)
     805           24 :       ALLOCATE (U_Pp(nrow, ncolumn))
     806           18 :       U_Pp(:, :) = RESHAPE(auto_ri%U_Pp_atom(first:first + nrow*ncolumn - 1), [nrow, ncolumn])
     807              : 
     808            6 :    END SUBROUTINE get_U_Pp_AA
     809              : 
     810              : ! **************************************************************************************************
     811              : !> \brief Splits the atoms of the Z_lP solve into a single-rank list ("small", Phase A: LAPACK
     812              : !>        dpotrf/dpotrs on one rank) and a distributed list ("big", Phase B: ScaLAPACK
     813              : !>        pdpotrf/pdpotrs over a rank subgroup of size G), and sizes G.
     814              : !>        Each atom's single-rank peak memory is estimated as
     815              : !>          peak(P) = 8*n_local_grid(P)^2                (dense conditioned Gram matrix)
     816              : !>                  + 8*n_local_grid(P)*n_ao_used(P)     (phi_local)
     817              : !>                  + 8*n_local_grid(P)*n_RI(P)*(1+n_threads)   (d_lp + OMP partials)
     818              : !>        and send atoms whose peak exceeds mem_safety * available-memory-per-proc to the
     819              : !>        distributed path; G is auto-sized so the biggest atom's distributed Gram matrix slice
     820              : !>        fits alongside the replicated phi_local + d_lp. G is floored by the ScaLAPACK 32-bit
     821              : !>        index limit (a local block-cyclic slice of ~n_local_grid^2/G elements must stay below
     822              : !>        2^31 or pdpotrf segfaults).
     823              : !>        Records and reports the memory estimates before the Z_lP solves.
     824              : !> \param bs_env ...
     825              : !> \param ri_rs_grid_points ...
     826              : !> \param cutoff_ri_per_atom ...
     827              : !> \param ri_blk_sizes per-atom ...
     828              : !> \param n_local_grid_atom ...
     829              : !> \param small_list ...
     830              : !> \param n_small ...
     831              : !> \param big_list ...
     832              : !> \param n_big ...
     833              : !> \param G ...
     834              : !> \param periodic_images use minimum-image distances for the Gamma integration domain
     835              : ! **************************************************************************************************
     836           48 :    SUBROUTINE classify_z_lp_atoms(bs_env, ri_rs_grid_points, cutoff_ri_per_atom, ri_blk_sizes, &
     837              :                                   n_local_grid_atom, small_list, n_small, big_list, n_big, G, periodic_images)
     838              : 
     839              : !$    USE OMP_LIB, ONLY: omp_get_max_threads
     840              : 
     841              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
     842              :       REAL(KIND=dp), DIMENSION(:, :), INTENT(IN)         :: ri_rs_grid_points
     843              : 
     844              :       REAL(KIND=dp), DIMENSION(:), INTENT(IN)            :: cutoff_ri_per_atom
     845              :       INTEGER, DIMENSION(:), INTENT(IN)                  :: ri_blk_sizes
     846              :       INTEGER, ALLOCATABLE, DIMENSION(:), INTENT(OUT)    :: n_local_grid_atom, small_list, big_list
     847              :       INTEGER, INTENT(OUT)                               :: n_small, n_big, G
     848              :       LOGICAL, INTENT(IN), OPTIONAL :: periodic_images
     849              :       CHARACTER(LEN=*), PARAMETER                        :: routineN = 'classify_z_lp_atoms'
     850              : 
     851              :       INTEGER                                            :: handle
     852              : 
     853              :       ! Conservative fraction of measured available memory usable per rank for the Z_lP
     854              :       REAL(KIND=dp), PARAMETER                           :: mem_safety = 0.8_dp
     855              : 
     856              :       ! ScaLAPACK/BLACS index the per-rank local block-cyclic slice (~n_local_grid^2/G
     857              :       ! elements) with 32-bit integers; keep it safely below 2^31 or pdpotrf segfaults.
     858              :       REAL(KIND=dp), PARAMETER                           :: scalapack_loc_limit = 2.0E9_dp
     859              : 
     860              :       INTEGER                                            :: G_atom, G_int32, l, n_ao_used_atom, &
     861              :                                                             n_grid_total, n_local_grid, natom, &
     862              :                                                             nthreads_cls, P_loop_atom
     863              :       REAL(KIND=dp)                                      :: budget_bytes, cutoff_ri, dlp_bytes, &
     864              :                                                             mem_avail_GB, ng, nri, peak_bytes, &
     865              :                                                             phi_bytes
     866              :       REAL(KIND=dp), DIMENSION(3)                        :: pos_P, displacement
     867              :       LOGICAL :: sum_images
     868              :       TYPE(mp_para_env_type), POINTER                    :: para_env
     869           48 :       TYPE(particle_type), DIMENSION(:), POINTER         :: particle_set
     870              : 
     871           48 :       CALL timeset(routineN, handle)
     872           48 :       sum_images = .FALSE.
     873           48 :       IF (PRESENT(periodic_images)) sum_images = periodic_images
     874              : 
     875           48 :       para_env => bs_env%para_env
     876           48 :       particle_set => bs_env%ri_rs%particle_set
     877           48 :       natom = bs_env%n_atom
     878           48 :       n_grid_total = bs_env%ri_rs%n_grid_points
     879           48 :       CPASSERT(SIZE(ri_rs_grid_points, 2) == n_grid_total)
     880              : 
     881              :       ! Per-atom sphere size: n_local_grid(P) = number of l with |r_l - R_P| <= cutoff_ri(P).
     882              :       ! It sets both the Gram matrix memory footprint (n_local_grid^2) and the solve
     883              :       ! cost (~n_local_grid^3), so it drives classification and the LPT load balancing.
     884          240 :       ALLOCATE (n_local_grid_atom(natom), small_list(natom), big_list(natom))
     885          166 :       DO P_loop_atom = 1, natom
     886          472 :          pos_P(:) = particle_set(P_loop_atom)%r(:)
     887          118 :          cutoff_ri = cutoff_ri_per_atom(P_loop_atom)
     888          118 :          n_local_grid = 0
     889        42132 :          DO l = 1, n_grid_total
     890       168056 :             displacement = ri_rs_grid_points(:, l) - pos_P
     891        42014 :             IF (sum_images) displacement = pbc(ri_rs_grid_points(:, l), pos_P, bs_env%ri_rs%cell)
     892       168174 :             IF (NORM2(displacement) <= cutoff_ri) THEN
     893        41876 :                n_local_grid = n_local_grid + 1
     894              :             END IF
     895              :          END DO
     896          166 :          n_local_grid_atom(P_loop_atom) = n_local_grid
     897              :       END DO
     898              : 
     899           48 :       nthreads_cls = 1
     900           48 : !$    nthreads_cls = omp_get_max_threads()
     901           48 :       CALL mp_mem_avail_per_rank_GB(bs_env%para_env, mem_avail_GB)  ! collective over all ranks
     902           48 :       budget_bytes = mem_safety*mem_avail_GB*1.0E9_dp
     903              : 
     904           48 :       n_small = 0
     905           48 :       n_big = 0
     906           48 :       G = 1
     907           48 :       G_atom = 1              ! max G a big atom needs (memory + ScaLAPACK int32 floor)
     908           48 :       IF (mem_avail_GB <= 0.0_dp .AND. bs_env%unit_nr > 0) THEN
     909            0 :          CPWARN("RI-RS Z_lP: no meminfo; single-rank solve for all atoms")
     910              :       END IF
     911          166 :       DO P_loop_atom = 1, natom
     912          118 :          ng = REAL(n_local_grid_atom(P_loop_atom), dp)
     913          118 :          nri = REAL(ri_blk_sizes(P_loop_atom), dp)
     914              :          CALL get_n_ao_in_sphere(bs_env, P_loop_atom, &
     915          118 :                                  cutoff_ri_per_atom(P_loop_atom), n_ao_used_atom, sum_images)
     916              :          CALL record_fit_memory(bs_env%ri_rs, n_local_grid_atom(P_loop_atom), &
     917          118 :                                 n_ao_used_atom, ri_blk_sizes(P_loop_atom), peak_bytes)
     918          166 :          IF (mem_avail_GB <= 0.0_dp .OR. peak_bytes <= budget_bytes) THEN
     919          118 :             n_small = n_small + 1
     920          118 :             small_list(n_small) = P_loop_atom
     921              :          ELSE
     922            0 :             n_big = n_big + 1
     923            0 :             big_list(n_big) = P_loop_atom
     924            0 :             phi_bytes = 8.0_dp*ng*REAL(n_ao_used_atom, dp)
     925            0 :             dlp_bytes = 8.0_dp*ng*nri*REAL(1 + nthreads_cls, dp)
     926              :             ! Bound both memory and ScaLAPACK's 32-bit local indexing.
     927            0 :             G_int32 = CEILING(ng*ng/scalapack_loc_limit)
     928              :             G_atom = MAX(G_atom, G_int32, &
     929            0 :                          CEILING(8.0_dp*ng*ng/MAX(budget_bytes - phi_bytes - dlp_bytes, 1.0_dp)))
     930              :          END IF
     931              :       END DO
     932           48 :       CALL print_fit_memory_estimate(bs_env, mem_avail_GB)
     933           48 :       IF (n_big > 0) THEN
     934            0 :          IF (G_atom > para_env%num_pe) THEN
     935              :             CALL cp_abort(__LOCATION__, &
     936              :                           "RI-RS Z_lP: an atom is too large to fit even when "// &
     937              :                           "distributed over all ranks. Add nodes, use fewer MPI ranks "// &
     938              :                           "per node, lower CUTOFF_RADIUS_RI, or raise EPS_FILTER "// &
     939            0 :                           "for more grid screening.")
     940              :          END IF
     941            0 :          G = MIN(MAX(G_atom, 2), para_env%num_pe)
     942              :       END IF
     943              : 
     944           48 :       CALL timestop(handle)
     945              : 
     946           48 :    END SUBROUTINE classify_z_lp_atoms
     947              : 
     948              : ! **************************************************************************************************
     949              : !> \brief Number of AO basis functions that can be non-zero inside the RI-RS integration sphere
     950              : !> \param bs_env ...
     951              : !> \param atom_P ...
     952              : !> \param cutoff_ri ...
     953              : !> \param n_ao_used ...
     954              : !> \param periodic_images use minimum-image distances to the Gamma integration sphere
     955              : ! **************************************************************************************************
     956          118 :    SUBROUTINE get_n_ao_in_sphere(bs_env, atom_P, cutoff_ri, n_ao_used, periodic_images)
     957              : 
     958              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
     959              :       INTEGER, INTENT(IN)                                :: atom_P
     960              :       REAL(KIND=dp), INTENT(IN)                          :: cutoff_ri
     961              :       INTEGER, INTENT(OUT)                               :: n_ao_used
     962              :       LOGICAL, INTENT(IN)                                :: periodic_images
     963              : 
     964              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'get_n_ao_in_sphere'
     965              : 
     966              :       INTEGER                                            :: handle, ri_atom
     967              :       REAL(KIND=dp)                                      :: displacement(3)
     968          118 :       TYPE(particle_type), DIMENSION(:), POINTER         :: particle_set
     969              : 
     970          118 :       CALL timeset(routineN, handle)
     971              : 
     972          118 :       particle_set => bs_env%ri_rs%particle_set
     973          118 :       n_ao_used = 0
     974          420 :       DO ri_atom = 1, bs_env%n_atom
     975         1208 :          displacement = particle_set(ri_atom)%r - particle_set(atom_P)%r
     976          302 :          IF (periodic_images) displacement = pbc(particle_set(ri_atom)%r, particle_set(atom_P)%r, bs_env%ri_rs%cell)
     977         1208 :          IF (NORM2(displacement) > &
     978              :              bs_env%ri_rs%radius_ao_per_atom(ri_atom) + cutoff_ri) CYCLE
     979              :          n_ao_used = n_ao_used + bs_env%i_ao_end_from_atom(ri_atom) - &
     980          420 :                      bs_env%i_ao_start_from_atom(ri_atom) + 1
     981              :       END DO
     982              : 
     983          118 :       CALL timestop(handle)
     984              : 
     985          118 :    END SUBROUTINE get_n_ao_in_sphere
     986              : 
     987              : ! **************************************************************************************************
     988              : !> \brief Builds the sphere-local AO matrix phi_local(l, μ) = ϕ_μ(r_l) for one RI atom P
     989              : !> \param bs_env ...
     990              : !> \param qs_kind_set ...
     991              : !> \param ri_rs_grid_points ...
     992              : !> \param atom_P ...
     993              : !> \param cutoff_ri ...
     994              : !> \param local_grid_idx ...
     995              : !> \param n_local_grid ...
     996              : !> \param phi_local ...
     997              : !> \param ao_atoms global indices of the active AO atoms
     998              : !> \param ao_col_start local phi column starts, including the terminal column offset
     999              : !> \param center ...
    1000              : !> \param periodic_images select Gamma image-summed AO values and minimum-image sphere distances
    1001              : !> \param ao_nonzero exact nonzero AO support on the retained grid rows
    1002              : ! **************************************************************************************************
    1003           59 :    SUBROUTINE build_phi_on_sphere(bs_env, qs_kind_set, ri_rs_grid_points, &
    1004              :                                   atom_P, cutoff_ri, local_grid_idx, n_local_grid, &
    1005              :                                   phi_local, ao_atoms, ao_col_start, center, periodic_images, ao_nonzero)
    1006              : 
    1007              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    1008              :       TYPE(qs_kind_type), DIMENSION(:), POINTER          :: qs_kind_set
    1009              :       REAL(KIND=dp), DIMENSION(:, :), INTENT(IN)         :: ri_rs_grid_points
    1010              :       INTEGER, INTENT(IN)                                :: atom_P
    1011              :       REAL(KIND=dp), INTENT(IN)                          :: cutoff_ri
    1012              :       INTEGER, ALLOCATABLE, DIMENSION(:), INTENT(OUT)    :: local_grid_idx
    1013              :       INTEGER, INTENT(OUT)                               :: n_local_grid
    1014              :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :), &
    1015              :          INTENT(OUT)                                     :: phi_local
    1016              :       INTEGER, ALLOCATABLE, DIMENSION(:), INTENT(OUT)    :: ao_atoms, ao_col_start
    1017              :       REAL(KIND=dp), DIMENSION(3), INTENT(IN), OPTIONAL  :: center
    1018              :       LOGICAL, INTENT(IN), OPTIONAL                      :: periodic_images
    1019              :       LOGICAL, ALLOCATABLE, INTENT(OUT), OPTIONAL        :: ao_nonzero(:, :)
    1020              : 
    1021              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'build_phi_on_sphere'
    1022              : 
    1023              :       INTEGER                                            :: col_end, col_start, handle, iactive, j, &
    1024              :                                                             k, l, loc_idx, n_active, n_ao_used, &
    1025              :                                                             n_grid_total, n_keep, ri_atom
    1026           59 :       INTEGER, ALLOCATABLE                               :: atom_candidates(:)
    1027              :       LOGICAL                                            :: sum_images
    1028              :       REAL(KIND=dp)                                      :: d_sP, dist, r2_threshold
    1029           59 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:)           :: w_pt
    1030           59 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :)        :: phi_keep, sphere_grid
    1031              :       REAL(KIND=dp), DIMENSION(3)                        :: displacement, pos_P
    1032              :       TYPE(cell_type), POINTER                           :: cell
    1033           59 :       TYPE(particle_type), DIMENSION(:), POINTER         :: particle_set
    1034              : 
    1035           59 :       CALL timeset(routineN, handle)
    1036           59 :       sum_images = .FALSE.
    1037           59 :       IF (PRESENT(periodic_images)) sum_images = periodic_images
    1038              : 
    1039           59 :       cell => bs_env%ri_rs%cell
    1040           59 :       particle_set => bs_env%ri_rs%particle_set
    1041              :       ! AUTO_RI may pass only the global grid points needed for the current atom block.
    1042           59 :       n_grid_total = SIZE(ri_rs_grid_points, 2)
    1043           59 :       IF (PRESENT(center)) THEN
    1044            0 :          pos_P(:) = center(:)
    1045              :       ELSE
    1046          236 :          pos_P(:) = particle_set(atom_P)%r(:)
    1047              :       END IF
    1048              : 
    1049           59 :       n_local_grid = 0
    1050        21066 :       DO l = 1, n_grid_total
    1051        84028 :          displacement = ri_rs_grid_points(:, l) - pos_P
    1052        21007 :          IF (sum_images) displacement = pbc(ri_rs_grid_points(:, l), pos_P, cell)
    1053        84028 :          dist = NORM2(displacement)
    1054        21066 :          IF (dist <= cutoff_ri) n_local_grid = n_local_grid + 1
    1055              :       END DO
    1056              : 
    1057          177 :       ALLOCATE (local_grid_idx(n_local_grid))
    1058              : 
    1059           59 :       n_local_grid = 0
    1060        21066 :       DO l = 1, n_grid_total
    1061        84028 :          displacement = ri_rs_grid_points(:, l) - pos_P
    1062        21007 :          IF (sum_images) displacement = pbc(ri_rs_grid_points(:, l), pos_P, cell)
    1063        84028 :          dist = NORM2(displacement)
    1064        21066 :          IF (dist <= cutoff_ri) THEN
    1065        20938 :             n_local_grid = n_local_grid + 1
    1066        20938 :             local_grid_idx(n_local_grid) = l
    1067              :          END IF
    1068              :       END DO
    1069              : 
    1070          177 :       ALLOCATE (sphere_grid(3, n_local_grid))
    1071        20997 :       DO loc_idx = 1, n_local_grid
    1072        83811 :          sphere_grid(:, loc_idx) = ri_rs_grid_points(:, local_grid_idx(loc_idx))
    1073              :       END DO
    1074              : 
    1075              :       ! Keep atoms in global order; phi columns are contiguous within each active atom.
    1076          177 :       ALLOCATE (atom_candidates(bs_env%n_atom))
    1077           59 :       n_active = 0
    1078          210 :       DO ri_atom = 1, bs_env%n_atom
    1079          604 :          displacement = particle_set(ri_atom)%r - pos_P
    1080          151 :          IF (sum_images) displacement = pbc(particle_set(ri_atom)%r, pos_P, cell)
    1081          604 :          d_sP = NORM2(displacement)
    1082          151 :          IF (d_sP > bs_env%ri_rs%radius_ao_per_atom(ri_atom) + cutoff_ri) CYCLE
    1083          151 :          IF (bs_env%i_ao_end_from_atom(ri_atom) < bs_env%i_ao_start_from_atom(ri_atom)) CYCLE
    1084          151 :          n_active = n_active + 1
    1085          210 :          atom_candidates(n_active) = ri_atom
    1086              :       END DO
    1087          328 :       ALLOCATE (ao_atoms(n_active), SOURCE=atom_candidates(:n_active))
    1088           59 :       DEALLOCATE (atom_candidates)
    1089          177 :       ALLOCATE (ao_col_start(n_active + 1))
    1090           59 :       ao_col_start(1) = 1
    1091          210 :       DO iactive = 1, n_active
    1092          151 :          ri_atom = ao_atoms(iactive)
    1093              :          ao_col_start(iactive + 1) = ao_col_start(iactive) + &
    1094          210 :                                      bs_env%i_ao_end_from_atom(ri_atom) - bs_env%i_ao_start_from_atom(ri_atom) + 1
    1095              :       END DO
    1096           59 :       n_ao_used = ao_col_start(n_active + 1) - 1
    1097          236 :       ALLOCATE (phi_local(n_local_grid, n_ao_used), SOURCE=0.0_dp)
    1098              : 
    1099          210 :       DO iactive = 1, n_active
    1100          151 :          ri_atom = ao_atoms(iactive)
    1101          151 :          col_start = ao_col_start(iactive)
    1102          151 :          col_end = ao_col_start(iactive + 1) - 1
    1103              :          ! A positive CUTOFF_RADIUS_RI_AO overrides the per-atom Gaussian radius
    1104              :          ! with a user-defined hard cutoff.
    1105          151 :          IF (.NOT. sum_images .AND. bs_env%ri_rs%cutoff_radius_ri_ao > 0.0_dp) THEN
    1106            9 :             r2_threshold = bs_env%ri_rs%cutoff_radius_ri_ao**2
    1107              :          ELSE
    1108          142 :             r2_threshold = bs_env%ri_rs%radius_ao_per_atom(ri_atom)**2
    1109              :          END IF
    1110              : 
    1111          210 :          IF (sum_images) THEN
    1112              :             CALL evaluate_ao_basis_on_points(phi_local(:, col_start:col_end), sphere_grid, &
    1113              :                                              bs_env%basis_set_AO( &
    1114              :                                              particle_set(ri_atom)%atomic_kind%kind_number)%gto_basis_set, &
    1115              :                                              particle_set(ri_atom)%r, cell, &
    1116            0 :                                              cutoff_squared=r2_threshold, periodic_images=.TRUE.)
    1117              :          ELSE
    1118              :             CALL evaluate_ao_on_points(phi_local(:, col_start:col_end), sphere_grid, &
    1119              :                                        ri_atom, particle_set, qs_kind_set, cell, &
    1120          151 :                                        cutoff_squared=r2_threshold)
    1121              :          END IF
    1122              :       END DO
    1123              : 
    1124           59 :       DEALLOCATE (sphere_grid)
    1125              : 
    1126           59 :       IF (.NOT. sum_images .AND. n_local_grid > 0) THEN
    1127          177 :          ALLOCATE (w_pt(n_local_grid))
    1128              :          !$OMP PARALLEL DO DEFAULT(NONE) &
    1129              :          !$OMP SHARED(n_local_grid, n_ao_used, phi_local, w_pt) &
    1130           59 :          !$OMP PRIVATE(l, j) SCHEDULE(STATIC)
    1131              :          DO l = 1, n_local_grid
    1132              :             w_pt(l) = 0.0_dp
    1133              :             DO j = 1, n_ao_used
    1134              :                w_pt(l) = MAX(w_pt(l), ABS(phi_local(l, j)))
    1135              :             END DO
    1136              :          END DO
    1137              :          !$OMP END PARALLEL DO
    1138        20997 :          n_keep = COUNT(w_pt > bs_env%eps_filter)
    1139           59 :          IF (n_keep < n_local_grid) THEN
    1140           24 :             ALLOCATE (phi_keep(n_keep, n_ao_used))
    1141            6 :             k = 0
    1142         2601 :             DO l = 1, n_local_grid
    1143         2601 :                IF (w_pt(l) > bs_env%eps_filter) THEN
    1144         2151 :                   k = k + 1
    1145        17208 :                   phi_keep(k, :) = phi_local(l, :)
    1146         2151 :                   local_grid_idx(k) = local_grid_idx(l)
    1147              :                END IF
    1148              :             END DO
    1149            6 :             CALL MOVE_ALLOC(phi_keep, phi_local)
    1150            6 :             n_local_grid = n_keep
    1151              :          END IF
    1152           59 :          DEALLOCATE (w_pt)
    1153              :       END IF
    1154              : 
    1155           59 :       IF (PRESENT(ao_nonzero)) THEN
    1156              :          ! Build support on the final retained rows, once for all RHS contractions using phi.
    1157          236 :          ALLOCATE (ao_nonzero(n_local_grid, n_active), SOURCE=.FALSE.)
    1158              :          !$OMP PARALLEL DO DEFAULT(NONE) SCHEDULE(STATIC) &
    1159              :          !$OMP SHARED(n_active, n_local_grid, ao_col_start, phi_local, ao_nonzero) &
    1160           59 :          !$OMP PRIVATE(iactive, j, l)
    1161              :          DO iactive = 1, n_active
    1162              :             DO j = ao_col_start(iactive), ao_col_start(iactive + 1) - 1
    1163              :                DO l = 1, n_local_grid
    1164              :                   ao_nonzero(l, iactive) = ao_nonzero(l, iactive) .OR. phi_local(l, j) /= 0.0_dp
    1165              :                END DO
    1166              :             END DO
    1167              :          END DO
    1168              :          !$OMP END PARALLEL DO
    1169              :       END IF
    1170              : 
    1171           59 :       CALL timestop(handle)
    1172              : 
    1173          118 :    END SUBROUTINE build_phi_on_sphere
    1174              : 
    1175              : ! **************************************************************************************************
    1176              : !> \brief Record the dense Gram, phi and threaded RHS memory model for an RI-RS fit.
    1177              : !>        The single-rank estimate is an upper bound for a distributed Gram solve.
    1178              : !> \param ri_rs owned fitting statistics, reset with the representation
    1179              : !> \param n_grid number of fitting grid rows, before screening when obtained by classification
    1180              : !> \param n_ao number of AO columns
    1181              : !> \param n_ri number of RHS columns
    1182              : !> \param peak_bytes optional single-rank estimate used by solver classification
    1183              : ! **************************************************************************************************
    1184          118 :    SUBROUTINE record_fit_memory(ri_rs, n_grid, n_ao, n_ri, peak_bytes)
    1185              : !$    USE OMP_LIB, ONLY: omp_get_max_threads
    1186              :       TYPE(ri_rs_env), INTENT(INOUT)                     :: ri_rs
    1187              :       INTEGER, INTENT(IN)                                :: n_grid, n_ao, n_ri
    1188              :       REAL(KIND=dp), INTENT(OUT), OPTIONAL               :: peak_bytes
    1189              : 
    1190              :       INTEGER                                            :: nthreads
    1191              :       REAL(KIND=dp)                                      :: ng, peak
    1192              : 
    1193          118 :       nthreads = 1
    1194          118 : !$    nthreads = omp_get_max_threads()
    1195          118 :       ng = REAL(n_grid, dp)
    1196              :       peak = 8.0_dp*ng*ng + 8.0_dp*ng*REAL(n_ao, dp) + &
    1197          118 :              8.0_dp*ng*REAL(n_ri, dp)*REAL(1 + nthreads, dp)
    1198          118 :       ri_rs%fit_max_grid = MAX(ri_rs%fit_max_grid, n_grid)
    1199          118 :       ri_rs%fit_peak_bytes = MAX(ri_rs%fit_peak_bytes, peak)
    1200          118 :       IF (PRESENT(peak_bytes)) peak_bytes = peak
    1201          118 :    END SUBROUTINE record_fit_memory
    1202              : 
    1203              : ! **************************************************************************************************
    1204              : !> \brief Prints the fitting memory bound before allocating the local fitting RHS and Gram matrix.
    1205              : !> \param bs_env recorded fitting sizes and output unit
    1206              : !> \param mem_avail_GB available memory per rank, measured collectively by the caller
    1207              : ! **************************************************************************************************
    1208           48 :    SUBROUTINE print_fit_memory_estimate(bs_env, mem_avail_GB)
    1209              :       TYPE(post_scf_bandstructure_type), POINTER         :: bs_env
    1210              :       REAL(KIND=dp), INTENT(IN)                          :: mem_avail_GB
    1211              : 
    1212              :       CHARACTER(LEN=max_line_length)                     :: msg
    1213              :       REAL(KIND=dp)                                      :: mem_gram_GB, mem_Zlp_peak_GB
    1214              : 
    1215           48 :       mem_gram_GB = 8.0_dp*REAL(bs_env%ri_rs%fit_max_grid, dp)**2*1.0E-9_dp
    1216           48 :       mem_Zlp_peak_GB = bs_env%ri_rs%fit_peak_bytes*1.0E-9_dp
    1217           48 :       IF (bs_env%unit_nr > 0) THEN
    1218           24 :          WRITE (bs_env%unit_nr, '(T2,A)') 'RI-RS fitting memory estimate per MPI process:'
    1219              :          WRITE (bs_env%unit_nr, '(T4,A,F37.2,A)') &
    1220           24 :             'Available memory per process (system)', mem_avail_GB, ' GB'
    1221              :          WRITE (bs_env%unit_nr, '(T4,A,F17.2,A)') &
    1222           24 :             'Required for Z_lP fit (Gram+phi+RHS, single-rank bound)', mem_Zlp_peak_GB, ' GB'
    1223              :          WRITE (bs_env%unit_nr, '(T4,A,T69,I12)') &
    1224           24 :             'Largest fitting-grid number of grid points:', bs_env%ri_rs%fit_max_grid
    1225              :          WRITE (bs_env%unit_nr, '(T4,A,T69,F9.2,A)') &
    1226           24 :             'Largest dense Gram matrix:', mem_gram_GB, ' GB'
    1227           24 :          CALL m_flush(bs_env%unit_nr)
    1228              :       END IF
    1229              : 
    1230           48 :       IF (mem_avail_GB > 0.0_dp .AND. mem_Zlp_peak_GB > mem_avail_GB) THEN
    1231              :          WRITE (msg, '(A,F0.2,A,F0.2,A)') &
    1232            0 :             "The estimated peak memory of the Z_lP solve, ", mem_Zlp_peak_GB, &
    1233            0 :             " GB per process, exceeds the available ", mem_avail_GB, &
    1234              :             " GB. The dense Gram matrix scales as n_local_grid^2; "// &
    1235              :             "the estimate assumes a single-rank solve. Localized fits may distribute the Gram "// &
    1236              :             "matrix over a ScaLAPACK subgroup. Use fewer MPI ranks per node if more memory "// &
    1237            0 :             "per rank is needed."
    1238            0 :          CPWARN(TRIM(msg))
    1239              :       END IF
    1240           48 :    END SUBROUTINE print_fit_memory_estimate
    1241              : 
    1242              : END MODULE ri_rs_setup
        

Generated by: LCOV version 2.0-1