# Analyzes data files collected by sel_waves.py to get the setup
# parameters for detune computations.
# Data is assumed to be in GDR mode, which is both good and bad:
# simpler math, but need an externally-provided bandwidth.
# Only needs/uses forward and cavity signals.

# for f in iq_sys*; do echo $f; python detune_coeff.py -f $f -l; done
# for f in iq_sys*; do S=`python detune_coeff.py -f $f`; m=${f%_[01]};
# m=${m#iq_}; echo "python \$BMB7_PATH/bmb7_gateway.py --ip $m -f
# live_prc_regmap.json --nvs $S"; done > set_detune.sh
import numpy as np
from numpy import sqrt, arctan2, exp, mean, std, pi
from matplotlib import pyplot
# import rf_controls


# dVc/dt = a*Vc + b*K
# a = (j*\omega_d - \alpha) --> a_i = -\alpha , a_q = \omega_d
# b =  2*\alpha --> b_i = 2*\alpha , b_q = 0
# \alpha = half bandwidth
# \omega_d = damping freq = \omega_o - sqrt(\omega_o^2  - \alpha^2)
# \omega_o = 2*pi*1.3 GHz

def fwd_coeff(fwd, verbose=False):
    # derived from rotate_fwd() in data-20170705/combo5.py
    mmm1 = np.cov(fwd.real, fwd.imag)
    e_val, e_vec = np.linalg.eig(mmm1)
    # we need e_val sorted from larger to smaller
    ev_list = list(zip(e_val, e_vec))
    ev_list.sort(key=lambda tup: tup[0], reverse=True)
    e_val, e_vec = zip(*ev_list)
    fp0 = arctan2(e_vec[0][0], e_vec[0][1])
    coeff = exp(-1j*fp0)
    fwdx = fwd * coeff
    # eigenvectors have arbitrary sign
    if mean(fwdx).real < 0:
        fwdx = -fwdx
        coeff = -coeff
        fp0 = (fp0 + 2*pi) % (2*pi) - pi
    drv = fwdx.imag/mean(fwdx.real)
    coeff = coeff/mean(fwdx.real)
    if verbose:
        print("Orthogonal fwd rms (%3.3f, %3.3f)" % tuple(sqrt(e_val)))
        print("Forward phase zero %3.3f radians" % fp0)
        ll = min(fwdx.real), max(fwdx.real), min(fwdx.imag), max(fwdx.imag)
        print("Forward range in-phase [%.3f %.3f] reactive [%.3f %.3f]" % ll)
        print("Drive normalized variation %3.3f rms" % std(drv))
    return coeff


# bw in Hz, so a in Hz
def detune_coeff(cav, fwd, bw=15.0, dt=1.0, plot=False, verbose=False, title=None):
    # loopback not used here
    fwd_c = fwd_coeff(fwd, verbose=verbose)
    cav_c = 1/mean(cav)
    beta = bw * fwd_c / cav_c
    if plot:
        fwdx = fwd * fwd_c
        cavx = cav * cav_c
        a = beta * fwd / cav
        t = np.arange(len(cav)) * dt
        f, (ax1, ax2) = pyplot.subplots(1, 2, figsize=(16, 8))
        # f.set_size_inches(12, 6)
        # pyplot.plot(drv.real, drv.imag)
        ax1.plot(fwdx.real, fwdx.imag)
        ax1.plot(cavx.real, cavx.imag)
        ax1.set_xlim(0.98, 1.02)
        ax1.set_ylim(-0.8, 0.8)
        # pyplot.plot(0, 0)
        ax2.plot(t, a.real)
        ax2.plot(t, a.imag)
        ax2.set_xlim(0, max(t))
        ax2.set_ylim(-12.0, 18.0)
        ax2.set_ylabel("Hz")
        if title is not None:
            f.suptitle(title)
        pyplot.show()
    return beta


# input beta in Hz
# fq is frequency quantum, user choice
# dt is digaree time step
# Identical to fpga_regs() in fitter.py
# fir_gain is prescale on dV/dt, see FIR filter comments in cgen_srf.py
def sf_consts(beta, fq, dt, fir_gain=80):
    invT = 1.0/(dt*fir_gain)  # units are /s
    iinvt = invT/(2*pi) / fq
    ibeta = beta / fq
    sf = [ibeta.real, ibeta.imag, iinvt, 32768]
    return [int(round(sf[kx])) for kx in range(4)]


def get_meta(fname):
    cav = {}
    noeq = "".maketrans("=", " ")
    names = {
        'Bandwidth': True,
        'bcoefm_si': True,
        'bcoefp': True,
        'cav_scale': True,
        'fwd_scale': True,
        'rev_scale': True,
        'acq_decim': True,
        'L': True,
        'freq': True,
        'imped': True}
    with open(fname, "r") as fd:
        for line in fd.readlines():
            if line.startswith("#"):
                aa = line.rstrip().translate(noeq).split()
                # print(aa)
                for ix in range(len(aa)-2):
                    name, val = aa[ix+1], aa[ix+2]
                    if name in names:
                        cav[name] = float(val)
    return cav


