Coverage for ase/calculators/cp2k.py: 81.00%

379 statements  

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

1"""This module defines an ASE interface to CP2K. 

2 

3https://www.cp2k.org/ 

4Author: Ole Schuett <ole.schuett@mat.ethz.ch> 

5""" 

6 

7import os 

8import os.path 

9import subprocess 

10from contextlib import AbstractContextManager 

11from warnings import warn 

12 

13import numpy as np 

14 

15import ase.io 

16from ase.calculators.calculator import ( 

17 Calculator, 

18 CalculatorSetupError, 

19 Parameters, 

20 all_changes, 

21) 

22from ase.config import cfg 

23from ase.units import Rydberg 

24 

25 

26class CP2K(Calculator, AbstractContextManager): 

27 """ASE-Calculator for CP2K. 

28 

29 CP2K is a program to perform atomistic and molecular simulations of solid 

30 state, liquid, molecular, and biological systems. It provides a general 

31 framework for different methods such as e.g., density functional theory 

32 (DFT) using a mixed Gaussian and plane waves approach (GPW) and classical 

33 pair and many-body potentials. 

34 

35 CP2K is freely available under the GPL license. 

36 It is written in Fortran 2003 and can be run efficiently in parallel. 

37 

38 Check https://www.cp2k.org about how to obtain and install CP2K. 

39 The CP2K-calculator relies on the CP2K shell mode (``-s`` flag). When a 

40 calculator object is instantiated, it launches CP2K as a subprocess in the 

41 background and communicates with it through stdin/stdout pipes. This has 

42 the advantage that the CP2K process is kept alive for the whole lifetime of 

43 the calculator object, i.e. there is no startup overhead for a sequence 

44 of energy evaluations. Furthermore, the usage of pipes avoids slow file- 

45 system I/O. This mechanism even works for MPI-parallelized runs, because 

46 stdin/stdout of the first rank are forwarded by the MPI-environment to the 

47 mpiexec-process. 

48 

49 The default command is ``cp2k.psmp -s``. To run a parallelized simulation 

50 use something like this:: 

51 

52 CP2K.command="env OMP_NUM_THREADS=2 mpiexec -np 4 cp2k.psmp -s" 

53 

54 The CP2K-shell can be shut down by calling :meth:`close`. 

55 The close method will be called automatically when using the calculator as 

56 part of a with statement:: 

57 

58 with CP2K() as calc: 

59 calc.get_potential_energy(atoms) 

60 

61 The shell will be restarted if you call the calculator object again. 

62 

63 Arguments: 

64 

65 auto_write: bool 

66 Flag to enable the auto-write mode. If enabled the 

67 ``write()`` routine is called after every 

68 calculation, which mimics the behavior of the 

69 ``FileIOCalculator``. Default is ``False``. 

70 basis_set: str 

71 Name of the basis set to be use. 

72 The default is ``DZVP-MOLOPT-SR-GTH``. 

73 basis_set_file: str 

74 Filename of the basis set file. 

75 Default is ``BASIS_MOLOPT``. 

76 Set the environment variable $CP2K_DATA_DIR 

77 to enabled automatic file discovered. 

78 charge: float 

79 The total charge of the system. Default is ``0``. 

80 command: str 

81 The command used to launch the CP2K-shell. 

82 If ``command`` is not passed as an argument to the 

83 constructor, the class-variable ``CP2K.command``, 

84 and then the environment variable 

85 ``$ASE_CP2K_COMMAND`` are checked. 

86 Eventually, ``cp2k.psmp -s`` is used as default. 

87 cutoff: float 

88 The cutoff of the finest grid level. Default is ``400 * Rydberg``. 

89 debug: bool 

90 Flag to enable debug mode. This will print all 

91 communication between the CP2K-shell and the 

92 CP2K-calculator. Default is ``False``. 

93 force_eval_method: str 

94 The method CP2K uses to evaluate energies and forces. 

95 The default is ``Quickstep``, which is CP2K's 

96 module for electronic structure methods like DFT. 

97 inp: str 

98 CP2K input template. If present, the calculator will 

99 augment the template, e.g. with coordinates, and use 

100 it to launch CP2K. Hence, this generic mechanism 

101 gives access to all features of CP2K. 

102 Note, that most keywords accept ``None`` to disable the generation 

103 of the corresponding input section. 

104 

105 This input template is important for advanced CP2K 

106 inputs, but is also needed for e.g. controlling the Brillouin 

107 zone integration. The example below illustrates some common 

108 options:: 

109 

110 inp = '''&FORCE_EVAL 

111 &DFT 

112 &KPOINTS 

113 SCHEME MONKHORST-PACK 12 12 8 

114 &END KPOINTS 

115 &SCF 

116 ADDED_MOS 10 

117 &SMEAR 

118 METHOD FERMI_DIRAC 

119 ELECTRONIC_TEMPERATURE [K] 500.0 

120 &END SMEAR 

121 &END SCF 

122 &END DFT 

123 &END FORCE_EVAL 

124 ''' 

125 

126 max_scf: int 

127 Maximum number of SCF iteration to be performed for 

128 one optimization. Default is ``50``. 

129 multiplicity: int, default=None 

130 Select the multiplicity of the system 

131 (two times the total spin plus one). 

132 If None, multiplicity is not explicitly given in the input file. 

133 poisson_solver: str 

134 The poisson solver to be used. Currently, the only supported 

135 values are ``auto`` and ``None``. Default is ``auto``. 

136 potential_file: str 

137 Filename of the pseudo-potential file. 

138 Default is ``POTENTIAL``. 

139 Set the environment variable $CP2K_DATA_DIR 

140 to enabled automatic file discovered. 

141 pseudo_potential: str 

142 Name of the pseudo-potential to be use. 

143 Default is ``auto``. This tries to infer the 

144 potential from the employed XC-functional, 

145 otherwise it falls back to ``GTH-PBE``. 

146 stress_tensor: bool 

147 Indicates whether the analytic stress-tensor should be calculated. 

148 Default is ``True``. 

149 uks: bool 

150 Requests an unrestricted Kohn-Sham calculations. 

151 This is need for spin-polarized systems, ie. with an 

152 odd number of electrons. Default is ``False``. 

153 xc: str 

154 Name of exchange and correlation functional. 

155 Accepts all functions supported by CP2K itself or libxc. 

156 Default is ``LDA``. 

157 print_level: str 

158 PRINT_LEVEL of global output. 

159 Possible options are: 

160 DEBUG Everything is written out, useful for debugging purposes only 

161 HIGH Lots of output 

162 LOW Little output 

163 MEDIUM Quite some output 

164 SILENT Almost no output 

165 Default is 'LOW' 

166 set_pos_file: bool 

167 Send updated positions to the CP2K shell via file instead of 

168 via stdin, which can bypass limitations for sending large 

169 structures via stdin for CP2K built with some MPI libraries. 

170 Requires CP2K 2024.2 

171 """ 

