Esempio n. 1
0
def plot_ratios(in_wave, out_wave):

    # compare filters for cumsum and integration
    diff_window = np.array([1.0, -1.0])
    padded = thinkdsp.zero_pad(diff_window, len(in_wave))
    diff_wave = thinkdsp.Wave(padded, framerate=in_wave.framerate)
    diff_filter = diff_wave.make_spectrum()

    cumsum_filter = diff_filter.copy()
    cumsum_filter.hs = 1 / cumsum_filter.hs
    cumsum_filter.plot(label='cumsum filter', color=GRAY, linewidth=7)

    integ_filter = cumsum_filter.copy()
    integ_filter.hs = integ_filter.framerate / (PI2 * 1j * integ_filter.fs)
    integ_filter.plot(label='integral filter')

    thinkplot.config(xlim=[0, integ_filter.max_freq],
                     yscale='log',
                     legend=True)
    thinkplot.save('diff_int8')

    # compare cumsum filter to actual ratios
    cumsum_filter.plot(label='cumsum filter', color=GRAY, linewidth=7)

    in_spectrum = in_wave.make_spectrum()
    out_spectrum = out_wave.make_spectrum()
    ratio_spectrum = out_spectrum.ratio(in_spectrum, thresh=1)
    ratio_spectrum.plot(label='ratio', style='.', markersize=4)

    thinkplot.config(xlabel='Frequency (Hz)',
                     ylabel='Amplitude ratio',
                     xlim=[0, integ_filter.max_freq],
                     yscale='log',
                     legend=True)
    thinkplot.save('diff_int9')
Esempio n. 2
0
def window_plot():
    """Makes a plot showing a sinusoid, hamming window, and their product.
    """
    signal = thinkdsp.SinSignal(freq=440)
    duration = signal.period * 10.25
    wave1 = signal.make_wave(duration)
    wave2 = signal.make_wave(duration)

    ys = numpy.hamming(len(wave1.ys))
    window = thinkdsp.Wave(ys, wave1.framerate)

    wave2.hamming()

    thinkplot.preplot(rows=3, cols=1)

    pyplot.subplots_adjust(wspace=0.3,
                           hspace=0.3,
                           right=0.95,
                           left=0.1,
                           top=0.95,
                           bottom=0.05)

    thinkplot.subplot(1)
    wave1.plot()
    thinkplot.config(axis=[0, duration, -1.07, 1.07])

    thinkplot.subplot(2)
    window.plot()
    thinkplot.config(axis=[0, duration, -1.07, 1.07])

    thinkplot.subplot(3)
    wave2.plot()
    thinkplot.config(axis=[0, duration, -1.07, 1.07], xlabel='time (s)')

    thinkplot.save(root='windowing2')
Esempio n. 3
0
def make_randombursts(sfs = 2000, fs = 96000, intervals = 8):
    """
    Assumes:
        sfs frequency of the carrier wave
        fs sampling frequency
        intervals number of random bursts to be created
    Returns:
        Wave object consisting of beeps with random amplitude
    """

    dt = 1/fs
    final = np.array([])

    for i in range(intervals):
        amp = 1
        wait = np.random.uniform(0.5,2)
        stime = np.random.uniform(0.02,0.1)
        t = np.arange(0,stime,dt)

        zeros = np.zeros(int(np.floor(fs*wait)))
        signal = amp*np.sin(t*np.pi*(1/stime))*np.sin(2*np.pi*t*sfs)
        final = np.concatenate((final,zeros))
        final = np.concatenate((final,signal))
        final = np.concatenate((final,zeros))
    final = np.concatenate((final, np.zeros(fs*2)))
    return dsp.Wave(final, framerate = fs)
