"""
概要:
    1s試行軌道によるHartree・HF・X-alpha/LDA交換のToyプログラムです。
詳細説明:
    modeにeを含めると全エネルギー、含めないと1s軌道エネルギーを表示します。
    既定は、1スピン軌道の分率占有数 0 <= Ne <= 1 に対するX-alpha/LDA交換です。
    hを加えると同じ軌道の厳密HF交換を使います。
"""

import sys
from math import exp, log, pi, sqrt

import numpy as np
from matplotlib import pyplot as plt
from scipy import integrate
from scipy.optimize import minimize_scalar


HartreeToeV = 27.211386245988
pi4 = 4.0 * pi
R1s0 = 1.0 / sqrt(pi)

# mode: d=基本量, k=ka掃引, n=Ne掃引, v=ka最適化, e=全エネルギー, g=グラフ
mode = 'k'
ELabel = 'E 1s'
XLabel = 'U(X-alpha)'

Z = 1.0
n, l, m = 1, 0, 0
ka = 1.0
Ne = 1.0
alpha = 2.0 / 3.0

Rmin = 0.0
Rmax = 20.0
nR = 2001
nmaxdiv = 80
epsR = 1.0e-4
eps = 1.0e-9
hparab = 0.01

Nearray = [1.0, 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1,
           0.07, 0.05, 0.04, 0.03, 0.02, 0.01, 1e-3, 1e-4, 1e-5, 1e-6]
kaarray = [0.5, 0.6, 0.65, 0.7, 0.8, 0.9, 0.95, 1.0, 1.05, 1.1, 1.2, 1.4]

tol = 1.0e-7
ka_bounds = (0.05, 2.5)


def pfloat(value):
    """
    概要:
        値を浮動小数点数に変換します。
    詳細説明:
        変換できない場合はNoneを返します。
    引数:
        :param value: 変換する値。
        :type value: any
    戻り値:
        :returns: 変換された浮動小数点数またはNone。
        :rtype: float or None
    """
    try:
        return float(value)
    except (TypeError, ValueError):
        return None


def pint(value):
    """
    概要:
        値を整数に変換します。
    詳細説明:
        変換できない場合はNoneを返します。
    引数:
        :param value: 変換する値。
        :type value: any
    戻り値:
        :returns: 変換された整数またはNone。
        :rtype: int or None
    """
    try:
        return int(value)
    except (TypeError, ValueError):
        return None


def getarg(position, defval=None):
    """
    概要:
        コマンドライン引数を文字列として取得します。
    引数:
        :param position: 引数のインデックス。
        :type position: int
        :param defval: 取得できなかった場合のデフォルト値。
        :type defval: any
    戻り値:
        :returns: 取得したコマンドライン引数またはデフォルト値。
        :rtype: str or any
    """
    try:
        return sys.argv[position]
    except IndexError:
        return defval


def getfloatarg(position, defval=None):
    """
    概要:
        コマンドライン引数を浮動小数点数として取得します。
    引数:
        :param position: 引数のインデックス。
        :type position: int
        :param defval: 取得できなかった場合のデフォルト値。
        :type defval: any
    戻り値:
        :returns: 取得した浮動小数点数またはデフォルト値。
        :rtype: float or any
    """
    value = pfloat(getarg(position, defval))
    return defval if value is None else value


def getintarg(position, defval=None):
    """
    概要:
        コマンドライン引数を整数として取得します。
    引数:
        :param position: 引数のインデックス。
        :type position: int
        :param defval: 取得できなかった場合のデフォルト値。
        :type defval: any
    戻り値:
        :returns: 取得した整数またはデフォルト値。
        :rtype: int or any
    """
    value = pint(getarg(position, defval))
    return defval if value is None else value


def usage(ka=ka, Z=Z, n=n, l=l, m=m):
    """
    概要:
        プログラムの使用方法を標準出力に表示します。
    引数:
        :param ka: 軌道のスケールパラメータ。
        :type ka: float
        :param Z: 原子番号。
        :type Z: float
        :param n: 主量子数。
        :type n: int
        :param l: 方位量子数。
        :type l: int
        :param m: 磁気量子数。
        :type m: int
    戻り値:
        :returns: なし
        :rtype: None
    """
    print(f"Usage: python {sys.argv[0]} mode Z ka Ne")
    print("  d: basic quantities and radial plots")
    print("  k: sweep ka")
    print("  n: sweep Ne")
    print("  v: optimize ka by total energy")
    print("  e: total energy (default: 1s orbital energy)")
    print("  h: use exact HF exchange (default: X-alpha/LDA exchange)")
    print("  g: plot graphs")
    print( "Note: this model assumes a single spin orbital with 0 <= Ne <= 1.")
    print(f"Example: python {sys.argv[0]} nvg {Z} {ka} {Ne}")
    print(f"Example: python {sys.argv[0]} nevg {Z} {ka} {Ne}")


