import sys
import numpy as np
from numpy import sqrt, exp, pi
import numpy.linalg as LA 
from matplotlib import pyplot as plt

"""
概要:
    平面波基底を用いた1次元バンド計算を行います。
詳細説明:
    ポテンシャルのフーリエ変換、固有方程式の求解、バンド構造および波動関数の計算を実行します。
    コマンドライン引数で ft、band、wf のモードを指定できます。
"""

#===================================
# physical constants
#===================================
pi   = 3.14159265358979323846
pi2  = 2.0 * pi
h    = 6.6260755e-34    # Js";
hbar = 1.05459e-34      # "Js";
c    = 2.99792458e8     # m/s";
e    = 1.60218e-19      # C";
e0   = 8.854418782e-12; # C<sup>2</sup>N<sup>-1</sup>m<sup>-2</sup>";
kB   = 1.380658e-23     # JK<sup>-1</sup>";
me   = 9.1093897e-31    # kg";
R    = 8.314462618      # J/K/mol
a0   = 5.29177e-11      # m";

KE = hbar * hbar / 2.0 / me / e * 1.0e20  # coefficient of kinetic energy
#print("KE = hbar*hbar/(2m)/e*1.0e20 = {}", KE)


#========================
# global configuration
#========================
mode = 'ft'   # ft|band|wf

#========================
# Crystal definition
#========================
# Si
a  = 5.4064   # angstrom, lattice parameter
na = 64       # division for FFT, must be 2^n

#========================
# Potential
#========================
pottype = 'rect'
#pottype = 'gauss'
bwidth =  0.5 # A,  barrier width
bpot   = 10.0 # eV, barrier height

#========================
# Band
#========================
nG   = 3     # # of G points (# of basis functions)
kmin = -0.5  # reduced coordinate k/(2pi/a)
kmax =  0.5  # first BZ: -0.5 <= k/(2pi/a) <= 0.5
nk = 21

# プロットするエネルギー範囲
Erange = [0.0, 10.0]    # eV

#========================
# Wave function
#========================
xwmin  = 0.0      # A
xwmax  = 3.0 * a  # A
nxw    = 101
kw     = 0.0      # reduced coordinate k/(2pi/a)
iLevel = 0

#===================================
# figure configuration
#===================================
figsize = (6, 8)
fontsize        = 12
legend_fontsize = 12


#==============================================
# fundamental functions
#==============================================
# 実数値に変換できない文字列をfloat()で変換するとエラーになってプログラムが終了する
# この関数は、変換できなかったらNoneを返すが、プログラムは終了させない
def pfloat(str):
    """
    概要:
        文字列を浮動小数点数に変換します。
    詳細説明:
        変換できない場合はエラーで終了させずに None を返します。
    引数:
        :param str: 変換対象の文字列。
        :type str: str
    戻り値:
        :returns: 変換後の浮動小数点数、または None。
        :rtype: float または None
    """
    try:
        return float(str)
    except:
        return None

# pfloat()のint版
def pint(str):
    """
    概要:
        文字列を整数に変換します。
    詳細説明:
        変換できない場合はエラーで終了させずに None を返します。
    引数:
        :param str: 変換対象の文字列。
        :type str: str
    戻り値:
        :returns: 変換後の整数、または None。
        :rtype: int または None
    """
    try:
        return int(str)
    except:
        return None

# 起動時引数を取得するsys.argリスト変数は、範囲外のindexを渡すとエラーになってプログラムが終了する
# egtarg()では、範囲外のindexを渡したときは、defvalを返す
def getarg(position, defval = None):
    """
    概要:
        コマンドライン引数から指定位置の文字列を取得します。
    詳細説明:
        範囲外のインデックスが指定された場合は、デフォルト値を返します。
    引数:
        :param position: 取得する引数のインデックス。
        :type position: int
        :param defval: 取得できなかった場合に返すデフォルト値。
        :type defval: any
    戻り値:
        :returns: コマンドライン引数の文字列、またはデフォルト値。
        :rtype: str または any
    """
    try:
        return sys.argv[position]
    except:
        return defval

