Coverage for ase/calculators/vasp/vasp.py: 45.84%

637 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 

5Kitchin. The path of the directory containing the pseudopotential 

6directories (potpaw,potpaw_GGA, potpaw_PBE, ...) should be set 

7by the environmental flag $VASP_PP_PATH. 

8 

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

10to a python script looking something like:: 

11 

12 import os 

13 exitcode = os.system('vasp') 

14 

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

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

17 

18https://www.vasp.at/ 

19""" 

20 

21import os 

22import re 

23import subprocess 

24import sys 

25from contextlib import contextmanager 

26from pathlib import Path 

27from typing import Any 

28from warnings import warn 

29from xml.etree import ElementTree 

30 

31import numpy as np 

32 

33import ase 

34from ase.calculators import calculator 

35from ase.calculators.calculator import Calculator 

36from ase.calculators.singlepoint import SinglePointDFTCalculator 

37from ase.calculators.vasp.create_input import GenerateVaspInput 

38from ase.config import cfg 

39from ase.io import jsonio, read 

40from ase.utils import PurePath, deprecated 

41from ase.vibrations.data import VibrationsData 

42 

43 

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

45 if len(args) >= 5 and '/' in args[4]: 

46 return True 

47 return '/' in kwargs.get('label', '') 

48 

49 

50class Vasp(GenerateVaspInput, Calculator): # type: ignore[misc] 

51 """ASE interface for the Vienna Ab initio Simulation Package (VASP), 

52 with the Calculator interface. 

53 

54 Parameters 

55 ---------- 

56 

57 atoms: object 

58 Attach an atoms object to the calculator. 

59 

60 label: str 

61 Prefix for the output file, and sets the working directory. 

62 Default is 'vasp'. 

63 

64 directory: str 

65 Set the working directory. Is prepended to ``label``. 

66 

67 restart: str or bool 

68 Sets a label for the directory to load files from. 

69 if :code:`restart=True`, the working directory from 

70 ``directory`` is used. 

71 

72 txt: bool, None, str or writable object 

73 - If txt is None, output stream will be supressed 

74 

75 - If txt is '-' the output will be sent through stdout 

76 

77 - If txt is a string a file will be opened,\ 

78 and the output will be sent to that file. 

79 

80 - Finally, txt can also be a an output stream,\ 

81 which has a 'write' attribute. 

82 

83 Default is 'vasp.out' 

84 

85 - Examples: 

86 >>> from ase.calculators.vasp import Vasp 

87 >>> calc = Vasp(label='mylabel', txt='vasp.out') # Redirect stdout 

88 >>> calc = Vasp(txt='myfile.txt') # Redirect stdout 

89 >>> calc = Vasp(txt='-') # Print vasp output to stdout 

90 >>> calc = Vasp(txt=None) # Suppress txt output 

91 

92 command: str 

93 Custom instructions on how to execute VASP. Has priority over 

94 environment variables. 

95 """ 

96 

97 name = 'vasp' 

98 ase_objtype = 'vasp_calculator' # For JSON storage 

99 

100 # Environment commands 

101 env_commands = ('ASE_VASP_COMMAND', 'VASP_COMMAND', 'VASP_SCRIPT') 

102 

103 implemented_properties = [ 

104 'energy', 

105 'free_energy', 

106 'forces', 

107 'dipole', 

108 'fermi', 

109 'stress', 

110 'magmom', 

111 'magmoms', 

112 ] 

113 

114 # Can be used later to set some ASE defaults 

115 default_parameters: dict[str, Any] = {} 

116 

117 @deprecated( 

118 'Specifying directory in "label" is deprecated, ' 

119 'use "directory" instead.', 

120 category=FutureWarning, 

121 callback=_prohibit_directory_in_label, 

122 ) 

123 def __init__( 

124 self, 

125 atoms=None, 

126 restart=None, 

127 directory='.', 

128 label='vasp', 

129 ignore_bad_restart_file=Calculator._deprecated, 

130 command=None, 

131 txt='vasp.out', 

132 **kwargs, 

133 ): 

134 """ 

135 .. deprecated:: 3.19.2 

136 Specifying directory in ``label`` is deprecated, 

137 use ``directory`` instead. 

138 """ 

139 

140 self._atoms = None 

141 self.results = {} 

142 

143 # Initialize parameter dictionaries 

144 GenerateVaspInput.__init__(self) 

145 self._store_param_state() # Initialize an empty parameter state 

146 

147 # Store calculator from vasprun.xml here - None => uninitialized 

148 self._xml_calc = None 

149 

150 # Set directory and label 

151 self.directory = directory 

152 if '/' in label: 

153 if self.directory != '.': 

154 msg = ( 

155 'Directory redundantly specified though directory=' 

156 f'"{self.directory}" and label="{label}". Please omit ' 

157 '"/" in label.' 

158 ) 

159 raise ValueError(msg) 

160 self.label = label 

161 else: 

162 self.prefix = label # The label should only contain the prefix 

163 

164 if isinstance(restart, bool): 

165 restart = self.label if restart is True else None 

166 

167 Calculator.__init__( 

168 self, 

169 restart=restart, 

170 ignore_bad_restart_file=ignore_bad_restart_file, 

171 # We already, manually, created the label 

172 label=self.label, 

173 atoms=atoms, 

174 **kwargs, 

175 ) 

176 

177 self.command = command 

178 

179 self._txt = None 

180 self.txt = txt # Set the output txt stream 

181 self.version = None 

182 

183 # XXX: This seems to break restarting, unless we return first. 

184 # Do we really still need to enfore this? 

185 

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

187 # # default to PW91. This is mostly chosen for backwards compatibility. 

188 # if kwargs.get('xc', None): 

189 # pass 

190 # elif not (kwargs.get('gga', None) or kwargs.get('pp', None)): 

191 # self.input_params.update({'xc': 'PW91'}) 

192 # # A null value of xc is permitted; custom recipes can be 

193 # # used by explicitly setting the pseudopotential set and 

194 # # INCAR keys 

195 # else: 

196 # self.input_params.update({'xc': None}) 

197 

198 def make_command(self, command=None): 

199 """Return command if one is passed, otherwise try to find 

