"""
概要:
    高速で堅牢なフェルミ・ディラック積分ライブラリです。
"""

from math import exp, gamma, isclose
from functools import lru_cache
import numpy as np
from scipy import integrate
from scipy.special import expit, log_expit
from scipy.special import zeta
from scipy.special import spence  # 追加：Li2(x)の計算に使用


xlim_exp = 40.0
#xlim_exp = 300.0

kF12 = 2.0 / np.sqrt(np.pi)  # 2/sqrt(pi)


# ------------------------------------------------------------
# Sommerfeld expansion coefficients for degenerate limit
# z_k = (1 - 2^(-(2k+1))) * zeta(2k+2)
# where zeta(s, 1) = Riemann zeta(s)
# for validation: _deg_coeffs = (0.822467, 0.947033, 0.985551, 0.996233, 0.999040, 0.999758, 0.999939, 0.999985)
# ------------------------------------------------------------
n_deg_coeffs = 10

"""
_deg_coeffs = [
    (1.0 - 2.0 ** (-(2 * k + 1))) * float(zeta(2 * k + 2, 1.0))
    for k in range(n_deg_coeffs)
]
"""

def generate_sommerfeld_coeffs(n_terms):
    """
    概要:
        縮退極限のためのゾンマーフェルト展開係数を生成します。
    引数:
        :param n_terms: 係数を計算する項数
        :type n_terms: int
    戻り値:
        :returns: 計算された係数のタプル
        :rtype: tuple
    """
    coeffs = []
    for k in range(1, n_terms + 1):
        # z_k = (1 - 2^(1-2k)) * zeta(2k)
        val = (1 - 2.0**(1 - 2*k)) * zeta(2*k, 1)
        coeffs.append(float(val))
    return tuple(coeffs)

_deg_coeffs = generate_sommerfeld_coeffs(n_deg_coeffs)

def _round_key(x, ndigit=10):
    """
    概要:
        キャッシュキー用の値を丸めます。
    引数:
        :param x: 丸める数値
        :type x: float
        :param ndigit: 小数点以下の桁数
        :type ndigit: int
    戻り値:
        :returns: 丸められた数値
        :rtype: float
    """
    return round(float(x), ndigit)


# ------------------------------------------------------------
# Fermi–Dirac occupations (x = E/kT, eta = Ef/kT)
# ------------------------------------------------------------
def fermi_dirac_e_npvector(x):
    """
    概要:
        numpy配列に対するフェルミ・ディラック分布を計算します。
    引数:
        :param x: エネルギーとフェルミ準位の差をkTで割った無次元量の配列
        :type x: numpy.ndarray
    戻り値:
        :returns: 計算された占有確率の配列
        :rtype: numpy.ndarray
    """
    x = np.clip(x, -xlim_exp, xlim_exp)
    pos = x > 0
    out = np.empty_like(x)
    exp_positive = np.exp(-x[pos])
    out[pos] = exp_positive / (1 + exp_positive)
    out[~pos] = 1 / (1 + np.exp(x[~pos]))
    return out

def fermi_dirac_e_if(x, eta, g=1.0):
    """
    概要:
        条件分岐を用いてフェルミ・ディラック分布を計算します。
    詳細説明:
        f = 1 / (1 + g * exp(x - eta)) を計算します。
    引数:
        :param x: エネルギーの無次元量
        :type x: float
        :param eta: フェルミ準位の無次元量
        :type eta: float
        :param g: 縮退度係数
        :type g: float
    戻り値:
        :returns: 計算された占有確率
        :rtype: float
    """
    xe = x - eta
    if xe < -xlim_exp: return 1.0
    if xe > xlim_exp: return 0.0
    return 1.0 / (1 + g * exp(xe))

