Coverage for ase/io/abinit.py: 85.32%

477 statements  

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

1import os 

2import re 

3from glob import glob 

4from os.path import join 

5from pathlib import Path 

6 

7import numpy as np 

8 

9from ase import Atoms 

10from ase.calculators.calculator import all_properties 

11from ase.calculators.singlepoint import SinglePointCalculator 

12from ase.data import chemical_symbols 

13from ase.units import Bohr, Hartree, fs 

14 

15 

16def read_abinit_in(fd): 

17 """Import ABINIT input file. 

18 

19 Reads cell, atom positions, etc. from abinit input file 

20 """ 

21 

22 tokens = [] 

23 

24 for line in fd: 

25 meat = line.split('#', 1)[0] 

26 tokens += meat.lower().split() 

27 

28 # note that the file can not be scanned sequentially 

29 

30 index = tokens.index('acell') 

31 unit = 1.0 

32 if tokens[index + 4].lower()[:3] != 'ang': 

33 unit = Bohr 

34 acell = [ 

35 unit * float(tokens[index + 1]), 

36 unit * float(tokens[index + 2]), 

37 unit * float(tokens[index + 3]), 

38 ] 

39 

40 index = tokens.index('natom') 

41 natom = int(tokens[index + 1]) 

42 

43 index = tokens.index('ntypat') 

44 ntypat = int(tokens[index + 1]) 

45 

46 index = tokens.index('typat') 

47 typat = [] 

48 while len(typat) < natom: 

49 token = tokens[index + 1] 

50 if '*' in token: # e.g. typat 4*1 3*2 ... 

51 nrepeat, typenum = token.split('*') 

52 typat += [int(typenum)] * int(nrepeat) 

53 else: 

54 typat.append(int(token)) 

55 index += 1 

56 assert natom == len(typat) 

57 

58 index = tokens.index('znucl') 

59 znucl = [] 

60 for i in range(ntypat): 

61 znucl.append(int(tokens[index + 1 + i])) 

62 

63 index = tokens.index('rprim') 

64 rprim = [] 

65 for i in range(3): 

66 rprim.append( 

67 [ 

68 acell[i] * float(tokens[index + 3 * i + 1]), 

69 acell[i] * float(tokens[index + 3 * i + 2]), 

70 acell[i] * float(tokens[index + 3 * i + 3]), 

71 ] 

72 ) 

73 

74 # create a list with the atomic numbers 

75 numbers = [] 

76 for i in range(natom): 

77 ii = typat[i] - 1 

78 numbers.append(znucl[ii]) 

79 

80 # now the positions of the atoms 

81 if 'xred' in tokens: 

82 index = tokens.index('xred') 

83 xred = [] 

84 for i in range(natom): 

85 xred.append( 

86 [ 

87 float(tokens[index + 3 * i + 1]), 

88 float(tokens[index + 3 * i + 2]), 

89 float(tokens[index + 3 * i + 3]), 

90 ] 

91 ) 

92 atoms = Atoms( 

93 cell=rprim, scaled_positions=xred, numbers=numbers, pbc=True 

94 ) 

95 else: 

96 if 'xcart' in tokens: 

97 index = tokens.index('xcart') 

98 unit = Bohr 

99 elif 'xangst' in tokens: 

100 unit = 1.0 

101 index = tokens.index('xangst') 

102 else: 

103 raise OSError( 

104 'No xred, xcart, or xangs keyword in abinit input file' 

105 ) 

106 

107 xangs = [] 

108 for i in range(natom): 

109 xangs.append( 

110 [ 

111 unit * float(tokens[index + 3 * i + 1]), 

112 unit * float(tokens[index + 3 * i + 2]), 

113 unit * float(tokens[index + 3 * i + 3]), 

114 ] 

115 ) 

116 atoms = Atoms(cell=rprim, positions=xangs, numbers=numbers, pbc=True) 

117 

118 try: 

119 ii = tokens.index('nsppol') 

120 except ValueError: 

121 nsppol = None 

122 else: 

123 nsppol = int(tokens[ii + 1]) 

124 

125 if nsppol == 2: 

126 index = tokens.index('spinat') 

127 magmoms = [float(tokens[index + 3 * i + 3]) for i in range(natom)] 

