#!/usr/bin/env python
usage="""
 Plot AGC rec16 or rec35 diagnostics from T04 file

Example:
 ./plot_agc.py --rec16 file.T04  # if "Log AGC Data" was checked
 ./plot_agc.py file.T04  # if "Log AGC Data" was not checked - slower rate...
"""

import argparse
parser = argparse.ArgumentParser(description=usage,
                                 formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('filename', help='T04 file')
parser.add_argument('--rec16', help='Use "Log AGC Data" diagnostics.', action="store_true")
parser.add_argument('--no_ui', help="Only store files. Don't pop up window", action="store_true")
parser.add_argument('-s','--start', help="Start GPS secs in week [0]", default=0)
parser.add_argument('-e','--end', help="End GPS secs in week [604800]", default=604800)
args = parser.parse_args()

if args.no_ui:
    import matplotlib
    matplotlib.use("agg")

from mutils import *

#filename='/net/daffy/mnt/data_drive/T01.BD935.4/5625C00359202211211200.T04'

# These currently match Stinger defines
RF = dotdict(['L1','L2','L5','G1','G2','E5B','E5','E6','B1','B3','S1'])
BANK = dotdict(['EXT','INT'])
HIST = dotdict(['IS','IM','IMpS','IMnS','QS','QM','QMpS','QMnS'])
PLOT_BANDS = [('L1','L1'),('L2','L2'),('L5','E5'),('B1','L1')]

if args.rec16:
    d=kv_info2arr(args.filename,key="AGC",convert_float=True)
    k=dotdict(['MSECS','rf_band','hist_func','antenna','bank',
               'dac_read','dac_drive','noise'])
    d=VdCls(d,k,[])

    scale=100.0 / 25.0e6 / 200.0e-3
    close('all')

    d0=d[(d.MSECS>=args.start*1e3)&(d.MSECS<=args.end*1e3)]
    for antenna in unique(d0.antenna):
        d0a = d0[d0.antenna==antenna]
        if len(d0a)==0:
            continue
        for band,ext_band in PLOT_BANDS:
            di = d0a[ (d0a.rf_band==RF[band]) & (d0a.hist_func==HIST.QM) & (d0a.bank==BANK.INT) ]
            de = d0a[ (d0a.rf_band==RF[ext_band]) & (d0a.hist_func==HIST.QM) & (d0a.bank==BANK.EXT) ]
            if len(di)==0 and len(de)==0:
                continue
            fig,ax=subplots(3,1,sharex=True,figsize=(8,6))
            ax[0].set_title('%s ant %d AGC diags\n%s'%(band,antenna,args.filename))
            ax[0].plot( de.MSECS*1e-3, de.dac_read*scale ) ;
            ax[0].set_ylabel('external QM %')
            ax[1].plot( di.MSECS*1e-3, di.noise ) ;
            ax[1].set_ylabel('internal noise')
            ax[2].plot( di.MSECS*1e-3, di.dac_read*scale ) ;
            ax[2].set_ylabel('internal QM %')
            ax[2].set_xlabel('GPS secs')
            for a in ax: a.grid()
            tight_layout()
            out_filename = '%s_a%d.png'%(band,antenna)
            print("Saving %s"%out_filename)
            savefig(out_filename)
else:
    d=vd2cls(args.filename,'-d35:267')
    d0=d[(d.MSECS>=args.start*1e3)&(d.MSECS<=args.end*1e3)]
    for antenna in unique(d0.antenna):
        d0a = d0[d0.antenna==antenna]
        if len(d0a)==0:
            continue
        for band,ext_band in PLOT_BANDS:
            di = d0a[ (d0a.rf_band==RF[band]) & (d0a.bank==BANK.INT) ]
            de = d0a[ (d0a.rf_band==RF[ext_band]) & (d0a.bank==BANK.EXT) ]
            if len(di)==0 and len(de)==0:
                continue
            fig,ax=subplots(3,1,sharex=True,figsize=(8,6))
            ax[0].set_title('%s ant %d rec35 AGC\n%s'%(band,antenna,args.filename))
            ax[0].plot( de.MSECS*1e-3, de.avg_Q ) ;
            ax[0].plot( de.MSECS*1e-3, de.max_Q, label='max' ) ;
            ax[0].plot( de.MSECS*1e-3, de.min_Q, label='min' ) ;
            ax[0].set_ylabel('external QM %')
            ax[1].plot( di.MSECS*1e-3, di.avg_noise ) ;
            ax[1].plot( di.MSECS*1e-3, di.max_noise,label='max' ) ;
            ax[1].plot( di.MSECS*1e-3, di.min_noise,label='min' ) ;
            ax[1].set_ylabel('internal noise')
            ax[2].plot( di.MSECS*1e-3, di.avg_Q ) ;
            ax[2].plot( di.MSECS*1e-3, di.max_Q, label='max' ) ;
            ax[2].plot( di.MSECS*1e-3, di.min_Q, label='min' ) ;
            ax[2].set_ylabel('internal QM %')
            ax[2].set_xlabel('GPS secs')
            for a in ax:
                a.grid()
                a.legend()
            tight_layout()
            out_filename = '%s_a%d_r35.png'%(band,antenna)
            print("Saving %s"%out_filename)
            savefig(out_filename)


if not args.no_ui:
    show()
