"""
概要:
    3次元周期境界条件下の井戸型ポテンシャルを平面波基底を用いて密行列対角化で解くスクリプトです。
詳細説明:
    NumPyまたはCuPyを使用し、CPUとGPUのいずれかを選択して計算できます。
    エネルギー単位はeV、長さ単位はオングストロームです。コマンドライン引数の backend によって
    使用するライブラリを切り替えます。
"""
import argparse
import csv
from pathlib import Path
from time import perf_counter

import numpy as np
from scipy.constants import hbar, electron_mass, electron_volt

KE = hbar**2 / (2 * electron_mass) / electron_volt * 1e20


def initialize():
    """
    概要:
        コマンドライン引数を解析して設定を初期化します。
    詳細説明:
        格子定数、井戸のサイズや深さ、平面波の数、k点の数、バンド数などのパラメータを取得し、
        不正な値が指定された場合はエラーを出力します。
    戻り値:
        :returns: コマンドライン引数を格納したNamespaceオブジェクト。
        :rtype: argparse.Namespace
    """
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument('--backend', choices=['numpy', 'gpu', 'both'], default='numpy')
    p.add_argument('--a', type=float, default=5.4064, help='cubic lattice constant [angstrom]')
    p.add_argument('--width', type=float, default=2.0, help='box well side length [angstrom]')
    p.add_argument('--depth', type=float, default=10.0, help='well depth [eV]; inside=-depth, outside=0')
    p.add_argument('--ng', type=int, default=5, help='odd number of plane waves PER AXIS; total=ng**3')
    p.add_argument('--nk', type=int, default=9, help='points per path segment, endpoints included')
    p.add_argument('--bands', type=int, default=8, help='number of bands saved/plotted (full diagonalization)')
    p.add_argument('--vectors', action='store_true', help='also compute eigenvectors (not saved)')
    p.add_argument('--repeat', type=int, default=1, help='repeat whole k path; report median total time')
    p.add_argument('--no-plot', action='store_true')
    p.add_argument('--output', type=Path, default=Path('pw3d'))
    a = p.parse_args()
    if a.a <= 0 or not 0 < a.width <= a.a or a.depth < 0:
        p.error('require a>0, 0<width<=a, depth>=0')
    if a.ng < 1 or a.ng % 2 != 1 or a.nk < 2 or a.bands < 1 or a.repeat < 1:
        p.error('ng must be positive odd; nk>=2; bands>=1; repeat>=1')
    return a


def kpath(nk):
    """
    概要:
        k空間のパスを生成します。
    詳細説明:
        逆格子のフラクショナル座標系で頂点間を補間し、計算対象となるk点の座標と
        累積距離を計算します。
    引数:
        :param nk: 各パスセグメントの分割ポイント数。
        :type nk: int
    戻り値:
        :returns: k点の座標配列、各点の累積距離配列、主要なパス境界の累積距離リストのタプル。
        :rtype: tuple
    """
    # Reciprocal fractional coordinates, in units of 2*pi/a.
    vertices = np.array([[0,0,0], [.5,0,0], [.5,.5,0], [0,0,0], [.5,.5,.5]])
    points, distances, ticks = [], [], [0.0]
    offset = 0.0
    for i, (u,v) in enumerate(zip(vertices[:-1], vertices[1:])):
        for j,t in enumerate(np.linspace(0,1,nk)):
            if i and j == 0:
                continue
            points.append(u + t*(v-u))
            distances.append(offset + t*np.linalg.norm(v-u))
        offset += np.linalg.norm(v-u)
        ticks.append(offset)
    return np.array(points), np.array(distances), ticks


