Debian Codegraph @

src/mbd.F90

raw
1 ! This Source Code Form is subject to the terms of the Mozilla Public
2 ! License, v. 2.0. If a copy of the MPL was not distributed with this
3 ! file, You can obtain one at http://mozilla.org/MPL/2.0/.
4 module mbd
5 !! High-level Fortran API.
6
7 use mbd_constants
8 use mbd_defaults
9 use mbd_version
10 use mbd_damping, only: damping_t
11 use mbd_formulas, only: scale_with_ratio
12 use mbd_geom, only: geom_t
13 use mbd_gradients, only: grad_request_t, grad_t
14 use mbd_methods, only: get_mbd_energy, get_mbd_scs_energy
15 use mbd_ts, only: get_ts_energy
16 use mbd_utils, only: result_t, exception_t, printer_i
17 use mbd_vdw_param, only: ts_vdw_params, tssurf_vdw_params, species_index
18
19 implicit none
20
21 private
22
23 public :: MBD_VERSION_MAJOR, MBD_VERSION_MINOR, MBD_VERSION_PATCH, MBD_VERSION_SUFFIX
24 public :: MBD_EXC_NEG_EIGVALS, MBD_EXC_NEG_POL, MBD_EXC_LINALG, MBD_EXC_UNIMPL, &
25 MBD_EXC_DAMPING, MBD_EXC_INPUT
26
27 type, public :: mbd_input_t
28 !! Contains user input to an MBD calculation.
29 character(len=30) :: method = 'mbd-rsscs'
30 !! VdW method to use to calculate energy and gradients.
31 !!
32 !! - `mbd-rsscs`: The MBD@rsSCS method.
33 !! - `mbd-nl`: The MBD-NL method.
34 !! - `ts`: The TS method.
35 !! - `mbd`: Generic MBD method (without any screening).
36 integer :: comm = -1
37 !! MPI communicator, as a plain integer handle.
38 !!
39 !! Only used when compiled with MPI. Leave as is to use the
40 !! MPI_COMM_WORLD communicator. The integer handle is accepted
41 !! regardless of whether the library was built against the
42 !! `mpi_f08` module; callers using `mpi_f08` should pass the
43 !! integer handle of their communicator (e.g. `mycomm%mpi_val`).
44 integer :: max_atoms_per_block = MAX_ATOMS_PER_BLOCK
45 !! Number of atoms per block in a BLACS grid.
46 integer :: log_level = MBD_LOG_LVL_INFO
47 !! Level of printing
48 procedure(printer_i), nopass, pointer :: printer => null()
49 !! If assigned, will be used for logging
50 logical :: calculate_forces = .true.
51 !! Whether to calculate forces.
52 logical :: calculate_vdw_params_gradients = .false.
53 !! Whether to calculate gradients of energy w.r.t. vdW parameters
54 logical :: calculate_spectrum = .false.
55 !! Whether to keep MBD eigenvalues.
56 logical :: do_rpa = .false.
57 !! Whether to evalulate the MBD energy as an RPA integral over frequency.
58 logical :: rpa_orders = .false.
59 !! Whether to calculate individual RPA orders
60 logical :: rpa_rescale_eigs = .false.
61 !! Whether to rescale RPA eigenvalues as in 10.1021/acs.jctc.6b00925.
62 integer :: n_omega_grid = N_FREQUENCY_GRID
63 !! Number of imaginary frequency grid points.
64 real(dp) :: k_grid_shift = K_GRID_SHIFT
65 !! Off-\(\Gamma\) shift of the \(k\)-point grid in units of
66 !! inter-\(k\)-point distance.
67 logical :: zero_negative_eigvals = .false.
68 !! Whether to zero out negative eigenvalues.
69 character(len=20) :: xc = ''
70 !! XC functional for automatic setting of damping parameters.
71 real(dp) :: ts_d = TS_DAMPING_D
72 !! TS damping parameter \(d\).
73 real(dp) :: ts_sr = -1
74 !! Custom TS damping parameter \(s_R\).
75 !!
76 !! Leave as is to use a value based on the XC functional.
77 real(dp) :: mbd_a = MBD_DAMPING_A
78 !! MBD damping parameter \(a\).
79 real(dp) :: mbd_beta = -1
80 !! Custom MBD damping parameter \(\beta\).
81 !!
82 !! Leave as is to use a value based on the XC functional.
83 character(len=10) :: vdw_params_kind = 'ts'
84 !! Which free-atom reference vdW parameters to use for scaling.
85 !!
86 !! - `ts`: Values from original TS method.
87 !! - `tssurf`: Values from the TS\(^\text{surf}\) approach.
88 character(len=3), allocatable :: atom_types(:)
89 !! (\(N\)) Atom types used for picking free-atom reference values.
90 real(dp), allocatable :: free_values(:, :)
91 !! (\(N\times3\), a.u.) Custom free-atom vdW paramters to use for
92 !! scaling.
93 !!
94 !! Columns contain static polarizabilities, C6 coefficients, and vdW
95 !! radii.
96 real(dp), allocatable :: coords(:, :)
97 !! (\(3\times N\), a.u.) Atomic coordinates.
98 real(dp), allocatable :: lattice_vectors(:, :)
99 !! (\(3\times 3\), a.u.) Lattice vectors in columns, unallocated if not
100 !! periodic.
101 integer :: k_grid(3) = [-1, -1, -1]
102 !! Number of \(k\)-points along reciprocal axes.
103 character(len=10) :: parallel_mode = 'auto'
104 !! Parallelization scheme.
105 !!
106 !! - `auto`: Pick based on system system size and number of \(k\)-points.
107 !! - `kpoints`: Parallelize over \(k\)-points.
108 !! - `atoms`: Parallelize over atom pairs.
109 end type
110
111 type, public :: mbd_calc_t
112 !! Represents an MBD calculation.
113 private
114 type(geom_t) :: geom
115 type(damping_t) :: damp
116 real(dp), allocatable :: alpha_0(:)
117 real(dp), allocatable :: C6(:)
118 character(len=30) :: method
119 type(result_t) :: results
120 type(grad_t) :: dalpha_0, dC6, dr_vdw
121 logical :: calculate_gradients
122 logical :: calculate_vdw_params_gradients
123 real(dp), allocatable :: free_values(:, :)
124 character(len=30) :: vdw_params_update
125 contains
126 procedure :: init => mbd_calc_init
127 procedure :: destroy => mbd_calc_destroy
128 procedure :: switch_forces => mbd_calc_switch_forces
129 procedure :: update_coords => mbd_calc_update_coords
130 procedure :: update_lattice_vectors => mbd_calc_update_lattice_vectors
131 procedure :: update_vdw_params_custom => mbd_calc_update_vdw_params_custom
132 procedure :: update_vdw_params_from_ratios => mbd_calc_update_vdw_params_from_ratios
133 procedure :: update_vdw_params_nl => mbd_calc_update_vdw_params_nl
134 procedure :: evaluate_vdw_method => mbd_calc_evaluate_vdw_method
135 procedure :: get_gradients => mbd_calc_get_gradients
136 procedure :: get_vdw_params_ratios_gradients => mbd_calc_get_vdw_params_ratios_gradients
137 procedure :: get_lattice_derivs => mbd_calc_get_lattice_derivs
138 procedure :: get_lattice_stress => mbd_calc_get_lattice_stress
139 procedure :: get_spectrum_modes => mbd_calc_get_spectrum_modes
140 procedure :: get_rpa_orders => mbd_calc_get_rpa_orders
141 procedure :: get_exception => mbd_calc_get_exception
142 end type
143
144 contains
145
146 subroutine mbd_calc_init(this, input)
147 !! Initialize an MBD calculation from an MBD input.
148 class(mbd_calc_t), target, intent(inout) :: this
149 type(mbd_input_t), intent(in) :: input
150 !! MBD input.
151
152 #ifdef WITH_MPI
153 if (input%comm /= -1) then
154 # ifdef WITH_MPIF08
155 this%geom%mpi_comm%mpi_val = input%comm
156 # else
157 this%geom%mpi_comm = input%comm
158 # endif
159 end if
160 #endif
161 #ifdef WITH_SCALAPACK
162 this%geom%max_atoms_per_block = input%max_atoms_per_block
163 #endif
164 this%method = input%method
165 this%calculate_gradients = input%calculate_forces
166 this%calculate_vdw_params_gradients = input%calculate_vdw_params_gradients
167 this%geom%get_eigs = input%calculate_spectrum
168 this%geom%get_modes = input%calculate_spectrum
169 this%geom%do_rpa = input%do_rpa
170 this%geom%get_rpa_orders = input%rpa_orders
171 this%geom%param%rpa_rescale_eigs = input%rpa_rescale_eigs
172 this%geom%param%n_freq = input%n_omega_grid
173 this%geom%param%k_grid_shift = input%k_grid_shift
174 this%geom%param%zero_negative_eigvals = input%zero_negative_eigvals
175 if (.not. all(input%k_grid == -1)) this%geom%k_grid = input%k_grid
176 this%geom%coords = input%coords
177 if (allocated(input%lattice_vectors)) then
178 if (input%method /= 'ts' .and. .not. allocated(this%geom%k_grid)) then
179 this%geom%exc = exception_t( &
180 MBD_EXC_INPUT, &
181 'calc%init()', &
182 'Lattice vectors present but no k-grid specified' &
183 )
184 return
185 end if
186 this%geom%lattice = input%lattice_vectors
187 end if
188 this%geom%parallel_mode = input%parallel_mode
189 if (associated(input%printer)) this%geom%log%printer => input%printer
190 this%geom%log%level = input%log_level
191 call this%geom%init()
192 if (allocated(input%free_values)) then
193 this%free_values = input%free_values
194 else
195 select case (input%vdw_params_kind)
196 case ('ts')
197 this%free_values = ts_vdw_params(:, species_index(input%atom_types))
198 case ('tssurf')
199 this%free_values = tssurf_vdw_params(:, species_index(input%atom_types))
200 end select
201 end if
202 if (input%xc == '') then
203 this%damp%beta = input%mbd_beta
204 this%damp%a = input%mbd_a
205 this%damp%ts_d = input%ts_d
206 this%damp%ts_sr = input%ts_sr
207 select case (input%method)
208 case ('ts')
209 if (input%ts_sr < 0) then
210 this%geom%exc%code = MBD_EXC_DAMPING
211 this%geom%exc%msg = 'Damping parameter S_r for TS not specified'
212 end if
213 case default
214 if (input%mbd_beta < 0) then
215 this%geom%exc%code = MBD_EXC_DAMPING
216 this%geom%exc%msg = 'Damping parameter beta for MBD not specified'
217 end if
218 end select
219 else
220 this%geom%exc = this%damp%set_params_from_xc(input%xc, input%method)
221 end if
222 if (this%geom%has_exc()) return
223 end subroutine
224
225 subroutine mbd_calc_destroy(this)
226 !! Finalize an MBD calculation.
227 class(mbd_calc_t), target, intent(inout) :: this
228
229 call this%geom%destroy()
230 end subroutine
231
232 subroutine mbd_calc_switch_forces(this, forces)
233 !! Update whether to calculate forces.
234 class(mbd_calc_t), intent(inout) :: this
235 logical, intent(in) :: forces
236 !! Whether to calcualte forces.
237
238 this%calculate_gradients = forces
239 end subroutine
240
241 subroutine mbd_calc_update_coords(this, coords)
242 !! Update atomic coordinates.
243 class(mbd_calc_t), intent(inout) :: this
244 real(dp), intent(in) :: coords(:, :)
245 !! (\(3\times N\), a.u.) New atomic coordinates.
246
247 this%geom%coords = coords
248 end subroutine
249
250 subroutine mbd_calc_update_lattice_vectors(this, latt_vecs)
251 !! Update unit-cell lattice vectors.
252 class(mbd_calc_t), intent(inout) :: this
253 real(dp), intent(in) :: latt_vecs(:, :)
254 !! (\(3\times 3\), a.u.) New lattice vectors in columns.
255
256 this%geom%lattice = latt_vecs
257 end subroutine
258
259 subroutine mbd_calc_update_vdw_params_custom(this, alpha_0, C6, r_vdw)
260 !! Update vdW parameters in a custom way.
261 class(mbd_calc_t), intent(inout) :: this
262 real(dp), intent(in) :: alpha_0(:)
263 !! (a.u.) New atomic static polarizabilities.
264 real(dp), intent(in) :: C6(:)
265 !! (a.u.) New atomic \(C_6\) coefficients.
266 real(dp), intent(in) :: r_vdw(:)
267 !! (a.u.) New atomic vdW radii.
268
269 this%alpha_0 = alpha_0
270 this%C6 = C6
271 this%damp%r_vdw = r_vdw
272 this%vdw_params_update = 'custom'
273 end subroutine
274
275 subroutine mbd_calc_update_vdw_params_from_ratios(this, ratios)
276 !! Update vdW parameters based on scaling of free-atom values.
277 class(mbd_calc_t), intent(inout) :: this
278 real(dp), intent(in) :: ratios(:)
279 !! Ratios of atomic volumes in the system and in vacuum.
280
281 real(dp), allocatable :: ones(:)
282 type(grad_request_t) :: grad
283
284 allocate (ones(size(ratios)), source=1d0)
285 grad%dV = this%calculate_vdw_params_gradients
286 ! Alias free_values before slicing it into the scale_with_ratio calls.
287 ! Passing an array section of an allocatable rank-2 component of the
288 ! polymorphic `this` straight into an array-valued function makes gfortran 16
289 ! emit an -fcheck=bounds check that reads the component descriptor through a
290 ! null pointer -- a bogus bounds error at -O0, a segfault at -O1/-Og
291 ! (libmbd/libmbd#127). Associating the component evaluates its descriptor
292 ! once and sidesteps the bad check; it is correct and idiomatic on every
293 ! compiler, so no version guard is needed. Do not fold the alias back into
294 ! `this%free_values(i, :)` while gfortran 16 is supported.
295 !
296 ! Scope of the bug: reproduced on the gfortran 16 series only -- 16.0 trunk
297 ! (r16-8100) and the 16.1.0 release (both x86-64 and aarch64). gfortran 13,
298 ! 14 and 15 are unaffected, and it is already fixed on the 17.0 trunk, so the
299 ! alias can be removed once gfortran 16 is no longer supported. No upstream
300 ! GCC bug was filed (it is fixed on trunk); a minimal standalone reproducer
301 ! is kept in the PR discussion for libmbd/libmbd#127.
302 associate (free_values => this%free_values)
303 this%alpha_0 = scale_with_ratio( &
304 free_values(1, :), ratios, ones, 1d0, this%dalpha_0, grad &
305 )
306 this%C6 = scale_with_ratio( &
307 free_values(2, :), ratios, ones, 2d0, this%dC6, grad &
308 )
309 this%damp%r_vdw = scale_with_ratio( &
310 free_values(3, :), ratios, ones, 1d0 / 3, this%dr_vdw, grad &
311 )
312 end associate
313 this%vdw_params_update = 'ratios'
314 end subroutine
315
316 subroutine mbd_calc_get_vdw_params_ratios_gradients(this, dE_dratios)
317 !! Get gradients of the energy w.r.t. Hirshfeld ratios if they were
318 !! requested in the MBD input.
319 class(mbd_calc_t), intent(inout) :: this
320 real(dp), intent(out) :: dE_dratios(:)
321 !! Gradients of the energy w.r.t. Hirshfeld ratios.
322
323 if (this%vdw_params_update /= 'ratios') return
324 dE_dratios = ( &
325 this%results%dE%dalpha * this%dalpha_0%dV &
326 + this%results%dE%dC6 * this%dC6%dV &
327 + this%results%dE%dr_vdw * this%dr_vdw%dV &
328 )
329 end subroutine
330
331 subroutine mbd_calc_update_vdw_params_nl(this, alpha_0_ratios, C6_ratios)
332 !! Update vdW parameters for the MBD-NL method.
333 class(mbd_calc_t), intent(inout) :: this
334 real(dp), intent(in) :: alpha_0_ratios(:)
335 !! Ratios of free-atom exact static polarizabilities and those from the
336 !! VV functional.
337 real(dp), intent(in) :: C6_ratios(:)
338 !! Ratios of free-atom exact \(C_6\) coefficients and those from the VV
339 !! functional.
340
341 this%alpha_0 = this%free_values(1, :) * alpha_0_ratios
342 this%C6 = this%free_values(2, :) * C6_ratios
343 this%damp%r_vdw = 2.5d0 * this%free_values(1, :)**(1d0 / 7) * alpha_0_ratios**(1d0 / 3)
344 this%vdw_params_update = 'nl'
345 end subroutine
346
347 subroutine mbd_calc_evaluate_vdw_method(this, energy)
348 !! Evaluate a given vdW method for a given system and vdW parameters,
349 !! retrieve energy.
350 class(mbd_calc_t), intent(inout) :: this
351 real(dp), intent(out) :: energy
352 !! (a.u.) VdW energy.
353
354 type(grad_request_t) :: grad
355
356 if (this%calculate_gradients) then
357 grad%dcoords = .true.
358 if (allocated(this%geom%lattice)) grad%dlattice = .true.
359 end if
360 if (this%calculate_vdw_params_gradients) then
361 grad%dalpha = .true.
362 grad%dC6 = .true.
363 grad%dr_vdw = .true.
364 end if
365 select case (this%method)
366 case ('mbd', 'mbd-nl')
367 this%damp%version = 'fermi,dip'
368 this%results = get_mbd_energy( &
369 this%geom, this%alpha_0, this%C6, this%damp, grad &
370 )
371 energy = this%results%energy
372 case ('mbd-rsscs')
373 this%results = get_mbd_scs_energy( &
374 this%geom, 'rsscs', this%alpha_0, this%C6, this%damp, grad &
375 )
376 energy = this%results%energy
377 case ('ts')
378 this%damp%version = 'fermi'
379 this%results = get_ts_energy( &
380 this%geom, this%alpha_0, this%C6, this%damp, grad &
381 )
382 energy = this%results%energy
383 end select
384 if (this%geom%log%level <= MBD_LOG_LVL_DEBUG) call this%geom%timer%print()
385 end subroutine
386
387 subroutine mbd_calc_get_gradients(this, gradients) ! 3 by N dE/dR
388 !! Retrieve nuclear energy gradients if they were requested in the MBD
389 !! input.
390 !!
391 !! The gradients are calculated together with the energy, so a call to this
392 !! method must be preceeded by a call to
393 !! [[mbd_calc_t:evaluate_vdw_method]]. For the same reason, the
394 !! gradients must be requested prior to this called via
395 !! [[mbd_input_t:calculate_forces]].
396 class(mbd_calc_t), intent(in) :: this
397 real(dp), intent(out) :: gradients(:, :)
398 !! (\(3\times N\), a.u.) Energy gradients, \(\mathrm dE/\mathrm d\mathbf
399 !! R_i\), index \(i\) runs over columns.
400
401 gradients = transpose(this%results%dE%dcoords)
402 end subroutine
403
404 subroutine mbd_calc_get_lattice_derivs(this, latt_derivs)
405 !! Provide lattice-vector energy gradients if they were requested in the MBD
406 !! input.
407 !!
408 !! The gradients are actually calculated together with the energy, so a call
409 !! to this method must be preceeded by a call to
410 !! [[mbd_calc_t:evaluate_vdw_method]]. For the same reason, the
411 !! gradients must be requested prior to this called via
412 !! [[mbd_input_t:calculate_forces]].
413 class(mbd_calc_t), intent(in) :: this
414 real(dp), intent(out) :: latt_derivs(:, :)
415 !! (\(3\times 3\), a.u.) Energy gradients, \(\mathrm dE/\mathrm d\mathbf
416 !! a_i\), index \(i\) runs over columns.
417
418 latt_derivs = transpose(this%results%dE%dlattice)
419 end subroutine
420
421 subroutine mbd_calc_get_lattice_stress(this, stress)
422 !! Provide stress tensor of the lattice.
423 !!
424 !! This is a utility function wrapping [[mbd_calc_t:get_lattice_derivs]].
425 !! The lattice vector gradients are coverted to the stress tensor.
426 class(mbd_calc_t), intent(in) :: this
427 real(dp), intent(out) :: stress(:, :)
428 !! (\(3\times 3\), a.u.) Stress tensor.
429
430 stress = ( &
431 matmul(this%geom%lattice, this%results%dE%dlattice) &
432 + matmul(this%geom%coords, this%results%dE%dcoords) &
433 )
434 end subroutine
435
436 subroutine mbd_calc_get_spectrum_modes(this, spectrum, modes)
437 !! Provide MBD spectrum if it was requested in the MBD input.
438 !!
439 !! The spectrum is actually calculated together with the energy, so a call
440 !! to this method must be preceeded by a call to
441 !! [[mbd_calc_t:evaluate_vdw_method]]. For the same reason, the
442 !! spectrum must be requested prior to this call via
443 !! [[mbd_input_t:calculate_spectrum]].
444 class(mbd_calc_t), intent(inout) :: this
445 real(dp), intent(out) :: spectrum(:)
446 !! (\(3N\), a.u.) Energies (frequencies) of coupled MBD modues,
447 !! \(\omega_i\).
448 real(dp), intent(out), allocatable, optional :: modes(:, :)
449 !! (\(3N\times 3N\)) Coupled-mode wave functions (MBD eigenstates),
450 !! \(\psi_j\), in the basis of uncoupled states,
451 !! \(C_{ij}=\langle\phi_i|\psi_j\rangle\), index \(j\) runs over
452 !! columns.
453 !!
454 !! To save memory, the argument must be allocatable, and the method
455 !! transfers allocation from the internal state to the argument. For
456 !! this reason, the method can be called only once wih this optional
457 !! argument per calculation.
458
459 spectrum = this%results%mode_eigs
460 if (present(modes)) call move_alloc(this%results%modes, modes)
461 end subroutine
462
463 subroutine mbd_calc_get_rpa_orders(this, rpa_orders)
464 !! Provide RPA orders if they were requested in the MBD input.
465 !!
466 !! The orders are actually calculated together with the energy, so a call
467 !! to this method must be preceeded by a call to
468 !! [[mbd_calc_t:evaluate_vdw_method]]. For the same reason, the
469 !! spectrum must be requested prior to this call via
470 !! [[mbd_input_t:do_rpa]] and [[mbd_input_t:rpa_orders]].
471 class(mbd_calc_t), intent(inout) :: this
472 real(dp), allocatable, intent(out) :: rpa_orders(:)
473 !! (a.u.) MBD energy decomposed to RPA orders.
474
475 rpa_orders = this%results%rpa_orders
476 end subroutine
477
478 subroutine mbd_calc_get_exception(this, code, origin, msg)
479 !! Retrieve an exception in the MBD calculation if it occured.
480 class(mbd_calc_t), intent(inout) :: this
481 integer, intent(out) :: code
482 !! Exception code, values defined in [[mbd_constants]].
483 character(*), intent(out) :: origin
484 !! Exception origin.
485 character(*), intent(out) :: msg
486 !! Exception message.
487
488 code = this%geom%exc%code
489 if (code == 0) return
490 origin = this%geom%exc%origin
491 msg = this%geom%exc%msg
492 this%geom%exc%code = 0
493 this%geom%exc%origin = ''
494 this%geom%exc%msg = ''
495 end subroutine
496
497 end module