128 atoms.set_initial_magnetic_moments(magmoms) 

129 

130 assert len(atoms) == natom 

131 return atoms 

132 

133 

134keys_with_units = { 

135 'toldfe': 'eV', 

136 'tsmear': 'eV', 

137 'paoenergyshift': 'eV', 

138 'zmunitslength': 'Bohr', 

139 'zmunitsangle': 'rad', 

140 'zmforcetollength': 'eV/Ang', 

141 'zmforcetolangle': 'eV/rad', 

142 'zmmaxdispllength': 'Ang', 

143 'zmmaxdisplangle': 'rad', 

144 'ecut': 'eV', 

145 'pawecutdg': 'eV', 

146 'dmenergytolerance': 'eV', 

147 'electronictemperature': 'eV', 

148 'oneta': 'eV', 

149 'onetaalpha': 'eV', 

150 'onetabeta': 'eV', 

151 'onrclwf': 'Ang', 

152 'onchemicalpotentialrc': 'Ang', 

153 'onchemicalpotentialtemperature': 'eV', 

154 'mdmaxcgdispl': 'Ang', 

155 'mdmaxforcetol': 'eV/Ang', 

156 'mdmaxstresstol': 'eV/Ang**3', 

157 'mdlengthtimestep': 'fs', 

158 'mdinitialtemperature': 'eV', 

159 'mdtargettemperature': 'eV', 

160 'mdtargetpressure': 'eV/Ang**3', 

161 'mdnosemass': 'eV*fs**2', 

162 'mdparrinellorahmanmass': 'eV*fs**2', 

163 'mdtaurelax': 'fs', 

164 'mdbulkmodulus': 'eV/Ang**3', 

165 'mdfcdispl': 'Ang', 

166 'warningminimumatomicdistance': 'Ang', 

167 'rcspatial': 'Ang', 

168 'kgridcutoff': 'Ang', 

169 'latticeconstant': 'Ang', 

170} 

171 

172 

173def write_abinit_in(fd, atoms, param=None, species=None, pseudos=None): 

174 from ase.calculators.calculator import kpts2mp 

175 

176 if param is None: 

177 param = {} 

178 

179 if species is None: 

180 species = sorted(set(atoms.numbers)) 

181 

182 inp = dict(param) 

183 xc = inp.pop('xc', 'LDA') 

184 for key in ['smearing', 'kpts', 'pps', 'raw']: 

185 inp.pop(key, None) 

186 

187 smearing = param.get('smearing') 

188 if 'tsmear' in param or 'occopt' in param: 

189 assert smearing is None 

190 

191 if smearing is not None: 

192 inp['occopt'] = {'fermi-dirac': 3, 'gaussian': 7}[smearing[0].lower()] 

193 inp['tsmear'] = smearing[1] 

194 

195 inp['natom'] = len(atoms) 

196 

197 if 'nbands' in param: 

198 inp['nband'] = param['nbands'] 

199 del inp['nbands'] 

200 

201 # ixc is set from paw/xml file. Ignore 'xc' setting then. 

202 if param.get('pps') not in ['pawxml']: 

203 if 'ixc' not in param: 

204 inp['ixc'] = { 

205 'LDA': 7, 

206 'PBE': 11, 

207 'revPBE': 14, 

208 'RPBE': 15, 

209 'WC': 23, 

210 }[xc] 

211 

212 magmoms = atoms.get_initial_magnetic_moments() 

213 if magmoms.any(): 

214 inp['nsppol'] = 2 

215 fd.write('spinat\n') 

216 for n, M in enumerate(magmoms): 

217 fd.write(f'{0:.14f} {0:.14f} {M:.14f}\n') 

218 else: 

219 inp['nsppol'] = 1 

220 

221 if param.get('kpts') is not None: 

222 mp = kpts2mp(atoms, param['kpts']) 

223 fd.write('kptopt 1\n') 

224 fd.write('ngkpt %d %d %d\n' % tuple(mp)) 

225 fd.write('nshiftk 1\n') 

226 fd.write('shiftk\n') 

227 fd.write('%.1f %.1f %.1f\n' % tuple((np.array(mp) + 1) % 2 * 0.5)) 

228 

