Coverage for ase/io/aims.py: 93.10%

812 statements  

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

1"""Defines class/functions to write input and parse output for FHI-aims.""" 

2 

3import os 

4import re 

5import time 

6import warnings 

7from functools import cached_property 

8from pathlib import Path 

9from typing import Any 

10 

11import numpy as np 

12 

13from ase import Atom, Atoms 

14from ase.calculators.calculator import kpts2mp 

15from ase.calculators.singlepoint import SinglePointDFTCalculator 

16from ase.constraints import FixAtoms, FixCartesian 

17from ase.data import atomic_numbers 

18from ase.io import ParseError 

19from ase.units import Ang, fs 

20from ase.utils import deprecated, reader, writer 

21 

22v_unit = Ang / (1000.0 * fs) 

23 

24LINE_NOT_FOUND = object() 

25 

26 

27class AimsParseError(Exception): 

28 """Exception raised if an error occurs when parsing an Aims output file""" 

29 

30 def __init__(self, message): 

31 self.message = message 

32 super().__init__(self.message) 

33 

34 

35# Read aims geometry files 

36 

37 

38@deprecated( 

39 message=( 

40 'FHI-aims IO is moving to the ase-io-aims plugin.' 

41 ' To test, install the plugin (`pip install ase-io-aims`)' 

42 ' and use `read(..., format=aims-plugin)`.' 

43 ' This functionality will be removed at a later date and' 

44 ' `format=aims` will be used for new functionality.' 

45 ), 

46 category=FutureWarning, 

47) 

48@reader 

49def read_aims(fd, apply_constraints=True): 

50 """Import FHI-aims geometry type files. 

51 

52 Reads unitcell, atom positions and constraints from 

53 a geometry.in file. 

54 

55 If geometric constraint (symmetry parameters) are in the file 

56 include that information in atoms.info["symmetry_block"] 

57 """ 

58 

59 lines = fd.readlines() 

60 return parse_geometry_lines(lines, apply_constraints=apply_constraints) 

61 

62 

63def parse_geometry_lines(lines, apply_constraints=True): 

64 

65 from ase import Atoms 

66 from ase.constraints import ( 

67 FixAtoms, 

68 FixCartesian, 

69 FixCartesianParametricRelations, 

70 FixScaledParametricRelations, 

71 ) 

72 

73 atoms = Atoms() 

74 

75 positions = [] 

76 cell = [] 

77 symbols = [] 

78 velocities = [] 

79 magmoms = [] 

80 symmetry_block = [] 

81 charges = [] 

82 fix = [] 

83 fix_cart = [] 

84 xyz = np.array([0, 0, 0]) 

85 i = -1 

86 n_periodic = -1 

87 periodic = np.array([False, False, False]) 

88 cart_positions, scaled_positions = False, False 

89 for line in lines: 

90 inp = line.split() 

91 if inp == []: 

92 continue 

93 if inp[0] in ['atom', 'atom_frac']: 

94 if inp[0] == 'atom': 

95 cart_positions = True 

96 else: 

97 scaled_positions = True 

98 

99 if xyz.all(): 

100 fix.append(i) 

101 elif xyz.any(): 

102 fix_cart.append(FixCartesian(i, xyz)) 

103 floatvect = float(inp[1]), float(inp[2]), float(inp[3]) 

104 positions.append(floatvect) 

105 symbols.append(inp[4]) 

106 magmoms.append(0.0) 

107 charges.append(0.0) 

108 xyz = np.array([0, 0, 0]) 

109 i += 1 

110 

111 elif inp[0] == 'lattice_vector': 

112 floatvect = float(inp[1]), float(inp[2]), float(inp[3]) 

113 cell.append(floatvect) 

114 n_periodic = n_periodic + 1 

115 periodic[n_periodic] = True 

116 

117 elif inp[0] == 'initial_moment': 

118 magmoms[-1] = float(inp[1]) 

119 

120 elif inp[0] == 'initial_charge': 

121 charges[-1] = float(inp[1]) 

122 

123 elif inp[0] == 'constrain_relaxation': 

124 if inp[1] == '.true.': 

125 fix.append(i) 

126 elif inp[1] == 'x': 

127 xyz[0] = 1 

128 elif inp[1] == 'y': 

129 xyz[1] = 1 

130 elif inp[1] == 'z': 

131 xyz[2] = 1 

132 

133 elif inp[0] == 'velocity': 

134 floatvect = [v_unit * float(line) for line in inp[1:4]] 

135 velocities.append(floatvect) 

136 

137 elif inp[0] in [ 

138 'symmetry_n_params', 

139 'symmetry_params', 

140 'symmetry_lv', 

141 'symmetry_frac', 

142 ]: 

143 symmetry_block.append(' '.join(inp)) 

144 

145 if xyz.all(): 

146 fix.append(i) 

147 elif xyz.any(): 

148 fix_cart.append(FixCartesian(i, xyz)) 

149 

150 if cart_positions and scaled_positions: 

151 raise Exception( 

152 "Can't specify atom positions with mixture of " 

153 'Cartesian and fractional coordinates' 

154 ) 

155 elif scaled_positions and periodic.any(): 

156 atoms = Atoms( 

157 symbols, scaled_positions=positions, cell=cell, pbc=periodic 

158 ) 

159 else: 

160 atoms = Atoms(symbols, positions) 

161 

162 if len(velocities) > 0: 

163 if len(velocities) != len(positions): 

164 raise Exception( 

165 'Number of positions and velocities have to coincide.' 

166 ) 

167 atoms.set_velocities(velocities) 

168 

169 fix_params = [] 

170 

171 if len(symmetry_block) > 5: 

172 params = symmetry_block[1].split()[1:] 

173 

174 lattice_expressions = [] 

175 lattice_params = [] 

176 

177 atomic_expressions = [] 

178 atomic_params = [] 

179 

180 n_lat_param = int(symmetry_block[0].split(' ')[2]) 

181 

182 lattice_params = params[:n_lat_param] 

183 atomic_params = params[n_lat_param:] 

184 

185 for ll, line in enumerate(symmetry_block[2:]): 

186 expression = ' '.join(line.split(' ')[1:]) 

187 if ll < 3: 

188 lattice_expressions += expression.split(',') 

189 else: 

190 atomic_expressions += expression.split(',') 

191 

192 fix_params.append( 

193 FixCartesianParametricRelations.from_expressions( 

194 list(range(3)), 

195 lattice_params, 

196 lattice_expressions, 

197 use_cell=True, 

198 ) 

199 ) 

200 

201 fix_params.append( 

202 FixScaledParametricRelations.from_expressions( 

203 list(range(len(atoms))), atomic_params, atomic_expressions 

204 ) 

205 ) 

206 

207 if any(magmoms): 

208 atoms.set_initial_magnetic_moments(magmoms) 

209 if any(charges): 

210 atoms.set_initial_charges(charges) 

211 

212 if periodic.any(): 

213 atoms.set_cell(cell) 

214 atoms.set_pbc(periodic) 

215 if len(fix): 

216 atoms.set_constraint([FixAtoms(indices=fix)] + fix_cart + fix_params) 

217 else: 

218 atoms.set_constraint(fix_cart + fix_params) 

219 

220 if fix_params and apply_constraints: 

221 atoms.set_positions(atoms.get_positions()) 

222 return atoms 

223 

224 

225def get_aims_header(): 

226 """Returns the header for aims input files""" 

227 lines = ['#' + '=' * 79] 

228 for line in [ 

229 'Created using the Atomic Simulation Environment (ASE)', 

230 time.asctime(), 

231 ]: 

232 lines.append('# ' + line + '\n') 

233 return lines 

234 

235 

236def _write_velocities_alias(args: list, kwargs: dict[str, Any]) -> bool: 

237 arg_position = 5 

238 if len(args) > arg_position and args[arg_position]: 

239 args[arg_position - 1] = True 

240 elif kwargs.get('velocities', False): 

241 if len(args) < arg_position: 

242 kwargs['write_velocities'] = True 

243 else: 

244 args[arg_position - 1] = True 

245 else: 

246 return False 

247 return True 

248 

249 