def basis(ng):
    """
    概要:
        平面波基底の格子点座標を生成します。
    引数:
        :param ng: 各軸ごとの平面波の数。
        :type ng: int
    戻り値:
        :returns: 3次元の基底ベクトルの配列。
        :rtype: numpy.ndarray
    """
    q = np.arange(-(ng//2), ng//2+1)
    return np.stack(np.meshgrid(q,q,q,indexing='ij'), axis=-1).reshape(-1,3)


def potential_matrix(xp, G, width, a, depth):
    """
    概要:
        井戸型ポテンシャルの行列を作成します。
    詳細説明:
        セル原点に中心を持つ井戸型ポテンシャルのフーリエ係数を解析的に計算し、行列を生成します。
        sinc関数を用いた計算を行います。
    引数:
        :param xp: 使用する配列モジュール。numpyまたはcupy。
        :type xp: module
        :param G: 平面波基底ベクトルの配列。
        :type G: numpy.ndarrayまたはcupy.ndarray
        :param width: 井戸の1辺の長さ。
        :type width: float
        :param a: 立方格子の格子定数。
        :type a: float
        :param depth: 井戸の深さ。
        :type depth: float
    戻り値:
        :returns: ポテンシャル行列。
        :rtype: numpy.ndarrayまたはcupy.ndarray
    """
    # Well centered at the cell origin. Analytic Fourier coefficient:
    # V_q = -depth * (width/a)^3 * product_axis sinc(q_axis*width/a).
    # sinc(z)=sin(pi*z)/(pi*z). Nonseparable product well, not Vx+Vy+Vz.
    M = len(G)
    V = xp.full((M,M), -depth*(width/a)**3, dtype=xp.float64)
    for axis in range(3):
        dq = G[:,axis,None] - G[None,:,axis]
        V *= xp.sinc(dq * (width/a))
    return V


def run(a, backend, ks, G_cpu):
    """
    概要:
        指定されたバックエンドを使用して固有値計算を実行します。
    詳細説明:
        バックエンドに応じてNumPyまたはCuPyを初期化し、各k点に対してハミルトニアン行列の構築と
        対角化を行い、エネルギー固有値を計算します。各ステップの処理時間も計測して記録します。
    引数:
        :param a: コマンドライン引数を格納したNamespace。
        :type a: argparse.Namespace
        :param backend: 使用するバックエンド名。numpyまたはgpu。
        :type backend: str
        :param ks: k点の配列。
        :type ks: numpy.ndarray
        :param G_cpu: CPU上の基底ベクトル配列。
        :type G_cpu: numpy.ndarray
    戻り値:
        :returns: 経過時間とエネルギー固有値のリスト、および実行時間の詳細な記録を含む辞書のリストのタプル。
        :rtype: tuple
    """
    start_init = perf_counter()
    if backend == 'numpy':
        xp = np
        def sync():
            pass
    else:
        import cupy as xp
        xp.cuda.Device().use()
        def sync():
            xp.cuda.get_current_stream().synchronize()
    # Unmeasured warmup: initializes context and eigensolver, not full-size solve.
    small = xp.eye(4, dtype=xp.float64)
    if a.vectors:
        xp.linalg.eigh(small)
    else:
        xp.linalg.eigvalsh(small)
    sync()
    startup = perf_counter()-start_init
    print(f'{backend}: startup/warmup={startup:.6f}s (separate from trials)', flush=True)
    all_rows, results = [], []
    for trial in range(a.repeat):
        sync()
        total_start = perf_counter()
        t = perf_counter()
        G = xp.asarray(G_cpu, dtype=xp.float64)
        k_device = xp.asarray(ks, dtype=xp.float64)
        sync()
        upload = perf_counter()-t
        t = perf_counter()
        V = potential_matrix(xp, G, a.width, a.a, a.depth)
        diag = xp.arange(len(G))
        sync()
        potential_time = perf_counter()-t
        energies = []
        construct_time = solve_time = download_time = 0.0
        for ik in range(len(ks)):
            t = perf_counter()
            H = V.copy()
            H[diag,diag] += KE*(2*np.pi/a.a)**2 * xp.sum((G+k_device[ik])**2, axis=1)
            sync()
            dt_build = perf_counter()-t
            t = perf_counter()
            if a.vectors:
                ev, vectors = xp.linalg.eigh(H)
            else:
                ev = xp.linalg.eigvalsh(H)
            sync()
            dt_solve = perf_counter()-t
            t = perf_counter()
            selected = ev[:min(a.bands,len(G))]
            energies.append(np.array(selected,copy=True) if backend == 'numpy' else xp.asnumpy(selected))
            sync()
            dt_download = perf_counter()-t
            construct_time += dt_build
            solve_time += dt_solve
            download_time += dt_download
            all_rows.append(dict(backend=backend, trial=trial+1, k_index=ik,
                                 build_seconds=dt_build, eig_seconds=dt_solve,
                                 result_copy_seconds=dt_download))
            if a.vectors:
                del vectors
            del H, ev
        sync()
        elapsed = perf_counter()-total_start
        energies = np.array(energies)
        results.append((elapsed, energies))
        print(f'{backend} trial {trial+1}: total={elapsed:.6f}s, input={upload:.6f}s, '
              f'V={potential_time:.6f}s, H={construct_time:.6f}s, '
              f'eigen={solve_time:.6f}s, result_copy={download_time:.6f}s', flush=True)
        all_rows.append(dict(backend=backend, trial=trial+1, k_index='TOTAL',
                             build_seconds=construct_time, eig_seconds=solve_time,
                             result_copy_seconds=download_time, total_seconds=elapsed,
                             input_seconds=upload, potential_seconds=potential_time,
                             startup_seconds=startup))
        del V, G, k_device
    return results, all_rows


def save_csv(path, rows):
    """
    概要:
        辞書のリストをCSVファイルとして保存します。
    引数:
        :param path: 保存先のファイルパス。
        :type path: pathlib.Path
        :param rows: CSVに書き込む辞書のリスト。
        :type rows: list
    """
    path.parent.mkdir(parents=True,exist_ok=True)
    fields = list(dict.fromkeys(k for r in rows for k in r))
    with path.open('w', newline='', encoding='utf-8-sig') as f:
        writer = csv.DictWriter(f,fieldnames=fields)
        writer.writeheader()
        writer.writerows(rows)
    print('Saved:',path)


def main():
    """
    概要:
        プログラムのメイン処理を実行します。
    詳細説明:
        パラメータの初期化、基底ベクトルやk点の生成を行い、指定されたバックエンドで
        対角化計算を実行します。計算後はパフォーマンス結果とバンド構造をCSVに保存し、
        プロットが有効な場合はグラフを表示して画像として保存します。
    """
    a = initialize()
    G = basis(a.ng)
    ks, distance, ticks = kpath(a.nk)
    M = len(G)
    print(f'Basis: {a.ng}**3 = {M}; real symmetric matrix {M}x{M}; '
          f'one matrix={M*M*8/2**20:.2f} MiB (workspace/additional arrays extra)')
    print(f'k-points={len(ks)}; full spectrum; eigenvectors={a.vectors}')
    print('Potential: periodic centered cubic well, inside=-depth, outside=0; analytic Fourier coefficients')
    print('Energies are absolute relative to outside potential=0.')
    backends = ['numpy','gpu'] if a.backend == 'both' else [a.backend]
    timings, bands = [], {}
    medians = {}
    for backend in backends:
        results, rows = run(a,backend,ks,G)
        timings.extend(rows)
        medians[backend] = float(np.median([r[0] for r in results]))
        bands[backend] = results[0][1]
        print(f'{backend}: median total={medians[backend]:.6f}s')
    if len(bands)==2:
        print(f'CPU/GPU speedup (median totals)={medians["numpy"]/medians["gpu"]:.3f}x')
        print(f'Max absolute CPU-GPU eigenvalue difference='
              f'{np.max(np.abs(bands["numpy"]-bands["gpu"])):.3e} eV')
    save_csv(a.output.with_name(a.output.name+'_timing.csv'),timings)
    records=[]
    for backend, es in bands.items():
        for i,(k,dist,vals) in enumerate(zip(ks,distance,es)):
            row=dict(backend=backend,k_index=i,kx=k[0],ky=k[1],kz=k[2],distance=dist)
            row.update({f'E{j}_eV':v for j,v in enumerate(vals)})
            records.append(row)
    save_csv(a.output.with_name(a.output.name+'_bands.csv'), records)
    if not a.no_plot:
        import matplotlib.pyplot as plt
        fig, ax = plt.subplots(figsize=(8,6))
        for backend,es in bands.items():
            for j in range(es.shape[1]):
                ax.plot(distance,es[:,j],'-' if backend=='numpy' else '--',
                        color='C0' if backend=='numpy' else 'C1',
                        label=backend if j==0 else None)
        ax.set_xticks(ticks,['Γ','X','M','Γ','R'])
        for tick in ticks:
            ax.axvline(tick,color='gray',lw=.5)
        ax.set_ylabel('Energy (eV)')
        ax.set_title(f'3D plane waves: {a.ng} per axis, {M} total')
        ax.legend()
        fig.tight_layout()
        path=a.output.with_name(a.output.name+'_bands.png')
        fig.savefig(path,dpi=160)
        print('Saved:',path)
        plt.show()


if __name__=='__main__':
    main()