229 valid_lists = (list, np.ndarray) 

230 for key in sorted(inp): 

231 value = inp[key] 

232 unit = keys_with_units.get(key) 

233 if unit is not None: 

234 if 'fs**2' in unit: 

235 value /= fs**2 

236 elif 'fs' in unit: 

237 value /= fs 

238 if isinstance(value, valid_lists): 

239 if isinstance(value[0], valid_lists): 

240 fd.write(f'{key}\n') 

241 for dim in value: 

242 write_list(fd, dim, unit) 

243 else: 

244 fd.write(f'{key}\n') 

245 write_list(fd, value, unit) 

246 else: 

247 if unit is None: 

248 fd.write(f'{key} {value}\n') 

249 else: 

250 fd.write(f'{key} {value} {unit}\n') 

251 

252 if param.get('raw') is not None: 

253 if isinstance(param['raw'], str): 

254 raise TypeError( 

255 'The raw parameter is a single string; expected ' 

256 'a sequence of lines' 

257 ) 

258 for line in param['raw']: 

259 if isinstance(line, tuple): 

260 fd.write(' '.join([f'{x}' for x in line]) + '\n') 

261 else: 

262 fd.write(f'{line}\n') 

263 

264 fd.write('#Definition of the unit cell\n') 

265 fd.write('acell\n') 

266 fd.write(f'{1.0:.14f} {1.0:.14f} {1.0:.14f} Angstrom\n') 

267 fd.write('rprim\n') 

268 if atoms.cell.rank != 3: 

269 raise RuntimeError( 

270 'Abinit requires a 3D cell, but cell is {}'.format(atoms.cell) 

271 ) 

272 for v in atoms.cell: 

273 fd.write('%.14f %.14f %.14f\n' % tuple(v)) 

274 

275 fd.write('chkprim 0 # Allow non-primitive cells\n') 

276 

277 fd.write('#Definition of the atom types\n') 

278 fd.write('ntypat %d\n' % (len(species))) 

279 fd.write('znucl {}\n'.format(' '.join(str(Z) for Z in species))) 

280 fd.write('#Enumerate different atomic species\n') 

281 fd.write('typat') 

282 fd.write('\n') 

283 

284 types = [] 

285 for Z in atoms.numbers: 

286 for n, Zs in enumerate(species): 

287 if Z == Zs: 

288 types.append(n + 1) 

289 n_entries_int = 20 # integer entries per line 

290 for n, type in enumerate(types): 

291 fd.write(' %d' % (type)) 

292 if n > 1 and ((n % n_entries_int) == 1): 

293 fd.write('\n') 

294 fd.write('\n') 

295 

296 if pseudos is not None: 

297 listing = ',\n'.join(pseudos) 

298 line = f'pseudos "{listing}"\n' 

299 fd.write(line) 

300 

301 fd.write('#Definition of the atoms\n') 

302 fd.write('xcart\n') 

303 for pos in atoms.positions / Bohr: 

304 fd.write('%.14f %.14f %.14f\n' % tuple(pos)) 

305 

306 fd.write( 

307 'chkexit 1 # abinit.exit file in the running ' 

308 'directory terminates after the current SCF\n' 

309 ) 

310 

311 

312def write_list(fd, value, unit): 

313 for element in value: 

314 fd.write(f'{element} ') 

315 if unit is not None: 

316 fd.write(f'{unit}') 

317 fd.write('\n') 

318 

319 

320def read_stress(fd): 

321 # sigma(1 1)= 4.02063464E-04 sigma(3 2)= 0.00000000E+00 

322 # sigma(2 2)= 4.02063464E-04 sigma(3 1)= 0.00000000E+00 

323 # sigma(3 3)= 4.02063464E-04 sigma(2 1)= 0.00000000E+00 

324 pat = re.compile(r'\s*sigma\(\d \d\)=\s*(\S+)\s*sigma\(\d \d\)=\s*(\S+)') 

325 stress = np.empty(6) 

326 for i in range(3): 

327 line = next(fd) 

328 m = pat.match(line) 

329 if m is None: 

330 # Not a real value error. What should we raise? 

331 raise ValueError( 

332 'Line {!r} does not match stress pattern {!r}'.format(line, pat) 

333 ) 

