from scipy import *
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import matplotlib.cm as cmx
import matplotlib.gridspec as gridspec
import matplotlib as mpl
import matplotlib.animation as animation
import sys


def get_kpath_and_kval(file_in):
	
    ftmp = open(file_in, 'r')
    kpath = ftmp.readline().rstrip('\n').split()
    kval = ftmp.readline().rstrip('\n').split()
    ftmp.close()

    if kpath[0] == '#' and kval[0] == '#':
        kval_float = [float(val) for val in kval[1:]]
        kpath_mod = []
        for i in range(len(kpath[1:])):
            if kpath[i+1] == 'G':
                kpath_mod.append('$\Gamma$')
            else:
                kpath_mod.append('$\mathrm{'+kpath[i+1]+'}$')

        return kpath_mod, kval_float
    else:
        return [], []

def shiftedColorMap(cmap, start=0, midpoint=0.5, stop=1.0, name='shiftedcmap'):
    '''
    Function to offset the "center" of a colormap. Useful for
    data with a negative min and positive max and you want the
    middle of the colormap's dynamic range to be at zero

    Input
    -----
      cmap : The matplotlib colormap to be altered
      start : Offset from lowest point in the colormap's range.
          Defaults to 0.0 (no lower ofset). Should be between
          0.0 and `midpoint`.
      midpoint : The new center of the colormap. Defaults to 
          0.5 (no shift). Should be between 0.0 and 1.0. In
          general, this should be  1 - vmax/(vmax + abs(vmin))
          For example if your data range from -15.0 to +5.0 and
          you want the center of the colormap at 0.0, `midpoint`
          should be set to  1 - 5/(5 + 15)) or 0.75
      stop : Offset from highets point in the colormap's range.
          Defaults to 1.0 (no upper ofset). Should be between
          `midpoint` and 1.0.
    '''
    cdict = {
        'red': [],
        'green': [],
        'blue': [],
        'alpha': []
    }

    # regular index to compute the colors
    reg_index = np.linspace(start, stop, 257)

    # shifted index to match the data
    shift_index = np.hstack([
        np.linspace(0.0, midpoint, 128, endpoint=False), 
        np.linspace(midpoint, 1.0, 129, endpoint=True)
    ])

    for ri, si in zip(reg_index, shift_index):
        r, g, b, a = cmap(ri)

        cdict['red'].append((si, r, r))
        cdict['green'].append((si, g, g))
        cdict['blue'].append((si, b, b))
        cdict['alpha'].append((si, a, a))

    newcmap = matplotlib.colors.LinearSegmentedColormap(name, cdict)
    plt.register_cmap(cmap=newcmap)

    return newcmap


mpl.rc('font',**{'family':'Times New Roman','sans-serif':['Helvetica']})
mpl.rc('ytick', labelsize=16)
mpl.rc('xtick.major', pad=8)
mpl.rc('ytick.major', pad=8)
mpl.rc('text', usetex=True)

filename1 = 'BGG_cell0_harm.bands'

band_FP = loadtxt(filename1)
band_scph= loadtxt("BGG_SCPH0_offdiag.scph_bands")
band_scph = band_scph.reshape((101,204,164))

#exp = loadtxt('STO_phband_300K_exp.dat')
#exp2 = loadtxt('STO_phband_300K_exp2.dat')

fig = plt.figure(figsize=(8,6))
ax_band2 = plt.subplot(111)

kpname, kpval = get_kpath_and_kval(filename1)
for i in range(len(kpval)):
    kpval[i] /= kpval[-1]

cm = plt.get_cmap('PuBu')
shifted_cm = shiftedColorMap(cm, start=0.60, stop=0.9)
cNorm = colors.Normalize(vmin = 0, vmax=1000)
scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=shifted_cm)
scalarMap._A = []
ax_band2.xaxis.grid(True, linestyle='-')
#ax_band2.axhspan(0,0, alpha=0.2, color='gray')
ax_band2.axis([0, 1, 0, 300])
ax_band2.axes.set_xticks(kpval)
ax_band2.axes.set_xticklabels(kpname, fontsize=18)
ax_band2.axes.set_ylabel(r"Phonon frequency (cm${}^{-1}$)", fontsize=18)
plt.setp(ax_band2.get_yticklabels(), fontsize=18)
ax_band2.yaxis.grid(False)

linewidth = 0.5
lines = []
ax_band2.plot(band_FP[:,0]/band_FP[-1,0], band_FP[:,2:], color='lightgray', alpha=0.5, linestyle = '-', lw = 1.0)
lines = []
for index in range(162):
    line, = ax_band2.plot([], [], color='red', linestyle='-', lw = 1.5, zorder=10)
    lines.append(line)
ttl = ax_band2.text(.45, 1.015, '', fontsize= 18, transform = ax_band2.transAxes)

def init():
    ttl.set_text('')
    for line in lines:
        line.set_data([],[])
    return lines, ttl

def animate(i):
    Temp = band_scph[i,0,0]
    print(Temp)
    ttl.set_text(r'$T$ = %s K' % str(Temp))
    ttl.set_position((0.4,1.05))
    ttl.set_size(20)
    ttl.set_weight('semibold')
    for lnum, line in enumerate(lines):
        line.set_data(band_scph[i,:,1]/band_scph[i,-1,1], band_scph[i,:,lnum+2])
    return lines, ttl

ntemp, nk, ns = np.shape(band_scph)
fig.tight_layout(rect=[0, 0.0, 1, 0.95])

anim = animation.FuncAnimation(fig, animate, init_func = init,
                               frames=101, interval=100, blit=False, repeat=False)

anim.save('anim.mp4', writer="ffmpeg", dpi=200)

#plt.savefig("STO_SCP_anime.pdf", format='pdf', transparent=True, bbox_inches = 'tight')


#plt.show()

