Coverage for ase/io/onetep.py: 83.06%

555 statements  

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

1import re 

2import warnings 

3from copy import deepcopy 

4from os.path import dirname, isfile 

5from pathlib import Path 

6 

7import numpy as np 

8 

9from ase.atoms import Atoms 

10from ase.calculators.singlepoint import SinglePointDFTCalculator 

11from ase.cell import Cell 

12from ase.units import Bohr 

13 

14no_positions_error = ( 

15 'no positions can be read from this onetep output ' 

16 'if you wish to use ASE to read onetep outputs ' 

17 'please use uppercase block positions in your calculations' 

18) 

19 

20unable_to_read = 'unable to read this onetep output file, ending' 

21 

22# taken from onetep source code, 

23# does not seem to be from any known NIST data 

24units = {'Hartree': 27.2116529, 'Bohr': 1 / 1.889726134583548707935} 

25 

26# Want to add a functionality? add a global constant below 

27ONETEP_START = re.compile( 

28 r'(?i)^\s*\|\s*Linear-Scaling\s*Ab\s*' 

29 r'Initio\s*Total\s*Energy\s*Program\s*\|\s*$' 

30) 

31ONETEP_STOP = re.compile(r'(?i)^\s*-+\s*TIMING\s*INFORMATION\s*-+\s*$') 

32ONETEP_TOTAL_ENERGY = re.compile( 

33 r'(?i)^\s*\|\s*\*{3}\s*NGWF\s*' r'optimisation\s*converged\s*\*{3}\s*\|\s*$' 

34) 

35ONETEP_FORCE = re.compile(r'(?i)^\s*\*+\s*Forces\s*\*+\s*$') 

36ONETEP_MULLIKEN = re.compile(r'(?i)^\s*Mulliken\s*Atomic\s*Populations\s*$') 

37ONETEP_SPIN = re.compile(r'(?i)^\s*Down\s*spin\s*density') 

38ONETEP_POSITION = re.compile(r'(?i)^\s*Cell\s*Contents\s*$') 

39ONETEP_FIRST_POSITION = re.compile( 

40 r'^\s*%BLOCK\s*POSITIONS\s*_?\s*(ABS|FRAC)\s*:?\s*([*#!].*)?$' 

41) 

42ONETEP_WRONG_FIRST_POSITION = re.compile( 

43 r'^\s*%block\s*positions\s*_?\s*(abs|frac)\s*:?\s*([*#!].*)?$' 

44) 

45ONETEP_RESUMING_GEOM = re.compile( 

46 r'(?i)^\s*<{16}\s*Resuming\s*previous' 

47 r'\s*ONETEP\s*Geometry\s*Optimisation\s*>{16}\s*$' 

48) 

49 

50ONETEP_ATOM_COUNT = re.compile(r'(?i)^\s*Totals\s*:\s*(\d+\s*)*$') 

51ONETEP_IBFGS_ITER = re.compile(r'(?i)^\s*BFGS\s*:\s*starting\s*iteration') 

52ONETEP_IBFGS_IMPROVE = re.compile(r'(?i)^\s*BFGS\s*:\s*improving\s*iteration') 

53ONETEP_START_GEOM = re.compile( 

54 r'(?i)^<+\s*Starting\s*ONETEP\s*Geometry\s*Optimisation\s*>+$' 

55) 

56ONETEP_END_GEOM = re.compile(r'(?i)^\s*BFGS\s*:\s*Final\s*Configuration:\s*$') 

57 

58ONETEP_SPECIES = re.compile(r'(?i)^\s*%BLOCK\s*SPECIES\s*:?\s*([*#!].*)?$') 

59 

60ONETEP_FIRST_CELL = re.compile( 

61 r'(?i)^\s*%BLOCK\s*LATTICE\s*_?\s*CART\s*:?\s*([*#!].*)?$' 

62) 

63ONETEP_STRESS_CELL = re.compile( 

64 r'(?i)^\s*stress_calculation:\s*cell\s*geometry\s*$' 

65) 

66 

67 

68def get_onetep_keywords(path): 

69 if isinstance(path, str): 

70 with open(path) as fd: 

71 results = read_onetep_in(fd, only_keywords=True) 

72 else: 

73 results = read_onetep_in(path, only_keywords=True) 

74 

75 # If there is an include file, the entire 

76 # file keyword's will be included in the dict 

77 # and the include_file keyword will be deleted 

78 if 'include_file' in results['keywords']: 

79 warnings.warn('include_file will be deleted from the dict') 

80 del results['keywords']['include_file'] 

81 return results['keywords'] 

82 

83 

84def read_onetep_in(fd, **kwargs): 

85 """ 

86 Read a single ONETEP input. 

87 

88 This function can be used to visually check ONETEP inputs, 

89 using the ase gui. It can also be used to get access to 

90 the input parameters attached to the ONETEP calculator 

91 returned 

92 

93 The function should work on inputs which contain 

94 'include_file' command(s), (possibly recursively 

95 but untested) 

96 

97 The function should work on input which contains 

98 exotic element(s) name(s) if the specie block is 

99 present to map them back to real element(s) 

100 

101 Parameters 

102 ---------- 

103 fd : io-object 

104 File to read. 

105 

106 Return 

107 ------ 

108 structure: Atoms 

109 Atoms object with cell and a Onetep calculator 

110 attached which contains the keywords dictionary 

111 """ 

112 

113 fdi_lines = fd.readlines() 

