Coverage for ase/io/castep/castep_reader.py: 91.15%

339 statements  

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

1import io 

2import re 

3import warnings 

4from collections import defaultdict 

5from typing import Any 

6 

7import numpy as np 

8 

9from ase import Atoms, units 

10from ase.calculators.singlepoint import SinglePointCalculator 

11from ase.constraints import FixAtoms, FixCartesian, FixConstraint 

12from ase.io import ParseError 

13from ase.utils import reader, string2index 

14 

15 

16@reader 

17def read_castep_castep(fd, index=-1): 

18 """Read a .castep file and returns an Atoms object. 

19 

20 The calculator information will be stored in the calc attribute. 

21 

22 Notes 

23 ----- 

24 This routine will return an atom ordering as found within the castep file. 

25 This means that the species will be ordered by ascending atomic numbers. 

26 The atoms witin a species are ordered as given in the original cell file. 

27 

28 """ 

29 # look for last result, if several CASTEP run are appended 

30 line_start, line_end, end_found = _find_last_record(fd) 

31 if not end_found: 

32 raise ParseError(f'No regular end found in {fd.name} file.') 

33 

34 # These variables are finally assigned to `SinglePointCalculator` 

35 # for backward compatibility with the `Castep` calculator. 

36 cut_off_energy = None 

37 kpoints = None 

38 total_time = None 

39 peak_memory = None 

40 

41 # jump back to the beginning to the last record 

42 fd.seek(0) 

43 for i, line in enumerate(fd): 

44 if i == line_start: 

45 break 

46 

47 # read header 

48 parameters_header = _read_header(fd) 

49 if 'cut_off_energy' in parameters_header: 

50 cut_off_energy = parameters_header['cut_off_energy'] 

51 if 'basis_precision' in parameters_header: 

52 del parameters_header['cut_off_energy'] # avoid conflict 

53 

54 markers_new_iteration = [ 

55 'BFGS: starting iteration', 

56 'BFGS: improving iteration', 

57 'Starting MD iteration', 

58 ] 

59 

60 images = [] 

61 

62 results = {} 

63 constraints = [] 

64 species_pot = [] 

65 castep_warnings = [] 

66 for i, line in enumerate(fd): 

67 if i > line_end: 

68 break 

69 

70 if 'Number of kpoints used' in line: 

71 kpoints = int(line.split('=')[-1].strip()) 

72 elif 'Unit Cell' in line: 

73 lattice_real = _read_unit_cell(fd) 

74 elif 'Cell Contents' in line: 

75 for line in fd: 

76 if 'Total number of ions in cell' in line: 

77 n_atoms = int(line.split()[7]) 

78 if 'Total number of species in cell' in line: 

79 int(line.split()[7]) 

80 fields = line.split() 

81 if len(fields) == 0: 

82 break 

83 elif 'Fractional coordinates of atoms' in line: 

84 species, custom_species, positions_frac = ( 

85 _read_fractional_coordinates(fd, n_atoms) 

86 ) 

87 elif 'Files used for pseudopotentials' in line: 

88 for line in fd: 

89 line = fd.readline() 

90 if 'Pseudopotential generated on-the-fly' in line: 

91 continue 

92 fields = line.split() 

93 if len(fields) == 2: 

94 species_pot.append(fields) 

95 else: 

96 break 

97 elif 'k-Points For BZ Sampling' in line: 

98 # TODO: generalize for non-Monkhorst Pack case 

99 # (i.e. kpoint lists) - 

100 # kpoints_offset cannot be read this way and 

101 # is hence always set to None 

102 for line in fd: 

103 if not line.strip(): 

104 break 

105 if 'MP grid size for SCF calculation' in line: 

106 # kpoints = ' '.join(line.split()[-3:]) 

107 # self.kpoints_mp_grid = kpoints 

108 # self.kpoints_mp_offset = '0. 0. 0.' 

109 # not set here anymore because otherwise 

110 # two calculator objects go out of sync 

111 # after each calculation triggering unnecessary 

