Coverage for ase/calculators/loggingcalc.py: 74.05%

131 statements  

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

1""" 

2Provides LoggingCalculator class to wrap a Calculator and record 

3number of enery and force calls 

4""" 

5 

6import json 

7import logging 

8import time 

9from typing import Any 

10 

11import numpy as np 

12 

13from ase.calculators.calculator import Calculator, all_properties 

14 

15logger = logging.getLogger(__name__) 

16 

17 

18class LoggingCalculator(Calculator): 

19 """Calculator wrapper to record and plot history of energy and function 

20 evaluations 

21 """ 

22 

23 implemented_properties = all_properties 

24 default_parameters: dict[str, Any] = {} 

25 name = 'LoggingCalculator' 

26 

27 property_to_method_name = { 

28 'energy': 'get_potential_energy', 

29 'energies': 'get_potential_energies', 

30 'forces': 'get_forces', 

31 'stress': 'get_stress', 

32 'stresses': 'get_stresses', 

33 } 

34 

35 def __init__(self, calculator, jsonfile=None, dumpjson=False): 

36 Calculator.__init__(self) 

37 self.calculator = calculator 

38 self.fmax = {} 

39 self.walltime = {} 

40 self.energy_evals = {} 

41 self.energy_count = {} 

42 self.set_label('(none)') 

43 if jsonfile is not None: 

44 self.read_json(jsonfile) 

45 self.dumpjson = dumpjson 

46 

47 def calculate(self, atoms, properties, system_changes): 

48 Calculator.calculate(self, atoms, properties, system_changes) 

49 

50 if isinstance(self.calculator, Calculator): 

51 results = [ 

52 self.calculator.get_property(prop, atoms) for prop in properties 

53 ] 

54 else: 

55 results = [] 

56 for prop in properties: 

57 method_name = self.property_to_method_name[prop] 

58 method = getattr(self.calculator, method_name) 

59 results.append(method(atoms)) 

60 

61 if 'energy' in properties or 'energies' in properties: 

62 self.energy_evals.setdefault(self.label, 0) 

63 self.energy_evals[self.label] += 1 

64 try: 

65 energy = results[properties.index('energy')] 

66 except IndexError: 

67 energy = sum(results[properties.index('energies')]) 

68 logger.info( 

69 'energy call count=%d energy=%.3f', 

70 self.energy_evals[self.label], 

71 energy, 

72 ) 

73 self.results = dict(zip(properties, results)) 

74 

75 if 'forces' in self.results: 

76 fmax = self.fmax.setdefault(self.label, []) 

77 walltime = self.walltime.setdefault(self.label, []) 

78 forces = self.results['forces'].copy() 

79 energy_count = self.energy_count.setdefault(self.label, []) 

80 energy_evals = self.energy_evals.setdefault(self.label, 0) 

81 energy_count.append(energy_evals) 

82 for constraint in atoms.constraints: 

83 constraint.adjust_forces(atoms, forces) 

84 fmax.append(abs(forces).max()) 

85 walltime.append(time.time()) 

86 logger.info('force call fmax=%.3f', fmax[-1]) 

87 

88 if self.dumpjson: 

89 self.write_json('dump.json') 

90 

91 def write_json(self, filename): 

92 with open(filename, 'w') as fd: 

93 json.dump( 

94 { 

95 'fmax': self.fmax, 

96 'walltime': self.walltime, 

97 'energy_evals': self.energy_evals, 

98 'energy_count': self.energy_count, 

99 }, 

100 fd, 

101 ) 

102 

103 def read_json(self, filename, append=False, label=None): 

104 with open(filename) as fd: 

105 dct = json.load(fd) 

106 

107 labels = dct['fmax'].keys() 

108 if label is not None and len(labels) == 1: 

109 for key in ('fmax', 'walltime', 'energy_evals', 'energy_count'): 

110 dct[key][label] = dct[key][labels[0]] 

111 del dct[key][labels[0]] 

112 if not append: 

113 self.fmax = {} 

114 self.walltime = {} 

