Coverage for ase/io/vasp.py: 90.93%

518 statements  

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

1""" 

2This module contains functionality for reading and writing an ASE 

3Atoms object in VASP POSCAR format. 

4 

5""" 

6 

7from __future__ import annotations 

8 

9import re 

10from collections import OrderedDict 

11from pathlib import Path 

12from typing import TextIO 

13 

14import numpy as np 

15 

16from ase import Atoms 

17from ase.constraints import FixAtoms, FixedLine, FixedPlane, FixScaled 

18from ase.constraints.constraint import FixConstraint 

19from ase.io import ParseError 

20from ase.io.formats import string2index 

21from ase.io.utils import ImageIterator 

22from ase.symbols import Symbols 

23from ase.units import Ang, GPa, fs 

24from ase.utils import reader, writer 

25 

26from .vasp_parsers import vasp_outcar_parsers as vop 

27 

28__all__ = [ 

29 'read_vasp', 

30 'read_vasp_out', 

31 'iread_vasp_out', 

32 'read_vasp_xdatcar', 

33 'read_vasp_xml', 

34 'write_vasp', 

35 'write_vasp_xdatcar', 

36] 

37 

38EVTOJ = 1.60217733e-19 # VASP constant.F 

39 

40 

41def parse_poscar_scaling_factor(line: str) -> np.ndarray: 

42 """Parse scaling factor(s) in the second line in POSCAR/CONTCAR. 

43 

44 This can also be one negative number or three positive numbers. 

45 

46 https://www.vasp.at/wiki/index.php/POSCAR#Full_format_specification 

47 

48 """ 

49 scale = [] 

50 for _ in line.split()[:3]: 

51 try: 

52 scale.append(float(_)) 

53 except ValueError: 

54 break 

55 if len(scale) not in {1, 3}: 

56 raise RuntimeError('The number of scaling factors must be 1 or 3.') 

57 if len(scale) == 3 and any(_ < 0.0 for _ in scale): 

58 raise RuntimeError('All three scaling factors must be positive.') 

59 return np.array(scale) 

60 

61 

62def get_atomtypes(fname): 

63 """Given a file name, get the atomic symbols. 

64 

65 The function can get this information from OUTCAR and POTCAR 

66 format files. The files can also be compressed with gzip or 

67 bzip2. 

68 

69 """ 

70 fpath = Path(fname) 

71 

72 atomtypes = [] 

73 atomtypes_alt = [] 

74 if fpath.suffix == '.gz': 

75 import gzip 

76 

77 opener = gzip.open 

78 elif fpath.suffix == '.bz2': 

79 import bz2 

80 

81 opener = bz2.BZ2File 

82 else: 

83 opener = open 

84 with opener(fpath) as fd: 

85 for line in fd: 

86 if 'TITEL' in line: 

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

88 elif 'POTCAR:' in line: 

89 atomtypes_alt.append( 

90 line.split()[2].split('_')[0].split('.')[0] 

91 ) 

92 

93 if len(atomtypes) == 0 and len(atomtypes_alt) > 0: 

94 # old VASP doesn't echo TITEL, but all versions print out species 

95 # lines preceded by "POTCAR:", twice 

96 if len(atomtypes_alt) % 2 != 0: 

97 raise ParseError( 

98 f'Tried to get atom types from {len(atomtypes_alt)}' 

99 '"POTCAR": lines in OUTCAR, but expected an even number' 

100 ) 

