def modelPulses(**kwargs):
    ampl = makeNP(kwargs.get('amplitude', 1))
    decay = makeNP(kwargs.get('decay', 0))
    t = makeNP(kwargs.get('t', 1))
    Fs = kwargs.get('Fs', 1)
    t = genTime(maxTime=t, Fs=Fs) if t.size == 1 else t
    timeSituations = np.arange(start=kwargs.get('start', t[0]),
                               stop=kwargs.get('stop', t[-1]),
                               step=kwargs.get('step', (t[-1] - t[0]) / 20))
    timeSamples = closeInVect(t, timeSituations)[0]
    envel = expPulses(t, timeSamples, decay, ampl, kwargs)[0] - np.max(ampl)
    ams = AMsign(t, kwargs.get('carrier', 0.1 * Fs), envel, depth=1)
    signalTupl = pa.awgn(ams[0], SNRdB=makeNP(kwargs.get('SNR', np.inf)))
    saveAudio(kwargs, signalTupl[0])
    return (signalTupl[0], ) + (timeSamples, t)
def modelModulated(**kwargs):
    t = makeNP(kwargs.get('t', 1))
    Fs = kwargs.get('Fs', 1)
    t = genTime(maxTime=t, Fs=Fs) if t.size == 1 else t
    (FMcomp, freq) = frequencyModulated(kwargs.get('FMfreq', 0),
                                        t,
                                        f0=kwargs.get('carrier', 0.1 * Fs),
                                        depth=kwargs.get('FMdepth', 0),
                                        phi0=kwargs.get('phi0', 0),
                                        linear=kwargs.get('linear', False))
    ams = AMsign(t,
                 FMcomp,
                 kwargs.get('AMfreq', 0),
                 depth=kwargs.get('AMdepth', 0))
    signalTupl = pa.awgn(ams[0], SNRdB=makeNP(kwargs.get('SNR', np.inf)))
    return (signalTupl[0], t, freq)
