#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 19 08:34:26 2017

@author: xliq
"""
'''
The MetroPy Raw-SNR File:
    Generates the Signal-to-Noise ratio plots for the raw Metrology data.
'''
#### Initialization
from sys import argv
FITS_file = argv[1]
rmsLength = int(argv[2])
resolution = int(argv[3])
img = argv[4]

#### Importing
# import necessary things from the init file
from MetroPy_Init import plotstyle, d_color
from MetroPy_Init import time, volts
from MetroPy_Helper import chunking, plotnumber, plotlabel

# import necessary packages
import os
import matplotlib as mpl
import matplotlib.pyplot as plt
# plotstyle for Metrology data
plt.style.use(plotstyle)
# numpy ofcourse
import numpy as np
#import progressbar as pb

# same format as raw2d, just signal-to-noise plots
size = [40, 40]
# plot limits formatting
offset = 5
limits = [1, 100]
time_int = [time[0], time[len(time) - 1]]
# partition the time array the same way as the volts array later
time_even, time_odd = chunking(time, rmsLength)

# activate progress bar
#bar = pb.ProgressBar()
# start the loop
counter = 0    
for n in np.arange(0, 80, 2):
    
    # formatting pre-requisites
    fig = plt.gcf()

    # subplotting
    ax = fig.add_subplot(8, 5, plotnumber('raw2d', n, counter))      
    
    # labeling
    plt.xlabel('Time [s]')
    plt.ylabel('Signal-To-Noise')
    plt.title('%s' %plotlabel('raw2d', n))        
    
    # outsourced chunking
    volts_even, volts_odd = chunking(volts[:,n], rmsLength)
    volts_even2, volts_odd2 = chunking(volts[:,n+1], rmsLength)
    
    signal_e = np.sqrt(volts_even**2 + volts_even2**2)
    mean_e = np.mean(signal_e, axis=1)
    stdev_e = np.std(signal_e, axis=1)
    
    signal_o = np.sqrt(volts_odd**2 + volts_odd2**2)
    mean_o = np.mean(signal_o)
    stdev_o = np.std(signal_o)
    
    # plot gaussian SNR
    plt.plot((time_int[0], time_int[1]),
             (1.8, 1.8), 
             color=d_color[3])
    
    # plot data SNR == mean / stdev
    # even part
    plt.semilogy(np.mean(time_even, axis=1),
                 mean_e / stdev_e,
                 lw=1,
                 color=d_color[0])
    # odd part
    plt.semilogy(np.mean(time_odd),
                 mean_o / stdev_o,
                 lw=1,
                 color=d_color[0])        
    
    # limits
    plt.xlim([time_int[0] - offset,
              time_int[1] + offset])
    plt.ylim(limits)
    
    # y axis ticks
    ax.yaxis.set_major_formatter(mpl.ticker.ScalarFormatter())
    ax.yaxis.set_major_formatter(mpl.ticker.FormatStrFormatter("%d"))
            
    fig.set_size_inches(size, forward=True)
    
    counter += 1

plt.savefig('%s.SNRraw.%s' %(FITS_file, img), bbox_inches='tight')
  
print('Raw SNR Plots: Done!')
