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

pw1d.py をダウンロード

pw1d.py
pw1d.py
  1import sys
  2import numpy as np
  3from numpy import sqrt, exp, pi
  4import numpy.linalg as LA 
  5from matplotlib import pyplot as plt
  6
  7"""
  8概要:
  9    平面波基底を用いた1次元バンド計算を行います。
 10詳細説明:
 11    ポテンシャルのフーリエ変換、固有方程式の求解、バンド構造および波動関数の計算を実行します。
 12    コマンドライン引数で ft、band、wf のモードを指定できます。
 13"""
 14
 15#===================================
 16# physical constants
 17#===================================
 18pi   = 3.14159265358979323846
 19pi2  = 2.0 * pi
 20h    = 6.6260755e-34    # Js";
 21hbar = 1.05459e-34      # "Js";
 22c    = 2.99792458e8     # m/s";
 23e    = 1.60218e-19      # C";
 24e0   = 8.854418782e-12; # C<sup>2</sup>N<sup>-1</sup>m<sup>-2</sup>";
 25kB   = 1.380658e-23     # JK<sup>-1</sup>";
 26me   = 9.1093897e-31    # kg";
 27R    = 8.314462618      # J/K/mol
 28a0   = 5.29177e-11      # m";
 29
 30KE = hbar * hbar / 2.0 / me / e * 1.0e20  # coefficient of kinetic energy
 31#print("KE = hbar*hbar/(2m)/e*1.0e20 = {}", KE)
 32
 33
 34#========================
 35# global configuration
 36#========================
 37mode = 'ft'   # ft|band|wf
 38
 39#========================
 40# Crystal definition
 41#========================
 42# Si
 43a  = 5.4064   # angstrom, lattice parameter
 44na = 64       # division for FFT, must be 2^n
 45
 46#========================
 47# Potential
 48#========================
 49pottype = 'rect'
 50#pottype = 'gauss'
 51bwidth =  0.5 # A,  barrier width
 52bpot   = 10.0 # eV, barrier height
 53
 54#========================
 55# Band
 56#========================
 57nG   = 3     # # of G points (# of basis functions)
 58kmin = -0.5  # reduced coordinate k/(2pi/a)
 59kmax =  0.5  # first BZ: -0.5 <= k/(2pi/a) <= 0.5
 60nk = 21
 61
 62# プロットするエネルギー範囲
 63Erange = [0.0, 10.0]    # eV
 64
 65#========================
 66# Wave function
 67#========================
 68xwmin  = 0.0      # A
 69xwmax  = 3.0 * a  # A
 70nxw    = 101
 71kw     = 0.0      # reduced coordinate k/(2pi/a)
 72iLevel = 0
 73
 74#===================================
 75# figure configuration
 76#===================================
 77figsize = (6, 8)
 78fontsize        = 12
 79legend_fontsize = 12
 80
 81
 82#==============================================
 83# fundamental functions
 84#==============================================
 85# 実数値に変換できない文字列をfloat()で変換するとエラーになってプログラムが終了する
 86# この関数は、変換できなかったらNoneを返すが、プログラムは終了させない
 87def pfloat(str):
 88    """
 89    概要:
 90        文字列を浮動小数点数に変換します。
 91    詳細説明:
 92        変換できない場合はエラーで終了させずに None を返します。
 93    引数:
 94        :param str: 変換対象の文字列。
 95        :type str: str
 96    戻り値:
 97        :returns: 変換後の浮動小数点数、または None。
 98        :rtype: float または None
 99    """