# 起動時引数を実数に変換して返す
def getfloatarg(position, defval = None):
    """
    概要:
        コマンドライン引数から指定位置の値を実数として取得します。
    引数:
        :param position: 取得する引数のインデックス。
        :type position: int
        :param defval: 取得または変換できなかった場合に返すデフォルト値。
        :type defval: float または any
    戻り値:
        :returns: 実数に変換された値、またはデフォルト値。
        :rtype: float または any
    """
    value = pfloat(getarg(position, defval))
    return defval if value is None else value

# 起動時引数を整数値に変換して返す
def getintarg(position, defval = None):
    """
    概要:
        コマンドライン引数から指定位置の値を整数として取得します。
    引数:
        :param position: 取得する引数のインデックス。
        :type position: int
        :param defval: 取得または変換できなかった場合に返すデフォルト値。
        :type defval: int または any
    戻り値:
        :returns: 整数に変換された値、またはデフォルト値。
        :rtype: int または any
    """
    value = pint(getarg(position, defval))
    return defval if value is None else value

def usage():
    """
    概要:
        スクリプトのコマンドライン引数の使い方を表示します。
    """
    print("")
    print("Usage: Variables in () are optional")
    print("  python {}".format(sys.argv[0]))
    print("  python {} (ft a na pottype bwidth bpot)".format(sys.argv[0]))
    print("  python {} (band a na pottype bwidth bpot nG kmin kmax nk)".format(sys.argv[0]))
    print("  python {} (wf a na pottype bwidth bpot nG kw iLevel xwmin xwmax nxw)".format(sys.argv[0]))
    print("    pottype: rect|gauss")
    print("     ex: python {} {} {} {} {} {} {}"
            .format(sys.argv[0], 'ft', a, na, pottype, bwidth, bpot))
    print("     ex: python {} {} {} {} {} {} {} {} {} {} {}"
            .format(sys.argv[0], 'band', a, na, pottype, bwidth, bpot, nG, kmin, kmax, nk))
    print("     ex: python {} {} {} {} {} {} {} {} {} {} {} {} {}"
            .format(sys.argv[0], 'wf', a, na, pottype, bwidth, bpot, nG, kw, iLevel, xwmin, xwmax, nxw))

def terminate(message = None):
    """
    概要:
        メッセージと使い方を表示してプログラムを終了します。
    引数:
        :param message: 表示するエラーメッセージ。
        :type message: str
    """
    print("")
    if message is not None:
        print("")
        print(message)
        print("")

    usage()
    print("")
    exit()

#==============================================
# update default values by startup arguments
#==============================================
argv = sys.argv
#if len(argv) == 1:
#    terminate()

mode    = getarg     (1, mode)
a       = getfloatarg(2, a)
na      = getintarg  (3, na)
pottype = getarg     (4, pottype)
bwidth  = getfloatarg(5, bwidth)
bpot    = getfloatarg(6, bpot)
if mode == 'band':
    nG   = getintarg  ( 7, nG)
    kmin = getfloatarg( 8, kmin)
    kmax = getfloatarg( 9, kmax)
    nk   = getintarg  (10, nk)
elif mode == 'wf':
    nG     = getintarg  ( 7, nG)
    kw     = getfloatarg( 8, kw)
    iLevel = getintarg  ( 9, iLevel)
    xwmin  = getfloatarg(10, xwmin)
    xwmax  = getfloatarg(11, xwmax)
    nxw    = getintarg  (12, nxw)


def reduce(x, x0):
    """
    概要:
        座標を周期境界内に還元します。
    引数:
        :param x: 元の座標。
        :type x: float
        :param x0: 周期。
        :type x0: float
    戻り値:
        :returns: x を x0 で割った剰余。
        :rtype: float
    """
    return x % x0

# rectangular barrier potential
def pot(x):
    """
    概要:
        位置 x におけるポテンシャルエネルギーを計算します。
    詳細説明:
        グローバル変数の pottype に応じて、矩形ポテンシャルまたはガウス型ポテンシャルの値を返します。
    引数:
        :param x: 座標。
        :type x: float
    戻り値:
        :returns: ポテンシャルの値。
        :rtype: float
    """
    global a
    global pottype, bwidth, bpot
    
    xred = reduce(x, a)

    if pottype == 'rect':
        if 0.0 <= xred <= bwidth:
            return bpot
        return 0.0
    if pottype == 'gauss':
        xx = (xred - 0.5 * a) / bwidth
        return bpot * exp(-xx * xx)