def terminate(message=None):
    """
    概要:
        メッセージを表示してプログラムを終了します。
    引数:
        :param message: 終了前に表示するメッセージ文字列。
        :type message: str or None
    戻り値:
        :returns: なし
        :rtype: None
    例外:
        :raises SystemExit: 常に発生します。
    """
    if message:
        print(message)
    usage()
    raise SystemExit(1)


def updatevars():
    """
    概要:
        コマンドライン引数からグローバル変数を更新します。
    戻り値:
        :returns: なし
        :rtype: None
    """
    global mode, ELabel, XLabel, ka, Z, Ne

    if len(sys.argv) == 1:
        terminate()

    mode = getarg(1, mode)
    Z = getfloatarg(2, Z)
    ka = getfloatarg(3, ka)
    Ne = getfloatarg(4, Ne)

    if Z <= 0.0 or ka <= 0.0 or Ne < 0.0:
        terminate("Z and ka must be positive, and Ne must be non-negative.")

    ELabel = 'Etot' if 'e' in mode else 'E 1s'
    XLabel = 'U(X-HF)' if 'h' in mode else 'U(X-alpha)'


yRr = []
yQr = []
r = []


def Rr(ka, Z, n, l, m, r):
    """
    概要:
        水素様1s軌道の動径波動関数の値を計算します。
    引数:
        :param ka: 軌道のスケールパラメータ。
        :type ka: float
        :param Z: 原子番号。
        :type Z: float
        :param n: 主量子数。
        :type n: int
        :param l: 方位量子数。
        :type l: int
        :param m: 磁気量子数。
        :type m: int
        :param r: 動径座標。
        :type r: float
    戻り値:
        :returns: 動径波動関数の値。
        :rtype: float
    """
    zeta = ka * Z
    return R1s0 * zeta**1.5 * exp(-zeta * r)


def rho(ka, Z, n, l, m, r):
    """
    概要:
        電子密度の動径分布を計算します。
    引数:
        :param ka: 軌道のスケールパラメータ。
        :type ka: float
        :param Z: 原子番号。
        :type Z: float
        :param n: 主量子数。
        :type n: int
        :param l: 方位量子数。
        :type l: int
        :param m: 磁気量子数。
        :type m: int
        :param r: 動径座標。
        :type r: float
    戻り値:
        :returns: 電子密度の値。
        :rtype: float
    """
    psi = Rr(ka, Z, n, l, m, r)
    return psi * psi


def build_Qr(ka, Z, n, l, m):
    """
    概要:
        軌道の積分量などを事前計算してグローバル変数に格納します。
    引数:
        :param ka: 軌道のスケールパラメータ。
        :type ka: float
        :param Z: 原子番号。
        :type Z: float
        :param n: 主量子数。
        :type n: int
        :param l: 方位量子数。
        :type l: int
        :param m: 磁気量子数。
        :type m: int
    戻り値:
        :returns: なし
        :rtype: None
    """
    global yRr, yQr

    zeta = ka * Z
    yRr = [Rr(ka, Z, n, l, m, ri) for ri in r]
    yQr = []
    for ri in r:
        x = zeta * ri
        yQr.append(1.0 - exp(-2.0 * x) * (1.0 + 2.0 * x + 2.0 * x * x))


def calTanal(Z=1.0, ka=1.0):
    """
    概要:
        解析的な運動エネルギーを計算します。
    引数:
        :param Z: 原子番号。
        :type Z: float
        :param ka: 軌道のスケールパラメータ。
        :type ka: float
    戻り値:
        :returns: 解析的運動エネルギー値 (eV)。
        :rtype: float
    """
    return 0.5 * (ka * Z)**2 * HartreeToeV


def calUanal(Z=1.0, ka=1.0):
    """
    概要:
        解析的なポテンシャルエネルギーを計算します。
    引数:
        :param Z: 原子番号。
        :type Z: float
        :param ka: 軌道のスケールパラメータ。
        :type ka: float
    戻り値:
        :returns: 解析的ポテンシャルエネルギー値 (eV)。
        :rtype: float
    """
    return -ka * Z**2 * HartreeToeV


def integrate3DR(func, rmin, rmax, limit=15, epsrel=1.0e-8):
    """
    概要:
        動径方向の3次元球積分を計算します。
    引数:
        :param func: 積分する関数。
        :type func: callable
        :param rmin: 積分下限。
        :type rmin: float
        :param rmax: 積分上限。
        :type rmax: float
        :param limit: 積分の分割上限。
        :type limit: int
        :param epsrel: 相対誤差の許容値。
        :type epsrel: float
    戻り値:
        :returns: 積分結果と推定誤差のタプル。
        :rtype: tuple
    """
    return integrate.quad(lambda rv: pi4 * rv * rv * func(rv), rmin, rmax,
                          limit=limit, epsrel=epsrel)


def calUZ(r, Z):
    """
    概要:
        原子核によるポテンシャルを計算します。
    引数:
        :param r: 動径座標。
        :type r: float
        :param Z: 原子番号。
        :type Z: float
    戻り値:
        :returns: ポテンシャルの値。
        :rtype: float
    """
    return -Z / max(r, 1.0e-3)


