Coverage for ase/spectrum/band_structure.py: 87.83%

189 statements  

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

1import numpy as np 

2 

3import ase # Annotations 

4from ase.calculators.calculator import PropertyNotImplementedError 

5from ase.utils import jsonable 

6 

7 

8def calculate_band_structure( 

9 atoms, 

10 path=None, 

11 scf_kwargs=None, 

12 bs_kwargs=None, 

13 kpts_tol=1e-6, 

14 cell_tol=1e-6, 

15): 

16 """Calculate band structure. 

17 

18 The purpose of this function is to abstract a band structure calculation 

19 so the workflow does not depend on the calculator. 

20 

21 First trigger SCF calculation if necessary, then set arguments 

22 on the calculator for band structure calculation, then return 

23 calculated band structure. 

24 

25 The difference from get_band_structure() is that the latter 

26 expects the calculation to already have been done.""" 

27 if path is None: 

28 path = atoms.cell.bandpath() 

29 

30 from ase.lattice import celldiff # Should this be a method on cell? 

31 

32 if any(path.cell.any(1) != atoms.pbc): 

33 raise ValueError( 

34 "The band path's cell, {}, does not match the " 

35 'periodicity {} of the atoms'.format(path.cell, atoms.pbc) 

36 ) 

37 cell_err = celldiff(path.cell, atoms.cell.uncomplete(atoms.pbc)) 

38 if cell_err > cell_tol: 

39 raise ValueError( 

40 'Atoms and band path have different unit cells. ' 

41 'Please reduce atoms to standard form. ' 

42 'Cell lengths and angles are {} vs {}'.format( 

43 atoms.cell.cellpar(), path.cell.cellpar() 

44 ) 

45 ) 

46 

47 calc = atoms.calc 

48 if calc is None: 

49 raise ValueError('Atoms have no calculator') 

50 

51 if scf_kwargs is not None: 

52 calc.set(**scf_kwargs) 

53 

54 # Proposed standard mechanism for calculators to advertise that they 

55 # use the bandpath keyword to handle band structures rather than 

56 # a double (SCF + BS) run. 

57 use_bandpath_kw = getattr(calc, 'accepts_bandpath_keyword', False) 

58 if use_bandpath_kw: 

59 calc.set(bandpath=path) 

60 atoms.get_potential_energy() 

61 return calc.band_structure() 

62 

63 atoms.get_potential_energy() 

64 

65 if hasattr(calc, 'get_fermi_level'): 

66 # What is the protocol for a calculator to tell whether 

67 # it has fermi_energy? 

68 eref = calc.get_fermi_level() 

69 else: 

70 eref = 0.0 

71 

72 if bs_kwargs is None: 

73 bs_kwargs = {} 

74 

75 calc.set(kpts=path, **bs_kwargs) 

76 calc.results.clear() # XXX get rid of me 

77 

78 # Calculators are too inconsistent here: 

79 # * atoms.get_potential_energy() will fail when total energy is 

80 # not in results after BS calculation (Espresso) 

81 # * calc.calculate(atoms) doesn't ask for any quantity, so some 

82 # calculators may not calculate anything at all 

83 # * 'bandstructure' is not a recognized property we can ask for 

84 try: 

85 atoms.get_potential_energy() 

86 except PropertyNotImplementedError: 

87 pass 

88 

89 ibzkpts = calc.get_ibz_k_points() 

90 kpts_err = np.abs(path.kpts - ibzkpts).max() 

91 if kpts_err > kpts_tol: 

92 raise RuntimeError( 

93 'Kpoints of calculator differ from those ' 

94 'of the band path we just used; ' 

95 'err={} > tol={}'.format(kpts_err, kpts_tol) 

96 ) 

97 

98 bs = get_band_structure(atoms, path=path, reference=eref) 

99 return bs 

100 

101 

102def get_band_structure(atoms=None, calc=None, path=None, reference=None): 

103 """Create band structure object from Atoms or calculator.""" 

104 # path and reference are used internally at the moment, but 

105 # the exact implementation will probably change. WIP. 

106 # 

107 # XXX We throw away info about the bandpath when we create the calculator. 

108 # If we have kept the bandpath, we can provide it as an argument here. 

109 # It would be wise to check that the bandpath kpoints are the same as 

