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

pw3d.py をダウンロード

pw3d.py
pw3d.py
  1"""
  2概要:
  3    3次元周期境界条件下の井戸型ポテンシャルを平面波基底を用いて密行列対角化で解くスクリプトです。
  4詳細説明:
  5    NumPyまたはCuPyを使用し、CPUとGPUのいずれかを選択して計算できます。
  6    エネルギー単位はeV、長さ単位はオングストロームです。コマンドライン引数の backend によって
  7    使用するライブラリを切り替えます。
  8"""
  9import argparse
 10import csv
 11from pathlib import Path
 12from time import perf_counter
 13
 14import numpy as np
 15from scipy.constants import hbar, electron_mass, electron_volt
 16
 17KE = hbar**2 / (2 * electron_mass) / electron_volt * 1e20
 18
 19
 20def initialize():
 21    """
 22    概要:
 23        コマンドライン引数を解析して設定を初期化します。
 24    詳細説明:
 25        格子定数、井戸のサイズや深さ、平面波の数、k点の数、バンド数などのパラメータを取得し、
 26        不正な値が指定された場合はエラーを出力します。
 27    戻り値:
 28        :returns: コマンドライン引数を格納したNamespaceオブジェクト。
 29        :rtype: argparse.Namespace
 30    """
 31    p = argparse.ArgumentParser(description=__doc__)
 32    p.add_argument('--backend', choices=['numpy', 'gpu', 'both'], default='numpy')
 33    p.add_argument('--a', type=float, default=5.4064, help='cubic lattice constant [angstrom]')
 34    p.add_argument('--width', type=float, default=2.0, help='box well side length [angstrom]')
 35    p.add_argument('--depth', type=float, default=10.0, help='well depth [eV]; inside=-depth, outside=0')
 36    p.add_argument('--ng', type=int, default=5, help='odd number of plane waves PER AXIS; total=ng**3')
 37    p.add_argument('--nk', type=int, default=9, help='points per path segment, endpoints included')
 38    p.add_argument('--bands', type=int, default=8, help='number of bands saved/plotted (full diagonalization)')
 39    p.add_argument('--vectors', action='store_true', help='also compute eigenvectors (not saved)')
 40    p.add_argument('--repeat', type=int, default=1, help='repeat whole k path; report median total time')
 41    p.add_argument('--no-plot', action='store_true')
 42    p.add_argument('--output', type=Path, default=Path('pw3d'))
 43    a = p.parse_args()
 44    if a.a <= 0 or not 0 < a.width <= a.a or a.depth < 0:
 45        p.error('require a>0, 0<width<=a, depth>=0')
 46    if a.ng < 1 or a.ng % 2 != 1 or a.nk < 2 or a.bands < 1 or a.repeat < 1:
 47        p.error('ng must be positive odd; nk>=2; bands>=1; repeat>=1')
 48    return a
 49
 50
 51def kpath(nk):
 52    """
 53    概要:
 54        k空間のパスを生成します。
 55    詳細説明:
 56        逆格子のフラクショナル座標系で頂点間を補間し、計算対象となるk点の座標と
 57        累積距離を計算します。
 58    引数:
 59        :param nk: 各パスセグメントの分割ポイント数。
 60        :type nk: int
 61    戻り値:
 62        :returns: k点の座標配列、各点の累積距離配列、主要なパス境界の累積距離リストのタプル。
 63        :rtype: tuple
 64    """
 65    # Reciprocal fractional coordinates, in units of 2*pi/a.
 66    vertices = np.array([[0,0,0], [.5,0,0], [.5,.5,0], [0,0,0], [.5,.5,.5]])
 67    points, distances, ticks = [], [], [0.0]
 68    offset = 0.0
 69    for i, (u,v) in enumerate(zip(vertices[:-1], vertices[1:])):
 70        for j,t in enumerate(np.linspace(0,1,nk)):
 71            if i and j == 0:
 72                continue
 73            points.append(u + t*(v-u))
 74            distances.append(offset + t*np.linalg.norm(v-u))
 75        offset += np.linalg.norm(v-u)
 76        ticks.append(offset)
 77    return np.array(points), np.array(distances), ticks
 78
 79
 80def basis(ng):
 81    """
 82    概要:
 83        平面波基底の格子点座標を生成します。
 84    引数:
 85        :param ng: 各軸ごとの平面波の数。
 86        :type ng: int
 87    戻り値:
 88        :returns: 3次元の基底ベクトルの配列。
 89        :rtype: numpy.ndarray
 90    """
 91    q = np.arange(-(ng//2), ng//2+1)
 92    return np.stack(np.meshgrid(q,q,q,indexing='ij'), axis=-1).reshape(-1,3)
 93
 94
 95def potential_matrix(xp, G, width, a, depth):
 96    """
 97    概要:
 98        井戸型ポテンシャルの行列を作成します。
 99    詳細説明:
100        セル原点に中心を持つ井戸型ポテンシャルのフーリエ係数を解析的に計算し、行列を生成します。
101        sinc関数を用いた計算を行います。
102    引数:
103        :param xp: 使用する配列モジュール。numpyまたはcupy。
104        :type xp: module
105        :param G: 平面波基底ベクトルの配列。
106        :type G: numpy.ndarrayまたはcupy.ndarray
107        :param width: 井戸の1辺の長さ。
108        :type width: float
109        :param a: 立方格子の格子定数。
110        :type a: float
111        :param depth: 井戸の深さ。
112        :type depth: float
113    戻り値:
114        :returns: ポテンシャル行列。
115        :rtype: numpy.ndarrayまたはcupy.ndarray
116    """
117    # Well centered at the cell origin. Analytic Fourier coefficient:
118    # V_q = -depth * (width/a)^3 * product_axis sinc(q_axis*width/a).
119    # sinc(z)=sin(pi*z)/(pi*z). Nonseparable product well, not Vx+Vy+Vz.
120    M = len(G)
121    V = xp.full((M,M), -depth*(width/a)**3, dtype=xp.float64)
122    for axis in range(3):
123        dq = G[:,axis,None] - G[None,:,axis]
124        V *= xp.sinc(dq * (width/a))
125    return V
126
127
128def run(a, backend, ks, G_cpu):
129    """
130    概要:
131        指定されたバックエンドを使用して固有値計算を実行します。
132    詳細説明:
133        バックエンドに応じてNumPyまたはCuPyを初期化し、各k点に対してハミルトニアン行列の構築と
134        対角化を行い、エネルギー固有値を計算します。各ステップの処理時間も計測して記録します。
135    引数:
136        :param a: コマンドライン引数を格納したNamespace。
137        :type a: argparse.Namespace
138        :param backend: 使用するバックエンド名。numpyまたはgpu。
139        :type backend: str
140        :param ks: k点の配列。
141        :type ks: numpy.ndarray
142        :param G_cpu: CPU上の基底ベクトル配列。
143        :type G_cpu: numpy.ndarray
144    戻り値:
145        :returns: 経過時間とエネルギー固有値のリスト、および実行時間の詳細な記録を含む辞書のリストのタプル。
146        :rtype: tuple
147    """
148    start_init = perf_counter()
149    if backend == 'numpy':
150        xp = np
151        def sync():
152            pass
153    else:
154        import cupy as xp
155        xp.cuda.Device().use()
156        def sync():
157            xp.cuda.get_current_stream().synchronize()
158    # Unmeasured warmup: initializes context and eigensolver, not full-size solve.
159    small = xp.eye(4, dtype=xp.float64)
160    if a.vectors:
161        xp.linalg.eigh(small)
162    else:
163        xp.linalg.eigvalsh(small)
164    sync()
165    startup = perf_counter()-start_init
166    print(f'{backend}: startup/warmup={startup:.6f}s (separate from trials)', flush=True)
167    all_rows, results = [], []
168    for trial in range(a.repeat):
169        sync()
170        total_start = perf_counter()
171        t = perf_counter()
172        G = xp.asarray(G_cpu, dtype=xp.float64)
173        k_device = xp.asarray(ks, dtype=xp.float64)
174        sync()
175        upload = perf_counter()-t
176        t = perf_counter()
177        V = potential_matrix(xp, G, a.width, a.a, a.depth)
178        diag = xp.arange(len(G))
179        sync()
180        potential_time = perf_counter()-t
181        energies = []
182        construct_time = solve_time = download_time = 0.0
183        for ik in range(len(ks)):
184            t = perf_counter()
185            H = V.copy()
186            H[diag,diag] += KE*(2*np.pi/a.a)**2 * xp.sum((G+k_device[ik])**2, axis=1)
187            sync()
188            dt_build = perf_counter()-t
189            t = perf_counter()
190            if a.vectors:
191                ev, vectors = xp.linalg.eigh(H)
192            else:
193                ev = xp.linalg.eigvalsh(H)
194            sync()
195            dt_solve = perf_counter()-t
196            t = perf_counter()
197            selected = ev[:min(a.bands,len(G))]
198            energies.append(np.array(selected,copy=True) if backend == 'numpy' else xp.asnumpy(selected))
199            sync()
200            dt_download = perf_counter()-t
201            construct_time += dt_build
202            solve_time += dt_solve
203            download_time += dt_download
204            all_rows.append(dict(backend=backend, trial=trial+1, k_index=ik,
205                                 build_seconds=dt_build, eig_seconds=dt_solve,
206                                 result_copy_seconds=dt_download))
207            if a.vectors:
208                del vectors
209            del H, ev
210        sync()
211        elapsed = perf_counter()-total_start
212        energies = np.array(energies)
213        results.append((elapsed, energies))
214        print(f'{backend} trial {trial+1}: total={elapsed:.6f}s, input={upload:.6f}s, '
215              f'V={potential_time:.6f}s, H={construct_time:.6f}s, '
216              f'eigen={solve_time:.6f}s, result_copy={download_time:.6f}s', flush=True)
217        all_rows.append(dict(backend=backend, trial=trial+1, k_index='TOTAL',
218                             build_seconds=construct_time, eig_seconds=solve_time,
219                             result_copy_seconds=download_time, total_seconds=elapsed,
220                             input_seconds=upload, potential_seconds=potential_time,
221                             startup_seconds=startup))
222        del V, G, k_device
223    return results, all_rows
224
225
226def save_csv(path, rows):
227    """
228    概要:
229        辞書のリストをCSVファイルとして保存します。
230    引数:
231        :param path: 保存先のファイルパス。
232        :type path: pathlib.Path
233        :param rows: CSVに書き込む辞書のリスト。
234        :type rows: list
235    """
236    path.parent.mkdir(parents=True,exist_ok=True)
237    fields = list(dict.fromkeys(k for r in rows for k in r))
238    with path.open('w', newline='', encoding='utf-8-sig') as f:
239        writer = csv.DictWriter(f,fieldnames=fields)
240        writer.writeheader()
241        writer.writerows(rows)
242    print('Saved:',path)
243
244
245def main():
246    """
247    概要:
248        プログラムのメイン処理を実行します。
249    詳細説明:
250        パラメータの初期化、基底ベクトルやk点の生成を行い、指定されたバックエンドで
251        対角化計算を実行します。計算後はパフォーマンス結果とバンド構造をCSVに保存し、
252        プロットが有効な場合はグラフを表示して画像として保存します。
253    """
254    a = initialize()
255    G = basis(a.ng)
256    ks, distance, ticks = kpath(a.nk)
257    M = len(G)
258    print(f'Basis: {a.ng}**3 = {M}; real symmetric matrix {M}x{M}; '
259          f'one matrix={M*M*8/2**20:.2f} MiB (workspace/additional arrays extra)')
260    print(f'k-points={len(ks)}; full spectrum; eigenvectors={a.vectors}')
261    print('Potential: periodic centered cubic well, inside=-depth, outside=0; analytic Fourier coefficients')
262    print('Energies are absolute relative to outside potential=0.')
263    backends = ['numpy','gpu'] if a.backend == 'both' else [a.backend]
264    timings, bands = [], {}
265    medians = {}
266    for backend in backends:
267        results, rows = run(a,backend,ks,G)
268        timings.extend(rows)
269        medians[backend] = float(np.median([r[0] for r in results]))
270        bands[backend] = results[0][1]
271        print(f'{backend}: median total={medians[backend]:.6f}s')
272    if len(bands)==2:
273        print(f'CPU/GPU speedup (median totals)={medians["numpy"]/medians["gpu"]:.3f}x')
274        print(f'Max absolute CPU-GPU eigenvalue difference='
275              f'{np.max(np.abs(bands["numpy"]-bands["gpu"])):.3e} eV')
276    save_csv(a.output.with_name(a.output.name+'_timing.csv'),timings)
277    records=[]
278    for backend, es in bands.items():
279        for i,(k,dist,vals) in enumerate(zip(ks,distance,es)):
280            row=dict(backend=backend,k_index=i,kx=k[0],ky=k[1],kz=k[2],distance=dist)
281            row.update({f'E{j}_eV':v for j,v in enumerate(vals)})
282            records.append(row)
283    save_csv(a.output.with_name(a.output.name+'_bands.csv'), records)
284    if not a.no_plot:
285        import matplotlib.pyplot as plt
286        fig, ax = plt.subplots(figsize=(8,6))
287        for backend,es in bands.items():
288            for j in range(es.shape[1]):
289                ax.plot(distance,es[:,j],'-' if backend=='numpy' else '--',
290                        color='C0' if backend=='numpy' else 'C1',
291                        label=backend if j==0 else None)
292        ax.set_xticks(ticks,['Γ','X','M','Γ','R'])
293        for tick in ticks:
294            ax.axvline(tick,color='gray',lw=.5)
295        ax.set_ylabel('Energy (eV)')
296        ax.set_title(f'3D plane waves: {a.ng} per axis, {M} total')
297        ax.legend()
298        fig.tight_layout()
299        path=a.output.with_name(a.output.name+'_bands.png')
300        fig.savefig(path,dpi=160)
301        print('Saved:',path)
302        plt.show()
303
304
305if __name__=='__main__':
306    main()