def calUrho(r, ka, Z, n, l, m):
    """
    概要:
        規格化された1s密度が作るHartreeポテンシャルを計算します。
    引数:
        :param r: 動径座標。
        :type r: float
        :param ka: 軌道のスケールパラメータ。
        :type ka: float
        :param Z: 原子番号。
        :type Z: float
        :param n: 主量子数。
        :type n: int
        :param l: 方位量子数。
        :type l: int
        :param m: 磁気量子数。
        :type m: int
    戻り値:
        :returns: Hartreeポテンシャルの値。
        :rtype: float
    """
    # 規格化された1s密度が作るHartreeポテンシャル。
    zeta = ka * Z
    if r < 1.0e-10:
        return zeta
    return 1.0 / r - exp(-2.0 * zeta * r) * (1.0 / r + zeta)


def calT(ka, Z, n, l, m, Ne, Rmin, Rmax, nmaxdiv, eps):
    """
    概要:
        運動エネルギーの期待値を数値積分で計算します。
    引数:
        :param ka: 軌道のスケールパラメータ。
        :type ka: float
        :param Z: 原子番号。
        :type Z: float
        :param n: 主量子数。
        :type n: int
        :param l: 方位量子数。
        :type l: int
        :param m: 磁気量子数。
        :type m: int
        :param Ne: 占有数。
        :type Ne: float
        :param Rmin: 積分下限。
        :type Rmin: float
        :param Rmax: 積分上限。
        :type Rmax: float
        :param nmaxdiv: 積分の分割上限。
        :type nmaxdiv: int
        :param eps: 許容誤差。
        :type eps: float
    戻り値:
        :returns: 運動エネルギーと誤差のタプル。
        :rtype: tuple
    """
    zeta = ka * Z
    Rmaxint = min(-log(eps) / zeta, Rmax)
    T, errT = integrate.quad(
        lambda rv: rv * (2.0 - zeta * rv) * exp(-2.0 * zeta * rv),
        Rmin, Rmaxint, limit=nmaxdiv, epsrel=eps
    )
    T *= 0.5 * pi4 * zeta * R1s0**2 * zeta**3
    return T, errT


def calUeZ(ka, Z, n, l, m, Ne, Rmin, Rmax, nmaxdiv, eps):
    """
    概要:
        電子と原子核間のポテンシャルエネルギーを数値積分で計算します。
    引数:
        :param ka: 軌道のスケールパラメータ。
        :type ka: float
        :param Z: 原子番号。
        :type Z: float
        :param n: 主量子数。
        :type n: int
        :param l: 方位量子数。
        :type l: int
        :param m: 磁気量子数。
        :type m: int
        :param Ne: 占有数。
        :type Ne: float
        :param Rmin: 積分下限。
        :type Rmin: float
        :param Rmax: 積分上限。
        :type Rmax: float
        :param nmaxdiv: 積分の分割上限。
        :type nmaxdiv: int
        :param eps: 許容誤差。
        :type eps: float
    戻り値:
        :returns: 核ポテンシャルエネルギーと誤差のタプル。
        :rtype: tuple
    """
    zeta = ka * Z
    Rmaxint = min(-log(eps) / zeta, Rmax)
    UeZ, errUeZ = integrate.quad(
        lambda rv: pi4 * rv * rho(ka, Z, n, l, m, rv),
        Rmin, Rmaxint, limit=nmaxdiv, epsrel=eps
    )
    return -Z * UeZ, errUeZ


def calUee(mode, ka, Z, n, l, m, Ne, Rmin, Rmax, nmaxdiv, eps):
    """
    概要:
        電子間のHartreeポテンシャルエネルギーを数値積分で計算します。
    引数:
        :param mode: 実行モード文字列。
        :type mode: str
        :param ka: 軌道のスケールパラメータ。
        :type ka: float
        :param Z: 原子番号。
        :type Z: float
        :param n: 主量子数。
        :type n: int
        :param l: 方位量子数。
        :type l: int
        :param m: 磁気量子数。
        :type m: int
        :param Ne: 占有数。
        :type Ne: float
        :param Rmin: 積分下限。
        :type Rmin: float
        :param Rmax: 積分上限。
        :type Rmax: float
        :param nmaxdiv: 積分の分割上限。
        :type nmaxdiv: int
        :param eps: 許容誤差。
        :type eps: float
    戻り値:
        :returns: Hartreeポテンシャルエネルギーと誤差のタプル。
        :rtype: tuple
    """
    zeta = ka * Z
    Rmaxint = min(-log(eps) / zeta, Rmax)
    J, errUee = integrate.quad(
        lambda rv: pi4 * rv * rv * calUrho(rv, ka, Z, n, l, m)
        * rho(ka, Z, n, l, m, rv),
        Rmin, Rmaxint, limit=nmaxdiv, epsrel=eps
    )

    # 軌道エネルギーにはN J、全エネルギーには1/2 N^2 Jが入る。
    Uee = 0.5 * Ne**2 * J if 'e' in mode else Ne * J
    return Uee, errUee


