Coverage for ase/io/espresso.py: 84.13%

813 statements  

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

1"""Reads Quantum ESPRESSO files. 

2 

3Read multiple structures and results from pw.x output files. Read 

4structures from pw.x input files. 

5 

6Built for PWSCF v.5.3.0 but should work with earlier and later versions. 

7Can deal with most major functionality, with the notable exception of ibrav, 

8for which we only support ibrav == 0 and force CELL_PARAMETERS to be provided 

9explicitly. 

10 

11Units are converted using CODATA 2006, as used internally by Quantum 

12ESPRESSO. 

13""" 

14 

15import operator as op 

16import re 

17import warnings 

18from collections import defaultdict 

19 

20import numpy as np 

21 

22from ase.atoms import Atoms 

23from ase.calculators.calculator import kpts2ndarray, kpts2sizeandoffsets 

24from ase.calculators.singlepoint import ( 

25 SinglePointDFTCalculator, 

26 SinglePointKPoint, 

27) 

28from ase.constraints import FixAtoms, FixCartesian 

29from ase.data import chemical_symbols 

30from ase.dft.kpoints import kpoint_convert 

31from ase.io.espresso_namelist.namelist import Namelist 

32from ase.units import create_units 

33from ase.utils import reader, writer 

34 

35# Quantum ESPRESSO uses CODATA 2006 internally 

36units = create_units('2006') 

37 

38# Section identifiers 

39_PW_START = 'Program PWSCF' 

40_PW_END = 'End of self-consistent calculation' 

41_PW_CELL = 'CELL_PARAMETERS' 

42_PW_POS = 'ATOMIC_POSITIONS' 

43_PW_MAGMOM = 'Magnetic moment per site' 

44_PW_FORCE = 'Forces acting on atoms' 

45_PW_TOTEN = '! total energy' 

46_PW_STRESS = 'total stress' 

47_PW_FERMI = 'the Fermi energy is' 

48_PW_HIGHEST_OCCUPIED = 'highest occupied level' 

49_PW_HIGHEST_OCCUPIED_LOWEST_FREE = 'highest occupied, lowest unoccupied level' 

50_PW_KPTS = 'number of k points=' 

51_PW_BANDS = _PW_END 

52_PW_BANDSTRUCTURE = 'End of band structure calculation' 

53_PW_DIPOLE = 'Debye' 

54_PW_DIPOLE_DIRECTION = 'Computed dipole along edir' 

55 

56# ibrav error message 

57ibrav_error_message = ( 

58 'ASE does not support ibrav != 0. Note that with ibrav ' 

59 '== 0, Quantum ESPRESSO will still detect the symmetries ' 

60 'of your system because the CELL_PARAMETERS are defined ' 

61 'to a high level of precision.' 

62) 

63 

64 

65@reader 

66def read_espresso_out(fileobj, index=slice(None), results_required=True): 

67 """Reads Quantum ESPRESSO output files. 

68 

69 The atomistic configurations as well as results (energy, force, stress, 

70 magnetic moments) of the calculation are read for all configurations 

71 within the output file. 

72 

73 Will probably raise errors for broken or incomplete files. 

74 

75 Parameters 

76 ---------- 

77 fileobj : file|str 

78 A file like object or filename 

79 index : slice 

80 The index of configurations to extract. 

81 results_required : bool 

82 If True, atomistic configurations that do not have any 

83 associated results will not be included. This prevents double 

84 printed configurations and incomplete calculations from being 

85 returned as the final configuration with no results data. 

86 

87 Yields 

88 ------ 

89 structure : Atoms 

90 The next structure from the index slice. The Atoms has a 

91 SinglePointCalculator attached with any results parsed from 

92 the file. 

93 

94 

95 """ 

96 # work with a copy in memory for faster random access 

97 pwo_lines = fileobj.readlines() 

98 

99 # TODO: index -1 special case? 

100 # Index all the interesting points 

101 indexes = { 

102 _PW_START: [], 

103 _PW_END: [], 

104 _PW_CELL: [], 

105 _PW_POS: [], 

106 _PW_MAGMOM: [], 

107 _PW_FORCE: [], 

108 _PW_TOTEN: [], 

109 _PW_STRESS: [], 

110 _PW_FERMI: [], 

111 _PW_HIGHEST_OCCUPIED: [], 

112 _PW_HIGHEST_OCCUPIED_LOWEST_FREE: [], 

113 _PW_KPTS: [], 

114 _PW_BANDS: [], 

115 _PW_BANDSTRUCTURE: [], 

116 _PW_DIPOLE: [], 

117 _PW_DIPOLE_DIRECTION: [], 

118 } 

119 

120 for idx, line in enumerate(pwo_lines): 

121 for identifier in indexes: 

122 if identifier in line: 

123 indexes[identifier].append(idx) 

124 

125 # Configurations are either at the start, or defined in ATOMIC_POSITIONS 

126 # in a subsequent step. Can deal with concatenated output files. 

127 all_config_indexes = sorted(indexes[_PW_START] + indexes[_PW_POS]) 

128 

129 # Slice only requested indexes 

130 # setting results_required argument stops configuration-only 

131 # structures from being returned. This ensures the [-1] structure 

132 # is one that has results. Two cases: 

133 # - SCF of last configuration is not converged, job terminated 

134 # abnormally. 

135 # - 'relax' and 'vc-relax' re-prints the final configuration but 

136 # only 'vc-relax' recalculates. 

137 if results_required: 

138 results_indexes = sorted( 

139 indexes[_PW_TOTEN] 

140 + indexes[_PW_FORCE] 

141 + indexes[_PW_STRESS] 

142 + indexes[_PW_MAGMOM] 

143 + indexes[_PW_BANDS] 

144 + indexes[_PW_BANDSTRUCTURE] 

145 ) 

146 

147 # Prune to only configurations with results data before the next 

148 # configuration 

149 results_config_indexes = [] 

150 for config_index, config_index_next in zip( 

151 all_config_indexes, all_config_indexes[1:] + [len(pwo_lines)] 

152 ): 

153 if any( 

154 config_index < results_index < config_index_next 

155 for results_index in results_indexes 

156 ): 

157 results_config_indexes.append(config_index) 

158 

159 # slice from the subset 

160 image_indexes = results_config_indexes[index] 

161 else: 

162 image_indexes = all_config_indexes[index] 

163 

164 # Extract initialisation information each time PWSCF starts 

165 # to add to subsequent configurations. Use None so slices know 

166 # when to fill in the blanks. 

167 pwscf_start_info = {idx: None for idx in indexes[_PW_START]} 

168 

169 for image_index in image_indexes: 

170 # Find the nearest calculation start to parse info. Needed in, 

171 # for example, relaxation where cell is only printed at the 

172 # start. 

173 if image_index in indexes[_PW_START]: 

174 prev_start_index = image_index 

175 else: 

176 # The greatest start index before this structure 

177 prev_start_index = [ 

178 idx for idx in indexes[_PW_START] if idx < image_index 

179 ][-1] 

180 

181 # add structure to reference if not there 

182 if pwscf_start_info[prev_start_index] is None: 

183 pwscf_start_info[prev_start_index] = parse_pwo_start( 

184 pwo_lines, prev_start_index 

185 ) 

186 

187 # Get the bounds for information for this structure. Any associated 

188 # values will be between the image_index and the following one, 

189 # EXCEPT for cell, which will be 4 lines before if it exists. 

190 for next_index in all_config_indexes: 

191 if next_index > image_index: 

192 break 

193 else: 

194 # right to the end of the file 

195 next_index = len(pwo_lines) 

196 

197 # Get the structure 

198 # Use this for any missing data 

199 prev_structure = pwscf_start_info[prev_start_index]['atoms'] 

200 cell_alat = pwscf_start_info[prev_start_index]['alat'] 

201 if image_index in indexes[_PW_START]: 

202 structure = prev_structure.copy() # parsed from start info 

203 else: 

204 if _PW_CELL in pwo_lines[image_index - 5]: 

205 # CELL_PARAMETERS would be just before positions if present 

206 cell, _ = get_cell_parameters( 

207 pwo_lines[image_index - 5 : image_index] 

208 ) 

209 else: 

210 cell = prev_structure.cell 

211 cell_alat = pwscf_start_info[prev_start_index]['alat'] 

212 

213 # give at least enough lines to parse the positions 

214 # should be same format as input card 

215 n_atoms = len(prev_structure) 

216 positions_card = get_atomic_positions( 

217 pwo_lines[image_index : image_index + n_atoms + 1], 

218 n_atoms=n_atoms, 

219 cell=cell, 

220 alat=cell_alat, 

221 ) 

222 

223 # convert to Atoms object 

224 symbols = [ 

225 label_to_symbol(position[0]) for position in positions_card 

226 ] 

227 positions = [position[1] for position in positions_card] 

228 constraint_flags = [position[2] for position in positions_card] 

229 structure = Atoms( 

230 symbols=symbols, positions=positions, cell=cell, pbc=True 

231 ) 

232 structure.set_constraint(convert_constraint_flags(constraint_flags)) 

233 

234 def find_thing(get_thing, indices, **kwargs): 

235 for index in indices: 

236 if image_index < index < next_index: 

237 return get_thing(pwo_lines, index, **kwargs) 

238 return None 

239 

240 natoms = len(structure) 

241 

242 energy = find_thing(_get_energy, indexes[_PW_TOTEN]) 

243 forces = find_thing(_get_forces, indexes[_PW_FORCE], natoms=natoms) 

244 stress = find_thing(_get_stress, indexes[_PW_STRESS]) 

245 magmoms = find_thing(_get_magmoms, indexes[_PW_MAGMOM], natoms=natoms) 

246 

247 # Dipole moment 

248 dipole = None 

249 if indexes[_PW_DIPOLE]: 

250 for dipole_index in indexes[_PW_DIPOLE]: 

251 if image_index < dipole_index < next_index: 

252 _dipole = float(pwo_lines[dipole_index].split()[-2]) 

253 

254 for dipole_index in indexes[_PW_DIPOLE_DIRECTION]: 

