Coverage for ase/io/castep/__init__.py: 74.33%

557 statements  

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

1"""This module defines I/O routines with CASTEP files. 

2The key idea is that all function accept or return atoms objects. 

3CASTEP specific parameters will be returned through the <atoms>.calc 

4attribute. 

5""" 

6 

7import os 

8import re 

9import warnings 

10from copy import deepcopy 

11 

12import numpy as np 

13 

14import ase 

15 

16# independent unit management included here: 

17# When high accuracy is required, this allows to easily pin down 

18# unit conversion factors from different "unit definition systems" 

19# (CODATA1986 for ase-3.6.0.2515 vs CODATA2002 for CASTEP 5.01). 

20# 

21# ase.units in in ase-3.6.0.2515 is based on CODATA1986 

22import ase.units 

23from ase.constraints import FixAtoms, FixCartesian, FixedLine, FixedPlane 

24from ase.geometry.cell import cellpar_to_cell 

25from ase.io.castep.castep_reader import read_castep_castep 

26from ase.parallel import paropen 

27from ase.spacegroup import Spacegroup 

28from ase.utils import ( 

29 atoms_to_spglib_cell, 

30 reader, 

31 spglib_new_errorhandling, 

32 writer, 

33) 

34 

35from .geom_md_ts import ( 

36 read_castep_geom, 

37 read_castep_md, 

38 write_castep_geom, 

39 write_castep_md, 

40) 

41 

42units_ase = { 

43 'hbar': ase.units._hbar * ase.units.J, 

44 'Eh': ase.units.Hartree, 

45 'kB': ase.units.kB, 

46 'a0': ase.units.Bohr, 

47 't0': ase.units._hbar * ase.units.J / ase.units.Hartree, 

48 'c': ase.units._c, 

49 'me': ase.units._me / ase.units._amu, 

50 'Pascal': 1.0 / ase.units.Pascal, 

51} 

52 

53# CODATA1986 (included herein for the sake of completeness) 

54# taken from 

55# http://physics.nist.gov/cuu/Archive/1986RMP.pdf 

56units_CODATA1986 = { 

57 'hbar': 6.5821220e-16, # eVs 

58 'Eh': 27.2113961, # eV 

59 'kB': 8.617385e-5, # eV/K 

60 'a0': 0.529177249, # A 

61 'c': 299792458, # m/s 

62 'e': 1.60217733e-19, # C 

63 'me': 5.485799110e-4, # u 

64} 

65 

66# CODATA2002: default in CASTEP 5.01 

67# (-> check in more recent CASTEP in case of numerical discrepancies?!) 

68# taken from 

69# http://physics.nist.gov/cuu/Document/all_2002.pdf 

70units_CODATA2002 = { 

71 'hbar': 6.58211915e-16, # eVs 

72 'Eh': 27.2113845, # eV 

73 'kB': 8.617343e-5, # eV/K 

74 'a0': 0.5291772108, # A 

75 'c': 299792458, # m/s 

76 'e': 1.60217653e-19, # C 

77 'me': 5.4857990945e-4, # u 

78} 

79 

80# (common) derived entries 

81for d in (units_CODATA1986, units_CODATA2002): 

82 d['t0'] = d['hbar'] / d['Eh'] # s 

83 d['Pascal'] = d['e'] * 1e30 # Pa 

84 

85 

86__all__ = [ 

87 # routines for the generic io function 

88 'read_castep_castep', 

89 'read_castep_cell', 

90 'read_castep_geom', 

91 'read_castep_md', 

92 'read_phonon', 

93 'read_castep_phonon', 

94 # additional reads that still need to be wrapped 

95 'read_param', 

96 'read_seed', 

97 # write that is already wrapped 

98 'write_castep_cell', 

99 'write_castep_geom', 

100 'write_castep_md', 

101 # param write - in principle only necessary in junction with the calculator 

102 'write_param', 

103] 

104 

105 

106def write_freeform(fd, outputobj): 

107 """ 

108 Prints out to a given file a CastepInputFile or derived class, such as 

109 CastepCell or CastepParam. 

110 """ 

111 

112 options = outputobj._options 

113 

114 # Some keywords, if present, are printed in this order 

115 preferred_order = [ 

116 'lattice_cart', 

117 'lattice_abc', 

118 'positions_frac', 

119 'positions_abs', 

120 'species_pot', 

121 'symmetry_ops', # CELL file 

122 'task', 

123 'cut_off_energy', # PARAM file 

124 ] 

125 

126 keys = outputobj.get_attr_dict().keys() 

127 # This sorts only the ones in preferred_order and leaves the rest 

128 # untouched 

129 keys = sorted( 

130 keys, 

131 key=lambda x: ( 

132 preferred_order.index(x) 

133 if x in preferred_order 

134 else len(preferred_order) 

135 ), 

136 ) 

137 

138 for kw in keys: 

139 opt = options[kw] 

140 if opt.type.lower() == 'block': 

141 fd.write( 

142 '%BLOCK {0}\n{1}\n%ENDBLOCK {0}\n\n'.format( 

143 kw.upper(), opt.value.strip('\n') 

144 ) 

145 ) 

146 else: 

147 fd.write(f'{kw.upper()}: {opt.value}\n') 

148 

149 

150@writer 

151def write_castep_cell( 

152 fd, 

153 atoms, 

154 positions_frac=False, 

155 force_write=False, 

156 precision=6, 

157 magnetic_moments=None, 

158 castep_cell=None, 

159): 