101 atomtypes = atomtypes_alt[0 : len(atomtypes_alt) // 2] 

102 

103 return atomtypes 

104 

105 

106def atomtypes_outpot(posfname, numsyms): 

107 """Try to retrieve chemical symbols from OUTCAR or POTCAR 

108 

109 If getting atomtypes from the first line in POSCAR/CONTCAR fails, it might 

110 be possible to find the data in OUTCAR or POTCAR, if these files exist. 

111 

112 posfname -- The filename of the POSCAR/CONTCAR file we're trying to read 

113 

114 numsyms -- The number of symbols we must find 

115 

116 """ 

117 posfpath = Path(posfname) 

118 

119 # Check files with exactly same path except POTCAR/OUTCAR instead 

120 # of POSCAR/CONTCAR. 

121 fnames = [posfpath.with_name('POTCAR'), posfpath.with_name('OUTCAR')] 

122 # Try the same but with compressed files 

123 fsc = [] 

124 for fnpath in fnames: 

125 fsc.append(fnpath.parent / (fnpath.name + '.gz')) 

126 fsc.append(fnpath.parent / (fnpath.name + '.bz2')) 

127 for f in fsc: 

128 fnames.append(f) 

129 # Code used to try anything with POTCAR or OUTCAR in the name 

130 # but this is no longer supported 

131 

132 tried = [] 

133 for fn in fnames: 

134 if fn in posfpath.parent.iterdir(): 

135 tried.append(fn) 

136 at = get_atomtypes(fn) 

137 if len(at) == numsyms: 

138 return at 

139 

140 raise ParseError( 

141 'Could not determine chemical symbols. Tried files ' + str(tried) 

142 ) 

143 

144 

145def get_atomtypes_from_formula(formula): 

146 """Return atom types from chemical formula (optionally prepended 

147 with and underscore). 

148 """ 

149 from ase.symbols import string2symbols 

150 

151 symbols = string2symbols(formula.split('_')[0]) 

152 atomtypes = [symbols[0]] 

153 for s in symbols[1:]: 

154 if s != atomtypes[-1]: 

155 atomtypes.append(s) 

156 return atomtypes 

157 

158 

159@reader 

160def read_vasp(fd): 

161 """Import POSCAR/CONTCAR type file. 

162 

163 Reads unitcell, atom positions and constraints from the POSCAR/CONTCAR 

164 file and tries to read atom types from POSCAR/CONTCAR header, if this 

165 fails the atom types are read from OUTCAR or POTCAR file. 

166 """ 

167 atoms = read_vasp_configuration(fd) 

168 velocity_init_line = fd.readline() 

169 if velocity_init_line.strip() and velocity_init_line[0].lower() == 'l': 

170 read_lattice_velocities(fd) 

171 velocities = read_velocities_if_present(fd, len(atoms)) 

172 if velocities is not None: 

173 atoms.set_velocities(velocities) 

174 return atoms 

175 

176 

177def read_vasp_configuration(fd): 

178 """Read common POSCAR/CONTCAR/CHGCAR/CHG quantities and return Atoms.""" 

179 from ase.data import chemical_symbols 

180 

181 # The first line is in principle a comment line, however in VASP 

182 # 4.x a common convention is to have it contain the atom symbols, 

183 # eg. "Ag Ge" in the same order as later in the file (and POTCAR 

184 # for the full vasp run). In the VASP 5.x format this information 

185 # is found on the fifth line. Thus we save the first line and use 

186 # it in case we later detect that we're reading a VASP 4.x format 

187 # file. 

188 line1 = fd.readline() 

189 

190 scale = parse_poscar_scaling_factor(fd.readline()) 

191 

192 # Now the lattice vectors 

193 cell = np.array([fd.readline().split()[:3] for _ in range(3)], dtype=float) 

194 # Negative scaling factor corresponds to the cell volume. 

195 if scale[0] < 0.0: 

196 scale = np.cbrt(-1.0 * scale / np.linalg.det(cell)) 

197 cell *= scale # This works for both one and three scaling factors. 

198 

199 # Number of atoms. Again this must be in the same order as 

200 # in the first line 

201 # or in the POTCAR or OUTCAR file 

202 atom_symbols = [] 

203 numofatoms = fd.readline().split() 

204 # Check whether we have a VASP 4.x or 5.x format file. If the 

205 # format is 5.x, use the fifth line to provide information about 

206 # the atomic symbols. 

207 vasp5 = False 

208 try: 

209 int(numofatoms[0]) 

210 except ValueError: 

211 vasp5 = True 

212 atomtypes = numofatoms 

213 numofatoms = fd.readline().split() 

214 

215 # check for comments in numofatoms line and get rid of them if necessary 

216 commentcheck = np.array(['!' in s for s in numofatoms]) 

217 if commentcheck.any(): 

218 # only keep the elements up to the first including a '!': 

219 numofatoms = numofatoms[: np.arange(len(numofatoms))[commentcheck][0]] 

220 

221 if not vasp5: 

222 # Split the comment line (first in the file) into words and 

223 # try to compose a list of chemical symbols 

224 from ase.formula import Formula 

225 

226 atomtypes = [] 

227 for word in line1.split(): 

228 word_without_delims = re.sub(r'-|_|,|\.|=|[0-9]|^', '', word) 

229 if len(word_without_delims) < 1: 

230 continue 

231 try: 

232 atomtypes.extend(list(Formula(word_without_delims))) 

233 except ValueError: 

234 # print(atomtype, e, 'is comment') 

235 pass 

236 # Now the list of chemical symbols atomtypes must be formed. 

237 # For example: atomtypes = ['Pd', 'C', 'O'] 

238 

239 numsyms = len(numofatoms) 

240 if len(atomtypes) < numsyms: 

241 # First line in POSCAR/CONTCAR didn't contain enough symbols. 

242 

243 # Sometimes the first line in POSCAR/CONTCAR is of the form 

244 # "CoP3_In-3.pos". Check for this case and extract atom types 

245 if len(atomtypes) == 1 and '_' in atomtypes[0]: 

246 atomtypes = get_atomtypes_from_formula(atomtypes[0]) 

247 else: 

248 atomtypes = atomtypes_outpot(fd.name, numsyms) 

249 else: 

250 try: 

251 for atype in atomtypes[:numsyms]: 

252 if atype not in chemical_symbols: 

253 raise KeyError 

254 except KeyError: 

255 atomtypes = atomtypes_outpot(fd.name, numsyms) 

256 

257 # Certain versions of VASP compiled with hdf5 support will write POTCAR 

258 # symbols with hashes to the CONTCAR (e.g. "Na_pv/6a2f546d)". 

259 for i, atomtype in enumerate(atomtypes): 

260 potcar_label = atomtype.split('/')[0] 

261 element_symbol = potcar_label.split('_')[0] 

262 atomtypes[i] = element_symbol 

263 

264 for i, num in enumerate(numofatoms): 

265 numofatoms[i] = int(num) 

266 atom_symbols.extend(numofatoms[i] * [atomtypes[i]]) 

267 

268 # Check if Selective dynamics is switched on 

269 sdyn = fd.readline().strip() 

270 selective_dynamics = sdyn[0].lower() == 's' 

271 

272 # Check if atom coordinates are cartesian or direct 

273 ac_type = fd.readline().strip() if selective_dynamics else sdyn 

274 cartesian = ac_type[0].lower() in {'c', 'k'} 

275 

276 tot_natoms = sum(numofatoms) 

277 atoms_pos = np.empty((tot_natoms, 3)) 

278 if selective_dynamics: 

279 selective_flags = np.empty((tot_natoms, 3), dtype=bool) 

280 for atom in range(tot_natoms): 

281 ac = fd.readline().split() 

282 atoms_pos[atom] = [float(_) for _ in ac[0:3]] 

283 if selective_dynamics: 

284 selective_flags[atom] = [_ == 'F' for _ in ac[3:6]] 

285 

286 atoms = Atoms(symbols=atom_symbols, cell=cell, pbc=True) 

287 if cartesian: 

288 atoms_pos *= scale 

289 atoms.set_positions(atoms_pos) 

290 else: 

291 atoms.set_scaled_positions(atoms_pos) 

292 if selective_dynamics: 

293 set_constraints(atoms, selective_flags) 

294 

295 return atoms 

296 

297 

298def read_lattice_velocities(fd): 

299 """ 

300 Read lattice velocities and vectors from POSCAR/CONTCAR. 

301 As lattice velocities are not yet implemented in ASE, this function just 

302 throws away these lines. 

303 """ 

304 fd.readline() # initialization state 

305 for _ in range(3): # lattice velocities 

306 fd.readline() 

307 for _ in range(3): # lattice vectors 

308 fd.readline() 

309 fd.readline() # get rid of 1 empty line below if it exists 

310 

311 

312def read_velocities_if_present(fd, natoms) -> np.ndarray | None: 

313 """Read velocities from POSCAR/CONTCAR if present, return in ASE units.""" 

314 # Check if it is the velocities block or the MD extra block 

315 words = fd.readline().split() 

316 if len(words) <= 1: # MD extra block or end of file 

317 return None 

318 atoms_vel = np.empty((natoms, 3)) 

319 atoms_vel[0] = (float(words[0]), float(words[1]), float(words[2])) 

320 for atom in range(1, natoms): 

321 words = fd.readline().split() 

322 assert len(words) == 3 

323 atoms_vel[atom] = (float(words[0]), float(words[1]), float(words[2])) 

324 

325 # unit conversion from Angstrom/fs to ASE units 

326 return atoms_vel * (Ang / fs) 

327 

328 

329def set_constraints(atoms: Atoms, selective_flags: np.ndarray) -> None: 

330 """Set constraints based on selective_flags""" 

331 constraints: list[FixConstraint] = [] 

332 indices = [] 

333 for ind, sflags in enumerate(selective_flags): 

334 if sflags.any() and not sflags.all(): 

335 constraints.append(FixScaled(ind, sflags, atoms.get_cell())) 

336 elif sflags.all(): 

337 indices.append(ind) 

338 if indices: 

339 constraints.append(FixAtoms(indices)) 

340 if constraints: 

341 atoms.set_constraint(constraints) 

342 

343 

344def iread_vasp_out(filename, index=-1): 

345 """Import OUTCAR type file, as a generator.""" 

346 it = ImageIterator(vop.outcarchunks) 

347 return it(filename, index=index) 

348 

349 

350@reader 

351def read_vasp_out(filename='OUTCAR', index=-1): 

352 """Import OUTCAR type file. 

353 

354 Reads unitcell, atom positions, energies, and forces from the OUTCAR file 

355 and attempts to read constraints (if any) from CONTCAR/POSCAR, if present. 

356 """ 

357 # "filename" is actually a file-descriptor thanks to @reader 

358 g = iread_vasp_out(filename, index=index) 

359 # Code borrowed from formats.py:read 

360 if isinstance(index, (slice, str)): 

361 # Return list of atoms 

362 return list(g) 

363 else: 

364 # Return single atoms object 

365 return next(g) 

366 

367 

368@reader 

369def read_vasp_xdatcar(filename='XDATCAR', index=-1): 

370 """Import XDATCAR file. 

371 

372 Parameters 

373 ---------- 

374 index : int or slice or str 

375 Which frame(s) to read. The default is -1 (last frame). 

376 See :func:`ase.io.read` for details. 

377 

378 Notes 

379 ----- 

380 Constraints ARE NOT stored in the XDATCAR, and as such, Atoms objects 

381 retrieved from the XDATCAR will not have constraints. 

382 """ 

383 fd = filename # @reader decorator ensures this is a file descriptor 

384 images = [] 

385 

386 cell = np.eye(3) 

387 atomic_formula = '' 

388 

389 while True: 

390 comment_line = fd.readline() 

391 if 'Direct configuration=' not in comment_line: 

392 try: 

393 lattice_constant = float(fd.readline()) 

394 except Exception: 

395 # XXX: When would this happen? 

396 break 

397 

398 xx = [float(x) for x in fd.readline().split()] 

399 yy = [float(y) for y in fd.readline().split()] 

400 zz = [float(z) for z in fd.readline().split()] 

401 cell = np.array([xx, yy, zz]) * lattice_constant 

402 

403 symbols = fd.readline().split() 

404 numbers = [int(n) for n in fd.readline().split()] 

405 total = sum(numbers) 

406 

407 atomic_formula = ''.join( 

408 f'{sym:s}{numbers[n]:d}' for n, sym in enumerate(symbols) 

409 ) 

410 

411 fd.readline() 

412 

413 coords = [np.array(fd.readline().split(), float) for _ in range(total)] 

414 

415 image = Atoms(atomic_formula, cell=cell, pbc=True) 

416 image.set_scaled_positions(np.array(coords)) 

417 images.append(image) 

418 

419 if index is None: 

420 index = -1 

421 

422 if isinstance(index, str): 

423 index = string2index(index) 

424 

425 return images[index] 

426 

427 

428def __get_xml_parameter(par): 

429 """An auxiliary function that enables convenient extraction of 

430 parameter values from a vasprun.xml file with proper type 

431 handling. 

432 

433 """ 

434 

435 def to_bool(b): 

436 if b == 'T': 

437 return True 

438 else: 

439 return False 

440 

441 to_type = {'int': int, 'logical': to_bool, 'string': str, 'float': float} 

442 

443 text = par.text 

444 if text is None: 

445 text = '' 

446 

447 # Float parameters do not have a 'type' attrib 

448 var_type = to_type[par.attrib.get('type', 'float')] 

449 

450 try: 

451 if par.tag == 'v': 

452 return list(map(var_type, text.split())) 

453 else: 

454 return var_type(text.strip()) 

455 except ValueError: 

456 # Vasp can sometimes write "*****" due to overflow 

457 return None 

458 

459 

460def read_vasp_xml(filename='vasprun.xml', index=-1): 

461 """Parse vasprun.xml file. 

462 

463 Reads unit cell, atom positions, energies, forces, and constraints 

464 from vasprun.xml file 

465 

466 .. versionchanged:: 3.30.0 (:mr:`4330`) 

467 It now parses configurations without energies for a corrupted file. 

468 

469 Examples 

470 -------- 

471 >>> import ase.io 

472 >>> ase.io.write("out.traj", ase.io.read("vasprun.xml", index=":")) 

473 """ 

474 import xml.etree.ElementTree as ET 

475 

476 tree = ET.iterparse(filename, events=['start', 'end']) 

477 

478 atoms_init, ibz_kpts, kpt_weights, parameters = _read_vasp_xml_header(tree) 

479 

480 calculation = [] 

481 try: 

482 for event, elem in tree: 

483 if event == 'start' and elem.tag == 'calculation': 

484 calculation.append(elem) 

485 

486 except ET.ParseError: 

487 pass 

488 

489 steps = calculation if calculation else [atoms_init] 

490 

491 steps = [steps[index]] if isinstance(index, int) else steps[index] 

492 

493 for step in steps: 

494 if isinstance(step, Atoms): 

495 yield step 

496 else: 

497 yield atoms_from_step( 

498 step, 

499 ibz_kpts=ibz_kpts, 

500 kpt_weights=kpt_weights, 

501 parameters=parameters, 

502 atoms=atoms_init.copy(), 

503 ) 

504 

505 

506def _read_vasp_xml_header(tree): 

507 import xml.etree.ElementTree as ET 

508 

509 atoms_init = None 

510 ibz_kpts = None 

511 kpt_weights = None 

512 parameters = OrderedDict() 

513 

514 try: 

515 for event, elem in tree: 

516 if event != 'end': 

517 continue 

518 

519 if elem.tag == 'kpoints': 

520 for subelem in elem.iter(tag='generation'): 

521 kpts_params = OrderedDict() 

522 parameters['kpoints_generation'] = kpts_params 

523 for par in subelem.iter(): 

524 if par.tag in ['v', 'i'] and 'name' in par.attrib: 

525 parname = par.attrib['name'].lower() 

526 kpts_params[parname] = __get_xml_parameter(par) 

527 

528 kpts = elem.findall("varray[@name='kpointlist']/v") 

529 ibz_kpts = np.zeros((len(kpts), 3)) 

530 

531 for i, kpt in enumerate(kpts): 

532 ibz_kpts[i] = [float(val) for val in kpt.text.split()] 

533 

534 kpt_weights = elem.findall('varray[@name="weights"]/v') 

535 kpt_weights = [float(val.text) for val in kpt_weights] 

536 

537 elif elem.tag == 'parameters': 

538 for par in elem.iter(): 

539 if par.tag in ['v', 'i']: 

540 parname = par.attrib['name'].lower() 

541 parameters[parname] = __get_xml_parameter(par) 

542 

543 elif elem.tag == 'atominfo': 

544 species = [] 

545 

546 for entry in elem.find("array[@name='atoms']/set"): 

547 species.append(entry[0].text.strip()) 

548 

549 elif ( 

550 elem.tag == 'structure' 

551 and elem.attrib.get('name') == 'initialpos' 

552 ): 

553 atoms_init = _read_vasp_xml_structure(elem, species) 

554 break 

555 

556 except ET.ParseError as parse_error: 

557 if atoms_init is None: 

558 raise parse_error 

559 

560 return atoms_init, ibz_kpts, kpt_weights, parameters 

561 

562 

563def atoms_from_step( 

564 step, 

565 ibz_kpts: np.ndarray, 

566 kpt_weights: list, 

567 parameters: dict, 

568 atoms: Atoms, 

569) -> Atoms: 

570 from ase.calculators.singlepoint import ( 

571 SinglePointDFTCalculator, 

572 SinglePointKPoint, 

573 ) 

574 

575 natoms = len(atoms) 

576 

577 cell = np.zeros((3, 3), dtype=float) 

578 for i, vector in enumerate( 

579 step.find('structure/crystal/varray[@name="basis"]') 

580 ): 

581 cell[i] = np.array([float(val) for val in vector.text.split()]) 

582 volume = np.linalg.det(cell) 

583 

584 energy, free_energy = _read_vasp_xml_energy(step, parameters, volume) 

585 

586 dipoles = step.findall('scstep/dipole') 

587 lastdipole = dipoles[-1] if dipoles else None 

588 

589 scpos = np.zeros((natoms, 3), dtype=float) 

590 for i, vector in enumerate( 

591 step.find('structure/varray[@name="positions"]') 

592 ): 

593 scpos[i] = np.array([float(val) for val in vector.text.split()]) 

594 

595 forces = None 

596 fblocks = step.find('varray[@name="forces"]') 

597 if fblocks is not None: 

598 forces = np.zeros((natoms, 3), dtype=float) 

599 for i, vector in enumerate(fblocks): 

600 forces[i] = np.array([float(val) for val in vector.text.split()]) 

601 

602 stress = None 

603 sblocks = step.find('varray[@name="stress"]') 

604 if sblocks is not None: 

605 stress = np.zeros((3, 3), dtype=float) 

606 for i, vector in enumerate(sblocks): 

607 stress[i] = np.array([float(val) for val in vector.text.split()]) 

608 stress *= -0.1 * GPa 

609 stress = stress.reshape(9)[[0, 4, 8, 5, 2, 1]] 

610 

611 dipole = None 

612 if lastdipole is not None: 

613 dblock = lastdipole.find('v[@name="dipole"]') 

614 if dblock is not None: 

615 dipole = np.zeros((1, 3), dtype=float) 

616 dipole = np.array([float(val) for val in dblock.text.split()]) 

617 

618 dblock = step.find('dipole/v[@name="dipole"]') 

619 if dblock is not None: 

620 dipole = np.zeros((1, 3), dtype=float) 

621 dipole = np.array([float(val) for val in dblock.text.split()]) 

622 

623 efermi = step.find('dos/i[@name="efermi"]') 

624 if efermi is not None: 

625 efermi = float(efermi.text) 

626 

627 kpoints = [] 

628 for ikpt in range(1, len(ibz_kpts) + 1): 

629 kblocks = step.findall( 

630 'eigenvalues/array/set/set/set[@comment="kpoint %d"]' % ikpt 

631 ) 

632 if kblocks is not None: 

633 for spin, kpoint in enumerate(kblocks): 

634 eigenvals = kpoint.findall('r') 

635 eps_n = np.zeros(len(eigenvals)) 

636 f_n = np.zeros(len(eigenvals)) 

637 for j, val in enumerate(eigenvals): 

638 val = val.text.split() 

639 eps_n[j] = float(val[0]) 

640 f_n[j] = float(val[1]) 

641 if len(kblocks) == 1: 

642 f_n *= 2 

643 kpoints.append( 

644 SinglePointKPoint( 

645 kpt_weights[ikpt - 1], spin, ikpt, eps_n, f_n 

646 ) 

647 ) 

648 

649 # DFPT properties 

650 # dielectric tensor 

651 dielectric_tensor = None 

652 sblocks = step.find('varray[@name="dielectric_dft"]') 

653 if sblocks is not None: 

654 dielectric_tensor = np.zeros((3, 3), dtype=float) 

655 for ii, vector in enumerate(sblocks): 

656 dielectric_tensor[ii] = np.fromstring(vector.text, sep=' ') 

657 

658 # Born effective charges 

659 born_charges = None 

660 fblocks = step.find('array[@name="born_charges"]') 

661 if fblocks is not None: 

662 born_charges = np.zeros((natoms, 3, 3), dtype=float) 

663 for ii, block in enumerate(fblocks[1:]): # 1. element = dimension 

664 for jj, vector in enumerate(block): 

665 born_charges[ii, jj] = np.fromstring(vector.text, sep=' ') 

666 

667 atoms.set_cell(cell) 

668 atoms.set_scaled_positions(scpos) 

669 atoms.calc = SinglePointDFTCalculator( 

670 atoms, 

671 energy=energy, 

672 forces=forces, 

673 stress=stress, 

674 free_energy=free_energy, 

675 ibzkpts=ibz_kpts, 

676 efermi=efermi, 

677 dipole=dipole, 

678 dielectric_tensor=dielectric_tensor, 

679 born_effective_charges=born_charges, 

680 ) 

681 atoms.calc.name = 'vasp' 

682 atoms.calc.kpts = kpoints if len(kpoints) else None 

683 atoms.calc.parameters = parameters 

684 return atoms 

685 

686 

687def _read_vasp_xml_structure(elem, species) -> Atoms: 

688 cell = np.array( 

689 [ 

690 [float(x) for x in vector.text.split()] 

691 for vector in elem.find("crystal/varray[@name='basis']") 

692 ] 

693 ) 

694 

695 scaled_positions = np.array( 

696 [ 

697 [float(x) for x in vector.text.split()] 

698 for vector in elem.find("varray[@name='positions']") 

699 ] 

700 ) 

701 

702 constraints: list[FixConstraint] = [] 

703 fixed_indices = [] 

704 

705 for i, entry in enumerate(elem.findall("varray[@name='selective']/v")): 

706 flags = np.array(entry.text.split() == np.array(['F', 'F', 'F'])) 

707 if flags.all(): 

708 fixed_indices.append(i) 

709 elif flags.any(): 

710 constraints.append(FixScaled(i, flags, cell)) 

711 

712 if fixed_indices: 

713 constraints.append(FixAtoms(fixed_indices)) 

714 

715 return Atoms( 

716 species, 

717 cell=cell, 

718 scaled_positions=scaled_positions, 

719 constraint=constraints, 

720 pbc=True, 

721 ) 

722 

723 

724def _read_vasp_xml_energy( 

725 step, 

726 parameters: dict, 

727 volume: float, 

728) -> tuple[float | None, float | None]: 

729 element0 = step.find('energy/i[@name="e_fr_energy"]') 

730 

731 if element0 is None: 

732 return None, None 

733 

734 free_energy = float(element0.text) 

735 

736 # https://gitlab.com/ase/ase/-/merge_requests/2685 

737 # e_fr_energy in calculation/energy is actually an enthalpy including 

738 # the PV term, unlike that in /calculation/scstep/energy or in OUTCAR, 

739 # and therefore we need to subtract the PV term. 

740 pressure = parameters.get('pstress', 0.0) 

741 pressure *= 1e-22 / EVTOJ # kbar -> eV/A3 

742 free_energy -= pressure * volume 

743 

744 # Workaround for VASP bug, e_0_energy contains the wrong value 

745 # in calculation/energy, but calculation/scstep/energy does not 

746 # include classical VDW corrections. So, first calculate 

747 # e_0_energy - e_fr_energy from calculation/scstep/energy, then 

748 # apply that correction to e_fr_energy from calculation/energy. 

749 lastscf = step.findall('scstep/energy')[-1] 

750 

751 de = float(lastscf.find('i[@name="e_0_energy"]').text) - float( 

752 lastscf.find('i[@name="e_fr_energy"]').text 

753 ) 

754 

755 energy = free_energy + de 

756 

757 return energy, free_energy 

758 

759 

760@writer 

761def write_vasp_xdatcar(fd, images, label=None): 

762 """Write VASP MD trajectory (XDATCAR) file 

763 

764 Only Vasp 5 format is supported (for consistency with read_vasp_xdatcar) 

765 

766 Args: 

767 fd (str, fp): Output file 

768 images (iterable of Atoms): Atoms images to write. These must have 

769 consistent atom order and lattice vectors - this will not be 

770 checked. 

771 label (str): Text for first line of file. If empty, default to list 

772 of elements. 

773 

774 """ 

775 

776 images = iter(images) 

777 image = next(images) 

778 

779 if not isinstance(image, Atoms): 

780 raise TypeError('images should be a sequence of Atoms objects.') 

781 

782 _write_xdatcar_header(fd, image, label) 

783 _write_xdatcar_config(fd, image, index=1) 

784 for i, image in enumerate(images): 

785 _write_xdatcar_header(fd, image, label) 

786 # Index is off by 2: 1-indexed file vs 0-indexed Python; 

787 # and we already wrote the first block. 

788 _write_xdatcar_config(fd, image, i + 2) 

789 

790 

791def _write_xdatcar_header(fd, atoms, label): 

792 symbol_count = _symbol_count_from_symbols(atoms.get_chemical_symbols()) 

793 

794 if label is None: 

795 label = ' '.join([s for s, _ in symbol_count]) 

796 fd.write(label + '\n') 

797 

798 # Not using lattice constants, set it to 1 

799 fd.write(' 1\n') 

800 

801 float_string = '{:11.6f}' 

802 for row_i in range(3): 

803 fd.write(' ') 

804 fd.write(' '.join(float_string.format(x) for x in atoms.cell[row_i])) 

805 fd.write('\n') 

806 

807 fd.write(_symbol_count_string(symbol_count, vasp5=True)) 

808 

809 

810def _write_xdatcar_config(fd, atoms, index): 

811 """Write a block of positions for XDATCAR file 

812 

813 Args: 

814 fd (fd): writeable Python file descriptor 

815 atoms (ase.Atoms): Atoms to write 

816 index (int): configuration number written to block header 

817 

818 """ 

819 fd.write(f'Direct configuration={index:6d}\n') 

820 float_string = '{:11.8f}' 

821 scaled_positions = atoms.get_scaled_positions(wrap=False) 

822 for row in scaled_positions: 

823 fd.write(' ') 

824 fd.write(' '.join([float_string.format(x) for x in row])) 

825 fd.write('\n') 

826 

827 

828def _symbol_count_from_symbols(symbols: Symbols) -> list[tuple[str, int]]: 

829 """Reduce list of chemical symbols into compact VASP notation 

830 

831 Args: 

832 symbols (iterable of str) 

833 

834 Returns 

835 ------- 

836 list of pairs [(el1, c1), (el2, c2), ...] 

837 

838 Example: 

839 >>> s = Atoms('Ar3NeHe2ArNe').symbols 

840 >>> _symbols_count_from_symbols(s) 

841 [('Ar', 3), ('Ne', 1), ('He', 2), ('Ar', 1), ('Ne', 1)] 

842 """ 

843 sc = [] 

844 psym = str(symbols[0]) # we cast to str to appease mypy 

845 count = 0 

846 for sym in symbols: 

847 if sym != psym: 

848 sc.append((psym, count)) 

849 psym = sym 

850 count = 1 

851 else: 

852 count += 1 

853 

854 sc.append((psym, count)) 

855 return sc 

856 

857 

858@writer 

859def write_vasp( 

860 fd: TextIO, 

861 atoms: Atoms, 

862 direct: bool = False, 

863 sort: bool = False, 

864 symbol_count: list[tuple[str, int]] | None = None, 

865 vasp5: bool = True, 

866 vasp6: bool = False, 

867 ignore_constraints: bool = False, 

868 potential_mapping: dict | None = None, 

869) -> None: 

870 """Method to write VASP position (POSCAR/CONTCAR) files. 

871 

872 Writes label, scalefactor, unitcell, # of various kinds of atoms, 

873 positions in cartesian or scaled coordinates (Direct), and constraints 

874 to file. Cartesian coordinates is default and default label is the 

875 atomic species, e.g. 'C N H Cu'. 

876 

877 Args: 

878 fd (TextIO): writeable Python file descriptor 

879 atoms (ase.Atoms): Atoms to write 

880 direct (bool): Write scaled coordinates instead of cartesian 

881 sort (bool): Sort the atomic indices alphabetically by element 

882 symbol_count (list of tuples of str and int, optional): Use the given 

883 combination of symbols and counts instead of automatically compute 

884 them 

885 vasp5 (bool): Write to the VASP 5+ format, where the symbols are 

886 written to file 

887 vasp6 (bool): Write symbols in VASP 6 format (which allows for 

888 potential type and hash) 

889 ignore_constraints (bool): Ignore all constraints on `atoms` 

890 potential_mapping (dict, optional): Map of symbols to potential file 

891 (and hash). Only works if `vasp6=True`. See `_symbol_string_count` 

892 

893 Raises 

894 ------ 

895 RuntimeError: raised if any of these are true: 

896 

897 1. `atoms` is not a single `ase.Atoms` object. 

898 2. The cell dimensionality is lower than 3 (0D-2D) 

899 3. One FixedPlane normal is not parallel to a unit cell vector 

900 4. One FixedLine direction is not parallel to a unit cell vector 

901 """ 

902 if isinstance(atoms, (list, tuple)): 

903 if len(atoms) > 1: 

904 raise RuntimeError( 

905 'Only one atomic structure can be saved to VASP ' 

906 'POSCAR/CONTCAR. Several were given.' 

907 ) 

908 else: 

909 atoms = atoms[0] 

910 

911 # Check lattice vectors are finite 

912 if atoms.cell.rank < 3: 

913 raise RuntimeError( 

914 'Lattice vectors must be finite and non-parallel. At least ' 

915 'one lattice length or angle is zero.' 

916 ) 

917 

918 # Write atomic positions in scaled or cartesian coordinates 

919 if direct: 

920 coord = atoms.get_scaled_positions(wrap=False) 

921 else: 

922 coord = atoms.positions 

923 

924 # Convert ASE constraints to VASP POSCAR constraints 

925 constraints_present = atoms.constraints and not ignore_constraints 

926 if constraints_present: 

927 sflags = _handle_ase_constraints(atoms) 

928 

929 # Conditionally sort ordering of `atoms` alphabetically by symbols 

930 if sort: 

931 ind = np.argsort(atoms.symbols) 

932 symbols = atoms.symbols[ind] 

933 coord = coord[ind] 

934 if constraints_present: 

935 sflags = sflags[ind] 

936 else: 

937 symbols = atoms.symbols 

938 

939 # Set or create a list of (symbol, count) pairs 

940 sc = symbol_count or _symbol_count_from_symbols(symbols) 

941 

942 # Write header as atomic species in `symbol_count` order 

943 label = ' '.join(f'{sym:2s}' for sym, _ in sc) 

944 fd.write(label + '\n') 

945 

946 # For simplicity, we write the unitcell in real coordinates, so the 

947 # scaling factor is always set to 1.0. 

948 fd.write(f'{1.0:19.16f}\n') 

949 

950 for vec in atoms.cell: 

951 fd.write(' ' + ' '.join([f'{el:21.16f}' for el in vec]) + '\n') 

952 

953 # Write version-dependent species-and-count section 

954 sc_str = _symbol_count_string(sc, vasp5, vasp6, potential_mapping) 

955 fd.write(sc_str) 

956 

957 # Write POSCAR switches 

958 if constraints_present: 

959 fd.write('Selective dynamics\n') 

960 

961 fd.write('Direct\n' if direct else 'Cartesian\n') 

962 

963 # Write atomic positions and, if any, the cartesian constraints 

964 for iatom, atom in enumerate(coord): 

965 for dcoord in atom: 

966 fd.write(f' {dcoord:19.16f}') 

967 if constraints_present: 

968 flags = ['F' if flag else 'T' for flag in sflags[iatom]] 

969 fd.write(''.join([f'{f:>4s}' for f in flags])) 

970 fd.write('\n') 

971 

972 # if velocities in atoms object write velocities 

973 if atoms.has('momenta'): 

974 cform = 3 * ' {:19.16f}' + '\n' 

975 fd.write('Cartesian\n') 

976 # unit conversion to Angstrom / fs 

977 vel = atoms.get_velocities() / (Ang / fs) 

978 for vatom in vel: 

979 fd.write(cform.format(*vatom)) 

980 

981 

982def _handle_ase_constraints(atoms: Atoms) -> np.ndarray: 

983 """Convert the ASE constraints on `atoms` to VASP constraints 

984 

985 Returns a boolean array with dimensions Nx3, where N is the number of 

986 atoms. A value of `True` indicates that movement along the given lattice 

987 vector is disallowed for that atom. 

988 

989 Args: 

990 atoms (Atoms) 

991 

992 Returns 

993 ------- 

994 boolean numpy array with dimensions Nx3 

995 

996 Raises 

997 ------ 

998 RuntimeError: If there is a FixedPlane or FixedLine constraint, that 

999 is not parallel to a cell vector. 

1000 """ 

1001 sflags = np.zeros((len(atoms), 3), dtype=bool) 

1002 for constr in atoms.constraints: 

1003 if isinstance(constr, FixScaled): 

1004 sflags[constr.index] |= constr.mask 

1005 elif isinstance(constr, FixAtoms): 

1006 sflags[constr.index] |= 3 * [True] 

1007 elif isinstance(constr, FixedPlane): 

1008 # Calculate if the plane normal is parallel to a cell vector 

1009 mask = np.all( 

1010 np.abs(np.cross(constr.dir, atoms.cell)) < 1e-5, axis=1 

1011 ) 

1012 if mask.sum() != 1: 

1013 raise RuntimeError( 

1014 'VASP requires that the direction of FixedPlane ' 

1015 'constraints is parallel with one of the cell axis' 

1016 ) 

1017 sflags[constr.index] |= mask 

1018 elif isinstance(constr, FixedLine): 

1019 # Calculate if line is parallel to a cell vector 

1020 mask = np.all( 

1021 np.abs(np.cross(constr.dir, atoms.cell)) < 1e-5, axis=1 

1022 ) 

1023 if mask.sum() != 1: 

1024 raise RuntimeError( 

1025 'VASP requires that the direction of FixedLine ' 

1026 'constraints is parallel with one of the cell axis' 

1027 ) 

1028 sflags[constr.index] |= ~mask 

1029 

1030 return sflags 

1031 

1032 

1033def _symbol_count_string( 

1034 symbol_count: list[tuple[str, int]], 

1035 vasp5: bool = True, 

1036 vasp6: bool = True, 

1037 symbol_mapping: dict | None = None, 

1038) -> str: 

1039 """Create the symbols-and-counts block for POSCAR or XDATCAR 

1040 

1041 Args: 

1042 symbol_count (list of 2-tuple): list of paired elements and counts 

1043 vasp5 (bool): if False, omit symbols and only write counts 

1044 vasp6 (bool): if True, write symbols in VASP 6 format (allows for 

1045 potential type and hash) 

1046 symbol_mapping (dict): mapping of symbols to VASP 6 symbols 

1047 

1048 e.g. if sc is [(Sn, 4), (S, 6)] then write for vasp 5: 

1049 Sn S 

1050 4 6 

1051 

1052 and for vasp 6 with mapping {'Sn': 'Sn_d_GW', 'S': 'S_GW/357d'}: 

1053 Sn_d_GW S_GW/357d 

1054 4 6 

1055 """ 

1056 symbol_mapping = symbol_mapping or {} 

1057 out_str = ' ' 

1058 

1059 # Allow for VASP 6 format, i.e., specifying the pseudopotential used 

1060 if vasp6: 

1061 out_str += ( 

1062 ' '.join( 

1063 [ 

1064 f'{symbol_mapping.get(s, s)[:14]:16s}' 

1065 for s, _ in symbol_count 

1066 ] 

1067 ) 

1068 + '\n ' 

1069 ) 

1070 out_str += ' '.join([f'{c:16d}' for _, c in symbol_count]) + '\n' 

1071 return out_str 

1072 

1073 # Write the species for VASP 5+ 

1074 if vasp5: 

1075 out_str += ' '.join([f'{s:3s}' for s, _ in symbol_count]) + '\n ' 

1076 

1077 # Write counts line 

1078 out_str += ' '.join([f'{c:3d}' for _, c in symbol_count]) + '\n' 

1079 

1080 return out_str