#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
概要:
    1次元調和ポテンシャルにおける厳密軌道解とThomas-Fermi近似の比較教材です。

準備:
    python -m pip install numpy scipy matplotlib

実行:
    python ho_thomas_fermi.py
    python ho_thomas_fermi.py --N 1
    python ho_thomas_fermi.py --N 20 --check
    python ho_thomas_fermi.py --N 8 --no-show --prefix results/ho8

モデルと単位:
    非相互作用、温度ゼロ、スピン自由度なし、または完全スピン偏極を仮定します。
    1軌道に1粒子が入り、Nは粒子数であると同時に占有軌道数となります。
    共通の調和ポテンシャルに閉じ込めたフェルミ粒子で、多電子相互作用はありません。
    長さ a=sqrt(hbar/(m*omega))、エネルギー hbar*omega を単位とします。
    以下の x は x_phys/a、V=x^2/2、密度の単位は1/aです。
    K(x)とU(x) はエネルギー密度 hbar*omega/a、Vは一粒子のエネルギーです。
    軌道phiの単位はa^(-1/2)であり、表示する軌道番号はn=1..Nです。
    通常の振動子量子数j=n-1、epsilon_n=n-1/2となり、基底状態はn=1です。

厳密解:
    phi_1=pi^(-1/4) exp(-x^2/2), phi_2=sqrt(2)x phi_1と定義します。
    規格化したHermite関数の漸化式から高階軌道を作ります。
    n_exact=sum(phi_n^2), K_exact=1/2 sum((dphi_n/dx)^2)です。
    微分は隣接軌道による解析的な漸化式で計算し、数値差分ではありません。
    U_exact=V*n_exactとなり、運動エネルギー密度は正定値の定義を採用します。
    別定義 -1/2 sum(phi*phi'') は局所的には異なりますが積分値は同じです。

TF近似:
    T_TF(n)=(pi^2/6) integral n^3 dxと表されます。
    E_TF(n)=T_TF(n)+integral V*n dx を粒子数固定で最小化すると、
    n_TF=sqrt(2(mu-V))/pi ただし mu>V であり、それ以外ゼロとなります。
    規格化からmu=N、転回点x_TF=+-sqrt(2N)となり、K_TF=(pi^2/6)*n_TF^3です。
    この特別な系ではT=U=N^2/4、E=N^2/2が厳密解とTFで一致します。
    しかし局所密度は異なります。TF汎関数に厳密密度を代入する3番目の比較
    K_TF_on_exact=(pi^2/6)*n_exact^3 は、汎関数の近似誤差を示します。
    この3番目の計算は最小化して得た状態ではなく、汎関数の評価実験です。

出力:
    PREFIX_comparison.png はV、K、n、U、エネルギー比較、密度差の図です。
    PREFIX_orbitals_01.png などはn=1..N全軌道を描画し、1ページ12軌道です。
    PREFIX_profiles.csv は密度とエネルギー密度の共通x格子データです。
    PREFIX_orbitals.csv は全軌道とその微分のデータです。
    PREFIX_energies.csv と PREFIX_summary.txt は積分値と説明を記録します。
    同名の出力は上書きされます。図は英語表記で日本語フォントに依存しません。
    CSVのTF積分は格子上のSimpson法なので転回点の平方根形による誤差があります。
    エネルギー表のTF値は転回点で区切った適応積分を使用します。
    --checkオプションで格子細分化と積分範囲拡大を独立に検証できます。
