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

bluefile = 'blue_2017_04_20_bin'
redfile = 'red_2017_04_20_bin'
postfile = 'bi_2017_04_20_bin'

bg_blue =  0.31
bg_red = 0.39

data_fromfile = np.genfromtxt(bluefile)
blue_single_atom = data_fromfile[:,0]
blue_single_bg = data_fromfile[:,2]

data_fromfile = np.genfromtxt(redfile)
red_single_atom = data_fromfile[:,1]
red_single_bg = data_fromfile[:,3]

data_fromfile = np.genfromtxt(postfile)

blue_atom_1 = data_fromfile[:,0] - bg_blue 
red_atom_1 = data_fromfile[:,1] - bg_red
blue_bg_1 = data_fromfile[:,2] - bg_blue 
red_bg_1 = data_fromfile[:,3] - bg_red
 
blue_atom_2= data_fromfile[:,4] - bg_blue 
red_atom_2 = data_fromfile[:,5] - bg_red
blue_bg_2 = data_fromfile[:,6] - bg_blue 
red_bg_2 = data_fromfile[:,7] - bg_red

binwidth = 2
binrange=  np.arange(0,300,binwidth)
hist_blue_single_atom , bins_blue_single_atom  = np.histogram(blue_single_atom , binrange)
hist_blue_single_bg, bins_blue_single_bg = np.histogram(blue_single_bg, binrange)
width_blue = binwidth*0.7
center_blue = (bins_blue_single_atom[:-1] + bins_blue_single_atom[1:]) / 2

hist_red_single_atom , bins_red_single_atom  = np.histogram(red_single_atom , binrange)
hist_red_single_bg, bins_red_single_bg = np.histogram(red_single_bg, binrange)
width_red = binwidth*0.7
center_red = (bins_red_single_atom[:-1] + bins_red_single_atom[1:]) / 2


# save post selected data for histo analysis ---------
post_blue = []
post_blue_bg = []
post_red = []
post_red_bg =[]	
th_atom = blue_atom_2 + red_atom_2
#take data in phase 1 if phase 2 is good
for i in range(0,len(blue_atom_1)-1):
	#if th_atom[i] < threshold[best_th_sum_idx]:
	if th_atom[i] < 69.09:
		post_blue.append(blue_atom_1[i])
		post_blue_bg.append(blue_bg_1[i])
		post_red.append(red_atom_1[i])
		post_red_bg.append(red_bg_1[i])
	
#evaluate tx
post_blue = np.array(post_blue)
post_blue_bg = np.array(post_blue_bg)
post_red = np.array(post_red)
post_red_bg = np.array(post_red_bg)


hist_blue_bi_atom , bins_blue_single_atom  = np.histogram(post_blue , binrange)
hist_red_bi_atom , bins_red_single_atom  = np.histogram(post_red  , binrange)

hist_sum_bi_atom , bins_red_single_atom  = np.histogram(post_blue+post_red, binrange)
hist_sum_bi_bg, bins_red_single_atom  = np.histogram(post_blue_bg + post_red_bg , binrange)

print("mean blue atom "+'%.3f'% np.mean(blue_single_atom)+",   mean blue bg "+'%.3f'% np.mean(blue_single_bg), ",   tx "+'%.3f'% (np.mean(blue_single_atom)/np.mean(blue_single_bg))  ) 
print("mean red atom "+'%.3f'% np.mean(red_single_atom)+",   mean red bg "+'%.3f'% np.mean(red_single_bg), ",   tx "+'%.3f'% (np.mean(red_single_atom)/np.mean(red_single_bg))  ) 
print("mean sum atom "+'%.3f'% np.mean(post_blue+post_red )+",   mean sum bg "+'%.3f'% np.mean(post_blue_bg + post_red_bg ), ",   tx "+'%.3f'% (np.mean(post_blue+post_red)/np.mean(post_blue_bg + post_red_bg )) ) 
print("bins in bi run "+'%.0f'% len(blue_atom_1 )+",  bins after post selection "+'%.0f'% len(post_blue ), ",   ratio "+'%.4f'% (len(post_blue)/len(blue_atom_1 )) ) 



savedata=np.zeros((len(bins_blue_single_atom )-1,9))
savedata[:,0] = bins_blue_single_atom[:-1]
savedata[:,1] = hist_blue_bi_atom
savedata[:,2] = hist_blue_single_atom
savedata[:,3] = hist_blue_single_bg
savedata[:,4] = hist_red_bi_atom
savedata[:,5] = hist_red_single_atom
savedata[:,6] = hist_red_single_bg
savedata[:,7] = hist_sum_bi_atom
savedata[:,8] = hist_sum_bi_bg
np.savetxt('histo.dat', savedata,header='#bin bi_blue sg_blue bg_blue bi_red sg_red bg_red bi_sum bi_sum_bg')