200 ASE_VASP_COMMAND, VASP_COMMAND or VASP_SCRIPT. 

201 If none are set, a CalculatorSetupError is raised""" 

202 if command: 

203 cmd = command 

204 else: 

205 # Search for the environment commands 

206 for env in self.env_commands: 

207 if env in cfg: 

208 cmd = cfg[env].replace('PREFIX', self.prefix) 

209 if env == 'VASP_SCRIPT': 

210 # Make the system python exe run $VASP_SCRIPT 

211 exe = sys.executable 

212 cmd = ' '.join([exe, cmd]) 

213 break 

214 else: 

215 msg = ( 

216 'Please set either command in calculator' 

217 ' or one of the following environment ' 

218 'variables (prioritized as follows): {}' 

219 ).format(', '.join(self.env_commands)) 

220 raise calculator.CalculatorSetupError(msg) 

221 return cmd 

222 

223 def set(self, **kwargs): 

224 """Override the set function, to test for changes in the 

225 Vasp Calculator, then call the create_input.set() 

226 on remaining inputs for VASP specific keys. 

227 

228 Allows for setting ``label``, ``directory`` and ``txt`` 

229 without resetting the results in the calculator. 

230 """ 

231 changed_parameters = {} 

232 

233 if 'label' in kwargs: 

234 self.label = kwargs.pop('label') 

235 

236 if 'directory' in kwargs: 

237 # str() call to deal with pathlib objects 

238 self.directory = str(kwargs.pop('directory')) 

239 

240 if 'txt' in kwargs: 

241 self.txt = kwargs.pop('txt') 

242 

243 if 'atoms' in kwargs: 

244 atoms = kwargs.pop('atoms') 

245 self.atoms = atoms # Resets results 

246 

247 if 'command' in kwargs: 

248 self.command = kwargs.pop('command') 

249 

250 changed_parameters.update(Calculator.set(self, **kwargs)) 

251 

252 # We might at some point add more to changed parameters, or use it 

253 if changed_parameters: 

254 self.clear_results() # We don't want to clear atoms 

255 if kwargs: 

256 # If we make any changes to Vasp input, we always reset 

257 GenerateVaspInput.set(self, **kwargs) 

258 self.results.clear() 

259 

260 def reset(self): 

261 self.atoms = None 

262 self.clear_results() 

263 

264 def clear_results(self): 

265 self.results.clear() 

266 self._xml_calc = None 

267 

268 @contextmanager 

269 def _txt_outstream(self): 

270 """Custom function for opening a text output stream. Uses self.txt 

271 to determine the output stream, and accepts a string or an open 

272 writable object. 

273 If a string is used, a new stream is opened, and automatically closes 

274 the new stream again when exiting. 

275 

276 Examples 

277 -------- 

278 # Pass a string 

279 calc.txt = 'vasp.out' 

280 with calc.txt_outstream() as out: 

281 calc.run(out=out) # Redirects the stdout to 'vasp.out' 

282 

283 # Use an existing stream 

284 mystream = open('vasp.out', 'w') 

285 calc.txt = mystream 

286 with calc.txt_outstream() as out: 

287 calc.run(out=out) 

288 mystream.close() 

289 

290 # Print to stdout 

291 calc.txt = '-' 

292 with calc.txt_outstream() as out: 

293 calc.run(out=out) # output is written to stdout 

294 """ 

295 

296 txt = self.txt 

297 open_and_close = False # Do we open the file? 

298 

299 if txt is None: 

300 # Suppress stdout 

301 out = subprocess.DEVNULL 

302 else: 

303 if isinstance(txt, str): 

304 if txt == '-': 

305 # subprocess.call redirects this to stdout 

306 out = None 

307 else: 

308 # Open the file in the work directory 

309 txt = self._indir(txt) 

310 # We wait with opening the file, until we are inside the 

311 # try/finally 

312 open_and_close = True 

313 elif hasattr(txt, 'write'): 

314 out = txt 

315 else: 

316 raise RuntimeError( 

317 'txt should either be a string' 

318 'or an I/O stream, got {}'.format(txt) 

319 ) 

320 

321 try: 

322 if open_and_close: 

323 out = open(txt, 'w') 

324 yield out 

325 finally: 

326 if open_and_close: 

327 out.close() 

328 

329 def calculate( 

330 self, 

331 atoms=None, 

332 properties=('energy',), 

333 system_changes=tuple(calculator.all_changes), 

334 ): 

335 """Do a VASP calculation in the specified directory. 

336 

337 This will generate the necessary VASP input files, and then 

338 execute VASP. After execution, the energy, forces. etc. are read 

339 from the VASP output files. 