114 

115 try: 

116 fd_path = Path(fd.name).resolve() 

117 fd_parent = fd_path.parent 

118 include_files = [fd_path] 

119 except AttributeError: 

120 # We are in a StringIO or something similar 

121 fd_path = Path().cwd() 

122 fd_parent = fd_path 

123 include_files = [Path().cwd()] 

124 

125 def clean_lines(lines): 

126 """ 

127 Remove indesirable line from the input 

128 """ 

129 new_lines = [] 

130 for line in lines: 

131 sep = re.split(r'[!#]', line.strip())[0] 

132 if sep: 

133 new_lines.append(sep) 

134 return new_lines 

135 

136 # Skip comments and empty lines 

137 fdi_lines = clean_lines(fdi_lines) 

138 

139 # Are we in a block? 

140 block_start = 0 

141 

142 keywords = {} 

143 atoms = Atoms() 

144 cell = np.zeros((3, 3)) 

145 fractional = False 

146 positions = False 

147 symbols = False 

148 

149 # Main loop reading the input 

150 for n, line in enumerate(fdi_lines): 

151 line_lower = line.lower() 

152 if re.search(r'^\s*%block', line_lower): 

153 block_start = n + 1 

154 if re.search(r'lattice_cart$', line_lower): 

155 if re.search(r'^\s*ang\s*$', fdi_lines[block_start]): 

156 cell = np.loadtxt(fdi_lines[n + 2 : n + 5]) 

157 else: 

158 cell = np.loadtxt(fdi_lines[n + 1 : n + 4]) 

159 cell *= Bohr 

160 

161 if not block_start: 

162 if 'devel_code' in line_lower: 

163 warnings.warn('devel_code is not supported') 

164 continue 

165 # Splits line on any valid onetep separator 

166 sep = re.split(r'[:=\s]+', line) 

167 keywords[sep[0]] = ' '.join(sep[1:]) 

168 # If include_file is used, we open the included file 

169 # and insert it in the current fdi_lines... 

170 # ONETEP does not work with cascade 

171 # and this SHOULD NOT work with cascade 

172 if re.search(r'^\s*include_file$', sep[0]): 

173 name = sep[1].replace("'", '') 

174 name = name.replace('"', '') 

175 new_path = fd_parent / name 

176 for path in include_files: 

177 if new_path.samefile(path): 

178 raise ValueError('invalid/recursive include_file') 

179 new_fd = open(new_path) 

180 new_lines = new_fd.readlines() 

181 new_lines = clean_lines(new_lines) 

182 for include_line in new_lines: 

183 sep = re.split(r'[:=\s]+', include_line) 

184 if re.search(r'^\s*include_file$', sep[0]): 

185 raise ValueError('nested include_file') 

186 fdi_lines[:] = ( 

187 fdi_lines[: n + 1] + new_lines + fdi_lines[n + 1 :] 

188 ) 

189 include_files.append(new_path) 

190 continue 

191 

192 if re.search(r'^\s*%endblock', line_lower): 

193 if re.search(r'\s*positions_', line_lower): 

194 head = re.search(r'(?i)^\s*(\S*)\s*$', fdi_lines[block_start]) 

195 head = head.group(1).lower() if head else '' 

196 conv = 1 if head == 'ang' else units['Bohr'] 

197 # Skip one line if head is True 

198 to_read = fdi_lines[block_start + int(bool(head)) : n] 

199 positions = np.loadtxt(to_read, usecols=(1, 2, 3)) 

200 positions *= conv 

201 symbols = np.loadtxt(to_read, usecols=(0), dtype='str') 

202 if re.search(r'.*frac$', line_lower): 

203 fractional = True 

204 elif re.search(r'^\s*%endblock\s*species$', line_lower): 

205 els = fdi_lines[block_start:n] 

206 species = {} 

207 for el in els: 

208 sep = el.split() 

209 species[sep[0]] = sep[1] 

210 to_read = [i.strip() for i in fdi_lines[block_start:n]] 

211 keywords['species'] = to_read 

212 elif re.search(r'lattice_cart$', line_lower): 

213 pass 

214 else: 

215 to_read = [i.strip() for i in fdi_lines[block_start:n]] 

216 block_title = line_lower.replace('%endblock', '').strip() 

217 keywords[block_title] = to_read 

218 block_start = 0 

219 

220 # We don't need a fully valid onetep 

221 # input to read the keywords, just 

222 # the keywords 

223 if kwargs.get('only_keywords', False): 

224 return {'keywords': keywords} 

225 # Necessary if we have only one atom 

226 # Check if the cell is valid (3D) 

227 if not cell.any(axis=1).all(): 

228 raise ValueError('invalid cell specified') 

229 

230 if positions is False: 

231 raise ValueError('invalid position specified') 

232 

233 if symbols is False: 

234 raise ValueError('no symbols found') 

235 

236 positions = positions.reshape(-1, 3) 

237 symbols = symbols.reshape(-1) 

238 tags = [] 

239 info = {'onetep_species': []} 

240 for symbol in symbols: 

241 label = symbol.replace(species[symbol], '') 

242 if label.isdigit(): 

243 tags.append(int(label)) 

244 else: 

245 tags.append(0) 

246 info['onetep_species'].append(symbol) 

247 atoms = Atoms( 

248 [species[i] for i in symbols], cell=cell, pbc=True, tags=tags, info=info 

249 ) 

250 if fractional: 