Esempio n. 4
0
def f0(frame, audiofile):
    threshold = 0.5

    clip = td.Wave(frame)
    spectrum = clip.make_spectrum()

    #sorted_by_Hz = sorted(spectrum.peaks(), key=lambda tup: tup[1])
    # to find F0 we can sort by Hz, unfortunately we have small readings at 0.0Hz
    # and other small frequencies which make finding the true F0 hard

    # remove the small amplitudes which don't well describe the energy in the sound.
    # What is small is likely to be relative to the largest amplitude so use some threshold
    greatest_Hz = (spectrum.peaks()[0])[0]
    selected_pairs = []
    list_pos = 0
    while True:
        pair = (spectrum.peaks()[list_pos])
        within_threshold = (pair[0] > (greatest_Hz * threshold))
        if within_threshold == False:
            break
        selected_pairs.append(pair)
        list_pos = list_pos + 1

    # selected_pairs is now a list of the pairs which have a prominent amplitude
    sorted_by_Hz = sorted(selected_pairs, key=lambda tup: tup[1])
    # the lowest Hz should now be F0, will need to tweek 0.5
    return [sorted_by_Hz[0][1]]
Esempio n. 5
0
def estimate(data):
    length = len(data)
    wave = thinkdsp.Wave(ys=data, framerate=Fs)
    spectrum = wave.make_spectrum()
    spectrum_heart = wave.make_spectrum()
    spectrum_resp = wave.make_spectrum()

    fft_mag = list(np.absolute(spectrum.hs))
    fft_length = len(fft_mag)

    spectrum_heart.high_pass(cutoff=0.5, factor=0)
    spectrum_heart.low_pass(cutoff=4, factor=0)
    fft_heart = list(np.absolute(spectrum_heart.hs))

    max_fft_heart = max(fft_heart)
    heart_sample = fft_heart.index(max_fft_heart)
    hr = heart_sample * Fs / length * 60

    spectrum_resp.high_pass(cutoff=0.15, factor=0)
    spectrum_resp.low_pass(cutoff=0.5, factor=0)
    fft_resp = list(np.absolute(spectrum_resp.hs))

    max_fft_resp = max(fft_resp)
    resp_sample = fft_resp.index(max_fft_resp)
    rr = resp_sample * Fs / length * 60

    if hr < 10:
        return hr, 0
    else:
        return hr, rr
    def testWaveAdd(self):
        ys = np.array([1, 2, 3, 4])
        wave1 = thinkdsp.Wave(ys, framerate=1)
        wave2 = wave1.copy()
        wave2.shift(2)
        wave = wave1 + wave2

        self.assertEqual(len(wave), 6)
        self.assertAlmostEqual(sum(wave.ys), 20)
Esempio n. 7
0
def sample(wave, factor):
    """Simulates sampling of a wave.
    
    wave: Wave object
    factor: ratio of the new framerate to the original
    """
    ys = np.zeros(len(wave))
    ys[::factor] = wave.ys[::factor]
    ts = wave.ts[:]
    return thinkdsp.Wave(ys, ts, wave.framerate)
Esempio n. 8
0
def make_filter(window, wave):
    """Computes the filter that corresponds to a window.
    
    window: NumPy array
    wave: wave used to choose the length and framerate
    
    returns: new Spectrum
    """
    padded = thinkdsp.zero_pad(window, len(wave))
    window_wave = thinkdsp.Wave(padded, framerate=wave.framerate)
    window_spectrum = window_wave.make_spectrum()
    return window_spectrum
Esempio n. 9
0
def sdoa(wave1, wave2):
    """
    Returns :
        the number of samples of difference as calculated with the algorithm. If x is the result then this means
        that wave 1 arrived before by x samples (negative means it arrived later)
    Assumes:
        Wave1 and Wave2 are wave objects with same number of samples
        pass_band is the pass_band used for the filter. If nothing is passed the signals are not filtered.
    """

    #creates the wave objects with the new signals
    h1 = dsp.Wave(np.abs(Hilbert(wave1.ys)), framerate = wave1.framerate)
    h2 = dsp.Wave(np.abs(Hilbert(wave2.ys)), framerate = wave2.framerate)

    percentage = h1.duration * 0.001
    start = percentage
    duration = h1.duration - percentage

    segment1 = h1.segment(start = start, duration = duration)
    segment2 = h2.segment(start = start, duration = duration)

    return (-1 )* correlate(h1,h2)