172 

173 implemented_properties = ['energy', 'free_energy', 'forces', 'stress'] 

174 command = None 

175 

176 default_parameters = dict( 

177 auto_write=False, 

178 basis_set='DZVP-MOLOPT-SR-GTH', 

179 basis_set_file='BASIS_MOLOPT', 

180 charge=0, 

181 cutoff=400 * Rydberg, 

182 force_eval_method='Quickstep', 

183 inp='', 

184 max_scf=50, 

185 multiplicity=None, 

186 potential_file='POTENTIAL', 

187 pseudo_potential='auto', 

188 stress_tensor=True, 

189 uks=False, 

190 poisson_solver='auto', 

191 xc='LDA', 

192 print_level='LOW', 

193 set_pos_file=False, 

194 ) 

195 

196 def __init__( 

197 self, 

198 restart=None, 

199 ignore_bad_restart_file=Calculator._deprecated, 

200 label='cp2k', 

201 atoms=None, 

202 command=None, 

203 debug=False, 

204 **kwargs, 

205 ): 

206 """Construct CP2K-calculator object.""" 

207 

208 self._debug = debug 

209 self._force_env_id = None 

210 self._shell = None 

211 self.label = None 

212 self.parameters = None 

213 self.results = None 

214 self.atoms = None 

215 

216 # Several places are check to determine self.command 

217 if command is not None: 

218 self.command = command 

219 elif CP2K.command is not None: 

220 self.command = CP2K.command 

221 elif cfg.parser.get('cp2k', 'cp2k_shell', fallback=None): 

