# 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


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 = 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 (%.1f, %.1f)" % tuple(sqrt(e_val)))
        print("Forward phase zero %.3f radians" % fp0)
        print("Drive normalized variation %.3f rms" % std(drv))
    return coeff


def detune_coeff(data, bw=15.0, dt=1.0, plot=False, verbose=False):
    # loopback not used here
    fwd = data[2] + 1j*data[3]
    # rev not used here
    cav = data[6] + 1j*data[7]
    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)
        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
def sf_consts(beta, fq, dt):
    fir_gain = 80  # prescale on dV/dt, see FIR filter comments in cgen_srf.py
    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)]


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("-p", "--port", dest="port", type=int, default=50006, help="Spartan UDP port")
    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="Verbode 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
    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))

        from prc import c_prc
        from sel_waves import iq_buf_collect, interpret_slow_data

        prc = c_prc(args.ip, args.port, regmappath=args.regmapfile)

        # Select zone (controller) 0 or 1
        cav_mask = 1 << z
        print("cav mask %d" % cav_mask)
        # Check if buufer 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()

    if data.shape[0] != 8 or data.shape[1] < 256:
        print('Bad data shape: {0}'.format(data.shape))
        exit(1)
    beta = detune_coeff(data, bw=15.0, dt=dt, plot=args.plot, verbose=args.verbose)
    if args.verbose:
        print("SI beta %.3f%+.3fj Hz" % (beta.real, beta.imag))

    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)]
    # Write to BMB7 if IP address is provided and from file otherwise
    if args.ip is not None:
        print("Writing to hardware: " + repr(sf))
        prc.query_resp_list(ss)
    else:
        # Remove path information to decode information from file name itself
        import ntpath
        datafilename = ntpath.basename(args.datafile)
        fpga = args.datafile[3:-2]
        sl = ["python $BMB7_PATH/bmb7_gateway.py --ip", fpga, "-f ", args.regmapfile, " --nvs"]
        sl += ["%s,%d" % p for p in ss]  # p is a tuple of two
        print(" ".join(sl))