255 if image_index < dipole_index < next_index: 

256 _direction = pwo_lines[dipole_index].strip() 

257 prefix = 'Computed dipole along edir(' 

258 _direction = _direction[len(prefix) :] 

259 _direction = int(_direction[0]) 

260 

261 dipole = np.eye(3)[_direction - 1] * _dipole * units['Debye'] 

262 

263 # Fermi level / highest occupied level 

264 efermi = None 

265 for fermi_index in indexes[_PW_FERMI]: 

266 if image_index < fermi_index < next_index: 

267 efermi = float(pwo_lines[fermi_index].split()[-2]) 

268 

269 if efermi is None: 

270 for ho_index in indexes[_PW_HIGHEST_OCCUPIED]: 

271 if image_index < ho_index < next_index: 

272 efermi = float(pwo_lines[ho_index].split()[-1]) 

273 

274 if efermi is None: 

275 for holf_index in indexes[_PW_HIGHEST_OCCUPIED_LOWEST_FREE]: 

276 if image_index < holf_index < next_index: 

277 efermi = float(pwo_lines[holf_index].split()[-2]) 

278 

279 # K-points 

280 ibzkpts = None 

281 weights = None 

282 kpoints_warning = ( 

283 'Number of k-points >= 100: ' 

284 + "set verbosity='high' to print them." 

285 ) 

286 

287 for kpts_index in indexes[_PW_KPTS]: 

288 nkpts = int(re.findall(r'\b\d+\b', pwo_lines[kpts_index])[0]) 

289 kpts_index += 2 

290 

291 if pwo_lines[kpts_index].strip() == kpoints_warning: 

292 continue 

293 

294 # QE prints the k-points in units of 2*pi/alat 

295 cell = structure.get_cell() 

296 ibzkpts = [] 

297 weights = [] 

298 for i in range(nkpts): 

299 L = pwo_lines[kpts_index + i].split() 

300 weights.append(float(L[-1])) 

301 coord = np.array([L[-6], L[-5], L[-4].strip('),')], dtype=float) 

302 coord *= 2 * np.pi / cell_alat 

303 coord = kpoint_convert(cell, ckpts_kv=coord) 

304 ibzkpts.append(coord) 

305 ibzkpts = np.array(ibzkpts) 

306 weights = np.array(weights) 

307 

308 # Bands 

309 kpts = None 

310 kpoints_warning = ( 

311 'Number of k-points >= 100: ' 

312 + "set verbosity='high' to print the bands." 

313 ) 

314 

315 for bands_index in indexes[_PW_BANDS] + indexes[_PW_BANDSTRUCTURE]: 

316 if image_index < bands_index < next_index: 

317 bands_index += 1 

318 # skip over the lines with DFT+U occupation matrices 

319 if 'enter write_ns' in pwo_lines[bands_index]: 

320 while 'exit write_ns' not in pwo_lines[bands_index]: 

321 bands_index += 1 

322 bands_index += 1 

323 

324 if pwo_lines[bands_index].strip() == kpoints_warning: 

325 continue 

326 

327 assert ibzkpts is not None 

328 spin, bands, eigenvalues = 0, [], [[], []] 

329 

330 while True: 

331 L = pwo_lines[bands_index].replace('-', ' -').split() 

332 if len(L) == 0: 

333 if len(bands) > 0: 

334 eigenvalues[spin].append(bands) 

335 bands = [] 

336 elif L == ['occupation', 'numbers']: 

337 # Skip the lines with the occupation numbers 

338 bands_index += len(eigenvalues[spin][0]) // 8 + 1 

339 elif L[0] == 'k' and L[1].startswith('='): 

340 pass 

341 elif 'SPIN' in L: 

342 if 'DOWN' in L: 

343 spin += 1 

344 else: 

345 try: 

346 bands.extend(map(float, L)) 

347 except ValueError: 

348 break 

349 bands_index += 1 

350 

351 if spin == 1: 

352 assert len(eigenvalues[0]) == len(eigenvalues[1]) 

353 assert len(eigenvalues[0]) == len(ibzkpts), ( 

354 np.shape(eigenvalues), 

355 len(ibzkpts), 

356 ) 

357 

358 kpts = [] 

359 for s in range(spin + 1): 

360 for w, k, e in zip(weights, ibzkpts, eigenvalues[s]): 

361 kpt = SinglePointKPoint(w, s, k, eps_n=e) 

362 kpts.append(kpt) 

363 

364 # Put everything together 

365 # 

366 # In PW the forces are consistent with the "total energy"; that's why 

367 # its value must be assigned to free_energy. 

368 # PW doesn't compute the extrapolation of the energy to 0K smearing 

369 # the closer thing to this is again the total energy that contains 

370 # the correct (i.e. variational) form of the band energy is 

371 # Eband = \int e N(e) de for e<Ef , where N(e) is the DOS 

372 # This differs by the term (-TS) from the sum of KS eigenvalues: 

373 # Eks = \sum wg(n,k) et(n,k) 

374 # which is non variational. When a Fermi-Dirac function is used 

375 # for a given T, the variational energy is REALLY the free energy F, 

376 # and F = E - TS , with E = non variational energy. 

377 # 

378 calc = SinglePointDFTCalculator( 

379 structure, 

380 energy=energy, 

381 free_energy=energy, 

382 forces=forces, 

383 stress=stress, 

384 magmoms=magmoms, 

385 efermi=efermi, 

386 ibzkpts=ibzkpts, 

387 dipole=dipole, 

388 ) 

389 calc.kpts = kpts 

390 structure.calc = calc 

391 

392 yield structure 

393 

394 

395def parse_pwo_start(lines, index=0): 

396 """Parse Quantum ESPRESSO calculation info from lines, 

397 starting from index. Return a dictionary containing extracted 

398 information. 

399 

400 - `celldm(1)`: lattice parameters (alat) 

401 - `cell`: unit cell in Angstrom 

402 - `symbols`: element symbols for the structure 

403 - `positions`: cartesian coordinates of atoms in Angstrom 

404 - `atoms`: an `ase.Atoms` object constructed from the extracted data 

405 

406 Parameters 

407 ---------- 

408 lines : list[str] 

409 Contents of PWSCF output file. 

410 index : int 

411 Line number to begin parsing. Only first calculation will 

412 be read. 

413 

414 Returns 

415 ------- 

416 info : dict 

417 Dictionary of calculation parameters, including `celldm(1)`, `cell`, 

418 `symbols`, `positions`, `atoms`. 

419 

420 Raises 

421 ------ 

422 KeyError 

423 If interdependent values cannot be found (especially celldm(1)) 

424 an error will be raised as other quantities cannot then be 

425 calculated (e.g. cell and positions). 

426 """ 

427 # TODO: extend with extra DFT info? 

428 

429 info = {} 

430 

431 for idx, line in enumerate(lines[index:], start=index): 

432 if 'celldm(1)' in line: 

433 # celldm(1) has more digits than alat!! 

434 info['celldm(1)'] = float(line.split()[1]) * units['Bohr'] 

435 info['alat'] = info['celldm(1)'] 

436 elif 'number of atoms/cell' in line: 

437 info['nat'] = int(line.split()[-1]) 

438 elif 'number of atomic types' in line: 

439 info['ntyp'] = int(line.split()[-1]) 

440 elif 'crystal axes:' in line: 

441 info['cell'] = info['celldm(1)'] * np.array( 

442 [ 

443 [float(x) for x in lines[idx + 1].split()[3:6]], 

444 [float(x) for x in lines[idx + 2].split()[3:6]], 

445 [float(x) for x in lines[idx + 3].split()[3:6]], 

446 ] 

447 ) 

448 elif 'positions (alat units)' in line: 

449 info['symbols'], info['positions'] = [], [] 

450 

451 for at_line in lines[idx + 1 : idx + 1 + info['nat']]: 

452 sym, x, y, z = parse_position_line(at_line) 

453 info['symbols'].append(label_to_symbol(sym)) 

454 info['positions'].append( 

455 [ 

456 x * info['celldm(1)'], 

457 y * info['celldm(1)'], 

458 z * info['celldm(1)'], 

459 ] 

460 ) 

461 # This should be the end of interesting info. 

462 # Break here to avoid dealing with large lists of kpoints. 

463 # Will need to be extended for DFTCalculator info. 

464 break 

465 

466 # Make atoms for convenience 

467 info['atoms'] = Atoms( 

468 symbols=info['symbols'], 

469 positions=info['positions'], 

470 cell=info['cell'], 

471 pbc=True, 

472 ) 

473 

474 return info 

475 

476 

477def parse_position_line(line): 

478 """Parse a single line from a pw.x output file. 

479 

480 The line must contain information about the atomic symbol and the position, 

481 e.g. 

482 

483 995 Sb tau( 995) = ( 1.4212023 0.7037863 0.1242640 ) 

484 

485 Parameters 

486 ---------- 

487 line : str 

488 Line to be parsed. 

489 

490 Returns 

491 ------- 

492 sym : str 

493 Atomic symbol. 

494 x : float 

495 x-position. 

496 y : float 

497 y-position. 

498 z : float 

499 z-position. 

500 """ 

501 pat = re.compile( 

502 r'\s*\d+\s*(\S+)\s*tau\(\s*\d+\)\s*=' 

503 r'\s*\(\s*(\S+)\s+(\S+)\s+(\S+)\s*\)' 

504 ) 

505 match = pat.match(line) 

506 assert match is not None 

507 sym, x, y, z = match.group(1, 2, 3, 4) 

508 return sym, float(x), float(y), float(z) 

509 

510 

511@reader 

512def read_espresso_in(fileobj): 

513 """Parse a Quantum ESPRESSO input files, '.in', '.pwi'. 

514 

515 ESPRESSO inputs are generally a fortran-namelist format with custom 

516 blocks of data. The namelist is parsed as a dict and an atoms object 

517 is constructed from the included information. 

518 

519 Parameters 

520 ---------- 

521 fileobj : file | str 

522 A file-like object that supports line iteration with the contents 

523 of the input file, or a filename. 

524 

525 Returns 

526 ------- 

527 atoms : Atoms 

528 Structure defined in the input file. 

529 

530 Raises 

531 ------ 

532 KeyError 

533 Raised for missing keys that are required to process the file 

534 """ 