def calLocalUXa(r, ka, Z, n, l, m, Ne):
    """
    概要:
        1スピン密度に対するX-alpha交換ポテンシャルを計算します。
    詳細説明:
        vx = -3 alpha (3 n_sigma(r)/(4 pi))^(1/3) と定義します。
        alpha=2/3なら、完全スピン分極した1電子系に対するDirac LDA交換ポテンシャルになります。
    引数:
        :param r: 動径座標。
        :type r: float
        :param ka: 軌道のスケールパラメータ。
        :type ka: float
        :param Z: 原子番号。
        :type Z: float
        :param n: 主量子数。
        :type n: int
        :param l: 方位量子数。
        :type l: int
        :param m: 磁気量子数。
        :type m: int
        :param Ne: 占有数。
        :type Ne: float
    戻り値:
        :returns: 局所的なX-alpha交換ポテンシャルの値。
        :rtype: float
    """
    if Ne <= 0.0:
        return 0.0
    density = Ne * rho(ka, Z, n, l, m, r)
    return -3.0 * alpha * (3.0 * density / pi4)**(1.0 / 3.0)


def calUXa(mode, ka, Z, n, l, m, Ne, Rmin, Rmax, nmaxdiv, eps):
    """
    概要:
        X-alpha交換エネルギーを数値積分で計算します。
    引数:
        :param mode: 実行モード文字列。
        :type mode: str
        :param ka: 軌道のスケールパラメータ。
        :type ka: float
        :param Z: 原子番号。
        :type Z: float
        :param n: 主量子数。
        :type n: int
        :param l: 方位量子数。
        :type l: int
        :param m: 磁気量子数。
        :type m: int
        :param Ne: 占有数。
        :type Ne: float
        :param Rmin: 積分下限。
        :type Rmin: float
        :param Rmax: 積分上限。
        :type Rmax: float
        :param nmaxdiv: 積分の分割上限。
        :type nmaxdiv: int
        :param eps: 許容誤差。
        :type eps: float
    戻り値:
        :returns: X-alpha交換エネルギーと誤差のタプル。
        :rtype: tuple
    """
    zeta = ka * Z
    Rmaxint = min(-log(eps) / zeta, Rmax)
    avg_vx, errUXa = integrate.quad(
        lambda rv: pi4 * rv * rv * calLocalUXa(rv, ka, Z, n, l, m, Ne)
        * rho(ka, Z, n, l, m, rv),
        Rmin, Rmaxint, limit=nmaxdiv, epsrel=eps
    )

    # 全エネルギーでは Ex[n]=3/4 ∫n_sigma(r)vx,sigma(r)dr、
    # 軌道エネルギーでは <vx,sigma> を使う。
    factor = 0.75 * Ne if 'e' in mode else 1.0
    return factor * avg_vx, factor * errUXa


def calUXHF(mode, ka, Z, n, l, m, Ne, Rmin, Rmax, nmaxdiv, eps):
    """
    概要:
        同じ1スピン軌道に対する厳密HF交換エネルギーを計算します。
    詳細説明:
        HFではFock交換がHartree自己相互作用を厳密に打ち消します。
        全エネルギーでは -Ne^2 J/2、軌道エネルギーでは -Ne J となります。
    引数:
        :param mode: 実行モード文字列。
        :type mode: str
        :param ka: 軌道のスケールパラメータ。
        :type ka: float
        :param Z: 原子番号。
        :type Z: float
        :param n: 主量子数。
        :type n: int
        :param l: 方位量子数。
        :type l: int
        :param m: 磁気量子数。
        :type m: int
        :param Ne: 占有数。
        :type Ne: float
        :param Rmin: 積分下限。
        :type Rmin: float
        :param Rmax: 積分上限。
        :type Rmax: float
        :param nmaxdiv: 積分の分割上限。
        :type nmaxdiv: int
        :param eps: 許容誤差。
        :type eps: float
    戻り値:
        :returns: HF交換エネルギーと誤差のタプル。
        :rtype: tuple
    """
    # calUee は、この mode に対応する Hartree 項を返すため、その符号を
    # 反転すれば同じ 1 スピン軌道の HF 交換項になる。
    Uee, errUee = calUee(mode, ka, Z, n, l, m, Ne,
                          Rmin, Rmax, nmaxdiv, eps)
    return -Uee, errUee