222 self.command = cfg.parser.get('cp2k', 'cp2k_shell') 

223 else: 

224 self.command = cfg.get('ASE_CP2K_COMMAND', 'cp2k.psmp -s') 

225 

226 super().__init__( 

227 restart=restart, 

228 ignore_bad_restart_file=ignore_bad_restart_file, 

229 label=label, 

230 atoms=atoms, 

231 **kwargs, 

232 ) 

233 if restart is not None: 

234 self.read(restart) 

235 

236 # Start the shell by default, which is how SocketIOCalculator 

237 self._shell = Cp2kShell(self.command, self._debug) 

238 

239 def __del__(self): 

240 """Terminate cp2k_shell child process""" 

241 self.close() 

242 

243 def __exit__(self, __exc_type, __exc_value, __traceback): 

244 self.close() 

245 

246 def close(self): 

247 """Close the attached shell""" 

248 if self._shell is not None: 

249 self._shell.close() 

250 self._shell = None 

251 self._force_env_id = None # Force env must be recreated 

252 

253 def set(self, **kwargs): 

254 """Set parameters like set(key1=value1, key2=value2, ...).""" 

255 msg = ( 

256 '"%s" is not a known keyword for the CP2K calculator. ' 

257 'To access all features of CP2K by means of an input ' 

258 'template, consider using the "inp" keyword instead.' 

259 ) 

260 for key in kwargs: 

261 if key not in self.default_parameters: 

262 raise CalculatorSetupError(msg % key) 

263 

264 changed_parameters = Calculator.set(self, **kwargs) 

265 if changed_parameters: 

266 self.reset() 

267 

268 def write(self, label): 

269 "Write atoms, parameters and calculated results into restart files." 

270 if self._debug: 

271 print('Writing restart to: ', label) 

272 self.atoms.write(label + '_restart.traj') 

273 self.parameters.write(label + '_params.ase') 

274 from ase.io.jsonio import write_json 

275 

276 with open(label + '_results.json', 'w') as fd: 

277 write_json(fd, self.results) 

278 

279 def read(self, label): 

280 "Read atoms, parameters and calculated results from restart files." 

281 self.atoms = ase.io.read(label + '_restart.traj') 

282 self.parameters = Parameters.read(label + '_params.ase') 

283 from ase.io.jsonio import read_json 

284 

285 with open(label + '_results.json') as fd: 

286 self.results = read_json(fd) 

287 

288 def calculate( 

289 self, atoms=None, properties=None, system_changes=all_changes 

290 ): 

291 """Do the calculation.""" 

292 

293 if not properties: 

294 properties = ['energy'] 

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

296 

297 # Start the shell if needed 

298 if self._shell is None: 

299 self._shell = Cp2kShell(self.command, self._debug) 

300 

301 if self._debug: 

302 print('system_changes:', system_changes) 

303 

304 if 'numbers' in system_changes: 

305 self._release_force_env() 

306 

307 if self._force_env_id is None: 

308 self._create_force_env() 

309 

310 # enable eV and Angstrom as units 

311 self._shell.send('UNITS_EV_A') 

312 self._shell.expect('* READY') 

313 

314 n_atoms = len(self.atoms) 

315 if 'cell' in system_changes: 

316 cell = self.atoms.get_cell() 

317 self._shell.send('SET_CELL %d' % self._force_env_id) 

318 for i in range(3): 

319 self._shell.send('%.18e %.18e %.18e' % tuple(cell[i, :])) 

320 self._shell.expect('* READY') 

321 

322 if 'positions' in system_changes: 

323 if self.parameters.set_pos_file: 

324 # TODO: Update version number when released 

325 if self._shell.version < 7: 

326 raise ValueError('SET_POS_FILE requires > CP2K 2024.2') 

327 pos: np.ndarray = self.atoms.get_positions() 

328 fn = self.label + '.pos' 

329 with open(fn, 'w') as fp: 

330 print(3 * n_atoms, file=fp) 

331 for pos in self.atoms.get_positions(): 

332 print('%.18e %.18e %.18e' % tuple(pos), file=fp) 

333 self._shell.send(f'SET_POS_FILE {fn} {self._force_env_id}') 

334 else: 

335 if len(atoms) > 100 and 'psmp' in self.command: 