535 # parse namelist section and extract remaining lines 

536 data, card_lines = read_fortran_namelist(fileobj) 

537 

538 # get the cell if ibrav=0 

539 if 'system' not in data: 

540 raise KeyError('Required section &SYSTEM not found.') 

541 elif 'ibrav' not in data['system']: 

542 raise KeyError('ibrav is required in &SYSTEM') 

543 elif data['system']['ibrav'] == 0: 

544 # celldm(1) is in Bohr, A is in angstrom. celldm(1) will be 

545 # used even if A is also specified. 

546 if 'celldm(1)' in data['system']: 

547 alat = data['system']['celldm(1)'] * units['Bohr'] 

548 elif 'A' in data['system']: 

549 alat = data['system']['A'] 

550 else: 

551 alat = None 

552 cell, _ = get_cell_parameters(card_lines, alat=alat) 

553 else: 

554 raise ValueError(ibrav_error_message) 

555 

556 # species_info holds some info for each element 

557 species_card = get_atomic_species( 

558 card_lines, n_species=data['system']['ntyp'] 

559 ) 

560 species_info = {} 

561 for ispec, (label, weight, pseudo) in enumerate(species_card): 

562 symbol = label_to_symbol(label) 

563 

564 # starting_magnetization is in fractions of valence electrons 

565 magnet_key = f'starting_magnetization({ispec + 1})' 

566 magmom = data['system'].get(magnet_key, 0.0) 

567 species_info[symbol] = { 

568 'weight': weight, 

569 'pseudo': pseudo, 

570 'magmom': magmom, 

571 } 

572 

573 positions_card = get_atomic_positions( 

574 card_lines, n_atoms=data['system']['nat'], cell=cell, alat=alat 

575 ) 

576 

577 symbols = [label_to_symbol(position[0]) for position in positions_card] 

578 positions = [position[1] for position in positions_card] 

579 constraint_flags = [position[2] for position in positions_card] 

580 magmoms = [species_info[symbol]['magmom'] for symbol in symbols] 

581 

582 # TODO: put more info into the atoms object 

583 # e.g magmom, forces. 

584 atoms = Atoms( 

585 symbols=symbols, 

586 positions=positions, 

587 cell=cell, 

588 pbc=True, 

589 magmoms=magmoms, 

590 ) 

591 atoms.set_constraint(convert_constraint_flags(constraint_flags)) 

592 

593 return atoms 

594 

595 

596def get_atomic_positions(lines, n_atoms, cell=None, alat=None): 

597 """Parse atom positions from ATOMIC_POSITIONS card. 

598 

599 Parameters 

600 ---------- 

601 lines : list[str] 

602 A list of lines containing the ATOMIC_POSITIONS card. 

603 n_atoms : int 

604 Expected number of atoms. Only this many lines will be parsed. 

605 cell : np.array 

606 Unit cell of the crystal. Only used with crystal coordinates. 

607 alat : float 

608 Lattice parameter for atomic coordinates. Only used for alat case. 

609 

610 Returns 

611 ------- 

612 positions : list[(str, (float, float, float), (int, int, int))] 

613 A list of the ordered atomic positions in the format: 

614 label, (x, y, z), (if_x, if_y, if_z) 

615 Force multipliers are set to None if not present. 

616 

617 Raises 

618 ------ 

619 ValueError 

620 Any problems parsing the data result in ValueError 

621 

622 """ 

623 

624 positions = None 

625 # no blanks or comment lines, can the consume n_atoms lines for positions 

626 trimmed_lines = (line for line in lines if line.strip() and line[0] != '#') 

627 

628 for line in trimmed_lines: 

629 if line.strip().startswith('ATOMIC_POSITIONS'): 

630 if positions is not None: 

631 raise ValueError('Multiple ATOMIC_POSITIONS specified') 

632 # Priority and behaviour tested with QE 5.3 

633 if 'crystal_sg' in line.lower(): 

634 raise NotImplementedError('CRYSTAL_SG not implemented') 

635 elif 'crystal' in line.lower(): 

636 cell = cell 

637 elif 'bohr' in line.lower(): 

638 cell = np.identity(3) * units['Bohr'] 

639 elif 'angstrom' in line.lower(): 

640 cell = np.identity(3) 

641 # elif 'alat' in line.lower(): 

642 # cell = np.identity(3) * alat 

643 else: 

644 if alat is None: 

645 raise ValueError( 

646 'Set lattice parameter in &SYSTEM for alat coordinates' 

647 ) 

648 # Always the default, will be DEPRECATED as mandatory 

649 # in future 

650 cell = np.identity(3) * alat 

651 

652 positions = [] 

653 for _ in range(n_atoms): 

654 split_line = next(trimmed_lines).split() 

655 # These can be fractions and other expressions 

656 position = np.dot( 

657 ( 

658 infix_float(split_line[1]), 

659 infix_float(split_line[2]), 

660 infix_float(split_line[3]), 

661 ), 

662 cell, 

663 ) 

664 if len(split_line) > 4: 

665 force_mult = tuple(int(split_line[i]) for i in (4, 5, 6)) 

666 else: 

667 force_mult = None 

668 

669 positions.append((split_line[0], position, force_mult)) 

670 

671 return positions 

672 

673 

674def get_atomic_species(lines, n_species): 

675 """Parse atomic species from ATOMIC_SPECIES card. 

676 

677 Parameters 

678 ---------- 

679 lines : list[str] 

680 A list of lines containing the ATOMIC_POSITIONS card. 

681 n_species : int 

682 Expected number of atom types. Only this many lines will be parsed. 

683 

684 Returns 

685 ------- 

686 species : list[(str, float, str)] 

687 

688 Raises 

689 ------ 

690 ValueError 

691 Any problems parsing the data result in ValueError 

692 """ 

693 

694 species = None 

695 # no blanks or comment lines, can the consume n_atoms lines for positions 

696 trimmed_lines = ( 

697 line.strip() 

698 for line in lines 

699 if line.strip() and not line.startswith('#') 

700 ) 

701 

702 for line in trimmed_lines: 

703 if line.startswith('ATOMIC_SPECIES'): 

704 if species is not None: 

705 raise ValueError('Multiple ATOMIC_SPECIES specified') 

706 

707 species = [] 

708 for _dummy in range(n_species): 

709 label_weight_pseudo = next(trimmed_lines).split() 

710 species.append( 

711 ( 

712 label_weight_pseudo[0], 

713 float(label_weight_pseudo[1]), 

714 label_weight_pseudo[2], 

715 ) 

716 ) 

717 

718 return species 

719 

720 

721def get_cell_parameters(lines, alat=None): 

722 """Parse unit cell from CELL_PARAMETERS card. 

723 

724 Parameters 

725 ---------- 

726 lines : list[str] 

727 A list with lines containing the CELL_PARAMETERS card. 

728 alat : float | None 

729 Unit of lattice vectors in Angstrom. Only used if the card is 

730 given in units of alat. alat must be None if CELL_PARAMETERS card 

731 is in Bohr or Angstrom. For output files, alat will be parsed from 

732 the card header and used in preference to this value. 

733 

734 Returns 

735 ------- 

736 cell : np.array | None 

737 Cell parameters as a 3x3 array in Angstrom. If no cell is found 

738 None will be returned instead. 

739 cell_alat : float | None 

740 If a value for alat is given in the card header, this is also 

741 returned, otherwise this will be None. 

742 

743 Raises 

744 ------ 

745 ValueError 

746 If CELL_PARAMETERS are given in units of bohr or angstrom 

747 and alat is not 

748 """ 

749 

750 cell = None 

751 cell_alat = None 

752 # no blanks or comment lines, can take three lines for cell 

753 trimmed_lines = (line for line in lines if line.strip() and line[0] != '#') 

754 

755 for line in trimmed_lines: 

756 if line.strip().startswith('CELL_PARAMETERS'): 

757 if cell is not None: 

758 # multiple definitions 

759 raise ValueError('CELL_PARAMETERS specified multiple times') 

760 # Priority and behaviour tested with QE 5.3 

761 if 'bohr' in line.lower(): 

762 if alat is not None: 

763 raise ValueError( 

764 'Lattice parameters given in ' 

765 '&SYSTEM celldm/A and CELL_PARAMETERS ' 

766 'bohr' 

767 ) 

768 cell_units = units['Bohr'] 

769 elif 'angstrom' in line.lower(): 

770 if alat is not None: 

771 raise ValueError( 

772 'Lattice parameters given in ' 

773 '&SYSTEM celldm/A and CELL_PARAMETERS ' 

774 'angstrom' 

775 ) 

776 cell_units = 1.0 

777 elif 'alat' in line.lower(): 

778 # Output file has (alat = value) (in Bohrs) 

779 if '=' in line: 

780 alat = float(line.strip(') \n').split()[-1]) * units['Bohr'] 

781 cell_alat = alat 

782 elif alat is None: 

783 raise ValueError( 

784 'Lattice parameters must be set in ' 

785 '&SYSTEM for alat units' 

786 ) 

787 cell_units = alat 

788 elif alat is None: 

789 # may be DEPRECATED in future 

790 cell_units = units['Bohr'] 

791 else: 

792 # may be DEPRECATED in future 

793 cell_units = alat 

794 # Grab the parameters; blank lines have been removed 

795 cell = [ 

796 [ffloat(x) for x in next(trimmed_lines).split()[:3]], 

797 [ffloat(x) for x in next(trimmed_lines).split()[:3]], 

798 [ffloat(x) for x in next(trimmed_lines).split()[:3]], 

799 ] 

800 cell = np.array(cell) * cell_units 

801 

802 return cell, cell_alat 

803 

804 

805def convert_constraint_flags(constraint_flags): 