Esempio n. 10
0
def hplot(wave1, wave2):
    """
    Assummes
        wave1 and wave2 are wave objects
    Returns
        Plot of wave1 and wave2 with respective envelopes obtained with hilbert Transforms
        wave1 is in blue wave2 is in red. Envelope 1 is in black envelope 2 is in cyan
    """

    #Remember to modify


    h1 = dsp.Wave(np.abs(Hilbert(wave1.ys)), framerate = wave1.framerate)
    h2 = dsp.Wave(np.abs(Hilbert(wave2.ys)), framerate = wave2.framerate)


    plt.plot(wave1.ts, wave1.ys, color = 'b')
    plt.plot(wave2.ts, wave2.ys, color = 'r')
    plt.plot(h1.ts, h1.ys, color = 'k')
    plt.plot(h2.ts, h2.ys, color = 'c')

    plt.show()
Esempio n. 11
0
def plot_diff_deriv(close):
    change = thinkdsp.Wave(np.diff(close.ys), framerate=1)

    deriv_spectrum = close.make_spectrum().differentiate()
    deriv = deriv_spectrum.make_wave()

    low, high = 0, 50
    thinkplot.preplot(2)
    thinkplot.plot(change.ys[low:high], label='diff')
    thinkplot.plot(deriv.ys[low:high], label='derivative')

    thinkplot.config(xlabel='Time (day)', ylabel='Price change ($)')
    thinkplot.save('diff_int4')
    def testMakeSpectrum(self):
        # rfft with n even
        ys = np.arange(10)
        wave = thinkdsp.Wave(ys, framerate=10)
        spectrum = wave.make_spectrum()
        self.assertAlmostEqual(spectrum.hs[0], 45)
        wave2 = spectrum.make_wave()
        #print(wave2.ys)
        self.assertArrayAlmostEqual(wave.ys, wave2.ys)

        # rfft with n odd
        ys = np.arange(11)
        wave = thinkdsp.Wave(ys, framerate=10)
        spectrum = wave.make_spectrum()
        self.assertAlmostEqual(spectrum.hs[0], 55)

        # TODO: make rfft invertible when n is odd
        #wave2 = spectrum.make_wave()
        #print(wave2.ys)
        #self.assertArrayAlmostEqual(wave.ys, wave2.ys)

        # fft with n even
        ys = np.arange(10)
        wave = thinkdsp.Wave(ys, framerate=10)
        spectrum = wave.make_spectrum(full=True)
        self.assertAlmostEqual(spectrum.hs[0], 45)
        wave2 = spectrum.make_wave()
        #print(wave2.ys)
        self.assertArrayAlmostEqual(wave.ys, wave2.ys)

        # fft with n odd
        ys = np.arange(11)
        wave = thinkdsp.Wave(ys, framerate=10)
        spectrum = wave.make_spectrum(full=True)
        self.assertAlmostEqual(spectrum.hs[0], 55)
        wave2 = spectrum.make_wave()
        #print(wave2.ys)
        self.assertArrayAlmostEqual(wave.ys, wave2.ys)
Esempio n. 13
0
    def apply_padding( self ):
        """
        Adds the neccesary padding to the signal instance variable.
        The variable used for the padding is that of the object when it is
        instantiated.
        """
        temp = self.signal.ys

        #padding entry and exit time
        pad_front = np.zeros(int(self.signal.framerate * self.tentry))
        pad_back = np.zeros(int(self.signal.framerate * self.texit))
        temp = np.concatenate((np.concatenate((pad_front, temp)), pad_back))

        self.signal = dsp.Wave(temp, framerate= self.signal.framerate)
Esempio n. 14
0
def main():
    plot_convolution()
    return

    plot_response()
    return

    df = pandas.read_csv('coindesk-bpi-USD-close.csv',
                         nrows=1625,
                         parse_dates=[0])
    ys = df.Close.values
    wave = thinkdsp.Wave(ys, framerate=1)
    #plot_wave_and_spectrum(wave, root='systems1')

    diff = numpy.diff(ys)
    wave2 = thinkdsp.Wave(diff, framerate=1)
    #plot_wave_and_spectrum(wave2, root='systems2')

    #plot_ratios(wave, wave2)
    plot_derivative(wave, wave2)
    return

    plot_filters(wave)