336 warn( 

337 'ASE may stall when passing large structures' 

338 ' to MPI versions of CP2K.' 

339 ' Consider using `set_pos_file=True`.' 

340 ) 

341 self._shell.send('SET_POS %d' % self._force_env_id) 

342 self._shell.send('%d' % (3 * n_atoms)) 

343 for pos in self.atoms.get_positions(): 

344 self._shell.send('%.18e %.18e %.18e' % tuple(pos)) 

345 self._shell.send('*END') 

346 max_change = float(self._shell.recv()) 

347 assert max_change >= 0 # sanity check 

348 self._shell.expect('* READY') 

349 

350 self._shell.send('EVAL_EF %d' % self._force_env_id) 

351 self._shell.expect('* READY') 

352 

353 self._shell.send('GET_E %d' % self._force_env_id) 

354 self.results['energy'] = float(self._shell.recv()) 

355 self.results['free_energy'] = self.results['energy'] 

356 self._shell.expect('* READY') 

357 

358 forces = np.zeros(shape=(n_atoms, 3)) 

359 self._shell.send('GET_F %d' % self._force_env_id) 

360 nvals = int(self._shell.recv()) 

361 assert nvals == 3 * n_atoms # sanity check 

362 for i in range(n_atoms): 

363 line = self._shell.recv() 

364 forces[i, :] = [float(x) for x in line.split()] 

365 self._shell.expect('* END') 

366 self._shell.expect('* READY') 

367 self.results['forces'] = forces 

368 

369 self._shell.send('GET_STRESS %d' % self._force_env_id) 

370 line = self._shell.recv() 

371 self._shell.expect('* READY') 

372 

373 stress = np.array([float(x) for x in line.split()]).reshape(3, 3) 

374 assert np.all(stress == np.transpose(stress)) # should be symmetric 

375 # Convert 3x3 stress tensor to Voigt form as required by ASE 

376 stress = np.array( 

377 [ 

378 stress[0, 0], 

379 stress[1, 1], 

380 stress[2, 2], 

381 stress[1, 2], 

382 stress[0, 2], 

383 stress[0, 1], 

384 ] 

385 ) 

386 self.results['stress'] = -1.0 * stress # cp2k uses the opposite sign 

387 

388 if self.parameters.auto_write: 

389 self.write(self.label) 

390 

391 def _create_force_env(self): 

392 """Instantiates a new force-environment""" 

393 assert self._force_env_id is None 

394 label_dir = os.path.dirname(self.label) 

395 if len(label_dir) > 0 and not os.path.exists(label_dir): 

396 print('Creating directory: ' + label_dir) 

397 os.makedirs(label_dir) # cp2k expects dirs to exist 

398 

399 inp = self._generate_input() 

400 inp_fn = self.label + '.inp' 

401 out_fn = self.label + '.out' 

402 self._write_file(inp_fn, inp) 

403 self._shell.send(f'LOAD {inp_fn} {out_fn}') 

404 self._force_env_id = int(self._shell.recv()) 

405 assert self._force_env_id > 0 

406 self._shell.expect('* READY') 

407 

408 def _write_file(self, fn, content): 

409 """Write content to a file""" 

410 if self._debug: 

411 print('Writting to file: ' + fn) 

412 print(content) 

413 if self._shell.version < 2.0: 

414 with open(fn, 'w') as fd: 

415 fd.write(content) 

416 else: 

417 lines = content.split('\n') 

418 if self._shell.version < 2.1: 

419 lines = [l.strip() for l in lines] # save chars 

420 self._shell.send('WRITE_FILE') 

421 self._shell.send(fn) 

422 self._shell.send('%d' % len(lines)) 

423 for line in lines: 

424 self._shell.send(line) 

425 self._shell.send('*END') 

426 self._shell.expect('* READY') 

427 

428 def _release_force_env(self): 

429 """Destroys the current force-environment""" 

430 if self._force_env_id: 

431 if self._shell.isready: 

432 self._shell.send('DESTROY %d' % self._force_env_id) 

433 self._shell.expect('* READY') 

434 else: 

435 msg = 'CP2K-shell not ready, could not release force_env.' 

436 warn(msg, RuntimeWarning) 

437 self._force_env_id = None 

438 

