thomas_fermi.py ダウンロード/コピー
thomas_fermi.py
thomas_fermi.py
1#!/usr/bin/env python3
2# -*- coding: utf-8 -*-
3"""
4概要:
5 中性原子の Thomas-Fermi 方程式を境界値問題として解く教育用プログラムです。
6詳細説明:
7 x は無次元距離、phi は遮蔽関数を表します。
8 phiの2階微分は phiの1.5乗 / xの平方根 で与えられ、phi(0)=1、phi(infinity)=0 を満たします。
9 原子の静電ポテンシャルは phi(x)/r に比例し、密度は phi/x の1.5乗に比例しますが、本プログラムは実単位に変換しません。
10 Z や軌道エネルギー、角運動量、SCF反復などは扱いません。
11 u=phi、v=phiの1階微分 として連立1階常微分方程式に変換し、scipy.integrate.solve_bvp で全区間を同時に解きます。
12 原点の特異性は小さな eps から級数展開で開始して避け、未知パラメータである原点での傾きは境界条件と同時に決定します。
13 遠方では有限距離での近似境界条件を課しており、check_domain オプションで計算領域を倍にして結果を比較できます。
14 tol は微分方程式の残差許容値であり、物理量の相対誤差保証ではありません。
15 教材としての観察ポイントとして、原点近傍級数は原点近くでのみ有効であること、遠方の漸近形は遠方でのみ有効であること、
16 shooting で初期傾きを変えると外向き積分が大きく変わることなどが確認できます。
17 実行すると指定された接頭辞のCSVファイルとPNG画像が出力されます。
18関連リンク:
19 scipy_integrate_solve_bvp
20"""
21from __future__ import annotations
22import argparse
23from pathlib import Path
24import sys
25import numpy as np
26from scipy.integrate import solve_bvp, solve_ivp
27
28
29def origin_series(x, b):
30 """
31 概要:
32 原点付近での関数の値と微分値を級数展開で計算します。
33 詳細説明:
34 元コードの級数に x の4乗項まで追加して計算を行います。
35 引数:
36 :param x: 評価する無次元距離の配列
37 :type x: numpy.ndarray
38 :param b: 原点での微係数の推定値
39 :type b: float
40 戻り値:
41 :returns: 遮蔽関数とその1階微分の値を格納した配列
42 :rtype: numpy.ndarray
43 """
44 u = (1 + b*x + 4/3*x**1.5 + 2*b/5*x**2.5 + x**3/3
45 + 3*b*b/70*x**3.5 + 2*b/15*x**4)
46 v = (b + 2*np.sqrt(x) + b*x**1.5 + x*x
47 + 3*b*b/20*x**2.5 + 8*b/15*x**3)
48 return np.array([u, v])
49
50
51def old_approximation(x):
52 """
53 概要:
54 過去の実装で用いられていた遠方近似関数を計算します。
55 詳細説明:
56 厳密解ではなく比較用や境界値問題の初期推定値として使用します。
57 引数:
58 :param x: 評価する無次元距離の配列
59 :type x: numpy.ndarray
60 戻り値:
61 :returns: 近似された遮蔽関数の値
62 :rtype: numpy.ndarray
63 """
64 lam, scale = 3.886, 5.2415
65 return (1 + (x/scale)**(3/lam))**(-lam)
66
67
68def rhs(x, y, p=None):
69 """
70 概要:
71 Thomas-Fermi方程式の常微分方程式としての右辺を評価します。
72 詳細説明:
73 Newton反復中の負の試行値に対する実数拡張を行っており、解の負値を黙って切り捨てることはしません。
74 最終解は別途正値性を検査します。
75 引数:
76 :param x: 無次元距離
77 :type x: numpy.ndarray
78 :param y: 遮蔽関数とその1階微分を含む配列
79 :type y: numpy.ndarray
80 :param p: 未知パラメータのリスト
81 :type p: list
82 戻り値:
83 :returns: 導関数の値を格納した配列
84 :rtype: numpy.ndarray
85 """
86 # Newton反復中の負の試行値に対する実数拡張。
87 # 最終解は別途正値性を検査する。解の負値を黙って切り捨てない。
88 u, v = y
89 return np.array([v, np.sign(u)*np.abs(u)**1.5/np.sqrt(x)])
90
91
92def solve_tf(eps=1e-6, xmax=200., tol=1e-7, verbose=0):
93 """
94 概要:
95 Thomas-Fermi方程式の境界値問題を解きます。
96 詳細説明:
97 2本の常微分方程式と未知の原点での傾きに対して、3つの境界条件を用いて解を決定します。
98 引数:
99 :param eps: 原点側の開始位置
100 :type eps: float
101 :param xmax: 遠方側の境界位置
102 :type xmax: float
103 :param tol: 境界値問題の残差許容値
104 :type tol: float
105 :param verbose: ログの出力レベル
106 :type verbose: int
107 戻り値:
108 :returns: 境界値問題の解を格納したオブジェクト
109 :rtype: scipy.optimize.OptimizeResult
110 例外:
111 :raises RuntimeError: ソルバが収束しなかった場合や解が正値でない場合に発生します
112 """
113 def boundary(ya, yb, p):
114 left = origin_series(eps, p[0])
115 return np.array([ya[0]-left[0], ya[1]-left[1],
116 xmax*yb[1]+3*yb[0]])
117
118 x = np.geomspace(eps, xmax, 600)
119 u = old_approximation(x)
120 t = (x/5.2415)**(3/3.886)
121 v = -3*u*t/(x*(1+t))
122 sol = solve_bvp(rhs, boundary, x, np.vstack([u, v]), p=[-1.588],
123 tol=tol, bc_tol=min(tol, 1e-10), max_nodes=50000,
124 verbose=verbose)
125 if not sol.success:
126 raise RuntimeError('BVP did not converge: '+sol.message)
127 check = sol.sol(np.geomspace(eps, xmax, 5000))
128 if not np.all(np.isfinite(check)) or np.any(check[0] <= 0):
129 raise RuntimeError('Nonpositive or nonfinite solution: change domain/tolerance.')
130 if np.any(check[1] > 1e-10):
131 raise RuntimeError('Solution is not monotonically decreasing.')
132 return sol
133
134
135def shoot(eps, xmax, b):
136 """
137 概要:
138 Thomas-Fermi方程式を初期値問題として解き、軌道を探索します。
139 詳細説明:
140 遮蔽関数がゼロと交差するか、または値が2に達した時点で計算を停止するイベント関数を設定して積分を行います。
141 引数:
142 :param eps: 原点側の開始位置
143 :type eps: float
144 :param xmax: 遠方側の境界位置
145 :type xmax: float
146 :param b: 原点での傾きの試行値
147 :type b: float
148 戻り値:
149 :returns: 初期値問題の解を格納したオブジェクト
150 :rtype: scipy.optimize.OptimizeResult
151 """
152 def zero(x, y):
153 return y[0]
154 def large(x, y):
155 return y[0]-2
156 zero.terminal, zero.direction = True, -1
157 large.terminal, large.direction = True, 1
158 return solve_ivp(rhs, (eps, xmax), origin_series(eps, b),
159 method='DOP853', rtol=1e-10, atol=1e-12,
160 max_step=0.1, events=(zero, large), dense_output=True)
161
162
163def main(argv=None):
164 """
165 概要:
166 コマンドライン引数を解析し、計算と結果の保存を実行します。
167 詳細説明:
168 引数に基づいて境界値問題を解き、計算結果をCSVファイルとして保存し、プロットを画像ファイルとして出力します。
169 引数:
170 :param argv: コマンドライン引数のリスト
171 :type argv: list
172 戻り値:
173 :returns: なし
174 :rtype: None
175 """
176 ap = argparse.ArgumentParser(description=__doc__,
177 formatter_class=argparse.RawDescriptionHelpFormatter)
178 ap.add_argument('--xmax', type=float, default=200., help='遠方境界 (default: 200)')
179 ap.add_argument('--eps', type=float, default=1e-6, help='原点側開始位置')
180 ap.add_argument('--tol', type=float, default=1e-7, help='BVP残差許容値')
181 ap.add_argument('--points', type=int, default=3001, help='CSV・描画点数(対数格子)')
182 ap.add_argument('--prefix', default='thomas_fermi', help='出力名の接頭辞')
183 ap.add_argument('--shooting', action='store_true', help='初期傾き依存性の図を追加')
184 ap.add_argument('--delta-b', type=float, default=1e-4, help='shootingでの傾きの変化量')
185 ap.add_argument('--check-domain', action='store_true', help='xmaxを2倍にして比較')
186 ap.add_argument('--no-show', action='store_true', help='図を保存するだけで表示しない')
187 ap.add_argument('--verbose', action='store_true', help='BVP反復ログを表示')
188 args = ap.parse_args(argv)
189 if not (np.isfinite(args.eps) and 0 < args.eps <= 1e-2):
190 ap.error('eps は 0 < eps <= 0.01 にしてください。')
191 if not (np.isfinite(args.xmax) and args.xmax >= 10):
192 ap.error('xmax は有限値で10以上にしてください。')
193 if not (np.isfinite(args.tol) and 1e-12 <= args.tol <= 1e-2):
194 ap.error('tol は 1e-12~1e-2 にしてください。')
195 if args.points < 100 or not (np.isfinite(args.delta_b) and args.delta_b > 0):
196 ap.error('points >= 100, delta-b > 0 にしてください。')
197
198 sol = solve_tf(args.eps, args.xmax, args.tol, 2 if args.verbose else 0)
199 b = float(sol.p[0])
200 x = np.r_[0., np.geomspace(args.eps, args.xmax, args.points-1)]
201 u, v = np.column_stack(([1., b], sol.sol(x[1:])))
202 near = origin_series(x, b)[0]
203 old = old_approximation(x)
204 far = np.full_like(x, np.nan)
205 far[1:] = 144/x[1:]**3
206 # 微分した補間解とODE右辺の差。原点ではphi''が発散するためNaN。
207 residual = np.full_like(x, np.nan)
208 residual[1:] = sol.sol(x[1:], 1)[1] - u[1:]**1.5/np.sqrt(x[1:])
209 print('Thomas-Fermi neutral atom: dimensionless x and phi')
210 print(f"B = phi'(0) : {b:.12f}")
211 print(f'BVP iterations : {sol.niter}; mesh nodes: {len(sol.x)}')
212 print(f'Max RMS residual : {max(sol.rms_residuals):.3e}')
213 print(f'Outer BC residual: {args.xmax*v[-1]+3*u[-1]:.3e}')
214 print(f'xmax^3 phi / 144 : {args.xmax**3*u[-1]/144:.8f} (asymptotic limit: 1)')
215 print('Finite-domain boundary approximation: use --check-domain to assess it.')
216 if args.check_domain:
217 larger = solve_tf(args.eps, 2*args.xmax, args.tol)
218 relative = np.abs(larger.sol(x[1:])[0]-u[1:])/larger.sol(x[1:])[0]
219 inner = x[1:] <= min(10., args.xmax/2)
220 print(f'Domain doubled: B = {larger.p[0]:.12f}, delta B = {larger.p[0]-b:+.3e}')
221 print(f'Max relative phi change (x <= {min(10., args.xmax/2):g}): {max(relative[inner]):.3e}')
222 print(f'Max relative phi change (whole original domain): {max(relative):.3e}')
223
224 out = Path(args.prefix)
225 out.parent.mkdir(parents=True, exist_ok=True)
226 csv_path, png_path = Path(str(out)+'.csv'), Path(str(out)+'.png')
227 np.savetxt(csv_path, np.column_stack((x, u, v, near, old, far, residual)),
228 delimiter=',', header='x,phi,dphi_dx,origin_series,old_approximation,144_over_x3,ode_residual',
229 comments='', fmt='%.12e')
230 import matplotlib
231 if args.no_show:
232 matplotlib.use('Agg')
233 import matplotlib.pyplot as plt
234 fig, axes = plt.subplots(2, 2, figsize=(12, 8), constrained_layout=True)
235 ax = axes[0, 0]
236 ax.plot(x, u, label='BVP solution', lw=2)
237 mask = x <= 0.5
238 ax.plot(x[mask], near[mask], '--', label='Origin series (x <= 0.5)')
239 ax.plot(x, old, ':', label='Old Perl approximation')
240 ax.set(xlim=(0, 5), ylim=(0, 1.05), ylabel='Screening function phi')
241 ax.legend()
242 ax = axes[0, 1]
243 ax.loglog(x[1:], u[1:], label='BVP solution')
244 mask = x >= 10
245 ax.loglog(x[mask], far[mask], '--', label='144 / x^3 (far limit)')
246 ax.loglog(x[1:], old[1:], ':', label='Old Perl approximation')
247 ax.set(xlim=(1e-2, args.xmax), ylim=(min(u[-1]/2, 1e-4), 2), ylabel='Screening function phi')
248 ax.legend()
249 ax = axes[1, 0]
250 ax.semilogx(x[1:], v[1:])
251 ax.set(ylabel="Slope dphi/dx", title=f"Origin slope B = {b:.9f}")
252 ax = axes[1, 1]
253 if args.shooting:
254 ax.plot(x, u, 'k--', label='BVP reference', lw=2)
255 for shift in (-args.delta_b, 0., args.delta_b):
256 ivp = shoot(args.eps, min(args.xmax, 30), b+shift)
257 label = f'B {shift:+.1e}' if shift else 'B (outward IVP)'
258 ax.plot(ivp.t, ivp.y[0], label=label)
259 print(f'Shooting delta B={shift:+.2e}: x_end={ivp.t[-1]:.6g}; {ivp.message}')
260 ax.set(xlim=(0, min(args.xmax, 30)), ylim=(0, 1.1), ylabel='phi', title='Sensitivity to initial slope')
261 ax.legend(fontsize=8)
262 else:
263 ax.semilogx(x[1:], (old[1:]-u[1:])/u[1:]*100)
264 ax.axhline(0, color='gray', lw=0.8)
265 ax.set(ylabel='Relative difference (%)', title='Old approximation vs BVP')
266 for ax in axes.flat:
267 ax.set_xlabel('Dimensionless distance x')
268 ax.grid(True, alpha=0.25)
269 fig.suptitle('Thomas-Fermi equation: boundary conditions determine the solution')
270 fig.savefig(png_path, dpi=160)
271 print(f'Saved: {csv_path}\nSaved: {png_path}')
272 if not args.no_show:
273 plt.show()
274 plt.close(fig)
275
276
277if __name__ == '__main__':
278 try:
279 main()
280 except (RuntimeError, OSError) as exc:
281 print(f'Error: {exc}', file=sys.stderr)
282 sys.exit(1)