112 # recalculation 

113 break 

114 

115 elif 'Final energy' in line: 

116 key = 'energy_without_dispersion_correction' 

117 results[key] = float(line.split()[-2]) 

118 elif 'Final free energy' in line: 

119 key = 'free_energy_without_dispersion_correction' 

120 results[key] = float(line.split()[-2]) 

121 elif 'NB est. 0K energy' in line: 

122 key = 'energy_zero_without_dispersion_correction' 

123 results[key] = float(line.split()[-2]) 

124 

125 # Add support for dispersion correction 

126 # filtering due to SEDC is done in get_potential_energy 

127 elif 'Dispersion corrected final energy' in line: 

128 key = 'energy_with_dispersion_correlation' 

129 results[key] = float(line.split()[-2]) 

130 elif 'Dispersion corrected final free energy' in line: 

131 key = 'free_energy_with_dispersion_correlation' 

132 results[key] = float(line.split()[-2]) 

133 elif 'NB dispersion corrected est. 0K energy' in line: 

134 key = 'energy_zero_with_dispersion_correlation' 

135 results[key] = float(line.split()[-2]) 

136 

137 # check if we had a finite basis set correction 

138 elif 'Total energy corrected for finite basis set' in line: 

139 key = 'energy_with_finite_basis_set_correction' 

140 results[key] = float(line.split()[-2]) 

141 

142 # ******************** Forces ********************* 

143 # ************** Symmetrised Forces *************** 

144 # ******************** Constrained Forces ******************** 

145 # ******************* Unconstrained Forces ******************* 

146 elif re.search(r'\**.* Forces \**', line): 

147 forces, constraints = _read_forces(fd, n_atoms) 

148 results['forces'] = np.array(forces) 

149 

150 # ***************** Stress Tensor ***************** 

151 # *********** Symmetrised Stress Tensor *********** 

152 elif re.search(r'\**.* Stress Tensor \**', line): 

153 results.update(_read_stress(fd)) 

154 

155 elif any(_ in line for _ in markers_new_iteration): 

156 _add_atoms( 

157 images, 

158 lattice_real, 

159 species, 

160 custom_species, 

161 positions_frac, 

162 constraints, 

163 results, 

164 ) 

165 # reset for the next step 

166 lattice_real = None 

167 species = None 

168 positions_frac = None 

169 results = {} 

170 constraints = [] 

171 

172 # extract info from the Mulliken analysis 

173 elif 'Atomic Populations' in line: 

174 results.update(_read_mulliken_charges(fd)) 

175 

176 # extract detailed Hirshfeld analysis (iprint > 1) 

177 elif 'Hirshfeld total electronic charge (e)' in line: 

178 results.update(_read_hirshfeld_details(fd, n_atoms)) 

179 

180 elif 'Hirshfeld Analysis' in line: 

181 results.update(_read_hirshfeld_charges(fd)) 

182 

183 # There is actually no good reason to get out of the loop 

184 # already at this point... or do I miss something? 

185 # elif 'BFGS: Final Configuration:' in line: 

186 # break 

187 elif 'warn' in line.lower(): 

188 castep_warnings.append(line) 

189 

190 # fetch some last info 

191 elif 'Total time' in line: 

192 pattern = r'.*=\s*([\d\.]+) s' 

193 total_time = float(re.search(pattern, line).group(1)) 

194 

195 elif 'Peak Memory Use' in line: 

196 pattern = r'.*=\s*([\d]+) kB' 

197 peak_memory = int(re.search(pattern, line).group(1)) 

198 

199 # add the last image 

200 _add_atoms( 

201 images, 

202 lattice_real, 

203 species, 

204 custom_species, 

205 positions_frac, 

206 constraints, 

207 results, 

208 ) 

209 

210 for atoms in images: 

211 # these variables are temporarily assigned to `SinglePointCalculator` 

212 # to be assigned to the `Castep` calculator for backward compatibility 

213 atoms.calc._cut_off_energy = cut_off_energy 

214 atoms.calc._kpoints = kpoints 

