Esempio n. 1
0
def main():

    data = 20, 15, 3
    probs = numpy.linspace(0, 1, 31)
    hypos = []
    for n in range(32, 350):
        for p1 in probs:
            for p2 in probs:
                hypos.append((n, p1, p2))

    suite = Lincoln(hypos)
    suite.Update(data)

    n_marginal = suite.Marginal(0)

    thinkplot.Pmf(n_marginal, label='n')
    thinkplot.Save(root='lincoln1',
                   xlabel='number of bugs',
                   ylabel='PMF',
                   formats=['pdf', 'png'])

    print('post mean n', n_marginal.Mean())
    print('MAP n', n_marginal.MaximumLikelihood())

    pmf1 = suite.Marginal(1, label='tester1')
    pmf2 = suite.Marginal(2, label='tester2')
    thinkplot.Pdfs([pmf1,pmf2])
    thinkplot.show(xlabel = 'testing effectiveness', ylabel = 'PMF')  

    print('prob greater', pmf1 > pmf2)
    print('prob greater', pmf1 < pmf2)  
Esempio n. 2
0
def processScoresTeamwise(pairs):
    """Average number of goals for each team.

    pairs: map from (team1, team2) to (score1, score2)
    """
    # map from team to list of goals scored
    goals_scored = {}
    for key, entries in pairs.iteritems():
        t1, t2 = key
        for entry in entries:
            g1, g2 = entry
            goals_scored.setdefault(t1, []).append(g1)
            goals_scored.setdefault(t2, []).append(g2)

    # make a list of average goals scored
    lams = []
    for key, goals in iter(goals_scored):
        lam = thinkstats.mean(goals)
        lams.append(lam)

    # make the distribution of average goals scored
    cdf = thinkbayes.makeCdfFromList(lams)
    thinkplot.cdf(cdf)
    thinkplot.show()

    mu, var = thinkstats.meanAndVariance(lams)
    print('mu, sig', mu, math.sqrt(var))
Esempio n. 3
0
def ex3():
    def VertLine(x, y=1):
        thinkplot.Plot([x, x], [0, y], color='0.8', linewidth=3)

    lam = 4
    goal_totals = [SimulateGame(lam=lam) for _ in range(1000)]
    print('RMSE', RMSE(goal_totals, lam))
    hist = thinkstats2.Hist(goal_totals)
    cdf = thinkstats2.Cdf(goal_totals)
    thinkplot.PrePlot(rows=2, cols=2)
    thinkplot.SubPlot(1)
    thinkplot.Hist(hist)
    thinkplot.SubPlot(2)
    thinkplot.Cdf(cdf)
    VertLine(cdf.Percentile(5))
    VertLine(cdf.Percentile(95))
    thinkplot.SubPlot(3)

    # lambda vs. rmse
    # rmse goes up as lambda goes up
    lams = range(1, 15)
    rmses = [RMSE([SimulateGame(lam=l) for _ in range(1000)], l) for l in lams]
    thinkplot.Plot(lams, rmses)
    thinkplot.SubPlot(4)

    # m vs. rmse
    # maybe rmse very slowly goes down as m goes up?
    # not at all clear that's really the case...
    ms = np.arange(10, 1000, 10)
    rmses = [RMSE([SimulateGame() for _ in range(m)], 4) for m in ms]
    thinkplot.Plot(ms, rmses)

    thinkplot.show()
Esempio n. 4
0
def main():
    """main."""
    suite = version3()
    print(suite.mean())

    thinkplot.pmf(suite)
    thinkplot.show()
def view_harmonics(freq, framerate):
    signal = thinkdsp.SawtoothSignal(freq)
    wave = signal.make_wave(duration=0.5, framerate=framerate)
    spectrum = wave.make_spectrum()
    spectrum.plot(color='blue')
    thinkplot.show(xlabel='frequency', ylabel='amplitude')

    display(wave.make_audio())
Esempio n. 6
0
def sawtooth_chirp():
    signal = thinkdsp.SawtoothChirp(start=220, end=880)
    wave = signal.make_wave(duration=2, framerate=44100)
    wave.apodize()
    wave.play()

    sp = wave.make_spectrogram(1024)
    sp.plot()
    thinkplot.show()