251 atoms.set_scaled_positions(positions / units['Bohr']) 

252 else: 

253 atoms.set_positions(positions) 

254 results = {'atoms': atoms, 'keywords': keywords} 

255 return results 

256 

257 

258def write_onetep_in( 

259 fd, 

260 atoms, 

261 edft=False, 

262 xc='PBE', 

263 ngwf_count=-1, 

264 ngwf_radius=9.0, 

265 keywords=None, 

266 pseudopotentials=None, 

267 pseudo_path='.', 

268 pseudo_suffix=None, 

269 **kwargs, 

270): 

271 """ 

272 Write a single ONETEP input. 

273 

274 This function will be used by ASE to perform 

275 various workflows (Opt, NEB...) or can be used 

276 manually to quickly create ONETEP input file(s). 

277 

278 The function will first write keywords in 

279 alphabetic order in lowercase. Secondly, blocks 

280 will be written in alphabetic order in uppercase. 

281 

282 Two ways to work with the function: 

283 

284 - By providing only (simple) keywords present in 

285 the parameters. ngwf_count and ngwf_radius 

286 accept multiple types as described in the Parameters 

287 section. 

288 

289 - If the keywords parameters is provided as a dictionary 

290 these keywords will be used to write the input file and 

291 will take priority. 

292 

293 If no pseudopotentials are provided in the parameters and 

294 the function will try to look for suitable pseudopotential 

295 in the pseudo_path. 

296 

297 Parameters 

298 ---------- 

299 fd : file 

300 File to write. 

301 atoms: Atoms 

302 Atoms including Cell object to write. 

303 edft: Bool 

304 Activate EDFT. 

305 xc: str 

306 DFT xc to use e.g (PBE, RPBE, ...) 

307 ngwf_count: int|list|dict 

308 Behaviour depends on the type: 

309 int: every species will have this amount 

310 of ngwfs. 

311 list: list of int, will be attributed 

312 alphabetically to species: 

313 dict: keys are species name(s), 

314 value are their number: 

315 ngwf_radius: int|list|dict 

316 Behaviour depends on the type: 

317 float: every species will have this radius. 

318 list: list of float, will be attributed 

319 alphabetically to species: 

320 [10.0, 9.0] 

321 dict: keys are species name(s), 

322 value are their radius: 

323 {'Na': 9.0, 'Cl': 10.0} 

324 keywords: dict 

325 Dictionary with ONETEP keywords to write, 

326 keywords with lists as values will be 

327 treated like blocks, with each element 

328 of list being a different line. 

329 pseudopotentials: dict 

330 Behaviour depends on the type: 

331 keys are species name(s) their 

332 value are the pseudopotential file to use: 

333 {'Na': 'Na.usp', 'Cl': 'Cl.usp'} 

334 pseudo_path: str 

335 Where to look for pseudopotential, correspond 

336 to the pseudo_path keyword of ONETEP. 

337 pseudo_suffix: str 

338 Suffix for the pseudopotential filename 

339 to look for, useful if you have multiple sets of 

340 pseudopotentials in pseudo_path. 

341 """ 

342 

343 if pseudopotentials is None: 

344 pseudopotentials = {} 

345 if keywords is None: 

346 keywords = {} 

347 label = kwargs.get('label', 'onetep') 

348 try: 

349 directory = kwargs.get('directory', Path(dirname(fd.name))) 

350 except AttributeError: 

351 directory = '.' 

352 autorestart = kwargs.get('autorestart', False) 

353 elements = np.array(atoms.symbols) 

354 tags = np.array(atoms.get_tags()) 

355 species_maybe = atoms.info.get('onetep_species', False) 

356 #  We look if the atom.info contains onetep species information 

357 # If it does, we use it, as it might contains character 

358 #  which are not allowed in ase tags, if not we fall back 

359 # to tags and use them instead. 

360 if species_maybe: 

361 if set(species_maybe) != set(elements): 

362 species = np.array(species_maybe) 

363 else: 

364 species = elements 

365 else: 

366 formatted_tags = np.array(['' if i == 0 else str(i) for i in tags]) 

367 species = np.char.add(elements, formatted_tags) 

368 numbers = np.array(atoms.numbers) 

369 tmp = np.argsort(species) 

370 # We sort both Z and name the same 

371 numbers = np.take_along_axis(numbers, tmp, axis=0) 

372 # u_elements = np.take_along_axis(elements, tmp, axis=0) 

373 u_species = np.take_along_axis(species, tmp, axis=0) 

374 elements = np.take_along_axis(elements, tmp, axis=0) 

375 # We want to keep unique but without sort: small trick with index 

376 idx = np.unique(u_species, return_index=True)[1] 

377 elements = elements[idx] 

378 # Unique species 

379 u_species = u_species[idx] 

380 numbers = numbers[idx] 

381 n_sp = len(u_species) 

382 

383 if isinstance(ngwf_count, int): 

384 ngwf_count = dict(zip(u_species, [ngwf_count] * n_sp)) 

385 elif isinstance(ngwf_count, list): 

386 ngwf_count = dict(zip(u_species, ngwf_count)) 

387 elif isinstance(ngwf_count, dict): 

388 pass 

389 else: 

390 raise TypeError('ngwf_count can only be int|list|dict') 

391 

392 if isinstance(ngwf_radius, float): 

393 ngwf_radius = dict(zip(u_species, [ngwf_radius] * n_sp)) 

394 elif isinstance(ngwf_radius, list): 

