LCOV - code coverage report
Current view: top level - src - qs_electrons_charge_mixing.F (source / functions) Coverage Total Hit
Test: CP2K Regtests (git:1be8651) Lines: 40.4 % 178 72
Test Date: 2026-11-24 01:22:08 Functions: 77.8 % 9 7

            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 Dual integer-electron-endpoint charge mixing for constant-potential MD,
      10              : !>        built on top of CP2K's stock MIXED force_eval
      11              : !>        (METHOD MIXED / MIXING_TYPE LINEAR_COMBINATION). Energy, forces and
      12              : !>        virial are already interpolated by stock force_env_methods.F's
      13              : !>        mixed_energy_forces using the LAMBDA value read from the input
      14              : !>        structure at every call; this module (a) pushes the dynamically
      15              : !>        tracked lambda into that input structure each step, (b) mixes
      16              : !>        Fermi level / workfunction, which stock MIXED does not touch, and
      17              : !>        (c) rebuilds a sub_force_env at a new integer CHARGE whenever q(t)
      18              : !>        drifts outside the currently-built bracket ("boundary crossing").
      19              : !> \author Nanchen DONGFANG
      20              : ! **************************************************************************************************
      21              : MODULE qs_electrons_charge_mixing
      22              :    USE cp_control_types,                ONLY: dft_control_type
      23              :    USE cp_log_handling,                 ONLY: cp_add_default_logger,&
      24              :                                               cp_logger_get_default_io_unit,&
      25              :                                               cp_logger_type,&
      26              :                                               cp_rm_default_logger
      27              :    USE cp_subsys_types,                 ONLY: cp_subsys_type
      28              :    USE force_env_methods,               ONLY: force_env_create
      29              :    USE force_env_types,                 ONLY: force_env_get,&
      30              :                                               force_env_release,&
      31              :                                               force_env_type
      32              :    USE global_types,                    ONLY: global_environment_type
      33              :    USE input_section_types,             ONLY: section_vals_get,&
      34              :                                               section_vals_get_subs_vals,&
      35              :                                               section_vals_type,&
      36              :                                               section_vals_val_get,&
      37              :                                               section_vals_val_set
      38              :    USE kinds,                           ONLY: dp
      39              :    USE message_passing,                 ONLY: mp_para_env_type
      40              :    USE qs_electrons_types,              ONLY: qs_electrons_type
      41              :    USE qs_electrons_workfunction,       ONLY: qs_electrons_compute_workfunction
      42              :    USE qs_environment,                  ONLY: qs_init
      43              :    USE qs_environment_types,            ONLY: get_qs_env,&
      44              :                                               qs_env_create,&
      45              :                                               qs_environment_type
      46              :    USE qs_mo_types,                     ONLY: get_mo_set,&
      47              :                                               mo_set_type,&
      48              :                                               set_mo_set
      49              :    USE qs_subsys_types,                 ONLY: qs_subsys_get,&
      50              :                                               qs_subsys_set,&
      51              :                                               qs_subsys_type
      52              :    USE scf_control_types,               ONLY: scf_control_type
      53              : #include "./base/base_uses.f90"
      54              : 
      55              :    IMPLICIT NONE
      56              : 
      57              :    PRIVATE
      58              : 
      59              :    CHARACTER(len=*), PARAMETER, PRIVATE :: moduleN = 'qs_electrons_charge_mixing'
      60              : 
      61              :    PUBLIC :: qs_electrons_charge_mixing_lambda, &
      62              :              push_lambda_to_mixed_env, &
      63              :              compute_mixed_workfunction, &
      64              :              charge_mixing_maybe_rebuild, &
      65              :              charge_mixing_sync_endpoint_state
      66              : 
      67              : CONTAINS
      68              : 
      69              : ! **************************************************************************************************
      70              : !> \brief Given the current electronic coordinate q and the integer span S,
      71              : !>        compute the bracketing integers N_lo/N_hi and the mixing weight
      72              : !>        lambda = (q - N_lo)/S.
      73              : !> \param electrons ...
      74              : !> \param lambda ...
      75              : !> \param n_lo ...
      76              : !> \param n_hi ...
      77              : ! **************************************************************************************************
      78            8 :    SUBROUTINE qs_electrons_charge_mixing_lambda(electrons, lambda, n_lo, n_hi)
      79              :       TYPE(qs_electrons_type), POINTER                   :: electrons
      80              :       REAL(KIND=dp), INTENT(OUT)                         :: lambda
      81              :       INTEGER, INTENT(OUT), OPTIONAL                     :: n_lo, n_hi
      82              : 
      83              :       INTEGER                                            :: my_n_hi, my_n_lo, span
      84              : 
      85            8 :       span = MAX(1, electrons%charge_mixing_span)
      86            8 :       my_n_lo = span*FLOOR(electrons%q/REAL(span, KIND=dp))
      87            8 :       my_n_hi = my_n_lo + span
      88            8 :       IF (electrons%lambda_is_fixed) THEN
      89              :          ! LAMBDA given in the input: hold the mixing weight there. n_lo/n_hi are
      90              :          ! still reported from q for the caller's benefit, but nothing rebuilds --
      91              :          ! charge_mixing_maybe_rebuild returns early in this mode -- so the two
      92              :          ! endpoints stay at whatever CHARGE the input built them with.
      93            0 :          lambda = electrons%lambda_fixed
      94              :       ELSE
      95            8 :          lambda = (electrons%q - REAL(my_n_lo, KIND=dp))/REAL(span, KIND=dp)
      96              :       END IF
      97              : 
      98            8 :       IF (PRESENT(n_lo)) n_lo = my_n_lo
      99            8 :       IF (PRESENT(n_hi)) n_hi = my_n_hi
     100              : 
     101            8 :    END SUBROUTINE qs_electrons_charge_mixing_lambda
     102              : 
     103              : ! **************************************************************************************************
     104              : !> \brief Push a dynamically computed lambda into the MIXED force_eval's
     105              : !>        input structure. force_env_methods.F::mixed_energy_forces reads
     106              : !>        MIXED%LINEAR%LAMBDA fresh from the input structure every call, so
     107              : !>        this alone is sufficient to make energy/force/virial mixing track
     108              : !>        our own extended-variable dynamics with zero changes to stock CP2K.
     109              : !>
     110              : !>        IMPORTANT sign convention: CP2K's own mixed_energy_forces computes
     111              : !>        E = LAMBDA*E(force_eval#1) + (1-LAMBDA)*E(force_eval#2). In our
     112              : !>        input, force_eval#1 is the N_lo endpoint and force_eval#2 is the
     113              : !>        N_hi endpoint, but our own `lambda` argument here uses the opposite
     114              : !>        (standard interpolation) convention, lambda = (q-N_lo)/S, i.e.
     115              : !>        lambda=0 at N_lo and lambda=1 at N_hi. So CP2K's LAMBDA must be set
     116              : !>        to (1-lambda), NOT lambda directly, or the mixing comes out
     117              : !>        backwards (mostly N_hi when q is near N_lo).
     118              : !> \param force_env the top-level MIXED force_env (force_env%in_use must be
     119              : !>        use_mixed_force; force_env%force_env_section must contain a MIXED
     120              : !>        subsection with MIXING_TYPE LINEAR_COMBINATION)
     121              : !> \param lambda our convention: 0 at N_lo, 1 at N_hi
     122              : ! **************************************************************************************************
     123            4 :    SUBROUTINE push_lambda_to_mixed_env(force_env, lambda)
     124              :       TYPE(force_env_type), POINTER                      :: force_env
     125              :       REAL(KIND=dp), INTENT(IN)                          :: lambda
     126              : 
     127              :       TYPE(section_vals_type), POINTER                   :: force_env_section, mixed_section
     128              : 
     129            4 :       NULLIFY (force_env_section, mixed_section)
     130            4 :       CALL force_env_get(force_env, force_env_section=force_env_section)
     131            4 :       mixed_section => section_vals_get_subs_vals(force_env_section, "MIXED")
     132            4 :       CALL section_vals_val_set(mixed_section, "LINEAR%LAMBDA", r_val=1.0_dp - lambda)
     133              : 
     134            4 :    END SUBROUTINE push_lambda_to_mixed_env
     135              : 
     136              : ! **************************************************************************************************
     137              : !> \brief Fermi level / workfunction mixing across the two integer-charge
     138              : !>        endpoints. Stock MIXED only combines energy/force/virial/dipole
     139              : !>        (mixed_environment_utils.F::mixed_map_forces), so these two
     140              : !>        quantities -- needed every step by our own O-B-A-B-O potentiostat
     141              : !>        to decide how to move q(t) -- are interpolated here, mirroring
     142              : !>        FFChargeMixTwoSockets._mix_results's fermi/workfunction lines.
     143              : !> \param force_env the top-level MIXED force_env; force_env%sub_force_env(1)
     144              : !>        and (2) must each be an ordinary QS force_env
     145              : !> \param axis ...
     146              : !> \param wf_min ...
     147              : !> \param wf_max ...
     148              : !> \param q current electronic coordinate (total electron count)
     149              : !> \param span charge_mixing_span (S)
     150              : !> \param fermi_level_eV ...
     151              : !> \param workfunction_eV ...
     152              : !> \param lambda_in optional explicit mixing weight; callers pass the value from
     153              : !>        qs_electrons_charge_mixing_lambda so a FIXED lambda is honoured here too
     154              : ! **************************************************************************************************
     155            4 :    SUBROUTINE compute_mixed_workfunction(force_env, axis, wf_min, wf_max, q, span, &
     156              :                                          fermi_level_eV, workfunction_eV, lambda_in)
     157              :       TYPE(force_env_type), POINTER                      :: force_env
     158              :       INTEGER, INTENT(IN)                                :: axis
     159              :       REAL(KIND=dp), INTENT(IN)                          :: wf_min, wf_max, q
     160              :       INTEGER, INTENT(IN)                                :: span
     161              :       REAL(KIND=dp), INTENT(OUT)                         :: fermi_level_eV, workfunction_eV
     162              :       REAL(KIND=dp), INTENT(IN), OPTIONAL                :: lambda_in
     163              : 
     164              :       INTEGER                                            :: n_lo
     165              :       REAL(KIND=dp)                                      :: fermi_hi, fermi_lo, lambda, wf_hi, wf_lo
     166              : 
     167              : ! Optional explicit mixing weight. Callers pass the value returned by
     168              : ! qs_electrons_charge_mixing_lambda so that a FIXED lambda is honoured here
     169              : ! too; without it this routine would re-derive lambda from q and the mixed
     170              : ! work function would disagree with the mixed energy.
     171              : 
     172            4 :       CPASSERT(ASSOCIATED(force_env%sub_force_env))
     173            4 :       CPASSERT(SIZE(force_env%sub_force_env) == 2)
     174              : 
     175            4 :       IF (PRESENT(lambda_in)) THEN
     176            4 :          lambda = lambda_in
     177              :       ELSE
     178            0 :          n_lo = span*FLOOR(q/REAL(span, KIND=dp))
     179            0 :          lambda = (q - REAL(n_lo, KIND=dp))/REAL(span, KIND=dp)
     180              :       END IF
     181              : 
     182              :       ! With MIXED%NGROUPS 2 (our default, for concurrent execution), CP2K
     183              :       ! splits ranks across the two sub-force_evals, so a given rank only has
     184              :       ! ONE of the two sub_force_env's built locally (f77_interface.F::
     185              :       ! create_force_env CYCLEs past the other for that rank's group).
     186              :       !
     187              :       ! Every rank within a given group calls qs_electrons_compute_workfunction
     188              :       ! (needed in case any internal fallback tier ever becomes a collective
     189              :       ! operation across that group, e.g. an OT calculate_subspace_eigenvalues
     190              :       ! path), but the Fermi level / workfunction result is IDENTICAL/replicated
     191              :       ! across every rank in that group -- so before the cross-group reduction,
     192              :       ! only that group's own "source" rank is allowed to keep its value; every
     193              :       ! other rank in the SAME group zeroes it out first. This exactly mirrors
     194              :       ! how force_env_methods.F::mixed_energy_forces combines energies(:)
     195              :       ! across groups (only para_env%is_source() assigns energies(iforce_eval)
     196              :       ! before the shared CALL force_env%para_env%sum(energies)). Without this
     197              :       ! is_source() gate, every rank in a group would contribute the SAME
     198              :       ! value to the sum, inflating the result by that group's rank count --
     199              :       ! which is what produced the ~12x-too-large workfunction seen earlier.
     200            4 :       fermi_lo = 0.0_dp
     201            4 :       wf_lo = 0.0_dp
     202            4 :       fermi_hi = 0.0_dp
     203            4 :       wf_hi = 0.0_dp
     204              : 
     205            4 :       IF (ASSOCIATED(force_env%sub_force_env(1)%force_env)) THEN
     206              :          CALL qs_electrons_compute_workfunction(force_env%sub_force_env(1)%force_env, axis, wf_min, wf_max, &
     207            4 :                                                 fermi_lo, wf_lo)
     208            4 :          IF (.NOT. force_env%sub_force_env(1)%force_env%para_env%is_source()) THEN
     209            2 :             fermi_lo = 0.0_dp
     210            2 :             wf_lo = 0.0_dp
     211              :          END IF
     212              :       END IF
     213            4 :       IF (ASSOCIATED(force_env%sub_force_env(2)%force_env)) THEN
     214              :          CALL qs_electrons_compute_workfunction(force_env%sub_force_env(2)%force_env, axis, wf_min, wf_max, &
     215            4 :                                                 fermi_hi, wf_hi)
     216            4 :          IF (.NOT. force_env%sub_force_env(2)%force_env%para_env%is_source()) THEN
     217            2 :             fermi_hi = 0.0_dp
     218            2 :             wf_hi = 0.0_dp
     219              :          END IF
     220              :       END IF
     221              : 
     222            4 :       CALL force_env%para_env%sum(fermi_lo)
     223            4 :       CALL force_env%para_env%sum(wf_lo)
     224            4 :       CALL force_env%para_env%sum(fermi_hi)
     225            4 :       CALL force_env%para_env%sum(wf_hi)
     226              : 
     227            4 :       fermi_level_eV = (1.0_dp - lambda)*fermi_lo + lambda*fermi_hi
     228            4 :       workfunction_eV = (1.0_dp - lambda)*wf_lo + lambda*wf_hi
     229              : 
     230            4 :    END SUBROUTINE compute_mixed_workfunction
     231              : 
     232              : ! **************************************************************************************************
     233              : !> \brief Check whether q(t) has drifted outside the currently-built
     234              : !>        [N_lo,N_hi] bracket and, if so, rebuild whichever endpoint(s) are
     235              : !>        now stale at the new integer electron count. Must be called every
     236              : !>        step, right after qs_electrons_drift and before
     237              : !>        push_lambda_to_mixed_env, so LAMBDA is always pushed against a
     238              : !>        bracket that actually matches the physically-built sub_force_env
     239              : !>        pair.
     240              : !> \param force_env the top-level MIXED force_env
     241              : !> \param electrons ...
     242              : ! **************************************************************************************************
     243            8 :    SUBROUTINE charge_mixing_maybe_rebuild(force_env, electrons)
     244              :       TYPE(force_env_type), POINTER                      :: force_env
     245              :       TYPE(qs_electrons_type), POINTER                   :: electrons
     246              : 
     247              :       INTEGER                                            :: n_hi, n_lo
     248              :       LOGICAL                                            :: moved
     249              :       REAL(KIND=dp)                                      :: lambda_unused
     250              : 
     251              :       ! A frozen mixing weight means the endpoints must stay exactly as the input
     252              :       ! built them; rebuilding to bracket q would silently change what LAMBDA is
     253              :       ! a weight BETWEEN.
     254            4 :       IF (electrons%lambda_is_fixed) RETURN
     255              : 
     256              :       ! n_lo = S*FLOOR(q/S), n_hi = n_lo + S, slot 1 <- n_lo, slot 2 <- n_hi.
     257              :       ! The endpoints are only updated when the bracket actually changes, by
     258              :       ! comparing against the tracked pair, because updating an endpoint mutates
     259              :       ! the SCF state and is not free.
     260            4 :       CALL qs_electrons_charge_mixing_lambda(electrons, lambda_unused, n_lo, n_hi)
     261              :       moved = (n_lo /= electrons%charge_mixing_current_n_lo) .OR. &
     262            4 :               (n_hi /= electrons%charge_mixing_current_n_hi)
     263              : 
     264            4 :       IF (n_lo /= electrons%charge_mixing_current_n_lo) THEN
     265            0 :          IF (electrons%charge_mixing_inplace) THEN
     266            0 :             CALL charge_mixing_set_endpoint_charge(force_env, 1, n_lo, electrons)
     267              :          ELSE
     268            0 :             CALL rebuild_charge_mixing_endpoint(force_env, 1, n_lo, electrons)
     269              :          END IF
     270            0 :          electrons%charge_mixing_current_n_lo = n_lo
     271              :       END IF
     272            4 :       IF (n_hi /= electrons%charge_mixing_current_n_hi) THEN
     273            0 :          IF (electrons%charge_mixing_inplace) THEN
     274            0 :             CALL charge_mixing_set_endpoint_charge(force_env, 2, n_hi, electrons)
     275              :          ELSE
     276            0 :             CALL rebuild_charge_mixing_endpoint(force_env, 2, n_hi, electrons)
     277              :          END IF
     278            0 :          electrons%charge_mixing_current_n_hi = n_hi
     279              :       END IF
     280              : 
     281              :       ! Read the counts back and abort if the endpoints did not actually take
     282              :       ! the change, rather than silently mixing the wrong states.
     283            4 :       CALL charge_mixing_verify_endpoints(force_env, electrons, moved)
     284              : 
     285              :    END SUBROUTINE charge_mixing_maybe_rebuild
     286              : 
     287              : ! **************************************************************************************************
     288              : !> \brief Record which integer electron counts the two FORCE_EVAL blocks are
     289              : !>        ACTUALLY built for, by interrogating them, so that the very first
     290              : !>        charge_mixing_maybe_rebuild can tell whether the input agrees with q.
     291              : !>
     292              : !>        This closes the "startup endpoint mismatch" hole.  The port assumes
     293              : !>        throughout that sub_force_env(1) carries N_lo and sub_force_env(2)
     294              : !>        carries N_hi -- push_lambda_to_mixed_env relies on it, since CP2K
     295              : !>        evaluates E = LAMBDA*E(1) + (1-LAMBDA)*E(2) and we therefore push
     296              : !>        LAMBDA = 1 - lambda.  Nothing in stock CP2K enforces that ordering:
     297              : !>        an input whose two blocks are written high-charge-first would mix
     298              : !>        BACKWARDS, silently, for the whole run, and the only symptom would be
     299              : !>        a potentiostat that pushes q the wrong way.
     300              : !>
     301              : !>        Reading the counts back here and letting maybe_rebuild correct them
     302              : !>        removes the dependence on the order of the input blocks.
     303              : !>
     304              : !>        Reading rather than blindly forcing a rebuild matters: seeding the
     305              : !>        tracking with -HUGE(0) would also fix the ordering, but it would force
     306              : !>        two full qs_init rebuilds at step 0 of every run, including the vast
     307              : !>        majority whose input is already correct.
     308              : !> \param force_env the top-level MIXED force_env
     309              : !> \param electrons ...
     310              : ! **************************************************************************************************
     311            2 :    SUBROUTINE charge_mixing_sync_endpoint_state(force_env, electrons)
     312              :       TYPE(force_env_type), POINTER                      :: force_env
     313              :       TYPE(qs_electrons_type), POINTER                   :: electrons
     314              : 
     315              :       INTEGER, DIMENSION(2)                              :: n_have
     316              : 
     317            2 :       IF (.NOT. electrons%charge_mixing_enabled) RETURN
     318              : 
     319            2 :       CALL charge_mixing_read_endpoint_counts(force_env, n_have)
     320            2 :       electrons%charge_mixing_current_n_lo = n_have(1)
     321            2 :       electrons%charge_mixing_current_n_hi = n_have(2)
     322              : 
     323              :    END SUBROUTINE charge_mixing_sync_endpoint_state
     324              : 
     325              : ! **************************************************************************************************
     326              : !> \brief Read back the integer electron count each of the two FORCE_EVAL
     327              : !>        endpoints is currently built for.
     328              : !>
     329              : !>        Under NGROUPS > 1 a rank sees only its OWN group's sub_force_env and
     330              : !>        the other pointer is null, so each slot starts at a sentinel that
     331              : !>        loses the MAX reduction and is contributed by whichever ranks hold it.
     332              : !>        Electron counts are positive, so MAX is safe, and every rank leaves
     333              : !>        with the same pair -- which matters because the caller may CPABORT on
     334              : !>        the result and that decision has to be collective.
     335              : !> \param force_env the top-level MIXED force_env
     336              : !> \param n_have (1) = slot 1's count, (2) = slot 2's count
     337              : ! **************************************************************************************************
     338            6 :    SUBROUTINE charge_mixing_read_endpoint_counts(force_env, n_have)
     339              :       TYPE(force_env_type), POINTER                      :: force_env
     340              :       INTEGER, DIMENSION(2), INTENT(OUT)                 :: n_have
     341              : 
     342              :       INTEGER                                            :: idx
     343              :       TYPE(force_env_type), POINTER                      :: sub
     344              :       TYPE(qs_subsys_type), POINTER                      :: subsys
     345              : 
     346           18 :       n_have = -HUGE(0)
     347            6 :       IF (.NOT. ASSOCIATED(force_env%sub_force_env)) RETURN
     348              : 
     349           18 :       DO idx = 1, 2
     350           12 :          NULLIFY (sub, subsys)
     351           12 :          IF (idx > SIZE(force_env%sub_force_env)) CYCLE
     352           12 :          sub => force_env%sub_force_env(idx)%force_env
     353           12 :          IF (.NOT. ASSOCIATED(sub)) CYCLE
     354           12 :          IF (.NOT. ASSOCIATED(sub%qs_env)) CYCLE
     355           12 :          CALL get_qs_env(sub%qs_env, subsys=subsys)
     356           12 :          IF (.NOT. ASSOCIATED(subsys)) CYCLE
     357           18 :          CALL qs_subsys_get(subsys, nelectron_total=n_have(idx))
     358              :       END DO
     359              : 
     360            6 :       CALL force_env%para_env%max(n_have)
     361              : 
     362              :    END SUBROUTINE charge_mixing_read_endpoint_counts
     363              : 
     364              : ! **************************************************************************************************
     365              : !> \brief Assert that the two endpoints really are built for the electron counts
     366              : !>        we think they are, and log the bracket whenever it moves.
     367              : !>
     368              : !>        The in-place path mutates dft_control%charge and
     369              : !>        the subsys electron counts directly, so a silent failure to take
     370              : !>        effect would look exactly like a converged run -- just one mixing two
     371              : !>        copies of the same integer-charge state, which makes E independent of
     372              : !>        lambda and leaves q with no restoring force at all.  Checking is cheap
     373              : !>        and turns that failure mode into an abort instead of a plausible
     374              : !>        trajectory.
     375              : !> \param force_env ...
     376              : !> \param electrons ...
     377              : !> \param moved whether the bracket changed on this step (controls logging)
     378              : ! **************************************************************************************************
     379            4 :    SUBROUTINE charge_mixing_verify_endpoints(force_env, electrons, moved)
     380              :       TYPE(force_env_type), POINTER                      :: force_env
     381              :       TYPE(qs_electrons_type), POINTER                   :: electrons
     382              :       LOGICAL, INTENT(IN)                                :: moved
     383              : 
     384              :       CHARACTER(LEN=256)                                 :: msg
     385              :       INTEGER                                            :: iw
     386              :       INTEGER, DIMENSION(2)                              :: n_have
     387              : 
     388            4 :       CALL charge_mixing_read_endpoint_counts(force_env, n_have)
     389              : 
     390            4 :       IF (n_have(1) /= electrons%charge_mixing_current_n_lo .OR. &
     391              :           n_have(2) /= electrons%charge_mixing_current_n_hi) THEN
     392              :          WRITE (msg, '(A,I0,A,I0,A,I0,A,I0,A)') &
     393            0 :             "CHARGE MIXING: endpoints disagree with the requested bracket. Wanted (", &
     394            0 :             electrons%charge_mixing_current_n_lo, ",", electrons%charge_mixing_current_n_hi, &
     395            0 :             ") but the FORCE_EVALs hold (", n_have(1), ",", n_have(2), ")."
     396            0 :          CPABORT(TRIM(msg))
     397              :       END IF
     398              : 
     399              :       ! A collapsed bracket makes E independent of lambda: the mixed energy is
     400              :       ! then a single integer-charge result, dPhi/dq is zero, and q drifts under
     401              :       ! no restoring force whatsoever.  It cannot arise from the arithmetic
     402              :       ! above, but it is the one corruption that would masquerade as a healthy
     403              :       ! trajectory, so it is worth naming explicitly.
     404            4 :       IF (n_have(2) - n_have(1) /= MAX(1, electrons%charge_mixing_span)) THEN
     405              :          WRITE (msg, '(A,I0,A,I0,A,I0,A)') &
     406            0 :             "CHARGE MIXING: endpoint separation is ", n_have(2) - n_have(1), &
     407            0 :             " but CHARGE_MIXING_SPAN is ", MAX(1, electrons%charge_mixing_span), &
     408            0 :             ". The two FORCE_EVALs no longer bracket q."
     409            0 :          CPABORT(TRIM(msg))
     410              :       END IF
     411              : 
     412            4 :       IF (moved) THEN
     413            0 :          iw = cp_logger_get_default_io_unit()
     414            0 :          IF (iw > 0) THEN
     415              :             WRITE (iw, '(T2,A,I0,A,I0,A,F14.8)') &
     416            0 :                "CHARGE MIXING| bracket now [", n_have(1), ",", n_have(2), "]  q = ", electrons%q
     417              :          END IF
     418              :       END IF
     419              : 
     420            4 :    END SUBROUTINE charge_mixing_verify_endpoints
     421              : 
     422              : ! **************************************************************************************************
     423              : !> \brief Tear down and rebuild force_env%sub_force_env(idx) at a new integer
     424              : !>        electron count, preserving the CURRENT (dynamics-evolved) geometry
     425              : !>        and cell by handing the old subsys straight to qs_init. This is the
     426              : !>        fallback path used when CHARGE_MIXING_INPLACE is off.
     427              : !> \param force_env the top-level MIXED force_env
     428              : !> \param idx 1 (the N_lo endpoint) or 2 (the N_hi endpoint)
     429              : !> \param new_n_electron the new integer electron count for this endpoint
     430              : !> \param electrons used only for neutral_electrons, to convert electron
     431              : !>        count back into CP2K's own CHARGE = neutral - n_electron convention
     432              : ! **************************************************************************************************
     433            0 :    SUBROUTINE rebuild_charge_mixing_endpoint(force_env, idx, new_n_electron, electrons)
     434              :       TYPE(force_env_type), POINTER                      :: force_env
     435              :       INTEGER, INTENT(IN)                                :: idx, new_n_electron
     436              :       TYPE(qs_electrons_type), POINTER                   :: electrons
     437              : 
     438              :       INTEGER                                            :: my_group, new_charge
     439              :       LOGICAL                                            :: subsys_explicit
     440              :       TYPE(cp_logger_type), POINTER                      :: sub_logger
     441              :       TYPE(cp_subsys_type), POINTER                      :: old_subsys
     442              :       TYPE(force_env_type), POINTER                      :: new_sub, old_sub
     443              :       TYPE(global_environment_type), POINTER             :: globenv
     444              :       TYPE(mp_para_env_type), POINTER                    :: para_env
     445              :       TYPE(qs_environment_type), POINTER                 :: new_qs_env
     446              :       TYPE(section_vals_type), POINTER                   :: dft_section, force_env_section, &
     447              :                                                             mixed_subsys_section, root_section, &
     448              :                                                             subsys_section
     449              : 
     450            0 :       NULLIFY (new_sub, old_sub, dft_section, force_env_section, subsys_section, &
     451            0 :                para_env, globenv, root_section, new_qs_env, old_subsys, sub_logger, &
     452            0 :                mixed_subsys_section)
     453              : 
     454            0 :       old_sub => force_env%sub_force_env(idx)%force_env
     455            0 :       IF (.NOT. ASSOCIATED(old_sub)) RETURN   ! not this rank's group under NGROUPS>1
     456              : 
     457              :       ! Install this group's own logger for the duration of the rebuild, exactly as
     458              :       ! mixed_energy_forces does before it touches a sub_force_env.  This is NOT
     459              :       ! cosmetic: distribute_molecules_1d (distribution_methods.F:102) takes NO
     460              :       ! para_env argument at all.  It reads its communicator straight off the
     461              :       ! default logger --
     462              :       !
     463              :       !    logger => cp_get_default_logger()
     464              :       !    ASSOCIATE (group => logger%para_env, mype => logger%para_env%mepos + 1, &
     465              :       !               npe   => logger%para_env%num_pe)
     466              :       !       ...
     467              :       !       nbins = npe
     468              :       !
     469              :       ! -- deals the atoms into nbins bins and lets a rank claim one only when
     470              :       ! ipe == mype.  At startup mixed_energy_forces has already installed the
     471              :       ! group logger, so the atoms are dealt across the GROUP.  A rebuild driven
     472              :       ! from the MD integrator runs outside mixed_energy_forces, where the default
     473              :       ! logger is the GLOBAL one: the atoms are then dealt across every rank in the
     474              :       ! job while the DFT-D3 energy is later summed over this group only, so every
     475              :       ! atom binned to a rank outside the group is silently dropped.  Measured:
     476              :       ! TOT_vdw 14112 -> 7042 pairs, rank-0 local particles 2 -> 1, at NGROUPS 2
     477              :       ! with a 16-rank group inside a 32-rank job.
     478              :       !
     479              :       ! distribution_2d is immune because distribute_molecules_2d is handed its
     480              :       ! blacs_env explicitly (rows2d/cols2d were verified unchanged at 9/9), and
     481              :       ! sab_vdw/sab_cn are the only neighbour lists affected because
     482              :       ! operator_type="PP" -> otype 4 is the only branch of build_neighbor_lists
     483              :       ! that reads atom2d%list_1d, which is built from local_particles.
     484              :       !
     485              :       ! The same wrong-logger para_env is what produced MPI_ERR_TRUNCATE in
     486              :       ! mp_sum_l at the first crossing: qs_init logs collectively, and outside
     487              :       ! mixed_energy_forces the DEFAULT logger's para_env spans every rank.
     488            0 :       IF (ASSOCIATED(force_env%mixed_env)) THEN
     489            0 :          IF (ASSOCIATED(force_env%mixed_env%sub_logger) .AND. &
     490              :              ASSOCIATED(force_env%mixed_env%group_distribution)) THEN
     491            0 :             my_group = force_env%mixed_env%group_distribution(force_env%para_env%mepos)
     492            0 :             sub_logger => force_env%mixed_env%sub_logger(my_group + 1)%p
     493              :          END IF
     494              :       END IF
     495            0 :       IF (ASSOCIATED(sub_logger)) CALL cp_add_default_logger(sub_logger)
     496              : 
     497            0 :       new_charge = NINT(electrons%neutral_electrons) - new_n_electron
     498              : 
     499            0 :       para_env => old_sub%para_env
     500            0 :       globenv => old_sub%globenv
     501            0 :       root_section => old_sub%root_section
     502            0 :       force_env_section => old_sub%force_env_section
     503            0 :       CALL force_env_get(old_sub, subsys=old_subsys)
     504              : 
     505              :       ! Mutate CHARGE in place on the (shared, reference-counted) input
     506              :       ! section before rebuilding -- qs_init reads DFT%CHARGE from
     507              :       ! force_env_section exactly as it did on the original, once-at-startup
     508              :       ! build, so this alone determines the new endpoint's electron count.
     509            0 :       dft_section => section_vals_get_subs_vals(force_env_section, "DFT")
     510            0 :       CALL section_vals_val_set(dft_section, "CHARGE", i_val=new_charge)
     511              : 
     512              :       ! Which &SUBSYS does qs_init read the kinds and basis sets from?
     513              :       !
     514              :       ! In the ORIGINAL input each sub-FORCE_EVAL carries its own &SUBSYS, so
     515              :       ! taking the child of this endpoint's force_env_section works. In a RESTART
     516              :       ! file it does not: CP2K's restart writer emits &SUBSYS exactly once, on the
     517              :       ! force_eval that owns the particles, and leaves the sub-FORCE_EVALs without
     518              :       ! one. CP2K's own startup path copes with that, which is why a restarted run
     519              :       ! reaches the first SCF happily -- but this rebuild then reads an empty
     520              :       ! section and aborts, first in cell_methods.F ("cell volume is too small")
     521              :       ! and, once the cell is inherited from the live environment, in
     522              :       ! qs_kind_types.F ("No &KIND section ... to associate to the atomic kind").
     523              :       !
     524              :       ! So: use this endpoint's own &SUBSYS when it is explicit, and otherwise
     525              :       ! fall back to the MIXED force_env's. The two describe the same atoms; only
     526              :       ! DFT%CHARGE differs between endpoints, and that lives in the &DFT section
     527              :       ! mutated above, not here.
     528            0 :       subsys_section => section_vals_get_subs_vals(force_env_section, "SUBSYS")
     529            0 :       CALL section_vals_get(subsys_section, explicit=subsys_explicit)
     530            0 :       IF (.NOT. subsys_explicit) THEN
     531            0 :          IF (ASSOCIATED(force_env%force_env_section)) THEN
     532            0 :             mixed_subsys_section => section_vals_get_subs_vals(force_env%force_env_section, "SUBSYS")
     533            0 :             CALL section_vals_get(mixed_subsys_section, explicit=subsys_explicit)
     534            0 :             IF (subsys_explicit) subsys_section => mixed_subsys_section
     535              :          END IF
     536              :       END IF
     537              : 
     538            0 :       ALLOCATE (new_qs_env)
     539            0 :       CALL qs_env_create(new_qs_env, globenv)
     540              :       ! cp_subsys=old_subsys hands the current MD-evolved positions, velocities and
     541              :       ! cell (including the reference cell) straight to the new environment, so
     542              :       ! neither positions nor the cell are re-read from the input file.
     543              :       CALL qs_init(new_qs_env, para_env, root_section=root_section, globenv=globenv, &
     544              :                    cp_subsys=old_subsys, force_env_section=force_env_section, &
     545            0 :                    subsys_section=subsys_section, use_motion_section=.FALSE.)
     546              : 
     547              :       ! force_env_create's signature IS confirmed (force_env_methods.F line
     548              :       ! 728): it ALLOCATEs new_sub itself (must be passed unallocated, which
     549              :       ! it is here), sets ref_count=1, and -- critically -- RETAINS every
     550              :       ! shared object it is handed before storing it:
     551              :       !   force_env%globenv => globenv;        CALL globenv_retain(...)
     552              :       !   force_env%root_section => root_section; CALL section_vals_retain(...)
     553              :       !   force_env%para_env => para_env;      CALL force_env%para_env%retain()
     554              :       !   CALL section_vals_retain(force_env_section); force_env%force_env_section => ...
     555              :       ! So handing it the SAME para_env/globenv/root_section/force_env_section
     556              :       ! that old_sub already owns is safe: new_sub's copies are retained
     557              :       ! (ref_count bumped) here, BEFORE old_sub is released below, so
     558              :       ! old_sub's release cannot pull any of them to zero out from under
     559              :       ! new_sub. qs_env is NOT retained (force_env%qs_env => qs_env is a
     560              :       ! direct, unshared assignment) -- correct here since new_qs_env was
     561              :       ! freshly allocated solely for this new_sub, not shared with old_sub.
     562              :       CALL force_env_create(new_sub, root_section=root_section, para_env=para_env, &
     563            0 :                             globenv=globenv, qs_env=new_qs_env, force_env_section=force_env_section)
     564              : 
     565              :       ! force_env_release's signature IS confirmed (force_env_types.F line
     566              : ! **************************************************************************************************
     567              : !> \brief ...
     568              : !> \param force_env ...
     569              : ! **************************************************************************************************
     570              :       ! 206): RECURSIVE SUBROUTINE force_env_release(force_env) with
     571              :       ! force_env as TYPE(force_env_type), POINTER -- exactly as called here.
     572              :       ! It is refcounted (decrements ref_count, only actually deallocates at
     573              :       ! zero) and nullifies the pointer on return, so old_sub itself does not
     574              :       ! need a manual NULLIFY afterward.
     575              :       ! ---------------------------------------------------------------------
     576              :       ! REMOVED: the sab_vdw / sab_cn handover from the old dispersion_env to
     577              :       ! the new one.  It was tested on-cluster and changed nothing (E_disp
     578              :       ! stayed at -0.16998 Ha), and the reason is structural, not empirical:
     579              :       ! build_neighbor_lists opens with CALL release_neighbor_list_sets(ab_list)
     580              :       ! (qs_neighbor_lists.F:1148), and build_qs_neighbor_lists calls it
     581              :       ! unconditionally for both sab_vdw and sab_cn.  Whatever is handed over
     582              :       ! here is therefore freed and regenerated at the new endpoint's first SCF.
     583              :       ! The handover was dead code.  Any fix must act at the construction site,
     584              :       ! not here.  The dispersion_env parameter dump that used to sit here is
     585              :       ! also gone: it answered its question (every parameter is identical
     586              :       ! between the two builds).  The live diagnostic is now the @@ NLDIAG /
     587              :       ! @@ NLDIST / @@ NLTOTAL block in qs_neighbor_lists.F, which reports pair
     588              :       ! counts and the atomic distribution for both the startup build and the
     589              :       ! rebuild in the same job.
     590              :       ! ---------------------------------------------------------------------
     591              : 
     592            0 :       CALL force_env_release(old_sub)
     593            0 :       force_env%sub_force_env(idx)%force_env => new_sub
     594              : 
     595            0 :       IF (ASSOCIATED(sub_logger)) CALL cp_rm_default_logger()
     596              : 
     597              :    END SUBROUTINE rebuild_charge_mixing_endpoint
     598              : 
     599              : ! **************************************************************************************************
     600              : !> \brief Change the electron count of an existing endpoint IN PLACE, without
     601              : !>        re-entering qs_init.
     602              : !>
     603              : !>        Both endpoints persist across boundary crossings and only their
     604              : !>        electron count changes. Everything qs_init constructs that does NOT depend on the
     605              : !>        electron count -- dispersion_env and its neighbour lists, pw_env, the
     606              : !>        atomic distributions, the basis, the wavefunction -- simply persists.
     607              : !>
     608              : !>        qs_environment.F derives the whole electron-count-dependent state from
     609              : !>        one line (line 1549):
     610              : !>
     611              : !>            nelectron = nelectron - dft_control%charge
     612              : !>
     613              : !>        and from it sets nelectron_spin / maxocc / n_mo, storing the counts on
     614              : !>        the subsys and the mo_sets. Reproducing just that chain is sufficient.
     615              : !>
     616              : !>        The allocated MO count (mo_set%nmo) is deliberately NOT touched: nmo
     617              : !>        is n_occupied + ADDED_MOS as qs_init sized it for the INPUT charge,
     618              : !>        and the occupations are recomputed from the Fermi level at every SCF,
     619              : !>        so nothing stale survives. Each crossing moves an endpoint by
     620              : !>        CHARGE_MIXING_SPAN electrons, so ADDED_MOS has to cover the furthest
     621              : !>        endpoint the run reaches; that is checked below rather than assumed.
     622              : !>
     623              : !>        OT is refused. Under OT every one of the nmo columns is fully occupied
     624              : !>        (no ADDED_MOS, no fractional occupation), so changing nelectron without
     625              : !>        resizing mo_coeff leaves the density at the OLD electron count while
     626              : !>        the subsys reports the new one. Use CHARGE_MIXING_INPLACE F with OT.
     627              : !>
     628              : !>        Restricted (nspins=1): the whole count goes in one channel; with
     629              : !>        smearing it need not be even. Unrestricted: the multiplicity is
     630              : !>        re-derived exactly as qs_init does it (qs_environment.F ~1551). The
     631              : !>        value dft_control%multiplicity holds is NOT reusable: qs_init has
     632              : !>        already overwritten the input's MULTIPLICITY 0 ("automatic") with 1 or
     633              : !>        2 for the INPUT parity, so reusing it after an odd span crossing gave
     634              : !>        (N+m-1)/2 + (N-m+1)/2 = N-1 electrons -- silently, since
     635              : !>        nelectron_total was still set to N. MULTIPLICITY is therefore re-read
     636              : !>        from the input: 0 is resolved again for the new parity, an explicit
     637              : !>        value is kept and must be compatible, as qs_init requires.
     638              : !> \param force_env the top-level MIXED force_env
     639              : !> \param idx which sub_force_env (1 = N_lo slot, 2 = N_hi slot)
     640              : !> \param new_n_electron the endpoint's new integer electron count
     641              : !> \param electrons ...
     642              : ! **************************************************************************************************
     643            0 :    SUBROUTINE charge_mixing_set_endpoint_charge(force_env, idx, new_n_electron, electrons)
     644              :       TYPE(force_env_type), POINTER                      :: force_env
     645              :       INTEGER, INTENT(IN)                                :: idx, new_n_electron
     646              :       TYPE(qs_electrons_type), POINTER                   :: electrons
     647              : 
     648              :       CHARACTER(LEN=256)                                 :: msg
     649              :       INTEGER                                            :: input_multiplicity, ispin, multiplicity, &
     650              :                                                             new_charge, nmo
     651              :       INTEGER, DIMENSION(2)                              :: nelectron_spin
     652              :       REAL(KIND=dp)                                      :: maxocc
     653              :       TYPE(dft_control_type), POINTER                    :: dft_control
     654              :       TYPE(force_env_type), POINTER                      :: sub
     655            0 :       TYPE(mo_set_type), DIMENSION(:), POINTER           :: mos
     656              :       TYPE(qs_subsys_type), POINTER                      :: subsys
     657              :       TYPE(scf_control_type), POINTER                    :: scf_control
     658              :       TYPE(section_vals_type), POINTER                   :: dft_section, sub_section
     659              : 
     660            0 :       NULLIFY (sub, dft_control, mos, subsys, scf_control, dft_section, sub_section)
     661              : 
     662            0 :       sub => force_env%sub_force_env(idx)%force_env
     663            0 :       IF (.NOT. ASSOCIATED(sub)) RETURN     ! not this rank's group under NGROUPS>1
     664            0 :       IF (.NOT. ASSOCIATED(sub%qs_env)) RETURN
     665              : 
     666            0 :       new_charge = NINT(electrons%neutral_electrons) - new_n_electron
     667              : 
     668              :       CALL get_qs_env(sub%qs_env, dft_control=dft_control, mos=mos, subsys=subsys, &
     669            0 :                       scf_control=scf_control)
     670              : 
     671            0 :       IF (ASSOCIATED(scf_control)) THEN
     672            0 :          IF (scf_control%use_ot) THEN
     673              :             msg = "CHARGE_MIXING_INPLACE cannot change the electron count under OT; "// &
     674            0 :                   "use CHARGE_MIXING_INPLACE F"
     675            0 :             CPABORT(TRIM(msg))
     676              :          END IF
     677              :       END IF
     678              : 
     679            0 :       IF (dft_control%nspins == 1) THEN
     680            0 :          multiplicity = dft_control%multiplicity
     681            0 :          nelectron_spin(1) = new_n_electron
     682            0 :          nelectron_spin(2) = 0
     683              :       ELSE
     684            0 :          CALL force_env_get(sub, force_env_section=sub_section)
     685            0 :          dft_section => section_vals_get_subs_vals(sub_section, "DFT")
     686            0 :          CALL section_vals_val_get(dft_section, "MULTIPLICITY", i_val=input_multiplicity)
     687            0 :          multiplicity = input_multiplicity
     688            0 :          IF (multiplicity == 0) THEN
     689            0 :             IF (MODULO(new_n_electron, 2) == 0) THEN
     690            0 :                multiplicity = 1
     691              :             ELSE
     692            0 :                multiplicity = 2
     693              :             END IF
     694              :          END IF
     695            0 :          IF (MODULO(new_n_electron + multiplicity - 1, 2) /= 0) THEN
     696            0 :             WRITE (msg, '(A,I0,A,I0,A)') "CHARGE MIXING: MULTIPLICITY ", multiplicity, &
     697            0 :                " is incompatible with ", new_n_electron, &
     698            0 :                " electrons. Use MULTIPLICITY 0 (automatic) or an even CHARGE_MIXING_SPAN."
     699            0 :             CPABORT(TRIM(msg))
     700              :          END IF
     701            0 :          nelectron_spin(1) = (new_n_electron + multiplicity - 1)/2
     702            0 :          nelectron_spin(2) = (new_n_electron - multiplicity + 1)/2
     703            0 :          IF (nelectron_spin(2) < 0) THEN
     704            0 :             CPABORT("CHARGE MIXING: too few electrons for this MULTIPLICITY")
     705              :          END IF
     706              :       END IF
     707              : 
     708              :       ! Every orbital the new occupation needs must already be allocated: nmo is
     709              :       ! never resized here. Without this an endpoint pushed past n_occ+ADDED_MOS
     710              :       ! would quietly hold fewer electrons than nelectron_total claims.
     711            0 :       IF (ASSOCIATED(mos)) THEN
     712            0 :          IF (SIZE(mos) /= dft_control%nspins) THEN
     713            0 :             msg = "CHARGE MIXING: mo_set count differs from nspins"
     714            0 :             CPABORT(TRIM(msg))
     715              :          END IF
     716            0 :          DO ispin = 1, SIZE(mos)
     717            0 :             CALL get_mo_set(mos(ispin), nmo=nmo, maxocc=maxocc)
     718            0 :             IF (REAL(nelectron_spin(ispin), KIND=dp) > maxocc*REAL(nmo, KIND=dp) + 1.0E-8_dp) THEN
     719            0 :                WRITE (msg, '(A,I0,A,I0,A,I0,A)') "CHARGE MIXING: endpoint at ", new_n_electron, &
     720            0 :                   " electrons needs more orbitals in spin ", ispin, " than the ", nmo, &
     721            0 :                   " allocated. Increase ADDED_MOS or use CHARGE_MIXING_INPLACE F."
     722            0 :                CPABORT(TRIM(msg))
     723              :             END IF
     724              :          END DO
     725              :       END IF
     726              : 
     727            0 :       dft_control%charge = new_charge
     728            0 :       dft_control%multiplicity = multiplicity
     729              : 
     730              :       CALL qs_subsys_set(subsys, nelectron_total=new_n_electron, &
     731            0 :                          nelectron_spin=nelectron_spin)
     732              : 
     733            0 :       IF (ASSOCIATED(mos)) THEN
     734            0 :          DO ispin = 1, SIZE(mos)
     735              :             CALL set_mo_set(mos(ispin), nelectron=nelectron_spin(ispin), &
     736            0 :                             n_el_f=REAL(nelectron_spin(ispin), KIND=dp))
     737              :          END DO
     738              :       END IF
     739              : 
     740            0 :    END SUBROUTINE charge_mixing_set_endpoint_charge
     741              : 
     742              : END MODULE qs_electrons_charge_mixing
        

Generated by: LCOV version 2.0-1