160 """ 

161 This CASTEP export function write minimal information to 

162 a .cell file. If the atoms object is a trajectory, it will 

163 take the last image. 

164 

165 Note that function has been altered in order to require a filedescriptor 

166 rather than a filename. This allows to use the more generic write() 

167 function from formats.py 

168 

169 Note that the "force_write" keywords has no effect currently. 

170 

171 Arguments: 

172 

173 positions_frac: boolean. If true, positions are printed as fractional 

174 rather than absolute. Default is false. 

175 castep_cell: if provided, overrides the existing CastepCell object in 

176 the Atoms calculator 

177 precision: number of digits to which lattice and positions are printed 

178 magnetic_moments: if None, no SPIN values are initialised. 

179 If 'initial', the values from 

180 get_initial_magnetic_moments() are used. 

181 If 'calculated', the values from 

182 get_magnetic_moments() are used. 

183 If an array of the same length as the atoms object, 

184 its contents will be used as magnetic moments. 

185 """ 

186 

187 if isinstance(atoms, list): 

188 if len(atoms) > 1: 

189 atoms = atoms[-1] 

190 

191 # Header 

192 fd.write('# written by ASE\n\n') 

193 

194 # To write this we simply use the existing Castep calculator, or create 

195 # one 

196 from ase.calculators.castep import Castep, CastepCell 

197 

198 try: 

199 has_cell = isinstance(atoms.calc.cell, CastepCell) 

200 except AttributeError: 

201 has_cell = False 

202 

203 if has_cell: 

204 cell = deepcopy(atoms.calc.cell) 

205 else: 

206 cell = Castep(keyword_tolerance=2).cell 

207 

208 # Write lattice 

209 fformat = f'%{precision + 3}.{precision}f' 

210 cell_block_format = ' '.join([fformat] * 3) 

211 cell.lattice_cart = [ 

212 cell_block_format % tuple(line) for line in atoms.get_cell() 

213 ] 

214 

215 if positions_frac: 

216 pos_keyword = 'positions_frac' 

217 positions = atoms.get_scaled_positions() 

218 else: 

219 pos_keyword = 'positions_abs' 

220 positions = atoms.get_positions() 

221 

222 if atoms.has('castep_custom_species'): 

223 elems = atoms.get_array('castep_custom_species') 

224 else: 

225 elems = atoms.get_chemical_symbols() 

226 if atoms.has('masses'): 

227 from ase.data import atomic_masses 

228 

229 masses = atoms.get_array('masses') 

230 custom_masses = {} 

231 

232 for i, species in enumerate(elems): 

233 custom_mass = masses[i] 

234 

235 # build record of different masses for each species 

236 if species not in custom_masses: 

237 # build dictionary of positions of all species with 

238 # same name and mass value ideally there should only 

239 # be one mass per species 

240 custom_masses[species] = {custom_mass: [i]} 

241 

242 # if multiple masses found for a species 

243 elif custom_mass not in custom_masses[species].keys(): 

244 # if custom species were already manually defined raise an error 

245 if atoms.has('castep_custom_species'): 

246 raise ValueError( 

247 'Could not write custom mass block for {0}. \n' 

248 'Custom mass was set ({1}), but an inconsistent set of ' 

249 'castep_custom_species already defines ' 

250 '({2}) for {0}. \n' 

251 'If using both features, ensure that ' 

252 'each species type in ' 

253 "atoms.arrays['castep_custom_species'] " 

254 'has consistent mass values and that each atom ' 

255 'with non-standard ' 

256 'mass belongs to a custom species type.' 

257 ''.format( 

258 species, 

259 custom_mass, 

260 list(custom_masses[species].keys())[0], 

261 ) 

262 ) 

263 

264 # append mass to create custom species later 

265 else: 

266 custom_masses[species][custom_mass] = [i] 

267 else: 

268 custom_masses[species][custom_mass].append(i) 

269 

270 # create species_mass block 

271 mass_block = [] 

272 

273 for el, mass_dict in custom_masses.items(): 

274 # ignore mass record that match defaults 

275 default = mass_dict.pop( 

276 atomic_masses[ 

277 atoms.get_array('numbers')[list(elems).index(el)] 

278 ], 

279 None, 

280 ) 

281 if mass_dict: 

282 # no custom species need to be created 

283 if len(mass_dict) == 1 and not default: 

284 mass_block.append( 

285 '{} {}'.format(el, list(mass_dict.keys())[0]) 

286 ) 

287 # for each custom mass, create new species and change names to 

288 # match in 'elems' list 

289 else: 

290 warnings.warn( 

291 'Custom mass specified for ' 

292 'standard species {}, creating custom species'.format( 

293 el 

294 ) 

295 ) 

296 

297 for i, vals in enumerate(mass_dict.items()): 

298 mass_val, idxs = vals 

299 custom_species_name = f'{el}:{i}' 

300 warnings.warn( 

301 'Creating custom species {} with mass {}'.format( 

302 custom_species_name, str(mass_dict) 

303 ) 

304 ) 

305 for idx in idxs: 

306 elems[idx] = custom_species_name 

307 mass_block.append( 

308 '{} {}'.format(custom_species_name, mass_val) 

309 ) 

310 

311 cell.species_mass = mass_block 

312 

313 if atoms.has('castep_labels'): 

314 labels = atoms.get_array('castep_labels') 

315 else: 

316 labels = ['NULL'] * len(elems) 

317 

318 if str(magnetic_moments).lower() == 'initial': 

319 magmoms = atoms.get_initial_magnetic_moments() 

320 elif str(magnetic_moments).lower() == 'calculated': 

321 magmoms = atoms.get_magnetic_moments() 

322 elif np.array(magnetic_moments).shape == (len(elems),): 

