Coverage for ase/calculators/harmonic.py: 96.99%
166 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
1import numpy as np
2from numpy.linalg import eigh, norm, pinv
3from scipy.linalg import lstsq # performs better than numpy.linalg.lstsq
5from ase import units
6from ase.calculators.calculator import (
7 BaseCalculator,
8 CalculationFailed,
9 Calculator,
10 CalculatorSetupError,
11 all_changes,
12)
15class HarmonicCalculator(BaseCalculator):
16 """Class for calculations with a Hessian-based harmonic force field.
18 See :class:`HarmonicForceField` and the literature. [1]_
19 """
21 implemented_properties = ['energy', 'forces']
23 def __init__(self, harmonicforcefield):
24 """
25 Parameters
26 ----------
27 harmonicforcefield: :class:`HarmonicForceField`
28 Class for calculations with a Hessian-based harmonic force field.
29 """
30 super().__init__() # parameters have been passed to the force field
31 self.harmonicforcefield = harmonicforcefield
33 def calculate(self, atoms, properties, system_changes):
34 self.atoms = atoms.copy() # for caching of results
35 energy, forces_x = self.harmonicforcefield.get_energy_forces(atoms)
36 self.results['energy'] = energy
37 self.results['forces'] = forces_x
40class HarmonicForceField:
41 def __init__(
42 self,
43 ref_atoms,
44 hessian_x,
45 ref_energy=0.0,
46 get_q_from_x=None,
47 get_jacobian=None,
48 cartesian=True,
49 variable_orientation=False,
50 hessian_limit=0.0,
51 constrained_q=None,
52 rcond=1e-7,
53 zero_thresh=0.0,
54 ):
55 """Class that represents a Hessian-based harmonic force field.
57 Energy and forces of this force field are based on the
58 Cartesian Hessian for a local reference configuration, i.e. if
59 desired, on the Hessian matrix transformed to a user-defined
60 coordinate system. The required Hessian has to be passed as
61 an argument, e.g. predetermined numerically via central finite
62 differences in Cartesian coordinates. Note that a potential
63 being harmonic in Cartesian coordinates **x** is not
64 necessarily equivalently harmonic in another coordinate system
65 **q**, e.g. when the transformation between the coordinate
66 systems is non-linear. By default, the force field is
67 evaluated in Cartesian coordinates in which energy and forces
68 are not rotationally and translationally invariant. Systems
69 with variable orientation, require rotationally and
70 translationally invariant calculations for which a set of
71 appropriate coordinates has to be defined. This can be a set
72 of (redundant) internal coordinates (bonds, angles, dihedrals,
73 coordination numbers, ...) or any other user-defined
74 coordinate system.
76 Together with the :class:`HarmonicCalculator` this
77 :class:`HarmonicForceField` can be used to compute
78 Anharmonic Corrections to the Harmonic Approximation. [1]_
80 Parameters
81 ----------
82 ref_atoms: :class:`~ase.Atoms` object
83 Reference structure for which energy (``ref_energy``) and Hessian
84 matrix in Cartesian coordinates (``hessian_x``) are provided.
86 hessian_x: numpy array
87 Cartesian Hessian matrix for the reference structure ``ref_atoms``.
88 If a user-defined coordinate system is provided via
89 ``get_q_from_x`` and ``get_jacobian``, the Cartesian Hessian matrix
90 is transformed to the user-defined coordinate system and back to
91 Cartesian coordinates, thereby eliminating rotational and
92 translational traits from the Hessian. The Hessian matrix
93 obtained after this double-transformation is then used as
94 the reference Hessian matrix to evaluate energy and forces for
95 ``cartesian = True``. For ``cartesian = False`` the reference
96 Hessian matrix transformed to the user-defined coordinates is used
97 to compute energy and forces.
99 ref_energy: float
100 Energy of the reference structure ``ref_atoms``, typically in `eV`.
102 get_q_from_x: python function, default: None (Cartesian coordinates)
103 Function that returns a vector of user-defined coordinates **q** for
104 a given :class:`~ase.Atoms` object 'atoms'. The signature should be:
105 :obj:`get_q_from_x(atoms)`.
107 get_jacobian: python function, default: None (Cartesian coordinates)
108 Function that returns the geometric Jacobian matrix of the
109 user-defined coordinates **q** w.r.t. Cartesian coordinates **x**
110 defined as `dq/dx` (Wilson B-matrix) for a given :class:`~ase.Atoms`
111 object 'atoms'. The signature should be: :obj:`get_jacobian(atoms)`.
113 cartesian: bool
114 Set to True to evaluate energy and forces based on the reference
115 Hessian (system harmonic in Cartesian coordinates).
116 Set to False to evaluate energy and forces based on the reference
117 Hessian transformed to user-defined coordinates (system harmonic in
118 user-defined coordinates).
120 hessian_limit: float
121 Reconstruct the reference Hessian matrix with a lower limit for the
122 eigenvalues, typically in `eV/A^2`. Eigenvalues in the interval
123 [``zero_thresh``, ``hessian_limit``] are set to ``hessian_limit``
124 while the eigenvectors are left untouched.
126 variable_orientation: bool
127 Set to True if the investigated :class:`~ase.Atoms` has got
128 rotational degrees of freedom such that the orientation with respect
129 to ``ref_atoms`` might be different (typically for molecules).
130 Set to False to speed up the calculation when ``cartesian = True``.
132 constrained_q: list
133 A list of indices 'i' of constrained coordinates `q_i` to be
134 projected out from the Hessian matrix
135 (e.g. remove forces along imaginary mode of a transition state).
137 rcond: float
138 Cutoff for singular value decomposition in the computation of the
139 Moore-Penrose pseudo-inverse during transformation of the Hessian
140 matrix. Equivalent to the rcond parameter in scipy.linalg.lstsq.
142 zero_thresh: float
143 Reconstruct the reference Hessian matrix with absolute eigenvalues
144 below this threshold set to zero.
146 """
147 self.check_input(
148 [get_q_from_x, get_jacobian], variable_orientation, cartesian
149 )
151 self.parameters = {
152 'ref_atoms': ref_atoms,
153 'ref_energy': ref_energy,
154 'hessian_x': hessian_x,
155 'hessian_limit': hessian_limit,
156 'get_q_from_x': get_q_from_x,
157 'get_jacobian': get_jacobian,
158 'cartesian': cartesian,
159 'variable_orientation': variable_orientation,
160 'constrained_q': constrained_q,
161 'rcond': rcond,
162 'zero_thresh': zero_thresh,
163 }
165 # set up user-defined coordinate system or Cartesian coordinates
166 self.get_q_from_x = self.parameters['get_q_from_x'] or (
167 lambda atoms: atoms.get_positions()
168 )
169 self.get_jacobian = self.parameters['get_jacobian'] or (
170 lambda atoms: np.diagflat(np.ones(3 * len(atoms)))
171 )
173 # reference Cartesian coords. x0; reference user-defined coords. q0
174 self.x0 = self.parameters['ref_atoms'].get_positions().ravel()
175 self.q0 = self.get_q_from_x(self.parameters['ref_atoms']).ravel()
176 self.setup_reference_hessians() # self._hessian_x and self._hessian_q
178 # store number of zero eigenvalues of G-matrix for redundancy check
179 jac0 = self.get_jacobian(self.parameters['ref_atoms'])
180 Gmat = jac0.T @ jac0
181 self.Gmat_eigvals, _ = eigh(Gmat) # stored for inspection purposes
182 self.zero_eigvals = len(
183 np.flatnonzero(
184 np.abs(self.Gmat_eigvals) < self.parameters['zero_thresh']
185 )
186 )
188 @staticmethod
189 def check_input(coord_functions, variable_orientation, cartesian):
190 if None in coord_functions:
191 if not all(func is None for func in coord_functions):
192 msg = (
193 'A user-defined coordinate system requires both '
194 '`get_q_from_x` and `get_jacobian`.'
195 )
196 raise CalculatorSetupError(msg)
197 if variable_orientation:
198 msg = (
199 'The use of `variable_orientation` requires a '
200 'user-defined, translationally and rotationally '
201 'invariant coordinate system.'
202 )
203 raise CalculatorSetupError(msg)
204 if not cartesian:
205 msg = (
206 'A user-defined coordinate system is required for '
207 'calculations with cartesian=False.'
208 )
209 raise CalculatorSetupError(msg)
211 def setup_reference_hessians(self):
212 """Prepare projector to project out constrained user-defined coordinates
213 **q** from Hessian. Then do transformation to user-defined coordinates
214 and back. Relevant literature:
215 * Peng, C. et al. J. Comput. Chem. 1996, 17 (1), 49-56.
216 * Baker, J. et al. J. Chem. Phys. 1996, 105 (1), 192–212."""
217 jac0 = self.get_jacobian(
218 self.parameters['ref_atoms']
219 ) # Jacobian (dq/dx)
220 jac0 = self.constrain_jac(jac0) # for reference Cartesian coordinates
221 ijac0 = self.get_ijac(jac0, self.parameters['rcond'])
222 self.transform2reference_hessians(jac0, ijac0) # perform projection
224 def constrain_jac(self, jac):
225 """Procedure by Peng, Ayala, Schlegel and Frisch adjusted for redundant
226 coordinates.
227 Peng, C. et al. J. Comput. Chem. 1996, 17 (1), 49–56.
228 """
229 proj = jac @ jac.T # build non-redundant projector
230 constrained_q = self.parameters['constrained_q'] or []
231 Cmat = np.zeros(proj.shape) # build projector for constraints
232 Cmat[constrained_q, constrained_q] = 1.0
233 proj = proj - proj @ Cmat @ pinv(Cmat @ proj @ Cmat) @ Cmat @ proj
234 jac = pinv(jac) @ proj # come back to redundant projector
235 return jac.T
237 def transform2reference_hessians(self, jac0, ijac0):
238 """Transform Cartesian Hessian matrix to user-defined coordinates
239 and back to Cartesian coordinates. For suitable coordinate systems
240 (e.g. internals) this removes rotational and translational degrees of
241 freedom. Furthermore, apply the lower limit to the force constants
242 and reconstruct Hessian matrix."""
243 hessian_x = self.parameters['hessian_x']
244 hessian_x = 0.5 * (hessian_x + hessian_x.T) # guarantee symmetry
245 hessian_q = ijac0.T @ hessian_x @ ijac0 # forward transformation
246 hessian_x = jac0.T @ hessian_q @ jac0 # backward transformation
247 hessian_x = 0.5 * (hessian_x + hessian_x.T) # guarantee symmetry
248 w, v = eigh(hessian_x) # rot. and trans. degrees of freedom are removed
249 w[np.abs(w) < self.parameters['zero_thresh']] = 0.0 # noise-cancelling
250 w[(w > 0.0) & (w < self.parameters['hessian_limit'])] = self.parameters[
251 'hessian_limit'
252 ]
253 # reconstruct Hessian from new eigenvalues and preserved eigenvectors
254 hessian_x = v @ np.diagflat(w) @ v.T # v.T == inv(v) due to symmetry
255 self._hessian_x = 0.5 * (hessian_x + hessian_x.T) # guarantee symmetry
256 self._hessian_q = ijac0.T @ self._hessian_x @ ijac0
258 @staticmethod
259 def get_ijac(jac, rcond): # jac is the Wilson B-matrix
260 """Compute Moore-Penrose pseudo-inverse of Wilson B-matrix."""
261 jac_T = jac.T # btw. direct Jacobian inversion is slow, hence form Gmat
262 Gmat = jac_T @ jac # avoid: numpy.linalg.pinv(Gmat, rcond) @ jac_T
263 ijac = lstsq(Gmat, jac_T, rcond, lapack_driver='gelsy')
264 return ijac[0] # [-1] would be eigenvalues of Gmat
266 def get_energy_forces(self, atoms):
267 """Return a tuple with energy and forces in Cartesian coordinates for
268 a given :class:`~ase.Atoms` object."""
269 q = self.get_q_from_x(atoms).ravel()
271 if self.parameters['cartesian']:
272 x = atoms.get_positions().ravel()
273 x0 = self.x0
274 hessian_x = self._hessian_x
276 if self.parameters['variable_orientation']:
277 # determine x0 for present orientation
278 x0 = self.back_transform(x, q, self.q0, atoms.copy())
279 ref_atoms = atoms.copy()
280 ref_atoms.set_positions(x0.reshape(int(len(x0) / 3), 3))
281 x0 = ref_atoms.get_positions().ravel()
282 # determine jac0 for present orientation
283 jac0 = self.get_jacobian(ref_atoms)
284 self.check_redundancy(jac0) # check for coordinate failure
285 # determine hessian_x for present orientation
286 hessian_x = jac0.T @ self._hessian_q @ jac0
288 xdiff = x - x0
289 forces_x = -hessian_x @ xdiff
290 energy = -0.5 * (forces_x * xdiff).sum()
292 else:
293 jac = self.get_jacobian(atoms)
294 self.check_redundancy(jac) # check for coordinate failure
295 qdiff = q - self.q0
296 forces_q = -self._hessian_q @ qdiff
297 forces_x = forces_q @ jac
298 energy = -0.5 * (forces_q * qdiff).sum()
300 energy += self.parameters['ref_energy']
301 forces_x = forces_x.reshape(int(forces_x.size / 3), 3)
302 return energy, forces_x
304 def back_transform(self, x, q, q0, atoms_copy):
305 """Find the right orientation in Cartesian reference coordinates."""
306 xk = 1 * x
307 qk = 1 * q
308 dq = qk - q0
309 err = abs(dq).max()
310 count = 0
311 atoms_copy.set_constraint() # helpful for back-transformation
312 while err > 1e-7: # back-transformation tolerance for convergence
313 count += 1
314 if count > 99: # maximum number of iterations during back-transf.
315 msg = (
316 'Back-transformation from user-defined to Cartesian '
317 'coordinates failed.'
318 )
319 raise CalculationFailed(msg)
320 jac = self.get_jacobian(atoms_copy)
321 ijac = self.get_ijac(jac, self.parameters['rcond'])
322 dx = ijac @ dq
323 xk = xk - dx
324 atoms_copy.set_positions(xk.reshape(int(len(xk) / 3), 3))
325 qk = self.get_q_from_x(atoms_copy).ravel()
326 dq = qk - q0
327 err = abs(dq).max()
328 return xk
330 def check_redundancy(self, jac):
331 """Compare number of zero eigenvalues of G-matrix to initial number."""
332 Gmat = jac.T @ jac
333 self.Gmat_eigvals, _ = eigh(Gmat)
334 zero_eigvals = len(
335 np.flatnonzero(
336 np.abs(self.Gmat_eigvals) < self.parameters['zero_thresh']
337 )
338 )
339 if zero_eigvals != self.zero_eigvals:
340 raise CalculationFailed(
341 'Suspected coordinate failure: '
342 f'G-matrix has got {zero_eigvals} '
343 'zero eigenvalues, but had '
344 f'{self.zero_eigvals} during setup'
345 )
347 @property
348 def hessian_x(self):
349 return self._hessian_x
351 @property
352 def hessian_q(self):
353 return self._hessian_q
356class SpringCalculator(Calculator):
357 """
358 Spring calculator corresponding to independent oscillators with a fixed
359 spring constant.
362 Energy for an atom is given as
364 E = k / 2 * (r - r_0)**2
366 where k is the spring constant and, r_0 the ideal positions.
369 Parameters
370 ----------
371 ideal_positions : array
372 array of the ideal crystal positions
373 k : float
374 spring constant in eV/Angstrom
375 """
377 implemented_properties = ['forces', 'energy', 'free_energy']
379 def __init__(self, ideal_positions, k):
380 Calculator.__init__(self)
381 self.ideal_positions = ideal_positions.copy()
382 self.k = k
384 def calculate(
385 self, atoms=None, properties=None, system_changes=all_changes
386 ):
387 if properties is None:
388 properties = ['energy']
389 Calculator.calculate(self, atoms, properties, system_changes)
390 energy, forces = self.compute_energy_and_forces(atoms)
391 self.results['energy'], self.results['forces'] = energy, forces
393 def compute_energy_and_forces(self, atoms):
394 disps = atoms.positions - self.ideal_positions
395 forces = -self.k * disps
396 energy = sum(self.k / 2.0 * norm(disps, axis=1) ** 2)
397 return energy, forces
399 def get_free_energy(self, T, method='classical'):
400 """Get analytic vibrational free energy for the spring system.
402 Parameters
403 ----------
404 T : float
405 temperature (K)
406 method : str
407 method for free energy computation; 'classical' or 'QM'.
408 """
409 F = 0.0
410 masses, counts = np.unique(self.atoms.get_masses(), return_counts=True)
411 for m, c in zip(masses, counts):
412 F += c * SpringCalculator.compute_Einstein_solid_free_energy(
413 self.k, m, T, method
414 )
415 return F
417 @staticmethod
418 def compute_Einstein_solid_free_energy(k, m, T, method='classical'):
419 """Get free energy (per atom) for an Einstein crystal.
421 Free energy of a Einstein solid given by classical (1) or QM (2)
422 1. F_E = 3NkbT log( hw/kbT )
423 2. F_E = 3NkbT log( 1-exp(hw/kbT) ) + zeropoint
425 Parameters
426 -----------
427 k : float
428 spring constant (eV/A^2)
429 m : float
430 mass (grams/mole or AMU)
431 T : float
432 temperature (K)
433 method : str
434 method for free energy computation, classical or QM.
436 Returns
437 --------
438 float
439 free energy of the Einstein crystal (eV/atom)
440 """
441 assert method in ['classical', 'QM']
443 hbar = units._hbar * units.J # eV/s
444 m = m / units.kg # mass kg
445 k = k * units.m**2 / units.J # spring constant J/m2
446 omega = np.sqrt(k / m) # angular frequency 1/s
448 if method == 'classical':
449 F_einstein = (
450 3 * units.kB * T * np.log(hbar * omega / (units.kB * T))
451 )
452 elif method == 'QM':
453 log_factor = np.log(1.0 - np.exp(-hbar * omega / (units.kB * T)))
454 F_einstein = 3 * units.kB * T * log_factor + 1.5 * hbar * omega
456 return F_einstein