import numpy as np
from numpy.polynomial import polynomial as poly
from scipy import signal
from numpy import random
from matplotlib import pyplot


# If I want 100 kHz span (+/- 50 kHz) resonance search
# I need 150 kZ/s suggests wave_samp_per = 9.5, try 8 yields 178 kZ/s.
# But run the simulations with 2 x os shorter timestep, and
# postprocess to get a prediction for the acquired waveform.
# os = over-sampling simulation coefficient
def stim(maxf=50e3, wsp=8, os=4, a_npt=2048, plot=False):
    dt = wsp*2*33*14/1320e6/2/os
    npt = a_npt*2*os
    t_span = dt*npt*0.75
    t = dt * np.arange(npt)
    if True:  # intended chirp
        x = 0.5*(t-t_span/2)**2   # max slope t_span/2
        phase = 2*np.pi*maxf*x*2.0/t_span
        #
        t_rise = t_span*0.125
        t_fall = t_rise
        envelope = np.minimum(1+0*t, t/t_rise)
        envelope = np.minimum(envelope, (t_span-t)/t_fall)
        envelope = np.maximum(envelope, 0)
        if plot:
            pyplot.plot(t, envelope)
            pyplot.show()
            exit(0)
        #
        z_drv = envelope * np.exp(1j*phase)
    else:  # stupid test square wave for sanity-check
        z_drv = 0*t
        z_drv[npt/2:] = 1
    return dt, t, z_drv


# Simulate cavity response given bandwidth and center frequency
def response(z_drv, dt, bw=16, cf=0):
    s_pole = 2*np.pi*(-bw+1j*cf)  # units are 1/s
    z_pole = np.exp(s_pole*dt)  # unitless
    cz = np.exp(2*np.pi*1j*cf*dt)  # center frequency in z plane
    # Configure filter for unity gain at z = cz
    #  b / (1 - z_pole / cz) = 1
    filt_a = np.array([1, -z_pole])
    filt_b = np.array([0.5, 0.5]) * (1 - z_pole/cz)
    z_resp = signal.lfilter(filt_b, filt_a, z_drv)
    return z_resp


# Create waveforms as the acquisition system will record them
def acq_filter(y, os=4):
    # Filter and decimate by os
    order1 = np.ones(os)/os
    filt_post_cic = poly.polymul(order1, order1)
    y2 = signal.lfilter(filt_post_cic, [1], y)[::os]
    # Filter and decimate by 2, matches bedrock's half_filt.v
    filt_post_hb = np.array([2, 0, -9, 0, 39, 64, 39, 0, -9, 0, 2])/128.0
    return signal.lfilter(filt_post_hb, [1], y2)[::2]


# Analyze waveforms according to first-order state-space equation
#  dy/dt = A*y + B*z
def analyze_waves(x, y, t, dt, h_order=4, maxf=0.29):
    order = 2 * h_order + 1
    diffr = signal.remez(order, [0, maxf], [1], [1], type="differentiator")
    delay = np.zeros(order)
    delay[h_order] = 1
    #
    x1 = signal.lfilter(delay, [1], x)
    y1 = signal.lfilter(delay, [1], y)
    dy_dt = 2 * np.pi * signal.lfilter(diffr, [1], y) / dt
    basis = np.vstack([y1, x1])
    fitc, resid, rank, sing = np.linalg.lstsq(basis.T, dy_dt, rcond=-1)
    sigma2 = resid[0]/(len(dy_dt)-2)  # 2 fitting degrees of freedom
    if False:  # re-do the lstsq() work "by hand"
        X = basis.T
        Xa = X.T.conj()  # adjoint, or Hermitian conjugate
        normal = Xa.dot(X)
        cofactor = np.linalg.inv(normal)
        fitc_hand = cofactor.dot(Xa.dot(dy_dt))
        eps = dy_dt - X.dot(fitc_hand)
        sigma2_hand = eps.T.conj().dot(eps) / (len(dy_dt)-2)
        print(sigma2, sigma2_hand)
        # print("normal", normal)
        # print("cofactor", cofactor)
        # print("fitc hand", fitc_hand)
        # print("fitc ltssq", fitc)
        print(fitc_hand)
        print(sigma2 * cofactor)
        # gives too-large an estimate for variance, by a factor of ~100;
        # is that because my differentiation step yields dy_dt noise that's
        # correlated?
    # print(fitc)
    fit_wave = basis.T.dot(fitc)
    return fitc, t, dy_dt, fit_wave, np.sqrt(sigma2)


def check_one(dt, t, z_drv, bw=16, cf=0, os=4, identity=False, plot=False):
    z_resp = response(z_drv, dt, bw=bw, cf=cf)
    npt = len(z_resp)
    z_resp += random.randn(npt) * 0.001  # -60 dBFS is huge,
    # reality will be closer to -80 dBFS
    # print("max resp %.4f" % max(abs(z_resp)))
    if identity:
        # Identity filter, no decimation
        d3 = z_drv
        z3 = z_resp
        t3 = t
        dt3 = dt
    else:
        d3 = acq_filter(z_drv, os=os)
        z3 = acq_filter(z_resp, os=os)
        t3 = t[::os*2]
        dt3 = dt*os*2
    if False:
        pyplot.plot(t3, d3.real)
        pyplot.plot(t3, d3.imag)
        pyplot.plot(t3, z3.real)
        pyplot.plot(t3, z3.imag)
        pyplot.xlabel("Time (s)")
        pyplot.ylabel("Response")
        pyplot.show()
    fitc, tf, dy_dt, fit_wave, rms = analyze_waves(d3, z3, t3, dt3)
    if plot:
        pyplot.plot(tf, dy_dt.real, label="meas")
        pyplot.plot(tf, fit_wave.real, label="fit sigma=%.1f" % rms)
        pyplot.xlabel("Time (s)")
        pyplot.ylabel("dy/dt")
        pyplot.legend(frameon=False)
        pyplot.show()
    return fitc


if __name__ == '__main__':
    os = 8
    dt, t, z_drv = stim(os=os)
    bw = 16  # Hz cavity bandwidth
    cf_list = [-2000]  # Hz center frequency
    cf_list = np.arange(-48000, 50000, 2000)
    cf_x = []
    many = len(cf_list) > 1
    for cf in cf_list:
        fitc = check_one(dt, t, z_drv, bw=bw, cf=cf, os=os, plot=not many)
        f_pole1 = fitc[0]/(2.0*np.pi)
        error = f_pole1.imag - cf
        # print("%d: pole at %.1f%+.1fj Hz" % (cf, f_pole1.real, f_pole1.imag))
        print("%6d %5.1f %8.1f %6.1f" %
              (cf, f_pole1.real, f_pole1.imag, error))
        cf_x += [f_pole1.imag]
    if many:
        cf_x = np.array(cf_x)
        pyplot.plot(cf_list, cf_x)
        pyplot.plot(cf_list, cf_list, "--")
        pyplot.xlabel("Actual center f (Hz)")
        pyplot.ylabel("Detected center f (Hz)")
        pyplot.show()
    if False:
        px = cf_list**2
        py = (cf_x/cf_list - 1)/px
        pyplot.plot(px, py)
        pyplot.xlabel("Actual center f^2 (Hz^2)")
        pyplot.ylabel("Normalized deviation (Hz^{-2})")
        pyplot.show()