323 magmoms = np.array(magnetic_moments) 

324 else: 

325 magmoms = [0] * len(elems) 

326 

327 pos_block = [] 

328 pos_block_format = '%s ' + cell_block_format 

329 

330 for i, el in enumerate(elems): 

331 xyz = positions[i] 

332 line = pos_block_format % tuple([el] + list(xyz)) 

333 # ADD other keywords if necessary 

334 if magmoms[i] != 0: 

335 line += f' SPIN={magmoms[i]} ' 

336 if labels[i].strip() not in ('NULL', ''): 

337 line += f' LABEL={labels[i]} ' 

338 pos_block.append(line) 

339 

340 setattr(cell, pos_keyword, pos_block) 

341 

342 constr_block = _make_block_ionic_constraints(atoms) 

343 if constr_block: 

344 cell.ionic_constraints = constr_block 

345 

346 write_freeform(fd, cell) 

347 

348 

349def _make_block_ionic_constraints(atoms: ase.Atoms) -> list[str]: 

350 constr_block: list[str] = [] 

351 species_indices = atoms.symbols.species_indices() 

352 for constr in atoms.constraints: 

353 if not _is_constraint_valid(constr, len(atoms)): 

354 continue 

355 for i in constr.index: 

356 symbol = atoms.get_chemical_symbols()[i] 

357 nis = species_indices[i] + 1 

358 if isinstance(constr, FixAtoms): 

359 for j in range(3): # constraint for all three directions 

360 ic = len(constr_block) + 1 

361 line = f'{ic:6d} {symbol:3s} {nis:3d} ' 

362 line += ['1 0 0', '0 1 0', '0 0 1'][j] 

363 constr_block.append(line) 

364 elif isinstance(constr, FixCartesian): 

365 for j, m in enumerate(constr.mask): 

366 if m == 0: # not constrained 

367 continue 

368 ic = len(constr_block) + 1 

369 line = f'{ic:6d} {symbol:3s} {nis:3d} ' 

370 line += ['1 0 0', '0 1 0', '0 0 1'][j] 

371 constr_block.append(line) 

372 elif isinstance(constr, FixedPlane): 

373 ic = len(constr_block) + 1 

374 line = f'{ic:6d} {symbol:3s} {nis:3d} ' 

375 line += ' '.join([str(d) for d in constr.dir]) 

376 constr_block.append(line) 

377 elif isinstance(constr, FixedLine): 

378 for direction in _calc_normal_vectors(constr): 

379 ic = len(constr_block) + 1 

380 line = f'{ic:6d} {symbol:3s} {nis:3d} ' 

381 line += ' '.join(str(_) for _ in direction) 

382 constr_block.append(line) 

383 return constr_block 

384 

385 

386def _is_constraint_valid(constraint, natoms: int) -> bool: 

387 supported_constraints = (FixAtoms, FixedPlane, FixedLine, FixCartesian) 

388 if not isinstance(constraint, supported_constraints): 

389 warnings.warn(f'{constraint} is not supported by ASE CASTEP, skipped') 

390 return False 

391 if any(i < 0 or i >= natoms for i in constraint.index): 

392 warnings.warn(f'{constraint} contains invalid indices, skipped') 

393 return False 

394 return True 

395 

396 

397def _calc_normal_vectors(constr: FixedLine) -> tuple[np.ndarray, np.ndarray]: 

398 direction = constr.dir 

399 

400 i2, i1 = np.argsort(np.abs(direction))[1:] 

401 v1 = direction[i1] 

402 v2 = direction[i2] 

403 n1 = np.zeros(3) 

404 n1[i2] = v1 

405 n1[i1] = -v2 

406 n1 = n1 / np.linalg.norm(n1) 

407 

408 n2 = np.cross(direction, n1) 

409 n2 = n2 / np.linalg.norm(n2) 

410 

411 return n1, n2 

412 

413 

414def read_freeform(fd): 

415 """ 

416 Read a CASTEP freeform file (the basic format of .cell and .param files) 

417 and return keyword-value pairs as a dict (values are strings for single 

418 keywords and lists of strings for blocks). 

419 """ 

420 

421 from ase.io.castep.castep_input_file import CastepInputFile 

422 

423 inputobj = CastepInputFile(keyword_tolerance=2) 

424 

425 filelines = fd.readlines() 

426 

427 keyw = None 

428 read_block = False 

429 block_lines = None 

430 

431 for i, l in enumerate(filelines): 

432 # Strip all comments, aka anything after a hash 

433 L = re.split(r'[#!;]', l, maxsplit=1)[0].strip() 

434 

435 if L == '': 

436 # Empty line... skip 

437 continue 

438 

439 lsplit = re.split(r'\s*[:=]*\s+', L, maxsplit=1) 

440 

441 if read_block: 

442 if lsplit[0].lower() == '%endblock': 

443 if len(lsplit) == 1 or lsplit[1].lower() != keyw: 

444 raise ValueError( 

445 'Out of place end of block at ' 

446 'line %i in freeform file' % i + 1 

447 ) 

448 else: 

449 read_block = False 

450 inputobj.__setattr__(keyw, block_lines) 

451 else: 

452 block_lines += [L] 

453 else: 

454 # Check the first word 

455 

456 # Is it a block? 

457 read_block = lsplit[0].lower() == '%block' 

458 if read_block: 

459 if len(lsplit) == 1: 

460 raise ValueError( 

461 ('Unrecognizable block at line %i in io freeform file') 

462 % i 

463 + 1 

464 ) 

465 else: 

466 keyw = lsplit[1].lower() 

467 else: 