806 """Convert Quantum ESPRESSO constraint flags to ASE Constraint objects. 

807 

808 Parameters 

809 ---------- 

810 constraint_flags : list[tuple[int, int, int]] 

811 List of constraint flags (0: fixed, 1: moved) for all the atoms. 

812 If the flag is None, there are no constraints on the atom. 

813 

814 Returns 

815 ------- 

816 constraints : list[FixAtoms | FixCartesian] 

817 List of ASE Constraint objects. 

818 """ 

819 constraints = [] 

820 for i, constraint in enumerate(constraint_flags): 

821 if constraint is None: 

822 continue 

823 # mask: False (0): moved, True (1): fixed 

824 mask = ~np.asarray(constraint, bool) 

825 constraints.append(FixCartesian(i, mask)) 

826 return canonicalize_constraints(constraints) 

827 

828 

829def canonicalize_constraints(constraints): 

830 """Canonicalize ASE FixCartesian constraints. 

831 

832 If the given FixCartesian constraints share the same `mask`, they can be 

833 merged into one. Further, if `mask == (True, True, True)`, they can be 

834 converted as `FixAtoms`. This method "canonicalizes" FixCartesian objects 

835 in such a way. 

836 

837 Parameters 

838 ---------- 

839 constraints : List[FixCartesian] 

840 List of ASE FixCartesian constraints. 

841 

842 Returns 

843 ------- 

844 constrants_canonicalized : List[FixAtoms | FixCartesian] 

845 List of ASE Constraint objects. 

846 """ 

847 # https://docs.python.org/3/library/collections.html#defaultdict-examples 

848 indices_for_masks = defaultdict(list) 

849 for constraint in constraints: 

850 key = tuple((constraint.mask).tolist()) 

851 indices_for_masks[key].extend(constraint.index.tolist()) 

852 

853 constraints_canonicalized = [] 

854 for mask, indices in indices_for_masks.items(): 

855 if mask == (False, False, False): # no directions are fixed 

856 continue 

857 if mask == (True, True, True): # all three directions are fixed 

858 constraints_canonicalized.append(FixAtoms(indices)) 

859 else: 

860 constraints_canonicalized.append(FixCartesian(indices, mask)) 

861 

862 return constraints_canonicalized 

863 

864 

865def str_to_value(string): 

866 """Attempt to convert string into int, float (including fortran double), 

867 or bool, in that order, otherwise return the string. 

868 Valid (case-insensitive) bool values are: '.true.', '.t.', 'true' 

869 and 't' (or false equivalents). 

870 

871 Parameters 

872 ---------- 

873 string : str 

874 Test to parse for a datatype 

875 

876 Returns 

877 ------- 

878 value : any 

879 Parsed string as the most appropriate datatype of int, float, 

880 bool or string. 

881 """ 

882 

883 # Just an integer 

884 try: 

885 return int(string) 

886 except ValueError: 

887 pass 

888 # Standard float 

889 try: 

890 return float(string) 

891 except ValueError: 

892 pass 

893 # Fortran double 

894 try: 

895 return ffloat(string) 

896 except ValueError: 

897 pass 

898 

899 # possible bool, else just the raw string 

900 if string.lower() in ('.true.', '.t.', 'true', 't'): 

901 return True 

902 elif string.lower() in ('.false.', '.f.', 'false', 'f'): 

903 return False 

904 else: 

905 return string.strip("'") 

906 

907 

908def read_fortran_namelist(fileobj): 

909 """Takes a fortran-namelist formatted file and returns nested 

910 dictionaries of sections and key-value data, followed by a list 

911 of lines of text that do not fit the specifications. 

912 Behaviour is taken from Quantum ESPRESSO 5.3. Parses fairly 

913 convoluted files the same way that QE should, but may not get 

914 all the MANDATORY rules and edge cases for very non-standard files 

915 Ignores anything after '!' in a namelist, split pairs on ',' 

916 to include multiple key=values on a line, read values on section 

917 start and end lines, section terminating character, '/', can appear 

918 anywhere on a line. All of these are ignored if the value is in 'quotes'. 

919 

920 Parameters 

921 ---------- 

922 fileobj : file 

923 An open file-like object. 

924 

925 Returns 

926 ------- 

927 data : dict[str, dict] 

928 Dictionary for each section in the namelist with 

929 key = value pairs of data. 

930 additional_cards : list[str] 

931 Any lines not used to create the data, 

932 assumed to belong to 'cards' in the input file. 

933 """ 

934 

935 data = {} 

936 card_lines = [] 

937 in_namelist = False 

938 section = 'none' # can't be in a section without changing this 

939 

940 for line in fileobj: 

941 # leading and trailing whitespace never needed 

942 line = line.strip() 

943 if line.startswith('&'): 

944 # inside a namelist 

945 section = line.split()[0][1:].lower() # case insensitive 

946 if section in data: 

947 # Repeated sections are completely ignored. 

948 # (Note that repeated keys overwrite within a section) 

949 section = '_ignored' 

950 data[section] = {} 

951 in_namelist = True 

952 if not in_namelist and line: 

953 # Stripped line is Truthy, so safe to index first character 

954 if line[0] not in ('!', '#'): 

955 card_lines.append(line) 

956 if in_namelist: 

957 # parse k, v from line: 

958 key = [] 

959 value = None 

960 in_quotes = False 

961 for character in line: 

962 if character == ',' and value is not None and not in_quotes: 

963 # finished value: 

964 data[section][''.join(key).strip()] = str_to_value( 

965 ''.join(value).strip() 

966 ) 

967 key = [] 

968 value = None 

969 elif character == '=' and value is None and not in_quotes: 

970 # start writing value 

971 value = [] 

972 elif character == "'": 

973 # only found in value anyway 

974 in_quotes = not in_quotes 

975 value.append("'") 

976 elif character == '!' and not in_quotes: 

977 break 

978 elif character == '/' and not in_quotes: 

979 in_namelist = False 

980 break 

981 elif value is not None: 

982 value.append(character) 

983 else: 

984 key.append(character) 

985 if value is not None: 

986 data[section][''.join(key).strip()] = str_to_value( 

987 ''.join(value).strip() 

988 ) 

989 

990 return Namelist(data), card_lines 

991 

992 

993def ffloat(string): 

994 """Parse float from fortran compatible float definitions. 

995 

996 In fortran exponents can be defined with 'd' or 'q' to symbolise 

997 double or quad precision numbers. Double precision numbers are 

998 converted to python floats and quad precision values are interpreted 

999 as numpy longdouble values (platform specific precision). 

1000 

1001 Parameters 

1002 ---------- 

1003 string : str 

1004 A string containing a number in fortran real format 

1005 

1006 Returns 

1007 ------- 

1008 value : float | np.longdouble 

1009 Parsed value of the string. 

1010 

1011 Raises 

1012 ------ 

1013 ValueError 

1014 Unable to parse a float value. 

1015 

1016 """ 

1017 

1018 if 'q' in string.lower(): 

1019 return np.longdouble(string.lower().replace('q', 'e')) 

1020 else: 

1021 return float(string.lower().replace('d', 'e')) 

1022 

1023 

1024def label_to_symbol(label): 

1025 """Convert a valid espresso ATOMIC_SPECIES label to a 

1026 chemical symbol. 

1027 

1028 Parameters 

1029 ---------- 

1030 label : str 

1031 chemical symbol X (1 or 2 characters, case-insensitive) 

1032 or chemical symbol plus a number or a letter, as in 

1033 "Xn" (e.g. Fe1) or "X_*" or "X-*" (e.g. C1, C_h; 

1034 max total length cannot exceed 3 characters). 

1035 

1036 Returns 

1037 ------- 

1038 symbol : str 

1039 The best matching species from ase.utils.chemical_symbols 

1040 

1041 Raises 

1042 ------ 

1043 KeyError 

1044 Couldn't find an appropriate species. 

1045 

1046 Notes 

1047 ----- 

1048 It's impossible to tell whether e.g. He is helium 

1049 or hydrogen labelled 'e'. 

1050 """ 

1051 

1052 # possibly a two character species 

1053 # ase Atoms need proper case of chemical symbols. 

1054 if len(label) >= 2: 

1055 test_symbol = label[0].upper() + label[1].lower() 

1056 if test_symbol in chemical_symbols: 

1057 return test_symbol 

1058 # finally try with one character 

1059 test_symbol = label[0].upper() 

1060 if test_symbol in chemical_symbols: 

1061 return test_symbol 

1062 else: 

1063 raise KeyError('Could not parse species from label {}.'.format(label)) 

1064 

1065 

1066def infix_float(text): 

1067 """Parse simple infix maths into a float for compatibility with 

1068 Quantum ESPRESSO ATOMIC_POSITIONS cards. Note: this works with the 

1069 example, and most simple expressions, but the capabilities of 

1070 the two parsers are not identical. Will also parse a normal float 

1071 value properly, but slowly. 

1072 

1073 >>> infix_float('1/2*3^(-1/2)') 

1074 0.28867513459481287 

1075 

1076 Parameters 

1077 ---------- 

1078 text : str 

1079 An arithmetic expression using +, -, *, / and ^, including brackets. 

1080 

1081 Returns 

1082 ------- 

1083 value : float 

1084 Result of the mathematical expression. 

1085 

1086 """ 

1087 

1088 def middle_brackets(full_text): 

1089 """Extract text from innermost brackets.""" 

1090 start, end = 0, len(full_text) 

1091 for idx, char in enumerate(full_text): 

1092 if char == '(': 

1093 start = idx 

1094 if char == ')': 

1095 end = idx + 1 

1096 break 

1097 return full_text[start:end] 

1098 

1099 def eval_no_bracket_expr(full_text): 

1100 """Calculate value of a mathematical expression, no brackets.""" 

1101 exprs = [('+', op.add), ('*', op.mul), ('/', op.truediv), ('^', op.pow)] 

1102 full_text = full_text.lstrip('(').rstrip(')') 

1103 try: 

1104 return float(full_text) 

1105 except ValueError: 

1106 for symbol, func in exprs: 

1107 if symbol in full_text: 

1108 left, right = full_text.split(symbol, 1) # single split 

