Coverage for ase/cli/run.py: 92.07%

164 statements  

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

1import sys 

2from typing import Any 

3 

4import numpy as np 

5 

6 

7class CLICommand: 

8 """Run calculation with one of ASE's calculators. 

9 

10 Four types of calculations can be done: 

11 

12 * single point 

13 * atomic relaxations 

14 * unit cell + atomic relaxations 

15 * equation-of-state 

16 

17 Examples of the four types of calculations: 

18 

19 ase run emt h2o.xyz 

20 ase run emt h2o.xyz -f 0.01 

21 ase run emt cu.traj -s 0.01 

22 ase run emt cu.traj -E 5,2.0 

23 """ 

24 

25 @staticmethod 

26 def add_arguments(parser): 

27 from ase.calculators.names import names 

28 

29 parser.add_argument( 

30 'calculator', 

31 help='Name of calculator to use. Must be one of: {}.'.format( 

32 ', '.join(names) 

33 ), 

34 ) 

35 CLICommand.add_more_arguments(parser) 

36 

37 @staticmethod 

38 def add_more_arguments(parser): 

39 add = parser.add_argument 

40 add( 

41 'name', 

42 nargs='?', 

43 default='-', 

44 help='Read atomic structure from this file.', 

45 ) 

46 add( 

47 '-p', 

48 '--parameters', 

49 default='', 

50 metavar='key=value,...', 

51 help='Comma-separated key=value pairs of ' 

52 + 'calculator specific parameters.', 

53 ) 

54 add('-t', '--tag', help='String tag added to filenames.') 

55 add( 

56 '--properties', 

57 default='efsdMm', 

58 help='Default value is "efsdMm" meaning calculate energy, ' 

59 + 'forces, stress, dipole moment, total magnetic moment and ' 

60 + 'atomic magnetic moments.', 

61 ) 

62 add( 

63 '-f', 

64 '--maximum-force', 

65 type=float, 

66 help='Relax internal coordinates.', 

67 ) 

68 add( 

69 '--constrain-tags', 

70 metavar='T1,T2,...', 

71 help='Constrain atoms with tags T1, T2, ...', 

72 ) 

73 add( 

74 '-s', 

75 '--maximum-stress', 

76 type=float, 

77 help='Relax unit-cell and internal coordinates.', 

78 ) 

79 add( 

80 '-E', 

81 '--equation-of-state', 

82 help='Use "-E 5,2.0" for 5 lattice constants ranging from ' 

83 '-2.0 %% to +2.0 %%.', 

84 ) 

85 add('--eos-type', default='sjeos', help='Selects the type of eos.') 

86 add('-o', '--output', help='Write result to file (append mode).') 

87 add( 

88 '--modify', 

89 metavar='...', 

90 help='Modify atoms with Python statement. ' 

91 + 'Example: --modify="atoms.positions[-1,2]+=0.1".', 

92 ) 

93 add( 

94 '--after', 

95 help='Perform operation after calculation. ' 

96 + 'Example: --after="atoms.calc.write(...)"', 

97 ) 

98 

99 @staticmethod 

100 def run(args): 

101 runner = Runner() 

102 runner.parse(args) 

103 runner.run() 

104 

105 

106class Runner: 

107 def __init__(self): 

108 self.args = None 

109 self.calculator_name = None 

110 

111 def parse(self, args): 

112 self.calculator_name = args.calculator 

113 self.args = args 

114 

115 def run(self): 

116 args = self.args 

117 

118 atoms = self.build(args.name) 

119 if args.modify: 

120 exec(args.modify, {'atoms': atoms, 'np': np}) 

121 

122 if args.name == '-': 

123 args.name = 'stdin' 

124 

125 self.set_calculator(atoms, args.name) 

126 

127 self.calculate(atoms, args.name) 

128 

129 def calculate(self, atoms, name): 

130 from ase.io import write 

131 

132 args = self.args 

133 

134 if args.maximum_force or args.maximum_stress: 

135 self.optimize(atoms, name) 

136 if args.equation_of_state: 

137 self.eos(atoms, name) 

138 self.calculate_once(atoms) 

139 

140 if args.after: 

141 exec(args.after, {'atoms': atoms}) 

142 

143 if args.output: 

144 write(args.output, atoms, append=True) 

145 

146 def build(self, name): 

147 import ase.db as db 

148 from ase.io import read 

149 

150 if name == '-': 

151 con = db.connect(sys.stdin, 'json') 

152 return con.get_atoms(add_additional_information=True) 

153 else: 

154 atoms = read(name) 

155 if isinstance(atoms, list): 

156 assert len(atoms) == 1 

157 atoms = atoms[0] 

158 return atoms 

159 

160 def set_calculator(self, atoms, name): 

161 from ase.calculators.calculator import get_calculator_class 

162 

163 cls = get_calculator_class(self.calculator_name) 

164 parameters = str2dict(self.args.parameters) 

165 if getattr(cls, 'nolabel', False): 

166 atoms.calc = cls(**parameters) 

167 else: 