468 keyw = lsplit[0].lower() 

469 

470 # Now save the value 

471 if read_block: 

472 block_lines = [] 

473 else: 

474 inputobj.__setattr__(keyw, ' '.join(lsplit[1:])) 

475 

476 return inputobj.get_attr_dict(types=True) 

477 

478 

479@reader 

480def read_castep_cell( 

481 fd, index=None, calculator_args=None, find_spg=False, units=units_CODATA2002 

482): 

483 """Read a .cell file and return an atoms object. 

484 Any value found that does not fit the atoms API 

485 will be stored in the atoms.calc attribute. 

486 

487 By default, the Castep calculator will be tolerant and in the absence of a 

488 castep_keywords.json file it will just accept all keywords that aren't 

489 automatically parsed. 

490 """ 

491 

492 from ase.calculators.castep import Castep 

493 

494 if calculator_args is None: 

495 calculator_args = {} 

496 cell_units = { # Units specifiers for CASTEP 

497 'bohr': units_CODATA2002['a0'], 

498 'ang': 1.0, 

499 'm': 1e10, 

500 'cm': 1e8, 

501 'nm': 10, 

502 'pm': 1e-2, 

503 } 

504 

505 calc = Castep(**calculator_args) 

506 

507 if calc.cell.castep_version == 0 and calc._kw_tol < 3: 

508 # No valid castep_keywords.json was found 

509 warnings.warn( 

510 'read_cell: Warning - Was not able to validate CASTEP input. ' 

511 'This may be due to a non-existing ' 

512 '"castep_keywords.json" ' 

513 'file or a non-existing CASTEP installation. ' 

514 'Parsing will go on but keywords will not be ' 

515 'validated and may cause problems if incorrect during a CASTEP ' 

516 'run.' 

517 ) 

518 

519 celldict = read_freeform(fd) 

520 

521 def parse_blockunit(line_tokens, blockname): 

522 u = 1.0 

523 if len(line_tokens[0]) == 1: 

524 usymb = line_tokens[0][0].lower() 

525 u = cell_units.get(usymb, 1) 

526 if usymb not in cell_units: 

527 warnings.warn( 

528 'read_cell: Warning - ignoring invalid ' 

529 'unit specifier in %BLOCK {} ' 

530 '(assuming Angstrom instead)'.format(blockname) 

531 ) 

532 line_tokens = line_tokens[1:] 

533 return u, line_tokens 

534 

535 # Arguments to pass to the Atoms object at the end 

536 aargs = {'pbc': True} 

537 

538 # Start by looking for the lattice 

539 lat_keywords = [w in celldict for w in ('lattice_cart', 'lattice_abc')] 

540 if all(lat_keywords): 

541 warnings.warn( 

542 'read_cell: Warning - two lattice blocks present in the' 

543 ' same file. LATTICE_ABC will be ignored' 

544 ) 

545 elif not any(lat_keywords): 

546 raise ValueError( 

547 'Cell file must contain at least one between ' 

548 'LATTICE_ABC and LATTICE_CART' 

549 ) 

550 

551 if 'lattice_abc' in celldict: 

552 lines = celldict.pop('lattice_abc')[0].split('\n') 

553 line_tokens = [line.split() for line in lines] 

554 

555 u, line_tokens = parse_blockunit(line_tokens, 'lattice_abc') 

556 

557 if len(line_tokens) != 2: 

558 warnings.warn( 

559 'read_cell: Warning - ignoring additional ' 

560 'lines in invalid %BLOCK LATTICE_ABC' 

561 ) 

562 

563 abc = [float(p) * u for p in line_tokens[0][:3]] 

564 angles = [float(phi) for phi in line_tokens[1][:3]] 

565 

566 aargs['cell'] = cellpar_to_cell(abc + angles) 

567 

568 if 'lattice_cart' in celldict: 

569 lines = celldict.pop('lattice_cart')[0].split('\n') 

570 line_tokens = [line.split() for line in lines] 

571 

572 u, line_tokens = parse_blockunit(line_tokens, 'lattice_cart') 

573 

574 if len(line_tokens) != 3: 

575 warnings.warn( 

576 'read_cell: Warning - ignoring more than ' 

577 'three lattice vectors in invalid %BLOCK ' 

578 'LATTICE_CART' 

579 ) 

580 

581 aargs['cell'] = [[float(x) * u for x in lt[:3]] for lt in line_tokens] 

582 

583 # Now move on to the positions 

584 pos_keywords = [w in celldict for w in ('positions_abs', 'positions_frac')] 

585 

586 if all(pos_keywords): 

587 warnings.warn( 

588 'read_cell: Warning - two lattice blocks present in the' 

589 ' same file. POSITIONS_FRAC will be ignored' 

590 ) 

591 del celldict['positions_frac'] 

592 elif not any(pos_keywords): 

593 raise ValueError( 

594 'Cell file must contain at least one between ' 

595 'POSITIONS_FRAC and POSITIONS_ABS' 

596 ) 

597 

598 aargs['symbols'] = [] 

599 pos_type = 'positions' 

600 pos_block = celldict.pop('positions_abs', [None])[0] 

601 if pos_block is None: 

602 pos_type = 'scaled_positions' 

603 pos_block = celldict.pop('positions_frac', [None])[0] 

604 aargs[pos_type] = [] 

605 

606 lines = pos_block.split('\n') 

607 line_tokens = [line.split() for line in lines] 

608 

609 if 'scaled' not in pos_type: 

610 u, line_tokens = parse_blockunit(line_tokens, 'positions_abs') 

611 else: 

612 u = 1.0 

613 