def calExchange(mode, ka, Z, n, l, m, Ne, Rmin, Rmax, nmaxdiv, eps):
    """
    概要:
        モードに応じた交換エネルギーを計算します。
    引数:
        :param mode: 実行モード文字列。
        :type mode: str
        :param ka: 軌道のスケールパラメータ。
        :type ka: float
        :param Z: 原子番号。
        :type Z: float
        :param n: 主量子数。
        :type n: int
        :param l: 方位量子数。
        :type l: int
        :param m: 磁気量子数。
        :type m: int
        :param Ne: 占有数。
        :type Ne: float
        :param Rmin: 積分下限。
        :type Rmin: float
        :param Rmax: 積分上限。
        :type Rmax: float
        :param nmaxdiv: 積分の分割上限。
        :type nmaxdiv: int
        :param eps: 許容誤差。
        :type eps: float
    戻り値:
        :returns: 交換エネルギーと誤差のタプル。
        :rtype: tuple
    """
    if 'h' in mode:
        return calUXHF(mode, ka, Z, n, l, m, Ne,
                       Rmin, Rmax, nmaxdiv, eps)
    return calUXa(mode, ka, Z, n, l, m, Ne,
                  Rmin, Rmax, nmaxdiv, eps)


def calTotalEnergy(ka, Z, n, l, m, Ne, Rmin, Rmax, nmaxdiv, eps):
    """
    概要:
        各エネルギー項と全エネルギーを計算して返します。
    引数:
        :param ka: 軌道のスケールパラメータ。
        :type ka: float
        :param Z: 原子番号。
        :type Z: float
        :param n: 主量子数。
        :type n: int
        :param l: 方位量子数。
        :type l: int
        :param m: 磁気量子数。
        :type m: int
        :param Ne: 占有数。
        :type Ne: float
        :param Rmin: 積分下限。
        :type Rmin: float
        :param Rmax: 積分上限。
        :type Rmax: float
        :param nmaxdiv: 積分の分割上限。
        :type nmaxdiv: int
        :param eps: 許容誤差。
        :type eps: float
    戻り値:
        :returns: 運動エネルギー、核ポテンシャル、電子間ポテンシャル、交換ポテンシャル、全エネルギーのタプル。
        :rtype: tuple
    """
    T, errT = calT(ka, Z, n, l, m, Ne, Rmin, Rmax, nmaxdiv, eps)
    UeZ, errUeZ = calUeZ(ka, Z, n, l, m, Ne, Rmin, Rmax, nmaxdiv, eps)
    Uee, errUee = calUee(mode, ka, Z, n, l, m, Ne, Rmin, Rmax, nmaxdiv, eps)
    UXa, errUXa = calExchange(mode, ka, Z, n, l, m, Ne,
                              Rmin, Rmax, nmaxdiv, eps)

    # 全エネルギーモードでは1電子項も電子数倍する。
    if 'e' in mode:
        T *= Ne
        UeZ *= Ne

    Etot = T + UeZ + Uee + UXa
    return T, UeZ, Uee, UXa, Etot


def calTotalEnergyOnly(kav, Z, n, l, m, Ne, Rmin, Rmax, nmaxdiv, eps):
    """
    概要:
        最適化用に全エネルギーのみを計算して返します。
    引数:
        :param kav: 最適化対象のスケールパラメータ。
        :type kav: float
        :param Z: 原子番号。
        :type Z: float
        :param n: 主量子数。
        :type n: int
        :param l: 方位量子数。
        :type l: int
        :param m: 磁気量子数。
        :type m: int
        :param Ne: 占有数。
        :type Ne: float
        :param Rmin: 積分下限。
        :type Rmin: float
        :param Rmax: 積分上限。
        :type Rmax: float
        :param nmaxdiv: 積分の分割上限。
        :type nmaxdiv: int
        :param eps: 許容誤差。
        :type eps: float
    戻り値:
        :returns: 全エネルギーの値。
        :rtype: float
    """
    T, _ = calT(kav, Z, n, l, m, Ne, Rmin, Rmax, nmaxdiv, eps)
    UeZ, _ = calUeZ(kav, Z, n, l, m, Ne, Rmin, Rmax, nmaxdiv, eps)
    Uee, _ = calUee('e', kav, Z, n, l, m, Ne, Rmin, Rmax, nmaxdiv, eps)
    total_mode = 'eh' if 'h' in mode else 'e'
    UXa, _ = calExchange(total_mode, kav, Z, n, l, m, Ne,
                         Rmin, Rmax, nmaxdiv, eps)
    return Ne * (T + UeZ) + Uee + UXa


def calOptimizedTotalEnergy(ka, Z, n, l, m, Ne, Rmin, Rmax, nmaxdiv, eps):
    """
    概要:
        全エネルギーを最小化する最適化を実行します。
    詳細説明:
        scipy.optimize.minimize_scalarを使用して最適なスケールパラメータを求めます。
    引数:
        :param ka: 軌道のスケールパラメータ初期値。
        :type ka: float
        :param Z: 原子番号。
        :type Z: float
        :param n: 主量子数。
        :type n: int
        :param l: 方位量子数。
        :type l: int
        :param m: 磁気量子数。
        :type m: int
        :param Ne: 占有数。
        :type Ne: float
        :param Rmin: 積分下限。
        :type Rmin: float
        :param Rmax: 積分上限。
        :type Rmax: float
        :param nmaxdiv: 積分の分割上限。
        :type nmaxdiv: int
        :param eps: 許容誤差。
        :type eps: float
    戻り値:
        :returns: 各エネルギー成分、全エネルギー、最適化されたスケールパラメータのタプル。
        :rtype: tuple
    """
    result = minimize_scalar(
        lambda kav: calTotalEnergyOnly(
            kav, Z, n, l, m, Ne, Rmin, Rmax, nmaxdiv, eps
        ),
        bounds=ka_bounds, method='bounded', options={'xatol': tol}
    )
    if not result.success:
        raise RuntimeError(result.message)

    kaopt = result.x
    T, UeZ, Uee, UXa, Etot = calTotalEnergy(
        kaopt, Z, n, l, m, Ne, Rmin, Rmax, nmaxdiv, eps
    )
    return T, UeZ, Uee, UXa, Etot, kaopt


