tkfermi_integral.py ダウンロード/コピー
tkfermi_integral.py
tkfermi_integral.py
1"""
2概要:
3 高速で堅牢なフェルミ・ディラック積分ライブラリです。
4"""
5
6from math import exp, gamma, isclose
7from functools import lru_cache
8import numpy as np
9from scipy import integrate
10from scipy.special import expit, log_expit
11from scipy.special import zeta
12from scipy.special import spence # 追加:Li2(x)の計算に使用
13
14
15xlim_exp = 40.0
16#xlim_exp = 300.0
17
18kF12 = 2.0 / np.sqrt(np.pi) # 2/sqrt(pi)
19
20
21# ------------------------------------------------------------
22# Sommerfeld expansion coefficients for degenerate limit
23# z_k = (1 - 2^(-(2k+1))) * zeta(2k+2)
24# where zeta(s, 1) = Riemann zeta(s)
25# for validation: _deg_coeffs = (0.822467, 0.947033, 0.985551, 0.996233, 0.999040, 0.999758, 0.999939, 0.999985)
26# ------------------------------------------------------------
27n_deg_coeffs = 10
28
29"""
30_deg_coeffs = [
31 (1.0 - 2.0 ** (-(2 * k + 1))) * float(zeta(2 * k + 2, 1.0))
32 for k in range(n_deg_coeffs)
33]
34"""
35
36def generate_sommerfeld_coeffs(n_terms):
37 """
38 概要:
39 縮退極限のためのゾンマーフェルト展開係数を生成します。
40 引数:
41 :param n_terms: 係数を計算する項数
42 :type n_terms: int
43 戻り値:
44 :returns: 計算された係数のタプル
45 :rtype: tuple
46 """
47 coeffs = []
48 for k in range(1, n_terms + 1):
49 # z_k = (1 - 2^(1-2k)) * zeta(2k)
50 val = (1 - 2.0**(1 - 2*k)) * zeta(2*k, 1)
51 coeffs.append(float(val))
52 return tuple(coeffs)
53
54_deg_coeffs = generate_sommerfeld_coeffs(n_deg_coeffs)
55
56def _round_key(x, ndigit=10):
57 """
58 概要:
59 キャッシュキー用の値を丸めます。
60 引数:
61 :param x: 丸める数値
62 :type x: float
63 :param ndigit: 小数点以下の桁数
64 :type ndigit: int
65 戻り値:
66 :returns: 丸められた数値
67 :rtype: float
68 """
69 return round(float(x), ndigit)
70
71
72# ------------------------------------------------------------
73# Fermi–Dirac occupations (x = E/kT, eta = Ef/kT)
74# ------------------------------------------------------------
75def fermi_dirac_e_npvector(x):
76 """
77 概要:
78 numpy配列に対するフェルミ・ディラック分布を計算します。
79 引数:
80 :param x: エネルギーとフェルミ準位の差をkTで割った無次元量の配列
81 :type x: numpy.ndarray
82 戻り値:
83 :returns: 計算された占有確率の配列
84 :rtype: numpy.ndarray
85 """
86 x = np.clip(x, -xlim_exp, xlim_exp)
87 pos = x > 0
88 out = np.empty_like(x)
89 exp_positive = np.exp(-x[pos])
90 out[pos] = exp_positive / (1 + exp_positive)
91 out[~pos] = 1 / (1 + np.exp(x[~pos]))
92 return out
93
94def fermi_dirac_e_if(x, eta, g=1.0):
95 """
96 概要:
97 条件分岐を用いてフェルミ・ディラック分布を計算します。
98 詳細説明:
99 f = 1 / (1 + g * exp(x - eta)) を計算します。
100 引数:
101 :param x: エネルギーの無次元量
102 :type x: float
103 :param eta: フェルミ準位の無次元量
104 :type eta: float
105 :param g: 縮退度係数
106 :type g: float
107 戻り値:
108 :returns: 計算された占有確率
109 :rtype: float
110 """
111 xe = x - eta
112 if xe < -xlim_exp: return 1.0
113 if xe > xlim_exp: return 0.0
114 return 1.0 / (1 + g * exp(xe))
115
116def fermi_dirac_e(x, eta, g=1.0):
117 """
118 概要:
119 フェルミ・ディラック分布による電子の占有確率を計算します。
120 詳細説明:
121 f = 1 / (1 + g * exp(x - eta)) = expit((eta - x) - ln(g)) を用いて安定に計算します。
122 引数:
123 :param x: エネルギーの無次元量
124 :type x: float or numpy.ndarray
125 :param eta: フェルミ準位の無次元量
126 :type eta: float or numpy.ndarray
127 :param g: 縮退度係数
128 :type g: float
129 戻り値:
130 :returns: 電子の占有確率
131 :rtype: float or numpy.ndarray
132 """
133 return expit((eta - x) - np.log(g))
134
135def log_fermi_dirac_e(x, eta, g=1.0):
136 """
137 概要:
138 フェルミ・ディラック分布による電子の占有確率の対数を計算します。
139 詳細説明:
140 安定した計算方法を用いて log(f) を求めます。
141 引数:
142 :param x: エネルギーの無次元量
143 :type x: float or numpy.ndarray
144 :param eta: フェルミ準位の無次元量
145 :type eta: float or numpy.ndarray
146 :param g: 縮退度係数
147 :type g: float
148 戻り値:
149 :returns: 占有確率の対数
150 :rtype: float or numpy.ndarray
151 """
152 return log_expit((eta - x) - np.log(g))
153
154def fermi_dirac_h(x, eta, g=1.0):
155 """
156 概要:
157 フェルミ・ディラック分布による正孔の占有確率を計算します。
158 詳細説明:
159 1 - f = 1 / (1 + g * exp(eta - x)) = expit((x - eta) - ln(g)) を用いて安定に計算します。
160 引数:
161 :param x: エネルギーの無次元量
162 :type x: float or numpy.ndarray
163 :param eta: フェルミ準位の無次元量
164 :type eta: float or numpy.ndarray
165 :param g: 縮退度係数
166 :type g: float
167 戻り値:
168 :returns: 正孔の占有確率
169 :rtype: float or numpy.ndarray
170 """
171 return expit((x - eta) - np.log(g))
172
173def log_fermi_dirac_h(x, eta, g=1.0):
174 """
175 概要:
176 フェルミ・ディラック分布による正孔の占有確率の対数を計算します。
177 詳細説明:
178 安定した計算方法を用いて log(1-f) を求めます。
179 引数:
180 :param x: エネルギーの無次元量
181 :type x: float or numpy.ndarray
182 :param eta: フェルミ準位の無次元量
183 :type eta: float or numpy.ndarray
184 :param g: 縮退度係数
185 :type g: float
186 戻り値:
187 :returns: 正孔の占有確率の対数
188 :rtype: float or numpy.ndarray
189 """
190 return log_expit((x - eta) - np.log(g))
191
192def ionized_acceptor_frac(eta, xA, g=1.0):
193 """
194 概要:
195 イオン化アクセプタの割合を計算します。
196 引数:
197 :param eta: フェルミ準位の無次元量
198 :type eta: float or numpy.ndarray
199 :param xA: アクセプタ準位の無次元量
200 :type xA: float or numpy.ndarray
201 :param g: 縮退度係数
202 :type g: float
203 戻り値:
204 :returns: イオン化したアクセプタの割合
205 :rtype: float or numpy.ndarray
206 """
207 return fermi_dirac_e(xA, eta, g=g)
208
209def ionized_donor_frac(eta, xD, g=1.0):
210 """
211 概要:
212 イオン化ドナーの割合を計算します。
213 詳細説明:
214 ND+/ND = 1 / (1 + g * exp(eta - xD)) を計算します。
215 引数:
216 :param eta: フェルミ準位の無次元量
217 :type eta: float or numpy.ndarray
218 :param xD: ドナー準位の無次元量
219 :type xD: float or numpy.ndarray
220 :param g: 縮退度係数
221 :type g: float
222 戻り値:
223 :returns: イオン化したドナーの割合
224 :rtype: float or numpy.ndarray
225 """
226 return fermi_dirac_h(xD, eta, g=g)
227
228# ============================================================
229# internal: degenerate limit (Sommerfeld-like)
230# ============================================================
231
232def _DegenerateFermiDirac(eta, r):
233 """
234 概要:
235 縮退極限でのフェルミ・ディラック積分を計算します。
236 引数:
237 :param eta: フェルミ準位の無次元量
238 :type eta: float
239 :param r: 積分の次数
240 :type r: float
241 戻り値:
242 :returns: 計算された積分値
243 :rtype: float
244 """
245 gi = eta ** (r + 1.0) / (r + 1.0)
246 t = r
247 gg = t / (eta * eta)
248 gs = gg * _deg_coeffs[0]
249 t -= 1.0
250
251 for k in range(1, n_deg_coeffs):
252 gg *= t * (t - 1.0) / (eta * eta)
253 gs += gg * _deg_coeffs[k]
254 t -= 2.0
255
256 return gi * (1.0 + 2.0 * (r + 1.0) * gs)
257
258
259# ============================================================
260# internal: non-degenerate limit (alternating series)
261# ============================================================
262
263def _NonDegenerateFermiDirac(eta, r, reltol=1e-10, max_terms=200000):
264 """
265 概要:
266 非縮退極限でのフェルミ・ディラック積分を計算します。
267 引数:
268 :param eta: フェルミ準位の無次元量
269 :type eta: float
270 :param r: 積分の次数
271 :type r: float
272 :param reltol: 相対許容誤差
273 :type reltol: float
274 :param max_terms: 最大項数
275 :type max_terms: int
276 戻り値:
277 :returns: 計算された積分値
278 :rtype: float
279 """
280 if eta < -20.0:
281 return gamma(r + 1.0) * exp(eta)
282
283 s = 1.0
284 total = 0.0
285 scale = 0.0
286
287 for _ in range(max_terms // 2):
288 t1 = exp(s * eta) / s**(r + 1.0)
289 s += 1.0
290 t2 = exp(s * eta) / s**(r + 1.0)
291 s += 1.0
292
293 subtotal = t1 - t2
294 total += subtotal
295
296 scale = max(scale, abs(t1), abs(t2))
297
298 if abs(subtotal) < reltol * max(abs(total), 1.0):
299 break
300
301 return total * gamma(r+1.0)
302
303
304# ============================================================
305# cache-safe wrapper
306# ============================================================
307
308def _func_Fr_x2(x, eta, r):
309 """
310 概要:
311 フェルミ・ディラック積分のための被積分関数を計算します。
312 引数:
313 :param x: 積分変数
314 :type x: float
315 :param eta: フェルミ準位の無次元量
316 :type eta: float
317 :param r: 積分の次数
318 :type r: float
319 戻り値:
320 :returns: 被積分関数の値
321 :rtype: float
322 """
323 return 2.0 * x ** (2.0 * r + 1.0) * expit(eta - x*x)
324
325def _FermiIntegral_core(eta, r, epsabs, epsrel, limit):
326 """
327 概要:
328 フェルミ・ディラック積分のコア計算を行います。
329 引数:
330 :param eta: フェルミ準位の無次元量
331 :type eta: float
332 :param r: 積分の次数
333 :type r: float
334 :param epsabs: 絶対許容誤差
335 :type epsabs: float
336 :param epsrel: 相対許容誤差
337 :type epsrel: float
338 :param limit: 積分分割数
339 :type limit: int
340 戻り値:
341 :returns: 計算された積分値
342 :rtype: float
343 """
344 # degenerate
345 if eta >= 25.0 + 2.0 * r:
346 return _DegenerateFermiDirac(eta, r)
347
348 # non-degenerate
349 if eta < -0.1:
350 return _NonDegenerateFermiDirac(eta, r)
351
352 # intermediate: z = x^2 + quad
353 lim = 17.0 + 4.5 * r + eta
354 lim = max(lim, 4.0)
355 f = lambda x: _func_Fr_x2(x, eta, r)
356
357 ret = 0.0
358 ret += integrate.quad(f, 0.0, 1.0, epsabs=epsabs, epsrel=epsrel, limit=limit)[0]
359 ret += integrate.quad(f, 1.0, 4.0, epsabs=epsabs, epsrel=epsrel, limit=limit)[0]
360 ret += integrate.quad(f, 4.0, lim, epsabs=epsabs, epsrel=epsrel, limit=limit)[0]
361
362 return ret
363
364@lru_cache(maxsize=1024)
365def _FermiIntegral_cached(eta, r, epsabs, epsrel, limit):
366 """
367 概要:
368 フェルミ・ディラック積分の計算結果をキャッシュして返します。
369 引数:
370 :param eta: フェルミ準位の無次元量
371 :type eta: float
372 :param r: 積分の次数
373 :type r: float
374 :param epsabs: 絶対許容誤差
375 :type epsabs: float
376 :param epsrel: 相対許容誤差
377 :type epsrel: float
378 :param limit: 積分分割数
379 :type limit: int
380 戻り値:
381 :returns: 計算された積分値
382 :rtype: float
383 """
384 return _FermiIntegral_core(eta, r, epsabs, epsrel, limit)
385
386# ============================================================
387# public API
388# ============================================================
389
390def FermiIntegral_fast(
391 eta, r,
392 *,
393 epsabs=1.0e-10,
394 epsrel=1.0e-8,
395 limit=50,
396 use_cache = True
397):
398 """
399 概要:
400 一般化されたフェルミ・ディラック積分 F_r(eta) を計算します。
401 詳細説明:
402 整数次数 (r = -1, 0, 1) については解析解や特殊関数を用いて高速化しています。
403 引数:
404 :param eta: フェルミ準位の無次元量
405 :type eta: float
406 :param r: 積分の次数
407 :type r: float
408 :param epsabs: 積分計算の絶対許容誤差
409 :type epsabs: float
410 :param epsrel: 積分計算の相対許容誤差
411 :type epsrel: float
412 :param limit: 積分計算の最大分割数
413 :type limit: int
414 :param use_cache: キャッシュを使用するかどうか
415 :type use_cache: bool
416 戻り値:
417 :returns: 計算された積分値
418 :rtype: float
419 """
420 # --- 整数次数の解析解 / 特殊関数による高速化 ---
421 is_integer_r = isclose(r, round(r), abs_tol=1e-12)
422 ri = int(round(r)) if is_integer_r else None
423
424 if is_integer_r:
425 # r = -1: F_{-1}(eta) = 1 / (1 + exp(-eta))
426 if ri == -1:
427 return expit(eta)
428
429 # r = 0: F_0(eta) = ln(1 + exp(eta))
430 if ri == 0:
431 if eta > 0:
432 return eta + np.log1p(np.exp(-eta))
433 else:
434 return np.log1p(np.exp(eta))
435
436 # r = 1: F_1(eta) = -Li2(-exp(eta))
437 # scipy.special.spence(z) は Li2(z) そのものではなく Li2(z)に関連した定義
438 # Li2(z) = spence(1-z) なので、F_1(eta) = -spence(1 + exp(eta))
439 if ri == 1:
440 if eta > 100:
441 # 漸近展開 (eta^2 / 2 + pi^2 / 6)
442 return 0.5 * eta**2 + np.pi**2 / 6.0
443 return -float(spence(1.0 + np.exp(eta)))
444
445 # キャッシュキーの作成と呼び出し
446 key = (
447 _round_key(eta),
448 _round_key(r),
449 epsabs,
450 epsrel,
451 limit,
452 )
453 if use_cache:
454 return _FermiIntegral_cached(*key)
455 else:
456 return _FermiIntegral_core(*key)
457
458def FermiIntegral_half(
459 eta,
460 *,
461 epsabs=1.0e-10,
462 epsrel=1.0e-8,
463 limit=50
464):
465 """
466 概要:
467 次数1/2のフェルミ・ディラック積分 F_{1/2}(eta) を計算します。
468 引数:
469 :param eta: フェルミ準位の無次元量
470 :type eta: float
471 :param epsabs: 積分計算の絶対許容誤差
472 :type epsabs: float
473 :param epsrel: 積分計算の相対許容誤差
474 :type epsrel: float
475 :param limit: 積分計算の最大分割数
476 :type limit: int
477 戻り値:
478 :returns: 計算された積分値
479 :rtype: float
480 """
481
482 return FermiIntegral_fast(
483 eta, 0.5,
484 epsabs=epsabs,
485 epsrel=epsrel,
486 limit=limit
487 )
488
489
490def FermiIntegral_3half(
491 eta,
492 *,
493 epsabs=1.0e-10,
494 epsrel=1.0e-8,
495 limit=50
496):
497 """
498 概要:
499 次数3/2のフェルミ・ディラック積分 F_{3/2}(eta) を計算します。
500 引数:
501 :param eta: フェルミ準位の無次元量
502 :type eta: float
503 :param epsabs: 積分計算の絶対許容誤差
504 :type epsabs: float
505 :param epsrel: 積分計算の相対許容誤差
506 :type epsrel: float
507 :param limit: 積分計算の最大分割数
508 :type limit: int
509 戻り値:
510 :returns: 計算された積分値
511 :rtype: float
512 """
513
514 return FermiIntegral_fast(
515 eta, 1.5,
516 epsabs=epsabs,
517 epsrel=epsrel,
518 limit=limit
519 )
520
521
522# ============================================================
523# carrier density helpers (Gamma-normalization NOT used)
524# ============================================================
525
526def electron_density(Nc, eta_c, *, epsabs=1.0e-10, epsrel=1.0e-8, limit=50):
527 """
528 概要:
529 電子密度を計算します。
530 詳細説明:
531 非放物線性を無視した標準的な放物線バンドを仮定します。
532 ガンマ関数による正規化を行わないフェルミ・ディラック積分を用いて計算します。
533 引数:
534 :param Nc: 伝導帯の有効状態密度
535 :type Nc: float
536 :param eta_c: 電子の無次元化学ポテンシャル (Ef - Ec) / (kT)
537 :type eta_c: float or numpy.ndarray
538 :param epsabs: 積分計算の絶対許容誤差
539 :type epsabs: float
540 :param epsrel: 積分計算の相対許容誤差
541 :type epsrel: float
542 :param limit: 積分計算の最大分割数
543 :type limit: int
544 戻り値:
545 :returns: Ncと同じ単位の電子密度
546 :rtype: float or numpy.ndarray
547 """
548
549 eta_arr = np.asarray(eta_c)
550 if eta_arr.ndim == 0:
551 return Nc * kF12 * FermiIntegral_half(
552 float(eta_arr), epsabs=epsabs, epsrel=epsrel, limit=limit
553 )
554 out = np.empty_like(eta_arr, dtype=float)
555 it = np.nditer(eta_arr, flags=["multi_index"])
556 for v in it:
557 out[it.multi_index] = Nc * kF12 * FermiIntegral_half(
558 float(v), epsabs=epsabs, epsrel=epsrel, limit=limit
559 )
560 return out
561
562
563def hole_density(Nv, eta_v, *, epsabs=1.0e-10, epsrel=1.0e-8, limit=50):
564 """
565 概要:
566 正孔密度を計算します。
567 詳細説明:
568 標準的な放物線価電子帯を仮定します。
569 ガンマ関数による正規化を行わないフェルミ・ディラック積分を用いて計算します。
570 引数:
571 :param Nv: 価電子帯の有効状態密度
572 :type Nv: float
573 :param eta_v: 正孔の無次元化学ポテンシャル (Ef - Ev) / (kT)
574 :type eta_v: float or numpy.ndarray
575 :param epsabs: 積分計算の絶対許容誤差
576 :type epsabs: float
577 :param epsrel: 積分計算の相対許容誤差
578 :type epsrel: float
579 :param limit: 積分計算の最大分割数
580 :type limit: int
581 戻り値:
582 :returns: Nvと同じ単位の正孔密度
583 :rtype: float or numpy.ndarray
584 """
585
586 eta_arr = np.asarray(eta_v)
587 if eta_arr.ndim == 0:
588 return Nv * kF12 * FermiIntegral_half(
589 float(-eta_arr), epsabs=epsabs, epsrel=epsrel, limit=limit
590 )
591 out = np.empty_like(eta_arr, dtype=float)
592 it = np.nditer(eta_arr, flags=["multi_index"])
593 for v in it:
594 out[it.multi_index] = Nv * kF12 * FermiIntegral_half(
595 float(-v), epsabs=epsabs, epsrel=epsrel, limit=limit
596 )
597 return out
598
599
600# ============================================================
601# self-test
602# ============================================================
603
604if __name__ == "__main__":
605 Nc = 1.0e19
606 Nv = 1.0e19
607 eta_list = [-10.0, -3.0, -1.0, 0.0, 2.0, 5.0, 10.0]
608
609 print("Fermi–Dirac integral test")
610 print("")
611
612 print("r = 1/2")
613 for eta in eta_list:
614 print(f" eta={eta:6.2f} F1/2={FermiIntegral_half(eta):.8e}")
615
616 print("\nr = 3/2")
617 for eta in eta_list:
618 n = electron_density(Nc, eta)
619 p = hole_density(Nv, eta)
620 print(f" eta={eta:6.2f} F3/2={FermiIntegral_3half(eta):.8e} n={n:.8e} p={p:.8e}")
621
622 print("\ncache info:")
623 print(_FermiIntegral_cached.cache_info())