1109 return func( 

1110 eval_no_bracket_expr(left), eval_no_bracket_expr(right) 

1111 ) 

1112 

1113 while '(' in text: 

1114 middle = middle_brackets(text) 

1115 text = text.replace(middle, f'{eval_no_bracket_expr(middle)}') 

1116 

1117 return float(eval_no_bracket_expr(text)) 

1118 

1119 

1120def kspacing_to_grid(atoms, spacing, calculated_spacing=None): 

1121 """ 

1122 Calculate the kpoint mesh that is equivalent to the given spacing 

1123 in reciprocal space (units Angstrom^-1). The number of kpoints is each 

1124 dimension is rounded up (compatible with CASTEP). 

1125 

1126 Parameters 

1127 ---------- 

1128 atoms: ase.Atoms 

1129 A structure that can have get_reciprocal_cell called on it. 

1130 spacing: float 

1131 Minimum K-Point spacing in $A^{-1}$. 

1132 calculated_spacing : list 

1133 If a three item list (or similar mutable sequence) is given the 

1134 members will be replaced with the actual calculated spacing in 

1135 $A^{-1}$. 

1136 

1137 Returns 

1138 ------- 

1139 kpoint_grid : [int, int, int] 

1140 MP grid specification to give the required spacing. 

1141 

1142 """ 

1143 # No factor of 2pi in ase, everything in A^-1 

1144 # reciprocal dimensions 

1145 r_x, r_y, r_z = np.linalg.norm(atoms.cell.reciprocal(), axis=1) 

1146 

1147 kpoint_grid = [ 

1148 int(r_x / spacing) + 1, 

1149 int(r_y / spacing) + 1, 

1150 int(r_z / spacing) + 1, 

1151 ] 

1152 

1153 for i, _ in enumerate(kpoint_grid): 

1154 if not atoms.pbc[i]: 

1155 kpoint_grid[i] = 1 

1156 

1157 if calculated_spacing is not None: 

1158 calculated_spacing[:] = [ 

1159 r_x / kpoint_grid[0], 

1160 r_y / kpoint_grid[1], 

1161 r_z / kpoint_grid[2], 

1162 ] 

1163 

1164 return kpoint_grid 

1165 

1166 

1167def format_atom_position(atom, crystal_coordinates, mask='', tidx=None): 

1168 """Format one line of atomic positions in 

1169 Quantum ESPRESSO ATOMIC_POSITIONS card. 

1170 

1171 >>> for atom in make_supercell(bulk('Li', 'bcc'), np.ones(3)-np.eye(3)): 

1172 >>> format_atom_position(atom, True) 

1173 Li 0.0000000000 0.0000000000 0.0000000000 

1174 Li 0.5000000000 0.5000000000 0.5000000000 

1175 

1176 Parameters 

1177 ---------- 

1178 atom : Atom 

1179 A structure that has symbol and [position | (a, b, c)]. 

1180 crystal_coordinates: bool 

1181 Whether the atomic positions should be written to the QE input file in 

1182 absolute (False, default) or relative (crystal) coordinates (True). 

1183 mask, optional : str 

1184 String of ndim=3 0 or 1 for constraining atomic positions. 

1185 tidx, optional : int 

1186 Magnetic type index. 

1187 

1188 Returns 

1189 ------- 

1190 atom_line : str 

1191 Input line for atom position 

1192 """ 

1193 if crystal_coordinates: 

1194 coords = [atom.a, atom.b, atom.c] 

1195 else: 

1196 coords = atom.position 

1197 line_fmt = '{atom.symbol}' 

1198 inps = dict(atom=atom) 

1199 if tidx is not None: 

1200 line_fmt += '{tidx}' 

1201 inps['tidx'] = tidx 

1202 line_fmt += ' {coords[0]:.10f} {coords[1]:.10f} {coords[2]:.10f} ' 

1203 inps['coords'] = coords 

1204 line_fmt += ' ' + mask + '\n' 

1205 astr = line_fmt.format(**inps) 

1206 return astr 

1207 

1208 

1209@writer 

1210def write_espresso_in( 

1211 fd, 

1212 atoms, 

1213 input_data=None, 

1214 pseudopotentials=None, 

1215 kspacing=None, 

1216 kpts=None, 

1217 koffset=(0, 0, 0), 

1218 crystal_coordinates=False, 

1219 additional_cards=None, 

1220 **kwargs, 

1221): 

1222 """ 

1223 Create an input file for pw.x. 

1224 

1225 Use set_initial_magnetic_moments to turn on spin, if nspin is set to 2 

1226 with no magnetic moments, they will all be set to 0.0. Magnetic moments 

1227 will be converted to the QE units (fraction of valence electrons) using 

1228 any pseudopotential files found, or a best guess for the number of 

1229 valence electrons. 

1230 

1231 Units are not converted for any other input data, so use Quantum ESPRESSO 

1232 units (Usually Ry or atomic units). 

1233 

1234 Keys with a dimension (e.g. Hubbard_U(1)) will be incorporated as-is 

1235 so the `i` should be made to match the output. 

1236 

1237 Implemented features: 

1238 

1239 - Conversion of :class:`ase.constraints.FixAtoms` and 

1240 :class:`ase.constraints.FixCartesian`. 

1241 - ``starting_magnetization`` derived from the ``magmoms`` and 

1242 pseudopotentials (searches default paths for pseudo files.) 

1243 - Automatic assignment of options to their correct sections. 

1244 

1245 Not implemented: 

1246 

1247 - Non-zero values of ibrav 

1248 - Lists of k-points 

1249 - Other constraints 

1250 - Hubbard parameters 

1251 - Validation of the argument types for input 

1252 - Validation of required options 

1253 

1254 Parameters 

1255 ---------- 

1256 fd: file | str 

1257 A file to which the input is written. 

1258 atoms: Atoms 

1259 A single atomistic configuration to write to ``fd``. 

1260 input_data: dict 

1261 A flat or nested dictionary with input parameters for pw.x 

1262 pseudopotentials: dict 

1263 A filename for each atomic species, e.g. 

1264 {'O': 'O.pbe-rrkjus.UPF', 'H': 'H.pbe-rrkjus.UPF'}. 

1265 A dummy name will be used if none are given. 

1266 kspacing: float 

1267 Generate a grid of k-points with this as the minimum distance, 

1268 in A^-1 between them in reciprocal space. If set to None, kpts 

1269 will be used instead. 

1270 kpts: (int, int, int), dict or np.ndarray 

1271 If ``kpts`` is a tuple (or list) of 3 integers, it is interpreted 

1272 as the dimensions of a Monkhorst-Pack grid. 

1273 If ``kpts`` is set to ``None``, only the Γ-point will be included 

1274 and QE will use routines optimized for Γ-point-only calculations. 

1275 Compared to Γ-point-only calculations without this optimization 

1276 (i.e. with ``kpts=(1, 1, 1)``), the memory and CPU requirements 

1277 are typically reduced by half. 

1278 If kpts is a dict, it will either be interpreted as a path 

1279 in the Brillouin zone (*) if it contains the 'path' keyword, 

1280 otherwise it is converted to a Monkhorst-Pack grid (**). 

1281 If ``kpts`` is a NumPy array, the raw k-points will be passed to 

1282 Quantum Espresso as given in the array (in crystal coordinates). 

1283 Must be of shape (n_kpts, 4). The fourth column contains the 

1284 k-point weights. 

1285 (*) see ase.dft.kpoints.bandpath 

1286 (**) see ase.calculators.calculator.kpts2sizeandoffsets 

1287 koffset: (int, int, int) 

1288 Offset of kpoints in each direction. Must be 0 (no offset) or 

1289 1 (half grid offset). Setting to True is equivalent to (1, 1, 1). 

1290 crystal_coordinates: bool 

1291 Whether the atomic positions should be written to the QE input file in 

1292 absolute (False, default) or relative (crystal) coordinates (True). 

1293 

1294 """ 

1295 

1296 # Convert to a namelist to make working with parameters much easier 

1297 # Note that the name ``input_data`` is chosen to prevent clash with 

1298 # ``parameters`` in Calculator objects 

1299 input_parameters = Namelist(input_data) 

1300 input_parameters.to_nested('pw', **kwargs) 

1301 

1302 # Convert ase constraints to QE constraints 

1303 # Nx3 array of force multipliers matches what QE uses 

1304 # Do this early so it is available when constructing the atoms card 

1305 moved = np.ones((len(atoms), 3), dtype=bool) 

1306 for constraint in atoms.constraints: 

1307 if isinstance(constraint, FixAtoms): 

1308 moved[constraint.index] = False 

1309 elif isinstance(constraint, FixCartesian): 

1310 moved[constraint.index] = ~constraint.mask 

1311 else: 

1312 warnings.warn(f'Ignored unknown constraint {constraint}') 

1313 masks = [] 

1314 for atom in atoms: 

1315 # only inclued mask if something is fixed 

1316 if not all(moved[atom.index]): 

1317 mask = ' {:d} {:d} {:d}'.format(*moved[atom.index]) 

1318 else: 

1319 mask = '' 

1320 masks.append(mask) 

1321 

1322 # Species info holds the information on the pseudopotential and 

1323 # associated for each element 

1324 if pseudopotentials is None: 

1325 pseudopotentials = {} 

1326 species_info = {} 

1327 for species in set(atoms.get_chemical_symbols()): 

1328 # Look in all possible locations for the pseudos and try to figure 

1329 # out the number of valence electrons 

1330 pseudo = pseudopotentials[species] 

1331 species_info[species] = {'pseudo': pseudo} 

1332 

1333 # Convert atoms into species. 

1334 # Each different magnetic moment needs to be a separate type even with 

1335 # the same pseudopotential (e.g. an up and a down for AFM). 

1336 # if any magmom are > 0 or nspin == 2 then use species labels. 

1337 # Rememeber: magnetisation uses 1 based indexes 

1338 atomic_species = {} 

1339 atomic_species_str = [] 

1340 atomic_positions_str = [] 

1341 