115 self.energy_evals = {} 

116 self.energy_count = {} 

117 self.fmax.update(dct['fmax']) 

118 self.walltime.update(dct['walltime']) 

119 self.energy_evals.update(dct['energy_evals']) 

120 self.energy_count.update(dct['energy_count']) 

121 

122 def tabulate(self): 

123 fmt1 = '%-10s %10s %10s %8s' 

124 title = fmt1 % ('Label', '# Force', '# Energy', 'Walltime/s') 

125 print(title) 

126 print('-' * len(title)) 

127 fmt2 = '%-10s %10d %10d %8.2f' 

128 for label in sorted(self.fmax.keys()): 

129 print( 

130 fmt2 

131 % ( 

132 label, 

133 len(self.fmax[label]), 

134 len(self.energy_count[label]), 

135 self.walltime[label][-1] - self.walltime[label][0], 

136 ) 

137 ) 

138 

139 def plot( 

140 self, 

141 fmaxlim=(1e-2, 1e2), 

142 forces=True, 

143 energy=True, 

144 walltime=True, 

145 markers=None, 

146 labels=None, 

147 **kwargs, 

148 ): 

149 import matplotlib.pyplot as plt 

150 

151 if markers is None: 

152 markers = [ 

153 c + s 

154 for c in ['r', 'g', 'b', 'c', 'm', 'y', 'k'] 

155 for s in ['.-', '.--'] 

156 ] 

157 nsub = sum([forces, energy, walltime]) 

158 nplot = 0 

159 

160 if labels is not None: 

161 fmax_values = [ 

162 v 

163 for (k, v) in sorted(zip(self.fmax.keys(), self.fmax.values())) 

164 ] 

165 self.fmax = dict(zip(labels, fmax_values)) 

166 

167 energy_count_values = [ 

168 v 

169 for (k, v) in sorted( 

170 zip(self.energy_count.keys(), self.energy_count.values()) 

171 ) 

172 ] 

173 self.energy_count = dict(zip(labels, energy_count_values)) 

174 

175 walltime_values = [ 

176 v 

177 for (k, v) in sorted( 

178 zip(self.walltime.keys(), self.walltime.values()) 

179 ) 

180 ] 

181 self.walltime = dict(zip(labels, walltime_values)) 

182 

183 if forces: 

184 nplot += 1 

185 plt.subplot(nsub, 1, nplot) 

186 for label, color in zip(sorted(self.fmax.keys()), markers): 

187 fmax = np.array(self.fmax[label]) 

188 idx = np.arange(len(fmax)) 

189 plt.semilogy(idx, fmax, color, label=label, **kwargs) 

190 

191 plt.xlabel('Number of force evaluations') 

192 plt.ylabel('Maximum force / eV/A') 

193 plt.ylim(*fmaxlim) 

194 plt.legend() 

195 

196 if energy: 

197 nplot += 1 

198 plt.subplot(nsub, 1, nplot) 

199 for label, color in zip(sorted(self.energy_count.keys()), markers): 

200 energy_count = np.array(self.energy_count[label]) 

201 fmax = np.array(self.fmax[label]) 

202 plt.semilogy(energy_count, fmax, color, label=label, **kwargs) 

203 

204 plt.xlabel('Number of energy evaluations') 

205 plt.ylabel('Maximum force / eV/A') 

206 plt.ylim(*fmaxlim) 

207 plt.legend() 

208 

209 if walltime: 

210 nplot += 1 

211 plt.subplot(nsub, 1, nplot) 

212 for label, color in zip(sorted(self.walltime.keys()), markers): 

213 walltime = np.array(self.walltime[label]) 

214 fmax = np.array(self.fmax[label]) 

215 walltime -= walltime[0] 

216 plt.semilogy(walltime, fmax, color, label=label, **kwargs) 

217 

218 plt.xlabel('Walltime / s') 

219 plt.ylabel('Maximum force / eV/A') 

220 plt.ylim(*fmaxlim) 

221 plt.legend() 

222 

223 plt.subplots_adjust(hspace=0.33)