Debian Codegraph @

src/pymbd/tensorflow.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 from math import pi
7
8 import numpy as np
9 import tensorflow as tf
10
11 from .pymbd import freq_grid
12
13 __all__ = ()
14
15 pi = tf.constant(pi, tf.float64)
16 ang = 1 / 0.529177249
17
18
19 class MBDEvaluator(object):
20 def __init__(self, gradients=False, **kwargs):
21 self._inputs = coords, alpha_0, C6, R_vdw, beta = [
22 tf.placeholder(tf.float64, shape=shape, name=name)
23 for shape, name in [
24 ((None, 3), 'coords'),
25 ((None,), 'alpha_0'),
26 ((None,), 'C6'),
27 ((None,), 'R_vdw'),
28 ((), 'beta'),
29 ]
30 ]
31 self._output = mbd_energy(*self._inputs, **kwargs)
32 if gradients:
33 self._init_gradients()
34 else:
35 self._gradients = None
36
37 def _init_gradients(self):
38 self._gradients = tf.gradients(self._output, [self._inputs[0]])[0]
39
40 def __call__(self, coords, alpha_0, C6, R_vdw, beta=0.83, gradients=None):
41 inputs = dict(zip(self._inputs, [coords, alpha_0, C6, R_vdw, beta]))
42 outputs = self._output
43 if gradients or gradients is None and self._gradients is not None:
44 if self._gradients is None:
45 self._init_gradients()
46 outputs = outputs, self._gradients
47 return tf.get_default_session().run(outputs, inputs)
48
49
50 def mbd_energy(coords, alpha_0, C6, R_vdw, beta, nfreq=15):
51 freq, freq_w = freq_grid(nfreq)
52 omega = 4 / 3 * C6 / alpha_0**2
53 alpha_dyn = [alpha_0 / (1 + (u / omega) ** 2) for u in freq]
54 alpha_dyn_rsscs = []
55 for a in alpha_dyn:
56 sigma = (tf.sqrt(2 / pi) * a / 3) ** (1 / 3)
57 dipmat = dipole_matrix(
58 coords, 'fermi,dip,gg', sigma=sigma, R_vdw=R_vdw, beta=beta
59 )
60 a_nlc = tf.linalg.inv(tf.diag(_repeat(1 / a, 3)) + dipmat)
61 a_contr = sum(tf.reduce_sum(a_nlc[i::3, i::3], 1) for i in range(3)) / 3
62 alpha_dyn_rsscs.append(a_contr)
63 alpha_dyn_rsscs = tf.stack(alpha_dyn_rsscs)
64 C6_rsscs = 3 / pi * tf.reduce_sum(freq_w[:, None] * alpha_dyn_rsscs**2, 0)
65 R_vdw_rsscs = R_vdw * (alpha_dyn_rsscs[0, :] / alpha_0) ** (1 / 3)
66 omega_rsscs = 4 / 3 * C6_rsscs / alpha_dyn_rsscs[0, :] ** 2
67 dipmat = dipole_matrix(coords, 'fermi,dip', R_vdw=R_vdw_rsscs, beta=beta)
68 pre = _repeat(omega_rsscs * tf.sqrt(alpha_dyn_rsscs[0, :]), 3)
69 eigs = tf.linalg.eigvalsh(
70 tf.diag(_repeat(omega_rsscs**2, 3)) + pre[:, None] * pre[None, :] * dipmat
71 )
72 ene = tf.reduce_sum(tf.sqrt(eigs)) / 2 - 3 * tf.reduce_sum(omega_rsscs) / 2
73 return ene
74
75
76 def dipole_matrix(coords, damping, beta=0.0, R_vdw=None, sigma=None, a=6.0):
77 Rs = coords[:, None, :] - coords[None, :, :]
78 if R_vdw is not None:
79 S_vdw = beta * (R_vdw[:, None] + R_vdw[None, :])
80 # 1e10 rather than inf is necessary to avoid nan gradients
81 dists = tf.sqrt(_set_diag(tf.reduce_sum(Rs**2, -1), 1e10))
82 if sigma is not None:
83 sigmaij = tf.sqrt(sigma[:, None] ** 2 + sigma[None, :] ** 2)
84 if damping == 'fermi,dip':
85 dipmat = damping_fermi(dists, S_vdw, a)[:, :, None, None] * T_bare(Rs)
86 elif damping == 'fermi,dip,gg':
87 dipmat = (1 - damping_fermi(dists, S_vdw, a)[:, :, None, None]) * T_erf_coulomb(
88 Rs, sigmaij
89 )
90 else:
91 raise ValueError(f'Unsupported damping: {damping}')
92 n_atoms = tf.shape(coords)[0]
93 return tf.reshape(tf.transpose(dipmat, (0, 2, 1, 3)), (3 * n_atoms, 3 * n_atoms))
94
95
96 def damping_fermi(R, S_vdw, d):
97 return 1 / (1 + tf.exp(-d * (R / S_vdw - 1)))
98
99
100 def T_bare(R):
101 R_2 = tf.reduce_sum(R**2, -1)
102 # 1e10 rather than inf is necessary to avoid nan gradients
103 R_5 = tf.sqrt(_set_diag(R_2, 1e10)) ** 5
104 return (
105 -3 * R[:, :, :, None] * R[:, :, None, :]
106 + R_2[:, :, None, None] * np.eye(3)[None, None, :, :]
107 ) / R_5[:, :, None, None]
108
109
110 def T_erf_coulomb(R, sigma):
111 bare = T_bare(R)
112 # 1e-10 rather than 0 is necessary to avoid nan gradients from sqrt(0)
113 R_1 = tf.sqrt(_set_diag(tf.reduce_sum(R**2, -1), 1e-10))
114 # 1e10 rather than inf is necessary to avoid nan gradients
115 R_5 = _set_diag(R_1**5, 1e10)
116 RR_R5 = R[:, :, :, None] * R[:, :, None, :] / R_5[:, :, None, None]
117 zeta = R_1 / sigma
118 theta = 2 * zeta / tf.sqrt(pi) * tf.exp(-(zeta**2))
119 erf_theta = tf.erf(zeta) - theta
120 return (
121 erf_theta[:, :, None, None] * bare
122 + (2 * (zeta**2) * theta)[:, :, None, None] * RR_R5
123 )
124
125
126 def _set_diag(A, val):
127 return tf.matrix_set_diag(A, tf.fill(tf.shape(A)[0:1], tf.cast(val, tf.float64)))
128
129
130 def _repeat(a, n):
131 return tf.reshape(tf.tile(a[:, None], (1, n)), (-1,))