100    try:
101        return float(str)
102    except:
103        return None
104
105# pfloat()のint版
106def pint(str):
107    """
108    概要:
109        文字列を整数に変換します。
110    詳細説明:
111        変換できない場合はエラーで終了させずに None を返します。
112    引数:
113        :param str: 変換対象の文字列。
114        :type str: str
115    戻り値:
116        :returns: 変換後の整数、または None。
117        :rtype: int または None
118    """
119    try:
120        return int(str)
121    except:
122        return None
123
124# 起動時引数を取得するsys.argリスト変数は、範囲外のindexを渡すとエラーになってプログラムが終了する
125# egtarg()では、範囲外のindexを渡したときは、defvalを返す
126def getarg(position, defval = None):
127    """
128    概要:
129        コマンドライン引数から指定位置の文字列を取得します。
130    詳細説明:
131        範囲外のインデックスが指定された場合は、デフォルト値を返します。
132    引数:
133        :param position: 取得する引数のインデックス。
134        :type position: int
135        :param defval: 取得できなかった場合に返すデフォルト値。
136        :type defval: any
137    戻り値:
138        :returns: コマンドライン引数の文字列、またはデフォルト値。
139        :rtype: str または any
140    """
141    try:
142        return sys.argv[position]
143    except:
144        return defval
145
146# 起動時引数を実数に変換して返す
147def getfloatarg(position, defval = None):
148    """
149    概要:
150        コマンドライン引数から指定位置の値を実数として取得します。
151    引数:
152        :param position: 取得する引数のインデックス。
153        :type position: int
154        :param defval: 取得または変換できなかった場合に返すデフォルト値。
155        :type defval: float または any
156    戻り値:
157        :returns: 実数に変換された値、またはデフォルト値。
158        :rtype: float または any
159    """
160    value = pfloat(getarg(position, defval))
161    return defval if value is None else value
162
163# 起動時引数を整数値に変換して返す
164def getintarg(position, defval = None):
165    """
166    概要:
167        コマンドライン引数から指定位置の値を整数として取得します。
168    引数:
169        :param position: 取得する引数のインデックス。
170        :type position: int
171        :param defval: 取得または変換できなかった場合に返すデフォルト値。
172        :type defval: int または any
173    戻り値:
174        :returns: 整数に変換された値、またはデフォルト値。
175        :rtype: int または any
176    """
177    value = pint(getarg(position, defval))
178    return defval if value is None else value
179
180def usage():
181    """
182    概要:
183        スクリプトのコマンドライン引数の使い方を表示します。
184    """
185    print("")
186    print("Usage: Variables in () are optional")
187    print("  python {}".format(sys.argv[0]))
188    print("  python {} (ft a na pottype bwidth bpot)".format(sys.argv[0]))
189    print("  python {} (band a na pottype bwidth bpot nG kmin kmax nk)".format(sys.argv[0]))
190    print("  python {} (wf a na pottype bwidth bpot nG kw iLevel xwmin xwmax nxw)".format(sys.argv[0]))
191    print("    pottype: rect|gauss")
192    print("     ex: python {} {} {} {} {} {} {}"
193            .format(sys.argv[0], 'ft', a, na, pottype, bwidth, bpot))
194    print("     ex: python {} {} {} {} {} {} {} {} {} {} {}"
195            .format(sys.argv[0], 'band', a, na, pottype, bwidth, bpot, nG, kmin, kmax, nk))
196    print("     ex: python {} {} {} {} {} {} {} {} {} {} {} {} {}"
197            .format(sys.argv[0], 'wf', a, na, pottype, bwidth, bpot, nG, kw, iLevel, xwmin, xwmax, nxw))
198
199def terminate(message = None):
200    """
201    概要:
202        メッセージと使い方を表示してプログラムを終了します。
203    引数:
204        :param message: 表示するエラーメッセージ。
205        :type message: str
206    """
207    print("")
208    if message is not None:
209        print("")
210        print(message)
211        print("")
212
213    usage()
214    print("")
215    exit()
216
217#==============================================
218# update default values by startup arguments
219#==============================================
220argv = sys.argv
221#if len(argv) == 1:
222#    terminate()
223
224mode    = getarg     (1, mode)
225a       = getfloatarg(2, a)
226na      = getintarg  (3, na)
227pottype = getarg     (4, pottype)
228bwidth  = getfloatarg(5, bwidth)
229bpot    = getfloatarg(6, bpot)
230if mode == 'band':
231    nG   = getintarg  ( 7, nG)
232    kmin = getfloatarg( 8, kmin)
233    kmax = getfloatarg( 9, kmax)
234    nk   = getintarg  (10, nk)
235elif mode == 'wf':
236    nG     = getintarg  ( 7, nG)
237    kw     = getfloatarg( 8, kw)
238    iLevel = getintarg  ( 9, iLevel)
239    xwmin  = getfloatarg(10, xwmin)
240    xwmax  = getfloatarg(11, xwmax)
241    nxw    = getintarg  (12, nxw)
242
243
244def reduce(x, x0):
245    """
246    概要:
247        座標を周期境界内に還元します。
248    引数:
249        :param x: 元の座標。
250        :type x: float
251        :param x0: 周期。
252        :type x0: float
253    戻り値:
254        :returns: x を x0 で割った剰余。
255        :rtype: float
256    """
257    return x % x0
258
259# rectangular barrier potential
260def pot(x):
261    """
262    概要:
263        位置 x におけるポテンシャルエネルギーを計算します。
264    詳細説明:
265        グローバル変数の pottype に応じて、矩形ポテンシャルまたはガウス型ポテンシャルの値を返します。
266    引数:
267        :param x: 座標。
268        :type x: float
269    戻り値:
270        :returns: ポテンシャルの値。
271        :rtype: float
272    """
273    global a
274    global pottype, bwidth, bpot
275    
276    xred = reduce(x, a)
277
278    if pottype == 'rect':
279        if 0.0 <= xred <= bwidth:
280            return bpot
281        return 0.0
282    if pottype == 'gauss':
283        xx = (xred - 0.5 * a) / bwidth
284        return bpot * exp(-xx * xx)
285
286def build_potential(xmin, xstep, n):
287    """
288    概要:
289        ポテンシャルの配列を生成します。
290    引数:
291        :param xmin: 座標の最小値。
292        :type xmin: float
293        :param xstep: 座標のステップサイズ。
294        :type xstep: float
295        :param n: 生成するデータ点の数。
296        :type n: int
297    戻り値:
298        :returns: 座標配列とポテンシャル配列のタプル。
299        :rtype: tuple
300    """
301    xpot = np.empty(n)
302    ypot = np.empty(n)
303    for i in range(n):
304        xx = xmin + i * xstep
305        xpot[i] = xx
306        ypot[i] = pot(xx)
307    return xpot, ypot
308
309# Glistのうち、与えられた逆格子の内部座標 dij に対応するインデックスを返す
310def find_iG(dij, Glist):
311    """
312    概要:
313        逆格子の内部座標 dij に対応するインデックスを検索します。
314    引数:
315        :param dij: 逆格子の内部座標。
316        :type dij: int
317        :param Glist: G点のリスト。
318        :type Glist: list または numpy.ndarray
319    戻り値:
320        :returns: Glist 内のインデックス、見つからない場合は None。
321        :rtype: int または None
322    """
323    for iG in range(len(Glist)):
324        if Glist[iG] == dij:
325            return iG
326    return None
327
328def get_Vft(iG, yft0):
329    """
330    概要:
331        フーリエ変換されたポテンシャルの成分を取得します。
332    引数:
333        :param iG: 取得する成分のインデックス。
334        :type iG: int
335        :param yft0: ポテンシャルのフーリエ変換結果の配列。
336        :type yft0: list または numpy.ndarray
337    戻り値:
338        :returns: 指定されたインデックスのポテンシャル成分。
339        :rtype: complex
340    """
341    return yft0[iG % len(yft0)]
342
343# 与えられた逆格子の内部座標 dij に対応するVftを返す
344def find_Vft(dij, Glist, Vft):
345    """
346    概要:
347        逆格子の内部座標 dij に対応するフーリエポテンシャルを検索します。
348    引数:
349        :param dij: 逆格子の内部座標。
350        :type dij: int
351        :param Glist: G点のリスト。
352        :type Glist: list または numpy.ndarray
353        :param Vft: フーリエポテンシャルの配列。
354        :type Vft: list または numpy.ndarray
355    戻り値:
356        :returns: 対応するフーリエポテンシャルの値、見つからない場合は 0.0。
357        :rtype: complex または float
358    """
359    for iG in range(len(Vft)):
360        if Glist[iG] == dij:
361            return Vft[iG]
362    return 0.0
363
364# ポテンシャルのフーリエ変換を取る
365# xft0, yft0は FFT の計算結果で、G < 0の成分は i>nahalf にある
366# i>nahalfをG<0に移動し、横軸を G に変換したのが xft, yft
367def cal_fft(na, a, ypot):
368    """
369    概要:
370        ポテンシャルの高速フーリエ変換を計算します。
371    詳細説明:
372        G が負の成分を適切な位置に移動し、横軸を G に変換した配列も作成します。
373    引数:
374        :param na: 格子の分割数。
375        :type na: int
376        :param a: 格子定数。
377        :type a: float
378        :param ypot: 実空間のポテンシャル配列。
379        :type ypot: numpy.ndarray
380    戻り値:
381        :returns: xft0、yft0、xft、yft、iGlist、nahalf、xftstep を含むタプル。
382        :rtype: tuple
383    """
384    xftstep = 1.0 / a
385    astep = a / na
386    nahalf = int(na/2)
387    xftmax = nahalf * xftstep
388
389    xft0 =range(na)
390    yft0 = np.fft.fft(ypot) * astep / a
391
392# note: The fft result has periodicity
393#       The second half at i >= nahalf data should be shifted to negative x
394    xft =  np.arange(-xftmax, xftmax, xftstep)
395    yft = np.empty(na, dtype = complex)
396    for i in range(nahalf):
397        yft[i] = yft0[nahalf + i]
398    for i in range(nahalf):
399        yft[i+nahalf] = yft0[i]
400
401    iGlist = []
402    for i in range(na):
403        if i <= nahalf:
404            iG = i
405        else:
406            iG = -(na - i)
407        iGlist.append(iG)
408
409    return xft0, yft0, xft, yft, iGlist, nahalf, xftstep
410
411# Extract G basis set for given nG
412# G range will be -Gmax - +Gmax
413def extract_basis(yft0, nG):
414    """
415    概要:
416        指定された nG に基づいて G基底セットを抽出します。
417    引数:
418        :param yft0: ポテンシャルのフーリエ変換結果の配列。
419        :type yft0: numpy.ndarray
420        :param nG: 抽出する基底関数の数。
421        :type nG: int
422    戻り値:
423        :returns: Glist、Vftlist、nGmax を含むタプル。
424        :rtype: tuple
425    """
426    Glist   = np.empty(nG, dtype = int)
427    Vftlist = np.empty(nG, dtype = complex)
428    nGmax = int(nG / 2)
429    if nG == 2:
430        Glist[0]   = 0
431        Vftlist[0] = yft0[0]
432        Glist[1]   = 1
433        Vftlist[1] = yft0[1]
434    else:
435        for i in range(nGmax + 1):
436            Glist[i]   = i
437            Vftlist[i] = yft0[i]
438            Glist[i + nGmax]   = -i
439            Vftlist[i + nGmax] = yft0[-i]
440    return Glist, Vftlist, nGmax
441
442def validate_nG(nG, na):
443    """
444    概要:
445        基底関数の数 nG が有効かどうかを検証し、必要に応じて修正します。
446    引数:
447        :param nG: 指定された基底関数の数。
448        :type nG: int
449        :param na: 格子の分割数。
450        :type na: int
451    戻り値:
452        :returns: 検証および修正後の基底関数の数。
453        :rtype: int
454    """
455    if nG <= 0:
456        terminate("Error: nG must be positive [nG={}]".format(nG))
457    if nG % 2 == 0:
458        nG += 1
459        print("nG is changed to the odd number {}.".format(nG))
460    if nG - 1 > na // 2:
461        terminate("Error: nG is too large for na={} [nG={}]".format(na, nG))
462    return nG
463    
464# 自由電子の運動エネルギーをG点内部座標 iG から計算
465def free_KE(k, iG):
466    """
467    概要:
468        G点内部座標 iG から自由電子の運動エネルギーを計算します。
469    引数:
470        :param k: 波数。
471        :type k: float
472        :param iG: 逆格子の内部座標。
473        :type iG: int
474    戻り値:
475        :returns: 計算された運動エネルギー。
476        :rtype: float
477    """
478    kK = KE * pow(2.0*pi/a, 2.0)  # coefficient of kinetic energy in eV and angstrom
479    return kK * (k + iG) * (k + iG)
480
481# 固有方程式を解き、固有エネルギーと平面波の係数を返す
482# 波動関数は規格化されていない
483def solve_pw(Glist, yft0, nGmax, nG, k, IsPrint = 0):
484    """
485    概要:
486        固有方程式を解き、固有エネルギーと平面波の係数を返します。
487    引数:
488        :param Glist: G点のリスト。
489        :type Glist: numpy.ndarray
490        :param yft0: ポテンシャルのフーリエ変換結果。
491        :type yft0: numpy.ndarray
492        :param nGmax: Gの最大インデックス。
493        :type nGmax: int
494        :param nG: 基底関数の数。
495        :type nG: int
496        :param k: 波数。
497        :type k: float
498        :param IsPrint: デバッグ出力のレベル。
499        :type IsPrint: int
500    戻り値:
501        :returns: 固有エネルギーの配列と平面波係数の行列のタプル。
502        :rtype: tuple
503    """
504    kK = KE * pow(2.0*pi/a, 2.0)  # coefficient of kinetic energy in eV and angstrom
505
506# H_GG' = kinetic delta_GG' + V_(G-G')
507    Hij = np.empty([nG, nG], dtype = complex)
508    for i in range(nG):
509        iG = Glist[i]
510        Vij = get_Vft(0, yft0)
511        Hij[i][i] = free_KE(k, iG) + Vij
512        for j in range(i+1, nG):
513            jG = Glist[j]
514            dij = iG - jG
515            Vij = get_Vft(dij, yft0)
516            if IsPrint >= 1:
517                print("  iG,jG,dij=", iG, jG, dij, "  nG(base)=[{}, {}]".format(-nGmax, nGmax), "  Vij=", Vij)
518            Hij[i][j] = Vij
519            Hij[j][i] = Hij[i][j].conjugate()
520
521#        print("  Hij=\n", Hij)
522    ei, ci = LA.eigh(Hij)
523    if IsPrint >= 1:
524        print("  ei=", ei)
525    if IsPrint >= 2:
526        print("  ci=", ci)
527
528    return ei, ci
529
530# 平面波の係数から波動関数を計算
531# i番目の基底の係数とG点内部座標を ci, Glistで渡す
532# 波動関数は規格化されていない
533def cal_wf(xwmin, xwmax, nxw, kw, ci, Glist):
534    """
535    概要:
536        平面波の係数から波動関数を計算します。
537    詳細説明:
538        波動関数は規格化されていません。
539    引数:
540        :param xwmin: 座標の最小値。
541        :type xwmin: float
542        :param xwmax: 座標の最大値。
543        :type xwmax: float
544        :param nxw: 座標点の数。
545        :type nxw: int
546        :param kw: 波動関数の波数。
547        :type kw: float
548        :param ci: 基底関数の係数。
549        :type ci: list または numpy.ndarray
550        :param Glist: G点のリスト。
551        :type Glist: numpy.ndarray
552    戻り値:
553        :returns: 座標配列、波動関数配列、電荷密度配列のタプル。
554        :rtype: tuple
555    """
556    nG = len(ci)
557    xwstep = (xwmax - xwmin) / (nxw - 1)
558    xwf  = np.empty(nxw, dtype = float)
559    ywf  = np.empty(nxw, dtype = complex)
560    ywf2 = np.empty(nxw, dtype = float)
561    for i in range(nxw):
562        x = xwmin + i * xwstep
563        f = 0.0
564        for iG in range(nG):
565            G = Glist[iG]
566            f += ci[iG] * exp(1.0j * (kw+G) * pi2/a * x)
567        f /= sqrt(a)
568#        print("f({})={}".format(x, f))
569        xwf[i] = x
570        ywf[i] = f
571        charge = f * f.conjugate()
572        ywf2[i] = charge.real
573    return xwf, ywf, ywf2
574
575def wf():
576    """
577    概要:
578        波動関数を計算してプロットします。
579    詳細説明:
580        グローバル変数を使用して計算条件を取得し、固有方程式を解いた後、指定されたエネルギー準位の波動関数を描画します。
581    """
582    global mode
583    global a, na
584    global nG, kw, iLevel
585    global xwmin, xwmax, nxw
586
587    nG = validate_nG(nG, na)
588
589    xwstep = (xwmax - xwmin) / (nxw - 1)
590
591    print("")
592    print("=== Input parameterss ===")
593    print("mode:", mode)
594    print("a=", a, "A")
595    print("  na=", na)
596    print("potential: {} w={} A  h={} eV".format(pottype, bwidth, bpot))
597    print("Wave function to be plotted: k = {}  iLevel = {}".format(kw, iLevel))
598    print("x range: {} - {} at {} step, {} points".format(xwmin, xwmax, xwstep, nxw))
599    print("potential: {} w={} A  h={} eV".format(pottype, bwidth, bpot))
600
601    astep = a / na
602    xpot, ypot   = build_potential(0.0, astep, na)
603    xplot, yplot = build_potential(xwmin, xwstep, nxw)
604
605    xft0, yft0, xft, yft, iGlist, nahalf, xftstep = cal_fft(na, a, ypot)
606
607    print("")
608    print("=== FT result ===")
609    print("{:4} {:4} {}".format("i", "iG", "ci"))
610    for i in range(na):
611        print("{:4d} {:4d} {}".format(i, iGlist[i], yft0[i]))
612
613# Extract G basis set for given nG
614    Glist, Vftlist, nGmax = extract_basis(yft0, nG)
615
616    print("")
617    print("=== G basis extracted ===")
618    print("nG =", nG)
619    print("{:4} {}".format("iG", "Vft"))
620    for i in range(nG):
621        print("{:4d} {}".format(Glist[i], Vftlist[i]))
622
623    print("")
624    print("=== Solve eigen equations ===")
625    k = kw
626    print("at k = {}".format(k))
627
628    yE, ci = solve_pw(Glist, yft0, nGmax, nG, k, IsPrint = 1)
629    print("  ei=", yE)
630    print("  ci=", ci)
631
632    print("")
633    print("=== Calculate wave function ===")
634    print("Energy levels:")
635    for i in range(len(yE)):
636        print("  {} {:12.6g} eV".format(i, yE[i].real))
637
638    print("")
639    print("at k = {}".format(k))
640    print("  selected for {}-th energy level:".format(iLevel))
641    print("    E = {:12.6g} eV".format(yE[iLevel].real))
642    print("  Wave function coefficinets")
643    ciLevel = [ci[i][iLevel] for i in range(nG)]
644    for i in range(nG):
645        print("    at iG={:3d}".format(Glist[i]), "  ci={:8.4f}".format(ci[i][iLevel]))
646
647    xwf, ywf, charge = cal_wf(xwmin, xwmax, nxw, kw, ciLevel, Glist)
648    
649    fig = plt.figure(figsize = (8, 8))
650    ax2 = fig.add_subplot(1, 1, 1)
651#    ax2 = fig.add_subplot(2, 1, 2)
652# ax2をax1に関連させる
653    ax1 = ax2.twinx()
654
655    ax1.set_xlim([xwmin, xwmax])
656    ax1.plot(xplot, yplot, linewidth = 0.5, label = '$V$($x$)')
657    ax1.plot(ax1.get_xlim(), [0.0, 0.0], color = 'r', linestyle = 'dashed', linewidth = 0.5)
658    ax2.set_xlim([xwmin, xwmax])
659    ax2.plot(xwf, ywf.real, linewidth = 1.5, label = r"$\Psi$ (real)")
660    ax2.plot(xwf, ywf.imag, linewidth = 1.5, label = r"$\Psi$ (imaginary)")
661    ax2.plot(xwf, charge, linewidth = 0.5, label = r"$|\Psi|^2$")
662    ax2.plot(ax1.get_xlim(), [0.0, 0.0], color = 'r', linestyle = 'dashed', linewidth = 0.5)
663
664#    ax1.set_xlabel("$x$ ($\AA$)", fontsize = fontsize)
665    ax1.set_ylabel("$V$($x$)", fontsize = fontsize)
666    ax2.set_xlabel(r"$x$ ($\AA$)", fontsize = fontsize)
667    ax2.set_ylabel(r"$\Psi$", fontsize = fontsize)
668
669# 凡例をまとめて出力する
670    handler1, label1 = ax1.get_legend_handles_labels()
671    handler2, label2 = ax2.get_legend_handles_labels()
672    ax2.legend(handler1 + handler2, label1 + label2, loc = 2, borderaxespad = 0.0, fontsize = legend_fontsize)
673#    ax2.legend(fontsize = legend_fontsize)
674    ax1.tick_params(labelsize = fontsize)
675    ax2.tick_params(labelsize = fontsize)
676    plt.tight_layout()
677
678    plt.pause(0.1)
679    print("Press ENTER to exit>>", end = '')
680    input()
681
682    return
683
684def band():
685    """
686    概要:
687        バンド構造を計算してプロットします。
688    詳細説明:
689        グローバル変数から計算条件を取得し、各波数点での固有エネルギーを計算してバンド図を描画します。
690    """
691    global mode
692    global a, na
693    global nG
694    global kmin, kmax, nk
695    global pottype, bwidth, bpot
696
697    nG = validate_nG(nG, na)
698    kstep = (kmax - kmin) / (nk - 1)
699
700    print("")
701    print("=== Input parameterss ===")
702    print("mode:", mode)
703    print("a=", a, "A")
704    print("  na=", na)
705    print("potential: {} w={} A  h={} eV".format(pottype, bwidth, bpot))
706    print("Basis function: nG=", nG)
707    print("k range: {} - {} at {} step, {} points".format(kmin, kmax, kstep, nk))
708    print("potential: {} w={} A  h={} eV".format(pottype, bwidth, bpot))
709
710    astep = a / na
711    xpot, ypot = build_potential(0.0, astep, na)
712
713    xft0, yft0, xft, yft, iGlist, nahalf, xftstep = cal_fft(na, a, ypot)
714
715    print("")
716    print("=== FT result ===")
717    print("{:4} {:4} {}".format("i", "iG", "ci"))
718    for i in range(na):
719        print("{:4d} {:4d} {}".format(i, iGlist[i], yft0[i]))
720
721# Extract G basis set for given nG
722    Glist, Vftlist, nGmax = extract_basis(yft0, nG)
723
724    print("")
725    print("=== FTed potential ===")
726    print("nG =", nG)
727    print("{:4} {}".format("iG", "Vft"))
728    for i in range(nG):
729        print("{:4d} {}".format(Glist[i], Vftlist[i]))
730
731    print("")
732    print("=== Solve eigen equations ===")
733    xk     = [kmin + i * kstep for i in range(nk)]
734    yE     = np.empty([nG, nk])
735    yEfree = np.empty([nG, nk])
736    for ik in range(nk):
737        k = kmin + ik * kstep
738        print("at k = {}".format(k))
739
740        ei,ci = solve_pw(Glist, yft0, nGmax, nG, k, IsPrint = 1)
741
742        for i in range(nG):
743            yE[i][ik] = ei[i]
744            iG = Glist[i]
745            print("k=", k, iG, k+iG)
746            yEfree[i][ik] = free_KE(k, iG)
747
748    fig = plt.figure(figsize = figsize)
749    ax1 = fig.add_subplot(1, 1, 1)
750
751    ax1.set_xlim([kmin, kmax])
752    ax1.set_ylim(Erange)
753    for iG in range(nG):
754        ax1.plot(xk, yE[iG], linestyle = '', marker = 'o', markersize = 2.0,
755                        markerfacecolor = 'none', markeredgecolor = 'black', markeredgewidth = 0.5,
756                        label = 'periodic potential' if iG == 0 else None)
757        ax1.plot(xk, yEfree[iG], linestyle = '-.', linewidth = 0.6, color = 'red',
758                 label = 'free electron' if iG == 0 else None)
759
760    ax1.set_xlabel(r"$k/(2\pi/a)$", fontsize = fontsize)
761    ax1.set_ylabel("E (eV)", fontsize = fontsize)
762    ax1.legend(fontsize = legend_fontsize)
763    plt.tight_layout()
764
765    plt.pause(0.1)
766    print("Press ENTER to exit>>", end = '')
767    input()
768   
769    return
770
771def ft():
772    """
773    概要:
774        ポテンシャルのフーリエ変換結果を計算してプロットします。
775    詳細説明:
776        実空間のポテンシャルと、そのフーリエ変換後の実部、虚部、絶対値をそれぞれ描画します。
777    """
778    global mode
779    global a, na
780    global pottype, bwidth, bpot
781
782    astep = a / na
783
784    print("")
785    print("=== Input parameterss ===")
786    print("mode:", mode)
787    print("a=", a, "A")
788    print("  na=", na)
789    print("  astep=", astep)
790    print("potential: {} w={} A  h={} eV".format(pottype, bwidth, bpot))
791    print("")
792    
793    xpot, ypot   = build_potential(0.0, astep, na)
794    xplot, yplot = build_potential(0.0, astep, 3 * na)
795
796    xft0, yft0, xft, yft, iG, nahalf, xftstep = cal_fft(na, a, ypot)
797
798    fig = plt.figure(figsize = (8, 8))
799    ax1 = fig.add_subplot(2, 2, 1)
800    ax2 = fig.add_subplot(2, 2, 3)
801    ax3 = fig.add_subplot(2, 2, 4)
802
803    ax1.plot(xplot, yplot, linewidth = 0.5)
804    ax2.plot(xft0, yft0.real, label = "real", linewidth = 0.5)
805    ax2.plot(xft0, yft0.imag, label = "imaginary", linewidth = 0.5)
806    ax3.plot(xft,  yft.real, marker = 'o', markersize = 1.0, linewidth = 0.5, label = "real")
807    ax3.plot(xft,  yft.imag, marker = 'o', markersize = 1.0, linewidth = 0.5, label = "imaginary")
808    ax3.plot(xft,  abs(yft), marker = 'o', markersize = 1.0, linewidth = 0.5, label = "absolute")
809    ax1.set_xlabel(r"$x$ ($\AA$)", fontsize = fontsize)
810    ax1.set_ylabel("pot (x)", fontsize = fontsize)
811    ax2.set_xlabel("i", fontsize = fontsize)
812    ax2.set_ylabel("FTed pot, raw x", fontsize = fontsize)
813    ax3.set_xlabel("1/x, normalized (1/A)", fontsize = fontsize)
814    ax3.set_ylabel("FTed pot")
815    ax3.set_xlim([-10.0 * xftstep, 10.0 * xftstep])
816#    ax1.legend(fontsize = legend_fontsize)
817    ax2.legend(fontsize = legend_fontsize)
818    ax3.legend(fontsize = legend_fontsize)
819    ax1.tick_params(labelsize = fontsize)
820    ax2.tick_params(labelsize = fontsize)
821    ax3.tick_params(labelsize = fontsize)
822    plt.tight_layout()
823
824    plt.pause(0.1)
825    print("Press ENTER to exit>>", end = '')
826    input()
827
828    return
829
830def main():
831    """
832    概要:
833        メイン処理を実行します。
834    詳細説明:
835        入力パラメータの妥当性をチェックし、指定されたモードに応じてフーリエ変換、バンド計算、波動関数計算のいずれかを行います。
836    """
837    global mode
838
839    if a <= 0.0:
840        terminate("Error: a must be positive.")
841    if na < 4 or na % 2 != 0:
842        terminate("Error: na must be an even integer >= 4.")
843    if pottype not in ('rect', 'gauss'):
844        terminate("Error: pottype must be rect or gauss.")
845    if bwidth <= 0.0:
846        terminate("Error: bwidth must be positive.")
847    if mode == 'band' and nk < 2:
848        terminate("Error: nk must be >= 2.")
849    if mode == 'wf' and nxw < 2:
850        terminate("Error: nxw must be >= 2.")
851    
852    if mode == 'ft':
853        ft()
854    elif mode == 'band':
855        band()
856    elif mode == 'wf':
857        wf()
858    else:
859        terminate("Error: Invalid mode [{}]".format(mode))
860
861
862if __name__ == "__main__":
863    main()