# Stand-alone mode reads 4-column output of get_raw_adcs making use
# of ssa_stim hardware.  Production use is called from ssa_cal.py.
#
# zone 0:
# python new_mem_gateway.py -a $IP --nvs ssa_stim_g_period,396 \
#  ssa_stim_ampstep,3000 ssa_stim_pertstep,1500 ssa_stim_en,1 dac_0_sel,2 dac_1_sel,0
# python get_raw_adcs.py -a $IP -m 0x9c -c 10
#
# zone 1:
# python new_mem_gateway.py -a $IP --nvs ssa_stim_g_period,396 \
#  ssa_stim_ampstep,3000 ssa_stim_pertstep,1500 ssa_stim_en,1 dac_0_sel,0 dac_1_sel,2
# python get_raw_adcs.py -a $IP -m 0xe1 -c 10

import numpy
from numpy import sqrt
import matplotlib
from matplotlib import pyplot

# See http://phyletica.org/matplotlib-fonts/
matplotlib.rcParams['pdf.fonttype'] = 42
matplotlib.rcParams['ps.fonttype'] = 42


# cav is defined in range 1-8
def stim_config(cav):
    c = cav-1
    # based on "column assignment" line in the raw_z_* files and
    # hardware mapping  2=loop1  3=fwd1  4=rev1  5=loop2  6=fwd2  7=rev2
    fix = 3 if (c % 2 == 1) else 0  # reverse
    fix = 2 if (c % 2 == 1) else 2  # loopback
    fix = 1 if (c % 2 == 1) else 1  # forward
    initial = 1  # no more workaround
    return fix, initial


def block_reduce(v):
    pstep = 2*numpy.pi*7.0/33.0
    npt = v.shape[0]
    theta = numpy.arange(npt)*pstep
    basis = numpy.vstack([numpy.cos(theta), numpy.sin(theta), theta*0+1])
    fitc, resid, rank, sing = numpy.linalg.lstsq(basis.T, v, rcond=-1)
    amp = fitc[0] + 1j*fitc[1]
    dc = fitc[2]
    err = sqrt(resid/(len(v)-3))
    return amp, dc, err


def stim_reduce(v):
    # npt = len(v)
    npt2 = int(len(v)/33)
    v_reshaped = numpy.reshape(v[0:npt2*33], [npt2, 33]).T
    qamp, qdc, qerr = block_reduce(v_reshaped)
    qerr[1::12] = 0
    if False:
        pyplot.plot(numpy.abs(qamp))
        pyplot.plot(qerr)
        pyplot.show()
    adc_fs = 32768.0  # counts
    v3 = qamp / adc_fs  # convert to fraction of ADC full-scale
    # hard-coded numbers based on ssa_stim_g_period=395 (33*12-1) and
    # 16384 data points from banyan_spurs
    v4 = numpy.reshape(v3[2:2+41*12], [41, 12])
    v4 = numpy.array([numpy.mean(v4[kx][1:13]) for kx in range(41)])
    return v4, qamp, qdc, qerr


def stim_pattern(npt, ssa_stim_ampstep=0, ssa_stim_pertstep=0, initial=1):
    # resynthesize test pattern; parallels ssa_stim.v
    # configuration needs to match acquisition setup
    nx = numpy.arange(npt)
    tp = ssa_stim_ampstep*(initial+numpy.floor(nx/6))
    tp += ssa_stim_pertstep*(nx % 6 == 2)
    tp = tp + ssa_stim_pertstep*1j*(nx % 6 == 4)
    return tp


def print_table(logf, v, initial=0):
    tp = stim_pattern(len(v), initial=initial) / 32768.0
    for kx in range(len(v)):
        pv = tp[kx].real, tp[kx].imag, v[kx].real, v[kx].imag
        logf.write("%7.4f %7.4f  %7.4f %7.4f\n" % pv)


def plot_excite_only():
    dt = 386 * 14 / 1320.0
    zz = numpy.array([0, 0])
    tp = numpy.concatenate((zz, stim_pattern(42), zz))
    npt = len(tp)
    t = dt * numpy.arange(0, len(tp))
    t2 = numpy.reshape(numpy.array([t-dt, t]).T, [2*npt, 1])
    e2 = numpy.reshape(numpy.array([tp, tp]).T, [2*npt, 1])
    t2[0] = -15
    t2[2*npt-1] = 190
    pyplot.plot(t2, abs(e2)/32768.0)
    pyplot.title('Excitation waveform amplitude')
    pyplot.xlabel('t ($\\mu$s)')
    pyplot.ylabel('drive amplitude (fraction of full-scale)')
    pyplot.ylim((-0.005, 1.05))
    pyplot.xlim((min(t2), max(t2)))


def stim_plot(v, ang=0.0, title=None, title_shift=0.0):
    vr, qamp, qdc, qerr = stim_reduce(v)
    vr_mid = vr[13]
    vr = vr*numpy.exp(-1j*numpy.angle(vr_mid))
    vp = vr*numpy.exp(-1j*ang)
    vp_end = vp[-3]
    pyplot.plot(vp.real, vp.imag, '-o')
    vp_end += title_shift
    pyplot.text(vp_end.real, vp_end.imag, title)
    return vr  # doesn't depend on ang


