Coverage for ase/calculators/genericfileio.py: 89.66%
116 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
1import shlex
2from abc import ABC, abstractmethod
3from collections.abc import Iterable, Mapping
4from contextlib import ExitStack
5from os import PathLike
6from pathlib import Path
7from typing import Any
9from ase.calculators.abc import GetOutputsMixin
10from ase.calculators.calculator import (
11 BadConfiguration,
12 BaseCalculator,
13 _validate_command,
14)
15from ase.config import cfg as _cfg
17link_calculator_docs = (
18 'https://docs.ase-lib.org/ase/calculators/'
19 'calculators.html#calculator-configuration'
20)
23class BaseProfile(ABC):
24 configvars: set[str] = set()
26 def __init__(self, command):
27 self.command = _validate_command(command)
29 @property
30 def _split_command(self):
31 return shlex.split(self.command)
33 def get_command(self, inputfile, calc_command=None) -> list[str]:
34 """
35 Get the command to run. This should be a list of strings.
37 Parameters
38 ----------
39 inputfile : str
40 calc_command: list[str]: calculator command (used for sockets)
42 Returns
43 -------
44 list of str
45 The command to run.
46 """
47 if calc_command is None:
48 calc_command = self.get_calculator_command(inputfile)
49 return [*self._split_command, *calc_command]
51 @abstractmethod
52 def get_calculator_command(self, inputfile):
53 """
54 The calculator specific command as a list of strings.
56 Parameters
57 ----------
58 inputfile : str
60 Returns
61 -------
62 list of str
63 The command to run.
64 """
66 def run(
67 self,
68 directory: Path,
69 inputfile: str | None,
70 outputfile: str,
71 errorfile: str | None = None,
72 append: bool = False,
73 ) -> None:
74 """
75 Run the command in the given directory.
77 Parameters
78 ----------
79 directory : pathlib.Path
80 The directory to run the command in.
81 inputfile : Optional[str]
82 The name of the input file.
83 outputfile : str
84 The name of the output file.
85 errorfile: Optional[str]
86 the stderror file
87 append: bool
88 if True then use append mode
89 """
91 import os
92 from subprocess import check_call
94 argv_command = self.get_command(inputfile)
95 mode = 'wb' if not append else 'ab'
97 with ExitStack() as stack:
98 output_path = directory / outputfile
99 fd_out = stack.enter_context(open(output_path, mode))
100 if errorfile is not None:
101 error_path = directory / errorfile
102 fd_err = stack.enter_context(open(error_path, mode))
103 else:
104 fd_err = None
105 check_call(
106 argv_command,
107 cwd=directory,
108 stdout=fd_out,
109 stderr=fd_err,
110 env=os.environ,
111 )
113 @abstractmethod
114 def version(self):
115 """Get the version of the code.
117 Returns
118 -------
119 str
120 The version of the code.
121 """
123 @classmethod
124 def from_config(cls, cfg, section_name):
125 """Create a profile from a configuration file.
127 Parameters
128 ----------
129 cfg : ase.config.Config
130 The configuration object.
131 section_name : str
132 The name of the section in the configuration file. E.g. the name
133 of the template that this profile is for.
135 Returns
136 -------
137 BaseProfile
138 The profile object.
139 """
140 section = cfg.parser[section_name]
141 command = section['command']
143 kwargs = {
144 varname: section[varname]
145 for varname in cls.configvars
146 if varname in section
147 }
149 try:
150 return cls(command=command, **kwargs)
151 except TypeError as err:
152 raise BadConfiguration(*err.args)
155def read_stdout(args, createfile=None):
156 """Run command in tempdir and return standard output.
158 Helper function for getting version numbers of DFT codes.
159 Most DFT codes don't implement a --version flag, so in order to
160 determine the code version, we just run the code until it prints
161 a version number."""
162 import tempfile
163 from subprocess import PIPE, Popen
165 with tempfile.TemporaryDirectory() as directory:
166 if createfile is not None:
167 path = Path(directory) / createfile
168 path.touch()
169 proc = Popen(
170 args,
171 stdout=PIPE,
172 stderr=PIPE,
173 stdin=PIPE,
174 cwd=directory,
175 encoding='utf-8', # Make this a parameter if any non-utf8/ascii
176 )
177 stdout, _ = proc.communicate()
178 # Exit code will be != 0 because there isn't an input file
179 return stdout
182class CalculatorTemplate(ABC):
183 def __init__(self, name: str, implemented_properties: Iterable[str]):
184 self.name = name
185 self.implemented_properties = frozenset(implemented_properties)
187 @abstractmethod
188 def write_input(
189 self, profile, directory, atoms, parameters, properties
190 ): ...
192 @abstractmethod
193 def execute(self, directory, profile): ...
195 @abstractmethod
196 def read_results(self, directory: PathLike) -> Mapping[str, Any]: ...
198 @abstractmethod
199 def load_profile(self, cfg): ...
201 def socketio_calculator(
202 self,
203 profile,
204 parameters,
205 directory,
206 # We may need quite a few socket kwargs here
207 # if we want to expose all the timeout etc. from
208 # SocketIOCalculator.
209 unixsocket=None,
210 port=None,
211 ):
212 import os
213 from subprocess import Popen
215 from ase.calculators.socketio import SocketIOCalculator
217 if port and unixsocket:
218 raise TypeError(
219 'For the socketio_calculator only a UNIX '
220 '(unixsocket) or INET (port) socket can be used'
221 ' not both.'
222 )
224 if not port and not unixsocket:
225 raise TypeError(
226 'For the socketio_calculator either a '
227 'UNIX (unixsocket) or INET (port) socket '
228 'must be used'
229 )
231 if not (
232 hasattr(self, 'socketio_argv')
233 and hasattr(self, 'socketio_parameters')
234 ):
235 raise TypeError(
236 f'Template {self} does not implement mandatory '
237 'socketio_argv() and socketio_parameters()'
238 )
240 # XXX need socketio ABC or something
241 argv = profile.get_command(
242 inputfile=None,
243 calc_command=self.socketio_argv(profile, unixsocket, port),
244 )
245 parameters = {
246 **self.socketio_parameters(unixsocket, port),
247 **parameters,
248 }
250 # Not so elegant that socket args are passed to this function
251 # via socketiocalculator when we could make a closure right here.
252 def launch(atoms, properties, port, unixsocket):
253 directory.mkdir(exist_ok=True, parents=True)
255 self.write_input(
256 atoms=atoms,
257 profile=profile,
258 parameters=parameters,
259 properties=properties,
260 directory=directory,
261 )
263 with open(directory / self.outputname, 'w') as out_fd:
264 return Popen(argv, stdout=out_fd, cwd=directory, env=os.environ)
266 return SocketIOCalculator(
267 launch_client=launch, unixsocket=unixsocket, port=port
268 )
271class GenericFileIOCalculator(BaseCalculator, GetOutputsMixin):
272 cfg = _cfg
274 def __init__(
275 self,
276 *,
277 template,
278 profile,
279 directory,
280 parameters=None,
281 ):
282 self.template = template
283 if profile is None:
284 if template.name not in self.cfg.parser:
285 raise BadConfiguration(
286 f"No configuration of '{template.name}'. "
287 f"See '{link_calculator_docs}'"
288 )
289 try:
290 profile = template.load_profile(self.cfg)
291 except Exception as err:
292 configvars = self.cfg.as_dict()
293 raise BadConfiguration(
294 f'Failed to load section [{template.name}] '
295 f'from configuration: {configvars}'
296 ) from err
298 self.profile = profile
300 # Maybe we should allow directory to be a factory, so
301 # calculators e.g. produce new directories on demand.
302 self.directory = Path(directory)
303 super().__init__(parameters)
305 def set(self, *args, **kwargs):
306 raise RuntimeError(
307 'No setting parameters for now, please. '
308 'Just create new calculators.'
309 )
311 def __repr__(self):
312 return f'{type(self).__name__}({self.template.name})'
314 @property
315 def implemented_properties(self):
316 return self.template.implemented_properties
318 @property
319 def name(self):
320 return self.template.name
322 def write_inputfiles(self, atoms, properties):
323 # SocketIOCalculators like to write inputfiles
324 # without calculating.
325 self.directory.mkdir(exist_ok=True, parents=True)
326 self.template.write_input(
327 profile=self.profile,
328 atoms=atoms,
329 parameters=self.parameters,
330 properties=properties,
331 directory=self.directory,
332 )
334 def calculate(self, atoms, properties, system_changes):
335 self.write_inputfiles(atoms, properties)
336 self.template.execute(self.directory, self.profile)
337 self.results = self.template.read_results(self.directory)
338 # XXX Return something useful?
340 def _outputmixin_get_results(self):
341 return self.results
343 def socketio(self, **socketkwargs):
344 return self.template.socketio_calculator(
345 directory=self.directory,
346 parameters=self.parameters,
347 profile=self.profile,
348 **socketkwargs,
349 )