Coverage for ase/calculators/vasp/create_input.py: 82.57%

614 statements  

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

1# Copyright (C) 2008 CSC - Scientific Computing Ltd. 

2"""This module defines an ASE interface to VASP. 

3 

4Developed on the basis of modules by Jussi Enkovaara and John Kitchin. 

5The pseudpotentials provided by VASP should be stored in a single directory 

6that is defined by the environment variable VASP_PP_PATH. The VASP_PP_PATH 

7should contain subdirectories of the form potpaw_LDA(.version) and 

8potpaw_PBE(.version). The version of the pseudopotentials can be specified 

9with the environment variable VASP_PP_VERSION or by the calculator input 

10parameter 'pp_version'. If neither is set, the default is to use the 

11unversioned directories to maintain backwards compatability. 

12 

13The user should also set the environmental flag $VASP_SCRIPT pointing 

14to a python script looking something like:: 

15 

16 import os 

17 exitcode = os.system('vasp') 

18 

19Alternatively, user can set the environmental flag $VASP_COMMAND pointing 

20to the command use the launch vasp e.g. 'vasp' or 'mpirun -n 16 vasp' 

21 

22https://www.vasp.at/ 

23""" 

24 

25import os 

26import re 

27import shutil 

28import warnings 

29from collections.abc import Callable, Iterable, Sequence 

30from os.path import join 

31from typing import Any, TextIO 

32 

33import numpy as np 

34 

35import ase 

36from ase import Atoms 

37from ase.calculators.calculator import InputError, kpts2ndarray 

38from ase.calculators.vasp.setups import get_default_setups 

39from ase.config import cfg 

40from ase.io.vasp_parsers.incar_writer import write_incar 

41 

42FLOAT_FORMAT = '5.6f' 

43EXP_FORMAT = '5.2e' 

44 

45_T_STRINGS = {'t', 'true', '.true.'} 

46_F_STRINGS = {'f', 'false', '.false.'} 

47 

48 

49def check_ichain(ichain, ediffg, iopt): 

50 ichain_dct = {} 

51 if ichain > 0: 

52 ichain_dct['ibrion'] = 3 

53 ichain_dct['potim'] = 0.0 

54 if iopt is None: 

55 warnings.warn('WARNING: optimization is set to LFBGS (IOPT = 1)') 

56 ichain_dct['iopt'] = 1 

57 if ediffg is None or float(ediffg > 0.0): 

58 raise RuntimeError('Please set EDIFFG < 0') 

59 return ichain_dct 

60 

61 

62def set_m_constr(atoms, lnoncollinear, m_constr, sorting): 

63 mag_dict = {} 

64 if not lnoncollinear or m_constr is None: 

65 return {} 

66 

67 m_constr = np.array(m_constr) 

68 if m_constr.shape != (len(atoms), 3): 

69 raise InputError( 

70 f'Expected m_constr tag to be of shape ({len(atoms)}, 3), ' 

71 f'i.e, 1 vector per atom, ' 

72 f'but got {m_constr.shape}' 

73 ) 

74 

75 m_constr = m_constr[sorting].flatten() 

76 line = _compactify_magmom_list(m_constr) 

77 mag_dict['m_constr'] = line 

78 return mag_dict 

79 

80 

81def _compactify_magmom_list(magmom): 

82 lst = [[1, magmom[0]]] 

83 for n in range(1, len(magmom)): 

84 if magmom[n] == magmom[n - 1]: 

85 lst[-1][0] += 1 

86 else: 

87 lst.append([1, magmom[n]]) 

88 line = ' '.join(['{:d}*{:.4f}'.format(mom[0], mom[1]) for mom in lst]) 

89 return line 

90 

91 

92def set_magmom(ispin, spinpol, atoms, magmom_input, sorting, lnoncollinear): 

93 """Helps to set the magmom tag in the INCAR file with correct formatting""" 

94 magmom_dct = {} 

95 if magmom_input is not None: 

96 if len(magmom_input) != len(atoms): 

97 msg = ( 

98 'Expected length of magmom tag to be' 

99 ' {}, i.e. 1 value per atom, but got {}' 

100 ).format(len(atoms), len(magmom_input)) 

101 raise ValueError(msg) 

102 

103 # Check if user remembered to specify ispin 

104 # note: we do not overwrite ispin if ispin=1 

105 # do not change ispin if lnoncollinear has been set by the user. 

106 # vasp ispin and lnoncollinear do not go together. 

107 if not ispin and not lnoncollinear: 

108 spinpol = True 

109 # note that ispin is an int key, but for the INCAR it does not 

110 # matter 

111 magmom_dct['ispin'] = 2 

112 magmom = np.array(magmom_input) 

113 magmom = magmom[sorting] 

114 

115 if magmom.ndim > 1: 

116 magmom = magmom.flatten() 

117 

118 elif spinpol: # and atoms.get_initial_magnetic_moments().any()): 

119 # We will write the magnetic moments even if they are zero. 

120 # but we could still be doing a spinpol calculation 

121 if not ispin and not lnoncollinear: 

122 magmom_dct['ispin'] = 2 

123 # Write out initial magnetic moments 

124 magmom = atoms.get_initial_magnetic_moments()[sorting] 

125 # unpack magmom array if three components specified 

126 if magmom.ndim > 1: 

127 magmom = [item for sublist in magmom for item in sublist] 

128 else: 

129 return spinpol, {} 

130 # Compactify the magmom list to symbol order 

131 line = _compactify_magmom_list(magmom) 

132 magmom_dct['magmom'] = line 

133 return spinpol, magmom_dct 

134 

135 

136def set_ldau(ldau_param, luj_params, symbol_count): 

137 """Helps to set the ldau tag in the INCAR file with correct formatting""" 

138 ldau_dct = {} 

139 if ldau_param is None: 

140 ldau_dct['ldau'] = '.TRUE.' 

141 llist = [] 

142 ulist = [] 

143 jlist = [] 

144 for symbol in symbol_count: 

145 # default: No +U 

146 luj = luj_params.get(symbol[0], {'L': -1, 'U': 0.0, 'J': 0.0}) 

147 llist.append(int(luj['L'])) 

148 ulist.append(f'{luj["U"]:{".3f"}}') 

149 jlist.append(f'{luj["J"]:{".3f"}}') 

150 ldau_dct['ldaul'] = llist 

151 ldau_dct['ldauu'] = ulist 

152 ldau_dct['ldauj'] = jlist 

153 return ldau_dct 

154 

155 

156def _calc_nelect_from_charge( 

157 nelect: float | None, 

158 charge: float | None, 

159 nelect_from_ppp: float, 

160) -> float | None: 

161 """Determine nelect resulting from a given charge if charge != 0.0. 

162 

163 If nelect is additionally given explicitly, then we need to determine it 

164 even for net charge of 0 to check for conflicts. 

165 

166 """ 

167 if charge is not None and charge != 0.0: 

168 nelect_from_charge = nelect_from_ppp - charge 

169 if nelect and nelect != nelect_from_charge: 