250# Write aims geometry files 

251@deprecated( 

252 'Use of `velocities` is deprecated, please use `write_velocities`', 

253 category=FutureWarning, 

254 callback=_write_velocities_alias, 

255) 

256@deprecated( 

257 message=( 

258 'FHI-aims IO is moving to the ase-io-aims plugin.' 

259 ' To test, install the plugin (`pip install ase-io-aims`)' 

260 ' and use `write(..., format=aims-plugin)`.' 

261 ' This functionality will be removed at a later date and' 

262 ' `format=aims` will be used for new functionality.' 

263 ), 

264 category=FutureWarning, 

265) 

266@writer 

267def write_aims( 

268 fd, 

269 atoms, 

270 scaled=False, 

271 geo_constrain=False, 

272 write_velocities=False, 

273 velocities=False, 

274 ghosts=None, 

275 info_str=None, 

276 wrap=False, 

277): 

278 """Method to write FHI-aims geometry files. 

279 

280 Writes the atoms positions and constraints (only FixAtoms is 

281 supported at the moment). 

282 

283 Args: 

284 fd: file object 

285 File to output structure to 

286 atoms: ase.atoms.Atoms 

287 structure to output to the file 

288 scaled: bool 

289 If True use fractional coordinates instead of Cartesian coordinates 

290 symmetry_block: list of str 

291 List of geometric constraints as defined in: 

292 :arxiv:`1908.01610` 

293 write_velocities: bool 

294 If True add the atomic velocity vectors to the file 

295 velocities: bool 

296 NOT AN ARRAY OF VELOCITIES, but the legacy version of 

297 `write_velocities` 

298 ghosts: list of Atoms 

299 A list of ghost atoms for the system 

300 info_str: str 

301 A string to be added to the header of the file 

302 wrap: bool 

303 Wrap atom positions to cell before writing 

304 

305 .. deprecated:: 3.23.0 

306 Use of ``velocities`` is deprecated, please use ``write_velocities``. 

307 """ 

308 

309 if scaled and not np.all(atoms.pbc): 

310 raise ValueError( 

311 'Requesting scaled for a calculation where scaled=True, but ' 

312 'the system is not periodic' 

313 ) 

314 

315 if geo_constrain: 

316 if not scaled and np.all(atoms.pbc): 

317 warnings.warn( 

318 'Setting scaled to True because a symmetry_block is detected.' 

319 ) 

320 scaled = True 

321 elif not np.all(atoms.pbc): 

322 warnings.warn( 

323 'Parameteric constraints can only be used in periodic systems.' 

324 ) 

325 geo_constrain = False 

326 

327 for line in get_aims_header(): 

328 fd.write(line + '\n') 

329 

330 # If writing additional information is requested via info_str: 

331 if info_str is not None: 

332 fd.write('\n# Additional information:\n') 

333 if isinstance(info_str, list): 

334 fd.write('\n'.join([f'# {s}' for s in info_str])) 

335 else: 

336 fd.write(f'# {info_str}') 

337 fd.write('\n') 

338 

339 fd.write('#=======================================================\n') 

340 

341 i = 0 

342 if atoms.get_pbc().any(): 

343 for n, vector in enumerate(atoms.get_cell()): 

344 fd.write('lattice_vector ') 

345 for i in range(3): 

346 fd.write(f'{vector[i]:16.16f} ') 

347 fd.write('\n') 

348 

349 fix_cart = np.zeros((len(atoms), 3), dtype=bool) 

350 for constr in atoms.constraints: 

351 if isinstance(constr, FixAtoms): 

352 fix_cart[constr.index] = (True, True, True) 

353 elif isinstance(constr, FixCartesian): 

354 fix_cart[constr.index] = constr.mask 

355 

356 if ghosts is None: 

357 ghosts = np.zeros(len(atoms)) 

358 else: 

359 assert len(ghosts) == len(atoms) 

360 

361 wrap = wrap and not geo_constrain 

362 scaled_positions = atoms.get_scaled_positions(wrap=wrap) 

363 

364 for i, atom in enumerate(atoms): 

365 if ghosts[i] == 1: 

366 atomstring = 'empty ' 

367 elif scaled: 

368 atomstring = 'atom_frac ' 

369 else: 

370 atomstring = 'atom ' 

371 fd.write(atomstring) 

372 if scaled: 

373 for pos in scaled_positions[i]: 

374 fd.write(f'{pos:16.16f} ') 

375 else: 

376 for pos in atom.position: 

377 fd.write(f'{pos:16.16f} ') 

378 fd.write(atom.symbol) 

379 fd.write('\n') 

380 # (1) all coords are constrained: 

381 if fix_cart[i].all(): 

382 fd.write(' constrain_relaxation .true.\n') 

383 # (2) some coords are constrained: 

384 elif fix_cart[i].any(): 

385 xyz = fix_cart[i] 

386 for n in range(3): 

387 if xyz[n]: 

388 fd.write(f' constrain_relaxation {"xyz"[n]}\n') 

389 if atom.charge: 

390 fd.write(f' initial_charge {atom.charge:16.6f}\n') 

391 if atom.magmom: 

392 fd.write(f' initial_moment {atom.magmom:16.6f}\n') 

393 

394 if write_velocities and atoms.get_velocities() is not None: 

395 v = atoms.get_velocities()[i] / v_unit 

396 fd.write(f' velocity {v[0]:.16f} {v[1]:.16f} {v[2]:.16f}\n') 

397 

398 if geo_constrain: 

399 for line in get_sym_block(atoms): 

400 fd.write(line) 

401 

402 

403def get_sym_block(atoms): 

404 """Get symmetry block for Parametric constraints in atoms.constraints""" 

405 from ase.constraints import ( 

406 FixCartesianParametricRelations, 

407 FixScaledParametricRelations, 

408 ) 

409 

410 # Initialize param/expressions lists 

411 atomic_sym_params = [] 

412 lv_sym_params = [] 

413 atomic_param_constr = np.zeros((len(atoms),), dtype='<U100') 

414 lv_param_constr = np.zeros((3,), dtype='<U100') 

415 

416 # Populate param/expressions list 

417 for constr in atoms.constraints: 

418 if isinstance(constr, FixScaledParametricRelations): 

419 atomic_sym_params += constr.params 

420 

421 if np.any(atomic_param_constr[constr.indices] != ''): 

422 warnings.warn( 

423 'multiple parametric constraints defined for the same ' 

424 'atom, using the last one defined' 

425 ) 

426 

427 atomic_param_constr[constr.indices] = [ 

428 ', '.join(expression) for expression in constr.expressions 

429 ] 

430 elif isinstance(constr, FixCartesianParametricRelations): 

431 lv_sym_params += constr.params 

432 

433 if np.any(lv_param_constr[constr.indices] != ''): 

434 warnings.warn( 

435 'multiple parametric constraints defined for the same ' 

436 'lattice vector, using the last one defined' 

437 ) 

438 

439 lv_param_constr[constr.indices] = [ 

440 ', '.join(expression) for expression in constr.expressions 

441 ] 

442 

443 if np.all(atomic_param_constr == '') and np.all(lv_param_constr == ''): 

444 return [] 

445 

446 # Check Constraint Parameters 

447 if len(atomic_sym_params) != len(np.unique(atomic_sym_params)): 

448 warnings.warn( 

449 'Some parameters were used across constraints, they will be ' 

450 'combined in the aims calculations' 

451 ) 

452 atomic_sym_params = np.unique(atomic_sym_params) 

453 

454 if len(lv_sym_params) != len(np.unique(lv_sym_params)): 

455 warnings.warn( 

456 'Some parameters were used across constraints, they will be ' 

457 'combined in the aims calculations' 

458 ) 

459 lv_sym_params = np.unique(lv_sym_params) 

460 

461 if np.any(atomic_param_constr == ''): 

462 raise OSError( 

463 'FHI-aims input files require all atoms have defined parametric ' 

464 'constraints' 

465 ) 

466 

467 cell_inds = np.where(lv_param_constr == '')[0] 

468 for ind in cell_inds: 