"""
from __future__ import annotations
import argparse
import csv
from pathlib import Path
import sys
import numpy as np
from scipy.integrate import simpson, quad


def orbitals(x, number):
    """
    概要:
        占有軌道指定本数と、微分に必要な次の軌道を漸化式で作成します。

    詳細説明:
        規格化したHermite関数の漸化式を用いて、基底状態から指定された数の
        波動関数とその1階導関数を計算します。微分は解析的な漸化式で計算します。

    引数:
        :param x: 空間座標の1次元配列
        :type x: numpy.ndarray
        :param number: 計算する軌道の数
        :type number: int

    戻り値:
        :returns: 軌道の配列と導関数の配列のタプル
        :rtype: tuple
    """
    phi = np.empty((number+1, len(x)))
    phi[0] = np.pi**(-0.25)*np.exp(-x*x/2)
    phi[1] = np.sqrt(2)*x*phi[0]
    for j in range(1, number):
        phi[j+1] = np.sqrt(2/(j+1))*x*phi[j]-np.sqrt(j/(j+1))*phi[j-1]
    derivative = np.empty((number, len(x)))
    for j in range(number):
        left = np.sqrt(j/2)*phi[j-1] if j else 0.
        derivative[j] = left-np.sqrt((j+1)/2)*phi[j+1]
    return phi[:number], derivative


def calculate(number, xmax, points):
    """
    概要:
        厳密解およびTF近似によるエネルギーと密度を計算します。

    詳細説明:
        指定された軌道数、空間範囲、格子点数を用いて、波動関数、運動エネルギー、
        ポテンシャルエネルギーを計算し、TF近似との比較データを生成します。

    引数:
        :param number: 粒子数および占有軌道数
        :type number: int
        :param xmax: 空間座標の最大絶対値
        :type xmax: float
        :param points: 空間座標の格子点数
        :type points: int

    戻り値:
        :returns: 各種計算結果を格納した辞書
        :rtype: dict
    """
    x = np.linspace(-xmax, xmax, points)
    phi, derivative = orbitals(x, number)
    v = x*x/2
    density = np.sum(phi*phi, axis=0)
    kinetic = np.sum(derivative*derivative, axis=0)/2
    tf_density = np.sqrt(np.maximum(2*number-x*x, 0))/np.pi
    tf_kinetic = np.pi**2/6*tf_density**3
    on_exact = np.pi**2/6*density**3
    potential = v*density
    tf_potential = v*tf_density
    integrate = lambda a: float(simpson(a, x=x))
    # TFの非解析的な端点を積分範囲の端に置き、格子の配置に依存させない。
    edge = np.sqrt(2*number)
    def ntf(t):
        return np.sqrt(max(2*number-t*t, 0))/np.pi
    tf_n = 2*quad(ntf, 0, edge, epsabs=1e-10, epsrel=1e-11)[0]
    tf_t = 2*quad(lambda t: np.pi**2/6*ntf(t)**3, 0, edge, epsabs=1e-10, epsrel=1e-11)[0]
    tf_u = 2*quad(lambda t: t*t/2*ntf(t), 0, edge, epsabs=1e-10, epsrel=1e-11)[0]
    rows = []
    for name, norm, t, u in [
        ('Exact orbitals', integrate(density), integrate(kinetic), integrate(potential)),
        ('TF minimum', tf_n, tf_t, tf_u),
        ('TF on exact density', integrate(density), integrate(on_exact), integrate(potential)),
        ('Analytical reference', float(number), number**2/4, number**2/4)]:
        rows.append((name, norm, t, u, t+u))
    return dict(x=x, phi=phi, derivative=derivative, v=v, density=density,
                kinetic=kinetic, tf_density=tf_density, tf_kinetic=tf_kinetic,
                on_exact=on_exact, potential=potential, tf_potential=tf_potential,
                rows=rows, tf_grid_norm=integrate(tf_density),
                norms=simpson(phi*phi, x=x, axis=1))


def save_and_plot(data, args):
    """
    概要:
        計算結果をCSVファイルとして保存し、比較グラフを描画します。

    詳細説明:
        解析で得られた密度やエネルギーのプロファイル、全占有軌道の形状をプロットし、
        指定された接頭辞を持つファイルに出力します。

    引数:
        :param data: calculate関数から返された計算結果の辞書
        :type data: dict
        :param args: コマンドライン引数を格納した名前空間オブジェクト
        :type args: argparse.Namespace

    戻り値:
        :returns: なし
        :rtype: None
    """
    import matplotlib
    if args.no_show:
        matplotlib.use('Agg')
    import matplotlib.pyplot as plt
    prefix = Path(args.prefix)
    prefix.parent.mkdir(parents=True, exist_ok=True)
    x = data['x']
    names = ['x_over_a', 'V', 'n_exact', 'n_TF', 'K_exact', 'K_TF',
             'K_TF_on_exact_density', 'U_exact', 'U_TF']
    keys = ['x', 'v', 'density', 'tf_density', 'kinetic', 'tf_kinetic',
            'on_exact', 'potential', 'tf_potential']
    np.savetxt(str(prefix)+'_profiles.csv', np.column_stack([data[k] for k in keys]),
               delimiter=',', header=','.join(names), comments='', fmt='%.12e')
    names = ['x_over_a']+[f'phi_{n}' for n in range(1,args.N+1)]+[f'dphi_{n}_dx' for n in range(1,args.N+1)]
    np.savetxt(str(prefix)+'_orbitals.csv', np.column_stack([x, data['phi'].T, data['derivative'].T]),
               delimiter=',', header=','.join(names), comments='', fmt='%.12e')
    with open(str(prefix)+'_energies.csv', 'w', newline='', encoding='utf-8') as f:
        writer = csv.writer(f)
        writer.writerow(['method','particle_number','T_over_hw','U_over_hw','E_over_hw'])
        writer.writerows(data['rows'])
    fig, axes = plt.subplots(2, 3, figsize=(15, 8), constrained_layout=True)
    ax = axes[0,0]
    ax.plot(x, data['v'], color='black', label='V(x) = x^2/2')
    ax.axhline(args.N, color='tab:orange', ls='--', label=f'TF chemical potential = {args.N}')
    ax.set(title='External potential (same in both models)', ylabel='V / (hbar omega)')
    ax.legend(fontsize=8)
    for ax, k1, k2, title, ylabel in [
        (axes[0,1], 'kinetic','tf_kinetic','Kinetic energy density (positive definition)','K / (hbar omega / a)'),
        (axes[0,2], 'density','tf_density','Particle density','n / (1/a)'),
        (axes[1,0], 'potential','tf_potential','Potential energy density U(x) = V(x)n(x)','U / (hbar omega / a)')]:
        ax.plot(x, data[k1], label='Exact orbitals', lw=1.8)
        ax.plot(x, data[k2], '--', label='TF minimum', lw=1.7)
        ax.set(title=title, ylabel=ylabel)
        if k1 == 'kinetic':
            ax.plot(x, data['on_exact'], ':', color='tab:green', label='TF functional on exact density')
        ax.legend(fontsize=8)
    ax = axes[1,1]
    for i, row in enumerate(data['rows'][:3]):
        ax.bar(np.arange(3)+(i-1)*.25, row[2:], width=.25, label=row[0])
    ax.set_xticks(np.arange(3), ['T', 'U', 'E = T + U'])
    ax.set(title='Integrated energies', ylabel='Energy / (hbar omega)')
    ax.legend(fontsize=8)
    ax = axes[1,2]
    ax.plot(x, data['density']-data['tf_density'], color='tab:purple')
    ax.axhline(0, color='gray', lw=.7)
    ax.set(title='Density difference: exact - TF', ylabel='Density difference / (1/a)')
    for ax in axes.flat:
        ax.grid(alpha=.2)
        if ax is not axes[1,1]:
            ax.set_xlabel('x / a')
            view = min(x[-1], np.sqrt(2*args.N)+3)
            ax.set_xlim(-view, view)
            if ax is axes[0,0]:
                ax.set_ylim(0, view*view/2)
            for edge in (-np.sqrt(2*args.N), np.sqrt(2*args.N)):
                ax.axvline(edge, color='gray', ls=':', lw=.7)
    fig.suptitle(f'1D harmonic trap: N={args.N} noninteracting spinless fermions, T=0', fontsize=14)
    fig.savefig(str(prefix)+'_comparison.png', dpi=160)
    if args.no_show:
        plt.close(fig)
    # 全占有軌道を省略せず表示する。12本ごとに別ページ。
    for start in range(0, args.N, 12):
        count = min(12, args.N-start)
        columns = min(3, count)
        rows = (count+columns-1)//columns
        fig, axes = plt.subplots(rows, columns, figsize=(5*columns, 2.6*rows),
                                 squeeze=False, constrained_layout=True)
        for ax in axes.flat[count:]:
            ax.set_visible(False)
        for offset, ax in enumerate(axes.flat[:count]):
            j = start+offset
            ax.plot(x, data['phi'][j], color=f'C{j%10}')
            ax.axhline(0, color='gray', lw=.6)
            ax.set(title=f'n={j+1} (j={j}), energy={j+0.5:g}, nodes={j}',
                   xlabel='x / a', ylabel='phi_n / a^(-1/2)')
            ax.set_xlim(-min(x[-1], np.sqrt(2*j+1)+3), min(x[-1], np.sqrt(2*j+1)+3))
            ax.grid(alpha=.2)
        fig.suptitle('Occupied orbitals: one particle in each orbital; integral |phi_n|^2 dx = 1')
        fig.savefig(str(prefix)+f'_orbitals_{start//12+1:02d}.png', dpi=150)
        if args.no_show:
            plt.close(fig)
    if not args.no_show:
        plt.show()
        plt.close('all')


def main(argv=None):
    """
    概要:
        1次元調和ポテンシャルにおける厳密解とTF近似の比較を実行します。

    詳細説明:
        コマンドライン引数を解析し、計算処理、結果の検証、ファイル保存、
        グラフ描画の一連の処理を順に実行します。

    引数:
        :param argv: コマンドライン引数のリスト
        :type argv: list

    戻り値:
        :returns: なし
        :rtype: None
    """
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument('--N', '--n', type=int, default=6, help='粒子数/占有軌道数、1..100 (default:6)')
    ap.add_argument('--points', type=int, default=6001, help='描画・積分用格子点数')
    ap.add_argument('--xmax', type=float, help='x/aの最大絶対値。既定sqrt(2N)+8')
    ap.add_argument('--prefix', default='ho_tf', help='出力名の接頭辞')
    ap.add_argument('--check', action='store_true', help='格子・範囲への依存性を検証')
    ap.add_argument('--no-show', action='store_true', help='図を保存して終了')
    args = ap.parse_args(argv)
    if not 1 <= args.N <= 100:
        ap.error('N must be between 1 and 100.')
    xmax = args.xmax if args.xmax is not None else np.sqrt(2*args.N)+8
    if not np.isfinite(xmax) or xmax <= np.sqrt(2*args.N):
        ap.error('xmax must exceed the TF turning point sqrt(2N).')
    if not 501 <= args.points <= 100001:
        ap.error('points must be between 501 and 100001.')
    data = calculate(args.N, xmax, args.points)
    lines = [f'1D harmonic trap, N={args.N}, spinless, noninteracting, zero temperature',
             'Length unit: a=sqrt(hbar/m/omega); energy unit: hbar*omega',
             'Orbital labels n=1..N; oscillator quantum number j=n-1',
             'K(x) uses the positive definition: 0.5 sum |dphi/dx|^2', '',
             f'{"Method":24s} {"Integral n":>14s} {"T":>16s} {"U":>16s} {"E=T+U":>16s}']
    for name, norm, t, u, e in data['rows']:
        lines.append(f'{name:24s} {norm:14.9f} {t:16.9f} {u:16.9f} {e:16.9f}')
    norm_error = max(abs(data['norms']-1))
    lines += ['', f'Max orbital normalization error: {norm_error:.3e}',
              f'TF particle number on plotting grid (Simpson): {data["tf_grid_norm"]:.9f}',
              'TF table values use adaptive integration inside the turning points.',
              'Exact table values use sampled orbitals (Simpson integration).',
              'TF and exact integrated T,U,E coincide for this special harmonic model.',
              'TF on exact density is a functional test, not a separately minimized state.']
    if norm_error > 1e-6:
        lines.append('WARNING: appreciable normalization error; enlarge xmax or increase points.')
    if args.check:
        for label, extent, points in [('Half grid spacing', xmax, 2*args.points-1),
                                      ('Larger domain', xmax+4, int((args.points-1)*(xmax+4)/xmax)+1)]:
            other = calculate(args.N, extent, points)
            delta = np.array(other['rows'][0][2:])-np.array(data['rows'][0][2:])
            delta_tf = other['rows'][2][2]-data['rows'][2][2]
            lines.append(f'{label}: delta(T,U,E)={delta}; delta T_TF[n_exact]={delta_tf:+.3e}')
    text = '\n'.join(lines)+'\n'
    print(text)
    prefix = Path(args.prefix)
    prefix.parent.mkdir(parents=True, exist_ok=True)
    Path(str(prefix)+'_summary.txt').write_text(text, encoding='utf-8')
    save_and_plot(data, args)
    print(f'Saved: {prefix}_comparison.png, {prefix}_orbitals_*.png, CSV files and summary.txt')


if __name__ == '__main__':
    try:
        main()
    except (ValueError, OSError) as exc:
        print(f'Error: {exc}', file=sys.stderr)
        sys.exit(1)