Coverage for ase/cli/template.py: 94.06%

202 statements  

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

1import string 

2 

3import numpy as np 

4 

5from ase.data import chemical_symbols 

6from ase.io import string2index 

7from ase.io.formats import parse_filename 

8 

9# default fields 

10 

11 

12def field_specs_on_conditions(calculator_outputs, rank_order): 

13 if calculator_outputs: 

14 field_specs = ['i:0', 'el', 'd', 'rd', 'df', 'rdf'] 

15 else: 

16 field_specs = ['i:0', 'el', 'dx', 'dy', 'dz', 'd', 'rd'] 

17 if rank_order is not None: 

18 field_specs[0] = 'i:1' 

19 if rank_order in field_specs: 

20 for c, i in enumerate(field_specs): 

21 if i == rank_order: 

22 field_specs[c] = i + ':0:1' 

23 else: 

24 field_specs.append(rank_order + ':0:1') 

25 else: 

26 field_specs[0] = field_specs[0] + ':1' 

27 return field_specs 

28 

29 

30def summary_functions_on_conditions(has_calc): 

31 if has_calc: 

32 return [rmsd, energy_delta] 

33 return [rmsd] 

34 

35 

36def header_alias(h): 

37 """Replace keyboard characters with Unicode symbols 

38 for pretty printing""" 

39 if h == 'i': 

40 h = 'index' 

41 elif h == 'an': 

42 h = 'atomic #' 

43 elif h == 't': 

44 h = 'tag' 

45 elif h == 'el': 

46 h = 'element' 

47 elif h[0] == 'd': 

48 h = h.replace('d', 'Δ') 

49 elif h[0] == 'r': 

50 h = 'rank ' + header_alias(h[1:]) 

51 elif h[0] == 'a': 

52 h = h.replace('a', '<') 

53 h += '>' 

54 return h 

55 

56 

57def prec_round(a, prec=2): 

58 """ 

59 To make hierarchical sorting different from non-hierarchical sorting 

60 with floats. 

61 """ 

62 if a == 0: 

63 return a 

64 else: 

65 s = 1 if a > 0 else -1 

66 m = np.log10(s * a) // 1 

67 c = np.log10(s * a) % 1 

68 return s * np.round(10**c, prec) * 10**m 

69 

70 

71prec_round = np.vectorize(prec_round) 

72 

73# end most settings 

74 

75# this will sort alphabetically by chemical symbol 

76num2sym = dict(zip(np.argsort(chemical_symbols), chemical_symbols)) 

77# to sort by atomic number, uncomment below 

78# num2sym = dict(zip(range(len(chemical_symbols)), chemical_symbols)) 

79sym2num = {v: k for k, v in num2sym.items()} 

80 

81atoms_props = [ 

82 'dx', 

83 'dy', 

84 'dz', 

85 'd', 

86 't', 

87 'an', 

88 'i', 

89 'el', 

90 'p1', 

91 'p2', 

92 'p1x', 

93 'p1y', 

94 'p1z', 

95 'p2x', 

96 'p2y', 

97 'p2z', 

98] 

99 

100 

101def get_field_data(atoms1, atoms2, field): 

102 if field[0] == 'r': 

103 field = field[1:] 

104 rank_order = True 

105 else: 

106 rank_order = False 

107 

108 if field in atoms_props: 

109 if field == 't': 

110 data = atoms1.get_tags() 

111 elif field == 'an': 

112 data = atoms1.numbers 

113 elif field == 'el': 

114 data = np.array([sym2num[sym] for sym in atoms1.symbols]) 

115 elif field == 'i': 

116 data = np.arange(len(atoms1)) 

117 else: 

118 if field.startswith('d'): 

119 y = atoms2.positions - atoms1.positions 

120 elif field.startswith('p'): 

121 if field[1] == '1': 

122 y = atoms1.positions 

123 else: 

124 y = atoms2.positions 

125 

126 if field.endswith('x'): 

127 data = y[:, 0] 

128 elif field.endswith('y'): 

129 data = y[:, 1] 

130 elif field.endswith('z'): 

131 data = y[:, 2] 

132 else: 

133 data = np.linalg.norm(y, axis=1) 

134 else: 

135 if field[0] == 'd': 