395 ngwf_radius = dict(zip(u_species, ngwf_radius)) 

396 elif isinstance(ngwf_radius, dict): 

397 pass 

398 else: 

399 raise TypeError('ngwf_radius can only be float|list|dict') 

400 

401 pp_files = re.sub('\'|"', '', keywords.get('pseudo_path', pseudo_path)) 

402 pp_files = Path(pp_files).glob('*') 

403 pp_files = [i for i in pp_files if i.is_file()] 

404 

405 if pseudo_suffix: 

406 common_suffix = [pseudo_suffix] 

407 else: 

408 common_suffix = ['.usp', '.recpot', '.upf', '.paw', '.psp', '.pspnc'] 

409 

410 if keywords.get('species_pot', False): 

411 pp_list = keywords['species_pot'] 

412 elif isinstance(pseudopotentials, dict): 

413 pp_list = [] 

414 for idx, el in enumerate(u_species): 

415 if el in pseudopotentials: 

416 pp_list.append(f'{el} {pseudopotentials[el]}') 

417 else: 

418 for i in pp_files: 

419 reg_el_candidate = re.split(r'[-_.:= ]+', i.stem)[0] 

420 if ( 

421 elements[idx] == reg_el_candidate.title() 

422 and i.suffix.lower() in common_suffix 

423 ): 

424 pp_list.append(f'{el} {i.name}') 

425 else: 

426 raise TypeError('pseudopotentials object can only be dict') 

427 

428 default_species = [] 

429 for idx, el in enumerate(u_species): 

430 tmp = '' 

431 tmp += u_species[idx] + ' ' + elements[idx] + ' ' 

432 tmp += str(numbers[idx]) + ' ' 

433 try: 

434 tmp += str(ngwf_count[el]) + ' ' 

435 except KeyError: 

436 tmp += str(ngwf_count[elements[idx]]) + ' ' 

437 try: 

438 tmp += str(ngwf_radius[el]) 

439 except KeyError: 

440 tmp += str(ngwf_radius[elements[idx]]) 

441 default_species.append(tmp) 

442 

443 positions_abs = ['ang'] 

444 for s, p in zip(species, atoms.get_positions()): 

445 line = '{s:>5} {0:>12.6f} {1:>12.6f} {2:>12.6f}'.format(s=s, *p) 

446 positions_abs.append(line) 

447 

448 lattice_cart = ['ang'] 

449 for axis in atoms.get_cell(): 

450 line = '{:>16.8f} {:>16.8f} {:>16.8f}'.format(*axis) 

451 lattice_cart.append(line) 

452 

453 # Default keywords if not provided by the user, 

454 # most of them are ONETEP default, except write_forces 

455 # which is always turned on. 

456 default_keywords = { 

457 'xc_functional': xc, 

458 'edft': edft, 

459 'cutoff_energy': 20, 

460 'paw': False, 

461 'task': 'singlepoint', 

462 'output_detail': 'normal', 

463 'species': default_species, 

464 'pseudo_path': pseudo_path, 

465 'species_pot': pp_list, 

466 'positions_abs': positions_abs, 

467 'lattice_cart': lattice_cart, 

468 'write_forces': True, 

469 'forces_output_detail': 'verbose', 

470 } 

471 

472 # Main loop, fill the keyword dictionary 

473 keywords = {key.lower(): value for key, value in keywords.items()} 

474 for value in default_keywords: 

475 if not keywords.get(value, None): 

476 keywords[value] = default_keywords[value] 

477 

478 # No pseudopotential provided, we look for them in pseudo_path 

479 # If autorestart is True, we look for restart files, 

480 # and turn on relevant keywords... 

481 if autorestart: 

482 keywords['read_denskern'] = isfile(directory / (label + '.dkn')) 

483 keywords['read_tightbox_ngwfs'] = isfile( 

484 directory / (label + '.tightbox_ngwfs') 

485 ) 

486 keywords['read_hamiltonian'] = isfile(directory / (label + '.ham')) 

487 

488 # If not EDFT, hamiltonian is irrelevant. 

489 # print(keywords.get('edft', False)) 

490 # keywords['read_hamiltonian'] = \ 

491 # keywords.get('read_hamiltonian', False) & keywords.get('edft', False) 

492 

493 keywords = dict(sorted(keywords.items())) 

494 

495 lines = [] 

496 block_lines = [] 

497 

498 for key, value in keywords.items(): 

499 if isinstance(value, (list, np.ndarray)): 

500 if not all(isinstance(_, str) for _ in value): 

501 raise TypeError('list values for blocks must be strings only') 

502 block_lines.append(('\n%block ' + key).upper()) 

503 block_lines.extend(value) 

504 block_lines.append(('%endblock ' + key).upper()) 

505 elif isinstance(value, bool): 

506 lines.append(str(key) + ' : ' + str(value)[0]) 

507 elif isinstance(value, (str, int, float)): 

508 lines.append(str(key) + ' : ' + str(value)) 

509 else: 

510 raise TypeError('keyword values must be list|str|bool') 

511 input_header = ( 

512 '!' 

513 + '-' * 78 

514 + '!\n' 

515 + '!' 

516 + '-' * 33 

517 + ' INPUT FILE ' 

518 + '-' * 33 

519 + '!\n' 

520 + '!' 

521 + '-' * 78 

522 + '!\n\n' 

523 ) 

524 