170 raise ValueError( 

171 'incompatible input parameters: ' 

172 f'nelect={nelect}, but charge={charge} ' 

173 f'(neutral nelect is {nelect_from_ppp})' 

174 ) 

175 return nelect_from_charge 

176 return nelect # NELECT explicitly given in INCAR (`None` if not given) 

177 

178 

179def get_pp_setup(setup) -> tuple[dict, Sequence[int]]: 

180 """ 

181 Get the pseudopotential mapping based on the "setpus" input. 

182 

183 Parameters 

184 ---------- 

185 setup : [str, dict] 

186 The setup to use for the calculation. This can be a string 

187 shortcut, or a dict of atom identities and suffixes. 

188 In the dict version it is also possible to select a base setup 

189 e.g.: {'base': 'minimal', 'Ca': '_sv', 2: 'O_s'} 

190 If the key is an integer, this means an atom index. 

191 For the string version, 'minimal', 'recommended' and 'GW' are 

192 available. The default is 'minimal 

193 

194 Returns 

195 ------- 

196 setups : dict 

197 The setup dictionary, with atom indices as keys and suffixes 

198 as values. 

199 special_setups : list 

200 A list of atom indices that have a special setup. 

201 """ 

202 special_setups = [] 

203 

204 # Avoid mutating the module dictionary, so we use a copy instead 

205 # Note, it is a nested dict, so a regular copy is not enough 

206 setups_defaults = get_default_setups() 

207 

208 # Default to minimal basis 

209 if setup is None: 

210 setup = {'base': 'minimal'} 

211 

212 # String shortcuts are initialised to dict form 

213 elif isinstance(setup, str): 

214 if setup.lower() in setups_defaults.keys(): 

215 setup = {'base': setup} 

216 

217 # Dict form is then queried to add defaults from setups.py. 

218 if 'base' in setup: 

219 setups = setups_defaults[setup['base'].lower()] 

220 else: 

221 setups = {} 

222 

223 # Override defaults with user-defined setups 

224 if setup is not None: 

225 setups.update(setup) 

226 

227 for m in setups: 

228 try: 

229 special_setups.append(int(m)) 

230 except ValueError: 

231 pass 

232 return setups, special_setups 

233 

234 

235def format_kpoints(kpts, atoms, reciprocal=False, gamma=False): 

236 tokens = [] 

237 append = tokens.append 

238 

239 append('KPOINTS created by Atomic Simulation Environment\n') 

240 

241 if isinstance(kpts, dict): 

242 kpts = kpts2ndarray(kpts, atoms=atoms) 

243 reciprocal = True 

244 

245 shape = np.array(kpts).shape 

246 

247 # Wrap scalar in list if necessary 

248 if shape == (): 

249 kpts = [kpts] 

250 shape = (1,) 

251 

252 if len(shape) == 1: 

253 append('0\n') 

254 if shape == (1,): 

255 append('Auto\n') 

256 elif gamma: 

257 append('Gamma\n') 

258 else: 

259 append('Monkhorst-Pack\n') 

260 append(' '.join(f'{kpt:d}' for kpt in kpts)) 

261 append('\n0 0 0\n') 

262 elif len(shape) == 2: 

263 append('%i \n' % (len(kpts))) 

264 if reciprocal: 

265 append('Reciprocal\n') 

266 else: 

267 append('Cartesian\n') 

268 for n in range(len(kpts)): 

269 [append('%f ' % kpt) for kpt in kpts[n]] 

270 if shape[1] == 4: 

271 append('\n') 

272 elif shape[1] == 3: 

273 append('1.0 \n') 

274 return ''.join(tokens) 

275 

276 

277exp_keys = [ 

278 'ediff', # stopping-criterion for electronic upd. 

279 'ediffg', # stopping-criterion for ionic upd. 

280 'symprec', # precession in symmetry routines 

281 # The next keywords pertain to the VTST add-ons from Graeme Henkelman's 

282 # group at UT Austin 

283 'fdstep', # Finite diference step for IOPT = 1 or 2 

284] 

285 

286dict_keys = [ 

287 'ldau_luj', # dictionary with L(S)DA+U parameters, e.g. {'Fe':{'L':2, 

288 # 'U':4.0, 'J':0.9}, ...} 

289] 

290 

291 

292class GenerateVaspInput: 

293 # Parameters corresponding to 'xc' settings. This may be modified 

294 # by the user in-between loading calculators.vasp submodule and 

295 # instantiating the calculator object with calculators.vasp.Vasp() 