215 atoms.calc._species_pot = species_pot 

216 atoms.calc._total_time = total_time 

217 atoms.calc._peak_memory = peak_memory 

218 atoms.calc._parameters_header = parameters_header 

219 

220 if castep_warnings: 

221 warnings.warn('WARNING: .castep file contains warnings') 

222 for warning in castep_warnings: 

223 warnings.warn(warning) 

224 

225 if isinstance(index, str): 

226 index = string2index(index) 

227 

228 return images[index] 

229 

230 

231def _find_last_record(fd): 

232 """Find the last record of the .castep file. 

233 

234 Returns 

235 ------- 

236 start : int 

237 Line number of the first line of the last record. 

238 end : int 

239 Line number of the last line of the last record. 

240 end_found : bool 

241 True if the .castep file ends as expected. 

242 

243 """ 

244 start = -1 

245 for i, line in enumerate(fd): 

246 if ( 

247 'Welcome' in line or 'Materials Studio' in line 

248 ) and 'CASTEP' in line: 

249 start = i 

250 

251 if start < 0: 

252 warnings.warn( 

253 f'Could not find CASTEP label in result file: {fd.name}.' 

254 ' Are you sure this is a .castep file?' 

255 ) 

256 return None 

257 

258 # search for regular end of file 

259 end_found = False 

260 # start to search from record beginning from the back 

261 # and see if 

262 end = -1 

263 fd.seek(0) 

264 for i, line in enumerate(fd): 

265 if i < start: 

266 continue 

267 if 'Finalisation time =' in line: 

268 end_found = True 

269 end = i 

270 break 

271 

272 return (start, end, end_found) 

273 

274 

275def _read_header(out: io.TextIOBase): 

276 """Read the header blocks from a .castep file. 

277 

278 Returns 

279 ------- 

280 parameters : dict 

281 Dictionary storing keys and values of a .param file. 

282 """ 

283 

284 def _parse_on_off(_: str): 

285 return {'on': True, 'off': False}[_] 

286 

287 read_title = False 

288 parameters: dict[str, Any] = {} 

289 for line in out: 

290 if len(line) == 0: # end of file 

291 break 

292 if re.search(r'^\s*\*+$', line) and read_title: # end of header 

293 break 

294 

295 if re.search(r'\**.* Title \**', line): 

296 read_title = True 

297 

298 # General Parameters 

299 

300 elif 'output verbosity' in line: 

301 parameters['iprint'] = int(line.split()[-1][1]) 

302 elif re.match(r'\stype of calculation\s*:', line): 

303 parameters['task'] = { 

304 'single point energy': 'SinglePoint', 

305 'geometry optimization': 'GeometryOptimization', 

306 'band structure': 'BandStructure', 

307 'molecular dynamics': 'MolecularDynamics', 

308 'optical properties': 'Optics', 

309 'phonon calculation': 'Phonon', 

310 'E-field calculation': 'Efield', 

311 'Phonon followed by E-field': 'Phonon+Efield', 

312 'transition state search': 'TransitionStateSearch', 

313 'Magnetic Resonance': 'MagRes', 

314 'Core level spectra': 'Elnes', 

315 'Electronic Spectroscopy': 'ElectronicSpectroscopy', 

316 }[line.split(':')[-1].strip()] 

317 elif 'stress calculation' in line: 

318 parameters['calculate_stress'] = _parse_on_off(line.split()[-1]) 

319 elif 'calculation limited to maximum' in line: 

320 parameters['run_time'] = float(line.split()[-2]) 

321 elif re.match(r'\soptimization strategy\s*:', line): 

322 parameters['opt_strategy'] = { 

323 'maximize speed(+++)': 'Speed', 

324 'minimize memory(---)': 'Memory', 

325 'balance speed and memory': 'Default', 

326 }[line.split(':')[-1].strip()] 

327 

328 # Exchange-Correlation Parameters 

329 elif re.match(r'\susing functional\s*:', line): 