525 input_footer = ( 

526 '\n!' 

527 + '-' * 78 

528 + '!\n' 

529 + '!' 

530 + '-' * 32 

531 + ' END OF INPUT ' 

532 + '-' * 32 

533 + '!\n' 

534 + '!' 

535 + '-' * 78 

536 + '!' 

537 ) 

538 

539 fd.write(input_header) 

540 fd.writelines(line + '\n' for line in lines) 

541 fd.writelines(b_line + '\n' for b_line in block_lines) 

542 

543 if 'devel_code' in kwargs: 

544 warnings.warn('writing devel code as it is, at the end of the file') 

545 fd.writelines('\n' + line for line in kwargs['devel_code']) 

546 

547 fd.write(input_footer) 

548 

549 

550def match_outputs(fdo_lines, output_keys): 

551 # Find all matches, append them to the dictionary 

552 breg = '|'.join([i.pattern.replace('(?i)', '') for i in output_keys]) 

553 prematch = {} 

554 

555 for idx, line in enumerate(fdo_lines): 

556 matches = re.search(breg, line) 

557 if matches: 

558 prematch[idx] = matches.group(0) 

559 

560 output = {key: [] for key in output_keys} 

561 for key, value in prematch.items(): 

562 for reg in output_keys: 

563 if re.search(reg, value): 

564 output[reg].append(key) 

565 break 

566 

567 return {key: np.array(value) for key, value in output.items()} 

568 

569 

570def read_onetep_out(fd, index=-1, improving=False, **kwargs): 

571 """ 

572 Read ONETEP output(s). 

573 

574 !!! 

575 This function will be used by ASE when performing 

576 various workflows (opt, NEB...) 

577 !!! 

578 

579 Parameters 

580 ---------- 

581 fd : file 

582 File to read. 

583 index: slice 

584 Which atomic configuration to read 

585 improving: Bool 

586 If the output is a geometry optimisation, 

587 improving = True will keep line search 

588 configuration from BFGS 

589 

590 Yields 

591 ------ 

592 structure: Atoms|list of Atoms 

593 """ 

594 # Put everything in memory 

595 fdo_lines = fd.readlines() 

596 n_lines = len(fdo_lines) 

597 

598 # Used to store index of important elements 

599 output = { 

600 ONETEP_START: [], 

601 ONETEP_STOP: [], 

602 ONETEP_TOTAL_ENERGY: [], 

603 ONETEP_FORCE: [], 

604 ONETEP_SPIN: [], 

605 ONETEP_MULLIKEN: [], 

606 ONETEP_POSITION: [], 

607 ONETEP_FIRST_POSITION: [], 

608 ONETEP_WRONG_FIRST_POSITION: [], 

609 ONETEP_ATOM_COUNT: [], 

610 ONETEP_IBFGS_IMPROVE: [], 

611 ONETEP_IBFGS_ITER: [], 

612 ONETEP_START_GEOM: [], 

613 ONETEP_RESUMING_GEOM: [], 

614 ONETEP_END_GEOM: [], 

615 ONETEP_SPECIES: [], 

616 ONETEP_FIRST_CELL: [], 

617 ONETEP_STRESS_CELL: [], 

618 } 

619 

620 # Index will be treated to get rid of duplicate or improving iterations 

621 output_corr = deepcopy(output) 

622 

623 # Core properties that will be used in Yield 

624 properties = [ 

625 ONETEP_TOTAL_ENERGY, 

626 ONETEP_FORCE, 

627 ONETEP_MULLIKEN, 

628 ONETEP_FIRST_CELL, 

629 ] 

630 

631 output = match_outputs(fdo_lines, [*output]) 

632 

633 # Conveniance notation (pointers: no overhead, no additional memory) 

634 ibfgs_iter = np.hstack((output[ONETEP_IBFGS_ITER], output[ONETEP_END_GEOM])) 

635 ibfgs_start = output[ONETEP_START_GEOM] 

636 ibfgs_improve = output[ONETEP_IBFGS_IMPROVE] 

637 ibfgs_resume = output[ONETEP_RESUMING_GEOM] 

638 

639 onetep_start = output[ONETEP_START] 

640 onetep_stop = output[ONETEP_STOP] 

641 

642 bfgs_keywords = np.hstack((ibfgs_improve, ibfgs_resume, ibfgs_iter)) 

643 bfgs_keywords = np.sort(bfgs_keywords) 

644 

645 core_keywords = np.hstack( 

646 ( 

647 ibfgs_iter, 

648 ibfgs_start, 

649 ibfgs_improve, 

650 ibfgs_resume, 

651 ibfgs_iter, 

652 onetep_start, 

653 onetep_stop, 

654 ) 

655 ) 

656 core_keywords = np.sort(core_keywords) 

657 

658 i_first_positions = output[ONETEP_FIRST_POSITION] 

659 is_frac_positions = [i for i in i_first_positions if 'FRAC' in fdo_lines[i]] 

660 

661 # In onetep species can have arbritary names, 

662 # We want to map them to real element names 

663 # Via the species block 

664 # species = np.concatenate((output[ONETEP_SPECIES], 

665 # output[ONETEP_SPECIESL])).astype(np.int32) 

666 species = output[ONETEP_SPECIES] 

667 

668 icells = np.hstack((output[ONETEP_FIRST_CELL], output[ONETEP_STRESS_CELL])) 

669 icells = icells.astype(np.int32) 

670 # Using the fact that 0 == False and > 0 == True 