1342 nspin = input_parameters['system'].get('nspin', 1) # 1 is the default 

1343 noncolin = input_parameters['system'].get('noncolin', False) 

1344 rescale_magmom_fac = kwargs.get('rescale_magmom_fac', 1.0) 

1345 if any(atoms.get_initial_magnetic_moments()): 

1346 if nspin == 1 and not noncolin: 

1347 # Force spin on 

1348 input_parameters['system']['nspin'] = 2 

1349 nspin = 2 

1350 

1351 if nspin == 2 or noncolin: 

1352 # Magnetic calculation on 

1353 for atom, mask, magmom in zip( 

1354 atoms, masks, atoms.get_initial_magnetic_moments() 

1355 ): 

1356 if (atom.symbol, magmom) not in atomic_species: 

1357 # for qe version 7.2 or older magmon must be rescale by 

1358 # about a factor 10 to assume sensible values 

1359 # since qe-v7.3 magmom values will be provided unscaled 

1360 fspin = float(magmom) / rescale_magmom_fac 

1361 # Index in the atomic species list 

1362 sidx = len(atomic_species) + 1 

1363 # Index for that atom type; no index for first one 

1364 tidx = sum(atom.symbol == x[0] for x in atomic_species) or ' ' 

1365 atomic_species[(atom.symbol, magmom)] = (sidx, tidx) 

1366 # Add magnetization to the input file 

1367 mag_str = f'starting_magnetization({sidx})' 

1368 input_parameters['system'][mag_str] = fspin 

1369 species_pseudo = species_info[atom.symbol]['pseudo'] 

1370 atomic_species_str.append( 

1371 f'{atom.symbol}{tidx} {atom.mass} {species_pseudo}\n' 

1372 ) 

1373 # lookup tidx to append to name 

1374 sidx, tidx = atomic_species[(atom.symbol, magmom)] 

1375 # construct line for atomic positions 

1376 atomic_positions_str.append( 

1377 format_atom_position( 

1378 atom, crystal_coordinates, mask=mask, tidx=tidx 

1379 ) 

1380 ) 

1381 else: 

1382 # Do nothing about magnetisation 

1383 for atom, mask in zip(atoms, masks): 

1384 if atom.symbol not in atomic_species: 

1385 atomic_species[atom.symbol] = True # just a placeholder 

1386 species_pseudo = species_info[atom.symbol]['pseudo'] 

1387 atomic_species_str.append( 

1388 f'{atom.symbol} {atom.mass} {species_pseudo}\n' 

1389 ) 

1390 # construct line for atomic positions 

1391 atomic_positions_str.append( 

1392 format_atom_position(atom, crystal_coordinates, mask=mask) 

1393 ) 

1394 

1395 # Add computed parameters 

1396 # different magnetisms means different types 

1397 input_parameters['system']['ntyp'] = len(atomic_species) 

1398 input_parameters['system']['nat'] = len(atoms) 

1399 

1400 # Use cell as given or fit to a specific ibrav 

1401 if 'ibrav' in input_parameters['system']: 

1402 ibrav = input_parameters['system']['ibrav'] 

1403 if ibrav != 0: 

1404 raise ValueError(ibrav_error_message) 

1405 else: 

1406 # Just use standard cell block 

1407 input_parameters['system']['ibrav'] = 0 

1408 

1409 # Construct input file into this 

1410 pwi = input_parameters.to_string(list_form=True) 

1411 

1412 # Pseudopotentials 

1413 pwi.append('ATOMIC_SPECIES\n') 

1414 pwi.extend(atomic_species_str) 

1415 pwi.append('\n') 

1416 

1417 # KPOINTS - add a MP grid as required 

1418 if kspacing is not None: 

1419 kgrid = kspacing_to_grid(atoms, kspacing) 

1420 elif kpts is not None: 

1421 if isinstance(kpts, dict) and 'path' not in kpts: 

1422 kgrid, shift = kpts2sizeandoffsets(atoms=atoms, **kpts) 

1423 koffset = [] 

1424 for i, x in enumerate(shift): 

1425 assert x == 0 or abs(x * kgrid[i] - 0.5) < 1e-14 

1426 koffset.append(0 if x == 0 else 1) 

1427 else: 

1428 kgrid = kpts 

1429 else: 

1430 kgrid = 'gamma' 

1431 

1432 # True and False work here and will get converted by ':d' format 

1433 if isinstance(koffset, int): 

1434 koffset = (koffset,) * 3 

1435 

1436 # BandPath object or bandpath-as-dictionary: 

1437 if isinstance(kgrid, dict) or hasattr(kgrid, 'kpts'): 

1438 pwi.append('K_POINTS crystal_b\n') 

1439 assert hasattr(kgrid, 'path') or 'path' in kgrid 

1440 kgrid = kpts2ndarray(kgrid, atoms=atoms) 

1441 pwi.append(f'{len(kgrid)}\n') 

1442 for k in kgrid: 

1443 pwi.append(f'{k[0]:.14f} {k[1]:.14f} {k[2]:.14f} 0\n') 

1444 pwi.append('\n') 

1445 elif isinstance(kgrid, str) and (kgrid == 'gamma'): 

1446 pwi.append('K_POINTS gamma\n') 

1447 pwi.append('\n') 

1448 elif isinstance(kgrid, np.ndarray): 

1449 if np.shape(kgrid)[1] != 4: 

1450 raise ValueError('Only Nx4 kgrids are supported right now.') 

1451 pwi.append('K_POINTS crystal\n') 

1452 pwi.append(f'{len(kgrid)}\n') 

1453 for k in kgrid: 

1454 pwi.append(f'{k[0]:.14f} {k[1]:.14f} {k[2]:.14f} {k[3]:.14f}\n') 

1455 pwi.append('\n') 

1456 else: 

1457 pwi.append('K_POINTS automatic\n') 

1458 pwi.append( 

1459 f'{kgrid[0]} {kgrid[1]} {kgrid[2]} ' 

1460 f' {koffset[0]:d} {koffset[1]:d} {koffset[2]:d}\n' 

1461 ) 

1462 pwi.append('\n') 

1463 

1464 # CELL block, if required 

1465 if input_parameters['SYSTEM']['ibrav'] == 0: 

1466 pwi.append('CELL_PARAMETERS angstrom\n') 

1467 pwi.append( 

1468 '{cell[0][0]:.14f} {cell[0][1]:.14f} {cell[0][2]:.14f}\n' 

1469 '{cell[1][0]:.14f} {cell[1][1]:.14f} {cell[1][2]:.14f}\n' 

1470 '{cell[2][0]:.14f} {cell[2][1]:.14f} {cell[2][2]:.14f}\n' 

1471 ''.format(cell=atoms.cell) 

1472 ) 

1473 pwi.append('\n') 

1474 

1475 # Positions - already constructed, but must appear after namelist 

1476 if crystal_coordinates: 

1477 pwi.append('ATOMIC_POSITIONS crystal\n') 

1478 else: 

1479 pwi.append('ATOMIC_POSITIONS angstrom\n') 

1480 pwi.extend(atomic_positions_str) 

1481 pwi.append('\n') 

1482 

1483 # DONE! 

1484 fd.write(''.join(pwi)) 

1485 

1486 if additional_cards: 

1487 if isinstance(additional_cards, list): 

1488 additional_cards = '\n'.join(additional_cards) 

1489 additional_cards += '\n' 

1490 

1491 fd.write(additional_cards) 

1492 

1493 

1494@writer 

1495def write_espresso_ph( 

1496 fd, input_data=None, qpts=None, nat_todo_indices=None, **kwargs 

1497) -> None: 

1498 """ 

1499 Function that write the input file for a ph.x calculation. Normal namelist 

1500 cards are passed in the input_data dictionary. Which can be either nested 

1501 or flat, ASE style. The q-points are passed in the qpts list. If qplot is 

1502 set to True then qpts is expected to be a list of list|tuple of length 4. 

1503 Where the first three elements are the coordinates of the q-point in units 

1504 of 2pi/alat and the last element is the weight of the q-point. if qplot is 

1505 set to False then qpts is expected to be a simple list of length 4 (single 

1506 q-point). Finally if ldisp is set to True, the above is discarded and the 

1507 q-points are read from the nq1, nq2, nq3 cards in the input_data dictionary. 

1508 

1509 Additionally, a nat_todo_indices kwargs (list[int]) can be specified in the 

1510 kwargs. It will be used if nat_todo is set to True in the input_data 

1511 dictionary. 

1512 

1513 Globally, this function follows the convention set in the ph.x documentation 

1514 (https://www.quantum-espresso.org/Doc/INPUT_PH.html) 

1515 

1516 Parameters 

1517 ---------- 

1518 fd 

1519 The file descriptor of the input file. 

1520 

1521 kwargs 

1522 kwargs dictionary possibly containing the following keys: 

1523 

1524 - input_data: dict 

1525 - qpts: list[list[float]] | list[tuple[float]] | list[float] 

1526 - nat_todo_indices: list[int] 

1527 

1528 Returns 

1529 ------- 

1530 None 

1531 """ 

1532 

1533 input_data = Namelist(input_data) 

1534 input_data.to_nested('ph', **kwargs) 

1535 

1536 input_ph = input_data['inputph'] 

1537 

1538 inp_nat_todo = input_ph.get('nat_todo', 0) 

1539 qpts = qpts or (0, 0, 0) 

1540 

1541 pwi = input_data.to_string() 

1542 

1543 fd.write(pwi) 

1544 

1545 qplot = input_ph.get('qplot', False) 

1546 ldisp = input_ph.get('ldisp', False) 

1547 

1548 if qplot: 

1549 fd.write(f'{len(qpts)}\n') 

1550 for qpt in qpts: 

1551 fd.write(f'{qpt[0]:0.8f} {qpt[1]:0.8f} {qpt[2]:0.8f} {qpt[3]:1d}\n') 

1552 elif not (qplot or ldisp): 

1553 fd.write(f'{qpts[0]:0.8f} {qpts[1]:0.8f} {qpts[2]:0.8f}\n') 

1554 if inp_nat_todo: 

