Coverage for ase/md/andersen.py: 98.25%

57 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-11-27 15:21 +0000

1"""Andersen dynamics class.""" 

2 

3from numpy import cos, log, ones, pi, random, repeat 

4 

5from ase import Atoms, units 

6from ase.md.md import MolecularDynamics 

7 

8 

9class Andersen(MolecularDynamics): 

10 """Andersen (constant N, V, T) molecular dynamics. 

11 

12 Andersen, J. Chem. Phys. 72, 2384–2393 (1980). 

13 https://doi.org/10.1063/1.439486 

14 """ 

15 

16 def __init__( 

17 self, 

18 atoms: Atoms, 

19 timestep: float, 

20 temperature_K: float, 

21 andersen_prob: float, 

22 fixcm: bool = True, 

23 rng=random, 

24 **kwargs, 

25 ): 

26 """ 

27 Parameters 

28 ---------- 

29 atoms: Atoms object 

30 The list of atoms. 

31 

32 timestep: float 

33 The time step in ASE time units. 

34 

35 temperature_K: float 

36 The desired temperature, in Kelvin. 

37 

38 andersen_prob: float 

39 A random collision probability, typically 1e-4 to 1e-1. 

40 In each time step, every velocity component of every atom is 

41 replaced by a random one with this probability. 

42 

43 fixcm: bool (optional) 

44 If True, the position and momentum of the center of mass is 

45 kept unperturbed. Default: True. 

46 

47 rng: RNG object, default: ``numpy.random`` 

48 Random number generator. This must have the ``random`` method 

49 with the same signature as ``numpy.random.random``. 

50 

51 **kwargs : dict, optional 

52 Additional arguments passed to 

53 :class:`~ase.md.md.MolecularDynamics` 

54 base class. 

55 

56 Physical background and limitations 

57 ----------------------------------- 

58 

59 The Andersen class implements Andersen dynamics, where constant 

60 temperature is imposed by stochastic collisions with a heat bath. 

61 With a (small) probability (``andersen_prob``) the collisions act 

62 occasionally on velocity components of randomly selected particles. 

63 Upon a collision the new velocity is drawn from the 

64 Maxwell-Boltzmann distribution at the corresponding temperature. 

65 The system is then integrated numerically at constant energy 

66 according to the Newtonian laws of motion. The algorithm generates 

67 a canonical distribution. [1] However, due to the random 

68 decorrelation of velocities, the dynamics are unphysical and 

69 cannot represent dynamical properties like diffusion or viscosity. 

70 Another disadvantage is that the collisions are stochastic in 

71 nature, so repeating the simulation will not give exactly 

72 the same trajectory. 

73 

74 References 

75 ---------- 

76 [1] D. Frenkel and B. Smit, Understanding Molecular Simulation 

77 (Academic Press, London, 1996). 

78 

79 Example 

80 -------- 

81 Room temperature simulation (300 Kelvin, Andersen probability: 0.002): 

82 

83 >>> from ase import units 

84 >>> from ase.build import bulk 

85 >>> from ase.calculators.emt import EMT 

86 >>> from ase.md.andersen import Andersen 

87 >>> atoms = bulk('Cu', cubic=True) 

88 >>> atoms.calc = EMT() 

89 >>> dyn = Andersen(atoms, 5 * units.fs, 300, 0.002) 

90 >>> dyn.run(10) 

91 True 

92 

93 """ 

94 self.temp = units.kB * temperature_K 

95 self.andersen_prob = andersen_prob 

96 self.fix_com = fixcm 

97 self.rng = rng 

98 MolecularDynamics.__init__(self, atoms, timestep, **kwargs) 

99 

100 def set_temperature(self, temperature_K): 

101 self.temp = units.kB * temperature_K 

102 

103 def set_andersen_prob(self, andersen_prob): 

104 self.andersen_prob = andersen_prob 

105 

106 def set_timestep(self, timestep): 

107 self.dt = timestep 

108 

109 def boltzmann_random(self, width, size): 

110 x = self.rng.random(size=size) 

111 y = self.rng.random(size=size) 

112 z = width * cos(2 * pi * x) * (-2 * log(1 - y)) ** 0.5 

113 return z 

114 

115 def get_maxwell_boltzmann_velocities(self): 

116 natoms = len(self.atoms) 

117 masses = repeat(self.masses, 3).reshape(natoms, 3) 

118 width = (self.temp / masses) ** 0.5 

119 velos = self.boltzmann_random(width, size=(natoms, 3)) 

120 return velos # [[x, y, z],] components for each atom 

121 

122 def step(self, forces=None): 

123 atoms = self.atoms 

124 

125 if forces is None: 

126 forces = atoms.get_forces(md=True) 

127 

128 self.v = atoms.get_velocities() 

129 

130 # Random atom-wise variables are stored as attributes and broadcasted: 

131 # - self.random_com_velocity # added to all atoms if self.fix_com 

132 # - self.random_velocity # added to some atoms if the per-atom 

133 # - self.andersen_chance # andersen_chance <= andersen_prob 

134 # a dummy communicator will be used for serial runs 

135 

136 if self.fix_com: 

137 # add random velocity to center of mass to prepare Andersen 

138 width = (self.temp / sum(self.masses)) ** 0.5 

139 self.random_com_velocity = ones( 

140 self.v.shape 

141 ) * self.boltzmann_random(width, (3)) 

142 self.comm.broadcast(self.random_com_velocity, 0) 

143 self.v += self.random_com_velocity 

144 

145 self.v += 0.5 * forces / self.masses * self.dt 

146 

147 # apply Andersen thermostat 

148 self.random_velocity = self.get_maxwell_boltzmann_velocities() 

149 self.andersen_chance = self.rng.random(size=self.v.shape) 

150 self.comm.broadcast(self.random_velocity, 0) 

151 self.comm.broadcast(self.andersen_chance, 0) 

152 self.v[self.andersen_chance <= self.andersen_prob] = ( 

153 self.random_velocity[self.andersen_chance <= self.andersen_prob] 

154 ) 

155 

156 x = atoms.get_positions() 

157 if self.fix_com: 

158 old_com = atoms.get_center_of_mass() 

159 self.v -= self._get_com_velocity(self.v) 

160 # Step: x^n -> x^(n+1) - this applies constraints if any 

161 atoms.set_positions(x + self.v * self.dt) 

162 if self.fix_com: 

163 atoms.set_center_of_mass(old_com) 

164 

165 # recalc velocities after RATTLE constraints are applied 

166 self.v = (atoms.get_positions() - x) / self.dt 

167 forces = atoms.get_forces(md=True) 

168 

169 # Update the velocities 

170 self.v += 0.5 * forces / self.masses * self.dt 

171 

172 if self.fix_com: 

173 self.v -= self._get_com_velocity(self.v) 

174 

175 # Second part of RATTLE taken care of here 

176 atoms.set_momenta(self.v * self.masses) 

177 

178 return forces