Coverage for ase/calculators/exciting/exciting.py: 87.67%
73 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"""ASE Calculator for the ground state exciting DFT code.
3Exciting calculator class in this file allow for writing exciting input
4files using ASE Atoms object that allow for the compiled exciting binary
5to run DFT on the geometry/material defined in the Atoms object. Also gives
6access to developer to a lightweight parser (lighter weight than NOMAD or
7the exciting parser in the exciting repository) to capture ground state
8properties.
10Note: excitingtools must be installed using `pip install excitingtools` to
11use this calculator.
12"""
14from collections.abc import Mapping
15from os import PathLike
16from pathlib import Path
17from typing import Any
19import ase.io.exciting
20from ase.calculators.calculator import PropertyNotImplementedError
21from ase.calculators.exciting.runner import (
22 SimpleBinaryRunner,
23 SubprocessRunResults,
24)
25from ase.calculators.genericfileio import (
26 BaseProfile,
27 CalculatorTemplate,
28 GenericFileIOCalculator,
29)
32class ExcitingProfile(BaseProfile):
33 """Defines all quantities that are configurable for a given machine.
35 Follows the generic pattern BUT currently not used by our calculator as:
36 * species_path is part of the input file in exciting.
37 * OnlyTypo fix part of the profile used in the base class is the run
38 method, which is part of the BinaryRunner class.
39 """
41 configvars = {'species_path'}
43 def __init__(self, command, species_path=None, **kwargs):
44 super().__init__(command, **kwargs)
46 self.species_path = species_path
48 def version(self):
49 """Return exciting version."""
50 # TARP No way to get the version for the binary in use
51 return
53 # Machine specific config files in the config
54 # species_file goes in the config
55 # binary file in the config.
56 # options for that, parallel info dictionary.
57 # Number of threads and stuff like that.
59 def get_calculator_command(self, input_file):
60 """Returns command to run binary as a list of strings."""
61 # input_file unused for exciting, it looks for input.xml in run
62 # directory.
63 if input_file is None:
64 return []
65 else:
66 return [str(input_file)]
69class ExcitingGroundStateTemplate(CalculatorTemplate):
70 """Template for Ground State Exciting Calculator
72 Abstract methods inherited from the base class:
73 * write_input
74 * execute
75 * read_results
76 """
78 parser = {'info.xml': ase.io.exciting.parse_output}
79 output_names = list(parser)
80 # Use frozenset since the CalculatorTemplate enforces it.
81 implemented_properties = frozenset(['energy', 'forces'])
82 _label = 'exciting'
84 def __init__(self):
85 super().__init__('exciting', self.implemented_properties)
86 self.errorname = f'{self._label}.err'
88 @staticmethod
89 def _require_forces(input_parameters):
90 """Expect ASE always wants forces, enforce setting in input_parameters.
92 Parameters
93 ----------
94 input_parameters : dict | ExcitingGroundStateInput
95 Exciting ground state input parameters.
97 Returns
98 -------
99 ExcitingGroundStateInput
100 Ground state input parameters, with "compute forces" set to true.
102 """
103 from excitingtools import ExcitingGroundStateInput
105 input_parameters = ExcitingGroundStateInput(input_parameters)
106 input_parameters.tforce = True
107 return input_parameters
109 def write_input(
110 self,
111 profile: ExcitingProfile, # ase test linter enforces method signatures
112 # be consistent with the
113 # abstract method that it implements
114 directory: PathLike,
115 atoms: ase.Atoms,
116 parameters: dict,
117 properties=None,
118 ):
119 """Write an exciting input.xml file based on the input args.
121 Parameters
122 ----------
123 profile : ExcitingProfile
124 Exciting code profile.
125 directory : PathLike
126 Directory in which to run calculator.
127 atoms : Atoms
128 ASE Atoms object.
129 parameters : dict
130 Exciting ground state input parameters, in a dictionary.
131 Expect species_path, title and ground_state data,
132 either in an object or as dict.
133 properties : None
134 Base method's API expects the physical properties
135 expected from a ground state calculation, for example energies
136 and forces. For us this is not used.
138 """
139 # Create a copy of the parameters dictionary so we don't
140 # modify the callers dictionary.
141 parameters_dict = parameters
142 required_keys = {'title', 'species_path', 'ground_state_input'}
143 assert required_keys <= set(parameters_dict)
144 file_name = Path(directory) / 'input.xml'
145 species_path = parameters_dict.pop('species_path')
146 title = parameters_dict.pop('title')
147 # We can also pass additional parameters which are actually called
148 # properties in the exciting input xml. We don't use this term
149 # since ASE use properties to refer to results of a calculation
150 # (e.g. force, energy).
151 if 'properties_input' not in parameters_dict:
152 parameters_dict['properties_input'] = None
154 ase.io.exciting.write_input_xml_file(
155 file_name=file_name,
156 atoms=atoms,
157 ground_state_input=parameters_dict['ground_state_input'],
158 species_path=species_path,
159 title=title,
160 properties_input=parameters_dict['properties_input'],
161 )
163 def execute(self, directory: PathLike, profile) -> SubprocessRunResults:
164 """Given an exciting calculation profile, execute the calculation.
166 When executing an exciting calculation, you need to call run on an
167 exciting binary runner which is stored as the profile variable. The
168 binary runner at initialization will set all of the directory
169 information so we don't use this variable again here.
171 Parameters
172 ----------
173 directory : PathLike
174 Not used but comes from the base class.
175 profile
176 This name comes from the superclass CalculatorTemplate.
177 It should be an instance of an exciting.runner.SimpleBinaryRunner.
179 Returns
180 -------
181 SubprocessRunResults
182 Results of the subprocess.run command.
184 """
185 return profile.run()
187 def read_results(self, directory: PathLike) -> Mapping[str, Any]:
188 """Parse results from each ground state output file.
190 Note we allow for the ability for there to be multiple output files.
192 Parameters
193 ----------
194 directory : PathLike
195 Directory path to output file from exciting simulation.
197 Returns
198 -------
199 Mapping[str, Any]
200 dictionary of results. This can be fed into
201 ExcitingGroundStateResults if the user wants to access properties
202 more easily.
204 """
205 results = {}
206 for file_name in self.output_names:
207 full_file_path = Path(directory) / file_name
208 result: dict = self.parser[file_name](full_file_path)
209 results.update(result)
210 return results
212 def load_profile(self, cfg, **kwargs):
213 """ExcitingProfile can be created via a config file.
215 Alternative to this method the profile can be created with it's
216 init method. This method allows for more settings to be passed.
217 """
218 return ExcitingProfile.from_config(cfg, self.name, **kwargs)
221class ExcitingGroundStateResults:
222 """Exciting Ground State Results."""
224 def __init__(self, results: dict) -> None:
225 self.results = results
226 self.final_scl_iteration = list(results['scl'].keys())[-1]
228 def total_energy(self) -> float:
229 """Return total energy of system."""
230 # TODO(Alex) We should a common list of keys somewhere
231 # such that parser -> results -> getters are consistent
232 return float(
233 self.results['scl'][self.final_scl_iteration]['Total energy']
234 )
236 def band_gap(self) -> float:
237 """Return the estimated fundamental gap from the exciting sim."""
238 return float(
239 self.results['scl'][self.final_scl_iteration][
240 'Estimated fundamental gap'
241 ]
242 )
244 def forces(self):
245 """Return forces present on the system.
247 Currently, not all exciting simulations return forces. We leave this
248 definition for future revisions.
249 """
250 raise PropertyNotImplementedError
252 def stress(self):
253 """Get the stress on the system.
255 Right now exciting does not yet calculate the stress on the system so
256 this won't work for the time being.
257 """
258 raise PropertyNotImplementedError
261class ExcitingGroundStateCalculator(GenericFileIOCalculator):
262 """Class for the ground state calculation.
264 Parameters
265 ----------
266 runner : SimpleBinaryRunner
267 Binary runner that will execute an exciting calculation and
268 return a result.
269 ground_state_input : dict | ExcitingGroundStateInput
270 Dictionary of ground state settings for example
271 {'rgkmax': 8.0, 'autormt': True} or an object of type
272 ExcitingGroundStateInput.
273 directory : str
274 Directory in which to run the job.
275 species_path : str
276 Path to the location of exciting's species files.
277 title : str, default: 'ASE-generated input'
278 Job name written to input.xml.
280 Examples
281 --------
282 >>> atoms: Atoms
283 >>> gs_calculator = ExcitingGroundState(runner, ground_state_input)
284 >>> results: ExcitingGroundStateResults = gs_calculator.calculate(atoms)
286 """
288 def __init__(
289 self,
290 *,
291 runner: SimpleBinaryRunner,
292 ground_state_input,
293 directory='./',
294 species_path='./',
295 title='ASE-generated input',
296 parameters: dict[str, Any] | None = None,
297 ):
298 self.runner = runner
299 # Package data to be passed to
300 # ExcitingGroundStateTemplate.write_input(..., input_parameters, ...)
301 # Structure not included, as it's passed when one calls .calculate
302 # method directly.
303 required_params = {
304 'title': title,
305 'species_path': species_path,
306 'ground_state_input': ground_state_input,
307 }
308 # Set parameters to an empty dict if it is None (or Falsey). This
309 # is needed for the next line.
310 parameters = parameters or {}
311 # Add key, value paris from required_params if they are not defined
312 # in parmaters.
313 parameters = required_params | parameters
314 # GenericFileIOCalculator expects a `profile`
315 # containing machine-specific settings, however, in exciting's case,
316 # the species file are defined in the input XML (hence passed in the
317 # parameters argument) and the only other machine-specific setting is
318 # the BinaryRunner. Furthermore, in GenericFileIOCalculator.calculate,
319 # profile is only used to provide a run method. We therefore pass the
320 # BinaryRunner in the place of a profile.
321 super().__init__(
322 profile=runner,
323 template=ExcitingGroundStateTemplate(),
324 directory=directory,
325 parameters=parameters,
326 )