Coverage for ase/md/langevin.py: 86.49%
74 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"""Langevin dynamics class."""
3import warnings
5import numpy as np
7from ase import Atoms, units
8from ase.md.md import MolecularDynamics
11class Langevin(MolecularDynamics):
12 """Langevin (constant N, V, T) molecular dynamics."""
14 # Helps Asap doing the right thing. Increment when changing stuff:
15 _lgv_version = 5
17 def __init__(
18 self,
19 atoms: Atoms,
20 timestep: float,
21 temperature: float | None = None,
22 friction: float | None = None,
23 fixcm: bool = True,
24 *,
25 temperature_K: float | None = None,
26 rng=None,
27 **kwargs,
28 ):
29 """
30 Parameters
31 ----------
32 atoms: Atoms object
33 The list of atoms.
35 timestep: float
36 The time step in ASE time units.
38 temperature: float (deprecated)
39 The desired temperature, in electron volt.
41 temperature_K: float
42 The desired temperature, in Kelvin.
44 friction: float
45 A friction coefficient in inverse ASE time units.
46 A typical range is 0.001–0.1 fs\\ :sup:`−1` (1–100 ps\\ :sup:`−1`).
47 For example, set ``0.01 / ase.units.fs`` to provide
48 0.01 fs\\ :sup:`−1` (10 ps\\ :sup:`−1`).
50 fixcm: bool (optional)
51 If True, the position and momentum of the center of mass is
52 kept unperturbed. Default: True.
54 .. deprecated:: 3.28.0
56 The implementation of ``fixcm=True`` does not strictly sample
57 the correct NVT distributions for positions and momenta.
58 The deviations are typically small for large systems but can be
59 more pronounced for small systems.
61 Use :class:`~ase.constraints.FixCom` instead.
62 ``fixcm`` will be removed from ASE in the near future.
64 rng: RNG object (optional)
65 Random number generator, by default numpy.random. Must have a
66 standard_normal method matching the signature of
67 numpy.random.standard_normal.
69 **kwargs : dict, optional
70 Additional arguments passed to
71 :class:`~ase.md.md.MolecularDynamics` base class.
73 Notes
74 -----
75 The temperature and friction are normally scalars, but in principle one
76 quantity per atom could be specified by giving an array.
77 This is mostly useful for the friction, where one can choose
78 a rather high friction near the boundaries, and set it to
79 zero in the part of the system where the phenomenon being
80 studied is located.
82 RATTLE constraints can be used with these propagators, see:
83 E. V.-Eijnden, and G. Ciccotti, Chem. Phys. Lett. 429, 310 (2006)
85 The propagator is Equation 23 (Eq. 39 if RATTLE constraints are used)
86 of the above reference. That reference also contains another
87 propagator in Eq. 21/34; but that propagator is not quasi-symplectic
88 and gives a systematic offset in the temperature at large time steps.
90 Physical background and limitations
91 -----------------------------------
93 The Langevin class implements Langevin dynamics, where a (small)
94 friction term and a fluctuating force are added to Newton's second law
95 which is then integrated numerically. The temperature of the heat
96 bath and magnitude of the friction are specified by the user, the
97 amplitude of the fluctuating force is then calculated to give that
98 temperature. This procedure has some physical justification: in a
99 real metal the atoms are (weakly) coupled to the electron gas, and the
100 electron gas therefore acts like a heat bath for the atoms. If heat
101 is produced locally, the atoms locally get a temperature that is
102 higher than the temperature of the electrons, heat is transferred to
103 the electrons and then rapidly transported away by them. A Langevin
104 equation is probably a reasonable model for this process.
106 A disadvantage of using Langevin dynamics is that if significant heat
107 is produced in the simulation, then the temperature will stabilize at
108 a value higher than the specified temperature of the heat bath, since
109 a temperature difference between the system and the heat bath is
110 necessary to get a finite heat flow. Another disadvantage is that the
111 fluctuating force is stochastic in nature, so repeating the simulation
112 will not give exactly the same trajectory.
114 Example
115 -------
116 >>> from ase import units
117 >>> from ase.build import bulk
118 >>> from ase.calculators.emt import EMT
119 >>> from ase.constraints import FixCom
120 >>> from ase.md.langevin import Langevin
121 >>> atoms = bulk('Cu', cubic=True)
122 >>> atoms.calc = EMT()
123 >>> atoms.set_constraint(FixCom())
124 >>> dyn = Langevin(
125 ... atoms,
126 ... timestep=5.0 * units.fs,
127 ... temperature_K=300,
128 ... friction=0.01 / units.fs,
129 ... fixcm=False,
130 ... )
131 >>> dyn.run(10)
132 True
133 """
134 if friction is None:
135 raise TypeError("Missing 'friction' argument.")
136 self.fr = friction
137 self.temp = units.kB * self._process_temperature(
138 temperature, temperature_K, 'eV'
139 )
141 if fixcm:
142 msg = (
143 'The implementation of `fixcm=True` in `Langevin` does not '
144 'strictly sample the correct NVT distributions. '
145 'The deviations are typically small for large systems but can '
146 'be more pronounced for small systems. '
147 'Use `fixcm=False` together with `ase.constraints.FixCom`. '
148 '`fixcm` is deprecated since ASE 3.28.0 and will be removed in '
149 'a future release.'
150 )
151 warnings.warn(msg, FutureWarning)
152 self.fix_com = fixcm
154 if rng is None:
155 self.rng = np.random
156 else:
157 self.rng = rng
158 MolecularDynamics.__init__(self, atoms, timestep, **kwargs)
159 self.updatevars()
161 def todict(self):
162 d = MolecularDynamics.todict(self)
163 d.update(
164 {
165 'temperature_K': self.temp / units.kB,
166 'friction': self.fr,
167 'fixcm': self.fix_com,
168 }
169 )
170 return d
172 def set_temperature(self, temperature=None, temperature_K=None):
173 self.temp = units.kB * self._process_temperature(
174 temperature, temperature_K, 'eV'
175 )
176 self.updatevars()
178 def set_friction(self, friction):
179 self.fr = friction
180 self.updatevars()
182 def set_timestep(self, timestep):
183 self.dt = timestep
184 self.updatevars()
186 def updatevars(self):
187 dt = self.dt
188 T = self.temp
189 fr = self.fr
190 masses = self.masses
191 sigma = np.sqrt(2 * T * fr / masses)
193 self.c1 = dt / 2.0 - dt * dt * fr / 8.0
194 self.c2 = dt * fr / 2 - dt * dt * fr * fr / 8.0
195 self.c3 = np.sqrt(dt) * sigma / 2.0 - dt**1.5 * fr * sigma / 8.0
196 self.c5 = dt**1.5 * sigma / (2 * np.sqrt(3))
197 self.c4 = fr / 2.0 * self.c5
199 def step(self, forces=None):
200 atoms = self.atoms
201 natoms = len(atoms)
203 if forces is None:
204 forces = atoms.get_forces(md=True)
206 # This velocity as well as rnd_pos, rnd_mom and a few other
207 # variables are stored as attributes, so Asap can do its magic
208 # when atoms migrate between processors.
209 self.v = atoms.get_velocities()
211 xi = self.rng.standard_normal(size=(natoms, 3))
212 eta = self.rng.standard_normal(size=(natoms, 3))
214 # When holonomic constraints for rigid linear triatomic molecules are
215 # present, ask the constraints to redistribute xi and eta within each
216 # triple defined in the constraints. This is needed to achieve the
217 # correct target temperature.
218 for constraint in self.atoms.constraints:
219 if hasattr(constraint, 'redistribute_forces_md'):
220 constraint.redistribute_forces_md(atoms, xi, rand=True)
221 constraint.redistribute_forces_md(atoms, eta, rand=True)
223 self.comm.broadcast(xi, 0)
224 self.comm.broadcast(eta, 0)
226 # To keep the center of mass stationary, we have to calculate
227 # the random perturbations to the positions and the momenta,
228 # and make sure that they sum to zero. This perturbs the
229 # temperature slightly, and we have to correct.
230 self.rnd_pos = self.c5 * eta
231 self.rnd_vel = self.c3 * xi - self.c4 * eta
232 # https://gitlab.com/ase/ase/-/merge_requests/3986
233 # The implementation of `fixcm=True` does not strictly sample the
234 # correct NVT distributions for positions and momenta.
235 # It is deprecated and will be removed in a future ASE release.
236 if self.fix_com:
237 factor = np.sqrt(natoms / (natoms - 1.0))
238 self.rnd_pos -= self.rnd_pos.sum(axis=0) / natoms
239 self.rnd_vel -= (self.rnd_vel * self.masses).sum(axis=0) / (
240 self.masses * natoms
241 )
242 self.rnd_pos *= factor
243 self.rnd_vel *= factor
245 # First halfstep in the velocity.
246 self.v += (
247 self.c1 * forces / self.masses - self.c2 * self.v + self.rnd_vel
248 )
250 # Full step in positions
251 x = atoms.get_positions()
253 # Step: x^n -> x^(n+1) - this applies constraints if any.
254 atoms.set_positions(x + self.dt * self.v + self.rnd_pos)
256 # recalc velocities after RATTLE constraints are applied
257 self.v = (self.atoms.get_positions() - x - self.rnd_pos) / self.dt
258 forces = atoms.get_forces(md=True)
260 # Update the velocities
261 self.v += (
262 self.c1 * forces / self.masses - self.c2 * self.v + self.rnd_vel
263 )
265 # Second part of RATTLE taken care of here
266 atoms.set_momenta(self.v * self.masses)
268 return forces