def stim_reorder(tp, vr):
    nik = list(numpy.nonzero((tp.imag == 0) * (tp.real > 0))[0])
    combo = [(tp[i]/32760.0, vr[i]) for i in nik]
    combo = sorted(combo, key=lambda t: t[0])
    # print combo
    tp = numpy.array([c[0] for c in combo])
    vr = numpy.array([c[1] for c in combo])
    return tp, vr


def analyze_ssa_cal(
    data=None,
    initial=1,
    ssa_stim_ampstep=0,
    ssa_stim_pertstep=0,
    ssa_stim_g_period=396,
    minx=0.050,
    pedestal=0.040,
    description="Unknown",
    fwd_scale=None,  # sqrt(W)
    plot_filename=None,
    plot=False
):
    if len(data) != 16384:
        return 0, False, "Invalid data length %d" % len(data)
    if ssa_stim_g_period != 396:
        return 0, False, "Invalid ssa_stim_g_period"
    vr, v10z, v10d, v10e = stim_reduce(data)
    tp = stim_pattern(
        len(vr),
        ssa_stim_ampstep=ssa_stim_ampstep,
        ssa_stim_pertstep=ssa_stim_pertstep, initial=initial)
    tp, vr = stim_reorder(tp, vr)
    x = numpy.abs(vr)
    maxp = max(x)**2
    y1 = abs(tp)
    # print(repr(x))
    # print(repr(y1))
    ssa_slope = numpy.median(y1/x)
    too_small = sum(y1 < ssa_slope*0.9*x)
    too_big = sum(y1 > ssa_slope*1.1*x + pedestal*0.9)
    # Done except for the plotting
    gain = vr/tp
    y2 = numpy.angle(gain)
    low_slope = (ssa_slope * minx + pedestal) / minx
    fit = x*ssa_slope
    target = x
    x_lo = ssa_slope * target * 0.85
    x_hi = (ssa_slope * target + pedestal) * 1.15
    x_hi2 = low_slope * target * 1.15
    # x_hi = min(x_hi, x_hi2)
    x_hi = [min(a, b) for a, b in zip(x_hi, x_hi2)]
    if plot or plot_filename:
        f, (ax1, ax2) = pyplot.subplots(2, 1, sharex='col', figsize=(7, 6))
        f.subplots_adjust(hspace=0.0)
        ssm = "Measured"
        if fwd_scale:
            maxp_kw = (max(x)*fwd_scale)**2*0.001
            ssm = "Measured, max %.2f kW" % maxp_kw
        ax1.plot(x, y1, '-o', label=ssm)
        ax1.plot(x, fit, '-', label="ssa_slope = %.3f" % ssa_slope)
        ax1.plot(x, x_hi, '-', label="x_hi")
        ax1.plot(x, x_lo, '-', label="x_lo")
        ax1.legend(frameon=False)
        ax2.plot(x, y2, '-o', label=description)
        ax2.set_xlabel('FWD measured (ADC normalized)')
        # ax1.set_ylabel('Large Signal Gain (dB)')
        ax1.set_ylabel('DAC Drive level (normalized)')
        ax2.set_ylabel('Large Signal Phase (rad)')
        ax1.set_xlim((0, max(x)))
        ax1.set_ylim((0, 1.0))
        if fwd_scale:
            # https://stackoverflow.com/questions/10514315/how-to-add-a-second-x-axis-in-matplotlib
            ax3 = ax1.twiny()
            ax3_powers = [100, 200, 300, 500, 1000, 1500, 2000, 3000]
            ax3_powers = [z for z in ax3_powers if sqrt(z)/fwd_scale < max(x)]
            ax3_powers = numpy.array(ax3_powers)
            ax3.set_xlim(0, max(x))
            ax3_powers
            ax3_adc = sqrt(ax3_powers)/fwd_scale
            ax3.set_xticks(ax3_adc)
            ax3.set_xticklabels(["%.1f" % (z*0.001) for z in ax3_powers])
            ax3.set_xlabel("Forward power (kW)")
            ax3.set_title(description, y=1.20)
        else:
            ax1.set_title(description)
        if plot_filename:
            pyplot.savefig(plot_filename, bbox_inches="tight")
        if plot:
            pyplot.show()
    if too_big + too_small == 0:
        valid = True
        chatter = "Success"
    else:
        valid = False
        chatter = "Rejected %d hi %d lo points" % (too_big, too_small)
    return ssa_slope, valid, chatter, maxp


def ssa_tester(fname):
    cav = 8
    fix, initial = stim_config(cav)
    d = numpy.loadtxt(fname).transpose()
    v = d[fix]
    ssa_slope, valid, chatter, maxp = analyze_ssa_cal(
        data=v,
        initial=initial,
        ssa_stim_ampstep=3470,
        ssa_stim_pertstep=1735,
        fwd_scale=96.244,  # sqrt(W)
        plot_filename="foo.png",
    )
    print("ssa_slope %.3f %s %.3f: %s" % (ssa_slope, valid, maxp, chatter))


if __name__ == "__main__":
    from sys import argv
    fname = argv[1]
    ssa_tester(fname)