Esempio n. 7
0
def sawtooth_chirp():
    signal = thinkdsp.SawtoothChirp(start=220, end=880)
    wave = signal.make_wave(duration=2, framerate=44100)
    wave.apodize()
    wave.play()

    sp = wave.make_spectrogram(1024)
    sp.plot()
    thinkplot.show()
Esempio n. 8
0
def main():
    hypos = range(0, 101)
    dataset = 'H' * 140 + 'T' * 110
    euro = Euro(hypos)
    for data in dataset:
        euro.Update(data)
    thinkplot.Clf()
    thinkplot.Pmf(euro)
    thinkplot.show()
Esempio n. 9
0
def Scatter(d, var1, var2, **kwargs):
    """Assuming numerical for now (will call isNumerical()"""
    xs = list(d[var1])
    ys = list(d[var2])
    RemoveNone(xs,ys)
    
    #print 'Spearman corr', thinkstats2.SpearmanCorr(xs, ys)
    
    thinkplot.Scatter(xs, ys, **kwargs)
    thinkplot.show()
Esempio n. 10
0
def main():
    thinkdsp.random_seed(19)

    signal = thinkdsp.BrownianNoise()
    make_periodogram(signal)
    return

    signal = thinkdsp.UncorrelatedUniformNoise()
    wave1 = signal.make_wave(duration=1.0, framerate=11025)
    wave2 = signal.make_wave(duration=1.0, framerate=11025)
    print wave1.cov(wave2)
    print wave1.cov(wave1)
    print wave2.cov(wave2)

    print wave1.cov_mat(wave2)

    print wave1.corr(wave2)
    print wave1.corr(wave1)
    print wave2.corr(wave2)
    return

    signal = thinkdsp.BrownianNoise()
    process_noise(signal, root='red')
    return

    signal = thinkdsp.UncorrelatedUniformNoise()
    process_noise(signal, root='white')
    return

    signal = thinkdsp.WhiteNoise()
    white, integ_white = test_noise(signal, 'white-noise')
    print white.estimate_slope()

    signal = thinkdsp.BrownianNoise()
    red, integ_red = test_noise(signal, 'red-noise')
    print red.estimate_slope()
    return

    signal = thinkdsp.PinkNoise(beta=1.0)
    pink, integ_pink = test_noise(signal, 'pink-noise')
    print pink.estimate_slope()

    thinkplot.preplot(num=3)
    white.plot(low=1, exponent=2, label='white', linewidth=2)
    pink.plot(low=1, exponent=2, label='pink', linewidth=2)
    red.plot(low=1, exponent=2, label='red', linewidth=2)
    thinkplot.show(xlabel='frequency (Hz)',
                   ylabel='power',
                   xscale='log',
                   yscale='log',
                   axis=[1, 18000, 1e-5, 1e8])
    

    return
Esempio n. 11
0
def main():
    thinkdsp.random_seed(19)

    signal = thinkdsp.BrownianNoise()
    make_periodogram(signal)
    return

    signal = thinkdsp.UncorrelatedUniformNoise()
    wave1 = signal.make_wave(duration=1.0, framerate=11025)
    wave2 = signal.make_wave(duration=1.0, framerate=11025)
    print wave1.cov(wave2)
    print wave1.cov(wave1)
    print wave2.cov(wave2)

    print wave1.cov_mat(wave2)

    print wave1.corr(wave2)
    print wave1.corr(wave1)
    print wave2.corr(wave2)
    return

    signal = thinkdsp.BrownianNoise()
    process_noise(signal, root='red')
    return

    signal = thinkdsp.UncorrelatedUniformNoise()
    process_noise(signal, root='white')
    return

    signal = thinkdsp.WhiteNoise()
    white, integ_white = test_noise(signal, 'white-noise')
    print white.estimate_slope()

    signal = thinkdsp.BrownianNoise()
    red, integ_red = test_noise(signal, 'red-noise')
    print red.estimate_slope()
    return

    signal = thinkdsp.PinkNoise(beta=1.0)
    pink, integ_pink = test_noise(signal, 'pink-noise')
    print pink.estimate_slope()

    thinkplot.preplot(num=3)
    white.plot(low=1, exponent=2, label='white', linewidth=2)
    pink.plot(low=1, exponent=2, label='pink', linewidth=2)
    red.plot(low=1, exponent=2, label='red', linewidth=2)
    thinkplot.show(xlabel='frequency (Hz)',
                   ylabel='power',
                   xscale='log',
                   yscale='log',
                   axis=[1, 18000, 1e-5, 1e8])

    return
