Debian Codegraph @

src/pymbd/pymbd.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 csv
7 from importlib.resources import files
8 from itertools import product
9
10 import numpy as np
11 from numpy.polynomial.legendre import leggauss
12 from scipy.special import erf, erfc
13
14 __all__ = [
15 'mbd_energy',
16 'mbd_energy_species',
17 'screening',
18 'screening_matrix',
19 'from_volumes',
20 'atomic_polarizabilities',
21 'molecular_polarizability',
22 'ang',
23 ]
24
25 ang = 1 / 0.529177249
26 """(a.u.) angstrom"""
27
28
29 def screening_matrix(coords, alpha_0, R_vdw, beta, lattice=None):
30 r"""Build the screened non-local polarizability matrix.
31
32 Returns the :math:`(3N, 3N)` matrix
33 :math:`\bar{\boldsymbol\alpha}=(\boldsymbol\alpha_0^{-1}+\mathbf T_\mathrm{GG})^{-1}`,
34 whose :math:`3\times3` blocks :math:`\bar{\boldsymbol\alpha}_{ij}` are the
35 dipole-screened polarizabilities coupling atoms :math:`i` and :math:`j`. This
36 is the shared core of :func:`screening`, :func:`atomic_polarizabilities`, and
37 :func:`molecular_polarizability`.
38
39 :param array-like coords: (a.u.) atom coordinates in rows
40 :param array-like alpha_0: (a.u.) atomic polarizabilities
41 :param array-like R_vdw: (a.u.) atomic vdW radii
42 :param float beta: MBD damping parameter :math:`\beta`
43 :param array-like lattice: (a.u.) lattice vectors in rows
44 """
45 alpha_0 = np.asarray(alpha_0)
46 sigma = (np.sqrt(2 / np.pi) * alpha_0 / 3) ** (1 / 3)
47 dipmat = dipole_matrix(
48 coords, 'fermi,dip,gg', sigma=sigma, R_vdw=R_vdw, beta=beta, lattice=lattice
49 )
50 return np.linalg.inv(np.diag(np.repeat(1 / alpha_0, 3)) + dipmat)
51
52
53 def _atomic_polarizability_tensors(a_nlc):
54 # contract the (3N, 3N) screened matrix over the second atom index into
55 # per-atom (N, 3, 3) polarizability tensors
56 n = a_nlc.shape[0] // 3
57 return a_nlc.reshape(n, 3, n, 3).swapaxes(1, 2).sum(axis=1)
58
59
60 def screening(coords, alpha_0, C6, R_vdw, beta, lattice=None, nfreq=15):
61 r"""Screen atomic polarizabilities.
62
63 :param array-like coords: (a.u.) atom coordinates in rows
64 :param array-like alpha_0: (a.u.) atomic polarizabilities
65 :param array-like C6: (a.u.) atomic :math:`C_6` coefficients
66 :param array-like R_vdw: (a.u.) atomic vdW radii
67 :param float beta: MBD damping parameter :math:`\beta`
68 :param array-like lattice: (a.u.) lattice vectors in rows
69 :param int nfreq: number of grid points for frequency quadrature
70
71 Returns static polarizabilities, :math:`C_6` coefficients, and
72 :math:`R_\mathrm{vdw}` coefficients (a.u.).
73 """
74 freq, freq_w = freq_grid(nfreq)
75 omega = 4 / 3 * C6 / alpha_0**2
76 alpha_dyn = [alpha_0 / (1 + (u / omega) ** 2) for u in freq]
77 alpha_dyn_rsscs = []
78 for a in alpha_dyn:
79 a_nlc = screening_matrix(coords, a, R_vdw, beta, lattice=lattice)
80 a_contr = np.einsum('aii->a', _atomic_polarizability_tensors(a_nlc)) / 3
81 alpha_dyn_rsscs.append(a_contr)
82 alpha_dyn_rsscs = np.stack(alpha_dyn_rsscs)
83 C6_rsscs = 3 / np.pi * np.sum(freq_w[:, None] * alpha_dyn_rsscs**2, 0)
84 R_vdw_rsscs = R_vdw * (alpha_dyn_rsscs[0, :] / alpha_0) ** (1 / 3)
85 return alpha_dyn_rsscs[0], C6_rsscs, R_vdw_rsscs
86
87
88 def atomic_polarizabilities(coords, species, volumes, beta, lattice=None, kind='TS'):
89 r"""Calculate static atomic polarizabilities.
90
91 :param array-like coords: (a.u.) atom coordinates in rows
92 :param array-like species: atom types (elements)
93 :param array-like volumes: ratios of Hirshfeld volumes in molecule and vacuum
94 :param float beta: MBD damping parameter :math:`\beta` (see J. Chem. Phys. 140, 18A508 (2014))
95 :param array-like lattice: (a.u.) lattice vectors in rows
96 :param str kind: one of 'TS', 'BG' or 'TSsurf'
97
98 Returns the isotropic per-atom screened static polarizabilities of shape
99 ``(N,)`` (a.u.).
100 """
101 alpha_0, _, R_vdw = from_volumes(species, volumes, kind=kind)
102 a_nlc = screening_matrix(coords, alpha_0, R_vdw, beta, lattice=lattice)
103 return np.einsum('aii->a', _atomic_polarizability_tensors(a_nlc)) / 3
104
105
106 def molecular_polarizability(coords, species, volumes, beta, lattice=None, kind='TS'):
107 r"""Calculate the static molecular polarizability tensor.
108
109 :param array-like coords: (a.u.) atom coordinates in rows
110 :param array-like species: atom types (elements)
111 :param array-like volumes: ratios of Hirshfeld volumes in molecule and vacuum
112 :param float beta: MBD damping parameter :math:`\beta` (see J. Chem. Phys. 140, 18A508 (2014))
113 :param array-like lattice: (a.u.) lattice vectors in rows
114 :param str kind: one of 'TS', 'BG' or 'TSsurf'
115
116 Returns the :math:`3\times3` static polarizability tensor (a.u.).
117 """
118 alpha_0, _, R_vdw = from_volumes(species, volumes, kind=kind)
119 a_nlc = screening_matrix(coords, alpha_0, R_vdw, beta, lattice=lattice)
120 return _atomic_polarizability_tensors(a_nlc).sum(axis=0)
121
122
123 def mbd_energy(coords, alpha_0, C6, R_vdw, beta, lattice=None, k_grid=None, nfreq=15):
124 r"""Calculate an MBD energy.
125
126 Use with Hirshfeld-partitioned atomic polarizabilities, C6 coefficients and
127 van der Waal radii. Otherwise use mbd_energy_species().
128
129 :param array-like coords: (a.u.) atomic coordinates in rows
130 :param array-like alpha_0: (a.u.) atomic polarizabilities
131 :param array-like C6: (a.u.) atomic :math:`C_6` coefficients
132 :param array-like R_vdw: (a.u.) atomic vdW radii
133 :param float beta: MBD damping parameter :math:`\beta`
134 :param array-like lattice: (a.u.) lattice vectors in rows
135 :param array-like k_grid: number of :math:`k`-points along reciprocal axes
136 :param int nfreq: number of grid points for frequency quadrature
137 """
138 coords, alpha_0, C6, R_vdw, lattice = map(
139 _array, (coords, alpha_0, C6, R_vdw, lattice)
140 )
141 alpha_0_rsscs, C6_rsscs, R_vdw_rsscs = screening(
142 coords, alpha_0, C6, R_vdw, beta, lattice=lattice, nfreq=15
143 )
144 omega_rsscs = 4 / 3 * C6_rsscs / alpha_0_rsscs**2
145 pre = np.repeat(omega_rsscs * np.sqrt(alpha_0_rsscs), 3)
146 if lattice is None:
147 k_points = [None]
148 else:
149 assert k_grid is not None
150 k_points = get_kpts(lattice, k_grid)
151 ene = 0.0
152 for k_point in k_points:
153 eigs = np.linalg.eigvalsh(
154 np.diag(np.repeat(omega_rsscs**2, 3))
155 + np.outer(pre, pre)
156 * dipole_matrix(
157 coords,
158 'fermi,dip',
159 R_vdw=R_vdw_rsscs,
160 beta=beta,
161 lattice=lattice,
162 k_point=k_point,
163 )
164 )
165 ene += np.sum(np.sqrt(eigs)) / 2
166 ene = ene / len(k_points) - 3 * np.sum(omega_rsscs) / 2
167 return ene
168
169
170 def mbd_energy_species(coords, species, volume_ratios, beta, **kwargs):
171 r"""Calculate an MBD energy from atom types and Hirshfeld-volume ratios.
172
173 :param array-like coords: (a.u.) atom coordinates in rows
174 :param array-like species: atom types (elements)
175 :param array-like volume_ratios: ratios of Hirshfeld volumes in molecule and vacuum
176 :param float beta: MBD damping parameter :math:`\beta` (use :math:'\beta = 0.83' for PBE xc-functional)
177 :param kwargs: see :func:`mbd_energy`
178 """
179 alpha_0, C6, R_vdw = from_volumes(species, volume_ratios)
180 return mbd_energy(coords, alpha_0, C6, R_vdw, beta, **kwargs)
181
182
183 def dipole_matrix(
184 coords, damping, beta=0.0, lattice=None, k_point=None, R_vdw=None, sigma=None, a=6.0
185 ):
186 if lattice is not None:
187 volume = max(np.abs(np.prod(np.linalg.eigvals(lattice))), 0.2)
188 ewald_alpha = 2.5 / volume ** (1 / 3)
189 real_space_cutoff = 6 / ewald_alpha
190 range_cell = supercell_circum(lattice, real_space_cutoff)
191 else:
192 range_cell = (0, 0, 0)
193 do_ewald = lattice is not None and damping in {'fermi,dip'}
194 n = len(coords)
195 dtype = float if k_point is None else complex
196 dipmat = np.zeros((n, n, 3, 3), dtype=dtype)
197 if R_vdw is not None:
198 S_vdw = beta * (R_vdw[:, None] + R_vdw[None, :])
199 if sigma is not None:
200 sigma_ij = np.sqrt(sigma[:, None] ** 2 + sigma[None, :] ** 2)
201 for idx_cell in product(*(range(-i, i + 1) for i in range_cell)):
202 R_cell = lattice.T.dot(idx_cell) if lattice is not None else np.zeros(3)
203 Rs = coords[:, None, :] - coords[None, :, :] + R_cell
204 dists = np.sqrt(np.sum(Rs**2, -1))
205 if damping == 'fermi,dip':
206 T = damping_fermi(dists, S_vdw, a)[:, :, None, None] * T_bare(Rs)
207 elif damping == 'fermi,dip,gg':
208 T = (1 - damping_fermi(dists, S_vdw, a)[:, :, None, None]) * T_erf_coulomb(
209 Rs, sigma_ij
210 )
211 else:
212 raise ValueError(f'Unsupported damping: {damping}')
213 if do_ewald:
214 T += T_erfc(Rs, ewald_alpha) - T_bare(Rs)
215 if k_point is not None:
216 k_pref = np.exp(-1j * np.sum(k_point * Rs, -1))
217 T = k_pref[:, :, None, None] * T
218 dipmat += T
219 if do_ewald:
220 dipmat += dipole_matrix_ewald(coords, lattice, ewald_alpha, k_point)
221 n = len(coords)
222 return np.reshape(np.transpose(dipmat, (0, 2, 1, 3)), (3 * n, 3 * n))
223
224
225 def dipole_matrix_ewald(coords, lattice, alpha, k_point=None):
226 Rs = coords[:, None, :] - coords[None, :, :]
227 rlattice = 2 * np.pi * np.linalg.inv(lattice.T)
228 volume = abs(np.prod(np.linalg.eigvals(lattice)))
229 rec_space_cutoff = 10 * alpha
230 range_G_vector = supercell_circum(rlattice, rec_space_cutoff)
231 dtype = float if k_point is None else complex
232 dipmat = np.zeros((len(Rs), len(Rs), 3, 3), dtype=dtype)
233 fourier_factor = (
234 (lambda x: np.cos(x)) if k_point is None else (lambda x: np.exp(1j * x))
235 )
236 for idx_gvec in product(*(range(-i, i + 1) for i in range_G_vector)):
237 if idx_gvec == (0, 0, 0):
238 continue
239 gvec = rlattice.T.dot(idx_gvec)
240 k_total = k_point + gvec if k_point is not None else gvec
241 k_sq = sum(k_total**2)
242 if np.sqrt(k_sq) > rec_space_cutoff:
243 continue
244 k_prefactor = (
245 4
246 * np.pi
247 / volume
248 * np.exp(-k_sq / (4 * alpha**2))
249 / k_sq
250 * np.outer(k_total, k_total)
251 )
252 dipmat += k_prefactor * fourier_factor(np.sum(gvec * Rs, -1))[:, :, None, None]
253 dipmat += -np.eye(len(Rs))[:, :, None, None] * np.diag(
254 np.repeat(4 * alpha**3 / (3 * np.sqrt(np.pi)), 3)
255 )
256 k_sq = np.sum(k_point**2) if k_point is not None else 0
257 if np.sqrt(k_sq) > 1e-15:
258 dipmat += (
259 4
260 * np.pi
261 / volume
262 * np.exp(-k_sq / (4 * alpha**2))
263 / k_sq
264 * np.outer(k_point, k_point)
265 )
266 else:
267 dipmat += np.diag(np.repeat(4 * np.pi / (3 * volume), 3))
268 return dipmat
269
270
271 def supercell_circum(latt, radius):
272 rlatt = 2 * np.pi * np.linalg.inv(latt.T)
273 layer_sep = np.sum(latt * rlatt / np.sqrt(np.sum(rlatt**2, 1))[None, :], 0)
274 return np.ceil(radius / layer_sep + 0.5).astype(int)
275
276
277 def damping_fermi(R, S_vdw, d):
278 return 1 / (1 + np.exp(-d * (R / S_vdw - 1)))
279
280
281 def T_bare(R):
282 R_2 = np.sum(R**2, -1)
283 R_5 = np.where(R_2 > 0, np.sqrt(R_2) ** 5, np.inf)
284 return (
285 -3 * R[:, :, :, None] * R[:, :, None, :]
286 + R_2[:, :, None, None] * np.eye(3)[None, None, :, :]
287 ) / R_5[:, :, None, None]
288
289
290 def T_erf_coulomb(R, sigma):
291 bare = T_bare(R)
292 R_1 = np.sqrt(np.sum(R**2, -1))
293 R_5 = np.where(R_1 > 0, R_1**5, np.inf)
294 RR_R5 = R[:, :, :, None] * R[:, :, None, :] / R_5[:, :, None, None]
295 zeta = R_1 / sigma
296 theta = 2 * zeta / np.sqrt(np.pi) * np.exp(-(zeta**2))
297 erf_theta = erf(zeta) - theta
298 return (
299 erf_theta[:, :, None, None] * bare
300 + (2 * (zeta**2) * theta)[:, :, None, None] * RR_R5
301 )
302
303
304 def T_erfc(R, a):
305 R_2 = np.sum(R**2, -1)
306 R_1 = np.sqrt(R_2)
307 R_3 = np.where(R_1 > 0, R_1**3, np.inf)
308 R_5 = np.where(R_1 > 0, R_1**5, np.inf)
309 B = (
310 erfc(a * R_1) + (2 * a * R_1 / np.sqrt(np.pi)) * np.exp(-((a * R_1) ** 2))
311 ) / R_3
312 C = (
313 3 * erfc(a * R_1)
314 + (2 * a * R_1 / np.sqrt(np.pi))
315 * (3 + 2 * (a * R_1) ** 2)
316 * np.exp(-((a * R_1) ** 2))
317 ) / R_5
318 return -C[:, :, None, None] * R[:, :, :, None] * R[:, :, None, :] + B[
319 :, :, None, None
320 ] * np.eye(3)
321
322
323 def from_volumes(species, volumes, kind='TS'):
324 r"""Scale free-atom vdW parameters by Hirshfeld volume ratios.
325
326 :param array-like species: atom types (elements)
327 :param array-like volumes: ratios of Hirshfeld volumes in molecule and vacuum
328 :param str kind: one of 'TS', 'BG' or 'TSsurf'
329
330 Returns partitioned atomic polarizabilities, :math:`C_6` coefficients, and
331 :math:`R_\mathrm{vdw}` coefficients (a.u.).
332 """
333 if kind == 'TS':
334 alpha_0, C6, R_vdw = (
335 np.array([vdw_params[sp][param] for sp in species])
336 for param in 'alpha_0(TS) C6(TS) R_vdw(TS)'.split()
337 )
338 elif kind == 'BG':
339 alpha_0, C6, R_vdw = (
340 np.array([vdw_params[sp][param] for sp in species])
341 for param in 'alpha_0(BG) C6(BG) R_vdw(TS)'.split()
342 )
343 elif kind == 'TSsurf':
344 alpha_0, C6, R_vdw = (
345 np.array(
346 [
347 vdw_params[sp][param]
348 or vdw_params[sp][param.replace('TSsurf', 'TS')]
349 for sp in species
350 ]
351 )
352 for param in 'alpha_0(TSsurf) C6(TSsurf) R_vdw(TSsurf)'.split()
353 )
354 else:
355 raise ValueError(f'Unkonwn vdW parameter kind: {kind}')
356 volumes = np.array(volumes)
357 alpha_0 *= volumes
358 C6 *= volumes**2
359 R_vdw *= volumes ** (1 / 3)
360 return alpha_0, C6, R_vdw
361
362
363 def get_kpts(lattice, k_grid, shift=0.5):
364 k_grid, lattice = map(np.array, (k_grid, lattice))
365 k_idxs = (np.array(list(product(*map(range, k_grid)))) + shift) / k_grid
366 k_idxs = np.where(k_idxs > 0.5, k_idxs - 1, k_idxs)
367 rlattice = 2 * np.pi * np.linalg.inv(lattice.T)
368 k_points = k_idxs.dot(rlattice)
369 return k_points
370
371
372 def freq_grid(n, L=0.6):
373 x, w = leggauss(n)
374 w = 2 * L / (1 - x) ** 2 * w
375 x = L * (1 + x) / (1 - x)
376 return np.hstack(([0], x[::-1])), np.hstack(([0], w[::-1]))
377
378
379 def _array(obj, *args, **kwargs):
380 if obj is not None:
381 kwargs.setdefault('dtype', float)
382 return np.array(obj, *args, **kwargs)
383
384
385 def _get_vdw_params():
386 csv_lines = (files(__package__) / 'vdw-params.csv').read_text().split('\n')
387 reader = csv.DictReader(csv_lines, quoting=csv.QUOTE_NONNUMERIC)
388 vdw_params = {row.pop('symbol'): row for row in reader}
389 return vdw_params
390
391
392 vdw_params = _get_vdw_params()