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

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 

8 

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 

16 

17link_calculator_docs = ( 

18 'https://docs.ase-lib.org/ase/calculators/' 

19 'calculators.html#calculator-configuration' 

20) 

21 

22 

23class BaseProfile(ABC): 

24 configvars: set[str] = set() 

25 

26 def __init__(self, command): 

27 self.command = _validate_command(command) 

28 

29 @property 

30 def _split_command(self): 

31 return shlex.split(self.command) 

32 

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. 

36 

37 Parameters 

38 ---------- 

39 inputfile : str 

40 calc_command: list[str]: calculator command (used for sockets) 

41 

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] 

50 

51 @abstractmethod 

52 def get_calculator_command(self, inputfile): 

53 """ 

54 The calculator specific command as a list of strings. 

55 

56 Parameters 

57 ---------- 

58 inputfile : str 

59 

60 Returns 

61 ------- 

62 list of str 

63 The command to run. 

64 """ 

65 

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. 

76 

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 """ 

90 

91 import os 

92 from subprocess import check_call 

93 

94 argv_command = self.get_command(inputfile) 

95 mode = 'wb' if not append else 'ab' 

96 

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 ) 

112 

113 @abstractmethod 

114 def version(self): 

115 """Get the version of the code. 

116 

117 Returns 

118 ------- 

119 str 

120 The version of the code. 

121 """ 

122 

123 @classmethod 

124 def from_config(cls, cfg, section_name): 

125 """Create a profile from a configuration file. 

126 

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. 

134 

135 Returns 

136 ------- 

137 BaseProfile 

138 The profile object. 

139 """ 

140 section = cfg.parser[section_name] 

141 command = section['command'] 

142 

143 kwargs = { 

144 varname: section[varname] 

145 for varname in cls.configvars 

146 if varname in section 

147 } 

148 

149 try: 

150 return cls(command=command, **kwargs) 

151 except TypeError as err: 

152 raise BadConfiguration(*err.args) 

153 

154 

155def read_stdout(args, createfile=None): 

156 """Run command in tempdir and return standard output. 

157 

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 

164 

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 

180 

181 

182class CalculatorTemplate(ABC): 

183 def __init__(self, name: str, implemented_properties: Iterable[str]): 

184 self.name = name 

185 self.implemented_properties = frozenset(implemented_properties) 

186 

187 @abstractmethod 

188 def write_input( 

189 self, profile, directory, atoms, parameters, properties 

190 ): ... 

191 

192 @abstractmethod 

193 def execute(self, directory, profile): ... 

194 

195 @abstractmethod 

196 def read_results(self, directory: PathLike) -> Mapping[str, Any]: ... 

197 

198 @abstractmethod 

199 def load_profile(self, cfg): ... 

200 

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 

214 

215 from ase.calculators.socketio import SocketIOCalculator 

216 

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 ) 

223 

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 ) 

230 

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 ) 

239 

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 } 

249 

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) 

254 

255 self.write_input( 

256 atoms=atoms, 

257 profile=profile, 

258 parameters=parameters, 

259 properties=properties, 

260 directory=directory, 

261 ) 

262 

263 with open(directory / self.outputname, 'w') as out_fd: 

264 return Popen(argv, stdout=out_fd, cwd=directory, env=os.environ) 

265 

266 return SocketIOCalculator( 

267 launch_client=launch, unixsocket=unixsocket, port=port 

268 ) 

269 

270 

271class GenericFileIOCalculator(BaseCalculator, GetOutputsMixin): 

272 cfg = _cfg 

273 

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 

297 

298 self.profile = profile 

299 

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) 

304 

305 def set(self, *args, **kwargs): 

306 raise RuntimeError( 

307 'No setting parameters for now, please. ' 

308 'Just create new calculators.' 

309 ) 

310 

311 def __repr__(self): 

312 return f'{type(self).__name__}({self.template.name})' 

313 

314 @property 

315 def implemented_properties(self): 

316 return self.template.implemented_properties 

317 

318 @property 

319 def name(self): 

320 return self.template.name 

321 

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 ) 

333 

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? 

339 

340 def _outputmixin_get_results(self): 

341 return self.results 

342 

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 )