296 xc_defaults = { 

297 'lda': {'pp': 'LDA'}, 

298 # GGAs 

299 'blyp': { # https://www.vasp.at/forum/viewtopic.php?p=17234 

300 'pp': 'PBE', 

301 'gga': 'B5', 

302 'aldax': 1.00, 

303 'aggax': 1.00, 

304 'aggac': 1.00, 

305 'aldac': 0.00, 

306 }, 

307 'pbe': {'pp': 'PBE', 'gga': 'PE'}, 

308 'pw91': {'gga': '91'}, 

309 'pbesol': {'gga': 'PS'}, 

310 'revpbe': {'gga': 'RE'}, 

311 'rpbe': {'gga': 'RP'}, 

312 'am05': {'gga': 'AM'}, 

313 # Meta-GGAs 

314 'tpss': {'metagga': 'TPSS'}, 

315 'revtpss': {'metagga': 'RTPSS'}, 

316 'm06l': {'metagga': 'M06L'}, 

317 'ms0': {'metagga': 'MS0'}, 

318 'ms1': {'metagga': 'MS1'}, 

319 'ms2': {'metagga': 'MS2'}, 

320 'scan': {'metagga': 'SCAN'}, 

321 'rscan': {'metagga': 'RSCAN'}, 

322 'r2scan': {'metagga': 'R2SCAN'}, 

323 'mbj': { 

324 # Modified Becke-Johnson 

325 'metagga': 'MBJ', 

326 }, 

327 'tb09': { 

328 # Alias for MBJ 

329 'metagga': 'MBJ', 

330 }, 

331 # vdW-DFs 

332 'vdw-df': {'gga': 'RE', 'luse_vdw': True, 'aggac': 0.0}, 

333 'vdw-df-cx': {'gga': 'CX', 'luse_vdw': True, 'aggac': 0.0}, 

334 'vdw-df-cx0p': { 

335 'gga': 'CX', 

336 'luse_vdw': True, 

337 'aggac': 0.0, 

338 'lhfcalc': True, 

339 'aexx': 0.2, 

340 'aggax': 0.8, 

341 }, 

342 'vdw-df3-opt1': { 

343 'gga': 'BO', 

344 'param1': 0.1122334456, 

345 'param2': 0.1234568, 

346 'aggac': 0.0, 

347 'luse_vdw': True, 

348 'ivdw_nl': 3, 

349 'alpha_vdw': 0.94950, 

350 'gamma_vdw': 1.12, 

351 }, 

352 'vdw-df3-opt2': { 

353 'gga': 'MK', 

354 'param1': 0.1234568, 

355 'param2': 0.58, 

356 'aggac': 0.0, 

357 'luse_vdw': True, 

358 'ivdw_nl': 4, 

359 'zab_vdw': -1.8867, 

360 'alpha_vdw': 0.28248, 

361 'gamma_vdw': 1.29, 

362 }, 

363 'rvv10': { 

364 'gga': 'ML', 

365 'luse_vdw': True, 

366 'ivdw_nl': 2, 

367 'bparam': 6.3, 

368 'cparam': 0.0093, 

369 }, 

370 'scan+rvv10': { 

371 'metagga': 'SCAN', 

372 'luse_vdw': True, 

373 'bparam': 15.7, 

374 'cparam': 0.0093, 

375 }, 

376 'pbe+rvv10l': { 

377 'gga': 'PE', 

378 'luse_vdw': True, 

379 'bparam': 10, 

380 'cparam': 0.0093, 

381 }, 

382 'r2scan+rvv10': { 

383 'metagga': 'R2SCAN', 

384 'luse_vdw': True, 

385 'bparam': 11.95, 

386 'cparam': 0.0093, 

387 }, 

388 'optpbe-vdw': {'gga': 'OR', 'luse_vdw': True, 'aggac': 0.0}, 

389 'optb88-vdw': { 

390 'gga': 'BO', 

391 'luse_vdw': True, 

392 'aggac': 0.0, 

393 'param1': 1.1 / 6.0, 

394 'param2': 0.22, 

395 }, 

396 'optb86b-vdw': { 

397 'gga': 'MK', 

398 'luse_vdw': True, 

399 'aggac': 0.0, 

400 'param1': 0.1234, 

401 'param2': 1.0, 

402 }, 

403 'vdw-df2': { 

404 'gga': 'ML', 

405 'luse_vdw': True, 

406 'aggac': 0.0, 

407 'zab_vdw': -1.8867, 

408 }, 

409 'rev-vdw-df2': { 

410 'gga': 'MK', 

411 'luse_vdw': True, 

412 'param1': 0.1234, 

413 'param2': 0.711357, 

414 'zab_vdw': -1.8867, 

415 'aggac': 0.0, 

416 }, 

417 'beef-vdw': {'gga': 'BF', 'luse_vdw': True, 'zab_vdw': -1.8867}, 

418 # Hartree-Fock and hybrids 

419 'hf': {'lhfcalc': True, 'aexx': 1.0, 'aldac': 0.0, 'aggac': 0.0}, 

420 'b3lyp': { 

421 'gga': 'B3', 

422 'lhfcalc': True, 

423 'aexx': 0.2, 

424 'aggax': 0.72, 

425 'aggac': 0.81, 

426 'aldac': 0.19, 

427 }, 

428 'pbe0': {'gga': 'PE', 'lhfcalc': True}, 

429 'hse03': {'gga': 'PE', 'lhfcalc': True, 'hfscreen': 0.3}, 

430 'hse06': {'gga': 'PE', 'lhfcalc': True, 'hfscreen': 0.2}, 

431 'hsesol': {'gga': 'PS', 'lhfcalc': True, 'hfscreen': 0.2}, 

432 # MN-VFM functionals 

433 'sogga': {'gga': 'SA'}, 

434 'sogga11': {'gga': 'S1'}, 

435 'sogga11-x': {'gga': 'SX', 'lhfcalc': True, 'aexx': 0.401}, 

436 'n12': {'gga': 'N2'}, 

437 'n12-sx': {'gga': 'NX', 'lhfcalc': True, 'lhfscreen': 0.2}, 

438 'mn12l': {'metagga': 'MN12L'}, 

439 'gam': {'gga': 'GA'}, 

440 'mn15l': {'metagga': 'MN15L'}, 

441 'hle17': {'metagga': 'HLE17'}, 

442 'revm06l': {'metagga': 'revM06L'}, 

443 'm06sx': { 

444 'metagga': 'M06SX', 

445 'lhfcalc': True, 

446 'hfscreen': 0.189, 

447 'aexx': 0.335, 

448 }, 

449 } 

450 

451 # environment variable for PP paths 

452 VASP_PP_PATH = 'VASP_PP_PATH' 

453 VASP_PP_VERSION = 'VASP_PP_VERSION' 

454 

455 def __init__(self, restart=None): 

456 self.float_params = {} 

457 self.exp_params = {} 

458 self.string_params = {} 

459 self.int_params = {} 

460 self.bool_params = {} 

461 self.list_bool_params = {} 

462 self.list_int_params = {} 

463 self.list_float_params = {} 

464 self.special_params = {} 

465 self.dict_params = {} 

466 self.atoms = None 

467 for key in exp_keys: 

468 self.exp_params[key] = None 

469 for key in dict_keys: 

470 self.dict_params[key] = None 

471 

472 # Initialize internal dictionary of input parameters which are 

473 # not regular VASP keys 

474 self.input_params = { 

475 'xc': None, # Exchange-correlation recipe (e.g. 'B3LYP') 

476 'pp': None, # Pseudopotential file (e.g. 'PW91') 

477 'pp_version': None, # pseudopotential version (e.g. '52', '64') 

478 'setups': None, # Special setups (e.g pv, sv, ...) 

479 'txt': '-', # Where to send information 

480 'kpts': (1, 1, 1), # k-points 

481 'kpts_opt': None, # optional NSCF k-points 

482 'gamma_opt': False, 

483 'reciprocal_opt': False, 

484 # Option to use gamma-sampling instead of Monkhorst-Pack: 

485 'gamma': False, 

486 # number of points between points in band structures: 

487 'kpts_nintersections': None, 

488 # Option to write explicit k-points in units 

489 # of reciprocal lattice vectors: 

490 'reciprocal': False, 

491 # Switch to disable writing constraints to POSCAR 

492 'ignore_constraints': False, 

493 # Net charge for the whole system; determines nelect if not 0 

494 'charge': None, 

495 # Deprecated older parameter which works just like "charge" but 

496 # with the sign flipped 

497 'net_charge': None, 

498 # Custom key-value pairs, written to INCAR with *no* type checking 

499 'custom': {}, 

500 } 

501 

502 def set_xc_params(self, xc): 

503 """Set parameters corresponding to XC functional""" 

504 xc = xc.lower() 

505 if xc is None: 

506 pass 

507 elif xc not in self.xc_defaults: 

508 xc_allowed = ', '.join(self.xc_defaults.keys()) 

509 raise ValueError( 

510 '{} is not supported for xc! Supported xc valuesare: {}'.format( 

511 xc, xc_allowed 

512 ) 

513 ) 

514 else: 

515 # XC defaults to PBE pseudopotentials 

516 if 'pp' not in self.xc_defaults[xc]: 

517 self.set(pp='PBE') 

518 self.set(**self.xc_defaults[xc]) 

519 

520 def set(self, **kwargs): 

521 

522 if ( 

523 ('ldauu' in kwargs) 

524 and ('ldaul' in kwargs) 

525 and ('ldauj' in kwargs) 

526 and ('ldau_luj' in kwargs) 

527 ): 

