/
empirical_dispersion.py
327 lines (285 loc) · 13.6 KB
/
empirical_dispersion.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
#
# @BEGIN LICENSE
#
# Psi4: an open-source quantum chemistry software package
#
# Copyright (c) 2007-2019 The Psi4 Developers.
#
# The copyrights for code used from other parties are included in
# the corresponding files.
#
# This file is part of Psi4.
#
# Psi4 is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, version 3.
#
# Psi4 is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License along
# with Psi4; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# @END LICENSE
#
import collections
import numpy as np
from qcelemental.models import ResultInput
import qcengine as qcng
from psi4 import core
from psi4.driver import p4util
from psi4.driver import driver_findif
from psi4.driver.p4util.exceptions import ValidationError
from psi4.driver.qcdb import interface_gcp as gcp
_engine_can_do = collections.OrderedDict([('libdisp', ['d1', 'd2', 'chg', 'das2009', 'das2010']),
('dftd3', ['d2', 'd3zero', 'd3bj', 'd3mzero', 'd3mbj']),
('nl', ['nl']),
('mp2d', ['dmp2']),
]) # yapf: disable
_capable_engines_for_disp = collections.defaultdict(list)
for eng, disps in _engine_can_do.items():
for disp in disps:
_capable_engines_for_disp[disp].append(eng)
class EmpiricalDispersion(object):
"""Lightweight unification of empirical dispersion calculation modes.
Attributes
----------
dashlevel: {'d1', 'd2', 'd3zero', 'd3bj', 'd3mzero', 'd3mbj', 'chg', 'das2009', 'das2010', 'nl', 'dmp2'}
Name of dispersion correction to be applied. Resolved
from `name_hint` and/or `level_hint` into a key of
`empirical_dispersion_resources.dashcoeff`.
dashparams : dict
Complete (number and parameter names vary by `dashlevel`)
set of parameter values defining the flexible parts
of `dashlevel`. Resolved into a complete set (keys of
dashcoeff[dashlevel]['default']) from `name_hint` and/or
`dashcoeff_supplement` and/or user `param_tweaks`.
fctldash : str
If `dashparams` for `dashlevel` corresponds to a defined,
named, untweaked "functional-dashlevel" set, then that
functional. Otherwise, empty string.
description : str
Tagline for dispersion `dashlevel`.
dashlevel_citation : str
Literature reference for dispersion `dashlevel` in general,
*not necessarily* for `dashparams`.
dashparams_citation : str
Literature reference for dispersion parameters, if `dashparams`
corresponds to a defined, named, untweaked "functional-dashlevel"
set with a citation. Otherwise, empty string.
dashcoeff_supplement : dict
See description in `qcengine.programs.empirical_dispersion_resources.from_arrays`. Used
here to "bless" the dispersion definitions attached to
the procedures/dft/*_functionals-defined dictionaries
as legit, non-custom, and of equal validity to
`qcengine.programs.empirical_dispersion_resources.dashcoeff` itself for purposes of
validating `fctldash`.
engine : {'libdisp', 'dftd3', 'nl', 'mp2d'}
Compute engine for dispersion. One of Psi4's internal libdisp
library, Grimme's DFTD3 executable, or nl.
disp : psi4.core.Dispersion
Only present for `engine=libdisp`. Psi4 class instance prepared
to compute dispersion.
ordered_params : list
Fixed-order list of relevant parameters for `dashlevel`. Matches
DFT_DISPERSION_PARAMETERS ordering. Used for printing.
Parameters
----------
name_hint : str, optional
Name of functional (func only, func & disp, or disp only) for
which to compute dispersion (e.g., blyp, BLYP-D2, blyp-d3bj,
blyp-d3(bj), hf+d). Any or all parameters initialized from
`dashcoeff[dashlevel][functional-without-dashlevel]` or
`dashcoeff_supplement[dashlevel][functional-with-dashlevel]
can be overwritten via `param_tweaks`.
level_hint : str, optional
Name of dispersion correction to be applied (e.g., d, D2,
d3(bj), das2010). Must be key in `dashcoeff` or "alias" or
"formal" to one.
param_tweaks : list or dict, optional
Values for the same keys as `dashcoeff[dashlevel]['default']`
(and same order if list) used to override any or all values
initialized by `name_hint`. Extra parameters will error.
engine : str, optional
Override which code computes dispersion. See above for allowed
values. Really only relevant for -D2, which can be computed by
libdisp or dftd3.
"""
def __init__(self, name_hint=None, level_hint=None, param_tweaks=None, **kwargs):
from .dft import dashcoeff_supplement
self.dashcoeff_supplement = dashcoeff_supplement
resolved = qcng.programs.empirical_dispersion_resources.from_arrays(
name_hint=name_hint,
level_hint=level_hint,
param_tweaks=param_tweaks,
dashcoeff_supplement=self.dashcoeff_supplement)
self.fctldash = resolved['fctldash']
self.dashlevel = resolved['dashlevel']
self.dashparams = resolved['dashparams']
self.description = qcng.programs.empirical_dispersion_resources.dashcoeff[self.dashlevel]['description']
self.ordered_params = qcng.programs.empirical_dispersion_resources.dashcoeff[self.dashlevel]['default'].keys()
self.dashlevel_citation = qcng.programs.empirical_dispersion_resources.dashcoeff[self.dashlevel]['citation']
self.dashparams_citation = resolved['dashparams_citation']
engine = kwargs.pop('engine', None)
if engine is None:
self.engine = _capable_engines_for_disp[self.dashlevel][0]
else:
if self.dashlevel in _engine_can_do[engine]:
self.engine = engine
else:
raise ValidationError("""This little engine ({}) can't ({})""".format(engine, self.dashlevel))
if self.engine == 'libdisp':
self.disp = core.Dispersion.build(self.dashlevel, **resolved['dashparams'])
def print_out(self):
"""Format dispersion parameters of `self` for output file."""
text = []
text.append(" => {}: Empirical Dispersion <=".format(
(self.fctldash.upper() if self.fctldash.upper() else 'Custom')))
text.append('')
text.append(self.description)
text.append(self.dashlevel_citation.rstrip())
if self.dashparams_citation:
text.append(" Parametrisation from:{}".format(self.dashparams_citation.rstrip()))
text.append('')
for op in self.ordered_params:
text.append(" %6s = %14.6f" % (op, self.dashparams[op]))
text.append('\n')
core.print_out('\n'.join(text))
def compute_energy(self, molecule: 'psi4.core.Molecule', wfn: 'psi4.core.Wavefunction' = None) -> float:
"""Compute dispersion energy based on engine, dispersion level, and parameters in `self`.
Parameters
----------
molecule : psi4.core.Molecule
System for which to compute empirical dispersion correction.
wfn :
Location to set QCVariables
Returns
-------
float
Dispersion energy [Eh].
Notes
-----
DISPERSION CORRECTION ENERGY
Disp always set. Overridden in SCF finalization, but that only changes for "-3C" methods.
self.fctldash + DISPERSION CORRECTION ENERGY
Set if `fctldash` nonempty.
"""
if self.engine in ['dftd3', 'mp2d']:
resi = ResultInput(
**{
'driver': 'energy',
'model': {
'method': self.fctldash,
'basis': '(auto)',
},
'keywords': {
'level_hint': self.dashlevel,
'params_tweaks': self.dashparams,
'dashcoeff_supplement': self.dashcoeff_supplement,
'verbose': 1,
},
'molecule': molecule.to_schema(dtype=2),
'provenance': p4util.provenance_stamp(__name__),
})
jobrec = qcng.compute(resi, self.engine, raise_error=True,
local_options={"scratch_directory": core.IOManager.shared_object().get_default_path()})
dashd_part = float(jobrec.extras['qcvars']['DISPERSION CORRECTION ENERGY'])
if wfn is not None:
for k, qca in jobrec.extras['qcvars'].items():
if 'CURRENT' not in k:
wfn.set_variable(k, p4util.plump_qcvar(qca, k))
if self.fctldash in ['hf3c', 'pbeh3c']:
gcp_part = gcp.run_gcp(molecule, self.fctldash, verbose=False, dertype=0)
dashd_part += gcp_part
return dashd_part
else:
ene = self.disp.compute_energy(molecule)
core.set_variable('DISPERSION CORRECTION ENERGY', ene)
if self.fctldash:
core.set_variable('{} DISPERSION CORRECTION ENERGY'.format(self.fctldash), ene)
return ene
def compute_gradient(self, molecule: 'psi4.core.Molecule',
wfn: 'psi4.core.Wavefunction' = None) -> 'psi4.core.Matrix':
"""Compute dispersion gradient based on engine, dispersion level, and parameters in `self`.
Parameters
----------
molecule : psi4.core.Molecule
System for which to compute empirical dispersion correction.
wfn :
Location to set QCVariables
Returns
-------
psi4.core.Matrix
(nat, 3) dispersion gradient [Eh/a0].
"""
if self.engine in ['dftd3', 'mp2d']:
resi = ResultInput(
**{
'driver': 'gradient',
'model': {
'method': self.fctldash,
'basis': '(auto)',
},
'keywords': {
'level_hint': self.dashlevel,
'params_tweaks': self.dashparams,
'dashcoeff_supplement': self.dashcoeff_supplement,
'verbose': 1,
},
'molecule': molecule.to_schema(dtype=2),
'provenance': p4util.provenance_stamp(__name__),
})
jobrec = qcng.compute(resi, self.engine, raise_error=True,
local_options={"scratch_directory": core.IOManager.shared_object().get_default_path()})
dashd_part = core.Matrix.from_array(
np.array(jobrec.extras['qcvars']['DISPERSION CORRECTION GRADIENT']).reshape(-1, 3))
if wfn is not None:
for k, qca in jobrec.extras['qcvars'].items():
if 'CURRENT' not in k:
wfn.set_variable(k, p4util.plump_qcvar(qca, k))
if self.fctldash in ['hf3c', 'pbeh3c']:
gcp_part = gcp.run_gcp(molecule, self.fctldash, verbose=False, dertype=1)
dashd_part.add(gcp_part)
return dashd_part
else:
return self.disp.compute_gradient(molecule)
def compute_hessian(self, molecule: 'psi4.core.Molecule',
wfn: 'psi4.core.Wavefunction' = None) -> 'psi4.core.Matrix':
"""Compute dispersion Hessian based on engine, dispersion level, and parameters in `self`.
Uses finite difference, as no dispersion engine has analytic second derivatives.
Parameters
----------
molecule : psi4.core.Molecule
System for which to compute empirical dispersion correction.
wfn :
Location to set QCVariables
Returns
-------
psi4.core.Matrix
(3*nat, 3*nat) dispersion Hessian [Eh/a0/a0].
"""
optstash = p4util.OptionsState(['PRINT'], ['PARENT_SYMMETRY'])
core.set_global_option('PRINT', 0)
core.print_out("\n\n Analytical Dispersion Hessians are not supported by dftd3 or gcp.\n")
core.print_out(" Computing the Hessian through finite difference of gradients.\n\n")
# Setup the molecule
molclone = molecule.clone()
molclone.reinterpret_coordentry(False)
molclone.fix_orientation(True)
molclone.fix_com(True)
# Record undisplaced symmetry for projection of diplaced point groups
core.set_global_option("PARENT_SYMMETRY", molecule.schoenflies_symbol())
findif_meta_dict = driver_findif.hessian_from_gradients_geometries(molclone, -1)
for displacement in findif_meta_dict["displacements"].values():
geom_array = np.reshape(displacement["geometry"], (-1, 3))
molclone.set_geometry(core.Matrix.from_array(geom_array))
molclone.update_geometry()
displacement["gradient"] = self.compute_gradient(molclone).np.ravel().tolist()
H = driver_findif.assemble_hessian_from_gradients(findif_meta_dict, -1)
if wfn is not None:
wfn.set_variable('DISPERSION CORRECTION HESSIAN', H)
optstash.restore()
return core.Matrix.from_array(H)