334 stress[i] = float(m.group(1)) 

335 stress[i + 3] = float(m.group(2)) 

336 unit = Hartree / Bohr**3 

337 return stress * unit 

338 

339 

340def consume_multiline(fd, headerline, nvalues, dtype): 

341 """Parse abinit-formatted "header + values" sections. 

342 

343 Example: 

344 

345 typat 1 1 1 1 1 

346 1 1 1 1 

347 """ 

348 tokens = headerline.split() 

349 assert tokens[0].isalpha() 

350 

351 values = tokens[1:] 

352 while len(values) < nvalues: 

353 line = next(fd) 

354 values.extend(line.split()) 

355 assert len(values) == nvalues 

356 return np.array(values).astype(dtype) 

357 

358 

359def read_abinit_out(fd): 

360 results = {} 

361 

362 def skipto(string): 

363 for line in fd: 

364 if string in line: 

365 return line 

366 raise RuntimeError(f'Not found: {string}') 

367 

368 line = skipto('Version') 

369 m = re.match(r'\.*?Version\s+(\S+)\s+of ABINIT', line) 

370 assert m is not None 

371 version = m.group(1) 

372 results['version'] = version 

373 

374 use_v9_format = int(version.split('.', 1)[0]) >= 9 

375 

376 shape_vars = {} 

377 

378 skipto('echo values of preprocessed input variables') 

379 

380 for line in fd: 

381 if '===============' in line: 

382 break 

383 

384 tokens = line.split() 

385 if not tokens: 

386 continue 

387 

388 for key in ['natom', 'nkpt', 'nband', 'ntypat']: 

389 if tokens[0] == key: 

390 shape_vars[key] = int(tokens[1]) 

391 

392 if line.lstrip().startswith('typat'): # Avoid matching ntypat 

393 types = consume_multiline(fd, line, shape_vars['natom'], int) 

394 

395 if 'znucl' in line: 

396 znucl = consume_multiline(fd, line, shape_vars['ntypat'], float) 

397 

398 if 'rprim' in line: 

399 cell = consume_multiline(fd, line, 9, float) 

400 cell = cell.reshape(3, 3) 

401 

402 natoms = shape_vars['natom'] 

403 

404 # Skip ahead to results: 

405 for line in fd: 

406 if 'was not enough scf cycles to converge' in line: 

407 raise RuntimeError(line) 

408 if 'iterations are completed or convergence reached' in line: 

409 break 

410 else: 

411 raise RuntimeError('Cannot find results section') 

412 

413 def read_array(fd, nlines): 

414 arr = [] 

415 for i in range(nlines): 

416 line = next(fd) 

417 arr.append(line.split()[1:]) 

418 arr = np.array(arr).astype(float) 

419 return arr 

420 

421 if use_v9_format: 

422 energy_header = '--- !EnergyTerms' 

423 total_energy_name = 'total_energy_eV' 

424 

425 def parse_energy(line): 

426 return float(line.split(':')[1].strip()) 

427 else: 

428 energy_header = 'Components of total free energy (in Hartree) :' 

429 total_energy_name = '>>>>>>>>> Etotal' 

430 

431 def parse_energy(line): 

432 return float(line.rsplit('=', 2)[1]) * Hartree 

433 

434 for line in fd: 

435 if 'cartesian coordinates (angstrom) at end' in line: 

436 positions = read_array(fd, natoms) 

437 if 'cartesian forces (eV/Angstrom) at end' in line: 

438 results['forces'] = read_array(fd, natoms) 

439 if 'Cartesian components of stress tensor (hartree/bohr^3)' in line: 

440 results['stress'] = read_stress(fd) 

441 

442 if line.strip() == energy_header: 

443 # Header not to be confused with EnergyTermsDC, 

444 # therefore we don't use .startswith() 

445 energy = None 

446 for line in fd: 

447 # Which of the listed energies should we include? 

448 if total_energy_name in line: 

449 energy = parse_energy(line) 

450 break 

451 if energy is None: 

452 raise RuntimeError('No energy found in output') 

453 results['energy'] = results['free_energy'] = energy 

454 

455 if 'END DATASET(S)' in line: 

456 break 

457 

458 znucl_int = znucl.astype(int) 

