Example #1
0
def plot_derivative(wave, wave2):
    # compute the derivative by spectral decomposition
    spectrum = wave.make_spectrum()
    spectrum3 = wave.make_spectrum()
    spectrum3.differentiate()

    # plot the derivative computed by diff and differentiate
    wave3 = spectrum3.make_wave()
    wave2.plot(color="0.7", label="diff")
    wave3.plot(label="derivative")
    thinkplot.config(xlabel="days", xlim=[0, 1650], ylabel="dollars", loc="upper left")

    thinkplot.save(root="systems4")

    # plot the amplitude ratio compared to the diff filter
    amps = spectrum.amps
    amps3 = spectrum3.amps
    ratio3 = amps3 / amps

    thinkplot.preplot(1)
    thinkplot.plot(ratio3, label="ratio")

    window = numpy.array([1.0, -1.0])
    padded = zero_pad(window, len(wave))
    fft_window = numpy.fft.rfft(padded)
    thinkplot.plot(abs(fft_window), color="0.7", label="filter")

    thinkplot.config(
        xlabel="frequency (1/days)", xlim=[0, 1650 / 2], ylabel="amplitude ratio", ylim=[0, 4], loc="upper left"
    )
    thinkplot.save(root="systems5")
def triangle_example(freq):
    """Makes a figure showing a triangle wave.

    freq: frequency in Hz
    """
    framerate = 10000
    signal = thinkdsp.TriangleSignal(freq)

    duration = signal.period * 3
    segment = signal.make_wave(duration, framerate=framerate)
    segment.plot()
    thinkplot.save(root='triangle-%d-1' % freq,
                   xlabel='Time (s)',
                   axis=[0, duration, -1.05, 1.05])

    wave = signal.make_wave(duration=0.5, framerate=framerate)
    spectrum = wave.make_spectrum()

    thinkplot.preplot(cols=2)
    spectrum.plot()
    thinkplot.config(xlabel='Frequency (Hz)', ylabel='Amplitude')

    thinkplot.subplot(2)
    spectrum.plot()
    thinkplot.config(ylim=[0, 500], xlabel='Frequency (Hz)')

    thinkplot.save(root='triangle-%d-2' % freq)
Example #3
0
def plot_amen2():
    wave = thinkdsp.read_wave('263868__kevcio__amen-break-a-160-bpm.wav')
    wave.normalize()

    ax1 = thinkplot.preplot(6, rows=4)
    wave.make_spectrum(full=True).plot(label='spectrum')
    xlim = [-22050 - 250, 22050]
    thinkplot.config(xlim=xlim, xticklabels='invisible')

    ax2 = thinkplot.subplot(2)
    impulses = make_impulses(wave, 4)
    impulses.make_spectrum(full=True).plot(label='impulses')
    thinkplot.config(xlim=xlim, xticklabels='invisible')

    ax3 = thinkplot.subplot(3)
    sampled = wave * impulses
    spectrum = sampled.make_spectrum(full=True)
    spectrum.plot(label='sampled')
    thinkplot.config(xlim=xlim, xticklabels='invisible')

    ax4 = thinkplot.subplot(4)
    spectrum.low_pass(5512.5)
    spectrum.plot(label='filtered')
    thinkplot.config(xlim=xlim, xlabel='Frequency (Hz)')

    thinkplot.save(root='sampling4', formats=FORMATS)
Example #4
0
def plot_convolution():
    response = thinkdsp.read_wave('180961__kleeb__gunshots.wav')
    response = response.segment(start=0.26, duration=5.0)
    response.normalize()

    dt = 1
    shift = dt * response.framerate
    factor = 0.5

    gun2 = response + shifted_scaled(response, shift, factor)
    gun2.plot()
    thinkplot.config(xlabel='time (s)',
                     ylabel='amplitude',
                     ylim=[-1.05, 1.05],
                     legend=False)
    thinkplot.save(root='systems8')

    signal = thinkdsp.SawtoothSignal(freq=410)
    wave = signal.make_wave(duration=0.1, framerate=response.framerate)

    total = 0
    for j, y in enumerate(wave.ys):
        total += shifted_scaled(response, j, y)

    total.normalize()

    wave.make_spectrum().plot(high=500, color='0.7', label='original')
    segment = total.segment(duration=0.2)
    segment.make_spectrum().plot(high=1000, label='convolved')
    thinkplot.config(xlabel='frequency (Hz)', ylabel='amplitude')
    thinkplot.save(root='systems9')
Example #5
0
def plot_sines():
    """Makes figures showing correlation of sine waves with offsets.
    """
    wave1 = make_wave(0)
    wave2 = make_wave(offset=1)

    thinkplot.preplot(2)
    wave1.segment(duration=0.01).plot(label='wave1')
    wave2.segment(duration=0.01).plot(label='wave2')

    corr_matrix = numpy.corrcoef(wave1.ys, wave2.ys, ddof=0)
    print(corr_matrix)

    thinkplot.save(root='autocorr1',
                   xlabel='time (s)',
                   ylabel='amplitude',
                   ylim=[-1.05, 1.05])

    offsets = numpy.linspace(0, PI2, 101)

    corrs = []
    for offset in offsets:
        wave2 = make_wave(offset)
        corr = corrcoef(wave1.ys, wave2.ys)
        corrs.append(corr)

    thinkplot.plot(offsets, corrs)
    thinkplot.save(root='autocorr2',
                   xlabel='offset (radians)',
                   ylabel='correlation',
                   xlim=[0, PI2],
                   ylim=[-1.05, 1.05])
