#!/usr/bin/env python3
"""
概要:
    He 1s^2 Hartree SCF: Numerov inward/outward matching (atomic units)

詳細説明:
    u=r R, integral(u^2 dr)=1。p=u^2 は1電子の動径確率密度です。
    全電子の動径密度は2p、3次元密度は2p/(4*pi*r^2)となります。
    他方の電子だけからVHを作るため、自己相互作用を含めません。
    このHe 1s^2の制限Hartree方程式は閉殻HFと一致します。
    iter=1は初期密度で固定したポテンシャルを1回解くone-shot処理です。
    SCF収束とグリッド/rmax収束は別であり、tolを小さくしても離散化誤差は残ります。
    密度残差はmixing前のp_out-p_inです。小さいmixingによる偽収束を防ぎます。
    未収束時には E=2*epsilon-J_out は使えません。
    E = 2*(uに対するT-2/rの期待値) + J_out を出力軌道について評価します。
    依存ライブラリは numpy scipy matplotlib です。
    実行例は python he_hartree_numerov.py --iter 100 --mixing 0.3 --tol 1e-8 などです。
"""

import argparse
import csv
import numpy as np
from scipy.integrate import simpson, cumulative_trapezoid
from scipy.linalg import eigh_tridiagonal
from scipy.optimize import brentq

REFERENCE = -2.861680  # rounded HF reference, Ha; not an exact correlated energy


def integral(y, r):
    """
    概要:
        シンプソン法を用いて関数を数値積分します。

    引数:
        :param y: 被積分関数の値の配列。
        :type y: numpy.ndarray
        :param r: 積分変数の配列。
        :type r: numpy.ndarray

    戻り値:
        :returns: 積分結果。
        :rtype: float
    """
    return float(simpson(y, x=r))


def normalize(u, r):
    """
    概要:
        波動関数を規格化します。

    詳細説明:
        uの二乗積分が1になるように定数倍します。

    引数:
        :param u: 波動関数の配列。
        :type u: numpy.ndarray
        :param r: 径方向のグリッド配列。
        :type r: numpy.ndarray

    戻り値:
        :returns: 規格化された波動関数の配列。
        :rtype: numpy.ndarray
    """
    return u / np.sqrt(integral(u*u, r))


def hartree(r, p):
    """
    概要:
        Hartreeポテンシャルを計算します。

    詳細説明:
        VH(r)=Q(<r)/r + integral_r^infinity p(s)/s ds で計算されます。pは積分して1になる密度です。

    引数:
        :param r: 径方向のグリッド配列。
        :type r: numpy.ndarray
        :param p: 確率密度の配列。
        :type p: numpy.ndarray

    戻り値:
        :returns: 計算されたHartreeポテンシャルの配列。
        :rtype: numpy.ndarray
    """
    f = np.zeros_like(r)
    f[1:] = p[1:] / r[1:]
    inside = cumulative_trapezoid(p, r, initial=0)
    outside = -cumulative_trapezoid(f[::-1], r[::-1], initial=0)[::-1]
    vh = outside.copy()
    vh[1:] += inside[1:] / r[1:]
    return vh


def numerov_branch(q, h, y0, y1):
    """
    概要:
        Numerov法による微分方程式の片側積分を実行します。

    詳細説明:
        y''=q*y を解きます。qは選択した積分方向に従って並べられていると仮定します。

    引数:
        :param q: 方程式の係数配列。
        :type q: numpy.ndarray
        :param h: グリッドの間隔。
        :type h: float
        :param y0: 最初の点の初期値。
        :type y0: float
        :param y1: 2番目の点の初期値。
        :type y1: float

    戻り値:
        :returns: Numerov法で積分された配列。
        :rtype: numpy.ndarray
    """
    y = np.empty(len(q))
    y[:2] = y0, y1
    a = h*h/12
    for i in range(1, len(q)-1):
        y[i+1] = ((2+10*a*q[i])*y[i] - (1-a*q[i-1])*y[i-1]) / (1-a*q[i+1])
        if abs(y[i+1]) > 1e100:
            y[:i+2] *= 1e-100
    return y


