Coverage for ase/dft/bandgap.py: 86.82%

129 statements  

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

1import warnings 

2from dataclasses import dataclass 

3 

4import numpy as np 

5 

6spin_error = ( 

7 'The spin keyword is no longer supported. Please call the function ' 

8 'with the energies corresponding to the desired spins.' 

9) 

10_deprecated = object() 

11 

12 

13def get_band_gap(calc, direct=False, spin=_deprecated): 

14 warnings.warn('Please use ase.dft.bandgap.bandgap() instead!') 

15 gap, (s1, k1, _n1), (s2, k2, _n2) = bandgap(calc, direct, spin=spin) 

16 ns = calc.get_number_of_spins() 

17 if ns == 2: 

18 return gap, (s1, k1), (s2, k2) 

19 return gap, k1, k2 

20 

21 

22@dataclass 

23class GapInfo: 

24 eigenvalues: np.ndarray 

25 

26 def __post_init__(self): 

27 self._gapinfo = _bandgap(self.eigenvalues, direct=False) 

28 self._direct_gapinfo = _bandgap(self.eigenvalues, direct=True) 

29 

30 @classmethod 

31 def fromcalc(cls, calc): 

32 kpts = calc.get_ibz_k_points() 

33 nk = len(kpts) 

34 ns = calc.get_number_of_spins() 

35 eigenvalues = np.array( 

36 [ 

37 [calc.get_eigenvalues(kpt=k, spin=s) for k in range(nk)] 

38 for s in range(ns) 

39 ] 

40 ) 

41 

42 efermi = calc.get_fermi_level() 

43 return cls(eigenvalues - efermi) 

44 

45 def gap(self): 

46 return self._gapinfo 

47 

48 def direct_gap(self): 

49 return self._direct_gapinfo 

50 

51 @property 

52 def is_metallic(self) -> bool: 

53 return self._gapinfo[0] == 0.0 

54 

55 @property 

56 def gap_is_direct(self) -> bool: 

57 """Whether the direct and indirect gaps are the same transition.""" 

58 return self._gapinfo[1:] == self._direct_gapinfo[1:] 

59 

60 def description(self, *, ibz_kpoints=None) -> str: 

61 """Return human-friendly description of direct/indirect gap. 

62 

63 If ibz_k_points are given, coordinates are printed as well.""" 

64 

65 lines: list[str] = [] 

66 add = lines.append 

67 

68 def skn(skn): 

69 """Convert k-point indices (s, k, n) to string.""" 

70 description = 's={}, k={}, n={}'.format(*skn) 

71 if ibz_kpoints is not None: 

72 coordtxt = '[{:.2f}, {:.2f}, {:.2f}]'.format( 

73 *ibz_kpoints[skn[1]] 

74 ) 

75 description = f'{description}, {coordtxt}' 

76 return f'({description})' 

77 

78 gap, skn1, skn2 = self.gap() 

79 direct_gap, skn_direct1, skn_direct2 = self.direct_gap() 

80 

81 if self.is_metallic: 

82 add('No gap') 

83 else: 

84 add(f'Gap: {gap:.3f} eV') 

85 add('Transition (v -> c):') 

86 add(f' {skn(skn1)} -> {skn(skn2)}') 

87 

88 if self.gap_is_direct: 

89 add('No difference between direct/indirect transitions') 

90 else: 

91 add('Direct/indirect transitions are different') 

92 add(f'Direct gap: {direct_gap:.3f} eV') 

93 if skn_direct1[0] == skn_direct2[0]: 

94 add(f'Transition at: {skn(skn_direct1)}') 

95 else: 

96 transition = skn( 

97 (f'{skn_direct1[0]}->{skn_direct2[0]}', *skn_direct1[1:]) 

98 ) 

99 add(f'Transition at: {transition}') 

100 

101 return '\n'.join(lines) 

102 

103 

104def bandgap( 

105 calc=None, 

106 direct=False, 

107 spin=_deprecated, 

108 eigenvalues=None, 

109 efermi=None, 

110 output=None, 

111 kpts=None, 

112): 

