#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
概要:
    中性原子の Thomas-Fermi 方程式を境界値問題として解く教育用プログラムです。
詳細説明:
    x は無次元距離、phi は遮蔽関数を表します。
    phiの2階微分は phiの1.5乗 / xの平方根 で与えられ、phi(0)=1、phi(infinity)=0 を満たします。
    原子の静電ポテンシャルは phi(x)/r に比例し、密度は phi/x の1.5乗に比例しますが、本プログラムは実単位に変換しません。
    Z や軌道エネルギー、角運動量、SCF反復などは扱いません。
    u=phi、v=phiの1階微分 として連立1階常微分方程式に変換し、scipy.integrate.solve_bvp で全区間を同時に解きます。
    原点の特異性は小さな eps から級数展開で開始して避け、未知パラメータである原点での傾きは境界条件と同時に決定します。
    遠方では有限距離での近似境界条件を課しており、check_domain オプションで計算領域を倍にして結果を比較できます。
    tol は微分方程式の残差許容値であり、物理量の相対誤差保証ではありません。
    教材としての観察ポイントとして、原点近傍級数は原点近くでのみ有効であること、遠方の漸近形は遠方でのみ有効であること、
    shooting で初期傾きを変えると外向き積分が大きく変わることなどが確認できます。
    実行すると指定された接頭辞のCSVファイルとPNG画像が出力されます。
関連リンク:
    scipy_integrate_solve_bvp