def solve_numerov(r, vh):
    """
    概要:
        Numerov法を用いて基底状態を解きます。

    詳細説明:
        粗い有限差分固有値は根の探索区間の目安だけに用います。
        最終固有値と軌道は両側Numerov積分と接続条件で決定します。

    引数:
        :param r: 径方向のグリッド配列。
        :type r: numpy.ndarray
        :param vh: Hartreeポテンシャルの配列。
        :type vh: numpy.ndarray

    戻り値:
        :returns: 固有値、波動関数の配列、ミスマッチの絶対値からなるタプル。
        :rtype: tuple

    例外:
        :raises RuntimeError: 根の探索に失敗した場合、または励起状態の根に遭遇した場合。
    """
    h = r[1]
    v = np.zeros_like(r)
    v[1:] = -2/r[1:] + vh[1:]
    m = int(np.clip(round(1.2/h), 4, len(r)-5))

    def branches(e):
        """
        概要:
            指定したエネルギーに対する外向きと内向きの波動関数を計算します。
        
        引数:
            :param e: 試行エネルギー。
            :type e: float
        
        戻り値:
            :returns: 外向きと内向きの波動関数配列のタプル。
            :rtype: tuple
        """
        # 原点の正則級数 u=r*(1-Z*r+b*r^2+c*r^3)。VH'(0)=0。
        z = 2.0
        b = (z*z + vh[0]-e)/3
        c = (-z*b-z*(vh[0]-e))/6
        seed = lambda x: x*(1-z*x+b*x*x+c*x**3)
        q = 2*(v-e)
        out = numerov_branch(q[1:m+3], h, seed(h), seed(2*h))
        # 遠方はV=-1/r。u ~ exp(-k*r)*r^(1/k)。比を使いunderflow回避。
        k = np.sqrt(-2*e)
        ratio = np.exp(k*h + np.log(r[-2]/r[-1])/k)
        inn = numerov_branch(q[m-2:][::-1], h, 1.0, ratio)[::-1]
        out /= np.max(np.abs(out))
        inn /= np.max(np.abs(inn))
        return out, inn

    def mismatch(e):
        """
        概要:
            接続点での波動関数の微分の不一致を計算します。
            
        引数:
            :param e: 試行エネルギー。
            :type e: float
            
        戻り値:
            :returns: 接続条件のミスマッチ量。
            :rtype: float
        """
        a, b = branches(e)
        # 接続点中心の5点微分。配列aではm-1、bでは2が接続点。
        i = m-1
        da = (a[i-2]-8*a[i-1]+8*a[i+1]-a[i+2])/(12*h)
        db = (b[0]-8*b[1]+8*b[3]-b[4])/(12*h)
        return da*b[2]-a[i]*db

    guess = eigh_tridiagonal(1/h**2+v[1:-1],
                            np.full(len(r)-3, -0.5/h**2),
                            select='i', select_range=(0, 0),
                            eigvals_only=True)[0]
    width = 0.02
    for _ in range(8):
        lo, hi = max(-2.1, guess-width), min(-1e-5, guess+width)
        if mismatch(lo)*mismatch(hi) < 0:
            break
        width *= 1.7
    else:
        raise RuntimeError('Cannot bracket ground state; refine grid / enlarge rmax.')
    e = brentq(mismatch, lo, hi, xtol=2e-12)
    a, b = branches(e)
    u = np.zeros_like(r)
    u[1:m+1] = a[:m]
    u[m+1:] = b[3:] * a[m-1]/b[2]
    u = normalize(u, r)
    significant = u[np.abs(u) > 1e-8*np.max(np.abs(u))]
    if np.any(significant[:-1]*significant[1:] < 0):
        raise RuntimeError('Excited-state root encountered (radial node).')
    if u[1] < 0:
        u = -u
    return e, u, abs(mismatch(e))


