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

schrodinger1d.py をダウンロード

schrodinger1d.py
schrodinger1d.py
  1"""
  2概要:
  3    1次元シュレーディンガー方程式をシューティング法で解くスクリプトです。
  4
  5詳細説明:
  6    与えられたエネルギー固有値の推測値 E に対して、ベルレ法を用いて
  7    波動関数を積分します。原子単位系を使用します。
  8
  9関連リンク:
 10    schrodinger1d_usage
 11"""
 12import argparse
 13import numpy as np
 14import pandas as pd
 15import matplotlib.pyplot as plt
 16
 17# =========================
 18# Potential (atomic units)
 19# =========================
 20def V(x):
 21    """
 22    概要:
 23        調和振動子ポテンシャルを計算します。
 24
 25    詳細説明:
 26        V(x) = 0.5 * x**2 の形式で、単位は Hartree (Ha) です。
 27
 28    引数:
 29        :param x: 空間座標
 30        :type x: float
 31
 32    戻り値:
 33        :returns: ポテンシャルエネルギーの値
 34        :rtype: float
 35    """
 36    return 0.5 * x**2
 37#    return 0.5 * x**2 + 1e-2 * x**4
 38
 39
 40# =========================
 41# Argument initialization
 42# =========================
 43def initialize():
 44    """
 45    概要:
 46        コマンドライン引数を定義してパースします。
 47
 48    詳細説明:
 49        エネルギー固有値の推測値、計算領域、メッシュ数、境界条件などの
 50        各種パラメータをパースして返します。
 51
 52    引数:
 53        なし
 54
 55    戻り値:
 56        :returns: ArgumentParserオブジェクトと、パース結果のNamespaceのタプル
 57        :rtype: tuple
 58    """
 59    parser = argparse.ArgumentParser(
 60        description="Solve 1D Schrodinger equation by shooting method (atomic units)"
 61    )
 62
 63    parser.add_argument("--E", type=float, required=True,
 64                        help="Energy eigenvalue guess (Ha)")
 65    parser.add_argument("--L", type=float, default=10.0,
 66                        help="Half domain size [-L, L]")
 67    parser.add_argument("--nx", type=int, default=2000,
 68                        help="Number of mesh points")
 69    parser.add_argument("--psi_max", type=float, default=1e10,
 70                        help="Divergence threshold for psi")
 71    parser.add_argument("--report_step", type=int, default=200,
 72                        help="Interval for progress report")
 73    parser.add_argument("--outfile", type=str, default="schrodinger.xlsx",
 74                        help="Output Excel filename")
 75
 76    # --- boundary condition ---
 77    parser.add_argument("--bc", choices=["asymptotic", "zero"],
 78                        default="asymptotic",
 79                        help="Boundary condition at x=-L")
 80
 81    # used only for bc=zero
 82    parser.add_argument("--eps", type=float, default=1e-6,
 83                        help="Initial derivative dpsi/dx at x=-L (bc=zero only)")
 84
 85    args = parser.parse_args()
 86    return parser, args
 87
 88
 89# =========================
 90# Schrodinger solver
 91# =========================
 92def solve_schrodinger(E, L, nx, psi_max, report_step, bc, eps):
 93    """
 94    概要:
 95        ベルレ法を用いて1次元シュレーディンガー方程式の数値積分を実行します。
 96
 97    詳細説明:
 98        指定された境界条件に従って初期値を設定し、微分方程式を解きます。
 99        波動関数の値が psi_max を超えた場合は発散とみなし、積分を打ち切ります。
100
101    引数:
102        :param E: エネルギー固有値の推測値 (Ha)
103        :type E: float
104        :param L: 計算領域の半幅 (-L から L まで)
105        :type L: float
106        :param nx: メッシュ点数
107        :type nx: int
108        :param psi_max: 波動関数の発散判定閾値
109        :type psi_max: float
110        :param report_step: 進捗報告のステップ間隔 (0以下の場合は報告しない)
111        :type report_step: int
112        :param bc: 境界条件の種類 (asymptotic または zero)
113        :type bc: str
114        :param eps: bc が zero の場合の初期微分値
115        :type eps: float
116
117    戻り値:
118        :returns: 空間座標配列、波動関数配列、実行結果情報の辞書のタプル
119        :rtype: tuple
120    """
121    x_full = np.linspace(-L, L, nx)
122    dx = x_full[1] - x_full[0]
123
124    psi_full = np.zeros(nx)
125
126    # =========================
127    # Initial conditions
128    # =========================
129    if bc == "zero":
130        # ψ(-L)=0, ψ'(-L)=eps
131        psi_full[0] = 0.0
132        psi_full[1] = eps * dx
133
134    elif bc == "asymptotic":
135        # ψ'(-L) = κ ψ(-L)
136        psi0 = 1e-6
137        kappa = np.sqrt(2.0 * (V(-L) - E))
138
139        psi_full[0] = psi0
140        psi_full[1] = psi0 * (1.0 + kappa * dx)
141
142    else:
143        raise ValueError("Unknown boundary condition")
144
145    diverged_x = None
146    diverge_index = None
147
148    # =========================
149    # Verlet integration
150    # =========================
151    for i in range(1, nx - 1):
152        k = 2.0 * (V(x_full[i]) - E)
153        psi_full[i + 1] = (
154            2.0 * psi_full[i]
155            - psi_full[i - 1]
156            + dx**2 * k * psi_full[i]
157        )
158
159        if abs(psi_full[i + 1]) > psi_max:
160            diverge_index = i + 1
161            diverged_x = x_full[i + 1]
162            break
163
164        if report_step > 0 and i % report_step == 0:
165            print(f"[INFO] step={i}, x={x_full[i]:.3f}, psi={psi_full[i]:.3e}")
166
167    info = {}
168
169    if diverge_index is None:
170        info["success"] = True
171        info["diverged"] = False
172        info["diverged_x"] = None
173        info["message"] = "integration completed successfully"
174        return x_full, psi_full, info
175    else:
176        info["success"] = False
177        info["diverged"] = True
178        info["diverged_x"] = diverged_x
179        info["message"] = f"diverged at x={diverged_x:.3f}"
180        return x_full[:diverge_index], psi_full[:diverge_index], info
181
182
183# =========================
184# Save & plot
185# =========================
186def save_and_plot(x, psi, outfile, diverged=False, diverged_x=None):
187    """
188    概要:
189        計算結果をExcelファイルに保存し、グラフを描画します。
190
191    詳細説明:
192        波動関数およびその確率密度をプロットします。
193        発散した場合は、発散開始位置に縦線を引きます。
194
195    引数:
196        :param x: 空間座標の配列
197        :type x: numpy.ndarray
198        :param psi: 波動関数の配列
199        :type psi: numpy.ndarray
200        :param outfile: 出力するExcelファイル名
201        :type outfile: str
202        :param diverged: 発散したかどうかを示すフラグ
203        :type diverged: bool
204        :param diverged_x: 発散が起きた空間座標 (発散していない場合は None)
205        :type diverged_x: float
206
207    戻り値:
208        なし
209    """
210    df = pd.DataFrame({
211        "x": x,
212        "psi": psi,
213        "psi2": psi**2
214    })
215    df.to_excel(outfile, index=False)
216    print(f"[INFO] Data saved to {outfile}")
217
218    plt.figure(figsize=(8, 5))
219    if not diverged:
220        plt.plot(x, psi, label=r"$\psi(x)$")
221    plt.plot(x, psi**2, label=r"$|\psi(x)|^2$")
222
223    if diverged and diverged_x is not None:
224        plt.axvline(diverged_x, color="r", linestyle="--",
225                    label="divergence start")
226
227    plt.xlabel("x (a.u.)")
228    plt.ylabel("Wavefunction")
229    if diverged:
230        plt.yscale("log")
231    plt.legend()
232    plt.grid()
233    plt.tight_layout()
234    plt.show()
235
236
237# =========================
238# Main
239# =========================
240def main():
241    """
242    概要:
243        メインの処理フローを実行します。
244
245    詳細説明:
246        コマンドライン引数を読み込み、指定された条件でシュレーディンガー方程式を
247        解き、最終的な計算結果の保存とプロットを行います。
248
249    引数:
250        なし
251
252    戻り値:
253        なし
254    """
255    _, args = initialize()
256
257    print("=== 1D Schrodinger Solver (atomic units) ===")
258    print(f"E = {args.E} Ha,  L = {args.L},  nx = {args.nx}")
259    print(f"Boundary condition: {args.bc}")
260
261    x, psi, info = solve_schrodinger(
262        E=args.E,
263        L=args.L,
264        nx=args.nx,
265        psi_max=args.psi_max,
266        report_step=args.report_step,
267        bc=args.bc,
268        eps=args.eps
269    )
270
271    print("[RESULT]", info["message"])
272    print(f"psi(end) = {psi[-1]:.3e}")
273
274    save_and_plot(
275        x,
276        psi,
277        args.outfile,
278        diverged=info["diverged"],
279        diverged_x=info["diverged_x"]
280    )
281
282
283if __name__ == "__main__":
284    main()