113 """Calculates the band-gap. 

114 

115 Parameters 

116 ---------- 

117 

118 calc: Calculator object 

119 Electronic structure calculator object. 

120 direct: bool 

121 Calculate direct band-gap. 

122 eigenvalues: ndarray of shape (nspin, nkpt, nband) or (nkpt, nband) 

123 Eigenvalues. 

124 efermi: float 

125 Fermi level (defaults to 0.0). 

126 

127 Returns a (gap, p1, p2) tuple where p1 and p2 are tuples of indices of the 

128 valence and conduction points (s, k, n). 

129 

130 Example: 

131 

132 >>> gap, p1, p2 = bandgap(silicon.calc) # doctest: +SKIP 

133 >>> gap, p1, p2 = bandgap(silicon.calc, direct=True) # doctest: +SKIP 

134 """ 

135 

136 if spin is not _deprecated: 

137 raise RuntimeError(spin_error) 

138 

139 if calc: 

140 kpts = calc.get_ibz_k_points() 

141 nk = len(kpts) 

142 ns = calc.get_number_of_spins() 

143 eigenvalues = np.array( 

144 [ 

145 [calc.get_eigenvalues(kpt=k, spin=s) for k in range(nk)] 

146 for s in range(ns) 

147 ] 

148 ) 

149 if efermi is None: 

150 efermi = calc.get_fermi_level() 

151 

152 efermi = efermi or 0.0 

153 

154 gapinfo = GapInfo(eigenvalues - efermi) 

155 

156 e_skn = gapinfo.eigenvalues 

157 if eigenvalues.ndim == 2: 

158 e_skn = e_skn[np.newaxis] # spinors 

159 

160 if not np.isfinite(e_skn).all(): 

161 raise ValueError('Bad eigenvalues!') 

162 

163 gap, (s1, k1, n1), (s2, k2, n2) = _bandgap(e_skn, direct) 

164 

165 if eigenvalues.ndim != 3: 

166 p1 = (k1, n1) 

167 p2 = (k2, n2) 

168 else: 

169 p1 = (s1, k1, n1) 

170 p2 = (s2, k2, n2) 

171 

172 return gap, p1, p2 

173 

174 

175def _bandgap(e_skn, direct): 

176 """Helper function.""" 

177 ns, nk, nb = e_skn.shape 

178 s1 = s2 = k1 = k2 = n1 = n2 = None 

179 

180 N_sk = (e_skn < 0.0).sum(2) # number of occupied bands 

181 

182 # Check for bands crossing the fermi-level 

183 if ns == 1: 

184 if np.ptp(N_sk[0]) > 0: 

185 return 0.0, (None, None, None), (None, None, None) 

186 else: 

187 if (np.ptp(N_sk, axis=1) > 0).any(): 

188 return 0.0, (None, None, None), (None, None, None) 

189 

190 if (N_sk == 0).any() or (N_sk == nb).any(): 

191 raise ValueError('Too few bands!') 

192 

193 e_skn = np.array( 

194 [ 

195 [e_skn[s, k, N_sk[s, k] - 1 : N_sk[s, k] + 1] for k in range(nk)] 

196 for s in range(ns) 

197 ] 

198 ) 

199 ev_sk = e_skn[:, :, 0] # valence band 

200 ec_sk = e_skn[:, :, 1] # conduction band 

201 

202 if ns == 1: 

203 s1 = 0 

204 s2 = 0 

205 gap, k1, k2 = find_gap(ev_sk[0], ec_sk[0], direct) 

206 n1 = N_sk[0, 0] - 1 

207 n2 = n1 + 1 

208 return gap, (0, k1, n1), (0, k2, n2) 

209 

210 gap, k1, k2 = find_gap(ev_sk.ravel(), ec_sk.ravel(), direct) 

211 if direct: 

212 # Check also spin flips: 

213 for s in [0, 1]: 

214 g, k, _ = find_gap(ev_sk[s], ec_sk[1 - s], direct) 

215 if g < gap: 

216 gap = g 

217 k1 = k + nk * s 

218 k2 = k + nk * (1 - s) 

219 

220 if gap > 0.0: 

221 s1, k1 = divmod(k1, nk) 

222 s2, k2 = divmod(k2, nk) 

223 n1 = N_sk[s1, k1] - 1 

224 n2 = N_sk[s2, k2] 

225 return gap, (s1, k1, n1), (s2, k2, n2) 

226 return 0.0, (None, None, None), (None, None, None) 

227 

228 

229def find_gap(ev_k, ec_k, direct): 

230 """Helper function.""" 

231 if direct: 

232 gap_k = ec_k - ev_k 

233 k = gap_k.argmin() 

234 return gap_k[k], k, k 

235 kv = ev_k.argmax() 

236 kc = ec_k.argmin() 

237 return ec_k[kc] - ev_k[kv], kv, kc