439 def _generate_input(self): 

440 """Generates a CP2K input file""" 

441 p = self.parameters 

442 root = parse_input(p.inp) 

443 root.add_keyword('GLOBAL', 'PROJECT ' + self.label) 

444 if p.print_level: 

445 root.add_keyword('GLOBAL', 'PRINT_LEVEL ' + p.print_level) 

446 if p.force_eval_method: 

447 root.add_keyword('FORCE_EVAL', 'METHOD ' + p.force_eval_method) 

448 if p.stress_tensor: 

449 root.add_keyword('FORCE_EVAL', 'STRESS_TENSOR ANALYTICAL') 

450 root.add_keyword( 

451 'FORCE_EVAL/PRINT/STRESS_TENSOR', '_SECTION_PARAMETERS_ ON' 

452 ) 

453 if p.basis_set_file: 

454 root.add_keyword( 

455 'FORCE_EVAL/DFT', 'BASIS_SET_FILE_NAME ' + p.basis_set_file 

456 ) 

457 if p.potential_file: 

458 root.add_keyword( 

459 'FORCE_EVAL/DFT', 'POTENTIAL_FILE_NAME ' + p.potential_file 

460 ) 

461 if p.cutoff: 

462 root.add_keyword( 

463 'FORCE_EVAL/DFT/MGRID', 'CUTOFF [eV] %.18e' % p.cutoff 

464 ) 

465 if p.max_scf: 

466 root.add_keyword('FORCE_EVAL/DFT/SCF', 'MAX_SCF %d' % p.max_scf) 

467 root.add_keyword('FORCE_EVAL/DFT/LS_SCF', 'MAX_SCF %d' % p.max_scf) 

468 

469 if p.xc: 

470 legacy_libxc = '' 

471 for functional in p.xc.split(): 

472 functional = functional.replace('LDA', 'PADE') # resolve alias 

473 xc_sec = root.get_subsection('FORCE_EVAL/DFT/XC/XC_FUNCTIONAL') 

474 # libxc input section changed over time 

475 if functional.startswith('XC_') and self._shell.version < 3.0: 

476 legacy_libxc += ' ' + functional # handled later 

477 elif functional.startswith('XC_') and self._shell.version < 5.0: 

478 s = InputSection(name='LIBXC') 

479 s.keywords.append('FUNCTIONAL ' + functional) 

480 xc_sec.subsections.append(s) 

481 elif functional.startswith('XC_'): 

482 s = InputSection(name=functional[3:]) 

483 xc_sec.subsections.append(s) 

484 else: 

485 s = InputSection(name=functional.upper()) 

486 xc_sec.subsections.append(s) 

487 if legacy_libxc: 

488 root.add_keyword( 

489 'FORCE_EVAL/DFT/XC/XC_FUNCTIONAL/LIBXC', 

490 'FUNCTIONAL ' + legacy_libxc, 

491 ) 

492 

493 if p.uks: 

494 root.add_keyword('FORCE_EVAL/DFT', 'UNRESTRICTED_KOHN_SHAM ON') 

495 

496 if p.multiplicity: 

497 root.add_keyword( 

498 'FORCE_EVAL/DFT', 'MULTIPLICITY %d' % p.multiplicity 

499 ) 

500 

501 if p.charge and p.charge != 0: 

502 root.add_keyword('FORCE_EVAL/DFT', 'CHARGE %d' % p.charge) 

503 

504 # add Poisson solver if needed 

505 if p.poisson_solver == 'auto' and not any(self.atoms.get_pbc()): 

506 root.add_keyword('FORCE_EVAL/DFT/POISSON', 'PERIODIC NONE') 

507 root.add_keyword('FORCE_EVAL/DFT/POISSON', 'PSOLVER MT') 

508 

509 # write coords 

510 syms = self.atoms.get_chemical_symbols() 

511 atoms = self.atoms.get_positions() 

512 for elm, pos in zip(syms, atoms): 

513 line = f'{elm} {pos[0]:.18e} {pos[1]:.18e} {pos[2]:.18e}' 

514 root.add_keyword('FORCE_EVAL/SUBSYS/COORD', line, unique=False) 

515 

516 # write cell 

517 pbc = ''.join([a for a, b in zip('XYZ', self.atoms.get_pbc()) if b]) 