"""
from __future__ import annotations
import argparse
from pathlib import Path
import sys
import numpy as np
from scipy.integrate import solve_bvp, solve_ivp


def origin_series(x, b):
    """
    概要:
        原点付近での関数の値と微分値を級数展開で計算します。
    詳細説明:
        元コードの級数に x の4乗項まで追加して計算を行います。
    引数:
        :param x: 評価する無次元距離の配列
        :type x: numpy.ndarray
        :param b: 原点での微係数の推定値
        :type b: float
    戻り値:
        :returns: 遮蔽関数とその1階微分の値を格納した配列
        :rtype: numpy.ndarray
    """
    u = (1 + b*x + 4/3*x**1.5 + 2*b/5*x**2.5 + x**3/3
         + 3*b*b/70*x**3.5 + 2*b/15*x**4)
    v = (b + 2*np.sqrt(x) + b*x**1.5 + x*x
         + 3*b*b/20*x**2.5 + 8*b/15*x**3)
    return np.array([u, v])


def old_approximation(x):
    """
    概要:
        過去の実装で用いられていた遠方近似関数を計算します。
    詳細説明:
        厳密解ではなく比較用や境界値問題の初期推定値として使用します。
    引数:
        :param x: 評価する無次元距離の配列
        :type x: numpy.ndarray
    戻り値:
        :returns: 近似された遮蔽関数の値
        :rtype: numpy.ndarray
    """
    lam, scale = 3.886, 5.2415
    return (1 + (x/scale)**(3/lam))**(-lam)


def rhs(x, y, p=None):
    """
    概要:
        Thomas-Fermi方程式の常微分方程式としての右辺を評価します。
    詳細説明:
        Newton反復中の負の試行値に対する実数拡張を行っており、解の負値を黙って切り捨てることはしません。
        最終解は別途正値性を検査します。
    引数:
        :param x: 無次元距離
        :type x: numpy.ndarray
        :param y: 遮蔽関数とその1階微分を含む配列
        :type y: numpy.ndarray
        :param p: 未知パラメータのリスト
        :type p: list
    戻り値:
        :returns: 導関数の値を格納した配列
        :rtype: numpy.ndarray
    """
    # Newton反復中の負の試行値に対する実数拡張。
    # 最終解は別途正値性を検査する。解の負値を黙って切り捨てない。
    u, v = y
    return np.array([v, np.sign(u)*np.abs(u)**1.5/np.sqrt(x)])


def solve_tf(eps=1e-6, xmax=200., tol=1e-7, verbose=0):
    """
    概要:
        Thomas-Fermi方程式の境界値問題を解きます。
    詳細説明:
        2本の常微分方程式と未知の原点での傾きに対して、3つの境界条件を用いて解を決定します。
    引数:
        :param eps: 原点側の開始位置
        :type eps: float
        :param xmax: 遠方側の境界位置
        :type xmax: float
        :param tol: 境界値問題の残差許容値
        :type tol: float
        :param verbose: ログの出力レベル
        :type verbose: int
    戻り値:
        :returns: 境界値問題の解を格納したオブジェクト
        :rtype: scipy.optimize.OptimizeResult
    例外:
        :raises RuntimeError: ソルバが収束しなかった場合や解が正値でない場合に発生します
    """
    def boundary(ya, yb, p):
        left = origin_series(eps, p[0])
        return np.array([ya[0]-left[0], ya[1]-left[1],
                         xmax*yb[1]+3*yb[0]])

    x = np.geomspace(eps, xmax, 600)
    u = old_approximation(x)
    t = (x/5.2415)**(3/3.886)
    v = -3*u*t/(x*(1+t))
    sol = solve_bvp(rhs, boundary, x, np.vstack([u, v]), p=[-1.588],
                    tol=tol, bc_tol=min(tol, 1e-10), max_nodes=50000,
                    verbose=verbose)
    if not sol.success:
        raise RuntimeError('BVP did not converge: '+sol.message)
    check = sol.sol(np.geomspace(eps, xmax, 5000))
    if not np.all(np.isfinite(check)) or np.any(check[0] <= 0):
        raise RuntimeError('Nonpositive or nonfinite solution: change domain/tolerance.')
    if np.any(check[1] > 1e-10):
        raise RuntimeError('Solution is not monotonically decreasing.')
    return sol


def shoot(eps, xmax, b):
    """
    概要:
        Thomas-Fermi方程式を初期値問題として解き、軌道を探索します。
    詳細説明:
        遮蔽関数がゼロと交差するか、または値が2に達した時点で計算を停止するイベント関数を設定して積分を行います。
    引数:
        :param eps: 原点側の開始位置
        :type eps: float
        :param xmax: 遠方側の境界位置
        :type xmax: float
        :param b: 原点での傾きの試行値
        :type b: float
    戻り値:
        :returns: 初期値問題の解を格納したオブジェクト
        :rtype: scipy.optimize.OptimizeResult
    """
    def zero(x, y):
        return y[0]
    def large(x, y):
        return y[0]-2
    zero.terminal, zero.direction = True, -1
    large.terminal, large.direction = True, 1
    return solve_ivp(rhs, (eps, xmax), origin_series(eps, b),
                     method='DOP853', rtol=1e-10, atol=1e-12,
                     max_step=0.1, events=(zero, large), dense_output=True)


def main(argv=None):
    """
    概要:
        コマンドライン引数を解析し、計算と結果の保存を実行します。
    詳細説明:
        引数に基づいて境界値問題を解き、計算結果をCSVファイルとして保存し、プロットを画像ファイルとして出力します。
    引数:
        :param argv: コマンドライン引数のリスト
        :type argv: list
    戻り値:
        :returns: なし
        :rtype: None
    """
    ap = argparse.ArgumentParser(description=__doc__,
                                 formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument('--xmax', type=float, default=200., help='遠方境界 (default: 200)')
    ap.add_argument('--eps', type=float, default=1e-6, help='原点側開始位置')
    ap.add_argument('--tol', type=float, default=1e-7, help='BVP残差許容値')
    ap.add_argument('--points', type=int, default=3001, help='CSV・描画点数（対数格子）')
    ap.add_argument('--prefix', default='thomas_fermi', help='出力名の接頭辞')
    ap.add_argument('--shooting', action='store_true', help='初期傾き依存性の図を追加')
    ap.add_argument('--delta-b', type=float, default=1e-4, help='shootingでの傾きの変化量')
    ap.add_argument('--check-domain', action='store_true', help='xmaxを2倍にして比較')
    ap.add_argument('--no-show', action='store_true', help='図を保存するだけで表示しない')
    ap.add_argument('--verbose', action='store_true', help='BVP反復ログを表示')
    args = ap.parse_args(argv)
    if not (np.isfinite(args.eps) and 0 < args.eps <= 1e-2):
        ap.error('eps は 0 < eps <= 0.01 にしてください。')
    if not (np.isfinite(args.xmax) and args.xmax >= 10):
        ap.error('xmax は有限値で10以上にしてください。')
    if not (np.isfinite(args.tol) and 1e-12 <= args.tol <= 1e-2):
        ap.error('tol は 1e-12～1e-2 にしてください。')
    if args.points < 100 or not (np.isfinite(args.delta_b) and args.delta_b > 0):
        ap.error('points >= 100, delta-b > 0 にしてください。')

    sol = solve_tf(args.eps, args.xmax, args.tol, 2 if args.verbose else 0)
    b = float(sol.p[0])
    x = np.r_[0., np.geomspace(args.eps, args.xmax, args.points-1)]
    u, v = np.column_stack(([1., b], sol.sol(x[1:])))
    near = origin_series(x, b)[0]
    old = old_approximation(x)
    far = np.full_like(x, np.nan)
    far[1:] = 144/x[1:]**3
    # 微分した補間解とODE右辺の差。原点ではphi''が発散するためNaN。
    residual = np.full_like(x, np.nan)
    residual[1:] = sol.sol(x[1:], 1)[1] - u[1:]**1.5/np.sqrt(x[1:])
    print('Thomas-Fermi neutral atom: dimensionless x and phi')
    print(f"B = phi'(0)       : {b:.12f}")
    print(f'BVP iterations   : {sol.niter}; mesh nodes: {len(sol.x)}')
    print(f'Max RMS residual : {max(sol.rms_residuals):.3e}')
    print(f'Outer BC residual: {args.xmax*v[-1]+3*u[-1]:.3e}')
    print(f'xmax^3 phi / 144 : {args.xmax**3*u[-1]/144:.8f} (asymptotic limit: 1)')
    print('Finite-domain boundary approximation: use --check-domain to assess it.')
    if args.check_domain:
        larger = solve_tf(args.eps, 2*args.xmax, args.tol)
        relative = np.abs(larger.sol(x[1:])[0]-u[1:])/larger.sol(x[1:])[0]
        inner = x[1:] <= min(10., args.xmax/2)
        print(f'Domain doubled: B = {larger.p[0]:.12f}, delta B = {larger.p[0]-b:+.3e}')
        print(f'Max relative phi change (x <= {min(10., args.xmax/2):g}): {max(relative[inner]):.3e}')
        print(f'Max relative phi change (whole original domain): {max(relative):.3e}')

    out = Path(args.prefix)
    out.parent.mkdir(parents=True, exist_ok=True)
    csv_path, png_path = Path(str(out)+'.csv'), Path(str(out)+'.png')
    np.savetxt(csv_path, np.column_stack((x, u, v, near, old, far, residual)),
               delimiter=',', header='x,phi,dphi_dx,origin_series,old_approximation,144_over_x3,ode_residual',
               comments='', fmt='%.12e')
    import matplotlib
    if args.no_show:
        matplotlib.use('Agg')
    import matplotlib.pyplot as plt
    fig, axes = plt.subplots(2, 2, figsize=(12, 8), constrained_layout=True)
    ax = axes[0, 0]
    ax.plot(x, u, label='BVP solution', lw=2)
    mask = x <= 0.5
    ax.plot(x[mask], near[mask], '--', label='Origin series (x <= 0.5)')
    ax.plot(x, old, ':', label='Old Perl approximation')
    ax.set(xlim=(0, 5), ylim=(0, 1.05), ylabel='Screening function phi')
    ax.legend()
    ax = axes[0, 1]
    ax.loglog(x[1:], u[1:], label='BVP solution')
    mask = x >= 10
    ax.loglog(x[mask], far[mask], '--', label='144 / x^3 (far limit)')
    ax.loglog(x[1:], old[1:], ':', label='Old Perl approximation')
    ax.set(xlim=(1e-2, args.xmax), ylim=(min(u[-1]/2, 1e-4), 2), ylabel='Screening function phi')
    ax.legend()
    ax = axes[1, 0]
    ax.semilogx(x[1:], v[1:])
    ax.set(ylabel="Slope dphi/dx", title=f"Origin slope B = {b:.9f}")
    ax = axes[1, 1]
    if args.shooting:
        ax.plot(x, u, 'k--', label='BVP reference', lw=2)
        for shift in (-args.delta_b, 0., args.delta_b):
            ivp = shoot(args.eps, min(args.xmax, 30), b+shift)
            label = f'B {shift:+.1e}' if shift else 'B (outward IVP)'
            ax.plot(ivp.t, ivp.y[0], label=label)
            print(f'Shooting delta B={shift:+.2e}: x_end={ivp.t[-1]:.6g}; {ivp.message}')
        ax.set(xlim=(0, min(args.xmax, 30)), ylim=(0, 1.1), ylabel='phi', title='Sensitivity to initial slope')
        ax.legend(fontsize=8)
    else:
        ax.semilogx(x[1:], (old[1:]-u[1:])/u[1:]*100)
        ax.axhline(0, color='gray', lw=0.8)
        ax.set(ylabel='Relative difference (%)', title='Old approximation vs BVP')
    for ax in axes.flat:
        ax.set_xlabel('Dimensionless distance x')
        ax.grid(True, alpha=0.25)
    fig.suptitle('Thomas-Fermi equation: boundary conditions determine the solution')
    fig.savefig(png_path, dpi=160)
    print(f'Saved: {csv_path}\nSaved: {png_path}')
    if not args.no_show:
        plt.show()
    plt.close(fig)


if __name__ == '__main__':
    try:
        main()
    except (RuntimeError, OSError) as exc:
        print(f'Error: {exc}', file=sys.stderr)
        sys.exit(1)