def sweep_Ne(Eanal):
    """
    概要:
        占有数Neを掃引してエネルギーを計算およびプロットします。
    引数:
        :param Eanal: 比較用の解析的エネルギー値。
        :type Eanal: float
    戻り値:
        :returns: なし
        :rtype: None
    """
    global ka

    print("\nNot optimized")
    print("Parabolic expansion around Ne=0.5")
    _, _, _, _, Fp = calTotalEnergy(ka, Z, n, l, m, 0.5 + hparab,
                                    Rmin, Rmax, nmaxdiv, eps)
    _, _, _, _, F0 = calTotalEnergy(ka, Z, n, l, m, 0.5,
                                    Rmin, Rmax, nmaxdiv, eps)
    _, _, _, _, Fm = calTotalEnergy(ka, Z, n, l, m, 0.5 - hparab,
                                    Rmin, Rmax, nmaxdiv, eps)
    Fp, F0, Fm = [value * HartreeToeV for value in (Fp, F0, Fm)]
    a1 = (Fp - Fm) / (2.0 * hparab)
    a2 = 0.5 * (Fp - 2.0 * F0 + Fm) / hparab**2
    print(f"{ELabel}(Ne) = {F0:.8f} + {a1:.8f}(Ne-0.5)"
          f" + {a2:.8f}(Ne-0.5)^2 eV")

    xNe, yE1s, yE1sparab = [], [], []
    components = [[], [], [], []]
    print(f"\n{'ka':>8s} {'Z':>8s} {'Ne':>10s} {'T':>12s} {'U(e-Z)':>12s}"
          f" {'U(e-e)':>12s} {XLabel:>12s} {ELabel:>14s} {'parabolic':>14s}")
    for Nei in Nearray:
        T, UeZ, Uee, UXa, F = calTotalEnergy(
            ka, Z, n, l, m, Nei, Rmin, Rmax, nmaxdiv, eps
        )
        Fparab = F0 + a1 * (Nei - 0.5) + a2 * (Nei - 0.5)**2
        values = [T, UeZ, Uee, UXa, F]
        values = [value * HartreeToeV for value in values]
        print(f"{ka:8.4f} {Z:8.4f} {Nei:10.4g} "
              + " ".join(f"{value:12.6f}" for value in values)
              + f" {Fparab:14.6f}")
        xNe.append(Nei)
        yE1s.append(values[-1])
        yE1sparab.append(Fparab)
        for array, value in zip(components, values[:4]):
            array.append(value)

    yE1sOpt, yE1sOptparab, ykaOpt = [], [], []
    if 'v' in mode:
        print("\nOptimized for ka by variational principle")
        _, _, _, _, Fp, _ = calOptimizedTotalEnergy(
            ka, Z, n, l, m, 0.5 + hparab, Rmin, Rmax, nmaxdiv, eps
        )
        _, _, _, _, F0opt, _ = calOptimizedTotalEnergy(
            ka, Z, n, l, m, 0.5, Rmin, Rmax, nmaxdiv, eps
        )
        _, _, _, _, Fm, _ = calOptimizedTotalEnergy(
            ka, Z, n, l, m, 0.5 - hparab, Rmin, Rmax, nmaxdiv, eps
        )
        Fp, F0opt, Fm = [value * HartreeToeV for value in (Fp, F0opt, Fm)]
        a1opt = (Fp - Fm) / (2.0 * hparab)
        a2opt = 0.5 * (Fp - 2.0 * F0opt + Fm) / hparab**2
        print(f"{ELabel}(Ne) = {F0opt:.8f} + {a1opt:.8f}(Ne-0.5)"
              f" + {a2opt:.8f}(Ne-0.5)^2 eV")

        print(f"\n{'ka':>8s} {'Z':>8s} {'Ne':>10s} {'T':>12s} {'U(e-Z)':>12s}"
              f" {'U(e-e)':>12s} {XLabel:>12s} {ELabel:>14s} {'parabolic':>14s}")
        for Nei in Nearray:
            T, UeZ, Uee, UXa, F, kaopt = calOptimizedTotalEnergy(
                ka, Z, n, l, m, Nei, Rmin, Rmax, nmaxdiv, eps
            )
            Fparab = F0opt + a1opt * (Nei - 0.5) + a2opt * (Nei - 0.5)**2
            values = [T, UeZ, Uee, UXa, F]
            values = [value * HartreeToeV for value in values]
            print(f"{kaopt:8.4f} {Z:8.4f} {Nei:10.4g} "
                  + " ".join(f"{value:12.6f}" for value in values)
                  + f" {Fparab:14.6f}")
            yE1sOpt.append(values[-1])
            yE1sOptparab.append(Fparab)
            ykaOpt.append(kaopt)

    if 'g' not in mode:
        return

    fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))
    ax1.plot(xNe, yE1s, 'o-', color='black', label=ELabel + ' (fixed ka)')
    ax1.plot(xNe, yE1sparab, '--', color='black', linewidth=0.8,
             label=ELabel + ' (quadratic near 0.5)')
    if 'v' in mode:
        ax1.plot(xNe, yE1sOpt, 'o-', color='red', label=ELabel + ' (optimized)')
        ax1.plot(xNe, yE1sOptparab, '--', color='red', linewidth=0.8,
                 label=ELabel + ' (optimized quadratic)')

    if 'e' in mode:
        ax1.plot(xNe, np.asarray(xNe) * Eanal, ':', color='blue',
                 label='noninteracting H-like: Ne E1s')
    else:
        ax1.axhline(Eanal, color='blue', linestyle=':',
                    label='noninteracting H-like E1s')
    ax1.axvline(0.5, color='gray', linestyle='--', label='Ne=0.5')
    ax1.set_xlabel('Ne')
    ax1.set_ylabel(ELabel + ' (eV)')
    ax1.legend(fontsize=8)

    if 'v' in mode:
        ax2.plot(xNe, ykaOpt, 'o-', color='black', label='optimized ka')
    ax2.axhline(1.0, color='red', linestyle='--', label='ka=1')
    ax2.axvline(0.5, color='gray', linestyle='--')
    ax2.set_xlabel('Ne')
    ax2.set_ylabel('ka')
    ax2.legend()
    plt.tight_layout()
    plt.show()