340 """ 

341 Calculator.calculate(self, atoms, properties, system_changes) 

342 # Check for zero-length lattice vectors and PBC 

343 # and that we actually have an Atoms object. 

344 check_atoms(self.atoms) 

345 

346 self.clear_results() 

347 

348 command = self.make_command(self.command) 

349 self.write_input(self.atoms, properties, system_changes) 

350 

351 with self._txt_outstream() as out: 

352 errorcode, stderr = self._run( 

353 command=command, out=out, directory=self.directory 

354 ) 

355 

356 if errorcode: 

357 raise calculator.CalculationFailed( 

358 '{} in {} returned an error: {:d} stderr {}'.format( 

359 self.name, Path(self.directory).resolve(), errorcode, stderr 

360 ) 

361 ) 

362 

363 # Read results from calculation 

364 self.update_atoms(atoms) 

365 self.read_results() 

366 

367 def _run(self, command=None, out=None, directory=None): 

368 """Method to explicitly execute VASP""" 

369 if command is None: 

370 command = self.command 

371 if directory is None: 

372 directory = self.directory 

373 result = subprocess.run( 

374 command, shell=True, cwd=directory, capture_output=True, text=True 

375 ) 

376 if out is not None: 

377 out.write(result.stdout) 

378 return result.returncode, result.stderr 

379 

380 def check_state(self, atoms, tol=1e-15): 

381 """Check for system changes since last calculation.""" 

382 

383 def compare_dict(d1, d2): 

384 """Helper function to compare dictionaries""" 

385 # Use symmetric difference to find keys which aren't shared 

386 # for python 2.7 compatibility 

387 if set(d1.keys()) ^ set(d2.keys()): 

388 return False 

389 

390 # Check for differences in values 

391 for key, value in d1.items(): 

392 if np.any(value != d2[key]): 

393 return False 

394 return True 

395 

396 # First we check for default changes 

397 system_changes = Calculator.check_state(self, atoms, tol=tol) 

398 

399 # We now check if we have made any changes to the input parameters 

400 # XXX: Should we add these parameters to all_changes? 

401 for param_string, old_dict in self.param_state.items(): 

402 param_dict = getattr(self, param_string) # Get current param dict 

403 if not compare_dict(param_dict, old_dict): 

404 system_changes.append(param_string) 

405 

406 return system_changes 

407 

408 def _store_param_state(self): 

409 """Store current parameter state""" 

410 self.param_state = dict( 

411 float_params=self.float_params.copy(), 

412 exp_params=self.exp_params.copy(), 

413 string_params=self.string_params.copy(), 

414 int_params=self.int_params.copy(), 

415 input_params=self.input_params.copy(), 

416 bool_params=self.bool_params.copy(), 

417 list_int_params=self.list_int_params.copy(), 

418 list_bool_params=self.list_bool_params.copy(), 

419 list_float_params=self.list_float_params.copy(), 

420 dict_params=self.dict_params.copy(), 

421 special_params=self.special_params.copy(), 

422 ) 

423 

424 def asdict(self): 

425 """Return a dictionary representation of the calculator state. 

426 Does NOT contain information on the ``command``, ``txt`` or 

427 ``directory`` keywords. 

428 Contains the following keys: 

429 

430 - ``ase_version`` 

431 - ``vasp_version`` 

432 - ``inputs`` 

433 - ``results`` 

434 - ``atoms`` (Only if the calculator has an ``Atoms`` object) 

435 """ 

436 # Get versions 

437 asevers = ase.__version__ 

438 vaspvers = self.get_version() 

439 

440 self._store_param_state() # Update param state 

441 # Store input parameters which have been set 

442 inputs = { 

443 key: value 

444 for param_dct in self.param_state.values() 

445 for key, value in param_dct.items() 

446 if value is not None 

447 } 

448 

449 dct = { 

450 'ase_version': asevers, 

451 'vasp_version': vaspvers, 

452 # '__ase_objtype__': self.ase_objtype, 

453 'inputs': inputs, 

454 'results': self.results.copy(), 

455 } 

456 

457 if self.atoms: 

458 # Encode atoms as dict 

459 from ase.db.row import atoms2dict 

460 

461 dct['atoms'] = atoms2dict(self.atoms) 

462 

463 return dct 

464 

465 def fromdict(self, dct): 

466 """Restore calculator from a :func:`~ase.calculators.vasp.Vasp.asdict` 

467 dictionary. 

468 

469 Parameters 

470 ---------- 

471 

472 dct: Dictionary 

473 The dictionary which is used to restore the calculator state. 

474 """ 

475 if 'vasp_version' in dct: 

476 self.version = dct['vasp_version'] 

477 if 'inputs' in dct: 

478 self.set(**dct['inputs']) 

479 self._store_param_state() 

480 if 'atoms' in dct: 

481 from ase.db.row import AtomsRow 

482 

483 atoms = AtomsRow(dct['atoms']).toatoms() 

484 self.atoms = atoms 

485 if 'results' in dct: 

486 self.results.update(dct['results']) 

487 

488 def write_json(self, filename): 

489 """Dump calculator state to JSON file. 

490 

491 Parameters 

492 ---------- 

493 

494 filename: string 

495 The filename which the JSON file will be stored to. 

496 Prepends the ``directory`` path to the filename. 

497 """ 

498 filename = self._indir(filename) 

499 dct = self.asdict() 

500 jsonio.write_json(filename, dct) 

501 

502 def read_json(self, filename): 

503 """Load Calculator state from an exported JSON Vasp file.""" 

504 dct = jsonio.read_json(filename) 

505 self.fromdict(dct) 

506 

507 def write_input(self, atoms, properties=None, system_changes=None): 

508 """Write VASP inputfiles, INCAR, KPOINTS and POTCAR""" 

509 self.initialize(atoms) 

510 GenerateVaspInput.write_input(self, atoms, directory=self.directory) 

511 

512 def read(self, label=None): 

513 """Read results from VASP output files. 

514 Files which are read: OUTCAR, CONTCAR and vasprun.xml 

515 Raises ReadError if they are not found""" 

516 if label is None: 

517 label = self.label 

518 Calculator.read(self, label) 

519 

520 # If we restart, self.parameters isn't initialized 

521 if self.parameters is None: 

522 self.parameters = self.get_default_parameters() 

523 

524 # Check for existence of the necessary output files 

525 for f in ['OUTCAR', 'CONTCAR', 'vasprun.xml']: 

526 file = self._indir(f) 

527 if not file.is_file(): 

528 raise calculator.ReadError( 

529 f'VASP outputfile {file} was not found' 

530 ) 

531 

532 # Build sorting and resorting lists 

533 self.read_sort() 

534 

535 # Read atoms 

536 self.atoms = self.read_atoms(filename=self._indir('CONTCAR')) 

537 

538 # Read parameters 

539 self.read_incar(filename=self._indir('INCAR')) 

540 self.read_kpoints(filename=self._indir('KPOINTS')) 

541 if self._indir('KPOINTS_OPT').is_file(): 

542 self.read_kpoints(filename=self._indir('KPOINTS_OPT'), opt=True) 

543 self.read_potcar(filename=self._indir('POTCAR')) 

544 

545 # Read the results from the calculation 

546 self.read_results() 

547 

548 def _indir(self, filename): 

549 """Prepend current directory to filename""" 

550 return Path(self.directory) / filename 

551 

552 def read_sort(self): 

553 """Create the sorting and resorting list from ase-sort.dat. 

