# written by He Xinyi, modified by T. Kamiya
"""
PDOS (部分状態密度) データをグラフ化し、画像ファイルとして保存するスクリプト。

詳細説明:
    このスクリプトは、コマンドライン引数で指定されたPDOSデータファイルを読み込み、
    Matplotlibライブラリを用いてPDOSプロットを生成します。
    生成されたグラフは 'dos.png' というファイル名でカレントディレクトリに保存されます。
    軸ラベル、フォント設定、凡例、プロット範囲など、グラフの表示に関する詳細な設定が含まれています。
    このスクリプトは、特定のファイル形式のDOSデータを視覚化するために設計されています。

:param file: PDOSデータを含む入力ファイルのパス。(sys.argv[1]で受け取られます)
:type file: str

:returns: なし。グラフ画像ファイル 'dos.png' がカレントディレクトリに生成されます。
:rtype: None

:doc:`pdos_usage`
"""

import numpy as np
import matplotlib as mpl
mpl.use('Agg') #silent mode
from matplotlib import pyplot as plt
import matplotlib.ticker as ticker
import sys

#------------------ FONT_setup ----------------------
font = {'family' : 'arial', 
    'color'  : 'black',
    'weight' : 'normal',
    'size' : 18.0,
    }


def usage():
    print("")
    print("usage: python {} dosfile".format(sys.argv[0]))
    print("")


def main():
    argv = sys.argv
    narg = len(argv)
    if narg < 2:
        usage()
        sys.exit(1)

    file = argv[1]
    xmin=-2
    xmax=2
    ymax=10

    #------------------- Data Read ----------------------
    print("")
    print(f"Read DOS from [{file}]")

    with open(file,"r") as reader:
        legend = reader.readline()
    legends=legend.split()[1:]
    legends=[i.replace("_"," ") for i in legends]
    legend_s=tuple(legends)
    datas=np.loadtxt(file,dtype=np.float64,skiprows=1)

    #--------------------- PLOTs ------------------------
    axe = plt.subplot(111)
    plt.subplots_adjust(left=0.18, right=0.95, top=0.95, bottom=0.18)
    # Color methods! choose only one of the two methods
    axe.plot(datas[:,0],datas[:,1:],linewidth=1.0) #auto colors

    axe.set_xlabel(r'${E}$-$E_{F}$ (eV)',fontdict=font)
    axe.set_ylabel(r'PDOS (states/eV)',fontdict=font)
    #my_y_ticks=np.arange(0, ymax,ymax/2)
    my_x_ticks=np.arange(-5, 5,1)
    plt.xticks(my_x_ticks,fontsize=font['size']-2)
    plt.yticks(fontsize=font['size']-2,fontname=font['family'])
    plt.legend(legend_s,loc='upper right')
    plt.xlim(( xmin,  xmax)) # set y limits manually
    plt.ylim(( 0,  ymax))
    leg = plt.gca().get_legend()
    ltext = leg.get_texts()
    plt.setp(ltext, fontsize=font['size']) 
    fig = plt.gcf()
    fig.set_size_inches( 5, 4)
    plt.savefig('dos.png',dpi= 300,transparent=True)


if __name__ == '__main__':
    main()