Esempio n. 12
0
def readNplotNUMKDHH(dctfile='2002FemResp.dct',
                     datfile='2002FemResp.dat.gz',
                     compression='gzip'):
    """ read data to fram and plot NUMKDHH PMF"""
    dct = thinkstats2.ReadStataDct(dctfile)
    df = dct.ReadFixedWidth(datfile, compression=compression)

    pmf = thinkstats2.Pmf(df.numkdhh)
    thinkplot.Pmf(pmf, label='numkdhh')

    pmf2 = BiasedPmf(pmf)
    thinkplot.Pmf(pmf2, label='biased')
    thinkplot.show()
def step_4():
    Sin1 = thinkdsp.CosSignal(freq=261.63, amp=0.5, offset=0)
    Sin2 = thinkdsp.CosSignal(freq=329.63, amp=0.5, offset=0)
    Sin3 = thinkdsp.CosSignal(freq=392.0, amp=0.5, offset=0)
    SumSignal = Sin1 + Sin2 + Sin3
    SumSignal_wave = SumSignal.make_wave(duration=3, start=0, framerate=8000)

    period = SumSignal.period
    SumSignal_seg = SumSignal_wave.segment(start=0, duration=period * 5)
    SumSignal_seg.plot()
    tp.show()

    SumSignal_wave.write(filename='output.wav')
Esempio n. 14
0
def main():
    N = 64
    
    #test_dct(N, freq=N/4)
    #test_dct(N, freq=N/4 + 0.25)

    test_fft(N, freq=N/4 + 0.25, window=True)
    test_dct(N, freq=N/4 + 0.25, window=True)

    thinkplot.show()
    return

    return
Esempio n. 15
0
def main():
    locomotiveNumbers = range(1, 1001)
    locomotive = Locomotive(locomotiveNumbers)
    locomotive.Update(60)
    locomotive.Update(160)
    locomotive.Update(80)
    locomotive.Update(570)
    locomotive.Update(640)
    print('Mean: {}'.format(locomotive.Mean()))

    thinkplot.preplot(1)
    thinkplot.Pmf(locomotive)
    thinkplot.show(xlabel='Number of train', ylabel='Probability')
def preprocessA(sample):
    signal = thinkDSP.read_wave("samples"+sample+".wav")
    spectrum = signal.make_spectrum()
    spectrum.high_pass(cutoff=100, factor=0.1)
    signal = spectrum.make_wave()
    #signal.write("outcome.wav")
    spectrogram = signal.make_spectrogram(seg_length=4096)
    specMatrix = spectrogram.plot(returnArray=1,length=None,high=8000, cmap="gray")
    thinkplot.show()
    maxi = np.amax(specMatrix,axis = 0)
    indi = np.argmax(specMatrix,axis = 0)
    final = np.column_stack([maxi,indi])
    np.save("sample"+sample,final)
