Coverage for ase/calculators/subprocesscalculator.py: 91.28%

195 statements  

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

1import os 

2import pickle 

3import sys 

4from abc import ABC, abstractmethod 

5from subprocess import PIPE, Popen 

6 

7from ase.calculators.calculator import Calculator, all_properties 

8 

9 

10class PackedCalculator(ABC): 

11 """Portable calculator for use via PythonSubProcessCalculator. 

12 

13 This class allows creating and talking to a calculator which 

14 exists inside a different process, possibly with MPI or srun. 

15 

16 Use this when you want to use ASE mostly in serial, but run some 

17 calculations in a parallel Python environment. 

18 

19 Most existing calculators can be used this way through the 

20 NamedPackedCalculator implementation. To customize the behaviour 

21 for other calculators, write a custom class inheriting this one. 

22 

23 Example:: 

24 

25 from ase.build import bulk 

26 

27 atoms = bulk('Au') 

28 pack = NamedPackedCalculator('emt') 

29 

30 with pack.calculator() as atoms.calc: 

31 energy = atoms.get_potential_energy() 

32 

33 The computation takes place inside a subprocess which lives as long 

34 as the with statement. 

35 """ 

36 

37 @abstractmethod 

38 def unpack_calculator(self) -> Calculator: 

39 """Return the calculator packed inside. 

40 

41 This method will be called inside the subprocess doing 

42 computations.""" 

43 

44 def calculator(self, mpi_command=None) -> 'PythonSubProcessCalculator': 

45 """Return a PythonSubProcessCalculator for this calculator. 

46 

47 The subprocess calculator wraps a subprocess containing 

48 the actual calculator, and computations are done inside that 

49 subprocess.""" 

50 return PythonSubProcessCalculator(self, mpi_command=mpi_command) 

51 

52 

53class NamedPackedCalculator(PackedCalculator): 

54 """PackedCalculator implementation which works with standard calculators. 

55 

56 This works with calculators known by ase.calculators.calculator.""" 

57 

58 def __init__(self, name, kwargs=None): 

59 self._name = name 

60 if kwargs is None: 

61 kwargs = {} 

62 self._kwargs = kwargs 

63 

64 def unpack_calculator(self): 

65 from ase.calculators.calculator import get_calculator_class 

66 

67 cls = get_calculator_class(self._name) 

68 return cls(**self._kwargs) 

69 

70 def __repr__(self): 

71 return f'{self.__class__.__name__}({self._name}, {self._kwargs})' 

72 

73 

74class MPICommand: 

75 def __init__(self, argv): 

76 self.argv = argv 

77 

78 @classmethod 

79 def python_argv(cls): 

80 return [sys.executable, '-m', 'ase.calculators.subprocesscalculator'] 

81 

82 @classmethod 

83 def parallel(cls, nprocs, mpi_argv=()): 

84 return cls( 

85 ['mpiexec', '-n', str(nprocs)] 

86 + list(mpi_argv) 

87 + cls.python_argv() 

88 + ['mpi4py'] 

89 ) 

90 

91 @classmethod 

92 def serial(cls): 

93 return MPICommand(cls.python_argv() + ['standard']) 

94 

95 def execute(self): 

96 # On this computer (Ubuntu 20.04 + OpenMPI) the subprocess crashes 

97 # without output during startup if os.environ is not passed along. 

98 # Hence we pass os.environ. Not sure if this is a machine thing 

99 # or in general. --askhl 

100 return Popen(self.argv, stdout=PIPE, stdin=PIPE, env=os.environ) 

101 

102 

103def gpaw_process(ncores=1, **kwargs): 

104 packed = NamedPackedCalculator('gpaw', kwargs) 

105 mpicommand = MPICommand( 

106 [ 

107 sys.executable, 

108 '-m', 

109 'gpaw', 

110 '-P', 

111 str(ncores), 

112 'python', 

113 '-m', 

114 'ase.calculators.subprocesscalculator', 

115 'standard', 

116 ] 

117 ) 