554 If the ase-sort.dat file does not exist, the sorting is redone. 

555 """ 

556 sortfile = self._indir('ase-sort.dat') 

557 if os.path.isfile(sortfile): 

558 self.sort = [] 

559 self.resort = [] 

560 with open(sortfile) as fd: 

561 for line in fd: 

562 sort, resort = line.split() 

563 self.sort.append(int(sort)) 

564 self.resort.append(int(resort)) 

565 else: 

566 # Redo the sorting 

567 atoms = read(self._indir('CONTCAR')) 

568 self.initialize(atoms) 

569 

570 def read_atoms(self, filename): 

571 """Read the atoms from file located in the VASP 

572 working directory. Normally called CONTCAR.""" 

573 return read(filename)[self.resort] 

574 

575 def update_atoms(self, atoms): 

576 """Update the atoms object with new positions and cell""" 

577 if ( 

578 self.int_params.get('ibrion') is not None 

579 and self.int_params.get('nsw') is not None 

580 ): 

581 if self.int_params['ibrion'] > -1 and self.int_params['nsw'] > 0: 

582 # Update atomic positions and unit cell with the ones read 

583 # from CONTCAR. 

584 atoms_sorted = read(self._indir('CONTCAR')) 

585 atoms.positions = atoms_sorted[self.resort].positions 

586 atoms.cell = atoms_sorted.cell 

587 

588 self.atoms = atoms # Creates a copy 

589 

590 def read_results(self): 

591 """Read the results from VASP output files""" 

592 # Temporarily load OUTCAR into memory 

593 outcar = self.load_file('OUTCAR') 

594 

595 # Read the data we can from vasprun.xml 

596 calc_xml = self._read_xml() 

597 xml_results = calc_xml.results 

598 

599 # Fix sorting 

600 xml_results['forces'] = xml_results['forces'][self.resort] 

601 

602 self.results.update(xml_results) 

603 

604 # Parse the outcar, as some properties are not loaded in vasprun.xml 

605 # We want to limit this as much as possible, as reading large OUTCAR's 

606 # is relatively slow 

607 # Removed for now 

608 # self.read_outcar(lines=outcar) 

609 

610 # Update results dict with results from OUTCAR 

611 # which aren't written to the atoms object we read from 

612 # the vasprun.xml file. 

613 

614 self.converged = self.read_convergence(lines=outcar) 

615 self.version = self.read_version() 

616 magmom, magmoms = self.read_mag(lines=outcar) 

617 dipole = self.read_dipole(lines=outcar) 

618 nbands = self.read_nbands(lines=outcar) 

619 self.results.update( 

620 dict(magmom=magmom, magmoms=magmoms, dipole=dipole, nbands=nbands) 

621 ) 

622 

623 # Stress is not always present. 

624 # Prevent calculation from going into a loop 

625 if 'stress' not in self.results: 

626 self.results.update(dict(stress=None)) 

627 

628 self._set_old_keywords() 

629 

630 # Store the parameters used for this calculation 

631 self._store_param_state() 

632 

633 def _set_old_keywords(self): 

634 """Store keywords for backwards compatibility wd VASP calculator""" 

635 self.spinpol = self.get_spin_polarized() 

636 self.fermi = self.get_fermi_level() 

637 self.nbands = self.get_number_of_bands() 

638 

639 # Below defines some functions for faster access to certain common keywords 

640 @property 

641 def kpts(self): 

642 """Access the kpts from input_params dict""" 

643 return self.input_params['kpts'] 

644 

645 @kpts.setter 

646 def kpts(self, kpts): 

647 """Set kpts in input_params dict""" 

648 self.input_params['kpts'] = kpts 

649 

650 @property 

651 def encut(self): 

652 """Direct access to the encut parameter""" 

653 return self.float_params.get('encut', self.int_params.get('encut')) 

654 

655 @encut.setter 

656 def encut(self, encut): 

657 """Direct access for setting the encut parameter""" 

658 self.set(encut=encut) 

659 

660 @property 

661 def xc(self): 

662 """Direct access to the xc parameter""" 

663 return self.get_xc_functional() 

664 

665 @xc.setter 

666 def xc(self, xc): 

667 """Direct access for setting the xc parameter""" 

668 self.set(xc=xc) 

669 

670 @property 

671 def atoms(self): 

672 return self._atoms 

673 

674 @atoms.setter 

675 def atoms(self, atoms): 

676 if atoms is None: 

677 self._atoms = None 

678 self.clear_results() 

679 else: 

680 if self.check_state(atoms): 

681 self.clear_results() 

682 self._atoms = atoms.copy() 

683 

684 def load_file(self, filename): 

685 """Reads a file in the directory, and returns the lines 

686 

687 Example: 

688 >>> from ase.calculators.vasp import Vasp 

689 >>> calc = Vasp() 

690 >>> outcar = calc.load_file('OUTCAR') # doctest: +SKIP 

691 """ 

692 filename = self._indir(filename) 

693 with open(filename) as fd: 

694 return fd.readlines() 

695 

696 @contextmanager 

697 def load_file_iter(self, filename): 

698 """Return a file iterator""" 

699 

700 filename = self._indir(filename) 

701 with open(filename) as fd: 

702 yield fd 

703 

704 def read_outcar(self, lines=None): 

705 """Read results from the OUTCAR file. 

706 Deprecated, see read_results()""" 

707 if not lines: 

708 lines = self.load_file('OUTCAR') 

709 # Spin polarized calculation? 

710 self.spinpol = self.get_spin_polarized() 

711 

712 self.version = self.get_version() 

713 

714 # XXX: Do we want to read all of this again? 

715 self.fermi = self.read_fermi(lines=lines) 

716 

717 self.nbands = self.read_nbands(lines=lines) 

718 

719 self.read_ldau() 

720 

721 def _read_xml(self) -> SinglePointDFTCalculator: 

722 """Read vasprun.xml, and return the last calculator object. 