671 has_bfgs = ( 

672 len(ibfgs_iter) 

673 + len(output[ONETEP_START_GEOM]) 

674 + len(output[ONETEP_RESUMING_GEOM]) 

675 ) 

676 

677 # When the input block position is written in lowercase 

678 # ONETEP does not print the initial position but a hash 

679 # of it, might be needed 

680 has_hash = len(output[ONETEP_WRONG_FIRST_POSITION]) 

681 

682 def is_in_bfgs(idx): 

683 """ 

684 Check if a given index is in a BFGS block 

685 """ 

686 for past, future in zip( 

687 output[ONETEP_START], 

688 np.hstack((output[ONETEP_START][1:], [n_lines])), 

689 ): 

690 if past < idx < future: 

691 if np.any( 

692 (past < ibfgs_start) & (ibfgs_start < future) 

693 ) or np.any((past < ibfgs_resume) & (ibfgs_resume < future)): 

694 return True 

695 return False 

696 

697 def where_in_bfgs(idx): 

698 for past, future in zip( 

699 core_keywords, np.hstack((core_keywords[1:], [n_lines])) 

700 ): 

701 if past < idx < future: 

702 if past in onetep_start: 

703 if future in ibfgs_start or future in ibfgs_resume: 

704 return 'resume' 

705 continue 

706 # Are we in start or resume or improve 

707 if past in ibfgs_start: 

708 return 'start' 

709 elif past in ibfgs_resume: 

710 return 'resume' 

711 elif past in ibfgs_improve: 

712 return 'improve' 

713 

714 return False 

715 

716 ipositions = np.hstack((output[ONETEP_POSITION], i_first_positions)).astype( 

717 np.int32 

718 ) 

719 ipositions = np.sort(ipositions) 

720 

721 n_pos = len(ipositions) 

722 

723 # Some ONETEP files will not have any positions 

724 # due to how the software is coded. As a last 

725 # resort we look for a geom file with the same label. 

726 

727 if n_pos == 0: 

728 if has_hash: 

729 raise RuntimeError(no_positions_error) 

730 raise RuntimeError(unable_to_read) 

731 

732 to_del = [] 

733 

734 # Important loop which: 

735 # - Get rid of improving BFGS iteration if improving == False 

736 # - Append None to properties to make sure each properties will 

737 # have the same length and each index correspond to the right 

738 # atomic configuration (hopefully). 

739 # Past is the index of the current atomic conf, future is the 

740 # index of the next one. 

741 

742 for idx, (past, future) in enumerate( 

743 zip(ipositions, np.hstack((ipositions[1:], [n_lines]))) 

744 ): 

745 if has_bfgs: 

746 which_bfgs = where_in_bfgs(past) 

747 

748 if which_bfgs == 'resume': 

749 to_del.append(idx) 

750 continue 

751 

752 if not improving: 

753 if which_bfgs == 'improve': 

754 to_del.append(idx) 

755 continue 

756 

757 # We append None if no properties in contained for 

758 # one specific atomic configurations. 

759 for prop in properties: 

760 (tmp,) = np.where((past < output[prop]) & (output[prop] <= future)) 

761 if len(tmp) == 0: 

762 output_corr[prop].append(None) 

763 else: 

764 output_corr[prop].extend(output[prop][tmp[:1]]) 

765 

766 if to_del and len(to_del) != n_pos: 

767 new_indices = np.setdiff1d(np.arange(n_pos), to_del) 

768 ipositions = ipositions[new_indices] 

769 

770 helper = _OnetepHelper(fdo_lines) 

771 

772 cells = [] 

773 for idx in icells: 

774 if idx in output[ONETEP_STRESS_CELL]: 

775 cell = helper.parse_cell(idx) if idx else None 

776 else: 

777 cell = helper.parse_first_cell(idx) if idx else None 

778 cells.append(cell) 

779 

780 def parse_multiple(parsefunc, indices): 

781 return [parsefunc(idx) if idx else None for idx in indices] 

782 

783 charges = parse_multiple(helper.parse_charge, output_corr[ONETEP_MULLIKEN]) 

784 energies = parse_multiple( 

785 helper.parse_energy, output_corr[ONETEP_TOTAL_ENERGY] 

786 ) 

787 magmoms = parse_multiple(helper.parse_spin, output_corr[ONETEP_MULLIKEN]) 

788 

789 real_species = [] 

790 for idx in species: 

791 real_specie = helper.parse_species(idx) 

792 real_species.append(real_specie) 

793 

794 positions, forces = [], [] 

795 for idx in ipositions: 

796 if idx in i_first_positions: 

797 position = helper.parse_first_positions(idx, species, real_species) 

798 else: 

799 position = helper.parse_positions(idx, species, real_species) 

800 if position: 

801 positions.append(position) 

802 else: 

803 n_pos -= 1 

804 break 

805 for idx in output_corr[ONETEP_FORCE]: 

806 force = helper.parse_force(idx) if idx else None 

807 forces.append(force) 

808 

809 n_pos = len(positions) 

810 

811 # Numpy trick to get rid of configuration that are essentially the same 

812 # in a regular geometry optimisation with internal BFGS, the first 

813 # configuration is printed three time, we get rid of it 

814 properties = [energies, forces, charges, magmoms] 

815 

816 if has_bfgs: 

817 tmp = [i.positions for i in positions] 

818 to_del = [] 

819 for i in range(len(tmp[:-1])): 

820 if is_in_bfgs(ipositions[i]): 

