he_hartree_numerov.py ダウンロード/コピー
he_hartree_numerov.py
he_hartree_numerov.py
1#!/usr/bin/env python3
2"""
3概要:
4 He 1s^2 Hartree SCF: Numerov inward/outward matching (atomic units)
5
6詳細説明:
7 u=r R, integral(u^2 dr)=1。p=u^2 は1電子の動径確率密度です。
8 全電子の動径密度は2p、3次元密度は2p/(4*pi*r^2)となります。
9 他方の電子だけからVHを作るため、自己相互作用を含めません。
10 このHe 1s^2の制限Hartree方程式は閉殻HFと一致します。
11 iter=1は初期密度で固定したポテンシャルを1回解くone-shot処理です。
12 SCF収束とグリッド/rmax収束は別であり、tolを小さくしても離散化誤差は残ります。
13 密度残差はmixing前のp_out-p_inです。小さいmixingによる偽収束を防ぎます。
14 未収束時には E=2*epsilon-J_out は使えません。
15 E = 2*(uに対するT-2/rの期待値) + J_out を出力軌道について評価します。
16 依存ライブラリは numpy scipy matplotlib です。
17 実行例は python he_hartree_numerov.py --iter 100 --mixing 0.3 --tol 1e-8 などです。
18"""
19
20import argparse
21import csv
22import numpy as np
23from scipy.integrate import simpson, cumulative_trapezoid
24from scipy.linalg import eigh_tridiagonal
25from scipy.optimize import brentq
26
27REFERENCE = -2.861680 # rounded HF reference, Ha; not an exact correlated energy
28
29
30def integral(y, r):
31 """
32 概要:
33 シンプソン法を用いて関数を数値積分します。
34
35 引数:
36 :param y: 被積分関数の値の配列。
37 :type y: numpy.ndarray
38 :param r: 積分変数の配列。
39 :type r: numpy.ndarray
40
41 戻り値:
42 :returns: 積分結果。
43 :rtype: float
44 """
45 return float(simpson(y, x=r))
46
47
48def normalize(u, r):
49 """
50 概要:
51 波動関数を規格化します。
52
53 詳細説明:
54 uの二乗積分が1になるように定数倍します。
55
56 引数:
57 :param u: 波動関数の配列。
58 :type u: numpy.ndarray
59 :param r: 径方向のグリッド配列。
60 :type r: numpy.ndarray
61
62 戻り値:
63 :returns: 規格化された波動関数の配列。
64 :rtype: numpy.ndarray
65 """
66 return u / np.sqrt(integral(u*u, r))
67
68
69def hartree(r, p):
70 """
71 概要:
72 Hartreeポテンシャルを計算します。
73
74 詳細説明:
75 VH(r)=Q(<r)/r + integral_r^infinity p(s)/s ds で計算されます。pは積分して1になる密度です。
76
77 引数:
78 :param r: 径方向のグリッド配列。
79 :type r: numpy.ndarray
80 :param p: 確率密度の配列。
81 :type p: numpy.ndarray
82
83 戻り値:
84 :returns: 計算されたHartreeポテンシャルの配列。
85 :rtype: numpy.ndarray
86 """
87 f = np.zeros_like(r)
88 f[1:] = p[1:] / r[1:]
89 inside = cumulative_trapezoid(p, r, initial=0)
90 outside = -cumulative_trapezoid(f[::-1], r[::-1], initial=0)[::-1]
91 vh = outside.copy()
92 vh[1:] += inside[1:] / r[1:]
93 return vh
94
95
96def numerov_branch(q, h, y0, y1):
97 """
98 概要:
99 Numerov法による微分方程式の片側積分を実行します。
100
101 詳細説明:
102 y''=q*y を解きます。qは選択した積分方向に従って並べられていると仮定します。
103
104 引数:
105 :param q: 方程式の係数配列。
106 :type q: numpy.ndarray
107 :param h: グリッドの間隔。
108 :type h: float
109 :param y0: 最初の点の初期値。
110 :type y0: float
111 :param y1: 2番目の点の初期値。
112 :type y1: float
113
114 戻り値:
115 :returns: Numerov法で積分された配列。
116 :rtype: numpy.ndarray
117 """
118 y = np.empty(len(q))
119 y[:2] = y0, y1
120 a = h*h/12
121 for i in range(1, len(q)-1):
122 y[i+1] = ((2+10*a*q[i])*y[i] - (1-a*q[i-1])*y[i-1]) / (1-a*q[i+1])
123 if abs(y[i+1]) > 1e100:
124 y[:i+2] *= 1e-100
125 return y
126
127
128def solve_numerov(r, vh):
129 """
130 概要:
131 Numerov法を用いて基底状態を解きます。
132
133 詳細説明:
134 粗い有限差分固有値は根の探索区間の目安だけに用います。
135 最終固有値と軌道は両側Numerov積分と接続条件で決定します。
136
137 引数:
138 :param r: 径方向のグリッド配列。
139 :type r: numpy.ndarray
140 :param vh: Hartreeポテンシャルの配列。
141 :type vh: numpy.ndarray
142
143 戻り値:
144 :returns: 固有値、波動関数の配列、ミスマッチの絶対値からなるタプル。
145 :rtype: tuple
146
147 例外:
148 :raises RuntimeError: 根の探索に失敗した場合、または励起状態の根に遭遇した場合。
149 """
150 h = r[1]
151 v = np.zeros_like(r)
152 v[1:] = -2/r[1:] + vh[1:]
153 m = int(np.clip(round(1.2/h), 4, len(r)-5))
154
155 def branches(e):
156 """
157 概要:
158 指定したエネルギーに対する外向きと内向きの波動関数を計算します。
159
160 引数:
161 :param e: 試行エネルギー。
162 :type e: float
163
164 戻り値:
165 :returns: 外向きと内向きの波動関数配列のタプル。
166 :rtype: tuple
167 """
168 # 原点の正則級数 u=r*(1-Z*r+b*r^2+c*r^3)。VH'(0)=0。
169 z = 2.0
170 b = (z*z + vh[0]-e)/3
171 c = (-z*b-z*(vh[0]-e))/6
172 seed = lambda x: x*(1-z*x+b*x*x+c*x**3)
173 q = 2*(v-e)
174 out = numerov_branch(q[1:m+3], h, seed(h), seed(2*h))
175 # 遠方はV=-1/r。u ~ exp(-k*r)*r^(1/k)。比を使いunderflow回避。
176 k = np.sqrt(-2*e)
177 ratio = np.exp(k*h + np.log(r[-2]/r[-1])/k)
178 inn = numerov_branch(q[m-2:][::-1], h, 1.0, ratio)[::-1]
179 out /= np.max(np.abs(out))
180 inn /= np.max(np.abs(inn))
181 return out, inn
182
183 def mismatch(e):
184 """
185 概要:
186 接続点での波動関数の微分の不一致を計算します。
187
188 引数:
189 :param e: 試行エネルギー。
190 :type e: float
191
192 戻り値:
193 :returns: 接続条件のミスマッチ量。
194 :rtype: float
195 """
196 a, b = branches(e)
197 # 接続点中心の5点微分。配列aではm-1、bでは2が接続点。
198 i = m-1
199 da = (a[i-2]-8*a[i-1]+8*a[i+1]-a[i+2])/(12*h)
200 db = (b[0]-8*b[1]+8*b[3]-b[4])/(12*h)
201 return da*b[2]-a[i]*db
202
203 guess = eigh_tridiagonal(1/h**2+v[1:-1],
204 np.full(len(r)-3, -0.5/h**2),
205 select='i', select_range=(0, 0),
206 eigvals_only=True)[0]
207 width = 0.02
208 for _ in range(8):
209 lo, hi = max(-2.1, guess-width), min(-1e-5, guess+width)
210 if mismatch(lo)*mismatch(hi) < 0:
211 break
212 width *= 1.7
213 else:
214 raise RuntimeError('Cannot bracket ground state; refine grid / enlarge rmax.')
215 e = brentq(mismatch, lo, hi, xtol=2e-12)
216 a, b = branches(e)
217 u = np.zeros_like(r)
218 u[1:m+1] = a[:m]
219 u[m+1:] = b[3:] * a[m-1]/b[2]
220 u = normalize(u, r)
221 significant = u[np.abs(u) > 1e-8*np.max(np.abs(u))]
222 if np.any(significant[:-1]*significant[1:] < 0):
223 raise RuntimeError('Excited-state root encountered (radial node).')
224 if u[1] < 0:
225 u = -u
226 return e, u, abs(mismatch(e))
227
228
229def energy(r, u):
230 """
231 概要:
232 変分全エネルギーを計算します。
233
234 詳細説明:
235 自己無撞着になる前の状態でも有効な全エネルギーを計算します。
236
237 引数:
238 :param r: 径方向のグリッド配列。
239 :type r: numpy.ndarray
240 :param u: 波動関数の配列。
241 :type u: numpy.ndarray
242
243 戻り値:
244 :returns: 全エネルギー、運動エネルギー、原子核引力エネルギー、クーロン反発エネルギーのタプル。
245 :rtype: tuple
246 """
247 h = r[1]
248 du = np.gradient(u, h, edge_order=2)
249 du[2:-2] = (u[:-4]-8*u[1:-3]+8*u[3:-1]-u[4:])/(12*h)
250 # 原点の片側4次微分
251 du[0] = (-25*u[0]+48*u[1]-36*u[2]+16*u[3]-3*u[4])/(12*h)
252 du[1] = (-3*u[0]-10*u[1]+18*u[2]-6*u[3]+u[4])/(12*h)
253 p = u*u
254 t = 0.5*integral(du*du, r)
255 vn = np.zeros_like(r)
256 vn[1:] = -2*p[1:]/r[1:]
257 nuclear = integral(vn, r)
258 j = integral(p*hartree(r, p), r)
259 return 2*(t+nuclear)+j, t, nuclear, j
260
261
262def references():
263 """
264 概要:
265 参考文献の情報を標準出力に表示します。
266
267 戻り値:
268 :returns: なし
269 :rtype: None
270 """
271 print('\nReference (nonrelativistic, infinite nuclear mass, He 1s^2):')
272 print(' Restricted Hartree = closed-shell HF: E_total ~ -2.86168 Ha')
273 print(' Correlated benchmark (NOT the SCF target): ~ -2.90372 Ha')
274 print(' A. W. Weiss, Oscillator Strengths for the Helium Isoelectronic Sequence,')
275 print(' J. Res. Natl. Bur. Stand. A Phys. Chem. 71A, 163-168 (1967), Table 1.')
276 print(' https://doi.org/10.6028/jres.071A.023')
277 print(' https://nvlpubs.nist.gov/nistpubs/jres/71A/jresv71An2p163_A1b.pdf')
278
279
280def main():
281 """
282 概要:
283 コマンドライン引数を解析し、HeのHartree-Fock計算を実行します。
284
285 詳細説明:
286 設定されたパラメータに基づいて自己無撞着場のイテレーションを行い、
287 結果をコンソールに出力します。オプションでCSVやグラフ出力も行います。
288
289 戻り値:
290 :returns: 終了ステータスコード。成功時は0、エラー時は0以外。
291 :rtype: int
292 """
293 ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
294 ap.add_argument('--iter', type=int, default=1, help='maximum solves (default: 1, one-shot)')
295 ap.add_argument('--mixing', type=float, default=0.3, help='new-density fraction, (0,1]')
296 ap.add_argument('--tol', type=float, default=1e-8, help='density L1 tolerance; default energy tolerance in Ha')
297 ap.add_argument('--tol-energy', type=float, help='energy tolerance in Ha (overrides --tol)')
298 ap.add_argument('--ngrid', type=int, default=6000, help='radial intervals')
299 ap.add_argument('--rmax', type=float, default=30.0, help='outer radius in Bohr')
300 ap.add_argument('--zeta', type=float, default=2.0, help='initial hydrogenic exponent')
301 ap.add_argument('--no-plot', action='store_true')
302 ap.add_argument('--savefig', help='optional figure filename')
303 ap.add_argument('--csv', help='optional history CSV filename')
304 args = ap.parse_args()
305 etol = args.tol if args.tol_energy is None else args.tol_energy
306 if args.iter < 1 or not 0 < args.mixing <= 1 or args.ngrid < 200 or args.rmax < 10 or args.zeta <= 0 or args.tol <= 0 or etol <= 0:
307 ap.error('Require iter>=1, 0<mixing<=1, ngrid>=200, rmax>=10, zeta>0, tolerances>0.')
308 r = np.linspace(0, args.rmax, args.ngrid+1)
309 if r[1] > 0.05:
310 ap.error('Grid too coarse: require rmax/ngrid <= 0.05 Bohr.')
311 u0 = normalize(r*np.exp(-args.zeta*r), r)
312 p = u0*u0
313 previous = energy(r, u0)[0]
314 hist = []
315 snapshots = []
316 converged = False
317 print('He 1s^2 Hartree / two-sided Numerov; atomic units')
318 print(f'h={r[1]:.6g} Bohr, rmax={args.rmax:g}, mixing={args.mixing:g}')
319 print(f'tol_density={args.tol:g}; tol_energy={etol:g} Ha')
320 print(f'Initial trial energy: {previous:.10f} Ha')
321 print(' iter N_electron epsilon[Ha] E_total[Ha] dE[Ha] residual_L1')
322 try:
323 for it in range(1, args.iter+1):
324 vh = hartree(r, p)
325 eps, u, match = solve_numerov(r, vh)
326 pout = u*u
327 total, t, vn, j = energy(r, u)
328 delta = total-previous
329 residual = integral(np.abs(pout-p), r)
330 ne = 2*integral(pout, r)
331 # 独立チェック: h_expect=eps-<VH_in>; 未収束でも使える。
332 identity = 2*eps-2*integral(pout*vh, r)+j
333 hist.append((it, ne, eps, total, delta, residual, match, total-identity))
334 snapshots.append(pout.copy())
335 print(f'{it:5d} {ne:12.8f} {eps:16.10f} {total:16.10f} {delta:+12.3e} {residual:14.3e}', flush=True)
336 if abs(delta) < etol and residual < args.tol:
337 converged = True
338 break
339 p = (1-args.mixing)*p + args.mixing*pout
340 previous = total
341 except RuntimeError as exc:
342 print(f'Numerov failure: {exc}')
343 if not hist:
344 references()
345 return 2
346 status = 'SCF CONVERGED' if converged else ('ONE-SHOT (not SCF converged)' if args.iter == 1 else 'NOT CONVERGED: last output retained')
347 print('\n'+status)
348 print(f'E_total - rounded HF reference = {total-REFERENCE:+.6e} Ha')
349 print(f'T(two electrons)={2*t:.10f}; V_nuclear={2*vn:.10f}; J={j:.10f} Ha')
350 print(f'Virial residual 2T+V = {4*t+2*vn+j:+.3e} Ha')
351 print(f'Energy quadrature/identity discrepancy = {total-identity:+.3e} Ha')
352 print('N_electron is checked AFTER normalization; it is not an SCF residual.')
353 print('SCF tolerance does not bound grid/box error. Repeat with doubled ngrid and larger rmax.')
354 references()
355 if args.csv:
356 with open(args.csv, 'w', newline='', encoding='utf-8') as stream:
357 writer = csv.writer(stream)
358 writer.writerow(('iteration','N_electron','epsilon_Ha','E_total_Ha','dE_Ha','density_residual_L1','matching_residual','energy_identity_error_Ha'))
359 writer.writerows(hist)
360 if not args.no_plot or args.savefig:
361 import matplotlib.pyplot as plt
362 fig, axes = plt.subplots(2, 2, figsize=(11, 8), constrained_layout=True)
363 ax = axes[0, 0]
364 ax.plot(r, 2*u0*u0, '--', label='initial')
365 for idx in np.unique(np.linspace(0, len(snapshots)-1, min(6, len(snapshots))).astype(int)):
366 ax.plot(r, 2*snapshots[idx], label=f'iter {idx+1}')
367 ax.set(xlim=(0, 6), xlabel='r [Bohr]', ylabel='Radial electron density 2|u|^2')
368 ax.legend()
369 ax = axes[0, 1]
370 ax.plot(r[1:], -2/r[1:], '--', label='nuclear')
371 ax.plot(r, vh, label='Hartree input (last solve)')
372 ax.plot(r[1:], -2/r[1:]+vh[1:], label='effective input')
373 ax.set(xlim=(0, 6), ylim=(-5, 2.5), xlabel='r [Bohr]', ylabel='Potential [Ha]')
374 ax.legend()
375 data = np.array(hist)
376 ax = axes[1, 0]
377 ax.plot(np.r_[0, data[:, 0]], np.r_[energy(r, u0)[0], data[:, 3]], 'o-', label='total energy')
378 ax.axhline(REFERENCE, ls='--', color='black', label='HF reference')
379 ax.set(xlabel='Iteration', ylabel='E_total [Ha]')
380 ax.legend()
381 ax = axes[1, 1]
382 ax.semilogy(data[:, 0], np.maximum(data[:, 5], 1e-16), 'o-', label='density L1')
383 ax.semilogy(data[:, 0], np.maximum(np.abs(data[:, 4]), 1e-16), 's-', label='|dE| [Ha]')
384 ax.set(xlabel='Iteration', ylabel='Residual (different units; see legend)')
385 ax.legend()
386 fig.suptitle(status)
387 if args.savefig:
388 fig.savefig(args.savefig, dpi=160)
389 if not args.no_plot:
390 plt.show()
391 plt.close(fig)
392 return 0
393
394
395if __name__ == '__main__':
396 raise SystemExit(main())