import matplotlib
# Allow running headless from the command line
matplotlib.use("agg")

from pylab import *
import numpy as np
import pandas as pd
import json

#files = [ 'ARGON1Hist.res',
#          'ARGON2Hist.res',
#          'KRYP1Hist.res']
# Load the JSON file 
with open('/net/higgs/mnt/data_drive/StingerLabLatency/receivers.json', 'r') as f:
  receivers = json.load(f)

NumRX = len(receivers)

# Columns
#
# Year
# Month
# Day
# GPS Week
# Week seconds
# Total Epochs
# Mean
# Percentiles

cols = ['Year','Month','Day','Week','Secs','Num','Mean', '50', '68', '95', '99', '100']

frames = []
# Read in the data
fig = figure()
for i in range(NumRX):
  df = pd.read_csv(receivers[i]['short'] + 'Hist.res',skiprows=1,header=None,delim_whitespace=True,names=cols)
  df.insert(len(cols), 'Time', df['Week'] + df['Secs']/(86400*7), True)
  frames.append(df)

# Plot a few things
figures = ['Mean', '50', '68', '95', '99', '100']
for plt in range(len(figures)):
  fig = figure()
  for i in range(NumRX):
    plot(frames[i]['Time'], frames[i][figures[plt]],label=receivers[i]['short'])

  # Prevent matplotlib from using exponential in the axis label
  ax = gca()
  ax.get_xaxis().get_major_formatter().set_useOffset(False)

  xlabel('Time [GPS Week]')
  legend()
  grid()
  title('Latency')
  if(plt == 0):
    ylabel('Mean [ms]')
    tight_layout()
    savefig('Mean.png',dpi=150)
  else:
    ylabel(figures[plt] + ' Percentile [ms]')
    tight_layout()
    savefig(figures[plt] + '-Percentile.png',dpi=150)

  close()