723 Returns calculator from the xml file. 

724 Raises a ReadError if the reader is not able to construct a calculator. 

725 """ 

726 file = self._indir('vasprun.xml') 

727 incomplete_msg = ( 

728 f'The file "{file}" is incomplete, and no DFT data was available. ' 

729 'This is likely due to an incomplete calculation.' 

730 ) 

731 try: 

732 _xml_atoms = read(file, index=-1, format='vasp-xml') 

733 # Silence mypy, we should only ever get a single atoms object 

734 assert isinstance(_xml_atoms, ase.Atoms) 

735 except ElementTree.ParseError as exc: 

736 raise calculator.ReadError(incomplete_msg) from exc 

737 

738 if _xml_atoms is None or _xml_atoms.calc is None: 

739 raise calculator.ReadError(incomplete_msg) 

740 

741 self._xml_calc = _xml_atoms.calc 

742 return self._xml_calc 

743 

744 @property 

745 def _xml_calc(self) -> SinglePointDFTCalculator: 

746 if self.__xml_calc is None: 

747 raise RuntimeError( 

748 'vasprun.xml data has not yet been loaded. ' 

749 'Run read_results() first.' 

750 ) 

751 return self.__xml_calc 

752 

753 @_xml_calc.setter 

754 def _xml_calc(self, value): 

755 self.__xml_calc = value 

756 

757 def get_ibz_k_points(self): 

758 calc = self._xml_calc 

759 return calc.get_ibz_k_points() 

760 

761 def get_kpt(self, kpt=0, spin=0): 

762 calc = self._xml_calc 

763 return calc.get_kpt(kpt=kpt, spin=spin) 

764 

765 def get_eigenvalues(self, kpt=0, spin=0): 

766 calc = self._xml_calc 

767 return calc.get_eigenvalues(kpt=kpt, spin=spin) 

768 

769 def get_fermi_level(self): 

770 calc = self._xml_calc 

771 return calc.get_fermi_level() 

772 

773 def get_homo_lumo(self): 

774 calc = self._xml_calc 

775 return calc.get_homo_lumo() 

776 

777 def get_homo_lumo_by_spin(self, spin=0): 

778 calc = self._xml_calc 

779 return calc.get_homo_lumo_by_spin(spin=spin) 

780 

781 def get_occupation_numbers(self, kpt=0, spin=0): 

782 calc = self._xml_calc 

783 return calc.get_occupation_numbers(kpt, spin) 

784 

785 def get_spin_polarized(self): 

786 calc = self._xml_calc 

787 return calc.get_spin_polarized() 

788 

789 def get_number_of_spins(self): 

790 calc = self._xml_calc 

791 return calc.get_number_of_spins() 

792 

793 def get_number_of_bands(self): 

794 return self.results.get('nbands', None) 

795 

796 def get_number_of_electrons(self, lines=None): 

797 if not lines: 

798 lines = self.load_file('OUTCAR') 

799 

800 nelect = None 

801 for line in lines: 

802 if 'total number of electrons' in line: 

803 nelect = float(line.split('=')[1].split()[0].strip()) 

804 break 

805 return nelect 

806 

807 def get_k_point_weights(self): 

808 filename = 'IBZKPT' 

809 return self.read_k_point_weights(filename) 

810 

811 def get_dos(self, spin=None, **kwargs): 

812 """ 

813 The total DOS. 

814 

815 Uses the ASE DOS module, and returns a tuple with 

816 (energies, dos). 

817 """ 

818 from ase.dft.dos import DOS 

819 

820 dos = DOS(self, **kwargs) 

821 e = dos.get_energies() 

822 d = dos.get_dos(spin=spin) 

823 return e, d 

824 

825 def get_version(self): 

826 if self.version is None: 

827 # Try if we can read the version number 

828 self.version = self.read_version() 

829 return self.version 

830 

831 def read_version(self): 

832 """Get the VASP version number""" 

833 # The version number is the first occurrence, so we can just 

834 # load the OUTCAR, as we will return soon anyway 

835 if not os.path.isfile(self._indir('OUTCAR')): 

836 return None 

837 with self.load_file_iter('OUTCAR') as lines: 

838 for line in lines: 

839 if ' vasp.' in line: 

840 return line[len(' vasp.') :].split()[0] 

841 # We didn't find the version in VASP 

842 return None 

843 

844 def get_number_of_iterations(self): 

845 return self.read_number_of_iterations() 

846 

847 def read_number_of_iterations(self): 

848 niter = None 

849 with self.load_file_iter('OUTCAR') as lines: 

850 for line in lines: 

851 # find the last iteration number 

852 if '- Iteration' in line: 

853 niter = list(map(int, re.findall(r'\d+', line)))[1] 

854 return niter 

855 

856 def read_number_of_ionic_steps(self): 

857 niter = None 

858 with self.load_file_iter('OUTCAR') as lines: 

859 for line in lines: 

860 if '- Iteration' in line: 

861 niter = list(map(int, re.findall(r'\d+', line)))[0] 

862 return niter 

863 

864 def read_ldau(self, lines=None): 

865 """Read the LDA+U values from OUTCAR""" 

866 if not lines: 

867 lines = self.load_file('OUTCAR') 

868 

869 ldau_luj = None 

870 ldauprint = None 

871 ldau = None 

872 ldautype = None 

873 atomtypes = [] 

874 # read ldau parameters from outcar 

875 for line in lines: 

876 if line.find('TITEL') != -1: # What atoms are present 

877 atomtypes.append(line.split()[3].split('_')[0].split('.')[0]) 

878 if line.find('LDAUTYPE') != -1: # Is this a DFT+U calculation 

879 ldautype = int(line.split('=')[-1]) 

880 ldau = True 

881 ldau_luj = {} 

882 if line.find('LDAUL') != -1: 

883 L = line.split('=')[-1].split() 

884 if line.find('LDAUU') != -1: 

885 U = line.split('=')[-1].split() 

886 if line.find('LDAUJ') != -1: 

887 J = line.split('=')[-1].split() 

888 # create dictionary 

889 if ldau: 

890 for i, symbol in enumerate(atomtypes): 

891 ldau_luj[symbol] = { 

892 'L': int(L[i]), 

893 'U': float(U[i]), 

894 'J': float(J[i]), 

895 } 

896 self.dict_params['ldau_luj'] = ldau_luj 

897 

898 self.ldau = ldau 

899 self.ldauprint = ldauprint 

900 self.ldautype = ldautype 

901 self.ldau_luj = ldau_luj 

902 return ldau, ldauprint, ldautype, ldau_luj 

903 

904 def get_xc_functional(self): 

905 """Returns the XC functional or the pseudopotential type 