def energy(r, u):
    """
    概要:
        変分全エネルギーを計算します。

    詳細説明:
        自己無撞着になる前の状態でも有効な全エネルギーを計算します。

    引数:
        :param r: 径方向のグリッド配列。
        :type r: numpy.ndarray
        :param u: 波動関数の配列。
        :type u: numpy.ndarray

    戻り値:
        :returns: 全エネルギー、運動エネルギー、原子核引力エネルギー、クーロン反発エネルギーのタプル。
        :rtype: tuple
    """
    h = r[1]
    du = np.gradient(u, h, edge_order=2)
    du[2:-2] = (u[:-4]-8*u[1:-3]+8*u[3:-1]-u[4:])/(12*h)
    # 原点の片側4次微分
    du[0] = (-25*u[0]+48*u[1]-36*u[2]+16*u[3]-3*u[4])/(12*h)
    du[1] = (-3*u[0]-10*u[1]+18*u[2]-6*u[3]+u[4])/(12*h)
    p = u*u
    t = 0.5*integral(du*du, r)
    vn = np.zeros_like(r)
    vn[1:] = -2*p[1:]/r[1:]
    nuclear = integral(vn, r)
    j = integral(p*hartree(r, p), r)
    return 2*(t+nuclear)+j, t, nuclear, j


def references():
    """
    概要:
        参考文献の情報を標準出力に表示します。

    戻り値:
        :returns: なし
        :rtype: None
    """
    print('\nReference (nonrelativistic, infinite nuclear mass, He 1s^2):')
    print('  Restricted Hartree = closed-shell HF: E_total ~ -2.86168 Ha')
    print('  Correlated benchmark (NOT the SCF target): ~ -2.90372 Ha')
    print('  A. W. Weiss, Oscillator Strengths for the Helium Isoelectronic Sequence,')
    print('  J. Res. Natl. Bur. Stand. A Phys. Chem. 71A, 163-168 (1967), Table 1.')
    print('  https://doi.org/10.6028/jres.071A.023')
    print('  https://nvlpubs.nist.gov/nistpubs/jres/71A/jresv71An2p163_A1b.pdf')