def main():
    matplotlib.rc('font', family='Times New Roman', size=12)
    Fs = 2000
    ampl = 1
    decay = 50
    t = genTime(maxTime=1, Fs=Fs)
    dFmax = 2
    freq = np.linspace(start=0, stop=dFmax, num=t.size)
    plotGraphs = 0
    roughFreq = (50, 200)
    kwargs = {
        'Fs': Fs,
        'SNRvals': np.arange(-2.5, -5.5, -0.5),
        'carrier': 100,
        'plotGraphs': plotGraphs,
        'experiences': 5,
        'processes': 5,
        'asyncLoop': True
    }
    kwargs.update({
        'roughFreqs': roughFreq,
        'formFactor': 128,
        'hold': 0,
        'secondsNum': 0.025,
        'percentOverlap': 75
    })  # (64, 128)(0.075, 0.02)
    # kwargs.update({'paramNames': ['amplitude', 'decay', 'timeSamples'], 'percentDeviation': [100, 50, 0]})
    # kwargs.update({'paramNames': 'amplitude', 'percentDeviation': 100})
    kwargs.update({'writeAudio': True, 'hold': 0})
    # kwargs.update({'start': 1, 'stop': 2, 't': 5, 'decay': decay, 'SNR': -5, 'fileName': 'aFewPulses.pkl'})
    # o = modelPulses(**kwargs)
    # (alpha, f, A, theta, res, timeSamplesIdsEst) = pulsesParamsEst(o[0], **kwargs)[0:6]

    # modTest(Fs=Fs, t=1, SNRvals=np.arange(4, -16.5, -0.5), fileName='linear02AM0.pkl',
    #carrier=100, FMfreq=freq, FMdepth=0.1, AMfreq=5, AMdepth=0.0, plotGraphs=plotGraphs, experiences=102, processes=6, asyncLoop=True)  # 6, -12
    #modTest(Fs=Fs, t=1, SNRvals=np.arange(-3, -16.5, -0.5), fileName='AMf5d025.pkl',
    # carrier=100, FMfreq=5, FMdepth=0.1, AMfreq=5, AMdepth=0.25, plotGraphs=plotGraphs, experiences=1)  # 6, -12
    #return
    pulsesTest(decay=decay,
               t=5,
               fileName='pulses_5trials__1.4hold.pkl',
               **kwargs)
    return
    modTest(t=1,
            fileName='pulses_104trials.pkl',
            FMfreq=5,
            FMdepth=0.1,
            AMfreq=5,
            AMdepth=0.25,
            **kwargs)  # 6, -12
    # np.hstack((np.arange(4, -5, -1), np.arange(-5, -7.5, -0.5), np.arange(-8, -22, -2)))
    #modTest(t=1, fileName='AMf5d02.pkl', FMfreq=5, FMdepth=0.1, AMfreq=5, AMdepth=0.2, **kwargs)  # 6, -12
    #modTest(t=1, fileName='AMf3d02.pkl', FMfreq=5, FMdepth=0.1, AMfreq=3, AMdepth=0.2, **kwargs)  # 6, -12
    return

    h0Sam = np.random.normal(loc=0.0, scale=1 / 3,
                             size=(1, 100))  # np.arange(0.1, 1.1, 0.05)
    h1Sam = np.random.normal(loc=1.0, scale=1 / 2.5,
                             size=(1, 100))  # np.arange(0.9, 2, 0.1)
    autoThresholding(h1Sam, h0Sam)

    from timeit import default_timer as timer
    #modTest(Fs=Fs, t=1, SNRvals=(0,), carrier=100, FMfreq=5, FMdepth=0.1, AMfreq=4, AMdepth=0.25, plotGraphs=plotGraphs, experiences=1)  # 6, -12
    tStart = timer()
    modTest(Fs=Fs,
            t=1,
            SNRvals=np.arange(4, 1, -1),
            fileName='',
            carrier=100,
            FMfreq=5,
            FMdepth=0.1,
            AMfreq=5,
            AMdepth=0,
            plotGraphs=plotGraphs,
            experiences=16,
            processes=4,
            asyncLoop=True)  # 6, -12
    elapsed2 = timer() - tStart
    print(('2 async', elapsed2))

    tStart = timer()
    modTest(Fs=Fs,
            t=1,
            SNRvals=np.arange(4, 1, -1),
            fileName='',
            carrier=100,
            FMfreq=5,
            FMdepth=0.1,
            AMfreq=5,
            AMdepth=0,
            plotGraphs=plotGraphs,
            experiences=16,
            processes=4)  # 6, -12
    elapsed1 = timer() - tStart
    print(('2 map', elapsed1))

    tStart = timer()
    modTest(Fs=Fs,
            t=1,
            SNRvals=np.arange(4, 1, -1),
            fileName='',
            carrier=100,
            FMfreq=5,
            FMdepth=0.1,
            AMfreq=5,
            AMdepth=0,
            plotGraphs=plotGraphs,
            experiences=16)  # 6, -12
    elapsed3 = timer() - tStart
    print(('Consequent', elapsed3))

    modTest(Fs=Fs,
            t=1,
            SNRvals=np.hstack((np.arange(4, -5, -1), np.arange(-5, -7.5, -0.5),
                               np.arange(-8, -16, -2))),
            fileName='',
            carrier=100,
            FMfreq=5,
            FMdepth=0.1,
            AMfreq=5,
            AMdepth=0,
            plotGraphs=plotGraphs,
            experiences=16)  # 6, -12

    pulsesTest(Fs=Fs,
               decay=decay,
               t=5,
               SNRvals=np.arange(0, -12, -2),
               carrier=100,
               plotGraphs=plotGraphs,
               experiences=5)

    # freq = np.ones((1, t.size))
    # freq[0, :] *= 100 * (1 + np.linspace(start=0, stop=dFmax, num=t.size))
    # freq = AMsign(t, np.ones((1, t.size))*100, 5, depth=0.1)[0]
    (FMcomp, freq) = frequencyModulated(
        5, t, f0=100, depth=0.1,
        phi0=0)  # chirp(t, freq[0, 0], t[-1], freq[0, -1])
    FMsignal = pa.awgn(FMcomp, SNRdB=60)[0]
    (representation, t0, fVectNew) = pa.DFTbank(FMsignal,
                                                rect=2,
                                                level=0.2,
                                                Fs=Fs,
                                                mirrorLen=0.15,
                                                df=0.05,
                                                freqLims=(50, 200),
                                                formFactor=128)
    tEnd = int(closeInVect(t, 0.15)[1])
    fInd = int(closeInVect(fVectNew, 100)[1])
    fig4 = plotRepresentation(t, representation, fVectNew, None)
    fig100 = plotSignal(representation[fInd, :], t, specKind='amplitude')
    (alpha, f, A, theta, resid,
     coefficient) = pa.thresholdRepreProny(representation,
                                           fVectNew,
                                           Fs=Fs,
                                           percentLength=2,
                                           percentOverlap=75,
                                           lowFreq=85,
                                           highFreq=120,
                                           hold=1.4)
    figFull = plotUnder(t, (FMcomp, alpha, (f, freq)),
                        yLims=[(-1.2, 1.2), (-30, 30), (85, 125)],
                        labels=(None, 'decay', ('estimated frequency',
                                                'initial frequency')),
                        secondParam=resid,
                        secondLim=None)  # (0, 2*10 ** -6)

    ams = AMsign(t, FMcomp, 5, depth=0.25)
    signal = pa.awgn(ams[0], SNRdB=60)[0]
    # figAM = plotSignal(signal, t, specKind='amplitude')
    (representation, t0, fVectNew) = pa.DFTbank(signal,
                                                rect=2,
                                                level=0.2,
                                                Fs=Fs,
                                                mirrorLen=0.15,
                                                df=1,
                                                freqLims=(50, 200),
                                                formFactor=128)
    fig4 = plotRepresentation(t, representation, fVectNew, None)
    fInd = int(closeInVect(fVectNew, 105)[1])
    fig100 = plotSignal(representation[fInd, :], t, specKind='amplitude')
    (alpha, f, A, theta, resid,
     coefficient) = pa.thresholdRepreProny(representation,
                                           fVectNew,
                                           Fs=Fs,
                                           percentLength=2,
                                           percentOverlap=75,
                                           lowFreq=80,
                                           highFreq=125,
                                           hold=1.4)
    figFull = plotUnder(t, (FMcomp, alpha, (f, freq)),
                        yLims=[(-1.2, 1.2), (-30, 30), (85, 125)],
                        secondParam=resid,
                        secondLim=None)  # (0, 2*10 ** -6)

    timeSituations = np.arange(start=0, stop=5, step=0.5)
    timeSamples = closeInVect(t, timeSituations)[0]
    envel = expPulses(t, timeSamples, decay, ampl)[0] - np.max(ampl)
    ams = AMsign(t, 100, envel, depth=1)
    signal = pa.awgn(ams[0], SNRdB=-2)[0]
    # fig = plotSignal(signal, t, specKind='amplitude')
    (representation, t0, fVectNew) = pa.DFTbank(signal,
                                                rect=2,
                                                level=0.2,
                                                Fs=Fs,
                                                mirrorLen=0.15,
                                                df=1,
                                                freqLims=(50, 200),
                                                formFactor=128)
    # fig4 = plotRepresentation(t, representation, fVectNew, None)
    (alpha, f, A, theta, resid,
     coefficient) = pa.thresholdRepreProny(representation,
                                           fVectNew,
                                           Fs=Fs,
                                           periodsNum=10,
                                           lowFreq=95,
                                           highFreq=105,
                                           hold=1.5)
    '''''
    fig3 = plt.figure()
    plt.plot(t, alpha)
    fig2 = plt.figure()
    plt.plot(t, f)
    fig4 = plt.figure()
    plt.plot(t, resid)
    fig4.show()
    ''' ''
    print(np.mean((f[:int(f.size * 0.85)] - 100)**2))
    # figFull = plotUnder(t, (representation[fInd, :], alpha, f), yLims=[(-0.6, 0.6), (12.5, 17.5), (95, 105)], secondParam=resid, secondLim=(0, 7*10**-6))
    # fig100 = plotSignal(representation[fInd, :], t, specKind='amplitude')
    (alpha1, f1, A1, theta1,
     resid1) = pa.pronyDecomp(representation[fInd, :tEnd], 2, Fs=Fs)
    print(np.sum(resid1.bse**2))

    ams = AMsign(t, 100, 5, depth=0.25)
    signal = pa.awgn(ams[0], SNRdB=-2)[0]
    # figAM = plotSignal(signal, t, specKind='amplitude')
    (representation, t0, fVectNew) = pa.DFTbank(signal,
                                                rect=2,
                                                level=0.2,
                                                Fs=Fs,
                                                mirrorLen=0.15,
                                                df=1,
                                                freqLims=(50, 200),
                                                formFactor=1024)
    fig4 = plotRepresentation(t, representation, fVectNew, None)
    fig100 = plotSignal(representation[fInd, :], t, specKind='amplitude')
    (alpha, f, A, theta, resid,
     coefficient) = pa.thresholdRepreProny(representation,
                                           fVectNew,
                                           Fs=Fs,
                                           percentLength=5,
                                           percentOverlap=75,
                                           lowFreq=95,
                                           highFreq=105,
                                           hold=1.4)
    figFull = plotUnder(t, (representation[fInd, :], alpha, f),
                        yLims=[(-2, 2), (-20, 20), (95, 105)],
                        secondParam=resid,
                        secondLim=None)  # (0, 2*10 ** -6)
    pass