469 lv_param_constr[ind] = '{:.16f}, {:.16f}, {:.16f}'.format( 

470 *atoms.cell[ind] 

471 ) 

472 

473 n_atomic_params = len(atomic_sym_params) 

474 n_lv_params = len(lv_sym_params) 

475 n_total_params = n_atomic_params + n_lv_params 

476 

477 sym_block = [] 

478 if n_total_params > 0: 

479 sym_block.append('#' + '=' * 55 + '\n') 

480 sym_block.append('# Parametric constraints\n') 

481 sym_block.append('#' + '=' * 55 + '\n') 

482 sym_block.append( 

483 'symmetry_n_params {:d} {:d} {:d}\n'.format( 

484 n_total_params, n_lv_params, n_atomic_params 

485 ) 

486 ) 

487 sym_block.append( 

488 'symmetry_params %s\n' % ' '.join(lv_sym_params + atomic_sym_params) 

489 ) 

490 

491 for constr in lv_param_constr: 

492 sym_block.append(f'symmetry_lv {constr:s}\n') 

493 

494 for constr in atomic_param_constr: 

495 sym_block.append(f'symmetry_frac {constr:s}\n') 

496 return sym_block 

497 

498 

499def format_aims_control_parameter(key, value, format='%s'): 

500 """Format a line for the aims control.in 

501 

502 Parameter 

503 --------- 

504 key: str 

505 Name of the paramteter to format 

506 value: Object 

507 The value to pass to the parameter 

508 format: str 

509 string to format the the text as 

510 

511 Returns 

512 ------- 

513 str 

514 The properly formatted line for the aims control.in 

515 """ 

516 return f'{key:35s}' + (format % value) + '\n' 

517 

518 

519# Write aims control.in files 

520@deprecated( 

521 message=( 

522 'FHI-aims IO is moving to the ase-io-aims plugin.' 

523 ' To test, install the plugin (`pip install ase-io-aims`)' 

524 ' and use `write(..., format=aims-control)`.' 

525 ' This functionality will be removed at a later date and' 

526 ' `format=aims` will be used for new functionality.' 

527 ), 

528 category=FutureWarning, 

529) 

530@writer 

531def write_control(fd, atoms, parameters, verbose_header=False): 

532 """Write the control.in file for FHI-aims 

533 Parameters 

534 ---------- 

535 fd: str 

536 The file object to write to 

537 atoms: atoms.Atoms 

538 The Atoms object for the requested calculation 

539 parameters: dict 

540 The dictionary of all paramters for the calculation 

541 verbose_header: bool 

542 If True then explcitly list the paramters used to generate the 

543 control.in file inside the header 

544 """ 

545 

546 parameters = dict(parameters) 

547 lim = '#' + '=' * 79 

548 

549 if parameters['xc'] == 'LDA': 

550 parameters['xc'] = 'pw-lda' 

551 

552 cubes = parameters.pop('cubes', None) 

553 

554 for line in get_aims_header(): 

555 fd.write(line + '\n') 

556 

557 if verbose_header: 

558 fd.write('# \n# List of parameters used to initialize the calculator:') 

559 for p, v in parameters.items(): 

560 s = f'# {p}:{v}\n' 

561 fd.write(s) 

562 fd.write(lim + '\n') 

563 

564 assert 'kpts' not in parameters or 'k_grid' not in parameters 

565 assert 'smearing' not in parameters or 'occupation_type' not in parameters 

566 

567 for key, value in parameters.items(): 

568 if key == 'kpts': 

569 mp = kpts2mp(atoms, parameters['kpts']) 

570 dk = 0.5 - 0.5 / np.array(mp) 

571 fd.write( 

572 format_aims_control_parameter('k_grid', tuple(mp), '%d %d %d') 

573 ) 

574 fd.write( 

575 format_aims_control_parameter('k_offset', tuple(dk), '%f %f %f') 

576 ) 

577 elif key in ('species_dir', 'tier'): 

578 continue 

579 elif key == 'aims_command': 

580 continue 

581 elif key == 'plus_u': 

582 continue 

583 elif key == 'smearing': 

584 name = parameters['smearing'][0].lower() 

585 if name == 'fermi-dirac': 

586 name = 'fermi' 

587 width = parameters['smearing'][1] 

588 if name == 'methfessel-paxton': 

589 order = parameters['smearing'][2] 

590 order = ' %d' % order 

591 else: 

592 order = '' 

593 

594 fd.write( 

595 format_aims_control_parameter( 

596 'occupation_type', (name, width, order), '%s %f%s' 

597 ) 

598 ) 

599 elif key == 'output': 

600 for output_type in value: 

601 fd.write(format_aims_control_parameter(key, output_type, '%s')) 

602 elif key == 'vdw_correction_hirshfeld' and value: 

603 fd.write(format_aims_control_parameter(key, '', '%s')) 

604 elif isinstance(value, bool): 

605 fd.write( 

606 format_aims_control_parameter(key, str(value).lower(), '.%s.') 

607 ) 

608 elif isinstance(value, (tuple, list)): 

609 fd.write( 

610 format_aims_control_parameter( 

611 key, ' '.join([str(x) for x in value]), '%s' 

612 ) 

613 ) 

614 elif isinstance(value, str): 

615 fd.write(format_aims_control_parameter(key, value, '%s')) 

616 else: 

617 fd.write(format_aims_control_parameter(key, value, '%r')) 

618 

619 if cubes: 

620 cubes.write(fd) 

621 

622 fd.write(lim + '\n\n') 

623 

624 # Get the species directory 

625 species_dir = get_species_directory 

626 # dicts are ordered as of python 3.7 

627 species_array = np.array(list(dict.fromkeys(atoms.symbols))) 

628 # Grab the tier specification from the parameters. THis may either 

629 # be None, meaning the default should be used for all species, or a 

630 # list of integers/None values giving a specific basis set size 

631 # for each species in the calculation. 

632 tier = parameters.pop('tier', None) 

633 tier_array = np.full(len(species_array), tier) 

634 # Path to species files for FHI-aims. In this files are specifications 

635 # for the basis set sizes depending on which basis set tier is used. 

636 species_dir = get_species_directory(parameters.get('species_dir')) 

637 # Parse the species files for each species present in the calculation 

638 # according to the tier of each species. 

639 species_basis_dict = parse_species_path( 

640 species_array=species_array, 

641 tier_array=tier_array, 

642 species_dir=species_dir, 

643 ) 

644 # Write the basis functions to be included for each species in the 

645 # calculation into the control.in file (fd). 

646 write_species(fd, species_basis_dict, parameters) 

647 

648 

649def get_species_directory(species_dir=None): 

650 """Get the directory where the basis set information is stored 

651 

652 If the requested directory does not exist then raise an Error 

653 

654 Parameters 

655 ---------- 

656 species_dir: str 

657 Requested directory to find the basis set info from. E.g. 

658 `~/aims2022/FHIaims/species_defaults/defaults_2020/light`. 

659 

660 Returns 

661 ------- 

662 Path 

663 The Path to the requested or default species directory. 

664 

665 Raises 

666 ------ 

667 RuntimeError 

668 If both the requested directory and the default one is not defined 

669 or does not exit. 

670 """ 

671 if species_dir is None: 

672 species_dir = os.environ.get('AIMS_SPECIES_DIR') 

673 

674 if species_dir is None: 

675 raise RuntimeError( 

676 'Missing species directory! Use species_dir ' 

677 + 'parameter or set $AIMS_SPECIES_DIR environment variable.' 

678 ) 

679 

680 species_path = Path(species_dir) 

681 if not species_path.exists(): 

682 raise RuntimeError( 

683 f'The requested species_dir {species_dir} does not exist' 

684 ) 

685 

686 return species_path 

687 

688 

689def write_species(control_file_descriptor, species_basis_dict, parameters): 