def main():
    """
    概要:
        コマンドライン引数を解析し、HeのHartree-Fock計算を実行します。

    詳細説明:
        設定されたパラメータに基づいて自己無撞着場のイテレーションを行い、
        結果をコンソールに出力します。オプションでCSVやグラフ出力も行います。

    戻り値:
        :returns: 終了ステータスコード。成功時は0、エラー時は0以外。
        :rtype: int
    """
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument('--iter', type=int, default=1, help='maximum solves (default: 1, one-shot)')
    ap.add_argument('--mixing', type=float, default=0.3, help='new-density fraction, (0,1]')
    ap.add_argument('--tol', type=float, default=1e-8, help='density L1 tolerance; default energy tolerance in Ha')
    ap.add_argument('--tol-energy', type=float, help='energy tolerance in Ha (overrides --tol)')
    ap.add_argument('--ngrid', type=int, default=6000, help='radial intervals')
    ap.add_argument('--rmax', type=float, default=30.0, help='outer radius in Bohr')
    ap.add_argument('--zeta', type=float, default=2.0, help='initial hydrogenic exponent')
    ap.add_argument('--no-plot', action='store_true')
    ap.add_argument('--savefig', help='optional figure filename')
    ap.add_argument('--csv', help='optional history CSV filename')
    args = ap.parse_args()
    etol = args.tol if args.tol_energy is None else args.tol_energy
    if args.iter < 1 or not 0 < args.mixing <= 1 or args.ngrid < 200 or args.rmax < 10 or args.zeta <= 0 or args.tol <= 0 or etol <= 0:
        ap.error('Require iter>=1, 0<mixing<=1, ngrid>=200, rmax>=10, zeta>0, tolerances>0.')
    r = np.linspace(0, args.rmax, args.ngrid+1)
    if r[1] > 0.05:
        ap.error('Grid too coarse: require rmax/ngrid <= 0.05 Bohr.')
    u0 = normalize(r*np.exp(-args.zeta*r), r)
    p = u0*u0
    previous = energy(r, u0)[0]
    hist = []
    snapshots = []
    converged = False
    print('He 1s^2 Hartree / two-sided Numerov; atomic units')
    print(f'h={r[1]:.6g} Bohr, rmax={args.rmax:g}, mixing={args.mixing:g}')
    print(f'tol_density={args.tol:g}; tol_energy={etol:g} Ha')
    print(f'Initial trial energy: {previous:.10f} Ha')
    print(' iter   N_electron     epsilon[Ha]      E_total[Ha]      dE[Ha]       residual_L1')
    try:
        for it in range(1, args.iter+1):
            vh = hartree(r, p)
            eps, u, match = solve_numerov(r, vh)
            pout = u*u
            total, t, vn, j = energy(r, u)
            delta = total-previous
            residual = integral(np.abs(pout-p), r)
            ne = 2*integral(pout, r)
            # 独立チェック: h_expect=eps-<VH_in>; 未収束でも使える。
            identity = 2*eps-2*integral(pout*vh, r)+j
            hist.append((it, ne, eps, total, delta, residual, match, total-identity))
            snapshots.append(pout.copy())
            print(f'{it:5d} {ne:12.8f} {eps:16.10f} {total:16.10f} {delta:+12.3e} {residual:14.3e}', flush=True)
            if abs(delta) < etol and residual < args.tol:
                converged = True
                break
            p = (1-args.mixing)*p + args.mixing*pout
            previous = total
    except RuntimeError as exc:
        print(f'Numerov failure: {exc}')
        if not hist:
            references()
            return 2
    status = 'SCF CONVERGED' if converged else ('ONE-SHOT (not SCF converged)' if args.iter == 1 else 'NOT CONVERGED: last output retained')
    print('\n'+status)
    print(f'E_total - rounded HF reference = {total-REFERENCE:+.6e} Ha')
    print(f'T(two electrons)={2*t:.10f}; V_nuclear={2*vn:.10f}; J={j:.10f} Ha')
    print(f'Virial residual 2T+V = {4*t+2*vn+j:+.3e} Ha')
    print(f'Energy quadrature/identity discrepancy = {total-identity:+.3e} Ha')
    print('N_electron is checked AFTER normalization; it is not an SCF residual.')
    print('SCF tolerance does not bound grid/box error. Repeat with doubled ngrid and larger rmax.')
    references()
    if args.csv:
        with open(args.csv, 'w', newline='', encoding='utf-8') as stream:
            writer = csv.writer(stream)
            writer.writerow(('iteration','N_electron','epsilon_Ha','E_total_Ha','dE_Ha','density_residual_L1','matching_residual','energy_identity_error_Ha'))
            writer.writerows(hist)
    if not args.no_plot or args.savefig:
        import matplotlib.pyplot as plt
        fig, axes = plt.subplots(2, 2, figsize=(11, 8), constrained_layout=True)
        ax = axes[0, 0]
        ax.plot(r, 2*u0*u0, '--', label='initial')
        for idx in np.unique(np.linspace(0, len(snapshots)-1, min(6, len(snapshots))).astype(int)):
            ax.plot(r, 2*snapshots[idx], label=f'iter {idx+1}')
        ax.set(xlim=(0, 6), xlabel='r [Bohr]', ylabel='Radial electron density 2|u|^2')
        ax.legend()
        ax = axes[0, 1]
        ax.plot(r[1:], -2/r[1:], '--', label='nuclear')
        ax.plot(r, vh, label='Hartree input (last solve)')
        ax.plot(r[1:], -2/r[1:]+vh[1:], label='effective input')
        ax.set(xlim=(0, 6), ylim=(-5, 2.5), xlabel='r [Bohr]', ylabel='Potential [Ha]')
        ax.legend()
        data = np.array(hist)
        ax = axes[1, 0]
        ax.plot(np.r_[0, data[:, 0]], np.r_[energy(r, u0)[0], data[:, 3]], 'o-', label='total energy')
        ax.axhline(REFERENCE, ls='--', color='black', label='HF reference')
        ax.set(xlabel='Iteration', ylabel='E_total [Ha]')
        ax.legend()
        ax = axes[1, 1]
        ax.semilogy(data[:, 0], np.maximum(data[:, 5], 1e-16), 'o-', label='density L1')
        ax.semilogy(data[:, 0], np.maximum(np.abs(data[:, 4]), 1e-16), 's-', label='|dE| [Ha]')
        ax.set(xlabel='Iteration', ylabel='Residual (different units; see legend)')
        ax.legend()
        fig.suptitle(status)
        if args.savefig:
            fig.savefig(args.savefig, dpi=160)
        if not args.no_plot:
            plt.show()
        plt.close(fig)
    return 0


if __name__ == '__main__':
    raise SystemExit(main())