110 # those stored in the calculator. 

111 atoms = atoms if atoms is not None else calc.atoms 

112 calc = calc if calc is not None else atoms.calc 

113 

114 kpts = calc.get_ibz_k_points() 

115 

116 energies = [] 

117 for s in range(calc.get_number_of_spins()): 

118 energies.append( 

119 [calc.get_eigenvalues(kpt=k, spin=s) for k in range(len(kpts))] 

120 ) 

121 energies = np.array(energies) 

122 

123 if path is None: 

124 from ase.dft.kpoints import ( 

125 BandPath, 

126 find_bandpath_kinks, 

127 resolve_custom_points, 

128 ) 

129 

130 standard_path = atoms.cell.bandpath(npoints=0) 

131 # Kpoints are already evaluated, we just need to put them into 

132 # the path (whether they fit our idea of what the path is, or not). 

133 # 

134 # Depending on how the path was established, the kpoints might 

135 # be valid high-symmetry points, but since there are multiple 

136 # high-symmetry points of each type, they may not coincide 

137 # with ours if the bandpath was generated by another code. 

138 # 

139 # Here we hack it so the BandPath has proper points even if they 

140 # come from some weird source. 

141 # 

142 # This operation (manually hacking the bandpath) is liable to break. 

143 # TODO: Make it available as a proper (documented) bandpath method. 

144 kinks = find_bandpath_kinks(atoms.cell, kpts, eps=1e-5) 

145 pathspec, special_points = resolve_custom_points( 

146 kpts[kinks], standard_path.special_points, eps=1e-5 

147 ) 

148 path = BandPath( 

149 standard_path.cell, 

150 kpts=kpts, 

151 path=pathspec, 

152 special_points=special_points, 

153 ) 

154 

155 # XXX If we *did* get the path, now would be a good time to check 

156 # that it matches the cell! Although the path can only be passed 

157 # because we internally want to not re-evaluate the Bravais 

158 # lattice type. (We actually need an eps parameter, too.) 

159 

160 if reference is None: 

161 # Fermi level should come from the GS calculation, not the BS one! 

162 reference = calc.get_fermi_level() 

163 

164 if reference is None: 

165 # Fermi level may not be available, e.g., with non-Fermi smearing. 

166 # XXX Actually get_fermi_level() should raise an error when Fermi 

167 # level wasn't available, so we should fix that. 

168 reference = 0.0 

169 

170 return BandStructure(path=path, energies=energies, reference=reference) 

171 

172 

173class BandStructurePlot: 

174 def __init__(self, bs): 

175 self.bs = bs 

176 self.ax = None 

177 self.xcoords = None 

178 

179 def plot( 

180 self, 

181 ax=None, 

182 *, 

183 spin=None, 

184 emin=-10, 

185 emax=5, 

186 filename=None, 

187 show=False, 

188 ylabel=None, 

189 colors=None, 

190 point_colors=None, 

191 label=None, 

192 loc=None, 

193 cmap=None, 

194 cmin=-1.0, 

195 cmax=1.0, 

196 sortcolors=False, 

197 colorbar=True, 

198 clabel='$s_z$', 

199 cax=None, 

200 **plotkwargs, 

201 ): 