136 y = atoms2.get_forces() - atoms1.get_forces() 

137 elif field[0] == 'a': 

138 y = (atoms2.get_forces() + atoms1.get_forces()) / 2 

139 else: 

140 if field[1] == '1': 

141 y = atoms1.get_forces() 

142 else: 

143 y = atoms2.get_forces() 

144 

145 if field.endswith('x'): 

146 data = y[:, 0] 

147 elif field.endswith('y'): 

148 data = y[:, 1] 

149 elif field.endswith('z'): 

150 data = y[:, 2] 

151 else: 

152 data = np.linalg.norm(y, axis=1) 

153 

154 if rank_order: 

155 return np.argsort(np.argsort(-data)) 

156 

157 return data 

158 

159 

160# Summary Functions 

161 

162 

163def rmsd(atoms1, atoms2): 

164 dpositions = atoms2.positions - atoms1.positions 

165 return 'RMSD={:+.1E}'.format( 

166 np.sqrt((np.linalg.norm(dpositions, axis=1) ** 2).mean()) 

167 ) 

168 

169 

170def energy_delta(atoms1, atoms2): 

171 E1 = atoms1.get_potential_energy() 

172 E2 = atoms2.get_potential_energy() 

173 return f'E1 = {E1:+.1E}, E2 = {E2:+.1E}, dE = {E2 - E1:+1.1E}' 

174 

175 

176def parse_field_specs(field_specs): 

177 fields = [] 

178 hier = [] 

179 scent = [] 

180 for fs in field_specs: 

181 fhs = fs.split(':') 

182 if len(fhs) == 3: 

183 scent.append(int(fhs[2])) 

184 hier.append(int(fhs[1])) 

185 fields.append(fhs[0]) 

186 elif len(fhs) == 2: 

187 scent.append(-1) 

188 hier.append(int(fhs[1])) 

189 fields.append(fhs[0]) 

190 elif len(fhs) == 1: 

191 scent.append(-1) 

192 hier.append(-1) 

193 fields.append(fhs[0]) 

194 mxm = max(hier) 

195 for c in range(len(hier)): 

196 if hier[c] < 0: 

197 mxm += 1 

198 hier[c] = mxm 

199 # reversed by convention of numpy lexsort 

200 hier = np.argsort(hier)[::-1] 

201 return fields, hier, np.array(scent) 

202 

203 

204# Class definitions 

205 

206 

207class MapFormatter(string.Formatter): 

208 """String formatting method to map string 

209 mapped to float data field 

210 used for sorting back to string.""" 

211 

212 def format_field(self, value, spec): 

213 if spec.endswith('h'): 

214 value = num2sym[int(value)] 

215 spec = spec[:-1] + 's' 

216 return super().format_field(value, spec) 

217 

218 

219class TableFormat: 

220 def __init__( 

221 self, 

222 columnwidth=9, 

223 precision=2, 

224 representation='E', 

225 toprule='=', 

226 midrule='-', 

227 bottomrule='=', 

228 ): 

229 

230 self.precision = precision 

231 self.representation = representation 

232 self.columnwidth = columnwidth 

233 self.formatter = MapFormatter().format 

234 self.toprule = toprule 

235 self.midrule = midrule 

236 self.bottomrule = bottomrule 

237 

238 self.fmt_class = { 

239 'signed float': '{{: ^{}.{}{}}}'.format( 

240 self.columnwidth, self.precision - 1, self.representation 

241 ), 

242 'unsigned float': '{{:^{}.{}{}}}'.format( 

243 self.columnwidth, self.precision - 1, self.representation 

244 ), 

245 'int': '{{:^{}n}}'.format(self.columnwidth), 

246 'str': '{{:^{}s}}'.format(self.columnwidth), 

247 'conv': '{{:^{}h}}'.format(self.columnwidth), 

248 } 

249 fmt = {} 

250 signed_floats = [ 

251 'dx', 

252 'dy', 

253 'dz', 

254 'dfx', 

255 'dfy', 

256 'dfz', 

257 'afx', 

258 'afy', 

259 'afz', 

260 'p1x', 

261 'p2x', 

262 'p1y', 

263 'p2y', 

264 'p1z', 

265 'p2z', 

266 'f1x', 

267 'f2x', 

268 'f1y', 

269 'f2y', 

270 'f1z', 

271 'f2z', 

272 ] 