906 

907 If a XC recipe is set explicitly with 'xc', this is returned. 

908 Otherwise, the XC functional associated with the 

909 pseudopotentials (LDA, PW91 or PBE) is returned. 

910 The string is always cast to uppercase for consistency 

911 in checks.""" 

912 if self.input_params.get('xc', None): 

913 return self.input_params['xc'].upper() 

914 if self.input_params.get('pp', None): 

915 return self.input_params['pp'].upper() 

916 raise ValueError('No xc or pp found.') 

917 

918 # Methods for reading information from OUTCAR files: 

919 def read_fermi(self, lines=None): 

920 """Method that reads Fermi energy from OUTCAR file""" 

921 if not lines: 

922 lines = self.load_file('OUTCAR') 

923 

924 E_f = None 

925 for line in lines: 

926 if 'E-fermi' in line: 

927 E_f = float(line.split()[2]) 

928 return E_f 

929 

930 def read_dipole(self, lines=None): 

931 """Read dipole from OUTCAR""" 

932 if not lines: 

933 lines = self.load_file('OUTCAR') 

934 

935 dipolemoment = np.zeros([1, 3]) 

936 for line in lines: 

937 if 'dipolmoment' in line: 

938 dipolemoment = np.array([float(f) for f in line.split()[1:4]]) 

939 return dipolemoment 

940 

941 def read_mag(self, lines=None): 

942 if not lines: 

943 lines = self.load_file('OUTCAR') 

944 p = self.int_params 

945 q = self.list_float_params 

946 if self.spinpol: 

947 magnetic_moment = self._read_magnetic_moment(lines=lines) 

948 if (p['lorbit'] is not None and p['lorbit'] >= 10) or ( 

949 p['lorbit'] is None and q['rwigs'] 

950 ): 

951 magnetic_moments = self._read_magnetic_moments(lines=lines) 

952 else: 

953 warn( 

954 'Magnetic moment data not written in OUTCAR (LORBIT<10),' 

955 ' setting magnetic_moments to zero.\nSet LORBIT>=10' 

956 ' to get information on magnetic moments' 

957 ) 

958 magnetic_moments = np.zeros(len(self.atoms)) 

959 else: 

960 magnetic_moment = 0.0 

961 magnetic_moments = np.zeros(len(self.atoms)) 

962 return magnetic_moment, magnetic_moments 

963 

964 def _read_magnetic_moments(self, lines=None): 

965 """Read magnetic moments from OUTCAR. 

966 Only reads the last occurrence.""" 

967 if not lines: 

968 lines = self.load_file('OUTCAR') 

969 

970 natoms = len(self.atoms) 

971 

972 labels = [ 

973 'magnetization (x)', 

974 'magnetization (y)', 

975 'magnetization (z)', 

976 ] 

977 

978 indices = {label: -1 for label in labels} 

979 

980 # Find last occurrence of each magnetization block 

981 for n, line in enumerate(lines): 

982 for label in labels: 

983 if label in line: 

984 indices[label] = n 

985 

986 x_idx = indices['magnetization (x)'] 

987 y_idx = indices['magnetization (y)'] 

988 z_idx = indices['magnetization (z)'] 

989 

990 # Non-collinear calculation 

991 if y_idx >= 0 and z_idx >= 0: 

992 magnetic_moments = np.zeros((natoms, 3)) 

993 

994 for component, idx in enumerate((x_idx, y_idx, z_idx)): 

995 for atom in range(natoms): 

996 magnetic_moments[atom, component] = float( 

997 lines[idx + atom + 4].split()[-1] 

998 ) 

999 

1000 # Collinear calculation 

1001 else: 

1002 magnetic_moments = np.zeros(natoms) 

1003 

1004 if x_idx >= 0: 

1005 for atom in range(natoms): 

1006 magnetic_moments[atom] = float( 

1007 lines[x_idx + atom + 4].split()[-1] 

1008 ) 

1009 

1010 return magnetic_moments[self.resort] 

1011 

1012 def _read_magnetic_moment(self, lines=None): 

1013 """Read magnetic moment from OUTCAR""" 

1014 if not lines: 

1015 lines = self.load_file('OUTCAR') 

1016 

1017 for line in lines: 

1018 if 'number of electron ' in line: 

1019 _ = line.split()[-1] 

1020 magnetic_moment = 0.0 if _ == 'magnetization' else float(_) 

1021 return magnetic_moment 

1022 

1023 def read_nbands(self, lines=None): 

1024 """Read number of bands from OUTCAR""" 

1025 if not lines: 

1026 lines = self.load_file('OUTCAR') 

1027 

1028 for line in lines: 

1029 line = self.strip_warnings(line) 

1030 if 'NBANDS' in line: 

1031 return int(line.split()[-1]) 

1032 return None 

1033 

1034 def read_convergence(self, lines=None): 

1035 """Method that checks whether a calculation has converged.""" 

1036 if not lines: 

1037 lines = self.load_file('OUTCAR') 

1038 

1039 converged = None 

1040 # First check electronic convergence 

1041 for line in lines: 

1042 # VASP 6 actually labels loop exit reason 

1043 if 'aborting loop' in line: 

1044 converged = 'because EDIFF is reached' in line 

1045 # NOTE: 'EDIFF was not reached (unconverged)' 

1046 # and 

1047 # 'because hard stop was set' 

1048 # will result in unconverged 

1049 break 

1050 # determine convergence by attempting to reproduce VASP's 

1051 # internal logic 

1052 if 'EDIFF ' in line: 

1053 ediff = float(line.split()[2]) 

1054 if 'total energy-change' in line: 

1055 # I saw this in an atomic oxygen calculation. it 

1056 # breaks this code, so I am checking for it here. 

1057 if 'MIXING' in line: 

1058 continue 

1059 split = line.split(':') 

1060 a = float(split[1].split('(')[0]) 

1061 b = split[1].split('(')[1][0:-2] 

1062 # sometimes this line looks like (second number wrong format!): 

1063 # energy-change (2. order) :-0.2141803E-08 ( 0.2737684-111) 

1064 # we are checking still the first number so 

1065 # let's "fix" the format for the second one 

1066 if 'e' not in b.lower(): 

1067 # replace last occurrence of - (assumed exponent) with -e 

1068 bsplit = b.split('-') 

1069 bsplit[-1] = 'e' + bsplit[-1] 

1070 b = '-'.join(bsplit).replace('-e', 'e-') 

1071 b = float(b) 

1072 if [abs(a), abs(b)] < [ediff, ediff]: 

1073 converged = True 

1074 else: 

1075 converged = False 

1076 continue 

1077 # Then if ibrion in [1,2,3] check whether ionic relaxation 

1078 # condition been fulfilled 

1079 if self.int_params.get('ibrion') in [1, 2, 3] and self.int_params.get( 

1080 'nsw' 

1081 ) not in [0]: 

1082 if not self.read_relaxed(): 

1083 converged = False 

1084 else: 

1085 converged = True 

1086 return converged 

1087 

1088 def read_k_point_weights(self, filename): 

1089 """Read k-point weighting. Normally named IBZKPT.""" 

1090 

1091 lines = self.load_file(filename) 

1092 

1093 if 'Tetrahedra\n' in lines: 

1094 N = lines.index('Tetrahedra\n') 

1095 else: 

1096 N = len(lines) 

1097 kpt_weights = [] 

1098 for n in range(3, N): 

1099 kpt_weights.append(float(lines[n].split()[3])) 

1100 kpt_weights = np.array(kpt_weights) 

1101 kpt_weights /= np.sum(kpt_weights) 

1102 

1103 return kpt_weights 

1104 

1105 def read_relaxed(self, lines=None): 

1106 """Check if ionic relaxation completed""" 

1107 if not lines: 

1108 lines = self.load_file('OUTCAR') 

1109 for line in lines: 

1110 if 'reached required accuracy' in line: 

1111 return True 

1112 return False 

1113 

1114 def read_spinpol(self, lines=None): 

1115 """Method which reads if a calculation from spinpolarized using OUTCAR. 

