Coverage for ase/md/velocitydistribution.py: 83.76%
117 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"""Module for setting up velocity distributions such as Maxwell–Boltzmann.
3Currently, only a few functions are defined, such as
4MaxwellBoltzmannDistribution, which sets the momenta of a list of
5atoms according to a Maxwell-Boltzmann distribution at a given
6temperature.
7"""
9from typing import Literal
11import numpy as np
13from ase import Atoms, units
14from ase.md.md import process_temperature
15from ase.parallel import world
16from ase.utils import deprecated
18# define a ``zero'' temperature to avoid divisions by zero
19eps_temp = 1e-12
22class UnitError(Exception):
23 """Exception raised when wrong units are specified"""
26def force_temperature(
27 atoms: Atoms,
28 temperature: float,
29 unit: Literal['K', 'eV'] = 'K',
30):
31 """
32 Force the temperature of the atomic system to a precise value.
34 This function adjusts the momenta of the atoms to achieve the
35 exact specified temperature, overriding the Maxwell-Boltzmann
36 distribution. The temperature can be specified in either Kelvin
37 (K) or electron volts (eV).
39 Parameters
40 ----------
41 atoms
42 The atomic system represented as an ASE Atoms object.
43 temperature
44 The exact temperature to force for the atomic system.
45 unit
46 The unit of the specified temperature.
47 Can be either 'K' (Kelvin) or 'eV' (electron volts). Default is 'K'.
48 """
50 if unit == 'K':
51 target_temperature = temperature
52 elif unit == 'eV':
53 target_temperature = temperature / units.kB
54 else:
55 raise UnitError(f"'{unit}' is not supported, use 'K' or 'eV'.")
57 temperature_atoms = atoms.get_temperature()
59 if (temperature_atoms < eps_temp) and (target_temperature > 0.0):
60 msg = 'Cannot rescale system at 0 K to finite temperature.'
61 raise RuntimeError(msg)
63 if target_temperature > 0.0:
64 scale = target_temperature / temperature_atoms
65 else:
66 scale = 0.0
68 atoms.set_momenta(atoms.get_momenta() * np.sqrt(scale))
71def _maxwellboltzmanndistribution(masses, temp, comm=world, rng=None):
72 """Return a Maxwell-Boltzmann distribution with a given temperature.
74 Parameters
75 ----------
76 masses: float
77 The atomic masses.
79 temp: float
80 The temperature in electron volt.
82 comm: MPI communicator (optional, default: ase.parallel.world)
83 Communicator used to distribute an identical distribution to all tasks.
85 rng: numpy RNG (optional)
86 The random number generator. Default: np.random
88 Returns
89 -------
90 np.ndarray
91 Maxwell-Boltzmann distributed momenta.
92 """
93 if rng is None:
94 rng = np.random
95 xi = rng.standard_normal((len(masses), 3))
96 comm.broadcast(xi, 0)
97 momenta = xi * np.sqrt(masses * temp)[:, np.newaxis]
98 return momenta
101@deprecated('Use thermalize_momenta', DeprecationWarning)
102def MaxwellBoltzmannDistribution(
103 atoms: Atoms,
104 *,
105 temperature_K: float,
106 comm=world,
107 force_temp: bool = False,
108 rng=None,
109):
110 """Set the atomic momenta to a Maxwell-Boltzmann distribution.
112 .. versionremoved:: 3.29.0
113 The ``temp`` argument is removed. Use ``temperature_K`` instead.
115 .. deprecated:: 3.29.0
116 Use :func:`thermalize_momenta` instead.
118 Parameters
119 ----------
120 atoms: Atoms object
121 The atoms. Their momenta will be modified.
123 temperature_K: float
124 The temperature in Kelvin.
126 comm: MPI communicator, default: :data:`ase.parallel.world`
127 Communicator used to distribute an identical distribution to all tasks.
129 .. versionadded:: 3.26.0
131 .. versionremoved:: 3.29.0
133 ``communicator`` has been removed in favor of ``comm``.
135 force_temp: bool (optional, default: False)
136 If True, the random momenta are rescaled so the kinetic energy is
137 exactly 3/2 N k T. This is a slight deviation from the correct
138 Maxwell-Boltzmann distribution.
140 rng: Numpy RNG (optional)
141 Random number generator. Default: numpy.random
142 If you would like to always get the identical distribution, you can
143 supply a random seed like ``rng=numpy.random.RandomState(seed)``, where
144 seed is an integer.
145 """
146 thermalize_momenta(
147 atoms,
148 temperature_K,
149 comm=comm,
150 exact_temperature=force_temp,
151 rng=rng,
152 )
155def thermalize_momenta(
156 atoms: Atoms,
157 temperature_K: float,
158 *,
159 comm=world,
160 exact_temperature: bool = False,
161 rng=None,
162) -> None:
163 """Set the atomic momenta to a Maxwell-Boltzmann distribution.
165 See :func:`MaxwellBoltzmannDistribution` for details of parameters.
167 .. versionadded:: 3.29.0
169 Parameters
170 ----------
171 atoms: Atoms object
172 The atoms. Their momenta will be modified.
174 temperature_K: float
175 The temperature in Kelvin.
177 comm: MPI communicator, default: :data:`ase.parallel.world`
178 Communicator used to distribute an identical distribution to all tasks.
180 exact_temperature: bool, default: False
181 If True, the random momenta are rescaled so the kinetic energy is
182 exactly 3/2 N k T. This is a slight deviation from the correct
183 Maxwell-Boltzmann distribution.
185 rng: Numpy RNG (optional)
186 Random number generator. Default: numpy.random
187 If you would like to always get the identical distribution, you can
188 supply a random seed like ``rng=numpy.random.RandomState(seed)``, where
189 seed is an integer.
190 """
191 temp = units.kB * temperature_K # K -> eV
192 masses = atoms.get_masses()
193 momenta = _maxwellboltzmanndistribution(masses, temp, comm=comm, rng=rng)
194 atoms.set_momenta(momenta, apply_constraint=True)
195 if exact_temperature:
196 force_temperature(atoms, temperature=temp, unit='eV')
199def Stationary(atoms: Atoms, preserve_temperature: bool = True):
200 "Sets the center-of-mass momentum to zero."
202 # Save initial temperature
203 temp0 = atoms.get_temperature()
205 p = atoms.get_momenta()
206 p0 = np.sum(p, 0)
207 # We should add a constant velocity, not momentum, to the atoms
208 m = atoms.get_masses()
209 mtot = np.sum(m)
210 v0 = p0 / mtot
211 p -= v0 * m[:, np.newaxis]
212 atoms.set_momenta(p)
214 if preserve_temperature:
215 force_temperature(atoms, temp0)
218def ZeroRotation(atoms: Atoms, preserve_temperature: float = True):
219 "Sets the total angular momentum to zero by counteracting rigid rotations."
221 # Save initial temperature
222 temp0 = atoms.get_temperature()
224 # Find the principal moments of inertia and principal axes basis vectors
225 Ip, basis = atoms.get_moments_of_inertia(vectors=True)
226 # Calculate the total angular momentum and transform to principal basis
227 Lp = np.dot(basis, atoms.get_angular_momentum())
228 # Calculate the rotation velocity vector in the principal basis, avoiding
229 # zero division, and transform it back to the cartesian coordinate system
230 omega = np.dot(np.linalg.inv(basis), np.select([Ip > 0], [Lp / Ip]))
231 # We subtract a rigid rotation corresponding to this rotation vector
232 com = atoms.get_center_of_mass()
233 positions = atoms.get_positions()
234 positions -= com # translate center of mass to origin
235 velocities = atoms.get_velocities()
236 atoms.set_velocities(velocities - np.cross(omega, positions))
238 if preserve_temperature:
239 force_temperature(atoms, temp0)
242def n_BE(temp, omega):
243 """Bose-Einstein distribution function.
245 Args:
246 temp: temperature converted to eV (*units.kB)
247 omega: sequence of frequencies converted to eV
249 Returns
250 -------
251 Value of Bose-Einstein distribution function for each energy
253 """
255 omega = np.asarray(omega)
257 # 0K limit
258 if temp < eps_temp:
259 n = np.zeros_like(omega)
260 else:
261 n = 1 / (np.exp(omega / (temp)) - 1)
262 return n
265def phonon_harmonics(
266 force_constants,
267 masses,
268 temp=None,
269 *,
270 temperature_K=None,
271 rng=np.random.rand,
272 quantum=False,
273 plus_minus=False,
274 return_eigensolution=False,
275 failfast=True,
276):
277 r"""Return displacements and velocities that produce a given temperature.
279 Parameters
280 ----------
281 force_constants: array of size 3N x 3N
282 force constants (Hessian) of the system in eV/Ų
284 masses: array of length N
285 masses of the structure in amu
287 temp: float (deprecated)
288 Temperature converted to eV (T * units.kB). Deprecated, use
289 ``temperature_K``.
291 temperature_K: float
292 Temperature in Kelvin.
294 rng: function
295 Random number generator function, e.g., np.random.rand
297 quantum: bool
298 True for Bose-Einstein distribution, False for Maxwell-Boltzmann
299 (classical limit)
301 plus_minus: bool
302 Displace atoms with +/- the amplitude accoding to PRB 94, 075125
304 return_eigensolution: bool
305 return eigenvalues and eigenvectors of the dynamical matrix
307 failfast: bool
308 True for sanity checking the phonon spectrum for negative
309 frequencies at Gamma
311 Returns
312 -------
313 Displacements, velocities generated from the eigenmodes,
314 (optional: eigenvalues, eigenvectors of dynamical matrix)
316 Notes
317 -----
318 Excite phonon modes to specified temperature.
320 This excites all phonon modes randomly so that each contributes,
321 on average, equally to the given temperature. Both potential
322 energy and kinetic energy will be consistent with the phononic
323 vibrations characteristic of the specified temperature.
325 In other words the system will be equilibrated for an MD run at
326 that temperature.
328 force_constants should be the matrix as force constants, e.g.,
329 as computed by the ase.phonons module.
331 Let X_ai be the phonon modes indexed by atom and mode, w_i the
332 phonon frequencies, and let 0 < Q_i <= 1 and 0 <= R_i < 1 be
333 uniformly random numbers. Then
335 .. code-block:: none
338 1/2
339 _ / k T \ --- 1 _ 1/2
340 R += | --- | > --- X (-2 ln Q ) cos (2 pi R )
341 a \ m / --- w ai i i
342 a i i
345 1/2
346 _ / k T \ --- _ 1/2
347 v = | --- | > X (-2 ln Q ) sin (2 pi R )
348 a \ m / --- ai i i
349 a i
351 References
352 ----------
353 D. West and S. K. Estreicher, Phys. Rev. Lett. 96, 115504 (2006).
354 https://doi.org/10.1103/PhysRevLett.96.115504
356 """
358 # Handle the temperature units
359 temp = units.kB * process_temperature(temp, temperature_K, 'eV')
361 # Build dynamical matrix
362 rminv = (masses**-0.5).repeat(3)
363 dynamical_matrix = force_constants * rminv[:, None] * rminv[None, :]
365 # Solve eigenvalue problem to compute phonon spectrum and eigenvectors
366 w2_s, X_is = np.linalg.eigh(dynamical_matrix)
368 # Check for soft modes
369 if failfast:
370 zeros = w2_s[:3]
371 worst_zero = np.abs(zeros).max()
372 if worst_zero > 1e-3:
373 msg = 'Translational deviate from 0 significantly: '
374 raise ValueError(msg + f'{w2_s[:3]}')
376 w2min = w2_s[3:].min()
377 if w2min < 0:
378 msg = 'Dynamical matrix has negative eigenvalues such as '
379 raise ValueError(msg + f'{w2min}')
381 # First three modes are translational so ignore:
382 nw = len(w2_s) - 3
383 n_atoms = len(masses)
384 w_s = np.sqrt(w2_s[3:])
385 X_acs = X_is[:, 3:].reshape(n_atoms, 3, nw)
387 # Assign the amplitudes according to Bose-Einstein distribution
388 # or high temperature (== classical) limit
389 if quantum:
390 hbar = units._hbar * units.J * units.s
391 A_s = np.sqrt(hbar * (2 * n_BE(temp, hbar * w_s) + 1) / (2 * w_s))
392 else:
393 A_s = np.sqrt(temp) / w_s
395 if plus_minus:
396 # create samples by multiplying the amplitude with +/-
397 # according to Eq. 5 in PRB 94, 075125
399 spread = (-1) ** np.arange(nw)
401 # gauge eigenvectors: largest value always positive
402 for ii in range(X_acs.shape[-1]):
403 vec = X_acs[:, :, ii]
404 max_arg = np.argmax(abs(vec))
405 X_acs[:, :, ii] *= np.sign(vec.flat[max_arg])
407 # Create velocities und displacements from the amplitudes and
408 # eigenvectors
409 A_s *= spread
410 phi_s = 2.0 * np.pi * rng(nw)
412 # Assign velocities, sqrt(2) compensates for missing sin(phi) in
413 # amplitude for displacement
414 v_ac = (w_s * A_s * np.sqrt(2) * np.cos(phi_s) * X_acs).sum(axis=2)
415 v_ac /= np.sqrt(masses)[:, None]
417 # Assign displacements
418 d_ac = (A_s * X_acs).sum(axis=2)
419 d_ac /= np.sqrt(masses)[:, None]
421 else:
422 # compute the gaussian distribution for the amplitudes
423 # We need 0 < P <= 1.0 and not 0 0 <= P < 1.0 for the logarithm
424 # to avoid (highly improbable) NaN.
426 # Box Muller [en.wikipedia.org/wiki/Box–Muller_transform]:
427 spread = np.sqrt(-2.0 * np.log(1.0 - rng(nw)))
429 # assign amplitudes and phases
430 A_s *= spread
431 phi_s = 2.0 * np.pi * rng(nw)
433 # Assign velocities and displacements
434 v_ac = (w_s * A_s * np.cos(phi_s) * X_acs).sum(axis=2)
435 v_ac /= np.sqrt(masses)[:, None]
437 d_ac = (A_s * np.sin(phi_s) * X_acs).sum(axis=2)
438 d_ac /= np.sqrt(masses)[:, None]
440 if return_eigensolution:
441 return d_ac, v_ac, w2_s, X_is
442 # else
443 return d_ac, v_ac
446def PhononHarmonics(
447 atoms,
448 force_constants,
449 temp=None,
450 *,
451 temperature_K=None,
452 rng=np.random,
453 quantum=False,
454 plus_minus=False,
455 return_eigensolution=False,
456 failfast=True,
457):
458 r"""Excite phonon modes to specified temperature.
460 This will displace atomic positions and set the velocities so as
461 to produce a random, phononically correct state with the requested
462 temperature.
464 Parameters
465 ----------
466 atoms: :class:`~ase.Atoms`
467 Positions and momenta of this object are perturbed.
469 force_constants: ndarray of size 3N x 3N
470 Force constants for the the structure represented by atoms in eV/Ų
472 temp: float (deprecated).
473 Temperature in eV. Deprecated, use ``temperature_K`` instead.
475 temperature_K: float
476 Temperature in Kelvin.
478 rng: Random number generator
479 RandomState or other random number generator, e.g., np.random.rand
481 quantum: bool
482 True for Bose-Einstein distribution, False for Maxwell-Boltzmann
483 (classical limit)
485 failfast: bool
486 True for sanity checking the phonon spectrum for negative frequencies
487 at Gamma.
489 """
491 # Receive displacements and velocities from phonon_harmonics()
492 d_ac, v_ac = phonon_harmonics(
493 force_constants=force_constants,
494 masses=atoms.get_masses(),
495 temp=temp,
496 temperature_K=temperature_K,
497 rng=rng.rand,
498 plus_minus=plus_minus,
499 quantum=quantum,
500 failfast=failfast,
501 return_eigensolution=False,
502 )
504 # Assign new positions (with displacements) and velocities
505 atoms.positions += d_ac
506 atoms.set_velocities(v_ac)