import numpy

datapath = '../../data/instruments/'
imgpath  = '../../img/'

# load histogram data
range_histogram = numpy.loadtxt(datapath + 'o3a_range_histogram.txt')
bins = range_histogram[:,0]
range_virgo_hist = range_histogram[:,1]
range_lho_hist = range_histogram[:,2]
range_llo_hist = range_histogram[:,3]

# compute medians
virgo_median = bins[numpy.where(numpy.cumsum(range_virgo_hist)/numpy.sum(range_virgo_hist) >= 0.5)[0][0]]
lho_median   = bins[numpy.where(numpy.cumsum(range_lho_hist)/numpy.sum(range_lho_hist) >= 0.5)[0][0]]
llo_median   = bins[numpy.where(numpy.cumsum(range_llo_hist)/numpy.sum(range_llo_hist) >= 0.5)[0][0]]

import matplotlib
matplotlib.use('agg')
matplotlib.rcParams['text.usetex'] = True
matplotlib.rcParams['font.size'] = 9
matplotlib.rcParams['savefig.dpi'] = 300
matplotlib.rcParams['text.latex.preamble'] = r'\usepackage{amsmath}'
matplotlib.rcParams['legend.fontsize'] = 9
from matplotlib import pyplot
pyplot.rc('axes', axisbelow=True)

colors = {'L1': '#4ba6ff', 'H1': '#ee0000', 'V1': '#9b59b6'}



fig = pyplot.figure(figsize=(3.375,3))
l1, = pyplot.fill(bins, range_virgo_hist / sum(range_virgo_hist) / (bins[1]-bins[0]), alpha=0.7, label=r'$\mathrm{Virgo}$', color=colors['V1'])
l2, = pyplot.fill(bins, range_lho_hist   / sum(range_lho_hist)   / (bins[1]-bins[0]), alpha=0.7, label=r'$\mathrm{LIGO}\,\mathrm{Hanford}$', color=colors['H1'])
l3, = pyplot.fill(bins, range_llo_hist   / sum(range_llo_hist)   / (bins[1]-bins[0]), alpha=0.7, label=r'$\mathrm{LIGO}\,\mathrm{Livingston}$', color=colors['L1'])
pyplot.vlines(lho_median, 0, 0.24, color=colors['H1'], linewidth=1, linestyle='--')
pyplot.vlines(llo_median, 0, 0.24, color=colors['L1'], linewidth=1, linestyle='--')
pyplot.vlines(virgo_median, 0, 0.24, color=colors['V1'], linewidth=1, linestyle='--')

pyplot.text(lho_median-15,   0.252, r'$%d\, \mathrm{Mpc}$' % lho_median, color=colors['H1'])
pyplot.text(llo_median-10,   0.252, r'$%d\, \mathrm{Mpc}$' % llo_median, color=colors['L1'])
pyplot.text(virgo_median-10, 0.252, r'$%d\, \mathrm{Mpc}$' % virgo_median, color=colors['V1'])

pyplot.legend(handles=(l2,l3,l1), loc='upper left')
pyplot.ylim([0, 0.4])
#xlim([80, 150])
pyplot.xlabel(r'$\mathrm{BNS}\,\mathrm{range}\,\mathrm{[Mpc]}$')
pyplot.ylabel(r'$\mathrm{Normalized}\,\mathrm{counts}$')
pyplot.grid()
fig.tight_layout()
pyplot.savefig(imgpath + "range_histograms.pdf")