168 atoms.calc = cls(label=self.get_filename(name), **parameters) 

169 

170 def calculate_once(self, atoms): 

171 from ase.calculators.calculator import PropertyNotImplementedError 

172 

173 args = self.args 

174 

175 for p in args.properties or 'efsdMm': 

176 _property, method = { 

177 'e': ('energy', 'get_potential_energy'), 

178 'f': ('forces', 'get_forces'), 

179 's': ('stress', 'get_stress'), 

180 'd': ('dipole', 'get_dipole_moment'), 

181 'M': ('magmom', 'get_magnetic_moment'), 

182 'm': ('magmoms', 'get_magnetic_moments'), 

183 }[p] 

184 try: 

185 getattr(atoms, method)() 

186 except PropertyNotImplementedError: 

187 pass 

188 

189 def optimize(self, atoms, name): 

190 from ase.constraints import FixAtoms 

191 from ase.filters import UnitCellFilter 

192 from ase.io import Trajectory 

193 from ase.optimize import LBFGS 

194 

195 args = self.args 

196 if args.constrain_tags: 

197 tags = [int(t) for t in args.constrain_tags.split(',')] 

198 mask = [t in tags for t in atoms.get_tags()] 

199 atoms.constraints = FixAtoms(mask=mask) 

200 

201 logfile = self.get_filename(name, 'log') 

202 if args.maximum_stress: 

203 optimizer = LBFGS(UnitCellFilter(atoms), logfile=logfile) 

204 fmax = args.maximum_stress 

205 else: 

206 optimizer = LBFGS(atoms, logfile=logfile) 

207 fmax = args.maximum_force 

208 

209 trajectory = Trajectory(self.get_filename(name, 'traj'), 'w', atoms) 

210 optimizer.attach(trajectory) 

211 optimizer.run(fmax=fmax) 

212 

213 def eos(self, atoms, name): 

214 from ase.eos import EquationOfState 

215 from ase.io import Trajectory 

216 

217 args = self.args 

218 

219 traj = Trajectory(self.get_filename(name, 'traj'), 'w', atoms) 

220 

221 N, eps = args.equation_of_state.split(',') 

222 N = int(N) 

223 eps = float(eps) / 100 

224 strains = np.linspace(1 - eps, 1 + eps, N) 

225 v1 = atoms.get_volume() 

226 volumes = strains**3 * v1 

227 energies = [] 

228 cell1 = atoms.cell.copy() 

229 for s in strains: 

230 atoms.set_cell(cell1 * s, scale_atoms=True) 

231 energies.append(atoms.get_potential_energy()) 

232 traj.write(atoms) 

233 traj.close() 

234 eos = EquationOfState(volumes, energies, args.eos_type) 

235 v0, e0, B = eos.fit() 

236 atoms.set_cell(cell1 * (v0 / v1) ** (1 / 3), scale_atoms=True) 

237 from ase.parallel import parprint as p 

238 

239 p('volumes:', volumes) 

240 p('energies:', energies) 

241 p('fitted energy:', e0) 

242 p('fitted volume:', v0) 

243 p('bulk modulus:', B) 

244 p('eos type:', args.eos_type) 

245 

246 def get_filename(self, name: str, ext: str = '') -> str: 

247 if '.' in name: 

248 name = name.rsplit('.', 1)[0] 

249 if self.args.tag is not None: 

250 name += '-' + self.args.tag 

251 if ext: 

252 name += '.' + ext 

253 return name 

254 

255 

256def str2dict(s: str, namespace=None, sep: str = '=') -> dict[str, Any]: 

257 """Convert comma-separated key=value string to dictionary. 

258 

259 Examples 

260 -------- 

261 

262 >>> str2dict('xc=PBE,nbands=200,parallel={band:4}') 

263 {'xc': 'PBE', 'nbands': 200, 'parallel': {'band': 4}} 

264 >>> str2dict('a=1.2,b=True,c=ab,d=1,2,3,e={f:42,g:cd}') 

265 {'a': 1.2, 'b': True, 'c': 'ab', 'd': (1, 2, 3), 'e': {'f': 42, 'g': 'cd'}} 

266 """ 

267 

268 if namespace is None: 

269 namespace = {} 

270 

271 def myeval(value): 

272 try: 

273 value = eval(value, namespace) 

274 except (NameError, SyntaxError): 

275 pass 

276 return value 

277 

278 dct = {} 

279 strings = (s + ',').split(sep) 

280 for i in range(len(strings) - 1): 

281 key = strings[i] 

282 m = strings[i + 1].rfind(',') 

283 value: Any = strings[i + 1][:m] 

284 if value[0] == '{': 

285 assert value[-1] == '}' 

286 value = str2dict(value[1:-1], namespace, ':') 

287 elif value[0] == '(': 

288 assert value[-1] == ')' 

289 value = [myeval(t) for t in value[1:-1].split(',')] 

290 else: 

291 value = myeval(value) 

292 dct[key] = value 

293 strings[i + 1] = strings[i + 1][m + 1 :] 

294 return dct