Debian Codegraph @

src/pymbd/fortran.py

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 from __future__ import division, print_function
5
6 import re
7 from functools import wraps
8
9 import numpy as np
10
11 from .__init__ import __version__ as PYMBD_VERSION
12 from .pymbd import _array, from_volumes
13
14 try:
15 from ._libmbd import ffi as _ffi, lib as _lib
16 except ImportError:
17 raise Exception('pyMBD C extension unimportable, cannot use Fortran') from None
18
19 __all__ = ['MBDGeom', 'with_mpi', 'with_scalapack']
20
21 with_mpi = _lib.cmbd_with_mpi
22 """Whether libMBD was compiled with MPI"""
23
24 with_scalapack = _lib.cmbd_with_scalapack
25 """Whether libMBD was compiled with Scalapack"""
26
27 LIBMBD_VERSION = (
28 _lib.cmbd_version_major,
29 _lib.cmbd_version_minor,
30 _lib.cmbd_version_patch,
31 _ffi.string(_lib.cmbd_version_suffix).strip().decode(),
32 )
33
34 # do not test versions when running autodoc
35 if PYMBD_VERSION and isinstance(LIBMBD_VERSION[0], int):
36 assert PYMBD_VERSION[0] == LIBMBD_VERSION[0]
37 if PYMBD_VERSION[0] == 0:
38 assert PYMBD_VERSION[1] == LIBMBD_VERSION[1]
39 else:
40 assert PYMBD_VERSION[1] <= LIBMBD_VERSION[1]
41 if len(PYMBD_VERSION) == 4:
42 git_commit = re.split('[+-]', PYMBD_VERSION[3])[1]
43 assert LIBMBD_VERSION[3].endswith(git_commit)
44
45
46 class MBDFortranError(Exception):
47 def __init__(self, code, origin, msg):
48 super(MBDFortranError, self).__init__(code, origin, msg)
49 self.code = code
50 self.origin = origin
51
52
53 def _auto_context(method):
54 @wraps(method)
55 def wrapper(self, *args, **kwargs):
56 if self._geom_f:
57 return method(self, *args, **kwargs)
58 with self:
59 return method(self, *args, **kwargs)
60
61 return wrapper
62
63
64 class MBDGeom(object):
65 """Represents an initialized libMBD `geom_t <../type/geom_t.html>`_ object.
66
67 :param array-like coords: (a.u.) atomic coordinates as rows
68 :param array-like lattice: (a.u.) lattice vectors as rows
69 :param array-like k_grid: number of :math:`k`-points per reciprocal lattice vector
70 :param array-like custom_k_pts: (a.u.) custom :math:`k`-points as rows
71 :param int n_freq: number of quadrature points for frequency integration
72 :param bool do_rpa: whether to calculate MBD energy via frequency integration
73 :param bool get_spectrum: whether to return eigenvalues and eigenvectors
74 :param bool get_rpa_orders: whether to return RPA order decomposition
75 :param bool rpa_rescale_eigs: whether to rescale RPA eigenvalues
76 """
77
78 def __init__(
79 self,
80 coords,
81 lattice=None,
82 k_grid=None,
83 custom_k_pts=None,
84 n_freq=None,
85 do_rpa=False,
86 get_spectrum=False,
87 get_rpa_orders=False,
88 rpa_rescale_eigs=False,
89 max_atoms_per_block=None,
90 ewald_cutoff_scaling=(1.0, 1.0),
91 ):
92 self._geom_f = None
93 self._coords, self._lattice = map(_array, (coords, lattice))
94 self._k_grid = _array(k_grid, dtype='i4')
95 self._custom_k_pts = _array(custom_k_pts)
96 self._n_freq = n_freq
97 self._do_rpa = do_rpa
98 self._get_spectrum = get_spectrum
99 self._get_rpa_orders = get_rpa_orders
100 self._rpa_rescale_eigs = rpa_rescale_eigs
101 self._max_atoms_per_block = max_atoms_per_block
102 self._ewald_cutoff_scaling = ewald_cutoff_scaling
103
104 def __len__(self):
105 return len(self._coords)
106
107 def __enter__(self):
108 self._geom_f = _lib.cmbd_init_geom(
109 len(self),
110 _cast('double*', self._coords),
111 _cast('double*', self._lattice),
112 _cast('int*', self._k_grid),
113 len(self._custom_k_pts) if self._custom_k_pts is not None else 0,
114 _cast('double*', self._custom_k_pts),
115 self._n_freq or 0,
116 self._do_rpa,
117 self._get_spectrum,
118 self._get_rpa_orders,
119 self._rpa_rescale_eigs,
120 self._max_atoms_per_block or 0,
121 self._ewald_cutoff_scaling,
122 )
123 return self
124
125 def __exit__(self, exc_type, exc_value, traceback):
126 _lib.cmbd_destroy_geom(self._geom_f)
127 self._geom_f = None
128
129 def _check_exc(self):
130 code = _array(0, dtype=int)
131 origin = _ffi.new('char[50]')
132 msg = _ffi.new('char[150]')
133 _lib.cmbd_get_exception(self._geom_f, _cast('int*', code), origin, msg)
134 if code != 0:
135 raise MBDFortranError(
136 int(code), _ffi.string(origin).decode(), _ffi.string(msg).decode()
137 )
138
139 @property
140 def coords(self):
141 """(a.u.) Atom coordinates in rows."""
142 return self._coords.copy()
143
144 @coords.setter
145 def coords(self, coords):
146 _lib.cmbd_update_coords(self._geom_f, _cast('double*', _array(coords)))
147
148 @property
149 def lattice(self):
150 """(a.u.) Lattice vectors in rows."""
151 return self._lattice.copy()
152
153 @lattice.setter
154 def lattice(self, lattice):
155 _lib.cmbd_update_lattice(self._geom_f, _cast('double*', _array(lattice)))
156
157 def has_lattice(self):
158 """Whether structure is a crystal."""
159 return self._lattice is not None
160
161 def print_timing(self):
162 """Print timing from libMBD."""
163 _lib.cmbd_print_timing(self._geom_f)
164
165 @_auto_context
166 def ts_energy(self, alpha_0, C6, R_vdw, sR, d=20.0, damping='fermi', force=False):
167 """Calculate a TS energy.
168
169 :param array-like alpha_0: (a.u.) atomic polarizabilities
170 :param array-like C6: (a.u.) atomic :math:`C_6` coefficients
171 :param array-like R_vdw: (a.u.) atomic vdW radii
172 :param float sR: TS damping parameter :math:`s_R`
173 :param float d: TS damping parameter :math:`d`
174 :param damping str: type of damping
175 :param force bool: if True, calculate energy gradients
176 """
177 alpha_0, C6, R_vdw = map(_array, (alpha_0, C6, R_vdw))
178 n_atoms = len(self)
179 damping_f = _lib.cmbd_init_damping(
180 len(self), damping.encode(), _cast('double*', R_vdw), _ffi.NULL, sR, d
181 )
182 res_f = _lib.cmbd_ts_energy(
183 self._geom_f,
184 _cast('double*', alpha_0),
185 _cast('double*', C6),
186 damping_f,
187 force,
188 )
189 _lib.cmbd_destroy_damping(damping_f)
190 self._check_exc()
191 ene = np.empty(1) # for some reason np.array(0) doesn't work
192 gradients, lattice_gradients = 2 * [None]
193 if force:
194 gradients = np.zeros((n_atoms, 3))
195 if self.has_lattice():
196 lattice_gradients = np.zeros((3, 3))
197 results = (ene, gradients, lattice_gradients, *(7 * [None]))
198 _lib.cmbd_get_results(res_f, *(_cast('double*', x) for x in results))
199 _lib.cmbd_destroy_result(res_f)
200 ene = ene.item()
201 if force:
202 ene = (ene, gradients)
203 if self.has_lattice():
204 ene += (lattice_gradients,)
205 return ene
206
207 @_auto_context
208 def mbd_energy( # noqa: C901
209 self,
210 alpha_0,
211 C6,
212 R_vdw=None,
213 beta=0.0,
214 a=6.0,
215 sigma=None,
216 damping='fermi,dip',
217 variant='rsscs',
218 force=False,
219 intermediates=False,
220 ):
221 r"""Calculate an MBD energy.
222
223 :param array-like alpha_0: (a.u.) atomic polarizabilities
224 :param array-like C6: (a.u.) atomic :math:`C_6` coefficients
225 :param array-like R_vdw: (a.u.) atomic vdW radii
226 :param array-like sigma: (a.u.) oscillator widths
227 :param float beta: MBD damping parameter :math:`\beta`
228 :param float a: MBD damping parameter :math:`a`
229 :param damping str: type of damping
230 :param variant str: one of 'plain', 'scs', 'rsscs'
231 :param force bool: if True, calculate energy gradients
232 """
233 alpha_0, C6, R_vdw, sigma = map(_array, (alpha_0, C6, R_vdw, sigma))
234 n_atoms = len(self)
235 damping_f = _lib.cmbd_init_damping(
236 n_atoms,
237 damping.encode(),
238 _cast('double*', R_vdw),
239 _cast('double*', sigma),
240 beta,
241 a,
242 )
243 args = (
244 self._geom_f,
245 _cast('double*', alpha_0),
246 _cast('double*', C6),
247 damping_f,
248 force,
249 )
250 if variant == 'plain':
251 res_f = _lib.cmbd_mbd_energy(*args)
252 else:
253 args = args[:1] + (variant.encode(),) + args[1:]
254 res_f = _lib.cmbd_mbd_scs_energy(*args)
255 _lib.cmbd_destroy_damping(damping_f)
256 self._check_exc()
257 ene = np.empty(1) # for some reason np.array(0) doesn't work
258 gradients, lattice_gradients = 2 * [None]
259 alpha_0_scs, C6_scs = 2 * [None]
260 eigs, modes, rpa_orders, eigs_k, modes_k = 5 * [None]
261 if force:
262 gradients = np.zeros((n_atoms, 3))
263 if self.has_lattice():
264 lattice_gradients = np.zeros((3, 3))
265 if intermediates:
266 alpha_0_scs, C6_scs = np.zeros(n_atoms), np.zeros(n_atoms)
267 if self._get_spectrum:
268 if self.has_lattice():
269 n_kpts = (
270 len(self._custom_k_pts)
271 if self._custom_k_pts is not None
272 else self._k_grid.prod()
273 )
274 eigs_k = np.zeros((3 * n_atoms, n_kpts), order='F')
275 modes_k = np.zeros(
276 (3 * n_atoms, 3 * n_atoms, n_kpts), dtype=complex, order='F'
277 )
278 else:
279 eigs = np.zeros(3 * n_atoms)
280 modes = np.zeros((3 * n_atoms, 3 * n_atoms), order='F')
281 elif self._get_rpa_orders:
282 rpa_orders = np.zeros(10)
283 results = (
284 ene,
285 gradients,
286 lattice_gradients,
287 eigs,
288 modes,
289 rpa_orders,
290 eigs_k,
291 modes_k,
292 alpha_0_scs,
293 C6_scs,
294 )
295 _lib.cmbd_get_results(res_f, *(_cast('double*', x) for x in results))
296 _lib.cmbd_destroy_result(res_f)
297 ene = ene.item()
298 if self.has_lattice():
299 eigs, modes = eigs_k, modes_k
300 if self._get_spectrum:
301 ene = ene, eigs, modes
302 elif self._get_rpa_orders:
303 ene = ene, rpa_orders
304 if force or intermediates:
305 ene = (ene,)
306 if force:
307 ene += (gradients,)
308 if self.has_lattice():
309 ene += (lattice_gradients,)
310 if intermediates:
311 ene += (alpha_0_scs, C6_scs)
312 return ene
313
314 @_auto_context
315 def dipole_matrix( # noqa: D102
316 self, damping, beta=0.0, k_point=None, R_vdw=None, sigma=None, a=6.0
317 ):
318 R_vdw, sigma, k_point = map(_array, (R_vdw, sigma, k_point))
319 n_atoms = len(self)
320 damping_f = _lib.cmbd_init_damping(
321 n_atoms,
322 damping.encode(),
323 _cast('double*', R_vdw),
324 _cast('double*', sigma),
325 beta,
326 a,
327 )
328 dipmat = np.empty(
329 (3 * n_atoms, 3 * n_atoms), dtype=float if k_point is None else complex
330 )
331 _lib.cmbd_dipole_matrix(
332 self._geom_f, damping_f, _cast('double*', k_point), _cast('double*', dipmat)
333 )
334 _lib.cmbd_destroy_damping(damping_f)
335 self._check_exc()
336 return dipmat
337
338 def mbd_energy_species(self, species, volume_ratios, beta, **kwargs):
339 r"""Calculate an MBD energy from atom types and Hirshfed-volume ratios.
340
341 :param array-like species: atom types (elements)
342 :param array-like volume_ratios: ratios of Hirshfeld volumes in
343 molecule and vacuum
344 :param float beta: MBD damping parameter :math:`\beta`
345 :param kwargs: see :meth:`mbd_energy`
346 """
347 alpha_0, C6, R_vdw = from_volumes(species, volume_ratios)
348 return self.mbd_energy(alpha_0, C6, R_vdw, beta, **kwargs)
349
350 def ts_energy_species(self, species, volume_ratios, beta, **kwargs):
351 """Calculate a TS energy from atom types and Hirshfed-volume ratios.
352
353 :param array-like species: atom types (elements)
354 :param array-like volume_ratios: ratios of Hirshfeld volumes in
355 molecule and vacuum
356 :param float sR: TS damping parameter :math:`s_R`
357 :param kwargs: see :meth:`ts_energy`
358 """
359 alpha_0, C6, R_vdw = from_volumes(species, volume_ratios)
360 return self.ts_energy(alpha_0, C6, R_vdw, beta, **kwargs)
361
362 @_auto_context
363 def dipole_energy(self, a0, w, w_t, version, r_vdw, beta, a, C): # noqa: D102
364 n_atoms = len(self)
365 res = _lib.cmbd_dipole_energy(
366 self._geom_f,
367 n_atoms,
368 _cast('double*', a0),
369 _cast('double*', w),
370 _cast('double*', w_t),
371 version.encode(),
372 _cast('double*', r_vdw),
373 beta,
374 a,
375 _cast('double*', C),
376 )
377 self._check_exc()
378 return res
379
380 @_auto_context
381 def coulomb_energy(self, q, m, w_t, version, r_vdw, beta, a, C): # noqa: D102
382 n_atoms = len(self)
383 res = _lib.cmbd_coulomb_energy(
384 self._geom_f,
385 n_atoms,
386 _cast('double*', q),
387 _cast('double*', m),
388 _cast('double*', w_t),
389 version.encode(),
390 _cast('double*', r_vdw),
391 beta,
392 a,
393 _cast('double*', C),
394 )
395 self._check_exc()
396 return res
397
398 @_auto_context
399 def nonint_density(self, pts, q, m, w):
400 r"""Evaluate the density of the non-interacting QDOs.
401
402 Returns the charge density of the quantum Drude oscillators (QDOs) in
403 the absence of the dipole coupling, that is a sum of independent
404 spherical Gaussians, one per atom,
405
406 .. math::
407 n(\mathbf r)=\sum_A q_A\left(\frac{m_A\omega_A}\pi\right)^\frac32
408 \exp\big(-m_A\omega_A|\mathbf r-\mathbf R_A|^2\big)
409
410 which integrates to :math:`\sum_A q_A`. The oscillator parameters are
411 related to the vdW parameters by
412 :math:`\omega_A=\tfrac43 C_{6,A}/\alpha_{0,A}^2` and
413 :math:`\alpha_{0,A}=q_A^2/(m_A\omega_A^2)`. The MBD convention is
414 :math:`m_A=1`, which gives :math:`q_A=\omega_A\sqrt{\alpha_{0,A}}`. See
415 :doc:`/densities` for a plotting example.
416
417 :param array-like pts: (a.u.) points at which to evaluate the density,
418 shape ``(n_pts, 3)``
419 :param array-like q: (a.u.) oscillator charges
420 :param array-like m: (a.u.) oscillator masses
421 :param array-like w: (a.u.) oscillator frequencies :math:`\omega`
422
423 :returns: (a.u.) density evaluated at ``pts``, shape ``(n_pts,)``
424 """
425 n_pts = len(pts)
426 n_atoms = len(self)
427 rho = np.empty(n_pts)
428 _lib.cmbd_nonint_density(
429 self._geom_f,
430 n_atoms,
431 n_pts,
432 _cast('double*', pts),
433 _cast('double*', q),
434 _cast('double*', m),
435 _cast('double*', w),
436 _cast('double*', rho),
437 )
438 self._check_exc()
439 return rho
440
441 @_auto_context
442 def int_density(self, pts, q, m, w_t, modes):
443 r"""Evaluate the density of the interacting QDOs.
444
445 Returns the charge density of the quantum Drude oscillators (QDOs) with
446 the dipole coupling switched on. Unlike :meth:`nonint_density`, each
447 per-atom contribution is a general (anisotropic) Gaussian obtained by
448 integrating out the remaining oscillators from the coupled ground-state
449 wavefunction (see :doc:`/densities` for the derivation and a plotting
450 example). Like the non-interacting density, it integrates to
451 :math:`\sum_A q_A`.
452
453 The coupled frequencies ``w_t`` and eigenmodes ``modes`` are the MBD
454 normal modes, obtained from :meth:`mbd_energy` with a geometry
455 constructed with ``get_spectrum=True`` (``w_t`` are the square roots of
456 the returned eigenvalues).
457
458 :param array-like pts: (a.u.) points at which to evaluate the density,
459 shape ``(n_pts, 3)``
460 :param array-like q: (a.u.) oscillator charges
461 :param array-like m: (a.u.) oscillator masses
462 :param array-like w_t: (a.u.) coupled MBD frequencies
463 :math:`\tilde\omega`, shape ``(3 n_atoms,)``
464 :param array-like modes: MBD eigenmodes, shape
465 ``(3 n_atoms, 3 n_atoms)``
466
467 :returns: (a.u.) density evaluated at ``pts``, shape ``(n_pts,)``
468 """
469 n_pts = len(pts)
470 n_atoms = len(self)
471 rho = np.empty(n_pts)
472 _lib.cmbd_int_density(
473 self._geom_f,
474 n_atoms,
475 n_pts,
476 _cast('double*', pts),
477 _cast('double*', q),
478 _cast('double*', m),
479 _cast('double*', w_t),
480 _cast('double*', modes),
481 _cast('double*', rho),
482 )
483 self._check_exc()
484 return rho
485
486
487 def _ndarray(ptr, shape=None, dtype='float'):
488 buffer_size = (np.prod(shape) if shape else 1) * np.dtype(dtype).itemsize
489 return np.ndarray(buffer=_ffi.buffer(ptr, buffer_size), shape=shape, dtype=dtype)
490
491
492 def _cast(ctype, array):
493 return _ffi.NULL if array is None else _ffi.cast(ctype, array.ctypes.data)