Esempio n. 15
0
def show_iq():
    arr= np.fromfile(sys.argv[1], dtype=np.int16)#按8位数据读取iq数据
    print(arr[0:100])
    arr1=arr[0::2];
    print(arr1[0:100])
    arr2=arr[1::2];
    print(arr2[0:100])
    print(arr.size, arr1.size,arr2.size)
    i = thinkdsp.Wave(arr1, framerate=2000000)
    i.plot()
    plt.show()

    q = thinkdsp.Wave(arr1, framerate=2000000)
    q.plot()
    plt.show()


    spectrum = i.make_spectrum()
    spectrum.plot()
    plt.show()

    spectrum.low_pass(cutoff=100000, factor=0.01)
    spectrum.plot()
    plt.show()
    violin_wave = spectrum.make_wave()
    violin_wave.plot()
    plt.show()

    '''
    real=arr[126500:128000:2]#取部分i数据
    imag=arr[126501:128000:2]#取部分q数据
    d_real=real.astype(np.float32)#数据类型转化,不然8位数据只能显示-127到127.卡了我一天不知道哪里错了
    d_imag=imag.astype(np.float32)
    comx=d_real+d_imag*1j#组成复数
    '''
    '''
Esempio n. 16
0
def main():
    names = ['date', 'open', 'high', 'low', 'close', 'volume']
    df = pd.read_csv('fb.csv', header=0, names=names, parse_dates=[0])
    ys = df.close.values[::-1]
    close = thinkdsp.Wave(ys, framerate=1)
    plot_wave_and_spectrum(close, root='diff_int1')

    change = thinkdsp.Wave(np.diff(ys), framerate=1)
    plot_wave_and_spectrum(change, root='diff_int2')

    plot_filters(close)

    plot_diff_deriv(close)

    signal = thinkdsp.SawtoothSignal(freq=50)
    in_wave = signal.make_wave(duration=0.1, framerate=44100)
    plot_sawtooth_and_spectrum(in_wave, 'diff_int6')

    out_wave = in_wave.cumsum()
    out_wave.unbias()
    plot_sawtooth_and_spectrum(out_wave, 'diff_int7')

    plot_integral(close)
    plot_ratios(in_wave, out_wave)
Esempio n. 17
0
def plot_filter():
    """Plots the filter that corresponds to a 2-element moving average.
    """
    impulse = np.zeros(8)
    impulse[0] = 1
    wave = thinkdsp.Wave(impulse, framerate=8)

    impulse_spectrum = wave.make_spectrum(full=True)
    window_array = np.array([
        0.5,
        0.5,
        0,
        0,
        0,
        0,
        0,
        0,
    ])
    window = thinkdsp.Wave(window_array, framerate=8)
    filtr = window.make_spectrum(full=True)

    filtr.plot()
    thinkplot.config(xlabel='Frequency', ylabel='Amplitude')
    thinkplot.save('systems1')
Esempio n. 18
0
def evalSymbReg(individual, target):
    # Transform the tree expression in a callable function
    func = toolbox.compile(expr=individual)
    # Evaluate the mean squared error between the expression
    # and the real function : x**4 + x**3 + x**2 + x
    gen_ys = np.array([func(x, f) for x in t])
    gen_sr = target.framerate
    generated = thinkdsp.Wave(ys=gen_ys, framerate=gen_sr)

    # gen_mfcc = getMFCC(gen_ys, gen_sr, False)
    # target_mfcc = getMFCC(target.ys, target.framerate, False)
    # result = mfcc_squared_error(gen_mfcc,target_mfcc)
    # result = mfcc_squared_error(gen_ys,target.ys)
    # result = mag_pha_s_error(target,generated)
    result = features_diff(target, generated)
    return result,
Esempio n. 19
0
def synthesize_example():
    amps = numpy.array([0.6, 0.25, 0.1, 0.05])
    freqs = [100, 200, 300, 400]

    framerate = 11025
    ts = numpy.linspace(0, 1, 11025)
    ys = synthesize2(amps, freqs, ts)
    wave = thinkdsp.Wave(ys, framerate)
    wave.normalize()
    wave.apodize()
    wave.play()

    n = len(freqs)
    amps2 = analyze1(ys[:n], freqs, ts[:n])
    print amps
    print amps2
Esempio n. 20
0
def main():
    random.seed(random.randint(1, 100))

    pop = toolbox.population(n=500)
    hof = tools.HallOfFame(1)

    # CXPB  - Probabilidade de crossover
    # MUTPB - Probabilidade de mutação
    # NGEN  - Numero de gerações
    CXPB, MUTPB, NGEN = 0.75, 0.12, 20

    stats = tools.Statistics(lambda ind: ind.fitness.values)
    stats.register("avg", np.mean)
    stats.register("std", np.std)
    stats.register("min", np.min)
    stats.register("max", np.max)

    pop, log = algorithms.eaSimple(pop,
                                   toolbox,
                                   CXPB,
                                   MUTPB,
                                   NGEN,
                                   stats=stats,
                                   halloffame=hof,
                                   verbose=True)
    # pop, log = algorithms.eaMuCommaLambda(population=pop,
    #                                      toolbox=toolbox,
    #                                      mu=200,
    #                                      lambda_=200,
    #                                      cxpb=CXPB,
    #                                      mutpb=MUTPB,
    #                                      ngen=NGEN,
    #                                      stats=mstats,
    #                                      halloffame=hof,
    #                                      verbose=True)
    # pop, log = gp.harm(pop, toolbox, 0.5, 0.1, 40, alpha=0.05, beta=10, gamma=0.25, rho=0.9, stats=mstats,
    #                   halloffame=hof, verbose=True)
    # print log
    function = gp.compile(hof[0], pset)
    gen_ys = np.array([function(x, f) for x in t])
    gen_sr = target.framerate
    generated = thinkdsp.Wave(ys=gen_ys, framerate=gen_sr)
    generated.write(filename="generated.wav")
    #plot_log(log, 'aaa')
    return pop, log, hof
Esempio n. 21
0
def synthesize_example():
    """Synthesizes a sum of sinusoids and plays it.
    """
    amps = np.array([0.6, 0.25, 0.1, 0.05])
    fs = [100, 200, 300, 400]

    framerate = 11025
    ts = np.linspace(0, 1, 11025)
    ys = synthesize2(amps, fs, ts)
    wave = thinkdsp.Wave(ys, framerate)
    wave.normalize()
    wave.apodize()
    wave.play()

    n = len(fs)
    amps2 = analyze1(ys[:n], fs, ts[:n])
    print(amps)
    print(amps2)
Esempio n. 22
0
def plot_gaussian():
    """Makes a plot showing the effect of convolution with a boxcar window.
    """
    # start with a square signal
    signal = thinkdsp.SquareSignal(freq=440)
    wave = signal.make_wave(duration=1, framerate=44100)
    spectrum = wave.make_spectrum()

    # and a boxcar window
    boxcar = numpy.ones(11)
    boxcar /= sum(boxcar)

    # and a gaussian window
    gaussian = scipy.signal.gaussian(M=11, std=2)
    gaussian /= sum(gaussian)

    thinkplot.preplot(2)
    thinkplot.plot(boxcar, label='boxcar')
    thinkplot.plot(gaussian, label='Gaussian')
    thinkplot.config(xlabel='index', ylabel='amplitude')
    thinkplot.save(root='convolution7')

    ys = numpy.convolve(wave.ys, gaussian, mode='same')
    smooth = thinkdsp.Wave(ys, framerate=wave.framerate)
    spectrum2 = smooth.make_spectrum()

    # plot the ratio of the original and smoothed spectrum
    amps = spectrum.amps
    amps2 = spectrum2.amps
    ratio = amps2 / amps
    ratio[amps < 560] = 0

    # plot the same ratio along with the FFT of the window
    padded = zero_pad(gaussian, len(wave))
    dft_gaussian = numpy.fft.rfft(padded)

    thinkplot.plot(abs(dft_gaussian), color='0.7', label='Gaussian filter')
    thinkplot.plot(ratio, label='amplitude ratio')

    thinkplot.config(xlabel='frequency (Hz)',
                     ylabel='amplitude ratio',
                     xlim=[0, 22050],
                     legend=False)
    thinkplot.save(root='convolution8')
Esempio n. 23
0
    def read_wave(filename='sound.wav'):
        """
        Reads a file and creates a wave objec that is then assigned to the instance variable abs
        representing the wave
        """
        wavob = wavio.read(filename)
        nchannel = len(wavob.data[0])
        sampw = wavob.sampwidth
        data = wavob.data
        framerate = wavob.rate

        ys = data[:,0]

        if(nchannel >= 2):
            ys = data[:,self.channel -1]

        #ts = np.arange(len(ys)) / framerate
        wav = dsp.Wave(ys, framerate=framerate)
        wav.normalize()
        self.wave = wav
def plot_filter(M=11, std=2):
    signal = thinkdsp.SquareSignal(freq=440)
    wave = signal.make_wave(duration=1, framerate=44100)
    spectrum = wave.make_spectrum()

    gaussian = scipy.signal.gaussian(M=M, std=std)
    gaussian /= sum(gaussian)
    high = gaussian.max()

    thinkplot.preplot(cols=2)
    thinkplot.plot(gaussian)
    thinkplot.config(xlabel='Index',
                     ylabel='Window',
                     xlim=[0, len(gaussian) - 1],
                     ylim=[0, 1.1 * high])

    ys = np.convolve(wave.ys, gaussian, mode='same')
    smooth = thinkdsp.Wave(ys, framerate=wave.framerate)
    spectrum2 = smooth.make_spectrum()

    # plot the ratio of the original and smoothed spectrum
    amps = spectrum.amps
    amps2 = spectrum2.amps
    ratio = amps2 / amps
    ratio[amps < 560] = 0

    # plot the same ratio along with the FFT of the window
    padded = thinkdsp.zero_pad(gaussian, len(wave))
    dft_gaussian = np.fft.rfft(padded)

    thinkplot.subplot(2)
    thinkplot.plot(abs(dft_gaussian), color=GRAY, label='Gaussian filter')
    thinkplot.plot(ratio, label='amplitude ratio')

    thinkplot.show(xlabel='Frequency (Hz)',
                   ylabel='Amplitude ratio',
                   xlim=[0, 22050],
                   ylim=[0, 1.05])
Esempio n. 25
0
def f0(frame, audiofile):
    #create a 'spectrum' list for the frame consisting of frequency/amplitude pairs
    clip = td.Wave(frame)
    spectrum = clip.make_spectrum()

    # to find F0 we can sort by Hz, unfortunately we have small readings at 0.0Hz
    # and other small frequencies which make finding the true F0 hard
    # remove the small amplitudes which don't well describe the energy in the sound.

    # What is small is likely to be relative to the largest amplitude so use some threshold
    threshold = 0.5

    #the pairs are sorted by amplitude, take the amplitude of the first pair as the greatest amplitude.
    greatest_amp = (spectrum.peaks()[0])[0]
    #a counter will be used to iterate over the positions of the list
    list_pos = 0
    #the pairs with amplitudes which are within the threshold will be copied to a new list
    selected_pairs = []
    while True:
        #select the next pair from the list
        pair = (spectrum.peaks()[list_pos])
        #test whether the pair's amplitude is within the threshold
        within_threshold = (pair[0] > (greatest_amp * threshold))
        #if not within the threshold the loop can break as all followings pairs will have lower amplitudes
        if within_threshold == False:
            break
        #if within the threshold add the pair to the list
        selected_pairs.append(pair)
        #increment the counter for the loop
        list_pos = list_pos + 1

    # selected_pairs is now a list of the pairs which have a prominent amplitude
    sorted_by_Hz = sorted(selected_pairs, key=lambda tup: tup[1])
    # the lowest Hz should now be F0
    if len(sorted_by_Hz) == 0:
        return [0]
    else:
        return [sorted_by_Hz[0][1]]
ys = segment.ys
N = len(ys)
padded = thinkdsp.zero_pad(window, N)

# In[6]:

prod = padded * ys

# In[7]:

sum(ys)

# In[8]:

convolved = np.convolve(ys, window, mode='valid')
smooth2 = thinkdsp.Wave(convolved, framerate=wave.framerate)
smooth2

# In[9]:

spectrum = wave.make_spectrum()
spectrum.plot(color='GRAY')

# In[10]:

convolved = np.convolve(wave.ys, window, mode='same')
smooth = thinkdsp.Wave(convolved, framerate=wave.framerate)
spectrum2 = smooth.make_spectrum()
spectrum2.plot()

# In[11]:
Esempio n. 27
0
''' Get Emerson wave form data '''
wave_data = getEmersonWaveFormData(filePath)
''' Get Waveform parameters from Emerson data JSON'''
wave_JSON = wave_data['signal']
dt_JSON = float(wave_data['deltaTime'])
timeStamp_JSON = float(wave_data['timestamp'])
N_wave_JSON = wave_data['len']
''' Calculated parameters'''
fs = 1 / dt_JSON
duration = N_wave_JSON * dt_JSON
''' creating linear time vector to create a wave object'''
t = np.linspace(0, duration, N_wave_JSON, endpoint=False)
'''=========================  Band-pass filter   =================================='''
'''====================================================================================='''
''' Creating a Wave object'''
raw_wave = thinkdsp.Wave(ys=wave_JSON, ts=t, framerate=fs)
''' working with the wave object'''
raw_wave.unbias()
raw_wave.normalize()
raw_wave.window(np.hanning(len(wave_JSON)))  # windowing = Hanning
''' Creating a spectrum object from a wave object'''
raw_spectrum = raw_wave.make_spectrum()
''' Filtering'''
raw_spectrum.high_pass(400)
raw_wave_filtered = raw_spectrum.make_wave()
filtered_signal = raw_wave_filtered.ys
''' Signal Enveloping using hilbert transform'''

analytic_signal = hilbert(filtered_signal)
amplitude_envelope = np.abs(analytic_signal)
instantaneous_phase = np.unwrap(np.angle(analytic_signal))
Esempio n. 28
0
def stretch(wave, stretch_factor):
    return thinkdsp.Wave(wave.ys,
                         wave.ts / stretch_factor,
                         framerate=wave.framerate * stretch_factor)
def demodulate_steps(wave):
    '''
    show the 8 plots of the demodulation process

    :param wave: thinkdsp.Wave object
    :return:
    '''

    # create a copy of the original wave
    raw_wave = wave.copy()

    # create a figure
    fig = plt.figure()

    # create a subplot
    ax = fig.add_subplot(421)
    # plot a segment of the raw_wave
    raw_wave_segment = raw_wave.segment(0, 0.1)
    raw_wave_segment.plot(label='raw wave', color='b')
    # show legend label
    ax.legend()

    # make a spectrum from test wave
    raw_spectrum = raw_wave.make_spectrum(full=False)

    # create another subplot
    ax = fig.add_subplot(422)
    # plot the raw spectrum
    raw_spectrum.plot(label='raw spectrum', color='g')
    # show legend label
    ax.legend()

    # apply a high pass filter at 2kHz to the raw spectrum
    raw_spectrum_filtered = raw_spectrum.copy()
    raw_spectrum_filtered.high_pass(2000)

    # create another subplot
    ax = fig.add_subplot(424)
    # plot the raw spectrum
    raw_spectrum_filtered.plot(label='high pass', color='r')
    # show legend label
    ax.legend()

    # make a time waveform from the filtered spectrum
    raw_wave_filtered = raw_spectrum_filtered.make_wave()
    # apply hanning windowing to the result waveform
    raw_wave_filtered.window(np.hanning(len(raw_wave_filtered)))

    # create another subplot
    ax = fig.add_subplot(423)
    # plot the raw spectrum
    raw_wave_filtered_segment = raw_wave_filtered.segment(0, 0.01)
    raw_wave_filtered.plot(label='high pass', color='c')
    # show legend label
    ax.legend()

    # obtain the envelop of the result waveform
    raw_wave_filtered_envelop = thinkdsp.Wave(
        ys=np.abs(hilbert(raw_wave_filtered.ys)),
        ts=raw_wave_filtered.ts,
        framerate=raw_wave_filtered.framerate)

    # create another subplot
    ax = fig.add_subplot(425)
    # plot the raw spectrum
    raw_wave_filtered_envelop_segment = raw_wave_filtered_envelop.segment(
        0, 0.01)
    raw_wave_filtered_envelop.plot(label='envelop', color='m')
    # show legend label
    ax.legend()

    # obtain the spectrum from the envelop
    raw_spectrum_filtered_envelop = raw_wave_filtered_envelop.make_spectrum(
        full=False)

    # create another subplot
    ax = fig.add_subplot(426)
    # plot the raw spectrum
    raw_spectrum_filtered_envelop.plot(label='envelop', color='y')
    # show legend label
    ax.legend()

    # color option = one of these {'b', 'g', 'r', 'c', 'm', 'y', 'k', 'w'}
    # show plot
    plt.show()
Esempio n. 30
0
def plot_boxcar():
    """Makes a plot showing the effect of convolution with a boxcar window.
    """
    # start with a square signal
    signal = thinkdsp.SquareSignal(freq=440)
    wave = signal.make_wave(duration=1, framerate=44100)

    # and a boxcar window
    window = numpy.ones(11)
    window /= sum(window)

    # select a short segment of the wave
    segment = wave.segment(duration=0.01)

    # and pad with window out to the length of the array
    padded = zero_pad(window, len(segment))

    # compute the first element of the smoothed signal
    prod = padded * segment.ys
    print(sum(prod))

    # compute the rest of the smoothed signal
    smoothed = numpy.zeros_like(segment.ys)
    rolled = padded
    for i in range(len(segment.ys)):
        smoothed[i] = sum(rolled * segment.ys)
        rolled = numpy.roll(rolled, 1)

    # plot the results
    segment.plot(color='0.7')
    smooth = thinkdsp.Wave(smoothed, framerate=wave.framerate)
    smooth.plot()
    thinkplot.config(ylim=[-1.05, 1.05], legend=False)
    thinkplot.save(root='convolution2')

    # compute the same thing using numpy.convolve
    segment.plot(color='0.7')
    ys = numpy.convolve(segment.ys, window, mode='valid')
    smooth2 = thinkdsp.Wave(ys, framerate=wave.framerate)
    smooth2.plot()
    thinkplot.config(ylim=[-1.05, 1.05], legend=False)
    thinkplot.save(root='convolution3')

    # plot the spectrum before and after smoothing
    spectrum = wave.make_spectrum()
    spectrum.plot(color='0.7')

    ys = numpy.convolve(wave.ys, window, mode='same')
    smooth = thinkdsp.Wave(ys, framerate=wave.framerate)
    spectrum2 = smooth.make_spectrum()
    spectrum2.plot()
    thinkplot.config(xlabel='frequency (Hz)',
                     ylabel='amplitude',
                     xlim=[0, 22050],
                     legend=False)
    thinkplot.save(root='convolution4')

    # plot the ratio of the original and smoothed spectrum
    amps = spectrum.amps
    amps2 = spectrum2.amps
    ratio = amps2 / amps
    ratio[amps < 560] = 0
    thinkplot.plot(ratio)

    thinkplot.config(xlabel='frequency (Hz)',
                     ylabel='amplitude ratio',
                     xlim=[0, 22050],
                     legend=False)
    thinkplot.save(root='convolution5')

    # plot the same ratio along with the FFT of the window
    padded = zero_pad(window, len(wave))
    dft_window = numpy.fft.rfft(padded)

    thinkplot.plot(abs(dft_window), color='0.7', label='boxcar filter')
    thinkplot.plot(ratio, label='amplitude ratio')

    thinkplot.config(xlabel='frequency (Hz)',
                     ylabel='amplitude ratio',
                     xlim=[0, 22050],
                     legend=False)
    thinkplot.save(root='convolution6')