614 # Here we extract all the possible additional info 

615 # These are marked by their type 

616 

617 add_info = { 

618 'SPIN': (float, 0.0), # (type, default) 

619 'MAGMOM': (float, 0.0), 

620 'LABEL': (str, 'NULL'), 

621 } 

622 add_info_arrays = {k: [] for k in add_info} 

623 

624 def parse_info(raw_info): 

625 

626 re_keys = ( 

627 r'({0})\s*[=:\s]{{1}}\s' 

628 r'*([^\s]*)' 

629 ).format('|'.join(add_info.keys())) 

630 # Capture all info groups 

631 info = re.findall(re_keys, raw_info) 

632 info = {g[0]: add_info[g[0]][0](g[1]) for g in info} 

633 return info 

634 

635 # Array for custom species (a CASTEP special thing) 

636 # Usually left unused 

637 custom_species = None 

638 

639 for tokens in line_tokens: 

640 # Now, process the whole 'species' thing 

641 spec_custom = tokens[0].split(':', 1) 

642 elem = spec_custom[0] 

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

644 # Add it to the custom info! 

645 custom_species = list(aargs['symbols']) 

646 if custom_species is not None: 

647 custom_species.append(tokens[0]) 

648 aargs['symbols'].append(elem) 

649 aargs[pos_type].append([float(p) * u for p in tokens[1:4]]) 

650 # Now for the additional information 

651 info = ' '.join(tokens[4:]) 

652 info = parse_info(info) 

653 for k in add_info: 

654 add_info_arrays[k] += [info.get(k, add_info[k][1])] 

655 

656 # read in custom species mass 

657 if 'species_mass' in celldict: 

658 spec_list = custom_species if custom_species else aargs['symbols'] 

659 aargs['masses'] = [None for _ in spec_list] 

660 lines = celldict.pop('species_mass')[0].split('\n') 

661 line_tokens = [line.split() for line in lines] 

662 

663 if len(line_tokens[0]) == 1: 

664 if line_tokens[0][0].lower() not in ('amu', 'u'): 

665 raise ValueError( 

666 "unit specifier '{}' in %BLOCK SPECIES_MASS " 

667 'not recognised'.format(line_tokens[0][0].lower()) 

668 ) 

669 line_tokens = line_tokens[1:] 

670 

671 for tokens in line_tokens: 

672 token_pos_list = [ 

673 i for i, x in enumerate(spec_list) if x == tokens[0] 

674 ] 

675 if len(token_pos_list) == 0: 

676 warnings.warn( 

677 'read_cell: Warning - ignoring unused ' 

678 'species mass {} in %BLOCK SPECIES_MASS'.format(tokens[0]) 

679 ) 

680 for idx in token_pos_list: 

681 aargs['masses'][idx] = tokens[1] 

682 

683 # Now on to the species potentials... 

684 if 'species_pot' in celldict: 

685 lines = celldict.pop('species_pot')[0].split('\n') 

686 line_tokens = [line.split() for line in lines] 

687 

688 for tokens in line_tokens: 

689 if len(tokens) == 1: 

690 # It's a library 

691 all_spec = ( 

692 set(custom_species) 

693 if custom_species is not None 

694 else set(aargs['symbols']) 

695 ) 

696 for s in all_spec: 

697 calc.cell.species_pot = (s, tokens[0]) 

698 else: 

699 calc.cell.species_pot = tuple(tokens[:2]) 

700 

701 # Ionic constraints 

702 raw_constraints = {} 

703 

704 if 'ionic_constraints' in celldict: 

705 lines = celldict.pop('ionic_constraints')[0].split('\n') 

706 line_tokens = [line.split() for line in lines] 

707 

708 for tokens in line_tokens: 

709 if len(tokens) != 6: 

710 continue 

711 _, species, nic, *xyz = tokens 

712 

713 nic = int(nic) 

714 raw_constraints.setdefault((species, nic), []) 

715 raw_constraints[(species, nic)].append(np.array(xyz, dtype=float)) 

716 

717 # Symmetry operations 

718 if 'symmetry_ops' in celldict: 

719 lines = celldict.pop('symmetry_ops')[0].split('\n') 

720 line_tokens = [line.split() for line in lines] 

721 

722 # Read them in blocks of four 

723 blocks = np.array(line_tokens).astype(float) 

724 if ( 

725 len(blocks.shape) != 2 

726 or blocks.shape[1] != 3 

727 or blocks.shape[0] % 4 != 0 

728 ): 

729 warnings.warn( 

730 'Warning: could not parse SYMMETRY_OPS block properly, skipping' 

731 ) 

732 else: 

733 blocks = blocks.reshape((-1, 4, 3)) 

734 rotations = blocks[:, :3] 

735 translations = blocks[:, 3] 

736 

737 # Regardless of whether we recognize them, store these 

738 calc.cell.symmetry_ops = (rotations, translations) 

739 

740 # Anything else that remains, just add it to the cell object: 

741 for k, (val, otype) in celldict.items(): 

742 try: 

743 if otype == 'block': 

744 val = val.split('\n') # Avoids a bug for one-line blocks 

745 calc.cell.__setattr__(k, val) 

746 except Exception as e: 

747 raise RuntimeError(f'Problem setting calc.cell.{k} = {val}: {e}') 

748 

749 # Get the relevant additional info 

750 aargs['magmoms'] = np.array(add_info_arrays['SPIN']) 

751 # SPIN or MAGMOM are alternative keywords 

752 aargs['magmoms'] = np.where( 

753 aargs['magmoms'] != 0, aargs['magmoms'], add_info_arrays['MAGMOM'] 

754 ) 

