Coverage for ase/calculators/aims.py: 44.00%

125 statements  

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

1"""This module defines an ASE interface to FHI-aims. 

2 

3Felix Hanke hanke@liverpool.ac.uk 

4Jonas Bjork j.bjork@liverpool.ac.uk 

5Simon P. Rittmeyer simon.rittmeyer@tum.de 

6 

7Edits on (24.11.2021) by Thomas A. R. Purcell purcell@fhi-berlin.mpg.de 

8""" 

9 

10import os 

11import re 

12 

13import numpy as np 

14 

15from ase.calculators.genericfileio import ( 

16 BaseProfile, 

17 CalculatorTemplate, 

18 GenericFileIOCalculator, 

19 read_stdout, 

20) 

21from ase.io import read, write 

22from ase.io.aims import write_control 

23 

24 

25def get_aims_version(string): 

26 match = re.search(r'\s*FHI-aims version\s*:\s*(\S+)', string, re.M) 

27 return match.group(1) 

28 

29 

30class AimsProfile(BaseProfile): 

31 configvars = {'default_species_directory'} 

32 

33 def __init__(self, command, default_species_directory=None, **kwargs): 

34 super().__init__(command, **kwargs) 

35 self.default_species_directory = default_species_directory 

36 

37 def get_calculator_command(self, inputfile): 

38 return [] 

39 

40 def version(self): 

41 return get_aims_version(read_stdout(self._split_command)) 

42 

43 

44class AimsTemplate(CalculatorTemplate): 

45 _label = 'aims' 

46 

47 def __init__(self): 

48 super().__init__( 

49 'aims', 

50 [ 

51 'energy', 

52 'free_energy', 

53 'forces', 

54 'stress', 

55 'stresses', 

56 'dipole', 

57 'magmom', 

58 ], 

59 ) 

60 

61 self.outputname = f'{self._label}.out' 

62 self.errorname = f'{self._label}.err' 

63 

64 def update_parameters(self, properties, parameters): 

65 """Check and update the parameters to match the desired calculation 

66 

67 Parameters 

68 ---------- 

69 properties: list of str 

70 The list of properties to calculate 

71 parameters: dict 

72 The parameters used to perform the calculation. 

73 

74 Returns 

75 ------- 

76 dict 

77 The updated parameters object 

78 """ 

79 parameters = dict(parameters) 

80 property_flags = { 

81 'forces': 'compute_forces', 

82 'stress': 'compute_analytical_stress', 

83 'stresses': 'compute_heat_flux', 

84 } 

85 # Ensure FHI-aims will calculate all desired properties 

86 for property in properties: 

87 aims_name = property_flags.get(property, None) 

88 if aims_name is not None: 

89 parameters[aims_name] = True 

90 

91 if 'dipole' in properties: 

92 if 'output' in parameters and 'dipole' not in parameters['output']: 

93 parameters['output'] = list(parameters['output']) 

94 parameters['output'].append('dipole') 

95 elif 'output' not in parameters: 

96 parameters['output'] = ['dipole'] 

97 

98 return parameters 

99 

100 def write_input(self, profile, directory, atoms, parameters, properties): 

101 """Write the geometry.in and control.in files for the calculation 

102 

103 Parameters 

104 ---------- 

105 directory : Path 

106 The working directory to store the input files. 

107 atoms : atoms.Atoms 

108 The atoms object to perform the calculation on. 

109 parameters: dict 

110 The parameters used to perform the calculation. 

111 properties: list of str 

112 The list of properties to calculate 

113 """ 

114 parameters = self.update_parameters(properties, parameters) 

115 

116 ghosts = parameters.pop('ghosts', None) 

117 geo_constrain = parameters.pop('geo_constrain', None) 

118 scaled = parameters.pop('scaled', None) 

119 write_velocities = parameters.pop('write_velocities', None) 

120 

121 if scaled is None: 

122 scaled = np.all(atoms.pbc) 

123 if write_velocities is None: 

124 write_velocities = atoms.has('momenta') 

125 

126 if geo_constrain is None: 

127 geo_constrain = scaled and 'relax_geometry' in parameters 

128 

129 have_lattice_vectors = atoms.pbc.any() 

130 have_k_grid = ( 

131 'k_grid' in parameters 

132 or 'kpts' in parameters 

133 or 'k_grid_density' in parameters 

134 ) 

135 if have_lattice_vectors and not have_k_grid: 

136 raise RuntimeError('Found lattice vectors but no k-grid!') 

137 if not have_lattice_vectors and have_k_grid: 

138 raise RuntimeError('Found k-grid but no lattice vectors!') 

139 

140 geometry_in = directory / 'geometry.in' 

141 

142 write( 

143 geometry_in, 

144 atoms, 

145 format='aims', 

146 scaled=scaled, 

147 geo_constrain=geo_constrain, 

148 write_velocities=write_velocities, 

149 ghosts=ghosts, 

150 ) 