Exemplo n.º 4
0
def waveProc(kwargs):
    signal = kwargs.get('signal')
    SNR = kwargs.get('SNR')
    dFmax = kwargs.get('dFmax')
    Fs = kwargs.get('Fs')
    freq = kwargs.get('freq')
    selectWinds = kwargs.get('selectWinds')
    signalN = pa.awgn(signal, SNRdB=SNR)[0]
    (representation, t0, fVectNew) = pa.DFTbank(signalN,
                                                rect=2,
                                                mirrorLen=0.15,
                                                level=0.2,
                                                freqLims=(50, 200),
                                                Fs=Fs,
                                                df=1,
                                                formFactor=1024)
    '''''
    if plotGraphs == 2:
        fig4 = plt.figure()
        grid = matplotlib.gridspec.GridSpec(1, 1)
        ax_specWav = fig4.add_subplot(grid[0])
        extent = t[0], t[-1], fVectNew[0], fVectNew[-1]
        ax_specWav.imshow(np.flipud(np.abs(representation)), extent=extent)
        ax_specWav.axis('auto')
        plt.ylim(int(np.min(freq) * 0.9), int(np.max(freq) * 1.1))
        fig4.show()
    ''' ''

    repFreq = pa.representationTrack(representation, fVectNew)

    (representation, t0, fVectNew) = pa.DFTbank(signalN,
                                                rect=2,
                                                mirrorLen=0.15,
                                                level=0.2,
                                                freqLims=(50, 200),
                                                Fs=Fs,
                                                df=1,
                                                formFactor=128)
    (alpha, f, A, theta, resid,
     coefficient) = pa.thresholdRepreProny(representation,
                                           fVectNew,
                                           Fs=Fs,
                                           centralFreq=0,
                                           lowFreq=95,
                                           highFreq=130,
                                           hold=1.4)
    '''''
    if plotGraphs:
        ax_FreqDev.plot(t, freq[0, :], linestyle='-', color='k', label='Мгновенная частота')
        ax_FreqR.plot(t, freq[0, :], linestyle='-', color='k', label='Мгновенная частота')
    ''' ''
    indexes = np.hstack(np.nonzero(f))
    # Select long stable windows.
    if selectWinds:
        errIdxs = pa.SM.validateTrack(f)
        errIdxsRepr = pa.SM.validateTrack(repFreq)
    else:
        errIdxs = np.hstack(np.nonzero(f))
        errIdxsRepr = np.hstack(np.nonzero(repFreq))
    validLen = errIdxs.size / f.size
    if validLen < 0.85:
        errIdxs = indexes
    validLenRepr = errIdxsRepr.size / f.size
    if validLenRepr < 0.85:
        errIdxsRepr = indexes
    '''''
    if plotGraphs:
        ax_FreqDev.plot(t[indexes], f[indexes], linestyle=':', color=cmap1(bi), label='Оценка частоты')
        # ax_FreqDev.plot(t[errIdxs], f[errIdxs], linestyle=':', color='r', label='Поправленная оценка')
        ax_FreqDev.set_xlabel('Время, сек')
        ax_FreqDev.set_ylabel('Частота, Гц')
        ax_FreqR.plot(t, repFreq, linestyle=':', color=cmap1(bi), label='Оценка частоты')
        ax_FreqR.set_xlabel('Время, сек')
        ax_FreqR.set_ylabel('Частота, Гц')
    ''' ''
    diff = freq[0, errIdxs] - f[errIdxs]
    err = pa.rms(diff)
    errRep = pa.rms(freq[0, errIdxsRepr] - repFreq[errIdxsRepr])
    #print('Coefficient {}, error {}, valid track length {} percents, representation error {}, repres. valid track len = {}'.format(
    #dFmax, err, validLen * 100, errRep, validLenRepr * 100))
    '''''
    if ai < 1 and bi < 1 and plotGraphs:
        ax_FreqDev.legend()
        ax_FreqR.legend()
    ''' ''
    return err, errRep, validLen, validLenRepr
