Coverage for ase/cli/diff.py: 85.56%

90 statements  

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

1# Note: 

2# Try to avoid module level import statements here to reduce 

3# import time during CLI execution 

4import sys 

5 

6from ase.cli.main import CLIError 

7 

8template_help = """ 

9Without argument, looks for ~/.ase/template.py. Otherwise, 

10expects the comma separated list of the fields to include 

11in their left-to-right order. Optionally, specify the 

12lexicographical sort hierarchy (0 is outermost sort) and if the 

13sort should be ascending or descending (1 or -1). By default, 

14sorting is descending, which makes sense for most things except 

15index (and rank, but one can just sort by the thing which is 

16ranked to get ascending ranks). 

17 

18* example: ase diff start.cif stop.cif --template 

19* i:0:1,el,dx,dy,dz,d,rd 

20 

21possible fields: 

22 

23* i: index 

24* dx,dy,dz,d: displacement/displacement components 

25* dfx,dfy,dfz,df: difference force/force components 

26* afx,afy,afz,af: average force/force components 

27* p1x,p1y,p1z,p: first image positions/position components 

28* p2x,p2y,p2z,p: second image positions/position components 

29* f1x,f1y,f1z,f: first image forces/force components 

30* f2x,f2y,f2z,f: second image forces/force components 

31* an: atomic number 

32* el: atomic element 

33* t: atom tag 

34* r<col>: the rank of that atom with respect to the column 

35 

36It is possible to change formatters in the template file.""" 

37 

38 

39class CLICommand: 

40 """Print differences between atoms/calculations. 

41 

42 Supports taking differences between different calculation runs of 

43 the same system as well as neighboring geometric images for one 

44 calculation run of a system. As part of a difference table or as a 

45 standalone display table, fields for non-difference quantities of image 1 

46 and image 2 are also provided. 

47 

48 See the --template-help for the formatting exposed in the CLI. More 

49 customization requires changing the input arguments to the Table 

50 initialization and/or editing the templates file. 

51 """ 

52 

53 @staticmethod 

54 def add_arguments(parser): 

55 add = parser.add_argument 

56 add( 

57 'file', 

58 help="""Possible file entries are 

59 

60 * 2 non-trajectory files: difference between them 

61 * 1 trajectory file: difference between consecutive images 

62 * 2 trajectory files: difference between corresponding image numbers 

63 * 1 trajectory file followed by hyphen-minus (ASCII 45): for display 

64 

65 Note deltas are defined as 2 - 1. 

66 

67 Use [FILE]@[SLICE] to select images. 

68 """, 

69 nargs='+', 

70 ) 

71 add( 

72 '-r', 

73 '--rank-order', 

74 metavar='FIELD', 

75 nargs='?', 

76 const='d', 

77 type=str, 

78 help="""Order atoms by rank, see --template-help for possible 

79fields. 

80 

81The default value, when specified, is d. When not 

82specified, ordering is the same as that provided by the 

83generator. For hierarchical sorting, see template.""", 

84 ) 

85 add( 

86 '-c', 

87 '--calculator-outputs', 

88 action='store_true', 

89 help='display calculator outputs of forces and energy', 

90 ) 

91 add( 

92 '--max-lines', 

93 metavar='N', 

94 type=int, 

95 help='show only so many lines (atoms) in each table ' 

96 ', useful if rank ordering', 

97 ) 

98 add( 

99 '-t', 

100 '--template', 

101 metavar='TEMPLATE', 

102 nargs='?', 

103 const='rc', 

104 help="""See --template-help for the help on this option.""", 

105 ) 

106 add( 

107 '--template-help', 

108 help="""Prints the help for the template file. 

109 Usage `ase diff - --template-help`""", 

110 action='store_true', 

111 ) 

112 add( 

113 '-s', 

114 '--summary-functions', 

115 metavar='SUMFUNCS', 

116 nargs='?', 

117 help="""Specify the summary functions. 

118 Possible values are `rmsd` and `dE`. 

119 Comma separate more than one summary function.""", 

120 ) 

121 add('--log-file', metavar='LOGFILE', help='print table to file') 

122 add('--as-csv', action='store_true', help='output table in csv format') 

123 add( 

124 '--precision', 

125 metavar='PREC', 

126 default=2, 

127 type=int, 

128 help='precision used in both display and sorting', 

129 ) 

130 