Esempio n. 17
0
def autocorr(wave):
    n = len(wave.ys)

    corrs = []
    lags = range(n//2)
    for lag in lags:
        y1 = wave.ys[lag:]
        y2 = wave.ys[:n-lag]
        corr = numpy.corrcoef(y1, y2)[0, 1]
        corrs.append(corr)

    thinkplot.plot(lags, corrs)
    thinkplot.show()
Esempio n. 18
0
def make_periodogram(signal):
    specs = []
    for i in range(10000):
        wave = signal.make_wave(duration=1.0, framerate=1024)
        spec = wave.make_spectrum()
        specs.append(spec)
    
    spectrum = sum(specs)
    print spectrum.estimate_slope()
    spectrum.plot_power(low=1)
    thinkplot.show(xlabel='frequency (Hz)',
                   ylabel='power density',
                   xscale='log',
                   yscale='log')
Esempio n. 19
0
def main():
	maleRates = [0.52, 0.38, 0.39, 1.01, 2.63]
	femaleRates = [50, 20.5]
	pdfMale = thinkbayes2.EstimatedPdf(maleRates)
	pdfFemale = thinkbayes2.EstimatedPdf(femaleRates)
	low, high = 0, 100
	n = 1001
	xs = numpy.linspace(low, high, n)
	pmfMale = pdfMale.MakePmf(steps=xs)
	pmfFemale = pdfFemale.MakePmf(steps=xs)

	thinkplot.Pdf(pdfMale, label='Male Prior')
	thinkplot.Pdf(pdfFemale, label='Female Prior')
	thinkplot.show()
Esempio n. 20
0
def make_periodogram(signal):
    specs = []
    for i in range(10000):
        wave = signal.make_wave(duration=1.0, framerate=1024)
        spec = wave.make_spectrum()
        specs.append(spec)

    spectrum = sum(specs)
    print spectrum.estimate_slope()
    spectrum.plot_power(low=1)
    thinkplot.show(xlabel='frequency (Hz)',
                   ylabel='power density',
                   xscale='log',
                   yscale='log')
def signal(offset):
    cos_sig = thinkdsp.CosSignal(freq=1.0, amp=1.0, offset=offset)
    sin_sig = thinkdsp.SinSignal(freq=1.0, amp=1.0, offset=offset)
    cos_wave = cos_sig.make_wave(duration=0.5, start=0, framerate=8000)
    sin_wave = sin_sig.make_wave(duration=0.5, start=0, framerate=8000)

    period = sin_sig.period
    cos_seg = cos_wave.segment(start=0, duration=period * 5)
    sin_seg = sin_wave.segment(start=0, duration=period * 5)

    sin_seg.plot()
    tp.show()
    cos_seg.plot()
    tp.show()
Esempio n. 22
0
def main():
    gss = read_gss()
    sample = utils.ResampleByYear(gss)
    grouped_year = sample.groupby(['year'])
    plot_relig(grouped_year)
    thinkplot.config(xlabel='Year of survey', ylabel='Percent')
    thinkplot.show()
    return

    # run the resamples
    dfs = [run(gss) for _ in range(101)]

    # make the plots
    single_plot(dfs)
    multi_plot(dfs)
Esempio n. 23
0
def main():
    df = ReadData()
    cdf = thinkstats2.Cdf(df['ps'])

    thinkplot.PrePlot(rows=1, cols=2)
    thinkplot.SubPlot(1)
    scale = thinkplot.Cdf(cdf, xscale='log')
    thinkplot.Config(title='logx', **scale)

    thinkplot.SubPlot(2)
    scale = thinkplot.Cdf(cdf, transform='pareto')
    thinkplot.Config(title='pareto', **scale)

    thinkplot.show(legend=False)
    
    print(df)
Esempio n. 24
0
def PMFDiff(scale1, scale2):
    """
    create (and plot) the PMF of the differences in corrolations between the scales
    based on gender.
    """
    
    # more the merrier (and slower)
    n = 1000
    
    # create the diff
    diff = randomDiffs(scale1, scale2, n)

    diff = [round(num, 3) for num in diff]
    pmf = MakePmfFromList(diff)
    thinkplot.Pmf(pmf)
    thinkplot.show()
Esempio n. 25
0
def plot_diff_filters(wave):

    window1 = np.array([1, -1])
    window2 = np.array([-1, 4, -3]) / 2.0
    window3 = np.array([2, -9, 18, -11]) / 6.0
    window4 = np.array([-3, 16, -36, 48, -25]) / 12.0
    window5 = np.array([12, -75, 200, -300, 300, -137]) / 60.0

    thinkplot.preplot(5)
    for i, window in enumerate([window1, window2, window3, window4, window5]):
        padded = thinkdsp.zero_pad(window, len(wave))
        fft_window = np.fft.rfft(padded)
        n = len(fft_window)
        thinkplot.plot(abs(fft_window)[:], label=i+1)

    thinkplot.show()
Esempio n. 26
0
def plot_diff_filters(wave):

    window1 = np.array([1, -1])
    window2 = np.array([-1, 4, -3]) / 2.0
    window3 = np.array([2, -9, 18, -11]) / 6.0
    window4 = np.array([-3, 16, -36, 48, -25]) / 12.0
    window5 = np.array([12, -75, 200, -300, 300, -137]) / 60.0

    thinkplot.preplot(5)
    for i, window in enumerate([window1, window2, window3, window4, window5]):
        padded = thinkdsp.zero_pad(window, len(wave))
        fft_window = np.fft.rfft(padded)
        n = len(fft_window)
        thinkplot.plot(abs(fft_window)[:], label=i + 1)

    thinkplot.show()
Esempio n. 27
0
def plot_amen():
    wave = thinkdsp.read_wave('263868__kevcio__amen-break-a-160-bpm.wav')
    wave.normalize()

    ax1 = thinkplot.preplot(2, rows=2)
    wave.make_spectrum(full=True).plot()

    xlim = [-22050, 22050]
    thinkplot.config(xlim=xlim, xticklabels='invisible')

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

    thinkplot.show()
    return
Esempio n. 28
0
def SurvivalHaz(introductions, lifetimes, plot=False):
    """Given lists of ages and lifespans, this function calculates the 
	Hazard and Survial curves.  If plot is set True, it will plot them."""
    haz = survival.EstimateHazardFunction(lifetimes, introductions)
    sf = haz.MakeSurvival()
    if plot:
        thinkplot.plot(sf, color='Grey')
        plt.xlabel("Age (books)")
        plt.ylabel("Probability of Surviving")
        plt.title('Survial Function')
        thinkplot.show()
        thinkplot.plot(haz, color='Grey')
        plt.title('Hazard Function')
        plt.xlabel("Age (books)")
        plt.ylabel("Percent of Lives That End")
        thinkplot.show()
    return sf, haz
Esempio n. 29
0
def plot_amen():
    wave = thinkdsp.read_wave('263868__kevcio__amen-break-a-160-bpm.wav')
    wave.normalize()

    ax1 = thinkplot.preplot(2, rows=2)
    wave.make_spectrum(full=True).plot()

    xlim = [-22050, 22050]
    thinkplot.config(xlim=xlim, xticklabels='invisible')

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

    thinkplot.show()
    return
Esempio n. 30
0
def main():
	maleRates = [0.52, 0.38, 0.39, 1.01, 2.63, 30]
	femaleRates = [50, 20.5, 40, 30, 45]
	pdfMale = thinkbayes2.EstimatedPdf(maleRates)
	pdfFemale = thinkbayes2.EstimatedPdf(femaleRates)
	low, high = 0, 100
	n = 1001
	xs = numpy.linspace(low, high, n)
	pmfMale = MakePmfTest(pdfMale,steps=xs)
	pmfFemale = MakePmfTest(pdfFemale,steps=xs)

	pmfMale.Normalize()
	pmfFemale.Normalize()

	thinkplot.Pdf(pmfMale, label='Male Prior')
	thinkplot.Pdf(pmfFemale, label='Female Prior')
	thinkplot.show()
def SurvivalHaz(introductions,lifetimes,plot=False):
	"""Given lists of ages and lifespans, this function calculates the 
	Hazard and Survial curves.  If plot is set True, it will plot them."""
	haz=survival.EstimateHazardFunction(lifetimes, introductions)
	sf=haz.MakeSurvival()
	if plot:
		thinkplot.plot(sf,color='Grey')
		plt.xlabel("Age (books)")
		plt.ylabel("Probability of Surviving")
		plt.title('Survial Function')
		thinkplot.show()
		thinkplot.plot(haz,color='Grey')
		plt.title('Hazard Function')
		plt.xlabel("Age (books)")
		plt.ylabel("Percent of Lives That End")
		thinkplot.show()
	return sf,haz
Esempio n. 32
0
	def CDFCabinLoadFactor(self, network):
		""" Plots a Cumulative Distrubtion Function for Cabin Load Factor.

		Cabin Load Factor is defined as the ratio between the total number of 
		passengers booked for a flight and the total capacity of the plane.

		"""

		clf_list =  network.countFinalCabinLoadFactor().values()
		
		# remove any invalid floats 'nan' or 'inf'
		clf_list[:] = [e for e in clf_list if not isnan(e) and not isinf(e)]

		clf_cdf = thinkstats2.MakeCdfFromList(clf_list)
		thinkplot.Cdf(clf_cdf)
		thinkplot.show(title='Fraction of the cabin filled at departure', 
					   xlabel='Cabin Load Factor',
					   ylabel='CDF')
Esempio n. 33
0
def test_make_dct():
    N = 32
    framerate = N
    amps = numpy.zeros(N)
    amps[2] = 1.0
    dct = thinkdsp.Dct(amps, framerate)
    wave = dct.make_wave()
    print wave.ys

    cos_sig = thinkdsp.CosSignal(freq=1, offset=math.pi/N)
    wave = cos_sig.make_wave(duration=1, start=0, framerate=framerate)
    print wave.ys

    dct = wave.make_dct()
    dct.plot()
    print dct.fs

    iv = dct_iv(wave.ys)
    thinkplot.plot(dct.fs, iv)
    thinkplot.show()
Esempio n. 34
0
def filter_wave(wave, start, duration, cutoff):
    """Selects a segment from the wave and filters it.
    
    Plots the spectrum and displays an Audio widget.
    
    wave: Wave object
    start: time in s
    duration: time in s
    cutoff: frequency in Hz
    """
    segment = wave.segment(start, duration)
    spectrum = segment.make_spectrum()

    spectrum.plot(color='0.7')
    spectrum.low_pass(cutoff)
    spectrum.plot(color='#045a8d')
    thinkplot.show(xlabel='Frequency (Hz)')

    audio = spectrum.make_wave().make_audio()
    display(audio)
def voice_analysis_test(filepath):
    f = thinkdsp.read_wave(filepath)
    # spectrum = f.make_spectrum()
    # spectrum.plot() # the squiggly blue line
    # sp = spectrum.peaks()
    fig, ax = plt.subplots()

    # ok, i am currently not recording x=frequency, y=occurrences like ithought i was
    f.make_spectrum().plot(high=2000)
    thinkplot.config(title='Spectrum',
                     xlabel='frequency (Hz)',
                     ylabel='number occurrences')
    thinkplot.show()

    f_spectrogram = f.make_spectrogram(seg_length=1024)
    f_spectrogram.plot(high=2000)
    thinkplot.config(title='Spectrogram',
                     xlabel='frequency (Hz)',
                     ylabel='number occurrences')
    thinkplot.show()
Esempio n. 36
0
def ex2(n=10, m=1000):
    def VertLine(x, y=1):
        thinkplot.Plot([x, x], [0, y], color='0.8', linewidth=3)

    print("Exericse 8.2")
    lam = 2
    estimates = ex2_helper()
    cdf = thinkstats2.Cdf(estimates)
    print('90% confidence interval is', cdf.Percentile(5), cdf.Percentile(95))
    print('RMSE', RMSE(estimates, lam))
    thinkplot.Cdf(cdf)
    VertLine(cdf.Percentile(5))
    VertLine(cdf.Percentile(95))
    thinkplot.show(xlabel='lambda', ylabel='probability')

    errors = []
    for n in np.arange(5, 55, 5):
        estimates = ex2_helper(n=n)
        errors.append(RMSE(estimates, lam))
    thinkplot.Plot(np.arange(5, 55, 5), errors)
    thinkplot.show(xlabel='n', ylabel='RMSE')
Esempio n. 37
0
def trombone_gliss():
    """Tests TromboneGliss.
    """
    low = 262
    high = 340
    signal = TromboneGliss(high, low)
    wave1 = signal.make_wave(duration=1)
    wave1.apodize()

    signal = TromboneGliss(low, high)
    wave2 = signal.make_wave(duration=1)
    wave2.apodize()

    wave = wave1 | wave2
    filename = 'gliss.wav'
    wave.write(filename)
    thinkdsp.play_wave(filename)

    sp = wave.make_spectrogram(1024)
    sp.plot(high=40)
    thinkplot.show()
Esempio n. 38
0
def trombone_gliss():
    """Tests TromboneGliss.
    """
    low = 262
    high = 340
    signal = TromboneGliss(high, low)
    wave1 = signal.make_wave(duration=1)
    wave1.apodize()

    signal = TromboneGliss(low, high)
    wave2 = signal.make_wave(duration=1)
    wave2.apodize()

    wave = wave1 | wave2
    filename = 'gliss.wav'
    wave.write(filename)
    thinkdsp.play_wave(filename)

    sp = wave.make_spectrogram(1024)
    sp.plot(high=40)
    thinkplot.show()
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. 40
0
import sys
sys.path.insert(1, 'dsp-modulo')

import numpy as np
import thinkplot as plt

from thinkdsp import decorate
from thinkdsp import UncorrelatedUniformNoise

senal = UncorrelatedUniformNoise()
wave = senal.make_wave(duration=0.5, framerate=22050)
wave.write("ruido_no_correlacional_uniforme.wav")

segmento = wave.segment(duration=0.05)

segmento.plot()
decorate(xlabel="Tiempo(s)", ylabel="Amplitud")
plt.show()

espectro = wave.make_spectrum()
espectro.plot_power()
decorate(xlabel="Frecuencia (Hz)", ylabel="Poder")
plt.show()

espectro_integrado = espectro.make_integrated_spectrum()
espectro_integrado.plot_power()
decorate(xlabel="Frecuencia (Hz)", ylabel="Poder acumulado")
plt.show()

pendiente = espectro.estimate_slope()
print("Pendiente: " + str(pendiente.slope))
Esempio n. 41
0
# -*- coding: utf-8 -*-
"""
Created on Fri Apr  1 22:08:35 2016

@author: azg
"""

import random
import thinkstats2
import thinkplot

random_list = [random.random() for _ in range(1000)]
random_list_pmf = thinkstats2.Pmf(random_list)
thinkplot.Pmf(random_list_pmf, linewidth=0.08, label="Random List PMF")
thinkplot.show()
random_list_cdf = thinkstats2.Cdf(random_list)
thinkplot.Cdf(random_list_cdf, label="Random List CDF")
thinkplot.show()
Esempio n. 42
0
import thinkstats2
import chap01soln
import thinkplot

resp = chap01soln.ReadFemResp()

numkdhh_hist = thinkstats2.Hist(resp.numkdhh)

thinkplot.Hist(numkdhh_hist)
thinkplot.show(xlabel='# children', ylabel ='frequency')

numkdhh_pmf = thinkstats2.Pmf(resp.numkdhh)

thinkplot.Pmf(numkdhh_pmf)
thinkplot.show(xlabel='# children', ylabel ='probability')

def BiasPmf(pmf, label):
    new_pmf = pmf.Copy(label=label)

    for x, p in pmf.Items():
        new_pmf.Mult(x, x)

    new_pmf.Normalize()
    return new_pmf

numkdhh_biased = BiasPmf(numkdhh_pmf, label='biased')

thinkplot.Pmf(numkdhh_biased)
thinkplot.Show(xlabel='# children', ylabel ='probability')
Esempio n. 43
0
sys.path.insert(1, 'dsp-modulo')

import numpy as np
import thinkplot as pl

from thinkdsp import decorate
from thinkdsp import UncorrelatedUniformNoise

senal = UncorrelatedUniformNoise()
wave = senal.make_wave(duration=0.5, framerate=22050)
wave.write("ruidoNoCorrelacionadoUniforme.wav")

segmento = wave.segment(duration=0.05)

segmento.plot()
decorate(xlabel="tiempo", ylabel="amplitud")
pl.show()

espectro = wave.make_spectrum()
espectro.plot_power()
decorate(xlabel="frecuencia", ylabel="power")
pl.show()

espectro_integrado = espectro.make_integrated_spectrum()
espectro_integrado.plot_power()
decorate(xlabel="frecuencia", ylabel="poder acumulado")
pl.show()

pendiente = espectro.estimate_slope()
print("pendiente: " + str(pendiente.slope))
Esempio n. 44
0
# 第1子と第2子以降に分ける
tmp = live.copy()
tmp.loc[tmp.prglngth <= 27] = np.nan
tmp.loc[tmp.prglngth > 47] = np.nan
firsts = tmp[tmp.birthord == 1]
others = tmp[tmp.birthord != 1]
first_pmf = thinkstats2.Pmf(firsts.prglngth)
others_pmf = thinkstats2.Pmf(others.prglngth)
# %%
# 棒グラフ表示
width = 0.45
thinkplot.PrePlot(2, cols=2)
thinkplot.Hist(first_pmf, align='right', width=width)
thinkplot.Hist(others_pmf, align='left', width=width)
thinkplot.Config(xlabl='week', ylabel='probability', axis=[27, 46, 0, 0.6])
thinkplot.show()
# %%
# ステップ関数表示
thinkplot.PrePlot(2)
thinkplot.Pmfs([first_pmf, others_pmf])
thinkplot.show(xlabl='week', ylabel='probability', axis=[27, 46, 0, 0.6])
# %% [markdown]
# ## 3.3 その他の可視化
# %%
# 差を棒グラフで表示
weeks = range(35, 46)
diffs = []
for week in weeks:
    p1 = first_pmf.Prob(week)
    p2 = others_pmf.Prob(week)
    diff = 100 * (p1 - p2)
Esempio n. 45
0
#%%
t = [1, 2, 2, 3, 5]
for x in range(6): 
    print("CDF({0}) = {1}".format(x, EvalCdf(t, x)))
#%% [markdown]
# ## 4.4 CDF の表現

#%%
import thinkstats2
import first
import thinkplot

live , firsts,others = first.MakeFrames() 
cdf = thinkstats2.Cdf(live.prglngth, label='prglngth')
thinkplot.Cdf(cdf)
thinkplot.show(xlabel='weeks', ylabel='CDF')

#%%

print("10% {0} weeks".format(cdf.Value(0.1)))
print("90% {0} weeks".format(cdf.Value(0.9)))

#%% [markdown]

# ## 4.5 CDFを比較する

#%%
first_cdf = thinkstats2.Cdf(firsts.totalwgt_lb, label='first')
other_cdf = thinkstats2.Cdf(others.totalwgt_lb, label='other')
thinkplot.PrePlot(2)
thinkplot.Cdfs([first_cdf, other_cdf])
import sys
sys.path.insert(1, 'dsp-modulo')

from thinkdsp import SinSignal
from thinkdsp import decorate
import thinkplot

frecuencia1 = SinSignal(freq=1500, amp=0.3, offset=0)
frecuencia2 = SinSignal(freq=380, amp=0.6, offset=0)

frecuencia3 = SinSignal(freq=5300, amp=1.0, offset=0)
frecuencia4 = SinSignal(freq=12300, amp=0.1, offset=0)

resultante1 = frecuencia1 + frecuencia2
resultante2 = frecuencia3 + frecuencia4

waveResultante1 = resultante1.make_wave(duration=1,start=0,framerate=44100)
waveResultante2 = resultante2.make_wave(duration=6,start=1.3,framerate=44100)

waveFinal = waveResultante1 + waveResultante2

waveFinal.plot()
decorate(xLabel="Tiempo (s)")
thinkplot.show()

espectro = waveFinal.make_spectrum()
espectro.plot()
decorate(xLabel="Frecuencia (Hz)")
thinkplot.show()
Esempio n. 47
0
def correlate(wave):
    corrs = numpy.correlate(wave.ys, wave.ys, mode='valid')
    print(len(corrs))
    thinkplot.plot(corrs)
    thinkplot.show()