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

ho_thomas_fermi.py をダウンロード

ho_thomas_fermi.py
ho_thomas_fermi.py
  1#!/usr/bin/env python3
  2# -*- coding: utf-8 -*-
  3"""
  4概要:
  5    1次元調和ポテンシャルにおける厳密軌道解とThomas-Fermi近似の比較教材です。
  6
  7準備:
  8    python -m pip install numpy scipy matplotlib
  9
 10実行:
 11    python ho_thomas_fermi.py
 12    python ho_thomas_fermi.py --N 1
 13    python ho_thomas_fermi.py --N 20 --check
 14    python ho_thomas_fermi.py --N 8 --no-show --prefix results/ho8
 15
 16モデルと単位:
 17    非相互作用、温度ゼロ、スピン自由度なし、または完全スピン偏極を仮定します。
 18    1軌道に1粒子が入り、Nは粒子数であると同時に占有軌道数となります。
 19    共通の調和ポテンシャルに閉じ込めたフェルミ粒子で、多電子相互作用はありません。
 20    長さ a=sqrt(hbar/(m*omega))、エネルギー hbar*omega を単位とします。
 21    以下の x は x_phys/a、V=x^2/2、密度の単位は1/aです。
 22    K(x)とU(x) はエネルギー密度 hbar*omega/a、Vは一粒子のエネルギーです。
 23    軌道phiの単位はa^(-1/2)であり、表示する軌道番号はn=1..Nです。
 24    通常の振動子量子数j=n-1、epsilon_n=n-1/2となり、基底状態はn=1です。
 25
 26厳密解:
 27    phi_1=pi^(-1/4) exp(-x^2/2), phi_2=sqrt(2)x phi_1と定義します。
 28    規格化したHermite関数の漸化式から高階軌道を作ります。
 29    n_exact=sum(phi_n^2), K_exact=1/2 sum((dphi_n/dx)^2)です。
 30    微分は隣接軌道による解析的な漸化式で計算し、数値差分ではありません。
 31    U_exact=V*n_exactとなり、運動エネルギー密度は正定値の定義を採用します。
 32    別定義 -1/2 sum(phi*phi'') は局所的には異なりますが積分値は同じです。
 33
 34TF近似:
 35    T_TF(n)=(pi^2/6) integral n^3 dxと表されます。
 36    E_TF(n)=T_TF(n)+integral V*n dx を粒子数固定で最小化すると、
 37    n_TF=sqrt(2(mu-V))/pi ただし mu>V であり、それ以外ゼロとなります。
 38    規格化からmu=N、転回点x_TF=+-sqrt(2N)となり、K_TF=(pi^2/6)*n_TF^3です。
 39    この特別な系ではT=U=N^2/4、E=N^2/2が厳密解とTFで一致します。
 40    しかし局所密度は異なります。TF汎関数に厳密密度を代入する3番目の比較
 41    K_TF_on_exact=(pi^2/6)*n_exact^3 は、汎関数の近似誤差を示します。
 42    この3番目の計算は最小化して得た状態ではなく、汎関数の評価実験です。
 43
 44出力:
 45    PREFIX_comparison.png はV、K、n、U、エネルギー比較、密度差の図です。
 46    PREFIX_orbitals_01.png などはn=1..N全軌道を描画し、1ページ12軌道です。
 47    PREFIX_profiles.csv は密度とエネルギー密度の共通x格子データです。
 48    PREFIX_orbitals.csv は全軌道とその微分のデータです。
 49    PREFIX_energies.csv と PREFIX_summary.txt は積分値と説明を記録します。
 50    同名の出力は上書きされます。図は英語表記で日本語フォントに依存しません。
 51    CSVのTF積分は格子上のSimpson法なので転回点の平方根形による誤差があります。
 52    エネルギー表のTF値は転回点で区切った適応積分を使用します。
 53    --checkオプションで格子細分化と積分範囲拡大を独立に検証できます。
 54"""
 55from __future__ import annotations
 56import argparse
 57import csv
 58from pathlib import Path
 59import sys
 60import numpy as np
 61from scipy.integrate import simpson, quad
 62
 63
 64def orbitals(x, number):
 65    """
 66    概要:
 67        占有軌道指定本数と、微分に必要な次の軌道を漸化式で作成します。
 68
 69    詳細説明:
 70        規格化したHermite関数の漸化式を用いて、基底状態から指定された数の
 71        波動関数とその1階導関数を計算します。微分は解析的な漸化式で計算します。
 72
 73    引数:
 74        :param x: 空間座標の1次元配列
 75        :type x: numpy.ndarray
 76        :param number: 計算する軌道の数
 77        :type number: int
 78
 79    戻り値:
 80        :returns: 軌道の配列と導関数の配列のタプル
 81        :rtype: tuple
 82    """
 83    phi = np.empty((number+1, len(x)))
 84    phi[0] = np.pi**(-0.25)*np.exp(-x*x/2)
 85    phi[1] = np.sqrt(2)*x*phi[0]
 86    for j in range(1, number):
 87        phi[j+1] = np.sqrt(2/(j+1))*x*phi[j]-np.sqrt(j/(j+1))*phi[j-1]
 88    derivative = np.empty((number, len(x)))
 89    for j in range(number):
 90        left = np.sqrt(j/2)*phi[j-1] if j else 0.
 91        derivative[j] = left-np.sqrt((j+1)/2)*phi[j+1]
 92    return phi[:number], derivative
 93
 94
 95def calculate(number, xmax, points):
 96    """
 97    概要:
 98        厳密解およびTF近似によるエネルギーと密度を計算します。
 99
100    詳細説明:
101        指定された軌道数、空間範囲、格子点数を用いて、波動関数、運動エネルギー、
102        ポテンシャルエネルギーを計算し、TF近似との比較データを生成します。
103
104    引数:
105        :param number: 粒子数および占有軌道数
106        :type number: int
107        :param xmax: 空間座標の最大絶対値
108        :type xmax: float
109        :param points: 空間座標の格子点数
110        :type points: int
111
112    戻り値:
113        :returns: 各種計算結果を格納した辞書
114        :rtype: dict
115    """
116    x = np.linspace(-xmax, xmax, points)
117    phi, derivative = orbitals(x, number)
118    v = x*x/2
119    density = np.sum(phi*phi, axis=0)
120    kinetic = np.sum(derivative*derivative, axis=0)/2
121    tf_density = np.sqrt(np.maximum(2*number-x*x, 0))/np.pi
122    tf_kinetic = np.pi**2/6*tf_density**3
123    on_exact = np.pi**2/6*density**3
124    potential = v*density
125    tf_potential = v*tf_density
126    integrate = lambda a: float(simpson(a, x=x))
127    # TFの非解析的な端点を積分範囲の端に置き、格子の配置に依存させない。
128    edge = np.sqrt(2*number)
129    def ntf(t):
130        return np.sqrt(max(2*number-t*t, 0))/np.pi
131    tf_n = 2*quad(ntf, 0, edge, epsabs=1e-10, epsrel=1e-11)[0]
132    tf_t = 2*quad(lambda t: np.pi**2/6*ntf(t)**3, 0, edge, epsabs=1e-10, epsrel=1e-11)[0]
133    tf_u = 2*quad(lambda t: t*t/2*ntf(t), 0, edge, epsabs=1e-10, epsrel=1e-11)[0]
134    rows = []
135    for name, norm, t, u in [
136        ('Exact orbitals', integrate(density), integrate(kinetic), integrate(potential)),
137        ('TF minimum', tf_n, tf_t, tf_u),
138        ('TF on exact density', integrate(density), integrate(on_exact), integrate(potential)),
139        ('Analytical reference', float(number), number**2/4, number**2/4)]:
140        rows.append((name, norm, t, u, t+u))
141    return dict(x=x, phi=phi, derivative=derivative, v=v, density=density,
142                kinetic=kinetic, tf_density=tf_density, tf_kinetic=tf_kinetic,
143                on_exact=on_exact, potential=potential, tf_potential=tf_potential,
144                rows=rows, tf_grid_norm=integrate(tf_density),
145                norms=simpson(phi*phi, x=x, axis=1))
146
147
148def save_and_plot(data, args):
149    """
150    概要:
151        計算結果をCSVファイルとして保存し、比較グラフを描画します。
152
153    詳細説明:
154        解析で得られた密度やエネルギーのプロファイル、全占有軌道の形状をプロットし、
155        指定された接頭辞を持つファイルに出力します。
156
157    引数:
158        :param data: calculate関数から返された計算結果の辞書
159        :type data: dict
160        :param args: コマンドライン引数を格納した名前空間オブジェクト
161        :type args: argparse.Namespace
162
163    戻り値:
164        :returns: なし
165        :rtype: None
166    """
167    import matplotlib
168    if args.no_show:
169        matplotlib.use('Agg')
170    import matplotlib.pyplot as plt
171    prefix = Path(args.prefix)
172    prefix.parent.mkdir(parents=True, exist_ok=True)
173    x = data['x']
174    names = ['x_over_a', 'V', 'n_exact', 'n_TF', 'K_exact', 'K_TF',
175             'K_TF_on_exact_density', 'U_exact', 'U_TF']
176    keys = ['x', 'v', 'density', 'tf_density', 'kinetic', 'tf_kinetic',
177            'on_exact', 'potential', 'tf_potential']
178    np.savetxt(str(prefix)+'_profiles.csv', np.column_stack([data[k] for k in keys]),
179               delimiter=',', header=','.join(names), comments='', fmt='%.12e')
180    names = ['x_over_a']+[f'phi_{n}' for n in range(1,args.N+1)]+[f'dphi_{n}_dx' for n in range(1,args.N+1)]
181    np.savetxt(str(prefix)+'_orbitals.csv', np.column_stack([x, data['phi'].T, data['derivative'].T]),
182               delimiter=',', header=','.join(names), comments='', fmt='%.12e')
183    with open(str(prefix)+'_energies.csv', 'w', newline='', encoding='utf-8') as f:
184        writer = csv.writer(f)
185        writer.writerow(['method','particle_number','T_over_hw','U_over_hw','E_over_hw'])
186        writer.writerows(data['rows'])
187    fig, axes = plt.subplots(2, 3, figsize=(15, 8), constrained_layout=True)
188    ax = axes[0,0]
189    ax.plot(x, data['v'], color='black', label='V(x) = x^2/2')
190    ax.axhline(args.N, color='tab:orange', ls='--', label=f'TF chemical potential = {args.N}')
191    ax.set(title='External potential (same in both models)', ylabel='V / (hbar omega)')
192    ax.legend(fontsize=8)
193    for ax, k1, k2, title, ylabel in [
194        (axes[0,1], 'kinetic','tf_kinetic','Kinetic energy density (positive definition)','K / (hbar omega / a)'),
195        (axes[0,2], 'density','tf_density','Particle density','n / (1/a)'),
196        (axes[1,0], 'potential','tf_potential','Potential energy density U(x) = V(x)n(x)','U / (hbar omega / a)')]:
197        ax.plot(x, data[k1], label='Exact orbitals', lw=1.8)
198        ax.plot(x, data[k2], '--', label='TF minimum', lw=1.7)
199        ax.set(title=title, ylabel=ylabel)
200        if k1 == 'kinetic':
201            ax.plot(x, data['on_exact'], ':', color='tab:green', label='TF functional on exact density')
202        ax.legend(fontsize=8)
203    ax = axes[1,1]
204    for i, row in enumerate(data['rows'][:3]):
205        ax.bar(np.arange(3)+(i-1)*.25, row[2:], width=.25, label=row[0])
206    ax.set_xticks(np.arange(3), ['T', 'U', 'E = T + U'])
207    ax.set(title='Integrated energies', ylabel='Energy / (hbar omega)')
208    ax.legend(fontsize=8)
209    ax = axes[1,2]
210    ax.plot(x, data['density']-data['tf_density'], color='tab:purple')
211    ax.axhline(0, color='gray', lw=.7)
212    ax.set(title='Density difference: exact - TF', ylabel='Density difference / (1/a)')
213    for ax in axes.flat:
214        ax.grid(alpha=.2)
215        if ax is not axes[1,1]:
216            ax.set_xlabel('x / a')
217            view = min(x[-1], np.sqrt(2*args.N)+3)
218            ax.set_xlim(-view, view)
219            if ax is axes[0,0]:
220                ax.set_ylim(0, view*view/2)
221            for edge in (-np.sqrt(2*args.N), np.sqrt(2*args.N)):
222                ax.axvline(edge, color='gray', ls=':', lw=.7)
223    fig.suptitle(f'1D harmonic trap: N={args.N} noninteracting spinless fermions, T=0', fontsize=14)
224    fig.savefig(str(prefix)+'_comparison.png', dpi=160)
225    if args.no_show:
226        plt.close(fig)
227    # 全占有軌道を省略せず表示する。12本ごとに別ページ。
228    for start in range(0, args.N, 12):
229        count = min(12, args.N-start)
230        columns = min(3, count)
231        rows = (count+columns-1)//columns
232        fig, axes = plt.subplots(rows, columns, figsize=(5*columns, 2.6*rows),
233                                 squeeze=False, constrained_layout=True)
234        for ax in axes.flat[count:]:
235            ax.set_visible(False)
236        for offset, ax in enumerate(axes.flat[:count]):
237            j = start+offset
238            ax.plot(x, data['phi'][j], color=f'C{j%10}')
239            ax.axhline(0, color='gray', lw=.6)
240            ax.set(title=f'n={j+1} (j={j}), energy={j+0.5:g}, nodes={j}',
241                   xlabel='x / a', ylabel='phi_n / a^(-1/2)')
242            ax.set_xlim(-min(x[-1], np.sqrt(2*j+1)+3), min(x[-1], np.sqrt(2*j+1)+3))
243            ax.grid(alpha=.2)
244        fig.suptitle('Occupied orbitals: one particle in each orbital; integral |phi_n|^2 dx = 1')
245        fig.savefig(str(prefix)+f'_orbitals_{start//12+1:02d}.png', dpi=150)
246        if args.no_show:
247            plt.close(fig)
248    if not args.no_show:
249        plt.show()
250        plt.close('all')
251
252
253def main(argv=None):
254    """
255    概要:
256        1次元調和ポテンシャルにおける厳密解とTF近似の比較を実行します。
257
258    詳細説明:
259        コマンドライン引数を解析し、計算処理、結果の検証、ファイル保存、
260        グラフ描画の一連の処理を順に実行します。
261
262    引数:
263        :param argv: コマンドライン引数のリスト
264        :type argv: list
265
266    戻り値:
267        :returns: なし
268        :rtype: None
269    """
270    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
271    ap.add_argument('--N', '--n', type=int, default=6, help='粒子数/占有軌道数、1..100 (default:6)')
272    ap.add_argument('--points', type=int, default=6001, help='描画・積分用格子点数')
273    ap.add_argument('--xmax', type=float, help='x/aの最大絶対値。既定sqrt(2N)+8')
274    ap.add_argument('--prefix', default='ho_tf', help='出力名の接頭辞')
275    ap.add_argument('--check', action='store_true', help='格子・範囲への依存性を検証')
276    ap.add_argument('--no-show', action='store_true', help='図を保存して終了')
277    args = ap.parse_args(argv)
278    if not 1 <= args.N <= 100:
279        ap.error('N must be between 1 and 100.')
280    xmax = args.xmax if args.xmax is not None else np.sqrt(2*args.N)+8
281    if not np.isfinite(xmax) or xmax <= np.sqrt(2*args.N):
282        ap.error('xmax must exceed the TF turning point sqrt(2N).')
283    if not 501 <= args.points <= 100001:
284        ap.error('points must be between 501 and 100001.')
285    data = calculate(args.N, xmax, args.points)
286    lines = [f'1D harmonic trap, N={args.N}, spinless, noninteracting, zero temperature',
287             'Length unit: a=sqrt(hbar/m/omega); energy unit: hbar*omega',
288             'Orbital labels n=1..N; oscillator quantum number j=n-1',
289             'K(x) uses the positive definition: 0.5 sum |dphi/dx|^2', '',
290             f'{"Method":24s} {"Integral n":>14s} {"T":>16s} {"U":>16s} {"E=T+U":>16s}']
291    for name, norm, t, u, e in data['rows']:
292        lines.append(f'{name:24s} {norm:14.9f} {t:16.9f} {u:16.9f} {e:16.9f}')
293    norm_error = max(abs(data['norms']-1))
294    lines += ['', f'Max orbital normalization error: {norm_error:.3e}',
295              f'TF particle number on plotting grid (Simpson): {data["tf_grid_norm"]:.9f}',
296              'TF table values use adaptive integration inside the turning points.',
297              'Exact table values use sampled orbitals (Simpson integration).',
298              'TF and exact integrated T,U,E coincide for this special harmonic model.',
299              'TF on exact density is a functional test, not a separately minimized state.']
300    if norm_error > 1e-6:
301        lines.append('WARNING: appreciable normalization error; enlarge xmax or increase points.')
302    if args.check:
303        for label, extent, points in [('Half grid spacing', xmax, 2*args.points-1),
304                                      ('Larger domain', xmax+4, int((args.points-1)*(xmax+4)/xmax)+1)]:
305            other = calculate(args.N, extent, points)
306            delta = np.array(other['rows'][0][2:])-np.array(data['rows'][0][2:])
307            delta_tf = other['rows'][2][2]-data['rows'][2][2]
308            lines.append(f'{label}: delta(T,U,E)={delta}; delta T_TF[n_exact]={delta_tf:+.3e}')
309    text = '\n'.join(lines)+'\n'
310    print(text)
311    prefix = Path(args.prefix)
312    prefix.parent.mkdir(parents=True, exist_ok=True)
313    Path(str(prefix)+'_summary.txt').write_text(text, encoding='utf-8')
314    save_and_plot(data, args)
315    print(f'Saved: {prefix}_comparison.png, {prefix}_orbitals_*.png, CSV files and summary.txt')
316
317
318if __name__ == '__main__':
319    try:
320        main()
321    except (ValueError, OSError) as exc:
322        print(f'Error: {exc}', file=sys.stderr)
323        sys.exit(1)