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 Perform a molecular dynamics (MD) run using QUICKSTEP
10 : !> \par History
11 : !> - Added support for Langevin regions (2014/02/05, LT)
12 : !> \author Matthias Krack (07.11.2002)
13 : ! **************************************************************************************************
14 : MODULE md_run
15 : USE atomic_kind_list_types, ONLY: atomic_kind_list_type
16 : USE averages_types, ONLY: average_quantities_type
17 : USE barostat_types, ONLY: barostat_type,&
18 : create_barostat_type
19 : USE cell_types, ONLY: cell_type
20 : USE constraint_clv, ONLY: shake_update_colv_low
21 : USE cp_external_control, ONLY: external_control
22 : USE cp_files, ONLY: close_file,&
23 : open_file
24 : USE cp_log_handling, ONLY: cp_get_default_logger,&
25 : cp_logger_get_default_io_unit,&
26 : cp_logger_type
27 : USE cp_output_handling, ONLY: cp_add_iter_level,&
28 : cp_iterate,&
29 : cp_p_file,&
30 : cp_print_key_finished_output,&
31 : cp_print_key_should_output,&
32 : cp_print_key_unit_nr,&
33 : cp_rm_iter_level
34 : USE cp_subsys_types, ONLY: cp_subsys_get,&
35 : cp_subsys_type
36 : USE distribution_1d_types, ONLY: distribution_1d_type
37 : USE force_env_methods, ONLY: force_env_calc_energy_force
38 : USE force_env_types, ONLY: force_env_get,&
39 : force_env_type
40 : USE force_env_utils, ONLY: force_env_rattle
41 : USE free_energy_methods, ONLY: free_energy_evaluate
42 : USE free_energy_types, ONLY: fe_env_create,&
43 : free_energy_type
44 : USE global_types, ONLY: global_environment_type
45 : USE hfx_ace_methods, ONLY: hfx_ace_set_dynamic_mode
46 : USE input_constants, ONLY: &
47 : ehrenfest, langevin_ensemble, npe_f_ensemble, npe_i_ensemble, &
48 : nph_uniaxial_damped_ensemble, nph_uniaxial_ensemble, npt_f_ensemble, npt_i_ensemble, &
49 : npt_ia_ensemble, nvt_ensemble, reftraj_ensemble
50 : USE input_cp2k_check, ONLY: remove_restart_info
51 : USE input_section_types, ONLY: section_vals_get,&
52 : section_vals_get_subs_vals,&
53 : section_vals_remove_values,&
54 : section_vals_type,&
55 : section_vals_val_get,&
56 : section_vals_val_set
57 : USE kinds, ONLY: default_string_length,&
58 : dp
59 : USE machine, ONLY: m_flush,&
60 : m_walltime
61 : USE md_ener_types, ONLY: create_md_ener,&
62 : md_ener_type
63 : USE md_energies, ONLY: initialize_md_ener,&
64 : md_ener_reftraj,&
65 : md_energy,&
66 : md_write_output
67 : USE md_environment_types, ONLY: get_md_env,&
68 : md_env_create,&
69 : md_env_release,&
70 : md_environment_type,&
71 : need_per_atom_wiener_process,&
72 : set_md_env
73 : USE md_util, ONLY: md_output,&
74 : update_expected_temperature
75 : USE md_vel_utils, ONLY: angvel_control,&
76 : comvel_control,&
77 : setup_velocities,&
78 : temperature_control
79 : USE mdctrl_methods, ONLY: mdctrl_callback
80 : USE mdctrl_types, ONLY: mdctrl_type
81 : USE message_passing, ONLY: mp_para_env_type
82 : USE metadynamics, ONLY: metadyn_finalise_plumed,&
83 : metadyn_forces,&
84 : metadyn_initialise_plumed,&
85 : metadyn_integrator,&
86 : metadyn_write_colvar
87 : USE metadynamics_types, ONLY: set_meta_env
88 : USE molecule_kind_types, ONLY: molecule_kind_type
89 : USE molecule_types, ONLY: global_constraint_type
90 : USE particle_list_types, ONLY: particle_list_type
91 : USE physcon, ONLY: angstrom,&
92 : evolt,&
93 : femtoseconds
94 : USE qs_electrons_charge_mixing, ONLY: charge_mixing_maybe_rebuild,&
95 : charge_mixing_sync_endpoint_state,&
96 : compute_mixed_workfunction,&
97 : push_lambda_to_mixed_env,&
98 : qs_electrons_charge_mixing_lambda
99 : USE qs_electrons_ne_electrode, ONLY: apply_ne_core_correction
100 : USE qs_electrons_types, ONLY: qs_electrons_init,&
101 : qs_electrons_type
102 : USE qs_electrons_workfunction, ONLY: qs_electrons_compute_workfunction
103 : USE qs_environment_methods, ONLY: qs_env_time_update
104 : USE qs_environment_types, ONLY: get_qs_env,&
105 : qs_environment_type
106 : USE reftraj_types, ONLY: create_reftraj,&
107 : reftraj_type
108 : USE reftraj_util, ONLY: initialize_reftraj,&
109 : write_output_reftraj
110 : USE rt_propagation, ONLY: rt_prop_setup
111 : USE simpar_methods, ONLY: read_md_section
112 : USE simpar_types, ONLY: create_simpar_type,&
113 : release_simpar_type,&
114 : simpar_type
115 : USE thermal_region_types, ONLY: thermal_regions_type
116 : USE thermal_region_utils, ONLY: create_thermal_regions,&
117 : print_thermal_regions_langevin
118 : USE thermostat_methods, ONLY: create_thermostats
119 : USE thermostat_types, ONLY: thermostats_type
120 : USE velocity_verlet_control, ONLY: velocity_verlet
121 : USE virial_methods, ONLY: virial_evaluate
122 : USE virial_types, ONLY: virial_type
123 : USE wiener_process, ONLY: create_wiener_process,&
124 : create_wiener_process_cv
125 : #include "../base/base_uses.f90"
126 :
127 : IMPLICIT NONE
128 :
129 : PRIVATE
130 :
131 : CHARACTER(len=*), PARAMETER, PRIVATE :: moduleN = 'md_run'
132 :
133 : PUBLIC :: qs_mol_dyn
134 :
135 : CONTAINS
136 :
137 : ! **************************************************************************************************
138 : !> \brief Main driver module for Molecular Dynamics
139 : !> \param force_env ...
140 : !> \param globenv ...
141 : !> \param averages ...
142 : !> \param rm_restart_info ...
143 : !> \param hmc_e_initial ...
144 : !> \param hmc_e_final ...
145 : !> \param mdctrl ...
146 : ! **************************************************************************************************
147 3582 : SUBROUTINE qs_mol_dyn(force_env, globenv, averages, rm_restart_info, hmc_e_initial, hmc_e_final, mdctrl)
148 :
149 : TYPE(force_env_type), POINTER :: force_env
150 : TYPE(global_environment_type), POINTER :: globenv
151 : TYPE(average_quantities_type), OPTIONAL, POINTER :: averages
152 : LOGICAL, INTENT(IN), OPTIONAL :: rm_restart_info
153 : REAL(KIND=dp), OPTIONAL :: hmc_e_initial, hmc_e_final
154 : TYPE(mdctrl_type), OPTIONAL, POINTER :: mdctrl
155 :
156 : LOGICAL :: my_rm_restart_info
157 : TYPE(md_environment_type), POINTER :: md_env
158 : TYPE(mp_para_env_type), POINTER :: para_env
159 : TYPE(section_vals_type), POINTER :: md_section, motion_section
160 :
161 1791 : my_rm_restart_info = .TRUE.
162 1791 : IF (PRESENT(rm_restart_info)) my_rm_restart_info = rm_restart_info
163 1791 : NULLIFY (md_env, para_env)
164 :
165 : ! Tell ACE that this is a dynamic run: Bypass C will use full HFX
166 : ! for the entire first MD step so wavefunction propagation delivers
167 : ! a near-converged C_occ to step 1, making the ACE BUILD accurate.
168 1791 : CALL hfx_ace_set_dynamic_mode(.TRUE.)
169 :
170 1791 : para_env => force_env%para_env
171 1791 : motion_section => section_vals_get_subs_vals(force_env%root_section, "MOTION")
172 1791 : md_section => section_vals_get_subs_vals(motion_section, "MD")
173 :
174 : ! Real call to MD driver - Low Level
175 1791 : ALLOCATE (md_env)
176 1791 : CALL md_env_create(md_env, md_section, para_env, force_env=force_env)
177 1791 : CALL set_md_env(md_env, averages=averages)
178 1791 : IF (PRESENT(hmc_e_initial) .AND. PRESENT(hmc_e_final)) THEN
179 : CALL qs_mol_dyn_low(md_env, md_section, motion_section, force_env, globenv, &
180 28 : hmc_e_initial=hmc_e_initial, hmc_e_final=hmc_e_final)
181 : ELSE
182 1763 : CALL qs_mol_dyn_low(md_env, md_section, motion_section, force_env, globenv, mdctrl=mdctrl)
183 : END IF
184 1791 : CALL md_env_release(md_env)
185 1791 : DEALLOCATE (md_env)
186 :
187 : ! Clean restartable sections..
188 1791 : IF (my_rm_restart_info) CALL remove_restart_info(force_env%root_section)
189 1791 : END SUBROUTINE qs_mol_dyn
190 :
191 : ! **************************************************************************************************
192 : !> \brief Purpose: Driver routine for MD run using QUICKSTEP.
193 : !> \param md_env ...
194 : !> \param md_section ...
195 : !> \param motion_section ...
196 : !> \param force_env ...
197 : !> \param globenv ...
198 : !> \param hmc_e_initial ...
199 : !> \param hmc_e_final ...
200 : !> \param mdctrl ...
201 : !> \par History
202 : !> - Cleaning (09.2007) Teodoro Laino [tlaino] - University of Zurich
203 : !> - Added lines to print out langevin regions (2014/02/04, LT)
204 : !> \author Creation (07.11.2002,MK)
205 : ! **************************************************************************************************
206 12537 : SUBROUTINE qs_mol_dyn_low(md_env, md_section, motion_section, force_env, globenv, hmc_e_initial, hmc_e_final, mdctrl)
207 :
208 : TYPE(md_environment_type), POINTER :: md_env
209 : TYPE(section_vals_type), POINTER :: md_section, motion_section
210 : TYPE(force_env_type), POINTER :: force_env
211 : TYPE(global_environment_type), POINTER :: globenv
212 : REAL(KIND=dp), OPTIONAL :: hmc_e_initial, hmc_e_final
213 : TYPE(mdctrl_type), OPTIONAL, POINTER :: mdctrl
214 :
215 : CHARACTER(LEN=*), PARAMETER :: routineN = 'qs_mol_dyn_low'
216 :
217 : CHARACTER(LEN=80) :: md_step_line
218 : CHARACTER(LEN=default_string_length) :: my_act, my_pos
219 : INTEGER :: handle, i, istep, md_stride, &
220 : output_unit, run_type_id
221 : INTEGER, POINTER :: itimes
222 : LOGICAL :: check, ehrenfest_md, electrons_enabled, &
223 : save_mem, should_stop, &
224 : write_binary_restart_file
225 : REAL(KIND=dp) :: dummy, grand_canonical_eV, lambda_mix, &
226 : legendre_eV, target_col, &
227 : time_iter_start, time_iter_stop
228 : REAL(KIND=dp), POINTER :: constant, time, used_time
229 : TYPE(atomic_kind_list_type), POINTER :: atomic_kinds
230 : TYPE(barostat_type), POINTER :: barostat
231 : TYPE(cell_type), POINTER :: cell
232 : TYPE(cp_logger_type), POINTER :: logger
233 : TYPE(cp_subsys_type), POINTER :: subsys, subsys_i
234 : TYPE(distribution_1d_type), POINTER :: local_particles
235 : TYPE(free_energy_type), POINTER :: fe_env
236 : TYPE(md_ener_type), POINTER :: md_ener
237 : TYPE(mp_para_env_type), POINTER :: para_env
238 : TYPE(particle_list_type), POINTER :: particles
239 : TYPE(qs_electrons_type), POINTER :: electrons
240 : TYPE(reftraj_type), POINTER :: reftraj
241 : TYPE(section_vals_type), POINTER :: constraint_section, electrons_section, &
242 : force_env_section, free_energy_section, global_section, reftraj_section, subsys_section, &
243 : work_section
244 : TYPE(simpar_type), POINTER :: simpar
245 : TYPE(thermal_regions_type), POINTER :: thermal_regions
246 : TYPE(thermostats_type), POINTER :: thermostats
247 : TYPE(virial_type), POINTER :: virial
248 :
249 : ! Column 9 of the .cpcont carries whichever target the run is actually controlling:
250 : ! target_col is set per step from the Fermi-level or work-function target.
251 : ! legendre_eV is the Legendre term Phi_target*(q - N_neutral), used by the
252 : ! grand-canonical potential below. It is not added to Conserved[eV], which is
253 : ! CP2K's own md_ener%constant, so that column means the same thing as in any
254 : ! other MD run. The electronic contributions to an extended-system invariant
255 : ! can be reconstructed from the printed columns:
256 : ! p^2/2m = 0.5_dp*electrons%p**2/electrons%mass * evolt
257 : ! thermostat heat = electrons%thermostat_energy * evolt
258 : ! Legendre term = Grand_canonical_potential[eV] - Potential[eV]
259 :
260 1791 : CALL timeset(routineN, handle)
261 1791 : CPASSERT(ASSOCIATED(globenv))
262 1791 : CPASSERT(ASSOCIATED(force_env))
263 :
264 1791 : NULLIFY (particles, cell, simpar, itimes, used_time, subsys, &
265 1791 : md_ener, thermostats, barostat, reftraj, force_env_section, &
266 1791 : reftraj_section, work_section, atomic_kinds, &
267 1791 : local_particles, time, fe_env, free_energy_section, &
268 1791 : constraint_section, thermal_regions, virial, subsys_i)
269 1791 : logger => cp_get_default_logger()
270 1791 : para_env => force_env%para_env
271 1791 : output_unit = cp_logger_get_default_io_unit(logger)
272 :
273 1791 : global_section => section_vals_get_subs_vals(force_env%root_section, "GLOBAL")
274 1791 : free_energy_section => section_vals_get_subs_vals(motion_section, "FREE_ENERGY")
275 1791 : constraint_section => section_vals_get_subs_vals(motion_section, "CONSTRAINT")
276 1791 : CALL section_vals_val_get(global_section, "SAVE_MEM", l_val=save_mem)
277 :
278 1791 : CALL section_vals_val_get(global_section, "RUN_TYPE", i_val=run_type_id)
279 1791 : IF (run_type_id == ehrenfest) CALL set_md_env(md_env, ehrenfest_md=.TRUE.)
280 :
281 1791 : CALL create_simpar_type(simpar)
282 1791 : force_env_section => force_env%force_env_section
283 1791 : subsys_section => section_vals_get_subs_vals(force_env_section, "SUBSYS")
284 1791 : CALL cp_add_iter_level(logger, "MD")
285 1791 : CALL cp_iterate(logger%iter_info, iter_nr=0)
286 : ! Read MD section
287 1791 : CALL read_md_section(simpar, motion_section, md_section)
288 : ! Setup print_keys
289 : simpar%info_constraint = cp_print_key_unit_nr(logger, constraint_section, &
290 1791 : "CONSTRAINT_INFO", extension=".shakeLog", log_filename=.FALSE.)
291 : simpar%lagrange_multipliers = cp_print_key_unit_nr(logger, constraint_section, &
292 1791 : "LAGRANGE_MULTIPLIERS", extension=".LagrangeMultLog", log_filename=.FALSE.)
293 : simpar%dump_lm = BTEST(cp_print_key_should_output(logger%iter_info, constraint_section, &
294 1791 : "LAGRANGE_MULTIPLIERS"), cp_p_file)
295 :
296 : ! Create the structure for the md energies
297 7164 : ALLOCATE (md_ener)
298 1791 : CALL create_md_ener(md_ener)
299 1791 : CALL set_md_env(md_env, md_ener=md_ener)
300 1791 : NULLIFY (md_ener)
301 :
302 : ! If requested setup Thermostats
303 : CALL create_thermostats(thermostats, md_section, force_env, simpar, para_env, &
304 1791 : globenv, global_section)
305 :
306 : ! If requested setup Barostat
307 1791 : CALL create_barostat_type(barostat, md_section, force_env, simpar, globenv)
308 :
309 : ! If requested setup different thermal regions
310 1791 : CALL create_thermal_regions(thermal_regions, md_section, simpar, force_env)
311 :
312 1791 : NULLIFY (electrons_section, electrons)
313 1791 : electrons_section => section_vals_get_subs_vals(md_section, "ELECTRONS")
314 1791 : CALL section_vals_val_get(electrons_section, "_SECTION_PARAMETERS_", l_val=electrons_enabled)
315 :
316 : ! Constant-potential setup (&ELECTRONS): the potentiostat driver, or the report-only
317 : ! logger. electrons stays NULL if the section is absent.
318 : CALL init_md_electrons(md_section, electrons_section, force_env, simpar, &
319 1791 : electrons_enabled, electrons, lambda_mix)
320 :
321 : ! If doing langevin_ensemble, then print out langevin_regions information upon request
322 1791 : IF (simpar%ensemble == langevin_ensemble) THEN
323 42 : my_pos = "REWIND"
324 42 : my_act = "WRITE"
325 : CALL print_thermal_regions_langevin(thermal_regions, simpar, &
326 42 : pos=my_pos, act=my_act)
327 : END IF
328 :
329 : CALL set_md_env(md_env, thermostats=thermostats, barostat=barostat, thermal_regions=thermal_regions, &
330 1791 : electrons=electrons)
331 :
332 1791 : CALL get_md_env(md_env, ehrenfest_md=ehrenfest_md)
333 :
334 : !If requested set up the REFTRAJ run
335 1791 : IF (simpar%ensemble == reftraj_ensemble .AND. ehrenfest_md) THEN
336 0 : CPABORT("Ehrenfest MD does not support reftraj ensemble ")
337 : END IF
338 1791 : IF (simpar%ensemble == reftraj_ensemble) THEN
339 36 : reftraj_section => section_vals_get_subs_vals(md_section, "REFTRAJ")
340 36 : ALLOCATE (reftraj)
341 36 : CALL create_reftraj(reftraj, reftraj_section, para_env)
342 36 : CALL set_md_env(md_env, reftraj=reftraj)
343 : END IF
344 :
345 : CALL force_env_get(force_env, subsys=subsys, cell=cell, &
346 1791 : force_env_section=force_env_section)
347 1791 : CALL cp_subsys_get(subsys, virial=virial)
348 :
349 : ! Set V0 if needed
350 1791 : IF (simpar%ensemble == nph_uniaxial_ensemble .OR. simpar%ensemble == nph_uniaxial_damped_ensemble) THEN
351 6 : IF (simpar%v0 == 0._dp) simpar%v0 = cell%deth
352 : END IF
353 :
354 : ! Initialize velocities possibly applying constraints at the zeroth MD step
355 : CALL section_vals_val_get(motion_section, "PRINT%RESTART%SPLIT_RESTART_FILE", &
356 1791 : l_val=write_binary_restart_file)
357 : CALL setup_velocities(force_env, simpar, globenv, md_env, md_section, constraint_section, &
358 1791 : write_binary_restart_file)
359 :
360 : ! Setup Free Energy Calculation (if required)
361 1791 : CALL fe_env_create(fe_env, free_energy_section)
362 :
363 : CALL set_md_env(md_env=md_env, simpar=simpar, fe_env=fe_env, cell=cell, &
364 1791 : force_env=force_env)
365 1791 : IF (simpar%constraint) CALL initialize_moving_colvars(force_env, motion_section, simpar)
366 :
367 : ! Possibly initialize Wiener processes
368 : ![NB] Tested again within create_wiener_process. Why??
369 1791 : IF (need_per_atom_wiener_process(md_env)) CALL create_wiener_process(md_env)
370 :
371 1791 : time_iter_start = m_walltime()
372 :
373 : CALL get_md_env(md_env, force_env=force_env, itimes=itimes, constant=constant, &
374 1791 : md_ener=md_ener, t=time, used_time=used_time)
375 :
376 : ! Attach the time counter of the meta_env to the one of the MD
377 1791 : CALL set_meta_env(force_env%meta_env, time=time)
378 :
379 : ! Initialize the md_ener structure
380 1791 : CALL initialize_md_ener(md_ener, force_env, simpar)
381 :
382 : ! Check for ensembles requiring the stress tensor - takes into account the possibility for
383 : ! multiple force_evals
384 : IF ((simpar%ensemble == npt_i_ensemble) .OR. &
385 : (simpar%ensemble == npt_ia_ensemble) .OR. &
386 : (simpar%ensemble == npt_f_ensemble) .OR. &
387 : (simpar%ensemble == npe_f_ensemble) .OR. &
388 : (simpar%ensemble == npe_i_ensemble) .OR. &
389 1791 : (simpar%ensemble == nph_uniaxial_ensemble) .OR. &
390 : (simpar%ensemble == nph_uniaxial_damped_ensemble)) THEN
391 178 : check = virial%pv_availability
392 178 : IF (.NOT. check) THEN
393 : CALL cp_abort(__LOCATION__, &
394 : "Virial evaluation not requested for this run in the input file!"// &
395 : " You may consider to switch on the virial evaluation with the keyword: STRESS_TENSOR."// &
396 0 : " Be sure the method you are using can compute the virial!")
397 : END IF
398 178 : IF (ASSOCIATED(force_env%sub_force_env)) THEN
399 32 : DO i = 1, SIZE(force_env%sub_force_env)
400 32 : IF (ASSOCIATED(force_env%sub_force_env(i)%force_env)) THEN
401 12 : CALL force_env_get(force_env%sub_force_env(i)%force_env, subsys=subsys_i)
402 12 : CALL cp_subsys_get(subsys_i, virial=virial)
403 12 : check = check .AND. virial%pv_availability
404 : END IF
405 : END DO
406 : END IF
407 178 : IF (.NOT. check) THEN
408 : CALL cp_abort(__LOCATION__, &
409 : "Virial evaluation not requested for all the force_eval sections present in"// &
410 : " the input file! You have to switch on the virial evaluation with the keyword: STRESS_TENSOR"// &
411 0 : " in each force_eval section. Be sure the method you are using can compute the virial!")
412 : END IF
413 : END IF
414 :
415 : ! Computing Forces at zero MD step
416 1791 : IF (simpar%ensemble /= reftraj_ensemble) THEN
417 1755 : CALL section_vals_val_get(md_section, "STEP_START_VAL", i_val=itimes)
418 1755 : CALL section_vals_val_get(md_section, "TIME_START_VAL", r_val=time)
419 1755 : CALL section_vals_val_get(md_section, "ECONS_START_VAL", r_val=constant)
420 1755 : CALL cp_iterate(logger%iter_info, iter_nr=itimes)
421 1755 : IF (save_mem) THEN
422 2 : work_section => section_vals_get_subs_vals(subsys_section, "VELOCITY")
423 2 : CALL section_vals_remove_values(work_section)
424 2 : work_section => section_vals_get_subs_vals(subsys_section, "SHELL_VELOCITY")
425 2 : CALL section_vals_remove_values(work_section)
426 2 : work_section => section_vals_get_subs_vals(subsys_section, "CORE_VELOCITY")
427 2 : CALL section_vals_remove_values(work_section)
428 : END IF
429 :
430 1755 : IF (ehrenfest_md) THEN
431 88 : CALL rt_prop_setup(force_env)
432 88 : force_env%qs_env%rtp%dt = simpar%dt
433 : ELSE
434 : ![NB] Lets let all methods, even ones without consistent energies, succeed here.
435 : ! They'll fail in actual integrator if needed
436 : ! consistent_energies=.FALSE. by default
437 1667 : CALL force_env_calc_energy_force(force_env, calc_force=.TRUE.)
438 : END IF
439 : ! ASSOCIATED rather than electrons_enabled: report-only mode needs this
440 : ! readback too -- computing the Fermi level and work function every step
441 : ! is the entire point of it. charge_mixing_enabled is false there, so it
442 : ! takes the plain single-force_env branch below.
443 1755 : IF (ASSOCIATED(electrons)) THEN
444 4 : IF (electrons%charge_mixing_enabled) THEN
445 : CALL compute_mixed_workfunction(force_env, electrons%potential_average_axis, &
446 : electrons%potential_average_min, electrons%potential_average_max, &
447 : electrons%q, electrons%charge_mixing_span, &
448 : electrons%current_fermi_level_eV, electrons%current_workfunction, &
449 2 : lambda_in=lambda_mix)
450 : ELSE
451 : CALL qs_electrons_compute_workfunction(force_env, electrons%potential_average_axis, &
452 : electrons%potential_average_min, electrons%potential_average_max, &
453 2 : electrons%current_fermi_level_eV, electrons%current_workfunction)
454 : END IF
455 : END IF
456 :
457 1755 : IF (ASSOCIATED(force_env%qs_env)) THEN
458 620 : CALL qs_env_time_update(force_env%qs_env, time, itimes)
459 : END IF
460 : ! Warm-up engines for metadynamics
461 1755 : IF (ASSOCIATED(force_env%meta_env)) THEN
462 : ! Setup stuff for plumed if needed
463 152 : IF (force_env%meta_env%use_plumed .EQV. .TRUE.) THEN
464 2 : CALL metadyn_initialise_plumed(force_env, simpar, itimes)
465 : ! Include the bias in the first half kick and initial energy/pressure.
466 : ! This also initializes PLUMED's first-step bookkeeping on restart.
467 2 : CALL metadyn_integrator(force_env, itimes)
468 : ELSE
469 150 : IF (force_env%meta_env%langevin) THEN
470 4 : CALL create_wiener_process_cv(force_env%meta_env)
471 : END IF
472 150 : IF (force_env%meta_env%well_tempered) THEN
473 2 : force_env%meta_env%wttemperature = simpar%temp_ext
474 2 : IF (force_env%meta_env%wtgamma > EPSILON(1._dp)) THEN
475 0 : dummy = force_env%meta_env%wttemperature*(force_env%meta_env%wtgamma - 1._dp)
476 0 : IF (force_env%meta_env%delta_t > EPSILON(1._dp)) THEN
477 0 : check = ABS(force_env%meta_env%delta_t - dummy) < 1.E+3_dp*EPSILON(1._dp)
478 0 : IF (.NOT. check) THEN
479 : CALL cp_abort(__LOCATION__, &
480 : "Inconsistency between DELTA_T and WTGAMMA (both specified):"// &
481 0 : " please, verify that DELTA_T=(WTGAMMA-1)*TEMPERATURE")
482 : END IF
483 : ELSE
484 0 : force_env%meta_env%delta_t = dummy
485 : END IF
486 : ELSE
487 : force_env%meta_env%wtgamma = 1._dp &
488 2 : + force_env%meta_env%delta_t/force_env%meta_env%wttemperature
489 : END IF
490 2 : force_env%meta_env%invdt = 1._dp/force_env%meta_env%delta_t
491 : END IF
492 150 : CALL metadyn_forces(force_env)
493 150 : CALL metadyn_write_colvar(force_env)
494 : END IF
495 : END IF
496 :
497 1755 : IF (simpar%do_respa) THEN
498 : CALL force_env_calc_energy_force(force_env%sub_force_env(1)%force_env, &
499 6 : calc_force=.TRUE.)
500 : END IF
501 :
502 1755 : CALL force_env_get(force_env, subsys=subsys)
503 :
504 : CALL cp_subsys_get(subsys, atomic_kinds=atomic_kinds, local_particles=local_particles, &
505 1755 : particles=particles, virial=virial)
506 :
507 : CALL virial_evaluate(atomic_kinds%els, particles%els, local_particles, &
508 1755 : virial, force_env%para_env)
509 :
510 1755 : CALL md_energy(md_env, md_ener)
511 :
512 : ! ASSOCIATED rather than electrons_enabled, so report-only mode writes
513 : ! its step-0 line too. There target_workfunction is 0, so legendre_eV
514 : ! vanishes and grand_canonical_eV reduces to E_pot.
515 1755 : IF (ASSOCIATED(electrons)) THEN
516 4 : IF (output_unit > 0 .AND. electrons%cpcont_unit > 0) THEN
517 : ! Grand-canonical potential, Omega = E - mu*(q - N_neutral), with
518 : ! mu = -Phi_target in work-function control and mu = e_F_target in
519 : ! Fermi-level control.
520 : ! Column 9 carries the control target actually in use (the work function
521 : ! or the Fermi level); the header written at file-open names which one.
522 2 : IF (electrons%control_fermi) THEN
523 : legendre_eV = -electrons%target_fermi_level* &
524 0 : (electrons%q - electrons%neutral_electrons)
525 0 : target_col = electrons%target_fermi_level
526 : ELSE
527 : legendre_eV = electrons%target_workfunction* &
528 2 : (electrons%q - electrons%neutral_electrons)
529 2 : target_col = electrons%target_workfunction
530 : END IF
531 2 : grand_canonical_eV = md_ener%epot*evolt + legendre_eV
532 2 : WRITE (electrons%cpcont_unit, '(I10,9ES20.10E3)') itimes, time*femtoseconds, &
533 2 : md_ener%epot*evolt, md_ener%constant*evolt, md_ener%temp_part, &
534 2 : electrons%q, electrons%current_fermi_level_eV, electrons%current_workfunction, &
535 4 : target_col, grand_canonical_eV
536 2 : CALL m_flush(electrons%cpcont_unit)
537 : END IF
538 : END IF
539 :
540 1755 : IF (electrons_enabled) CALL store_electrons_restart(electrons_section, electrons)
541 1755 : CALL md_write_output(md_env) !inits the print env at itimes == 0 also writes trajectories
542 1755 : md_stride = 1
543 : ELSE
544 36 : CALL get_md_env(md_env, reftraj=reftraj)
545 36 : CALL initialize_reftraj(reftraj, reftraj_section, md_env)
546 36 : itimes = reftraj%info%first_snapshot - 1
547 36 : md_stride = reftraj%info%stride
548 36 : IF (ASSOCIATED(force_env%meta_env)) THEN
549 4 : IF (force_env%meta_env%use_plumed .EQV. .TRUE.) THEN
550 0 : CALL metadyn_initialise_plumed(force_env, simpar, itimes)
551 : END IF
552 : END IF
553 : END IF
554 :
555 : CALL cp_print_key_finished_output(simpar%info_constraint, logger, &
556 1791 : constraint_section, "CONSTRAINT_INFO")
557 : CALL cp_print_key_finished_output(simpar%lagrange_multipliers, logger, &
558 1791 : constraint_section, "LAGRANGE_MULTIPLIERS")
559 :
560 : ! if we need the initial kinetic energy for Hybrid Monte Carlo
561 1791 : IF (PRESENT(hmc_e_initial)) hmc_e_initial = md_ener%ekin
562 :
563 1791 : IF (itimes >= simpar%max_steps) CALL cp_abort(__LOCATION__, &
564 0 : "maximum step number smaller than initial step value")
565 :
566 : ! Real MD Loop
567 41419 : DO istep = 1, simpar%nsteps, md_stride
568 : ! Increase counters
569 39647 : itimes = itimes + 1
570 39647 : time = time + simpar%dt
571 : !needed when electric field fields are applied
572 39647 : IF (ASSOCIATED(force_env%qs_env)) THEN
573 3284 : CALL qs_env_time_update(force_env%qs_env, time, itimes)
574 : END IF
575 39647 : IF (ehrenfest_md) force_env%qs_env%rtp%istep = istep
576 :
577 39647 : IF (.NOT. logger%iter_info%last_iter(logger%iter_info%n_rlevel)) THEN
578 39647 : CALL cp_iterate(logger%iter_info, last=(istep == simpar%nsteps), iter_nr=itimes)
579 : ELSE
580 0 : CALL cp_iterate(logger%iter_info, last=.TRUE., iter_nr=itimes)
581 : END IF
582 :
583 39647 : IF (output_unit > 0 .AND. &
584 : BTEST(cp_print_key_should_output(logger%iter_info, md_section, &
585 : "PRINT%PROGRAM_RUN_INFO"), cp_p_file)) THEN
586 17946 : WRITE (md_step_line, FMT="(A,I12,A,I0)") "MD STEP: ", istep, " / ", simpar%nsteps
587 :
588 498754 : WRITE (UNIT=output_unit, FMT="(/,T2,A)") REPEAT("-", LEN_TRIM(md_step_line))
589 17946 : WRITE (UNIT=output_unit, FMT="(T2,A)") TRIM(md_step_line)
590 498754 : WRITE (UNIT=output_unit, FMT="(T2,A)") REPEAT("-", LEN_TRIM(md_step_line))
591 17946 : CALL m_flush(output_unit)
592 : END IF
593 :
594 : ! Open possible Shake output units
595 : simpar%info_constraint = cp_print_key_unit_nr(logger, constraint_section, "CONSTRAINT_INFO", &
596 39647 : extension=".shakeLog", log_filename=.FALSE.)
597 : simpar%lagrange_multipliers = cp_print_key_unit_nr( &
598 : logger, constraint_section, &
599 39647 : "LAGRANGE_MULTIPLIERS", extension=".LagrangeMultLog", log_filename=.FALSE.)
600 : simpar%dump_lm = BTEST(cp_print_key_should_output(logger%iter_info, constraint_section, &
601 39647 : "LAGRANGE_MULTIPLIERS"), cp_p_file)
602 :
603 : ! Update temperature for thermal regions and thermostat regions
604 39647 : CALL update_expected_temperature(md_env)
605 :
606 : ! Velocity Verlet Integrator
607 39647 : CALL velocity_verlet(md_env, globenv)
608 :
609 : ! Close Shake output if requested...
610 : CALL cp_print_key_finished_output(simpar%info_constraint, logger, &
611 39647 : constraint_section, "CONSTRAINT_INFO")
612 : CALL cp_print_key_finished_output(simpar%lagrange_multipliers, logger, &
613 39647 : constraint_section, "LAGRANGE_MULTIPLIERS")
614 :
615 : ! Free Energy calculation
616 39647 : CALL free_energy_evaluate(md_env, should_stop, free_energy_section)
617 :
618 39647 : IF (should_stop) EXIT
619 :
620 : ! Test for <PROJECT_NAME>.EXIT_MD or for WALL_TIME to exit
621 : ! Default:
622 : ! IF so we don't overwrite the restart or append to the trajectory
623 : ! because the execution could in principle stop inside the SCF where energy
624 : ! and forces are not converged.
625 : ! But:
626 : ! You can force to print the last step (for example if the method used
627 : ! to compute energy and forces is not SCF based) activating the print_key
628 : ! MOTION%MD%PRINT%FORCE_LAST.
629 39647 : CALL external_control(should_stop, "MD", globenv=globenv)
630 :
631 : !check if upper bound of total steps has been reached
632 39647 : IF (.NOT. (istep == simpar%nsteps) .AND. logger%iter_info%last_iter(logger%iter_info%n_rlevel)) should_stop = .TRUE.
633 39647 : IF (itimes >= simpar%max_steps) should_stop = .TRUE.
634 :
635 : ! call external hook e.g. from global optimization
636 39647 : IF (PRESENT(mdctrl)) THEN
637 1363 : CALL mdctrl_callback(mdctrl, md_env, should_stop)
638 : END IF
639 :
640 39647 : IF (should_stop) THEN
641 19 : CALL cp_iterate(logger%iter_info, last=.TRUE., iter_nr=itimes)
642 : !In Ehrenfest molecular dynamics the external control is only checked after a converged propagation
643 : !The restart needs to be written in order to be consistent with the mos/density matrix for the restart
644 19 : IF (run_type_id == ehrenfest) THEN
645 2 : IF (electrons_enabled) CALL store_electrons_restart(electrons_section, electrons)
646 2 : CALL md_output(md_env, md_section, force_env%root_section, .FALSE.)
647 : ELSE
648 17 : IF (electrons_enabled) CALL store_electrons_restart(electrons_section, electrons)
649 17 : CALL md_output(md_env, md_section, force_env%root_section, should_stop)
650 : END IF
651 : EXIT
652 : END IF
653 :
654 39628 : IF (simpar%ensemble /= reftraj_ensemble) THEN
655 39344 : CALL md_energy(md_env, md_ener)
656 39344 : CALL temperature_control(simpar, md_env, md_ener, force_env, logger)
657 39344 : CALL comvel_control(md_ener, force_env, md_section, logger)
658 39344 : CALL angvel_control(md_ener, force_env, md_section, logger)
659 :
660 : ! ASSOCIATED rather than electrons_enabled, so report-only mode
661 : ! writes a line every step as well.
662 39344 : IF (ASSOCIATED(electrons)) THEN
663 4 : IF (output_unit > 0 .AND. electrons%cpcont_unit > 0) THEN
664 : ! Column 9 is the control target -- see the comment at the
665 : ! step-0 write above.
666 2 : IF (electrons%control_fermi) THEN
667 : legendre_eV = -electrons%target_fermi_level* &
668 0 : (electrons%q - electrons%neutral_electrons)
669 0 : target_col = electrons%target_fermi_level
670 : ELSE
671 : legendre_eV = electrons%target_workfunction* &
672 2 : (electrons%q - electrons%neutral_electrons)
673 2 : target_col = electrons%target_workfunction
674 : END IF
675 2 : grand_canonical_eV = md_ener%epot*evolt + legendre_eV
676 2 : WRITE (electrons%cpcont_unit, '(I10,9ES20.10E3)') itimes, time*femtoseconds, &
677 2 : md_ener%epot*evolt, md_ener%constant*evolt, md_ener%temp_part, &
678 2 : electrons%q, electrons%current_fermi_level_eV, electrons%current_workfunction, &
679 4 : target_col, grand_canonical_eV
680 2 : CALL m_flush(electrons%cpcont_unit)
681 : END IF
682 : END IF
683 : ELSE
684 284 : CALL md_ener_reftraj(md_env, md_ener)
685 : END IF
686 :
687 39628 : time_iter_stop = m_walltime()
688 39628 : used_time = time_iter_stop - time_iter_start
689 39628 : time_iter_start = time_iter_stop
690 :
691 39628 : IF (electrons_enabled) CALL store_electrons_restart(electrons_section, electrons)
692 39628 : CALL md_output(md_env, md_section, force_env%root_section, should_stop)
693 120694 : IF (simpar%ensemble == reftraj_ensemble) THEN
694 284 : CALL write_output_reftraj(md_env)
695 : END IF
696 : END DO
697 :
698 : ! Guarded on ASSOCIATED: with no &ELECTRONS section at all, `electrons` is
699 : ! NULL and this dereferenced a null pointer on the ionode of every ordinary
700 : ! MD run. Also guarded on cpcont_unit > 0, since the unit keeps its -1
701 : ! default on every rank that never opened the file.
702 1791 : IF (ASSOCIATED(electrons)) THEN
703 4 : IF (output_unit > 0 .AND. electrons%cpcont_unit > 0) THEN
704 2 : CALL close_file(electrons%cpcont_unit)
705 : END IF
706 : END IF
707 :
708 : ! if we need the final kinetic energy for Hybrid Monte Carlo
709 1791 : IF (PRESENT(hmc_e_final)) hmc_e_final = md_ener%ekin
710 :
711 : ! Remove the iteration level
712 1791 : CALL cp_rm_iter_level(logger, "MD")
713 :
714 : ! Clean up PLUMED
715 1791 : IF (ASSOCIATED(force_env%meta_env)) THEN
716 156 : IF (force_env%meta_env%use_plumed .EQV. .TRUE.) THEN
717 2 : CALL metadyn_finalise_plumed()
718 : END IF
719 : END IF
720 :
721 : ! Deallocate Thermostats and Barostats
722 1791 : CALL release_simpar_type(simpar)
723 1791 : CALL timestop(handle)
724 :
725 1791 : END SUBROUTINE qs_mol_dyn_low
726 :
727 : ! **************************************************************************************************
728 : !> \brief Project initial or restarted velocities onto the upcoming target rate.
729 : !> \param force_env ...
730 : !> \param motion_section ...
731 : !> \param simpar ...
732 : ! **************************************************************************************************
733 318 : SUBROUTINE initialize_moving_colvars(force_env, motion_section, simpar)
734 : TYPE(force_env_type), POINTER :: force_env
735 : TYPE(section_vals_type), POINTER :: motion_section
736 : TYPE(simpar_type), POINTER :: simpar
737 :
738 : INTEGER :: i
739 : LOGICAL :: moving
740 : REAL(KIND=dp) :: dt
741 : TYPE(cp_subsys_type), POINTER :: subsys
742 : TYPE(global_constraint_type), POINTER :: gci
743 318 : TYPE(molecule_kind_type), POINTER :: kinds(:)
744 :
745 318 : CALL force_env_get(force_env, subsys=subsys)
746 318 : CALL cp_subsys_get(subsys, molecule_kind_set=kinds, gci=gci)
747 318 : dt = simpar%dt
748 318 : IF (simpar%do_respa) dt = dt/simpar%n_time_steps
749 318 : moving = .FALSE.
750 1168 : DO i = 1, SIZE(kinds)
751 850 : IF (.NOT. ASSOCIATED(kinds(i)%colv_list)) CYCLE
752 456 : CALL shake_update_colv_low(kinds(i)%colv_list, dt, motion_section, initialize=.TRUE.)
753 1534 : moving = moving .OR. ANY(kinds(i)%colv_list%expected_value_growth_speed /= 0.0_dp)
754 : END DO
755 318 : IF (ASSOCIATED(gci%colv_list)) THEN
756 38 : CALL shake_update_colv_low(gci%colv_list, dt, motion_section, initialize=.TRUE.)
757 92 : moving = moving .OR. ANY(gci%colv_list%expected_value_growth_speed /= 0.0_dp)
758 : END IF
759 318 : gci%joint_colvar_checks = moving
760 318 : IF (moving) CALL force_env_rattle(force_env, dt=dt, shake_tol=simpar%shake_tol, reset=.TRUE.)
761 318 : END SUBROUTINE initialize_moving_colvars
762 :
763 : ! **************************************************************************************************
764 : !> \brief Reads the &ELECTRONS section and sets up the electronic driver for the MD run.
765 : !> "&ELECTRONS T": constant-potential driver (potentiostat, optional charge mixing) and
766 : !> .cpcont log. "&ELECTRONS 0": report-only, an ordinary MD run that also logs the Fermi
767 : !> level and work function. Absent section: electrons is left NULL.
768 : !> \param md_section ...
769 : !> \param electrons_section ...
770 : !> \param force_env ...
771 : !> \param simpar ...
772 : !> \param electrons_enabled value of _SECTION_PARAMETERS_
773 : !> \param electrons the electronic state, NULL if no electronic driver is active
774 : !> \param lambda_mix initial charge-mixing weight, 0 if charge mixing is off
775 : ! **************************************************************************************************
776 3582 : SUBROUTINE init_md_electrons(md_section, electrons_section, force_env, simpar, &
777 : electrons_enabled, electrons, lambda_mix)
778 : TYPE(section_vals_type), POINTER :: md_section, electrons_section
779 : TYPE(force_env_type), POINTER :: force_env
780 : TYPE(simpar_type), POINTER :: simpar
781 : LOGICAL, INTENT(IN) :: electrons_enabled
782 : TYPE(qs_electrons_type), POINTER :: electrons
783 : REAL(KIND=dp), INTENT(OUT) :: lambda_mix
784 :
785 : CHARACTER(LEN=*), PARAMETER :: routineN = 'init_md_electrons'
786 :
787 : CHARACTER(LEN=23) :: cpcont_target_label
788 : CHARACTER(LEN=6) :: cpcont_pos
789 : INTEGER :: charge_span, cpcont_step0, handle, iw, &
790 : nelec_report, output_unit, wf_axis
791 : LOGICAL :: charge_mixing, cm_inplace, &
792 : control_fermi, electrons_explicit, &
793 : electrons_report, lambda_is_fixed
794 : REAL(KIND=dp) :: cur_ef, cur_wf, lambda_fix, mass_electrons, neutral_e, p_init, pot_energy, &
795 : q_init, target_ef, target_wf, tau_pot, temp_pot, wf_max_a, wf_min_a
796 1791 : REAL(KIND=dp), DIMENSION(:), POINTER :: wf_region
797 : TYPE(cp_logger_type), POINTER :: logger
798 : TYPE(qs_environment_type), POINTER :: qs_env_report
799 :
800 1791 : CALL timeset(routineN, handle)
801 1791 : lambda_mix = 0.0_dp
802 :
803 : ! "&ELECTRONS 0" -- section present with a false parameter -- selects
804 : ! report-only mode: the .cpcont file is written for an ordinary MD run,
805 : ! with the Fermi level and work function computed and logged every step,
806 : ! but q is never propagated and no potentiostat, charge mixing or core
807 : ! correction is applied. An ABSENT section must keep meaning "do nothing
808 : ! at all", and both cases leave _SECTION_PARAMETERS_ at .FALSE., so the
809 : ! two are separated by asking whether the section was written explicitly.
810 : ! (CP2K's logical parser accepts 0/1 as well as F/T, so "&ELECTRONS 0"
811 : ! and "&ELECTRONS F" are the same thing.)
812 1791 : CALL section_vals_get(electrons_section, explicit=electrons_explicit)
813 1791 : electrons_report = electrons_explicit .AND. (.NOT. electrons_enabled)
814 :
815 1791 : NULLIFY (electrons, qs_env_report, wf_region)
816 1791 : IF (electrons_enabled) THEN
817 : ! The constant-potential hooks (electronic kick/drift, endpoint rebuild,
818 : ! lambda push, potentiostat) live inside the per-ensemble integrator
819 : ! routines in integrator.F, and are currently implemented only in nvt()
820 : ! and langevin(). Under any other ensemble the atoms would propagate
821 : ! normally while q(t) stayed frozen at Q_INIT and the mixing weight was
822 : ! never updated -- the run would finish and write entirely plausible
823 : ! output that means nothing. Refuse rather than fail silently.
824 2 : IF (simpar%ensemble /= nvt_ensemble .AND. &
825 : simpar%ensemble /= langevin_ensemble) THEN
826 0 : CPABORT("&ELECTRONS requires ENSEMBLE NVT or LANGEVIN")
827 : END IF
828 :
829 2 : CALL section_vals_val_get(electrons_section, "POTENTIAL_AVERAGE_AXIS", i_val=wf_axis)
830 : ! r_vals returns a POINTER INTO THE INPUT TREE, not a copy. The previous
831 : ! line here was
832 : !
833 : ! wf_region = wf_region*angstrom
834 : !
835 : ! which converted the stored value from bohr to angstrom IN PLACE,
836 : ! corrupting the input tree. On a fresh run that was invisible: the
837 : ! converted numbers were what the work-function routine wanted, and
838 : ! nothing read the section again. But CP2K's restart writer does read it,
839 : ! and converts bohr -> angstrom a second time on output, so every restart
840 : ! divided the averaging region by 1.8897 (bohr per angstrom) and the
841 : ! error COMPOUNDED with each continuation. A 12.5-15.0 angstrom vacuum
842 : ! window became 6.61-7.94 after one restart -- inside the slab rather
843 : ! than in the vacuum, making the work function, dPhi/dq and hence the
844 : ! whole potentiostat meaningless while still looking plausible.
845 : !
846 : ! Convert into local scalars and leave the input tree alone.
847 2 : CALL section_vals_val_get(electrons_section, "POTENTIAL_AVERAGE_REGION", r_vals=wf_region)
848 2 : wf_min_a = wf_region(1)*angstrom
849 2 : wf_max_a = wf_region(2)*angstrom
850 2 : CALL section_vals_val_get(electrons_section, "NEUTRAL_ELECTRONS", r_val=neutral_e)
851 2 : CALL section_vals_val_get(electrons_section, "Q_INIT", r_val=q_init)
852 2 : CALL section_vals_val_get(electrons_section, "TARGET_WORKFUNCTION", r_val=target_wf)
853 : ! TARGET_WORKFUNCTION carries unit_str="eV", so the input machinery
854 : ! returns it in atomic units (Hartree) whether the deck wrote a bare
855 : ! number, [eV] or [hartree]. The potentiostat works in eV throughout --
856 : ! qs_electrons_force forms (current_workfunction - target_workfunction)
857 : ! in eV before dividing by HARTREE_TO_EV, and the .cpcont writes both
858 : ! columns as eV -- so convert back here, exactly as
859 : ! POTENTIAL_AVERAGE_REGION above is converted with `angstrom'.
860 2 : target_wf = target_wf*evolt
861 : ! Fermi-level control is selected simply by setting TARGET_FERMI_LEVEL;
862 : ! its default is HUGE, the sentinel for "not given".
863 2 : CALL section_vals_val_get(electrons_section, "CHARGE_MIXING_INPLACE", l_val=cm_inplace)
864 2 : CALL section_vals_val_get(electrons_section, "LAMBDA", r_val=lambda_fix)
865 2 : lambda_is_fixed = (lambda_fix < 0.5_dp*HUGE(0.0_dp))
866 2 : IF (.NOT. lambda_is_fixed) lambda_fix = 0.0_dp
867 2 : IF (lambda_is_fixed) THEN
868 0 : CPWARN("LAMBDA is fixed: q(t) frozen, potentiostat inactive, no endpoint rebuilds")
869 : END IF
870 2 : CALL section_vals_val_get(electrons_section, "TARGET_FERMI_LEVEL", r_val=target_ef)
871 2 : control_fermi = (target_ef < 0.5_dp*HUGE(0.0_dp))
872 2 : IF (control_fermi) THEN
873 : ! TARGET_FERMI_LEVEL takes PRECEDENCE rather than being mutually
874 : ! exclusive. It cannot be an abort: TARGET_WORKFUNCTION has a
875 : ! non-zero default (5.0 eV), so "was it set?" is unanswerable from
876 : ! its value alone, and an exclusivity check would fire on every
877 : ! Fermi-mode run. Precedence also means a restart file written in
878 : ! work-function mode -- which necessarily carries an explicit
879 : ! TARGET_WORKFUNCTION -- can be switched to Fermi control by adding
880 : ! one line, without having to delete the old target by hand.
881 0 : IF (ABS(target_wf - 5.0_dp) > 1.0E-12_dp) THEN
882 0 : CPWARN("TARGET_FERMI_LEVEL is set: TARGET_WORKFUNCTION is ignored")
883 : END IF
884 : ELSE
885 2 : target_ef = 0.0_dp
886 : END IF
887 2 : CALL section_vals_val_get(electrons_section, "MASS", r_val=mass_electrons)
888 2 : CALL section_vals_val_get(electrons_section, "TAU_POTENTIOSTAT", r_val=tau_pot)
889 2 : CALL section_vals_val_get(electrons_section, "TEMP_POTENTIOSTAT", r_val=temp_pot)
890 2 : CALL section_vals_val_get(electrons_section, "CHARGE_MIXING", l_val=charge_mixing)
891 2 : charge_span = 1
892 2 : IF (charge_mixing) CALL section_vals_val_get(electrons_section, "CHARGE_MIXING_SPAN", i_val=charge_span)
893 : ! The mixing code clamps S with MAX(1, S), but a zero or negative span is
894 : ! an input error, not something to correct silently.
895 2 : IF (charge_span < 1) CPABORT("CHARGE_MIXING_SPAN must be a positive integer")
896 : ! Restartable state. On a fresh run these carry their defaults (p = 0,
897 : ! no accumulated potentiostat heat) so behaviour is unchanged; on a
898 : ! restart they carry the live values written by store_electrons_restart
899 : ! below, and the electronic dynamics continues rather than restarting.
900 2 : CALL section_vals_val_get(electrons_section, "P_INIT", r_val=p_init)
901 2 : CALL section_vals_val_get(electrons_section, "POTENTIOSTAT_ENERGY", r_val=pot_energy)
902 2 : CALL section_vals_val_get(electrons_section, "CURRENT_FERMI_LEVEL", r_val=cur_ef)
903 2 : CALL section_vals_val_get(electrons_section, "CURRENT_WORKFUNCTION", r_val=cur_wf)
904 :
905 2 : IF (charge_mixing) THEN
906 : CALL qs_electrons_init(electrons, q_init=q_init, p_init=p_init, mass=mass_electrons, &
907 : neutral_electrons=neutral_e, target_workfunction=target_wf, &
908 : tau_potentiostat=tau_pot, temp_potentiostat=temp_pot, &
909 : potential_average_axis=wf_axis, potential_average_min=wf_min_a, &
910 : potential_average_max=wf_max_a, charge_mixing_span=charge_span, &
911 : target_fermi_level=target_ef, control_fermi=control_fermi, &
912 : lambda_fixed=lambda_fix, lambda_is_fixed=lambda_is_fixed, &
913 2 : charge_mixing_inplace=cm_inplace)
914 : ELSE
915 : CALL qs_electrons_init(electrons, q_init=q_init, p_init=p_init, mass=mass_electrons, &
916 : neutral_electrons=neutral_e, target_workfunction=target_wf, &
917 : tau_potentiostat=tau_pot, temp_potentiostat=temp_pot, &
918 : potential_average_axis=wf_axis, potential_average_min=wf_min_a, &
919 : potential_average_max=wf_max_a, &
920 : target_fermi_level=target_ef, control_fermi=control_fermi, &
921 : lambda_fixed=lambda_fix, lambda_is_fixed=lambda_is_fixed, &
922 0 : charge_mixing_inplace=cm_inplace)
923 : END IF
924 : ! qs_electrons_init zeroes these; restore them after it.
925 : !
926 : ! p and thermostat_energy are load-bearing: without them a restart
927 : ! resumes with the electronic variable at rest and its potentiostat
928 : ! heat accounting reset to zero, mid-trajectory.
929 : !
930 : ! current_fermi_level_eV and current_workfunction are NOT load-bearing:
931 : ! the initial force evaluation below (line ~523) recomputes both before
932 : ! the first electronic kick, on restarts as well as fresh runs. They are
933 : ! restored only so the step-0 .cpcont line of a continued run reports the
934 : ! values the previous run ended on rather than zeros.
935 2 : electrons%p = p_init
936 2 : electrons%thermostat_energy = pot_energy
937 2 : electrons%current_fermi_level_eV = cur_ef
938 2 : electrons%current_workfunction = cur_wf
939 :
940 2 : IF (charge_mixing) THEN
941 : ! Normalise the endpoints BEFORE the first force evaluation, so that
942 : ! slot 1 holds N_lo and slot 2 holds N_hi whatever order the input's
943 : ! two FORCE_EVAL blocks were written in, and whether or not their
944 : ! CHARGE values bracket Q_INIT. Without this the step-0 energy,
945 : ! Fermi level and work function are computed from endpoints that need
946 : ! not bracket q -- the "startup endpoint mismatch" -- and if the two
947 : ! blocks happen to be in the wrong order the mixing is inverted for
948 : ! the whole run. Reading the counts back off the sub_force_envs
949 : ! first means the common case -- an input that already agrees with
950 : ! Q_INIT -- costs nothing at all, while a disagreeing or misordered
951 : ! one is corrected before it can affect a single step.
952 2 : CALL charge_mixing_sync_endpoint_state(force_env, electrons)
953 2 : CALL charge_mixing_maybe_rebuild(force_env, electrons)
954 2 : CALL qs_electrons_charge_mixing_lambda(electrons, lambda_mix)
955 2 : CALL push_lambda_to_mixed_env(force_env, lambda_mix)
956 : ! Report the bracket explicitly. The whole scheme rests on slot 1
957 : ! being the LOW endpoint, and until now nothing in the output let
958 : ! you check that; a misordered input was invisible.
959 2 : iw = cp_logger_get_default_io_unit()
960 2 : IF (iw > 0) THEN
961 1 : WRITE (iw, '(/,T2,A)') REPEAT("-", 77)
962 1 : WRITE (iw, '(T2,A)') "CHARGE MIXING| endpoint bracket at start of MD"
963 1 : WRITE (iw, '(T2,A,T50,I20)') "CHARGE MIXING| FORCE_EVAL 1, N_lo [electrons]", &
964 2 : electrons%charge_mixing_current_n_lo
965 1 : WRITE (iw, '(T2,A,T50,I20)') "CHARGE MIXING| FORCE_EVAL 2, N_hi [electrons]", &
966 2 : electrons%charge_mixing_current_n_hi
967 1 : WRITE (iw, '(T2,A,T50,F20.10)') "CHARGE MIXING| q [electrons]", electrons%q
968 1 : WRITE (iw, '(T2,A,T50,F20.10)') "CHARGE MIXING| lambda (weight on N_hi)", lambda_mix
969 1 : WRITE (iw, '(T2,A)') REPEAT("-", 77)
970 : END IF
971 : ELSE
972 0 : CALL apply_ne_core_correction(force_env, electrons%q, electrons%neutral_electrons)
973 : END IF
974 :
975 2 : logger => cp_get_default_logger()
976 2 : output_unit = cp_logger_get_default_io_unit()
977 2 : IF (output_unit > 0) THEN
978 : ! ALWAYS append, never truncate. This deliberately does not mirror
979 : ! CP2K's own .ener file, which rewinds on a fresh run.
980 : !
981 : ! The previous version keyed the choice on STEP_START_VAL > 0, which
982 : ! is set only when a restart file supplies it. Any other route back
983 : ! into a directory -- resuming from copied coordinates, a restart
984 : ! that did not carry STEP_START_VAL, or simply relaunching after a
985 : ! job was killed mid-run -- left it at 0 and silently overwrote the
986 : ! whole preceding trajectory. The asymmetry matters: an overwritten
987 : ! trajectory is unrecoverable, whereas a file that accumulates across
988 : ! runs costs only a little disk and is trivially split on the header
989 : ! lines. STEP_START_VAL is still read, but now only to label the
990 : ! boundary in the header below.
991 1 : CALL section_vals_val_get(md_section, "STEP_START_VAL", i_val=cpcont_step0)
992 1 : cpcont_pos = "APPEND"
993 : CALL open_file(file_name=TRIM(logger%iter_info%project_name)//"-1.cpcont", &
994 : file_status="UNKNOWN", file_form="FORMATTED", file_action="WRITE", &
995 1 : file_position=TRIM(cpcont_pos), unit_number=electrons%cpcont_unit)
996 : ! Column meanings:
997 : !
998 : ! Conserved[eV] -- CP2K's own md_ener%constant: the atomic degrees of
999 : ! freedom plus, under NVT, the atomic thermostat. It does not include
1000 : ! the electronic kinetic energy, the potentiostat heat or the Legendre
1001 : ! term, so that it keeps its usual meaning in every CP2K MD run.
1002 : !
1003 : ! Grand_canonical_potential[eV] -- Omega = E_pot - mu*(q - N_neutral).
1004 : ! In work-function control mu = -Phi_target, so
1005 : ! Omega = E_pot + Phi_target*(q - N_neutral).
1006 : ! Header on every run, fresh or continued. Since the file is now
1007 : ! always opened APPEND, this lands at the start of each run's block
1008 : ! and marks where that run began -- the boundary is explicit rather
1009 : ! than inferred. It costs nothing downstream: gnuplot skips '#' lines
1010 : ! by default, and the awk idiom used throughout this project already
1011 : ! filters them with !/^#/.
1012 : ! Column 9 holds whichever target this run controls, so the header
1013 : ! names that one. Under Fermi control TARGET_WORKFUNCTION is ignored
1014 : ! everywhere else, and labelling the column after it made a
1015 : ! Fermi-mode file look as though a 5.0 eV work-function target were
1016 : ! in force.
1017 1 : IF (control_fermi) THEN
1018 0 : cpcont_target_label = "Fermi_target[eV]"
1019 : ELSE
1020 1 : cpcont_target_label = "Workfunction_target[eV]"
1021 : END IF
1022 : WRITE (electrons%cpcont_unit, '(A,I0)') &
1023 1 : "# --- run opened here, STEP_START_VAL = ", cpcont_step0
1024 : WRITE (electrons%cpcont_unit, '(A)') "# Step Time[fs] Potential[eV] Conserved[eV] "// &
1025 : "Temperature[K] Electronic_charge Fermi_level[eV] Workfunction[eV] "// &
1026 1 : TRIM(cpcont_target_label)//" Grand_canonical_potential[eV]"
1027 1 : CALL m_flush(electrons%cpcont_unit)
1028 : END IF
1029 : END IF
1030 :
1031 : ! ------------------------------------------------------------------
1032 : ! Report-only mode: "&ELECTRONS 0"
1033 : ! ------------------------------------------------------------------
1034 1791 : IF (electrons_report) THEN
1035 : ! Plain single-FORCE_EVAL only. A MIXED force_env has no single qs_env
1036 : ! to read the electron count or the Hartree potential from, and routing
1037 : ! through compute_mixed_workfunction would drag in exactly the
1038 : ! charge-mixing machinery this mode exists to stay clear of.
1039 2 : IF (ASSOCIATED(force_env%sub_force_env)) THEN
1040 0 : CPABORT("&ELECTRONS 0 (report-only) requires a plain FORCE_EVAL, not METHOD MIXED")
1041 : END IF
1042 :
1043 : ! Unlike the full mode this works under any ensemble: q is never
1044 : ! propagated, so there is no integrator hook that has to exist.
1045 2 : CALL section_vals_val_get(electrons_section, "POTENTIAL_AVERAGE_AXIS", i_val=wf_axis)
1046 2 : CALL section_vals_val_get(electrons_section, "POTENTIAL_AVERAGE_REGION", r_vals=wf_region)
1047 2 : wf_min_a = wf_region(1)*angstrom
1048 2 : wf_max_a = wf_region(2)*angstrom
1049 :
1050 : ! Electronic_charge is the system's real electron count, constant for
1051 : ! the whole run. Read it from the environment rather than from
1052 : ! NEUTRAL_ELECTRONS so the column is right whatever DFT%CHARGE was set
1053 : ! to, and so the keyword is not silently required in this mode.
1054 2 : CALL force_env_get(force_env, qs_env=qs_env_report)
1055 2 : CALL get_qs_env(qs_env_report, nelectron_total=nelec_report)
1056 :
1057 : ! target_workfunction = 0 does double duty: the Workfunction_target
1058 : ! column reads 0 throughout, as intended, and the Legendre term
1059 : ! Phi_target*(q - N) vanishes so Grand_canonical_potential reduces to
1060 : ! E_pot. Every column therefore keeps the same definition it has in the
1061 : ! full mode -- the two file types stay directly comparable, and the same
1062 : ! plotting scripts work on both. mass/tau/temp are never used because
1063 : ! report_only gates every kick, drift and thermostat call in
1064 : ! integrator.F; they are given harmless non-zero values only so that
1065 : ! nothing downstream can divide by zero.
1066 : CALL qs_electrons_init(electrons, q_init=REAL(nelec_report, KIND=dp), p_init=0.0_dp, &
1067 : mass=1.0_dp, neutral_electrons=REAL(nelec_report, KIND=dp), &
1068 : target_workfunction=0.0_dp, tau_potentiostat=1.0_dp, &
1069 : temp_potentiostat=0.0_dp, &
1070 : potential_average_axis=wf_axis, potential_average_min=wf_min_a, &
1071 2 : potential_average_max=wf_max_a, report_only=.TRUE.)
1072 :
1073 2 : logger => cp_get_default_logger()
1074 2 : output_unit = cp_logger_get_default_io_unit()
1075 2 : IF (output_unit > 0) THEN
1076 1 : CALL section_vals_val_get(md_section, "STEP_START_VAL", i_val=cpcont_step0)
1077 : CALL open_file(file_name=TRIM(logger%iter_info%project_name)//"-1.cpcont", &
1078 : file_status="UNKNOWN", file_form="FORMATTED", file_action="WRITE", &
1079 1 : file_position="APPEND", unit_number=electrons%cpcont_unit)
1080 : ! Report-only controls nothing, so column 9 has no target to name.
1081 : ! It is written as 0 (target_workfunction is 0 in this mode and
1082 : ! control_fermi is false) and the header says so plainly rather than
1083 : ! borrowing a label that would imply a target is in force.
1084 1 : cpcont_target_label = "Nothing_important"
1085 : WRITE (electrons%cpcont_unit, '(A,I0,A)') &
1086 1 : "# --- run opened here, STEP_START_VAL = ", cpcont_step0, &
1087 2 : " (report-only: no potentiostat, q fixed at the system electron count)"
1088 : WRITE (electrons%cpcont_unit, '(A)') "# Step Time[fs] Potential[eV] Conserved[eV] "// &
1089 : "Temperature[K] Electronic_charge Fermi_level[eV] Workfunction[eV] "// &
1090 1 : TRIM(cpcont_target_label)//" Grand_canonical_potential[eV]"
1091 1 : CALL m_flush(electrons%cpcont_unit)
1092 : END IF
1093 : END IF
1094 :
1095 1791 : CALL timestop(handle)
1096 1791 : END SUBROUTINE init_md_electrons
1097 :
1098 : ! **************************************************************************************************
1099 : !> \brief Write the live state of the electronic extended variable back into the
1100 : !> &ELECTRONS input section, so that CP2K's ordinary restart dump carries
1101 : !> it and a continued run resumes the electronic dynamics instead of
1102 : !> silently resetting q to Q_INIT with p = 0 mid-trajectory.
1103 : !>
1104 : !> Called immediately before every md_output / md_write_output, which are
1105 : !> the only places a restart file is produced. Deliberately NOT guarded by
1106 : !> output_unit > 0: section_vals_val_set mutates the replicated input tree,
1107 : !> so every rank must apply the same update or the trees diverge.
1108 : !>
1109 : !> Q_INIT doubles as the restart slot for q, in the same way CP2K reuses
1110 : !> the input coordinates as the restart slot for the positions. The units
1111 : !> match the getters in qs_mol_dyn_low: q and p in atomic units,
1112 : !> thermostat_energy in Hartree, Fermi level and work function in eV.
1113 : !> \param electrons_section the &MOTION%MD%ELECTRONS section
1114 : !> \param electrons the live electronic state
1115 : ! **************************************************************************************************
1116 4 : SUBROUTINE store_electrons_restart(electrons_section, electrons)
1117 : TYPE(section_vals_type), POINTER :: electrons_section
1118 : TYPE(qs_electrons_type), POINTER :: electrons
1119 :
1120 4 : IF (.NOT. ASSOCIATED(electrons_section)) RETURN
1121 4 : IF (.NOT. ASSOCIATED(electrons)) RETURN
1122 :
1123 4 : CALL section_vals_val_set(electrons_section, "Q_INIT", r_val=electrons%q)
1124 4 : CALL section_vals_val_set(electrons_section, "P_INIT", r_val=electrons%p)
1125 : CALL section_vals_val_set(electrons_section, "POTENTIOSTAT_ENERGY", &
1126 4 : r_val=electrons%thermostat_energy)
1127 : CALL section_vals_val_set(electrons_section, "CURRENT_FERMI_LEVEL", &
1128 4 : r_val=electrons%current_fermi_level_eV)
1129 : CALL section_vals_val_set(electrons_section, "CURRENT_WORKFUNCTION", &
1130 4 : r_val=electrons%current_workfunction)
1131 :
1132 : END SUBROUTINE store_electrons_restart
1133 :
1134 : END MODULE md_run
|