Coverage for ase/md/nptberendsen.py: 63.86%
83 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"""Berendsen NPT dynamics class."""
3import warnings
4from typing import IO
6import numpy as np
8from ase import Atoms, units
9from ase.md.nvtberendsen import NVTBerendsen
12class NPTBerendsen(NVTBerendsen):
13 def __init__(
14 self,
15 atoms: Atoms,
16 timestep: float,
17 temperature: float | None = None,
18 *,
19 temperature_K: float | None = None,
20 pressure: float | None = None,
21 pressure_au: float | None = None,
22 taut: float = 0.5e3 * units.fs,
23 taup: float = 1e3 * units.fs,
24 compressibility: float | None = None,
25 compressibility_au: float | None = None,
26 fixcm: bool = True,
27 trajectory: str | None = None,
28 logfile: IO | str | None = None,
29 loginterval: int = 1,
30 append_trajectory: bool = False,
31 ):
32 """Berendsen (constant N, P, T) molecular dynamics.
34 This dynamics scale the velocities and volumes to maintain a constant
35 pressure and temperature. The shape of the simulation cell is not
36 altered, if that is desired use Inhomogenous_NPTBerendsen.
38 Parameters
39 ----------
40 atoms: Atoms object
41 The list of atoms.
43 timestep: float
44 The time step in ASE time units.
46 temperature: float
47 The desired temperature, in Kelvin.
49 temperature_K: float
50 Alias for ``temperature``.
52 pressure: float (deprecated)
53 The desired pressure, in bar (1 bar = 1e5 Pa). Deprecated,
54 use ``pressure_au`` instead.
56 pressure_au: float
57 The desired pressure, in atomic units (eV/Å^3).
59 taut: float
60 Time constant for Berendsen temperature coupling in ASE
61 time units. Default: 0.5 ps.
63 taup: float
64 Time constant for Berendsen pressure coupling. Default: 1 ps.
66 compressibility: float (deprecated)
67 The compressibility of the material, in bar-1. Deprecated,
68 use ``compressibility_au`` instead.
70 compressibility_au: float
71 The compressibility of the material, in atomic units (Å^3/eV).
73 fixcm: bool (optional)
74 If True, the position and momentum of the center of mass is
75 kept unperturbed. Default: True.
77 trajectory: Trajectory object or str (optional)
78 Attach trajectory object. If *trajectory* is a string a
79 Trajectory will be constructed. Use *None* for no
80 trajectory.
82 logfile: file object or str (optional)
83 If *logfile* is a string, a file with that name will be opened.
84 Use '-' for stdout.
86 loginterval: int (optional)
87 Only write a log line for every *loginterval* time steps.
88 Default: 1
90 append_trajectory: boolean (optional)
91 Defaults to False, which causes the trajectory file to be
92 overwriten each time the dynamics is restarted from scratch.
93 If True, the new structures are appended to the trajectory
94 file instead.
96 Physical background and limitations
97 -----------------------------------
99 In Berendsen NPT simulations the velocities are scaled to achieve
100 the desired temperature.
102 The atom positions and the simulation cell are scaled in order
103 to achieve the desired pressure.
105 This method does not result in proper NPT sampling but it usually is
106 sufficiently good in practice (with large `taut` and `taup`).
107 For discussion see the gromacs manual at https://www.gromacs.org
108 or amber at https://ambermd.org.
110 Example
111 --------
112 Room temperature simulation (300 K, 0.1 fs time step, atmospheric
113 pressure):
115 >>> from ase import units
116 >>> from ase.build import bulk
117 >>> from ase.calculators.emt import EMT
118 >>> from ase.md import thermalize_momenta
119 >>> from ase.md.nptberendsen import NPTBerendsen
120 >>> atoms = bulk('Cu', cubic=True)
121 >>> atoms.calc = EMT()
122 >>> thermalize_momenta(atoms, temperature_K=300)
123 >>> dyn = NPTBerendsen(atoms, timestep=0.1 * units.fs,
124 ... temperature_K=300, taut=100 * units.fs,
125 ... pressure_au=1.01325 * units.bar,
126 ... taup=1000 * units.fs,
127 ... compressibility_au=4.57e-5 / units.bar)
128 >>> dyn.run(10)
129 True
130 """
132 NVTBerendsen.__init__(
133 self,
134 atoms,
135 timestep,
136 temperature=temperature,
137 temperature_K=temperature_K,
138 taut=taut,
139 fixcm=fixcm,
140 trajectory=trajectory,
141 logfile=logfile,
142 loginterval=loginterval,
143 append_trajectory=append_trajectory,
144 )
145 self.taup = taup
146 self.pressure = self._process_pressure(pressure, pressure_au)
147 if compressibility is not None and compressibility_au is not None:
148 raise TypeError(
149 "Do not give both 'compressibility' and 'compressibility_au'"
150 )
151 if compressibility is not None:
152 # Specified in bar, convert to atomic units
153 warnings.warn(
154 FutureWarning('Specify the compressibility in atomic units.')
155 )
156 self.set_compressibility(
157 compressibility_au=compressibility / (1e5 * units.Pascal)
158 )
159 else:
160 self.set_compressibility(compressibility_au=compressibility_au)
162 def set_taup(self, taup):
163 self.taup = taup
165 def get_taup(self):
166 return self.taup
168 def set_pressure(
169 self, pressure=None, *, pressure_au=None, pressure_bar=None
170 ):
171 self.pressure = self._process_pressure(
172 pressure, pressure_bar, pressure_au
173 )
175 def get_pressure(self):
176 return self.pressure
178 def set_compressibility(self, *, compressibility_au):
179 self.compressibility = compressibility_au
181 def get_compressibility(self):
182 return self.compressibility
184 def set_timestep(self, timestep):
185 self.dt = timestep
187 def get_timestep(self):
188 return self.dt
190 def scale_positions_and_cell(self):
191 """Do the Berendsen pressure coupling,
192 scale the atom position and the simulation cell."""
194 taupscl = self.dt / self.taup
195 stress = self.atoms.get_stress(voigt=False, include_ideal_gas=True)
196 old_pressure = -stress.trace() / 3
197 scl_pressure = 1.0 - taupscl * self.compressibility / 3.0 * (
198 self.pressure - old_pressure
199 )
201 cell = self.atoms.get_cell()
202 cell = scl_pressure * cell
203 self.atoms.set_cell(cell, scale_atoms=True)
205 def step(self, forces=None):
206 """move one timestep forward using Berenden NPT molecular dynamics."""
208 NVTBerendsen.scale_velocities(self)
209 self.scale_positions_and_cell()
211 # one step velocity verlet
212 atoms = self.atoms
214 if forces is None:
215 forces = atoms.get_forces(md=True)
217 p = self.atoms.get_momenta()
218 p += 0.5 * self.dt * forces
220 if self.fix_com:
221 # calculate the center of mass
222 # momentum and subtract it
223 psum = p.sum(axis=0) / float(len(p))
224 p = p - psum
226 self.atoms.set_positions(
227 self.atoms.get_positions()
228 + self.dt * p / self.atoms.get_masses()[:, np.newaxis]
229 )
231 # We need to store the momenta on the atoms before calculating
232 # the forces, as in a parallel Asap calculation atoms may
233 # migrate during force calculations, and the momenta need to
234 # migrate along with the atoms. For the same reason, we
235 # cannot use self.masses in the line above.
237 self.atoms.set_momenta(p)
238 forces = self.atoms.get_forces(md=True)
239 atoms.set_momenta(self.atoms.get_momenta() + 0.5 * self.dt * forces)
241 return forces
243 def _process_pressure(self, pressure, pressure_au):
244 """Handle that pressure can be specified in multiple units.
246 For at least a transition period, Berendsen NPT dynamics in ASE can
247 have the pressure specified in either bar or atomic units (eV/Å^3).
249 Two parameters:
251 pressure: None or float
252 The original pressure specification in bar.
253 A warning is issued if this is not None.
255 pressure_au: None or float
256 Pressure in ev/Å^3.
258 Exactly one of the two pressure parameters must be different from
259 None, otherwise an error is issued.
261 Return value: Pressure in eV/Å^3.
262 """
263 if (pressure is not None) + (pressure_au is not None) != 1:
264 raise TypeError(
265 "Exactly one of the parameters 'pressure',"
266 + " and 'pressure_au' must"
267 + ' be given'
268 )
270 if pressure is not None:
271 w = (
272 "The 'pressure' parameter is deprecated, please"
273 + ' specify the pressure in atomic units (eV/Å^3)'
274 + " using the 'pressure_au' parameter."
275 )
276 warnings.warn(FutureWarning(w))
277 return pressure * (1e5 * units.Pascal)
278 else:
279 return pressure_au
282class Inhomogeneous_NPTBerendsen(NPTBerendsen):
283 """Berendsen (constant N, P, T) molecular dynamics.
285 This dynamics scale the velocities and volumes to maintain a constant
286 pressure and temperature. The size of the unit cell is allowed to change
287 independently in the three directions, but the angles remain constant.
289 Usage: NPTBerendsen(atoms, timestep, temperature, taut, pressure, taup)
291 Parameters
292 ----------
293 mask : tuple[int]
294 Specifies which axes participate in the barostat. Default (1, 1, 1)
295 means that all axes participate, set any of them to zero to disable
296 the barostat in that direction.
297 """
299 def __init__(self, *args, mask=(1, 1, 1), **kwargs):
300 NPTBerendsen.__init__(self, *args, **kwargs)
301 self.mask = mask
303 def scale_positions_and_cell(self):
304 """Do the Berendsen pressure coupling,
305 scale the atom position and the simulation cell."""
307 taupscl = self.dt * self.compressibility / self.taup / 3.0
308 stress = -self.atoms.get_stress(include_ideal_gas=True)
309 if stress.shape == (6,):
310 stress = stress[:3]
311 elif stress.shape == (3, 3):
312 stress = [stress[i][i] for i in range(3)]
313 else:
314 raise ValueError(
315 'Cannot use a stress tensor of shape ' + str(stress.shape)
316 )
317 pbc = self.atoms.get_pbc()
318 scl_pressurex = (
319 1.0 - taupscl * (self.pressure - stress[0]) * pbc[0] * self.mask[0]
320 )
321 scl_pressurey = (
322 1.0 - taupscl * (self.pressure - stress[1]) * pbc[1] * self.mask[1]
323 )
324 scl_pressurez = (
325 1.0 - taupscl * (self.pressure - stress[2]) * pbc[2] * self.mask[2]
326 )
327 cell = self.atoms.get_cell()
328 cell = np.array(
329 [
330 scl_pressurex * cell[0],
331 scl_pressurey * cell[1],
332 scl_pressurez * cell[2],
333 ]
334 )
335 self.atoms.set_cell(cell, scale_atoms=True)