Ejemplo n.º 1
0
def get_square_wave_data(freq,
                         offset,
                         duration=0.1,
                         framerate=40000,
                         noise_ratio=0):
    signal = thinkdsp.SquareSignal(freq=freq, amp=1.0, offset=offset)
    wave = signal.make_wave(duration=duration, start=0, framerate=framerate)
    if noise_ratio != 0:
        wave.ys += numpy.random.standard_normal(wave.ys.shape) * noise_ratio
    return wave.ys
Ejemplo n.º 2
0
def waveform(freq, btn_input):
    if btn_input == 1:
        signal = thinkdsp.SinSignal(freq)
    if btn_input == 2:
        signal = thinkdsp.SquareSignal(freq)
    if btn_input == 3:
        signal = thinkdsp.TriangleSignal(freq)

    wave = signal.make_wave(framerate=samplingFreq)
    return wave
Ejemplo n.º 3
0
def get_sawtooth_square_wave(freq, offset, duration=0.1, framerate=40000):
    signal_sawtooth = thinkdsp.SawtoothSignal(freq=freq,
                                              amp=1.0,
                                              offset=offset)
    signal_square = thinkdsp.SquareSignal(freq=freq,
                                          amp=1.0,
                                          offset=offset + 2 * numpy.pi * 0.2)
    components = [signal_sawtooth, signal_square]
    signal = thinkdsp.SumSignal(*components)
    wave = signal.make_wave(duration=duration, start=0, framerate=40000)
    wave.ys = wave.ys / len(components)  # normalization
    return wave.ys