def build_potential(xmin, xstep, n):
    """
    概要:
        ポテンシャルの配列を生成します。
    引数:
        :param xmin: 座標の最小値。
        :type xmin: float
        :param xstep: 座標のステップサイズ。
        :type xstep: float
        :param n: 生成するデータ点の数。
        :type n: int
    戻り値:
        :returns: 座標配列とポテンシャル配列のタプル。
        :rtype: tuple
    """
    xpot = np.empty(n)
    ypot = np.empty(n)
    for i in range(n):
        xx = xmin + i * xstep
        xpot[i] = xx
        ypot[i] = pot(xx)
    return xpot, ypot

# Glistのうち、与えられた逆格子の内部座標 dij に対応するインデックスを返す
def find_iG(dij, Glist):
    """
    概要:
        逆格子の内部座標 dij に対応するインデックスを検索します。
    引数:
        :param dij: 逆格子の内部座標。
        :type dij: int
        :param Glist: G点のリスト。
        :type Glist: list または numpy.ndarray
    戻り値:
        :returns: Glist 内のインデックス、見つからない場合は None。
        :rtype: int または None
    """
    for iG in range(len(Glist)):
        if Glist[iG] == dij:
            return iG
    return None

def get_Vft(iG, yft0):
    """
    概要:
        フーリエ変換されたポテンシャルの成分を取得します。
    引数:
        :param iG: 取得する成分のインデックス。
        :type iG: int
        :param yft0: ポテンシャルのフーリエ変換結果の配列。
        :type yft0: list または numpy.ndarray
    戻り値:
        :returns: 指定されたインデックスのポテンシャル成分。
        :rtype: complex
    """
    return yft0[iG % len(yft0)]

# 与えられた逆格子の内部座標 dij に対応するVftを返す
def find_Vft(dij, Glist, Vft):
    """
    概要:
        逆格子の内部座標 dij に対応するフーリエポテンシャルを検索します。
    引数:
        :param dij: 逆格子の内部座標。
        :type dij: int
        :param Glist: G点のリスト。
        :type Glist: list または numpy.ndarray
        :param Vft: フーリエポテンシャルの配列。
        :type Vft: list または numpy.ndarray
    戻り値:
        :returns: 対応するフーリエポテンシャルの値、見つからない場合は 0.0。
        :rtype: complex または float
    """
    for iG in range(len(Vft)):
        if Glist[iG] == dij:
            return Vft[iG]
    return 0.0

# ポテンシャルのフーリエ変換を取る
# xft0, yft0は FFT の計算結果で、G < 0の成分は i>nahalf にある
# i>nahalfをG<0に移動し、横軸を G に変換したのが xft, yft
def cal_fft(na, a, ypot):
    """
    概要:
        ポテンシャルの高速フーリエ変換を計算します。
    詳細説明:
        G が負の成分を適切な位置に移動し、横軸を G に変換した配列も作成します。
    引数:
        :param na: 格子の分割数。
        :type na: int
        :param a: 格子定数。
        :type a: float
        :param ypot: 実空間のポテンシャル配列。
        :type ypot: numpy.ndarray
    戻り値:
        :returns: xft0、yft0、xft、yft、iGlist、nahalf、xftstep を含むタプル。
        :rtype: tuple
    """
    xftstep = 1.0 / a
    astep = a / na
    nahalf = int(na/2)
    xftmax = nahalf * xftstep

    xft0 =range(na)
    yft0 = np.fft.fft(ypot) * astep / a

# note: The fft result has periodicity
#       The second half at i >= nahalf data should be shifted to negative x
    xft =  np.arange(-xftmax, xftmax, xftstep)
    yft = np.empty(na, dtype = complex)
    for i in range(nahalf):
        yft[i] = yft0[nahalf + i]
    for i in range(nahalf):
        yft[i+nahalf] = yft0[i]

    iGlist = []
    for i in range(na):
        if i <= nahalf:
            iG = i
        else:
            iG = -(na - i)
        iGlist.append(iG)

    return xft0, yft0, xft, yft, iGlist, nahalf, xftstep