690 """Write species for the calculation depending on basis set size. 

691 

692 The calculation should include certain basis set size function depending 

693 on the numerical settings (light, tight, really tight) and the basis set 

694 size (minimal, tier1, tier2, tier3, tier4). If the basis set size is not 

695 given then a 'standard' basis set size is used for each numerical setting. 

696 The species files are defined according to these standard basis set sizes 

697 for the numerical settings in the FHI-aims repository. 

698 

699 Note, for FHI-aims in ASE, we don't explicitly give the numerical setting. 

700 Instead we include the numerical setting in the species path: e.g. 

701 `~/aims2022/FHIaims/species_defaults/defaults_2020/light` this path has 

702 `light`, the numerical setting, as the last folder in the path. 

703 

704 Example - a basis function might be commented in the standard basis set size 

705 such as "# hydro 4 f 7.4" and this basis function should be 

706 uncommented for another basis set size such as tier4. 

707 

708 Args: 

709 control_file_descriptor: File descriptor for the control.in file into 

710 which we need to write relevant basis functions to be included for 

711 the calculation. 

712 species_basis_dict: Dictionary where keys as the species symbols and 

713 each value is a single string containing all the basis functions 

714 to be included in the caclculation. 

715 parameters: Calculation parameters as a dict. 

716 """ 

717 # Now for every species (key) in the species_basis_dict, save the 

718 # relevant basis functions (values) from the species_basis_dict, by 

719 # writing to the file handle (species_file_descriptor) given to this 

720 # function. 

721 for species_symbol, basis_set_text in species_basis_dict.items(): 

722 control_file_descriptor.write(basis_set_text) 

723 if parameters.get('plus_u') is not None: 

724 if species_symbol in parameters.plus_u: 

725 control_file_descriptor.write( 

726 f'plus_u {parameters.plus_u[species_symbol]} \n' 

727 ) 

728 

729 

730def parse_species_path(species_array, tier_array, species_dir): 

731 """Parse the species files for each species according to the tier given. 

732 

733 Args: 

734 species_array: An array of species/element symbols present in the unit 

735 cell (e.g. ['C', 'H'].) 

736 tier_array: An array of None/integer values which define which basis 

737 set size to use for each species/element in the calcualtion. 

738 species_dir: Directory containing FHI-aims species files. 

739 

740 Returns 

741 ------- 

742 Dictionary containing species as keys and the basis set specification 

743 for each species as text as the value for the key. 

744 """ 

745 if len(species_array) != len(tier_array): 

746 raise ValueError( 

747 f'The species array length: {len(species_array)}, ' 

748 f'is not the same as the tier_array length: {len(tier_array)}' 

749 ) 

750 

751 species_basis_dict = {} 

752 

753 for symbol, tier in zip(species_array, tier_array): 

754 path = species_dir / f'{atomic_numbers[symbol]:02}_{symbol}_default' 

755 # Open the species file: 

756 with open(path, encoding='utf8') as species_file_handle: 

757 # Read the species file into a string. 

758 species_file_str = species_file_handle.read() 

759 species_basis_dict[symbol] = manipulate_tiers( 

760 species_file_str, tier 

761 ) 

762 return species_basis_dict 

763 

764 

765def manipulate_tiers(species_string: str, tier: None | int = 1): 

766 """Adds basis set functions based on the tier value. 

767 

768 This function takes in the species file as a string, it then searches 

769 for relevant basis functions based on the tier value to include in a new 

770 string that is returned. 

771 

772 Args: 

773 species_string: species file (default) for a given numerical setting 

774 (light, tight, really tight) given as a string. 

775 tier: The basis set size. This will dictate which basis set functions 

776 are included in the returned string. 

777 

778 Returns 

779 ------- 

780 Basis set functions defined by the tier as a string. 

781 """ 

782 if tier is None: # Then we use the default species file untouched. 

783 return species_string 

784 tier_pattern = r'(# \".* tier\" .*|# +Further.*)' 

785 top, *tiers = re.split(tier_pattern, species_string) 

786 tier_comments = tiers[::2] 

787 tier_basis = tiers[1::2] 

788 assert len(tier_comments) == len(tier_basis), ( 

789 'Something wrong with splitting' 

790 ) 

791 n_tiers = len(tier_comments) 

792 assert tier <= n_tiers, f'Only {n_tiers} tiers available, you choose {tier}' 

793 string_new = top 

794 for i, (c, b) in enumerate(zip(tier_comments, tier_basis)): 

795 b = re.sub(r'\n( *for_aux| *hydro| *ionic| *confined)', r'\n#\g<1>', b) 

796 if i < tier: 

797 b = re.sub( 

798 r'\n#( *for_aux| *hydro| *ionic| *confined)', r'\n\g<1>', b 

799 ) 

800 string_new += c + b 

801 return string_new 

802 

803 

804# Read aims.out files 

805scalar_property_to_line_key = { 

806 'free_energy': ['| Electronic free energy'], 

807 'number_of_iterations': ['| Number of self-consistency cycles'], 

808 'magnetic_moment': ['N_up - N_down'], 

809 'n_atoms': ['| Number of atoms'], 

810 'n_bands': [ 

811 'Number of Kohn-Sham states', 

812 'Reducing total number of Kohn-Sham states', 

813 'Reducing total number of Kohn-Sham states', 

814 ], 

815 'n_electrons': ['The structure contains'], 

816 'n_kpts': ['| Number of k-points'], 

817 'n_spins': ['| Number of spin channels'], 

818 'electronic_temp': ['Occupation type:'], 

819 'fermi_energy': ['| Chemical potential (Fermi level)'], 

820} 

821 

822 

823class AimsOutChunk: 

824 """Base class for AimsOutChunks""" 

825 

826 def __init__(self, lines): 

827 """Constructor 

828 

829 Parameters 

830 ---------- 

831 lines: list of str 

832 The set of lines from the output file the encompasses either 

833 a single structure within a trajectory or 

834 general information about the calculation (header) 

835 """ 

836 self.lines = lines 

837 

838 def reverse_search_for(self, keys, line_start=0): 

839 """Find the last time one of the keys appears in self.lines 

840 

841 Parameters 

842 ---------- 

843 keys: list of str 

844 The key strings to search for in self.lines 

845 line_start: int 

846 The lowest index to search for in self.lines 

847 

848 Returns 

849 ------- 

850 int 

851 The last time one of the keys appears in self.lines 

852 """ 

853 for ll, line in enumerate(self.lines[line_start:][::-1]): 

854 if any(key in line for key in keys): 

855 return len(self.lines) - ll - 1 

856 

857 return LINE_NOT_FOUND 

858 

859 def search_for_all(self, key, line_start=0, line_end=-1): 

860 """Find the all times the key appears in self.lines 

861 

862 Parameters 

863 ---------- 

864 key: str 

865 The key string to search for in self.lines 

866 line_start: int 

867 The first line to start the search from 

868 line_end: int 

869 The last line to end the search at 

870 

871 Returns 

872 ------- 

873 list of ints 

874 All times the key appears in the lines 

875 """ 

876 line_index = [] 

877 for ll, line in enumerate(self.lines[line_start:line_end]): 

878 if key in line: 

879 line_index.append(ll + line_start) 

880 return line_index 

881 

882 def parse_scalar(self, property): 

883 """Parse a scalar property from the chunk 

884 

885 Parameters 

886 ---------- 

887 property: str 

888 The property key to parse 

889 

890 Returns 

891 ------- 

892 float 

893 The scalar value of the property 

894 """ 

895 line_start = self.reverse_search_for( 

896 scalar_property_to_line_key[property] 

897 ) 

898 

899 if line_start == LINE_NOT_FOUND: 

900 return None 

901 

902 line = self.lines[line_start] 

903 return float(line.split(':')[-1].strip().split()[0]) 

904 

905 

906class AimsOutHeaderChunk(AimsOutChunk): 

907 """The header of the aims.out file containint general information""" 

908 

909 def __init__(self, lines): 

910 """Constructor 

911 

912 Parameters 

913 ---------- 

914 lines: list of str 

915 The lines inside the aims.out header 

916 """ 

917 super().__init__(lines) 

918 

919 @cached_property 

920 def constraints(self): 

921 """Parse the constraints from the aims.out file 

922 

923 Constraints for the lattice vectors are not supported. 

924 """ 

925 

926 line_inds = self.search_for_all('Found relaxation constraint for atom') 

927 if len(line_inds) == 0: 

928 return [] 

929 