if __name__ == "__main__":
    from argparse import ArgumentParser

    parser = ArgumentParser(description="Detune coefficient computation")
    parser.add_argument("-a", "--address", dest="ip", default=None, help="BMB7 IP address")
    parser.add_argument("-f", "--datafile", dest="datafile", default=None, help="IQ data input file")
    parser.add_argument("-m", "--regmapfile", dest="regmapfile",
                        default='./live_prc_regmap.json', help="Register map file save path")
    parser.add_argument("-z0", "--zone0", action="store_true", dest="zone0", help="Controller zone 0 (shell_0)")
    parser.add_argument("-z1", "--zone1", action="store_true", dest="zone1", help="Controller zone 1 (shell_1)")
    parser.add_argument("-v", "--verbose", action="store_true", dest="verbose", help="Verbose mode")
    parser.add_argument("-l", "--plot", action="store_true", dest="plot", help="Plot")
    parser.add_argument("-i", "--id", dest="header_id", default=None, help="Header ID for data file")
    parser.add_argument("-o", "--outputfile", dest="outfile", default=None, help="Output file name")

    args = parser.parse_args()

    clk = 1320.0e6 / 14.0
    cav_meta = {}
    wave_samp_per = 255
    dt = wave_samp_per * 33 / clk

    if args.zone0 and args.zone1:
        print("Cannot pick controller zones 0 and 1 at once")
        exit(1)

    if args.datafile is None and args.ip is None:
        print("No data file name or board IP address provided, aborting...")
        exit(1)

    if not args.zone0 and not args.zone1 and args.datafile:
        z = 1 if args.datafile[-2:] == "_1" else 0
        if args.verbose:
            print("No controller zone selected, trying to deduce that from datafile...")
            print("Data file is %s" % (args.datafile))
            print("Deduced controller zone is %d" % z)

    elif args.zone0:
        z = 0
    else:
        z = 1

    # Read from BMB7 if IP address is provided and from file otherwise
    if args.ip is not None:
        print("Ip provided: %s" % (args.ip))
        title = args.ip

        from prc import c_prc
        from sel_waves import iq_buf_collect, interpret_slow_data

        prc = c_prc(args.ip)

        # Select zone (controller) 0 or 1
        cav_mask = 1 << z
        print("cav mask %d" % cav_mask)
        # Check if buffer is ready
        b_status = prc.query_resp_list(["llrf_circle_ready"])[0]
        print("starting status %d" % b_status)
        # Number of points in the acquisition
        npt = 8192
        # Channel count is fixed to 8
        chcount = 8

        # If not ready, request a new buffer to be captured
        if b_status & cav_mask == cav_mask:
            s = prc.query_resp_list(["llrf_circle_ready", ("circle_buf_flip", cav_mask), "llrf_circle_ready"])

        (nblock, datetimestr, slow_data) = iq_buf_collect(prc, chcount, npt, cav_mask=cav_mask, verbose=True)

        isd = interpret_slow_data(slow_data)
        header = datetimestr + " %d %d" % (isd[0], isd[5])  # circle_count and time_stamp

        if args.outfile is not None:
            print("Generating data file %s" % args.outfile)
            if args.header_id:
                header += "\n" + args.header_id
            np.savetxt(args.outfile, nblock, fmt="%d", header=header)
            data = nblock.transpose()

    else:
        data = np.loadtxt(args.datafile).transpose()
        fwd = data[2] + 1j*data[3]
        cav = data[0] + 1j*data[1]
        cav = cav*1e6  # work in SI volts
        title = args.datafile
        cav_meta = get_meta(args.datafile)

    if data.shape[1] < 256:
        print('Bad data shape: {0}'.format(data.shape))
        exit(1)
    # Here hbw is the half-bandwidth
    # wish for pythonic shortcut that doesn't need to repeat the dictionary index
    hbw = cav_meta['Bandwidth'] if 'Bandwidth' in cav_meta else 16.63
    f0 = cav_meta['freq'] if 'freq' in cav_meta else 1300e6
    RoverQ = cav_meta['imped'] if 'imped' in cav_meta else 1012
    # print("meta", hbw, f0, RoverQ)
    beta = detune_coeff(cav, fwd, bw=hbw, dt=dt, plot=args.plot, verbose=args.verbose, title=title)
    whb = 2*np.pi*hbw  # /s
    w0 = 2*np.pi*f0  # /s
    expectb = sqrt(2*w0*whb*RoverQ)
    si_beta = 2*np.pi*np.abs(beta)
    beta_deg = np.angle(beta, deg=True)
    if args.verbose:
        print("SI beta %3.3f%+3.3fj Hz" % (beta.real, beta.imag))
        print("Magnitude: %.4g sqrt(Ohm)/s, Phase: %3.3f deg" % (si_beta, beta_deg))
        print("Expected b %.4g sqrt(Ohm)/s" % expectb)
    pp = title, hbw, expectb, si_beta, 1e6*cav_meta['bcoefm_si'], beta_deg, cav_meta['bcoefp']
    print("summary %s %6.2f %#12.6g %#12.6g %#12.6g %7.2f %7.2f" % pp)

    fq = 0.002  # Hz frequency quantum
    digaree_Tstep = 32*33*14/1320e6  # baked into piezo_control.v
    sf = sf_consts(beta, fq, digaree_Tstep)
    ss = [('shell_{0}_dsp_piezo_sf_consts[{1}]'.format(z, ix), sf[ix]) for ix in range(4)]
    ss += [('cct1_cavity{0}_detune_en'.format(z), 1)]