1555 tmp = [str(i) for i in nat_todo_indices] 

1556 fd.write(' '.join(tmp)) 

1557 fd.write('\n') 

1558 

1559 

1560class _PHHelper: 

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

1562 

1563 def __init__(self, fdo_lines): 

1564 self.fdo_lines = fdo_lines 

1565 self.n_lines = len(fdo_lines) 

1566 

1567 def _read_qpoints(self, idx): 

1568 match = re.findall(self.freg, self.fdo_lines[idx]) 

1569 return tuple(round(float(x), 7) for x in match) 

1570 

1571 def _read_kpoints(self, idx): 

1572 n_kpts = int(re.findall(self.freg, self.fdo_lines[idx])[0]) 

1573 kpts = [] 

1574 for line in self.fdo_lines[idx + 2 : idx + 2 + n_kpts]: 

1575 if bool(re.search(r'^\s*k\(.*wk', line)): 

1576 kpts.append( 

1577 [ 

1578 round(float(x), 7) 

1579 for x in re.findall(self.freg, line)[1:] 

1580 ] 

1581 ) 

1582 return np.array(kpts) 

1583 

1584 def _read_repr(self, idx): 

1585 n_repr, curr, n = ( 

1586 int(re.findall(self.freg, self.fdo_lines[idx])[0]), 

1587 0, 

1588 0, 

1589 ) 

1590 representations = {} 

1591 while idx + n < self.n_lines: 

1592 if re.search(r'^\s*Representation.*modes', self.fdo_lines[idx + n]): 

1593 curr = int(re.findall(self.freg, self.fdo_lines[idx + n])[0]) 

1594 representations[curr] = {'done': False, 'modes': []} 

1595 if re.search( 

1596 r'Calculated\s*using\s*symmetry', self.fdo_lines[idx + n] 

1597 ) or re.search(r'-\s*Done\s*$', self.fdo_lines[idx + n]): 

1598 representations[curr]['done'] = True 

1599 if re.search( 

1600 r'(?i)^\s*(mode\s*#\s*\d\s*)+', self.fdo_lines[idx + n] 

1601 ): 

1602 representations[curr]['modes'] = self._read_modes(idx + n) 

1603 if curr == n_repr: 

1604 break 

1605 n += 1 

1606 return representations 

1607 

1608 def _read_modes(self, idx): 

1609 n = 1 

1610 n_modes = len(re.findall(r'mode', self.fdo_lines[idx])) 

1611 modes = [] 

1612 while not modes or bool(re.match(r'^\s*\(', self.fdo_lines[idx + n])): 

1613 tmp = re.findall(self.freg, self.fdo_lines[idx + n]) 

1614 modes.append([round(float(x), 5) for x in tmp]) 

1615 n += 1 

1616 return np.hsplit(np.array(modes), n_modes) 

1617 

1618 def _read_eqpoints(self, idx): 

1619 n_star = int(re.findall(self.freg, self.fdo_lines[idx])[0]) 

1620 return np.loadtxt( 

1621 self.fdo_lines[idx + 2 : idx + 2 + n_star], usecols=(1, 2, 3) 

1622 ).reshape(-1, 3) 

1623 

1624 def _read_freqs(self, idx): 

1625 n = 0 

1626 freqs = [] 

1627 stop = 0 

1628 while not freqs or stop < 2: 

1629 if bool(re.search(r'^\s*freq', self.fdo_lines[idx + n])): 

1630 tmp = re.findall(self.freg, self.fdo_lines[idx + n])[1] 

1631 freqs.append(float(tmp)) 

1632 if bool(re.search(r'\*{5,}', self.fdo_lines[idx + n])): 

1633 stop += 1 

1634 n += 1 

1635 return np.array(freqs) 

1636 

1637 def _read_sym(self, idx): 

1638 n = 1 

1639 sym = {} 

1640 while bool(re.match(r'^\s*freq', self.fdo_lines[idx + n])): 

1641 r = re.findall('\\d+', self.fdo_lines[idx + n]) 

1642 r = tuple(range(int(r[0]), int(r[1]) + 1)) 

1643 sym[r] = self.fdo_lines[idx + n].split('-->')[1].strip() 

1644 sym[r] = re.sub(r'\s+', ' ', sym[r]) 

1645 n += 1 

1646 return sym 

1647 

1648 def _read_epsil(self, idx): 

1649 epsil = np.zeros((3, 3)) 

1650 for n in range(1, 4): 

1651 tmp = re.findall(self.freg, self.fdo_lines[idx + n]) 

1652 epsil[n - 1] = [round(float(x), 9) for x in tmp] 

1653 return epsil 

1654 

1655 def _read_born(self, idx): 

1656 n = 1 

1657 born = [] 

1658 while idx + n < self.n_lines: 

1659 if re.search(r'^\s*atom\s*\d\s*\S', self.fdo_lines[idx + n]): 

1660 pass 

1661 elif re.search(r'^\s*E\*?(x|y|z)\s*\(', self.fdo_lines[idx + n]): 

1662 tmp = re.findall(self.freg, self.fdo_lines[idx + n]) 

1663 born.append([round(float(x), 5) for x in tmp]) 

1664 else: 

1665 break 

1666 n += 1 

1667 born = np.array(born) 