528 raise NotImplementedError( 

529 'You can either specify ldaul, ldauu, and ldauj OR ' 

530 'ldau_luj. ldau_luj is not a VASP keyword. It is a ' 

531 'dictionary that specifies L, U and J for each ' 

532 'chemical species in the atoms object. ' 

533 'For example for a water molecule:' 

534 """ldau_luj={'H':{'L':2, 'U':4.0, 'J':0.9}, 

535 'O':{'L':2, 'U':4.0, 'J':0.9}}""" 

536 ) 

537 

538 if 'xc' in kwargs: 

539 self.set_xc_params(kwargs['xc']) 

540 for key, value in kwargs.items(): 

541 if key in self.float_params: 

542 self.float_params[key] = value 

543 elif key in self.exp_params: 

544 self.exp_params[key] = value 

545 elif key in self.string_params: 

546 self.string_params[key] = value 

547 elif key in self.int_params: 

548 self.int_params[key] = value 

549 elif key in self.bool_params: 

550 self.bool_params[key] = value 

551 elif key in self.list_bool_params: 

552 self.list_bool_params[key] = value 

553 elif key in self.list_int_params: 

554 self.list_int_params[key] = value 

555 elif key in self.list_float_params: 

556 self.list_float_params[key] = value 

557 elif key in self.special_params: 

558 self.special_params[key] = value 

559 elif key in self.dict_params: 

560 self.dict_params[key] = value 

561 elif key in self.input_params: 

562 self.input_params[key] = value 

563 elif value is None: 

564 # There is no value to write, and no existing typed parameter 

565 # to clear. Existing parameters are cleared above. 

566 continue 

567 elif isinstance(value, str): 

568 self.string_params[key] = value 

569 # `bool` is a subclass of `int` and should be checked earlier. 

570 # https://docs.python.org/3/c-api/bool.html 

571 elif isinstance(value, bool): 

572 self.bool_params[key] = value 

573 elif isinstance(value, (int, np.integer)): 

574 self.int_params[key] = value 

575 elif isinstance(value, (float, np.floating)): 

576 self.float_params[key] = value 

577 elif isinstance(value, Iterable) and not isinstance( 

578 value, (str, bytes) 

579 ): 

580 if len(value) == 0: 

581 msg = f'empty list is given for {key}' 

582 raise ValueError(msg) 

583 if isinstance(_flatten(value)[0], bool): 

584 self.list_bool_params[key] = value 

585 elif isinstance(_flatten(value)[0], (int, np.integer)): 

586 self.list_int_params[key] = value 

587 elif isinstance(_flatten(value)[0], (float, np.floating)): 

588 self.list_float_params[key] = value 

589 else: 

590 msg = f'cannot handle type of value for {key} = {value!r}' 

591 raise TypeError(msg) 

592 else: 

593 msg = f'cannot handle type of value for {key} = {value!r}' 

594 raise TypeError(msg) 

595 

596 def check_xc(self): 

597 """Make sure the calculator has functional & pseudopotentials set up 

598 

599 If no XC combination, GGA functional or POTCAR type is specified, 

600 default to PW91. Otherwise, try to guess the desired pseudopotentials. 

601 """ 

602 

603 p = self.input_params 

604 

605 # There is no way to correctly guess the desired 

606 # set of pseudopotentials without 'pp' being set. 

607 # Usually, 'pp' will be set by 'xc'. 

608 if 'pp' not in p or p['pp'] is None: 

609 if self.string_params.get('gga') is None: 

610 p.update({'pp': 'lda'}) 

611 elif self.string_params['gga'].lower() == 'pe': 

612 p.update({'pp': 'pbe'}) 

613 else: 

614 raise NotImplementedError( 

615 'Unable to guess the desired set of pseudopotential' 

616 '(POTCAR) files. Please do one of the following: \n' 

617 "1. Use the 'xc' parameter to define your XC functional." 

618 "These 'recipes' determine the pseudopotential file as " 

619 'well as setting the INCAR parameters.\n' 

620 "2. Use the 'gga' settings None (default) or 'PE'; " 

621 'these correspond to LDA and PBE, respectively.\n' 

622 "3. Set the POTCAR explicitly with the 'pp' flag. The " 

623 'value should be the name of a folder on the VASP_PP_PATH' 

624 ", and the aliases 'LDA' and 'PBE' are also accepted.\n" 

625 ) 

626 

627 if ( 

628 p['xc'] is not None 

629 and p['xc'].lower() == 'lda' 

630 and p['pp'].lower() != 'lda' 

631 ): 

632 warnings.warn( 

633 'XC is set to LDA, but PP is set to ' 

634 '{0}. \nThis calculation is using the {0} ' 

635 'POTCAR set. \n Please check that this is ' 

636 'really what you intended!' 

637 '\n'.format(p['pp'].upper()) 

638 ) 

639 

640 def _make_sort( 

641 self, atoms: ase.Atoms, special_setups: Sequence[int] = () 

642 ) -> tuple[list[int], list[int]]: 

643 symbols, _ = count_symbols(atoms, exclude=special_setups) 

644 

645 # Create sorting list 

646 srt = [] # type: list[int] 

647 srt.extend(special_setups) 

648 

649 for symbol in symbols: 

650 for m, atom in enumerate(atoms): 

651 if m in special_setups: 

652 continue 

653 if atom.symbol == symbol: 

654 srt.append(m) 

655 # Create the resorting list 

656 resrt = list(range(len(srt))) 

657 for n in range(len(resrt)): 

658 resrt[srt[n]] = n 

659 return srt, resrt 

660 

661 def _set_spinpol(self, atoms): 

662 if self.int_params.get('ispin') is None: 

663 self.spinpol = atoms.get_initial_magnetic_moments().any() 

664 else: 

665 # VASP runs non-spin-polarized calculations when `ispin=1`, 

666 # regardless if `magmom` is specified or not. 

667 self.spinpol = self.int_params['ispin'] == 2 

668 

669 def _build_pp_list( 

670 self, atoms, setups=None, special_setups: Sequence[int] = () 

671 ): 

672 """Build the pseudopotential lists""" 

673 

674 p = self.input_params 

675 

676 if p['pp_version'] is not None: 

677 pp_version = p['pp_version'] 

678 elif self.VASP_PP_VERSION in cfg: 

679 pp_version = cfg[self.VASP_PP_VERSION] 

680 else: 

681 pp_version = '' 

682 

683 if setups is None: 

684 setups, special_setups = get_pp_setup(p['setups']) 

685 

686 symbols, _ = count_symbols(atoms, exclude=special_setups) 

687 

688 # Potpaw folders may be identified by an alias or full name 

689 for pp_alias, pp_folder in ( 

690 ('lda', f'potpaw_LDA.{pp_version}' if pp_version else 'potpaw'), 

691 ('pbe', f'potpaw_PBE.{pp_version}' if pp_version else 'potpaw_PBE'), 

692 ): 

693 if p['pp'].lower() == pp_alias: 

694 break 

695 else: 

696 pp_folder = p['pp'] 

697 

698 if self.VASP_PP_PATH in cfg: 

699 pppath = cfg[self.VASP_PP_PATH] 