518 if len(pbc) == 0: 

519 pbc = 'NONE' 

520 root.add_keyword('FORCE_EVAL/SUBSYS/CELL', 'PERIODIC ' + pbc) 

521 c = self.atoms.get_cell() 

522 for i, a in enumerate('ABC'): 

523 line = f'{a} {c[i, 0]:.18e} {c[i, 1]:.18e} {c[i, 2]:.18e}' 

524 root.add_keyword('FORCE_EVAL/SUBSYS/CELL', line) 

525 

526 # determine pseudo-potential 

527 potential = p.pseudo_potential 

528 if p.pseudo_potential == 'auto': 

529 if p.xc and p.xc.upper() in ( 

530 'LDA', 

531 'PADE', 

532 'BP', 

533 'BLYP', 

534 'PBE', 

535 ): 

536 potential = 'GTH-' + p.xc.upper() 

537 else: 

538 msg = 'No matching pseudo potential found, using GTH-PBE' 

539 warn(msg, RuntimeWarning) 

540 potential = 'GTH-PBE' # fall back 

541 

542 # write atomic kinds 

543 subsys = root.get_subsection('FORCE_EVAL/SUBSYS').subsections 

544 kinds = {s.params: s for s in subsys if s.name == 'KIND'} 

545 for elem in set(self.atoms.get_chemical_symbols()): 

546 if elem not in kinds.keys(): 

547 s = InputSection(name='KIND', params=elem) 

548 subsys.append(s) 

549 kinds[elem] = s 

550 if p.basis_set: 

551 kinds[elem].keywords.append('BASIS_SET ' + p.basis_set) 

552 if potential: 

553 kinds[elem].keywords.append('POTENTIAL ' + potential) 

554 

555 output_lines = ['!!! Generated by ASE !!!'] + root.write() 

556 return '\n'.join(output_lines) 

557 

558 

559class Cp2kShell: 

560 """Wrapper for CP2K-shell child-process""" 

561 

562 def __init__(self, command, debug): 

563 """Construct CP2K-shell object""" 

564 

565 self.isready = False 

566 self.version = 1.0 # assume oldest possible version until verified 

567 self._debug = debug 

568 

569 # launch cp2k_shell child process 

570 if self._debug: 

571 print(command) 

572 self._child = subprocess.Popen( 

573 command, 

574 shell=True, 

575 universal_newlines=True, 

576 stdin=subprocess.PIPE, 

577 stdout=subprocess.PIPE, 

578 bufsize=1, 

579 ) 

580 

581 # Check successful startup 

582 # Ignore startup noise, like the banner on SIRIUS builds 

583 max_startup_lines = 1000 

584 for _ in range(max_startup_lines): 

585 line = self.recv() 

586 if line == '* READY': 

587 break 

588 else: 

589 raise RuntimeError( 

590 'Did not receive "* READY" after starting CP2K shell.' 

591 ) 

592 

593 # check version of shell 

594 self.send('VERSION') 

595 line = self.recv() 

596 if not line.startswith('CP2K Shell Version:'): 

597 raise RuntimeError( 

598 'Cannot determine version of CP2K shell. ' 

599 'Probably the shell version is too old. ' 

600 'Please update to CP2K 3.0 or newer. ' 

601 f'Received: {line}' 

602 ) 

603 

604 shell_version = line.rsplit(':', 1)[1] 

605 self.version = float(shell_version) 

606 assert self.version >= 1.0 

607 

608 self.expect('* READY') 

609 

610 # enable harsh mode, stops on any error 

611 self.send('HARSH') 

612 self.expect('* READY') 

613 

614 def __del__(self): 

615 """Terminate cp2k_shell child process""" 

616 self.close() 

617 

618 def close(self): 

619 """Terminate cp2k_shell child process""" 

620 if self.isready: 

621 self.send('EXIT') 

622 self._child.communicate() 

623 rtncode = self._child.wait() 

624 assert rtncode == 0 # child process exited properly? 

625 elif getattr(self, '_child', None) is not None: 

626 warn('CP2K-shell not ready, sending SIGTERM.', RuntimeWarning) 

627 self._child.terminate() 

628 self._child.communicate() 

629 self._child = None 

630 self.version = None 

631 self.isready = False 

632 