330 functional_abbrevs = { 

331 'Local Density Approximation': 'LDA', 

332 'Perdew Wang (1991)': 'PW91', 

333 'Perdew Burke Ernzerhof': 'PBE', 

334 'revised Perdew Burke Ernzerhof': 'RPBE', 

335 'PBE with Wu-Cohen exchange': 'WC', 

336 'PBE for solids (2008)': 'PBESOL', 

337 'Hartree-Fock': 'HF', 

338 'Hartree-Fock +': 'HF-LDA', 

339 'Screened Hartree-Fock': 'sX', 

340 'Screened Hartree-Fock + ': 'sX-LDA', 

341 'hybrid PBE0': 'PBE0', 

342 'hybrid B3LYP': 'B3LYP', 

343 'hybrid HSE03': 'HSE03', 

344 'hybrid HSE06': 'HSE06', 

345 'RSCAN': 'RSCAN', 

346 } 

347 

348 # If the name is not recognised, use the whole string. 

349 # This won't work in a new calculation, so will need to load from 

350 # .param file in such cases... but at least it will fail rather 

351 # than use the wrong XC! 

352 _xc_full_name = line.split(':')[-1].strip() 

353 parameters['xc_functional'] = functional_abbrevs.get( 

354 _xc_full_name, _xc_full_name 

355 ) 

356 

357 elif 'DFT+D: Semi-empirical dispersion correction' in line: 

358 parameters['sedc_apply'] = _parse_on_off(line.split()[-1]) 

359 elif 'SEDC with' in line: 

360 parameters['sedc_scheme'] = { 

361 'OBS correction scheme': 'OBS', 

362 'G06 correction scheme': 'G06', 

363 'D3 correction scheme': 'D3', 

364 'D3(BJ) correction scheme': 'D3-BJ', 

365 'D4 correction scheme': 'D4', 

366 'JCHS correction scheme': 'JCHS', 

367 'TS correction scheme': 'TS', 

368 'TSsurf correction scheme': 'TSSURF', 

369 'TS+SCS correction scheme': 'TSSCS', 

370 'aperiodic TS+SCS correction scheme': 'ATSSCS', 

371 'aperiodic MBD@SCS method': 'AMBD', 

372 'MBD@SCS method': 'MBD', 

373 'aperiodic MBD@rsSCS method': 'AMBD*', 

374 'MBD@rsSCS method': 'MBD*', 

375 'XDM correction scheme': 'XDM', 

376 }[line.split(':')[-1].strip()] 

377 

378 # Basis Set Parameters 

379 

380 elif 'basis set accuracy' in line: 

381 parameters['basis_precision'] = line.split()[-1] 

382 elif 'plane wave basis set cut-off' in line: 

383 parameters['cut_off_energy'] = float(line.split()[-2]) 

384 elif re.match(r'\sfinite basis set correction\s*:', line): 

385 parameters['finite_basis_corr'] = { 

386 'none': 0, 

387 'manual': 1, 

388 'automatic': 2, 

389 }[line.split()[-1]] 

390 

391 # Electronic Parameters 

392 

393 elif 'treating system as spin-polarized' in line: 

394 parameters['spin_polarized'] = True 

395 

396 # Electronic Minimization Parameters 

397 

398 elif 'Treating system as non-metallic' in line: 

399 parameters['fix_occupancy'] = True 

400 elif 'total energy / atom convergence tol.' in line: 

401 parameters['elec_energy_tol'] = float(line.split()[-2]) 

402 elif 'convergence tolerance window' in line: 

403 parameters['elec_convergence_win'] = int(line.split()[-2]) 

404 elif 'max. number of SCF cycles:' in line: 

405 parameters['max_scf_cycles'] = float(line.split()[-1]) 

406 elif 'dump wavefunctions every' in line: 

407 parameters['num_dump_cycles'] = float(line.split()[-3]) 

408 

409 # Density Mixing Parameters 

410 

411 elif 'density-mixing scheme' in line: 

412 parameters['mixing_scheme'] = line.split()[-1] 

413 