# Extract G basis set for given nG
# G range will be -Gmax - +Gmax
def extract_basis(yft0, nG):
    """
    概要:
        指定された nG に基づいて G基底セットを抽出します。
    引数:
        :param yft0: ポテンシャルのフーリエ変換結果の配列。
        :type yft0: numpy.ndarray
        :param nG: 抽出する基底関数の数。
        :type nG: int
    戻り値:
        :returns: Glist、Vftlist、nGmax を含むタプル。
        :rtype: tuple
    """
    Glist   = np.empty(nG, dtype = int)
    Vftlist = np.empty(nG, dtype = complex)
    nGmax = int(nG / 2)
    if nG == 2:
        Glist[0]   = 0
        Vftlist[0] = yft0[0]
        Glist[1]   = 1
        Vftlist[1] = yft0[1]
    else:
        for i in range(nGmax + 1):
            Glist[i]   = i
            Vftlist[i] = yft0[i]
            Glist[i + nGmax]   = -i
            Vftlist[i + nGmax] = yft0[-i]
    return Glist, Vftlist, nGmax

def validate_nG(nG, na):
    """
    概要:
        基底関数の数 nG が有効かどうかを検証し、必要に応じて修正します。
    引数:
        :param nG: 指定された基底関数の数。
        :type nG: int
        :param na: 格子の分割数。
        :type na: int
    戻り値:
        :returns: 検証および修正後の基底関数の数。
        :rtype: int
    """
    if nG <= 0:
        terminate("Error: nG must be positive [nG={}]".format(nG))
    if nG % 2 == 0:
        nG += 1
        print("nG is changed to the odd number {}.".format(nG))
    if nG - 1 > na // 2:
        terminate("Error: nG is too large for na={} [nG={}]".format(na, nG))
    return nG
    
# 自由電子の運動エネルギーをG点内部座標 iG から計算
def free_KE(k, iG):
    """
    概要:
        G点内部座標 iG から自由電子の運動エネルギーを計算します。
    引数:
        :param k: 波数。
        :type k: float
        :param iG: 逆格子の内部座標。
        :type iG: int
    戻り値:
        :returns: 計算された運動エネルギー。
        :rtype: float
    """
    kK = KE * pow(2.0*pi/a, 2.0)  # coefficient of kinetic energy in eV and angstrom
    return kK * (k + iG) * (k + iG)

# 固有方程式を解き、固有エネルギーと平面波の係数を返す
# 波動関数は規格化されていない
def solve_pw(Glist, yft0, nGmax, nG, k, IsPrint = 0):
    """
    概要:
        固有方程式を解き、固有エネルギーと平面波の係数を返します。
    引数:
        :param Glist: G点のリスト。
        :type Glist: numpy.ndarray
        :param yft0: ポテンシャルのフーリエ変換結果。
        :type yft0: numpy.ndarray
        :param nGmax: Gの最大インデックス。
        :type nGmax: int
        :param nG: 基底関数の数。
        :type nG: int
        :param k: 波数。
        :type k: float
        :param IsPrint: デバッグ出力のレベル。
        :type IsPrint: int
    戻り値:
        :returns: 固有エネルギーの配列と平面波係数の行列のタプル。
        :rtype: tuple
    """
    kK = KE * pow(2.0*pi/a, 2.0)  # coefficient of kinetic energy in eV and angstrom

# H_GG' = kinetic delta_GG' + V_(G-G')
    Hij = np.empty([nG, nG], dtype = complex)
    for i in range(nG):
        iG = Glist[i]
        Vij = get_Vft(0, yft0)
        Hij[i][i] = free_KE(k, iG) + Vij
        for j in range(i+1, nG):
            jG = Glist[j]
            dij = iG - jG
            Vij = get_Vft(dij, yft0)
            if IsPrint >= 1:
                print("  iG,jG,dij=", iG, jG, dij, "  nG(base)=[{}, {}]".format(-nGmax, nGmax), "  Vij=", Vij)
            Hij[i][j] = Vij
            Hij[j][i] = Hij[i][j].conjugate()

#        print("  Hij=\n", Hij)
    ei, ci = LA.eigh(Hij)
    if IsPrint >= 1:
        print("  ei=", ei)
    if IsPrint >= 2:
        print("  ci=", ci)

    return ei, ci