118 return PythonSubProcessCalculator(packed, mpicommand) 

119 

120 

121class PythonSubProcessCalculator(Calculator): 

122 """Calculator for running calculations in external processes. 

123 

124 TODO: This should work with arbitrary commands including MPI stuff. 

125 

126 This calculator runs a subprocess wherein it sets up an 

127 actual calculator. Calculations are forwarded through pickle 

128 to that calculator, which returns results through pickle.""" 

129 

130 implemented_properties = list(all_properties) 

131 

132 def __init__(self, calc_input, mpi_command=None): 

133 super().__init__() 

134 

135 # self.proc = None 

136 self.calc_input = calc_input 

137 if mpi_command is None: 

138 mpi_command = MPICommand.serial() 

139 self.mpi_command = mpi_command 

140 

141 self.protocol = None 

142 

143 def set(self, **kwargs): 

144 if hasattr(self, 'client'): 

145 raise RuntimeError('No setting things for now, thanks') 

146 

147 def __repr__(self): 

148 return '{}({})'.format(type(self).__name__, self.calc_input) 

149 

150 def __enter__(self): 

151 assert self.protocol is None 

152 proc = self.mpi_command.execute() 

153 self.protocol = Protocol(proc) 

154 self.protocol.send(self.calc_input) 

155 return self 

156 

157 def __exit__(self, *args): 

158 self.protocol.send('stop') 

159 self.protocol.proc.communicate() 

160 self.protocol = None 

161 

162 def _run_calculation(self, atoms, properties, system_changes): 

163 self.protocol.send('calculate') 

164 self.protocol.send((atoms, properties, system_changes)) 

165 

166 def calculate(self, atoms, properties, system_changes): 

167 Calculator.calculate(self, atoms, properties, system_changes) 

168 # We send a pickle of self.atoms because this is a fresh copy 

169 # of the input, but without an unpicklable calculator: 

170 self._run_calculation(self.atoms.copy(), properties, system_changes) 

171 results = self.protocol.recv() 

172 self.results.update(results) 

173 

174 def backend(self): 

175 return ParallelBackendInterface(self) 

176 

177 

178class Protocol: 

179 def __init__(self, proc): 

180 self.proc = proc 

181 

182 def send(self, obj): 

183 pickle.dump(obj, self.proc.stdin) 

184 self.proc.stdin.flush() 

185 

186 def recv(self): 

187 response_type, value = pickle.load(self.proc.stdout) 

188 

189 if response_type == 'raise': 

190 raise value 

191 

192 assert response_type == 'return' 

193 return value 

194 

195 

196class MockMethod: 

197 def __init__(self, name, calc): 

198 self.name = name 

199 self.calc = calc 

200 

201 def __call__(self, *args, **kwargs): 

202 protocol = self.calc.protocol 

203 protocol.send('callmethod') 

204 protocol.send([self.name, args, kwargs]) 

205 return protocol.recv() 

206 

207 

208class ParallelBackendInterface: 

209 def __init__(self, calc): 

210 self.calc = calc 

211 

212 def __getattr__(self, name): 

213 return MockMethod(name, self.calc) 

214 

215 

216run_modes = {'standard', 'mpi4py'} 

217 

218 

219def callmethod(calc, attrname, args, kwargs): 

220 method = getattr(calc, attrname) 

221 value = method(*args, **kwargs) 

222 return value 

223 

224 

225def callfunction(func, args, kwargs): 

226 return func(*args, **kwargs) 

227 

228 

229def calculate(calc, atoms, properties, system_changes): 

230 # Again we need formalization of the results/outputs, and 

231 # a way to programmatically access all available properties. 

232 # We do a wild hack for now: 

233 calc.results.clear() 

234 # If we don't clear(), the caching is broken! For stress. 

235 # But not for forces. What dark magic from the depths of the 

236 # underworld is at play here? 

237 calc.calculate( 

238 atoms=atoms, properties=properties, system_changes=system_changes 

239 ) 