414 return parameters 

415 

416 

417def _read_unit_cell(out: io.TextIOBase): 

418 """Read a Unit Cell block from a .castep file.""" 

419 for line in out: 

420 fields = line.split() 

421 if len(fields) == 6: 

422 break 

423 lattice_real = [] 

424 for _ in range(3): 

425 lattice_real.append([float(f) for f in fields[0:3]]) 

426 line = out.readline() 

427 fields = line.split() 

428 return np.array(lattice_real) 

429 

430 

431def _read_forces(out: io.TextIOBase, n_atoms: int): 

432 """Read a block for atomic forces from a .castep file.""" 

433 constraints: list[FixConstraint] = [] 

434 forces = [] 

435 for line in out: 

436 fields = line.split() 

437 if len(fields) == 7: 

438 break 

439 for n in range(n_atoms): 

440 consd = np.array([0, 0, 0]) 

441 fxyz = [0.0, 0.0, 0.0] 

442 for i, force_component in enumerate(fields[-4:-1]): 

443 if force_component.count("(cons'd)") > 0: 

444 consd[i] = 1 

445 # remove constraint labels in force components 

446 fxyz[i] = float(force_component.replace("(cons'd)", '')) 

447 if consd.all(): 

448 constraints.append(FixAtoms(n)) 

449 elif consd.any(): 

450 constraints.append(FixCartesian(n, consd)) 

451 forces.append(fxyz) 

452 line = out.readline() 

453 fields = line.split() 

454 return forces, constraints 

455 

456 

457def _read_fractional_coordinates(out: io.TextIOBase, n_atoms: int): 

458 """Read fractional coordinates from a .castep file.""" 

459 species: list[str] = [] 

460 custom_species: list[str] | None = None # A CASTEP special thing 

461 positions_frac: list[list[float]] = [] 

462 for line in out: 

463 fields = line.split() 

464 if len(fields) == 7: 

465 break 

466 for _ in range(n_atoms): 

467 spec_custom = fields[1].split(':', 1) 

468 elem = spec_custom[0] 

469 if len(spec_custom) > 1 and custom_species is None: 

470 # Add it to the custom info! 

471 custom_species = list(species) 

472 species.append(elem) 

473 if custom_species is not None: 

474 custom_species.append(fields[1]) 

475 positions_frac.append([float(s) for s in fields[3:6]]) 

476 line = out.readline() 

477 fields = line.split() 

478 return species, custom_species, positions_frac 

479 

480 

481def _read_stress(out: io.TextIOBase): 

482 """Read a block for the stress tensor from a .castep file.""" 

483 for line in out: 

484 fields = line.split() 

485 if len(fields) == 6: 

486 break 

487 results = {} 

488 stress = [] 

489 for _ in range(3): 

490 stress.append([float(s) for s in fields[2:5]]) 

491 line = out.readline() 

492 fields = line.split() 

493 # stress in .castep file is given in GPa 

494 results['stress'] = np.array(stress) * units.GPa 

495 results['stress'] = results['stress'].reshape(9)[[0, 4, 8, 5, 2, 1]] 

496 line = out.readline() 

497 if 'Pressure:' in line: 

498 results['pressure'] = float(line.split()[-2]) * units.GPa # type: ignore[assignment] 

499 return results 

500 

501 

502def _add_atoms( 

503 images, 

504 lattice_real, 

505 species, 

506 custom_species, 

507 positions_frac, 

508 constraints, 

509 results, 

510): 

511 # If all the lattice parameters are fixed, 

512 # the `Unit Cell` block in the .castep file is not printed 

513 # in every ionic step. 

514 # The lattice paramters are therefore taken from the last step. 

515 # This happens: 

516 # - `GeometryOptimization`: `FIX_ALL_CELL : TRUE` 

517 # - `MolecularDynamics`: `MD_ENSEMBLE : NVE or NVT` 

518 if lattice_real is None: 

519 lattice_real = images[-1].cell.copy() 

520 

521 # for highly symmetric systems (where essentially only the 