Exemplo n.º 5
0
 harmDisp = np.zeros_like(SNRs)
 noisDisp = np.zeros_like(SNRs)
 dF = np.zeros_like(SNRs)
 dF2 = np.zeros((SNRs.size, distances.size))
 freq = np.ones((1, t.size))
 freq[0, :] = freq[0, :] * 100 * (
     1 + np.linspace(start=0, stop=coefficients[ai], num=t.size))
 (frq, frqWinIdxs) = pa.windowing(
     freq[0, :], int(np.round(freq[0, :].size * percentLength / 100)),
     percentOverlap)
 fOrig = frq[:, 0]
 for bi in range(SNRs.size):
     for ci in range(experiences):
         signal = chirp(t, freq[0, 0], t[-1], freq[0, -1])
         #(alpha, f, A, theta, resid, coefficient) = pa.timeSegmentedProny(signal, Fs=Fs, percentLength=10, percentOverlap=50, order=2)
         (signal, noise) = pa.awgn(signal, SNRdB=SNRs[bi])[0:2]
         spec = np.fft.rfft(signal) / signal.size
         spec[fVect < 95] = 0  # freq[0, 0] * 0.95
         spec[fVect > 135] = 0  # freq[0, -1] * 1.05
         cmp = np.fft.irfft(spec) * spec.size * 2
         (alpha, f, A, theta, resid, coefficient) = pa.timeSegmentedProny(
             cmp,
             Fs=Fs,
             percentLength=percentLength,
             percentOverlap=percentOverlap,
             order=2)
         fTemp = np.array(f)[:, 1]
         dF[bi] += pa.rms(fOrig - fTemp)
         harmDisp += np.std(fTemp)
         spec2 = np.fft.rfft(noise) / noise.size
         spec2[fVect < 95] = 0  # freq[0, 0] * 0.95