240 results = calc.results 

241 return results 

242 

243 

244def bad_mode(): 

245 return SystemExit(f'sys.argv[1] must be one of {run_modes}') 

246 

247 

248def parallel_startup(): 

249 try: 

250 run_mode = sys.argv[1] 

251 except IndexError: 

252 raise bad_mode() 

253 

254 if run_mode not in run_modes: 

255 raise bad_mode() 

256 

257 if run_mode == 'mpi4py': 

258 # We must import mpi4py before the rest of ASE, or world will not 

259 # be correctly initialized. 

260 import mpi4py # noqa 

261 

262 # We switch stdout so stray print statements won't interfere with outputs: 

263 binary_stdout = sys.stdout.buffer 

264 sys.stdout = sys.stderr 

265 

266 return Client(input_fd=sys.stdin.buffer, output_fd=binary_stdout) 

267 

268 

269class Client: 

270 def __init__(self, input_fd, output_fd): 

271 from ase.parallel import world 

272 

273 self._world = world 

274 self.input_fd = input_fd 

275 self.output_fd = output_fd 

276 

277 def recv(self): 

278 from ase.parallel import broadcast 

279 

280 if self._world.rank == 0: 

281 obj = pickle.load(self.input_fd) 

282 else: 

283 obj = None 

284 

285 obj = broadcast(obj, 0, self._world) 

286 return obj 

287 

288 def send(self, obj): 

289 if self._world.rank == 0: 

290 pickle.dump(obj, self.output_fd) 

291 self.output_fd.flush() 

292 

293 def mainloop(self, calc): 

294 while True: 

295 instruction = self.recv() 

296 if instruction == 'stop': 

297 return 

298 

299 instruction_data = self.recv() 

300 

301 response_type, value = self.process_instruction( 

302 calc, instruction, instruction_data 

303 ) 

304 self.send((response_type, value)) 

305 

306 def process_instruction(self, calc, instruction, instruction_data): 

307 if instruction == 'callmethod': 

308 function = callmethod 

309 args = (calc, *instruction_data) 

310 elif instruction == 'calculate': 

311 function = calculate 

312 args = (calc, *instruction_data) 

313 elif instruction == 'callfunction': 

314 function = callfunction 

315 args = instruction_data 

316 else: 

317 raise RuntimeError(f'Bad instruction: {instruction}') 

318 

319 try: 

320 value = function(*args) 

321 except Exception as ex: 

322 import traceback 

323 

324 traceback.print_exc() 

325 response_type = 'raise' 

326 value = ex 

327 else: 

328 response_type = 'return' 

329 return response_type, value 

330 

331 

332class ParallelDispatch: 

333 """Utility class to run functions in parallel. 

334 

335 with ParallelDispatch(...) as parallel: 

336 parallel.call(function, args, kwargs) 

337 

338 """ 

339 

340 def __init__(self, mpicommand): 

341 self._mpicommand = mpicommand 

342 self._protocol = None 

343 

344 def call(self, func, *args, **kwargs): 

345 self._protocol.send('callfunction') 

346 self._protocol.send((func, args, kwargs)) 

347 return self._protocol.recv() 

348 

349 def __enter__(self): 

350 assert self._protocol is None 

351 self._protocol = Protocol(self._mpicommand.execute()) 

352 

353 # Even if we are not using a calculator, we have to send one: 

354 pack = NamedPackedCalculator('emt', {}) 

355 self._protocol.send(pack) 

356 # (We should get rid of that requirement.) 

357 

358 return self 

359 

360 def __exit__(self, *args): 

361 self._protocol.send('stop') 

362 self._protocol.proc.communicate() 

363 self._protocol = None 

364 

365 

366def main(): 

367 client = parallel_startup() 

368 pack = client.recv() 

369 calc = pack.unpack_calculator() 

370 client.mainloop(calc) 

371 

372 

373if __name__ == '__main__': 

374 main()