Coverage for ase/calculators/vasp/vasp_auxiliary.py: 29.74%

195 statements  

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

1import os 

2import re 

3 

4import numpy as np 

5 

6 

7def get_vasp_version(string): 

8 """Extract version number from header of stdout. 

9 

10 Example:: 

11 

12 >>> get_vasp_version('potato vasp.6.1.2 bumblebee') 

13 '6.1.2' 

14 

15 """ 

16 match = re.search(r'vasp\.(\S+)', string, re.M) 

17 return match.group(1) 

18 

19 

20class VaspChargeDensity: 

21 """Class for representing VASP charge density. 

22 

23 Filename is normally CHG.""" 

24 

25 # Can the filename be CHGCAR? There's a povray tutorial 

26 # in doc/tutorials where it's CHGCAR as of January 2021. --askhl 

27 

28 def __init__(self, filename): 

29 # Instance variables 

30 self.atoms = [] # List of Atoms objects 

31 self.chg = [] # Charge density 

32 self.chgdiff = [] # Charge density difference, if spin polarized 

33 self.aug = '' # Augmentation charges, not parsed just a big string 

34 self.augdiff = '' # Augmentation charge differece, is spin polarized 

35 

36 # Note that the augmentation charge is not a list, since they 

37 # are needed only for CHGCAR files which store only a single 

38 # image. 

39 if filename is not None: 

40 self.read(filename) 

41 

42 def is_spin_polarized(self): 

43 if len(self.chgdiff) > 0: 

44 return True 

45 return False 

46 

47 def _read_chg(self, fobj, chg, volume): 

48 """Read charge from file object 

49 

50 Utility method for reading the actual charge density (or 

51 charge density difference) from a file object. On input, the 

52 file object must be at the beginning of the charge block, on 

53 output the file position will be left at the end of the 

54 block. The chg array must be of the correct dimensions. 

55 

56 """ 

57 # VASP writes charge density as 

58 # WRITE(IU,FORM) (((C(NX,NY,NZ),NX=1,NGXC),NY=1,NGYZ),NZ=1,NGZC) 

59 # Fortran nested implied do loops; innermost index fastest 

60 # First, just read it in 

61 for zz in range(chg.shape[2]): 

62 for yy in range(chg.shape[1]): 

63 chg[:, yy, zz] = np.fromfile(fobj, count=chg.shape[0], sep=' ') 

64 chg /= volume 

65 

66 def read(self, filename): 

67 """Read CHG or CHGCAR file. 

68 

69 If CHG contains charge density from multiple steps all the 

70 steps are read and stored in the object. By default VASP 

71 writes out the charge density every 10 steps. 

72 

73 chgdiff is the difference between the spin up charge density 

74 and the spin down charge density and is thus only read for a 

75 spin-polarized calculation. 

76 

77 aug is the PAW augmentation charges found in CHGCAR. These are 

78 not parsed, they are just stored as a string so that they can 

79 be written again to a CHGCAR format file. 

80 

81 """ 

82 import ase.io.vasp as aiv 

83 

84 with open(filename) as fd: 

85 self.atoms = [] 

86 self.chg = [] 

87 self.chgdiff = [] 

88 self.aug = '' 

89 self.augdiff = '' 

90 while True: 

91 try: 

92 atoms = aiv.read_vasp_configuration(fd) 

93 except (KeyError, RuntimeError, ValueError): 

94 # Probably an empty line, or we tried to read the 

95 # augmentation occupancies in CHGCAR 

96 break 

97 

98 # Note: We continue reading from the same file, and 

99 # this relies on read_vasp() to read no more lines 

100 # than it currently does. 

101 fd.readline() 

102 

103 ngr = fd.readline().split() 

104 ng = (int(ngr[0]), int(ngr[1]), int(ngr[2])) 

105 chg = np.empty(ng) 

106 self._read_chg(fd, chg, atoms.get_volume()) 

107 self.chg.append(chg) 

108 self.atoms.append(atoms) 

109 # Check if the file has a spin-polarized charge density part, 

110 # and if so, read it in. 

111 fl = fd.tell() 

112 # First check if the file has an augmentation charge part 

113 # (CHGCAR file.) 

114 line1 = fd.readline() 

115 if line1 == '': 

116 break 

117 elif line1.find('augmentation') != -1: 

118 augs = [line1] 

119 while True: 

120 line2 = fd.readline() 

121 if line2.split() == ngr: 

122 self.aug = ''.join(augs) 

123 augs = [] 

124 chgdiff = np.empty(ng) 

125 self._read_chg(fd, chgdiff, atoms.get_volume()) 

126 self.chgdiff.append(chgdiff) 

127 elif line2 == '': 

128 break 

129 else: 

130 augs.append(line2) 

131 if len(self.aug) == 0: 

132 self.aug = ''.join(augs) 

133 augs = [] 

134 else: 

135 self.augdiff = ''.join(augs) 

136 augs = [] 

137 elif line1.split() == ngr: 

138 chgdiff = np.empty(ng) 

