Fj_test_extreme.py ダウンロード/コピー
Fj_test_extreme.py
Fj_test_extreme.py
1#!/usr/bin/env python3
2# -*- coding: utf-8 -*-
3"""
4Fj_test_extreme.py
5
6Fermi–Dirac integral (non-normalized) test & benchmark with edge/extreme cases.
7
8We test the integral
9 Fj(j, eta) = ∫_0^∞ x^j * f(eta - x) dx
10where f(z) = 1/(1+exp(-z)) = expit(z).
11
12Notes:
13- For j = -1, the integral form diverges at x→0. We instead use the exact identity:
14 F0(eta) = ∫_0^∞ f(eta-x) dx = log(1+exp(eta))
15 d/deta F0(eta) = expit(eta)
16 and define Fj(-1, eta) := expit(eta) (consistent with the recurrence dFj/deta = Fj-1).
17- For other j > -1, we use numerical quadrature (quad) with a conservative finite upper bound.
18
19Edge/limit checks added:
20- Non-degenerate (eta << 0): Fj ≈ exp(eta) * Γ(j+1)
21- T→0 step limit (eta): Fj_0K = ∫_0^{max(eta,0)} x^j dx = max(eta,0)^{j+1}/(j+1)
22- Degenerate (eta >> 1): Sommerfeld (up to π^4 term where applicable)
23
24Usage:
25 python Fj_test_extreme.py
26"""
27
28import time
29import math
30import numpy as np
31from scipy.special import expit, log1p, gamma
32from scipy.integrate import quad
33
34from tkfermi_integral import FermiIntegral_fast
35
36
37# ============================================================
38# Core implementations
39# ============================================================
40def _upper_bound(eta: float) -> float:
41 """
42 Heuristic finite upper bound for quad.
43 - for large positive eta, integrand ~ x^j for x<eta, so upper must exceed eta.
44 - for large x, occupation decays ~ exp(eta-x), so eta+50 is plenty in double precision.
45 """
46 return float(max(eta + 60.0, 120.0))
47
48
49def Fj_expit(j: float, eta: float) -> float:
50 """quad + expit integrand; special-cases j=-1."""
51 if j == -1:
52 return float(expit(eta))
53 if j <= -1:
54 raise ValueError("This implementation supports j > -1, except j=-1 (handled analytically).")
55
56 upper = _upper_bound(eta)
57 integrand = lambda x: (x ** j) * expit(eta - x)
58 res, _ = quad(integrand, 0.0, upper, epsabs=1e-12, epsrel=1e-12, limit=200)
59 return float(res)
60
61
62def Fj_raw(j: float, eta: float) -> float:
63 """quad + raw exp; special-cases j=-1."""
64 if j == -1:
65 # d/deta log(1+exp(eta)) = expit(eta)
66 return float(expit(eta))
67 if j <= -1:
68 raise ValueError("This implementation supports j > -1, except j=-1 (handled analytically).")
69
70 upper = _upper_bound(eta)
71 integrand = lambda x: (x ** j) / (1.0 + np.exp(x - eta))
72 res, _ = quad(integrand, 0.0, upper, epsabs=1e-12, epsrel=1e-12, limit=200)
73 return float(res)
74
75
76def Fj_fast(j: float, eta: float):
77 """Wrapper for your fast implementation. Returns None if not supported."""
78 try:
79 return float(FermiIntegral_fast(eta, j))
80 except Exception:
81 return None
82
83
84# ============================================================
85# Asymptotic / limit reference checks
86# ============================================================
87def Fj_nondegenerate_approx(j: float, eta: float) -> float:
88 """
89 For eta << 0:
90 expit(eta-x) ≈ exp(eta-x)
91 Fj ≈ exp(eta) ∫_0^∞ x^j e^{-x} dx = exp(eta) Γ(j+1)
92 """
93 if j == -1:
94 # expit(eta) ~ exp(eta) for eta<<0
95 return float(np.exp(eta))
96 return float(np.exp(eta) * gamma(j + 1.0))
97
98
99def Fj_0K_step(j: float, eta: float) -> float:
100 """
101 T→0 limit of expit(eta-x) -> Θ(eta-x):
102 Fj_0K = ∫_0^{max(eta,0)} x^j dx = max(eta,0)^(j+1)/(j+1) (j>-1)
103 For j=-1, Fj -> Θ(eta) (but we keep expit(eta) as smooth finite-T analogue).
104 """
105 if j == -1:
106 return float(1.0 if eta > 0 else 0.0)
107 if eta <= 0:
108 return 0.0
109 return float((eta ** (j + 1.0)) / (j + 1.0))
110
111
112def Fj_sommerfeld(j: float, eta: float) -> float:
113 """
114 Sommerfeld expansion (non-normalized) for eta >> 1, j > -1.
115
116 Leading term (0K):
117 η^(j+1)/(j+1)
118 + π^2/6 * j * η^(j-1)
119 + 7π^4/360 * j*(j-1)*(j-2) * η^(j-3) (only meaningful if j>=3 roughly)
120 """
121 if j == -1:
122 # expit(eta) -> 1 for eta>>1
123 return 1.0
124 if eta <= 0:
125 # not a good regime; still return 0K limit
126 return Fj_0K_step(j, eta)
127
128 term0 = (eta ** (j + 1.0)) / (j + 1.0)
129 term2 = (math.pi**2 / 6.0) * j * (eta ** (j - 1.0)) if j > 0 else 0.0
130
131 # π^4 term requires j-3 power; for small j this diverges / is meaningless.
132 if j > 2.0:
133 term4 = (7.0 * math.pi**4 / 360.0) * j * (j - 1.0) * (j - 2.0) * (eta ** (j - 3.0))
134 else:
135 term4 = 0.0
136
137 return float(term0 + term2 + term4)
138
139
140# ============================================================
141# Test helpers
142# ============================================================
143def rel_err(a: float, b: float, tiny: float = 1e-300) -> float:
144 return abs(a - b) / max(abs(b), tiny)
145
146
147def print_header(title: str):
148 print("\n" + "=" * 78)
149 print(title)
150 print("=" * 78)
151
152
153# ============================================================
154# Main tests
155# ============================================================
156def main():
157 # Requested j list including -1
158 j_values = [-1.0, -0.5, 0.0, 0.5, 1.0, 1.5, 2.0]
159
160 # Baseline sweep
161 eta_values = np.array([-20, -10, -5, -2, -1, -0.1, 0.0, 0.1, 1, 2, 5, 10, 20], dtype=float)
162
163 # Extreme / edge cases
164 eta_extreme = np.array([-100, -50, -40, 40, 50, 100], dtype=float)
165
166 # Tolerance for cross-implementation numeric agreement (quad expit vs quad raw)
167 tol_abs = 1e-10
168
169 print_header("A) Consistency check: quad(expit) vs quad(raw) vs fast (if available)")
170 print(f"abs diff tolerance (quad vs quad): {tol_abs:g}")
171 print("-" * 78)
172 print(" j eta quad_expit quad_raw |diff| fast status")
173 print("-" * 78)
174
175 for j in j_values:
176 for eta in eta_values:
177 v1 = Fj_expit(j, float(eta))
178 v2 = Fj_raw(j, float(eta))
179 d12 = abs(v1 - v2)
180
181 v3 = Fj_fast(j, float(eta))
182 if v3 is None:
183 status = "PASS" if d12 < tol_abs else "FAIL"
184 v3s = " (n/a)"
185 else:
186 d13 = abs(v1 - v3)
187 status = "PASS" if (d12 < tol_abs and d13 < tol_abs) else "FAIL"
188 v3s = f"{v3: .6e}"
189
190 print(f"{j:6.1f} {eta:8.2f} {v1: .6e} {v2: .6e} {d12: .2e} {v3s:>12} {status}")
191 print("-" * 78)
192
193 # ------------------------------------------------------------
194 # Edge / limit checks
195 # ------------------------------------------------------------
196 print_header("B) Edge/limit checks: nondegenerate (eta<<0), 0K-step, Sommerfeld (eta>>0)")
197 print("We compare quad(expit) against asymptotic/limit formulae.\n"
198 "For very negative eta: Fj ≈ exp(eta)*Gamma(j+1)\n"
199 "For large positive eta: use 0K step and Sommerfeld expansion as references.\n")
200 print("-" * 78)
201 print(" j eta quad_expit approx_type approx_value rel.err")
202 print("-" * 78)
203
204 # 1) nondegenerate checks
205 for j in j_values:
206 for eta in [-40.0, -50.0]:
207 v = Fj_expit(j, eta)
208 a = Fj_nondegenerate_approx(j, eta)
209 print(f"{j:5.1f} {eta:7.1f} {v: .6e} nondegenerate {a: .6e} {rel_err(v,a):.2e}")
210
211 print("-" * 78)
212
213 # 2) 0K-step check (finite eta, compare to step integral)
214 for j in [x for x in j_values if x != -1.0]:
215 for eta in [-5.0, -1.0, 0.0, 1.0, 5.0, 10.0]:
216 v = Fj_expit(j, eta)
217 a = Fj_0K_step(j, eta)
218 print(f"{j:5.1f} {eta:7.1f} {v: .6e} 0K step {a: .6e} {rel_err(v,a):.2e}")
219
220 print("-" * 78)
221
222 # 3) Sommerfeld check (eta large)
223 for j in [x for x in j_values if x not in (-1.0, 0.0)]: # j=0 has special exact form; skip
224 for eta in [20.0, 40.0]:
225 v = Fj_expit(j, eta)
226 a = Fj_sommerfeld(j, eta)
227 print(f"{j:5.1f} {eta:7.1f} {v: .6e} Sommerfeld {a: .6e} {rel_err(v,a):.2e}")
228
229 # Special exact identity for j=0
230 print("-" * 78)
231 for eta in [-40.0, -10.0, 0.0, 10.0, 40.0]:
232 v = Fj_expit(0.0, eta)
233 a = float(np.log1p(np.exp(eta))) # exact: ∫ f(eta-x) dx = log(1+exp(eta))
234 print(f"{0.0:5.1f} {eta:7.1f} {v: .6e} exact log1p {a: .6e} {rel_err(v,a):.2e}")
235
236 # ------------------------------------------------------------
237 # Benchmark
238 # ------------------------------------------------------------
239 print_header("C) Benchmark (per-call time)")
240 N = 30 # repeat count
241
242 j_bench = [0.5, 1.5]
243 eta_bench = [-10.0, -1.0, 0.0, 1.0, 10.0, 50.0]
244
245 for j in j_bench:
246 print(f"\n[j={j}]")
247 print("-" * 78)
248 for eta in eta_bench:
249 # expit quad
250 t0 = time.perf_counter()
251 for _ in range(N):
252 Fj_expit(j, eta)
253 t1 = time.perf_counter()
254 time_expit = (t1 - t0) / N
255
256 # raw quad
257 t0 = time.perf_counter()
258 for _ in range(N):
259 Fj_raw(j, eta)
260 t1 = time.perf_counter()
261 time_raw = (t1 - t0) / N
262
263 # fast (if any)
264 t_fast = None
265 ok_fast = True
266 try:
267 t0 = time.perf_counter()
268 for _ in range(N * 20):
269 FermiIntegral_fast(eta, j)
270 t1 = time.perf_counter()
271 t_fast = (t1 - t0) / (N * 20)
272 except Exception:
273 ok_fast = False
274
275 print(f"eta={eta:6.1f} | quad(expit)={time_expit*1e3:8.3f} ms quad(raw)={time_raw*1e3:8.3f} ms"
276 + (f" fast={t_fast*1e6:8.3f} µs" if ok_fast else " fast=(n/a)"))
277 print("-" * 78)
278
279 # ------------------------------------------------------------
280 # Extreme eta quick sanity (avoid too much time)
281 # ------------------------------------------------------------
282 print_header("D) Extreme eta sanity (quick)")
283 print("We only run quad(expit) once per point for extreme eta to avoid long runtimes.")
284 print("-" * 78)
285 print(" j eta Fj_expit")
286 print("-" * 78)
287 for j in j_values:
288 for eta in eta_extreme:
289 v = Fj_expit(j, float(eta))
290 print(f"{j:6.1f} {eta:8.1f} {v: .6e}")
291 print("-" * 78)
292
293
294if __name__ == "__main__":
295 main()