459 znucl_int[znucl_int != znucl] = 0 # (Fractional Z) 

460 numbers = znucl_int[types - 1] 

461 

462 atoms = Atoms(numbers=numbers, positions=positions, cell=cell, pbc=True) 

463 

464 calc_results = { 

465 name: results[name] for name in set(all_properties) & set(results) 

466 } 

467 atoms.calc = SinglePointCalculator(atoms, **calc_results) 

468 atoms.calc.name = 'abinit' 

469 

470 results['atoms'] = atoms 

471 return results 

472 

473 

474def match_kpt_header(line): 

475 headerpattern = ( 

476 r'\s*kpt#\s*\S+\s*' 

477 r'nband=\s*(\d+),\s*' 

478 r'wtk=\s*(\S+?),\s*' 

479 r'kpt=\s*(\S+)+\s*(\S+)\s*(\S+)' 

480 ) 

481 m = re.match(headerpattern, line) 

482 assert m is not None, line 

483 nbands = int(m.group(1)) 

484 weight = float(m.group(2)) 

485 kvector = np.array(m.group(3, 4, 5)).astype(float) 

486 return nbands, weight, kvector 

487 

488 

489def read_eigenvalues_for_one_spin(fd, nkpts): 

490 

491 kpoint_weights = [] 

492 kpoint_coords = [] 

493 

494 eig_kn = [] 

495 for _ in range(nkpts): 

496 header = next(fd) 

497 nbands, weight, kvector = match_kpt_header(header) 

498 kpoint_coords.append(kvector) 

499 kpoint_weights.append(weight) 

500 

501 eig_n = [] 

502 while len(eig_n) < nbands: 

503 line = next(fd) 

504 tokens = line.split() 

505 values = np.array(tokens).astype(float) * Hartree 

506 eig_n.extend(values) 

507 assert len(eig_n) == nbands 

508 eig_kn.append(eig_n) 

509 assert nbands == len(eig_kn[0]) 

510 

511 kpoint_weights = np.array(kpoint_weights) 

512 kpoint_coords = np.array(kpoint_coords) 

513 eig_kn = np.array(eig_kn) 

514 return kpoint_coords, kpoint_weights, eig_kn 

515 

516 

517def read_eig(fd): 

518 line = next(fd) 

519 results = {} 

520 m = re.match(r'\s*Fermi \(or HOMO\) energy \(hartree\)\s*=\s*(\S+)', line) 

521 if m is not None: 

522 results['fermilevel'] = float(m.group(1)) * Hartree 

523 line = next(fd) 

524 

525 nspins = 1 

526 

527 m = re.match(r'\s*Magnetization \(Bohr magneton\)=\s*(\S+)', line) 

528 if m is not None: 

529 nspins = 2 

530 magmom = float(m.group(1)) 

531 results['magmom'] = magmom 

532 line = next(fd) 

533 

534 if 'Total spin up' in line: 

535 assert nspins == 2 

536 line = next(fd) 

537 

538 m = re.match( 

539 r'\s*Eigenvalues \(hartree\) for nkpt\s*=' 

540 r'\s*(\S+)\s*k\s*points', 

541 line, 

542 ) 

543 if 'SPIN' in line or 'spin' in line: 

544 # If using spinpol with fixed magmoms, we don't get the magmoms 

545 # listed before now. 

546 nspins = 2 

547 assert m is not None 

548 nkpts = int(m.group(1)) 

549 

550 eig_skn = [] 

551 

552 kpts, weights, eig_kn = read_eigenvalues_for_one_spin(fd, nkpts) 

553 nbands = eig_kn.shape[1] 

554 

555 eig_skn.append(eig_kn) 

556 if nspins == 2: 

557 line = next(fd) 

558 assert 'SPIN DOWN' in line 

559 _, _, eig_kn = read_eigenvalues_for_one_spin(fd, nkpts) 

560 assert eig_kn.shape == (nkpts, nbands) 

561 eig_skn.append(eig_kn) 

562 eig_skn = np.array(eig_skn) 

563 

564 eigshape = (nspins, nkpts, nbands) 

565 assert eig_skn.shape == eigshape, (eig_skn.shape, eigshape) 

566 

