Esempio n. 1
1
def sweep(duration, dt, f, method='linear', phi=0,
          vertex_zero=True, autocorrelate=True, return_t=False):
    """
    Generates a linear frequency modulated wavelet (sweep)
    Does a wrapping of scipy.signal.chirp

    :param duration: The length in seconds of the wavelet.
    :param dt: is the sample interval in seconds (usually 0.001, 0.002, 0.004)
    :param f: Tuple of (f1, f2), or a similar list. A list of lists
              will create a wavelet bank.
    :keyword method: {'linear','quadratic','logarithmic'}, optional
    :keyword phi: float, phase offset in degrees
    :keyword vertex_zero: bool, optional
        This parameter is only used when method is 'quadratic'.
        It determines whether the vertex of the parabola that
        is the graph of the frequency is at t=0 or t=t1.

    :returns: An LFM waveform.
    """

    t0 = -duration/2.
    t1 = duration/2.
    t = np.arange(t0, t1, dt)

    freq = np.array(f)

    if freq.size == 2:
        A = chirp(t, freq[0], t1, freq[1],
                  method, phi, vertex_zero)
        if autocorrelate:
            A = np.correlate(A, A, mode='same')
        output = A / np.amax(A)

    else:
        output = np.zeros((t.size, freq.shape[1]))

        for i in range(freq.shape[1]):
            A = chirp(t, freq[0, i], t1, freq[1, i],
                      method, phi, vertex_zero)

            if autocorrelate:
                A = np.correlate(A, A, mode='same')
            output[:, i] = A / np.max(A)

    if return_t:
        Sweep = namedtuple('Sweep', ['amplitude', 'time'])
        return Sweep(output, t)
    else:
        return output