755 labels = np.array(add_info_arrays['LABEL']) 

756 

757 aargs['calculator'] = calc 

758 

759 atoms = ase.Atoms(**aargs) 

760 _set_spacegroup_info(find_spg, atoms) 

761 

762 atoms.new_array('castep_labels', labels) 

763 if custom_species is not None: 

764 atoms.new_array('castep_custom_species', np.array(custom_species)) 

765 

766 fixed_atoms = [] 

767 constraints = [] 

768 index_dict = atoms.symbols.indices() 

769 for (species, nic), value in raw_constraints.items(): 

770 absolute_nr = index_dict[species][nic - 1] 

771 if len(value) == 3: 

772 # Check if they are linearly independent 

773 if np.linalg.det(value) == 0: 

774 warnings.warn( 

775 'Error: Found linearly dependent constraints attached ' 

776 'to atoms %s' % (absolute_nr) 

777 ) 

778 continue 

779 fixed_atoms.append(absolute_nr) 

780 elif len(value) == 2: 

781 direction = np.cross(value[0], value[1]) 

782 # Check if they are linearly independent 

783 if np.linalg.norm(direction) == 0: 

784 warnings.warn( 

785 'Error: Found linearly dependent constraints attached ' 

786 'to atoms %s' % (absolute_nr) 

787 ) 

788 continue 

789 constraint = FixedLine(indices=absolute_nr, direction=direction) 

790 constraints.append(constraint) 

791 elif len(value) == 1: 

792 direction = np.array(value[0], dtype=float) 

793 constraint = FixedPlane(indices=absolute_nr, direction=direction) 

794 constraints.append(constraint) 

795 else: 

796 warnings.warn( 

797 f'Error: Found {len(value)} statements attached to atoms ' 

798 f'{absolute_nr}' 

799 ) 

800 

801 # we need to sort the fixed atoms list in order not to raise an assertion 

802 # error in FixAtoms 

803 if fixed_atoms: 

804 constraints.append(FixAtoms(indices=sorted(fixed_atoms))) 

805 if constraints: 

806 atoms.set_constraint(constraints) 

807 

808 atoms.calc.atoms = atoms 

809 atoms.calc.push_oldstate() 

810 

811 return atoms 

812 

813 

814def read_phonon( 

815 filename, 

816 index=None, 

817 read_vib_data=False, 

818 gamma_only=True, 

819 frequency_factor=None, 

820 units=units_CODATA2002, 

821): 

822 """ 

823 Wrapper function for the more generic read() functionality. 

824 

825 Note that this is function is intended to maintain backwards-compatibility 

826 only. For documentation see read_castep_phonon(). 

827 """ 

828 from ase.io import read 

829 

830 if read_vib_data: 

831 full_output = True 

832 else: 

833 full_output = False 

834 

835 return read( 

836 filename, 

837 index=index, 

838 format='castep-phonon', 

839 full_output=full_output, 

840 read_vib_data=read_vib_data, 

841 gamma_only=gamma_only, 

842 frequency_factor=frequency_factor, 

843 units=units, 

844 ) 

845 

846 

847def read_castep_phonon( 

848 fd, 

849 index=None, 

850 read_vib_data=False, 

851 gamma_only=True, 

852 frequency_factor=None, 

853 units=units_CODATA2002, 

854): 

855 """ 

856 Reads a .phonon file written by a CASTEP Phonon task and returns an atoms 

857 object, as well as the calculated vibrational data if requested. 

858 

859 Note that the index argument has no effect as of now. 

860 """ 

861 

862 # fd is closed by embracing read() routine 

863 lines = fd.readlines() 

864 

865 atoms = None 

866 cell = [] 

867 N = Nb = Nq = 0 

868 scaled_positions = [] 

869 symbols = [] 

870 masses = [] 

871 

872 # header 

873 L = 0 

874 while L < len(lines): 

875 line = lines[L] 

876 

877 if 'Number of ions' in line: 

878 N = int(line.split()[3]) 

879 elif 'Number of branches' in line: 

880 Nb = int(line.split()[3]) 

881 elif 'Number of wavevectors' in line: 

882 Nq = int(line.split()[3]) 

883 elif 'Unit cell vectors (A)' in line: 

884 for _ in range(3): 

885 L += 1 

886 fields = lines[L].split() 

887 cell.append([float(x) for x in fields[0:3]]) 

888 elif 'Fractional Co-ordinates' in line: 

889 for _ in range(N): 

890 L += 1 

891 fields = lines[L].split() 

892 scaled_positions.append([float(x) for x in fields[1:4]]) 

893 symbols.append(fields[4]) 

894 masses.append(float(fields[5])) 

895 elif 'END header' in line: 

896 L += 1 

897 atoms = ase.Atoms( 

898 symbols=symbols, scaled_positions=scaled_positions, cell=cell 

899 ) 

900 break 

901 

902 L += 1 

903 

904 # Eigenmodes and -vectors 

905 if frequency_factor is None: 

906 Kayser_to_eV = 1e2 * 2 * np.pi * units['hbar'] * units['c'] 

907 # N.B. "fixed default" unit for frequencies in .phonon files is "cm-1" 

908 # (i.e. the latter is unaffected by the internal unit conversion system of 

909 # CASTEP!) set conversion factor to convert therefrom to eV by default for 

910 # now 

911 frequency_factor = Kayser_to_eV 

912 qpoints = [] 

913 weights = [] 

914 frequencies = [] 

915 displacements = [] 

916 for _ in range(Nq): 

917 fields = lines[L].split() 

918 qpoints.append([float(x) for x in fields[2:5]]) 