930 fix = [] 

931 fix_cart = [] 

932 for ll in line_inds: 

933 line = self.lines[ll] 

934 xyz = [0, 0, 0] 

935 ind = int(line.split()[5][:-1]) - 1 

936 if 'All coordinates fixed' in line: 

937 if ind not in fix: 

938 fix.append(ind) 

939 if 'coordinate fixed' in line: 

940 coord = line.split()[6] 

941 if coord == 'x': 

942 xyz[0] = 1 

943 elif coord == 'y': 

944 xyz[1] = 1 

945 elif coord == 'z': 

946 xyz[2] = 1 

947 keep = True 

948 for n, c in enumerate(fix_cart): 

949 if ind == c.index: 

950 keep = False 

951 break 

952 if keep: 

953 fix_cart.append(FixCartesian(ind, xyz)) 

954 else: 

955 fix_cart[n].mask[xyz.index(1)] = 1 

956 if len(fix) > 0: 

957 fix_cart.append(FixAtoms(indices=fix)) 

958 

959 return fix_cart 

960 

961 @cached_property 

962 def initial_cell(self): 

963 """Parse the initial cell from the aims.out file""" 

964 line_start = self.reverse_search_for(['| Unit cell:']) 

965 if line_start == LINE_NOT_FOUND: 

966 return None 

967 

968 return [ 

969 [float(inp) for inp in line.split()[-3:]] 

970 for line in self.lines[line_start + 1 : line_start + 4] 

971 ] 

972 

973 @cached_property 

974 def initial_atoms(self): 

975 """Create an atoms object for the initial geometry.in structure 

976 from the aims.out file""" 

977 line_start = self.reverse_search_for(['Atomic structure:']) 

978 if line_start == LINE_NOT_FOUND: 

979 raise AimsParseError( 

980 'No information about the structure in the chunk.' 

981 ) 

982 

983 line_start += 2 

984 

985 cell = self.initial_cell 

986 positions = np.zeros((self.n_atoms, 3)) 

987 symbols = [''] * self.n_atoms 

988 for ll, line in enumerate( 

989 self.lines[line_start : line_start + self.n_atoms] 

990 ): 

991 inp = line.split() 

992 positions[ll, :] = [float(pos) for pos in inp[4:7]] 

993 symbols[ll] = inp[3] 

994 

995 atoms = Atoms(symbols=symbols, positions=positions) 

996 

997 if cell: 

998 atoms.set_cell(cell) 

999 atoms.set_pbc([True, True, True]) 

1000 atoms.set_constraint(self.constraints) 

1001 

1002 return atoms 

1003 

1004 @cached_property 

1005 def is_md(self): 

1006 """Determine if calculation is a molecular dynamics calculation""" 

1007 return LINE_NOT_FOUND != self.reverse_search_for( 

1008 ['Complete information for previous time-step:'] 

1009 ) 

1010 

1011 @cached_property 

1012 def is_relaxation(self): 

1013 """Determine if the calculation is a geometry optimization or not""" 

1014 return LINE_NOT_FOUND != self.reverse_search_for( 

1015 ['Geometry relaxation:'] 

1016 ) 

1017 

1018 @cached_property 

1019 def _k_points(self): 

1020 """Get the list of k-points used in the calculation""" 

1021 n_kpts = self.parse_scalar('n_kpts') 

1022 if n_kpts is None: 

1023 return { 

1024 'k_points': None, 

1025 'k_point_weights': None, 

1026 } 

1027 n_kpts = int(n_kpts) 

1028 

1029 line_start = self.reverse_search_for(['| K-points in task']) 

1030 line_end = self.reverse_search_for(['| k-point:']) 

1031 if ( 

1032 (line_start == LINE_NOT_FOUND) 

1033 or (line_end == LINE_NOT_FOUND) 

1034 or (line_end - line_start != n_kpts) 

1035 ): 

1036 return { 

1037 'k_points': None, 

1038 'k_point_weights': None, 

1039 } 

1040 

1041 k_points = np.zeros((n_kpts, 3)) 

1042 k_point_weights = np.zeros(n_kpts) 

1043 for kk, line in enumerate(self.lines[line_start + 1 : line_end + 1]): 

1044 k_points[kk] = [float(inp) for inp in line.split()[4:7]] 

1045 k_point_weights[kk] = float(line.split()[-1]) 

1046 

1047 return { 

1048 'k_points': k_points, 

1049 'k_point_weights': k_point_weights, 

1050 } 

1051 

1052 @cached_property 

1053 def n_atoms(self): 

1054 """The number of atoms for the material""" 

1055 n_atoms = self.parse_scalar('n_atoms') 

1056 if n_atoms is None: 

1057 raise AimsParseError( 

1058 'No information about the number of atoms in the header.' 

1059 ) 

1060 return int(n_atoms) 

1061 

1062 @cached_property 

1063 def n_bands(self): 

1064 """The number of Kohn-Sham states for the chunk""" 

1065 line_start = self.reverse_search_for( 

1066 scalar_property_to_line_key['n_bands'] 

1067 ) 

1068 

1069 if line_start == LINE_NOT_FOUND: 

1070 raise AimsParseError( 

1071 'No information about the number of Kohn-Sham states ' 

1072 'in the header.' 

1073 ) 

1074 

1075 line = self.lines[line_start] 

1076 if '| Number of Kohn-Sham states' in line: 

1077 return int(line.split(':')[-1].strip().split()[0]) 

1078 

1079 return int(line.split()[-1].strip()[:-1]) 

1080 

1081 @cached_property 

1082 def n_electrons(self): 

1083 """The number of electrons for the chunk""" 

1084 line_start = self.reverse_search_for( 

1085 scalar_property_to_line_key['n_electrons'] 

1086 ) 

1087 

1088 if line_start == LINE_NOT_FOUND: 

1089 raise AimsParseError( 

1090 'No information about the number of electrons in the header.' 

1091 ) 

1092 

1093 line = self.lines[line_start] 

1094 return int(float(line.split()[-2])) 

1095 

1096 @cached_property 

1097 def n_k_points(self): 

1098 """The number of k_ppoints for the calculation""" 

1099 n_kpts = self.parse_scalar('n_kpts') 

1100 if n_kpts is None: 

1101 return None 

1102 

1103 return int(n_kpts) 

1104 

1105 @cached_property 

1106 def n_spins(self): 

1107 """The number of spin channels for the chunk""" 

1108 n_spins = self.parse_scalar('n_spins') 

1109 if n_spins is None: 

1110 raise AimsParseError( 

1111 'No information about the number of spin ' 

1112 'channels in the header.' 

1113 ) 

1114 return int(n_spins) 

1115 

1116 @cached_property 

1117 def electronic_temperature(self): 

1118 """The electronic temperature for the chunk""" 

1119 line_start = self.reverse_search_for( 

1120 scalar_property_to_line_key['electronic_temp'] 

1121 ) 

1122 if line_start == LINE_NOT_FOUND: 

1123 return 0.10 

1124 

1125 line = self.lines[line_start] 

1126 return float(line.split('=')[-1].strip().split()[0]) 

1127 

1128 @property 

1129 def k_points(self): 

1130 """All k-points listed in the calculation""" 

1131 return self._k_points['k_points'] 

1132 

1133 @property 

1134 def k_point_weights(self): 

1135 """The k-point weights for the calculation""" 

1136 return self._k_points['k_point_weights'] 

1137 

1138 @cached_property 

1139 def header_summary(self): 

1140 """Dictionary summarizing the information inside the header""" 

1141 return { 

1142 'initial_atoms': self.initial_atoms, 

1143 'initial_cell': self.initial_cell, 

1144 'constraints': self.constraints, 

1145 'is_relaxation': self.is_relaxation, 

1146 'is_md': self.is_md, 

1147 'n_atoms': self.n_atoms, 

1148 'n_bands': self.n_bands, 

1149 'n_electrons': self.n_electrons, 

1150 'n_spins': self.n_spins, 

1151 'electronic_temperature': self.electronic_temperature, 

1152 'n_k_points': self.n_k_points, 

1153 'k_points': self.k_points, 

1154 'k_point_weights': self.k_point_weights, 

1155 } 