Esempio n. 2
0
        def tb_stimulus():
            # pulse the reset
            yield reset.pulse(100)
            for ii in xrange(2):
                yield clock.posedge
                
            # chirp 1 (time response pictoral)
            print("   chirp 1 ...")
            samp_in = signal.chirp(np.arange(args.Nsamps/2)*1/args.Fs,
                                   8, .64, 480,
                                   method=u'logarithmic')*.94
            samp_in = np.concatenate(
                (samp_in,
                 np.array([ss for ss in reversed(samp_in[:-1])] )))
            samp_out = []
            fsamp_out=[]
            # input samples, save the output
            for ii in xrange(args.Nsamps-1):
                sig_in.next = int(np.floor(samp_in[ii]*(sMax)))
                yield clock.posedge
                samp_out.append(sig_out//float(sMax))
                fsamp_out.append(int(np.floor(samp_in[ii]*(sMax))))
            samp_out = np.array(samp_out)
            #fsamp_out = np.array(fsamp_out)
            #fsamp_out.save('fsamp_out.dat')
            fh=open('fsamp_out.dat','w')
            cPickle.dump(fsamp_out,fh)
            c = signal.lfilter(coef, 1, samp_in)
            sdiff = np.abs(c[:-2] - samp_out[2:])
            plt.figure(3); plt.plot(sdiff)
            #print(np.max(sdiff), np.mean(sdiff**2))
            #assert np.max(sdiff) < 1e-3, "error too large" 
            assert np.max(sdiff) > 1e-3, "error too large" 
            ia = np.concatenate((np.ones(args.Nflt/2)*.98, samp_in))
            fig,ax = plt.subplots(1)
            ax.plot(ia, 'b'); ax.plot(samp_out[1:], 'r'); ax.plot(c, 'y--')
            fig.savefig('__plot2.png')

            # chirp 2 (frequency response, more points)
            print("   chrip 2 ...")
            Nfft = 8*args.Nsamps
            samp_in = signal.chirp(np.arange(Nfft)*1/args.Fs,
                                   0.1, 1, 500)*.98
            samp_out = []
            for ii in xrange(Nfft):
                sig_in.next = int(np.floor(samp_in[ii]*(sMax)))
                yield clock.posedge
                samp_out.append(sig_out//float(sMax))
            samp_out = np.array(samp_out)
            Pi,fi = mlab.psd(samp_in)
            Po,fo = mlab.psd(samp_out)
            ax1.plot(pi*fi, 10*log10(abs(Po/Pi)), 'r')
            ax1.grid(True)
            fig1.savefig('__plot1.png')
            
            raise StopSimulation
Esempio n. 3
0
def main():

    fs = 100e3

    ### Make sound
    t = np.arange(0, 0.1, 1 / fs)
    s = dsp.chirp(t, 80, t[-1], 20000)
    s = cochlea.set_dbspl(s, 50)
    pad = np.zeros(10e-3 * fs)
    sound = np.concatenate((s, pad))

    ### Run model
    anf = cochlea.run_zilany2014(
        sound, fs, anf_num=(100, 0, 0), cf=(125, 20000, 100), seed=0, powerlaw="approximate", species="human"
    )

    ### Accumulate spike trains
    anf_acc = th.accumulate(anf, keep=["cf", "duration"])
    anf_acc.sort("cf", ascending=False, inplace=True)

    ### Plot auditory nerve response
    fig, ax = plt.subplots(2, 1)
    th.plot_signal(signal=sound, fs=fs, ax=ax[0])
    th.plot_neurogram(anf_acc, fs, ax=ax[1])
    plt.show()
Esempio n. 4
0
def generate_chirp_spectrogram_plot():
    fs = 10e3
    N = 1e5
    amp = 2 * np.sqrt(2)
    noise_power = 0.001 * fs / 2
    time = np.arange(N) / fs
    freq = np.linspace(1e3, 2e3, N)
    x = amp * chirp(time, 1e3, 2.0, 6e3, method='quadratic') + \
        np.random.normal(scale=np.sqrt(noise_power), size=time.shape)

    f, t, Sxx = spectrogram(x, fs)

    ax = plt.subplot(211)
    ax.pcolormesh(t, f, Sxx)
    ax.set_ylabel('Frequency [Hz]')
    ax.set_xlabel('Time [sec]')

    f, t, Sxx = spectrogram_lspopt(x, fs, c_parameter=20.0)

    ax = plt.subplot(212)
    ax.pcolormesh(t, f, Sxx)
    ax.set_ylabel('Frequency [Hz]')
    ax.set_xlabel('Time [sec]')

    plt.show()
Esempio n. 5
0
def sweep_cosine(n, fs, f0, f1, A=1., kwargs=None):
    """
    Build a generator that yields a sweep sine between f0 and f1.

    Parameters
    ----------
    n : int
        Number of samples generated.
    fs : int
        Sample rate in Hz.
    f0 : float
        Initial frequency in Hz.
    f1 : float
        Final frequency in Hz such that f1>f0
    A : float, optional
        Amplitude (the default is 1.0).
    phi : float, optional
        original phase in degrees, default is -90 (sin chirp).

    Yields
    ------
    s : float
        Sequence of sweep values.
    """
    if kwargs is None:
        kwargs = {}
    if 'phi' not in kwargs.keys():
        kwargs.update({'phi': -90})
    from numpy import linspace
    from scipy.signal import chirp
    T = float(n-1)/float(fs)
    for t in linspace(0, T, n):
        yield A*chirp(t, f0=f0, f1=f1, t1=T, **kwargs)
def main():

    fs = 100e3

    ### Make sound
    t = np.arange(0, 0.1, 1/fs)
    s = dsp.chirp(t, 80, t[-1], 20000)
    s = cochlea.set_dbspl(s, 50)
    s = np.concatenate( (s, np.zeros(10e-3 * fs)) )



    ### Run model
    rates = cochlea.run_zilany2014_rate(
        s,
        fs,
        anf_types=['msr'],
        cf=(125, 20000, 100),
        powerlaw='approximate',
        species='human'
    )


    ### Plot rates
    fig, ax = plt.subplots()
    img = ax.imshow(
        rates.T,
        aspect='auto'
    )
    plt.colorbar(img)
    plt.show()
Esempio n. 7
0
def sweepChirp(dur,f0,chirpLength,f1):
    '''Generate a sweeping chirp from f0 to f1'''
    # http://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.chirp.html
    t = range(1,dur+1)
    t1 = chirpLength
    sweep = chirp(t, f0, t1, f1, method='linear', phi=0, vertex_zero=True)
    return sweep
 def setUp(self):
     samplerate = 16000  # LimsiSad require Fs = 16000 Hz
     duration = 10
     t = np.arange(0, duration, 1/samplerate)
     samples = chirp(t=t, f0=20, t1=t[-1], f1=samplerate/2,
                     method='logarithmic')
     decoder_cls = timeside.core.get_processor('array_decoder')
     self.decoder = decoder_cls(samples, samplerate=samplerate)
Esempio n. 9
0
def createChirp(rate,chirp_len,chunk,begin_freq,end_freq):
	time_base=np.arange(0,chirp_len,1.0/rate)
	chirp_data_Hex=10*'\x00\x00' # add some zeros before the signal, this must be counted for the time of flight
	for t in np.nditer(time_base):
		chirp_data_Hex=chirp_data_Hex+struct.pack('h',int(ss.chirp(t,begin_freq,chirp_len,end_freq)*(32767))) #32767 is the max value for format paInt16
	chirp_data_Int=np.array(struct.unpack("%dh" % (len(chirp_data_Hex)/2), chirp_data_Hex))
	norm_chirp=math.sqrt(((chirp_data_Int/10000.0)*(chirp_data_Int/10000.0)).sum())*10000
	return chirp_data_Hex,chirp_data_Int,norm_chirp
Esempio n. 10
0
 def write_bin(self,rate,time):
     t=arange(0,time,1.0/self._framerate)
     wave_data=signal.chirp(t,rate,time,rate,method='linear')*self._volumn
     wave_data=wave_data.astype(short)
     if self.f:
         self.f.writeframes(wave_data.tostring())
     else:
         self.data+=wave_data.tostring()
     self._tall+=time
Esempio n. 11
0
    def create(self):

        t = np.linspace(
            0,
            self.duration,
            self.sample_rate * self.duration - 1
        )
        sweep = chirp(t, 20, self.duration, 20000, self.method) * 32767

        return sweep.astype(np.int16)
Esempio n. 12
0
	def _render(self):
		times = self.t_axis()
		t1 = times[-1]
		return chirp(
			t=self.t_axis(),
			f0=self.f0,
			f1=self.f1,
			t1=t1,
			method=self.method
		)
Esempio n. 13
0
File: pybej.py Progetto: lnyk/pybej
def CreateSweep(framerate = 44100, duration = 3, freq_start = 20, freq_stop = 18000):
    # 打开WAV文档
    f = wave.open(r"sweep.wav", "wb")

    # 配置声道数、量化位数和取样频率
    f.setnchannels(1)
    f.setsampwidth(2)
    f.setframerate(framerate)
    # 产生升序频率扫描波
    t = np.arange(0, duration/2, 1.0/framerate)
    wave_data = signal.chirp(t, freq_start, duration/2, freq_stop, method='linear') * 10000
    wave_data = wave_data.astype(np.short)
    # 将wav_data转换为二进制数据写入文件
    f.writeframes(wave_data.tostring())
    # 产生降序频率扫描波
    wave_data = signal.chirp(t, freq_stop, duration/2, freq_start, method='linear') * 10000
    wave_data = wave_data.astype(np.short)
    # 将wav_data转换为二进制数据写入文件
    f.writeframes(wave_data.tostring())
    f.close()
Esempio n. 14
0
def main(N=1e7):
    N = int(N)
    # Generate a chirp that sweeps all frequencies
    c = ss.chirp(np.arange(N),0,N-1,0.49)
    # Compute fft for plot
    C = np.fft.fft(c, N*10)
    # This is the groundtruth IF
    f = 0.5*np.arange(N)/(N-1)
    # Compute AM-FM DCA 
    ia,ip,ifeq = amfm_DCA(c)
  
    print "%.2e"%np.linalg.norm(np.abs(ifeq-f)/N)
Esempio n. 15
0
def GenerateData(freq_low, freq_high, length, sampling_freq):
    '''
    Simple chirp synthesis
    '''
    end_time_s = float(length) / sampling_freq

    time = numpy.arange(0,
                        end_time_s,
                        1.0 / sampling_freq)
    return signal.chirp(t = time,
                        f0 = freq_low,
                        t1 = end_time_s,
                        f1 = freq_high)
Esempio n. 16
0
def test_strf_fit():
    
    # stimulus features
    lo_freq = 200 # Hz
    hi_freq = 12000 # Hz
    fs = hi_freq*2 # Hz
    duration = 100 # seconds
    tr_length = 1.0 # seconds
    tr_sampling_rate = 1 # number of time-samples per TR to plot the STRF in
    time_window = 0.5 # seconds
    freq_window = 256 # this is 2x the number of freq bins we'll end up with in the spectrogram
    scale_factor = 1.0 # how much to downsample the spectrotemporal space
    num_timepoints = np.floor(duration / tr_length)
    degrees = 0.0
    
    # sample the time from 0-duration by the fs
    time = np.linspace(0,duration,duration*fs)
    
    # create a chirp stimulus
    signal = chirp(time, lo_freq, duration, hi_freq)
    
    # instantiate an instance of the Stimulus class
    stimulus = AuditoryStimulus(signal, tr_length, freq_window, time_window, sampling_rate=fs, 
                                tr_sampling_rate=tr_sampling_rate, scale_factor=scale_factor)
    
    
    # set some parameters for the mock STRF
    freq_center = 5678 # center frequency
    freq_sigma = 234 # frequency dispersion
    hrf_delay = 0.987 # seconds
    
    # initialize the strf model
    model = strf.SpectrotemporalModel(stimulus)
    
    # generate the modeled BOLD response
    data = strf.compute_model_ts(freq_center, freq_sigma, hrf_delay,
                                 model.stimulus.time_coord, 
                                 model.stimulus.freq_coord,
                                 model.stimulus.spectrogram.astype('double'),
                                 tr_length, num_timepoints, norm_func=utils.zscore)
    
    # set some searh parameters
    search_bounds = ((lo_freq, hi_freq),(lo_freq, hi_freq/2),(-5,5),)
    fit_bounds = ((lo_freq, hi_freq),(lo_freq, hi_freq/2),(-5,5),)
    
    # fit the response
    fit = strf.SpectrotemporalFit(data, model, search_bounds, fit_bounds, tr_length)
    
    # assert
    npt.assert_almost_equal(fit.estimate,[freq_center,freq_sigma,hrf_delay])
Esempio n. 17
0
    def signal(self, fs, atten, caldb, calv):
        amp = self.amplitude(caldb, calv)
        npts = self._duration*fs
        t = np.arange(npts).astype(float)/fs
        signal = chirp(t, f0=self._start_f, f1=self._stop_f, t1=self._duration)
        amp_scale = signal_amplitude(signal, fs)
        signal = ((signal/amp_scale)*amp)

        if self._risefall > 0:
            rf_npts = int(self._risefall * fs) / 2
            wnd = hann(rf_npts*2) # cosine taper
            signal[:rf_npts] = signal[:rf_npts] * wnd[:rf_npts]
            signal[-rf_npts:] = signal[-rf_npts:] * wnd[rf_npts:]
        return signal
Esempio n. 18
0
    def set_gram(self):
        '''
        Generate some raw data for testing. 

        Data is a chirp sweeping from 100Hz to 10kHz logarithmically over 10
        seconds at a 44.1kHz sampling rate.
        '''
        fs = 44100
        t_begin = 0
        t_end = 100
        t = np.linspace(t_begin, t_end, (t_end - t_begin)*fs)
        signal = chirp(t, f0=100, t1=100, f1=10000, method='logarithmic')
        self.gram = RawLTSA(signal, fs)
        self.gram()
        return self.gram
def generate_ess(fs, f0, f1, t_sw):

    #compute Sweep time in samples

    n_samp = int(fs * t_sw)

    #generate time vector
    t_vec = numpy.linspace(0, t_sw, n_samp)

    #generate sine sweep
    m_sig = chirp(t_vec, f0, t_sw , f1, method='logarithmic')
    
    m_sig_list = m_sig.tolist()

    return m_sig_list
Esempio n. 20
0
def test_spectrogram_method():
    """Test the spectrogram method's functionality."""
    fs = 10e3
    N = 1e5
    amp = 2 * np.sqrt(2)
    noise_power = 0.001 * fs / 2
    time = np.arange(N) / fs
    freq = np.linspace(1e3, 2e3, N)
    x = amp * chirp(time, 1e3, 2.0, 6e3, method='quadratic') + \
        np.random.normal(scale=np.sqrt(noise_power), size=time.shape)

    f, t, Sxx = spectrogram_lspopt(x, fs, c_parameter=20.0)
    f_sp, t_sp, Sxx_sp = spectrogram(x, fs)

    assert True
Esempio n. 21
0
def wave(duration, dt, f):
    """
    Generates a monofrequency waveform
    
    :param duration: The length in seconds of the wave.
    :param dt: is the sample interval in seconds (usually 0.001, 0.002, 0.004)
    :param f: frequency
    
    :returns: A waveform.
    """
    
    t = np.arange(0, duration , dt)
    A = chirp(t, f0=f, f1=f, t1=duration, method="linear")
    output =  A / np.amax(A)

    return output
Esempio n. 22
0
def test_attenuation_curve():
    fs = 5e5
    duration = 0.2
    npts = duration*fs
    t = np.arange(npts).astype(float)/fs

    # add linear drop to get log atten curve
    desired_signal = signal.chirp(t, f0=5000, f1=1e5, t1=duration)
    received_signal = desired_signal*np.linspace(10, 1, npts)

    atten = tools.attenuation_curve(desired_signal, received_signal, fs, 5000, smooth_pts=99)
    atten_range = np.amax(atten[100:20000]) - np.amin(atten[100:20000])

    assert np.around(atten_range) == 20
    assert np.around(atten[20000]) == 20
    assert atten[1000] == 0
Esempio n. 23
0
def _create_chirp(args, imax=8):
    """generate a chirp signal, DUT input
    """
    tarray = np.arange(args.Nsamps/2)*(1./args.Fs)
    # chirp(tarray, time zero freq, time end freq, end freq)
    xin = signal.chirp(tarray, 2, tarray[-1], 230,
                       method=u'logarithmic') * .94

    # chirp down and up
    xin = np.concatenate(
        (xin, 
         np.array([-1*ss for ss in reversed(xin[:-1])]),
         -1*xin[:30],
        ))

    xin = map(int, [round(xx*imax) for xx in xin])
    return xin
Esempio n. 24
0
def main():

    fs = 100e3

    ### Make sound
    t = np.arange(0, 0.1, 1/fs)
    s = dsp.chirp(t, 80, t[-1], 20000)
    s = cochlea.set_dbspl(s, 50)
    s = np.concatenate( (s, np.zeros(10e-3 * fs)) )



    ### Run model
    anf = cochlea.run_zilany2009(
        s,
        fs,
        anf_num=(100,0,0),
        cf=(80, 20000, 100),
        seed=0,
        powerlaw='approximate'
    )



    ### Plot auditory nerve response
    anf_acc = th.accumulate(anf, keep=['cf', 'duration'])
    anf_acc.sort('cf', ascending=False, inplace=True)

    cfs = anf.cf.unique()

    fig, ax = plt.subplots(2,1, sharex=True)
    th.plot_neurogram(
        anf_acc,
        fs,
        ax=ax[0]
    )

    th.plot_raster(
        anf[anf.cf==cfs[30]],
        ax=ax[1]
    )

    ax[1].set_title("CF = {}".format(cfs[30]))

    plt.show()
Esempio n. 25
0
def sweep(duration, dt, f, method = 'linear'):
    """
    Generates a sweep
    Does a wrapping of scipy.signal.chirp
    
    :param duration: The length in seconds of the wavelet.
    :param dt: is the sample interval in seconds (usually 0.001, 0.002, 0.004)
    :param f: Tuple of (f1, f2) with starting and end frequencies
    :keyword method: {'linear','quadratic','logarithmic'}, optional

    :returns: An LFM waveform.
    """
    
    t = np.arange(0, duration , dt)
    freq = np.array( f )
    A = chirp(t, f0=freq[0], f1=freq[1], t1=duration, method=method)
    output =  A / np.amax(A)

    return output
def main():

    fs = 48e3

    ### Make sound
    tmax = 0.03
    t = np.arange(0, tmax, 1/fs)
    s = dsp.chirp(t, 80, t[-1], 16000)
    sound = cochlea.set_dbspl(s, 50)



    ### Run model
    anf = run_matlab_auditory_periphery(
        sound,
        fs,
        anf_num=(100,50,20),
        cf=(125, 16000, 80),
        seed=0,
    )



    ### Accumulate spike trains
    anf_acc = th.accumulate(anf, keep=['cf', 'duration'])
    anf_acc.sort('cf', ascending=False, inplace=True)



    ### Plot auditory nerve response
    fig, ax = plt.subplots(2, 1, sharex=True)
    th.plot_signal(
        signal=sound,
        fs=fs,
        ax=ax[0]
    )
    th.plot_neurogram(
        anf_acc,
        fs,
        ax=ax[1]
    )
    plt.show()
Esempio n. 27
0
  def test_sweep(self):
    amp = db_to_ratio(-6)
    te = 8
    t = numpy.linspace(0, 8, self.from_rate*8)
    x = signal.chirp(t, f0=0, f1=self.from_rate, t1=te, method='quadratic') * amp
    print("done chirp")

    y = self.resample(x)
    print("done filtering")

    nfft = 64
    win = scipy.hamming(nfft)

    plot.subplot(211)
    plot.specgram(x, NFFT=nfft, Fs=self.from_rate, noverlap=nfft/2, window=win)

    plot.subplot(212)
    plot.specgram(y, NFFT=nfft, Fs=self.to_rate, noverlap=nfft/2, window=win)

    plot.show()
Esempio n. 28
0
def xtest_calibrate_signal():
    fs = 5e5
    duration = 0.2
    npts = duration*fs
    t = np.arange(npts).astype(float)/fs

    frange = [5000, 100000]
    # add linear drop to get log atten curve
    desired_signal = signal.chirp(t, f0=5000, f1=1e5, t1=duration)
    received_signal = desired_signal*np.linspace(1, 0.1, npts)

    calibrated_signal = tools.calibrate_signal(desired_signal, received_signal, fs, frange)

    plt.plot(desired_signal)
    plt.figure()
    plt.plot(calibrated_signal)
    plt.show()

    assert calibrated_signal.shape == desired_signal.shape
    print 'signal max', np.amax(calibrated_signal)
    assert np.amax(calibrated_signal) == 10
Esempio n. 29
0
def demo(args):
    """
    Demo of AM-FM.

    Parameters
    ----------
    args: argparse args
    """
    logger.info("Running a demo of AM-FM")
    # number of time points
    N = args.N

    logger.info("Generating a chirp that sweeps all frequencies")
    c = ss.chirp(range(N), 0 , N - 1, 0.49)

    logger.info("Computing fft for plot")
    C = np.fft.fft(c, N * 10)
    # This is the groundtruth IF
    f = 0.5 * np.arange(N) / (N - 1)

    logger.info("Computing AM-FM DCA")
    ia, ip, ifeq = amfm_DCA(c)
    # plot results

    logger.info("Plotting")
    plt.subplot(311)
    plt.plot(c)
    plt.title("Time series")
    plt.subplot(312)
    plt.plot(np.fft.fftfreq(N * 10), np.abs(C), ".")
    plt.title("Frequency spectrum")
    plt.subplot(313)
    plt.plot(f)
    plt.plot(ifeq)
    plt.legend(["Ideal", "Estimated"], loc = "best")
    plt.title("Frequency vs time")
    if args.out_file:
        plt.savefig(args.out_file)
    else:
        plt.show()
Esempio n. 30
0
def main():

    fs = 48e3

    ### Make sound
    t = np.arange(0, 0.1, 1/fs)
    s = dsp.chirp(t, 80, t[-1], 20000)
    s = cochlea.set_dbspl(s, 50)
    s = np.concatenate( (s, np.zeros(10e-3 * fs)) )



    ### Run model
    anf_trains = cochlea.run_holmberg2007(
        s,
        fs,
        anf_num=(100,0,0),
        seed=0,
    )


    ### Plot auditory nerve response
    anf_acc = th.accumulate(anf_trains, keep=['cf', 'duration'])
    anf_acc.sort('cf', ascending=False, inplace=True)


    fig, ax = plt.subplots(2,1)
    th.plot_signal(
        signal=s,
        fs=fs,
        ax=ax[0]
    )
    th.plot_neurogram(
        anf_acc,
        fs,
        ax=ax[1]
    )
    plt.show()
Esempio n. 31
0
############ Mixed sine
print("chirp")
NSAMP = 500
F0 = 200 + (50 * np.random.rand(NSAMP, ))
F1 = 900 + (100 * np.random.rand(NSAMP, ))
### amps in 0.5, 3.0
amps = 2.5 * np.random.rand(NSAMP, )
amps += 0.5
###
meth = ['linear', 'quadratic', 'logarithmic', 'hyperbolic']
imeth = np.random.randint(0, 4, size=(NSAMP, ))
### output array
MS = np.zeros((NSAMP, tsize))
### workloop
for i in range(NSAMP):
    MS[i] = amps[i] * ssg.chirp(
        t, f0=F0[i], t1=T, f1=F1[i], method=meth[imeth[i]])
    MS[i] += np.random.randn(tsize, )
    ### end
### spectogram
spdict = {'fs': fs, 'nperseg': fs // 9, 'noverlap': fs // 10, 'nfft': fs // 9}
###### size from ipy shell
MSP = np.zeros((NSAMP, 114, 80))
for i in range(NSAMP):
    sf, st, sxx = ssg.spectrogram(MS[i], **spdict)
    MSP[i] = sxx
### end
if True:
    np.save("chirp_timeseries_noise.npy", MS)
    np.save("chirp_sxx_noise.npy", MSP)
Esempio n. 32
0
print("Serial connected")

mode = str(sys.argv[1])

# Torque bandwidth: 0.1, 40, 60, 400, 6
# Hysteresis: .1, .1, 180, 400, 6
freq_start = 2  #0.1#.25 #Hz
freq_end = 2  #40#.25 #Hz
time_end = 3  #400 #seconds
eval_freq = 400  #300#200 #evaluations per second
max_torque = 15  #10 #Nm

file_name = str(sys.argv[2]) + '_' + str(max_torque) + 'Nm' + '.csv'

t = np.linspace(0, time_end, time_end * eval_freq)
chrp = signal.chirp(t, freq_start, time_end, freq_end)


def p():
    pub = rospy.Publisher("/blue_controllers/torque_controller/command",
                          Float64MultiArray,
                          queue_size=1)
    rospy.init_node('p')
    rate = rospy.Rate(
        500)  #Make sure this is fast enough to handle our frequency
    start_time = time.time() + 1  # in seconds
    pitch = 0
    roll = 0
    count = 0
    cmd = Float64MultiArray()
    while not rospy.is_shutdown():
Esempio n. 33
0
# declare general signal variables:
dur = 3  # duration in seconds
sr = 44100  # sampling rate
t = np.linspace(0, dur, dur * sr, endpoint=False)  # time vector

# Q: What's the dimensionality of the time vector? why?
# A: 1x132300, there are 132300 timestamps refering to each sample
# Q: What is the Nyquist limit of this signal?
# A:sr/2  ->  22050Hz

# Define the nyquist limit using the relevant variables defined so far
nyq = int(sr / 2)  # your code here

# generate a sine sweep lasting dur and going from 20Hz to 20kHz. Hint: use the scipy chirp function
y = chirp(t, 20, 3, 20000)  # your code here

# we can listen to the resulting signal using these functions
from IPython.display import Audio
Audio(data=y, rate=sr)

librosa.display.waveplot(y, sr)

# compute the FFT of the signal using scipy's fft
Y = fft(y)  # your code here

# the FFT is complex-valued, so get its magnitude using np.abs
Y = np.abs(Y)  # your code here

# compute the frequency bins for the fft using np.linspace
f = np.linspace(0, Y.shape[0], Y.shape[0]) * sr / Y.shape[0]  # your code here
Esempio n. 34
0
File: base.py Progetto: hxxn85/chirp
def chirp(b, tp, oversamplerate, f):
    fs = oversamplerate * b
    n = int(fs * tp)
    t = np.arange(n) / fs

    return signal.chirp(t, f[0], tp, f[1])
def generate_sweep(f1, f2, fs, T, volume):
    assert volume > 0 and volume <= 1, "The volume must be between 0 and 1"
    t = np.linspace(0, T, T*fs)
    w = (chirp(t, f1, T, f2, method='linear', phi=90)*volume).astype(np.float32)
    return w
Esempio n. 36
0
def genSyncPulse(f0 = 440.0, f1 = 4200.0, fs = 44100.0, t1 = 0.05, method='quadratic'):
    t = np.r_[0:t1:1.0/fs]
    return sp.chirp(t,f0,t1,f1, method=method)
Esempio n. 37
0
def demoBandpassFilterFIR():
    order = 20
    sampRate = 256.0
    nyquist = sampRate / 2.0
    lowFreq = 1.5
    highFreq = 40.0

    sincBla = BandpassFilter(lowFreq,
                             highFreq,
                             sampRate,
                             order,
                             filtType='sinc-blackman')
    sincHan = BandpassFilter(lowFreq,
                             highFreq,
                             sampRate,
                             order,
                             filtType='sinc-hann')
    sincHam = BandpassFilter(lowFreq,
                             highFreq,
                             sampRate,
                             order,
                             filtType='sinc-hamming')
    lanczos = BandpassFilter(lowFreq,
                             highFreq,
                             sampRate,
                             order,
                             filtType='lanczos')

    fig = plt.figure(figsize=(18, 10))
    fig.canvas.set_window_title('FIR Bandpass Filter Demo')
    axLn = fig.add_subplot(2, 2, 1)
    axDb = fig.add_subplot(2, 2, 2)

    for ax, scale in zip((axLn, axDb), ('linear', 'db')):
        sincBla.plotFreqResponse(showCorners=True,
                                 scale=scale,
                                 label='Sinc-Blackman',
                                 ax=ax,
                                 linewidth=2)
        sincHan.plotFreqResponse(showCorners=False,
                                 scale=scale,
                                 label='Sinc-Hann',
                                 ax=ax,
                                 linewidth=2)
        sincHam.plotFreqResponse(showCorners=False,
                                 scale=scale,
                                 label='Sinc-Hamming',
                                 ax=ax,
                                 linewidth=2)
        lanczos.plotFreqResponse(showCorners=False,
                                 scale=scale,
                                 label='Lanczos',
                                 ax=ax,
                                 linewidth=2)
        #ax.grid()

    axLn.autoscale(tight=True)
    axLn.set_title('Amplitude Response')
    axLn.legend(loc='upper right')

    axDb.set_xlim((0.0, nyquist))
    axDb.set_ylim((-100.0, 0.0))
    axDb.set_title('Power Response')

    axPh = fig.add_subplot(2, 2, 3)
    scale = 'radians'
    sincBla.plotPhaseResponse(showCorners=False,
                              scale=scale,
                              label='Sinc-Blackman',
                              ax=axPh,
                              linewidth=2)
    sincHan.plotPhaseResponse(showCorners=False,
                              scale=scale,
                              label='Sinc-Hann',
                              ax=axPh,
                              linewidth=2)
    sincHam.plotPhaseResponse(showCorners=False,
                              scale=scale,
                              label='Sinc-Hamming',
                              ax=axPh,
                              linewidth=2)
    lanczos.plotPhaseResponse(showCorners=True,
                              scale=scale,
                              label='Lanczos',
                              ax=axPh,
                              linewidth=2)
    axPh.autoscale(tight=True)
    axPh.set_title('Phase Response')

    t = np.linspace(0.0, 2.0, 2.0 * sampRate, endpoint=False)
    f = np.linspace(0.0, nyquist, 2.0 * sampRate, endpoint=False)
    chirp = spsig.chirp(t, 0.0, 2.0, nyquist)

    chirpSincBla = sincBla.filter(chirp)
    chirpSincHan = sincHan.filter(chirp)
    chirpSincHam = sincHam.filter(chirp)
    chirpLanczos = lanczos.filter(chirp)

    sep = -np.arange(0, 5) * 2.0
    chirpAll = np.vstack((chirpSincBla, chirpSincHan, chirpSincHam,
                          chirpLanczos, chirp)).T + sep

    axCh = fig.add_subplot(2, 2, 4)
    axCh.plot(f, chirpAll)
    axCh.vlines(lowFreq, 1, -9, color='violet', linestyle='--')
    axCh.vlines(highFreq, 1, -9, color='violet', linestyle='--')
    axCh.set_yticks([])
    axCh.set_xlabel('Frequency (Hz)')
    axCh.set_ylabel('Chirp')
    axCh.autoscale(tight=True)

    axChTwiny = axCh.twiny()
    axChTwiny.hlines(sep, 0.0, t[-1], linestyle='--', color='black')
    axChTwiny.set_xlabel('Time (s)')

    fig.tight_layout()
Esempio n. 38
0
 Fs = 96000  # Sampling frequency
 Fnyq = Fs / 2  # Nyquist frequency
 dt = 1.0 / Fs  # Sampling interval
 T = 1.0  # Acquisition time
 N = Fs * T  # Total number of samples
 f_range = np.arange(1, Fnyq) * np.pi / Fnyq  # Digital frequencies range
 ramp = np.arange(0, N)  # Linear ramp
 t = ramp * dt  # Time vector
 Fmin = 1  # Chirp min. frequency
 Fmax = 3000  # Chirp max. frequency
 sel = np.arange(Fmin, Fmax)  # Plot range selection
 Win_len = T  # Length of Hanning window
 #
 # Chirp signal with passed with an hp filter
 #
 x = chirp(t, Fmin, T, Fmax, method='linear', phi=0)
 #
 f_hp = 10
 #                 bessel(N, Wn,        btype='low', analog=False, output='ba', fs=None)
 B_hp, A_hp = bessel(1,
                     f_hp / Fnyq,
                     'hp',
                     analog=False,
                     output='ba',
                     norm='mag')
 #
 #                 freqz(b,      a=1,    worN=None,  whole=0,     plot=None)
 w_norm_hp, h_hp = freqz(b=B_hp,
                         a=A_hp,
                         worN=f_range,
                         whole=False,
Esempio n. 39
0
H = 256
if from_file:
    x = np.fromfile('/tmp/me.f64', dtype='float64')
    N = 0
    while N < (len(x) - H):
        N += H
    x = x[:N]
    n = np.arange(N)
    x += np.random.standard_normal(N) * 1e-8
else:
    N = 500 * H
    attack_times = np.array([100 * H + 10, 200 * H - 10, 300 * H - 20])
    n = np.arange(N)
    # chirp frequency
    f0 = 0.01
    x = signal.chirp(n, f0, N, f0)
    x[attack_times] = 1
av = attack_avoider(attack_times, -H, H + W, H)
# stretch factor
S = 1.
# shift factors
min_P = 1.5
max_P = .5
P_osc_freq = 0.00001
p = signal.chirp(n, P_osc_freq, N, P_osc_freq)

p = 0.5 * (p + 1)
p *= (max_P - min_P)
p += min_P

Esempio n. 40
0
def noise_gen(f0, len=21):
    t = np.arange(0, len, 1.0 / 128)
    w = chirp(t, f0, f1=0, t1=21, method="quadratic")
    # pl.plot(t,w)
    # pl.show()
    return w
Esempio n. 41
0
def gen_sweep(start, end, duration):
    t = np.linspace(0, duration, fs*duration)
    w = chirp(t, f0=start, f1=end, t1=duration, method='linear')
    return w
Esempio n. 42
0
    # nodes = [node.path for node in wp.get_level(2, 'freq')]
    # np_lst = []
    # for node in nodes:
    #     np_lst.append(wp[node].data)
    # viz = np.stack(np_lst)

    # print(res)
    # print(viz)
    # print(np.round(res))
    # print(np.round(viz))
    # print('err', np.mean(np.abs(res - viz)))
    # print('stop')

    t = np.linspace(0, 10, 5001)
    wavelet = pywt.Wavelet('db4')
    w = signal.chirp(t, f0=.00001, f1=20, t1=10, method='linear')

    plt.plot(t, w)
    plt.title("Linear Chirp, f(0)=6, f(10)=1")
    plt.xlabel('t (sec)')
    plt.show()

    wp = WaveletPacket(data=np.expand_dims(np.expand_dims(w, 0), 0),
                       wavelet=wavelet,
                       mode='reflect')
    nodes = wp.get_level(7)
    np_lst = []
    for node in nodes:
        np_lst.append(np.squeeze(wp[node]))
    viz = np.stack(np_lst)
    plt.imshow(viz[:20, :])
Esempio n. 43
0
'''
# -*- coding: utf-8 -*-
'''
import matplotlib.pyplot as plt
import numpy as np
import scipy.signal as signal

a = np.array([1.0, -1.947463016918843, 0.9555873701383931])
b = np.array([0.9833716591860479, -1.947463016918843, 0.9722157109523452])

# 44.1kHz, 1秒的频率扫描波
t = np.arange(0, 0.5, 1 / 44100.0)
x = signal.chirp(t, f0=10, t1=0.5, f1=1000.0)

# 直接一次计算滤波器的输出
y = signal.lfilter(b, a, x)

# 将输入信号分为50个数据一组
x2 = x.reshape((-1, 50))

# 滤波器的初始状态为0, 长度是滤波器系数长度-1
z = np.zeros(max(len(a), len(b)) - 1, dtype=np.float)
y2 = []  # 保存输出的列表

for tx in x2:
    # 对每段信号进行滤波,并更新滤波器的状态z
    ty, z = signal.lfilter(b, a, tx, zi=z)
    # 将输出添加到输出列表中
    y2.append(ty)

# 将输出y2转换为一维数组
Esempio n. 44
0
import soundfile as sf
from scipy.signal import chirp
import numpy as np
import matplotlib.pyplot as plt


# 数値をminus→逆位相にする関数
def calc_minus(n):
    return n * (-1)


# サンプル波形を生成(チャープ信号)
samplerate = 44100  # サンプリングレート
ts = 0  # 信号の開始時間
tf = 3  # 信号の終了時間
t = np.linspace(ts, tf, tf * samplerate)  # 時間軸を作成
L = chirp(t, f0=100, f1=300, t1=tf,
          method='linear')  # 100Hz - 300Hz  linear に tf秒で出力する
R = list(map(calc_minus, L))  #逆位相のリストを作成する

LR_minus = []
LR_plus = []

for (L_data, R_data) in zip(L, R):
    LR_minus.append([L_data, R_data])
    LR_plus.append([L_data, L_data])

#[[L,R],[L,R],[L,R] ・・・] というリストを soundfile はwav に変換することができる

sf.write('stereo_minus.wav', LR_minus, samplerate)
sf.write('stereo_plus.wav', LR_plus, samplerate)
Esempio n. 45
0
# -*- coding: utf-8 -*-
import scipy.signal as signal
import pylab as pl
import numpy as np
from numpy.lib.stride_tricks import as_strided

sampling_rate = 8000.0
fft_size = 1024
step = fft_size/16 
time = 2

t = np.arange(0, time, 1/sampling_rate)
sweep = signal.chirp(t, f0=100, t1 = time, f1=0.8*sampling_rate/2, method="logarithmic")
number = (len(sweep)-fft_size)/step 
data = as_strided(sweep, shape=(number, fft_size), strides=(step*8, 8)) 

window = signal.hann(fft_size) 
data = data * window 

spectrogram = np.abs(np.fft.rfft(data, axis=1)) 
spectrogram /= fft_size/2
np.log10(spectrogram, spectrogram)
spectrogram *= 20.0

pl.figure(figsize=(8,4))
im = pl.imshow(spectrogram.T, origin = "lower", 
    extent=[0, 2, 0, sampling_rate/2], aspect='auto') 
bar = pl.colorbar(im, fraction=0.05)
bar.set_label("能量(dB)")
pl.xlabel("时间(秒)")
pl.ylabel("频率(Hz)")
Esempio n. 46
0
def sweep(freqMin=None,
          freqMax=None,
          samplingRate=None,
          fftDegree=None,
          startMargin=None,
          stopMargin=None,
          method='logarithmic',
          windowing='hann'):
    """
    Generates a chirp signal defined by the "method" input, windowed, with
    silence interval at the beggining and end of the signal, plus a hanning
    fade in and fade out.

    >>> x = pytta.generate.sweep()
    >>> x.plot_time()

    Return a signalObj containing a logarithmic chirp signal from 17.8 Hz
    to 22050 Hz, with a fade in beginning at 17.8 Hz time instant and ending at
    the 20 Hz time instant; plus a fade out beginning at 20000 Hz time instant
    and ending at 22050 Hz time instant.

    The fade in and the fade out are made with half hanning window. First half
    for the fade in and last half for the fade out. Different number of points
    are used for each fade, so the number of time samples during each frequency
    is respected.

    Input arguments (default), (type):
    ------------------------

        * freqMin (20), (float)

        * freqMax (20), (float)

        * samplingRate (44100), (int)

        * fftDegree (18), (float)

        * startMargin (0.3), (float)

        * stopMargin (0.7), (float)

        * method (logarithmic'), (string)

        * windowing ('hann'), (string)


    """
    # Code snippet to guarantee that generated object name is
    # the declared at global scope
    # for frame, line in traceback.walk_stack(None):
    for framenline in traceback.walk_stack(None):
        # varnames = frame.f_code.co_varnames
        varnames = framenline[0].f_code.co_varnames
        if varnames == ():
            break
    # creation_file, creation_line, creation_function, \
    #     creation_text = \
    extracted_text = \
        traceback.extract_stack(framenline[0], 1)[0]
    # traceback.extract_stack(frame, 1)[0]
    # creation_name = creation_text.split("=")[0].strip()
    creation_name = extracted_text[3].split("=")[0].strip()

    # It was done like this because a function default argument is a value
    # assigned at import time, and PyTTa have a default object that handles
    # default values for all functions and all classes across all submodules.
    # In order to it work as expected, the values should be reassigned at
    # every function call to get updated default values. Otherwise, despite
    # how the default has it's properties values changed, it won't change
    # for the function calls.
    if freqMin is None:
        freqMin = default.freqMin
    if freqMax is None:
        freqMax = default.freqMax
    if samplingRate is None:
        samplingRate = default.samplingRate
    if fftDegree is None:
        fftDegree = default.fftDegree
    if startMargin is None:
        startMargin = default.startMargin
    if stopMargin is None:
        stopMargin = default.stopMargin

    # frequency limits [Hz]
    freqLimits = {
        'freqMin': freqMin / (2**(1 / 6)),
        'freqMax': min(freqMax * (2**(1 / 6)), samplingRate / 2)
    }
    samplingTime = 1 / samplingRate  # [s] sampling period

    stopSamples = stopMargin * samplingRate
    # [samples] initial silence number of samples

    startSamples = startMargin * samplingRate
    # [samples] ending silence number of samples

    marginSamples = startSamples + stopSamples
    # [samples] total silence number of samples

    numSamples = 2**fftDegree  # [samples] full signal number of samples

    sweepSamples = numSamples - marginSamples + 1
    # [samples] actual sweep number of samples

    if sweepSamples < samplingRate / 10:
        raise Exception('Too small resultant sweep. For such big margins you' +
                        ' must increase your fftDegree.')

    sweepTime = sweepSamples / samplingRate  # [s] sweep's time length
    timeVecSweep = np.arange(0, sweepTime, samplingTime)  # [s] time vector
    if timeVecSweep.size > sweepSamples:
        timeVecSweep = timeVecSweep[0:int(sweepSamples)]  # adjust length
    sweep = 0.95 * ss.chirp(timeVecSweep,
                            freqLimits['freqMin'],
                            sweepTime,
                            freqLimits['freqMax'],
                            'logarithmic',
                            phi=-90)  # sweep, time domain
    sweep = __do_sweep_windowing(sweep, timeVecSweep, freqLimits, freqMin,
                                 freqMax, windowing)  # fade in and fade out
    # add initial and ending slices
    timeSignal = np.concatenate(
        (np.zeros(int(startSamples)), sweep, np.zeros(int(stopSamples))))
    if timeSignal.size != numSamples:
        timeSignal = timeSignal[0:int(numSamples)]  # adjust length

    # transforms into a pytta signalObj and sets the correct name
    sweepSignal = SignalObj(signalArray=timeSignal,
                            domain='time',
                            samplingRate=samplingRate,
                            **freqLimits)

    sweepSignal.creation_name = creation_name

    return sweepSignal
Esempio n. 47
0
w, h = signal.freqz(b, a)

# 计算增益
power = 20 * np.log10(np.clip(np.abs(h), 1e-8, 1e100))

# 绘制增益
pl.subplot(211)
pl.plot(w / np.pi * sampling_rate / 2, power)
pl.title("freqz计算的滤波器频谱")
pl.ylim(-100, 20)
pl.ylabel("增益(dB)")

# 产生2秒钟的取样频率为sampling_rate Hz的频率扫描信号
# 开始频率为0, 结束频率为sampling_rate/2
t = np.arange(0, 2, 1 / sampling_rate)
sweep = signal.chirp(t, f0=0, t1=2, f1=sampling_rate / 2)

# 将频率扫描信号进行滤波
out = signal.lfilter(b, a, sweep)

# 将波形转换为能量
out = 20 * np.log10(np.abs(out))

# 找到所有局部最大值的下标
index = np.where(np.logical_and(out[1:-1] > out[:-2],
                                out[1:-1] > out[2:]))[0] + 1

# 绘制滤波之后的波形的增益
pl.subplot(212)
pl.plot(t[index] / 2.0 * 4000, out[index])
pl.title("频率扫描波测量的滤波器频谱")
Esempio n. 48
0
from __future__ import division

import numpy as np
import scipy.signal as sp

from helpers import *
#import matplotlib.pyplot as plt

f0 = 440.0
f1 = 4200.0
fs = 44100.0
t1 = 0.05
t = np.r_[0:t1:1.0/fs]

SYNC_PULSE = sp.chirp(t,f0,t1,f1, method='quadratic')

def genPreamble(data = None, mod_func = None, sync_pulse = SYNC_PULSE):
    if data:
        mod_data = mod_func(data)
        return np.append(sync_pulse, mod_data)

    else:
        return sync_pulse

def genSyncPulse(f0 = 440.0, f1 = 4200.0, fs = 44100.0, t1 = 0.05, method='quadratic'):
    t = np.r_[0:t1:1.0/fs]
    return sp.chirp(t,f0,t1,f1, method=method)

def genSyncPulse2(fc= 1800, fd = 600, fs = 44100.0, t = .05):
    num_samples = int(t * fs)
    pulse = np.ones(num_samples)
Esempio n. 49
0
def demoBandpassFilterIIR():
    order = 5
    sampRate = 256.0
    nyquist = sampRate / 2.0
    lowFreq = 1.5
    highFreq = 45.0
    zeroPhase = True

    butter = BandpassFilter(lowFreq,
                            highFreq,
                            sampRate,
                            order,
                            filtType='butter',
                            zeroPhase=zeroPhase)
    #cheby1 = BandpassFilter(0.0, highFreq, sampRate, order,
    #                        filtType='cheby1', rp=1.0, zeroPhase=zeroPhase)
    cheby2 = BandpassFilter(lowFreq,
                            highFreq,
                            sampRate,
                            order,
                            filtType='cheby2',
                            rs=20.0,
                            zeroPhase=zeroPhase)
    ellip = BandpassFilter(lowFreq,
                           highFreq,
                           sampRate,
                           order,
                           filtType='ellip',
                           rp=1.0,
                           rs=20.0,
                           zeroPhase=zeroPhase)
    bessel = BandpassFilter(lowFreq,
                            highFreq,
                            sampRate,
                            order,
                            filtType='bessel',
                            zeroPhase=zeroPhase)

    fig = plt.figure(figsize=(18, 10))
    fig.canvas.set_window_title('IIR Bandpass Filter Demo')
    axLn = fig.add_subplot(2, 2, 1)
    axDb = fig.add_subplot(2, 2, 2)

    for ax, scale in zip((axLn, axDb), ('linear', 'db')):
        butter.plotFreqResponse(showCorners=False,
                                scale=scale,
                                label='Butterworth',
                                ax=ax,
                                linewidth=2)
        #cheby1.plotFreqResponse(showCorners=False, scale=scale, label='Cbebyshev-I', ax=ax, linewidth=2)
        cheby2.plotFreqResponse(showCorners=False,
                                scale=scale,
                                label='Cbebyshev-II',
                                ax=ax,
                                linewidth=2)
        ellip.plotFreqResponse(showCorners=False,
                               scale=scale,
                               label='Elliptical',
                               ax=ax,
                               linewidth=2)
        bessel.plotFreqResponse(showCorners=True,
                                scale=scale,
                                label='Bessel',
                                ax=ax,
                                linewidth=2)
        #ax.grid()

    axLn.autoscale(tight=True)
    axLn.set_title('Amplitude Response')
    axLn.legend(loc='upper right')

    axDb.set_xlim((0.0, nyquist))
    axDb.set_ylim((-100.0, 0.0))
    axDb.set_title('Power Response')

    axPh = fig.add_subplot(2, 2, 3)
    scale = 'radians'
    butter.plotPhaseResponse(showCorners=False,
                             scale=scale,
                             label='Butterworth',
                             ax=axPh,
                             linewidth=2)
    #cheby1.plotPhaseResponse(showCorners=False, scale=scale, label='Chebyshev-I', ax=axPh, linewidth=2)
    cheby2.plotPhaseResponse(showCorners=False,
                             scale=scale,
                             label='Chebyshev-II',
                             ax=axPh,
                             linewidth=2)
    ellip.plotPhaseResponse(showCorners=False,
                            scale=scale,
                            label='Elliptical',
                            ax=axPh,
                            linewidth=2)
    bessel.plotPhaseResponse(showCorners=True,
                             scale=scale,
                             label='Bessel',
                             ax=axPh,
                             linewidth=2)
    axPh.autoscale(tight=True)
    axPh.set_title('Phase Response')

    t = np.linspace(0.0, 2.0, 2.0 * sampRate, endpoint=False)
    f = np.linspace(0.0, nyquist, 2.0 * sampRate, endpoint=False)
    chirp = spsig.chirp(t, 0.0, 2.0, nyquist)

    chirpButter = butter.filter(chirp)
    #chirpCheby1 = cheby1.filter(chirp)
    chirpCheby2 = cheby2.filter(chirp)
    chirpEllip = ellip.filter(chirp)
    chirpBessel = bessel.filter(chirp)

    sep = -np.arange(0, 5) * 2.0
    chirpAll = np.vstack(
        (chirpButter, chirpCheby2, chirpEllip, chirpBessel, chirp)).T + sep

    axCh = fig.add_subplot(2, 2, 4)
    axCh.plot(f, chirpAll)
    axCh.vlines(lowFreq, 1, -9, color='violet', linestyle='--')
    axCh.vlines(highFreq, 1, -9, color='violet', linestyle='--')
    axCh.set_yticks([])
    axCh.set_xlabel('Frequency (Hz)')
    axCh.set_ylabel('Chirp')
    axCh.autoscale(tight=True)
    axChTwiny = axCh.twiny()
    axChTwiny.hlines(sep, 0.0, t[-1], linestyle='--', color='black')
    axChTwiny.set_xlabel('Time (s)')

    fig.tight_layout()
Esempio n. 50
0
#!/usr/bin/env python
from matplotlib import pyplot as plt
from scipy.io import wavfile
import numpy as np
from scipy.signal import decimate,chirp
from scipy.fftpack import fft, ifft,fftfreq
input_dir='/is/ei/naji/Dropbox/Winter Semster 2014/Master Thesis/Programming/Echo Test/'
#s=wavfile.read(input_dir+'Linchirp.wav')
#x=s[1][:200000]
rate=10000
t=np.linspace(0,5,rate*5)
x=chirp(t, f0=2000, t1=5, f1=5000, method='linear')
print x.shape
#x = s1 + s2 + nse # the signal
NFFT = 1000       # the length of the windowing segments
Fs = 1. # the sampling frequency

# Pxx is the segments x freqs array of instantaneous power, freqs is
# the frequency vector, bins are the centers of the time bins in which
# the power is computed, and im is the matplotlib.image.AxesImage
# instance
wavfile.write(input_dir+'chirp_test.wav',rate,x)
ax1 = plt.subplot(211) 
plt.plot(t, x)
plt.subplot(212, sharex=ax1)
Pxx, freqs, bins, im = plt.specgram(x, NFFT=NFFT, Fs=Fs, noverlap=900,cmap=plt.cm.gist_heat)
plt.figure()
#print fftfreq(x.shape[0])
plt.plot(fftfreq(x.shape[0]),abs(fft(x)))
plt.show()
Esempio n. 51
0
show_plot = True
SR = 16000
T = 16
N = SR * T
n = np.arange(N)
t = n / SR
x = np.zeros(N)
T_start = 6
N_start = int(np.round(T_start * SR))
T_end = 12
N_end = int(np.round(T_end * SR))
L_tone = N_end - N_start
n_tone = np.arange(L_tone)
f0 = 1000
x[N_start:N_end] = signal.chirp(n_tone, f0 / SR, L_tone, f0 / SR)
x += np.random.standard_normal(N) * 1e-6
attack_times = [N_start, N_end]

# first time-stretch factor
ts_0 = 3 / 2
# first pitch-shift factor
ps_0 = 0.75

# prepare control signals
W = 1024
H = 128
T_out = T
N_out = int(np.ceil(SR * T_out))
y = np.zeros(N_out)
Esempio n. 52
0
import matplotlib as mpl
import matplotlib.pyplot as plt
from scipy import signal, misc
from scipy import fftpack


f0 = 165
f1 = 295
f2 = 575
fs = 8000

t = np.linspace(0, 2, 2 * fs, endpoint=False)
x0 = np.sin(f0 * 2 * np.pi * t)
x1 = np.sin(f1 * 2 * np.pi * t)
x2 = np.sin(f2 * 2 * np.pi * t)
x3 = signal.chirp(t, 700, 2, 900, method='linear')
x4 = x0 + x1 + x2 + x3

X0 = fftpack.fft(x0)
X1 = fftpack.fft(x1)
X2 = fftpack.fft(x2)
X3 = fftpack.fft(x3)
X4 = fftpack.fft(x4)

fig, ax = plt.subplots(5)
freqs = fftpack.fftfreq(len(t)) * fs

ax[0].stem(freqs, np.abs(X0), use_line_collection=True)
ax[0].set_xlim(-fs/8, fs/8)
ax[0].set_ylabel('(A)', rotation=0, fontsize=15)
ax[1].stem(freqs, np.abs(X1), use_line_collection=True)
Esempio n. 53
0
from scipy import io, signal  # we will also import the signal module, from s


def plot_spectrogram(spg, t, f, freq_lims=[0, 100], plot_db=False):
    plt.figure(figsize=(15, 4))
    if plot_db:
        plt.imshow(10 * np.log10(spg),
                   aspect='auto',
                   extent=[t[0], t[-1], f[-1], f[0]])
    else:
        plt.imshow(spg, aspect='auto', extent=[t[0], t[-1], f[-1], f[0]])
        plt.xlabel('Time')
        plt.ylabel('Frequency(Hz)')
        plt.ylim(freq_lims)
        plt.colorbar()
        plt.tight_layout()


T, fs = 20, 1000
t = np.arange(0, T, 1 / float(fs))
# simulate a signal
# refer to the function documentation for f0, t1, f1
sig = signal.chirp(t, f0=10, t1=20, f1=30)

# plot it
plt.figure(figsize=(15, 3))
plt.plot(t, sig)
plt.xlim([0, 5])
plt.xlabel('Time (s)')
plt.ylabel('Voltage (V)')
Esempio n. 54
0
freq, H = signal.freqz(b)

filterFig, filterAxList = plt.subplots(2,1,sharex=True)
filterAxList[0].plot(1e-6*fs*freq/2/np.pi,20*np.log10(np.abs(H)),'b')
filterAxList[0].set_ylabel('Amplitude Response [dB]')
filterAxList[0].axis((0, 1e-6*fs/2, -150, 0))
filterAxList[0].grid()
filterAxList[1].plot(1e-6*fs*freq/2/np.pi,np.unwrap(np.angle(H)),'b')
filterAxList[1].set_xlabel('Frequency [MHz]')
filterAxList[1].set_ylabel('Phase Response [radians]')
filterAxList[1].grid()

chirpAmplitude = 0.3
chirpLength = 256
chirpSignal = chirpAmplitude*signal.hilbert(signal.chirp(np.arange(chirpLength)/fs, f0=150e6, f1=180e6, t1=(chirpLength-1)/fs, phi=90, method='linear')).astype(np.complex64)

intAmplitude = 1
intLength = 512
intSignal = intAmplitude*signal.hilbert(np.cos(2*np.pi*50e6*np.arange(intLength)/fs)).astype(np.complex64)

noiseVar = 0.01
group_delay = 16
rxSig_raw = np.concatenate((np.zeros(10), intSignal, np.zeros(64), chirpSignal, np.zeros(128)))
rxSig_noisy = rxSig_raw + np.sqrt(noiseVar/2)*(np.random.randn(len(rxSig_raw))+1j*np.random.randn(len(rxSig_raw)))
# rxSig_filtered = signal.lfilter(b,1,rxSig_noisy)[group_delay:]
rxSig_filtered = signal.filtfilt(b,1,rxSig_noisy)
import pdb; pdb.set_trace()

sigFig = plt.figure()
plt.plot(np.real(rxSig_raw),'r',label='Original')
Esempio n. 55
0
# -*- coding: utf-8 -*-
import wave
import numpy as np
import scipy.signal as signal

framerate = 44100
time = 10

# 产生10秒44.1kHz的100Hz - 1kHz的频率扫描波
t = np.arange(0, time, 1.0/framerate)
wave_data = signal.chirp(t, 100, time, 1000, method='linear') * 10000
wave_data = wave_data.astype(np.short)

# 打开WAV文档
f = wave.open(r"sweep.wav", "wb")

# 配置声道数、量化位数和取样频率
f.setnchannels(1)
f.setsampwidth(2)
f.setframerate(framerate)
# 将wav_data转换为二进制数据写入文件
f.writeframes(wave_data.tostring())
f.close()
Esempio n. 56
0
### ------------------- Test that it works properly ---------------------------

if __name__ == '__main__':
    import numpy.random
    import scipy.signal as ssi
    import matplotlib.pyplot as plt

    # Send a chirp with some noise, and try to recover its frequency

    # Input signal
    f0 = 50
    f1 = 1000
    t = np.arange(0, 10, 1 / 44100)
    ft = f0 * (f1 / f0)**(t / max(t))
    chirp = ssi.chirp(t, f0, max(t), f1, method='log')
    noise_lv = 0.1
    chirp += numpy.random.randn(len(chirp)) * noise_lv

    # Slicing the signal
    N = 256  # slice size
    sliced = [chirp[N * k:N * (k + 1)] for k in range(int(len(chirp) / N))]
    f_correct = [ft[N * k] for k in range(int(len(chirp) / N))]

    # Getting the estimation
    pf = PeriodFinder()
    f_estimates = []
    for slice_ in sliced:
        f_estimates.append(pf(slice_))

    # Comparison
Esempio n. 57
0
from pylab import *
import scipy.signal as signal
import stockwell.smt as smt

signal.chirp
#?signal.chirp
t = linspace(0, 10, num=1000)
ch = signal.chirp(t, 1.0, 6.0, 20.0)
#figure()
#plot(t,ch)
K = 4
N = len(t)
tapers = smt.calc_tapers(K, N)
chs = smt.mtst(K, tapers, ch, 0, len(ch) / 2)
chtapers = smt.calc_tapers(K, len(ch))
chs = smt.mtst(K, chtapers, ch, 0, len(ch) / 2)

# these don't quite look right
#figure(); imshow(chs); axis('auto')
#figure(); subplot(211); plot(ch); subplot(212); imshow(chs); axis('auto')
## now try a longer signal

import stockwell.plots as stplot

print("powerstack of multitaper version of signal")
stplot.stpowerstack(ch, chs)
from time_map_tstretch import attack_avoider

W = 1024
H = 256
N = 500 * H
n = np.arange(N)
# chirp frequency
f0 = 0.01
# stretch factor
S = 1.
# shift factor
P = 0.5

attack_times = np.array([1513, 3013, 4513])

x = signal.chirp(n, f0, N, f0)
x[attack_times] = 1
av = attack_avoider(attack_times, -H, H + W, H)

output_times = np.round(np.arange(0, N, S * H)).astype('int')
y = np.zeros(len(output_times) * H, dtype=x.dtype)

wl = window_tools.windowed_lookup(x, W)
pv = pvoc_synth(signal.get_window('hann', W), signal.get_window('hann', W), W,
                H, lambda t: wl.access(t))

h_y = 0
for h in output_times:
    lookup_times = np.arange(0, H * P, P)
    n_lookups = int(np.ceil((H + 2) / H * P))
    y_tmp = np.zeros(H * n_lookups)
Esempio n. 59
0
def sweep(freqMin = None,
          freqMax = None,
          samplingRate = None,
          fftDegree = None,
          startMargin = None,
          stopMargin = None,
          method = 'logarithmic',
          windowing = 'hann'):
    """
   Generates a chirp signal defined by the "method" input, windowed, with
   silence interval at the beggining and end of the signal, plus a hanning
   fade in and fade out.
 
   >>> x = pytta.generate.sweep()
   >>> x.plot_time()

   Return a signalObj containing a logarithmic chirp signal from 17.8 Hz
   to 22050 Hz, with a fade in beginning at 17.8 Hz time instant and ending at
   the 20 Hz time instant; plus a fade out beginning at 20000 Hz time instant
   and ending at 22050 Hz time instant.

   The fade in and the fade out are made with half hanning window. First half
   for the fade in and last half for the fade out. Different number of points
   are used for each fade, so the number of time samples during each frequency
   is respected.

    """
    if freqMin is None: freqMin = default.freqMin
    if freqMax is None: freqMax = default.freqMax
    if samplingRate is None: samplingRate = default.samplingRate
    if fftDegree is None: fftDegree = default.fftDegree
    if startMargin is None: startMargin = default.startMargin
    if stopMargin is None: stopMargin = default.stopMargin
    
    freqLimits = np.array( [ freqMin / ( 2**(1/6) ), \
                           min( freqMax*( 2**(1/6) ), \
                                   samplingRate/2 )
                           ] ) # frequency limits [Hz]
    samplingTime = 1/samplingRate # [s] sampling period
    
    stopSamples = stopMargin*samplingRate 
    # [samples] initial silence number of samples
    
    startSamples = startMargin*samplingRate
    # [samples] ending silence number of samples
    
    marginSamples = startSamples + stopSamples
    # [samples] total silence number of samples
    
    numSamples = 2**fftDegree # [samples] full signal number of samples
    
    sweepSamples = numSamples - marginSamples +1
    # [samples] actual sweep number of samples
    
    sweepTime = sweepSamples/samplingRate # [s] sweep's time length
    timeVecSweep = np.arange(0, sweepTime, samplingTime) # [s] sweep time vector
    if timeVecSweep.size > sweepSamples:
        timeVecSweep = timeVecSweep[0:int(sweepSamples)] # adjust length
    sweep = 0.8*signal.chirp(timeVecSweep, \
                             freqLimits[0],\
                             sweepTime, \
                             freqLimits[1],\
                              'logarithmic', \
                              phi=-90) # sweep, time domain
    sweep = __do_sweep_windowing(sweep, \
                                 timeVecSweep, \
                                 freqLimits, \
                                 freqMin, \
                                 freqMax, \
                                 windowing) # fade in and fade out
    timeSignal = np.concatenate( ( np.zeros( \
                                   int(startSamples) ), \
                                   sweep, \
                                   np.zeros( \
                                   int(stopSamples) 
                                   ) ) ) # add initial and ending sileces
    if timeSignal.size != numSamples:
        timeSignal = timeSignal[0:int(numSamples)] # adjust length
    
    sweepSignal = SignalObj(timeSignal,'time',samplingRate) 
    # transforms into a pytta signalObj
    
    sweepSignal._freqMin, sweepSignal._freqMax \
            = freqLimits[0], freqLimits[1] 
    # pass on the frequency limits considering the fade in and fade out
    return sweepSignal
plt.subplot(1,2,1) #6
f, tt, Sxx =sg.spectrogram(signalAndNoise,fs,wind,len(wind),overl) #7
plt.pcolormesh(tt,f,Sxx,cmap='hot') #!4
plt.ylabel('Frequency (Hz)');plt.xlabel('Time (sec)') #15 label axes
plt.ylim([0,20]) #16
wind = np.hanning(windLength);#8
plt.subplot(1,2,2) #9
f, tt, Sxx =sg.spectrogram(signalAndNoise,fs,wind,len(wind),overl) #7
plt.pcolormesh(tt,f,Sxx,cmap='hot') #14
plt.ylabel('Frequency (Hz)');plt.xlabel('Time (sec)')#15 label axes
plt.ylim([0,20]) #16

#%% Chirp

time = np.linspace(0,2,fs*2)#1
y=sg.chirp(time,100,1,200,'quadratic'); #2
#3 playing sounds is beyond "1" in Python
fig=plt.figure(figsize=(10,10))#4
ax = plt.subplot(4,1,1)#5
ax.plot(time,y) #6
ax = plt.subplot(4,1,2) #7
windLength = 128; #8
overl = windLength-1; #9
freqBins = 250; #10
wind=np.kaiser(windLength,0)
f, tt, Sxx =sg.spectrogram(y,fs,wind,len(wind),overl); #7
plt.pcolormesh(tt,f,Sxx);
ax = plt.subplot(4,1,3) #12
wind=np.hanning(windLength);
f, tt, Sxx =sg.spectrogram(y,fs,wind,len(wind),overl); #7
plt.pcolormesh(tt,f,Sxx)