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


postfile = '2017-04-20/bi_2017_04_20_bin'


data_fromfile = np.genfromtxt(postfile)

blue_atom_1 = data_fromfile[:,0]
red_atom_1 = data_fromfile[:,1]
blue_bg_1 = data_fromfile[:,2]
red_bg_1 = data_fromfile[:,3]

blue_atom_2= data_fromfile[:,4]
red_atom_2 = data_fromfile[:,5]
blue_bg_2 = data_fromfile[:,6]
red_bg_2 = data_fromfile[:,7]

binwidth = 4
binrange=  np.arange(0,300,binwidth)
hist_blue_atom_1 , bins_blue_atom_1  = np.histogram(blue_atom_1 , binrange)
hist_blue_bg_1, bins_blue_bg_1 = np.histogram(blue_bg_1, binrange)
width_blue = binwidth*0.7
center_blue = (bins_blue_atom_1[:-1] + bins_blue_atom_1[1:]) / 2

hist_red_atom_1 , bins_red_atom_1  = np.histogram(red_atom_1 , binrange)
hist_red_bg_1, bins_red_bg_1 = np.histogram(red_bg_1, binrange)
width_red = binwidth*0.7
center_red = (bins_red_atom_1[:-1] + bins_red_atom_1[1:]) / 2

hist_blue_atom_2 , bins_blue_atom_2  = np.histogram(blue_atom_2 , binrange)
hist_blue_bg_2, bins_blue_bg_2 = np.histogram(blue_bg_2, binrange)
width_blue = binwidth*0.7
center_blue = (bins_blue_atom_2[:-1] + bins_blue_atom_2[1:]) / 2

hist_red_atom_2 , bins_red_atom_2  = np.histogram(red_atom_2 , binrange)
hist_red_bg_2, bins_red_bg_2 = np.histogram(red_bg_2, binrange)
width_red = binwidth*0.7
center_red = (bins_red_atom_2[:-1] + bins_red_atom_2[1:]) / 2

hist_atom_1_sum , bins_atom_1__sum  = np.histogram(blue_atom_1+red_atom_1 , binrange)
hist_bg_1_sum, bins_bg_1_sum = np.histogram(blue_bg_1+red_bg_1, binrange)

hist_atom_2_sum , bins_atom_2__sum  = np.histogram(blue_atom_2+red_atom_2 , binrange)
hist_bg_2_sum, bins_bg_2_sum = np.histogram(blue_bg_2+red_bg_2, binrange)



# 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] < 70:
		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)

binwidth = 4
binrange=  np.arange(0,300,binwidth)
hist_blue_bi_atom , bins  = np.histogram(post_blue , binrange)
hist_blue_bi_bg , bins  = np.histogram(post_blue_bg , binrange)
hist_red_bi_atom , bins  = np.histogram(post_red  , binrange)
hist_red_bi_bg , bins  = np.histogram(post_red_bg  , binrange)
hist_sum_bi_atom , bins  = np.histogram(post_blue+post_red, binrange)
hist_sum_bi_bg, bins  = np.histogram(post_blue_bg + post_red_bg , binrange)

print("mean blue atom "+'%.3f'% np.mean(blue_atom_2)+",   mean blue bg "+'%.3f'% np.mean(blue_bg_2), ",   tx "+'%.3f'% (np.mean(blue_atom_2)/np.mean(blue_bg_2))  ) 
print("mean red atom "+'%.3f'% np.mean(red_atom_2)+",   mean red bg "+'%.3f'% np.mean(red_bg_2), ",   tx "+'%.3f'% (np.mean(red_atom_2)/np.mean(red_bg_2))  ) 
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_atom_2)-1,13))
savedata[:,0] = bins_blue_atom_2[:-1]
savedata[:,1] = hist_blue_atom_1*1.0 #/ hist_blue_atom_1.sum()
savedata[:,2] = hist_blue_bg_1*1.0 #/ hist_blue_bg_1.sum()
savedata[:,3] = hist_red_atom_1*1.0 #/ hist_red_atom_1.sum()
savedata[:,4] = hist_red_bg_1*1.0 #/ hist_red_bg_1.sum()
savedata[:,5] = hist_blue_atom_2*1.0 #/ hist_blue_atom_2.sum()
savedata[:,6] = hist_blue_bg_2*1.0 #/ hist_blue_bg_2.sum()
savedata[:,7] = hist_red_atom_2*1.0 #/ hist_red_atom_2.sum()
savedata[:,8] = hist_red_bg_2*1.0 #/ hist_red_bg_2.sum()
savedata[:,9] = hist_atom_1_sum*1.0 #/ hist_blue_atom_2.sum()
savedata[:,10] = hist_bg_1_sum*1.0 #/ hist_blue_bg_2.sum()
savedata[:,11] = hist_atom_2_sum*1.0 #/ hist_red_atom_2.sum()
savedata[:,12] = hist_bg_2_sum*1.0 #/ hist_red_bg_2.sum()
np.savetxt('histo_no_th.dat', savedata,header='#bin blue-1(at|bg) red-1(at|bg) blue-2(at|bg) red-2(at|bg) sum-1(at|bg) sum-2(at|bg)' , fmt='%.3f')

savedata=np.zeros((len(bins)-1,7))
savedata[:,0] = bins[:-1]
savedata[:,1] = hist_blue_bi_atom*1.0 #/ hist_blue_bi_atom.sum()
savedata[:,2] = hist_blue_bi_bg*1.0 #/ hist_blue_bi_bg.sum()
savedata[:,3] = hist_red_bi_atom*1.0 #/ hist_red_bi_atom.sum()
savedata[:,4] = hist_red_bi_bg*1.0 #/ hist_red_bi_bg.sum()
savedata[:,5] = hist_sum_bi_atom*1.0 #/ hist_sum_bi_atom.sum()
savedata[:,6] = hist_sum_bi_bg*1.0 #/ hist_sum_bi_bg.sum()
np.savetxt('histo_bi.dat', savedata,header='#bin blue-bi(at|bg) red-bi(at|bg) sum-bi(at|bg)' , fmt='%.3f')


# 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_atom_2/sum(hist_blue_atom_2), align='center', width=width_blue,alpha = 0.5)
#plt.bar(center_blue, hist_blue_bg_2/sum(hist_blue_bg_2), 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_bg_2 , 100, (0,200), normed=True,  histtype='step', color='grey',  linewidth=1.5, label='reference')
blue_fig.hist(blue_atom_2 , 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_atom_2/sum(hist_red_atom_2), align='center', width=width_red,alpha = 0.5)
#plt.bar(center_red, hist_red_bg_2/sum(hist_red_bg_2), 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_bg_2 , 100, (0,200), normed=True,  histtype='step', color='grey',linewidth=1.5, label='reference')
red_fig.hist(red_atom_2 , 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()
