Coverage for ase/md/logger.py: 83.05%

59 statements  

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

1"""Logging for molecular dynamics.""" 

2 

3import weakref 

4from typing import IO, Any 

5 

6from ase import Atoms, units 

7from ase.parallel import world 

8from ase.utils import IOContext 

9 

10 

11class MDLogger(IOContext): 

12 """Class for logging molecular dynamics simulations. 

13 

14 A logging mechanism is provided, printing time; total, potential and 

15 kinetic energy; and temperature (calculated from the kinetic energy). 

16 It is enabled by giving the ``logfile`` argument when the dynamics 

17 object is created, ``logfile`` may be an open file, a filename or the 

18 string '-' meaning standard output. By default, a line is printed 

19 for each timestep, specifying the ``loginterval`` argument will change 

20 this to a more reasonable frequency. 

21 

22 The logging can be customized by explicitly attaching an 

23 :class:`MDLogger` to the dynamics object, see the example below. 

24 

25 Parameters 

26 ---------- 

27 dyn : :class:`~ase.md.md.MolecularDynamics` 

28 ASE :class:`~ase.md.md.MolecularDynamics` object. 

29 Only a weak reference is kept. 

30 atoms : :class:`~ase.Atoms` 

31 ASE :class:`~ase.Atoms` object. 

32 logfile : IO | str 

33 File name or open file, "-" meaning standard output. 

34 header : bool, default: :obj:`True` 

35 If :obj:`True`, a header line defining the columns is written when 

36 the logger is created. 

37 stress : bool, default: :obj:`False` 

38 If :obj:`True`, the logger also writes the six components of the 

39 stress tensor, in GPa. 

40 peratom : bool, default: :obj:`False` 

41 If :obj:`True`, the logger writes energies per atom instead of total 

42 energies. 

43 mode : str, default: ``'a'`` 

44 If 'a', append to existing file, if 'w' overwrite 

45 existing file. 

46 comm : MPI communicator, default: :data:`ase.parallel.world` 

47 Only the process with rank 0 writes to the file. 

48 

49 Notes 

50 ----- 

51 Attaching a logger as in the example below does *not* create a cyclic 

52 reference to the dynamics object. 

53 

54 If building your own logging class, be sure not to attach the dynamics 

55 object directly to the logging object. Instead, create a weak reference 

56 using the ``proxy`` method of the ``weakref`` package. See the 

57 :class:`MDLogger` source code for an example. (If this is not done, a 

58 cyclic reference may be created which can cause certain calculators 

59 to not terminate correctly.) 

60 

61 Example 

62 ------- 

63 Skip the header line and write energies per atom instead of total 

64 energies: 

65 

66 >>> from ase import units 

67 >>> from ase.build import bulk 

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

69 >>> from ase.md import MDLogger 

70 >>> from ase.md.verlet import VelocityVerlet 

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

72 >>> atoms.calc = EMT() 

73 >>> dyn = VelocityVerlet(atoms, timestep=2 * units.fs) 

74 >>> dyn.attach(MDLogger(dyn, atoms, 'md.log', header=False, stress=False, 

75 ... peratom=True, mode='a'), interval=1000) 

76 >>> dyn.run(10) # take 10 steps 

77 True 

78 """ 

79 

80 def __init__( 

81 self, 

82 dyn: Any, # not fully annotated so far to avoid a circular import 

83 atoms: Atoms, 

84 logfile: IO | str, 

85 header: bool = True, 

86 stress: bool = False, 

87 peratom: bool = False, 

88 mode: str = 'a', 

89 comm=world, 

90 ): 

91 self.dyn = weakref.proxy(dyn) if hasattr(dyn, 'get_time') else None 

92 self.atoms = atoms 

93 global_natoms = atoms.get_global_number_of_atoms() 

94 self.logfile = self.openfile(file=logfile, mode=mode, comm=comm) 

95 self.stress = stress 

96 self.peratom = peratom 

97 if self.dyn is not None: 

98 self.hdr = '%-9s ' % ('Time[ps]',) 

99 self.fmt = '%-10.4f ' 

100 else: 

101 self.hdr = '' 

102 self.fmt = '' 

103 if self.peratom: 

104 self.hdr += '%12s %12s %12s %6s' % ( 

105 'Etot/N[eV]', 

106 'Epot/N[eV]', 

107 'Ekin/N[eV]', 

108 'T[K]', 

109 ) 

110 self.fmt += '%12.4f %12.4f %12.4f %6.1f' 

111 else: 

112 self.hdr += '%12s %12s %12s %6s' % ( 

113 'Etot[eV]', 

114 'Epot[eV]', 

115 'Ekin[eV]', 

116 'T[K]', 

117 ) 

118 # Choose a sensible number of decimals 

119 if global_natoms <= 100: 

120 digits = 4 

121 elif global_natoms <= 1000: 

122 digits = 3 

123 elif global_natoms <= 10000: 

124 digits = 2 

125 else: 

126 digits = 1 

127 self.fmt += 3 * ('%%12.%df ' % (digits,)) + ' %6.1f' 

128 if self.stress: 

129 self.hdr += ( 

130 ' ---------------------- stress [GPa] ' 

131 '-----------------------' 

132 ) 

133 self.fmt += 6 * ' %10.3f' 

134 self.fmt += '\n' 

135 if header: 

136 self.logfile.write(self.hdr + '\n') 

137 

138 def __del__(self): 

139 self.close() 

140 

141 def __call__(self): 

142 epot = self._potential_energy() 

143 ekin = self.atoms.get_kinetic_energy() 

144 temp = self.atoms.get_temperature() 

145 global_natoms = self.atoms.get_global_number_of_atoms() 

146 if self.peratom: 

147 epot /= global_natoms 

148 ekin /= global_natoms 

149 if self.dyn is not None: 

150 t = self.dyn.get_time() / (1000 * units.fs) 

151 dat = (t,) 

152 else: 

153 dat = () 

154 dat += (epot + ekin, epot, ekin, temp) 

155 if self.stress: 

156 dat += tuple(self._stress() / units.GPa) 

157 self.logfile.write(self.fmt % dat) 

158 self.logfile.flush() 

159 

160 def _potential_energy(self): 

161 return self.atoms.get_potential_energy() 

162 

163 def _stress(self): 

164 return self.atoms.get_stress(include_ideal_gas=True)