1116 

1117 Depreciated: Use get_spin_polarized() instead. 

1118 """ 

1119 if not lines: 

1120 lines = self.load_file('OUTCAR') 

1121 

1122 for line in lines: 

1123 if 'ISPIN' in line: 

1124 if int(line.split()[2]) == 2: 

1125 self.spinpol = True 

1126 else: 

1127 self.spinpol = False 

1128 return self.spinpol 

1129 

1130 def strip_warnings(self, line): 

1131 """Returns empty string instead of line from warnings in OUTCAR.""" 

1132 if line[0] == '|': 

1133 return '' 

1134 return line 

1135 

1136 @property 

1137 def txt(self): 

1138 return self._txt 

1139 

1140 @txt.setter 

1141 def txt(self, txt): 

1142 if isinstance(txt, PurePath): 

1143 txt = str(txt) 

1144 self._txt = txt 

1145 

1146 def get_number_of_grid_points(self): 

1147 raise NotImplementedError 

1148 

1149 def get_pseudo_density(self): 

1150 raise NotImplementedError 

1151 

1152 def get_pseudo_wavefunction(self, n=0, k=0, s=0, pad=True): 

1153 raise NotImplementedError 

1154 

1155 def get_bz_k_points(self): 

1156 raise NotImplementedError 

1157 

1158 def read_vib_freq(self, lines=None) -> tuple[list[float], list[float]]: 

1159 """Read vibrational frequencies. 

1160 

1161 Returns 

1162 ------- 

1163 List of real and list of imaginary frequencies 

1164 (imaginary number as real number). 

1165 """ 

1166 freq = [] 

1167 i_freq = [] 

1168 

1169 if not lines: 

1170 lines = self.load_file('OUTCAR') 

1171 

1172 for line in lines: 

1173 data = line.split() 

1174 if 'THz' in data: 

1175 if 'f/i=' not in data: 

1176 freq.append(float(data[-2])) 

1177 else: 

1178 i_freq.append(float(data[-2])) 

1179 return freq, i_freq 

1180 

1181 def _read_massweighted_hessian_xml(self): 

1182 """Read the Mass Weighted Hessian from vasprun.xml. 

1183 

1184 Returns 

1185 ------- 

1186 The Mass Weighted Hessian as np.ndarray from the xml file. 

1187 

1188 Raises a ReadError if the reader is not able to read the Hessian. 

1189 

1190 Converts to ASE units for VASP version 6. 