139 self._read_chg(fd, chgdiff, atoms.get_volume()) 

140 self.chgdiff.append(chgdiff) 

141 else: 

142 fd.seek(fl) 

143 

144 def _write_chg(self, fobj, chg, volume, format='chg'): 

145 """Write charge density 

146 

147 Utility function similar to _read_chg but for writing. 

148 

149 """ 

150 # Make a 1D copy of chg, must take transpose to get ordering right 

151 chgtmp = chg.T.ravel() 

152 # Multiply by volume 

153 chgtmp = chgtmp * volume 

154 # Must be a tuple to pass to string conversion 

155 chgtmp = tuple(chgtmp) 

156 # CHG format - 10 columns 

157 if format.lower() == 'chg': 

158 # Write all but the last row 

159 for ii in range((len(chgtmp) - 1) // 10): 

160 fobj.write( 

161 ' %#11.5G %#11.5G %#11.5G %#11.5G %#11.5G\ 

162 %#11.5G %#11.5G %#11.5G %#11.5G %#11.5G\n' 

163 % chgtmp[ii * 10 : (ii + 1) * 10] 

164 ) 

165 # If the last row contains 10 values then write them without a 

166 # newline 

167 if len(chgtmp) % 10 == 0: 

168 fobj.write( 

169 ' %#11.5G %#11.5G %#11.5G %#11.5G %#11.5G' 

170 ' %#11.5G %#11.5G %#11.5G %#11.5G %#11.5G' 

171 % chgtmp[len(chgtmp) - 10 : len(chgtmp)] 

172 ) 

173 # Otherwise write fewer columns without a newline 

174 else: 

175 for ii in range(len(chgtmp) % 10): 

176 fobj.write( 

177 (' %#11.5G') 

178 % chgtmp[len(chgtmp) - len(chgtmp) % 10 + ii] 

179 ) 

180 # Other formats - 5 columns 

181 else: 

182 # Write all but the last row 

183 for ii in range((len(chgtmp) - 1) // 5): 

184 fobj.write( 

185 ' %17.10E %17.10E %17.10E %17.10E %17.10E\n' 

186 % chgtmp[ii * 5 : (ii + 1) * 5] 

187 ) 

188 # If the last row contains 5 values then write them without a 

189 # newline 

190 if len(chgtmp) % 5 == 0: 

191 fobj.write( 

192 ' %17.10E %17.10E %17.10E %17.10E %17.10E' 

193 % chgtmp[len(chgtmp) - 5 : len(chgtmp)] 

194 ) 

195 # Otherwise write fewer columns without a newline 

196 else: 

197 for ii in range(len(chgtmp) % 5): 

198 fobj.write( 

199 (' %17.10E') 

200 % chgtmp[len(chgtmp) - len(chgtmp) % 5 + ii] 

201 ) 

202 # Write a newline whatever format it is 

203 fobj.write('\n') 

204 

205 def write(self, filename, format=None): 

206 """Write VASP charge density in CHG format. 

207 

208 filename: str 

209 Name of file to write to. 

210 format: str 

211 String specifying whether to write in CHGCAR or CHG 

212 format. 

213 

214 """ 

215 import ase.io.vasp as aiv 

216 

217 if format is None: 

218 if filename.lower().find('chgcar') != -1: 

219 format = 'chgcar' 

220 elif filename.lower().find('chg') != -1: 

221 format = 'chg' 

222 elif len(self.chg) == 1: 

223 format = 'chgcar' 

224 else: 

225 format = 'chg' 

226 with open(filename, 'w') as fd: 

227 for ii, chg in enumerate(self.chg): 

228 if format == 'chgcar' and ii != len(self.chg) - 1: 

229 continue # Write only the last image for CHGCAR 

230 aiv.write_vasp(fd, self.atoms[ii], direct=True) 

231 fd.write('\n') 

232 for dim in chg.shape: 

233 fd.write(' %4i' % dim) 

234 fd.write('\n') 

235 vol = self.atoms[ii].get_volume() 

236 self._write_chg(fd, chg, vol, format) 

237 if format == 'chgcar': 

238 fd.write(self.aug) 

239 if self.is_spin_polarized(): 

240 if format == 'chg': 

241 fd.write('\n') 

242 for dim in chg.shape: 

243 fd.write(' %4i' % dim) 

244 fd.write('\n') # a new line after dim is required 

245 self._write_chg(fd, self.chgdiff[ii], vol, format) 

246 if format == 'chgcar': 

247 # a new line is always provided self._write_chg 

248 fd.write(self.augdiff) 

249 if format == 'chg' and len(self.chg) > 1: 

250 fd.write('\n') 

251 

252 

253class VaspDos: 

254 """Class for representing density-of-states produced by VASP 

255 

256 The energies are in property self.energy 

257 

258 Site-projected DOS is accesible via the self.site_dos method. 

259 

260 Total and integrated DOS is accessible as numpy.ndarray's in the 

261 properties self.dos and self.integrated_dos. If the calculation is 

262 spin polarized, the arrays will be of shape (2, NDOS), else (1, 

263 NDOS). 

264 

265 The self.efermi property contains the currently set Fermi 

266 level. Changing this value shifts the energies. 

267 

268 """ 

269 

270 def __init__(self, doscar='DOSCAR', efermi=0.0): 

271 """Initialize""" 

272 self._efermi = 0.0 

273 self.read_doscar(doscar) 

274 self.efermi = efermi 

275 

276 # we have determine the resort to correctly map ase atom index to the 

277 # POSCAR. 

278 self.sort = [] 

279 self.resort = [] 

280 if os.path.isfile('ase-sort.dat'): 

281 with open('ase-sort.dat') as file: 

282 lines = file.readlines() 

283 for line in lines: 

284 data = line.split() 

285 self.sort.append(int(data[0])) 

286 self.resort.append(int(data[1])) 

287 

288 def _set_efermi(self, efermi): 

289 """Set the Fermi level.""" 

290 ef = efermi - self._efermi 

291 self._efermi = efermi 

292 self._total_dos[0, :] = self._total_dos[0, :] - ef 

293 try: 

294 self._site_dos[:, 0, :] = self._site_dos[:, 0, :] - ef 

295 except IndexError: 

296 pass 

297 

298 def _get_efermi(self): 

299 return self._efermi 

300 

301 efermi = property(_get_efermi, _set_efermi, None, 'Fermi energy.') 

302 

303 def _get_energy(self): 

304 """Return the array with the energies.""" 

305 return self._total_dos[0, :] 

306 

307 energy = property(_get_energy, None, None, 'Array of energies') 

308 

309 def site_dos(self, atom, orbital): 

310 """Return an NDOSx1 array with dos for the chosen atom and orbital. 

311 

312 atom: int 

313 Atom index 

314 orbital: int or str 

315 Which orbital to plot 

316 

317 If the orbital is given as an integer: 

318 If spin-unpolarized calculation, no phase factors: 

319 s = 0, p = 1, d = 2 

320 Spin-polarized, no phase factors: 

321 s-up = 0, s-down = 1, p-up = 2, p-down = 3, d-up = 4, d-down = 5 

322 If phase factors have been calculated, orbitals are 

323 s, py, pz, px, dxy, dyz, dz2, dxz, dx2 

324 double in the above fashion if spin polarized. 

325 

326 """ 

327 # Correct atom index for resorting if we need to. This happens when the 

328 # ase-sort.dat file exists, and self.resort is not empty. 

329 if self.resort: 

330 atom = self.resort[atom] 

331 

332 # Integer indexing for orbitals starts from 1 in the _site_dos array 

333 # since the 0th column contains the energies 

334 if isinstance(orbital, int): 

335 return self._site_dos[atom, orbital + 1, :] 

336 n = self._site_dos.shape[1] 

337 

338 from .vasp_data import PDOS_orbital_names_and_DOSCAR_column 

339 

340 norb = PDOS_orbital_names_and_DOSCAR_column[n] 

341 

342 return self._site_dos[atom, norb[orbital.lower()], :] 

343 

344 def _get_dos(self): 

345 if self._total_dos.shape[0] == 3: 

346 return self._total_dos[1, :] 

347 elif self._total_dos.shape[0] == 5: 

348 return self._total_dos[1:3, :] 

349 

350 dos = property(_get_dos, None, None, 'Average DOS in cell') 

351 

352 def _get_integrated_dos(self): 

353 if self._total_dos.shape[0] == 3: 

354 return self._total_dos[2, :] 

355 elif self._total_dos.shape[0] == 5: 

356 return self._total_dos[3:5, :] 

357 

358 integrated_dos = property( 

359 _get_integrated_dos, None, None, 'Integrated average DOS in cell' 

360 ) 

361 

362 def read_doscar(self, fname='DOSCAR'): 

363 """Read a VASP DOSCAR file""" 

364 with open(fname) as fd: 

365 natoms = int(fd.readline().split()[0]) 

366 [fd.readline() for _ in range(4)] 

367 # First we have a block with total and total integrated DOS 

368 ndos = int(fd.readline().split()[2]) 

369 dos = [] 

370 for _ in range(ndos): 

371 dos.append(np.array([float(x) for x in fd.readline().split()])) 

372 self._total_dos = np.array(dos).T 

373 # Next we have one block per atom, if INCAR contains the stuff 

374 # necessary for generating site-projected DOS 

375 dos = [] 

376 for _ in range(natoms): 

377 line = fd.readline() 

378 if line == '': 

379 # No site-projected DOS 

380 break 

381 ndos = int(line.split()[2]) 

382 line = fd.readline().split() 

383 cdos = np.empty((ndos, len(line))) 

384 cdos[0] = np.array(line) 

385 for nd in range(1, ndos): 

386 line = fd.readline().split() 

387 cdos[nd] = np.array([float(x) for x in line]) 

388 dos.append(cdos.T) 

389 self._site_dos = np.array(dos)