
import numpy as np
import matplotlib.pyplot as plt
import math

def readResults():

    
    labels = ['1','2','3', '4', '5']
    
    for n in labels: 

        old = np.genfromtxt('galaxy_model_check/old0{}.dat'.format(n))
        new = np.genfromtxt('galaxy_model_check/new0{}.dat'.format(n))
        
        if n=='1':
            runningOld = old
            runningNew = new
        else: 
            runningOld = np.concatenate((runningOld, old))
            runningNew = np.concatenate((runningNew, new))
            
    return runningOld, runningNew


def main():
    old, new = readResults()

    for i in range(5):
        print('\nfrequency: ', i)
        hold = old[:,i]
        hnew = new[:,i]
    
        absDiff = [ abs(10.**hn-10.**ho) for hn,ho in zip(hnew,hold) ] 
        
        percentDiff = [ 100*(abs((10.**hn)-(10.**ho))/(10.**ho)) for hn,ho in zip(hnew,hold) ] 

        for p in percentDiff: 
            if p>=5: print('help!', p, '%')


        # for the binning
        minimumh = math.floor(min(min(hnew),min(hold)))
        maximumh = math.ceil(max(max(hnew),max(hold)))
        bins = np.arange(minimumh, maximumh, 0.5)

        fig, (ax1, ax2, ax3) = plt.subplots(1,3)
        
        # plotting hold and hnew
        ax1.hist(hnew,histtype='step',label='new',bins=bins,lw=2,color='#E69F00')
        ax1.hist(hold,histtype='step',label='old',bins=bins,lw=2,color='#0072B2',ls=':')
        ax1.set_xlabel(r'$\log_{10} h_{\rm c}$',fontsize=14)
        ax1.set_ylabel('count',fontsize=14)
        ax1.legend()
        
        # plotting difference
        ax2.hist(np.log10(absDiff),histtype='step',label='abs(hnew-hold)',lw=2,color='#009E73')
        ax2.set_xlabel(r'$\log_{10} |h_{\rm c, new} - h_{\rm c, old}|$',fontsize=14)
        ax2.set_ylabel('count',fontsize=14)
        ax2.legend()
        
        # plotting percentage difference
        ax3.hist(percentDiff,histtype='step',label='%-difference',lw=2,color='#009E73')
        ax3.set_xlabel(r'percent difference $\left(100*\frac{|h_{\rm c, new}-h_{\rm c, old}|}{h_{\rm c, old}}\right)$',fontsize=14)
        ax3.set_ylabel('count',fontsize=14)
        ax3.legend()
        
        #ax2.set_title('{} draws from prior'.format(nDrawsToDo),fontsize=14)
        
        fig.set_figwidth(20)
        plt.tight_layout()

        plt.savefig('galaxy_model_check/model_check.png')
        plt.savefig('model_check.pdf')
        plt.show()
    
    
if __name__ == "__main__":
    main()