821 if np.array_equal(tmp[i], tmp[i + 1]): 

822 # If the deleted configuration has a property 

823 # we want to keep it 

824 for prop in properties: 

825 if prop[i + 1] is not None and prop[i] is None: 

826 prop[i] = prop[i + 1] 

827 to_del.append(i + 1) 

828 c = np.full((len(tmp)), True) 

829 c[to_del] = False 

830 energies = [energies[i] for i in range(n_pos) if c[i]] 

831 forces = [forces[i] for i in range(n_pos) if c[i]] 

832 charges = [charges[i] for i in range(n_pos) if c[i]] 

833 magmoms = [magmoms[i] for i in range(n_pos) if c[i]] 

834 positions = [positions[i] for i in range(n_pos) if c[i]] 

835 ipositions = [ipositions[i] for i in range(n_pos) if c[i]] 

836 

837 n_pos = len(positions) 

838 

839 # We take care of properties that only show up at 

840 # the beginning of onetep calculation 

841 whole = np.append(output[ONETEP_START], n_lines) 

842 

843 if n_pos == 0: 

844 raise RuntimeError(unable_to_read) 

845 

846 spin = np.full((n_pos), 1) 

847 for sp in output[ONETEP_SPIN]: 

848 tmp = zip(whole, whole[1:]) 

849 for past, future in tmp: 

850 if past < sp < future: 

851 p = (past < ipositions) & (ipositions < future) 

852 spin[p] = 2 

853 

854 cells_all = np.ones((n_pos, 3, 3)) 

855 for idx, cell in enumerate(output[ONETEP_FIRST_CELL]): 

856 tmp = zip(whole, whole[1:]) 

857 for past, future in tmp: 

858 if past < cell < future: 

859 p = (past < ipositions) & (ipositions < future) 

860 cells_all[p] = cells[idx] 

861 

862 # Prepare atom objects with all the properties 

863 if isinstance(index, int): 

864 indices = [range(n_pos)[index]] 

865 else: 

866 indices = range(n_pos)[index] 

867 

868 for idx in indices: 

869 positions[idx].set_cell(cells_all[idx]) 

870 if ipositions[idx] in is_frac_positions: 

871 positions[idx].set_scaled_positions(positions[idx].get_positions()) 

872 positions[idx].set_initial_charges(charges[idx]) 

873 calc = SinglePointDFTCalculator( 

874 positions[idx], 

875 energy=energies[idx] if energies else None, 

876 free_energy=energies[idx] if energies else None, 

877 forces=forces[idx] if forces else None, 

878 charges=charges[idx] if charges else None, 

879 magmoms=magmoms[idx] if magmoms else None, 

880 ) 

881 # calc.kpts = [(0, 0, 0) for _ in range(spin[idx])] 

882 positions[idx].calc = calc 

883 yield positions[idx] 

884 

885 

886class _OnetepHelper: 

887 def __init__(self, fdo_lines): 

888 self.fdo_lines = fdo_lines 

889 

890 # Bunch of methods to grep properties from output. 

891 def parse_cell(self, idx): 

892 a, b, c = np.loadtxt([self.fdo_lines[idx + 2]]) * units['Bohr'] 

893 al, be, ga = np.loadtxt([self.fdo_lines[idx + 4]]) 

894 cell = Cell.fromcellpar([a, b, c, al, be, ga]) 

895 return np.array(cell) 

896 

897 def parse_charge(self, idx): 

898 n = 0 

899 offset = 4 

900 while idx + n < len(self.fdo_lines): 

901 if not self.fdo_lines[idx + n].strip(): 

902 tmp_charges = np.loadtxt( 

903 self.fdo_lines[idx + offset : idx + n - 1], usecols=3 

904 ) 

905 return np.reshape(tmp_charges, -1) 

906 n += 1 

907 return None 

908 

909 #  In ONETEP there is no way to differentiate electronic entropy 

910 #  and entropy due to solvent, therefore there is no way to 

911 # extrapolate the energy at 0 K. We return the last energy 

912 #  instead. 

913 

914 def parse_energy(self, idx): 

915 freg = re.compile(r'-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+\-]?\d+)?') 

916 

917 n = 0 

918 while idx + n < len(self.fdo_lines): 

919 if re.search( 

920 r'^\s*\|\s*Total\s*:.*\|\s*$', self.fdo_lines[idx + n] 

921 ): 

922 energy_str = re.search(freg, self.fdo_lines[idx + n]).group(0) 

923 return float(energy_str) * units['Hartree'] 

924 n += 1 

925 return None 

926 

927 def parse_first_cell(self, idx): 

928 n = 0 

929 offset = 1 

930 while idx + n < len(self.fdo_lines): 

931 if re.search( 

932 r'(?i)^\s*"?\s*ang\s*"?\s*([*#!].*)?$', self.fdo_lines[idx + n] 

933 ): 

934 offset += 1 

935 if re.search( 

936 r'(?i)^\s*%ENDBLOCK\s*LATTICE' 

937 r'\s*_?\s*CART\s*:?\s*([*#!].*)?$', 

938 self.fdo_lines[idx + n], 

939 ): 

940 cell = np.loadtxt(self.fdo_lines[idx + offset : idx + n]) 

941 return cell if offset == 2 else cell * units['Bohr'] 

942 n += 1 

943 return None 

944 

945 def parse_first_positions(self, idx, species, real_species): 

946 n = 0 

947 offset = 1 