def fermi_dirac_e(x, eta, g=1.0):
    """
    概要:
        フェルミ・ディラック分布による電子の占有確率を計算します。
    詳細説明:
        f = 1 / (1 + g * exp(x - eta)) = expit((eta - x) - ln(g)) を用いて安定に計算します。
    引数:
        :param x: エネルギーの無次元量
        :type x: float or numpy.ndarray
        :param eta: フェルミ準位の無次元量
        :type eta: float or numpy.ndarray
        :param g: 縮退度係数
        :type g: float
    戻り値:
        :returns: 電子の占有確率
        :rtype: float or numpy.ndarray
    """
    return expit((eta - x) - np.log(g))

def log_fermi_dirac_e(x, eta, g=1.0):
    """
    概要:
        フェルミ・ディラック分布による電子の占有確率の対数を計算します。
    詳細説明:
        安定した計算方法を用いて log(f) を求めます。
    引数:
        :param x: エネルギーの無次元量
        :type x: float or numpy.ndarray
        :param eta: フェルミ準位の無次元量
        :type eta: float or numpy.ndarray
        :param g: 縮退度係数
        :type g: float
    戻り値:
        :returns: 占有確率の対数
        :rtype: float or numpy.ndarray
    """
    return log_expit((eta - x) - np.log(g))

def fermi_dirac_h(x, eta, g=1.0):
    """
    概要:
        フェルミ・ディラック分布による正孔の占有確率を計算します。
    詳細説明:
        1 - f = 1 / (1 + g * exp(eta - x)) = expit((x - eta) - ln(g)) を用いて安定に計算します。
    引数:
        :param x: エネルギーの無次元量
        :type x: float or numpy.ndarray
        :param eta: フェルミ準位の無次元量
        :type eta: float or numpy.ndarray
        :param g: 縮退度係数
        :type g: float
    戻り値:
        :returns: 正孔の占有確率
        :rtype: float or numpy.ndarray
    """
    return expit((x - eta) - np.log(g))

def log_fermi_dirac_h(x, eta, g=1.0):
    """
    概要:
        フェルミ・ディラック分布による正孔の占有確率の対数を計算します。
    詳細説明:
        安定した計算方法を用いて log(1-f) を求めます。
    引数:
        :param x: エネルギーの無次元量
        :type x: float or numpy.ndarray
        :param eta: フェルミ準位の無次元量
        :type eta: float or numpy.ndarray
        :param g: 縮退度係数
        :type g: float
    戻り値:
        :returns: 正孔の占有確率の対数
        :rtype: float or numpy.ndarray
    """
    return log_expit((x - eta) - np.log(g))

def ionized_acceptor_frac(eta, xA, g=1.0):
    """
    概要:
        イオン化アクセプタの割合を計算します。
    引数:
        :param eta: フェルミ準位の無次元量
        :type eta: float or numpy.ndarray
        :param xA: アクセプタ準位の無次元量
        :type xA: float or numpy.ndarray
        :param g: 縮退度係数
        :type g: float
    戻り値:
        :returns: イオン化したアクセプタの割合
        :rtype: float or numpy.ndarray
    """
    return fermi_dirac_e(xA, eta, g=g)

def ionized_donor_frac(eta, xD, g=1.0):
    """
    概要:
        イオン化ドナーの割合を計算します。
    詳細説明:
        ND+/ND = 1 / (1 + g * exp(eta - xD)) を計算します。
    引数:
        :param eta: フェルミ準位の無次元量
        :type eta: float or numpy.ndarray
        :param xD: ドナー準位の無次元量
        :type xD: float or numpy.ndarray
        :param g: 縮退度係数
        :type g: float
    戻り値:
        :returns: イオン化したドナーの割合
        :rtype: float or numpy.ndarray
    """
    return fermi_dirac_h(xD, eta, g=g)

# ============================================================
# internal: degenerate limit (Sommerfeld-like)
# ============================================================

def _DegenerateFermiDirac(eta, r):
    """
    概要:
        縮退極限でのフェルミ・ディラック積分を計算します。
    引数:
        :param eta: フェルミ準位の無次元量
        :type eta: float
        :param r: 積分の次数
        :type r: float
    戻り値:
        :returns: 計算された積分値
        :rtype: float
    """
    gi = eta ** (r + 1.0) / (r + 1.0)
    t = r
    gg = t / (eta * eta)
    gs = gg * _deg_coeffs[0]
    t -= 1.0

    for k in range(1, n_deg_coeffs):
        gg *= t * (t - 1.0) / (eta * eta)
        gs += gg * _deg_coeffs[k]
        t -= 2.0

    return gi * (1.0 + 2.0 * (r + 1.0) * gs)


