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