151 

152 control = directory / 'control.in' 

153 

154 if ( 

155 'species_dir' not in parameters 

156 and profile.default_species_directory is not None 

157 ): 

158 parameters['species_dir'] = profile.default_species_directory 

159 

160 write_control(control, atoms, parameters) 

161 

162 def execute(self, directory, profile): 

163 profile.run(directory, None, self.outputname, errorfile=self.errorname) 

164 

165 def read_results(self, directory): 

166 dst = directory / self.outputname 

167 return read(dst, format='aims-output', index=-1).calc.results 

168 

169 def load_profile(self, cfg, **kwargs): 

170 return AimsProfile.from_config(cfg, self.name, **kwargs) 

171 

172 def socketio_argv(self, profile, unixsocket, port): 

173 return profile._split_command 

174 

175 def socketio_parameters(self, unixsocket, port): 

176 if port: 

177 use_pimd_wrapper = ('localhost', port) 

178 else: 

179 # (INET port number should be unused.) 

180 use_pimd_wrapper = (f'UNIX:{unixsocket}', 31415) 

181 

182 return dict(use_pimd_wrapper=use_pimd_wrapper, compute_forces=True) 

183 

184 

185class Aims(GenericFileIOCalculator): 

186 def __init__( 

187 self, 

188 profile=None, 

189 directory='.', 

190 **kwargs, 

191 ): 

192 """Construct the FHI-aims calculator. 

193 

194 The keyword arguments (kwargs) can be one of the ASE standard 

195 keywords: 'xc', 'kpts' and 'smearing' or any of FHI-aims' 

196 native keywords. 

197 

198 

199 Arguments: 

200 

201 cubes: AimsCube object 

202 Cube file specification. 

203 

204 tier: int or array of ints 

205 Set basis set tier for all atomic species. 

206 

207 plus_u : dict 

208 For DFT+U. Adds a +U term to one specific shell of the species. 

209 

210 kwargs : dict 

211 Any of the base class arguments. 

212 

213 """ 

214 

215 super().__init__( 

216 template=AimsTemplate(), 

217 profile=profile, 

218 parameters=kwargs, 

219 directory=directory, 

220 ) 

221 

222 

223class AimsCube: 

224 "Object to ensure the output of cube files, can be attached to Aims object" 

225 

226 def __init__( 

227 self, 

228 origin=(0, 0, 0), 

229 edges=None, 

230 points=(50, 50, 50), 

231 plots=(), 

232 ): 

233 """parameters: 

234 

235 origin, edges, points: 

236 Same as in the FHI-aims output 

237 plots: 

238 what to print, same names as in FHI-aims""" 

239 

240 if edges is None: 

241 edges = [(0.1, 0.0, 0.0), (0.0, 0.1, 0.0), (0.0, 0.0, 0.1)] 

242 self.name = 'AimsCube' 

243 self.origin = origin 

244 self.edges = edges 

245 self.points = points 

246 self.plots = plots 

247 

248 def ncubes(self): 

249 """returns the number of cube files to output""" 

250 return len(self.plots) 

251 

252 def move_to_base_name(self, basename): 

253 """when output tracking is on or the base namem is not standard, 

254 this routine will rename add the base to the cube file output for 

255 easier tracking""" 

256 for plot in self.plots: 

257 found = False 

258 cube = plot.split() 

259 if ( 

260 cube[0] == 'total_density' 

261 or cube[0] == 'spin_density' 

262 or cube[0] == 'delta_density' 

263 ): 

264 found = True 

265 old_name = cube[0] + '.cube' 

266 new_name = basename + '.' + old_name 

267 if cube[0] == 'eigenstate' or cube[0] == 'eigenstate_density': 

268 found = True 

269 state = int(cube[1]) 

270 s_state = cube[1] 

271 for i in [10, 100, 1000, 10000]: 

272 if state < i: 

273 s_state = '0' + s_state 

274 old_name = cube[0] + '_' + s_state + '_spin_1.cube' 

275 new_name = basename + '.' + old_name 

276 if found: 

277 # XXX Should not use platform dependent commands! 

278 os.system('mv ' + old_name + ' ' + new_name) 

279 

280 def add_plot(self, name): 

281 """in case you forgot one ...""" 

282 self.plots += [name] 

283 

284 def write(self, file): 

285 """write the necessary output to the already opened control.in""" 

286 file.write('output cube ' + self.plots[0] + '\n') 

287 file.write(' cube origin ') 

288 for ival in self.origin: 

289 file.write(str(ival) + ' ') 

290 file.write('\n') 

291 for i in range(3): 

292 file.write(' cube edge ' + str(self.points[i]) + ' ') 

293 for ival in self.edges[i]: 

294 file.write(str(ival) + ' ') 

295 file.write('\n') 

296 if self.ncubes() > 1: 

297 for i in range(self.ncubes() - 1): 

298 file.write('output cube ' + self.plots[i + 1] + '\n')