1668 return np.vsplit(born, len(born) // 3) 

1669 

1670 def _read_born_dfpt(self, idx): 

1671 n = 1 

1672 born = [] 

1673 while idx + n < self.n_lines: 

1674 if re.search(r'^\s*atom\s*\d\s*\S', self.fdo_lines[idx + n]): 

1675 pass 

1676 elif re.search(r'^\s*P(x|y|z)\s*\(', self.fdo_lines[idx + n]): 

1677 tmp = re.findall(self.freg, self.fdo_lines[idx + n]) 

1678 born.append([round(float(x), 5) for x in tmp]) 

1679 else: 

1680 break 

1681 n += 1 

1682 born = np.array(born) 

1683 return np.vsplit(born, len(born) // 3) 

1684 

1685 def _read_pola(self, idx): 

1686 pola = np.zeros((3, 3)) 

1687 for n in range(1, 4): 

1688 tmp = re.findall(self.freg, self.fdo_lines[idx + n])[:3] 

1689 pola[n - 1] = [round(float(x), 2) for x in tmp] 

1690 return pola 

1691 

1692 def _read_positions(self, idx): 

1693 positions = [] 

1694 symbols = [] 

1695 n = 1 

1696 while re.findall(r'^\s*\d+', self.fdo_lines[idx + n]): 

1697 symbols.append(self.fdo_lines[idx + n].split()[1]) 

1698 positions.append( 

1699 [ 

1700 round(float(x), 5) 

1701 for x in re.findall(self.freg, self.fdo_lines[idx + n])[-3:] 

1702 ] 

1703 ) 

1704 n += 1 

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

1706 atoms.pbc = True 

1707 return atoms 

1708 

1709 def _read_alat(self, idx): 

1710 return round(float(re.findall(self.freg, self.fdo_lines[idx])[1]), 5) 

1711 

1712 def _read_cell(self, idx): 

1713 cell = [] 

1714 n = 1 

1715 while re.findall(r'^\s*a\(\d\)', self.fdo_lines[idx + n]): 

1716 cell.append( 

1717 [ 

1718 round(float(x), 4) 

1719 for x in re.findall(self.freg, self.fdo_lines[idx + n])[-3:] 

1720 ] 

1721 ) 

1722 n += 1 

1723 return np.array(cell) 

1724 

1725 def _read_electron_phonon(self, idx): 

1726 results = {} 

1727 

1728 broad_re = r'^\s*Gaussian\s*Broadening:\s+([\d.]+)\s+Ry, ngauss=\s+\d+' 

1729 dos_re = ( 

1730 r'^\s*DOS\s*=\s*([\d.]+)\s*states/' 

1731 r'spin/Ry/Unit\s*Cell\s*at\s*Ef=\s+([\d.]+)\s+eV' 

1732 ) 

1733 lg_re = r'^\s*lambda\(\s+(\d+)\)=\s+([\d.]+)\s+gamma=\s+([\d.]+)\s+GHz' 

1734 end_re = r'^\s*Number\s*of\s*q\s*in\s*the\s*star\s*=\s+(\d+)$' 

1735 

1736 lambdas = [] 

1737 gammas = [] 

1738 

1739 current = None 

1740 

1741 n = 1 

1742 while idx + n < self.n_lines: 

1743 line = self.fdo_lines[idx + n] 

1744 

1745 broad_match = re.match(broad_re, line) 

1746 dos_match = re.match(dos_re, line) 

1747 lg_match = re.match(lg_re, line) 

1748 end_match = re.match(end_re, line) 

1749 

1750 if broad_match: 

1751 if lambdas: 

1752 results[current]['lambdas'] = lambdas 

1753 results[current]['gammas'] = gammas 

1754 lambdas = [] 

1755 gammas = [] 

1756 current = float(broad_match[1]) 

1757 results[current] = {} 

1758 elif dos_match: 

1759 results[current]['dos'] = float(dos_match[1]) 

1760 results[current]['fermi'] = float(dos_match[2]) 

1761 elif lg_match: 

1762 lambdas.append(float(lg_match[2])) 

1763 gammas.append(float(lg_match[3])) 

1764 

1765 if end_match: 

1766 results[current]['lambdas'] = lambdas 

1767 results[current]['gammas'] = gammas 

1768 break 

1769 

1770 n += 1 

1771 

1772 return results 

1773 

1774 

1775@reader 

1776def read_espresso_ph(fileobj): 

1777 """ 

1778 Function that reads the output of a ph.x calculation. 

1779 It returns a dictionary where each q-point number is a key and 

1780 the value is a dictionary with the following keys if available: 

1781 

1782 - qpoints: The q-point in cartesian coordinates. 

1783 - kpoints: The k-points in cartesian coordinates. 

1784 - dieltensor: The dielectric tensor. 

1785 - borneffcharge: The effective Born charges. 

1786 - borneffcharge_dfpt: The effective Born charges from DFPT. 

1787 - polarizability: The polarizability tensor. 

1788 - modes: The phonon modes. 

1789 - eqpoints: The symmetrically equivalent q-points. 

1790 - freqs: The phonon frequencies. 

1791 - mode_symmetries: The symmetries of the modes. 

1792 - atoms: The atoms object. 

1793 

1794 Some notes: 

1795 

1796 - For some reason, the cell is not defined to high level of 

1797 precision in ph.x outputs. Be careful when using the atoms object 

1798 retrieved from this function. 

1799 - This function can be called on incomplete calculations i.e. 

1800 if the calculation couldn't diagonalize the dynamical matrix 

1801 for some q-points, the results for the other q-points will 

1802 still be returned. 

1803 

1804 Parameters 

1805 ---------- 

1806 fileobj 

1807 The file descriptor of the output file. 

1808 

1809 Returns 

1810 ------- 

1811 dict 

1812 The results dictionnary as described above. 

1813 """ 

1814 

1815 QPOINTS = r'(?i)^\s*Calculation\s*of\s*q' 

1816 NKPTS = r'(?i)^\s*number\s*of\s*k\s*points\s*' 

1817 DIEL = r'(?i)^\s*Dielectric\s*constant\s*in\s*cartesian\s*axis\s*$' 

1818 BORN = r'(?i)^\s*Effective\s*charges\s*\(d\s*Force\s*/\s*dE\)' 

1819 POLA = r'(?i)^\s*Polarizability\s*(a.u.)\^3' 

1820 REPR = r'(?i)^\s*There\s*are\s*\d+\s*irreducible\s*representations\s*$' 

1821 EQPOINTS = r'(?i)^\s*Number\s*of\s*q\s*in\s*the\s*star\s*=\s*' 

1822 DIAG = r'(?i)^\s*Diagonalizing\s*the\s*dynamical\s*matrix\s*$' 

1823 MODE_SYM = r'(?i)^\s*Mode\s*symmetry,\s*' 

1824 BORN_DFPT = r'(?i)^\s*Effective\s*charges\s*\(d\s*P\s*/\s*du\)' 

1825 POSITIONS = r'(?i)^\s*site\s*n\..*\(alat\s*units\)' 

1826 ALAT = r'(?i)^\s*celldm\(1\)=' 

1827 CELL = r'^\s*crystal\s*axes:\s*\(cart.\s*coord.\s*in\s*units\s*of\s*alat\)' 

1828 ELECTRON_PHONON = r'(?i)^\s*electron-phonon\s*interaction\s*...\s*$' 

1829 

1830 output = { 

1831 QPOINTS: [], 

1832 NKPTS: [], 

1833 DIEL: [], 

1834 BORN: [], 

1835 BORN_DFPT: [], 

1836 POLA: [], 

1837 REPR: [], 

1838 EQPOINTS: [], 

1839 DIAG: [], 

1840 MODE_SYM: [], 

1841 POSITIONS: [], 

1842 ALAT: [], 

1843 CELL: [], 

1844 ELECTRON_PHONON: [], 

1845 } 

1846 

1847 names = { 

1848 QPOINTS: 'qpoints', 

1849 NKPTS: 'kpoints', 

1850 DIEL: 'dieltensor', 

1851 BORN: 'borneffcharge', 

1852 BORN_DFPT: 'borneffcharge_dfpt', 

1853 POLA: 'polarizability', 

1854 REPR: 'representations', 

1855 EQPOINTS: 'eqpoints', 

1856 DIAG: 'freqs', 

1857 MODE_SYM: 'mode_symmetries', 

1858 POSITIONS: 'positions', 

1859 ALAT: 'alat', 

1860 CELL: 'cell', 

1861 ELECTRON_PHONON: 'ep_data', 

1862 } 

1863 

1864 unique = { 

1865 QPOINTS: True, 

1866 NKPTS: False, 

1867 DIEL: True, 

1868 BORN: True, 

1869 BORN_DFPT: True, 

1870 POLA: True, 

1871 REPR: True, 

1872 EQPOINTS: True, 

1873 DIAG: True, 

1874 MODE_SYM: True, 

1875 POSITIONS: True, 

1876 ALAT: True, 

1877 CELL: True, 

1878 ELECTRON_PHONON: True, 

1879 } 

1880 

1881 results = {} 

1882 fdo_lines = [i for i in fileobj.read().splitlines() if i] 

1883 n_lines = len(fdo_lines) 

1884 

1885 for idx, line in enumerate(fdo_lines): 

1886 for key in output: 

1887 if bool(re.match(key, line)): 

1888 output[key].append(idx) 

1889 

1890 output = {key: np.array(value) for key, value in output.items()} 

1891 

1892 helper = _PHHelper(fdo_lines) 

1893 

1894 properties = { 

1895 NKPTS: helper._read_kpoints, 

1896 DIEL: helper._read_epsil, 

1897 BORN: helper._read_born, 

1898 BORN_DFPT: helper._read_born_dfpt, 

1899 POLA: helper._read_pola, 

1900 REPR: helper._read_repr, 

1901 EQPOINTS: helper._read_eqpoints, 

1902 DIAG: helper._read_freqs, 

1903 MODE_SYM: helper._read_sym, 

1904 POSITIONS: helper._read_positions, 

1905 ALAT: helper._read_alat, 

1906 CELL: helper._read_cell, 

1907 ELECTRON_PHONON: helper._read_electron_phonon, 

1908 } 

1909 

1910 iblocks = np.append(output[QPOINTS], n_lines) 

1911 

1912 for qnum, (past, future) in enumerate(zip(iblocks[:-1], iblocks[1:])): 

1913 qpoint = helper._read_qpoints(past) 

1914 results[qnum + 1] = curr_result = {'qpoint': qpoint} 

1915 for prop in properties: 

1916 p = (past < output[prop]) & (output[prop] < future) 

1917 selected = output[prop][p] 

1918 if len(selected) == 0: 

1919 continue 

1920 if unique[prop]: 

1921 idx = output[prop][p][-1] 

1922 curr_result[names[prop]] = properties[prop](idx) 

1923 else: 

1924 tmp = {k + 1: 0 for k in range(len(selected))} 

1925 for k, idx in enumerate(selected): 

1926 tmp[k + 1] = properties[prop](idx) 

1927 curr_result[names[prop]] = tmp 

1928 alat = curr_result.pop('alat', 1.0) 

1929 atoms = curr_result.pop('positions', None) 

1930 cell = curr_result.pop('cell', np.eye(3)) 

1931 if atoms: 

1932 atoms.positions *= alat * units['Bohr'] 

1933 atoms.cell = cell * alat * units['Bohr'] 

1934 atoms.wrap() 

1935 curr_result['atoms'] = atoms 

1936 

1937 return results 

1938 

1939 

1940@writer 

1941def write_fortran_namelist( 

1942 fd, input_data=None, binary=None, additional_cards=None, **kwargs 

1943) -> None: 

1944 """ 

1945 Function which writes input for simple espresso binaries. 

1946 List of supported binaries are in the espresso_keys.py file. 

1947 Non-exhaustive list (to complete) 

1948 

1949 Note: "EOF" is appended at the end of the file. 

1950 (https://lists.quantum-espresso.org/pipermail/users/2020-November/046269.html) 

1951 

1952 Additional fields are written 'as is' in the input file. It is expected 

1953 to be a string or a list of strings. 

1954 

1955 Parameters 

1956 ---------- 

1957 fd 

1958 The file descriptor of the input file. 

1959 input_data: dict 

1960 A flat or nested dictionary with input parameters for the binary.x 

1961 binary: str 

1962 Name of the binary 

1963 additional_cards: str | list[str] 

1964 Additional fields to be written at the end of the input file, after 

1965 the namelist. It is expected to be a string or a list of strings. 

1966 

1967 Returns 

1968 ------- 

1969 None 

1970 """ 

1971 input_data = Namelist(input_data) 

1972 

1973 if binary: 

1974 input_data.to_nested(binary, **kwargs) 

1975 

1976 pwi = input_data.to_string() 

1977 

1978 fd.write(pwi) 

1979 

1980 if additional_cards: 

1981 if isinstance(additional_cards, list): 

1982 additional_cards = '\n'.join(additional_cards) 

1983 additional_cards += '\n' 

1984 

1985 fd.write(additional_cards) 

1986 

1987 fd.write('EOF') 

1988 

1989 

1990def _get_energy(pwo_lines, energy_index): 

1991 return float(pwo_lines[energy_index].split()[-2]) * units['Ry'] 

1992 

1993 

1994def _get_forces(pwo_lines, force_index, natoms): 

1995 # Before QE 5.3 'negative rho' added 2 lines before forces 

1996 # Use exact lines to stop before 'non-local' forces 

1997 # in high verbosity 

1998 if not pwo_lines[force_index + 2].strip(): 

1999 force_index += 4 

2000 else: 

2001 force_index += 2 

2002 # assume contiguous 

2003 forces = [ 

2004 [float(x) for x in force_line.split()[-3:]] 

2005 for force_line in pwo_lines[force_index : force_index + natoms] 

2006 ] 

2007 return np.array(forces) * units['Ry'] / units['Bohr'] 

2008 

2009 

2010def _get_stress(pwo_lines, stress_index): 

2011 sxx, sxy, sxz = pwo_lines[stress_index + 1].split()[:3] 

2012 _, syy, syz = pwo_lines[stress_index + 2].split()[:3] 

2013 _, _, szz = pwo_lines[stress_index + 3].split()[:3] 

2014 stress = np.array([sxx, syy, szz, syz, sxz, sxy], dtype=float) 

2015 # sign convention is opposite of ase 

2016 stress *= -1 * units['Ry'] / (units['Bohr'] ** 3) 

2017 return stress 

2018 

2019 

2020def _get_magmoms(pwo_lines, magmoms_index, natoms): 

2021 return [ 

2022 float(mag_line.split()[-1]) 

2023 for mag_line in pwo_lines[ 

2024 magmoms_index + 1 : magmoms_index + 1 + natoms 

2025 ] 

2026 ]