700 if not os.path.exists(pppath): 

701 raise RuntimeError(f'VASP_PP_PATH does not exist: {pppath}') 

702 else: 

703 pppath = None 

704 ppp_list = [] 

705 # Setting the pseudopotentials, first special setups and 

706 # then according to symbols 

707 for m in special_setups: 

708 if m in setups: 

709 special_setup_index = m 

710 elif str(m) in setups: 

711 special_setup_index = str(m) # type: ignore[assignment] 

712 else: 

713 raise Exception( 

714 'Having trouble with special setup index {}.' 

715 ' Please use an int.'.format(m) 

716 ) 

717 potcar = join(pp_folder, setups[special_setup_index], 'POTCAR') 

718 potcar_path = join(pppath, potcar) if pppath is not None else potcar 

719 

720 if os.path.exists(potcar_path): 

721 ppp_list.append(potcar_path) 

722 elif os.path.exists(potcar_path + '.Z'): 

723 ppp_list.append(potcar_path + '.Z') 

724 else: 

725 msg = """Looking for {}. 

726 No pseudopotential for symbol{} with setup {} """.format( 

727 potcar_path, atoms.symbols[m], setups[special_setup_index] 

728 ) 

729 raise RuntimeError(msg) 

730 

731 for symbol in symbols: 

732 try: 

733 potcar = join(pp_folder, symbol + setups[symbol], 'POTCAR') 

734 except (TypeError, KeyError): 

735 potcar = join(pp_folder, symbol, 'POTCAR') 

736 

737 potcar_path = join(pppath, potcar) if pppath is not None else potcar 

738 

739 if os.path.exists(potcar_path): 

740 ppp_list.append(potcar_path) 

741 elif os.path.exists(potcar_path + '.Z'): 

742 ppp_list.append(potcar_path + '.Z') 

743 else: 

744 msg = """Looking for {} 

745 The pseudopotentials are expected to be in: 

746 LDA: $VASP_PP_PATH/potpaw_LDA(.52|.54|.64) 

747 or $VASP_PP_PATH/potpaw 

748 PBE: $VASP_PP_PATH/potpaw_PBE(.52|.54|.64) 

749 

750 No pseudopotential for {}!""".format( 

751 potcar_path, symbol 

752 ) 

753 raise RuntimeError(msg) 

754 return ppp_list 

755 

756 def initialize(self, atoms: Atoms) -> None: 

757 """Initialize a VASP calculation 

758 

759 Constructs the POTCAR file (does not actually write it). 

760 User should specify the PATH 

761 to the pseudopotentials in VASP_PP_PATH environment variable 

762 

763 The pseudopotentials are expected to be in: 

764 LDA: $VASP_PP_PATH/potpaw_LDA(.52|.54|.64) or $VASP_PP_PATH/potpaw 

765 PBE: $VASP_PP_PATH/potpaw_PBE(.52|.54|.64) 

766 

767 if your pseudopotentials are somewhere else, or named 

768 differently you may make symlinks at the paths above that 

769 point to the right place. Alternatively, you may pass the full 

770 name of a folder on the VASP_PP_PATH to the 'pp' parameter. 

771 """ 

772 

773 self.check_xc() 

774 self.atoms = atoms 

775 self.all_symbols = atoms.get_chemical_symbols() 

776 self.natoms = len(atoms) 

777 

778 self._set_spinpol(atoms) 

779 

780 setups, special_setups = get_pp_setup(self.input_params['setups']) 

781 

782 # Determine the number of atoms of each atomic species 

783 # sorted after atomic species 

784 symbols, symbolcount = count_symbols(atoms, exclude=special_setups) 

785 self.sort, self.resort = self._make_sort( 

786 atoms, special_setups=special_setups 

787 ) 

788 

789 self.atoms_sorted = atoms[self.sort] 

790 

791 # Check if the necessary POTCAR files exists and 

792 # create a list of their paths. 

793 atomtypes = atoms.get_chemical_symbols() 

794 self.symbol_count: list[tuple[str, int]] = [] 

795 for m in special_setups: 

796 self.symbol_count.append((atomtypes[m], 1)) 

797 for s in symbols: 

798 self.symbol_count.append((s, symbolcount[s])) 

799 

800 # create pseudopotential list 

801 self.ppp_list = self._build_pp_list( 

802 atoms, 

803 setups=setups, 

804 special_setups=special_setups, 

805 ) 

806 

807 self.converged = None 

808 self.setups_changed = None 

809 

810 def default_nelect_from_ppp(self) -> float: 

811 """Get default number of electrons from ppp_list and symbol_count 

812 

813 "Default" here means that the resulting cell would be neutral. 

814 """ 

815 symbol_valences: list[tuple[str, float]] = [] 

816 for filename in self.ppp_list: 

817 with open_potcar(filename=filename) as ppp_file: 

818 r = read_potcar_numbers_of_electrons(ppp_file) 

819 symbol_valences.extend(r) 

820 assert len(self.symbol_count) == len(symbol_valences) 

821 default_nelect = 0.0 

822 for (symbol1, count), (symbol2, valence) in zip( 

823 self.symbol_count, symbol_valences 

824 ): 

825 assert symbol1 == symbol2 

826 default_nelect += count * valence 

827 return default_nelect 

828 

829 def write_input(self, atoms, directory='./'): 

830 from ase.io.vasp import write_vasp 

831 

832 write_vasp( 

833 join(directory, 'POSCAR'), 

834 self.atoms_sorted, 

835 symbol_count=self.symbol_count, 

836 ignore_constraints=self.input_params['ignore_constraints'], 

837 ) 

838 self.write_incar(atoms, directory=directory) 

839 self.write_potcar(directory=directory) 

840 self.write_kpoints(atoms=atoms, directory=directory) 

841 self.write_sort_file(directory=directory) 

842 self.copy_vdw_kernel(directory=directory) 

843 

844 def copy_vdw_kernel(self, directory='./'): 

845 """Method to copy the vdw_kernel.bindat file. 

846 Set ASE_VASP_VDW environment variable to the vdw_kernel.bindat 

847 folder location. Checks if LUSE_VDW is enabled, and if no location 

848 for the vdW kernel is specified, a warning is issued.""" 

849 

850 vdw_env = 'ASE_VASP_VDW' 

851 kernel = 'vdw_kernel.bindat' 

852 dst = os.path.join(directory, kernel) 

853 

854 # No need to copy the file again 

855 if os.path.isfile(dst): 

856 return 

857 

858 if self.bool_params.get('luse_vdw'): 

859 src = None 

860 if vdw_env in cfg: 

861 src = os.path.join(cfg[vdw_env], kernel) 

862 

863 if not src or not os.path.isfile(src): 

864 warnings.warn( 

865 ( 

866 'vdW has been enabled, however no' 

867 ' location for the {} file' 

868 ' has been specified.' 

869 ' Set {} environment variable to' 

870 ' copy the vdW kernel.' 

871 ).format(kernel, vdw_env) 

872 ) 

873 else: 

874 shutil.copyfile(src, dst) 

875 

876 def clean(self): 