1191 """ 

1192 

1193 file = self._indir('vasprun.xml') 

1194 try: 

1195 tree = ElementTree.iterparse(file) 

1196 hessian = None 

1197 for event, elem in tree: 

1198 if elem.tag == 'dynmat': 

1199 for i, entry in enumerate( 

1200 elem.findall('varray[@name="hessian"]/v') 

1201 ): 

1202 text_split = entry.text.split() 

1203 if not text_split: 

1204 raise ElementTree.ParseError( 

1205 'Could not find varray hessian!' 

1206 ) 

1207 if i == 0: 

1208 n_items = len(text_split) 

1209 hessian = np.zeros((n_items, n_items)) 

1210 assert isinstance(hessian, np.ndarray) 

1211 hessian[i, :] = np.array( 

1212 [float(val) for val in text_split] 

1213 ) 

1214 if i != n_items - 1: 

1215 raise ElementTree.ParseError( 

1216 'Hessian is not quadratic!' 

1217 ) 

1218 # VASP6+ uses THz**2 as unit, not mEV**2 as before 

1219 for entry in elem.findall('i[@name="unit"]'): 

1220 if entry.text.strip() == 'THz^2': 

1221 conv = ( 

1222 ase.units._amu 

1223 / ase.units._e 

1224 / 1e-4 

1225 * (2 * np.pi) ** 2 

1226 ) # THz**2 to eV**2 

1227 # VASP6 uses factor 2pi 

1228 # 1e-4 = (angstrom to meter times Hz to THz) squared 

1229 # = (1e10 times 1e-12)**2 

1230 break 

1231 else: # Catch changes in VASP 

1232 vasp_version_error_msg = ( 

1233 f'The file "{file}" is from a ' 

1234 'non-supported VASP version. ' 

1235 'Not sure what unit the Hessian ' 

1236 'is in, aborting.' 

1237 ) 

1238 raise calculator.ReadError(vasp_version_error_msg) 

1239 

1240 else: 

1241 conv = 1.0 # VASP version <6 unit is meV**2 

1242 assert isinstance(hessian, np.ndarray) 

1243 hessian *= conv 

1244 if hessian is None: 

1245 raise ElementTree.ParseError('Hessian is None!') 

1246 

1247 except ElementTree.ParseError as exc: 

1248 incomplete_msg = ( 

1249 f'The file "{file}" is incomplete, ' 

1250 'and no DFT data was available. ' 

1251 'This is likely due to an incomplete calculation.' 

1252 ) 

1253 raise calculator.ReadError(incomplete_msg) from exc 

1254 # VASP uses the negative definition of the hessian compared to ASE 

1255 return -hessian 

1256 

1257 def get_vibrations(self) -> VibrationsData: 

1258 """Get a VibrationsData Object from a VASP Calculation. 

1259 

1260 Returns 

1261 ------- 

1262 VibrationsData object. 

1263 

1264 Note that the atoms in the VibrationsData object can be resorted. 

1265 

1266 Uses the (mass weighted) Hessian from vasprun.xml, different masses 

1267 in the POTCAR can therefore result in different results. 

1268 

1269 Note the limitations concerning k-points and symmetry mentioned in 

1270 the VASP-Wiki. 

1271 """ 

1272 

1273 mass_weighted_hessian = self._read_massweighted_hessian_xml() 

1274 # get indices of freely moving atoms, i.e. respect constraints. 

1275 indices = VibrationsData.indices_from_constraints(self.atoms) 

1276 # save the corresponding sorted atom numbers 

1277 sort_indices = np.array(self.sort)[indices] 

1278 # mass weights = 1/sqrt(mass) 

1279 mass_weights = np.repeat( 

1280 self.atoms.get_masses()[sort_indices] ** -0.5, 3 

1281 ) 

1282 # get the unweighted hessian = H_w / m_w / m_w^T 

1283 # ugly and twice the work, but needed since vasprun.xml does 

1284 # not have the unweighted ase.vibrations.vibration will do the 

1285 # opposite in Vibrations.read 

1286 hessian = ( 

1287 mass_weighted_hessian / mass_weights / mass_weights[:, np.newaxis] 

1288 ) 

1289 

1290 return VibrationsData.from_2d(self.atoms[self.sort], hessian, indices) 

1291 

1292 def get_nonselfconsistent_energies(self, bee_type): 

1293 """Method that reads and returns BEE energy contributions 

1294 written in OUTCAR file. 

1295 """ 

1296 assert bee_type == 'beefvdw' 

1297 cmd = 'grep -32 "BEEF xc energy contributions" OUTCAR | tail -32' 

1298 p = os.popen(cmd, 'r') 

1299 s = p.readlines() 

1300 p.close() 

1301 xc = np.array([]) 

1302 for line in s: 

1303 l_ = float(line.split(':')[-1]) 

1304 xc = np.append(xc, l_) 

1305 assert len(xc) == 32 

1306 return xc 

1307 

1308 

1309##################################### 

1310# Below defines helper functions 

1311# for the VASP calculator 

1312##################################### 

1313 

1314 

1315def check_atoms(atoms: ase.Atoms) -> None: 

1316 """Perform checks on the atoms object, to verify that 

1317 it can be run by VASP. 

1318 A CalculatorSetupError error is raised if the atoms are not supported. 

1319 """ 

1320 

1321 # Loop through all check functions 

1322 for check in (check_atoms_type, check_cell, check_pbc): 

1323 check(atoms) 

1324 

1325 

1326def check_cell(atoms: ase.Atoms) -> None: 

1327 """Check if there is a zero unit cell. 

1328 Raises CalculatorSetupError if the cell is wrong. 

1329 """ 

1330 if atoms.cell.rank < 3: 

1331 raise calculator.CalculatorSetupError( 

1332 'The lattice vectors are zero! ' 

1333 'This is the default value - please specify a ' 

1334 'unit cell.' 

1335 ) 

1336 

1337 

1338def check_pbc(atoms: ase.Atoms) -> None: 

1339 """Check if any boundaries are not PBC, as VASP 

1340 cannot handle non-PBC. 

1341 Raises CalculatorSetupError. 

1342 """ 

1343 if not atoms.pbc.all(): 

1344 raise calculator.CalculatorSetupError( 

1345 'Vasp cannot handle non-periodic boundaries. ' 

1346 'Please enable all PBC, e.g. atoms.pbc=True' 

1347 ) 

1348 

1349 

1350def check_atoms_type(atoms: ase.Atoms) -> None: 

1351 """Check that the passed atoms object is in fact an Atoms object. 

1352 Raises CalculatorSetupError. 

1353 """ 

1354 if not isinstance(atoms, ase.Atoms): 

1355 raise calculator.CalculatorSetupError( 

1356 'Expected an Atoms object, instead got object of type {}'.format( 

1357 type(atoms) 

1358 ) 

1359 )