# 平面波の係数から波動関数を計算
# i番目の基底の係数とG点内部座標を ci, Glistで渡す
# 波動関数は規格化されていない
def cal_wf(xwmin, xwmax, nxw, kw, ci, Glist):
    """
    概要:
        平面波の係数から波動関数を計算します。
    詳細説明:
        波動関数は規格化されていません。
    引数:
        :param xwmin: 座標の最小値。
        :type xwmin: float
        :param xwmax: 座標の最大値。
        :type xwmax: float
        :param nxw: 座標点の数。
        :type nxw: int
        :param kw: 波動関数の波数。
        :type kw: float
        :param ci: 基底関数の係数。
        :type ci: list または numpy.ndarray
        :param Glist: G点のリスト。
        :type Glist: numpy.ndarray
    戻り値:
        :returns: 座標配列、波動関数配列、電荷密度配列のタプル。
        :rtype: tuple
    """
    nG = len(ci)
    xwstep = (xwmax - xwmin) / (nxw - 1)
    xwf  = np.empty(nxw, dtype = float)
    ywf  = np.empty(nxw, dtype = complex)
    ywf2 = np.empty(nxw, dtype = float)
    for i in range(nxw):
        x = xwmin + i * xwstep
        f = 0.0
        for iG in range(nG):
            G = Glist[iG]
            f += ci[iG] * exp(1.0j * (kw+G) * pi2/a * x)
        f /= sqrt(a)
#        print("f({})={}".format(x, f))
        xwf[i] = x
        ywf[i] = f
        charge = f * f.conjugate()
        ywf2[i] = charge.real
    return xwf, ywf, ywf2

def wf():
    """
    概要:
        波動関数を計算してプロットします。
    詳細説明:
        グローバル変数を使用して計算条件を取得し、固有方程式を解いた後、指定されたエネルギー準位の波動関数を描画します。
    """
    global mode
    global a, na
    global nG, kw, iLevel
    global xwmin, xwmax, nxw

    nG = validate_nG(nG, na)

    xwstep = (xwmax - xwmin) / (nxw - 1)

    print("")
    print("=== Input parameterss ===")
    print("mode:", mode)
    print("a=", a, "A")
    print("  na=", na)
    print("potential: {} w={} A  h={} eV".format(pottype, bwidth, bpot))
    print("Wave function to be plotted: k = {}  iLevel = {}".format(kw, iLevel))
    print("x range: {} - {} at {} step, {} points".format(xwmin, xwmax, xwstep, nxw))
    print("potential: {} w={} A  h={} eV".format(pottype, bwidth, bpot))

    astep = a / na
    xpot, ypot   = build_potential(0.0, astep, na)
    xplot, yplot = build_potential(xwmin, xwstep, nxw)

    xft0, yft0, xft, yft, iGlist, nahalf, xftstep = cal_fft(na, a, ypot)

    print("")
    print("=== FT result ===")
    print("{:4} {:4} {}".format("i", "iG", "ci"))
    for i in range(na):
        print("{:4d} {:4d} {}".format(i, iGlist[i], yft0[i]))

# Extract G basis set for given nG
    Glist, Vftlist, nGmax = extract_basis(yft0, nG)

    print("")
    print("=== G basis extracted ===")
    print("nG =", nG)
    print("{:4} {}".format("iG", "Vft"))
    for i in range(nG):
        print("{:4d} {}".format(Glist[i], Vftlist[i]))

    print("")
    print("=== Solve eigen equations ===")
    k = kw
    print("at k = {}".format(k))

    yE, ci = solve_pw(Glist, yft0, nGmax, nG, k, IsPrint = 1)
    print("  ei=", yE)
    print("  ci=", ci)

    print("")
    print("=== Calculate wave function ===")
    print("Energy levels:")
    for i in range(len(yE)):
        print("  {} {:12.6g} eV".format(i, yE[i].real))

    print("")
    print("at k = {}".format(k))
    print("  selected for {}-th energy level:".format(iLevel))
    print("    E = {:12.6g} eV".format(yE[iLevel].real))
    print("  Wave function coefficinets")
    ciLevel = [ci[i][iLevel] for i in range(nG)]
    for i in range(nG):
        print("    at iG={:3d}".format(Glist[i]), "  ci={:8.4f}".format(ci[i][iLevel]))

    xwf, ywf, charge = cal_wf(xwmin, xwmax, nxw, kw, ciLevel, Glist)
    
    fig = plt.figure(figsize = (8, 8))
    ax2 = fig.add_subplot(1, 1, 1)