877 """Method which cleans up after a calculation. 

878 

879 The default files generated by Vasp will be deleted IF this 

880 method is called. 

881 

882 """ 

883 files = [ 

884 'CHG', 

885 'CHGCAR', 

886 'POSCAR', 

887 'INCAR', 

888 'CONTCAR', 

889 'DOSCAR', 

890 'EIGENVAL', 

891 'IBZKPT', 

892 'KPOINTS', 

893 'OSZICAR', 

894 'OUTCAR', 

895 'PCDAT', 

896 'POTCAR', 

897 'vasprun.xml', 

898 'WAVECAR', 

899 'XDATCAR', 

900 'PROCAR', 

901 'ase-sort.dat', 

902 'LOCPOT', 

903 'AECCAR0', 

904 'AECCAR1', 

905 'AECCAR2', 

906 ] 

907 for f in files: 

908 try: 

909 os.remove(f) 

910 except OSError: 

911 pass 

912 

913 def write_incar(self, atoms, directory='./', **kwargs): 

914 """Writes the INCAR file.""" 

915 incar_params = {} 

916 

917 # float params 

918 float_dct = { 

919 key: f'{val:{FLOAT_FORMAT}}' 

920 for key, val in self.float_params.items() 

921 if val is not None 

922 } 

923 

924 if ( 

925 'charge' in self.input_params 

926 and self.input_params['charge'] is not None 

927 ): 

928 nelect_val = _calc_nelect_from_charge( 

929 self.float_params['nelect'], 

930 self.input_params['charge'], 

931 self.default_nelect_from_ppp(), 

932 ) 

933 if nelect_val: 

934 float_dct['nelect'] = f'{nelect_val:{FLOAT_FORMAT}}' 

935 incar_params.update(float_dct) 

936 

937 # exp params 

938 exp_dct = { 

939 key: f'{val:{EXP_FORMAT}}' 

940 for key, val in self.exp_params.items() 

941 if val is not None 

942 } 

943 incar_params.update(exp_dct) 

944 

945 # string_params 

946 string_dct = { 

947 key: val 

948 for key, val in self.string_params.items() 

949 if val is not None 

950 } 

951 incar_params.update(string_dct) 

952 

953 # int params 

954 int_dct = { 

955 key: val for key, val in self.int_params.items() if val is not None 

956 } 

957 if 'ichain' in int_dct.keys(): 

958 ichain_dict = check_ichain( 

959 ichain=int_dct['ichain'], 

960 ediffg=self.exp_params.get('ediffg', None), 

961 iopt=int_dct.get('iopt', None), 

962 ) 

963 int_dct.update(ichain_dict) 

964 incar_params.update(int_dct) 

965 

966 # list_bool_params 

967 bool_dct = { 

968 key: val 

969 for key, val in self.list_bool_params.items() 

970 if val is not None 

971 } 

972 for key, val in bool_dct.items(): 

973 bool_dct[key] = [_to_vasp_bool(x) for x in val] 

974 incar_params.update(bool_dct) 

975 

976 # list_int_params 

977 int_dct = { 

978 key: val 

979 for key, val in self.list_int_params.items() 

980 if val is not None 

981 } 

982 if ( 

983 'ldaul' in int_dct.keys() 

984 and self.dict_params['ldau_luj'] is not None 

985 ): 

986 del int_dct['ldaul'] 

987 incar_params.update(int_dct) 

988 

989 # list_float_params 

990 float_dct = { 

991 key: val 

992 for key, val in self.list_float_params.items() 

993 if val is not None 

994 } 

995 if ( 

996 'ldauu' in float_dct.keys() 

997 and self.dict_params['ldau_luj'] is not None 

998 ): 

999 del float_dct['ldauu'] 

1000 if ( 

1001 'ldauj' in float_dct.keys() 

1002 and self.dict_params['ldau_luj'] is not None 

1003 ): 

1004 del float_dct['ldauj'] 

1005 incar_params.update(float_dct) 

1006 

1007 # bool params 

1008 bool_dct = { 

1009 key: _to_vasp_bool(val) 

1010 for key, val in self.bool_params.items() 

1011 if val is not None 

1012 } 

1013 incar_params.update(bool_dct) 

1014 

1015 # special params 

1016 special_dct = { 

1017 key: val 

1018 for key, val in self.special_params.items() 

1019 if val is not None 

1020 } 

1021 incar_params.update(special_dct) 

1022 

1023 # dict params 

1024 dict_dct = { 

1025 key: val for key, val in self.dict_params.items() if val is not None 

1026 } 

1027 if 'ldau_luj' in dict_dct.keys(): 

1028 ldau_dict = set_ldau( 

1029 ldau_param=self.bool_params.get('ldau'), 

1030 luj_params=dict_dct['ldau_luj'], 

1031 symbol_count=self.symbol_count, 

1032 ) 

1033 dict_dct.update(ldau_dict) 

1034 del dict_dct['ldau_luj'] 

1035 incar_params.update(dict_dct) 

1036 

1037 # set magmom based on input or initial atoms object 

1038 spinpol, magmom_dct = set_magmom( 

1039 atoms=atoms, 

1040 ispin=self.int_params.get('ispin'), 

1041 spinpol=self.spinpol, 

1042 magmom_input=incar_params.get('magmom'), 

1043 sorting=self.sort, 

1044 lnoncollinear=self.bool_params.get('lnoncollinear', False), 

1045 ) 

1046 self.spinpol = spinpol 

1047 incar_params.update(magmom_dct) 

1048 

1049 # set non-llinear magmoms m_constr. 

1050 magm_constr_dct = set_m_constr( 

1051 atoms=atoms, 

1052 lnoncollinear=self.bool_params.get('lnoncollinear', False), 

1053 m_constr=incar_params.get('m_constr'), 

1054 sorting=self.sort, 

1055 ) 

1056 incar_params.update(magm_constr_dct) 

1057 

1058 # Custom key-value pairs, which receive no formatting 

1059 # Use the comment "# <Custom ASE key>" to denote such 

1060 # a custom key-value pair, as we cannot otherwise 

1061 # reliably and easily identify such non-standard entries 

1062 

1063 cust_dict = { 

1064 key: str(val) + ' # <Custom ASE key>' 

1065 for key, val in self.input_params['custom'].items() 

1066 if val is not None 

1067 } 

1068 incar_params.update(cust_dict) 

1069 

1070 write_incar(directory=directory, parameters=incar_params) 

1071 

1072 def write_kpoints(self, atoms=None, directory='./', **kwargs): 

1073 """Write KPOINTS and, when requested, KPOINTS_OPT.""" 

1074 

1075 if atoms is None: 

1076 atoms = self.atoms 

1077 

1078 for suffix in ('', '_opt'): 

1079 spacing = self.float_params.get('kspacing' + suffix) 

1080 if spacing is not None and not spacing > 0: 

1081 raise ValueError( 

1082 f'KSPACING{suffix.upper()} value {spacing} ' 

1083 'is not allowable. ' 

1084 'Please use None or a positive number.' 

1085 ) 

1086 if spacing is not None: 

