Coverage for ase/md/md.py: 84.62%
65 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"""Molecular Dynamics."""
3import warnings
4from typing import IO
6import numpy as np
8from ase import Atoms, units
9from ase.md.logger import MDLogger
10from ase.optimize.optimize import BaseDynamics
13def process_temperature(
14 temperature: float | None,
15 temperature_K: float | None,
16 orig_unit: str,
17) -> float:
18 """Handle that temperature can be specified in multiple units.
20 For at least a transition period, molecular dynamics in ASE can
21 have the temperature specified in either Kelvin or Electron
22 Volt. The different MD algorithms had different defaults, by
23 forcing the user to explicitly choose a unit we can resolve
24 this. Using the original method then will issue a
25 FutureWarning.
27 Four parameters:
29 temperature: None or float
30 The original temperature specification in whatever unit was
31 historically used. A warning is issued if this is not None and
32 the historical unit was eV.
34 temperature_K: None or float
35 Temperature in Kelvin.
37 orig_unit: str
38 Unit used for the `temperature`` parameter. Must be 'K' or 'eV'.
40 Exactly one of the two temperature parameters must be different from
41 None, otherwise an error is issued.
43 Return value: Temperature in Kelvin.
44 """
45 if (temperature is not None) + (temperature_K is not None) != 1:
46 raise TypeError(
47 "Exactly one of the parameters 'temperature',"
48 + " and 'temperature_K', must be given"
49 )
50 if temperature is not None:
51 w = "Specify the temperature in K using the 'temperature_K' argument"
52 if orig_unit == 'K':
53 return temperature
54 elif orig_unit == 'eV':
55 warnings.warn(FutureWarning(w))
56 return temperature / units.kB
57 else:
58 raise ValueError('Unknown temperature unit ' + orig_unit)
60 assert temperature_K is not None
61 return temperature_K
64class MolecularDynamics(BaseDynamics):
65 """Base-class for all MD classes."""
67 def __init__(
68 self,
69 atoms: Atoms,
70 timestep: float,
71 trajectory: str | None = None,
72 logfile: IO | str | None = None,
73 loginterval: int = 1,
74 **kwargs,
75 ):
76 """Molecular Dynamics object.
78 Parameters
79 ----------
80 atoms : Atoms object
81 The Atoms object to operate on.
83 timestep : float
84 The time step in ASE time units.
86 trajectory : Trajectory object or str
87 Attach trajectory object. If *trajectory* is a string a
88 Trajectory will be constructed. Use *None* for no
89 trajectory.
91 logfile : file object or str (optional)
92 If *logfile* is a string, a file with that name will be opened.
93 Use '-' for stdout.
95 loginterval : int, default: 1
96 Only write a log line for every *loginterval* time steps.
98 kwargs : dict, optional
99 Extra arguments passed to :class:`~ase.optimize.optimize.Dynamics`.
100 """
101 # dt as to be attached _before_ parent class is initialized
102 self.dt = timestep
104 super().__init__(
105 atoms,
106 logfile=None,
107 trajectory=trajectory,
108 loginterval=loginterval,
109 **kwargs,
110 )
112 # Some codes (e.g. Asap) may be using filters to
113 # constrain atoms or do other things. Current state of the art
114 # is that "atoms" must be either Atoms or Filter in order to
115 # work with dynamics.
116 #
117 # In the future, we should either use a special role interface
118 # for MD, or we should ensure that the input is *always* a Filter.
119 # That way we won't need to test multiple cases. Currently,
120 # we do not test /any/ kind of MD with any kind of Filter in ASE.
121 self.atoms = atoms
122 masses = self.atoms.get_masses()
124 if 0 in masses:
125 warnings.warn(
126 'Zero mass encountered in atoms; this will '
127 'likely lead to errors if the massless atoms '
128 'are unconstrained.'
129 )
131 self.masses = masses.reshape((-1, 1))
133 if not self.atoms.has('momenta'):
134 self.atoms.set_momenta(np.zeros([len(self.atoms), 3]))
136 if logfile:
137 logger = self.closelater(
138 MDLogger(dyn=self, atoms=atoms, logfile=logfile, comm=self.comm)
139 )
140 self.attach(logger, loginterval)
142 def todict(self):
143 return {
144 'type': 'molecular-dynamics',
145 'md-type': self.__class__.__name__,
146 'timestep': self.dt,
147 }
149 def irun(self, steps=50):
150 """Run molecular dynamics algorithm as a generator.
152 Parameters
153 ----------
154 steps : int, default=DEFAULT_MAX_STEPS
155 Number of molecular dynamics steps to be run.
157 Yields
158 ------
159 converged : bool
160 True if the maximum number of steps are reached.
161 """
162 # update the maximum number of steps
163 self.max_steps = self.nsteps + steps
165 if self.nsteps == 0:
166 # For historical reasons we do a magical incantation
167 # here with forces, log, observers.
168 self._refresh_properties()
169 self.log()
170 self.call_observers()
172 yield self.nsteps == self.max_steps
174 # run the algorithm until converged or max_steps reached
175 while self.nsteps < self.max_steps:
176 self.step()
177 self.nsteps += 1
178 self._refresh_properties()
179 self.log()
180 self.call_observers()
181 yield self.nsteps == self.max_steps
183 def _refresh_properties(self):
184 """Ensure up-to-date forces/energies are cached
185 for downstream readers (logger, observers).
186 """
187 self.atoms.get_forces()
189 def log(self):
190 # Subclasses can override this.
191 return None
193 def run(self, steps=50):
194 """Run molecular dynamics algorithm.
196 Parameters
197 ----------
198 steps : int, default=DEFAULT_MAX_STEPS
199 Number of molecular dynamics steps to be run.
201 Returns
202 -------
203 converged : bool
204 True if the maximum number of steps are reached.
205 """
206 converged = steps == 0
207 for converged in self.irun(steps=steps):
208 pass
209 return converged
211 def get_time(self):
212 return self.nsteps * self.dt
214 def converged(self, gradient=None):
215 """MD is 'converged' when number of maximum steps is reached."""
216 # We take gradient now (due to optimizers). Should refactor.
217 return self.nsteps >= self.max_steps
219 def _get_com_velocity(self, velocity):
220 """Return the center of mass velocity.
221 Internal use only. This function can be reimplemented by Asap.
222 """
223 return np.dot(self.masses.ravel(), velocity) / self.masses.sum()
225 # Make the process_temperature function available to subclasses
226 # as a static method. This makes it easy for MD objects to use
227 # it, while functions in md.velocitydistribution have access to it
228 # as a function.
229 _process_temperature = staticmethod(process_temperature)