Ejemplo n.º 4
0
def square_example(freq):
    framerate = 10000
    signal = thinkdsp.SquareSignal(freq)

    duration = signal.period*3
    segment = signal.make_wave(duration, framerate=framerate)
    segment.plot()
    thinkplot.save(root='square-%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()
    spectrum.plot()
    thinkplot.save(root='square-%d-2' % freq,
                   xlabel='frequency (Hz)',
                   ylabel='amplitude')
Ejemplo n.º 5
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')
Ejemplo n.º 6
0
def square_example(freq):
    """Makes a figure showing a square wave.

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

    duration = signal.period * 3
    segment = signal.make_wave(duration, framerate=framerate)
    segment.plot()
    thinkplot.save(root='square-%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()
    spectrum.plot()
    thinkplot.save(root='square-%d-2' % freq, xlabel='Frequency (Hz)')
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])
import thinkstats2

import numpy as np
import pandas as pd
import scipy.signal

np.set_printoptions(precision=3, suppress=True)

# In[2]:

PI2 = 2 * np.pi
GRAY = '0.7'

# In[3]:

signal = thinkdsp.SquareSignal(freq=440)
wave = signal.make_wave(duration=1, framerate=4400)
segment = wave.segment(duration=0.01)

# In[4]:

window = np.ones(11)
window /= sum(window)

# In[5]:

ys = segment.ys
N = len(ys)
padded = thinkdsp.zero_pad(window, N)

# In[6]:
Ejemplo n.º 9
0
def get_square_wave(freq, offset, duration=0.1, framerate=40000):
    signal = thinkdsp.SquareSignal(freq=freq, amp=1.0, offset=offset)
    wave = signal.make_wave(duration=duration, start=0, framerate=framerate)
    return wave.ys
Ejemplo n.º 10
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')
Ejemplo n.º 11
0
from thinkdsp import TriangleSignal
from thinkdsp import decorate
import matplotlib.pyplot as plt
import numpy as np

#方波
class SquareSignal(Sinusoid):
    def evaliate(self,ts):
        cycles = self.freq*ts+self.offset/PI2
        frac,_ = np.modf(cycles)
        ys =self.amp*np.sign(unbias(frac))
        return ys

plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams['axes.unicode_minus']=False


square = thinkdsp.SquareSignal(1100)
plt.subplot(2,1,1)
plt.ylabel('1100hz方波')
square.plot()

wave = square.make_wave(duration=0.5,framerate = 10000)
spectrum = wave.make_spectrum()
plt.subplot(2,1,2)
plt.ylabel('频谱')
spectrum.plot()



plt.show()
Ejemplo n.º 12
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Aug  2 16:59:32 2018

@author: MikeNagler
"""

import thinkdsp
from thinkdsp import Signal, Wave, Spectrum

signal1 = thinkdsp.SquareSignal(freq=1100, amp=1.0, offset=0)
wave1 = signal1.make_wave(duration=1, start=0, framerate=10000)
spectrum1 = wave1.make_spectrum()
spectrum1.plot()

wave1.write(filename='temp.wav')
thinkdsp.play_wave(filename='temp.wav', player='afplay')
Ejemplo n.º 13
0
import thinkdsp
import matplotlib.pyplot as plt
from winsound import PlaySound
signal_tri = thinkdsp.SquareSignal(1100)
plt.subplot(211)
signal_tri.plot()
wave = signal_tri.make_wave(duration=5, framerate=10000)
spectrum = wave.make_spectrum()
wave.write("1.wav")
PlaySound("1.wav", flags=8)
plt.subplot(212)
spectrum.plot()
plt.show()

Ejemplo n.º 14
0
Archivo: 2-2.py Proyecto: wht-s/456
signal1.plot()

sawtooth = SawtoothSignal().make_wave(duration=0.5, framerate=10000)
plt.subplot(3, 2, 2)
plt.title('频谱')
sawtooth.make_spectrum().plot()

signal2 = thinkdsp.TriangleSignal(200)
plt.subplot(3, 2, 3)
plt.ylabel('200Hz三角波')
signal2.plot()

wave2 = signal2.make_wave(duration=0.5, framerate=10000)
spectrum = wave2.make_spectrum()
plt.subplot(3, 2, 4)

spectrum.plot()

signal3 = thinkdsp.SquareSignal(200)
plt.subplot(3, 2, 5)
plt.ylabel('200Hz方波')
signal3.plot()

wave3 = signal3.make_wave(duration=0.5, framerate=10000)
spectrum = wave3.make_spectrum()
plt.subplot(3, 2, 6)

spectrum.plot()

plt.show()
Ejemplo n.º 15
0
# -*- coding: utf-8 -*-
"""
Created on Thu Aug  2 18:06:16 2018

@author: MikeNagler
"""

import thinkdsp
from thinkdsp import Signal, Wave, Spectrum

def modify_spectrum(spectrum):
    spectrum.hs[0] = 0
    for i in range(1, len(spectrum.fs)):
        spectrum.hs[i] = spectrum.hs[i] / spectrum.fs[i] 

signal = thinkdsp.SquareSignal() 
signal.plot() 

wave = signal.make_wave(duration=1) 
wave.plot() 

wave.write(filename='temp.wav')

spectrum = wave.make_spectrum() 
print(spectrum.hs[1000]) 
spectrum.plot()

# print(spectrum.fs[10] == 10) ### ok, so fs is just an array of all the frequencies

modify_spectrum(spectrum)
print(spectrum.hs[1000])
Ejemplo n.º 16
0
            # print(spectrum.fs[i])
            # print(spectrum.hs[i])
    return spectrum


signal_tri = thinkdsp.TriangleSignal(200)  #生成一个200Hz的方波
plt.subplot(331)
signal_tri.plot()
wave = signal_tri.make_wave(duration=0.01, framerate=10000)
spectrum = wave.make_spectrum()
plt.subplot(334)
spectrum.plot()
s = af(spectrum)
plt.subplot(337)
s.plot()
signal_squ = thinkdsp.SquareSignal(200)  #生成一个200Hz的三角波
plt.subplot(332)
signal_squ.plot()
wave = signal_squ.make_wave(duration=0.01, framerate=10000)
spectrum = wave.make_spectrum()
plt.subplot(335)
spectrum.plot()
s = af(spectrum)
plt.subplot(338)
s.plot()
signal_saw = thinkdsp.SawtoothSignal(200)  #生成一个200Hz的锯齿波
plt.subplot(333)
signal_saw.plot()
wave = signal_saw.make_wave(duration=0.01, framerate=10000)
spectrum = wave.make_spectrum()
plt.subplot(336)