Example #6
0
def single_plot(dfs):
    """Make the plot.
    """
    for i, age_group in enumerate(age_groups):
        print(i, age_group)
        series = [df.loc[age_group] for df in dfs]
        models = [fit_row(s).fittedvalues for s in series]
        xs = series[0].index + 2

        rows = thinkstats2.PercentileRows(models, [5, 95])
        thinkplot.fill_between(xs,
                               rows[0],
                               rows[1],
                               color=colors[i],
                               alpha=0.3)

        rows = thinkstats2.PercentileRows(series, [50])
        thinkplot.plot(xs,
                       rows[0],
                       label=labels[i],
                       color=colors[i],
                       alpha=0.6)

    thinkplot.config(xlabel=xlabel, ylabel=ylabel, loc='upper left', axis=axis)
    plt.gca().get_legend().set(title='Age group')
    thinkplot.save(root='age_religion2')
Example #7
0
def plot_response():
    thinkplot.preplot(cols=2)

    response = thinkdsp.read_wave('180961__kleeb__gunshots.wav')
    response = response.segment(start=0.26, duration=5.0)
    response.normalize()
    response.plot()
    thinkplot.config(xlabel='time',
                     xlim=[0, 5.0],
                     ylabel='amplitude',
                     ylim=[-1.05, 1.05])

    thinkplot.subplot(2)
    transfer = response.make_spectrum()
    transfer.plot()
    thinkplot.config(xlabel='frequency', xlim=[0, 22500], ylabel='amplitude')

    thinkplot.save(root='systems6')

    wave = thinkdsp.read_wave('92002__jcveliz__violin-origional.wav')
    wave.ys = wave.ys[:len(response)]
    wave.normalize()
    spectrum = wave.make_spectrum()

    output = (spectrum * transfer).make_wave()
    output.normalize()

    wave.plot(color='0.7')
    output.plot(alpha=0.4)
    thinkplot.config(xlabel='time',
                     xlim=[0, 5.0],
                     ylabel='amplitude',
                     ylim=[-1.05, 1.05])
    thinkplot.save(root='systems7')