Exemplo n.º 6
0
    comp = amplitude * chirp(t, freq[ai, 0], t[-1],
                             freq[ai, -1])  #*np.sin(fullPhase)
    #comp = pa.abwgn(comp, SNRdB=-7, Fs=Fs, band=(freq[ai, 0]*0.95, freq[ai, -1]*1.05))[0]
    signal = signal + comp
    k[ai] = (freq[ai, -1] - freq[ai, 0]) / (t[-1] - t[0]) / freq[ai, 0]
    #Plot instantateous frequency
    if plotGraphs:
        analytic_signal = hilbert(comp)
        instantaneous_phase = np.unwrap(np.angle(analytic_signal))
        instantaneous_frequency = (np.diff(instantaneous_phase) /
                                   (2.0 * np.pi) * Fs)
        plt.plot(t[1:], instantaneous_frequency)

# signal = chirp(t, freq[0, 0], t[-1], freq[0, -1])
# signal = pa.abwgn(signal, SNRdB=10, Fs=Fs, band=(95, 105))[0]
signal = pa.awgn(signal, SNRdB=-2)[0]
if plotGraphs:
    spec = np.fft.rfft(signal) / signal.size
    grid = matplotlib.gridspec.GridSpec(2, 1)
    fig = plt.figure(figsize=(16, 10))
    ax_signal = fig.add_subplot(grid[0])
    ax_spectr = fig.add_subplot(grid[1])
    ax_phase = ax_spectr.twinx()
    ax_signal.plot(t, signal)
    ax_spectr.plot(fVect, np.abs(spec))
    ax_phase.plot(fVect, np.angle(spec) / np.pi, '1k')
    ax_spectr.grid(color='r', linestyle='--')
    ax_phase.grid(color='k', linestyle=':')
    fig.show()

    fig2 = plt.figure(figsize=(16, 10))