def sweep_ka(Eanal):
    """
    概要:
        スケールパラメータkaを掃引してエネルギーを計算およびプロットします。
    引数:
        :param Eanal: 比較用の解析的エネルギー値。
        :type Eanal: float
    戻り値:
        :returns: なし
        :rtype: None
    """
    xka, yE1s = [], []
    yT, yUeZ, yUee, yUXa = [], [], [], []

    print(f"\n{'ka':>8s} {'Z':>8s} {'Ne':>8s} {'T':>12s} {'U(e-Z)':>12s}"
          f" {'U(e-e)':>12s} {XLabel:>12s} {ELabel:>14s}")
    for kav in kaarray:
        T, UeZ, Uee, UXa, F = calTotalEnergy(
            kav, Z, n, l, m, Ne, Rmin, Rmax, nmaxdiv, eps
        )
        values = [value * HartreeToeV for value in (T, UeZ, Uee, UXa, F)]
        print(f"{kav:8.4f} {Z:8.4f} {Ne:8.4f} "
              + " ".join(f"{value:12.6f}" for value in values))
        xka.append(kav)
        yT.append(values[0])
        yUeZ.append(values[1])
        yUee.append(values[2])
        yUXa.append(values[3])
        yE1s.append(values[4])

    if 'v' in mode:
        T, UeZ, Uee, UXa, F, kaopt = calOptimizedTotalEnergy(
            ka, Z, n, l, m, Ne, Rmin, Rmax, nmaxdiv, eps
        )
        print(f"\noptimized ka={kaopt:.8f}, {ELabel}={F*HartreeToeV:.8f} eV")

    if 'g' not in mode:
        return

    fig, axes = plt.subplots(2, 3, figsize=(13, 8))
    plots = [
        (yE1s, ELabel), (yT, 'T'), (yUeZ, 'U(e-Z)'),
        (yUee, 'U(e-e)'), (yUXa, XLabel)
    ]
    for ax, (values, label) in zip(axes.flat, plots):
        ax.plot(xka, values, 'o-', color='black')
        ax.set_xlabel('ka')
        ax.set_ylabel(label + ' (eV)')
        ax.grid(alpha=0.25)

    Eref = Ne * Eanal if 'e' in mode else Eanal
    axes[0, 0].axhline(Eref, color='red', linestyle='--',
                       label='noninteracting H-like reference')
    axes[0, 0].legend()
    axes[1, 2].axis('off')
    plt.tight_layout()
    plt.show()


