Coverage for ase/calculators/vdwcorrection.py: 86.10%
187 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-27 15:21 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-27 15:21 +0000
1"""van der Waals correction schemes for DFT"""
3import numpy as np
4from scipy.special import erfc, erfinv
6from ase.calculators.calculator import Calculator
7from ase.calculators.polarizability import StaticPolarizabilityCalculator
8from ase.neighborlist import neighbor_list
9from ase.parallel import myslice, world
10from ase.units import Bohr, Hartree
11from ase.utils import IOContext
13# dipole polarizabilities and C6 values from
14# X. Chu and A. Dalgarno, J. Chem. Phys. 121 (2004) 4083
15# atomic units, a_0^3
16vdWDB_Chu04jcp = {
17 # Element: [alpha, C6]; units [Bohr^3, Hartree * Bohr^6]
18 'H': [4.5, 6.5], # [exact, Tkatchenko PRL]
19 'He': [1.38, 1.42],
20 'Li': [164, 1392],
21 'Be': [38, 227],
22 'B': [21, 99.5],
23 'C': [12, 46.6],
24 'N': [7.4, 24.2],
25 'O': [5.4, 15.6],
26 'F': [3.8, 9.52],
27 'Ne': [2.67, 6.20],
28 'Na': [163, 1518],
29 'Mg': [71, 626],
30 'Al': [60, 528],
31 'Si': [37, 305],
32 'P': [25, 185],
33 'S': [19.6, 134],
34 'Cl': [15, 94.6],
35 'Ar': [11.1, 64.2],
36 'Ca': [160, 2163],
37 'Sc': [120, 1383],
38 'Ti': [98, 1044],
39 'V': [84, 832],
40 'Cr': [78, 602],
41 'Mn': [63, 552],
42 'Fe': [56, 482],
43 'Co': [50, 408],
44 'Ni': [48, 373],
45 'Cu': [42, 253],
46 'Zn': [40, 284],
47 'As': [29, 246],
48 'Se': [25, 210],
49 'Br': [20, 162],
50 'Kr': [16.7, 130],
51 'Sr': [199, 3175],
52 'Te': [40, 445],
53 'I': [35, 385],
54}
56vdWDB_alphaC6 = vdWDB_Chu04jcp
58# dipole polarizabilities and C6 values from
59# V. G. Ruiz et al. Phys. Rev. Lett 108 (2012) 146103
60# atomic units, a_0^3
61vdWDB_Ruiz12prl = {
62 'Ag': [50.6, 339],
63 'Au': [36.5, 298],
64 'Pd': [23.7, 158],
65 'Pt': [39.7, 347],
66}
68vdWDB_alphaC6.update(vdWDB_Ruiz12prl)
70# C6 values and vdW radii from
71# S. Grimme, J Comput Chem 27 (2006) 1787-1799
72vdWDB_Grimme06jcc = {
73 # Element: [C6, R0]; units [J nm^6 mol^{-1}, Angstrom]
74 'H': [0.14, 1.001],
75 'He': [0.08, 1.012],
76 'Li': [1.61, 0.825],
77 'Be': [1.61, 1.408],
78 'B': [3.13, 1.485],
79 'C': [1.75, 1.452],
80 'N': [1.23, 1.397],
81 'O': [0.70, 1.342],
82 'F': [0.75, 1.287],
83 'Ne': [0.63, 1.243],
84 'Na': [5.71, 1.144],
85 'Mg': [5.71, 1.364],
86 'Al': [10.79, 1.639],
87 'Si': [9.23, 1.716],
88 'P': [7.84, 1.705],
89 'S': [5.57, 1.683],
90 'Cl': [5.07, 1.639],
91 'Ar': [4.61, 1.595],
92 'K': [10.80, 1.485],
93 'Ca': [10.80, 1.474],
94 'Sc': [10.80, 1.562],
95 'Ti': [10.80, 1.562],
96 'V': [10.80, 1.562],
97 'Cr': [10.80, 1.562],
98 'Mn': [10.80, 1.562],
99 'Fe': [10.80, 1.562],
100 'Co': [10.80, 1.562],
101 'Ni': [10.80, 1.562],
102 'Cu': [10.80, 1.562],
103 'Zn': [10.80, 1.562],
104 'Ga': [16.99, 1.650],
105 'Ge': [17.10, 1.727],
106 'As': [16.37, 1.760],
107 'Se': [12.64, 1.771],
108 'Br': [12.47, 1.749],
109 'Kr': [12.01, 1.727],
110 'Rb': [24.67, 1.628],
111 'Sr': [24.67, 1.606],
112 'Y-Cd': [24.67, 1.639],
113 'In': [37.32, 1.672],
114 'Sn': [38.71, 1.804],
115 'Sb': [38.44, 1.881],
116 'Te': [31.74, 1.892],
117 'I': [31.50, 1.892],
118 'Xe': [29.99, 1.881],
119}
122# Optimal range parameters sR for different XC functionals
123# to be used with the Tkatchenko-Scheffler scheme
124# Reference: M.A. Caro arXiv:1704.00761 (2017)
125sR_opt = {
126 'PBE': 0.940,
127 'RPBE': 0.590,
128 'revPBE': 0.585,
129 'PBEsol': 1.055,
130 'BLYP': 0.625,
131 'AM05': 0.840,
132 'PW91': 0.965,
133}
136def get_logging_file_descriptor(calculator):
137 if hasattr(calculator, 'log'):
138 fd = calculator.log
139 if hasattr(fd, 'write'):
140 return fd
141 if hasattr(fd, 'fd'):
142 return fd.fd
143 if hasattr(calculator, 'txt'):
144 return calculator.txt
147class vdWTkatchenko09prl(Calculator, IOContext):
148 """vdW correction after Tkatchenko and Scheffler PRL 102 (2009) 073005."""
150 def __init__(
151 self,
152 hirshfeld=None,
153 vdwradii=None,
154 calculator=None,
155 Rmax=10.0, # maximal radius for periodic calculations
156 Ldecay=1.0, # decay length for smoothing in periodic calcs
157 vdWDB_alphaC6=vdWDB_alphaC6,
158 txt=None,
159 sR=None,
160 comm=world,
161 ):
162 """Constructor
164 Parameters
165 ----------
166 hirshfeld: the Hirshfeld partitioning object
167 calculator: the calculator to get the PBE energy
168 """
169 self.hirshfeld = hirshfeld
170 if calculator is None:
171 self.calculator = self.hirshfeld.get_calculator()
172 else:
173 self.calculator = calculator
175 if txt is None:
176 txt = get_logging_file_descriptor(self.calculator)
177 if hasattr(self.calculator, 'world'):
178 self.comm = self.calculator.world
179 else:
180 self.comm = comm # the best we know
181 self.txt = self.openfile(file=txt, comm=self.comm)
183 self.vdwradii = vdwradii
184 self.vdWDB_alphaC6 = vdWDB_alphaC6
185 self.Rmax = Rmax
186 self.Ldecay = Ldecay
187 self.atoms = None
189 if sR is None:
190 try:
191 xc_name = self.calculator.get_xc_functional()
192 self.sR = sR_opt[xc_name]
193 except KeyError:
194 raise ValueError(
195 'Tkatchenko-Scheffler dispersion correction not '
196 + f'implemented for {xc_name} functional'
197 )
198 else:
199 self.sR = sR
200 self.d = 20
202 Calculator.__init__(self)
204 self.parameters['calculator'] = self.calculator.name
205 self.parameters['xc'] = self.calculator.get_xc_functional()
207 @property
208 def implemented_properties(self):
209 return self.calculator.implemented_properties
211 def calculation_required(self, atoms, quantities):
212 if self.calculator.calculation_required(atoms, quantities):
213 return True
214 for quantity in quantities:
215 if quantity not in self.results:
216 return True
217 return False
219 def calculate(self, atoms=None, properties=None, system_changes=None):
220 if system_changes is None:
221 system_changes = []
222 if properties is None:
223 properties = ['energy', 'forces']
224 Calculator.calculate(self, atoms, properties, system_changes)
225 self.update(atoms, properties)
227 def update(self, atoms=None, properties=None):
228 if properties is None:
229 properties = ['energy', 'free_energy', 'forces']
230 if not self.calculation_required(atoms, properties):
231 return
233 if atoms is None:
234 atoms = self.calculator.get_atoms()
236 properties = list(properties)
237 for name in 'energy', 'free_energy', 'forces':
238 if name not in properties:
239 properties.append(name)
241 for name in properties:
242 self.results[name] = self.calculator.get_property(name, atoms)
243 self.parameters['uncorrected_energy'] = self.results['energy']
244 self.atoms = atoms.copy()
246 if self.vdwradii is not None:
247 # external vdW radii
248 vdwradii = self.vdwradii
249 assert len(atoms) == len(vdwradii)
250 else:
251 vdwradii = []
252 for atom in atoms:
253 self.vdwradii.append(vdWDB_Grimme06jcc[atom.symbol][1])
255 if self.hirshfeld is None:
256 volume_ratios = [1.0] * len(atoms)
257 elif hasattr(self.hirshfeld, '__len__'): # a list
258 assert len(atoms) == len(self.hirshfeld)
259 volume_ratios = self.hirshfeld
260 else: # should be an object
261 self.hirshfeld.initialize()
262 volume_ratios = self.hirshfeld.get_effective_volume_ratios()
264 # correction for effective C6
265 na = len(atoms)
266 C6eff_a = np.empty(na)
267 alpha_a = np.empty(na)
268 R0eff_a = np.empty(na)
269 for a, atom in enumerate(atoms):
270 # free atom values
271 alpha_a[a], C6eff_a[a] = self.vdWDB_alphaC6[atom.symbol]
272 # correction for effective C6
273 C6eff_a[a] *= Hartree * volume_ratios[a] ** 2 * Bohr**6
274 R0eff_a[a] = vdwradii[a] * volume_ratios[a] ** (1 / 3.0)
275 C6eff_aa = np.empty((na, na))
276 for a in range(na):
277 for b in range(a, na):
278 C6eff_aa[a, b] = (
279 2
280 * C6eff_a[a]
281 * C6eff_a[b]
282 / (
283 alpha_a[b] / alpha_a[a] * C6eff_a[a]
284 + alpha_a[a] / alpha_a[b] * C6eff_a[b]
285 )
286 )
287 C6eff_aa[b, a] = C6eff_aa[a, b]
289 # New implementation by Miguel Caro
290 # (complaints etc to mcaroba@gmail.com)
291 # If all 3 PBC are False, we do the summation over the atom
292 # pairs in the simulation box. If any of them is True, we
293 # use the cutoff radius instead
294 pbc_c = atoms.get_pbc()
295 EvdW = 0.0
296 forces = 0.0 * self.results['forces']
297 # PBC: we build a neighbor list according to the Reff criterion
298 if pbc_c.any():
299 # Effective cutoff radius
300 tol = 1.0e-5
301 Reff = self.Rmax + self.Ldecay * erfinv(1.0 - 2.0 * tol)
302 # Build list of neighbors
303 n_list = neighbor_list(
304 quantities='ijdDS', a=atoms, cutoff=Reff, self_interaction=False
305 )
306 atom_list = [[] for _ in range(len(atoms))]
307 d_list = [[] for _ in range(len(atoms))]
308 v_list = [[] for _ in range(len(atoms))]
309 # r_list = [[] for _ in range(0, len(atoms))]
310 # Look for neighbor pairs
311 for k in range(len(n_list[0])):
312 i = n_list[0][k]
313 j = n_list[1][k]
314 dist = n_list[2][k]
315 vect = n_list[3][k] # vect is the distance rj - ri
316 # repl = n_list[4][k]
317 if j >= i:
318 atom_list[i].append(j)
319 d_list[i].append(dist)
320 v_list[i].append(vect)
321 # r_list[i].append( repl )
322 # Not PBC: we loop over all atoms in the unit cell only
323 else:
324 atom_list = []
325 d_list = []
326 v_list = []
327 # r_list = []
328 # Do this to avoid double counting
329 for i in range(len(atoms)):
330 atom_list.append(range(i + 1, len(atoms)))
331 d_list.append(
332 [atoms.get_distance(i, j) for j in range(i + 1, len(atoms))]
333 )
334 v_list.append(
335 [
336 atoms.get_distance(i, j, vector=True)
337 for j in range(i + 1, len(atoms))
338 ]
339 )
340 # r_list.append( [[0,0,0] for j in range(i+1, len(atoms))])
341 # No PBC means we are in the same cell
343 # Here goes the calculation, valid with and without
344 # PBC because we loop over
345 # independent pairwise *interactions*
346 ms = myslice(len(atoms), self.comm)
347 for i in range(len(atoms))[ms]:
348 # for j, r, vect, repl in zip(atom_list[i], d_list[i],
349 # v_list[i], r_list[i]):
350 for j, r, vect in zip(atom_list[i], d_list[i], v_list[i]):
351 r6 = r**6
352 Edamp, Fdamp = self.damping(
353 r, R0eff_a[i], R0eff_a[j], d=self.d, sR=self.sR
354 )
355 if pbc_c.any():
356 smooth = 0.5 * erfc((r - self.Rmax) / self.Ldecay)
357 smooth_der = (
358 -1.0
359 / np.sqrt(np.pi)
360 / self.Ldecay
361 * np.exp(-(((r - self.Rmax) / self.Ldecay) ** 2))
362 )
363 else:
364 smooth = 1.0
365 smooth_der = 0.0
366 # Here we compute the contribution to the energy
367 # Self interactions (only possible in PBC) are double counted.
368 # We correct it here
369 if i == j:
370 EvdW -= (Edamp * C6eff_aa[i, j] / r6) / 2.0 * smooth
371 else:
372 EvdW -= (Edamp * C6eff_aa[i, j] / r6) * smooth
373 # Here we compute the contribution to the forces
374 # We neglect the C6eff contribution to the forces
375 # (which can actually be larger
376 # than the other contributions)
377 # Self interactions do not contribute to the forces
378 if i != j:
379 # Force on i due to j
380 force_ij = (
381 -(
382 (Fdamp - 6 * Edamp / r)
383 * C6eff_aa[i, j]
384 / r6
385 * smooth
386 + (Edamp * C6eff_aa[i, j] / r6) * smooth_der
387 )
388 * vect
389 / r
390 )
391 # Forces go both ways for every interaction
392 forces[i] += force_ij
393 forces[j] -= force_ij
394 EvdW = self.comm.sum_scalar(EvdW)
395 self.comm.sum(forces)
397 self.results['energy'] += EvdW
398 self.results['free_energy'] += EvdW
399 self.results['forces'] += forces
401 if self.txt:
402 print(('\n' + self.__class__.__name__), file=self.txt)
403 print(f'vdW correction: {EvdW}', file=self.txt)
404 print(f'Energy: {self.results["energy"]}', file=self.txt)
405 print('\nForces in eV/Ang:', file=self.txt)
406 symbols = self.atoms.get_chemical_symbols()
407 for ia, symbol in enumerate(symbols):
408 print(
409 '%3d %-2s %10.5f %10.5f %10.5f'
410 % ((ia, symbol) + tuple(self.results['forces'][ia])),
411 file=self.txt,
412 )
413 self.txt.flush()
415 def damping(
416 self,
417 RAB,
418 R0A,
419 R0B,
420 d=20, # steepness of the step function for PBE
421 sR=0.94,
422 ):
423 """Damping factor.
425 Standard values for d and sR as given in
426 Tkatchenko and Scheffler PRL 102 (2009) 073005."""
427 scale = 1.0 / (sR * (R0A + R0B))
428 x = RAB * scale
429 chi = np.exp(-d * (x - 1.0))
430 return 1.0 / (1.0 + chi), d * scale * chi / (1.0 + chi) ** 2
433def calculate_ts09_polarizability(atoms):
434 """Calculate polarizability tensor
436 atoms: Atoms object
437 The atoms object must have a vdWTkatchenko90prl calculator attached.
439 Returns
440 -------
441 polarizability tensor:
442 Unit (e^2 Angstrom^2 / eV).
443 Multiply with Bohr * Ha to get (Angstrom^3)
444 """
445 calc = atoms.calc
446 assert isinstance(calc, vdWTkatchenko09prl)
447 atoms.get_potential_energy()
449 volume_ratios = calc.hirshfeld.get_effective_volume_ratios()
451 na = len(atoms)
452 alpha_a = np.empty(na)
453 alpha_eff_a = np.empty(na)
454 for a, atom in enumerate(atoms):
455 # free atom values
456 alpha_a[a], _ = calc.vdWDB_alphaC6[atom.symbol]
457 # effective polarizability assuming linear combination
458 # of atomic polarizability from ts09
459 alpha_eff_a[a] = volume_ratios[a] * alpha_a[a]
461 alpha = np.sum(alpha_eff_a) * Bohr**2 / Hartree
462 return np.diag([alpha] * 3)
465class TS09Polarizability(StaticPolarizabilityCalculator):
466 """Class interface as expected by Displacement"""
468 def __call__(self, atoms):
469 return calculate_ts09_polarizability(atoms)