#    ax2 = fig.add_subplot(2, 1, 2)
# ax2をax1に関連させる
    ax1 = ax2.twinx()

    ax1.set_xlim([xwmin, xwmax])
    ax1.plot(xplot, yplot, linewidth = 0.5, label = '$V$($x$)')
    ax1.plot(ax1.get_xlim(), [0.0, 0.0], color = 'r', linestyle = 'dashed', linewidth = 0.5)
    ax2.set_xlim([xwmin, xwmax])
    ax2.plot(xwf, ywf.real, linewidth = 1.5, label = r"$\Psi$ (real)")
    ax2.plot(xwf, ywf.imag, linewidth = 1.5, label = r"$\Psi$ (imaginary)")
    ax2.plot(xwf, charge, linewidth = 0.5, label = r"$|\Psi|^2$")
    ax2.plot(ax1.get_xlim(), [0.0, 0.0], color = 'r', linestyle = 'dashed', linewidth = 0.5)

#    ax1.set_xlabel("$x$ ($\AA$)", fontsize = fontsize)
    ax1.set_ylabel("$V$($x$)", fontsize = fontsize)
    ax2.set_xlabel(r"$x$ ($\AA$)", fontsize = fontsize)
    ax2.set_ylabel(r"$\Psi$", fontsize = fontsize)

# 凡例をまとめて出力する
    handler1, label1 = ax1.get_legend_handles_labels()
    handler2, label2 = ax2.get_legend_handles_labels()
    ax2.legend(handler1 + handler2, label1 + label2, loc = 2, borderaxespad = 0.0, fontsize = legend_fontsize)
#    ax2.legend(fontsize = legend_fontsize)
    ax1.tick_params(labelsize = fontsize)
    ax2.tick_params(labelsize = fontsize)
    plt.tight_layout()

    plt.pause(0.1)
    print("Press ENTER to exit>>", end = '')
    input()

    return

def band():
    """
    概要:
        バンド構造を計算してプロットします。
    詳細説明:
        グローバル変数から計算条件を取得し、各波数点での固有エネルギーを計算してバンド図を描画します。
    """
    global mode
    global a, na
    global nG
    global kmin, kmax, nk
    global pottype, bwidth, bpot

    nG = validate_nG(nG, na)
    kstep = (kmax - kmin) / (nk - 1)

    print("")
    print("=== Input parameterss ===")
    print("mode:", mode)
    print("a=", a, "A")
    print("  na=", na)
    print("potential: {} w={} A  h={} eV".format(pottype, bwidth, bpot))
    print("Basis function: nG=", nG)
    print("k range: {} - {} at {} step, {} points".format(kmin, kmax, kstep, nk))
    print("potential: {} w={} A  h={} eV".format(pottype, bwidth, bpot))

    astep = a / na
    xpot, ypot = build_potential(0.0, astep, na)

    xft0, yft0, xft, yft, iGlist, nahalf, xftstep = cal_fft(na, a, ypot)

    print("")
    print("=== FT result ===")
    print("{:4} {:4} {}".format("i", "iG", "ci"))
    for i in range(na):
        print("{:4d} {:4d} {}".format(i, iGlist[i], yft0[i]))

# Extract G basis set for given nG
    Glist, Vftlist, nGmax = extract_basis(yft0, nG)

    print("")
    print("=== FTed potential ===")
    print("nG =", nG)
    print("{:4} {}".format("iG", "Vft"))
    for i in range(nG):
        print("{:4d} {}".format(Glist[i], Vftlist[i]))

    print("")
    print("=== Solve eigen equations ===")
    xk     = [kmin + i * kstep for i in range(nk)]
    yE     = np.empty([nG, nk])
    yEfree = np.empty([nG, nk])
    for ik in range(nk):
        k = kmin + ik * kstep
        print("at k = {}".format(k))

        ei,ci = solve_pw(Glist, yft0, nGmax, nG, k, IsPrint = 1)

        for i in range(nG):
            yE[i][ik] = ei[i]
            iG = Glist[i]
            print("k=", k, iG, k+iG)
            yEfree[i][ik] = free_KE(k, iG)

    fig = plt.figure(figsize = figsize)
    ax1 = fig.add_subplot(1, 1, 1)

    ax1.set_xlim([kmin, kmax])
    ax1.set_ylim(Erange)
    for iG in range(nG):
        ax1.plot(xk, yE[iG], linestyle = '', marker = 'o', markersize = 2.0,
                        markerfacecolor = 'none', markeredgecolor = 'black', markeredgewidth = 0.5,
                        label = 'periodic potential' if iG == 0 else None)
        ax1.plot(xk, yEfree[iG], linestyle = '-.', linewidth = 0.6, color = 'red',
                 label = 'free electron' if iG == 0 else None)

    ax1.set_xlabel(r"$k/(2\pi/a)$", fontsize = fontsize)
    ax1.set_ylabel("E (eV)", fontsize = fontsize)
    ax1.legend(fontsize = legend_fontsize)
    plt.tight_layout()

    plt.pause(0.1)
    print("Press ENTER to exit>>", end = '')
    input()
   
    return

