Debian Codegraph @

src/pymbd/utils.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 numpy as np
7
8 __all__ = ()
9
10
11 def numerical_gradients(geom, func, *args, delta=1e-3, **kwargs):
12 steps, diff = finite_diff_gen(kwargs.pop('npts', 5))
13 coords_0 = geom.coords
14 gradients = np.zeros(coords_0.shape)
15 for i_atom in range(coords_0.shape[0]):
16 for i_xyz in range(3):
17 ene = {}
18 for step in steps:
19 coords = coords_0.copy()
20 coords[i_atom, i_xyz] += step * delta
21 geom.coords = coords
22 ene[step] = getattr(geom, func)(*args, **kwargs)
23 gradients[i_atom, i_xyz] = diff(ene, delta)
24 return gradients
25
26
27 def numerical_latt_gradients(geom, func, *args, **kwargs):
28 delta = kwargs.pop('delta', 1e-3)
29 steps, diff = finite_diff_gen(kwargs.pop('npts', 5))
30 lattice_0 = geom.lattice
31 gradients = np.zeros((3, 3))
32 for i_vec in range(3):
33 for i_xyz in range(3):
34 ene = {}
35 for step in steps:
36 lattice = lattice_0.copy()
37 lattice[i_vec, i_xyz] += step * delta
38 geom.lattice = lattice
39 ene[step] = getattr(geom, func)(*args, **kwargs)
40 gradients[i_vec, i_xyz] = diff(ene, delta)
41 return gradients
42
43
44 def _diff3(x, delta):
45 return (-1.0 / 2 * x[-1] + 1.0 / 2 * x[1]) / delta
46
47
48 def _diff5(x, delta):
49 return (
50 1.0 / 12 * x[-2] - 2.0 / 3 * x[-1] + 2.0 / 3 * x[1] - 1.0 / 12 * x[2]
51 ) / delta
52
53
54 def finite_diff_gen(npts):
55 return {3: ([-1, 1], _diff3), 5: ([-2, -1, 1, 2], _diff5)}[npts]