567 results['ibz_kpoints'] = kpts 

568 results['kpoint_weights'] = weights 

569 results['eigenvalues'] = eig_skn 

570 return results 

571 

572 

573def get_default_abinit_pp_paths(): 

574 return os.environ.get('ABINIT_PP_PATH', '.').split(':') 

575 

576 

577def prepare_abinit_input( 

578 directory, 

579 atoms, 

580 properties, 

581 parameters, 

582 pp_paths=None, 

583 raise_exception=True, 

584): 

585 directory = Path(directory) 

586 species = sorted(set(atoms.numbers)) 

587 if pp_paths is None: 

588 pp_paths = get_default_abinit_pp_paths() 

589 ppp = get_ppp_list( 

590 atoms, 

591 species, 

592 raise_exception=raise_exception, 

593 xc=parameters['xc'], 

594 pps=parameters['pps'], 

595 search_paths=pp_paths, 

596 ) 

597 

598 inputfile = directory / 'abinit.in' 

599 

600 # XXX inappropriate knowledge about choice of outputfile 

601 outputfile = directory / 'abinit.abo' 

602 

603 # Abinit will write to label.txtA if label.txt already exists, 

604 # so we remove it if it's there: 

605 if outputfile.exists(): 

606 outputfile.unlink() 

607 

608 with open(inputfile, 'w') as fd: 

609 write_abinit_in( 

610 fd, atoms, param=parameters, species=species, pseudos=ppp 

611 ) 

612 

613 

614def read_abinit_outputs(directory, label): 

615 directory = Path(directory) 

616 textfilename = directory / f'{label}.abo' 

617 results = {} 

618 with open(textfilename) as fd: 

619 dct = read_abinit_out(fd) 

620 results.update(dct) 

621 

622 # The eigenvalues section in the main file is shortened to 

623 # a limited number of kpoints. We read the complete one from 

624 # the EIG file then: 

625 with open(directory / f'{label}o_EIG') as fd: 

626 dct = read_eig(fd) 

627 results.update(dct) 

628 return results 

629 

630 

631def read_abinit_gsr(filename): 

632 import netCDF4 

633 

634 data = netCDF4.Dataset(filename) 

635 data.set_auto_mask(False) 

636 version = data.abinit_version 

637 

638 typat = data.variables['atom_species'][:] 

639 cell = data.variables['primitive_vectors'][:] * Bohr 

640 znucl = data.variables['atomic_numbers'][:] 

641 xred = data.variables['reduced_atom_positions'][:] 

642 

643 znucl_int = znucl.astype(int) 

644 znucl_int[znucl_int != znucl] = 0 # (Fractional Z) 

645 numbers = znucl_int[typat - 1] 

646 

647 atoms = Atoms(numbers=numbers, scaled_positions=xred, cell=cell, pbc=True) 

648 

649 results = {} 

650 

651 def addresult(name, abinit_name, unit=1): 

652 if abinit_name not in data.variables: 

653 return 

654 values = data.variables[abinit_name][:] 

655 # Within the netCDF4 dataset, the float variables return a array(float) 

656 # The tolist() is here to ensure that the result is of type float 

657 if not values.shape: 

658 values = values.tolist() 

659 results[name] = values * unit 

660 

661 addresult('energy', 'etotal', Hartree) 

662 addresult('free_energy', 'etotal', Hartree) 

663 addresult('forces', 'cartesian_forces', Hartree / Bohr) 

664 addresult('stress', 'cartesian_stress_tensor', Hartree / Bohr**3) 

665 

666 atoms.calc = SinglePointCalculator(atoms, **results) 

667 atoms.calc.name = 'abinit' 

668 results['atoms'] = atoms 

669 

670 addresult('fermilevel', 'fermie', Hartree) 

671 addresult('ibz_kpoints', 'reduced_coordinates_of_kpoints') 

672 addresult('eigenvalues', 'eigenvalues', Hartree) 

673 addresult('occupations', 'occupations') 

674 addresult('kpoint_weights', 'kpoint_weights') 

675 results['version'] = version 

676 

677 return results 

678 

679 

680def get_ppp_list(atoms, species, raise_exception, xc, pps, search_paths): 

681 ppp_list = [] 

682 