522 # stress is optimized, but the atomic positions) positions 

523 # are only printed once. 

524 if species is None: 

525 species = images[-1].symbols 

526 if positions_frac is None: 

527 positions_frac = images[-1].get_scaled_positions() 

528 

529 _set_energy_and_free_energy(results) 

530 

531 atoms = Atoms( 

532 species, 

533 cell=lattice_real, 

534 constraint=constraints, 

535 pbc=True, 

536 scaled_positions=positions_frac, 

537 ) 

538 if custom_species is not None: 

539 atoms.new_array( 

540 'castep_custom_species', 

541 np.array(custom_species), 

542 ) 

543 

544 atoms.calc = SinglePointCalculator(atoms) 

545 atoms.calc.results = results 

546 

547 images.append(atoms) 

548 

549 

550def _read_mulliken_charges(out: io.TextIOBase): 

551 """Read a block for Mulliken charges from a .castep file.""" 

552 for i in range(3): 

553 line = out.readline() 

554 if i == 1: 

555 spin_polarized = 'Spin' in line 

556 results = defaultdict(list) 

557 for line in out: 

558 fields = line.split() 

559 if len(fields) == 1: 

560 break 

561 if spin_polarized: 

562 if len(fields) != 7: # due to CASTEP 18 outformat changes 

563 results['charges'].append(float(fields[-2])) 

564 results['magmoms'].append(float(fields[-1])) 

565 else: 

566 results['charges'].append(float(fields[-1])) 

567 return {k: np.array(v) for k, v in results.items()} 

568 

569 

570def _read_hirshfeld_details(out: io.TextIOBase, n_atoms: int): 

571 """Read the Hirshfeld analysis when iprint > 1 from a .castep file.""" 

572 results = defaultdict(list) 

573 for _ in range(n_atoms): 

574 for line in out: 

575 if line.strip() == '': 

576 break # end for each atom 

577 if 'Hirshfeld / free atomic volume :' in line: 

578 line = out.readline() 

579 fields = line.split() 

580 results['hirshfeld_volume_ratios'].append(float(fields[0])) 

581 return {k: np.array(v) for k, v in results.items()} 

582 

583 

584def _read_hirshfeld_charges(out: io.TextIOBase): 

585 """Read a block for Hirshfeld charges from a .castep file.""" 

586 for i in range(3): 

587 line = out.readline() 

588 if i == 1: 

589 spin_polarized = 'Spin' in line 

590 results = defaultdict(list) 

591 for line in out: 

592 fields = line.split() 

593 if len(fields) == 1: 

594 break 

595 if spin_polarized: 

596 results['hirshfeld_charges'].append(float(fields[-2])) 

597 results['hirshfeld_magmoms'].append(float(fields[-1])) 

598 else: 

599 results['hirshfeld_charges'].append(float(fields[-1])) 

600 return {k: np.array(v) for k, v in results.items()} 

601 

602 

603def _set_energy_and_free_energy(results: dict[str, Any]): 

604 """Set values referred to as `energy` and `free_energy`.""" 

605 if 'energy_with_dispersion_correction' in results: 

606 suffix = '_with_dispersion_correction' 

607 else: 

608 suffix = '_without_dispersion_correction' 

609 

610 if 'free_energy' + suffix in results: # metallic 

611 keye = 'energy_zero' + suffix 

612 keyf = 'free_energy' + suffix 

613 else: # non-metallic 

614 # The finite basis set correction is applied to the energy at finite T 

615 # (not the energy at 0 K). We should hence refer to the corrected value 

616 # as `energy` only when the free energy is unavailable, i.e., only when 

617 # FIX_OCCUPANCY : TRUE and thus no smearing is applied. 

618 if 'energy_with_finite_basis_set_correction' in results: 

619 keye = 'energy_with_finite_basis_set_correction' 

620 else: 

621 keye = 'energy' + suffix 

622 keyf = 'energy' + suffix 

623 

624 results['energy'] = results[keye] 

625 results['free_energy'] = results[keyf]