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

plot_wf.py をダウンロード

plot_wf.py
plot_wf.py
   1"""
   2概要:
   3水素原子の波動関数プロットスクリプトです。
   4このスクリプトは、水素原子の電子の波動関数、その絶対値、位相、確率密度分布などを様々な形式で可視化します。
   5コマンドライン引数でプロットモードと関数タイプを指定し、静的プロット、アニメーション、等値面、3D散布図など多様な表現で波動関数を分析することができます。
   6
   7詳細説明:
   8本スクリプトは以下の主要な機能を提供します。
   9rplotは球面調和関数の実部、虚部、絶対値、絶対値の二乗を3D表面としてプロットします。
  10ranimはrplotの3D表面プロットをアニメーション化します。
  11dotとdotcは波動関数の確率密度に比例した3D散布図をプロットし位相による色分けを行います。
  12dotanimはdotプロットをアニメーション化します。
  13iso3dとiso3danimは波動関数の等値面を3Dでプロットしアニメーション化も行います。
  14Rnlは動径波動関数と動径確率密度分布を2Dでプロットします。
  15YlmとPhiは球面調和関数の角度依存部分を2Dでプロットします。
  16normalizeは波動関数の正規化を数値的に検証します。
  17torus、isosurface3d、contour3d、3dMC_animationはその他の汎用的な3Dプロットやアニメーションを提供します。
  18
  19利用可能な関数タイプの指定について。
  201s、2s、2px、3dxyなどの軌道指定が可能です。
  21Rnl、Ylm、Theta、Phi、normalizeなどの波動関数コンポーネントが指定可能です。
  22cは複素数、rは実部、iは虚部、aは絶対値、a2は絶対値の2乗の表示タイプとなります。
  23
  24関連リンク:
  25元記事 https://zenn.dev/shittoku_xxx/articles/13afd6fdfac44e
  26"""
  27
  28import sys
  29import argparse
  30import numpy as np
  31from numpy import abs, angle, exp, sqrt, cos, sin, arccos, arctan2, pi, min, max
  32from scipy.integrate import quad
  33from scipy.constants import physical_constants
  34from scipy.special import sph_harm, lpmv, assoc_laguerre
  35
  36import matplotlib
  37import matplotlib.pyplot as plt
  38from matplotlib import cm
  39from matplotlib.animation import FuncAnimation
  40from matplotlib.colors import LightSource, Normalize, LinearSegmentedColormap
  41
  42import tkWavefunction_H as wf
  43import tklib.tkgraphic.tkPlot3d as plt3d
  44
  45
  46a0 = physical_constants['Bohr radius'][0] * 1e10  # オングストローム単位に変換
  47pi = np.pi
  48
  49
  50mode = 'rplot'
  51functype = '2px'
  52
  53# for Monte Carlo sampling
  54nsamples = 30000
  55
  56figsize = (12, 10)
  57fontsize = 16
  58
  59
  60nbins = 100
  61colors_wf    = [(0, 0, 1), (0, 1, 0), (1, 0, 0)]  # 緑、青、赤
  62colors_phase = [(1, 0, 0), (0, 1, 0), (0, 0, 1), (1, 1, 0), (1, 0, 0)]  # 赤, 緑, 青, 黄, 赤
  63cmap_name_wf    = 'custom cmap for wavefunction'
  64cmap_name_phase = 'custom cmap for phase'
  65
  66
  67class CustomArgumentParser(argparse.ArgumentParser):
  68    """
  69    概要:
  70        argparse.ArgumentParser を拡張し、カスタムのヘルプメッセージを提供するクラス。
  71
  72    詳細説明:
  73        標準のヘルプ出力に加えて、一般的な使用方法と具体的な使用例を追記します。
  74    """
  75    def print_help(self, *args, **kwargs):
  76        """
  77        概要:
  78            カスタムのヘルプメッセージを出力します。
  79
  80        詳細説明:
  81            親クラスの print_help メソッドの実行前後に、
  82            本スクリプトの一般的な使用法と具体的な使用例をコンソールに表示します。
  83
  84        引数:
  85            :param args: argparse.ArgumentParser.print_help に渡される可変長引数。
  86            :type args: tuple
  87            :param kwargs: argparse.ArgumentParser.print_help に渡されるキーワード引数。
  88            :type kwargs: dict
  89
  90        戻り値:
  91            :returns: None
  92        """
  93        print()
  94        print("General usage:")
  95        super().print_help(*args, **kwargs)
  96        print()
  97        print("Examples:")
  98        print(r"usage: python .\plot_wf.py [rplot|ranim|dot|dotc|dotanim|iso3d|iso3danim|rsurface] [100r|2pxa etc]")
  99        print(r"usage: python .\plot_wf.py [Rnl|Ylm|Theta|Phi|normalize]")
 100        print(r"usage: python .\plot_wf.py [3dMC_animation|contour3d|torus]")
 101
 102def usage():
 103    """
 104    概要:
 105        コマンドライン引数のヘルプメッセージを表示します。
 106
 107    詳細説明:
 108        CustomArgumentParser クラスの print_help メソッドを呼び出し、
 109        プログラムの使用法と例をコンソールに出力します。
 110
 111    戻り値:
 112        :returns: None
 113    """
 114    parser.print_help()
 115
 116def torus(theta: np.ndarray, phi: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
 117    """
 118    概要:
 119        トーラスの3D座標を計算します。
 120
 121    詳細説明:
 122        トーラスの大半径Rと小半径rを用いて、与えられた角度からX, Y, Z座標を計算します。
 123
 124    引数:
 125        :param theta: トーラスの縦方向の角度 (0から2π) を表すNumPy配列。
 126        :type theta: numpy.ndarray
 127        :param phi: トーラスの横方向の角度 (0から2π) を表すNumPy配列。
 128        :type phi: numpy.ndarray
 129
 130    戻り値:
 131        :returns: X, Y, Z座標のタプル。各要素はNumPy配列。
 132        :rtype: tuple
 133    """
 134# トーラスのパラメータ
 135    R = 3  # 大半径
 136    r = 1  # 小半径
 137
 138    X = (R + r * np.cos(theta)) * np.cos(phi)
 139    Y = (R + r * np.cos(theta)) * np.sin(phi)
 140    Z = r * np.sin(theta)
 141    return X, Y, Z
 142
 143def sphere(X: np.ndarray, Y: np.ndarray, Z: np.ndarray) -> np.ndarray:
 144    """
 145    概要:
 146        3次元空間における点 (X, Y, Z) の半径の二乗を計算します。
 147
 148    詳細説明:
 149        各座標成分の二乗和 X^2 + Y^2 + Z^2 を計算し、
 150        単位球や一般的な球の等値面を定義する際に利用できます。
 151
 152    引数:
 153        :param X: X座標のNumPy配列。
 154        :type X: numpy.ndarray
 155        :param Y: Y座標のNumPy配列。
 156        :type Y: numpy.ndarray
 157        :param Z: Z座標のNumPy配列。
 158        :type Z: numpy.ndarray
 159
 160    戻り値:
 161        :returns: 各点における X^2 + Y^2 + Z^2 の値。NumPy配列。
 162        :rtype: numpy.ndarray
 163    """
 164    return (X**2 + Y**2 + Z**2)  # 単位球: x^2 + y^2 + z^2 = r^2
 165
 166def exp_r2(X: np.ndarray, Y: np.ndarray, Z: np.ndarray) -> np.ndarray:
 167    """
 168    概要:
 169        exp(-r^2) の値を計算します。
 170
 171    詳細説明:
 172        3次元空間における点 (X, Y, Z) から原点までの距離rの二乗を用いて、
 173        ガウス型の減衰関数 exp(-(X^2 + Y^2 + Z^2)) を計算します。
 174
 175    引数:
 176        :param X: X座標のNumPy配列。
 177        :type X: numpy.ndarray
 178        :param Y: Y座標のNumPy配列。
 179        :type Y: numpy.ndarray
 180        :param Z: Z座標のNumPy配列。
 181        :type Z: numpy.ndarray
 182
 183    戻り値:
 184        :returns: 各点における exp(-(X^2 + Y^2 + Z^2)) の値。NumPy配列。
 185        :rtype: numpy.ndarray
 186    """
 187    r2 = X**2 + Y**2 + Z**2
 188    return np.exp(-r2)
 189
 190
 191def plot_torus() -> matplotlib.pyplot:
 192    """
 193    概要:
 194        トーラスの3D表面プロットを作成します。
 195
 196    詳細説明:
 197        torus 関数を用いて座標を生成し、カスタムカラーマップで色付けされた
 198        トーラスの表面をMatplotlibの3Dプロットで描画します。
 199
 200    戻り値:
 201        :returns: プロットが描画された matplotlib.pyplot モジュール。
 202        :rtype: matplotlib.pyplot
 203    """
 204# パラメトリック変数
 205    theta = np.linspace(0, 2 * np.pi, 100)
 206    phi = np.linspace(0, 2 * np.pi, 100)
 207    theta, phi = np.meshgrid(theta, phi)
 208
 209    X, Y, Z = torus(theta, phi)
 210
 211# カスタムカラーマップの定義
 212    colors = [(1, 0.5, 0.5), (0, 1, 0), (1, 0.5, 0.5)]  # 薄い赤から青、符水赤へのグラデーション
 213    color_map = plt3d.make_color_map(phi, colors, cmap_name = 'custom_cmap', nbins = nbins)
 214
 215# プロット
 216    fig = plt.figure()
 217    ax = fig.add_subplot(111, projection='3d')
 218
 219    plt3d.plot_surface3d(ax, X, Y, Z, facecolors = color_map, edgecolor = 'none', alpha = 0.7, shade = True)
 220
 221    return plt
 222
 223def plot_isosurface3d() -> matplotlib.pyplot:
 224    """
 225    概要:
 226        定義された関数に基づき、複数の等値面を3Dでプロットします。
 227
 228    詳細説明:
 229        3Dグリッド上でスカラー場 f (グローバル変数) を計算し、
 230        指定されたレベルで等値面を抽出し、Matplotlibの3Dプロットで描画します。
 231
 232    戻り値:
 233        :returns: プロットが描画された matplotlib.pyplot モジュール。
 234        :rtype: matplotlib.pyplot
 235    """
 236# 3次元グリッドを作成
 237    x = np.linspace(-1.2, 1.2, 40)
 238    y = np.linspace(-1.2, 1.2, 40)
 239    z = np.linspace(-1.2, 1.2, 40)
 240    X, Y, Z = np.meshgrid(x, y, z, indexing='ij')
 241
 242# 3Dスカラー場: 球の等値面 (中心を原点にする)
 243    F = f(X, Y, Z)
 244
 245# 等値面のレベル
 246    levels = [0.1, 0.2, 0.3]
 247    colors = ['cyan', 'magenta', 'yellow']  # 等値面の色
 248
 249# 3D プロット
 250    fig = plt.figure(figsize=(8, 8))
 251    ax = fig.add_subplot(111, projection='3d')
 252
 253    dx, dy, dz = x[1] - x[0], y[1] - y[0], z[1] - z[0]
 254    plt3d.plot_isosurface3d(ax, X, Y, Z, F, levels = levels, origin = [x.min(), y.min(), z.min()], spacing = [dx, dy, dz],
 255            colors = colors, edgecolor = 'k', alpha = 0.3, linewidth = 0.1)
 256
 257    return plt
 258
 259def plot_contour3d() -> matplotlib.pyplot:
 260    """
 261    概要:
 262        exp(-r^2) 関数のスライスされた等高線を3Dでプロットします。
 263
 264    詳細説明:
 265        3Dグリッド上で exp_r2 関数を計算し、特定のZ座標でのスライスにおける
 266        等高線 (F[:, :, 50]) をMatplotlibの3Dプロットに描画します。
 267
 268    戻り値:
 269        :returns: プロットが描画された matplotlib.pyplot モジュール。
 270        :rtype: matplotlib.pyplot
 271    """
 272    x = np.linspace(-5, 5, 100)
 273    y = np.linspace(-5, 5, 100)
 274    z = np.linspace(-5, 5, 100)
 275    X, Y, Z = np.meshgrid(x, y, z)
 276    F = exp_r2(X, Y, Z)
 277
 278    fig = plt.figure()
 279    ax = fig.add_subplot(111, projection='3d')
 280
 281    plt3d.contour3d(ax, X[:, :, 50], Y[:, :, 50], F[:, :, 50], nbins = nbins, cmap = cm.viridis)
 282
 283    return plt
 284
 285def plot_3dMC_animation() -> None:
 286    """
 287    概要:
 288        モンテカルロサンプリングを用いた3Dアニメーションをプロットします。
 289
 290    詳細説明:
 291        確率分布 abs(x) * 4 * pi * r^3 * exp(-r^2) に基づいてランダムな点を3D空間に順次追加し、
 292        その分布の変化をアニメーションとして表示します。
 293        点のX座標の符号に基づいて赤または青に色分けされます。
 294        アニメーションはユーザーがEnterキーを押すまで継続します。
 295
 296    戻り値:
 297        :returns: None
 298    """
 299# サンプル点の総数と一度に追加する点の数
 300    num_points = 100000
 301    nadd = 100
 302
 303# アニメーションの設定
 304    fig = plt.figure()
 305    ax = fig.add_subplot(111, projection='3d')
 306    sc = ax.scatter([], [], [], marker='o', s=1, alpha=0.5)
 307
 308# 初期化関数
 309    def init():
 310        sc._offsets3d = ([], [], [])
 311        return sc,
 312
 313# 更新関数
 314    def update(frame):
 315        new_points = nadd  # 追加する新しい点の数
 316        u = np.random.rand(new_points)
 317        r = np.cbrt(-np.log(1 - u))  # 立方根で変換
 318
 319        phi = np.random.rand(new_points) * 2.0 * np.pi
 320        cos_theta = np.random.rand(new_points) * 2 - 1  # cos(θ) を一様分布させる
 321        theta = np.arccos(cos_theta)
 322
 323        x = r * np.sin(theta) * np.cos(phi)
 324        y = r * np.sin(theta) * np.sin(phi)
 325        z = r * np.cos(theta)
 326
 327    # x, y, z の範囲を -10 から 10 にスケーリング
 328        x = (x / np.max(np.abs(x))) * 10
 329        y = (y / np.max(np.abs(y))) * 10
 330        z = (z / np.max(np.abs(z))) * 10
 331
 332    # 分布関数 abs(x) * 4π r^3 exp(-r**2)
 333        weights = np.abs(x) * 4 * np.pi * r**3 * np.exp(-r**2)
 334        weights /= np.sum(weights)  # 正規化
 335
 336        indices = np.random.choice(np.arange(new_points), size=new_points, p=weights)
 337        x_sampled = x[indices]
 338        y_sampled = y[indices]
 339        z_sampled = z[indices]
 340
 341        offsets = np.array(sc._offsets3d)
 342        offsets = np.vstack([offsets.T, np.column_stack((x_sampled, y_sampled, z_sampled))]).T
 343        sc._offsets3d = (offsets[0], offsets[1], offsets[2])
 344
 345    # 色の設定
 346        color_map = np.where(offsets[0] > 0, 'red', 'blue')  # x > 0 を赤、x < 0 を青
 347        sc.set_color(color_map)
 348
 349        ax.set_xlabel('X')
 350        ax.set_ylabel('Y')
 351        ax.set_zlabel('Z')
 352
 353    # 軸の範囲を設定
 354        ax.set_xlim([-10, 10])
 355        ax.set_ylim([-10, 10])
 356        ax.set_zlim([-10, 10])
 357
 358    # タイトルに点の総数を表示
 359        ax.set_title(f'Total points: {len(offsets[0])}')
 360
 361        return sc,
 362
 363# アニメーションの作成
 364    ani = FuncAnimation(fig, update, frames=num_points // nadd, init_func=init, blit=False, repeat=False)
 365
 366    if fplot: plt.pause(0.1)
 367
 368#ani.save('3dMC_animation.gif', writer='imagemagick')
 369
 370    input("Press ENTER to terminate>>")
 371
 372    return None
 373
 374def plot_Phi() -> matplotlib.pyplot:
 375    """
 376    概要:
 377        球面調和関数の角度依存部分 exp(j*m*phi) の実部と虚部をプロットします。
 378
 379    詳細説明:
 380        さまざまな磁気量子数 m (0から4) に対して、角度 phi に応じた
 381        exp(j*m*phi) の実部と虚部の変化を2つのサブプロットに分けてグラフ化します。
 382
 383    戻り値:
 384        :returns: プロットが描画された matplotlib.pyplot モジュール。
 385        :rtype: matplotlib.pyplot
 386    """
 387    N = 101
 388    phi0, phi1 = 0.0, 2.0 * pi
 389    phi = np.linspace(phi0, phi1, N)
 390
 391    flist = []
 392    for m in range(0, 5):
 393        f = wf.Ylm_phi(m, phi)
 394        flist.append([m, f.real, f.imag])
 395
 396    fig, axes = plt.subplots(2, 1, figsize = (10, 10))
 397 
 398    phi_deg = 180.0 / pi * phi
 399    for inf in flist:
 400        axes[0].plot(phi_deg, inf[1], label = f"m={inf[0]},real")
 401        axes[1].plot(phi_deg, inf[2], label = f"m={inf[0]},imag")
 402    axes[0].set_xlabel('phi')
 403    axes[0].set_ylabel('exp(j*m*phi),real')
 404    axes[0].legend()
 405
 406    axes[1].set_xlabel('phi')
 407    axes[1].set_ylabel('exp(j*m*phi),imag')
 408    axes[1].legend()
 409    
 410    return plt
 411
 412
 413def plot_Ylm() -> matplotlib.pyplot:
 414    """
 415    概要:
 416        球面調和関数の角度依存部分 Ylm_theta(l, m, theta) をプロットします。
 417
 418    詳細説明:
 419        さまざまな方位量子数 l (0から2) と磁気量子数 m に対して、
 420        角度 theta に応じた Ylm_theta の変化をグラフに描画します。
 421
 422    戻り値:
 423        :returns: プロットが描画された matplotlib.pyplot モジュール。
 424        :rtype: matplotlib.pyplot
 425    """
 426    N = 101
 427    theta0, theta1 = 0.0, pi
 428    theta = np.linspace(theta0, theta1, N)
 429
 430    flist = []
 431    for l in range(0, 3):
 432        for m in range(-l, l + 1):
 433            f = wf.Ylm_theta(l, m, theta)
 434            flist.append([l, m, f])
 435
 436    fig, ax = plt.subplots(1, 1, figsize = (10, 10))
 437 
 438    theta_deg = 180.0 / pi * theta
 439    for inf in flist:
 440        ax.plot(theta_deg, inf[2], label = f"l,m={inf[0]},{inf[1]}")
 441    ax.set_title('Spherical harmonic (theta dependence)')
 442    ax.set_xlabel('theta')
 443    ax.set_ylabel('Ylm')
 444
 445    ax.legend()
 446    
 447    return plt
 448
 449def plot_Rnl() -> matplotlib.pyplot:
 450    """
 451    概要:
 452        水素原子の動径波動関数 Rnl(r) と動径確率密度分布 Pnl(r) をプロットします。
 453
 454    詳細説明:
 455        主量子数 n と方位量子数 l の異なる組み合わせ (1s, 2s, 2p, ..., 4f) について、
 456        動径波動関数 Rnl(r) と r^2 * abs(Rnl(r))^2 (動径確率密度分布) を計算し、
 457        それぞれを9つのサブプロットを持つ2つの図に描画します。
 458        fplot および fsave 引数に応じて表示または保存されます。
 459
 460    戻り値:
 461        :returns: プロットが描画された matplotlib.pyplot モジュール。
 462        :rtype: matplotlib.pyplot
 463    """
 464    Nr = 101
 465    rmin = 0.0
 466    rmax = 40.0
 467
 468    a00 = 1.0
 469    r = np.linspace(rmin, rmax, Nr)
 470    f1list = []
 471    f2list = []
 472    P1list = []
 473    P2list = []
 474    for inf in [['1s', 1, 0], ['2s', 2, 0], ['2p', 2, 1], ['3s', 3, 0], ['3p', 3, 1], ['3d', 3, 2], 
 475                ['4s', 4, 0], ['4p', 4, 1], ['4d', 4, 2], ['4f', 4, 3]]:
 476        f1 = wf.Rnl(r, inf[1], inf[2])
 477        f2 = wf.Rnl_if(r, inf[1], inf[2])
 478        f1list.append([inf[0], inf[1], inf[2], f1])
 479        f2list.append([inf[0], inf[1], inf[2], f2])
 480        if f1 is not None:
 481            P1list.append([inf[0], inf[1], inf[2], r**2 * f1**2])
 482        else:
 483            P1list.append([inf[0], inf[1], inf[2], None])
 484        if f2 is not None:
 485            P2list.append([inf[0], inf[1], inf[2], r**2 * f2**2])
 486        else:
 487            P2list.append([inf[0], inf[1], inf[2], None])
 488
 489#plot
 490#   plt.rcParams["font.size"] = 18
 491    fig1, ax1 = plt.subplots(3, 3, figsize = (10, 10))
 492    ax1 = ax1.flatten()
 493    fig1.subplots_adjust(hspace=0.4, wspace=0.3)
 494    fig1.suptitle('$R_{nl}(r)$: Radial wave function')
 495
 496    for ax, inf1, inf2 in zip(ax1, f1list, f2list):
 497        if inf1[3] is not None:
 498            ax.plot(r, inf1[3], label='Module')
 499        if inf2[3] is not None:
 500            ax.plot(r, inf2[3], label='explicit', linestyle = 'None', marker='o', markersize = 2.0)
 501        ax.set_title(inf1[0])
 502        ax.grid()
 503        ax.legend()
 504        ax.set_xlabel('r/$a_0$')
 505        ax.set_ylabel('$R_{nl}(r)$')
 506
 507    if fsave: plt.savefig('plot_wf_Rnl.png')
 508
 509#動径確率密度分布の描画
 510    fig2, ax2 = plt.subplots(3, 3, figsize = (10, 10))
 511    ax2 = ax2.flatten()
 512    fig2.subplots_adjust(hspace=0.4, wspace=0.3)
 513    fig2.suptitle('$P_{nl}(r)$: Radial probability density distribution')
 514
 515    for ax, inf1, inf2 in zip(ax2, P1list, P2list):
 516        if inf1[3] is not None:
 517            ax.plot(r, inf1[3], label='Module')
 518        if inf2[3] is not None:
 519            ax.plot(r, inf2[3], label='explicit', linestyle = 'None', marker='o', markersize = 2.0)
 520        ax.set_title(inf1[0])
 521        ax.grid()
 522        ax.legend()
 523        ax.set_xlabel('r/$a_0$')
 524        ax.set_ylabel('$P_{nl}(r)$')
 525
 526    if fsave: plt.savefig('plot_wf_Pnl.png')
 527
 528    return plt
 529
 530def plot_rplot() -> matplotlib.pyplot:
 531    """
 532    概要:
 533        指定された水素原子の波動関数 (球面調和関数) の3D表面プロットを作成します。
 534
 535    詳細説明:
 536        グローバル変数 nlm で指定された量子数 n, l, m と orb_type に基づいて
 537        波動関数を計算し、その実部、虚部、絶対値、または絶対値の2乗を3D空間にプロットします。
 538        プロットの色は波動関数の値または位相に基づいてカスタムカラーマップで色分けされます。
 539        XY, YZ, ZX平面に波動関数の2D等高線も重ねて描画されます。
 540        波動関数のエネルギー En も表示されます。
 541
 542    戻り値:
 543        :returns: プロットが描画された matplotlib.pyplot モジュール。
 544        :rtype: matplotlib.pyplot
 545    """
 546    n, l, m = nlm
 547    orb_name = wf.get_orb_name(n, l, m)
 548    n, l, m = wf.get_qnumbers(n, l, m)
 549
 550    print()
 551    print(f"Plot R(theta, phi) for {orb_name}  n, l, m=({n}, {l}, {m})")
 552    print(f"  orbital type: {orb_type}")
 553    En = wf.En(n)
 554    print(f"  En={En:.6g} eV")
 555
 556    theta = np.linspace(0, pi, 101)
 557    phi   = np.linspace(0, 2.0 * pi, 101)
 558    Theta2d, Phi2d = np.meshgrid(theta, phi)
 559#    r  = wf.Ylm_real(Theta2d, Phi2d, l, m)
 560    f = wf.Ylm(Theta2d, Phi2d, l, m)
 561    r, phase = wf.get_by_type(f, orb_type)
 562    nfigures = 2
 563    if orb_type == 'a':
 564        title = r"|$\psi$|"
 565    elif orb_type == 'a2':
 566        title = r"|$\psi$|$^2$"
 567    elif orb_type == 'r':
 568        title = r"$\psi_r$"
 569    elif orb_type == 'i':
 570        title = r"$\psi_i$"
 571
 572    ra = abs(r)
 573    z   = ra * cos(Theta2d)
 574    rxy = ra * sin(Theta2d)
 575    x   = rxy * cos(Phi2d)
 576    y   = rxy * sin(Phi2d)
 577
 578    alpha = 0.7
 579
 580# カスタムカラーマップの作成
 581    color_list = colors_wf
 582    cmap_name = cmap_name_wf
 583    custom_cmap = LinearSegmentedColormap.from_list(cmap_name, color_list, N = nbins)
 584# rの値にcmapを対応させる
 585    norm = Normalize(vmin = min(r), vmax = max(r))
 586    face_colors = custom_cmap(norm(r))
 587
 588#    ax = fig.add_subplot(111, projection='3d')
 589    fig, axes = plt.subplots(1, nfigures, figsize = (8 * nfigures, 10), subplot_kw = {'projection': '3d'})
 590    if nfigures == 1:
 591        ax = axes
 592    else:
 593        ax = axes[0]
 594        ax2 = axes[1]
 595
 596    if phase is None:
 597        options = {"facecolors": face_colors, "edgecolor": None}
 598    else:
 599        phase_min = np.min(phase)
 600        phase_max = np.max(phase)
 601        if phase_min == phase_max:
 602            phase_min -= 0.1
 603            phase_max += 0.1
 604        normalized_phase = (phase - phase_min) / (phase_max - phase_min)
 605
 606# カスタムカラーマップを定義
 607        colors = colors_phase
 608        cmap_name = cmap_name_phase
 609        custom_cmap = LinearSegmentedColormap.from_list(cmap_name, colors, N = nbins)
 610        facecolors = custom_cmap(normalized_phase)
 611
 612        options = {"facecolors": facecolors, "edgecolor": None}
 613
 614    plt3d.plot_surface3d(ax, x, y, z, **options, alpha = alpha, shade = False,
 615                    xlabel = 'x', ylabel = 'y', zlabel = 'z')
 616
 617    def contour_func(x, y, z):
 618        f = wf.Ylm_xyz(x, y, z, l, m)
 619        r, phase = wf.get_by_type(f, orb_type)
 620        return r
 621
 622    maxx = plt3d.get_max_xyz(x, y, z)
 623    plt3d.plot_contours_xyz_by_func(ax, contour_func, minx = -maxx, maxx = maxx, nmesh = 100,
 624                            posx = 0.1, posy = 0.1, posz = 0.1,
 625                            offsetx = -maxx, offsety = maxx, offsetz = -maxx, 
 626                            cmap = custom_cmap, levels = 20, alpha = 0.3)
 627
 628    plt3d.set_cubic_scale(ax, maxx)
 629    ax.set_title(title)
 630
 631    if phase is None:
 632        cbar = plt3d.show_color_bar(fig, ax, scale = z, cmap = custom_cmap, shrink = 0.5, aspect = 10.0)
 633        if orb_type == 'i':
 634            cbar.set_label(r'$\psi_i$')
 635        else:
 636            cbar.set_label(r'$\psi_r$')
 637    else:
 638        vmin = phase_min * 180.0 / pi
 639        vmax = phase_max * 180.0 / pi
 640        scmap = plt.cm.ScalarMappable(cmap = custom_cmap, norm = plt.Normalize(vmin = vmin, vmax = vmax))
 641        scmap.set_array(normalized_phase)
 642        cbar = plt.colorbar(scmap, ax=ax, shrink=0.5, aspect=10.0)
 643        cbar.set_label('phase')
 644
 645    if phase is not None and nfigures > 1:
 646        ra = abs(phase)
 647        z   = ra * cos(Theta2d)
 648        rxy = ra * sin(Theta2d)
 649        x   = rxy * cos(Phi2d)
 650        y   = rxy * sin(Phi2d)
 651        plt3d.plot_surface3d(ax2, x * 180.0/pi, y * 180.0/pi, z * 180.0/pi, **options, alpha = alpha, shade = False,
 652                    xlabel = 'x', ylabel = 'y', zlabel = 'z')
 653#        plt3d.set_cubic_scale(ax2, maxx)
 654        ax2.set_title("phase")
 655
 656    return plt
 657
 658def plot_ranim() -> None:
 659    """
 660    概要:
 661        水素原子の波動関数の3D表面プロットをアニメーションとして表示します。
 662
 663    詳細説明:
 664        plot_rplot と同様に、グローバル変数 nlm と orb_type に基づいて
 665        波動関数を計算し、時間依存性 (phase_m パラメータ) を加えてアニメーション化します。
 666        波動関数の位相変化を表現し、GIFファイルとして保存することも可能です。
 667        アニメーションはユーザーがEnterキーを押すまで継続します。
 668
 669    戻り値:
 670        :returns: None
 671    """
 672    n, l, m = nlm
 673    orb_name = wf.get_orb_name(n, l, m)
 674    n, l, m = wf.get_qnumbers(n, l, m)
 675
 676    print()
 677    print(f"Animation of R(theta, phi)=Ylm(theta, phi) for {orb_name}  n, l, m=({n}, {l}, {m})")
 678    print(f"  orbital type: {orb_type}")
 679    En = wf.En(n)
 680    print(f"  En={En:.6g} eV")
 681
 682    theta = np.linspace(0, pi, 101)
 683    phi   = np.linspace(0, 2.0 * pi, 101)
 684    Theta2d, Phi2d = np.meshgrid(theta, phi)
 685#    r  = wf.Ylm_real(Theta2d, Phi2d, l, m)
 686    f = wf.Ylm(Theta2d, Phi2d, l, m)
 687    r, phase = wf.get_by_type(f, orb_type)
 688    nfigures = 1
 689    if orb_type == 'a':
 690        title = rf"|$\psi$| ({n}{l}{m})"
 691    elif orb_type == 'a2':
 692        title = rf"|$\psi$|$^2$ ({n}{l}{m})"
 693    elif orb_type == 'r':
 694        title = rf"$\psi_r$ ({n}{l}{m})"
 695    elif orb_type == 'i':
 696        title = rf"$\psi_i$ ({n}{l}{m})"
 697
 698    ra = abs(r)
 699    z   = ra * cos(Theta2d)
 700    rxy = ra * sin(Theta2d)
 701    x   = rxy * cos(Phi2d)
 702    y   = rxy * sin(Phi2d)
 703
 704    alpha = 0.7
 705
 706    fig, ax = plt.subplots(1, nfigures, figsize = (8, 8), subplot_kw = {'projection': '3d'})
 707
 708    phase_min = -pi
 709    phase_max =  pi
 710    normalized_phase = (phase - phase_min) / (phase_max - phase_min)
 711
 712# カスタムカラーマップを定義
 713    colors = colors_phase
 714    cmap_name = cmap_name_phase
 715    custom_cmap = LinearSegmentedColormap.from_list(cmap_name, colors, N = nbins)
 716    facecolors = custom_cmap(normalized_phase)
 717
 718    options = {"facecolors": facecolors, "edgecolor": None}
 719
 720    plt3d.plot_surface3d(ax, x, y, z, **options, alpha = alpha, shade = False,
 721                    xlabel = 'x', ylabel = 'y', zlabel = 'z')
 722
 723    maxx = plt3d.get_max_xyz(x, y, z)
 724    plt3d.set_cubic_scale(ax, maxx)
 725    ax.set_title(title)
 726
 727    vmin = -180.0
 728    vmax =  180.0
 729    scmap = plt.cm.ScalarMappable(cmap = custom_cmap, norm = plt.Normalize(vmin = vmin, vmax = vmax))
 730    scmap.set_array(normalized_phase)
 731    cbar = plt.colorbar(scmap, ax = ax, shrink = 0.5, aspect = 10.0)
 732    cbar.set_label('phase')
 733
 734    nmaxiter = 100
 735    wait = 5 # ms
 736    ani = None
 737    window_closed = False
 738    def update_animation(frame):
 739        nonlocal window_closed, ani
 740
 741        if window_closed :
 742            if ani.event_source: ani.event_source.stop()
 743            return ax
 744
 745        if frame % 10 == 0: print(f"frame: {frame}/{nmaxiter}")
 746
 747        ax.cla()  # 軸の設定を保持するために全体をクリア
 748
 749        f = wf.Ylm(Theta2d, Phi2d, l, m, phase_m = frame * 0.1)
 750        r, phase = wf.get_by_type(f, orb_type)
 751        ra = abs(r)
 752        z   = ra * cos(Theta2d)
 753        rxy = ra * sin(Theta2d)
 754        x   = rxy * cos(Phi2d)
 755        y   = rxy * sin(Phi2d)
 756
 757        phase_min = -pi
 758        phase_max =  pi
 759        normalized_phase = (phase - phase_min) / (phase_max - phase_min)
 760        custom_cmap = LinearSegmentedColormap.from_list(cmap_name, colors, N = nbins)
 761        facecolors = custom_cmap(normalized_phase)
 762        options = {"facecolors": facecolors, "edgecolor": None}
 763
 764        plt3d.plot_surface3d(ax, x, y, z, **options, alpha = alpha, shade = False,
 765                    xlabel = 'x', ylabel = 'y', zlabel = 'z')
 766
 767        plt3d.set_cubic_scale(ax, maxx)
 768        ax.set_title(f"{title} frame: {frame}/{nmaxiter}")
 769
 770        if fplot: plt.pause(0.1)
 771
 772#        if frame >= nmaxiter - 1: 
 773#            ani.event_source.stop()
 774#            return ax
 775        
 776        return ax
 777
 778    def on_close(event):
 779        nonlocal window_closed
 780
 781        window_closed = True
 782
 783    fig.canvas.mpl_connect('close_event', on_close)
 784
 785    ani = FuncAnimation(fig, update_animation, frames = nmaxiter, interval = wait)
 786#ani = FuncAnimation(fig, update, frames=nmaxiter, init_func=init, blit=False, repeat=False)
 787
 788    outfile = f'plot_wf_{mode}_{functype}.gif'
 789    if fsave:
 790        print(f"saving to {outfile}")
 791        ani.save(outfile, writer='imagemagick')
 792
 793    if fplot:
 794        input("Press Enter to close the window...")
 795
 796#    plt.show()
 797
 798    return None
 799
 800
 801def plot_rsurface() -> matplotlib.pyplot:
 802    """
 803    概要:
 804        水素原子の動径波動関数の実部を3D表面としてプロットします。
 805
 806    詳細説明:
 807        球面座標系における動径波動関数の実部を計算し、それを3D空間の表面として描画します。
 808        X軸、Y軸、Z軸はそれぞれ直交座標に対応し、色は波動関数の値に基づいて色分けされます。
 809        XY, YZ, ZX平面に波動関数の2D等高線も重ねて描画されます。
 810
 811    戻り値:
 812        :returns: プロットが描画された matplotlib.pyplot モジュール。
 813        :rtype: matplotlib.pyplot
 814    """
 815    n, l, m = nlm
 816    orb_name = wf.get_orb_name(n, l, m)
 817    n, l, m = wf.get_qnumbers(n, l, m)
 818
 819    print()
 820    print(f"Plot R(theta, phi) for {orb_name}  n, l, m=({n}, {l}, {m})")
 821
 822    theta = np.linspace(0, pi, 101)
 823    phi   = np.linspace(0, 2.0 * pi, 101)
 824    Theta2d, Phi2d = np.meshgrid(theta, phi)
 825    r  = wf.Ylm_real(Theta2d, Phi2d, l, m)
 826    ra = abs(r)
 827    z   = ra * cos(Theta2d)
 828    rxy = ra * sin(Theta2d)
 829    x   = rxy * cos(Phi2d)
 830    y   = rxy * sin(Phi2d)
 831
 832    alpha = 0.7
 833
 834
 835# カスタムカラーマップの作成
 836    color_list = colors_wf
 837    cmap_name = cmap_name_wf
 838    custom_cmap = LinearSegmentedColormap.from_list(cmap_name, color_list, N = nbins)
 839# rの値にcmapを対応させる
 840    norm = Normalize(vmin = min(r), vmax = max(r))
 841    face_colors = custom_cmap(norm(r))
 842
 843    fig = plt.figure()
 844    ax = fig.add_subplot(111, projection = '3d')
 845
 846#    options = {"colors": colors}
 847#    options = {"color": color}
 848#    options = {"cmap": cmap, "edgecolor": None}
 849    options = {"facecolors": face_colors, "edgecolor": None}
 850#    options = {"facecolors": colors, "edgecolor": None}
 851    plt3d.plot_surface3d(ax, x, y, r, **options, alpha = alpha, shade = False,
 852                    xlabel = 'x', ylabel = 'y', zlabel = 'z')
 853
 854    maxx = plt3d.get_max_xyz(x, y, z)
 855    plt3d.plot_contours_xyz_by_func(ax, lambda x, y, z: wf.Ylm_xyz_real(x, y, z, l, m), minx = -maxx, maxx = maxx, nmesh = 100,
 856                            posx = 0.1, posy = 0.1, posz = 0.1,
 857                            offsetx = -maxx, offsety = maxx, offsetz = -maxx, 
 858                            cmap = custom_cmap, levels = 20, alpha = 0.3)
 859
 860    plt3d.set_cubic_scale(ax, maxx)
 861
 862    plt3d.show_color_bar(fig, ax, scale = z, cmap = custom_cmap, shrink = 0.5, aspect = 10.0)
 863
 864    return plt
 865
 866
 867def estimate_max_f(func, minx: float = -3, maxx: float = -3, nsamples_estimate: int = 1000) -> float:
 868    """
 869    概要:
 870        3次元空間で定義された関数の絶対値の最大値を推定します。
 871
 872    詳細説明:
 873        指定された範囲内でランダムにサンプリングを行い、
 874        関数の最大値を概算します。これはリジェクションサンプリングの受け入れ率Mを
 875        決定する際に使用されます。
 876
 877    引数:
 878        :param func: 最大値を推定する対象の関数 (3つの引数x, y, zを取る)。
 879        :type func: callable
 880        :param minx: X, Y, Z座標の最小値。
 881        :type minx: float
 882        :param maxx: X, Y, Z座標の最大値。
 883        :type maxx: float
 884        :param nsamples_estimate: 最大値推定のためのサンプル数。
 885        :type nsamples_estimate: int
 886
 887    戻り値:
 888        :returns: 推定された関数の最大値。
 889        :rtype: float
 890    """
 891    x_samples, y_samples, z_samples = np.random.uniform(minx, maxx, (3, nsamples_estimate))
 892    f_vals = func(x_samples, y_samples, z_samples)
 893    maxf = np.max(f_vals)
 894
 895    return maxf
 896
 897def rejection_sampling(func, func2, M: float | None = None,  minx: float = -3, maxx: float = 3, nsamples: int = 10000, nsamples_estimate: int = 1000) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray, float]:
 898    """
 899    概要:
 900        リジェクションサンプリングを用いて、指定された関数に従う3D点をサンプリングします。
 901
 902    詳細説明:
 903        3次元の関数 func (絶対値) と func2 (値と位相) に基づいて、
 904        ランダムな点を生成し、そのうち条件を満たす点のみを採択します。
 905        これにより、波動関数の確率密度に比例する点の分布を得ます。
 906        M が指定されない場合、estimate_max_f を用いて自動で推定されます。
 907
 908    引数:
 909        :param func: サンプリングの確率密度として使用する関数(絶対値)。
 910        :type func: callable
 911        :param func2: 波動関数の値と位相を返す関数。
 912        :type func2: callable
 913        :param M: サンプリングの受け入れ率の上限値。Noneの場合、estimate_max_f で推定される。
 914        :type M: float
 915        :param minx: サンプリング範囲の最小X, Y, Z座標。
 916        :type minx: float
 917        :param maxx: サンプリング範囲の最大X, Y, Z座標。
 918        :type maxx: float
 919        :param nsamples: 試行するサンプル点の総数。
 920        :type nsamples: int
 921        :param nsamples_estimate: M がNoneの場合に estimate_max_f で使われるサンプル数。
 922        :type nsamples_estimate: int
 923
 924    戻り値:
 925        :returns: サンプリングされたX, Y, Z座標、関数値、位相のNumPy配列、および最終的に使用されたM値のタプル。
 926        :rtype: tuple
 927    """
 928    if M is None: M = estimate_max_f(lambda x, y, z: abs(func(x, y, z)), minx, maxx, nsamples_estimate)
 929
 930    x_list = []
 931    y_list = []
 932    z_list = []
 933    f_list = []
 934    phase_list = []
 935    for _ in range(nsamples):
 936        x, y, z = np.random.uniform(minx, maxx, 3)
 937        f_val, p_val = func2(x, y, z)
 938        if np.random.uniform(0, M) < abs(f_val):
 939            x_list.append(x)
 940            y_list.append(y)
 941            z_list.append(z)
 942            f_list.append(f_val)
 943            phase_list.append(p_val)
 944
 945    return np.array(x_list), np.array(y_list), np.array(z_list), np.array(f_list), np.array(phase_list), M
 946
 947def plot_dot(plot_contours: bool = True) -> matplotlib.pyplot:
 948    """
 949    概要:
 950        リジェクションサンプリングで生成された点を用いて、水素原子の波動関数を3D散布図でプロットします。
 951
 952    詳細説明:
 953        グローバル変数 nlm と orb_type で指定された波動関数の確率密度に比例して
 954        分布する点を3D空間に描画し、点の色は波動関数の位相によって色分けされます。
 955        plot_contours がTrueの場合、波動関数の値に基づく2D等高線もプロットされます。
 956        各軸のスケールは立方体になるように調整されます。
 957
 958    引数:
 959        :param plot_contours: 波動関数の等高線プロットを表示するかどうかのブール値。
 960        :type plot_contours: bool
 961
 962    戻り値:
 963        :returns: プロットが描画された matplotlib.pyplot モジュール。
 964        :rtype: matplotlib.pyplot
 965    """
 966    nsamples_estimate = 1000
 967    n, l, m = nlm
 968
 969    maxx_list = [None, 3.0, 5.0, 10.0, 15.0, 25.0]
 970    kmaxx_list = [0.5, 0.7, 1.0, 1.0, 1.0, 1.0]
 971    maxx = maxx_list[n] * kmaxx_list[l]
 972    minx = -maxx
 973
 974    offsetx = -maxx
 975    offsety = maxx
 976    offsetz = -maxx
 977    posx = 0.1
 978    posy = 0.1
 979    posz = 0.1
 980    
 981    if orb_type == 'r':
 982        title = r'$\psi_r$'
 983    elif orb_type == 'i':
 984        title = r'$\psi_i$'
 985    elif orb_type == 'a':
 986        title = r'|$\psi$|'
 987    elif orb_type == 'a2':
 988        title = r'|$\psi_i$|$^2$'
 989
 990    print()
 991    print(f"Plot wave function with dots: n,l,m=({n},{l},{m})")
 992    print(f"nsamples={nsamples}")
 993
 994
 995#    func = lambda x, y, z: wf.psi_xyz_real(x, y, z, n, l, m)
 996    def func(x, y, z):
 997        f = wf.psi_xyz(x, y, z, n, l, m)
 998        f, phase = wf.get_by_type(f, orb_type)
 999        return f
1000
1001    def func2(x, y, z):
1002        f = wf.psi_xyz(x, y, z, n, l, m)
1003        f, phase = wf.get_by_type(f, orb_type)
1004        return f, phase
1005
1006    x_sampled, y_sampled, z_sampled, f_sampled, phase_sampled, M = rejection_sampling(func, func2, None, minx, maxx, nsamples, nsamples_estimate)
1007    nsampled = f_sampled.size
1008
1009# 正規化の重み
1010    weights = np.abs(f_sampled)
1011    weights /= np.sum(weights)
1012
1013    print(f"nsampled={nsampled}")
1014    print("Estimated max func:", M)
1015
1016    alpha_s = 0.2
1017    alpha_c = 0.1
1018
1019# 3Dプロットで色を変える
1020    fig = plt.figure(figsize = (10, 10))
1021    ax = fig.add_subplot(111, projection = '3d')
1022
1023# phaseに基づいて色を設定
1024    colors = colors_phase
1025    custom_cmap = LinearSegmentedColormap.from_list(cmap_name_phase, colors, N = nbins)
1026    norm = Normalize(vmin = -pi, vmax = pi)
1027    scatter = plt3d.plot_scatter3d(ax, x_sampled, y_sampled, z_sampled, minx, maxx, minx, maxx, minx, maxx, 
1028                    size = 1.0, c = phase_sampled, cmap = custom_cmap, norm = norm, alpha = alpha_s)
1029
1030    pad = 0.1
1031    if True:
1032        scmap = plt.cm.ScalarMappable(cmap = custom_cmap, norm = norm)
1033        scmap.set_array(phase_sampled)
1034        cbar = fig.colorbar(scmap, ax = ax, shrink = 0.5, aspect = 10.0, pad = pad)
1035        cbar.set_label('phase')
1036
1037    if plot_contours:
1038#       maxx = plt3d.get_max_xyz(x1, y1, z1)
1039# カスタムカラーマップの作成
1040        color_list = colors_wf
1041        custom_cmap = LinearSegmentedColormap.from_list(cmap_name_wf, color_list, N = nbins)
1042
1043        fr1d = f_sampled.flatten()
1044        minF = min(fr1d)
1045        maxF = max(fr1d)
1046
1047# rの値にcmapを対応させる
1048        norm = Normalize(vmin = minF, vmax = maxF)
1049
1050        plt3d.plot_contours_xyz_by_func(ax, func, minx = -maxx, maxx = maxx, nmesh = 100,
1051                            posx = posx, posy = posy, posz = posz,
1052                            offsetx = -maxx, offsety = maxx, offsetz = -maxx, 
1053                            cmap = custom_cmap, levels = 20, alpha = alpha_c)
1054
1055        scmap = plt.cm.ScalarMappable(cmap = custom_cmap, norm = norm)
1056        scmap.set_array(f_sampled)
1057        cbar = fig.colorbar(scmap, ax = ax, shrink = 0.5, aspect = 10.0, pad = pad)
1058        cbar.set_label(title)
1059
1060    plt3d.set_cubic_scale(ax, maxx)
1061
1062    plt.title(f"dot plot of {title} for nlm={n}{l}{m}")
1063
1064    return plt
1065
1066def plot_dotanim(plot_contours: bool = True) -> matplotlib.pyplot:
1067    """
1068    概要:
1069        リジェクションサンプリングで生成された点を用いて、水素原子の波動関数の3D散布図アニメーションをプロットします。
1070
1071    詳細説明:
1072        plot_dot と同様に、グローバル変数 nlm と orb_type に基づいて
1073        波動関数の確率密度に比例した3D散布図を、時間依存性 (phase パラメータ) を加えてアニメーション化します。
1074        点の色は波動関数の位相によって色分けされ、GIFファイルとして保存することも可能です。
1075        アニメーションはユーザーがEnterキーを押すまで継続します。
1076        plot_contours 引数は現在この関数では使用されていません。
1077
1078    引数:
1079        :param plot_contours: 等高線プロットを表示するかどうかのブール値 (アニメーションでは未使用)。
1080        :type plot_contours: bool
1081
1082    戻り値:
1083        :returns: プロットが描画された matplotlib.pyplot モジュール。
1084        :rtype: matplotlib.pyplot
1085    """
1086    nsamples_estimate = 1000
1087    n, l, m = nlm
1088
1089    maxx_list = [None, 3.0, 5.0, 10.0, 15.0, 25.0]
1090    kmaxx_list = [0.5, 0.7, 1.0, 1.0, 1.0, 1.0]
1091    maxx = maxx_list[n] * kmaxx_list[l]
1092    minx = -maxx
1093
1094    if orb_type == 'r':
1095        title = r'$\psi_r$'
1096    elif orb_type == 'i':
1097        title = r'$\psi_i$'
1098    elif orb_type == 'a':
1099        title = r'|$\psi$|'
1100    elif orb_type == 'a2':
1101        title = r'|$\psi_i$|$^2$'
1102
1103    print()
1104    print(f"Animation of wave function with dots: n,l,m=({n},{l},{m})")
1105    print(f"nsamples={nsamples}")
1106
1107    def func(x, y, z):
1108        f = wf.psi_xyz(x, y, z, n, l, m)
1109        f, phase = wf.get_by_type(f, orb_type)
1110        return f
1111
1112    def func2(x, y, z):
1113        f = wf.psi_xyz(x, y, z, n, l, m)
1114        f, phase = wf.get_by_type(f, orb_type)
1115        return f, phase
1116
1117    x_sampled, y_sampled, z_sampled, f_sampled, phase_sampled, M = rejection_sampling(func, func2, None, minx, maxx, nsamples, nsamples_estimate)
1118    nsampled = f_sampled.size
1119    print(f"nsampled={nsampled}")
1120    print("Estimated max func:", M)
1121
1122# plot
1123    fig = plt.figure(figsize = (10, 10))
1124    ax = fig.add_subplot(111, projection = '3d')
1125
1126# phaseに基づいて色を設定
1127    colors = colors_phase
1128    custom_cmap = LinearSegmentedColormap.from_list(cmap_name_phase, colors, N = nbins)
1129    norm = Normalize(vmin = -pi, vmax = pi)
1130
1131    scatter = plt3d.plot_scatter3d(ax, x_sampled, y_sampled, z_sampled, minx, maxx, minx, maxx, minx, maxx, 
1132                    size = 1.0, c = phase_sampled, cmap = custom_cmap, norm = norm)
1133
1134    scmap = plt.cm.ScalarMappable(cmap = custom_cmap, norm = norm)
1135    scmap.set_array(phase_sampled)
1136    cbar = fig.colorbar(scmap, ax = ax, shrink = 0.5, aspect = 10.0)
1137    cbar.set_label('phase')
1138
1139    plt3d.set_cubic_scale(ax, maxx)
1140    plt.title(f"dot plot of {title} for nlm={n}{l}{m}")
1141
1142    nmaxiter = 62
1143    wait = 5 # ms
1144    ani = None
1145    window_closed = False
1146    def update_animation(frame):
1147        nonlocal window_closed, ani
1148
1149        if window_closed :
1150            if ani.event_source: ani.event_source.stop()
1151            return ax
1152
1153        if frame == 0 and not hasattr(update_animation, 'initialized'):
1154            update_animation.initialized = True
1155            return
1156        if frame % 10 == 0: print(f"frame: {frame}/{nmaxiter}")
1157
1158        ax.cla()  # 軸の設定を保持するために全体をクリア
1159
1160        def func2(x, y, z):
1161            f = wf.psi_xyz(x, y, z, n, l, m, phase = frame * 0.1)
1162            f, phase = wf.get_by_type(f, orb_type)
1163            return f, phase
1164
1165        x_sampled, y_sampled, z_sampled, f_sampled, phase_sampled, _M \
1166                = rejection_sampling(None, func2, M, minx, maxx, nsamples, nsamples_estimate)
1167
1168        plt3d.plot_scatter3d(ax, x_sampled, y_sampled, z_sampled, minx, maxx, minx, maxx, minx, maxx, 
1169                    size = 1.0, c = phase_sampled, cmap = custom_cmap, norm = norm)
1170
1171        plt3d.set_cubic_scale(ax, maxx)
1172        ax.set_title(f"{title} frame: {frame}/{nmaxiter}")
1173
1174        if fplot: plt.pause(0.1)
1175
1176        return ax
1177
1178    def on_close(event):
1179        nonlocal window_closed
1180        window_closed = True
1181
1182    fig.canvas.mpl_connect('close_event', on_close)
1183
1184    ani = FuncAnimation(fig, update_animation, frames = nmaxiter, interval = wait)
1185
1186    outfile = f'plot_wf_{mode}_{functype}.gif'
1187    if fsave:
1188        print(f"saving to {outfile}")
1189        ani.save(outfile, writer='imagemagick')
1190
1191
1192    if fplot: 
1193#    plt.show()
1194        plt.pause(0.1)
1195        input("Press Enter to close the window...")
1196
1197    return plt
1198
1199
1200def plot_iso3d() -> matplotlib.pyplot:
1201    """
1202    概要:
1203        水素原子の波動関数の等値面を3Dでプロットします。
1204
1205    詳細説明:
1206        グローバル変数 nlm と orb_type で指定された量子数に基づいて
1207        3次元グリッド上で水素原子の波動関数を計算し、指定されたレベルで等値面を抽出してプロットします。
1208        波動関数の値に基づく2D等高線も重ねて描画されます。
1209
1210    戻り値:
1211        :returns: プロットが描画された matplotlib.pyplot モジュール。
1212        :rtype: matplotlib.pyplot
1213    """
1214    n, l, m = nlm
1215    orb_name = wf.get_orb_name(n, l, m)
1216    n, l, m = wf.get_qnumbers(n, l, m)
1217
1218    maxx_list = [None, 3.0, 5.0, 10.0, 15.0, 25.0]
1219    kmaxx_list = [0.5, 0.7, 1.0, 1.0, 1.0, 1.0]
1220    maxx = maxx_list[n] * kmaxx_list[l]
1221
1222    x = np.linspace(-maxx, maxx, 50)
1223    y = np.linspace(-maxx, maxx, 50)
1224    z = np.linspace(-maxx, maxx, 50)
1225    X, Y, Z = np.meshgrid(x, y, z)
1226
1227    def func(x, y, z):
1228        f = wf.psi_xyz(x, y, z, n, l, m)
1229        f, phase = wf.get_by_type(f, orb_type)
1230        return f, phase
1231
1232    def func1(x, y, z):
1233        return func(x, y, z)[0]
1234
1235    F, phase = func(X, Y, Z)
1236
1237# 等値面のレベル
1238    fr1d = F.flatten()
1239    minF = min(fr1d)
1240    maxF = max(fr1d)
1241    print(f"F range: {minF} - {maxF}")
1242    levels = [-0.6 * maxF, -0.3 * maxF, 0.3 * maxF, 0.6 * maxF]
1243    colors = ['blue', 'cyan', 'pink', 'red']  # 等値面の色
1244
1245# 3D プロット
1246    fig = plt.figure(figsize = (8, 8))
1247    ax = fig.add_subplot(111, projection='3d')
1248
1249    dx, dy, dz = x[1] - x[0], y[1] - y[0], z[1] - z[0]
1250    plt3d.plot_isosurface3d(ax, X, Y, Z, F, levels = levels, origin = [x.min(), y.min(), z.min()], spacing = [dx, dy, dz],
1251            colors = colors, edgecolor = 'k', alpha = 0.3, linewidth = 0.1)
1252
1253# 2D等高線
1254# カスタムカラーマップの作成
1255    color_list = colors_wf
1256    cmap_name = cmap_name_wf
1257    custom_cmap = LinearSegmentedColormap.from_list(cmap_name, color_list, N = nbins)
1258# rの値にcmapを対応させる
1259#    norm = Normalize(vmin = -maxF, vmax = maxF)
1260    norm = Normalize(vmin = minF, vmax = maxF)
1261    face_colors = custom_cmap(norm(F))
1262
1263    maxx = plt3d.get_max_xyz(X, Y, Z)
1264    plt3d.plot_contours_xyz_by_func(ax, func1, minx = -maxx, maxx = maxx, nmesh = 100,
1265                            posx = 0.1, posy = 0.1, posz = 0.1,
1266                            offsetx = -maxx, offsety = maxx, offsetz = -maxx, 
1267                            cmap = custom_cmap, levels = 20, alpha = 0.3)
1268
1269    plt3d.set_cubic_scale(ax, maxx)
1270
1271    scmap = plt.cm.ScalarMappable(cmap = custom_cmap, norm = norm)
1272    scmap.set_array(F)
1273    cbar = plt.colorbar(scmap, ax=ax, shrink=0.5, aspect=10.0)
1274    plt.title(f"isosurfaces for nlm={n}{l}{m}")
1275
1276    return plt
1277
1278def plot_iso3danim() -> matplotlib.pyplot:
1279    """
1280    概要:
1281        水素原子の波動関数の等値面アニメーションを3Dでプロットします。
1282
1283    詳細説明:
1284        plot_iso3d と同様に、グローバル変数 nlm と orb_type に基づいて
1285        波動関数の等値面を計算し、時間依存性 (phase パラメータ) を加えてアニメーション化します。
1286        波動関数の位相変化を表現し、GIFファイルとして保存することも可能です。
1287        アニメーションはユーザーがEnterキーを押すまで継続します。
1288
1289    戻り値:
1290        :returns: プロットが描画された matplotlib.pyplot モジュール。
1291        :rtype: matplotlib.pyplot
1292    """
1293    n, l, m = nlm
1294    orb_name = wf.get_orb_name(n, l, m)
1295    n, l, m = wf.get_qnumbers(n, l, m)
1296
1297    if orb_type == 'r':
1298        title = r'$\psi_r$'
1299    elif orb_type == 'i':
1300        title = r'$\psi_i$'
1301    elif orb_type == 'a':
1302        title = r'|$\psi$|'
1303    elif orb_type == 'a2':
1304        title = r'|$\psi_i$|$^2$'
1305
1306    maxx_list = [None, 3.0, 5.0, 10.0, 15.0, 25.0]
1307    kmaxx_list = [0.5, 0.7, 1.0, 1.0, 1.0, 1.0]
1308    maxx = maxx_list[n] * kmaxx_list[l]
1309
1310    x = np.linspace(-maxx, maxx, 50)
1311    y = np.linspace(-maxx, maxx, 50)
1312    z = np.linspace(-maxx, maxx, 50)
1313    X, Y, Z = np.meshgrid(x, y, z)
1314
1315    def func(x, y, z):
1316        f = wf.psi_xyz(x, y, z, n, l, m)
1317        f, phase = wf.get_by_type(f, orb_type)
1318        return f, phase
1319
1320    def func1(x, y, z):
1321        return func(x, y, z)[0]
1322
1323    F, phase = func(X, Y, Z)
1324
1325# 等値面のレベル
1326    fr1d = F.flatten()
1327    minF = min(fr1d)
1328    maxF = max(fr1d)
1329    print(f"F range: {minF} - {maxF}")
1330    levels = [-0.6 * maxF, -0.3 * maxF, 0.3 * maxF, 0.6 * maxF]
1331    colors = ['blue', 'cyan', 'pink', 'red']  # 等値面の色
1332
1333# 3D プロット
1334    fig = plt.figure(figsize = (8, 8))
1335    ax = fig.add_subplot(111, projection='3d')
1336
1337    dx, dy, dz = x[1] - x[0], y[1] - y[0], z[1] - z[0]
1338    plt3d.plot_isosurface3d(ax, X, Y, Z, F, levels = levels, origin = [x.min(), y.min(), z.min()], spacing = [dx, dy, dz],
1339            colors = colors, edgecolor = 'k', alpha = 0.3, linewidth = 0.1)
1340
1341    plt3d.set_cubic_scale(ax, maxx)
1342    plt.title(f"isosurfaces for nlm={n}{l}{m}")
1343
1344    nmaxiter = 62
1345    wait = 5 # ms
1346    ani = None
1347    window_closed = False
1348    def update_animation(frame):
1349        nonlocal window_closed, ani
1350
1351        if window_closed :
1352            if ani.event_source: ani.event_source.stop()
1353            return ax
1354
1355        if frame == 0 and not hasattr(update_animation, 'initialized'):
1356            update_animation.initialized = True
1357            return
1358        if frame % 10 == 0: print(f"frame: {frame}/{nmaxiter}")
1359
1360        ax.cla()  # 軸の設定を保持するために全体をクリア
1361
1362        def func(x, y, z):
1363            f = wf.psi_xyz(x, y, z, n, l, m, phase = frame * 0.1)
1364            f, phase = wf.get_by_type(f, orb_type)
1365            return f, phase
1366
1367        F, phase = func(X, Y, Z)
1368        plt3d.plot_isosurface3d(ax, X, Y, Z, F, levels = levels, origin = [x.min(), y.min(), z.min()], spacing = [dx, dy, dz],
1369                colors = colors, edgecolor = 'k', alpha = 0.3, linewidth = 0.1)
1370
1371        plt3d.set_cubic_scale(ax, maxx)
1372        ax.set_title(f"{title} frame: {frame}/{nmaxiter}")
1373
1374        if fplot: plt.pause(0.1)
1375
1376        return ax
1377
1378    def on_close(event):
1379        nonlocal window_closed
1380        window_closed = True
1381
1382    fig.canvas.mpl_connect('close_event', on_close)
1383
1384    ani = FuncAnimation(fig, update_animation, frames = nmaxiter, interval = wait)
1385
1386#    plt.show()
1387
1388    outfile = f'plot_wf_{mode}_{functype}.gif'
1389    if fsave:
1390        print(f"saving to {outfile}")
1391        ani.save(outfile, writer='imagemagick')
1392
1393    if fplot: 
1394#    plt.show()
1395#        plt.pause(0.1)
1396        input("Press Enter to close the window...")
1397
1398    return plt
1399
1400
1401def make_3d_density_map(output_file: str = "EDens.vasp", Z: float = 1.0, n: int = 1, l: int = 0, m: int = 0, lx: float = 10.0, ly: float = 10.0, lz: float = 10.0, step: float = 0.2) -> int:
1402    """
1403    概要:
1404        水素原子の電子密度を3DグリッドデータとしてVASP形式で出力します。
1405
1406    詳細説明:
1407        指定された量子数 n, l, m と原子番号 Z の波動関数に基づいて、
1408        X, Y, Z方向のグリッド上に電子密度 (波動関数の絶対値の2乗) を計算し、
1409        VASP (LOCPOT) ファイル形式で出力します。
1410
1411    引数:
1412        :param output_file: 出力ファイル名。Orbital名が埋め込まれる(例: "EDens_{Orb}.vasp")。
1413        :type output_file: str
1414        :param Z: 原子番号 (陽子数)。
1415        :type Z: float
1416        :param n: 主量子数。
1417        :type n: int
1418        :param l: 方位量子数。
1419        :type l: int
1420        :param m: 磁気量子数。
1421        :type m: int
1422        :param lx: X方向のボックスサイズ。
1423        :type lx: float
1424        :param ly: Y方向のボックスサイズ。
1425        :type ly: float
1426        :param lz: Z方向のボックスサイズ。
1427        :type lz: float
1428        :param step: グリッドのステップサイズ。
1429        :type step: float
1430
1431    戻り値:
1432        :returns: 成功時は0、ファイル書き込みエラー時はマイナス1、無効な量子数の場合はマイナス2を返します。
1433        :rtype: int
1434    """
1435    print("\nCalc 3D Electron Density map\n")
1436
1437    OrbName = wf.GetOrbName(n, l, m)
1438    print(f"  Z={Z}")
1439    print(f"  n,l,m={n},{l},{m}")
1440    print(f"  Orbital: {OrbName}")
1441    output_file = output_file.replace("{Orb}", OrbName)
1442    print(f"OutFile: [{output_file}]")
1443
1444    try:
1445        out = open(output_file, "w")
1446    except IOError:
1447        print(f"Error: Can not write to [{output_file}].")
1448        return -1
1449
1450    nx = int(lx / step + 0.1)
1451    ny = int(ly / step + 0.1)
1452    nz = int(lz / step + 0.1)
1453    print(f"Range: {lx} {ly} {lz}")
1454    print(f"nMesh: {nx} {ny} {nz}")
1455
1456    out.write(f"Electron density for Z={Z}, n={n}, l={l}, m={m}\n")
1457    out.write(f"   {lx:12.6f}\n")
1458    out.write(f"     {lx/lx:12.6f}   {0.0:12.6f}   {0.0:12.6f}\n")
1459    out.write(f"     {0.0:12.6f}   {ly/lx:12.6f}   {0.0:12.6f}\n")
1460    out.write(f"     {0.0:12.6f}   {0.0:12.6f}   {lz/lx:12.6f}\n")
1461    out.write("  1\n")
1462    out.write("Direct\n")
1463    out.write("  0.500000  0.500000  0.500000\n")
1464    out.write("\n")
1465    out.write(f"  {nx:3d}  {ny:3d}  {nz:3d}\n")
1466
1467    count = 0
1468    for ix in range(nx):
1469        for iy in range(ny):
1470            for iz in range(nz):
1471                x = ix * step
1472                y = iy * step
1473                z = iz * step
1474                # 中心は(0.5*lx, 0.5*ly, 0.5*lz)
1475                f = wf.cal_wave_function(Z, n, l, m, x, y, z, 0.5*lx, 0.5*ly, 0.5*lz)
1476                if f is None:
1477                    print(f"Invalid n,l,m({n},{l},{m}).")
1478                    out.close()
1479                    return -2
1480
1481                out.write(f" {f:11.5g}")
1482                count += 1
1483                if count % 10 == 0:
1484                    out.write("\n")
1485
1486    out.close()
1487
1488def integ_MC3d(f, x_min: float, x_max: float, y_min: float, y_max: float, z_min: float, z_max: float, n_samples: int) -> float:
1489    """
1490    概要:
1491        モンテカルロ法(リジェクトサンプリングではない)を用いて、3次元空間の関数を積分します。
1492
1493    詳細説明:
1494        指定された関数の3次元積分を、指定された範囲内でランダムにサンプリングした点での
1495        関数値の平均に体積を掛けることで近似します。
1496
1497    引数:
1498        :param f: 積分する対象の関数。
1499        :type f: callable
1500        :param x_min: X軸の最小値。
1501        :type x_min: float
1502        :param x_max: X軸の最大値。
1503        :type x_max: float
1504        :param y_min: Y軸の最小値。
1505        :type y_min: float
1506        :param y_max: Y軸の最大値。
1507        :type y_max: float
1508        :param z_min: Z軸の最小値。
1509        :type z_min: float
1510        :param z_max: Z軸の最大値。
1511        :type z_max: float
1512        :param n_samples: サンプリング点の数。
1513        :type n_samples: int
1514
1515    戻り値:
1516        :returns: 近似された積分の値。
1517        :rtype: float
1518    """
1519    x_samples = np.random.uniform(x_min, x_max, n_samples)
1520    y_samples = np.random.uniform(y_min, y_max, n_samples)
1521    z_samples = np.random.uniform(z_min, z_max, n_samples)
1522    
1523    S = sum(f(x_samples, y_samples, z_samples))
1524    volume = (x_max - x_min) * (y_max - y_min) * (z_max - z_min)
1525    integral = S * volume / n_samples
1526
1527    return integral
1528
1529def normalize() -> None:
1530    """
1531    概要:
1532        水素原子の波動関数が正規化されているかを確認します。
1533
1534    詳細説明:
1535        動径波動関数 Rnl(r) と全波動関数 psi(x,y,z) の両方について、
1536        abs(psi)^2 (確率密度) が全空間で1に積分されることを検証します。
1537        動径部分の積分には scipy.integrate.quad を、3次元部分の積分には
1538        モンテカルロ積分を使用します。異なる量子数 n, l の組み合わせについて検証結果を出力します。
1539
1540    戻り値:
1541        :returns: None
1542    """
1543    print("\nCalculate |psi(x,y,z)|^2 to check normalization\n")
1544    print("Rnl:")
1545    for n in range(1, 5):
1546        for l in range(0, n):
1547            def func(r):
1548#                return r**2 * abs(wf.psi_r(r, 0.0, 0.0, n, l, 0))**2
1549                return 4 * pi * r**2 * abs(wf.psi_r(r, 0.0, 0.0, n, l, 0))**2
1550#                return 4 * pi * r**2 * wf.Rnl(r, n, 0)**2
1551
1552            result, error = quad(func, 0, np.inf)
1553            print(f"  n,l={n},{l}: S={result} +- {error}")
1554
1555    nsampling = 1000000
1556    print()
1557    print("psi:")
1558    for n in range(1, 5):
1559        lmax = n - 1
1560        for l in range(0, lmax + 1):
1561            print(f"Orbital: {n}{l}0: En={wf.En(n):.6g} eV", end = '')
1562
1563            def psi2(x, y, z):
1564                f = wf.psi_xyz(x, y, z, n, l, 0)
1565                return f.real**2 + f.imag**2
1566
1567            if n == 1:
1568                maxx = 5.0
1569            else:
1570                maxx = 20.0
1571            integ = integ_MC3d(psi2, -maxx, maxx, -maxx, maxx, -maxx, maxx, nsampling)
1572            print(f"  |psi|^2={integ}")
1573
1574def main(mode: str) -> None:
1575    """
1576    概要:
1577        プログラムの主要な実行ロジックを制御します。
1578
1579    詳細説明:
1580        コマンドライン引数から受け取った mode に基づいて、
1581        対応するプロット関数または処理関数 (例: plot_torus, plot_Rnl, normalize) を呼び出します。
1582        結果のプロット表示 (fplot) やファイル保存 (fsave) も管理します。
1583        無効な mode が指定された場合はエラーメッセージを出力し終了します。
1584
1585    引数:
1586        :param mode: 実行モードを指定する文字列。
1587        :type mode: str
1588
1589    戻り値:
1590        :returns: None
1591    """
1592
1593    if mode == 'torus':
1594        plt = plot_torus()
1595    elif mode == 'Rnl':
1596        plt = plot_Rnl()
1597    elif mode == 'Ylm' or mode == 'Theta':
1598        plt = plot_Ylm()
1599    elif mode == 'Phi':
1600        plt = plot_Phi()
1601    elif mode == 'normalize':
1602        normalize()
1603        exit()
1604    elif mode == 'rplot':
1605        plt = plot_rplot()
1606    elif mode == 'ranim':
1607        plt = plot_ranim()
1608    elif mode == 'dot':
1609        plt = plot_dot(plot_contours = False)
1610    elif mode == 'dotc':
1611        plt = plot_dot(plot_contours = True)
1612    elif mode == 'dotanim':
1613        plt = plot_dotanim(plot_contours = False)
1614    elif mode == 'iso3d':
1615        plt = plot_iso3d()
1616    elif mode == 'iso3danim':
1617        plt = plot_iso3danim()
1618    elif mode == 'rsurface':
1619        plt = plot_rsurface()
1620    elif mode == 'isosurface3d':
1621        plt = plot_isosurface3d()
1622    elif mode == 'contour3d':
1623        plt = plot_contour3d()
1624    elif mode == '3dMC_animation':
1625        plt = plot_3dMC_animation()
1626    else:
1627        print(f"\nError: Invalid mode [{mode}]")
1628        exit()
1629
1630    if plt:
1631        if fsave: 
1632            output_file = f"plot_wf_{mode}_{functype}.png"
1633            print()
1634            print(f"Save plot to {output_file}")
1635            plt.savefig(output_file)
1636        if fplot: plt.show()
1637
1638
1639if __name__ == "__main__":
1640# argparse のセットアップ
1641    parser = CustomArgumentParser(description='Plot wave functions of H\n\n')
1642    parser.add_argument('mode', nargs='?', default=mode, help='Mode of operation')
1643    parser.add_argument('functype', nargs='?', default=functype, help='Function type')
1644    parser.add_argument('nsamples', nargs='?', type=int, default=nsamples, help='Number of samples for Monte Carlo sampling')
1645    parser.add_argument('--fplot', type=int, default=1, help='Flag to plot graphs (1: enable, 0: disable)')
1646    parser.add_argument('--fsave', type=int, default=1, help='Flag to save figure file (1: enable, 0: disable)')
1647
1648# 引数の解析
1649    args = parser.parse_args()
1650
1651# 引数の設定
1652    mode = args.mode
1653    functype = args.functype
1654    nsamples = args.nsamples
1655    fplot = args.fplot
1656    fsave = args.fsave
1657
1658# 使用例の出力
1659    print()
1660    print(f"mode: {mode}")
1661    print(f"function type: {functype}")
1662    ftype, nlmt = wf.analyze_function(functype)
1663    nlm, orb_type = nlmt[:3], nlmt[3]
1664    print(f"   type: {ftype}  nlm:", nlm, f"  orb_type: {orb_type}")
1665    print(f"nsamples = {nsamples}")
1666    print(f"fplot = {fplot}")
1667
1668    if mode == 'torus':
1669        f = torus
1670    elif ftype == 'c' or ftype == 'r':
1671        f = wf.psi_r
1672    else:
1673        if ftype == 'f':
1674            if nlm == 'sphere':
1675                f = sphere
1676            elif nlm == 'exp_r2':
1677                f = exp_r2
1678        elif mode == 'contour3d' or mode == 'iso3d':
1679            f = sphere
1680        else:
1681            f = sphere
1682
1683    main(mode)
1684    usage()