1087 continue 

1088 kpts = self.input_params['kpts' + suffix] 

1089 if kpts is None: 

1090 continue 

1091 kpointstring = format_kpoints( 

1092 kpts=kpts, 

1093 atoms=atoms, 

1094 reciprocal=self.input_params['reciprocal' + suffix], 

1095 gamma=self.input_params['gamma' + suffix], 

1096 ) 

1097 with open(join(directory, 'KPOINTS' + suffix.upper()), 'w') as fd: 

1098 fd.write(kpointstring) 

1099 

1100 def write_potcar(self, suffix='', directory='./'): 

1101 """Writes the POTCAR file.""" 

1102 

1103 with open(join(directory, 'POTCAR' + suffix), 'w') as potfile: 

1104 for filename in self.ppp_list: 

1105 with open_potcar(filename=filename) as ppp_file: 

1106 for line in ppp_file: 

1107 potfile.write(line) 

1108 

1109 def write_sort_file(self, directory='./'): 

1110 """Writes a sortings file. 

1111 

1112 This file contains information about how the atoms are sorted in 

1113 the first column and how they should be resorted in the second 

1114 column. It is used for restart purposes to get sorting right 

1115 when reading in an old calculation to ASE.""" 

1116 

1117 with open(join(directory, 'ase-sort.dat'), 'w') as fd: 

1118 for n in range(len(self.sort)): 

1119 fd.write('%5i %5i \n' % (self.sort[n], self.resort[n])) 

1120 

1121 # The below functions are used to restart a calculation 

1122 

1123 @staticmethod 

1124 def set_if_none(collection: dict[str, Any], key: str, value: Any) -> None: 

1125 collection[key] = ( 

1126 value if collection.get(key) is None else collection[key] 

1127 ) 

1128 

1129 def read_incar(self, filename): 

1130 """Method that imports settings from INCAR file. 

1131 

1132 Typically named INCAR.""" 

1133 

1134 self.spinpol = False 

1135 with open(filename) as fd: 

1136 lines = fd.readlines() 

1137 

1138 for line in lines: 

1139 try: 

1140 # Make multiplication, comments, and parameters easier to spot 

1141 line = line.replace('*', ' * ') 

1142 line = line.replace('=', ' = ') 

1143 line = line.replace('#', '# ') 

1144 data = line.split() 

1145 # Skip empty and commented lines. 

1146 if len(data) == 0: 

1147 continue 

1148 elif data[0][0] in ['#', '!']: 

1149 continue 

1150 key = data[0].lower() 

1151 if '<Custom ASE key>' in line: 

1152 # This key was added with custom key-value pair formatting. 

1153 # Unconditionally add it, no type checking 

1154 # Get value between "=" and the comment, e.g. 

1155 # key = 1 2 3 # <Custom ASE key> 

1156 # value should be '1 2 3' 

1157 

1158 # Split at first occurence of "=" 

1159 value = line.split('=', 1)[1] 

1160 # First "#" denotes beginning of comment 

1161 # Add everything before comment as a string to custom dict 

1162 value = value.split('#', 1)[0].strip() 

1163 self.set_if_none(self.inputs_params['custom'], key, value) 

1164 elif key in exp_keys: 

1165 self.set_if_none(self.exp_params, key, float(data[2])) 

1166 elif key == 'ispin': 

1167 self.set_if_none(self.int_params, key, int(data[2])) 

1168 if int(data[2]) == 2: 

1169 self.spinpol = True 

1170 elif key == 'ldaul': 

1171 lst = _parse_list_value(data[2:], int) 

1172 self.set_if_none(self.list_int_params, key, lst) 

1173 elif key in {'magmom', 'ldauu', 'ldauj'}: 

1174 lst = _parse_list_value(data[2:], float) 

1175 self.set_if_none(self.list_float_params, key, lst) 

1176 if key == 'magmom' and self.atoms is not None: 

1177 lst = np.array(lst) 

1178 self.atoms.set_initial_magnetic_moments( 

1179 lst[self.resort] 

1180 ) 

1181 

1182 # non-registered keys 

1183 elif len(_args_without_comment(data)) > 3: # multiple values 

1184 data = _args_without_comment(data) 

1185 if data[2].lower() in _T_STRINGS | _F_STRINGS: 

1186 value = [_from_vasp_bool(x) for x in data[2:]] 

1187 self.set_if_none(self.list_bool_params, key, value) 

1188 elif data[2].isdigit(): 

1189 value = [int(x) for x in data[2:]] 

1190 self.set_if_none(self.list_int_params, key, value) 

1191 else: 

1192 value = [float(x) for x in data[2:]] 

1193 self.set_if_none(self.list_float_params, key, value) 

1194 elif data[2].lower() in _T_STRINGS | _F_STRINGS: 

1195 value = _from_vasp_bool(data[2]) 

1196 self.set_if_none(self.bool_params, key, value) 

1197 elif data[2].isdigit(): 

1198 self.set_if_none(self.int_params, key, int(data[2])) 

1199 else: 

1200 try: 

1201 self.set_if_none(self.float_params, key, float(data[2])) 

1202 except ValueError: 

1203 self.set_if_none(self.string_params, key, data[2]) 

1204 

1205 except KeyError as exc: 

1206 raise KeyError( 

1207 f'Keyword "{key}" in INCAR is not known by calculator.' 

1208 ) from exc 

1209 except IndexError as exc: 

1210 raise IndexError(f'Value missing for keyword "{key}".') from exc 

1211 

1212 def read_kpoints(self, filename, opt=False): 

1213 """Read kpoints file, typically named KPOINTS.""" 

1214 # If we used VASP builtin kspacing, 

1215 suffix = '_opt' if opt else '' 

1216 if self.float_params.get('kspacing' + suffix) is not None: 

1217 # Don't update kpts array 

1218 return 

1219 

1220 with open(filename) as fd: 

1221 lines = fd.readlines() 

1222 

1223 ktype = lines[2].split()[0].lower()[0] 

1224 if ktype in ['g', 'm', 'a']: 

1225 if ktype == 'g': 

1226 self.set(**{'gamma' + suffix: True}) 

1227 kpts = np.array([int(lines[3].split()[i]) for i in range(3)]) 

1228 elif ktype == 'a': 

1229 kpts = np.array([int(lines[3].split()[i]) for i in range(1)]) 

1230 elif ktype == 'm': 

1231 self.set(**{'gamma' + suffix: False}) 

1232 kpts = np.array([int(lines[3].split()[i]) for i in range(3)]) 

1233 else: 

1234 if ktype in ['c', 'k']: 

1235 self.set(**{'reciprocal' + suffix: False}) 

1236 else: 

1237 self.set(**{'reciprocal' + suffix: True}) 

1238 kpts = np.array( 

1239 [list(map(float, line.split())) for line in lines[3:]] 

1240 ) 

1241 self.set(**{'kpts' + suffix: kpts}) 

1242 

1243 def read_potcar(self, filename): 

1244 """Read the pseudopotential XC functional from POTCAR file.""" 

1245 

1246 # Search for key 'LEXCH' in POTCAR 