# ============================================================
# internal: non-degenerate limit (alternating series)
# ============================================================

def _NonDegenerateFermiDirac(eta, r, reltol=1e-10, max_terms=200000):
    """
    概要:
        非縮退極限でのフェルミ・ディラック積分を計算します。
    引数:
        :param eta: フェルミ準位の無次元量
        :type eta: float
        :param r: 積分の次数
        :type r: float
        :param reltol: 相対許容誤差
        :type reltol: float
        :param max_terms: 最大項数
        :type max_terms: int
    戻り値:
        :returns: 計算された積分値
        :rtype: float
    """
    if eta < -20.0:
        return gamma(r + 1.0) * exp(eta)

    s = 1.0
    total = 0.0
    scale = 0.0

    for _ in range(max_terms // 2):
        t1 = exp(s * eta) / s**(r + 1.0)
        s += 1.0
        t2 = exp(s * eta) / s**(r + 1.0)
        s += 1.0

        subtotal = t1 - t2
        total += subtotal

        scale = max(scale, abs(t1), abs(t2))

        if abs(subtotal) < reltol * max(abs(total), 1.0):
            break

    return total * gamma(r+1.0)


# ============================================================
# cache-safe wrapper
# ============================================================

def _func_Fr_x2(x, eta, r):
    """
    概要:
        フェルミ・ディラック積分のための被積分関数を計算します。
    引数:
        :param x: 積分変数
        :type x: float
        :param eta: フェルミ準位の無次元量
        :type eta: float
        :param r: 積分の次数
        :type r: float
    戻り値:
        :returns: 被積分関数の値
        :rtype: float
    """
    return 2.0 * x ** (2.0 * r + 1.0) * expit(eta - x*x)

def _FermiIntegral_core(eta, r, epsabs, epsrel, limit):
    """
    概要:
        フェルミ・ディラック積分のコア計算を行います。
    引数:
        :param eta: フェルミ準位の無次元量
        :type eta: float
        :param r: 積分の次数
        :type r: float
        :param epsabs: 絶対許容誤差
        :type epsabs: float
        :param epsrel: 相対許容誤差
        :type epsrel: float
        :param limit: 積分分割数
        :type limit: int
    戻り値:
        :returns: 計算された積分値
        :rtype: float
    """
    # degenerate
    if eta >= 25.0 + 2.0 * r:
        return _DegenerateFermiDirac(eta, r)

    # non-degenerate
    if eta < -0.1:
        return _NonDegenerateFermiDirac(eta, r)

    # intermediate: z = x^2 + quad
    lim = 17.0 + 4.5 * r + eta
    lim = max(lim, 4.0)
    f = lambda x: _func_Fr_x2(x, eta, r)

    ret = 0.0
    ret += integrate.quad(f, 0.0, 1.0, epsabs=epsabs, epsrel=epsrel, limit=limit)[0]
    ret += integrate.quad(f, 1.0, 4.0, epsabs=epsabs, epsrel=epsrel, limit=limit)[0]
    ret += integrate.quad(f, 4.0, lim, epsabs=epsabs, epsrel=epsrel, limit=limit)[0]

    return ret

@lru_cache(maxsize=1024)
def _FermiIntegral_cached(eta, r, epsabs, epsrel, limit):
    """
    概要:
        フェルミ・ディラック積分の計算結果をキャッシュして返します。
    引数:
        :param eta: フェルミ準位の無次元量
        :type eta: float
        :param r: 積分の次数
        :type r: float
        :param epsabs: 絶対許容誤差
        :type epsabs: float
        :param epsrel: 相対許容誤差
        :type epsrel: float
        :param limit: 積分分割数
        :type limit: int
    戻り値:
        :returns: 計算された積分値
        :rtype: float
    """
    return _FermiIntegral_core(eta, r, epsabs, epsrel, limit)

# ============================================================
# public API
# ============================================================

def FermiIntegral_fast(
    eta, r,
    *,
    epsabs=1.0e-10,
    epsrel=1.0e-8,
    limit=50,
    use_cache = True
):
    """
    概要:
        一般化されたフェルミ・ディラック積分 F_r(eta) を計算します。
    詳細説明:
        整数次数 (r = -1, 0, 1) については解析解や特殊関数を用いて高速化しています。
    引数:
        :param eta: フェルミ準位の無次元量
        :type eta: float
        :param r: 積分の次数
        :type r: float
        :param epsabs: 積分計算の絶対許容誤差
        :type epsabs: float
        :param epsrel: 積分計算の相対許容誤差
        :type epsrel: float
        :param limit: 積分計算の最大分割数
        :type limit: int
        :param use_cache: キャッシュを使用するかどうか
        :type use_cache: bool
    戻り値:
        :returns: 計算された積分値
        :rtype: float
    """
    # --- 整数次数の解析解 / 特殊関数による高速化 ---
    is_integer_r = isclose(r, round(r), abs_tol=1e-12)
    ri = int(round(r)) if is_integer_r else None
    
    if is_integer_r:
    # r = -1: F_{-1}(eta) = 1 / (1 + exp(-eta))
        if ri == -1:
            return expit(eta)

    # r = 0: F_0(eta) = ln(1 + exp(eta))
        if ri == 0:
            if eta > 0:
                return eta + np.log1p(np.exp(-eta))
            else:
                return np.log1p(np.exp(eta))

    # r = 1: F_1(eta) = -Li2(-exp(eta))
    # scipy.special.spence(z) は Li2(z) そのものではなく Li2(z)に関連した定義
    # Li2(z) = spence(1-z) なので、F_1(eta) = -spence(1 + exp(eta))
        if ri == 1:
            if eta > 100:
            # 漸近展開 (eta^2 / 2 + pi^2 / 6)
                return 0.5 * eta**2 + np.pi**2 / 6.0
            return -float(spence(1.0 + np.exp(eta)))

    # キャッシュキーの作成と呼び出し
    key = (
        _round_key(eta),
        _round_key(r),
        epsabs,
        epsrel,
        limit,
    )
    if use_cache:
        return _FermiIntegral_cached(*key)
    else:
        return _FermiIntegral_core(*key)

def FermiIntegral_half(
    eta,
    *,
    epsabs=1.0e-10,
    epsrel=1.0e-8,
    limit=50
):
    """
    概要:
        次数1/2のフェルミ・ディラック積分 F_{1/2}(eta) を計算します。
    引数:
        :param eta: フェルミ準位の無次元量
        :type eta: float
        :param epsabs: 積分計算の絶対許容誤差
        :type epsabs: float
        :param epsrel: 積分計算の相対許容誤差
        :type epsrel: float
        :param limit: 積分計算の最大分割数
        :type limit: int
    戻り値:
        :returns: 計算された積分値
        :rtype: float
    """

    return FermiIntegral_fast(
        eta, 0.5,
        epsabs=epsabs,
        epsrel=epsrel,
        limit=limit
    )


def FermiIntegral_3half(
    eta,
    *,
    epsabs=1.0e-10,
    epsrel=1.0e-8,
    limit=50
):
    """
    概要:
        次数3/2のフェルミ・ディラック積分 F_{3/2}(eta) を計算します。
    引数:
        :param eta: フェルミ準位の無次元量
        :type eta: float
        :param epsabs: 積分計算の絶対許容誤差
        :type epsabs: float
        :param epsrel: 積分計算の相対許容誤差
        :type epsrel: float
        :param limit: 積分計算の最大分割数
        :type limit: int
    戻り値:
        :returns: 計算された積分値
        :rtype: float
    """

    return FermiIntegral_fast(
        eta, 1.5,
        epsabs=epsabs,
        epsrel=epsrel,
        limit=limit
    )


# ============================================================
# carrier density helpers (Gamma-normalization NOT used)
# ============================================================

def electron_density(Nc, eta_c, *, epsabs=1.0e-10, epsrel=1.0e-8, limit=50):
    """
    概要:
        電子密度を計算します。
    詳細説明:
        非放物線性を無視した標準的な放物線バンドを仮定します。
        ガンマ関数による正規化を行わないフェルミ・ディラック積分を用いて計算します。
    引数:
        :param Nc: 伝導帯の有効状態密度
        :type Nc: float
        :param eta_c: 電子の無次元化学ポテンシャル (Ef - Ec) / (kT)
        :type eta_c: float or numpy.ndarray
        :param epsabs: 積分計算の絶対許容誤差
        :type epsabs: float
        :param epsrel: 積分計算の相対許容誤差
        :type epsrel: float
        :param limit: 積分計算の最大分割数
        :type limit: int
    戻り値:
        :returns: Ncと同じ単位の電子密度
        :rtype: float or numpy.ndarray
    """

    eta_arr = np.asarray(eta_c)
    if eta_arr.ndim == 0:
        return Nc * kF12 * FermiIntegral_half(
            float(eta_arr), epsabs=epsabs, epsrel=epsrel, limit=limit
        )
    out = np.empty_like(eta_arr, dtype=float)
    it = np.nditer(eta_arr, flags=["multi_index"])
    for v in it:
        out[it.multi_index] = Nc * kF12 * FermiIntegral_half(
            float(v), epsabs=epsabs, epsrel=epsrel, limit=limit
        )
    return out


def hole_density(Nv, eta_v, *, epsabs=1.0e-10, epsrel=1.0e-8, limit=50):
    """
    概要:
        正孔密度を計算します。
    詳細説明:
        標準的な放物線価電子帯を仮定します。
        ガンマ関数による正規化を行わないフェルミ・ディラック積分を用いて計算します。
    引数:
        :param Nv: 価電子帯の有効状態密度
        :type Nv: float
        :param eta_v: 正孔の無次元化学ポテンシャル (Ef - Ev) / (kT)
        :type eta_v: float or numpy.ndarray
        :param epsabs: 積分計算の絶対許容誤差
        :type epsabs: float
        :param epsrel: 積分計算の相対許容誤差
        :type epsrel: float
        :param limit: 積分計算の最大分割数
        :type limit: int
    戻り値:
        :returns: Nvと同じ単位の正孔密度
        :rtype: float or numpy.ndarray
    """

    eta_arr = np.asarray(eta_v)
    if eta_arr.ndim == 0:
        return Nv * kF12 * FermiIntegral_half(
            float(-eta_arr), epsabs=epsabs, epsrel=epsrel, limit=limit
        )
    out = np.empty_like(eta_arr, dtype=float)
    it = np.nditer(eta_arr, flags=["multi_index"])
    for v in it:
        out[it.multi_index] = Nv * kF12 * FermiIntegral_half(
            float(-v), epsabs=epsabs, epsrel=epsrel, limit=limit
        )
    return out


# ============================================================
# self-test
# ============================================================

if __name__ == "__main__":
    Nc = 1.0e19
    Nv = 1.0e19
    eta_list = [-10.0, -3.0, -1.0, 0.0, 2.0, 5.0, 10.0]

    print("Fermi–Dirac integral test")
    print("")

    print("r = 1/2")
    for eta in eta_list:
        print(f"  eta={eta:6.2f}  F1/2={FermiIntegral_half(eta):.8e}")

    print("\nr = 3/2")
    for eta in eta_list:
        n = electron_density(Nc, eta)
        p = hole_density(Nv, eta)
        print(f"  eta={eta:6.2f}  F3/2={FermiIntegral_3half(eta):.8e}  n={n:.8e}  p={p:.8e}")

    print("\ncache info:")
    print(_FermiIntegral_cached.cache_info())