948 while idx + n < len(self.fdo_lines): 

949 if re.search( 

950 r'(?i)^\s*"?\s*ang\s*"?\s*([*#!].*)?$', self.fdo_lines[idx + n] 

951 ): 

952 offset += 1 

953 if re.search( 

954 r'^\s*%ENDBLOCK\s*POSITIONS_', self.fdo_lines[idx + n] 

955 ): 

956 if 'FRAC' in self.fdo_lines[idx + n]: 

957 conv_factor = 1 

958 else: 

959 conv_factor = units['Bohr'] 

960 tmp = np.loadtxt( 

961 self.fdo_lines[idx + offset : idx + n], dtype='str' 

962 ).reshape(-1, 4) 

963 els = tmp[:, 0] 

964 if offset == 2: 

965 pos = tmp[:, 1:].astype(np.float64) 

966 else: 

967 pos = tmp[:, 1:].astype(np.float64) * conv_factor 

968 try: 

969 atoms = Atoms(els, pos) 

970 # ASE doesn't recognize names used in ONETEP 

971 # as chemical symbol: dig deeper 

972 except KeyError: 

973 tags, real_elements = self.find_correct_species( 

974 els, idx, species, real_species, first=True 

975 ) 

976 atoms = Atoms(real_elements, pos) 

977 atoms.set_tags(tags) 

978 atoms.info['onetep_species'] = list(els) 

979 return atoms 

980 n += 1 

981 return None 

982 

983 def parse_force(self, idx): 

984 n = 0 

985 while idx + n < len(self.fdo_lines): 

986 if re.search( 

987 r'(?i)^\s*\*\s*TOTAL:.*\*\s*$', self.fdo_lines[idx + n] 

988 ): 

989 tmp = np.loadtxt( 

990 self.fdo_lines[idx + 6 : idx + n - 2], 

991 dtype=np.float64, 

992 usecols=(3, 4, 5), 

993 ) 

994 return tmp * units['Hartree'] / units['Bohr'] 

995 n += 1 

996 return None 

997 

998 def parse_positions(self, idx, species, real_species): 

999 n = 0 

1000 offset = 7 

1001 stop = 0 

1002 while idx + n < len(self.fdo_lines): 

1003 if re.search(r'^\s*x{60,}\s*$', self.fdo_lines[idx + n]): 

1004 stop += 1 

1005 if stop == 2: 

1006 tmp = np.loadtxt( 

1007 self.fdo_lines[idx + offset : idx + n], 

1008 dtype='str', 

1009 usecols=(1, 3, 4, 5), 

1010 ) 

1011 els = tmp[:, 0] 

1012 pos = tmp[:, 1:].astype(np.float64) * units['Bohr'] 

1013 try: 

1014 atoms = Atoms(els, pos) 

1015 # ASE doesn't recognize names used in ONETEP 

1016 # as chemical symbol: dig deeper 

1017 except KeyError: 

1018 tags, real_elements = self.find_correct_species( 

1019 els, idx, species, real_species 

1020 ) 

1021 atoms = Atoms(real_elements, pos) 

1022 atoms.set_tags(tags) 

1023 atoms.info['onetep_species'] = list(els) 

1024 return atoms 

1025 n += 1 

1026 return None 

1027 

1028 def parse_species(self, idx): 

1029 n = 1 

1030 element_map = {} 

1031 while idx + n < len(self.fdo_lines): 

1032 sep = self.fdo_lines[idx + n].split() 

1033 if re.search( 

1034 r'(?i)^\s*%ENDBLOCK\s*SPECIES\s*:?\s*([*#!].*)?$', 

1035 self.fdo_lines[idx + n], 

1036 ): 

1037 return element_map 

1038 to_skip = re.search( 

1039 r'(?i)^\s*(ang|bohr)\s*([*#!].*)?$', self.fdo_lines[idx + n] 

1040 ) 

1041 if not to_skip: 

1042 element_map[sep[0]] = sep[1] 

1043 n += 1 

1044 return None 

1045 

1046 def parse_spin(self, idx): 

1047 n = 0 

1048 offset = 4 

1049 while idx + n < len(self.fdo_lines): 

1050 if not self.fdo_lines[idx + n].strip(): 

1051 # If no spin is present we return None 

1052 try: 

1053 tmp_spins = np.loadtxt( 

1054 self.fdo_lines[idx + offset : idx + n - 1], usecols=4 

1055 ) 

1056 return np.reshape(tmp_spins, -1) 

1057 except ValueError: 

1058 return None 

1059 n += 1 

1060 return None 

1061 

1062 # This is needed if ASE doesn't recognize the element 

1063 def find_correct_species( 

1064 self, els, idx, species, real_species, first=False 

1065 ): 

1066 real_elements = [] 

1067 tags = [] 

1068 # Find nearest species block in case of 

1069 # multi-output file with different species blocks. 

1070 if first: 

1071 closest_species = np.argmin(abs(idx - species)) 

1072 else: 

1073 tmp = idx - species 

1074 tmp[tmp < 0] = 9999999999 

1075 closest_species = np.argmin(tmp) 

1076 elements_map = real_species[closest_species] 

1077 for el in els: 

1078 real_elements.append(elements_map[el]) 

1079 tag_maybe = el.replace(elements_map[el], '') 

1080 if tag_maybe.isdigit(): 

1081 tags.append(int(tag_maybe)) 

1082 else: 

1083 tags.append(False) 

1084 return tags, real_elements