1156 

1157 

1158class AimsOutCalcChunk(AimsOutChunk): 

1159 """A part of the aims.out file correponding to a single structure""" 

1160 

1161 def __init__(self, lines, header): 

1162 """Constructor 

1163 

1164 Parameters 

1165 ---------- 

1166 lines: list of str 

1167 The lines used for the structure 

1168 header: dict 

1169 A summary of the relevant information from the aims.out header 

1170 """ 

1171 super().__init__(lines) 

1172 self._header = header.header_summary 

1173 

1174 @cached_property 

1175 def _atoms(self): 

1176 """Create an atoms object for the subsequent structures 

1177 calculated in the aims.out file""" 

1178 start_keys = [ 

1179 'Atomic structure (and velocities) as used in the preceding ' 

1180 'time step', 

1181 'Updated atomic structure', 

1182 'Atomic structure that was used in the preceding time step of ' 

1183 'the wrapper', 

1184 ] 

1185 line_start = self.reverse_search_for(start_keys) 

1186 if line_start == LINE_NOT_FOUND: 

1187 return self.initial_atoms 

1188 

1189 line_start += 1 

1190 

1191 line_end = self.reverse_search_for( 

1192 [ 

1193 'Next atomic structure:', 

1194 'Writing the current geometry to file "geometry.in.next_step"', 

1195 ], 

1196 line_start, 

1197 ) 

1198 if line_end == LINE_NOT_FOUND: 

1199 line_end = len(self.lines) 

1200 

1201 cell = [] 

1202 velocities = [] 

1203 atoms = Atoms() 

1204 for line in self.lines[line_start:line_end]: 

1205 if 'lattice_vector ' in line: 

1206 cell.append([float(inp) for inp in line.split()[1:]]) 

1207 elif 'atom ' in line: 

1208 line_split = line.split() 

1209 atoms.append( 

1210 Atom( 

1211 line_split[4], 

1212 tuple(float(inp) for inp in line_split[1:4]), 

1213 ) 

1214 ) 

1215 elif 'velocity ' in line: 

1216 velocities.append([float(inp) for inp in line.split()[1:]]) 

1217 

1218 assert len(atoms) == self.n_atoms 

1219 assert (len(velocities) == self.n_atoms) or (len(velocities) == 0) 

1220 if len(cell) == 3: 

1221 atoms.set_cell(np.array(cell)) 

1222 atoms.set_pbc([True, True, True]) 

1223 elif len(cell) != 0: 

1224 raise AimsParseError( 

1225 'Parsed geometry has incorrect number of lattice vectors.' 

1226 ) 

1227 

1228 if len(velocities) > 0: 

1229 atoms.set_velocities(np.array(velocities)) 

1230 atoms.set_constraint(self.constraints) 

1231 

1232 return atoms 

1233 

1234 @cached_property 

1235 def forces(self): 

1236 """Parse the forces from the aims.out file""" 

1237 line_start = self.reverse_search_for(['Total atomic forces']) 

1238 if line_start == LINE_NOT_FOUND: 

1239 return None 

1240 

1241 line_start += 1 

1242 

1243 return np.array( 

1244 [ 

1245 [float(inp) for inp in line.split()[-3:]] 

1246 for line in self.lines[line_start : line_start + self.n_atoms] 

1247 ] 

1248 ) 

1249 

1250 @cached_property 

1251 def stresses(self): 

1252 """Parse the stresses from the aims.out file""" 

1253 line_start = self.reverse_search_for( 

1254 ['Per atom stress (eV) used for heat flux calculation'] 

1255 ) 

1256 if line_start == LINE_NOT_FOUND: 

1257 return None 

1258 line_start += 3 

1259 stresses = [] 

1260 for line in self.lines[line_start : line_start + self.n_atoms]: 

1261 xx, yy, zz, xy, xz, yz = (float(d) for d in line.split()[2:8]) 

1262 stresses.append([xx, yy, zz, yz, xz, xy]) 

1263 

1264 return np.array(stresses) 

1265 

1266 @cached_property 

1267 def stress(self): 

1268 """Parse the stress from the aims.out file""" 

1269 from ase.stress import full_3x3_to_voigt_6_stress 

1270 

1271 line_start = self.reverse_search_for( 

1272 [ 

1273 'Analytical stress tensor - Symmetrized', 

1274 'Numerical stress tensor', 

1275 ] 

1276 ) # Offest to relevant lines 

1277 if line_start == LINE_NOT_FOUND: 

1278 return None 

1279 

1280 stress = [ 

1281 [float(inp) for inp in line.split()[2:5]] 

1282 for line in self.lines[line_start + 5 : line_start + 8] 

1283 ] 

1284 return full_3x3_to_voigt_6_stress(stress) 

1285 

1286 @cached_property 

1287 def is_metallic(self): 

1288 """Checks the outputfile to see if the chunk corresponds 

1289 to a metallic system""" 

1290 line_start = self.reverse_search_for( 

1291 [ 

1292 'material is metallic within the approximate finite ' 

1293 'broadening function (occupation_type)' 

1294 ] 

1295 ) 

1296 return line_start != LINE_NOT_FOUND 

1297 

1298 @cached_property 

1299 def total_energy(self): 

1300 """Parse the energy from the aims.out file""" 

1301 if np.all(self._atoms.pbc) and self.is_metallic: 

1302 line_ind = self.reverse_search_for(['Total energy corrected']) 

1303 else: 

1304 line_ind = self.reverse_search_for(['Total energy uncorrected']) 

1305 if line_ind == LINE_NOT_FOUND: 

1306 raise AimsParseError('No energy is associated with the structure.') 

1307 

1308 return float(self.lines[line_ind].split()[5]) 

1309 

1310 @cached_property 

1311 def dipole(self): 

1312 """Parse the electric dipole moment from the aims.out file.""" 

1313 line_start = self.reverse_search_for(['Total dipole moment [eAng]']) 

1314 if line_start == LINE_NOT_FOUND: 

1315 return None 

1316 

1317 line = self.lines[line_start] 

1318 return np.array([float(inp) for inp in line.split()[6:9]]) 

1319 

1320 @cached_property 

1321 def dielectric_tensor(self): 

1322 """Parse the dielectric tensor from the aims.out file""" 

1323 line_start = self.reverse_search_for( 

1324 [ 

1325 'DFPT for dielectric_constant:--->', 

1326 'PARSE DFPT_dielectric_tensor', 

1327 ], 

1328 ) 

1329 if line_start == LINE_NOT_FOUND: 

1330 return None 

1331 

1332 # we should find the tensor in the next three lines: 

1333 lines = self.lines[line_start + 1 : line_start + 4] 

1334 

1335 # make ndarray and return 

1336 return np.array([np.fromstring(line, sep=' ') for line in lines]) 

1337 

1338 @cached_property 

1339 def polarization(self): 

1340 """Parse the polarization vector from the aims.out file""" 

1341 line_start = self.reverse_search_for(['| Cartesian Polarization']) 

1342 if line_start == LINE_NOT_FOUND: 

1343 return None 

1344 line = self.lines[line_start] 

1345 return np.array([float(s) for s in line.split()[-3:]]) 

1346 

1347 @cached_property 

1348 def _hirshfeld(self): 

1349 """Parse the Hirshfled charges volumes, and dipole moments from the 

1350 ouput""" 

1351 line_start = self.reverse_search_for( 

1352 ['Performing Hirshfeld analysis of fragment charges and moments.'] 

1353 ) 

1354 if line_start == LINE_NOT_FOUND: 

1355 return { 

1356 'charges': None, 

1357 'volumes': None, 

1358 'atomic_dipoles': None, 

1359 'dipole': None, 

1360 } 

1361 

1362 line_inds = self.search_for_all('Hirshfeld charge', line_start, -1) 

1363 hirshfeld_charges = np.array( 

1364 [float(self.lines[ind].split(':')[1]) for ind in line_inds] 

1365 ) 

1366 

1367 line_inds = self.search_for_all('Hirshfeld volume', line_start, -1) 