1247 xc_flag = None 

1248 with open(filename) as fd: 

1249 for line in fd: 

1250 key = line.split()[0].upper() 

1251 if key == 'LEXCH': 

1252 xc_flag = line.split()[-1].upper() 

1253 break 

1254 

1255 if xc_flag is None: 

1256 raise ValueError('LEXCH flag not found in POTCAR file.') 

1257 

1258 # Values of parameter LEXCH and corresponding XC-functional 

1259 xc_dict = {'PE': 'PBE', '91': 'PW91', 'CA': 'LDA'} 

1260 

1261 if xc_flag not in xc_dict.keys(): 

1262 raise ValueError( 

1263 'Unknown xc-functional flag found in POTCAR, LEXCH=%s' % xc_flag 

1264 ) 

1265 

1266 self.input_params['pp'] = xc_dict[xc_flag] 

1267 

1268 def todict(self): 

1269 """Returns a dictionary of all parameters 

1270 that can be used to construct a new calculator object""" 

1271 dict_list = [ 

1272 'float_params', 

1273 'exp_params', 

1274 'string_params', 

1275 'int_params', 

1276 'bool_params', 

1277 'list_bool_params', 

1278 'list_int_params', 

1279 'list_float_params', 

1280 'special_params', 

1281 'dict_params', 

1282 'input_params', 

1283 ] 

1284 dct = {} 

1285 for item in dict_list: 

1286 dct.update(getattr(self, item)) 

1287 dct = {key: value for key, value in dct.items() if value is not None} 

1288 return dct 

1289 

1290 

1291def _args_without_comment(data, marks=None): 

1292 """Check split arguments list for a comment, return data up to marker 

1293 

1294 INCAR reader splits list arguments on spaces and leaves comment markers as 

1295 individual items. This function returns only the data portion of the list. 

1296 

1297 """ 

1298 if marks is None: 

1299 marks = ['!', '#'] 

1300 comment_locs = [data.index(mark) for mark in marks if mark in data] 

1301 if comment_locs == []: 

1302 return data 

1303 else: 

1304 return data[: min(comment_locs)] 

1305 

1306 

1307def _from_vasp_bool(x): 

1308 """Cast vasp boolean to Python bool 

1309 

1310 VASP files sometimes use T or F as shorthand for the preferred Boolean 

1311 notation .TRUE. or .FALSE. As capitalisation is pretty inconsistent in 

1312 practice, we allow all cases to be cast to a Python bool. 

1313 

1314 """ 

1315 assert isinstance(x, str) 

1316 if re.search(r'^\.?[tT]', x): 

1317 return True 

1318 elif re.search(r'^\.?[fF]', x): 

1319 return False 

1320 else: 

1321 raise ValueError(f'Value "{x}" not recognized as bool') 

1322 

1323 

1324def _to_vasp_bool(x): 

1325 """Convert Python boolean to string for VASP input 

1326 

1327 In case the value was modified to a string already, appropriate strings 

1328 will also be accepted and cast to a standard .TRUE. / .FALSE. format. 

1329 

1330 """ 

1331 if isinstance(x, str): 

1332 if x.lower() in ('.true.', 't'): 

1333 x = True 

1334 elif x.lower() in ('.false.', 'f'): 

1335 x = False 

1336 else: 

1337 raise ValueError('"%s" not recognised as VASP Boolean') 

1338 assert isinstance(x, bool) 

1339 if x: 

1340 return '.TRUE.' 

1341 else: 

1342 return '.FALSE.' 

1343 

1344 

1345def _flatten(values: Iterable) -> Iterable: 

1346 result: list[Any] = [] 

1347 for value in values: 

1348 if isinstance(value, Iterable) and not isinstance(value, (str, bytes)): 

1349 result.extend(_flatten(value)) 

1350 else: 

1351 result.append(value) 

1352 return result 

1353 

1354 

1355def _parse_list_value(data: list[str], converter: Callable) -> list: 

1356 value: list = [] 

1357 i = 0 

1358 while i < len(data): 

1359 if data[i] in ['#', '!']: 

1360 break 

1361 if data[i] == '*': 

1362 b = value.pop() 

1363 i += 1 

1364 for _ in range(int(b)): 

1365 value.append(converter(data[i])) 

1366 else: 

1367 value.append(converter(data[i])) 

1368 i += 1 

1369 return value 

1370 

1371 

1372def open_potcar(filename): 

1373 """Open POTCAR file with transparent decompression if archive (.Z)""" 

1374 import gzip 

1375 

1376 if filename.endswith('R'): 

1377 return open(filename) 

1378 elif filename.endswith('.Z'): 

1379 return gzip.open(filename) 

1380 else: 

1381 raise ValueError(f'Invalid POTCAR filename: "{filename}"') 

1382 

1383 

1384def read_potcar_numbers_of_electrons(fd: TextIO, /) -> list[tuple[str, float]]: 

1385 """Read number of valence electrons for each atomtype from a POTCAR file. 

1386 

1387 Returns 

1388 ------- 

1389 list[tuple[str, float]] 

1390 List of (atomic symbol, number of valence electrons). 

1391 

1392 """ 

1393 nelect: list[tuple[str, float]] = [] 

1394 lines = fd.readlines() 

1395 for n, line in enumerate(lines): 

1396 if 'TITEL' in line: 

1397 symbol = line.split('=')[1].split()[1].split('_')[0].strip() 

1398 linep4 = lines[n + 4] 

1399 zval = float(linep4.split(';')[1].split('=')[1].split()[0].strip()) 

1400 nelect.append((symbol, zval)) 

1401 return nelect 

1402 

1403 

1404def count_symbols(atoms: Atoms, exclude=()) -> tuple[list[str], dict[str, int]]: 

1405 """Count symbols in atoms object, excluding a set of indices 

1406 

1407 Parameters 

1408 ---------- 

1409 atoms: Atoms object to be grouped 

1410 exclude: List of indices to be excluded from the counting 

1411 

1412 Returns 

1413 ------- 

1414 Tuple of (symbols, symbolcount) 

1415 symbols: The unique symbols in the included list 

1416 symbolscount: Count of symbols in the included list 

1417 

1418 Example: 

1419 

1420 >>> from ase.build import bulk 

1421 >>> atoms = bulk('NaCl', crystalstructure='rocksalt', a=4.1, cubic=True) 

1422 >>> count_symbols(atoms) 

1423 (['Na', 'Cl'], {'Na': 4, 'Cl': 4}) 

1424 >>> count_symbols(atoms, exclude=(1, 2, 3)) 

1425 (['Na', 'Cl'], {'Na': 3, 'Cl': 2}) 

1426 """ 

1427 symbols: list[str] = [] 

1428 symbolcount: dict[str, int] = {} 

1429 for m, symbol in enumerate(atoms.symbols): 

1430 if m in exclude: 

1431 continue 

1432 if symbol not in symbols: 

1433 symbols.append(symbol) 

1434 symbolcount[symbol] = 1 

1435 else: 

1436 symbolcount[symbol] += 1 

1437 return symbols, symbolcount