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

wavefunction2D.py をダウンロード

wavefunction2D.py
wavefunction2D.py
  1import sys
  2import os
  3from numpy import sin, cos, tan, arcsin, arccos, arctan, arctan2, exp, log, sqrt
  4import numpy as np
  5from numpy import linalg as la
  6from mpl_toolkits.mplot3d import Axes3D
  7import matplotlib.pyplot as plt
  8from matplotlib.colors import Normalize
  9
 10"""
 112次元波動関数描画ツール
 12
 13概要:
 14このスクリプトは、様々な物理モデル(自由電子、無限井戸型量子ドット、水素原子)における2次元波動関数を計算し、視覚化します。
 15波動関数の実部、虚部、および確率密度を1Dプロットと2Dカラーマップ/3Dサーフェスプロットで表示します。
 16起動時引数により、モード、量子数、ブロッホ波ベクトル、メッシュ数を設定できます。
 17
 18詳細説明:
 19pwモードは、自由電子(平面波)の波動関数を計算します。
 20qboxモードは、無限井戸型量子ドット内の粒子の波動関数を計算します。
 21Hモードは、水素原子様の波動関数を計算します。
 22波動関数はブロッホ波の位相因子 phi と組み合わせて計算されます。
 23表示範囲は単位セル内外を指定でき、単位セル境界も明示されます。
 24
 25関連リンク:
 26wavefunction2D_usage
 27"""
 28
 29
 30pi   = 3.1415926535
 31pi2  = pi + pi
 32pi2j = 1.0j * pi2
 33
 34
 35#===================
 36# 初期値
 37#===================
 38"""
 39概要:
 40スクリプトの実行モードと物理パラメータの初期設定。
 41
 42詳細説明:
 43これらの値はコマンドライン引数によって上書きされる可能性があります。
 44"""
 45# mode: 'pw', 'qbox', 'H', 'harmonic'
 46#mode = 'pw'
 47mode = 'qbox'
 48
 49# lattice parameter
 50ax, ay, az = 1.0, 1.0, 1.0
 51nlxrange, nlyrange, nlzrange = (-1.5, 1.5), (-1.5, 1.5), (-1.5, 1.5)
 52# number of mesh
 53nmeshx, nmeshy, nmeshz = 120, 120, 120
 54
 55# quantum number: kx, ky, kz in pi/a for mode = 'pw
 56n1, n2, n3 = 0.0, 0.0, 0.0
 57# k vector in pi/a for mode = 'pw
 58kx, ky, kz = 0.0, 0.0, 0.0
 59
 60# Elementary charge
 61e = 1.602176634e-19  # C
 62# Boha radius
 63aB = 0.529177         # A
 64# Nuclear charge
 65Z  = 1.0
 66
 67# Expansion ratio for psi(x) of qdt model
 68#kqbox = [0.3, 0.3, 0.8, 0.8, 0.8]
 69kqbox = [1.0, 1.0, 1.0, 1.0, 1.0]
 70
 71# Expansion ratio for R(r) of H model
 72kR = [0.5, 6.0, 15.0]
 73
 74#=============================
 75# Graph configuration
 76#=============================
 77"""
 78概要:
 79グラフ描画に関する設定パラメータ。
 80
 81詳細説明:
 82matplotlibによるプロットの外観を制御します。
 83"""
 84figsize         = (12, 8)
 85fontsize        = 10
 86legend_fontsize = 10
 87cmap_r = 'bwr'  # 'plasma', 'coolwarm', 'rainbow'
 88
 89#===================
 90# 起動時引数
 91#===================
 92if __name__ == "__main__":
 93    argv = sys.argv
 94    narg = len(argv)
 95    if narg >= 2:
 96        mode = argv[1]
 97    if narg >= 3:
 98        n1 = float(argv[2])
 99    if narg >= 4:
100        n2 = float(argv[3])
101    if narg >= 5:
102        n3 = float(argv[4])
103    if narg >= 6:
104        kx = float(argv[5])
105    if narg >= 7:
106        ky = float(argv[6])
107    if narg >= 8:
108        kz = float(argv[7])
109    if narg >= 9:
110        nmeshx = float(argv[8])
111    if narg >= 10:
112        nmeshy = float(argv[9])
113    if narg >= 11:
114        nmeshz = float(argv[10])
115
116def usage():
117    """
118    概要:
119    スクリプトの正しい使用法と引数の説明を表示します。
120
121    詳細説明:
122    スクリプトの実行時に指定可能なモード(自由電子、無限井戸型量子ドット、水素原子)と、それぞれのモードで必要な量子数や波ベクトル、メッシュ数の引数の形式を示します。
123    """
124    print("")
125    print("kx, ky, kz: Bloch's wave vector")
126    print("nmeshx, nmeshy, nmeshz: Number of x, y, z mesh to calculate wavefunction values")
127    print("usage: python {} pw kx0 ky0 kz0 kx ky kz nmeshx nmeshy nmeshz".format(argv[0]))
128    print("   For free electron (plain wave)")
129    print("usage: python {} qbox nx ny nz kx ky kz nmeshx nmeshy nmeshz".format(argv[0]))
130    print("   For quantum dot separated by infite potential barrier")
131    print("usage: python {} H n l m kx ky kz nmeshx nmeshy nmeshz".format(argv[0]))
132    print("   For hydrogen like model. Radius of wavefunctions are adjusted for clear visualization")
133    print("")
134
135def terminate(message, usage = usage):
136    """
137    概要:
138    エラーメッセージを表示し、スクリプトを終了します。
139
140    詳細説明:
141    指定されたメッセージを出力した後、usage関数を呼び出して使用法を表示し、システムを終了します。
142
143    引数:
144    :param message: 表示するエラーメッセージ。
145    :type message: str
146    :param usage: 使用法を表示するための関数。デフォルトはスクリプト内のusage関数。
147    :type usage: callable
148    """
149    print("")
150    print(message)
151    exit()
152
153
154def reduce2unitcell(x):
155    """
156    概要:
157    座標を単位セル内に収まるように変換します。
158
159    詳細説明:
160    与えられた座標 x を、周期境界条件を考慮して -0.5 から 0.5 の範囲にマッピングします。これは、物理的な系が周期性を持ち、単位セル内の振る舞いに関心がある場合に有用です。
161
162    引数:
163    :param x: 変換する座標値。
164    :type x: float
165
166    戻り値:
167    :returns: 単位セル内に収まるように変換された座標値。
168    :rtype: float
169    """
170    x += 0.5
171    if x < 0.0:
172        x = x - int(x) + 1.0
173    if x >= 1.0:
174        x = x - int(x)
175    return x - 0.5
176    
177def phi(x, y, z, ax, ay, az, kx, ky, kz):
178    """
179    概要:
180    ブロッホ波の位相因子を計算します。
181
182    詳細説明:
183    3次元空間におけるブロッホ波の複素位相因子 exp(i * 2 * pi * (kx*x/ax + ky*y/ay + kz*z/az)) を計算します。これは、周期的なポテンシャル下での波動関数に現れる位相項を表します。
184
185    引数:
186    :param x: x座標。
187    :type x: float
188    :param y: y座標。
189    :type y: float
190    :param z: z座標。
191    :type z: float
192    :param ax: x方向の格子定数。
193    :type ax: float
194    :param ay: y方向の格子定数。
195    :type ay: float
196    :param az: z方向の格子定数。
197    :type az: float
198    :param kx: x方向の波のベクトル成分 (pi/a単位)。
199    :type kx: float
200    :param ky: y方向の波のベクトル成分 (pi/a単位)。
201    :type ky: float
202    :param kz: z方向の波のベクトル成分 (pi/a単位)。
203    :type kz: float
204
205    戻り値:
206    :returns: 計算されたブロッホ波の位相因子。
207    :rtype: complex
208    """
209    return exp(pi2j * (kx * x / ax + ky * y / ay + kz * z / az))
210
211def psi_pw(x, y, z, ax, ay, az, n1, n2, n3, kx, ky, kz, xonly = False, yonly = False, zonly = False):
212    """
213    概要:
214    自由電子(平面波)の波動関数を計算します。
215
216    詳細説明:
217    ブロッホの定理に基づき、平面波 exp(i * 2 * pi * (n1*x/ax + ...)) にブロッホ波の位相因子 phi を乗じた形で波動関数を計算します。xonly、yonly、zonly フラグにより、特定の方向の成分のみを返すことができます。
218
219    引数:
220    :param x: x座標。
221    :type x: float
222    :param y: y座標。
223    :type y: float
224    :param z: z座標。
225    :type z: float
226    :param ax: x方向の格子定数。
227    :type ax: float
228    :param ay: y方向の格子定数。
229    :type ay: float
230    :param az: z方向の格子定数。
231    :type az: float
232    :param n1: x方向の量子数 (pi/a単位)。
233    :type n1: float
234    :param n2: y方向の量子数 (pi/a単位)。
235    :type n2: float
236    :param n3: z方向の量子数 (pi/a単位)。
237    :type n3: float
238    :param kx: x方向のブロッホ波ベクトル成分 (pi/a単位)。
239    :type kx: float
240    :param ky: y方向のブロッホ波ベクトル成分 (pi/a単位)。
241    :type ky: float
242    :param kz: z方向のブロッホ波ベクトル成分 (pi/a単位)。
243    :type kz: float
244    :param xonly: x方向の成分のみを計算する場合にTrue。デフォルトはFalse。
245    :type xonly: bool
246    :param yonly: y方向の成分のみを計算する場合にTrue。デフォルトはFalse。
247    :type yonly: bool
248    :param zonly: z方向の成分のみを計算する場合にTrue。デフォルトはFalse。
249    :type zonly: bool
250
251    戻り値:
252    :returns: 波動関数の実部、虚部、および確率密度 (abs(Psi)の2乗)。
253    :rtype: tuple
254    """
255    fx = exp(pi2j * (n1 * x / ax))
256    fy = exp(pi2j * (n2 * y / ay))
257    fz = exp(pi2j * (n3 * z / az))
258
259#    phi = exp(pi2j * (kx * x / ax + ky * y / ay + kz * z / az))
260    _phi = phi(x, y, z, ax, ay, az, kx, ky, kz)
261
262    if xonly:
263        f = fx * _phi
264    elif yonly:
265        f = fy * _phi
266    elif zonly:
267        f = fz * _phi
268    else:
269        f = fx * fy * fz * _phi
270    
271    return f.real, f.imag, f.real * f.real + f.imag * f.imag
272
273def psi_qbox1(x, y, z, ax, ay, az, n1, n2, n3, kx, ky, kz, xonly = False, yonly = False, zonly = False):
274    """
275    概要:
276    無限井戸型量子ドットモデルの波動関数の基本成分を計算します。
277
278    詳細説明:
279    周期的な境界条件下での無限井戸型量子ドットの波動関数を計算します。reduce2unitcell を使用して座標を単位セル内にマッピングし、奇数および偶数の量子数に応じてcos関数やsin関数を適用します。ブロッホ波の位相因子 phi と乗算されます。
280
281    引数:
282    :param x: x座標。
283    :type x: float
284    :param y: y座標。
285    :type y: float
286    :param z: z座標。
287    :type z: float
288    :param ax: x方向の格子定数。
289    :type ax: float
290    :param ay: y方向の格子定数。
291    :type ay: float
292    :param az: z方向の格子定数。
293    :type az: float
294    :param n1: x方向の量子数 (整数)。
295    :type n1: float
296    :param n2: y方向の量子数 (整数)。
297    :type n2: float
298    :param n3: z方向の量子数 (整数)。
299    :type n3: float
300    :param kx: x方向のブロッホ波ベクトル成分 (pi/a単位)。
301    :type kx: float
302    :param ky: y方向のブロッホ波ベクトル成分 (pi/a単位)。
303    :type ky: float
304    :param kz: z方向のブロッホ波ベクトル成分 (pi/a単位)。
305    :type kz: float
306    :param xonly: x方向の成分のみを計算する場合にTrue。デフォルトはFalse。
307    :type xonly: bool
308    :param yonly: y方向の成分のみを計算する場合にTrue。デフォルトはFalse。
309    :type yonly: bool
310    :param zonly: z方向の成分のみを計算する場合にTrue。デフォルトはFalse。
311    :type zonly: bool
312
313    戻り値:
314    :returns: 計算された波動関数の複素数値。
315    :rtype: complex
316    """
317    n1 = int(n1 + 1.0e-3)
318    n2 = int(n2 + 1.0e-3)
319    n3 = int(n3 + 1.0e-3)
320    x0 = reduce2unitcell(x) * kqbox[n1-1]
321    y0 = reduce2unitcell(y) * kqbox[n2-1]
322    z0 = reduce2unitcell(z) * kqbox[n3-1]
323
324    if n1 % 2 == 1:
325        fx = cos(pi * x0 / ax * n1)
326    else:
327        fx = sin(pi * x0 / ax * n1)
328    if n2 % 2 == 1:
329        fy = cos(pi * y0 / ay * n2)
330    else:
331        fy = sin(pi * y0 / ay * n2)
332    if n3 % 2 == 1:
333#        fz = cos(pi * z0 / az * n3)
334        fz = 1.0
335    else:
336#        fz = sin(pi * z0 / az * n3)
337        fz = 1.0
338
339    _phi = phi(x, y, z, ax, ay, az, kx, ky, kz)
340
341    if xonly:
342        f = fx * _phi
343    elif yonly:
344        f = fy * _phi
345    elif zonly:
346        f = fz * _phi
347    else:
348        f = fx * fy * fz * _phi
349    
350    return f
351
352def psi_qbox(x, y, z, ax, ay, az, n1, n2, n3, kx, ky, kz, xonly = False, yonly = False, zonly = False):
353    """
354    概要:
355    無限井戸型量子ドットモデルの波動関数を周期境界条件を考慮して計算します。
356
357    詳細説明:
358    psi_qbox1 を用いて、中心セルとその隣接する6つのセル(x, y, z方向のプラスマイナス1)からの寄与を合計することで、周期性を模倣した波動関数を構築します。これにより全空間にわたって連続的な波動関数を表現します。
359
360    引数:
361    :param x: x座標。
362    :type x: float
363    :param y: y座標。
364    :type y: float
365    :param z: z座標。
366    :type z: float
367    :param ax: x方向の格子定数。
368    :type ax: float
369    :param ay: y方向の格子定数。
370    :type ay: float
371    :param az: z方向の格子定数。
372    :type az: float
373    :param n1: x方向の量子数 (整数)。
374    :type n1: float
375    :param n2: y方向の量子数 (整数)。
376    :type n2: float
377    :param n3: z方向の量子数 (整数)。
378    :type n3: float
379    :param kx: x方向のブロッホ波ベクトル成分 (pi/a単位)。
380    :type kx: float
381    :param ky: y方向のブロッホ波ベクトル成分 (pi/a単位)。
382    :type ky: float
383    :param kz: z方向のブロッホ波ベクトル成分 (pi/a単位)。
384    :type kz: float
385    :param xonly: x方向の成分のみを計算する場合にTrue。デフォルトはFalse。
386    :type xonly: bool
387    :param yonly: y方向の成分のみを計算する場合にTrue。デフォルトはFalse。
388    :type yonly: bool
389    :param zonly: z方向の成分のみを計算する場合にTrue。デフォルトはFalse。
390    :type zonly: bool
391
392    戻り値:
393    :returns: 波動関数の実部、虚部、および確率密度 (abs(Psi)の2乗)。
394    :rtype: tuple
395    """
396    f = 0.0
397    for v in [[0, 0, 0], [-1, 0, 0], [1, 0, 0], [0, -1, 0], [0, 1, 0], [0, 0, -1], [0, 0, 1]]:
398        f += psi_qbox1(x, y, z, ax, ay, az, n1, n2, n3, kx + v[0], ky + v[1], kz + v[2], xonly, yonly, zonly)
399    
400    return f.real, f.imag, f.real * f.real + f.imag * f.imag
401
402
403def psi_R_H(r, n, l):
404    """
405    概要:
406    水素様原子の動径波動関数 R_nl(r) を計算します。
407
408    詳細説明:
409    主量子数 n と方位量子数 l に基づいて、水素原子の動径波動関数を計算します。kR 配列は、視覚化のために動径方向のスケールを調整するために使用されます。サポートされている量子数は n, l = 1,0 や 2,0 や 2,1 や 3,0 や 3,1 や 3,2 です。
410
411    引数:
412    :param r: 動径座標。
413    :type r: float
414    :param n: 主量子数。
415    :type n: int
416    :param l: 方位量子数。
417    :type l: int
418
419    戻り値:
420    :returns: 計算された動径波動関数 R_nl(r) の値。
421    :rtype: float
422    """
423    n = int(n + 1.0e-3)
424    kZaB = kR[n-1] * Z / aB
425
426    if n == 1:
427        return 2.0 * pow(kZaB, 1.5) * exp(-kZaB * r)
428    elif n == 2 and l == 0:
429        return 2.0 * pow(kZaB / 2.0, 1.5) * (2.0 - kZaB * r) * exp(-0.5 * kZaB * r)
430    elif n == 2 and l == 1:
431        return 1.0 / sqrt(3.0) * pow(kZaB / 2.0, 1.5) * kZaB * r * exp(-0.5 * kZaB * r)
432    elif n == 3 and l == 0:
433        return 2.0 / 3.0 * pow(kZaB / 3.0, 1.5) * (3.0 - 2.0 * kZaB * r + 2.0 / 9.0 * kZaB * kZaB * r * r) * exp(-kZaB / 3.0 * r)
434    elif n == 3 and l == 1:
435        return 1.0 / 81.0 / sqrt(3.0) * pow(2.0 * kZaB, 1.5) * (6.0 - Z / aB * r) * kZaB * r * exp(-kZaB / 3.0 * r)
436    elif n == 3 and l == 2:
437        return 1.0 / 81.0 / sqrt(15.0) * pow(2.0 * kZaB, 1.5) * kZaB * kZaB * r * r * exp(-kZaB / 3.0 * r)
438    else:
439        terminate(f"Invalid quantum numbers [n={n}, l={l}]", usage = usage)
440
441def psi_Y_H(Theta, Phi, l, m):
442    """
443    概要:
444    水素様原子の球面調和関数 Y_lm(Theta, Phi) を計算します。
445
446    詳細説明:
447    方位量子数 l と磁気量子数 m に基づいて、球面調和関数を計算します。ここでは、一般的な原子軌道(s, pz, px, py, dz2, dxz, dyz, dx2-y2, dxy)に対応する実数形式の球面調和関数を返します。サポートされている量子数は l, m = 0,0 や 1,0 や 1,1 や 1,-1 や 2,0 や 2,1 や 2,-1 や 2,2 や 2,-2 です。
448
449    引数:
450    :param Theta: 極角 (ラジアン)。
451    :type Theta: float
452    :param Phi: 方位角 (ラジアン)。
453    :type Phi: float
454    :param l: 方位量子数。
455    :type l: int
456    :param m: 磁気量子数。
457    :type m: int
458
459    戻り値:
460    :returns: 計算された球面調和関数 Y_lm(Theta, Phi) の値。
461    :rtype: float
462    """
463    l = int(l + 1.0e-3)
464    if m < 0:
465        m = int(m - 1.0e-3)
466    else:
467        m = int(m + 1.0e-3)
468
469    if l == 0 and m == 0:
470        return sqrt(1.0 / 4.0 / pi)
471    elif l == 1 and m == 0:
472        return sqrt(3.0 / 4.0 / pi) * cos(Theta)
473    elif l == 1 and m == 1:
474        return +sqrt(3.0 / 8.0 / pi) * sin(Theta) * sqrt(2.0) * cos(Phi) #exp(1.0j * Phi)
475    elif l == 1 and m == -1:
476        return +sqrt(3.0 / 8.0 / pi) * sin(Theta) * sqrt(2.0) * sin(Phi) #exp(-1.0j * Phi)
477    elif l == 2 and m == 0:
478        return +sqrt(5.0 / 16.0 / pi) * (cos(Theta)**2 - 1.0)
479    elif l == 2 and m == 1:
480        return +sqrt(15.0 / 8.0 / pi) * cos(Theta) * sin(Theta) * sqrt(2.0) * cos(Phi) #exp(1.0j * Phi)
481    elif l == 2 and m == -1:
482        return +sqrt(15.0 / 8.0 / pi) * cos(Theta) * sin(Theta) * sqrt(2.0) * sin(Phi) #exp(-1.0j * Phi)
483    elif l == 2 and m == 2:
484        return sqrt(15.0 / 32.0 / pi) * sin(Theta)**2 * sqrt(2.0) * cos(2.0 * Phi) #exp(2.0j * Phi)
485    elif l == 2 and m == -2:
486        return sqrt(15.0 / 32.0 / pi) * sin(Theta)**2 * sqrt(2.0) * sin(2.0 * Phi) #exp(-2.0j * Phi)
487    else:
488        terminate(f"psi_Y_H(): Invalid quantum number [m={m}]", usage = usage)    
489
490def wfname_H(n, l, m):
491    """
492    概要:
493    水素様原子の波動関数に対応する軌道名(例: 1s, 2pz)を生成します。
494
495    詳細説明:
496    主量子数 n、方位量子数 l、磁気量子数 m に基づいて、一般的な原子軌道の表記(s, pz, px, py, dz2, dxz, dyz, dx2-y2, dxy)を生成します。
497
498    引数:
499    :param n: 主量子数。
500    :type n: int
501    :param l: 方位量子数。
502    :type l: int
503    :param m: 磁気量子数。
504    :type m: int
505
506    戻り値:
507    :returns: 生成された軌道名。
508    :rtype: str
509    """
510    print("n=", n, l, m)
511    n = int(n+1.0e-3)
512    l = int(l+1.0e-3)
513    if m < 0:
514        m = int(m-1.0e-3)
515    else:
516        m = int(m+1.0e-3)
517    print("n=", n, l, m)
518
519    s = f"{n}"
520    if l == 0:
521        s += 's'
522    elif l == 1 and m == 0:
523        s += 'pz'
524    elif l == 1 and m == 1:
525        s += 'px'
526    elif l == 1 and m == -1:
527        s += 'py'
528    elif l == 2 and m == 0:
529        s += 'dz2'
530    elif l == 2 and m == 1:
531        s += 'dxz'
532    elif l == 2 and m == -1:
533        s += 'dyz'
534    elif l == 2 and m == 2:
535        s += 'dx2-y2'
536    elif l == 2 and m == -2:
537        s += 'dxy'
538    else:
539        terminate(f"wfname_H(): Invalid quantum number [m={m}]", usage = usage)    
540    return s
541    
542def psi_H1(x, y, z, ax, ay, az, n, l, m, kx, ky, kz, xonly = False, yonly = False, zonly = False):
543    """
544    概要:
545    水素様原子モデルの波動関数の基本成分を計算します。
546
547    詳細説明:
548    動径波動関数 psi_R_H と球面調和関数 psi_Y_H を組み合わせて波動関数を計算し、さらにブロッホ波の位相因子 phi を乗じます。座標は reduce2unitcell で単位セルにマッピングされ、極座標に変換されます。
549
550    引数:
551    :param x: x座標。
552    :type x: float
553    :param y: y座標。
554    :type y: float
555    :param z: z座標。
556    :type z: float
557    :param ax: x方向の格子定数。
558    :type ax: float
559    :param ay: y方向の格子定数。
560    :type ay: float
561    :param az: z方向の格子定数。
562    :type az: float
563    :param n: 主量子数。
564    :type n: int
565    :param l: 方位量子数。
566    :type l: int
567    :param m: 磁気量子数。
568    :type m: int
569    :param kx: x方向のブロッホ波ベクトル成分 (pi/a単位)。
570    :type kx: float
571    :param ky: y方向のブロッホ波ベクトル成分 (pi/a単位)。
572    :type ky: float
573    :param kz: z方向のブロッホ波ベクトル成分 (pi/a単位)。
574    :type kz: float
575    :param xonly: x方向の成分のみを計算する場合にTrue。デフォルトはFalse。
576    :type xonly: bool
577    :param yonly: y方向の成分のみを計算する場合にTrue。デフォルトはFalse。
578    :type yonly: bool
579    :param zonly: z方向の成分のみを計算する場合にTrue。デフォルトはFalse。
580    :type zonly: bool
581
582    戻り値:
583    :returns: 計算された波動関数の複素数値。
584    :rtype: complex
585    """
586    x0 = reduce2unitcell(x)
587    y0 = reduce2unitcell(y)
588    z0 = reduce2unitcell(z)
589    rxy = sqrt(x0 * x0 + y0 * y0)
590    r   = sqrt(x0 * x0 + y0 * y0 + z0 * z0)
591    Phi = arctan2(y0, x0)
592    if rxy == 0.0:
593        Theta = 0.0
594    else:
595        Theta = arcsin(rxy / r)
596#    print("r=", x, y, z, x0, y0, z0, r, rxy, Theta, Phi)
597
598    Rnl = psi_R_H(r, n, l)
599    Yml = psi_Y_H(Theta, Phi, l, m)
600#    print("r=", r, Theta, Phi, Rnl, Yml)
601#    print("phi=", Theta, Phi, Rnl, Yml)
602
603    _phi = phi(x, y, z, ax, ay, az, kx, ky, kz)
604
605    f = Rnl * Yml * _phi
606    
607    return f
608
609def psi_H(x, y, z, ax, ay, az, n, l, m, kx, ky, kz, xonly = False, yonly = False, zonly = False):
610    """
611    概要:
612    水素様原子モデルの波動関数を周期境界条件を考慮して計算します。
613
614    詳細説明:
615    psi_H1 を用いて、中心セルとその隣接する6つのセル(x, y, z方向のプラスマイナス1)からの寄与を合計することで、周期性を模倣した波動関数を構築します。これにより全空間にわたって連続的な波動関数を表現します。
616
617    引数:
618    :param x: x座標。
619    :type x: float
620    :param y: y座標。
621    :type y: float
622    :param z: z座標。
623    :type z: float
624    :param ax: x方向の格子定数。
625    :type ax: float
626    :param ay: y方向の格子定数。
627    :type ay: float
628    :param az: z方向の格子定数。
629    :type az: float
630    :param n: 主量子数。
631    :type n: int
632    :param l: 方位量子数。
633    :type l: int
634    :param m: 磁気量子数。
635    :type m: int
636    :param kx: x方向のブロッホ波ベクトル成分 (pi/a単位)。
637    :type kx: float
638    :param ky: y方向のブロッホ波ベクトル成分 (pi/a単位)。
639    :type ky: float
640    :param kz: z方向のブロッホ波ベクトル成分 (pi/a単位)。
641    :type kz: float
642    :param xonly: x方向の成分のみを計算する場合にTrue。デフォルトはFalse。
643    :type xonly: bool
644    :param yonly: y方向の成分のみを計算する場合にTrue。デフォルトはFalse。
645    :type yonly: bool
646    :param zonly: z方向の成分のみを計算する場合にTrue。デフォルトはFalse。
647    :type zonly: bool
648
649    戻り値:
650    :returns: 波動関数の実部、虚部、および確率密度 (abs(Psi)の2乗)。
651    :rtype: tuple
652    """
653    f = 0.0
654    for v in [[0, 0, 0], [-1, 0, 0], [1, 0, 0], [0, -1, 0], [0, 1, 0], [0, 0, -1], [0, 0, 1]]:
655        f += psi_H1(x, y, z, ax, ay, az, n, l, m, kx + v[0], ky + v[1], kz + v[2], xonly, yonly, zonly)
656    
657    return f.real, f.imag, f.real * f.real + f.imag * f.imag
658
659def main():
660    """
661    概要:
662    スクリプトのメイン処理を実行します。
663
664    詳細説明:
665    コマンドライン引数に基づき、計算モードと物理パラメータを設定し、選択されたモードに応じて波動関数計算関数を決定します。その後、各方向の波動関数を計算し、matplotlibを用いて1Dプロットや2Dカラーマップなどを表示します。
666    """
667    global n1, n2, n3
668    
669    print("")
670    print(f"mode: {mode}")
671    print(f"lattice parameters: {ax}, {ay}, {az} A")
672    print(f"plot range in unit cell: {nlxrange}, {nlyrange}, {nlzrange}")
673    print(f"number of mesh: {nmeshx}, {nmeshy}, {nmeshz}")
674
675    if mode == 'pw':
676        psi = psi_pw
677    elif mode == 'qbox':
678        psi = psi_qbox
679    elif mode == 'H':
680        psi = psi_H
681    else:
682        terminate(f"Error: Invalid mode [{mode}]", usage = usage)
683
684    xstart = nlxrange[0]
685    xend   = nlxrange[1]
686    xstep  = (xend - xstart) / nmeshx
687    print("")
688    print(f"plot psi(x) for x range ({xstart:6.2f} - {xend:6.2f}) at {xstep:8.4f} step")
689    x     = []
690    fxr   = []
691    fxi   = []
692    fx2   = []
693    phixr = []
694    phixi = []
695    print("x\ty\tz\tPsi_r\tPsi_i\t|Psi|2\tphi_r\tphi_i")
696    for i in range(nmeshx + 1):
697        _x = xstart + i * xstep
698        _yr, _yi, _y2 = psi(_x, 0.0, 0.0, ax, ay, az, n1, n2, n3, kx, ky, kz, xonly = True)
699        _phi = phi(_x, 0.0, 0.0, ax, ay, az, kx, ky, kz)
700        x.append(_x)
701        fxr.append(_yr)
702        fxi.append(_yi)
703        fx2.append(_y2)
704        phixr.append(_phi.real)
705        phixi.append(_phi.imag)
706        print(f"{_x:8.3f}\t{_yr:8.3f}\t{_yi:8.3f}\t{_y2:8.3f}\t{_phi.real:8.3f}\t{_phi.imag:8.3f}")
707
708    ystart = nlyrange[0]
709    yend   = nlyrange[1]
710    ystep  = (yend - ystart) / nmeshy
711    print("")
712    print(f"plot psi(y) for y range ({ystart:6.2f} - {yend:6.2f}) at {ystep:8.4f} step")
713    y  = []
714    fyr = []
715    fyi = []
716    fy2 = []
717    phiyr = []
718    phiyi = []
719    print("x\ty\tz\tPsi_r\tPsi_i\t|Psi|2\tphi_r\tphi_i")
720    for i in range(nmeshy + 1):
721        _y = ystart + i * ystep
722        _yr, _yi, _y2 = psi(0.0, _y, 0.0, ax, ay, az, n1, n2, n3, kx, ky, kz, yonly = True)
723        _phi = phi(0.0, _y, 0.0, ax, ay, az, kx, ky, kz)
724        y.append(_y)
725        fyr.append(_yr)
726        fyi.append(_yi)
727        fy2.append(_y2)
728        phiyr.append(_phi.real)
729        phiyi.append(_phi.imag)
730        print(f"{_y:8.3f}\t{_yr:8.3f}\t{_yi:8.3f}\t{_y2:8.3f}\t{_phi.real:8.3f}\t{_phi.imag:8.3f}")
731
732    print("")
733    print(f"plot psi(x, y) for x range ({xstart:6.2f} - {xend:6.2f}) at {xstep:8.4f} step and y range ({ystart:6.2f} - {yend:6.2f}) at {ystep:8.4f} step")
734    x3d  = np.empty([nmeshx+1, nmeshy+1], dtype = float)
735    y3d  = np.empty([nmeshx+1, nmeshy+1], dtype = float)
736    f3dr = np.empty([nmeshx+1, nmeshy+1], dtype = float)
737    f3di = np.empty([nmeshx+1, nmeshy+1], dtype = float)
738    f3d2 = np.empty([nmeshx+1, nmeshy+1], dtype = float)
739    print("x\ty\tz\tPsi_r\tPsi_i\t|Psi|2")
740    for iy in range(nmeshy + 1):
741        _y = ystart + iy * ystep
742        for ix in range(nmeshx + 1):
743            _x = xstart + ix * xstep
744            _yr, _yi, _y2 = psi(_x, _y, 0.0, ax, ay, az, n1, n2, n3, kx, ky, kz)
745            x3d[ix][iy]  = _x
746            y3d[ix][iy]  = _y
747            f3dr[ix][iy] = _yr
748            f3di[ix][iy] = _yi
749            f3d2[ix][iy] = _y2
750            if -0.5 <= _x <= 0.5 and -0.5 <= _y <= 0.5:
751                print(f"{_x:8.3f}\t{_y:8.3f}\t{_yr:8.3f}\t{_yi:8.3f}\t{_y2:8.3f}")
752
753    print("")
754    print("Quantum number:")
755    if mode == 'pw':
756        print(f"kx0, ky0, kz0 = {n1}, {n2}, {n3} * pi/a")
757    elif mode == 'qbox':
758        print(f"nx, ny, nz = {n1}, {n2}, {n3}")
759    elif mode == 'H':
760        print(f"n, l, m = {n1}, {n2}, {n3}")
761    else:
762        terminate(f"Error: Invalid mode [{mode}]", usage = usage)
763        
764    print(f"kx, ky, kz = {kx}, {ky}, {kz} * pi/a")
765
766#=============================
767# グラフの表示
768#=============================
769    maxfr = 0.0
770    for list in f3dr:
771        for v in list:
772            if abs(v) > maxfr:
773                maxfr = abs(v)
774    if maxfr < 1.0e-3:
775        maxfr = 1.0e-3
776    print("maxfr=", maxfr)
777
778    maxfi = 0.0
779    for list in f3di:
780        for v in list:
781            if abs(v) > maxfi:
782                maxfi = abs(v)
783    if maxfi < 1.0e-3:
784        maxfi = 1.0e-3
785    print("maxfi=", maxfi)
786    if maxfi > 1.0e-3:
787        maxfi = 1.0e-3
788
789    print("")
790    fig = plt.figure(figsize = figsize)
791
792    if mode == 'H':
793        wfn = wfname_H(n1, n2, n3)
794    else:
795        wfn = ''
796    if mode != 'pw':
797        n1 = int(n1 + 1.0e-3)
798        n2 = int(n2 + 1.0e-3)
799        if n3 < 0:
800            n3 = int(n3 - 1.0e-3)
801        else:
802            n3 = int(n3 + 1.0e-3)
803    title = f"mode:{mode} n=({n1},{n2},{n3}){wfn} k=({kx},{ky},{kz})"
804    plt.suptitle(title)
805
806    axcr   = fig.add_subplot(2, 3, 1)
807    axci   = fig.add_subplot(2, 3, 2)
808    ax3dr  = fig.add_subplot(2, 3, 3, projection='3d')
809    ax3di  = fig.add_subplot(2, 3, 6, projection='3d')
810    axfx   = fig.add_subplot(4, 3,  7)
811    axphix = fig.add_subplot(4, 3, 10)
812    axfy   = fig.add_subplot(4, 3,  8)
813    axphiy = fig.add_subplot(4, 3, 11)
814
815    axfx.plot(x, fxr, label = '$\psi$$_x$$_r$', linestyle = 'dashed', linewidth = 0.5, color = 'red')
816    axfx.plot(x, fxi, label = '$\psi$$_x$$_i$', linestyle = 'dashed', linewidth = 0.5, color = 'blue')
817#    axfx.plot(x, fx2, label = '|$\psi$$|$^2$', linestyle = '-',     linewidth = 0.5, color = 'green')
818    xlim = nlxrange #axfx.get_xlim()
819    ylim = axfx.get_ylim()
820    axfx.plot(xlim, [0.0, 0.0], linestyle = 'dashed', linewidth = 0.3, color = 'red')
821    for i in range(int(nlxrange[0]), int(nlxrange[1]) + 1):
822        axfx.plot([i + 0.5, i + 0.5], ylim, linestyle = '-', linewidth = 0.5, color = 'black')
823    axfx.set_xlim(xlim)
824    axfx.set_ylim(ylim)
825    axfx.set_xlabel("$x$ (A)", fontsize = fontsize)
826    axfx.set_ylabel("$\psi$$_x$($x$)", fontsize = fontsize)
827    axfx.legend(fontsize = legend_fontsize, loc = 'best')
828    axfx.tick_params(labelsize = fontsize)
829
830    axphix.plot(x, phixr, label = '$\phi_r$', linestyle = 'dashed', linewidth = 0.5, color = 'red')
831    axphix.plot(x, phixi, label = '$\phi_i$', linestyle = 'dashed', linewidth = 0.5, color = 'blue')
832    xlim = nlxrange #axfx.get_xlim()
833    ylim = axphix.get_ylim()
834    axphix.plot(xlim, [0.0, 0.0], linestyle = 'dashed', linewidth = 0.3, color = 'red')
835    for i in range(int(nlxrange[0]), int(nlxrange[1]) + 1):
836        axphix.plot([i + 0.5, i + 0.5], ylim, linestyle = '-', linewidth = 0.5, color = 'black')
837    axphix.set_xlim(xlim)
838    axphix.set_ylim(ylim)
839    axphix.set_xlabel("$x$ (A)", fontsize = fontsize)
840    axphix.set_ylabel("$\phi$($x$)", fontsize = fontsize)
841    axphix.legend(fontsize = legend_fontsize, loc = 'best')
842    axphix.tick_params(labelsize = fontsize)
843
844    axfy.plot(y, fyr, label = '$\psi$$_y$$_r$', linestyle = 'dashed', linewidth = 0.5, color = 'red')
845    axfy.plot(y, fyi, label = '$\psi$$_y$$_i$', linestyle = 'dashed', linewidth = 0.5, color = 'blue')
846#    axfy.plot(y, fy2, label = '|$\psi$$_y$|$^2$', linestyle = '-',      linewidth = 0.5, color = 'black')
847    xlim = nlyrange #axfx.get_ylim()
848    ylim = axfy.get_ylim()
849    axfy.plot(xlim, [0.0, 0.0], linestyle = 'dashed', linewidth = 0.3, color = 'red')
850    for i in range(int(nlxrange[0]), int(nlxrange[1]) + 1):
851        axfy.plot([i + 0.5, i + 0.5], ylim, linestyle = '-', linewidth = 0.5, color = 'black')
852    axfy.set_xlim(xlim)
853    axfy.set_ylim(ylim)
854    axfy.set_xlabel("$y$ (A)", fontsize = fontsize)
855    axfy.set_ylabel("$\psi$$_y$($y$)", fontsize = fontsize)
856    axfy.legend(fontsize = legend_fontsize, loc = 'best')
857    axfy.tick_params(labelsize = fontsize)
858
859    axphiy.plot(y, phiyr, label = '$\phi_r$', linestyle = 'dashed', linewidth = 0.5, color = 'red')
860    axphiy.plot(y, phiyi, label = '$\phi_i$', linestyle = 'dashed', linewidth = 0.5, color = 'blue')
861    xlim = nlyrange #axfx.get_ylim()
862    ylim = axphiy.get_ylim()
863    axphiy.plot(xlim, [0.0, 0.0], linestyle = 'dashed', linewidth = 0.3, color = 'red')
864    for i in range(int(nlxrange[0]), int(nlxrange[1]) + 1):
865        axphiy.plot([i + 0.5, i + 0.5], ylim, linestyle = '-', linewidth = 0.5, color = 'black')
866    axphiy.set_xlim(xlim)
867    axphiy.set_ylim(ylim)
868    axphiy.set_xlabel("$y$ (A)", fontsize = fontsize)
869    axphiy.set_ylabel("$\phi$($y$)", fontsize = fontsize)
870    axphiy.legend(fontsize = legend_fontsize, loc = 'best')
871    axphiy.tick_params(labelsize = fontsize)
872
873    surf = ax3dr.plot_surface(x3d, y3d, f3dr, label = '$\Psi_r$', cmap = cmap_r)
874    ax3dr.contour(x3d, y3d, f3dr, cmap = cmap_r, offset = -1,
875                vmin = -maxfr, vmax = maxfr, levels = 100) 
876#                norm = Normalize(vmin = -maxfr, vmax = maxfr), levels = 100) 
877#    fig.colorbar(surf, ax = ax3dr)
878#    ax3dr.set_aspect('equal')
879    ax3dr.set_xlabel("$x$ (A)", fontsize = fontsize)
880    ax3dr.set_ylabel("$y$ (A)", fontsize = fontsize)
881    ax3dr.set_zlabel("$\Psi$$_r$", fontsize = fontsize)
882#    ax3dr.legend(fontsize = legend_fontsize, loc = 'best')
883    ax3dr.tick_params(labelsize = fontsize)
884
885    surf = ax3di.plot_surface(x3d, y3d, f3di, label = '$\Psi_i$', cmap = cmap_r)
886    ax3di.contour(x3d, y3d, f3di, cmap = cmap_r, offset = -1,
887                norm = Normalize(vmin = -maxfi, vmax = maxfi), levels = 100) 
888#    fig.colorbar(surf, ax = ax3di)
889#    ax3di.set_aspect('equal')
890    ax3di.set_xlabel("$x$ (A)", fontsize = fontsize)
891    ax3di.set_ylabel("$y$ (A)", fontsize = fontsize)
892    ax3di.set_zlabel("$\Psi$$_i$", fontsize = fontsize)
893#    ax3di.legend(fontsize = legend_fontsize, loc = 'best')
894    ax3di.tick_params(labelsize = fontsize)
895
896    axcr.set_title("$\Psi_r$")
897#    contour = axcr.pcolormesh(x3d, y3d, f3dr, label = '$\Psi_r$', cmap = cmap_r, shading='auto')
898    if maxfr > 1.0e-3:
899#        contour = axcr.contour(x3d, y3d, f3dr, cmap = cmap_r, 
900#                levels = np.arange(-maxfr, maxfr, 0.01 * maxfr))
901        contour = axcr.contourf(x3d, y3d, f3dr, 
902                cmap = cmap_r, norm = Normalize(vmin = -maxfr, vmax = maxfr), levels = 100) 
903        fig.colorbar(contour, ax = axcr, shrink = 0.5)
904    axcr.set_aspect('equal')
905    xlim = nlxrange #axfy.get_xlim()
906    ylim = nlyrange #axfy.get_ylim()
907    for i in range(int(nlxrange[0]), int(nlxrange[1]) + 1):
908#        if i == 0:
909#            continue
910        axcr.plot([i + 0.5, i + 0.5], ylim, linestyle = '-', linewidth = 1.0, color = 'black')
911    for i in range(int(nlyrange[0]), int(nlyrange[1]) + 1):
912#        if i == 0:
913#            continue
914        axcr.plot(xlim, [i + 0.5, i + 0.5], linestyle = '-', linewidth = 1.0, color = 'black')
915    axcr.plot(xlim, [0.0, 0.0], linestyle = '-', linewidth = 0.5, color = 'red')
916    axcr.plot([0.0, 0.0], ylim, linestyle = '-', linewidth = 0.5, color = 'red')
917    axcr.set_xlim(xlim)
918    axcr.set_ylim(ylim)
919    axcr.set_xlabel("$x$ (A)", fontsize = fontsize)
920    axcr.set_ylabel("$y$ (A)", fontsize = fontsize)
921#    axcr.legend(fontsize = legend_fontsize, loc = 'best')
922    axcr.tick_params(labelsize = fontsize)
923
924    axci.set_title("$\Psi_i$")
925#    contour = axci.pcolormesh(x3d, y3d, f3di, label = '$\Psi_i$', cmap = cmap_r, shading='auto')
926    if maxfi > 1.0e-3:
927#        contour = axci.contour(x3d, y3d, f3di, cmap = cmap_r, 
928#                levels = np.arange(-maxfi, maxfi, 0.01 * maxfi))
929        contour = axci.contourf(x3d, y3d, f3di, 
930                cmap = cmap_r, norm = Normalize(vmin = -maxfi, vmax = maxfi), levels = 100) 
931        fig.colorbar(contour, ax = axci, shrink = 0.5)
932    axci.set_aspect('equal')
933    xlim = nlxrange #axfy.get_xlim()
934    ylim = nlyrange #axfy.get_ylim()
935    for i in range(int(nlxrange[0]), int(nlxrange[1]) + 1):
936#        if i == 0:
937#            continue
938        axci.plot([i + 0.5, i + 0.5], ylim, linestyle = '-', linewidth = 1.0, color = 'black')
939    for i in range(int(nlyrange[0]), int(nlyrange[1]) + 1):
940#        if i == 0:
941#            continue
942        axci.plot(xlim, [i + 0.5, i + 0.5], linestyle = '-', linewidth = 1.0, color = 'black')
943    axci.plot(xlim, [0.0, 0.0], linestyle = '-', linewidth = 0.5, color = 'red')
944    axci.plot([0.0, 0.0], ylim, linestyle = '-', linewidth = 0.5, color = 'red')
945    axci.set_xlim(xlim)
946    axci.set_ylim(ylim)
947    axci.set_xlabel("$x$ (A)", fontsize = fontsize)
948    axci.set_ylabel("$y$ (A)", fontsize = fontsize)
949#    axci.legend(fontsize = legend_fontsize, loc = 'best')
950    axci.tick_params(labelsize = fontsize)
951
952    plt.tight_layout()
953    plt.pause(0.1)
954
955    print("Press ENTER to exit>>", end = '')
956    input()
957
958    terminate("", usage = usage)
959
960
961if __name__ == '__main__':
962    main()