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
« 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.
3Felix Hanke hanke@liverpool.ac.uk
4Jonas Bjork j.bjork@liverpool.ac.uk
5Simon P. Rittmeyer simon.rittmeyer@tum.de
7Edits on (24.11.2021) by Thomas A. R. Purcell purcell@fhi-berlin.mpg.de
8"""
10import os
11import re
13import numpy as np
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
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)
30class AimsProfile(BaseProfile):
31 configvars = {'default_species_directory'}
33 def __init__(self, command, default_species_directory=None, **kwargs):
34 super().__init__(command, **kwargs)
35 self.default_species_directory = default_species_directory
37 def get_calculator_command(self, inputfile):
38 return []
40 def version(self):
41 return get_aims_version(read_stdout(self._split_command))
44class AimsTemplate(CalculatorTemplate):
45 _label = 'aims'
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 )
61 self.outputname = f'{self._label}.out'
62 self.errorname = f'{self._label}.err'
64 def update_parameters(self, properties, parameters):
65 """Check and update the parameters to match the desired calculation
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.
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
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']
98 return parameters
100 def write_input(self, profile, directory, atoms, parameters, properties):
101 """Write the geometry.in and control.in files for the calculation
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)
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)
121 if scaled is None:
122 scaled = np.all(atoms.pbc)
123 if write_velocities is None:
124 write_velocities = atoms.has('momenta')
126 if geo_constrain is None:
127 geo_constrain = scaled and 'relax_geometry' in parameters
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!')
140 geometry_in = directory / 'geometry.in'
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 )
152 control = directory / 'control.in'
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
160 write_control(control, atoms, parameters)
162 def execute(self, directory, profile):
163 profile.run(directory, None, self.outputname, errorfile=self.errorname)
165 def read_results(self, directory):
166 dst = directory / self.outputname
167 return read(dst, format='aims-output', index=-1).calc.results
169 def load_profile(self, cfg, **kwargs):
170 return AimsProfile.from_config(cfg, self.name, **kwargs)
172 def socketio_argv(self, profile, unixsocket, port):
173 return profile._split_command
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)
182 return dict(use_pimd_wrapper=use_pimd_wrapper, compute_forces=True)
185class Aims(GenericFileIOCalculator):
186 def __init__(
187 self,
188 profile=None,
189 directory='.',
190 **kwargs,
191 ):
192 """Construct the FHI-aims calculator.
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.
199 Arguments:
201 cubes: AimsCube object
202 Cube file specification.
204 tier: int or array of ints
205 Set basis set tier for all atomic species.
207 plus_u : dict
208 For DFT+U. Adds a +U term to one specific shell of the species.
210 kwargs : dict
211 Any of the base class arguments.
213 """
215 super().__init__(
216 template=AimsTemplate(),
217 profile=profile,
218 parameters=kwargs,
219 directory=directory,
220 )
223class AimsCube:
224 "Object to ensure the output of cube files, can be attached to Aims object"
226 def __init__(
227 self,
228 origin=(0, 0, 0),
229 edges=None,
230 points=(50, 50, 50),
231 plots=(),
232 ):
233 """parameters:
235 origin, edges, points:
236 Same as in the FHI-aims output
237 plots:
238 what to print, same names as in FHI-aims"""
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
248 def ncubes(self):
249 """returns the number of cube files to output"""
250 return len(self.plots)
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)
280 def add_plot(self, name):
281 """in case you forgot one ..."""
282 self.plots += [name]
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')