def ft():
    """
    概要:
        ポテンシャルのフーリエ変換結果を計算してプロットします。
    詳細説明:
        実空間のポテンシャルと、そのフーリエ変換後の実部、虚部、絶対値をそれぞれ描画します。
    """
    global mode
    global a, na
    global pottype, bwidth, bpot

    astep = a / na

    print("")
    print("=== Input parameterss ===")
    print("mode:", mode)
    print("a=", a, "A")
    print("  na=", na)
    print("  astep=", astep)
    print("potential: {} w={} A  h={} eV".format(pottype, bwidth, bpot))
    print("")
    
    xpot, ypot   = build_potential(0.0, astep, na)
    xplot, yplot = build_potential(0.0, astep, 3 * na)

    xft0, yft0, xft, yft, iG, nahalf, xftstep = cal_fft(na, a, ypot)

    fig = plt.figure(figsize = (8, 8))
    ax1 = fig.add_subplot(2, 2, 1)
    ax2 = fig.add_subplot(2, 2, 3)
    ax3 = fig.add_subplot(2, 2, 4)

    ax1.plot(xplot, yplot, linewidth = 0.5)
    ax2.plot(xft0, yft0.real, label = "real", linewidth = 0.5)
    ax2.plot(xft0, yft0.imag, label = "imaginary", linewidth = 0.5)
    ax3.plot(xft,  yft.real, marker = 'o', markersize = 1.0, linewidth = 0.5, label = "real")
    ax3.plot(xft,  yft.imag, marker = 'o', markersize = 1.0, linewidth = 0.5, label = "imaginary")
    ax3.plot(xft,  abs(yft), marker = 'o', markersize = 1.0, linewidth = 0.5, label = "absolute")
    ax1.set_xlabel(r"$x$ ($\AA$)", fontsize = fontsize)
    ax1.set_ylabel("pot (x)", fontsize = fontsize)
    ax2.set_xlabel("i", fontsize = fontsize)
    ax2.set_ylabel("FTed pot, raw x", fontsize = fontsize)
    ax3.set_xlabel("1/x, normalized (1/A)", fontsize = fontsize)
    ax3.set_ylabel("FTed pot")
    ax3.set_xlim([-10.0 * xftstep, 10.0 * xftstep])
#    ax1.legend(fontsize = legend_fontsize)
    ax2.legend(fontsize = legend_fontsize)
    ax3.legend(fontsize = legend_fontsize)
    ax1.tick_params(labelsize = fontsize)
    ax2.tick_params(labelsize = fontsize)
    ax3.tick_params(labelsize = fontsize)
    plt.tight_layout()

    plt.pause(0.1)
    print("Press ENTER to exit>>", end = '')
    input()

    return

def main():
    """
    概要:
        メイン処理を実行します。
    詳細説明:
        入力パラメータの妥当性をチェックし、指定されたモードに応じてフーリエ変換、バンド計算、波動関数計算のいずれかを行います。
    """
    global mode

    if a <= 0.0:
        terminate("Error: a must be positive.")
    if na < 4 or na % 2 != 0:
        terminate("Error: na must be an even integer >= 4.")
    if pottype not in ('rect', 'gauss'):
        terminate("Error: pottype must be rect or gauss.")
    if bwidth <= 0.0:
        terminate("Error: bwidth must be positive.")
    if mode == 'band' and nk < 2:
        terminate("Error: nk must be >= 2.")
    if mode == 'wf' and nxw < 2:
        terminate("Error: nxw must be >= 2.")
    
    if mode == 'ft':
        ft()
    elif mode == 'band':
        band()
    elif mode == 'wf':
        wf()
    else:
        terminate("Error: Invalid mode [{}]".format(mode))


if __name__ == "__main__":
    main()