919 weights.append(float(fields[5])) 

920 

921 freqs = [] 

922 for _ in range(Nb): 

923 L += 1 

924 fields = lines[L].split() 

925 freqs.append(frequency_factor * float(fields[1])) 

926 frequencies.append(np.array(freqs)) 

927 

928 # skip the two Phonon Eigenvectors header lines 

929 L += 2 

930 

931 # generate a list of displacements with a structure that is identical to 

932 # what is stored internally in the Vibrations class (see in 

933 # ase.vibrations.Vibrations.modes): 

934 # np.array(displacements).shape == (Nb,3*N) 

935 

936 disps = [] 

937 for _ in range(Nb): 

938 disp_coords = [] 

939 for _ in range(N): 

940 L += 1 

941 fields = lines[L].split() 

942 disp_x = float(fields[2]) + float(fields[3]) * 1.0j 

943 disp_y = float(fields[4]) + float(fields[5]) * 1.0j 

944 disp_z = float(fields[6]) + float(fields[7]) * 1.0j 

945 disp_coords.extend([disp_x, disp_y, disp_z]) 

946 disps.append(np.array(disp_coords)) 

947 displacements.append(np.array(disps)) 

948 

949 L += 1 

950 

951 if read_vib_data: 

952 if gamma_only: 

953 vibdata = [frequencies[0], displacements[0]] 

954 else: 

955 vibdata = [qpoints, weights, frequencies, displacements] 

956 return vibdata, atoms 

957 else: 

958 return atoms 

959 

960 

961# Routines that only the calculator requires 

962 

963 

964def read_param(filename='', calc=None, fd=None, get_interface_options=False): 

965 if fd is None: 

966 if filename == '': 

967 raise ValueError('One between filename and fd must be provided') 

968 fd = open(filename) 

969 elif filename: 

970 warnings.warn( 

971 'Filestream used to read param, file name will be ignored' 

972 ) 

973 

974 # If necessary, get the interface options 

975 if get_interface_options: 

976 int_opts = {} 

977 optre = re.compile(r'# ASE_INTERFACE ([^\s]+) : ([^\s]+)') 

978 

979 lines = fd.readlines() 

980 fd.seek(0) 

981 

982 for line in lines: 

983 m = optre.search(line) 

984 if m: 

985 int_opts[m.groups()[0]] = m.groups()[1] 

986 

987 data = read_freeform(fd) 

988 

989 if calc is None: 

990 from ase.calculators.castep import Castep 

991 

992 calc = Castep(check_castep_version=False, keyword_tolerance=2) 

993 

994 for kw, (val, otype) in data.items(): 

995 if otype == 'block': 

996 val = val.split('\n') # Avoids a bug for one-line blocks 

997 calc.param.__setattr__(kw, val) 

998 

999 if not get_interface_options: 

1000 return calc 

1001 else: 

1002 return calc, int_opts 

1003 

1004 

1005def write_param( 

1006 filename, 

1007 param, 

1008 check_checkfile=False, 

1009 force_write=False, 

1010 interface_options=None, 

1011): 

1012 """Writes a CastepParam object to a CASTEP .param file 

1013 

1014 Parameters 

1015 ---------- 

1016 filename: the location of the file to write to. If it 

1017 exists it will be overwritten without warning. If it 

1018 doesn't it will be created. 

1019 param: a CastepParam instance 

1020 check_checkfile : if set to True, write_param will 

1021 only write continuation or reuse statement 

1022 if a restart file exists in the same directory 

1023 """ 

1024 if os.path.isfile(filename) and not force_write: 

1025 warnings.warn( 

1026 'ase.io.castep.write_param: Set optional argument ' 

1027 'force_write=True to overwrite %s.' % filename 

1028 ) 

1029 return False 

1030 

1031 out = paropen(filename, 'w') 

1032 out.write('#######################################################\n') 

1033 out.write(f'#CASTEP param file: {filename}\n') 

1034 out.write('#Created using the Atomic Simulation Environment (ASE)#\n') 

1035 if interface_options is not None: 

1036 out.write('# Internal settings of the calculator\n') 

1037 out.write('# This can be switched off by settings\n') 

1038 out.write('# calc._export_settings = False\n') 

1039 out.write('# If stated, this will be automatically processed\n') 

1040 out.write('# by ase.io.castep.read_seed()\n') 

1041 for option, value in sorted(interface_options.items()): 

1042 out.write(f'# ASE_INTERFACE {option} : {value}\n') 

1043 out.write('#######################################################\n\n') 

1044 

1045 if check_checkfile: 

1046 param = deepcopy(param) # To avoid modifying the parent one 

1047 for checktype in ['continuation', 'reuse']: 

1048 opt = getattr(param, checktype) 

1049 if opt and opt.value: 

1050 fname = opt.value 

1051 if fname == 'default': 

1052 fname = os.path.splitext(filename)[0] + '.check' 

1053 if not ( 

1054 os.path.exists(fname) 

1055 or 

1056 # CASTEP also understands relative path names, hence 

1057 # also check relative to the param file directory 

1058 os.path.exists( 

1059 os.path.join(os.path.dirname(filename), opt.value) 

1060 ) 

1061 ): 

1062 opt.clear() 

1063 

1064 write_freeform(out, param) 

1065 

1066 out.close() 

1067 

1068 

1069def read_seed(seed, new_seed=None, ignore_internal_keys=False): 