131 @staticmethod 

132 def run(args, parser): 

133 import io 

134 

135 if args.template_help: 

136 print(template_help) 

137 return 

138 

139 encoding = 'utf-8' 

140 

141 if args.log_file is None: 

142 out = io.TextIOWrapper(sys.stdout.buffer, encoding=encoding) 

143 else: 

144 out = open(args.log_file, 'w', encoding=encoding) 

145 

146 with out: 

147 CLICommand.diff(args, out) 

148 

149 @staticmethod 

150 def diff(args, out): 

151 from ase.cli.template import ( 

152 Table, 

153 TableFormat, 

154 energy_delta, 

155 field_specs_on_conditions, 

156 rmsd, 

157 slice_split, 

158 summary_functions_on_conditions, 

159 ) 

160 from ase.io import read 

161 

162 if args.template is None: 

163 field_specs = field_specs_on_conditions( 

164 args.calculator_outputs, args.rank_order 

165 ) 

166 else: 

167 field_specs = args.template.split(',') 

168 if not args.calculator_outputs: 

169 for field_spec in field_specs: 

170 if 'f' in field_spec: 

171 raise CLIError( 

172 'field requiring calculation outputs ' 

173 'without --calculator-outputs' 

174 ) 

175 

176 if args.summary_functions is None: 

177 summary_functions = summary_functions_on_conditions( 

178 args.calculator_outputs 

179 ) 

180 else: 

181 summary_functions_dct = {'rmsd': rmsd, 'dE': energy_delta} 

182 summary_functions = args.summary_functions.split(',') 

183 if not args.calculator_outputs: 

184 for sf in summary_functions: 

185 if sf == 'dE': 

186 raise CLIError( 

187 'summary function requiring calculation outputs ' 

188 'without --calculator-outputs' 

189 ) 

190 summary_functions = [ 

191 summary_functions_dct[i] for i in summary_functions 

192 ] 

193 

194 have_two_files = len(args.file) == 2 

195 file1 = args.file[0] 

196 actual_filename, index = slice_split(file1) 

197 atoms1 = read(actual_filename, index) 

198 natoms1 = len(atoms1) 

199 

200 if have_two_files: 

201 if args.file[1] == '-': 

202 atoms2 = atoms1 

203 

204 def header_fmt(c): 

205 return f'image # {c}' 

206 else: 

207 file2 = args.file[1] 

208 actual_filename, index = slice_split(file2) 

209 atoms2 = read(actual_filename, index) 

210 natoms2 = len(atoms2) 

211 

212 same_length = natoms1 == natoms2 

213 one_l_one = natoms1 == 1 or natoms2 == 1 

214 

215 if not same_length and not one_l_one: 

216 raise CLIError( 

217 'Trajectory files are not the same length ' 

218 'and both > 1\n{}!={}'.format(natoms1, natoms2) 

219 ) 

220 elif not same_length and one_l_one: 

221 print( 

222 'One file contains one image ' 

223 'and the other multiple images,\n' 

224 'assuming you want to compare all images ' 

225 'with one reference image' 

226 ) 

227 if natoms1 > natoms2: 

228 atoms2 = natoms1 * atoms2 

229 else: 

230 atoms1 = natoms2 * atoms1 

231 

232 def header_fmt(c): 

233 return f'sys-ref image # {c}' 

234 else: 

235 

236 def header_fmt(c): 

237 return f'sys2-sys1 image # {c}' 

238 else: 

239 atoms2 = atoms1.copy() 

240 atoms1 = atoms1[:-1] 

241 atoms2 = atoms2[1:] 

242 natoms2 = natoms1 = natoms1 - 1 

243 

244 def header_fmt(c): 

245 return f'images {c + 1}-{c}' 

246 

247 natoms = natoms1 # = natoms2 

248 

249 output = '' 

250 tableformat = TableFormat( 

251 precision=args.precision, columnwidth=7 + args.precision 

252 ) 

253 

254 table = Table( 

255 field_specs, 

256 max_lines=args.max_lines, 

257 tableformat=tableformat, 

258 summary_functions=summary_functions, 

259 ) 

260 

261 for counter in range(natoms): 

262 table.title = header_fmt(counter) 

263 output += ( 

264 table.make(atoms1[counter], atoms2[counter], csv=args.as_csv) 

265 + '\n' 

266 ) 

267 print(output, file=out)