633 def send(self, line): 

634 """Send a line to the cp2k_shell""" 

635 assert self._child.poll() is None # child process still alive? 

636 if self._debug: 

637 print('Sending: ' + line) 

638 if self.version < 2.1 and len(line) >= 80: 

639 raise Exception('Buffer overflow, upgrade CP2K to r16779 or later') 

640 assert len(line) < 800 # new input buffer size 

641 self.isready = False 

642 self._child.stdin.write(line + '\n') 

643 

644 def recv(self): 

645 """Receive a line from the cp2k_shell""" 

646 assert self._child.poll() is None # child process still alive? 

647 line = self._child.stdout.readline().strip() 

648 if self._debug: 

649 print('Received: ' + line) 

650 self.isready = line == '* READY' 

651 return line 

652 

653 def expect(self, line): 

654 """Receive a line and asserts that it matches the expected one""" 

655 received = self.recv() 

656 assert received == line 

657 

658 

659class InputSection: 

660 """Represents a section of a CP2K input file""" 

661 

662 def __init__(self, name, params=None): 

663 self.name = name.upper() 

664 self.params = params 

665 self.keywords = [] 

666 self.subsections = [] 

667 

668 def write(self): 

669 """Outputs input section as string""" 

670 output = [] 

671 for k in self.keywords: 

672 output.append(k) 

673 for s in self.subsections: 

674 if s.params: 

675 output.append(f'&{s.name} {s.params}') 

676 else: 

677 output.append(f'&{s.name}') 

678 for l in s.write(): 

679 output.append(f' {l}') 

680 output.append(f'&END {s.name}') 

681 return output 

682 

683 def add_keyword(self, path, line, unique=True): 

684 """Adds a keyword to section.""" 

685 parts = path.upper().split('/', 1) 

686 candidates = [s for s in self.subsections if s.name == parts[0]] 

687 if len(candidates) == 0: 

688 s = InputSection(name=parts[0]) 

689 self.subsections.append(s) 

690 candidates = [s] 

691 elif len(candidates) != 1: 

692 raise Exception(f'Multiple {parts[0]} sections found ') 

693 

694 key = line.split()[0].upper() 

695 if len(parts) > 1: 

696 candidates[0].add_keyword(parts[1], line, unique) 

697 elif key == '_SECTION_PARAMETERS_': 

698 if candidates[0].params is not None: 

699 msg = f'Section parameter of section {parts[0]} already set' 

700 raise Exception(msg) 

701 candidates[0].params = line.split(' ', 1)[1].strip() 

702 else: 

703 old_keys = [k.split()[0].upper() for k in candidates[0].keywords] 

704 if unique and key in old_keys: 

705 msg = 'Keyword %s already present in section %s' 

706 raise Exception(msg % (key, parts[0])) 

707 candidates[0].keywords.append(line) 

708 

709 def get_subsection(self, path): 

710 """Finds a subsection""" 

711 parts = path.upper().split('/', 1) 

712 candidates = [s for s in self.subsections if s.name == parts[0]] 

713 if len(candidates) > 1: 

714 raise Exception(f'Multiple {parts[0]} sections found ') 

715 if len(candidates) == 0: 

716 s = InputSection(name=parts[0]) 

717 self.subsections.append(s) 

718 candidates = [s] 

719 if len(parts) == 1: 

720 return candidates[0] 

721 return candidates[0].get_subsection(parts[1]) 

722 

723 

724def parse_input(inp): 

725 """Parses the given CP2K input string""" 

726 root_section = InputSection('CP2K_INPUT') 

727 section_stack = [root_section] 

728 

729 for line in inp.split('\n'): 

730 line = line.split('!', 1)[0].strip() 

731 if len(line) == 0: 

732 continue 

733 

734 if line.upper().startswith('&END'): 

735 s = section_stack.pop() 

736 elif line[0] == '&': 

737 parts = line.split(' ', 1) 

738 name = parts[0][1:] 

739 if len(parts) > 1: 

740 s = InputSection(name=name, params=parts[1].strip()) 

741 else: 

742 s = InputSection(name=name) 

743 section_stack[-1].subsections.append(s) 

744 section_stack.append(s) 

745 else: 

746 section_stack[-1].keywords.append(line) 

747 

748 return root_section