1368 hirshfeld_volumes = np.array( 

1369 [float(self.lines[ind].split(':')[1]) for ind in line_inds] 

1370 ) 

1371 

1372 line_inds = self.search_for_all( 

1373 'Hirshfeld dipole vector', line_start, -1 

1374 ) 

1375 hirshfeld_atomic_dipoles = np.array( 

1376 [ 

1377 [float(inp) for inp in self.lines[ind].split(':')[1].split()] 

1378 for ind in line_inds 

1379 ] 

1380 ) 

1381 

1382 if not np.any(self._atoms.pbc): 

1383 positions = self._atoms.get_positions() 

1384 hirshfeld_dipole = np.sum( 

1385 hirshfeld_charges.reshape((-1, 1)) * positions, 

1386 axis=1, 

1387 ) 

1388 else: 

1389 hirshfeld_dipole = None 

1390 return { 

1391 'charges': hirshfeld_charges, 

1392 'volumes': hirshfeld_volumes, 

1393 'atomic_dipoles': hirshfeld_atomic_dipoles, 

1394 'dipole': hirshfeld_dipole, 

1395 } 

1396 

1397 @cached_property 

1398 def _eigenvalues(self): 

1399 """Parse the eigenvalues and occupancies of the system. If eigenvalue 

1400 for a particular k-point is not present in the output file 

1401 then set it to np.nan 

1402 """ 

1403 

1404 line_start = self.reverse_search_for(['Writing Kohn-Sham eigenvalues.']) 

1405 if line_start == LINE_NOT_FOUND: 

1406 return {'eigenvalues': None, 'occupancies': None} 

1407 

1408 line_end_1 = self.reverse_search_for( 

1409 ['Self-consistency cycle converged.'], line_start 

1410 ) 

1411 line_end_2 = self.reverse_search_for( 

1412 [ 

1413 'What follows are estimated values for band gap, ' 

1414 'HOMO, LUMO, etc.', 

1415 'Current spin moment of the entire structure :', 

1416 'Highest occupied state (VBM)', 

1417 ], 

1418 line_start, 

1419 ) 

1420 if line_end_1 == LINE_NOT_FOUND: 

1421 line_end = line_end_2 

1422 elif line_end_2 == LINE_NOT_FOUND: 

1423 line_end = line_end_1 

1424 else: 

1425 line_end = min(line_end_1, line_end_2) 

1426 

1427 n_kpts = self.n_k_points if np.all(self._atoms.pbc) else 1 

1428 if n_kpts is None: 

1429 return {'eigenvalues': None, 'occupancies': None} 

1430 

1431 eigenvalues = np.full((n_kpts, self.n_bands, self.n_spins), np.nan) 

1432 occupancies = np.full((n_kpts, self.n_bands, self.n_spins), np.nan) 

1433 

1434 occupation_block_start = self.search_for_all( 

1435 'State Occupation Eigenvalue [Ha] Eigenvalue [eV]', 

1436 line_start, 

1437 line_end, 

1438 ) 

1439 kpt_def = self.search_for_all('K-point: ', line_start, line_end) 

1440 

1441 if len(kpt_def) > 0: 

1442 kpt_inds = [int(self.lines[ll].split()[1]) - 1 for ll in kpt_def] 

1443 elif (self.n_k_points is None) or (self.n_k_points == 1): 

1444 kpt_inds = [0] * self.n_spins 

1445 else: 

1446 raise ParseError('Cannot find k-point definitions') 

1447 

1448 assert len(kpt_inds) == len(occupation_block_start) 

1449 spins = [0] * len(occupation_block_start) 

1450 

1451 if self.n_spins == 2: 

1452 spin_def = self.search_for_all('Spin-', line_start, line_end) 

1453 assert len(spin_def) == len(occupation_block_start) 

1454 

1455 spins = [ 

1456 int('Spin-down eigenvalues:' in self.lines[ll]) 

1457 for ll in spin_def 

1458 ] 

1459 

1460 for occ_start, kpt_ind, spin in zip( 

1461 occupation_block_start, kpt_inds, spins 

1462 ): 

1463 for ll, line in enumerate( 

1464 self.lines[occ_start + 1 : occ_start + self.n_bands + 1] 

1465 ): 

1466 if '***' in line: 

1467 warn_msg = f'The {ll + 1}th eigenvalue for the ' 

1468 '{kpt_ind+1}th k-point and {spin}th channels could ' 

1469 'not be read (likely too large to be printed ' 

1470 'in the output file)' 

1471 warnings.warn(warn_msg) 

1472 continue 

1473 split_line = line.split() 

1474 eigenvalues[kpt_ind, ll, spin] = float(split_line[3]) 

1475 occupancies[kpt_ind, ll, spin] = float(split_line[1]) 

1476 return {'eigenvalues': eigenvalues, 'occupancies': occupancies} 

1477 

1478 @cached_property 

1479 def atoms(self): 

1480 """Convert AimsOutChunk to Atoms object and add all non-standard 

1481 outputs to atoms.info""" 

1482 atoms = self._atoms 

1483 

1484 atoms.calc = SinglePointDFTCalculator( 

1485 atoms, 

1486 energy=self.free_energy, 

1487 free_energy=self.free_energy, 

1488 forces=self.forces, 

1489 stress=self.stress, 

1490 stresses=self.stresses, 

1491 magmom=self.magmom, 

1492 dipole=self.dipole, 

1493 dielectric_tensor=self.dielectric_tensor, 

1494 polarization=self.polarization, 

1495 ) 

1496 return atoms 

1497 

1498 @property 

1499 def results(self): 

1500 """Convert an AimsOutChunk to a Results Dictionary""" 

1501 results = { 

1502 'energy': self.free_energy, 

1503 'free_energy': self.free_energy, 

1504 'total_energy': self.total_energy, 

1505 'forces': self.forces, 

1506 'stress': self.stress, 

1507 'stresses': self.stresses, 

1508 'magmom': self.magmom, 

1509 'dipole': self.dipole, 

1510 'fermi_energy': self.E_f, 

1511 'n_iter': self.n_iter, 

1512 'hirshfeld_charges': self.hirshfeld_charges, 

1513 'hirshfeld_dipole': self.hirshfeld_dipole, 

1514 'hirshfeld_volumes': self.hirshfeld_volumes, 

1515 'hirshfeld_atomic_dipoles': self.hirshfeld_atomic_dipoles, 

1516 'eigenvalues': self.eigenvalues, 

1517 'occupancies': self.occupancies, 

1518 'dielectric_tensor': self.dielectric_tensor, 

1519 'polarization': self.polarization, 

1520 } 

1521 

1522 return { 

1523 key: value for key, value in results.items() if value is not None 

1524 } 

1525 

1526 @property 

1527 def initial_atoms(self): 

1528 """The initial structure defined in the geoemtry.in file""" 

1529 return self._header['initial_atoms'] 

1530 

1531 @property 

1532 def initial_cell(self): 

1533 """The initial lattice vectors defined in the geoemtry.in file""" 

1534 return self._header['initial_cell'] 

1535 

1536 @property 

1537 def constraints(self): 

1538 """The relaxation constraints for the calculation""" 

1539 return self._header['constraints'] 

1540 

1541 @property 

1542 def n_atoms(self): 

1543 """The number of atoms for the material""" 

1544 return self._header['n_atoms'] 

1545 

1546 @property 

1547 def n_bands(self): 

1548 """The number of Kohn-Sham states for the chunk""" 

1549 return self._header['n_bands'] 

1550 

1551 @property 

1552 def n_electrons(self): 

1553 """The number of electrons for the chunk""" 

1554 return self._header['n_electrons'] 

1555 

1556 @property 

1557 def n_spins(self): 

1558 """The number of spin channels for the chunk""" 

1559 return self._header['n_spins'] 

1560 

1561 @property 

1562 def electronic_temperature(self): 

1563 """The electronic temperature for the chunk""" 

1564 return self._header['electronic_temperature'] 

1565 

1566 @property 

1567 def n_k_points(self): 

1568 """The number of electrons for the chunk""" 

1569 return self._header['n_k_points'] 

1570 

1571 @property 

1572 def k_points(self): 