def debug(Eanal):
    """
    概要:
        デバッグ出力として各種物理量の計算結果や分布をプロットします。
    引数:
        :param Eanal: 比較用の解析的エネルギー値。
        :type Eanal: float
    戻り値:
        :returns: なし
        :rtype: None
    """
    ka_plot = ka

    print(f"\n{'ka':>8s} {'Z':>8s} {'Ne':>8s} {'T':>12s} {'U(e-Z)':>12s}"
          f" {'U(e-e)':>12s} {XLabel:>12s} {ELabel:>14s}")
    T, UeZ, Uee, UXa, F = calTotalEnergy(
        ka_plot, Z, n, l, m, Ne, Rmin, Rmax, nmaxdiv, eps
    )
    values = [value * HartreeToeV for value in (T, UeZ, Uee, UXa, F)]
    print(f"{ka_plot:8.4f} {Z:8.4f} {Ne:8.4f} "
          + " ".join(f"{value:12.6f}" for value in values))

    if 'v' in mode:
        T, UeZ, Uee, UXa, F, ka_plot = calOptimizedTotalEnergy(
            ka, Z, n, l, m, Ne, Rmin, Rmax, nmaxdiv, eps
        )
        values = [value * HartreeToeV for value in (T, UeZ, Uee, UXa, F)]
        print("\nOptimized for ka by variational principle")
        print(f"{ka_plot:8.4f} {Z:8.4f} {Ne:8.4f} "
              + " ".join(f"{value:12.6f}" for value in values))

    if 'g' not in mode:
        return

    build_Qr(ka_plot, Z, n, l, m)
    yDensity = [Ne * rho(ka_plot, Z, n, l, m, ri) for ri in r]
    yRadial = [pi4 * ri * ri * value for ri, value in zip(r, yDensity)]
    ypotZ = [calUZ(ri, Z) for ri in r]
    ypotrho = [Ne * calUrho(ri, ka_plot, Z, n, l, m) for ri in r]
    if 'h' in mode:
        # 同一軌道への Fock 作用は -Ne*V_H(r) となり、Hartree 項を打ち消す。
        ypotXa = [-Ne * calUrho(ri, ka_plot, Z, n, l, m) for ri in r]
        xpotential_label = 'V_X-HF (on 1s)'
    else:
        ypotXa = [calLocalUXa(ri, ka_plot, Z, n, l, m, Ne) for ri in r]
        xpotential_label = 'V_X-alpha'
    ypotEff = [vz + vh + vx for vz, vh, vx in zip(ypotZ, ypotrho, ypotXa)]

    fig, axes = plt.subplots(2, 2, figsize=(12, 8))
    ax1, ax2, ax3, ax4 = axes.flat
    ax1.plot(r, yRr, color='black', label='psi_1s(r)')
    ax1.set(xlim=(Rmin, Rmax), xlabel='r (bohr)', ylabel='psi_1s(r)')
    ax1.legend()

    ax2.plot(r, yRadial, color='black', label='4 pi r^2 n(r)')
    ax2.plot(r, Ne * np.asarray(yQr), color='blue', label='N(<r)')
    ax2.set(xlim=(Rmin, Rmax), xlabel='r (bohr)', ylabel='electron distribution')
    ax2.legend()

    ax3.plot(r, ypotZ, color='black', label='V_nuclear')
    ax3.plot(r, ypotrho, color='blue', label='V_H')
    ax3.plot(r, ypotXa, color='green', label=xpotential_label)
    ax3.plot(r, ypotEff, color='red', label='V_effective')
    ax3.set(xlim=(Rmin, Rmax), ylim=(-4.0 * ka_plot * Z, ka_plot * Z),
            xlabel='r (bohr)', ylabel='potential (Hartree)')
    ax3.legend()

    ax4.plot(r, yDensity, color='black', label='n(r)')
    ax4.set(xlim=(Rmin, Rmax), xlabel='r (bohr)', ylabel='density')
    ax4.legend()
    plt.tight_layout()
    plt.show()


def main():
    """
    概要:
        メイン処理を実行します。
    戻り値:
        :returns: なし
        :rtype: None
    """
    global r

    updatevars()
    # 表示用グリッドは宣言した Rmax までとする。以前は nR+100 点を
    # 作っており、表示上の Rmax と実データ範囲が一致していなかった。
    r = np.linspace(Rmin, Rmax, nR)

    print(f"\nmode: {mode}")
    print(f"Orbital: ka={ka}, Z={Z}, n={n}, l={l}, m={m}")
    print(f"Ne={Ne}, Rmax={Rmax}")
    print(f"Rmax estimate for epsR={epsR}: {-log(epsR)/(Z*ka):.6f} bohr")

    Tanal = calTanal(Z, ka)
    Uanal = calUanal(Z, ka)
    Etrial = Tanal + Uanal
    Eanal = -0.5 * Z**2 * HartreeToeV
    print("\nAnalytical values for the trial orbital")
    print(f"T={Tanal:.8f} eV, U={Uanal:.8f} eV, E={Etrial:.8f} eV")
    print(f"Exact H-like 1s energy={Eanal:.8f} eV")

    norm, err = integrate.quad(
        lambda rv: pi4 * rv * rv * rho(ka, Z, n, l, m, rv),
        Rmin, Rmax, limit=nmaxdiv, epsrel=eps
    )
    print(f"Normalization integral={norm:.12f}")

    if 'd' in mode:
        debug(Eanal)
    if 'k' in mode:
        sweep_ka(Eanal)
    if 'n' in mode:
        sweep_Ne(Eanal)


if __name__ == '__main__':
    main()