1070 """A wrapper around the CASTEP Calculator in conjunction with 

1071 read_cell and read_param. Basically this can be used to reuse 

1072 a previous calculation which results in a triple of 

1073 cell/param/castep file. The label of the calculation if pre- 

1074 fixed with `copy_of_` and everything else will be recycled as 

1075 much as possible from the addressed calculation. 

1076 

1077 Please note that this routine will return an atoms ordering as specified 

1078 in the cell file! It will thus undo the potential reordering internally 

1079 done by castep. 

1080 """ 

1081 

1082 directory = os.path.abspath(os.path.dirname(seed)) 

1083 seed = os.path.basename(seed) 

1084 

1085 paramfile = os.path.join(directory, f'{seed}.param') 

1086 cellfile = os.path.join(directory, f'{seed}.cell') 

1087 castepfile = os.path.join(directory, f'{seed}.castep') 

1088 checkfile = os.path.join(directory, f'{seed}.check') 

1089 

1090 atoms = read_castep_cell(cellfile) 

1091 atoms.calc._directory = directory 

1092 atoms.calc._rename_existing_dir = False 

1093 atoms.calc._castep_pp_path = directory 

1094 atoms.calc.merge_param(paramfile, ignore_internal_keys=ignore_internal_keys) 

1095 if new_seed is None: 

1096 atoms.calc._label = f'copy_of_{seed}' 

1097 else: 

1098 atoms.calc._label = str(new_seed) 

1099 if os.path.isfile(castepfile): 

1100 # _set_atoms needs to be True here 

1101 # but we set it right back to False 

1102 # atoms.calc._set_atoms = False 

1103 # BUGFIX: I do not see a reason to do that! 

1104 atoms.calc.read(castepfile) 

1105 # atoms.calc._set_atoms = False 

1106 

1107 # if here is a check file, we also want to re-use this information 

1108 if os.path.isfile(checkfile): 

1109 atoms.calc._check_file = os.path.basename(checkfile) 

1110 

1111 # sync the top-level object with the 

1112 # one attached to the calculator 

1113 atoms = atoms.calc.atoms 

1114 else: 

1115 # There are cases where we only want to restore a calculator/atoms 

1116 # setting without a castep file... 

1117 # No print statement required in these cases 

1118 warnings.warn( 

1119 'Corresponding *.castep file not found. ' 

1120 'Atoms object will be restored from *.cell and *.param only.' 

1121 ) 

1122 atoms.calc.push_oldstate() 

1123 

1124 return atoms 

1125 

1126 

1127@reader 

1128def read_bands(fd, units=units_CODATA2002): 

1129 """Read Castep.bands file to kpoints, weights and eigenvalues. 

1130 

1131 Parameters 

1132 ---------- 

1133 fd : str | io.TextIOBase 

1134 Path to the `.bands` file or file descriptor for open `.bands` file. 

1135 units : dict 

1136 Conversion factors for atomic units. 

1137 

1138 Returns 

1139 ------- 

1140 kpts : np.ndarray 

1141 1d NumPy array for k-point coordinates. 

1142 weights : np.ndarray 

1143 1d NumPy array for k-point weights. 

1144 eigenvalues : np.ndarray 

1145 NumPy array for eigenvalues with shape (spin, kpts, nbands). 

1146 efermi : float 

1147 Fermi energy. 

1148 

1149 """ 

1150 Hartree = units['Eh'] 

1151 

1152 nkpts = int(fd.readline().split()[-1]) 

1153 nspin = int(fd.readline().split()[-1]) 

1154 _ = float(fd.readline().split()[-1]) 

1155 nbands = int(fd.readline().split()[-1]) 

1156 efermi = float(fd.readline().split()[-1]) 

1157 

1158 kpts = np.zeros((nkpts, 3)) 

1159 weights = np.zeros(nkpts) 

1160 eigenvalues = np.zeros((nspin, nkpts, nbands)) 

1161 

1162 # Skip unit cell 

1163 for _ in range(4): 

1164 fd.readline() 

1165 

1166 def _kptline_to_i_k_wt(line: str) -> tuple[int, list[float], float]: 

1167 split_line = line.split() 

1168 i_kpt = int(split_line[1]) - 1 

1169 kpt = list(map(float, split_line[2:5])) 

1170 wt = float(split_line[5]) 

1171 return i_kpt, kpt, wt 

1172 

1173 # CASTEP often writes these out-of-order, so check index and write directly 

1174 # to the correct row 

1175 for _ in range(nkpts): 

1176 i_kpt, kpt, wt = _kptline_to_i_k_wt(fd.readline()) 

1177 kpts[i_kpt, :], weights[i_kpt] = kpt, wt 

1178 for spin in range(nspin): 

1179 fd.readline() # Skip 'Spin component N' line 

1180 eigenvalues[spin, i_kpt, :] = [ 

1181 float(fd.readline()) for _ in range(nbands) 

1182 ] 

1183 

1184 return (kpts, weights, eigenvalues * Hartree, efermi * Hartree) 

1185 

1186 

1187def _set_spacegroup_info(find_spg: bool, atoms: ase.Atoms) -> None: 

1188 """If requested, get spacegroup with spglib and attach to atoms.info""" 

1189 

1190 if not find_spg: 

1191 return 

1192 

1193 try: 

1194 import spglib 

1195 except ImportError: 

1196 warnings.warn( 

1197 'spglib not found installed on this system - ' 

1198 'automatic spacegroup detection is not possible' 

1199 ) 

1200 return 

1201 

1202 symmd = spglib_new_errorhandling(spglib.get_symmetry_dataset)( 

1203 atoms_to_spglib_cell(atoms) 

1204 ) 

1205 atoms_spg = Spacegroup(int(symmd['number'])) 

1206 atoms.info['spacegroup'] = atoms_spg