(git:27c966b)
Loading...
Searching...
No Matches
qs_electrons_charge_mixing.F
Go to the documentation of this file.
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! **************************************************************************************************
38 USE kinds, ONLY: dp
42 USE qs_environment, ONLY: qs_init
46 USE qs_mo_types, ONLY: get_mo_set,&
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
66
67CONTAINS
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 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 span = max(1, electrons%charge_mixing_span)
86 my_n_lo = span*floor(electrons%q/real(span, kind=dp))
87 my_n_hi = my_n_lo + span
88 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 lambda = electrons%lambda_fixed
94 ELSE
95 lambda = (electrons%q - real(my_n_lo, kind=dp))/real(span, kind=dp)
96 END IF
97
98 IF (PRESENT(n_lo)) n_lo = my_n_lo
99 IF (PRESENT(n_hi)) n_hi = my_n_hi
100
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 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 NULLIFY (force_env_section, mixed_section)
130 CALL force_env_get(force_env, force_env_section=force_env_section)
131 mixed_section => section_vals_get_subs_vals(force_env_section, "MIXED")
132 CALL section_vals_val_set(mixed_section, "LINEAR%LAMBDA", r_val=1.0_dp - lambda)
133
134 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 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 cpassert(ASSOCIATED(force_env%sub_force_env))
173 cpassert(SIZE(force_env%sub_force_env) == 2)
174
175 IF (PRESENT(lambda_in)) THEN
176 lambda = lambda_in
177 ELSE
178 n_lo = span*floor(q/real(span, kind=dp))
179 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 fermi_lo = 0.0_dp
201 wf_lo = 0.0_dp
202 fermi_hi = 0.0_dp
203 wf_hi = 0.0_dp
204
205 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 fermi_lo, wf_lo)
208 IF (.NOT. force_env%sub_force_env(1)%force_env%para_env%is_source()) THEN
209 fermi_lo = 0.0_dp
210 wf_lo = 0.0_dp
211 END IF
212 END IF
213 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 fermi_hi, wf_hi)
216 IF (.NOT. force_env%sub_force_env(2)%force_env%para_env%is_source()) THEN
217 fermi_hi = 0.0_dp
218 wf_hi = 0.0_dp
219 END IF
220 END IF
221
222 CALL force_env%para_env%sum(fermi_lo)
223 CALL force_env%para_env%sum(wf_lo)
224 CALL force_env%para_env%sum(fermi_hi)
225 CALL force_env%para_env%sum(wf_hi)
226
227 fermi_level_ev = (1.0_dp - lambda)*fermi_lo + lambda*fermi_hi
228 workfunction_ev = (1.0_dp - lambda)*wf_lo + lambda*wf_hi
229
230 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 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 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 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 (n_hi /= electrons%charge_mixing_current_n_hi)
263
264 IF (n_lo /= electrons%charge_mixing_current_n_lo) THEN
265 IF (electrons%charge_mixing_inplace) THEN
266 CALL charge_mixing_set_endpoint_charge(force_env, 1, n_lo, electrons)
267 ELSE
268 CALL rebuild_charge_mixing_endpoint(force_env, 1, n_lo, electrons)
269 END IF
270 electrons%charge_mixing_current_n_lo = n_lo
271 END IF
272 IF (n_hi /= electrons%charge_mixing_current_n_hi) THEN
273 IF (electrons%charge_mixing_inplace) THEN
274 CALL charge_mixing_set_endpoint_charge(force_env, 2, n_hi, electrons)
275 ELSE
276 CALL rebuild_charge_mixing_endpoint(force_env, 2, n_hi, electrons)
277 END IF
278 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 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 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 IF (.NOT. electrons%charge_mixing_enabled) RETURN
318
319 CALL charge_mixing_read_endpoint_counts(force_env, n_have)
320 electrons%charge_mixing_current_n_lo = n_have(1)
321 electrons%charge_mixing_current_n_hi = n_have(2)
322
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 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 n_have = -huge(0)
347 IF (.NOT. ASSOCIATED(force_env%sub_force_env)) RETURN
348
349 DO idx = 1, 2
350 NULLIFY (sub, subsys)
351 IF (idx > SIZE(force_env%sub_force_env)) cycle
352 sub => force_env%sub_force_env(idx)%force_env
353 IF (.NOT. ASSOCIATED(sub)) cycle
354 IF (.NOT. ASSOCIATED(sub%qs_env)) cycle
355 CALL get_qs_env(sub%qs_env, subsys=subsys)
356 IF (.NOT. ASSOCIATED(subsys)) cycle
357 CALL qs_subsys_get(subsys, nelectron_total=n_have(idx))
358 END DO
359
360 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 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 CALL charge_mixing_read_endpoint_counts(force_env, n_have)
389
390 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 "CHARGE MIXING: endpoints disagree with the requested bracket. Wanted (", &
394 electrons%charge_mixing_current_n_lo, ",", electrons%charge_mixing_current_n_hi, &
395 ") but the FORCE_EVALs hold (", n_have(1), ",", n_have(2), ")."
396 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 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 "CHARGE MIXING: endpoint separation is ", n_have(2) - n_have(1), &
407 " but CHARGE_MIXING_SPAN is ", max(1, electrons%charge_mixing_span), &
408 ". The two FORCE_EVALs no longer bracket q."
409 cpabort(trim(msg))
410 END IF
411
412 IF (moved) THEN
414 IF (iw > 0) THEN
415 WRITE (iw, '(T2,A,I0,A,I0,A,F14.8)') &
416 "CHARGE MIXING| bracket now [", n_have(1), ",", n_have(2), "] q = ", electrons%q
417 END IF
418 END IF
419
420 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 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 NULLIFY (new_sub, old_sub, dft_section, force_env_section, subsys_section, &
451 para_env, globenv, root_section, new_qs_env, old_subsys, sub_logger, &
452 mixed_subsys_section)
453
454 old_sub => force_env%sub_force_env(idx)%force_env
455 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 IF (ASSOCIATED(force_env%mixed_env)) THEN
489 IF (ASSOCIATED(force_env%mixed_env%sub_logger) .AND. &
490 ASSOCIATED(force_env%mixed_env%group_distribution)) THEN
491 my_group = force_env%mixed_env%group_distribution(force_env%para_env%mepos)
492 sub_logger => force_env%mixed_env%sub_logger(my_group + 1)%p
493 END IF
494 END IF
495 IF (ASSOCIATED(sub_logger)) CALL cp_add_default_logger(sub_logger)
496
497 new_charge = nint(electrons%neutral_electrons) - new_n_electron
498
499 para_env => old_sub%para_env
500 globenv => old_sub%globenv
501 root_section => old_sub%root_section
502 force_env_section => old_sub%force_env_section
503 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 dft_section => section_vals_get_subs_vals(force_env_section, "DFT")
510 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 subsys_section => section_vals_get_subs_vals(force_env_section, "SUBSYS")
529 CALL section_vals_get(subsys_section, explicit=subsys_explicit)
530 IF (.NOT. subsys_explicit) THEN
531 IF (ASSOCIATED(force_env%force_env_section)) THEN
532 mixed_subsys_section => section_vals_get_subs_vals(force_env%force_env_section, "SUBSYS")
533 CALL section_vals_get(mixed_subsys_section, explicit=subsys_explicit)
534 IF (subsys_explicit) subsys_section => mixed_subsys_section
535 END IF
536 END IF
537
538 ALLOCATE (new_qs_env)
539 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 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 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 CALL force_env_release(old_sub)
593 force_env%sub_force_env(idx)%force_env => new_sub
594
595 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 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 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 NULLIFY (sub, dft_control, mos, subsys, scf_control, dft_section, sub_section)
661
662 sub => force_env%sub_force_env(idx)%force_env
663 IF (.NOT. ASSOCIATED(sub)) RETURN ! not this rank's group under NGROUPS>1
664 IF (.NOT. ASSOCIATED(sub%qs_env)) RETURN
665
666 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 scf_control=scf_control)
670
671 IF (ASSOCIATED(scf_control)) THEN
672 IF (scf_control%use_ot) THEN
673 msg = "CHARGE_MIXING_INPLACE cannot change the electron count under OT; "// &
674 "use CHARGE_MIXING_INPLACE F"
675 cpabort(trim(msg))
676 END IF
677 END IF
678
679 IF (dft_control%nspins == 1) THEN
680 multiplicity = dft_control%multiplicity
681 nelectron_spin(1) = new_n_electron
682 nelectron_spin(2) = 0
683 ELSE
684 CALL force_env_get(sub, force_env_section=sub_section)
685 dft_section => section_vals_get_subs_vals(sub_section, "DFT")
686 CALL section_vals_val_get(dft_section, "MULTIPLICITY", i_val=input_multiplicity)
687 multiplicity = input_multiplicity
688 IF (multiplicity == 0) THEN
689 IF (modulo(new_n_electron, 2) == 0) THEN
690 multiplicity = 1
691 ELSE
692 multiplicity = 2
693 END IF
694 END IF
695 IF (modulo(new_n_electron + multiplicity - 1, 2) /= 0) THEN
696 WRITE (msg, '(A,I0,A,I0,A)') "CHARGE MIXING: MULTIPLICITY ", multiplicity, &
697 " is incompatible with ", new_n_electron, &
698 " electrons. Use MULTIPLICITY 0 (automatic) or an even CHARGE_MIXING_SPAN."
699 cpabort(trim(msg))
700 END IF
701 nelectron_spin(1) = (new_n_electron + multiplicity - 1)/2
702 nelectron_spin(2) = (new_n_electron - multiplicity + 1)/2
703 IF (nelectron_spin(2) < 0) THEN
704 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 IF (ASSOCIATED(mos)) THEN
712 IF (SIZE(mos) /= dft_control%nspins) THEN
713 msg = "CHARGE MIXING: mo_set count differs from nspins"
714 cpabort(trim(msg))
715 END IF
716 DO ispin = 1, SIZE(mos)
717 CALL get_mo_set(mos(ispin), nmo=nmo, maxocc=maxocc)
718 IF (real(nelectron_spin(ispin), kind=dp) > maxocc*real(nmo, kind=dp) + 1.0e-8_dp) THEN
719 WRITE (msg, '(A,I0,A,I0,A,I0,A)') "CHARGE MIXING: endpoint at ", new_n_electron, &
720 " electrons needs more orbitals in spin ", ispin, " than the ", nmo, &
721 " allocated. Increase ADDED_MOS or use CHARGE_MIXING_INPLACE F."
722 cpabort(trim(msg))
723 END IF
724 END DO
725 END IF
726
727 dft_control%charge = new_charge
728 dft_control%multiplicity = multiplicity
729
730 CALL qs_subsys_set(subsys, nelectron_total=new_n_electron, &
731 nelectron_spin=nelectron_spin)
732
733 IF (ASSOCIATED(mos)) THEN
734 DO ispin = 1, SIZE(mos)
735 CALL set_mo_set(mos(ispin), nelectron=nelectron_spin(ispin), &
736 n_el_f=real(nelectron_spin(ispin), kind=dp))
737 END DO
738 END IF
739
740 END SUBROUTINE charge_mixing_set_endpoint_charge
741
static GRID_HOST_DEVICE int modulo(int a, int m)
Equivalent of Fortran's MODULO, which always return a positive number. https://gcc....
static GRID_HOST_DEVICE int idx(const orbital a)
Return coset index of given orbital angular momentum.
Defines control structures, which contain the parameters and the settings for the DFT-based calculati...
various routines to log and control the output. The idea is that decisions about where to log should ...
subroutine, public cp_rm_default_logger()
the cousin of cp_add_default_logger, decrements the stack, so that the default logger is what it has ...
integer function, public cp_logger_get_default_io_unit(logger)
returns the unit nr for the ionode (-1 on all other processors) skips as well checks if the procs cal...
subroutine, public cp_add_default_logger(logger)
adds a default logger. MUST be called before logging occours
types that represent a subsys, i.e. a part of the system
Interface for the force calculations.
subroutine, public force_env_create(force_env, root_section, para_env, globenv, fist_env, qs_env, meta_env, sub_force_env, qmmm_env, qmmmx_env, eip_env, pwdft_env, force_env_section, mixed_env, embed_env, nnp_env, ipi_env)
creates and initializes a force environment
Interface for the force calculations.
recursive subroutine, public force_env_get(force_env, in_use, fist_env, qs_env, meta_env, fp_env, subsys, para_env, potential_energy, additional_potential, kinetic_energy, harmonic_shell, kinetic_shell, cell, sub_force_env, qmmm_env, qmmmx_env, eip_env, pwdft_env, globenv, input, force_env_section, method_name_id, root_section, mixed_env, nnp_env, embed_env, ipi_env)
returns various attributes about the force environment
recursive subroutine, public force_env_release(force_env)
releases the given force env
Define type storing the global information of a run. Keep the amount of stored data small....
objects that represent the structure of input sections and the data contained in an input section
subroutine, public section_vals_val_set(section_vals, keyword_name, i_rep_section, i_rep_val, val, l_val, i_val, r_val, c_val, l_vals_ptr, i_vals_ptr, r_vals_ptr, c_vals_ptr)
sets the requested value
recursive type(section_vals_type) function, pointer, public section_vals_get_subs_vals(section_vals, subsection_name, i_rep_section, can_return_null)
returns the values of the requested subsection
subroutine, public section_vals_get(section_vals, ref_count, n_repetition, n_subs_vals_rep, section, explicit)
returns various attributes about the section_vals
subroutine, public section_vals_val_get(section_vals, keyword_name, i_rep_section, i_rep_val, n_rep_val, val, l_val, i_val, r_val, c_val, l_vals, i_vals, r_vals, c_vals, explicit)
returns the requested value
Defines the basic variable types.
Definition kinds.F:23
integer, parameter, public dp
Definition kinds.F:34
Interface to the message passing library MPI.
Dual integer-electron-endpoint charge mixing for constant-potential MD, built on top of CP2K's stock ...
subroutine, public push_lambda_to_mixed_env(force_env, lambda)
Push a dynamically computed lambda into the MIXED force_eval's input structure. force_env_methods....
subroutine, public charge_mixing_maybe_rebuild(force_env, electrons)
Check whether q(t) has drifted outside the currently-built [N_lo,N_hi] bracket and,...
subroutine, public qs_electrons_charge_mixing_lambda(electrons, lambda, n_lo, n_hi)
Given the current electronic coordinate q and the integer span S, compute the bracketing integers N_l...
subroutine, public charge_mixing_sync_endpoint_state(force_env, electrons)
Record which integer electron counts the two FORCE_EVAL blocks are ACTUALLY built for,...
subroutine, public compute_mixed_workfunction(force_env, axis, wf_min, wf_max, q, span, fermi_level_ev, workfunction_ev, lambda_in)
Fermi level / workfunction mixing across the two integer-charge endpoints. Stock MIXED only combines ...
State of the fictitious electronic degree of freedom (electron number q, its momentum,...
Work function and Fermi level readback from the converged SCF, using the planar average of the Hartre...
subroutine, public qs_electrons_compute_workfunction(force_env, axis, minimum_a, maximum_a, fermi_level_ev, workfunction_ev)
Compute the work function (vacuum Hartree level minus Fermi level, in eV) from the planar average of ...
subroutine, public get_qs_env(qs_env, atomic_kind_set, qs_kind_set, cell, super_cell, cell_ref, use_ref_cell, kpoints, dft_control, mos, sab_orb, sab_all, qmmm, qmmm_periodic, mimic, sac_ae, sac_ppl, sac_lri, sap_ppnl, sab_vdw, sab_scp, sap_oce, sab_lrc, sab_se, sab_xtbe, sab_tbe, sab_core, sab_xb, sab_xtb_pp, sab_xtb_nonbond, sab_almo, sab_kp, sab_kp_nosym, sab_cneo, particle_set, energy, force, matrix_h, matrix_h_im, matrix_ks, matrix_ks_im, matrix_vxc, run_rtp, rtp, matrix_h_kp, matrix_h_im_kp, matrix_ks_kp, matrix_ks_im_kp, matrix_vxc_kp, kinetic_kp, matrix_s_kp, matrix_w_kp, matrix_s_ri_aux_kp, matrix_s, matrix_s_ri_aux, matrix_w, matrix_p_mp2, matrix_p_mp2_admm, matrix_vhxc, rho, rho_xc, pw_env, ewald_env, ewald_pw, active_space, mpools, input, para_env, blacs_env, scf_control, rel_control, kinetic, qs_charges, vppl, xcint_weights, rho_core, rho_nlcc, rho_nlcc_g, ks_env, ks_qmmm_env, wf_history, scf_env, local_particles, local_molecules, distribution_2d, dbcsr_dist, molecule_kind_set, molecule_set, subsys, cp_subsys, oce, local_rho_set, rho_atom_set, task_list, task_list_soft, rho0_atom_set, rho0_mpole, rhoz_set, rhoz_cneo_set, ecoul_1c, rho0_s_rs, rho0_s_gs, rhoz_cneo_s_rs, rhoz_cneo_s_gs, do_kpoints, has_unit_metric, requires_mo_derivs, mo_derivs, mo_loc_history, nkind, natom, nelectron_total, nelectron_spin, efield, neighbor_list_id, linres_control, xas_env, virial, cp_ddapc_env, cp_ddapc_ewald, outer_scf_history, outer_scf_ihistory, x_data, et_coupling, dftb_potential, results, se_taper, se_store_int_env, se_nddo_mpole, se_nonbond_env, admm_env, lri_env, lri_density, exstate_env, ec_env, harris_env, dispersion_env, gcp_env, vee, rho_external, external_vxc, mask, mp2_env, bs_env, kg_env, wanniercentres, atprop, ls_scf_env, do_transport, transport_env, v_hartree_rspace, s_mstruct_changed, rho_changed, potential_changed, forces_up_to_date, mscfg_env, almo_scf_env, gradient_history, variable_history, embed_pot, spin_embed_pot, polar_env, mos_last_converged, eeq, rhs, do_rixs, tb_tblite)
Get the QUICKSTEP environment.
subroutine, public qs_env_create(qs_env, globenv)
allocates and intitializes a qs_env
subroutine, public qs_init(qs_env, para_env, root_section, globenv, cp_subsys, kpoint_env, qmmm, qmmm_env_qm, force_env_section, subsys_section, use_motion_section, silent, multip, charge)
Read the input and the database files for the setup of the QUICKSTEP environment.
Definition and initialisation of the mo data type.
Definition qs_mo_types.F:22
subroutine, public set_mo_set(mo_set, maxocc, homo, lfomo, nao, nelectron, n_el_f, nmo, eigenvalues, occupation_numbers, uniform_occupation, kts, mu, flexible_electron_count)
Set the components of a MO set data structure.
subroutine, public get_mo_set(mo_set, maxocc, homo, lfomo, nao, nelectron, n_el_f, nmo, eigenvalues, occupation_numbers, mo_coeff, mo_coeff_b, uniform_occupation, kts, mu, flexible_electron_count, cmo_coeff)
Get the components of a MO set data structure.
types that represent a quickstep subsys
subroutine, public qs_subsys_get(subsys, atomic_kinds, atomic_kind_set, particles, particle_set, local_particles, molecules, molecule_set, molecule_kinds, molecule_kind_set, local_molecules, para_env, colvar_p, shell_particles, core_particles, gci, multipoles, natom, nparticle, ncore, nshell, nkind, atprop, virial, results, cell, cell_ref, use_ref_cell, energy, force, qs_kind_set, cp_subsys, nelectron_total, nelectron_spin)
...
subroutine, public qs_subsys_set(subsys, cp_subsys, local_particles, local_molecules, cell, cell_ref, use_ref_cell, energy, force, qs_kind_set, nelectron_total, nelectron_spin)
...
parameters that control an scf iteration
type of a logger, at the moment it contains just a print level starting at which level it should be l...
represents a system: atoms, molecules, their pos,vel,...
wrapper to abstract the force evaluation of the various methods
contains the initially parsed file and the initial parallel environment
stores all the informations relevant to an mpi environment