Example #8
0
def plot_facebook():
    """Plot Facebook prices and a smoothed time series.
    """
    names = ['date', 'open', 'high', 'low', 'close', 'volume']
    df = pd.read_csv('fb.csv', header=0, names=names, parse_dates=[0])
    close = df.close.values[::-1]
    dates = df.date.values[::-1]
    days = (dates - dates[0]) / np.timedelta64(1,'D')

    M = 30
    window = np.ones(M)
    window /= sum(window)
    smoothed = np.convolve(close, window, mode='valid')
    smoothed_days = days[M//2: len(smoothed) + M//2]
    
    thinkplot.plot(days, close, color=GRAY, label='daily close')
    thinkplot.plot(smoothed_days, smoothed, label='30 day average')
    
    last = days[-1]
    thinkplot.config(xlabel='Time (days)', 
                     ylabel='Price ($)',
                     xlim=[-7, last+7],
                     legend=True,
                     loc='lower right')
    thinkplot.save(root='convolution1')
Example #9
0
def segment_spectrum(filename, start, duration=1.0):
    """Plots the spectrum of a segment of a WAV file.

    Output file names are the given filename plus a suffix.

    filename: string
    start: start time in s
    duration: segment length in s
    """
    wave = thinkdsp.read_wave(filename)
    plot_waveform(wave)

    # extract a segment
    segment = wave.segment(start, duration)
    segment.ys = segment.ys[:1024]
    print len(segment.ys)

    segment.normalize()
    segment.apodize()
    spectrum = segment.make_spectrum()

    segment.play()

    # plot the spectrum
    n = len(spectrum.hs)
    spectrum.plot()

    thinkplot.save(root=filename,
                   xlabel='frequency (Hz)',
                   ylabel='amplitude density')
Example #10
0
def plot_pink_noise():
    """Makes a plot showing power spectrums for pink noise.
    """
    thinkdsp.random_seed(20)

    duration = 1.0
    framerate = 512

    signal = thinkdsp.UncorrelatedUniformNoise()
    wave = signal.make_wave(duration=duration, framerate=framerate)
    white = wave.make_spectrum()

    signal = thinkdsp.PinkNoise()
    wave = signal.make_wave(duration=duration, framerate=framerate)
    pink = wave.make_spectrum()

    signal = thinkdsp.BrownianNoise()
    wave = signal.make_wave(duration=duration, framerate=framerate)
    red = wave.make_spectrum()

    linewidth = 1
    white.plot_power(low=1, label='white', color='gray', linewidth=linewidth)
    pink.plot_power(low=1, label='pink', color='pink', linewidth=linewidth)
    red.plot_power(low=1, label='red', color='red', linewidth=linewidth)
    thinkplot.save(root='noise-triple',
                   xlabel='frequency (Hz)',
                   ylabel='power',
                   xscale='log',
                   yscale='log',
                   axis=[1, 300, 1e-4, 1e5])
Example #11
0
def plot_beeps():
    wave = thinkdsp.read_wave('253887__themusicalnomad__positive-beeps.wav')
    wave.normalize()

    thinkplot.preplot(3)

    # top left
    ax1 = plt.subplot2grid((4, 2), (0, 0), rowspan=2)
    plt.setp(ax1.get_xticklabels(), visible=False)

    wave.plot()
    thinkplot.config(title='Input waves', legend=False)

    # bottom left
    imp_sig = thinkdsp.Impulses([0.01, 0.4, 0.8, 1.2],
                                amps=[1, 0.5, 0.25, 0.1])
    impulses = imp_sig.make_wave(start=0,
                                 duration=1.3,
                                 framerate=wave.framerate)

    ax2 = plt.subplot2grid((4, 2), (2, 0), rowspan=2, sharex=ax1)
    impulses.plot()
    thinkplot.config(xlabel='Time (s)')

    # center right
    convolved = wave.convolve(impulses)

    ax3 = plt.subplot2grid((4, 2), (1, 1), rowspan=2)
    plt.title('Convolution')
    convolved.plot()
    thinkplot.config(xlabel='Time (s)')

    thinkplot.save(root='sampling1', formats=FORMATS, legend=False)
Example #12
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')
Example #13
0
def dct_plot():
    signal = thinkdsp.TriangleSignal(freq=400)
    wave = signal.make_wave(duration=1.0, framerate=10000)
    dct = wave.make_dct()
    dct.plot()
    thinkplot.config(xlabel='Frequency (Hz)', ylabel='DCT')
    thinkplot.save(root='dct1', formats=['pdf', 'eps'])
Example #14
0
def plot_amen2():
    wave = thinkdsp.read_wave('263868__kevcio__amen-break-a-160-bpm.wav')
    wave.normalize()

    ax1 = thinkplot.preplot(6, rows=4)
    wave.make_spectrum(full=True).plot(label='spectrum')
    xlim = [-22050-250, 22050]
    thinkplot.config(xlim=xlim, xticklabels='invisible')

    ax2 = thinkplot.subplot(2)
    impulses = make_impulses(wave, 4)
    impulses.make_spectrum(full=True).plot(label='impulses')
    thinkplot.config(xlim=xlim, xticklabels='invisible')

    ax3 = thinkplot.subplot(3)
    sampled = wave * impulses
    spectrum = sampled.make_spectrum(full=True)
    spectrum.plot(label='sampled')
    thinkplot.config(xlim=xlim, xticklabels='invisible')

    ax4 = thinkplot.subplot(4)
    spectrum.low_pass(5512.5)
    spectrum.plot(label='filtered')
    thinkplot.config(xlim=xlim, xlabel='Frequency (Hz)')

    thinkplot.save(root='sampling4',
                   formats=FORMATS)
Example #15
0
def triangle_example(freq):
    """Makes a figure showing a triangle wave.

    freq: frequency in Hz
    """
    framerate = 10000
    signal = thinkdsp.TriangleSignal(freq)

    duration = signal.period*3
    segment = signal.make_wave(duration, framerate=framerate)
    segment.plot()
    thinkplot.save(root='triangle-%d-1' % freq,
                   xlabel='Time (s)',
                   axis=[0, duration, -1.05, 1.05])

    wave = signal.make_wave(duration=0.5, framerate=framerate)
    spectrum = wave.make_spectrum()

    thinkplot.preplot(cols=2)
    spectrum.plot()
    thinkplot.config(xlabel='Frequency (Hz)',
                     ylabel='Amplitude')

    thinkplot.subplot(2)
    spectrum.plot()
    thinkplot.config(ylim=[0, 500],
                     xlabel='Frequency (Hz)')
    
    thinkplot.save(root='triangle-%d-2' % freq)
Example #16
0
def aliasing_example(offset=0.000003):
    """Makes a figure showing the effect of aliasing.
    """
    framerate = 10000

    def plot_segment(freq):
        signal = thinkdsp.CosSignal(freq)
        duration = signal.period*4
        thinkplot.Hlines(0, 0, duration, color='gray')
        segment = signal.make_wave(duration, framerate=framerate*10)
        segment.plot(linewidth=0.5, color='gray')
        segment = signal.make_wave(duration, framerate=framerate)
        segment.plot_vlines(label=freq, linewidth=4)

    thinkplot.preplot(rows=2)
    plot_segment(4500)
    thinkplot.config(axis=[-0.00002, 0.0007, -1.05, 1.05])

    thinkplot.subplot(2)
    plot_segment(5500)
    thinkplot.config(axis=[-0.00002, 0.0007, -1.05, 1.05])

    thinkplot.save(root='aliasing1',
                   xlabel='Time (s)',
                   formats=FORMATS)
Example #17
0
def plot_pink_noise():
    """Makes a plot showing power spectrums for pink noise.
    """
    thinkdsp.random_seed(20)

    duration = 1.0
    framerate = 512

    def make_spectrum(signal):
        wave = signal.make_wave(duration=duration, framerate=framerate)
        spectrum = wave.make_spectrum()
        spectrum.hs[0] = 0
        return spectrum

    signal = thinkdsp.UncorrelatedUniformNoise()
    white = make_spectrum(signal)

    signal = thinkdsp.PinkNoise()
    pink = make_spectrum(signal)

    signal = thinkdsp.BrownianNoise()
    red = make_spectrum(signal)

    linewidth = 2
    # colorbrewer2.org 4-class sequential OrRd
    white.plot_power(label='white', color='#fdcc8a', linewidth=linewidth)
    pink.plot_power(label='pink', color='#fc8d59', linewidth=linewidth)
    red.plot_power(label='red', color='#d7301f', linewidth=linewidth)
    thinkplot.save(root='noise-triple',
                   xlabel='Frequency (Hz)',
                   ylabel='Power',
                   xscale='log',
                   yscale='log',
                   xlim=[1, red.fs[-1]])
Example #18
0
def aliasing_example(offset=0.000003):
    """Makes a figure showing the effect of aliasing.
    """
    framerate = 10000
    thinkplot.preplot(num=2)

    freq1 = 4500
    signal = thinkdsp.CosSignal(freq1)
    duration = signal.period*5
    segment = signal.make_wave(duration, framerate=framerate)
    thinkplot.Hlines(0, 0, duration, color='gray')

    segment.shift(-offset)
    segment.plot_vlines(label=freq1, linewidth=3)

    freq2 = 5500
    signal = thinkdsp.CosSignal(freq2)
    segment = signal.make_wave(duration, framerate=framerate)
    segment.shift(+offset)
    segment.plot_vlines(label=freq2, linewidth=3)

    thinkplot.save(root='aliasing1',
                   xlabel='Time (s)',
                   axis=[-0.00002, duration, -1.05, 1.05]
                   )
Example #19
0
def three_spectrums():
    """Makes a plot showing three spectrums for a sinusoid.
    """
    thinkplot.preplot(rows=1, cols=3)

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

    xticks = range(0, 900, 200)

    thinkplot.subplot(1)
    thinkplot.config(xticks=xticks)
    discontinuity(num_periods=30, hamming=False)

    thinkplot.subplot(2)
    thinkplot.config(xticks=xticks)
    discontinuity(num_periods=30.25, hamming=False)

    thinkplot.subplot(3)
    thinkplot.config(xticks=xticks)
    discontinuity(num_periods=30.25, hamming=True)

    thinkplot.save(root='windowing1')
Example #20
0
def plot_filters(close):
    """Plots the filter that corresponds to diff, deriv, and integral.
    """
    thinkplot.preplot(3, cols=2)

    diff_window = np.array([1.0, -1.0])
    diff_filter = make_filter(diff_window, close)
    diff_filter.plot(label='diff')

    deriv_filter = close.make_spectrum()
    deriv_filter.hs = PI2 * 1j * deriv_filter.fs
    deriv_filter.plot(label='derivative')

    thinkplot.config(xlabel='Frequency (1/day)',
                     ylabel='Amplitude ratio',
                     loc='upper left')

    thinkplot.subplot(2)
    integ_filter = deriv_filter.copy()
    integ_filter.hs = 1 / (PI2 * 1j * integ_filter.fs)

    integ_filter.plot(label='integral')
    thinkplot.config(xlabel='Frequency (1/day)',
                     ylabel='Amplitude ratio',
                     yscale='log')
    thinkplot.save('diff_int3')
Example #21
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')
Example #22
0
def plot_pink_noise():
    """Makes a plot showing power spectrums for pink noise.
    """
    thinkdsp.random_seed(20)

    duration = 1.0
    framerate = 512

    signal = thinkdsp.UncorrelatedUniformNoise()
    wave = signal.make_wave(duration=duration, framerate=framerate)
    white = wave.make_spectrum()

    signal = thinkdsp.PinkNoise()
    wave = signal.make_wave(duration=duration, framerate=framerate)
    pink = wave.make_spectrum()

    signal = thinkdsp.BrownianNoise()
    wave = signal.make_wave(duration=duration, framerate=framerate)
    red = wave.make_spectrum()

    linewidth = 1
    white.plot_power(low=1, label='white', color='gray', linewidth=linewidth)
    pink.plot_power(low=1, label='pink', color='pink', linewidth=linewidth)
    red.plot_power(low=1, label='red', color='red', linewidth=linewidth)
    thinkplot.save(root='noise-triple',
                   xlabel='frequency (Hz)',
                   ylabel='power',
                   xscale='log',
                   yscale='log',
                   axis=[1, 300, 1e-4, 1e5])
Example #23
0
def main():
    
    # make_figures()

    wave = thinkdsp.read_wave('28042__bcjordan__voicedownbew.wav')
    wave.unbias()
    wave.normalize()
    track_pitch(wave)

    
    return


    thinkplot.preplot(rows=1, cols=2)
    plot_shifted(wave, 0.0003)
    thinkplot.config(xlabel='time (s)',
                     ylabel='amplitude',
                     ylim=[-1, 1])

    thinkplot.subplot(2)
    plot_shifted(wave, 0.00225)
    thinkplot.config(xlabel='time (s)',
                     ylim=[-1, 1])

    thinkplot.save(root='autocorr3')
Example #24
0
def make_figures():

    wave1 = make_wave(0)
    wave2 = make_wave(offset=1)

    thinkplot.preplot(2)
    wave1.segment(duration=0.01).plot(label='wave1')
    wave2.segment(duration=0.01).plot(label='wave2')

    numpy.corrcoef(wave1.ys, wave2.ys)

    thinkplot.save(root='autocorr1',
                   xlabel='time (s)',
                   ylabel='amplitude')


    offsets = numpy.linspace(0, PI2, 101)

    corrs = []
    for offset in offsets:
        wave2 = make_wave(offset)
        corr = numpy.corrcoef(wave1.ys, wave2.ys)[0, 1]
        corrs.append(corr)
    
    thinkplot.plot(offsets, corrs)
    thinkplot.save(root='autocorr2',
                   xlabel='offset (radians)',
                   ylabel='correlation',
                   xlim=[0, PI2])
Example #25
0
def plot_beeps():
    wave = thinkdsp.read_wave('253887__themusicalnomad__positive-beeps.wav')
    wave.normalize()

    thinkplot.preplot(3)

    # top left
    ax1 = plt.subplot2grid((4, 2), (0, 0), rowspan=2)
    plt.setp(ax1.get_xticklabels(), visible=False)

    wave.plot()
    thinkplot.config(title='Input waves', legend=False)

    # bottom left
    imp_sig = thinkdsp.Impulses([0.01, 0.4, 0.8, 1.2], 
                                amps=[1, 0.5, 0.25, 0.1])
    impulses = imp_sig.make_wave(start=0, duration=1.3, 
                                 framerate=wave.framerate)

    ax2 = plt.subplot2grid((4, 2), (2, 0), rowspan=2, sharex=ax1)
    impulses.plot()
    thinkplot.config(xlabel='Time (s)')

    # center right
    convolved = wave.convolve(impulses)

    ax3 = plt.subplot2grid((4, 2), (1, 1), rowspan=2)
    plt.title('Convolution')
    convolved.plot()
    thinkplot.config(xlabel='Time (s)')

    thinkplot.save(root='sampling1',
                   formats=FORMATS,
                   legend=False)
Example #26
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')
Example #27
0
def plot_facebook():
    """Plot Facebook prices and a smoothed time series.
    """
    names = ['date', 'open', 'high', 'low', 'close', 'volume']
    df = pd.read_csv('fb.csv', header=0, names=names, parse_dates=[0])
    close = df.close.values[::-1]
    dates = df.date.values[::-1]
    days = (dates - dates[0]) / np.timedelta64(1,'D')

    M = 30
    window = np.ones(M)
    window /= sum(window)
    smoothed = np.convolve(close, window, mode='valid')
    smoothed_days = days[M//2: len(smoothed) + M//2]
    
    thinkplot.plot(days, close, color=GRAY, label='daily close')
    thinkplot.plot(smoothed_days, smoothed, label='30 day average')
    
    last = days[-1]
    thinkplot.config(xlabel='Time (days)', 
                     ylabel='Price ($)',
                     xlim=[-7, last+7],
                     legend=True,
                     loc='lower right')
    thinkplot.save(root='convolution1')
Example #28
0
def segment_spectrum(filename, start, duration=1.0):
    """Plots the spectrum of a segment of a WAV file.

    Output file names are the given filename plus a suffix.

    filename: string
    start: start time in s
    duration: segment length in s
    """
    wave = thinkdsp.read_wave(filename)
    plot_waveform(wave)

    # extract a segment
    segment = wave.segment(start, duration)
    segment.ys = segment.ys[:1024]
    print len(segment.ys)

    segment.normalize()
    segment.apodize()
    spectrum = segment.make_spectrum()

    segment.play()

    # plot the spectrum
    n = len(spectrum.hs)
    spectrum.plot()

    thinkplot.save(root=filename,
                   xlabel='frequency (Hz)',
                   ylabel='amplitude density')
Example #29
0
def chirp_spectrum():
    """Plots the spectrum of a one-second one-octave linear chirp.
    """
    signal = thinkdsp.Chirp(start=220, end=440)
    wave = signal.make_wave(duration=1)

    thinkplot.preplot(3, cols=3)
    duration = 0.01
    wave.segment(0, duration).plot()
    thinkplot.config(ylim=[-1.05, 1.05])

    thinkplot.subplot(2)
    wave.segment(0.5, duration).plot()
    thinkplot.config(yticklabels='invisible',
                     xlabel='Time (s)')

    thinkplot.subplot(3)
    wave.segment(0.9, duration).plot()
    thinkplot.config(yticklabels='invisible')

    thinkplot.save('chirp3')


    spectrum = wave.make_spectrum()
    spectrum.plot(high=700)
    thinkplot.save('chirp1',
                   xlabel='Frequency (Hz)',
                   ylabel='Amplitude')
Example #30
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 = np.hamming(len(wave1.ys))
    ts = wave1.ts
    window = thinkdsp.Wave(ys, ts, 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')
def plot_sines():
    """Makes figures showing correlation of sine waves with offsets.
    """
    wave1 = make_wave(0)
    wave2 = make_wave(offset=1)

    thinkplot.preplot(2)
    wave1.segment(duration=0.01).plot(label='wave1')
    wave2.segment(duration=0.01).plot(label='wave2')

    corr_matrix = numpy.corrcoef(wave1.ys, wave2.ys, ddof=0)
    print(corr_matrix)

    thinkplot.save(root='autocorr1',
                   xlabel='time (s)',
                   ylabel='amplitude',
                   ylim=[-1.05, 1.05])


    offsets = numpy.linspace(0, PI2, 101)

    corrs = []
    for offset in offsets:
        wave2 = make_wave(offset)
        corr = corrcoef(wave1.ys, wave2.ys)
        corrs.append(corr)
    
    thinkplot.plot(offsets, corrs)
    thinkplot.save(root='autocorr2',
                   xlabel='offset (radians)',
                   ylabel='correlation',
                   xlim=[0, PI2],
                   ylim=[-1.05, 1.05])
Example #32
0
def plot_filters(close):
    """Plots the filter that corresponds to diff, deriv, and integral.
    """
    thinkplot.preplot(3, cols=2)

    diff_window = np.array([1.0, -1.0])
    diff_filter = make_filter(diff_window, close)
    diff_filter.plot(label='diff')

    deriv_filter = close.make_spectrum()
    deriv_filter.hs = PI2 * 1j * deriv_filter.fs
    deriv_filter.plot(label='derivative')

    thinkplot.config(xlabel='Frequency (1/day)',
                     ylabel='Amplitude ratio',
                     loc='upper left')

    thinkplot.subplot(2)
    integ_filter = deriv_filter.copy()
    integ_filter.hs = 1 / (PI2 * 1j * integ_filter.fs)

    integ_filter.plot(label='integral')
    thinkplot.config(xlabel='Frequency (1/day)',
                     ylabel='Amplitude ratio', 
                     yscale='log')
    thinkplot.save('diff_int3')
Example #33
0
def chirp_spectrum():
    """Plots the spectrum of a one-second one-octave linear chirp.
    """
    signal = thinkdsp.Chirp(start=220, end=440)
    wave = signal.make_wave(duration=1)

    thinkplot.preplot(3, cols=3)
    duration = 0.01
    wave.segment(0, duration).plot()
    thinkplot.config(ylim=[-1.05, 1.05])

    thinkplot.subplot(2)
    wave.segment(0.5, duration).plot()
    thinkplot.config(yticklabels='invisible',
                     xlabel='Time (s)')

    thinkplot.subplot(3)
    wave.segment(0.9, duration).plot()
    thinkplot.config(yticklabels='invisible')

    thinkplot.save('chirp3')


    spectrum = wave.make_spectrum()
    spectrum.plot(high=700)
    thinkplot.save('chirp1',
                   xlabel='Frequency (Hz)')
Example #34
0
def plot_pink_noise():
    """Makes a plot showing power spectrums for pink noise.
    """
    thinkdsp.random_seed(20)

    duration = 1.0
    framerate = 512

    def make_spectrum(signal):
        wave = signal.make_wave(duration=duration, framerate=framerate)
        spectrum = wave.make_spectrum()
        spectrum.hs[0] = 0
        return spectrum

    signal = thinkdsp.UncorrelatedUniformNoise()
    white = make_spectrum(signal)

    signal = thinkdsp.PinkNoise()
    pink = make_spectrum(signal)

    signal = thinkdsp.BrownianNoise()
    red = make_spectrum(signal)

    linewidth = 2
    white.plot_power(label='white', color='#9ecae1', linewidth=linewidth)
    pink.plot_power(label='pink', color='#4292c6', linewidth=linewidth)
    red.plot_power(label='red', color='#2171b5', linewidth=linewidth)
    thinkplot.save(root='noise-triple',
                   xlabel='Frequency (Hz)',
                   ylabel='Power',
                   xscale='log',
                   yscale='log',
                   xlim=[1, red.fs[-1]])
Example #35
0
def plot_convolution():
    response = thinkdsp.read_wave("180961__kleeb__gunshots.wav")
    response = response.segment(start=0.26, duration=5.0)
    response.normalize()

    dt = 1
    shift = dt * response.framerate
    factor = 0.5

    gun2 = response + shifted_scaled(response, shift, factor)
    gun2.plot()
    thinkplot.config(xlabel="time (s)", ylabel="amplitude", ylim=[-1.05, 1.05], legend=False)
    thinkplot.save(root="systems8")

    signal = thinkdsp.SawtoothSignal(freq=410)
    wave = signal.make_wave(duration=0.1, framerate=response.framerate)

    total = 0
    for j, y in enumerate(wave.ys):
        total += shifted_scaled(response, j, y)

    total.normalize()

    wave.make_spectrum().plot(high=500, color="0.7", label="original")
    segment = total.segment(duration=0.2)
    segment.make_spectrum().plot(high=1000, label="convolved")
    thinkplot.config(xlabel="frequency (Hz)", ylabel="amplitude")
    thinkplot.save(root="systems9")
Example #36
0
def plot_response():
    thinkplot.preplot(cols=2)

    response = thinkdsp.read_wave("180961__kleeb__gunshots.wav")
    response = response.segment(start=0.26, duration=5.0)
    response.normalize()
    response.plot()
    thinkplot.config(xlabel="time", xlim=[0, 5.0], ylabel="amplitude", ylim=[-1.05, 1.05])

    thinkplot.subplot(2)
    transfer = response.make_spectrum()
    transfer.plot()
    thinkplot.config(xlabel="frequency", xlim=[0, 22500], ylabel="amplitude")

    thinkplot.save(root="systems6")

    wave = thinkdsp.read_wave("92002__jcveliz__violin-origional.wav")
    wave.ys = wave.ys[: len(response)]
    wave.normalize()
    spectrum = wave.make_spectrum()

    output = (spectrum * transfer).make_wave()
    output.normalize()

    wave.plot(color="0.7")
    output.plot(alpha=0.4)
    thinkplot.config(xlabel="time", xlim=[0, 5.0], ylabel="amplitude", ylim=[-1.05, 1.05])
    thinkplot.save(root="systems7")
Example #37
0
def chirp_spectrum():
    """Plots the spectrum of a one-second one-octave linear chirp.
    """
    signal = thinkdsp.Chirp(start=220, end=440)
    wave = signal.make_wave(duration=1)
    spectrum = wave.make_spectrum()
    spectrum.plot(high=660)
    thinkplot.save("chirp1", xlabel="frequency (Hz)", ylabel="amplitude")
Example #38
0
def dct_plot():
    signal = thinkdsp.TriangleSignal(freq=400)
    wave = signal.make_wave(duration=1.0, framerate=10000)
    dct = wave.make_dct()
    dct.plot()
    thinkplot.config(xlabel='Frequency (Hz)', ylabel='DCT')
    thinkplot.save(root='dct1',
                   formats=['pdf', 'eps'])
Example #39
0
def plot_diff_filter(close):
    """Plots the filter that corresponds to first order finite difference.
    """
    diff_window = np.array([1.0, -1.0])
    diff_filter = make_filter(diff_window, close)
    diff_filter.plot()
    thinkplot.config(xlabel='Frequency (1/day)', ylabel='Amplitude ratio')
    thinkplot.save('diff_int3')
Example #40
0
def chirp_spectrum():
    """Plots the spectrum of a one-second one-octave linear chirp.
    """
    signal = thinkdsp.Chirp(start=220, end=440)
    wave = signal.make_wave(duration=1)
    spectrum = wave.make_spectrum()
    spectrum.plot(high=660)
    thinkplot.save('chirp1', xlabel='frequency (Hz)', ylabel='amplitude')
Example #41
0
def plot(res, index):

    slices = [[0, None], [400, 1000], [860, 900]]
    start, end = slices[index]
    xs, ys = zip(*res[start:end])
    thinkplot.plot(xs, ys)
    thinkplot.save(root='dft%d' % index,
                   xlabel='freq (Hz)',
                   ylabel='cov',
                   formats=['png'])
Example #42
0
def plot(res, index):

    slices = [[0, None], [400, 1000], [860, 900]]
    start, end = slices[index]
    xs, ys = zip(*res[start:end])
    thinkplot.plot(xs, ys)
    thinkplot.save(root='dft%d' % index,
                   xlabel='freq (Hz)',
                   ylabel='cov',
                   formats=['png'])
Example #43
0
def plot_convolution(response):
    """Plots the impulse response and a shifted, scaled copy.
    """
    shift = 1
    factor = 0.5

    gun2 = response + shifted_scaled(response, shift, factor)
    gun2.plot()
    thinkplot.config(xlabel='Time (s)', ylim=[-1.05, 1.05], legend=False)
    thinkplot.save(root='systems8')
Example #44
0
def main():
    """main."""
    dataset = [30, 60, 90]

    for high in [500, 1000, 2000]:
        suite = make_posterior(high, dataset)
        print(high, suite.mean())

    thinkplot.save(root='train2',
                   xlabel='Number of trains',
                   ylabel='Probability')
Example #45
0
def violin_spectrogram():
    """Makes a spectrogram of a violin recording.
    """
    wave = thinkdsp.read_wave("92002__jcveliz__violin-origional.wav")

    seg_length = 2048
    spectrogram = wave.make_spectrogram(seg_length)
    spectrogram.plot(high=seg_length / 8)

    # TODO: try imshow?

    thinkplot.save("spectrogram1", xlabel="time (s)", ylabel="frequency (Hz)", formats=["pdf"])
Example #46
0
def plot_waveform(wave, start=1.30245, duration=0.00683):
    """Plots a short window from a wave.

    duration: float
    """
    segment = wave.segment(start, duration)
    segment.normalize()

    segment.plot()
    thinkplot.save(root='waveform',
                   xlabel='time (s)',
                   axis=[0, duration, -1.05, 1.05])
Example #47
0
def plot_convolution(response):
    """Plots the impulse response and a shifted, scaled copy.
    """
    shift = 1
    factor = 0.5
    
    gun2 = response + shifted_scaled(response, shift, factor)
    gun2.plot()
    thinkplot.config(xlabel='Time (s)',
                     ylim=[-1.05, 1.05],
                     legend=False)
    thinkplot.save(root='systems8')
Example #48
0
def plot_sampling(wave, root):
    ax1 = thinkplot.preplot(2, rows=2)
    wave.make_spectrum(full=True).plot(label='spectrum')

    thinkplot.config(xlim=XLIM, xticklabels='invisible')

    ax2 = thinkplot.subplot(2)
    sampled = sample(wave, 4)
    sampled.make_spectrum(full=True).plot(label='sampled')
    thinkplot.config(xlim=XLIM, xlabel='Frequency (Hz)')

    thinkplot.save(root=root, formats=FORMATS)
Example #49
0
def main():
    gss = utils.ReadGss('gss_college_religion')
    diffs = [run(gss) for _ in range(101)]
    years = diffs[0].index

    rows = thinkstats2.PercentileRows(diffs, [5, 50, 95])
    thinkplot.fill_between(years, rows[0], rows[2], alpha=0.2)
    thinkplot.plot(years, rows[1])
    thinkplot.config(xlabel='Year',
                     ylabel='Difference in fraction with no affiliation',
                     xlim=[1970, 2018])
    thinkplot.save(root='college_religion')
Example #50
0
def plot_waveform(wave, start=1.30245, duration=0.00683):
    """Plots a short window from a wave.

    duration: float
    """
    segment = wave.segment(start, duration)
    segment.normalize()

    segment.plot()
    thinkplot.save(root='waveform',
                   xlabel='time (s)',
                   axis=[0, duration, -1.05, 1.05])
Example #51
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')
Example #52
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')
Example #53
0
def plot_sampling(wave, root):
    ax1 = thinkplot.preplot(2, rows=2)
    wave.make_spectrum(full=True).plot(label='spectrum')

    thinkplot.config(xlim=XLIM, xticklabels='invisible')

    ax2 = thinkplot.subplot(2)
    sampled = sample(wave, 4)
    sampled.make_spectrum(full=True).plot(label='sampled')
    thinkplot.config(xlim=XLIM, xlabel='Frequency (Hz)')

    thinkplot.save(root=root,
                   formats=FORMATS)
Example #54
0
def plot_wave_and_spectrum(wave, root):
    """Makes a plot showing 
    """
    thinkplot.preplot(cols=2)
    wave.plot()
    thinkplot.config(xlabel="days", xlim=[0, 1650], ylabel="dollars", legend=False)

    thinkplot.subplot(2)
    spectrum = wave.make_spectrum()
    print(spectrum.estimate_slope())
    spectrum.plot()
    thinkplot.config(xlabel="frequency (1/days)", ylabel="power", xscale="log", yscale="log", legend=False)

    thinkplot.save(root=root)
Example #55
0
def chirp_spectrogram():
    """Makes a spectrogram of a one-second one-octave linear chirp.
    """
    signal = thinkdsp.Chirp(start=220, end=440)
    wave = signal.make_wave(duration=1, framerate=11025)
    spectrogram = wave.make_spectrogram(seg_length=512)

    print "time res", spectrogram.time_res
    print "freq res", spectrogram.freq_res
    print "product", spectrogram.time_res * spectrogram.freq_res

    spectrogram.plot(high=32)

    thinkplot.save("chirp2", xlabel="time (s)", ylabel="frequency (Hz)")
Example #56
0
def plot_power_density(root, spectrum):
    """
    """
    # 4: CDF of power density
    cdf = thinkstats2.MakeCdfFromList(spectrum.power)
    thinkplot.cdf(cdf)
    thinkplot.save(root=root + 'noise4', xlabel='power density', ylabel='CDF')

    # 5: CCDF of power density, log-y
    thinkplot.cdf(cdf, complement=True)
    thinkplot.save(root=root + 'noise5',
                   xlabel='power density',
                   ylabel='log(CCDF)',
                   yscale='log')
Example #57
0
def main():
    """main."""
    hypos = range(1, 1001)
    suite = Train(hypos)

    suite.update(60)
    print(suite.mean())

    thinkplot.pre_plot(1)
    thinkplot.pmf(suite)
    thinkplot.save(root='train1',
                   xlabel='Number of trains',
                   ylabel='Probability',
                   formats=['pdf', 'eps'])
Example #58
0
def chirp_spectrogram():
    """Makes a spectrogram of a one-second one-octave linear chirp.
    """
    signal = thinkdsp.Chirp(start=220, end=440)
    wave = signal.make_wave(duration=1, framerate=11025)
    spectrogram = wave.make_spectrogram(seg_length=512)

    print('time res', spectrogram.time_res)
    print('freq res', spectrogram.freq_res)
    print('product', spectrogram.time_res * spectrogram.freq_res)

    spectrogram.plot(high=32)

    thinkplot.save('chirp2', xlabel='time (s)', ylabel='frequency (Hz)')
Example #59
0
def plot_suites(suites, root):
    """Plot two suites.

    suite1, suite2: Suite objects
    root: string filename to write
    """
    thinkplot.clear_figure()
    thinkplot.pre_plot(len(suites))
    thinkplot.pmfs(suites)

    thinkplot.save(root=root,
                   xlabel='x',
                   ylabel='Probability',
                   formats=['pdf', 'eps'])
Example #60
0
def plot_autocorr():
    """Plots autocorrelation for pink noise with different parameters
    """
    numpy.random.seed(19)
    thinkplot.preplot(3)

    for beta in [1.2, 1.0, 0.7]:
        label = r'$\beta$ = %.1f' % beta
        plot_pink_autocorr(beta, label)

    thinkplot.config(xlabel='lag',
                     ylabel='correlation',
                     xlim=[-1, 200],
                     ylim=[-0.05, 1.05])
    thinkplot.save(root='autocorr4')