202 """Plot band-structure. 

203 

204 ax: Axes 

205 MatPlotLib Axes object. Will be created if not supplied. 

206 spin: int or None 

207 If given, only plot the specified spin channel. 

208 If None, plot all spins. 

209 Default: None, i.e., plot all spins. 

210 emin, emax: float 

211 Minimum and maximum energy above reference. 

212 filename: str 

213 If given, write image to a file. 

214 show: bool 

215 Show the image (not needed in notebooks). 

216 ylabel: str 

217 The label along the y-axis. Defaults to 'energies [eV]' 

218 colors: sequence of str 

219 A sequence of one or two color specifications, depending on 

220 whether there is spin. 

221 Default: green if no spin, yellow and blue if spin is present. 

222 point_colors: ndarray 

223 An array of numbers of the shape (nspins, n_kpts, nbands) which 

224 are then mapped onto colors by the colormap (see ``cmap``). 

225 ``colors`` and ``point_colors`` are mutually exclusive 

226 label: str or list of str 

227 Label for the curves on the legend. A string if one spin is 

228 present, a list of two strings if two spins are present. 

229 Default: If no spin is given, no legend is made; if spin is 

230 present default labels 'spin up' and 'spin down' are used, but 

231 can be suppressed by setting ``label=False``. 

232 loc: str 

233 Location of the legend. 

234 

235 If ``point_colors`` is given, the following arguments can be specified. 

236 

237 cmap: 

238 Only used if colors is an array of numbers. A matplotlib 

239 colormap object, or a string naming a standard colormap. 

240 Default: The matplotlib default, typically 'viridis'. 

241 cmin, cmax: float 

242 Minimal and maximal values used for colormap translation. 

243 Default: -1.0 and 1.0 

244 colorbar: bool 

245 Whether to make a colorbar. 

246 clabel: str 

247 Label for the colorbar (default 's_z', set to None to suppress. 

248 cax: Axes 

249 Axes object used for plotting colorbar. Default: split off a 

250 new one. 

251 sortcolors (bool or callable): 

252 Sort points so highest color values are in front. If a callable is 

253 given, then it is called on the color values to determine the sort 

254 order. 

255 

256 Any additional keyword arguments are passed directly to matplotlib's 

257 plot() or scatter() methods, depending on whether point_colors is 

258 given. 

259 """ 

260 import matplotlib.pyplot as plt 

261 

262 if colors is not None and point_colors is not None: 

263 raise ValueError("Don't give both 'color' and 'point_color'") 

264 

265 if self.ax is None: 

266 ax = self.prepare_plot(ax, emin, emax, ylabel) 

267 

268 if spin is None: 

269 e_skn = self.bs.energies 

270 elif spin not in [0, 1]: 

271 raise ValueError(f'spin should be 0 or 1, not {spin}') 

272 else: 

273 # Select only one spin channel. 

274 e_skn = self.bs.energies[spin, np.newaxis] 

275 

276 nspins = len(e_skn) 

277 

278 if point_colors is None: 

279 # Normal band structure plot 

280 if colors is None: 

281 if len(e_skn) == 1: 

282 colors = 'g' 

283 else: 

284 colors = 'yb' 

285 elif len(colors) != nspins: 

286 raise ValueError( 

287 f'colors should be a sequence of {nspins} colors' 

288 ) 

289 

290 # Default values for label 

291 if label is None and nspins == 2: 

292 label = ['spin up', 'spin down'] 

293 

294 if label: 

295 if nspins == 1 and isinstance(label, str): 

296 label = [label] 

297 elif len(label) != nspins: 

298 raise ValueError( 

299 f'label should be a list of {nspins} strings' 

300 ) 

301 

302 for spin, e_kn in enumerate(e_skn): 

303 kwargs = dict(color=colors[spin]) 

304 kwargs.update(plotkwargs) 

305 lbl = None # Retain lbl=None if label=False 

306 if label: 

307 lbl = label[spin] 

308 ax.plot(self.xcoords, e_kn[:, 0], label=lbl, **kwargs) 

309 

310 for e_k in e_kn.T[1:]: 

311 ax.plot(self.xcoords, e_k, **kwargs) 

312 show_legend = label is not None or nspins == 2 

313 

314 else: 

315 # A color per datapoint. 

316 kwargs = dict(vmin=cmin, vmax=cmax, cmap=cmap, s=1) 

317 kwargs.update(plotkwargs) 

318 shape = e_skn.shape 

319 xcoords = np.zeros(shape) 

320 xcoords += self.xcoords[np.newaxis, :, np.newaxis] 

321 if sortcolors: 

322 if callable(sortcolors): 

323 perm = sortcolors(point_colors).argsort(axis=None) 

324 else: 

325 perm = point_colors.argsort(axis=None) 

326 e_skn = e_skn.ravel()[perm].reshape(shape) 

327 point_colors = point_colors.ravel()[perm].reshape(shape) 

328 xcoords = xcoords.ravel()[perm].reshape(shape) 

329 

330 things = ax.scatter(xcoords, e_skn, c=point_colors, **kwargs) 

331 if colorbar: 

332 cbar = plt.colorbar(things, cax=cax) 

333 if clabel: 

334 cbar.set_label(clabel) 

335 show_legend = False 

336 

337 self.finish_plot(filename, show, loc, show_legend) 

