H1s_HF_LDA.py ダウンロード/コピー

H1s_HF_LDA.py をダウンロード

H1s_HF_LDA.py
H1s_HF_LDA.py
   1"""
   2概要:
   3    1s試行軌道によるHartree・HF・X-alpha/LDA交換のToyプログラムです。
   4詳細説明:
   5    modeにeを含めると全エネルギー、含めないと1s軌道エネルギーを表示します。
   6    既定は、1スピン軌道の分率占有数 0 <= Ne <= 1 に対するX-alpha/LDA交換です。
   7    hを加えると同じ軌道の厳密HF交換を使います。
   8"""
   9
  10import sys
  11from math import exp, log, pi, sqrt
  12
  13import numpy as np
  14from matplotlib import pyplot as plt
  15from scipy import integrate
  16from scipy.optimize import minimize_scalar
  17
  18
  19HartreeToeV = 27.211386245988
  20pi4 = 4.0 * pi
  21R1s0 = 1.0 / sqrt(pi)
  22
  23# mode: d=基本量, k=ka掃引, n=Ne掃引, v=ka最適化, e=全エネルギー, g=グラフ
  24mode = 'k'
  25ELabel = 'E 1s'
  26XLabel = 'U(X-alpha)'
  27
  28Z = 1.0
  29n, l, m = 1, 0, 0
  30ka = 1.0
  31Ne = 1.0
  32alpha = 2.0 / 3.0
  33
  34Rmin = 0.0
  35Rmax = 20.0
  36nR = 2001
  37nmaxdiv = 80
  38epsR = 1.0e-4
  39eps = 1.0e-9
  40hparab = 0.01
  41
  42Nearray = [1.0, 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1,
  43           0.07, 0.05, 0.04, 0.03, 0.02, 0.01, 1e-3, 1e-4, 1e-5, 1e-6]
  44kaarray = [0.5, 0.6, 0.65, 0.7, 0.8, 0.9, 0.95, 1.0, 1.05, 1.1, 1.2, 1.4]
  45
  46tol = 1.0e-7
  47ka_bounds = (0.05, 2.5)
  48
  49
  50def pfloat(value):
  51    """
  52    概要:
  53        値を浮動小数点数に変換します。
  54    詳細説明:
  55        変換できない場合はNoneを返します。
  56    引数:
  57        :param value: 変換する値。
  58        :type value: any
  59    戻り値:
  60        :returns: 変換された浮動小数点数またはNone。
  61        :rtype: float or None
  62    """
  63    try:
  64        return float(value)
  65    except (TypeError, ValueError):
  66        return None
  67
  68
  69def pint(value):
  70    """
  71    概要:
  72        値を整数に変換します。
  73    詳細説明:
  74        変換できない場合はNoneを返します。
  75    引数:
  76        :param value: 変換する値。
  77        :type value: any
  78    戻り値:
  79        :returns: 変換された整数またはNone。
  80        :rtype: int or None
  81    """
  82    try:
  83        return int(value)
  84    except (TypeError, ValueError):
  85        return None
  86
  87
  88def getarg(position, defval=None):
  89    """
  90    概要:
  91        コマンドライン引数を文字列として取得します。
  92    引数:
  93        :param position: 引数のインデックス。
  94        :type position: int
  95        :param defval: 取得できなかった場合のデフォルト値。
  96        :type defval: any
  97    戻り値:
  98        :returns: 取得したコマンドライン引数またはデフォルト値。
  99        :rtype: str or any
 100    """
 101    try:
 102        return sys.argv[position]
 103    except IndexError:
 104        return defval
 105
 106
 107def getfloatarg(position, defval=None):
 108    """
 109    概要:
 110        コマンドライン引数を浮動小数点数として取得します。
 111    引数:
 112        :param position: 引数のインデックス。
 113        :type position: int
 114        :param defval: 取得できなかった場合のデフォルト値。
 115        :type defval: any
 116    戻り値:
 117        :returns: 取得した浮動小数点数またはデフォルト値。
 118        :rtype: float or any
 119    """
 120    value = pfloat(getarg(position, defval))
 121    return defval if value is None else value
 122
 123
 124def getintarg(position, defval=None):
 125    """
 126    概要:
 127        コマンドライン引数を整数として取得します。
 128    引数:
 129        :param position: 引数のインデックス。
 130        :type position: int
 131        :param defval: 取得できなかった場合のデフォルト値。
 132        :type defval: any
 133    戻り値:
 134        :returns: 取得した整数またはデフォルト値。
 135        :rtype: int or any
 136    """
 137    value = pint(getarg(position, defval))
 138    return defval if value is None else value
 139
 140
 141def usage(ka=ka, Z=Z, n=n, l=l, m=m):
 142    """
 143    概要:
 144        プログラムの使用方法を標準出力に表示します。
 145    引数:
 146        :param ka: 軌道のスケールパラメータ。
 147        :type ka: float
 148        :param Z: 原子番号。
 149        :type Z: float
 150        :param n: 主量子数。
 151        :type n: int
 152        :param l: 方位量子数。
 153        :type l: int
 154        :param m: 磁気量子数。
 155        :type m: int
 156    戻り値:
 157        :returns: なし
 158        :rtype: None
 159    """
 160    print(f"Usage: python {sys.argv[0]} mode Z ka Ne")
 161    print("  d: basic quantities and radial plots")
 162    print("  k: sweep ka")
 163    print("  n: sweep Ne")
 164    print("  v: optimize ka by total energy")
 165    print("  e: total energy (default: 1s orbital energy)")
 166    print("  h: use exact HF exchange (default: X-alpha/LDA exchange)")
 167    print("  g: plot graphs")
 168    print( "Note: this model assumes a single spin orbital with 0 <= Ne <= 1.")
 169    print(f"Example: python {sys.argv[0]} nvg {Z} {ka} {Ne}")
 170    print(f"Example: python {sys.argv[0]} nevg {Z} {ka} {Ne}")
 171
 172
 173def terminate(message=None):
 174    """
 175    概要:
 176        メッセージを表示してプログラムを終了します。
 177    引数:
 178        :param message: 終了前に表示するメッセージ文字列。
 179        :type message: str or None
 180    戻り値:
 181        :returns: なし
 182        :rtype: None
 183    例外:
 184        :raises SystemExit: 常に発生します。
 185    """
 186    if message:
 187        print(message)
 188    usage()
 189    raise SystemExit(1)
 190
 191
 192def updatevars():
 193    """
 194    概要:
 195        コマンドライン引数からグローバル変数を更新します。
 196    戻り値:
 197        :returns: なし
 198        :rtype: None
 199    """
 200    global mode, ELabel, XLabel, ka, Z, Ne
 201
 202    if len(sys.argv) == 1:
 203        terminate()
 204
 205    mode = getarg(1, mode)
 206    Z = getfloatarg(2, Z)
 207    ka = getfloatarg(3, ka)
 208    Ne = getfloatarg(4, Ne)
 209
 210    if Z <= 0.0 or ka <= 0.0 or Ne < 0.0:
 211        terminate("Z and ka must be positive, and Ne must be non-negative.")
 212
 213    ELabel = 'Etot' if 'e' in mode else 'E 1s'
 214    XLabel = 'U(X-HF)' if 'h' in mode else 'U(X-alpha)'
 215
 216
 217yRr = []
 218yQr = []
 219r = []
 220
 221
 222def Rr(ka, Z, n, l, m, r):
 223    """
 224    概要:
 225        水素様1s軌道の動径波動関数の値を計算します。
 226    引数:
 227        :param ka: 軌道のスケールパラメータ。
 228        :type ka: float
 229        :param Z: 原子番号。
 230        :type Z: float
 231        :param n: 主量子数。
 232        :type n: int
 233        :param l: 方位量子数。
 234        :type l: int
 235        :param m: 磁気量子数。
 236        :type m: int
 237        :param r: 動径座標。
 238        :type r: float
 239    戻り値:
 240        :returns: 動径波動関数の値。
 241        :rtype: float
 242    """
 243    zeta = ka * Z
 244    return R1s0 * zeta**1.5 * exp(-zeta * r)
 245
 246
 247def rho(ka, Z, n, l, m, r):
 248    """
 249    概要:
 250        電子密度の動径分布を計算します。
 251    引数:
 252        :param ka: 軌道のスケールパラメータ。
 253        :type ka: float
 254        :param Z: 原子番号。
 255        :type Z: float
 256        :param n: 主量子数。
 257        :type n: int
 258        :param l: 方位量子数。
 259        :type l: int
 260        :param m: 磁気量子数。
 261        :type m: int
 262        :param r: 動径座標。
 263        :type r: float
 264    戻り値:
 265        :returns: 電子密度の値。
 266        :rtype: float
 267    """
 268    psi = Rr(ka, Z, n, l, m, r)
 269    return psi * psi
 270
 271
 272def build_Qr(ka, Z, n, l, m):
 273    """
 274    概要:
 275        軌道の積分量などを事前計算してグローバル変数に格納します。
 276    引数:
 277        :param ka: 軌道のスケールパラメータ。
 278        :type ka: float
 279        :param Z: 原子番号。
 280        :type Z: float
 281        :param n: 主量子数。
 282        :type n: int
 283        :param l: 方位量子数。
 284        :type l: int
 285        :param m: 磁気量子数。
 286        :type m: int
 287    戻り値:
 288        :returns: なし
 289        :rtype: None
 290    """
 291    global yRr, yQr
 292
 293    zeta = ka * Z
 294    yRr = [Rr(ka, Z, n, l, m, ri) for ri in r]
 295    yQr = []
 296    for ri in r:
 297        x = zeta * ri
 298        yQr.append(1.0 - exp(-2.0 * x) * (1.0 + 2.0 * x + 2.0 * x * x))
 299
 300
 301def calTanal(Z=1.0, ka=1.0):
 302    """
 303    概要:
 304        解析的な運動エネルギーを計算します。
 305    引数:
 306        :param Z: 原子番号。
 307        :type Z: float
 308        :param ka: 軌道のスケールパラメータ。
 309        :type ka: float
 310    戻り値:
 311        :returns: 解析的運動エネルギー値 (eV)。
 312        :rtype: float
 313    """
 314    return 0.5 * (ka * Z)**2 * HartreeToeV
 315
 316
 317def calUanal(Z=1.0, ka=1.0):
 318    """
 319    概要:
 320        解析的なポテンシャルエネルギーを計算します。
 321    引数:
 322        :param Z: 原子番号。
 323        :type Z: float
 324        :param ka: 軌道のスケールパラメータ。
 325        :type ka: float
 326    戻り値:
 327        :returns: 解析的ポテンシャルエネルギー値 (eV)。
 328        :rtype: float
 329    """
 330    return -ka * Z**2 * HartreeToeV
 331
 332
 333def integrate3DR(func, rmin, rmax, limit=15, epsrel=1.0e-8):
 334    """
 335    概要:
 336        動径方向の3次元球積分を計算します。
 337    引数:
 338        :param func: 積分する関数。
 339        :type func: callable
 340        :param rmin: 積分下限。
 341        :type rmin: float
 342        :param rmax: 積分上限。
 343        :type rmax: float
 344        :param limit: 積分の分割上限。
 345        :type limit: int
 346        :param epsrel: 相対誤差の許容値。
 347        :type epsrel: float
 348    戻り値:
 349        :returns: 積分結果と推定誤差のタプル。
 350        :rtype: tuple
 351    """
 352    return integrate.quad(lambda rv: pi4 * rv * rv * func(rv), rmin, rmax,
 353                          limit=limit, epsrel=epsrel)
 354
 355
 356def calUZ(r, Z):
 357    """
 358    概要:
 359        原子核によるポテンシャルを計算します。
 360    引数:
 361        :param r: 動径座標。
 362        :type r: float
 363        :param Z: 原子番号。
 364        :type Z: float
 365    戻り値:
 366        :returns: ポテンシャルの値。
 367        :rtype: float
 368    """
 369    return -Z / max(r, 1.0e-3)
 370
 371
 372def calUrho(r, ka, Z, n, l, m):
 373    """
 374    概要:
 375        規格化された1s密度が作るHartreeポテンシャルを計算します。
 376    引数:
 377        :param r: 動径座標。
 378        :type r: float
 379        :param ka: 軌道のスケールパラメータ。
 380        :type ka: float
 381        :param Z: 原子番号。
 382        :type Z: float
 383        :param n: 主量子数。
 384        :type n: int
 385        :param l: 方位量子数。
 386        :type l: int
 387        :param m: 磁気量子数。
 388        :type m: int
 389    戻り値:
 390        :returns: Hartreeポテンシャルの値。
 391        :rtype: float
 392    """
 393    # 規格化された1s密度が作るHartreeポテンシャル。
 394    zeta = ka * Z
 395    if r < 1.0e-10:
 396        return zeta
 397    return 1.0 / r - exp(-2.0 * zeta * r) * (1.0 / r + zeta)
 398
 399
 400def calT(ka, Z, n, l, m, Ne, Rmin, Rmax, nmaxdiv, eps):
 401    """
 402    概要:
 403        運動エネルギーの期待値を数値積分で計算します。
 404    引数:
 405        :param ka: 軌道のスケールパラメータ。
 406        :type ka: float
 407        :param Z: 原子番号。
 408        :type Z: float
 409        :param n: 主量子数。
 410        :type n: int
 411        :param l: 方位量子数。
 412        :type l: int
 413        :param m: 磁気量子数。
 414        :type m: int
 415        :param Ne: 占有数。
 416        :type Ne: float
 417        :param Rmin: 積分下限。
 418        :type Rmin: float
 419        :param Rmax: 積分上限。
 420        :type Rmax: float
 421        :param nmaxdiv: 積分の分割上限。
 422        :type nmaxdiv: int
 423        :param eps: 許容誤差。
 424        :type eps: float
 425    戻り値:
 426        :returns: 運動エネルギーと誤差のタプル。
 427        :rtype: tuple
 428    """
 429    zeta = ka * Z
 430    Rmaxint = min(-log(eps) / zeta, Rmax)
 431    T, errT = integrate.quad(
 432        lambda rv: rv * (2.0 - zeta * rv) * exp(-2.0 * zeta * rv),
 433        Rmin, Rmaxint, limit=nmaxdiv, epsrel=eps
 434    )
 435    T *= 0.5 * pi4 * zeta * R1s0**2 * zeta**3
 436    return T, errT
 437
 438
 439def calUeZ(ka, Z, n, l, m, Ne, Rmin, Rmax, nmaxdiv, eps):
 440    """
 441    概要:
 442        電子と原子核間のポテンシャルエネルギーを数値積分で計算します。
 443    引数:
 444        :param ka: 軌道のスケールパラメータ。
 445        :type ka: float
 446        :param Z: 原子番号。
 447        :type Z: float
 448        :param n: 主量子数。
 449        :type n: int
 450        :param l: 方位量子数。
 451        :type l: int
 452        :param m: 磁気量子数。
 453        :type m: int
 454        :param Ne: 占有数。
 455        :type Ne: float
 456        :param Rmin: 積分下限。
 457        :type Rmin: float
 458        :param Rmax: 積分上限。
 459        :type Rmax: float
 460        :param nmaxdiv: 積分の分割上限。
 461        :type nmaxdiv: int
 462        :param eps: 許容誤差。
 463        :type eps: float
 464    戻り値:
 465        :returns: 核ポテンシャルエネルギーと誤差のタプル。
 466        :rtype: tuple
 467    """
 468    zeta = ka * Z
 469    Rmaxint = min(-log(eps) / zeta, Rmax)
 470    UeZ, errUeZ = integrate.quad(
 471        lambda rv: pi4 * rv * rho(ka, Z, n, l, m, rv),
 472        Rmin, Rmaxint, limit=nmaxdiv, epsrel=eps
 473    )
 474    return -Z * UeZ, errUeZ
 475
 476
 477def calUee(mode, ka, Z, n, l, m, Ne, Rmin, Rmax, nmaxdiv, eps):
 478    """
 479    概要:
 480        電子間のHartreeポテンシャルエネルギーを数値積分で計算します。
 481    引数:
 482        :param mode: 実行モード文字列。
 483        :type mode: str
 484        :param ka: 軌道のスケールパラメータ。
 485        :type ka: float
 486        :param Z: 原子番号。
 487        :type Z: float
 488        :param n: 主量子数。
 489        :type n: int
 490        :param l: 方位量子数。
 491        :type l: int
 492        :param m: 磁気量子数。
 493        :type m: int
 494        :param Ne: 占有数。
 495        :type Ne: float
 496        :param Rmin: 積分下限。
 497        :type Rmin: float
 498        :param Rmax: 積分上限。
 499        :type Rmax: float
 500        :param nmaxdiv: 積分の分割上限。
 501        :type nmaxdiv: int
 502        :param eps: 許容誤差。
 503        :type eps: float
 504    戻り値:
 505        :returns: Hartreeポテンシャルエネルギーと誤差のタプル。
 506        :rtype: tuple
 507    """
 508    zeta = ka * Z
 509    Rmaxint = min(-log(eps) / zeta, Rmax)
 510    J, errUee = integrate.quad(
 511        lambda rv: pi4 * rv * rv * calUrho(rv, ka, Z, n, l, m)
 512        * rho(ka, Z, n, l, m, rv),
 513        Rmin, Rmaxint, limit=nmaxdiv, epsrel=eps
 514    )
 515
 516    # 軌道エネルギーにはN J、全エネルギーには1/2 N^2 Jが入る。
 517    Uee = 0.5 * Ne**2 * J if 'e' in mode else Ne * J
 518    return Uee, errUee
 519
 520
 521def calLocalUXa(r, ka, Z, n, l, m, Ne):
 522    """
 523    概要:
 524        1スピン密度に対するX-alpha交換ポテンシャルを計算します。
 525    詳細説明:
 526        vx = -3 alpha (3 n_sigma(r)/(4 pi))^(1/3) と定義します。
 527        alpha=2/3なら、完全スピン分極した1電子系に対するDirac LDA交換ポテンシャルになります。
 528    引数:
 529        :param r: 動径座標。
 530        :type r: float
 531        :param ka: 軌道のスケールパラメータ。
 532        :type ka: float
 533        :param Z: 原子番号。
 534        :type Z: float
 535        :param n: 主量子数。
 536        :type n: int
 537        :param l: 方位量子数。
 538        :type l: int
 539        :param m: 磁気量子数。
 540        :type m: int
 541        :param Ne: 占有数。
 542        :type Ne: float
 543    戻り値:
 544        :returns: 局所的なX-alpha交換ポテンシャルの値。
 545        :rtype: float
 546    """
 547    if Ne <= 0.0:
 548        return 0.0
 549    density = Ne * rho(ka, Z, n, l, m, r)
 550    return -3.0 * alpha * (3.0 * density / pi4)**(1.0 / 3.0)
 551
 552
 553def calUXa(mode, ka, Z, n, l, m, Ne, Rmin, Rmax, nmaxdiv, eps):
 554    """
 555    概要:
 556        X-alpha交換エネルギーを数値積分で計算します。
 557    引数:
 558        :param mode: 実行モード文字列。
 559        :type mode: str
 560        :param ka: 軌道のスケールパラメータ。
 561        :type ka: float
 562        :param Z: 原子番号。
 563        :type Z: float
 564        :param n: 主量子数。
 565        :type n: int
 566        :param l: 方位量子数。
 567        :type l: int
 568        :param m: 磁気量子数。
 569        :type m: int
 570        :param Ne: 占有数。
 571        :type Ne: float
 572        :param Rmin: 積分下限。
 573        :type Rmin: float
 574        :param Rmax: 積分上限。
 575        :type Rmax: float
 576        :param nmaxdiv: 積分の分割上限。
 577        :type nmaxdiv: int
 578        :param eps: 許容誤差。
 579        :type eps: float
 580    戻り値:
 581        :returns: X-alpha交換エネルギーと誤差のタプル。
 582        :rtype: tuple
 583    """
 584    zeta = ka * Z
 585    Rmaxint = min(-log(eps) / zeta, Rmax)
 586    avg_vx, errUXa = integrate.quad(
 587        lambda rv: pi4 * rv * rv * calLocalUXa(rv, ka, Z, n, l, m, Ne)
 588        * rho(ka, Z, n, l, m, rv),
 589        Rmin, Rmaxint, limit=nmaxdiv, epsrel=eps
 590    )
 591
 592    # 全エネルギーでは Ex[n]=3/4 ∫n_sigma(r)vx,sigma(r)dr、
 593    # 軌道エネルギーでは <vx,sigma> を使う。
 594    factor = 0.75 * Ne if 'e' in mode else 1.0
 595    return factor * avg_vx, factor * errUXa
 596
 597
 598def calUXHF(mode, ka, Z, n, l, m, Ne, Rmin, Rmax, nmaxdiv, eps):
 599    """
 600    概要:
 601        同じ1スピン軌道に対する厳密HF交換エネルギーを計算します。
 602    詳細説明:
 603        HFではFock交換がHartree自己相互作用を厳密に打ち消します。
 604        全エネルギーでは -Ne^2 J/2、軌道エネルギーでは -Ne J となります。
 605    引数:
 606        :param mode: 実行モード文字列。
 607        :type mode: str
 608        :param ka: 軌道のスケールパラメータ。
 609        :type ka: float
 610        :param Z: 原子番号。
 611        :type Z: float
 612        :param n: 主量子数。
 613        :type n: int
 614        :param l: 方位量子数。
 615        :type l: int
 616        :param m: 磁気量子数。
 617        :type m: int
 618        :param Ne: 占有数。
 619        :type Ne: float
 620        :param Rmin: 積分下限。
 621        :type Rmin: float
 622        :param Rmax: 積分上限。
 623        :type Rmax: float
 624        :param nmaxdiv: 積分の分割上限。
 625        :type nmaxdiv: int
 626        :param eps: 許容誤差。
 627        :type eps: float
 628    戻り値:
 629        :returns: HF交換エネルギーと誤差のタプル。
 630        :rtype: tuple
 631    """
 632    # calUee は、この mode に対応する Hartree 項を返すため、その符号を
 633    # 反転すれば同じ 1 スピン軌道の HF 交換項になる。
 634    Uee, errUee = calUee(mode, ka, Z, n, l, m, Ne,
 635                          Rmin, Rmax, nmaxdiv, eps)
 636    return -Uee, errUee
 637
 638
 639def calExchange(mode, ka, Z, n, l, m, Ne, Rmin, Rmax, nmaxdiv, eps):
 640    """
 641    概要:
 642        モードに応じた交換エネルギーを計算します。
 643    引数:
 644        :param mode: 実行モード文字列。
 645        :type mode: str
 646        :param ka: 軌道のスケールパラメータ。
 647        :type ka: float
 648        :param Z: 原子番号。
 649        :type Z: float
 650        :param n: 主量子数。
 651        :type n: int
 652        :param l: 方位量子数。
 653        :type l: int
 654        :param m: 磁気量子数。
 655        :type m: int
 656        :param Ne: 占有数。
 657        :type Ne: float
 658        :param Rmin: 積分下限。
 659        :type Rmin: float
 660        :param Rmax: 積分上限。
 661        :type Rmax: float
 662        :param nmaxdiv: 積分の分割上限。
 663        :type nmaxdiv: int
 664        :param eps: 許容誤差。
 665        :type eps: float
 666    戻り値:
 667        :returns: 交換エネルギーと誤差のタプル。
 668        :rtype: tuple
 669    """
 670    if 'h' in mode:
 671        return calUXHF(mode, ka, Z, n, l, m, Ne,
 672                       Rmin, Rmax, nmaxdiv, eps)
 673    return calUXa(mode, ka, Z, n, l, m, Ne,
 674                  Rmin, Rmax, nmaxdiv, eps)
 675
 676
 677def calTotalEnergy(ka, Z, n, l, m, Ne, Rmin, Rmax, nmaxdiv, eps):
 678    """
 679    概要:
 680        各エネルギー項と全エネルギーを計算して返します。
 681    引数:
 682        :param ka: 軌道のスケールパラメータ。
 683        :type ka: float
 684        :param Z: 原子番号。
 685        :type Z: float
 686        :param n: 主量子数。
 687        :type n: int
 688        :param l: 方位量子数。
 689        :type l: int
 690        :param m: 磁気量子数。
 691        :type m: int
 692        :param Ne: 占有数。
 693        :type Ne: float
 694        :param Rmin: 積分下限。
 695        :type Rmin: float
 696        :param Rmax: 積分上限。
 697        :type Rmax: float
 698        :param nmaxdiv: 積分の分割上限。
 699        :type nmaxdiv: int
 700        :param eps: 許容誤差。
 701        :type eps: float
 702    戻り値:
 703        :returns: 運動エネルギー、核ポテンシャル、電子間ポテンシャル、交換ポテンシャル、全エネルギーのタプル。
 704        :rtype: tuple
 705    """
 706    T, errT = calT(ka, Z, n, l, m, Ne, Rmin, Rmax, nmaxdiv, eps)
 707    UeZ, errUeZ = calUeZ(ka, Z, n, l, m, Ne, Rmin, Rmax, nmaxdiv, eps)
 708    Uee, errUee = calUee(mode, ka, Z, n, l, m, Ne, Rmin, Rmax, nmaxdiv, eps)
 709    UXa, errUXa = calExchange(mode, ka, Z, n, l, m, Ne,
 710                              Rmin, Rmax, nmaxdiv, eps)
 711
 712    # 全エネルギーモードでは1電子項も電子数倍する。
 713    if 'e' in mode:
 714        T *= Ne
 715        UeZ *= Ne
 716
 717    Etot = T + UeZ + Uee + UXa
 718    return T, UeZ, Uee, UXa, Etot
 719
 720
 721def calTotalEnergyOnly(kav, Z, n, l, m, Ne, Rmin, Rmax, nmaxdiv, eps):
 722    """
 723    概要:
 724        最適化用に全エネルギーのみを計算して返します。
 725    引数:
 726        :param kav: 最適化対象のスケールパラメータ。
 727        :type kav: float
 728        :param Z: 原子番号。
 729        :type Z: float
 730        :param n: 主量子数。
 731        :type n: int
 732        :param l: 方位量子数。
 733        :type l: int
 734        :param m: 磁気量子数。
 735        :type m: int
 736        :param Ne: 占有数。
 737        :type Ne: float
 738        :param Rmin: 積分下限。
 739        :type Rmin: float
 740        :param Rmax: 積分上限。
 741        :type Rmax: float
 742        :param nmaxdiv: 積分の分割上限。
 743        :type nmaxdiv: int
 744        :param eps: 許容誤差。
 745        :type eps: float
 746    戻り値:
 747        :returns: 全エネルギーの値。
 748        :rtype: float
 749    """
 750    T, _ = calT(kav, Z, n, l, m, Ne, Rmin, Rmax, nmaxdiv, eps)
 751    UeZ, _ = calUeZ(kav, Z, n, l, m, Ne, Rmin, Rmax, nmaxdiv, eps)
 752    Uee, _ = calUee('e', kav, Z, n, l, m, Ne, Rmin, Rmax, nmaxdiv, eps)
 753    total_mode = 'eh' if 'h' in mode else 'e'
 754    UXa, _ = calExchange(total_mode, kav, Z, n, l, m, Ne,
 755                         Rmin, Rmax, nmaxdiv, eps)
 756    return Ne * (T + UeZ) + Uee + UXa
 757
 758
 759def calOptimizedTotalEnergy(ka, Z, n, l, m, Ne, Rmin, Rmax, nmaxdiv, eps):
 760    """
 761    概要:
 762        全エネルギーを最小化する最適化を実行します。
 763    詳細説明:
 764        scipy.optimize.minimize_scalarを使用して最適なスケールパラメータを求めます。
 765    引数:
 766        :param ka: 軌道のスケールパラメータ初期値。
 767        :type ka: float
 768        :param Z: 原子番号。
 769        :type Z: float
 770        :param n: 主量子数。
 771        :type n: int
 772        :param l: 方位量子数。
 773        :type l: int
 774        :param m: 磁気量子数。
 775        :type m: int
 776        :param Ne: 占有数。
 777        :type Ne: float
 778        :param Rmin: 積分下限。
 779        :type Rmin: float
 780        :param Rmax: 積分上限。
 781        :type Rmax: float
 782        :param nmaxdiv: 積分の分割上限。
 783        :type nmaxdiv: int
 784        :param eps: 許容誤差。
 785        :type eps: float
 786    戻り値:
 787        :returns: 各エネルギー成分、全エネルギー、最適化されたスケールパラメータのタプル。
 788        :rtype: tuple
 789    """
 790    result = minimize_scalar(
 791        lambda kav: calTotalEnergyOnly(
 792            kav, Z, n, l, m, Ne, Rmin, Rmax, nmaxdiv, eps
 793        ),
 794        bounds=ka_bounds, method='bounded', options={'xatol': tol}
 795    )
 796    if not result.success:
 797        raise RuntimeError(result.message)
 798
 799    kaopt = result.x
 800    T, UeZ, Uee, UXa, Etot = calTotalEnergy(
 801        kaopt, Z, n, l, m, Ne, Rmin, Rmax, nmaxdiv, eps
 802    )
 803    return T, UeZ, Uee, UXa, Etot, kaopt
 804
 805
 806def sweep_Ne(Eanal):
 807    """
 808    概要:
 809        占有数Neを掃引してエネルギーを計算およびプロットします。
 810    引数:
 811        :param Eanal: 比較用の解析的エネルギー値。
 812        :type Eanal: float
 813    戻り値:
 814        :returns: なし
 815        :rtype: None
 816    """
 817    global ka
 818
 819    print("\nNot optimized")
 820    print("Parabolic expansion around Ne=0.5")
 821    _, _, _, _, Fp = calTotalEnergy(ka, Z, n, l, m, 0.5 + hparab,
 822                                    Rmin, Rmax, nmaxdiv, eps)
 823    _, _, _, _, F0 = calTotalEnergy(ka, Z, n, l, m, 0.5,
 824                                    Rmin, Rmax, nmaxdiv, eps)
 825    _, _, _, _, Fm = calTotalEnergy(ka, Z, n, l, m, 0.5 - hparab,
 826                                    Rmin, Rmax, nmaxdiv, eps)
 827    Fp, F0, Fm = [value * HartreeToeV for value in (Fp, F0, Fm)]
 828    a1 = (Fp - Fm) / (2.0 * hparab)
 829    a2 = 0.5 * (Fp - 2.0 * F0 + Fm) / hparab**2
 830    print(f"{ELabel}(Ne) = {F0:.8f} + {a1:.8f}(Ne-0.5)"
 831          f" + {a2:.8f}(Ne-0.5)^2 eV")
 832
 833    xNe, yE1s, yE1sparab = [], [], []
 834    components = [[], [], [], []]
 835    print(f"\n{'ka':>8s} {'Z':>8s} {'Ne':>10s} {'T':>12s} {'U(e-Z)':>12s}"
 836          f" {'U(e-e)':>12s} {XLabel:>12s} {ELabel:>14s} {'parabolic':>14s}")
 837    for Nei in Nearray:
 838        T, UeZ, Uee, UXa, F = calTotalEnergy(
 839            ka, Z, n, l, m, Nei, Rmin, Rmax, nmaxdiv, eps
 840        )
 841        Fparab = F0 + a1 * (Nei - 0.5) + a2 * (Nei - 0.5)**2
 842        values = [T, UeZ, Uee, UXa, F]
 843        values = [value * HartreeToeV for value in values]
 844        print(f"{ka:8.4f} {Z:8.4f} {Nei:10.4g} "
 845              + " ".join(f"{value:12.6f}" for value in values)
 846              + f" {Fparab:14.6f}")
 847        xNe.append(Nei)
 848        yE1s.append(values[-1])
 849        yE1sparab.append(Fparab)
 850        for array, value in zip(components, values[:4]):
 851            array.append(value)
 852
 853    yE1sOpt, yE1sOptparab, ykaOpt = [], [], []
 854    if 'v' in mode:
 855        print("\nOptimized for ka by variational principle")
 856        _, _, _, _, Fp, _ = calOptimizedTotalEnergy(
 857            ka, Z, n, l, m, 0.5 + hparab, Rmin, Rmax, nmaxdiv, eps
 858        )
 859        _, _, _, _, F0opt, _ = calOptimizedTotalEnergy(
 860            ka, Z, n, l, m, 0.5, Rmin, Rmax, nmaxdiv, eps
 861        )
 862        _, _, _, _, Fm, _ = calOptimizedTotalEnergy(
 863            ka, Z, n, l, m, 0.5 - hparab, Rmin, Rmax, nmaxdiv, eps
 864        )
 865        Fp, F0opt, Fm = [value * HartreeToeV for value in (Fp, F0opt, Fm)]
 866        a1opt = (Fp - Fm) / (2.0 * hparab)
 867        a2opt = 0.5 * (Fp - 2.0 * F0opt + Fm) / hparab**2
 868        print(f"{ELabel}(Ne) = {F0opt:.8f} + {a1opt:.8f}(Ne-0.5)"
 869              f" + {a2opt:.8f}(Ne-0.5)^2 eV")
 870
 871        print(f"\n{'ka':>8s} {'Z':>8s} {'Ne':>10s} {'T':>12s} {'U(e-Z)':>12s}"
 872              f" {'U(e-e)':>12s} {XLabel:>12s} {ELabel:>14s} {'parabolic':>14s}")
 873        for Nei in Nearray:
 874            T, UeZ, Uee, UXa, F, kaopt = calOptimizedTotalEnergy(
 875                ka, Z, n, l, m, Nei, Rmin, Rmax, nmaxdiv, eps
 876            )
 877            Fparab = F0opt + a1opt * (Nei - 0.5) + a2opt * (Nei - 0.5)**2
 878            values = [T, UeZ, Uee, UXa, F]
 879            values = [value * HartreeToeV for value in values]
 880            print(f"{kaopt:8.4f} {Z:8.4f} {Nei:10.4g} "
 881                  + " ".join(f"{value:12.6f}" for value in values)
 882                  + f" {Fparab:14.6f}")
 883            yE1sOpt.append(values[-1])
 884            yE1sOptparab.append(Fparab)
 885            ykaOpt.append(kaopt)
 886
 887    if 'g' not in mode:
 888        return
 889
 890    fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))
 891    ax1.plot(xNe, yE1s, 'o-', color='black', label=ELabel + ' (fixed ka)')
 892    ax1.plot(xNe, yE1sparab, '--', color='black', linewidth=0.8,
 893             label=ELabel + ' (quadratic near 0.5)')
 894    if 'v' in mode:
 895        ax1.plot(xNe, yE1sOpt, 'o-', color='red', label=ELabel + ' (optimized)')
 896        ax1.plot(xNe, yE1sOptparab, '--', color='red', linewidth=0.8,
 897                 label=ELabel + ' (optimized quadratic)')
 898
 899    if 'e' in mode:
 900        ax1.plot(xNe, np.asarray(xNe) * Eanal, ':', color='blue',
 901                 label='noninteracting H-like: Ne E1s')
 902    else:
 903        ax1.axhline(Eanal, color='blue', linestyle=':',
 904                    label='noninteracting H-like E1s')
 905    ax1.axvline(0.5, color='gray', linestyle='--', label='Ne=0.5')
 906    ax1.set_xlabel('Ne')
 907    ax1.set_ylabel(ELabel + ' (eV)')
 908    ax1.legend(fontsize=8)
 909
 910    if 'v' in mode:
 911        ax2.plot(xNe, ykaOpt, 'o-', color='black', label='optimized ka')
 912    ax2.axhline(1.0, color='red', linestyle='--', label='ka=1')
 913    ax2.axvline(0.5, color='gray', linestyle='--')
 914    ax2.set_xlabel('Ne')
 915    ax2.set_ylabel('ka')
 916    ax2.legend()
 917    plt.tight_layout()
 918    plt.show()
 919
 920
 921def sweep_ka(Eanal):
 922    """
 923    概要:
 924        スケールパラメータkaを掃引してエネルギーを計算およびプロットします。
 925    引数:
 926        :param Eanal: 比較用の解析的エネルギー値。
 927        :type Eanal: float
 928    戻り値:
 929        :returns: なし
 930        :rtype: None
 931    """
 932    xka, yE1s = [], []
 933    yT, yUeZ, yUee, yUXa = [], [], [], []
 934
 935    print(f"\n{'ka':>8s} {'Z':>8s} {'Ne':>8s} {'T':>12s} {'U(e-Z)':>12s}"
 936          f" {'U(e-e)':>12s} {XLabel:>12s} {ELabel:>14s}")
 937    for kav in kaarray:
 938        T, UeZ, Uee, UXa, F = calTotalEnergy(
 939            kav, Z, n, l, m, Ne, Rmin, Rmax, nmaxdiv, eps
 940        )
 941        values = [value * HartreeToeV for value in (T, UeZ, Uee, UXa, F)]
 942        print(f"{kav:8.4f} {Z:8.4f} {Ne:8.4f} "
 943              + " ".join(f"{value:12.6f}" for value in values))
 944        xka.append(kav)
 945        yT.append(values[0])
 946        yUeZ.append(values[1])
 947        yUee.append(values[2])
 948        yUXa.append(values[3])
 949        yE1s.append(values[4])
 950
 951    if 'v' in mode:
 952        T, UeZ, Uee, UXa, F, kaopt = calOptimizedTotalEnergy(
 953            ka, Z, n, l, m, Ne, Rmin, Rmax, nmaxdiv, eps
 954        )
 955        print(f"\noptimized ka={kaopt:.8f}, {ELabel}={F*HartreeToeV:.8f} eV")
 956
 957    if 'g' not in mode:
 958        return
 959
 960    fig, axes = plt.subplots(2, 3, figsize=(13, 8))
 961    plots = [
 962        (yE1s, ELabel), (yT, 'T'), (yUeZ, 'U(e-Z)'),
 963        (yUee, 'U(e-e)'), (yUXa, XLabel)
 964    ]
 965    for ax, (values, label) in zip(axes.flat, plots):
 966        ax.plot(xka, values, 'o-', color='black')
 967        ax.set_xlabel('ka')
 968        ax.set_ylabel(label + ' (eV)')
 969        ax.grid(alpha=0.25)
 970
 971    Eref = Ne * Eanal if 'e' in mode else Eanal
 972    axes[0, 0].axhline(Eref, color='red', linestyle='--',
 973                       label='noninteracting H-like reference')
 974    axes[0, 0].legend()
 975    axes[1, 2].axis('off')
 976    plt.tight_layout()
 977    plt.show()
 978
 979
 980def debug(Eanal):
 981    """
 982    概要:
 983        デバッグ出力として各種物理量の計算結果や分布をプロットします。
 984    引数:
 985        :param Eanal: 比較用の解析的エネルギー値。
 986        :type Eanal: float
 987    戻り値:
 988        :returns: なし
 989        :rtype: None
 990    """
 991    ka_plot = ka
 992
 993    print(f"\n{'ka':>8s} {'Z':>8s} {'Ne':>8s} {'T':>12s} {'U(e-Z)':>12s}"
 994          f" {'U(e-e)':>12s} {XLabel:>12s} {ELabel:>14s}")
 995    T, UeZ, Uee, UXa, F = calTotalEnergy(
 996        ka_plot, Z, n, l, m, Ne, Rmin, Rmax, nmaxdiv, eps
 997    )
 998    values = [value * HartreeToeV for value in (T, UeZ, Uee, UXa, F)]
 999    print(f"{ka_plot:8.4f} {Z:8.4f} {Ne:8.4f} "
1000          + " ".join(f"{value:12.6f}" for value in values))
1001
1002    if 'v' in mode:
1003        T, UeZ, Uee, UXa, F, ka_plot = calOptimizedTotalEnergy(
1004            ka, Z, n, l, m, Ne, Rmin, Rmax, nmaxdiv, eps
1005        )
1006        values = [value * HartreeToeV for value in (T, UeZ, Uee, UXa, F)]
1007        print("\nOptimized for ka by variational principle")
1008        print(f"{ka_plot:8.4f} {Z:8.4f} {Ne:8.4f} "
1009              + " ".join(f"{value:12.6f}" for value in values))
1010
1011    if 'g' not in mode:
1012        return
1013
1014    build_Qr(ka_plot, Z, n, l, m)
1015    yDensity = [Ne * rho(ka_plot, Z, n, l, m, ri) for ri in r]
1016    yRadial = [pi4 * ri * ri * value for ri, value in zip(r, yDensity)]
1017    ypotZ = [calUZ(ri, Z) for ri in r]
1018    ypotrho = [Ne * calUrho(ri, ka_plot, Z, n, l, m) for ri in r]
1019    if 'h' in mode:
1020        # 同一軌道への Fock 作用は -Ne*V_H(r) となり、Hartree 項を打ち消す。
1021        ypotXa = [-Ne * calUrho(ri, ka_plot, Z, n, l, m) for ri in r]
1022        xpotential_label = 'V_X-HF (on 1s)'
1023    else:
1024        ypotXa = [calLocalUXa(ri, ka_plot, Z, n, l, m, Ne) for ri in r]
1025        xpotential_label = 'V_X-alpha'
1026    ypotEff = [vz + vh + vx for vz, vh, vx in zip(ypotZ, ypotrho, ypotXa)]
1027
1028    fig, axes = plt.subplots(2, 2, figsize=(12, 8))
1029    ax1, ax2, ax3, ax4 = axes.flat
1030    ax1.plot(r, yRr, color='black', label='psi_1s(r)')
1031    ax1.set(xlim=(Rmin, Rmax), xlabel='r (bohr)', ylabel='psi_1s(r)')
1032    ax1.legend()
1033
1034    ax2.plot(r, yRadial, color='black', label='4 pi r^2 n(r)')
1035    ax2.plot(r, Ne * np.asarray(yQr), color='blue', label='N(<r)')
1036    ax2.set(xlim=(Rmin, Rmax), xlabel='r (bohr)', ylabel='electron distribution')
1037    ax2.legend()
1038
1039    ax3.plot(r, ypotZ, color='black', label='V_nuclear')
1040    ax3.plot(r, ypotrho, color='blue', label='V_H')
1041    ax3.plot(r, ypotXa, color='green', label=xpotential_label)
1042    ax3.plot(r, ypotEff, color='red', label='V_effective')
1043    ax3.set(xlim=(Rmin, Rmax), ylim=(-4.0 * ka_plot * Z, ka_plot * Z),
1044            xlabel='r (bohr)', ylabel='potential (Hartree)')
1045    ax3.legend()
1046
1047    ax4.plot(r, yDensity, color='black', label='n(r)')
1048    ax4.set(xlim=(Rmin, Rmax), xlabel='r (bohr)', ylabel='density')
1049    ax4.legend()
1050    plt.tight_layout()
1051    plt.show()
1052
1053
1054def main():
1055    """
1056    概要:
1057        メイン処理を実行します。
1058    戻り値:
1059        :returns: なし
1060        :rtype: None
1061    """
1062    global r
1063
1064    updatevars()
1065    # 表示用グリッドは宣言した Rmax までとする。以前は nR+100 点を
1066    # 作っており、表示上の Rmax と実データ範囲が一致していなかった。
1067    r = np.linspace(Rmin, Rmax, nR)
1068
1069    print(f"\nmode: {mode}")
1070    print(f"Orbital: ka={ka}, Z={Z}, n={n}, l={l}, m={m}")
1071    print(f"Ne={Ne}, Rmax={Rmax}")
1072    print(f"Rmax estimate for epsR={epsR}: {-log(epsR)/(Z*ka):.6f} bohr")
1073
1074    Tanal = calTanal(Z, ka)
1075    Uanal = calUanal(Z, ka)
1076    Etrial = Tanal + Uanal
1077    Eanal = -0.5 * Z**2 * HartreeToeV
1078    print("\nAnalytical values for the trial orbital")
1079    print(f"T={Tanal:.8f} eV, U={Uanal:.8f} eV, E={Etrial:.8f} eV")
1080    print(f"Exact H-like 1s energy={Eanal:.8f} eV")
1081
1082    norm, err = integrate.quad(
1083        lambda rv: pi4 * rv * rv * rho(ka, Z, n, l, m, rv),
1084        Rmin, Rmax, limit=nmaxdiv, epsrel=eps
1085    )
1086    print(f"Normalization integral={norm:.12f}")
1087
1088    if 'd' in mode:
1089        debug(Eanal)
1090    if 'k' in mode:
1091        sweep_ka(Eanal)
1092    if 'n' in mode:
1093        sweep_Ne(Eanal)
1094
1095
1096if __name__ == '__main__':
1097    main()