#np.savetxt('histo.dat', np.transpose(np.array([bins_blue_single_atom, hist_blue_bi_atom , hist_blue_single_atom, hist_blue_single_bg, hist_red_bi_atom , hist_red_single_atom, hist_red_single_bg, hist_sum_bi_atom , hist_sum_bi_bg ])),header='#bin bi_blue sg_blue bg_blue bi_red sg_red bg_red bi_sum bi_sum_bg')



# Three subplots sharing both x/y axes
f, (blue_fig, red_fig, sum_fig) = plt.subplots(3, sharex=True, sharey=True)

#blue_fig.set_title('Sharing both axes')

# Fine-tune figure; make subplots close to each other and hide x ticks for
# all but bottom plot.
f.subplots_adjust(hspace=0)
plt.setp([a.get_xticklabels() for a in f.axes[:-1]], visible=False)
blue_fig.tick_params( labelsize=16)
red_fig.tick_params( labelsize=16)
sum_fig.tick_params( labelsize=16)
#blue_fig = plt.figure(1)
#plt.bar(center_blue, hist_blue_single_atom/sum(hist_blue_single_atom), align='center', width=width_blue,alpha = 0.5)
#plt.bar(center_blue, hist_blue_single_bg/sum(hist_blue_single_bg), align='center', width=width_blue, color='grey', alpha = 0.5)
#plt.bar(center_blue, hist_blue_bi_atom/sum(hist_blue_bi_atom), align='center', width=width_blue, color='green', alpha = 0.5)
blue_fig.hist(blue_single_bg , 100, (0,200), normed=True,  histtype='step', color='grey',  linewidth=1.5, label='reference')
blue_fig.hist(blue_single_atom , 100, (0,200), normed=True,  histtype='step', color='blue', linewidth=1.5, label='one side CW')
blue_fig.hist(post_blue, 100, (0,200), normed=True,  histtype='step', color='green', linewidth=1.5, label='both sides')

blue_fig.legend()
blue_fig.annotate('detector 1', xy=(50, 0.07), size='14' )

#blue_fig.xlabel('counts')
#blue_fig.ylabel('rel. freq. of occurances')
#blue_fig.title('BLUE detector')
#blue_fig.xlim([0,140])
#blue_fig.ylim([0,0.1])
#blue_fig.savefig('blue_bin_hist'+'.pdf', bbox_inches='tight')

#red_fig = plt.figure(2)
plt.xlabel('counts', size =18)
red_fig.set_ylabel(r'relative frequency of occurances', size =18)
red_fig.get_yaxis().set_label_coords(-0.1,0.5)
#plt.title('RED detector')
#plt.bar(center_red, hist_red_single_atom/sum(hist_red_single_atom), align='center', width=width_red,alpha = 0.5)
#plt.bar(center_red, hist_red_single_bg/sum(hist_red_single_bg), align='center', width=width_red, color='grey',alpha = 0.5)
#plt.bar(center_blue, hist_red_bi_atom/sum(hist_red_bi_atom), align='center', width=width_blue, color='green', alpha = 0.5)
red_fig.hist(red_single_bg , 100, (0,200), normed=True,  histtype='step', color='grey',linewidth=1.5, label='reference')
red_fig.hist(red_single_atom , 100, (0,200), normed=True,  histtype='step', color='blue', linewidth=1.5, label='one side ACW')
red_fig.hist(post_red, 100, (0,200), normed=True,  histtype='step', color='green', linewidth=1.5,label='both sides')
red_fig.legend()
red_fig.annotate('detector 2', xy=(50, 0.07), size='14' )
#plt.savefig('red_bin_hist'+'.pdf', bbox_inches='tight')
#plt.xlim([0,80])

#sum_fig = plt.figure(3)

#plt.title('Blue+Red detector')
#plt.bar(center_red, hist_sum_bi_atom/sum(hist_sum_bi_atom) , align='center', width=width_red, color='green',alpha = 0.5)
#plt.bar(center_red, hist_sum_bi_bg/sum(hist_sum_bi_bg), align='center', width=width_red, color='grey',alpha = 0.5)
sum_fig.hist(post_blue_bg + post_red_bg , 100, (0,200), normed=True,  histtype='step', color='grey', linewidth=1.5, label='reference')
sum_fig.hist(post_blue+post_red , 100, (0,200), normed=True,  histtype='step', color='green', linewidth=1.5, label='both sides')
sum_fig.legend()
sum_fig.annotate('detector 1+2', xy=(50, 0.07), size='14' )


plt.xlim([0,200])
plt.ylim([0,0.09])
plt.yticks([0,0.05])
plt.savefig('hist'+'.pdf', bbox_inches='tight')

#blue_fig.show()
#red_fig.show()
#sum_fig.show()
plt.show()