683 xcname = 'GGA' if xc != 'LDA' else 'LDA' 

684 for Z in species: 

685 number = abs(Z) 

686 symbol = chemical_symbols[number] 

687 

688 names = [] 

689 for s in [symbol, symbol.lower()]: 

690 for xcn in [xcname, xcname.lower()]: 

691 if pps in ['paw']: 

692 hghtemplate = '%s-%s-%s.paw' # E.g. "H-GGA-hard-uspp.paw" 

693 names.append(hghtemplate % (s, xcn, '*')) 

694 names.append(f'{s}[.-_]*.paw') 

695 elif pps in ['pawxml']: 

696 hghtemplate = '%s.%s%s.xml' # E.g. "H.GGA_PBE-JTH.xml" 

697 names.append(hghtemplate % (s, xcn, '*')) 

698 names.append(f'{s}[.-_]*.xml') 

699 elif pps in ['hgh.k']: 

700 hghtemplate = '%s-q%s.hgh.k' # E.g. "Co-q17.hgh.k" 

701 names.append(hghtemplate % (s, '*')) 

702 names.append(f'{s}[.-_]*.hgh.k') 

703 names.append(f'{s}[.-_]*.hgh') 

704 elif pps in ['tm']: 

705 hghtemplate = '%d%s%s.pspnc' # E.g. "44ru.pspnc" 

706 names.append(hghtemplate % (number, s, '*')) 

707 names.append(f'{s}[.-_]*.pspnc') 

708 elif pps in ['psp8']: 

709 hghtemplate = '%s.psp8' # E.g. "Si.psp8" 

710 names.append(hghtemplate % (s)) 

711 elif pps in ['hgh', 'hgh.sc']: 

712 hghtemplate = '%d%s.%s.hgh' # E.g. "42mo.6.hgh" 

713 # There might be multiple files with different valence 

714 # electron counts, so we must choose between 

715 # the ordinary and the semicore versions for some elements. 

716 # 

717 # Therefore we first use glob to get all relevant files, 

718 # then pick the correct one afterwards. 

719 names.append(hghtemplate % (number, s, '*')) 

720 names.append('%d%s%s.hgh' % (number, s, '*')) 

721 names.append(f'{s}[.-_]*.hgh') 

722 else: # default extension 

723 names.append('%02d-%s.%s.%s' % (number, s, xcn, pps)) 

724 names.append('%02d[.-_]%s*.%s' % (number, s, pps)) 

725 names.append('%02d%s*.%s' % (number, s, pps)) 

726 names.append(f'{s}[.-_]*.{pps}') 

727 

728 found = False 

729 for name in names: # search for file names possibilities 

730 for path in search_paths: # in all available directories 

731 filenames = glob(join(path, name)) 

732 if not filenames: 

733 continue 

734 if pps == 'paw': 

735 # warning: see download.sh in 

736 # abinit-pseudopotentials*tar.gz for additional 

737 # information! 

738 # 

739 # XXXX This is probably buggy, max(filenames) uses 

740 # an lexicographic order so 14 < 8, and it's 

741 # untested so if I change it I'm sure things will 

742 # just be inconsistent. --askhl 

743 filenames[0] = max(filenames) # Semicore or hard 

744 elif pps == 'hgh': 

745 # Lowest valence electron count 

746 filenames[0] = min(filenames) 

747 elif pps == 'hgh.k': 

748 # Semicore - highest electron count 

749 filenames[0] = max(filenames) 

750 elif pps == 'tm': 

751 # Semicore - highest electron count 

752 filenames[0] = max(filenames) 

753 elif pps == 'hgh.sc': 

754 # Semicore - highest electron count 

755 filenames[0] = max(filenames) 

756 

757 if filenames: 

758 found = True 

759 ppp_list.append(filenames[0]) 

760 break 

761 if found: 

762 break 

763 

764 if not found: 

765 ppp_list.append('Provide {}.{}.{}?'.format(symbol, '*', pps)) 

766 if raise_exception: 

767 msg = ( 

768 'Could not find {} pseudopotential {} for {} in {}'.format( 

769 xcname.lower(), pps, symbol, search_paths 

770 ) 

771 ) 

772 raise RuntimeError(msg) 

773 

774 return ppp_list