1573 """The number of spin channels for the chunk""" 

1574 return self._header['k_points'] 

1575 

1576 @property 

1577 def k_point_weights(self): 

1578 """k_point_weights electronic temperature for the chunk""" 

1579 return self._header['k_point_weights'] 

1580 

1581 @cached_property 

1582 def free_energy(self): 

1583 """The free energy for the chunk""" 

1584 return self.parse_scalar('free_energy') 

1585 

1586 @cached_property 

1587 def n_iter(self): 

1588 """The number of SCF iterations needed to converge the SCF cycle for 

1589 the chunk""" 

1590 return self.parse_scalar('number_of_iterations') 

1591 

1592 @cached_property 

1593 def magmom(self): 

1594 """The magnetic moment for the chunk""" 

1595 return self.parse_scalar('magnetic_moment') 

1596 

1597 @cached_property 

1598 def E_f(self): 

1599 """The Fermi energy for the chunk""" 

1600 return self.parse_scalar('fermi_energy') 

1601 

1602 @cached_property 

1603 def converged(self): 

1604 """True if the chunk is a fully converged final structure""" 

1605 return (len(self.lines) > 0) and ('Have a nice day.' in self.lines[-5:]) 

1606 

1607 @property 

1608 def hirshfeld_charges(self): 

1609 """The Hirshfeld charges for the chunk""" 

1610 return self._hirshfeld['charges'] 

1611 

1612 @property 

1613 def hirshfeld_atomic_dipoles(self): 

1614 """The Hirshfeld atomic dipole moments for the chunk""" 

1615 return self._hirshfeld['atomic_dipoles'] 

1616 

1617 @property 

1618 def hirshfeld_volumes(self): 

1619 """The Hirshfeld volume for the chunk""" 

1620 return self._hirshfeld['volumes'] 

1621 

1622 @property 

1623 def hirshfeld_dipole(self): 

1624 """The Hirshfeld systematic dipole moment for the chunk""" 

1625 if not np.any(self._atoms.pbc): 

1626 return self._hirshfeld['dipole'] 

1627 

1628 return None 

1629 

1630 @property 

1631 def eigenvalues(self): 

1632 """All outputted eigenvalues for the system""" 

1633 return self._eigenvalues['eigenvalues'] 

1634 

1635 @property 

1636 def occupancies(self): 

1637 """All outputted occupancies for the system""" 

1638 return self._eigenvalues['occupancies'] 

1639 

1640 

1641def get_header_chunk(fd): 

1642 """Returns the header information from the aims.out file""" 

1643 header = [] 

1644 line = '' 

1645 

1646 # Stop the header once the first SCF cycle begins 

1647 while ( 

1648 'Convergence: q app. | density | eigen (eV) | Etot (eV)' 

1649 not in line 

1650 and 'Convergence: q app. | density, spin | eigen (eV) |' 

1651 not in line 

1652 and 'Begin self-consistency iteration #' not in line 

1653 ): 

1654 try: 

1655 line = next(fd).strip() # Raises StopIteration on empty file 

1656 except StopIteration: 

1657 raise ParseError( 

1658 'No SCF steps present, calculation failed at setup.' 

1659 ) 

1660 

1661 header.append(line) 

1662 return AimsOutHeaderChunk(header) 

1663 

1664 

1665def get_aims_out_chunks(fd, header_chunk): 

1666 """Yield unprocessed chunks (header, lines) for each AimsOutChunk image.""" 

1667 try: 

1668 line = next(fd).strip() # Raises StopIteration on empty file 

1669 except StopIteration: 

1670 return 

1671 

1672 # If the calculation is relaxation the updated structural information 

1673 # occurs before the re-initialization 

1674 if header_chunk.is_relaxation: 

1675 chunk_end_line = ( 

1676 'Geometry optimization: Attempting to predict improved coordinates.' 

1677 ) 

1678 else: 

1679 chunk_end_line = 'Begin self-consistency loop: Re-initialization' 

1680 

1681 # If SCF is not converged then do not treat the next chunk_end_line as a 

1682 # new chunk until after the SCF is re-initialized 

1683 ignore_chunk_end_line = False 

1684 while True: 

1685 try: 

1686 line = next(fd).strip() # Raises StopIteration on empty file 

1687 except StopIteration: 

1688 break 

1689 

1690 lines = [] 

1691 while chunk_end_line not in line or ignore_chunk_end_line: 

1692 lines.append(line) 

1693 # If SCF cycle not converged or numerical stresses are requested, 

1694 # don't end chunk on next Re-initialization 

1695 patterns = [ 

1696 ( 

1697 'Self-consistency cycle not yet converged -' 

1698 ' restarting mixer to attempt better convergence.' 

1699 ), 

1700 ( 

1701 'Components of the stress tensor (for mathematical ' 

1702 'background see comments in numerical_stress.f90).' 

1703 ), 

1704 'Calculation of numerical stress completed', 

1705 ] 

1706 if any(pattern in line for pattern in patterns): 

1707 ignore_chunk_end_line = True 

1708 elif 'Begin self-consistency loop: Re-initialization' in line: 

1709 ignore_chunk_end_line = False 

1710 

1711 try: 

1712 line = next(fd).strip() 

1713 except StopIteration: 

1714 break 

1715 

1716 yield AimsOutCalcChunk(lines, header_chunk) 

1717 

1718 

1719def check_convergence(chunks, non_convergence_ok=False): 

1720 """Check if the aims output file is for a converged calculation 

1721 

1722 Parameters 

1723 ---------- 

1724 chunks: list of AimsOutChunks 

1725 The list of chunks for the aims calculations 

1726 non_convergence_ok: bool 

1727 True if it is okay for the calculation to not be converged 

1728 

1729 Returns 

1730 ------- 

1731 bool 

1732 True if the calculation is converged 

1733 """ 

1734 if not non_convergence_ok and not chunks[-1].converged: 

1735 raise ParseError('The calculation did not complete successfully') 

1736 return True 

1737 

1738 

1739@deprecated( 

1740 message=( 

1741 'FHI-aims IO is moving to the ase-io-aims plugin.' 

1742 ' To test, install the plugin (`pip install ase-io-aims`)' 

1743 ' and use `read(..., format=aims-output-plugin)`.' 

1744 ' This functionality will be removed at a later date and' 

1745 ' `format=aims` will be used for new functionality.' 

1746 ), 

1747 category=FutureWarning, 

1748) 

1749@reader 

1750def read_aims_output(fd, index=-1, non_convergence_ok=False): 

1751 """Import FHI-aims output files with all data available, i.e. 

1752 relaxations, MD information, force information etc etc etc.""" 

1753 header_chunk = get_header_chunk(fd) 

1754 chunks = list(get_aims_out_chunks(fd, header_chunk)) 

1755 check_convergence(chunks, non_convergence_ok) 

1756 

1757 # Relaxations have an additional footer chunk due to how it is split 

1758 if header_chunk.is_relaxation: 

1759 images = [chunk.atoms for chunk in chunks[:-1]] 

1760 else: 

1761 images = [chunk.atoms for chunk in chunks] 

1762 return images[index] 

1763 

1764 

1765@deprecated( 

1766 message=( 

1767 'FHI-aims IO is moving to the ase-io-aims plugin.' 

1768 ' To test, install the plugin (`pip install ase-io-aims`)' 

1769 ' and use the function supported there.' 

1770 ' This functionality will be removed at a later date and' 

1771 ' `format=aims` will be used for new functionality.' 

1772 ), 

1773 category=FutureWarning, 

1774) 

1775@reader 

1776def read_aims_results(fd, index=-1, non_convergence_ok=False): 

1777 """Import FHI-aims output files and summarize all relevant information 

1778 into a dictionary""" 

1779 header_chunk = get_header_chunk(fd) 

1780 chunks = list(get_aims_out_chunks(fd, header_chunk)) 

1781 check_convergence(chunks, non_convergence_ok) 

1782 

1783 # Relaxations have an additional footer chunk due to how it is split 

1784 if header_chunk.is_relaxation and (index == -1): 

1785 return chunks[-2].results 

1786 

1787 return chunks[index].results