273 for sf in signed_floats: 

274 fmt[sf] = self.fmt_class['signed float'] 

275 unsigned_floats = ['d', 'df', 'af', 'p1', 'p2', 'f1', 'f2'] 

276 for usf in unsigned_floats: 

277 fmt[usf] = self.fmt_class['unsigned float'] 

278 integers = ( 

279 ['i', 'an', 't'] 

280 + ['r' + sf for sf in signed_floats] 

281 + ['r' + usf for usf in unsigned_floats] 

282 ) 

283 for i in integers: 

284 fmt[i] = self.fmt_class['int'] 

285 fmt['el'] = self.fmt_class['conv'] 

286 

287 self.fmt = fmt 

288 

289 

290class Table: 

291 def __init__( 

292 self, 

293 field_specs, 

294 summary_functions=None, 

295 tableformat=None, 

296 max_lines=None, 

297 title='', 

298 tablewidth=None, 

299 ): 

300 

301 if summary_functions is None: 

302 summary_functions = [] 

303 self.max_lines = max_lines 

304 self.summary_functions = summary_functions 

305 self.field_specs = field_specs 

306 

307 self.fields, self.hier, self.scent = parse_field_specs(self.field_specs) 

308 self.nfields = len(self.fields) 

309 

310 # formatting 

311 if tableformat is None: 

312 self.tableformat = TableFormat() 

313 else: 

314 self.tableformat = tableformat 

315 

316 if tablewidth is None: 

317 self.tablewidth = self.tableformat.columnwidth * self.nfields 

318 else: 

319 self.tablewidth = tablewidth 

320 

321 self.title = title 

322 

323 def make(self, atoms1, atoms2, csv=False): 

324 header = self.make_header(csv=csv) 

325 body = self.make_body(atoms1, atoms2, csv=csv) 

326 if self.max_lines is not None: 

327 body = body[: self.max_lines] 

328 summary = self.make_summary(atoms1, atoms2) 

329 

330 return '\n'.join( 

331 [ 

332 self.title, 

333 self.tableformat.toprule * self.tablewidth, 

334 header, 

335 self.tableformat.midrule * self.tablewidth, 

336 body, 

337 self.tableformat.bottomrule * self.tablewidth, 

338 summary, 

339 ] 

340 ) 

341 

342 def make_header(self, csv=False): 

343 if csv: 

344 return ','.join([header_alias(field) for field in self.fields]) 

345 

346 fields = self.tableformat.fmt_class['str'] * self.nfields 

347 headers = [header_alias(field) for field in self.fields] 

348 

349 return self.tableformat.formatter(fields, *headers) 

350 

351 def make_summary(self, atoms1, atoms2): 

352 return '\n'.join( 

353 [ 

354 summary_function(atoms1, atoms2) 

355 for summary_function in self.summary_functions 

356 ] 

357 ) 

358 

359 def make_body(self, atoms1, atoms2, csv=False): 

360 field_data = np.array( 

361 [get_field_data(atoms1, atoms2, field) for field in self.fields] 

362 ) 

363 

364 sorting_array = field_data * self.scent[:, np.newaxis] 

365 sorting_array = sorting_array[self.hier] 

366 sorting_array = prec_round(sorting_array, self.tableformat.precision) 

367 

368 field_data = field_data[:, np.lexsort(sorting_array)].transpose() 

369 

370 if csv: 

371 rowformat = ','.join( 

372 [ 

373 '{:h}' 

374 if field == 'el' 

375 else '{{:.{}E}}'.format(self.tableformat.precision) 

376 for field in self.fields 

377 ] 

378 ) 

379 else: 

380 rowformat = ''.join( 

381 [self.tableformat.fmt[field] for field in self.fields] 

382 ) 

383 body = [ 

384 self.tableformat.formatter(rowformat, *row) for row in field_data 

385 ] 

386 return '\n'.join(body) 

387 

388 

389default_index = string2index(':') 

390 

391 

392def slice_split(filename): 

393 if '@' in filename: 

394 filename, index = parse_filename(filename, None) 

395 else: 

396 filename, index = parse_filename(filename, default_index) 

397 return filename, index