338 

339 return ax 

340 

341 def prepare_plot(self, ax=None, emin=-10, emax=5, ylabel=None): 

342 import matplotlib.pyplot as plt 

343 

344 if ax is None: 

345 ax = plt.figure().add_subplot(111) 

346 

347 def pretty(kpt): 

348 if kpt == 'G': 

349 kpt = r'$\Gamma$' 

350 elif len(kpt) == 2: 

351 kpt = kpt[0] + '$_' + kpt[1] + '$' 

352 return kpt 

353 

354 self.xcoords, label_xcoords, orig_labels = self.bs.get_labels() 

355 label_xcoords = list(label_xcoords) 

356 labels = [pretty(name) for name in orig_labels] 

357 

358 i = 1 

359 while i < len(labels): 

360 if label_xcoords[i - 1] == label_xcoords[i]: 

361 labels[i - 1] = labels[i - 1] + ',' + labels[i] 

362 labels.pop(i) 

363 label_xcoords.pop(i) 

364 else: 

365 i += 1 

366 

367 for x in label_xcoords[1:-1]: 

368 ax.axvline(x, color='0.5') 

369 

370 ylabel = ylabel if ylabel is not None else 'energies [eV]' 

371 

372 ax.set_xticks(label_xcoords) 

373 ax.set_xticklabels(labels) 

374 ax.set_ylabel(ylabel) 

375 ax.axhline(self.bs.reference, color='k', ls=':') 

376 ax.axis(xmin=0, xmax=self.xcoords[-1], ymin=emin, ymax=emax) 

377 self.ax = ax 

378 return ax 

379 

380 def finish_plot(self, filename, show, loc, show_legend=False): 

381 import matplotlib.pyplot as plt 

382 

383 if show_legend: 

384 leg = self.ax.legend(loc=loc) 

385 leg.get_frame().set_alpha(1) 

386 

387 if filename: 

388 self.ax.figure.savefig(filename) 

389 

390 if show: 

391 plt.show() 

392 

393 

394@jsonable('bandstructure') 

395class BandStructure: 

396 """A band structure consists of an array of eigenvalues and a bandpath. 

397 

398 BandStructure objects support JSON I/O. 

399 """ 

400 

401 def __init__(self, path, energies, reference=0.0): 

402 self._path = path 

403 self._energies = np.asarray(energies) 

404 assert self.energies.shape[0] in [1, 2] # spins x kpts x bands 

405 assert self.energies.shape[1] == len(path.kpts) 

406 assert np.isscalar(reference) 

407 self._reference = reference 

408 

409 @property 

410 def energies(self) -> np.ndarray: 

411 """The energies of this band structure. 

412 

413 This is a numpy array of shape (nspins, nkpoints, nbands).""" 

414 return self._energies 

415 

416 @property 

417 def path(self) -> 'ase.dft.kpoints.BandPath': 

418 """The :class:`~ase.dft.kpoints.BandPath` of this band structure.""" 

419 return self._path 

420 

421 @property 

422 def reference(self) -> float: 

423 """The reference energy. 

424 

425 Semantics may vary; typically a Fermi energy or zero, 

426 depending on how the band structure was created.""" 

427 return self._reference 

428 

429 def subtract_reference(self) -> 'BandStructure': 

430 """Return new band structure with reference energy subtracted.""" 

431 return BandStructure( 

432 self.path, self.energies - self.reference, reference=0.0 

433 ) 

434 

435 def todict(self): 

436 return dict( 

437 path=self.path, energies=self.energies, reference=self.reference 

438 ) 

439 

440 def get_labels(self, eps=1e-5): 

441 """ "See :func:`ase.dft.kpoints.labels_from_kpts`.""" 

442 return self.path.get_linear_kpoint_axis(eps=eps) 

443 

444 def plot(self, *args, **kwargs): 

445 """Plot this band structure.""" 

446 bsp = BandStructurePlot(self) 

447 return bsp.plot(*args, **kwargs) 

448 

449 def __repr__(self): 

450 return '{}(path={!r}, energies=[{} values], reference={})'.format( 

451 self.__class__.__name__, 

452 self.path, 

453 '{}x{}x{}'.format(*self.energies.shape), 

454 self.reference, 

455 )