Example #1
1
def THDN(signal, sample_rate, filename):

    signal = signal - mean(signal)  # this is so that the DC offset is not the peak in the case of PDM
    windowed = signal * blackmanharris(len(signal)) 

    

    # Find the peak of the frequency spectrum (fundamental frequency), and filter 
    # the signal by throwing away values between the nearest local minima
    f = rfft(windowed)

    #limit the bandwidth
    if len(f) > 24000:
       f[24000:len(f)] = 0

    bandwidth_limited = irfft(f)
    total_rms = rms_flat(bandwidth_limited)

    #for i in range(6000):
       #print abs(f[i])
    i = argmax(abs(f))

    #This will be exact if the frequency under test falls into the middle of an fft bin 
    print 'Frequency: %f Hz' % (sample_rate * (i / len(windowed)))
    lowermin, uppermin = find_range(abs(f), i)


    #notch out the signal
    f[lowermin: uppermin] = 0



    noise = irfft(f)
    THDN = rms_flat(noise) / total_rms
    print "THD+N:     %.12f%% or %.12f dB" % (THDN * 100, 20 * log10(THDN))
Example #2
1
def freq_from_HPS(sig, fs):
    """
    Estimate frequency using harmonic product spectrum (HPS)
    
    """
    windowed = sig * blackmanharris(len(sig))

    from pylab import subplot, plot, log, copy, show

    #harmonic product spectrum:
    c = abs(rfft(windowed))
    maxharms = 8
    subplot(maxharms,1,1)
    plot(log(c))
    for x in range(2,maxharms):
        a = copy(c[::x]) #Should average or maximum instead of decimating
        # max(c[::x],c[1::x],c[2::x],...)
        c = c[:len(a)]
        i = argmax(abs(c))
        true_i = parabolic(abs(c), i)[0]
        print 'Pass %d: %f Hz' % (x, fs * true_i / len(windowed))
        c *= a
        subplot(maxharms,1,x)
        plot(log(c))
    show()
Example #3
0
def window(f,start,stop,type='blackman'):
    """
    runs the data through a hamming window.
    @param f: The data matrix
    @param start: The start index of the hamming window.
    @param stop: The end index of the hamming window.
    """
    h=numpy.zeros(f.shape,dtype=float)

    if len(h.shape)==1:
        if type=='hamming':
            h[start:stop]=signal.hamming(stop-start)
        elif type=='blackman':
            h[start:stop]=signal.blackman(stop-start)
        elif type=='hann':
            h[start:stop]=signal.hann(stop-start)
        elif type=='blackmanharris':
            h[start:stop]=signal.blackmanharris(stop-start)
        elif type=='rectangular' or type=='rect' or type=='boxcar':
            h[start:stop]=signal.boxcar(stop-start)
    else:
        if type=='hamming':
            h[:,start:stop]=signal.hamming(stop-start)
        elif type=='blackman':
            h[:,start:stop]=signal.blackman(stop-start)
        elif type=='hann':
            h[:,start:stop]=signal.hann(stop-start)
        elif type=='blackmanharris':
            h[:,start:stop]=signal.blackmanharris(stop-start)
        elif type=='rectangular' or type=='rect' or type=='boxcar':
            h[:,start:stop]=signal.boxcar(stop-start)
    return numpy.multiply(f,h)
def delayTransformVisibilities(visList,df,kernel=None,wind='Blackman-Harris'):
    '''
     ARGS:
     visList: nfreqxnvis complex matrix of visibilities
     df: float indicating channel width
     RETURNS:
     ndelayxnvis grid of delay-transformed visibilities
    '''
    nf=visList.shape[0]
    if kernel is None:
        kernel=np.ones(nf)

    nv=visList.shape[1]
    windowGrid=np.zeros_like(visList)
    if wind=='Blackman-Harris':
        window=signal.blackmanharris(nf)
    elif wind=='Nithya':
        window=signal.blackmanharris(nf/2)
        window=signal.fftconvolve(window,window,mode='full')
        window=np.append(window,window[-1])
    window/=window.max()
    window/=np.sqrt(np.mean(np.abs(kernel*window)**2.)) 
    for vNum in range(nv):
        windowGrid[:,vNum]=window*kernel
    return df*fft.fftshift(fft.fft(fft.fftshift(visList*windowGrid,axes=[0]),axis=0),axes=[0])
Example #5
0
 def test_basic(self):
     assert_allclose(signal.blackmanharris(6, False),
                     [6.0e-05, 0.055645, 0.520575, 1.0, 0.520575, 0.055645])
     assert_allclose(signal.blackmanharris(6),
                     [6.0e-05, 0.1030114893456638, 0.7938335106543362,
                      0.7938335106543364, 0.1030114893456638, 6.0e-05])
     assert_allclose(signal.blackmanharris(7, sym=True),
                     [6.0e-05, 0.055645, 0.520575, 1.0, 0.520575, 0.055645,
                      6.0e-05])
Example #6
0
 def test_basic(self):
     assert_allclose(signal.blackmanharris(6, False),
                     [6.0e-05, 0.055645, 0.520575, 1.0, 0.520575, 0.055645])
     assert_allclose(signal.blackmanharris(7, sym=False),
                     [6.0e-05, 0.03339172347815117, 0.332833504298565,
                      0.8893697722232837, 0.8893697722232838,
                      0.3328335042985652, 0.03339172347815122])
     assert_allclose(signal.blackmanharris(6),
                     [6.0e-05, 0.1030114893456638, 0.7938335106543362,
                      0.7938335106543364, 0.1030114893456638, 6.0e-05])
     assert_allclose(signal.blackmanharris(7, sym=True),
                     [6.0e-05, 0.055645, 0.520575, 1.0, 0.520575, 0.055645,
                      6.0e-05])
Example #7
0
def sinewaveSynth(freq, mag, N, H, fs):
  # Synthesis of a time-varying sinusoid
  # freq,mag, phase: frequency, magnitude and phase of sinusoid,
  # N: synthesis FFT size, H: hop size, fs: sampling rate
  # returns y: output array sound
  hN = N/2                                                # half of FFT size for synthesis
  L = freq.size                                           # number of frames
  pout = 0                                                # initialize output sound pointer         
  ysize = H*(L+3)                                         # output sound size
  y = np.zeros(ysize)                                     # initialize output array
  sw = np.zeros(N)                                        # initialize synthesis window
  ow = triang(2*H);                                       # triangular window
  sw[hN-H:hN+H] = ow                                      # add triangular window
  bh = blackmanharris(N)                                  # blackmanharris window
  bh = bh / sum(bh)                                       # normalized blackmanharris window
  sw[hN-H:hN+H] = sw[hN-H:hN+H]/bh[hN-H:hN+H]             # normalized synthesis window
  lastfreq = freq[0]                                      # initialize synthesis frequencies
  phase = 0                                               # initialize synthesis phases 
  for l in range(L):                                      # iterate over all frames
    phase += (np.pi*(lastfreq+freq[l])/fs)*H            # propagate phases
    Y = UF.genSpecSines(freq[l], mag[l], phase, N, fs)    # generate sines in the spectrum         
    lastfreq = freq[l]                                    # save frequency for phase propagation
    yw = np.real(fftshift(ifft(Y)))                       # compute inverse FFT
    y[pout:pout+N] += sw*yw                               # overlap-add and apply a synthesis window
    pout += H                                             # advance sound pointer
  y = np.delete(y, range(hN))                             # delete half of first window
  y = np.delete(y, range(y.size-hN, y.size))              # delete half of the last window 
  return y
Example #8
0
def stochasticResidual(x, N, H, sfreq, smag, sphase, fs, stocf):
  # subtract sinusoids from a sound
  # x: input sound, N: fft-size, H: hop-size
  # sfreq, smag, sphase: sinusoidal frequencies, magnitudes and phases
  # returns mYst: stochastic approximation of residual 
  hN = N/2  
  x = np.append(np.zeros(hN),x)                    # add zeros at beginning to center first window at sample 0
  x = np.append(x,np.zeros(hN))                    # add zeros at the end to analyze last sample
  bh = blackmanharris(N)                           # synthesis window
  w = bh/ sum(bh)                                  # normalize synthesis window
  L = sfreq[:,0].size                              # number of frames   
  pin = 0
  for l in range(L):
    xw = x[pin:pin+N]*w                            # window the input sound                               
    X = fft(fftshift(xw))                          # compute FFT 
    Yh = UF_C.genSpecSines(N*sfreq[l,:]/fs, smag[l,:], sphase[l,:], N)   # generate spec sines          
    Xr = X-Yh                                      # subtract sines from original spectrum
    mXr = 20*np.log10(abs(Xr[:hN]))                # magnitude spectrum of residual
    mXrenv = resample(np.maximum(-200, mXr), mXr.size*stocf)  # decimate the mag spectrum                        
    if l == 0: 
      mYst = np.array([mXrenv])
    else:
      mYst = np.vstack((mYst, np.array([mXrenv])))
    pin += H                                       # advance sound pointer
  return mYst
Example #9
0
    def run(self, tf, dt, K, c1, c2):
        """ Run a simulation """
        n, m, k = self.n, self.m, self.k

        # Total simulation time
        simTime = int(tf / dt)

        # Returns the three synaptic connections kernels
        W12, W21, W22, delays = self.build_kernels(K)

        # Compute delays by dividing distances by axonal velocity
        delays12 = np.floor(delays[0] / c2)
        delays21 = np.floor(delays[1] / c1)
        delays22 = np.floor(delays[2] / c2)
        maxDelay = int(max(delays12[0].max(), delays21[0].max(), delays22[0].max()))

        # Set the initial conditions and the history
        self.initial_conditions(simTime)

        # Initialize the cortical and striatal inputs
        Cx = 0.5
        Str = 0.4

        # Presynaptic activities
        pre12, pre21, pre22 = np.empty((m,)), np.empty((m,)), np.empty((m,))

        # Simulation
        for i in range(maxDelay, simTime):
            # Take into account the history of rate for each neuron according
            # to its axonal delay
            for idxi, ii in enumerate(range(m)):
                mysum = 0.0
                for jj in range(k, n):
                    mysum += (W12[ii, jj] * self.X2[i - delays12[ii, jj], jj]) * self.dx
                pre12[idxi] = mysum

            for idxi, ii in enumerate(range(k, n)):
                mysum = 0.0
                for jj in range(0, m):
                    mysum += (W21[ii, jj] * self.X1[i - delays21[ii, jj], jj]) * self.dx
                pre21[idxi] = mysum

            for idxi, ii in enumerate(range(k, n)):
                mysum = 0.0
                for jj in range(k, n):
                    mysum += (W22[ii, jj] * self.X2[i - delays22[ii, jj], jj]) * self.dx
                pre22[idxi] = mysum

            # Forward Euler step
            self.X1[i, :m] = self.X1[i - 1, :m] + (-self.X1[i - 1, :m] + self.S1(-pre12 + Cx)) * dt / self.tau1
            self.X2[i, k:] = self.X2[i - 1, k:] + (-self.X2[i - 1, k:] + self.S2(pre21 - pre22 - Str)) * dt / self.tau2
        dx = 1.0 / float(m)
        fr = self.X1.sum(axis=1) * dx / 1.0

        signal = detrend(fr)
        windowed = signal * blackmanharris(len(signal))
        f = rfft(windowed)
        i = np.argmax(np.abs(f))
        # true_i = parabolic(np.log(np.abs(f)), i)[0]
        return i
Example #10
0
def sineModelSynth(tfreq, tmag, tphase, N, H, fs):
    """
    Synthesis of a sound using the sinusoidal model
    tfreq, tmag, tphase: frequencies, magnitudes and phases of sinusoids
    N: synthesis FFT size, H: hop size, fs: sampling rate
    returns y: output array sound
    """

    hN = N / 2 # half of FFT size for synthesis
    L = tfreq.shape[0] # number of frames
    pout = 0
    ysize = H * (L+3)
    y = np.zeros(ysize)
    # synthesis window
    sw = np.zeros(N)
    ow = triang(2 * H)
    sw[hN-H:hN+H] = ow
    bh = blackmanharris(N)
    bh = bh / sum(bh)
    sw[hN-H:hN+H] = sw[hN-H:hN+H] / bh[hN-H:hN+H]
    lastytfreq = tfreq[0,:]
    ytphase = 2*np.pi*np.random.rand(tfreq[0,:].size)
    for l in range(L): # iterate over all frames
        if (tphase.size > 0):
            ytphase = tphase[l, :]
Example #11
0
def waveform_to_file(station,clen=10000,oversample=10, filt=False, outpath=None,verbose=False):
    """
    lets use 0.1 s code cycle and coherence assumption
    our transmit bandwidth is 100 kHz, and with a clen=10e3 baud code,
    that is 0.1 seconds per cycle as a coherence assumption.
    furthermore, we use a 1 MHz bandwidth, so we oversample by a factor of 10.

    NOTE: this writing method doesn't store any metadata - have to know the sample rate
    """

    a = rep_seq(create_pseudo_random_code(clen,station,verbose), rep=oversample)

    if filt == True:
        w = np.zeros([oversample*clen], dtype='complex64') # yes, zeros for zero-padded
        fl = int(oversample+(0.1*oversample))

        w[:fl]= signal.blackmanharris(fl) # W[fl:] \equiv 0

        aa = np.fft.ifft(np.fft.fft(w) * np.fft.fft(a))

        a = (aa/abs(aa).max()).astype('complex64') #normalized, single prec complex

    if outpath:
        p = Path(outpath).expanduser()
        p.mkdir(parents=True, exist_ok=True)

        ofn = p / f"code-l{clen}-b{oversample}-{station:06d}.bin"
        print('writing',ofn)

        # https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.tofile.html
        a.tofile(ofn) # this binary format is OK for GNU Radio to read

    return a
def sineSubtraction(x, N, H, sfreq, smag, sphase, fs):
	"""
	Subtract sinusoids from a sound
	x: input sound, N: fft-size, H: hop-size
	sfreq, smag, sphase: sinusoidal frequencies, magnitudes and phases
	returns xr: residual sound
	"""

	hN = N/2                                           # half of fft size
	x = np.append(np.zeros(hN),x)                      # add zeros at beginning to center first window at sample 0
	x = np.append(x,np.zeros(hN))                      # add zeros at the end to analyze last sample
	bh = blackmanharris(N)                             # blackman harris window
	w = bh/ sum(bh)                                    # normalize window
	sw = np.zeros(N)                                   # initialize synthesis window
	sw[hN-H:hN+H] = triang(2*H) / w[hN-H:hN+H]         # synthesis window
	L = sfreq.shape[0]                                 # number of frames, this works if no sines
	xr = np.zeros(x.size)                              # initialize output array
	pin = 0
	for l in range(L):
		xw = x[pin:pin+N]*w                              # window the input sound
		X = fft(fftshift(xw))                            # compute FFT
		Yh = UF_C.genSpecSines(N*sfreq[l,:]/fs, smag[l,:], sphase[l,:], N)   # generate spec sines
		Xr = X-Yh                                        # subtract sines from original spectrum
		xrw = np.real(fftshift(ifft(Xr)))                # inverse FFT
		xr[pin:pin+N] += xrw*sw                          # overlap-add
		pin += H                                         # advance sound pointer
	xr = np.delete(xr, range(hN))                      # delete half of first window which was added in stftAnal
	xr = np.delete(xr, range(xr.size-hN, xr.size))     # delete half of last window which was added in stftAnal
	return xr
def freq_power_from_fft(sig, fs):
	# Compute Fourier transform of windowed signal
	windowed = sig * blackmanharris(CHUNK)
	fftData = abs(rfft(windowed))
	# powerData = 20*log10(fftData)
	# Find the index of the peak and interpolate to get a more accurate peak
	i = argmax(fftData) # Just use this for less-accurate, naive version
	# make sure i is not an endpoint of the bin
	if i != len(fftData)-1 and i != 0:
		#print("data: " + str(parabolic(log(abs(fftData)), i)))
		true_i,logmag = parabolic(log(abs(fftData)), i)
		# Convert to equivalent frequency
		freq=  fs * true_i / len(windowed)
		#print("frequency="+ str(freq) + " log of magnitude=" + str(logmag))
		if logmag < 0:
			logmag = 0	
		return freq,logmag
	
	else:
		freq = fs * i / len(windowed)
		logmag = log(abs(fftData))[i]
		if logmag < 0:
			logmag = 0
		#print("frequency="+ str(freq) + "log of magnitude not interp=" + str(logmag))
		return freq,logmag
def stochasticResidualAnal(x, N, H, sfreq, smag, sphase, fs, stocf):
	"""
	Subtract sinusoids from a sound and approximate the residual with an envelope
	x: input sound, N: fft size, H: hop-size
	sfreq, smag, sphase: sinusoidal frequencies, magnitudes and phases
	fs: sampling rate; stocf: stochastic factor, used in the approximation
	returns stocEnv: stochastic approximation of residual
	"""

	hN = N/2                                              # half of fft size
	x = np.append(np.zeros(hN),x)                         # add zeros at beginning to center first window at sample 0
	x = np.append(x,np.zeros(hN))                         # add zeros at the end to analyze last sample
	bh = blackmanharris(N)                                # synthesis window
	w = bh/ sum(bh)                                       # normalize synthesis window
	L = sfreq.shape[0]                                    # number of frames, this works if no sines
	pin = 0
	for l in range(L):
		xw = x[pin:pin+N] * w                               # window the input sound
		X = fft(fftshift(xw))                               # compute FFT
		Yh = UF_C.genSpecSines(N*sfreq[l,:]/fs, smag[l,:], sphase[l,:], N)   # generate spec sines
		Xr = X-Yh                                           # subtract sines from original spectrum
		mXr = 20*np.log10(abs(Xr[:hN]))                     # magnitude spectrum of residual
		mXrenv = resample(np.maximum(-200, mXr), mXr.size*stocf)  # decimate the mag spectrum
		if l == 0:                                          # if first frame
			stocEnv = np.array([mXrenv])
		else:                                               # rest of frames
			stocEnv = np.vstack((stocEnv, np.array([mXrenv])))
		pin += H                                            # advance sound pointer
	return stocEnv
Example #15
0
def sineModelSynth(tfreq, tmag, tphase, N, H, fs):
	"""
	Synthesis of a sound using the sinusoidal model
	tfreq,tmag,tphase: frequencies, magnitudes and phases of sinusoids
	N: synthesis FFT size, H: hop size, fs: sampling rate
	returns y: output array sound
	"""
	
	hN = N/2                                                # half of FFT size for synthesis
	L = tfreq.shape[0]                                      # number of frames
	pout = 0                                                # initialize output sound pointer         
	ysize = H*(L+3)                                         # output sound size
	y = np.zeros(ysize)                                     # initialize output array
	sw = np.zeros(N)                                        # initialize synthesis window
	ow = triang(2*H)                                        # triangular window
	sw[hN-H:hN+H] = ow                                      # add triangular window
	bh = blackmanharris(N)                                  # blackmanharris window
	bh = bh / sum(bh)                                       # normalized blackmanharris window
	sw[hN-H:hN+H] = sw[hN-H:hN+H]/bh[hN-H:hN+H]             # normalized synthesis window
	lastytfreq = tfreq[0,:]                                 # initialize synthesis frequencies
	ytphase = 2*np.pi*np.random.rand(tfreq[0,:].size)       # initialize synthesis phases 
	for l in range(L):                                      # iterate over all frames
		if (tphase.size > 0):                                 # if no phases generate them
			ytphase = tphase[l,:] 
		else:
			ytphase += (np.pi*(lastytfreq+tfreq[l,:])/fs)*H     # propagate phases
		Y = UF.genSpecSines(tfreq[l,:], tmag[l,:], ytphase, N, fs)  # generate sines in the spectrum         
		lastytfreq = tfreq[l,:]                               # save frequency for phase propagation
		ytphase = ytphase % (2*np.pi)                         # make phase inside 2*pi
		yw = np.real(fftshift(ifft(Y)))                       # compute inverse FFT
		y[pout:pout+N] += sw*yw                               # overlap-add and apply a synthesis window
		pout += H                                             # advance sound pointer
	y = np.delete(y, range(hN))                             # delete half of first window
	y = np.delete(y, range(y.size-hN, y.size))              # delete half of the last window 
	return y
Example #16
0
def plot_specgram(ax, data, fs, nfft=256, noverlap=128, window='hann',
                  cmap='jet', interpolation='bilinear', rasterized=True):

    if window not in SPECGRAM_WINDOWS:
        raise ValueError("Window not supported")

    elif window == "boxcar":
        mwindow = signal.boxcar(nfft)
    elif window == "hamming":
        mwindow = signal.hamming(nfft)
    elif window == "hann":
        mwindow = signal.hann(nfft)
    elif window == "bartlett":
        mwindow = signal.bartlett(nfft)
    elif window == "blackman":
        mwindow = signal.blackman(nfft)
    elif window == "blackmanharris":
        mwindow = signal.blackmanharris(nfft)

    specgram, freqs, time = mlab.specgram(data, NFFT=nfft, Fs=fs,
                                          window=mwindow,
                                          noverlap=noverlap)
    specgram = 10 * np.log10(specgram[1:, :])
    specgram = np.flipud(specgram)

    freqs = freqs[1:]
    halfbin_time = (time[1] - time[0]) / 2.0
    halfbin_freq = (freqs[1] - freqs[0]) / 2.0
    extent = (time[0] - halfbin_time, time[-1] + halfbin_time,
              freqs[0] - halfbin_freq, freqs[-1] + halfbin_freq)

    ax.imshow(specgram, cmap=cmap, interpolation=interpolation,
                            extent=extent, rasterized=rasterized)
    ax.axis('tight')
def _BLACKMANHARRIS_Window(signal):
    """ blackman-harris window process
        Use Windows to smooth transient data in the begin/end
    """
    windowed = signal * blackmanharris(len(signal))  # TODO Kaiser?

    return windowed
def harmonicModel(x, fs, w, N, t, nH, minf0, maxf0, f0et):
	"""
	Analysis/synthesis of a sound using the sinusoidal harmonic model
	x: input sound, fs: sampling rate, w: analysis window, 
	N: FFT size (minimum 512), t: threshold in negative dB, 
	nH: maximum number of harmonics, minf0: minimum f0 frequency in Hz, 
	maxf0: maximim f0 frequency in Hz, 
	f0et: error threshold in the f0 detection (ex: 5),
	returns y: output array sound
	"""

	hN = N/2                                                # size of positive spectrum
	hM1 = int(math.floor((w.size+1)/2))                     # half analysis window size by rounding
	hM2 = int(math.floor(w.size/2))                         # half analysis window size by floor
	x = np.append(np.zeros(hM2),x)                          # add zeros at beginning to center first window at sample 0
	x = np.append(x,np.zeros(hM1))                          # add zeros at the end to analyze last sample
	Ns = 512                                                # FFT size for synthesis (even)
	H = Ns/4                                                # Hop size used for analysis and synthesis
	hNs = Ns/2      
	pin = max(hNs, hM1)                                     # init sound pointer in middle of anal window          
	pend = x.size - max(hNs, hM1)                           # last sample to start a frame
	fftbuffer = np.zeros(N)                                 # initialize buffer for FFT
	yh = np.zeros(Ns)                                       # initialize output sound frame
	y = np.zeros(x.size)                                    # initialize output array
	w = w / sum(w)                                          # normalize analysis window
	sw = np.zeros(Ns)                                       # initialize synthesis window
	ow = triang(2*H)                                        # overlapping window
	sw[hNs-H:hNs+H] = ow      
	bh = blackmanharris(Ns)                                 # synthesis window
	bh = bh / sum(bh)                                       # normalize synthesis window
	sw[hNs-H:hNs+H] = sw[hNs-H:hNs+H] / bh[hNs-H:hNs+H]     # window for overlap-add
	hfreqp = []
	f0t = 0
	f0stable = 0
	while pin<pend:             
	#-----analysis-----             
		x1 = x[pin-hM1:pin+hM2]                               # select frame
		mX, pX = DFT.dftAnal(x1, w, N)                        # compute dft
		ploc = UF.peakDetection(mX, t)                        # detect peak locations     
		iploc, ipmag, ipphase = UF.peakInterp(mX, pX, ploc)   # refine peak values
		ipfreq = fs * iploc/N
		f0t = UF.f0Twm(ipfreq, ipmag, f0et, minf0, maxf0, f0stable)  # find f0
		if ((f0stable==0)&(f0t>0)) \
				or ((f0stable>0)&(np.abs(f0stable-f0t)<f0stable/5.0)):
			f0stable = f0t                                     # consider a stable f0 if it is close to the previous one
		else:
			f0stable = 0
		hfreq, hmag, hphase = harmonicDetection(ipfreq, ipmag, ipphase, f0t, nH, hfreqp, fs) # find harmonics
		hfreqp = hfreq
	#-----synthesis-----
		Yh = UF.genSpecSines(hfreq, hmag, hphase, Ns, fs)     # generate spec sines          
		fftbuffer = np.real(ifft(Yh))                         # inverse FFT
		yh[:hNs-1] = fftbuffer[hNs+1:]                        # undo zero-phase window
		yh[hNs-1:] = fftbuffer[:hNs+1] 
		y[pin-hNs:pin+hNs] += sw*yh                           # overlap-add
		pin += H                                              # advance sound pointer
	y = np.delete(y, range(hM2))                            # delete half of first window which was added in stftAnal
	y = np.delete(y, range(y.size-hM1, y.size))             # add zeros at the end to analyze last sample
	return y
def freq_from_fft(signal, fs):
    # Compute Fourier transform of windowed signal
    windowed = signal * blackmanharris(len(signal))
    f = rfft(windowed)
    i = argmax(abs(f))
    
    # Convert to equivalent frequency
    return fs*i/len(windowed)
Example #20
0
def sprModel(x, fs, w, N, t):
	"""
	Analysis/synthesis of a sound using the sinusoidal plus residual model, one frame at a time
	x: input sound, fs: sampling rate, w: analysis window, 
	N: FFT size (minimum 512), t: threshold in negative dB, 
	returns y: output sound, ys: sinusoidal component, xr: residual component
	"""

	hN = N/2                                                      # size of positive spectrum
	hM1 = int(math.floor((w.size+1)/2))                           # half analysis window size by rounding
	hM2 = int(math.floor(w.size/2))                               # half analysis window size by floor
	Ns = 512                                                      # FFT size for synthesis (even)
	H = Ns/4                                                      # Hop size used for analysis and synthesis
	hNs = Ns/2      
	pin = max(hNs, hM1)                                           # initialize sound pointer in middle of analysis window          
	pend = x.size - max(hNs, hM1)                                 # last sample to start a frame
	fftbuffer = np.zeros(N)                                       # initialize buffer for FFT
	ysw = np.zeros(Ns)                                            # initialize output sound frame
	xrw = np.zeros(Ns)                                            # initialize output sound frame
	ys = np.zeros(x.size)                                         # initialize output array
	xr = np.zeros(x.size)                                         # initialize output array
	w = w / sum(w)                                                # normalize analysis window
	sw = np.zeros(Ns)     
	ow = triang(2*H)                                              # overlapping window
	sw[hNs-H:hNs+H] = ow      
	bh = blackmanharris(Ns)                                       # synthesis window
	bh = bh / sum(bh)                                             # normalize synthesis window
	wr = bh                                                       # window for residual
	sw[hNs-H:hNs+H] = sw[hNs-H:hNs+H] / bh[hNs-H:hNs+H]
	while pin<pend:  
  #-----analysis-----             
		x1 = x[pin-hM1:pin+hM2]                                     # select frame
		mX, pX = DFT.dftAnal(x1, w, N)                              # compute dft
		ploc = UF.peakDetection(mX, t)                              # find peaks 
		iploc, ipmag, ipphase = UF.peakInterp(mX, pX, ploc)         # refine peak values		iploc, ipmag, ipphase = UF.peakInterp(mX, pX, ploc)          # refine peak values
		ipfreq = fs*iploc/float(N)                                  # convert peak locations to Hertz
		ri = pin-hNs-1                                              # input sound pointer for residual analysis
		xw2 = x[ri:ri+Ns]*wr                                        # window the input sound                                       
		fftbuffer = np.zeros(Ns)                                    # reset buffer
		fftbuffer[:hNs] = xw2[hNs:]                                 # zero-phase window in fftbuffer
		fftbuffer[hNs:] = xw2[:hNs]                           
		X2 = fft(fftbuffer)                                         # compute FFT for residual analysis
  #-----synthesis-----
		Ys = UF.genSpecSines(ipfreq, ipmag, ipphase, Ns, fs)        # generate spec of sinusoidal component          
		Xr = X2-Ys;                                                 # get the residual complex spectrum
		fftbuffer = np.zeros(Ns)
		fftbuffer = np.real(ifft(Ys))                               # inverse FFT of sinusoidal spectrum
		ysw[:hNs-1] = fftbuffer[hNs+1:]                             # undo zero-phase window
		ysw[hNs-1:] = fftbuffer[:hNs+1] 
		fftbuffer = np.zeros(Ns)
		fftbuffer = np.real(ifft(Xr))                               # inverse FFT of residual spectrum
		xrw[:hNs-1] = fftbuffer[hNs+1:]                             # undo zero-phase window
		xrw[hNs-1:] = fftbuffer[:hNs+1]
		ys[ri:ri+Ns] += sw*ysw                                      # overlap-add for sines
		xr[ri:ri+Ns] += sw*xrw                                      # overlap-add for residual
		pin += H                                                    # advance sound pointer
	y = ys+xr                                                     # sum of sinusoidal and residual components
	return y, ys, xr
 def calculate(self):
     data = self.data * blackmanharris(self.data.size)
     finfo = np.abs(rfft(data))
     xvals = fftfreq(self.data.size, d=(1.0 / self.fs))
     xvals = xvals[:xvals.size / 8]
     if finfo.size != xvals.size:
         finfo = finfo[:xvals.size]
         xvals = xvals[:finfo.size]
     return xvals, finfo
Example #22
0
def multiply_blackmann_harris_window(inputs, axis=1):
    n = inputs.shape[axis]
    w = blackmanharris(n)
    #w=w/np.mean(w)
    # make w have same dimensionality as inputs,
    # to ensure correct dimensions are multiplied
    for i_axis in xrange(inputs.ndim):
        if i_axis != axis:
            w = np.expand_dims(w, i_axis)
    return w * inputs
Example #23
0
    def getHz(self, soundData, rate):
        usedata = unpack("%dh" % (len(soundData) / 2), soundData)
        usedata = np.array(usedata, dtype="h")
        window = usedata * blackmanharris(len(usedata))
        fouriour = np.fft.rfft(window)
        fouriour = np.delete(fouriour, len(fouriour) - 1)

        i = np.argmax(abs(fouriour))
        true_i = parabolic(np.log(abs(fouriour)), i)[0]

        return rate * true_i / len(window)
Example #24
0
def hpsModelSynth(hfreq, hmag, hphase, mYst, N, H, fs):
	# Synthesis of a sound using the harmonic plus stochastic model
	# hfreq: harmonic frequencies, hmag:harmonic amplitudes, mYst: stochastic envelope
	# Ns: synthesis FFT size, H: hop size, fs: sampling rate 
	# y: output sound, yh: harmonic component, yst: stochastic component
	hN = N/2                                                  # half of FFT size for synthesis
	L = hfreq[:,0].size                                       # number of frames
	nH = hfreq[0,:].size                                      # number of harmonics
	pout = 0                                                  # initialize output sound pointer         
	ysize = H*(L+4)                                           # output sound size
	yhw = np.zeros(N)                                        # initialize output sound frame
	ysw = np.zeros(N)                                        # initialize output sound frame
	yh = np.zeros(ysize)                                      # initialize output array
	yst = np.zeros(ysize)                                     # initialize output array
	sw = np.zeros(N)     
	ow = triang(2*H)                                          # overlapping window
	sw[hN-H:hN+H] = ow      
	bh = blackmanharris(N)                                   # synthesis window
	bh = bh / sum(bh)                                         # normalize synthesis window
	wr = bh                                                   # window for residual
	sw[hN-H:hN+H] = sw[hN-H:hN+H] / bh[hN-H:hN+H]             # synthesis window for harmonic component
	sws = H*hanning(N)/2                                      # synthesis window for stochastic component
	lastyhfreq = hfreq[0,:]                                   # initialize synthesis harmonic frequencies
	yhphase = 2*np.pi*np.random.rand(nH)                      # initialize synthesis harmonic phases     
	for l in range(L):
		yhfreq = hfreq[l,:]                                     # synthesis harmonics frequencies
		yhmag = hmag[l,:]                                       # synthesis harmonic amplitudes
		mYrenv = mYst[l,:]                                      # synthesis residual envelope
		if (hphase.size > 0):
			yhphase = hphase[l,:] 
		else:
			yhphase += (np.pi*(lastyhfreq+yhfreq)/fs)*H             # propagate phases
		lastyhfreq = yhfreq
		Yh = UF.genSpecSines(yhfreq, yhmag, yhphase, N, fs)     # generate spec sines 
		mYs = resample(mYrenv, hN)                              # interpolate to original size
		mYs = 10**(mYs/20)                                      # dB to linear magnitude  
		pYs = 2*np.pi*np.random.rand(hN)                        # generate phase random values
		Ys = np.zeros(N, dtype = complex)
		Ys[:hN] = mYs * np.exp(1j*pYs)                         # generate positive freq.
		Ys[hN+1:] = mYs[:0:-1] * np.exp(-1j*pYs[:0:-1])        # generate negative freq.
		fftbuffer = np.zeros(N)
		fftbuffer = np.real(ifft(Yh))                           # inverse FFT of harm spectrum
		yhw[:hN-1] = fftbuffer[hN+1:]                         # undo zer-phase window
		yhw[hN-1:] = fftbuffer[:hN+1] 
		fftbuffer = np.zeros(N)
		fftbuffer = np.real(ifft(Ys))                           # inverse FFT of stochastic approximation spectrum
		ysw[:hN-1] = fftbuffer[hN+1:]                           # undo zero-phase window
		ysw[hN-1:] = fftbuffer[:hN+1]
		yh[pout:pout+N] += sw*yhw                               # overlap-add for sines
		yst[pout:pout+N] += sws*ysw                             # overlap-add for stoch
		pout += H                                               # advance sound pointer
	y = yh+yst                                                # sum harmonic and stochastic components
	return y, yh, yst
Example #25
0
def freq_from_hps(signal, fs):
    """
    Estimate frequency using harmonic product spectrum.

    Note: Low frequency noise piles up and overwhelms the desired peaks.

    From: https://gist.github.com/endolith/255291 and
          https://github.com/endolith/waveform-analyzer

    Parameters
    ----------
    signal : list or array
        time series data
    fs : integer
        sample rate

    Returns
    -------
    frequency : float
        frequency (Hz)

    """
    import numpy as np
    from scipy.signal import blackmanharris, decimate

    from mhealthx.signals import parabolic

    N = len(signal)
    signal -= np.mean(signal) # Remove DC offset

    # Compute Fourier transform of windowed signal:
    windowed = signal * blackmanharris(len(signal))

    # Get spectrum:
    X = np.log(abs(np.fft.rfft(windowed)))

    # Downsample sum logs of spectra instead of multiplying:
    hps = np.copy(X)
    for h in np.arange(2, 9): # TODO: choose a smarter upper limit
        dec = decimate(X, h)
        hps[:len(dec)] += dec

    # Find the peak and interpolate to get a more accurate peak:
    i_peak = np.argmax(hps[:len(dec)])
    i_interp = parabolic(hps, i_peak)[0]

    # Convert to equivalent frequency:
    frequency = fs * i_interp / N # Hz

    return frequency
Example #26
0
def sineModelMultiRes(x, fs, wList, NList, t, BList):
	"""
	Analysis/synthesis of a sound using the sinusoidal model, without sine tracking
	x: input array sound, w: analysis window, N: size of complex spectrum, t: threshold in negative dB 
	returns y: output array sound
	"""

	#-----synthesis params init-----             
	Ns = 512                                                # FFT size for synthesis (even)
	H = Ns/4                                                # Hop size used for analysis and synthesis
	hNs = Ns/2                                              # half of synthesis FFT size
	yw = np.zeros(Ns)                                       # initialize output sound frame
	y = np.zeros(x.size)                                    # initialize output array
	sw = np.zeros(Ns)                                       # initialize synthesis window
	ow = triang(2*H)                                        # triangular window
	sw[hNs-H:hNs+H] = ow                                    # add triangular window
	bh = blackmanharris(Ns)                                 # blackmanharris window
	bh = bh / sum(bh)                                       # normalized blackmanharris window
	sw[hNs-H:hNs+H] = sw[hNs-H:hNs+H] / bh[hNs-H:hNs+H]     # normalized synthesis window
	for i in range(3):
	#-----analysis params init-----             
		w = wList[i]
		N = NList[i]
		Bmin = BList[i][0]
		Bmax = BList[i][1]
		hM1 = int(math.floor((w.size+1)/2))                     # half analysis window size by rounding
		hM2 = int(math.floor(w.size/2))                         # half analysis window size by floor
		pin = max(hNs, hM1)                                     # init sound pointer in middle of anal window       
		pend = x.size - max(hNs, hM1)                           # last sample to start a frame
		fftbuffer = np.zeros(N)                                 # initialize buffer for FFT	
		w = w / sum(w)                                          # normalize analysis window
		while pin<pend:                                         # while input sound pointer is within sound 
		#-----analysis-----             			
			x1 = x[pin-hM1:pin+hM2]                               # select frame
			mX, pX = DFT.dftAnal(x1, w, N)                        # compute dft
			ploc = UF.peakDetection(mX, t)                        # detect locations of peaks
			iploc, ipmag, ipphase = UF.peakInterp(mX, pX, ploc)   # refine peak values by interpolation
			ipfreq = fs*iploc/float(N)                            # convert peak locations to Hertz
			ipmag = ipmag[np.logical_and(ipfreq>=Bmin, ipfreq<Bmax)]
			ipphase = ipphase[np.logical_and(ipfreq>=Bmin, ipfreq<Bmax)]
			ipfreq = ipfreq[np.logical_and(ipfreq>=Bmin, ipfreq<Bmax)]
		#-----synthesis-----
			Y = UF.genSpecSines(ipfreq, ipmag, ipphase, Ns, fs)   # generate sines in the spectrum         
			fftbuffer = np.real(ifft(Y))                          # compute inverse FFT
			yw[:hNs-1] = fftbuffer[hNs+1:]                        # undo zero-phase window
			yw[hNs-1:] = fftbuffer[:hNs+1] 
			y[pin-hNs:pin+hNs] += sw*yw                           # overlap-add and apply a synthesis window
			pin += H                                              # advance sound pointer

	return y
Example #27
0
File: utils.py Project: TShi/voice
def freq_from_fft(signal, fs):
    """Estimate frequency from peak of FFT

    """
    # Compute Fourier transform of windowed signal
    windowed = signal * blackmanharris(len(signal))
    f = rfft(windowed)

    # Find the peak and interpolate to get a more accurate peak
    i = argmax(abs(f)) # Just use this for less-accurate, naive version
    true_i = parabolic(log(abs(f)), i)[0]

    # Convert to equivalent frequency
    return fs * true_i / len(windowed)
Example #28
0
def pitch_detect(sample):
	if  type(sample) is array.array:
		pass
	else:
		sample = array.array('h',sample)
	window = signal.blackmanharris(len(sample),False)
	window = np.array(window)
	window -=window.mean()
	freq= abs(fp.rfft(window))

	i = np.argmax(abs(freq)) # Just use this for less-accurate, naive version
	true_i = parabolic(np.log(abs(freq)), i)[0]
    
    # Convert to equivalent frequency
	return RATE * true_i / len(window)
Example #29
0
def freq_from_fft(sig, fs):
    """Estimate frequency from peak of FFT

    """
    # Compute Fourier transform of windowed signal
    N = next_fast_len(sig.size)
    windowed = sig * signal.blackmanharris(len(sig))
    f = np.fft.rfft(windowed, N)

    # Find the peak and interpolate to get a more accurate peak
    i = np.argmax(abs(f)) # Just use this for less-accurate, naive version
    true_i = parabolic(np.log(abs(f)), i)[0]

    # Convert to equivalent frequency
    return fs * true_i / N
Example #30
0
def sineModel(x, fs, w, N, t):
  # Analysis/synthesis of a sound using the sinusoidal model
  # x: input array sound, w: analysis window, N: size of complex spectrum,
  # t: threshold in negative dB 
  # returns y: output array sound

  hN = N/2                                                # size of positive spectrum
  hM1 = int(math.floor((w.size+1)/2))                     # half analysis window size by rounding
  hM2 = int(math.floor(w.size/2))                         # half analysis window size by floor
  Ns = 512                                                # FFT size for synthesis (even)
  H = Ns/4                                                # Hop size used for analysis and synthesis
  hNs = Ns/2                                              # half of synthesis FFT size
  pin = max(hNs, hM1)                                     # initialize sound pointer in middle of analysis window       
  pend = x.size - max(hNs, hM1)                           # last sample to start a frame
  fftbuffer = np.zeros(N)                                 # initialize buffer for FFT
  yw = np.zeros(Ns)                                       # initialize output sound frame
  y = np.zeros(x.size)                                    # initialize output array
  w = w / sum(w)                                          # normalize analysis window
  sw = np.zeros(Ns)                                       # initialize synthesis window
  ow = triang(2*H);                                       # triangular window
  sw[hNs-H:hNs+H] = ow                                    # add triangular window
  bh = blackmanharris(Ns)                                 # blackmanharris window
  bh = bh / sum(bh)                                       # normalized blackmanharris window
  sw[hNs-H:hNs+H] = sw[hNs-H:hNs+H] / bh[hNs-H:hNs+H]     # normalized synthesis window

  while pin<pend:                                         # while input sound pointer is within sound 
  #-----analysis-----             
    xw = x[pin-hM1:pin+hM2] * w                           # window the input sound
    fftbuffer = np.zeros(N)                               # reset buffer
    fftbuffer[:hM1] = xw[hM2:]                            # zero-phase window in fftbuffer
    fftbuffer[N-hM2:] = xw[:hM2]        
    X = fft(fftbuffer)                                    # compute FFT
    mX = 20 * np.log10( abs(X[:hN]) )                     # magnitude spectrum of positive frequencies
    ploc = PP.peakDetection(mX, hN, t)                    # detect locations of peaks
    pmag = mX[ploc]                                       # get the magnitude of the peaks
    pX = np.unwrap( np.angle(X[:hN]) )                    # unwrapped phase spect. of positive freq.
    iploc, ipmag, ipphase = PP.peakInterp(mX, pX, ploc)   # refine peak values by interpolation
  
  #-----synthesis-----
    plocs = iploc*Ns/N;                                   # adapt peak locations to size of synthesis FFT
    Y = GS.genSpecSines(plocs, ipmag, ipphase, Ns)        # generate sines in the spectrum         
    fftbuffer = np.real( ifft(Y) )                        # compute inverse FFT
    yw[:hNs-1] = fftbuffer[hNs+1:]                        # undo zero-phase window
    yw[hNs-1:] = fftbuffer[:hNs+1] 
    y[pin-hNs:pin+hNs] += sw*yw                           # overlap-add and apply a synthesis window
    pin += H                                              # advance sound pointer
    
  return y
Ns = 256
hNs = Ns // 2
yw = np.zeros(Ns)
fs = 44100
freqs = np.array([1000.0, 4000.0, 8000.0])
amps = np.array([.6, .4, .6])
phases = ([0.5, 1.2, 2.3])
yploc = Ns * freqs / fs
ypmag = 20 * np.log10(amps / 2.0)
ypphase = phases

Y = UF.genSpecSines(freqs, ypmag, ypphase, Ns, fs)
mY = 20 * np.log10(abs(Y[:hNs]))
pY = np.unwrap(np.angle(Y[:hNs]))
y = fftshift(ifft(Y)) * sum(blackmanharris(Ns))

plt.figure(1, figsize=(9, 5))
plt.subplot(3, 1, 1)
plt.plot(fs * np.arange(Ns / 2) / Ns, mY, 'r', lw=1.5)
plt.axis([0, fs / 2.0, -100, 0])
plt.title("mY, freqs (Hz) = 1000, 4000, 8000; amps = .6, .4, .6")

plt.subplot(3, 1, 2)
pY[pY == 0] = np.nan
plt.plot(fs * np.arange(Ns / 2) / Ns, pY, 'c', lw=1.5)
plt.axis([0, fs / 2.0, -.01, 3.0])
plt.title("pY, phases (radians) = .5, 1.2, 2.3")

plt.subplot(3, 1, 3)
plt.plot(np.arange(-hNs, hNs), y, 'b', lw=1.5)
                 '../../software/models/'))
import utilFunctions as UF
from scipy.signal import blackmanharris, triang
from scipy.fftpack import ifft

fs = 44100
Ns = 512
hNs = Ns / 2
H = Ns / 4
ipfreq = np.array([4000.0])
ipmag = np.array([0.0])
ipphase = np.array([0.0])
Y = UF.genSpecSines_p(ipfreq, ipmag, ipphase, Ns, fs)
y = np.real(ifft(Y))

# undo the blackman harris window and apply a triangle function
sw = np.zeros(Ns)
ow = triang(Ns / 2)
sw[int(hNs - H):int(hNs + H)] = ow
bh = blackmanharris(Ns)
bh = bh / sum(bh)
# sw is the synthesis window
sw[int(hNs -
       H):int(hNs +
              H)] = sw[int(hNs - H):int(hNs + H)] / bh[int(hNs - H):int(hNs +
                                                                        H)]

yw = np.zeros(Ns)
yw[:int(hNs - 1)] = y[int(hNs + 1):]
yw[int(hNs - 1):] = y[:int(hNs + 1)]
yw *= sw
Example #33
0
def hprModel(x, fs, w, N, t, nH, minf0, maxf0, f0et):
    """
	Analysis/synthesis of a sound using the harmonic plus residual model
	x: input sound, fs: sampling rate, w: analysis window, 
	N: FFT size (minimum 512), t: threshold in negative dB, 
	nH: maximum number of harmonics, minf0: minimum f0 frequency in Hz, 
	maxf0: maximim f0 frequency in Hz, 
	f0et: error threshold in the f0 detection (ex: 5),
	maxhd: max. relative deviation in harmonic detection (ex: .2)
	returns y: output sound, yh: harmonic component, xr: residual component
	"""

    hN = N // 2  # size of positive spectrum
    hM1 = int(math.floor(
        (w.size + 1) / 2))  # half analysis window size by rounding
    hM2 = int(math.floor(w.size / 2))  # half analysis window size by floor
    Ns = 512  # FFT size for synthesis (even)
    H = Ns // 4  # Hop size used for analysis and synthesis
    hNs = Ns // 2
    pin = max(hNs,
              hM1)  # initialize sound pointer in middle of analysis window
    pend = x.size - max(hNs, hM1)  # last sample to start a frame
    fftbuffer = np.zeros(N)  # initialize buffer for FFT
    yhw = np.zeros(Ns)  # initialize output sound frame
    xrw = np.zeros(Ns)  # initialize output sound frame
    yh = np.zeros(x.size)  # initialize output array
    xr = np.zeros(x.size)  # initialize output array
    w = w / sum(w)  # normalize analysis window
    sw = np.zeros(Ns)
    ow = triang(2 * H)  # overlapping window
    sw[hNs - H:hNs + H] = ow
    bh = blackmanharris(Ns)  # synthesis window
    bh = bh / sum(bh)  # normalize synthesis window
    wr = bh  # window for residual
    sw[hNs - H:hNs + H] = sw[hNs - H:hNs + H] / bh[hNs - H:hNs + H]
    hfreqp = []
    f0t = 0
    f0stable = 0
    while pin < pend:
        #-----analysis-----
        x1 = x[pin - hM1:pin + hM2]  # select frame
        mX, pX = DFT.dftAnal(x1, w, N)  # compute dft
        ploc = UF.peakDetection(mX, t)  # find peaks
        iploc, ipmag, ipphase = UF.peakInterp(mX, pX,
                                              ploc)  # refine peak values
        ipfreq = fs * iploc / N  # convert locations to Hz
        f0t = UF.f0Twm(ipfreq, ipmag, f0et, minf0, maxf0, f0stable)  # find f0
        if ((f0stable==0)&(f0t>0)) \
         or ((f0stable>0)&(np.abs(f0stable-f0t)<f0stable/5.0)):
            f0stable = f0t  # consider a stable f0 if it is close to the previous one
        else:
            f0stable = 0
        hfreq, hmag, hphase = HM.harmonicDetection(ipfreq, ipmag, ipphase, f0t,
                                                   nH, hfreqp,
                                                   fs)  # find harmonics
        hfreqp = hfreq
        ri = pin - hNs - 1  # input sound pointer for residual analysis
        xw2 = x[ri:ri + Ns] * wr  # window the input sound
        fftbuffer = np.zeros(Ns)  # reset buffer
        fftbuffer[:hNs] = xw2[hNs:]  # zero-phase window in fftbuffer
        fftbuffer[hNs:] = xw2[:hNs]
        X2 = fft(
            fftbuffer)  # compute FFT of input signal for residual analysis
        #-----synthesis-----
        Yh = UF.genSpecSines(hfreq, hmag, hphase, Ns, fs)  # generate sines
        Xr = X2 - Yh  # get the residual complex spectrum
        fftbuffer = np.zeros(Ns)
        fftbuffer = np.real(ifft(Yh))  # inverse FFT of harmonic spectrum
        yhw[:hNs - 1] = fftbuffer[hNs + 1:]  # undo zero-phase window
        yhw[hNs - 1:] = fftbuffer[:hNs + 1]
        fftbuffer = np.zeros(Ns)
        fftbuffer = np.real(ifft(Xr))  # inverse FFT of residual spectrum
        xrw[:hNs - 1] = fftbuffer[hNs + 1:]  # undo zero-phase window
        xrw[hNs - 1:] = fftbuffer[:hNs + 1]
        yh[ri:ri + Ns] += sw * yhw  # overlap-add for sines
        xr[ri:ri + Ns] += sw * xrw  # overlap-add for residual
        pin += H  # advance sound pointer
    y = yh + xr  # sum of harmonic and residual components
    return y, yh, xr
Example #34
0
def sineModelMultiRes(x, fs, windows, fftSizes, t, bands):
    """
	Analysis/synthesis of a sound using a multi-resolution sinusoidal model, without sine tracking
	x: input array sound, 
	s: sampling frequency, 
	w: analysis windows, 
	fftSizes: sizes of complex spectrum, 
	t: threshold in negative dB,
	bands: bands of the sounds for multi-resolution analysis

	returns y: output array sound
	"""

    # Resynthesis values
    Ns = 512  # FFT size for synthesis (even)
    H = Ns // 4  # Hop size used for analysis and synthesis
    hNs = Ns // 2  # half of synthesis FFT size
    yw = np.zeros(Ns)  # initialize output sound frame

    x = np.array(x)  # Convert input to numpy array

    # Create output buffers for all the bands
    y1 = np.zeros(x.size)
    y2 = np.zeros(x.size)
    y3 = np.zeros(x.size)
    outputArrays = np.array([y1, y2, y3])

    sw = np.zeros(Ns)  # initialize synthesis window
    ow = triang(2 * H)  # triangular window
    sw[hNs - H:hNs + H] = ow  # add triangular window
    bh = blackmanharris(Ns)  # blackmanharris window
    bh = bh / sum(bh)  # normalized blackmanharris window
    sw[hNs - H:hNs +
       H] = sw[hNs - H:hNs + H] / bh[hNs - H:hNs +
                                     H]  # normalized synthesis window

    # Compute analysis/synthesis 3 times with each window/fft/band
    for i in range(0, 3):

        #-----variable inits-----

        # Get the current window bounds (rounding up/floor down)
        hM1 = int(math.floor((windows[i].size + 1) / 2))
        hM2 = int(math.floor(windows[i].size / 2))

        # Get start/end pin for current window
        pin = max(hNs, hM1)
        pend = x.size - max(hNs, hM1)

        # Normalize window
        w = windows[i] / sum(windows[i])

        # Get current FFT size and init FFT buffer
        N = fftSizes[i]
        fftbuffer = np.zeros(N)

        # Pick up/down bin limits
        binCutoffUpLimit = (np.ceil(bands[i] * N / fs)) - 1
        if i == 0:
            binCutoffDownLimit = 0
        else:
            binCutoffDownLimit = np.ceil(bands[i - 1] * N / fs)

        while pin < pend:

            #-----analysis-----

            # Get the frame with current window size
            x1 = x[pin - hM1:pin + hM2]

            # Get the spectra for each frame sizes using windows with their respective FFT sizes
            mX, pX = DFT.dftAnal(x1, w, N)

            # Only get the part of the spectrum we're interested in for the current band
            mXFilt = mX.copy()
            mXFilt[binCutoffDownLimit:] = -120
            mXFilt[:binCutoffUpLimit] = -120

            # Get the peaks out of each spectrum
            ploc = UF.peakDetection(mX, t)

            # Refine peak values by interpolation
            iploc, ipmag, ipphase = UF.peakInterp(mX, pX, ploc)

            # Convert peak locations to Hertz
            ipfreq = fs * iploc / float(N)

            #-----synthesis-----
            Y = UF.genSpecSines(ipfreq, ipmag, ipphase, Ns,
                                fs)  # generate sines in the spectrum
            fftbuffer = np.real(ifft(Y))  # compute inverse FFT
            yw[:hNs - 1] = fftbuffer[hNs + 1:]  # undo zero-phase window
            yw[hNs - 1:] = fftbuffer[:hNs + 1]
            # Place sample to respective output array
            outputArrays[
                i][pin - hNs:pin +
                   hNs] += sw * yw  # overlap-add and apply a synthesis window
            pin += H  # advance sound pointer

        # Sum the content of the three time-domain-bandlimited output arrays into final output array
        out = outputArrays.sum(axis=0)
        # Scale down the final output (optimally I would have windowed-out for the filtering process)
        out *= 0.3

    return out
Example #35
0
import matplotlib.pyplot as plt
import numpy as np
from scipy.fftpack import fft
from scipy import signal

M = 64
N = 512
hN = N / 2
hM = M / 2
fftbuffer = np.zeros(N)
mX1 = np.zeros(N)

plt.figure(1, figsize=(7.5, 4))
fftbuffer[hN - hM:hN + hM] = signal.blackmanharris(M)
plt.subplot(2, 1, 1)
plt.plot(np.arange(-hN, hN), fftbuffer, 'b', lw=1.5)
plt.axis([-hN, hN, 0, 1.1])

X = fft(fftbuffer)
mX = 20 * np.log10(abs(X))
mX1[:hN] = mX[hN:]
mX1[N - hN:] = mX[:hN]

plt.subplot(2, 1, 2)
plt.plot(np.arange(-hN, hN), mX1 - max(mX), 'r', lw=1.5)
plt.axis([-hN, hN, -110, 0])

plt.tight_layout()
plt.savefig('blackman-harris.png')
plt.show()
Example #36
0
A = lambda t: A_fun(t, F_m, F_0)
F = lambda t: F_fun(t, F_m, F_0)
reltol = 1e-8
abstol = 1e-10
theta1 = np.pi / 3

pool = mp.Pool()
pool.map(ode_parallel, range(ky_n))
pool.close()

dt = tspan[1] - tspan[0]
jx_er = np.gradient(jx_er, dt)
jy_er = np.gradient(jy_er, dt)

# Applying window functions to the current
window = signal.blackmanharris(jx_ra.shape[0])
jx_ra *= window
jy_ra *= window
jx_er *= window
jy_er *= window

# Material properties (in terms of of fundamental freq.
x_mingab = 8
x_maxgab = 31
x_specrange = 51

# Axis of HHG-spectra
L = tspan.shape[0]
n = np.power(2, nextpow2(L))
t_step = tspan[1] - tspan[0]
f = np.arange(int(n / 2) + 1) / t_step * np.pi / (int(n / 2) + 1) / omega
plt.subplot(3,2,1)
plt.plot(freqaxis, mX, 'r', lw=1.5)
plt.axis([0,fs/2,-110, 0])
plt.title ('mW1; Hamming')

plt.subplot(3,2,3)
plt.plot(freqaxis, pX, 'c', lw=1.5)
plt.axis([0,fs/2,min(pX),max(pX)])
plt.title ('pW1; Hamming')

plt.subplot(3,2,5)
plt.plot(np.arange(-hM,hM+1), y[0:M], 'b', lw=1.5)
plt.axis([-hM,hM+1,-1,1])
plt.title ('y1')

w = blackmanharris(255)
mX, pX = DFT.dftAnal(x, w, N)
y = DFT.dftSynth(mX,pX,M)*sum(w)

plt.subplot(3,2,2)
plt.plot(freqaxis, mX, 'r', lw=1.5)
plt.axis([0,fs/2,-110, 0])
plt.title ('mW2; Blackman Harris')

plt.subplot(3,2,4)
plt.plot(freqaxis, pX, 'c', lw=1.5)
plt.axis([0,fs/2,min(pX),max(pX)])
plt.title ('pW2; Blackman Harris')

plt.subplot(3,2,6)
plt.plot(np.arange(-hM,hM+1), y[0:M], 'b', lw=1.5)
Example #38
0
def sineModelMultiRes_combined(x, fs, multi_w, multi_N, t, multi_B):
    """
    Analysis/synthesis of a sound using the sinusoidal model, without sine tracking
    x: input array sound, w: analysis window, N: size of complex spectrum, t: threshold in negative dB
    returns y: output array sound
    """

    # fallback for original code
    w = multi_w[0]
    N = multi_N[0]

    bands = range(len(multi_B))  # to iterate over bands

    #-orig-----------------------------
    hM1 = int(math.floor(
        (w.size + 1) / 2))  # half analysis window size by rounding
    hM2 = int(math.floor(w.size / 2))  # half analysis window size by floor
    #-multi----------------------------
    multi_w_size = np.array([multi_w[i].size for i in bands])
    multi_hM1 = np.floor((multi_w_size + 1) / 2.0).astype(
        int)  # half analysis window size by rounding
    multi_hM2 = np.floor(multi_w_size / 2.0).astype(
        int)  # half analysis window size by floor
    #----------------------------------

    Ns = 512  # FFT size for synthesis (even)
    H = Ns / 4  # Hop size used for analysis and synthesis
    hNs = Ns / 2  # half of synthesis FFT size

    #-orig-----------------------------
    pin = max(hNs, hM1)  # init sound pointer in middle of anal window
    pend = x.size - max(hNs, hM1)  # last sample to start a frame
    #-multi----------------------------
    multi_pin = np.maximum(
        hNs, multi_hM1)  # init sound pointer in middle of anal window
    multi_pend = x.size - multi_pin  # last sample to start a frame
    #----------------------------------

    #-orig-----------------------------
    fftbuffer = np.zeros(N)  # initialize buffer for FFT
    #-multi----------------------------
    fftbuffer_combined = np.zeros(N)
    #multi_fftbuffer = [np.array(multi_N[i]) for i in bands]
    #----------------------------------

    yw = np.zeros(Ns)  # initialize output sound frame
    y = np.zeros(x.size)  # initialize output array

    #-multi----------------------------
    yw_combined = np.zeros(Ns)  # initialize output sound frame
    y_combined = np.zeros(x.size)  # initialize output array

    #-orig-----------------------------
    w = w / sum(w)  # normalize analysis window
    #-multi----------------------------
    multi_w = [multi_w[i] / sum(multi_w[i])
               for i in bands]  # normalize analysis window
    #----------------------------------

    sw = np.zeros(Ns)  # initialize synthesis window
    ow = triang(2 * H)  # triangular window
    sw[hNs - H:hNs + H] = ow  # add triangular window
    bh = blackmanharris(Ns)  # blackmanharris window
    bh = bh / sum(bh)  # normalized blackmanharris window
    sw[hNs - H:hNs +
       H] = sw[hNs - H:hNs + H] / bh[hNs - H:hNs +
                                     H]  # normalized synthesis window

    while pin < pend and (multi_pin < multi_pend
                          ).all():  # while input sound pointer is within sound
        #-----analysis-----

        #-orig-----------------------------
        x1 = x[pin - hM1:pin + hM2]  # select frame
        #-multi----------------------------
        multi_x1 = [
            x[(multi_pin[i] - multi_hM1[i]):(multi_pin[i] + multi_hM2[i])]
            for i in bands
        ]  # select frame
        #----------------------------------

        #-orig-----------------------------
        mX, pX = DFT.dftAnal(x1, w, N)  # compute dft
        #-multi----------------------------
        multi_mX = []
        multi_pX = []
        for i in bands:
            mXi, pXi = DFT.dftAnal(multi_x1[i], multi_w[i], multi_N[i])
            multi_mX.append(mXi)
            multi_pX.append(pXi)
        #----------------------------------

        # we could apply the filters for the bands here already ...

        #-orig-----------------------------
        ploc = UF.peakDetection(mX, t)  # detect locations of peaks
        #pmag = mX[ploc]                                       # get the magnitude of the peaks
        #-multi----------------------------
        multi_ploc = []
        #multi_pmag = []
        for i in bands:
            ploci = UF.peakDetection(multi_mX[i],
                                     t)  # detect locations of peaks
            #pmagi = multi_mX[i][ploci]                                       # get the magnitude of the peaks
            multi_ploc.append(ploci)
            #multi_pmag.append(pmagi)
        #----------------------------------

        #-orig-----------------------------
        iploc, ipmag, ipphase = UF.peakInterp(
            mX, pX, ploc)  # refine peak values by interpolation
        ipfreq = fs * iploc / float(N)  # convert peak locations to Hertz
        #-multi----------------------------
        #multi_iploc = []
        multi_ipmag = []
        multi_ipphase = []
        multi_ipfreq = []
        for i in bands:
            iploci, ipmagi, ipphasei = UF.peakInterp(
                multi_mX[i], multi_pX[i],
                multi_ploc[i])  # refine peak values by interpolation
            ipfreqi = fs * iploci / float(
                multi_N[i])  # convert peak locations to Hertz
            #multi_iploc.append(iploci)
            multi_ipmag.append(ipmagi)
            multi_ipphase.append(ipphasei)
            multi_ipfreq.append(ipfreqi)
        #----------------------------------

        # ... but we shall decide here!
        """
        print "--------------------------------------"
        print ipfreq
        print ipmag
        print ipphase
        """
        """
        ipfreq_combined = []
        ipmag_combined = []
        ipphase_combined = []
        for i in bands:
            for p in range(len(multi_ipfreq[i])):
                f = multi_ipfreq[i][p]
                if (i == 0 or f >= multi_B[i-1]) and f < multi_B[i]:
                    ipfreq_combined.append(f)
                    ipmag_combined.append(multi_ipmag[i][p])
                    ipphase_combined.append(multi_ipphase[i][p])


        #ipfreq = np.array(ipfreq_combined)
        #ipmag = np.array(ipmag_combined)
        #ipphase = np.array(ipphase_combined)
        """

        # count first for array allocation
        num_ip = 0
        for i in bands:
            for p in range(len(multi_ipfreq[i])):
                f = multi_ipfreq[i][p]
                if (i == 0 or f >= multi_B[i - 1]) and f < multi_B[i]:
                    num_ip += 1

        ipfreq_combined = np.zeros(num_ip)
        ipmag_combined = np.zeros(num_ip)
        ipphase_combined = np.zeros(num_ip)
        ip = 0
        for i in bands:
            for p in range(len(multi_ipfreq[i])):
                f = multi_ipfreq[i][p]
                if (i == 0 or f >= multi_B[i - 1]) and f < multi_B[i]:
                    ipfreq_combined[ip] = f
                    ipmag_combined[ip] = multi_ipmag[i][p]
                    ipphase_combined[ip] = multi_ipphase[i][p]
                    ip += 1
        """
        print "--------------------------------------"
        print ipfreq_combined
        print ipmag_combined
        print ipphase_combined
        """

        #-----synthesis-----
        Y = UF.genSpecSines(ipfreq, ipmag, ipphase, Ns,
                            fs)  # generate sines in the spectrum
        fftbuffer = np.real(ifft(Y))  # compute inverse FFT
        yw[:hNs - 1] = fftbuffer[hNs + 1:]  # undo zero-phase window
        yw[hNs - 1:] = fftbuffer[:hNs + 1]
        y[pin - hNs:pin +
          hNs] += sw * yw  # overlap-add and apply a synthesis window
        #print y[pin-hNs:pin+hNs]
        pin += H  # advance sound pointer

        Y_combined = UF.genSpecSines(ipfreq_combined, ipmag_combined,
                                     ipphase_combined, Ns,
                                     fs)  # generate sines in the spectrum
        fftbuffer_combined = np.real(ifft(Y_combined))  # compute inverse FFT
        yw_combined[:hNs -
                    1] = fftbuffer_combined[hNs + 1:]  # undo zero-phase window
        yw_combined[hNs - 1:] = fftbuffer_combined[:hNs + 1]
        y_combined[
            pin - hNs:pin +
            hNs] += sw * yw_combined  # overlap-add and apply a synthesis window
        #print y_combined[pin-hNs:pin+hNs]
        multi_pin += H
        """
        plt.figure(1)
        plt.plot(abs(Y))
        plt.figure(2)
        plt.plot(abs(Y_combined))
        plt.show()
        """

    return y, y_combined
Example #39
0
def sineModelMultiRes(x, fs, w, N, t,B):
	"""
	Analysis/synthesis of a sound using the sinusoidal model, without sine tracking
	x: input array sound, w: analysis window, N: size of complex spectrum, t: threshold in negative dB
	returns y: output array sound
	MODIFIED by RJL for Audio Signal Processing course on coursera to allow for multi resolutions
	w=[w1,w2,w3] are the windows for the three bands (with corresponding fft size N= [N1,N2,N3]).
	The bands are defined by the boundaries B= [Ba,Bb].  I.e Band 1 is 0<= f< Ba, band 2 is Ba <= f < Bb,
	and band 3 is Bb <= f < 22050.  (The assignement instructions suggested as input three 'bands' but only two
	numbers are requred here.)

	"""
	# Note: For production code would need to make sure the arguments are lists of the correct size Here

	hM1s = [int(math.floor((aw.size+1)/2)) for aw in w]     # half analysis window size by rounding
	hM2s = [int(math.floor(aw.size/2)) for aw in w]         # half analysis window size by floor
	Ns = 512                                                # FFT size for synthesis (even)
	H = Ns//4                                               # Hop size used for analysis and synthesis
	hNs = Ns//2                                             # half of synthesis FFT size
	pin = max(hNs, max(hM1s))                               # init sound pointer in middle of anal window
	pend = x.size - max(hNs, max(hM1s))                     # last sample to start a frame
	fftbuffers = [np.zeros(n) for n in N]                   # initialize buffers for FFTs
	yw = np.zeros(Ns)                                       # initialize output sound frame
	y = np.zeros(x.size)                                    # initialize output array
	w = [aw / sum(aw) for aw in w]                                          # normalize analysis windows
	sw = np.zeros(Ns)                                       # initialize synthesis window
	ow = triang(2*H)                                        # triangular window
	sw[hNs-H:hNs+H] = ow                                    # add triangular window
	bh = blackmanharris(Ns)                                 # blackmanharris window
	bh = bh / sum(bh)                                       # normalized blackmanharris window
	sw[hNs-H:hNs+H] = sw[hNs-H:hNs+H] / bh[hNs-H:hNs+H]     # normalized synthesis window

	B = [(0,B[0]),(B[0],B[1]),(B[1],22050)]							# set up bands
	ipfreq = [0,0,0]
	ipphase =[0,0,0]
	ipmag =[0,0,0]
	while pin<pend:                                         # while input sound pointer is within sound
	#-----analysis----- Basically unchanged but done three times, ecept i get rid of frequencies not in band

		for i in range(0,3):								# here we mandate three bands!
			x1 = x[pin-hM1s[i]:pin+hM2s[i]]                               # select frame
			mX, pX = DFT.dftAnal(x1, w[i], N[i])                        # compute dft
			ploc = UF.peakDetection(mX, t)                        # detect locations of peaks
			iploc, ipmagt, ipphaset = UF.peakInterp(mX, pX, ploc)   # refine peak values by interpolation
			ipfreqt = fs*iploc/float(N[i])                            # convert peak locations to Her

			indexes = [j for (j,f) in enumerate(ipfreqt) if f >= B[i][0] and f < B[i][1] ]    # filter out of band peaks
			ipfreq[i] = ipfreqt[indexes]			# There must be an easier way, but here are rebuild
			ipphase[i] = ipphaset[indexes]			# with only the indexes where the freq is in range
			ipmag[i] = ipmagt[indexes]
		# Combine the peaks into single combined analysis. This is verbose but clear

		ipfreqC = np.concatenate((ipfreq[0],ipfreq[1],ipfreq[2]))
		ipphaseC =  np.concatenate((ipphase[0] , ipphase[1] ,ipphase[2]))
		ipmagC =  np.concatenate((ipmag[0],ipmag[1],ipmag[2]))

	#-----synthesis-----   completely unchanged.
		# import pdb; pdb.set_trace()
		Y = UF.genSpecSines(ipfreqC, ipmagC, ipphaseC, Ns, fs)   # generate sines in the spectrum
		fftbuffer = np.real(ifft(Y))                          # compute inverse FFT
		yw[:hNs-1] = fftbuffer[hNs+1:]                        # undo zero-phase window
		yw[hNs-1:] = fftbuffer[:hNs+1]
		y[pin-hNs:pin+hNs] += sw*yw                           # overlap-add and apply a synthesis window
		pin += H                                              # advance sound pointer
	return y
Example #40
0
from scipy.io import wavfile
from scipy import signal
from sinemodel import *

# read the wav file
filename = "sound/Wave_5.wav"
[fs, x] = wavfile.read(filename)

# parameter
L = size(x)
dureefenetre = 23e-3  #duration of each window
#M=fs*dureefenetre
M = dureefenetre * fs  #window size
if (M % 2 == 0): M += 1
H_ratio = 0.25  # Ratio (hop size)/(window size)
w = signal.blackmanharris(M)  # window for tram
N = 1024  # fft size
Ns = 1024  # window size for synthesis
seuil = -50

#t = linspace(0,1,16000);
#x = sin(2*pi*1000*t);
y = sinemodel(x, w, N, Ns, H_ratio, seuil)
#==============================================================================
#   Analysis/synthesis of a sound using the sinusoidal model
#   x: input sound, w: analysis window (odd size), N: FFT size,
#   seuil: threshold in negative dB, y: output sound
#   Ns: FFT size for synthesis (even)
#   H_Ratio: (hop size)/(window size)
#==============================================================================
wavfile.write('test.wav', fs, y)
Example #41
0
else:
    data = cic_out
    rate = Fs / cic_rate

data_len = len(data)
t = np.arange(data_len) / rate

# plot of time
fig = plt.figure(1)
plt.plot(t, np.real(data))
plt.grid()
plt.xlabel("Time")
plt.ylabel("data")
plt.title("sinusoid - time")

# plot of frequency
fig = plt.figure(2)
f = rate * fftshift(fftfreq(data_len)) / 1e6
win = signal.blackmanharris(data_len)
data_bhwin = data * win
bh_gain = sum(win) / data_len
data_dB = 20 * np.log10(
    np.abs(fftshift(fft(data_bhwin))) / (data_len * (data_scl / 2) * bh_gain))
plt.plot(f, data_dB)
plt.grid()
plt.xlabel("Frequency (MHz)")
plt.ylabel("dB")
plt.title("sinusoid - freq")
plt.xlim((0, (rate / 1e6) / 2))
plt.show()
Example #42
0
def freq_from_fft(sig, fs):
    windowed = sig * blackmanharris(len(sig))
    f = rfft(windowed)
    i = argmax(abs(f)) # Just use this for less-accurate, naive version
    true_i = parabolic(abs(f), i)[0]
    return fs * true_i / len(windowed)
x = np.concatenate((x, np.zeros(pad)))
"""
# Display waveform
plt.figure(figsize=(20,5))
plt.plot(x)
plt.axis([0, x.size, -1.1, 1.1])
plt.title("Original signal")
plt.ylabel("Amplitude[V]")
plt.xlabel("Time[s]")
plt.grid()
plt.show()
"""

# Compute STFT
print "Computing STFT... "
w = signal.blackmanharris(N)
# without zero padding
M = w.size  # size of analysis window
hM1 = int(math.floor((M + 1) / 2))  # half analysis window size by rounding
hM2 = int(math.floor(M / 2))  # half analysis window size by floor
x = np.append(np.zeros(hM2),
              x)  # add zeros at beginning to center first window at sample 0
x = np.append(x, np.zeros(hM1))  # add zeros at the end to analyze last sample
pin = hM1  # initialize sound pointer in middle of analysis window
pend = x.size - hM1  # last sample to start a frame
w = w / sum(w)  # normalize analysis window
yp = np.zeros(x.size)  # initialize output array
yh = np.zeros(x.size)  # initialize output array
nframes = (x.size - M) / overlap + 1
S = np.zeros(shape=(nframes,
                    hM2 + 1))  # initialize magnitude of spectrogram array
def hpsModel(x, fs, w, N, t, nH, minf0, maxf0, f0et, stocf):
    """
	Analysis/synthesis of a sound using the harmonic plus stochastic model, one frame at a time, no harmonic tracking
	x: input sound; fs: sampling rate, w: analysis window; N: FFT size (minimum 512), t: threshold in negative dB, 
	nH: maximum number of harmonics, minf0: minimum f0 frequency in Hz; maxf0: maximim f0 frequency in Hz, 
	f0et: error threshold in the f0 detection (ex: 5); stocf: decimation factor of mag spectrum for stochastic analysis
	returns y: output sound, yh: harmonic component, yst: stochastic component
	"""

    hN = N // 2  # size of positive spectrum
    hM1 = int(math.floor(
        (w.size + 1) / 2))  # half analysis window size by rounding
    hM2 = int(math.floor(w.size / 2))  # half analysis window size by floor
    Ns = 512  # FFT size for synthesis (even)
    H = Ns // 4  # Hop size used for analysis and synthesis
    hNs = Ns // 2
    pin = max(hNs,
              hM1)  # initialize sound pointer in middle of analysis window
    pend = x.size - max(hNs, hM1)  # last sample to start a frame
    fftbuffer = np.zeros(N)  # initialize buffer for FFT
    yhw = np.zeros(Ns)  # initialize output sound frame
    ystw = np.zeros(Ns)  # initialize output sound frame
    yh = np.zeros(x.size)  # initialize output array
    yst = np.zeros(x.size)  # initialize output array
    w = w / sum(w)  # normalize analysis window
    sw = np.zeros(Ns)
    ow = triang(2 * H)  # overlapping window
    sw[hNs - H:hNs + H] = ow
    bh = blackmanharris(Ns)  # synthesis window
    bh = bh / sum(bh)  # normalize synthesis window
    wr = bh  # window for residual
    sw[hNs - H:hNs +
       H] = sw[hNs - H:hNs +
               H] / bh[hNs - H:hNs +
                       H]  # synthesis window for harmonic component
    sws = H * hanning(Ns) / 2  # synthesis window for stochastic
    hfreqp = []
    f0t = 0
    f0stable = 0
    while pin < pend:
        #-----analysis-----
        x1 = x[pin - hM1:pin + hM2]  # select frame
        mX, pX = DFT.dftAnal(x1, w, N)  # compute dft
        ploc = UF.peakDetection(mX, t)  # find peaks
        iploc, ipmag, ipphase = UF.peakInterp(mX, pX,
                                              ploc)  # refine peak values
        ipfreq = fs * iploc / N  # convert peak locations to Hz
        f0t = UF.f0Twm(ipfreq, ipmag, f0et, minf0, maxf0, f0stable)  # find f0
        if ((f0stable==0)&(f0t>0)) \
         or ((f0stable>0)&(np.abs(f0stable-f0t)<f0stable/5.0)):
            f0stable = f0t  # consider a stable f0 if it is close to the previous one
        else:
            f0stable = 0
        hfreq, hmag, hphase = HM.harmonicDetection(ipfreq, ipmag, ipphase, f0t,
                                                   nH, hfreqp,
                                                   fs)  # find harmonics
        hfreqp = hfreq
        ri = pin - hNs - 1  # input sound pointer for residual analysis
        xw2 = x[ri:ri + Ns] * wr  # window the input sound
        fftbuffer = np.zeros(Ns)  # reset buffer
        fftbuffer[:hNs] = xw2[hNs:]  # zero-phase window in fftbuffer
        fftbuffer[hNs:] = xw2[:hNs]
        X2 = fft(fftbuffer)  # compute FFT for residual analysis
        #-----synthesis-----
        Yh = UF.genSpecSines(hfreq, hmag, hphase, Ns,
                             fs)  # generate spec sines of harmonic component
        Xr = X2 - Yh  # get the residual complex spectrum
        mXr = 20 * np.log10(abs(Xr[:hNs]))  # magnitude spectrum of residual
        mXrenv = resample(
            np.maximum(-200, mXr),
            mXr.size * stocf)  # decimate the magnitude spectrum and avoid -Inf
        stocEnv = resample(mXrenv, hNs)  # interpolate to original size
        pYst = 2 * np.pi * np.random.rand(hNs)  # generate phase random values
        Yst = np.zeros(Ns, dtype=complex)
        Yst[:hNs] = 10**(stocEnv / 20) * np.exp(
            1j * pYst)  # generate positive freq.
        Yst[hNs + 1:] = 10**(stocEnv[:0:-1] / 20) * np.exp(
            -1j * pYst[:0:-1])  # generate negative freq.

        fftbuffer = np.zeros(Ns)
        fftbuffer = np.real(ifft(Yh))  # inverse FFT of harmonic spectrum
        yhw[:hNs - 1] = fftbuffer[hNs + 1:]  # undo zero-phase window
        yhw[hNs - 1:] = fftbuffer[:hNs + 1]

        fftbuffer = np.zeros(Ns)
        fftbuffer = np.real(ifft(Yst))  # inverse FFT of stochastic spectrum
        ystw[:hNs - 1] = fftbuffer[hNs + 1:]  # undo zero-phase window
        ystw[hNs - 1:] = fftbuffer[:hNs + 1]

        yh[ri:ri + Ns] += sw * yhw  # overlap-add for sines
        yst[ri:ri + Ns] += sws * ystw  # overlap-add for stochastic
        pin += H  # advance sound pointer

    y = yh + yst  # sum of harmonic and stochastic components
    return y, yh, yst
Example #45
0
def sineModelMultiRes(x, fs, multi_w, multi_N, t, multi_B):
    """
    Analysis/synthesis of a sound using the sinusoidal model, without sine tracking
    x: input array sound, w: analysis window, N: size of complex spectrum, t: threshold in negative dB
    returns y: output array sound
    """

    bands = range(len(multi_B))  # to iterate over bands

    N = max(multi_N)

    multi_w_size = np.array([multi_w[i].size for i in bands])
    multi_hM1 = np.floor((multi_w_size + 1) / 2.0).astype(
        int)  # half analysis window size by rounding
    multi_hM2 = np.floor(multi_w_size / 2.0).astype(
        int)  # half analysis window size by floor

    Ns = 512  # FFT size for synthesis (even)
    H = Ns / 4  # Hop size used for analysis and synthesis
    hNs = Ns / 2  # half of synthesis FFT size

    multi_pin = np.maximum(
        hNs, multi_hM1)  # init sound pointer in middle of anal window
    multi_pend = x.size - multi_pin  # last sample to start a frame

    fftbuffer_combined = np.zeros(N)

    yw_combined = np.zeros(Ns)  # initialize output sound frame
    y_combined = np.zeros(x.size)  # initialize output array

    multi_w = [multi_w[i] / sum(multi_w[i])
               for i in bands]  # normalize analysis window

    sw = np.zeros(Ns)  # initialize synthesis window
    ow = triang(2 * H)  # triangular window
    sw[hNs - H:hNs + H] = ow  # add triangular window
    bh = blackmanharris(Ns)  # blackmanharris window
    bh = bh / sum(bh)  # normalized blackmanharris window
    sw[hNs - H:hNs +
       H] = sw[hNs - H:hNs + H] / bh[hNs - H:hNs +
                                     H]  # normalized synthesis window

    while (multi_pin <
           multi_pend).all():  # while input sound pointer is within sound
        #-----analysis-----

        multi_x1 = [
            x[(multi_pin[i] - multi_hM1[i]):(multi_pin[i] + multi_hM2[i])]
            for i in bands
        ]  # select frame

        multi_mX = []
        multi_pX = []
        for i in bands:
            mXi, pXi = DFT.dftAnal(multi_x1[i], multi_w[i], multi_N[i])
            multi_mX.append(mXi)
            multi_pX.append(pXi)

        multi_ploc = []
        for i in bands:
            ploci = UF.peakDetection(multi_mX[i],
                                     t)  # detect locations of peaks
            multi_ploc.append(ploci)

        multi_ipmag = []
        multi_ipphase = []
        multi_ipfreq = []
        for i in bands:
            iploci, ipmagi, ipphasei = UF.peakInterp(
                multi_mX[i], multi_pX[i],
                multi_ploc[i])  # refine peak values by interpolation
            ipfreqi = fs * iploci / float(
                multi_N[i])  # convert peak locations to Hertz
            multi_ipmag.append(ipmagi)
            multi_ipphase.append(ipphasei)
            multi_ipfreq.append(ipfreqi)

        # count first for array allocation
        num_ip = 0
        for i in bands:
            for p in range(len(multi_ipfreq[i])):
                f = multi_ipfreq[i][p]
                if (i == 0 or f >= multi_B[i - 1]) and f < multi_B[i]:
                    num_ip += 1

        ipfreq_combined = np.zeros(num_ip)
        ipmag_combined = np.zeros(num_ip)
        ipphase_combined = np.zeros(num_ip)
        ip = 0
        for i in bands:
            for p in range(len(multi_ipfreq[i])):
                f = multi_ipfreq[i][p]
                if (i == 0 or f >= multi_B[i - 1]) and f < multi_B[i]:
                    ipfreq_combined[ip] = f
                    ipmag_combined[ip] = multi_ipmag[i][p]
                    ipphase_combined[ip] = multi_ipphase[i][p]
                    ip += 1

    #-----synthesis-----
        Y_combined = UF.genSpecSines(ipfreq_combined, ipmag_combined,
                                     ipphase_combined, Ns,
                                     fs)  # generate sines in the spectrum
        fftbuffer_combined = np.real(ifft(Y_combined))  # compute inverse FFT
        yw_combined[:hNs -
                    1] = fftbuffer_combined[hNs + 1:]  # undo zero-phase window
        yw_combined[hNs - 1:] = fftbuffer_combined[:hNs + 1]
        y_combined[
            multi_pin[0] - hNs:multi_pin[0] +
            hNs] += sw * yw_combined  # overlap-add and apply a synthesis window
        multi_pin += H

    return y_combined
Example #46
0
def genCQTkernel(fmax, bins, fs, **kwargs):
    '''
    %Calculating the CQT Kernel for one octave. All atoms are center-stacked. 
    %Atoms are placed so that the stacks of lower octaves are centered at the 
    %same positions in time, however, their amount is reduced by factor two for 
    %each octave down. 
    % 
    %INPUT: 
    %   fmax          ... highest frequency of interest 
    %   bins          ... number of bins per octave 
    %   fs            ... sampling frequency 
    % 
    %optional input parameters (parameter name/value pairs): 
    % 
    %   'q'             ... Q scaling factor. Default: 1. 
    %   'atomHopFactor' ... relative hop size corresponding to the shortest 
    %                       temporal atom. Default: 0.25. 
    %   'thresh'        ... values smaller than 'tresh' in the spectral kernel are rounded to 
    %                       zero. Default: 0.0005. 
    %   'win'           ... defines which window will be used for the CQT. Valid 
    %                       values are: 'blackman','hann' and 'blackmanharris'. To 
    %                       use the square root of each window use the prefix 'sqrt_' 
    %                      (i.e. 'sqrt_blackman'). Default: 'sqrt_blackmanharris' 
    %   'perfRast'      ... if set to 1 the kernel is designed in order to 
    %                       enable perfect rasterization using the function 
    %                       cqtPerfectRast() (Default: perRast=0). See documentation of 
    %                       'cqtPerfectRast' for further information. 
    % 
    %OUTPUT: 
    %   cqtKernel   ... Dict that contains the spectral kernel 'fKernel' 
    %                   additional design parameters used in cqt(), cqtPerfectRast() and icqt(). 
    % 
    %He Wang, 2020/12/01 [email protected]
    '''
    # input parameters 
    q             = kwargs.get('q', 1)
    atomHopFactor = kwargs.get('atomHopFactor', 0.25)
    thresh        = kwargs.get('thresh', 0.0005)
    winFlag       = kwargs.get('win', 'sqrt_blackmanharris')
    perfRast      = kwargs.get('perfRast', 0)
        
    # define 
    fmin = (fmax/2)*2**(1/bins)
    Q = 1/(2**(1/bins)-1)
    Q = Q*q
    Nk_max = Q * fs / fmin
    Nk_max = round_half_up(Nk_max) # length of the largest atom [samples] 

    # Compute FFT size, FFT hop, atom hop, ... 
    Nk_min = round_half_up( Q * fs / (fmin*2**((bins-1)/bins)) ) # length of the shortest atom [samples] 
    atomHOP = round_half_up(Nk_min * atomHopFactor) # atom hop size 
    first_center = np.ceil(Nk_max/2) # first possible center position within the frame 
    first_center = atomHOP * np.ceil(first_center/atomHOP) # lock the first center to an integer multiple of the atom hop size 
    FFTLen = 2**nextpow2(first_center+np.ceil(Nk_max/2)) # use smallest possible FFT size (increase sparsity) 

    if perfRast:
        winNr = int(np.floor((FFTLen-np.ceil(Nk_max/2)-first_center)/atomHOP)) # number of temporal atoms per FFT Frame 
        if winNr == 0 :
            FFTLen = FFTLen * 2
            winNr = int(np.floor((FFTLen-np.ceil(Nk_max/2)-first_center)/atomHOP))
    else:
        winNr = int(np.floor((FFTLen-np.ceil(Nk_max/2)-first_center)/atomHOP))+1 # number of temporal atoms per FFT Frame 


    last_center = first_center + (winNr-1)*atomHOP
    fftHOP = (last_center + atomHOP) - first_center # hop size of FFT frames 
    fftOLP = (FFTLen-fftHOP/FFTLen)*100 # overlap of FFT frames in percent ***AK:needed? 
    
    # init variables 
    tempKernel= np.zeros((1, FFTLen), dtype=complex)
    sparKernel= np.zeros((1, FFTLen), dtype=complex)#[]
    
    # Compute kernel 
    atomInd = 0
    for k in range(bins):

        Nk = int(round_half_up( Q * fs / (fmin*2**(k/bins)) )) # N[k] = (fs/fk)*Q. Rounding will be omitted in future versions 
        
        if winFlag == 'sqrt_blackmanharris': 
            winFct = np.sqrt(blackmanharris(Nk))
        elif winFlag == 'blackmanharris': 
            winFct = blackmanharris(Nk)
        elif winFlag == 'sqrt_hann':
            winFct = np.sqrt(hann(Nk, 'periodic'))
        elif winFlag == 'hann':
            winFct = hann(Nk, 'periodic')
        elif winFag == 'sqrt_blackman':
            winFct = np.sqrt(blackman(Nk, False))
        elif winFag == 'blackman':
            winFct = blackman(Nk, False)
        else:
            winFct = np.sqrt(blackmanharris(Nk))
            if k==1:
                warnings.warn('QT:INPUT','Non-existing window function. Default window is used!', UserWarning)
            
        fk = fmin*2**(k/bins)
        tempKernelBin = (winFct/Nk) * np.exp(2*np.pi*1j*fk*np.arange(Nk)/fs)
        atomOffset = first_center - np.ceil(Nk/2)

        for i in range(winNr):
            shift = int(atomOffset + (i * atomHOP))

            tempKernel[:, shift: Nk+shift] = tempKernelBin

            atomInd += 1
            specKernel= np.fft.fft(tempKernel)
            specKernel[abs(specKernel)<=thresh] = 0 
            sparKernel = np.append(sparKernel, specKernel, axis=0)
            tempKernel = np.zeros((1, FFTLen), dtype=complex) # reset window   


    sparKernel = (sparKernel.T/FFTLen)[:,1:]

    # Normalize the magnitudes of the atoms 
    wx1=np.argmax(np.abs(sparKernel)[:,0])
    wx2=np.argmax(np.abs(sparKernel)[:,-1])
    wK=sparKernel[wx1: wx2+1,:]

    wK = np.diag(np.dot(wK, wK.conj().T))
    wK = wK[int(round_half_up(1/q)): -int(round_half_up(1/q))-2]
    weight = 1./np.mean(np.abs(wK))
    weight = weight * (fftHOP/FFTLen)
    weight = np.sqrt(weight) # sqrt because the same weight is applied in icqt again 
    sparKernel = weight*sparKernel

    return {'fKernel': sparKernel, 'fftLEN':FFTLen,'fftHOP':fftHOP,'fftOverlap':fftOLP,'perfRast':perfRast,
     'bins':bins,'firstcenter':first_center,'atomHOP':atomHOP,'atomNr':winNr,'Nk_max':Nk_max,'Q':Q,'fmin':fmin }
Example #47
0
	def get_data(self):
		"""Get spectrogram data from the tuner.  Will return width number of
		values which are the intensities of each frequency bucket (i.e. FFT of
		radio samples).
		"""
		# Get width number of raw samples so the number of frequency bins is
		# the same as the display width.  Add two because there will be mean/DC
		# values in the results which are ignored. Increase by 1/self.zoom_fac if needed


		if self.zoom_fac < (self.sdr.sample_rate/1000000):
			zoom = int(self.width*((self.sdr.sample_rate/1000000)/self.zoom_fac))
		else:
			zoom = self.width
			self.zoom_fac = self.get_sample_rate()

                # Read the full array in case we want to write it to a file
		rawsamples = self.sdr.read_samples(freqshow.SDR_SAMPLE_SIZE)

                # Write the data if requested
		if self.record_iq == True:
                    # do something

		if zoom < freqshow.SDR_SAMPLE_SIZE:
			freqbins = rawsamples[0:zoom+2]
		else:
			zoom = self.width
			self.zoom_fac = self.get_sample_rate()
			freqbins = rawsamples[0:zoom+2]


		# Apply a window function to the sample to remove power in sample sidebands before the fft.

		if self.filter == 'kaiser':
			window = signal.kaiser(freqshow.SDR_SAMPLE_SIZE, self.kaiser_beta, False,)[0:zoom+2]  # for every bin there is a window the same exact size as the read samples.
		elif self.filter == 'boxcar':
			window = signal.boxcar(freqshow.SDR_SAMPLE_SIZE, False,)[0:zoom+2]
                elif self.filter == 'hann':
                        window = signal.hann(freqshow.SDR_SAMPLE_SIZE, False,)[0:zoom+2]
                elif self.filter == 'hamming':
                        window = signal.hamming(freqshow.SDR_SAMPLE_SIZE, False,)[0:zoom+2]
                elif self.filter == 'blackman':
                        window = signal.blackman(freqshow.SDR_SAMPLE_SIZE, False,)[0:zoom+2]
                elif self.filter == 'blackmanharris':
                        window = signal.blackmanharris(freqshow.SDR_SAMPLE_SIZE, False,)[0:zoom+2]
                elif self.filter == 'bartlett':
                        window = signal.bartlett(freqshow.SDR_SAMPLE_SIZE, False,)[0:zoom+2]
                elif self.filter == 'barthann':
                        window = signal.barthann(freqshow.SDR_SAMPLE_SIZE, False,)[0:zoom+2]
                elif self.filter == 'nuttall':
                        window = signal.nuttall(freqshow.SDR_SAMPLE_SIZE, False,)[0:zoom+2]
		else:
			window = 1

		samples = freqbins * window

		# Run an FFT and take the absolute value to get frequency magnitudes.
		freqs = np.absolute(fft(samples))

		# Ignore the mean/DC values at the ends.
		freqs = freqs[1:-1]

                # Reverse the order of the freqs array if swaping I and Q
		if self.swap_iq == True:
                	freqs = freqs[::-1]

		# Shift FFT result positions to put center frequency in center.
		freqs = np.fft.fftshift(freqs)

               	# Truncate the freqs array to the width of the screen if neccesary.
                if freqs.size > self.width:

                	freq_step = self.get_freq_step()   # Get the frequency step in Hz between pixels.
                	shiftsweep = int(self.get_lo_offset()*1000000/freq_step) # LO offset in pixels.
                	extra_samples = int((freqs.size - self.width)/2)  # The excess samples either side of the display width in pixels.

                	if extra_samples > abs(shiftsweep): # check if there is room to shift the array by the LO offset.

                        	if self.get_swap_iq() == True:
                                	lextra = extra_samples + shiftsweep
                        	elif self.get_swap_iq() == False:
                                	lextra = extra_samples - shiftsweep
                	else:
                        	lextra = extra_samples

			rextra = freqs.size - (lextra + self.width)
			freqs = freqs[lextra:-rextra]

		# Convert to decibels.
		freqs = 20.0*np.log10(freqs)

		# Get signal strength of the center frequency.

#		for i in range ( 1, 11):
#			self.sig_strength = (self.get_sig_strength() + freqs[((zoom+2)/2)+i-5])
#		self.sig_strength = self.get_sig_strength()/10

		# Update model's min and max intensities when auto scaling each value.
		if self.min_auto_scale:
			min_intensity = np.min(freqs)
			self.min_intensity = min_intensity if self.min_intensity is None \
				else min(min_intensity, self.min_intensity)
		if self.max_auto_scale:
			max_intensity = np.max(freqs)
			self.max_intensity = max_intensity if self.max_intensity is None \
				else max(max_intensity, self.max_intensity)
		# Update intensity range (length between min and max intensity).
		self.range = self.max_intensity - self.min_intensity

		# Return frequency intensities.
		return freqs
Example #48
0
def blackman_harris_taper(frequency_range):
    window = signal.blackmanharris(len(frequency_range))
    return window
Example #49
0
def sineModelMultiRes(x, fs, w_seq, N_seq, t, B_seq):
    """
    Analysis/synthesis of a sound using the sinusoidal model, without sine tracking
    using multi-resolution approach.
    x: input array sound, fs: sample rate
    w: sequence of three analysis windows
    N: sequence of three sizes of complex spectrum
    t: threshold in negative dB
    B: sequence of three frequency bands, represented as (min Hz, max Hz) tuples
    returns y: output array sound
    """

    assert len(w_seq) == len(
        N_seq), "w_seq and N_seq must be sequences of the same size"
    assert len(w_seq) == len(
        B_seq), "w_seq and B_seq must be sequences of the same size"
    k = len(w_seq)

    # Each analysis frame should be the same length as the largest window
    # but each hop should be the same length as the smallest window
    min_window_size = min([item.size for item in w_seq])
    max_window_size = max([item.size for item in w_seq])
    logger.debug("min_window_size {}".format(min_window_size))
    logger.debug("max_window_size {}".format(max_window_size))

    hM1 = int(math.floor(min_window_size + 1) /
              2)  # half analysis window size by rounding
    hM2 = int(math.floor(min_window_size /
                         2))  # half analysis window size by floor

    hM1_max = int(math.floor(max_window_size + 1) / 2)
    hM2_max = int(math.floor(max_window_size / 2))

    max_N = max(N_seq)

    Ns = 512  # FFT size for synthesis (even)
    H = Ns / 4  # Hop size used for analysis and synthesis
    hNs = Ns / 2  # half of synthesis FFT size
    pin = max(hNs, hM1)  # init sound pointer in middle of anal window
    pend = x.size - pin  # last sample to start a frame
    yw = np.zeros(Ns)  # initialize output sound frame
    y = np.zeros(x.size)  # initialize output array
    sw = np.zeros(Ns)  # initialize synthesis window
    ow = triang(2 * H)  # triangular window
    sw[hNs - H:hNs + H] = ow  # add triangular window
    bh = blackmanharris(Ns)  # blackmanharris window
    bh = bh / sum(bh)  # normalized blackmanharris window
    sw[hNs - H:hNs +
       H] = sw[hNs - H:hNs + H] / bh[hNs - H:hNs +
                                     H]  # normalized synthesis window

    for i in range(len(w_seq)):
        w_seq[i] = w_seq[i] / sum(w_seq[i])  # normalize analysis windows

    logger.debug("Hop size {}".format(H))

    while pin < pend:  # while input sound pointer is within sound
        #logger.debug("pin {}".format(pin))

        # -----analysis-----
        iplocs = [None] * k
        ipmags = [None] * k
        ipphases = [None] * k
        ipfreqs = [None] * k

        # The frame of audio to analyse must be as wide as the largest window
        x1 = get_frame(x, pin, max_window_size)

        # For each band perform analysis with specified FFT size and window.
        for i, (w, N) in enumerate(zip(w_seq, N_seq)):
            iplocs[i], ipmags[i], ipphases[i], ipfreqs[i] = analysis(
                x1, fs, w, N, t)

        # For each band, pick detected frequencies inside the band. Ignore detected frequencies outside band.
        # Aggregate the detected frequencies (and associated magnitude, phase) into a single set of values.
        final_ipmag = np.array([])
        final_ipphase = np.array([])
        final_ipfreq = np.array([])
        for ipmag, ipphase, ipfreq, (freq_min,
                                     freq_max) in zip(ipmags, ipphases,
                                                      ipfreqs, B_seq):
            for pmag, pphase, pfreq in zip(ipmag, ipphase, ipfreq):
                if freq_min <= pfreq < freq_max:
                    final_ipmag = np.append(final_ipmag, pmag)
                    final_ipphase = np.append(final_ipphase, pphase)
                    final_ipfreq = np.append(final_ipfreq, pfreq)
                    #logger.debug("Add {} Hz from range ({}, {})".format(pfreq, freq_min, freq_max))

        # -----synthesis-----
        Y = UF.genSpecSines(final_ipfreq, final_ipmag, final_ipphase, Ns,
                            fs)  # generate sines in the spectrum
        fftbuffer = np.real(ifft(Y))  # compute inverse FFT
        yw[:hNs - 1] = fftbuffer[hNs + 1:]  # undo zero-phase window
        yw[hNs - 1:] = fftbuffer[:hNs + 1]
        y[pin - hNs:pin +
          hNs] += sw * yw  # overlap-add and apply a synthesis window
        pin += H
    return y
Example #50
0
    def run(self, tf, dt, c1, c2):
        np.random.seed(62)
        """ Run a simulation """
        n, m, k = self.n, self.m, self.k

        # Total simulation time
        simTime = int(tf / dt)

        # Returns the three synaptic connections kernels
        W12, W21, W22, delays = self.build_kernels()

        # Compute delays by dividing distances by axonal velocity
        delays12 = np.floor(delays[0] / c2)
        delays21 = np.floor(delays[1] / c1)
        delays22 = np.floor(delays[2] / c2)
        maxDelay = int(
            max(delays12[0].max(), delays21[0].max(), delays22[0].max()))

        # Set the initial conditions and the history
        self.initial_conditions(simTime)

        # Initialize the cortical and striatal inputs
        Cx = 0.5
        Str = 0.4

        # Presynaptic activities
        pre12, pre21, pre22 = np.empty((m, )), np.empty((m, )), np.empty((m, ))

        # Simulation
        for i in range(maxDelay, simTime):
            # Take into account the history of rate for each neuron according
            # to its axonal delay
            for idxi, ii in enumerate(range(m)):
                mysum = 0.0
                for jj in range(k, n):
                    mysum += (W12[ii, jj] *
                              self.X2[i - delays12[ii, jj], jj]) * self.dx
                pre12[idxi] = mysum

            for idxi, ii in enumerate(range(k, n)):
                mysum = 0.0
                for jj in range(0, m):
                    mysum += (W21[ii, jj] *
                              self.X1[i - delays21[ii, jj], jj]) * self.dx
                pre21[idxi] = mysum

            for idxi, ii in enumerate(range(k, n)):
                mysum = 0.0
                for jj in range(k, n):
                    mysum += (W22[ii, jj] *
                              self.X2[i - delays22[ii, jj], jj]) * self.dx
                pre22[idxi] = mysum

            # Forward Euler step
            self.X1[i, :m] = (
                self.X1[i - 1, :m] +
                (-self.X1[i - 1, :m] + self.S1(-pre12 + Cx)) * dt / self.tau1)
            self.X2[i, k:] = (
                self.X2[i - 1, k:] +
                (-self.X2[i - 1, k:] + self.S2(pre21 - pre22 - Str)) * dt /
                self.tau2)
        dx = 1.0 / float(m)
        fr = self.X1.sum(axis=1) * dx / 1.0

        signal = detrend(fr)
        windowed = signal * blackmanharris(len(signal))
        f = rfft(windowed)
        i = np.argmax(np.abs(f))
        # true_i = parabolic(np.log(np.abs(f)), i)[0]
        return i
Example #51
0
def tapering_window(tseries, method="Hanning"):
    """
    Returns Tapered 1D time series.
   Input:
        1) tseries : 1D variable containing time series data.
        2) method  : Use any one of the teppering window given below.
                    "Hanning" (default)
                    "Hamming"
                    "Boxcar"
                    "Tukey"
                    "Blackman-Harris"
                    "Kaiser".
    Output:
    1) tseries_tapered    : Time series after applaying tapering window

    Example:
        tapering_window(time_series)
        tapering_window(time_series,"Tukey")
    """
    length = len(tseries)
    if method == "Hanning":
        # The Hanning window is a taper formed by using a weighted cosine.
        # w(n)=  0.5-0.5*cos(2*pi*n/(M-1)))
        #  with      0<=M<=1
        wind_hanning = np.hanning(length)
        tseries_tapered = tseries * wind_hanning
        print("Hanning window is applied.....")
    elif method == "Hamming":
        # The Hanning window is a taper formed by using a weighted cosine.
        # w(n)=  0.54-0.46*cos(2*pi*n/(M-1)))
        #  with      0<=M<=1
        wind_hamming = np.hamming(length)
        tseries_tapered = tseries * wind_hamming
        print("Hamming window is applied.....")
    elif method == "Boxcar":
        wind_boxcar = signal.boxcar(length)
        tseries_tapered = tseries * wind_boxcar
        print("Boxcar window is applied.....")
    elif method == "Tukey":
        # Also called "Planck-taper" window is a bump function
        wind_tukey = signal.tukey(length)
        tseries_tapered = tseries * wind_tukey
        print("Tukey window is applied.....")
    elif method == "Blackman-Harris":
        # A generalization of the Hamming family
        # w(n)=a0-a1cos(2*pi*n/N)+a2cos(4*pi*n/N)-a3cos(6*pi*n/N)
        wind_buckman = signal.blackmanharris(length)
        tseries_tapered = tseries * wind_buckman
        print("Blackman-Harris window is applied.....")
    elif method == "Kaiser":
        # The Kaiser window is a taper formed by using a Bessel function.
        # w(n)=I0(beta*sqrt(1=(4*n^2/(M-1)^2))/(I0*beta)
        # with
        #   -(M-1)/2<=n<=(M-1)/2
        # The Kaiser can approximate many other windows by varying
        # the beta parameter.
        beta = 14.0
        wind_kaiser = np.kaiser(length, beta)
        tseries_tapered = tseries * wind_kaiser
        print("kaiser window is applied.....")
    return tseries_tapered
Example #52
0
def sine_model(s,a_win,overlap_factor,N_fft_a,N_fft_s,thres,robot):

#   Window size (analysis)
    N_a = np.size(a_win)

#   Window size (synthesis). We keep N_fft_synthesis and N_s identical, since
#   0-padding will not add any relevant information
    N_s = N_fft_s
    mid_fft_a = int((N_fft_a+1)/2)
    
#   Normalize analysis window
    a_win = a_win/np.sum(a_win)    

#   Hop size
    H = int(round(N_a/overlap_factor))
       
#   Total number of signal points
    N_pts = np.size(s,0)
    
#   Initialize output
    y = np.zeros(N_pts)
    
#   Build corrected Blackman-Harris window (synthesis)    
    s_win = np.zeros(N_fft_s)
    t_win = sig.triang((2*H)-1)

#   Add triangular window at the center    
    s_win[(N_s/2)+1-H+1:(N_s/2)+H+1] = t_win

    b_win = sig.blackmanharris(N_s)
    b_win = b_win/np.sum(b_win)    
    
    s_win[(N_s/2)+1-H+1:(N_s/2)+H+1] = s_win[(N_s/2)+1-H+1:(N_s/2)+H+1]/b_win[(N_s/2)+1-H+1:(N_s/2)+H+1]
        
#   Initialize the reading pointer
    p_in = int(max(0.5*(N_a-1),(0.5*N_s)-1))
    
#   Initialize the upper limit of the pointer
    p_end = N_pts-1-int(max(0.5*N_s,0.5*(N_a-1)))
    
#   Debug variable    
    k = 0

    while p_in < p_end:

#       Fill the buffer
        s_w = s[p_in-int(0.5*(N_a-1)):p_in+int(0.5*(N_a-1))+1]
        
#       Apply analysis window
        s_w = s_w*a_win         

#       Zero phase correction and 0-padding
        s_temp = np.zeros(N_fft_a)
        s_temp[0:((N_a-1)/2)] = s_w[((N_a+1)/2):]
        s_temp[N_fft_a-((N_a+1)/2):] = s_w[:((N_a+1)/2)]
        
#       Compute FFT     
        X = np.fft.fft(s_temp,N_fft_a)
        mod_X = 20*np.log10(np.abs(X[:mid_fft_a+1]))
        arg_X = np.unwrap(np.angle(X[:mid_fft_a+1]))
        
        lower_bound     = mod_X[1:mid_fft_a-1] > mod_X[0:mid_fft_a-2]
        max_estimation  = mod_X[1:mid_fft_a-1] > thres
        upper_bound     = mod_X[1:mid_fft_a-1] > mod_X[2:mid_fft_a]

#       Search for the indexes where the three conditions are satisfied
        peak_loc = np.where(lower_bound & max_estimation & upper_bound)        
        peak_loc = peak_loc[0] + 1                     
        
#       Interpolated values
        peak_mag = quadratic_max(mod_X[peak_loc-1],mod_X[peak_loc],mod_X[peak_loc+1])
        peak_loc_interp = quadratic_argmax(peak_loc,mod_X[peak_loc-1],mod_X[peak_loc],mod_X[peak_loc+1])
        peak_phase = np.interp(peak_loc_interp,np.array(range(np.size(arg_X))),arg_X)
#       Fun ...(0 phase reconstruction, aka robotic voice)
        
        if robot==1:        
            peak_phase = np.zeros(np.size(arg_X))
        
#       Synthesize signal and remove zero-phase correction
        Y = sine_synthesis(peak_loc_interp*N_fft_s/N_fft_a,peak_mag,peak_phase,N_fft_s,N_fft_s)
        y_w = np.fft.fftshift(np.real(np.fft.ifft(Y)))
        


#       -----------------------------------------------------------------------
#       Section for debugging purposes
        if (k == 9): 
            plt.plot(s_w,'b')
            plt.title('Input signal versus output signal (time domain)')            
            plt.hold(True)
            plt.plot(y_w,'r')
            plt.grid()
            
            plt.figure()
            plt.plot(20*np.log10(X),'b')
            plt.title('Input signal versus output signal (frequency domain)')
            plt.hold(True)
            plt.plot(20*np.log10(Y),'r')
            plt.grid()              
            
        k += 1            
#       -----------------------------------------------------------------------

#       Apply synthesis window           
        y_w = y_w*s_win

#       Overlap-add                
        y[p_in-int(0.5*N_s)+1:p_in+int(0.5*N_s)+1] += y_w

#       Jump to the next position
        p_in += H
        
    return y
# =============================================================================    
Example #53
0
    def iq_file(self):
        


        for path in self.chooseFileDlg.GetPaths():
            iq_file = open(path,'rb').read()
            iq_gps_centr = []
            for line in iq_file:
                line = ord(line)
                iq_gps_centr.append(line)
            

            wave1_list = []
                    
            wave1_list.append('Start')
            wave1_list.append(iq_gps_centr[1])
            
            longtitude_int = iq_gps_centr[2]
            longtitude_frac_high = iq_gps_centr[3] << 8
            longtitude_frac_low = iq_gps_centr[4]
            longtitude_frac = longtitude_frac_high + longtitude_frac_low
            longtitude = longtitude_int + longtitude_frac / (10 ** len(str(longtitude_frac))) 
            longtitude = float('%.6f' % longtitude)
            wave1_list.append(longtitude)
            
            wave1_list.append(iq_gps_centr[5] >> 7)
            
            latitude_int = iq_gps_centr[5] & 0x7F
            latitude_frac_high = iq_gps_centr[6] << 8
            latitude_frac_low = iq_gps_centr[7]
            latitude_frac = latitude_frac_high + latitude_frac_low
            latitude = latitude_int + latitude_frac / (10 ** len(str(latitude_frac)))
            latitude = float('%.6f' % latitude)
            wave1_list.append(latitude)
            
            height_flag = iq_gps_centr[8] >> 7
            height_high = (iq_gps_centr[8] & 0x7F) << 8
            height_low = iq_gps_centr[9]
            height = height_high + height_low
            if height_flag == 1 :
                height = - height
            wave1_list.append(height)
            
            
            
            freq_centr_int_h = iq_gps_centr[10] << 6
            freq_centr_int_l = iq_gps_centr[11] & 0x3F
            freq_centr_frac_h = (iq_gps_centr[11] >> 6)<< 8
            freq_centr_frac_l = iq_gps_centr[12]
            freq_centr_int = freq_centr_int_h + freq_centr_int_l
            freq_centr_frac = freq_centr_frac_h + freq_centr_frac_l
            freq_centr = freq_centr_int + freq_centr_frac / (10 ** len(str(freq_centr_frac)))
            freq_centr = float('%.4f' % freq_centr)

            wave1_list.append(freq_centr)
            
            bandwidth = iq_gps_centr[13] >> 4
            if (bandwidth == 1) :
                bandwidth_rate = 5
                wave1_list.append(5)
                wave1_list.append(5)
            elif (bandwidth == 2):
                bandwidth_rate = 2.5
                wave1_list.append(2.5)
                wave1_list.append(2.5)
            elif (bandwidth == 3):
                bandwidth_rate = 1.25
                wave1_list.append(1.25)
                wave1_list.append(1.25)
            elif (bandwidth == 4):
                bandwidth_rate = 0.625
                wave1_list.append(0.625)
                wave1_list.append(0.625)
            elif (bandwidth == 5):
                bandwidth_rate = 0.125
                wave1_list.append(0.125)
                wave1_list.append(0.125)
            
            wave1_list.append(iq_gps_centr[14])
            wave1_list.append('')
            
            # print wave1_list
            # print len(wave1_list)
            a = path.index('IQ')
            filename = path[(a + 3) : -3]
            
            
            wave1_file = open(r'./LocalData/Wave2/' + filename  + '.wave2','w')
            for i in range(len(wave1_list)):
                wave1_file.write(str(wave1_list[i]) + '\n')
            wave1_file.close() 
            
          
            N = iq_gps_centr[14]
            
            for j in range(N):
                IData = []
                QData = []
                for i in range(2000):
                    HighI1 = ((iq_gps_centr[6001 * (j + 1) - 5985 + i * 3]) >> 4) << 8
                    LowI1 = iq_gps_centr[6001 * (j + 1) - 5984 + i * 3]
                    if (HighI1 >= 2048):
                        I1 = -(2 ** 12 - HighI1 - LowI1)
                    else :
                        I1 = (HighI1 + LowI1)
                    IData.append(I1)
            
                    HighQ1 = ((iq_gps_centr[6001 * (j + 1) - 5985 + i * 3]) & 0x0F) << 8
                    LowQ1 = iq_gps_centr[6001 * (j + 1) - 5983 + i * 3]
                    if (HighQ1 >= 2048):
                        Q1 = -(2 ** 12 - HighQ1 - LowQ1)
                    else :
                        Q1 = (HighQ1 + LowQ1)
                    QData.append(Q1)

            
                IQData = []
                for i in range(2000):
                    data1 = complex(IData[i]/2047,-QData[i]/2047)
                    IQData.append(data1)
                for i in range(48):
                    IQData.append(0)
                    
                n = 2048 
                y = IQData[:]
                w = signal.blackmanharris(n) 
                y = y*w
                y_fft = np.fft.fft(y)
                y_fftshift = np.fft.fftshift(y_fft)
                yk = (1 / sqrt(sum(abs(w * w))/ 2048)) * y_fftshift 
                pk = [] ##### pk:相对平均功率谱
                fk = [] ##### fk:对应的实际频率值
                angle = [] #### angle:对应的相位谱
        
                
                for k in range(-1024,1024):
                    fk.append(freq_centr + k * bandwidth_rate / 2048)
                    
                
                for i in range(len(yk)):
                    pk.append(-57.206 + 20 * log10(abs(yk[i])))
                    
                    if (yk[i].real == 0)and(yk[i].imag > 0) :
                        angle.append(90)
                    elif (yk[i].real == 0)and(yk[i].imag < 0) :
                        angle.append(-90)
                    elif (yk[i].real == 0)and(yk[i].imag == 0) :
                        angle.append(0)
                    else :
                        angle.append(57.3 * atan(yk[i].imag / yk[i].real))
                    angle[i] = '%.2f' % angle[i]
                
                if self.am_fm_mode.GetSelection() == 0 : ###am
                    data = self.am_mode(IData, QData)
                elif(self.am_fm_mode.GetSelection() == 1 ): ###fm
                    data = self.fm_mode(IData, QData)  #### data:解调后对应的值
                
                

                if self.spec_mode.GetValue(): 
                    if(self.parent.IQ2SpecFrame_test == None):    
                        self.parent.IQ2SpecFrame_test = DrawPanel(self.parent,fk,pk,angle,data,self.chooseFileDlg.GetPaths(),self.am_fm_mode.GetSelection(),self.choosefilemode)
                        self.parent.IQ2SpecFrame_test.Activate()
                    
                        
                    self.parent.IQ2SpecFrame_test.spec.set_txt(filename, longtitude, latitude, height, freq_centr, bandwidth_rate)
#                     self.parent.IQ2SpecFrame_test.spec.setLbl_draw(fk,pk)
                    self.parent.IQ2SpecFrame_test.spec.filePath(self.chooseFileDlg.GetPaths())
                    self.parent.IQ2SpecFrame_test.wave.filePath(self.chooseFileDlg.GetPaths())
                    self.parent.IQ2SpecFrame_test.wave.am_fm_mode_refresh(self.am_fm_mode.GetSelection())

                    
                if self.water_mode.GetValue():
                    if(self.parent.WaterFrame_pl == None):
                        self.parent.WaterFrame_pl = IQ2_Water(self.parent,fk,pk,self.chooseFileDlg.GetPaths(),self.choosefilemode)
                        self.parent.WaterFrame_pl.Activate()
                    self.parent.WaterFrame_pl.set_txt(filename, longtitude, latitude, height, freq_centr, bandwidth_rate)
                    self.parent.WaterFrame_pl.fileDraw(self.chooseFileDlg.GetPaths())
                    self.parent.WaterFrame_pl.setLbl_draw(fk,pk)
            
                
                wave1_file = open(r'./LocalData/Wave2/' + filename + '.wave2','a')
                for i in range(2000):
                    wave1_file.write(str('%.4f' % data[i]) + '\n')
                wave1_file.close() 
            
             
            wave1_file = open(r'./LocalData/Wave2/' + filename + '.wave2','a')
            wave1_file.write('end')
            wave1_file.close()
Example #54
0
				Thd(x, fs)
				ThdN(x, fs)
			
			elif c == 'w':
				sRate = 44100.0
				t = np.arange(0, 2.0, 1/sRate)
				samples = np.sin(2*np.pi*440.0*t)
				writeWaveFile('test1.wav', samples, int(sRate))

				sampleRate = 44100
				samples = KarplusStrong(1*sampleRate, sampleRate, 391)
				writeWaveFile('test2.wav', samples, int(sampleRate))


				samples -= np.mean(samples)
				windowed = samples * signal.blackmanharris(len(samples))

				f = np.fft.rfft(windowed)
				i = np.argmax(np.abs(f))
				ThdValue = rms_harmony(f, i) / np.abs(f[i])

				print('freq = %f and thd = %f' %(i, ThdValue))

				#Thd(samples, sampleRate)
				#ThdN(samples, sampleRate)

				plt.plot(np.abs(f))
				#plt.legend(['test1', 'test2'], loc='best')
				plt.grid()
				plt.show()
			
Example #55
0
hold(True)

from scipy import signal as si

b = si.kaiser(N, 3)
gfiltpak.gfreqz(b,
                a,
                color='m',
                magfig=mag_p,
                angfig=ang_p,
                label="kaiser",
                threedb=True)

hold(True)
b = si.blackmanharris(N)
gfiltpak.gfreqz(b, a, color='g', magfig=mag_p, angfig=ang_p, ylimmag=[-500, 0])

hold(True)
b = si.blackman(N)
gfiltpak.gfreqz(b, a, color='y', magfig=mag_p, angfig=ang_p)

# Show
mag_p.legend(('r', 'k', '3dB', 'b-h', 'b'), numpoints=4, fancybox=True)
ang_p.legend(('r', 'k', 'b-h', 'b'), numpoints=2, fancybox=True)

##############################################################
## IIR filter
c = 1
b = [1]
root_r = 0.10
Example #56
0
 def test_blackman_harris(self):
     size = randint(0, 1000)
     generated = windowing.blackman_harris(size)
     reference = signal.blackmanharris(size)
     for g, r in zip(generated, reference):
         self.assertAlmostEqual(g, r)
Example #57
0
    [coords_xy, coords_xy, coords_z], fg_lightcone)
highres_lightcone_fg = f_lc(
    np.array([xx.flatten(), yy.flatten(),
              zz.flatten()]).T).reshape(Ngrid, Ngrid, len(new_coords_z))

# interpolate the eor across frequency to make sure we have the same dimension as foregrounds
f_lc_fg = scipy.interpolate.RegularGridInterpolator(
    [coords_xy, coords_xy, coords_z], lightcone_eor)
highres_lightcone_eor = f_lc(
    np.array([xx.flatten(), yy.flatten(),
              zz.flatten()]).T).reshape(Ngrid, Ngrid, len(new_coords_z))

# Find the PS of foregrounds plus eor
P_both, kperp, kparal = get_power(
    (highres_lightcone_fg + highres_lightcone_eor) *
    signal.blackmanharris(len(new_coords_z)), [500, 500, Lz_Mpc],
    bins=50,
    res_ndim=2,
    bin_ave=False,
    get_variance=False)

# Find the PS of foregrounds only
P_fg = get_power(highres_lightcone_fg *
                 signal.blackmanharris(len(new_coords_z)), [500, 500, Lz_Mpc],
                 bins=50,
                 res_ndim=2,
                 bin_ave=False,
                 get_variance=False)[0]

# Find the PS of eor only
P_eor = get_power(highres_lightcone_eor *
Example #58
0
def sineModel_MultiRes(x, fs, w1, w2, w3, N1, N2, N3, t, B1, B2, B3):
    """
    Week 10, Project:  A multi-resolution sinusoidal model
    Analysis/synthesis of a sound using the sinusoidal model, without sine tracking
    Using Multi-resolution sine model
    x: input array sound, w: analysis window, N: size of complex spectrum, t: threshold in negative dB
    N1, N2, N3: size of the 3 complex spectrum
    B1, B2, B3: Frequency band edges (Upper limits) of the 3 frequency bands
    [0 - B1] is the first frequency band
    [B1 - B2] is the second frequency band
    [B2 - B3] is the third frequency band

    returns y: output array sound
    """

    hM1_1 = int(math.floor(
        (w1.size + 1) / 2))  # half analysis for 1st window size by rounding
    hM1_2 = int(math.floor(w1.size /
                           2))  # half analysis for 1st  window size by floor
    hM2_1 = int(math.floor(
        (w2.size + 1) / 2))  # half analysis for 2nd window size by rounding
    hM2_2 = int(math.floor(w2.size /
                           2))  #half analysis for 2nd  window size by floor
    hM3_1 = int(math.floor(
        (w3.size + 1) / 2))  # half analysis for 3rd window size by rounding
    hM3_2 = int(math.floor(w3.size /
                           2))  #half analysis for 3rd  window size by floor
    Ns = 512  # FFT size for synthesis (even)
    H = Ns // 4  # Hop size used for analysis and synthesis
    hNs = Ns // 2  # half of synthesis FFT size
    pin = max(hNs, hM1_1, hM2_1,
              hM3_1)  # init sound pointer in middle of biggest anal window
    pend = x.size - pin  # last sample to start a frame
    fftbuffer = np.zeros(max(N1, N2, N3))  # initialize buffer for FFT
    yw = np.zeros(Ns)  # initialize output sound frame
    y = np.zeros(x.size)  # initialize output array
    w_1 = w1 / sum(w1)  # normalize the 1st analysis window
    w_2 = w2 / sum(w2)  # normalize the 2nd analysis window
    w_3 = w3 / sum(w3)  # normalize the 3rd analysis window
    sw = np.zeros(Ns)  # initialize synthesis window
    ow = triang(2 * H)  # triangular window
    sw[hNs - H:hNs + H] = ow  # add triangular window
    bh = blackmanharris(Ns)  # blackmanharris window
    bh = bh / sum(bh)  # normalized blackmanharris window
    sw[hNs - H:hNs +
       H] = sw[hNs - H:hNs + H] / bh[hNs - H:hNs +
                                     H]  # normalized synthesis window

    while pin < pend:  # while input sound pointer is within sound
        # -----analysis-----
        #Selecting THREE FRAMES for the same CENTRAL PIN POINT, but FOR DIFFERENT LENGTHS
        x1 = x[pin - hM1_1:pin + hM1_2]  # select frame for window size 1
        x2 = x[pin - hM2_1:pin + hM2_2]  # select frame for window size2
        x3 = x[pin - hM3_1:pin + hM3_2]  # select frame for window size3
        mX1, pX1 = DFT.dftAnal(x1, w1, N1)  # compute dft for 1st frame
        mX2, pX2 = DFT.dftAnal(x2, w2, N2)  # compute dft for 2nd frame
        mX3, pX3 = DFT.dftAnal(x3, w3, N3)  # compute dft for 3rd frame
        ploc1 = UF.peakDetection(mX1,
                                 t)  # detect locations of peaks for 1st frame
        ploc2 = UF.peakDetection(mX2,
                                 t)  # detect locations of peaks for 2nd frame
        ploc3 = UF.peakDetection(mX3,
                                 t)  # detect locations of peaks for 3rd frame
        iploc1, ipmag1, ipphase1 = UF.peakInterp(
            mX1, pX1,
            ploc1)  # refine peak values by interpolation for the 1st frame
        iploc2, ipmag2, ipphase2 = UF.peakInterp(
            mX2, pX2,
            ploc2)  # refine peak values by interpolation for the 2nd frame
        iploc3, ipmag3, ipphase3 = UF.peakInterp(
            mX3, pX3,
            ploc3)  # refine peak values by interpolation for the 3rd frame
        ipfreq1 = fs * iploc1 / float(
            N1)  # convert peak locations of 1st frame to Hertz
        ipfreq2 = fs * iploc2 / float(
            N2)  # convert peak locations of 2nd frame to Hertz
        ipfreq3 = fs * iploc3 / float(
            N3)  # convert peak locations of 3rd frame to Hertz

        # Looking for indices of peak frequencies
        # in each band, for each window calculation
        indice_1 = np.logical_and(ipfreq1 > 0, ipfreq1 < B1)
        indice_2 = np.logical_and(ipfreq2 >= B1, ipfreq2 < B2)
        indice_3 = np.logical_and(ipfreq3 >= B2, ipfreq3 < B3)

        # Getting peaks which fall in selected frequency bands
        ipfreq = np.concatenate(
            (ipfreq1[indice_1], ipfreq2[indice_2], ipfreq3[indice_3]))
        ipmag = np.concatenate(
            (ipmag1[indice_1], ipmag2[indice_2], ipmag3[indice_3]))
        ipphase = np.concatenate(
            (ipphase1[indice_1], ipphase2[indice_2], ipphase3[indice_3]))

        # -----synthesis-----
        Y = UF.genSpecSines(ipfreq, ipmag, ipphase, Ns,
                            fs)  # generate sines in the spectrum
        fftbuffer = np.real(ifft(Y))  # compute inverse FFT
        yw[:hNs - 1] = fftbuffer[hNs + 1:]  # undo zero-phase window
        yw[hNs - 1:] = fftbuffer[:hNs + 1]
        y[pin - hNs:pin +
          hNs] += sw * yw  # overlap-add and apply a synthesis window
        pin += H  # advance sound pointer
    return y
Example #59
0
def harmonicModel(x, fs, w, N, t, nH, minf0, maxf0, f0et):

    #Analysis/synthesis of a sound using the sinusoidal harmonic model
    #x: input sound, fs: sampling rate, w: analysis window,
    #N: FFT size (minimum 512), t: threshold in negative dB,
    #nH: maximum number of harmonics, minf0: minimum f0 frequency in Hz,
    #maxf0: maximim f0 frequency in Hz,
    #f0et: error threshold in the f0 detection (ex: 5),
    #returns y: output array sound

    hN = N / 2  # size of positive spectrum
    hM1 = int(math.floor(
        (w.size + 1) / 2))  # half analysis window size by rounding
    hM2 = int(math.floor(w.size / 2))  # half analysis window size by floor
    x = np.append(
        np.zeros(hM2),
        x)  # add zeros at beginning to center first window at sample 0
    x = np.append(x,
                  np.zeros(hM1))  # add zeros at the end to analyze last sample
    Ns = 512  # FFT size for synthesis (even)
    H = Ns / 4  # Hop size used for analysis and synthesis
    hNs = Ns / 2
    pin = max(hNs, hM1)  # init sound pointer in middle of anal window
    pend = x.size - max(hNs, hM1)  # last sample to start a frame
    fftbuffer = np.zeros(N)  # initialize buffer for FFT
    yh = np.zeros(Ns)  # initialize output sound frame
    y = np.zeros(x.size)  # initialize output array
    w = w / sum(w)  # normalize analysis window
    sw = np.zeros(Ns)  # initialize synthesis window
    ow = triang(2 * H)  # overlapping window
    sw[hNs - H:hNs + H] = ow
    bh = blackmanharris(Ns)  # synthesis window
    bh = bh / sum(bh)  # normalize synthesis window
    sw[hNs - H:hNs +
       H] = sw[hNs - H:hNs + H] / bh[hNs - H:hNs + H]  # window for overlap-add
    hfreqp = []
    f0t = 0
    f0stable = 0
    while pin < pend:
        #-----analysis-----
        x1 = x[pin - hM1:pin + hM2]  # select frame
        mX, pX = DFT.dftAnal(x1, w, N)  # compute dft
        ploc = UF.peakDetection(mX, t)  # detect peak locations
        iploc, ipmag, ipphase = UF.peakInterp(mX, pX,
                                              ploc)  # refine peak values
        ipfreq = fs * iploc / N
        f0t = UF.f0Twm(ipfreq, ipmag, f0et, minf0, maxf0, f0stable)  # find f0
        if ((f0stable==0)&(f0t>0)) \
          or ((f0stable>0)&(np.abs(f0stable-f0t)<f0stable/5.0)):
            f0stable = f0t  # consider a stable f0 if it is close to the previous one
        else:
            f0stable = 0
        hfreq, hmag, hphase = harmonicDetection(ipfreq, ipmag, ipphase, f0t,
                                                nH, hfreqp,
                                                fs)  # find harmonics
        hfreqp = hfreq
        #-----synthesis-----
        Yh = UF.genSpecSines(hfreq, hmag, hphase, Ns,
                             fs)  # generate spec sines
        fftbuffer = np.real(ifft(Yh))  # inverse FFT
        yh[:hNs - 1] = fftbuffer[hNs + 1:]  # undo zero-phase window
        yh[hNs - 1:] = fftbuffer[:hNs + 1]
        y[pin - hNs:pin + hNs] += sw * yh  # overlap-add
        pin += H  # advance sound pointer
    y = np.delete(
        y,
        range(hM2))  # delete half of first window which was added in stftAnal
    y = np.delete(y,
                  range(y.size - hM1,
                        y.size))  # add zeros at the end to analyze last sample
    return y
Example #60
0
def spsModel(x, fs, w, N, t, stocf):
    """
	Analysis/synthesis of a sound using the sinusoidal plus stochastic model
	x: input sound, fs: sampling rate, w: analysis window, 
	N: FFT size (minimum 512), t: threshold in negative dB, 
	stocf: decimation factor of mag spectrum for stochastic analysis
	returns y: output sound, ys: sinusoidal component, yst: stochastic component
	"""

    hN = N // 2  # size of positive spectrum
    hM1 = int(math.floor(
        (w.size + 1) / 2))  # half analysis window size by rounding
    hM2 = int(math.floor(w.size / 2))  # half analysis window size by floor
    Ns = 512  # FFT size for synthesis (even)
    H = Ns // 4  # Hop size used for analysis and synthesis
    hNs = Ns // 2
    pin = max(hNs,
              hM1)  # initialize sound pointer in middle of analysis window
    pend = x.size - max(hNs, hM1)  # last sample to start a frame
    fftbuffer = np.zeros(N)  # initialize buffer for FFT
    ysw = np.zeros(Ns)  # initialize output sound frame
    ystw = np.zeros(Ns)  # initialize output sound frame
    ys = np.zeros(x.size)  # initialize output array
    yst = np.zeros(x.size)  # initialize output array
    w = w / sum(w)  # normalize analysis window
    sw = np.zeros(Ns)
    ow = triang(2 * H)  # overlapping window
    sw[hNs - H:hNs + H] = ow
    bh = blackmanharris(Ns)  # synthesis window
    bh = bh / sum(bh)  # normalize synthesis window
    wr = bh  # window for residual
    sw[hNs - H:hNs + H] = sw[hNs - H:hNs + H] / bh[hNs - H:hNs + H]
    sws = H * hanning(Ns) / 2  # synthesis window for stochastic

    while pin < pend:
        #-----analysis-----
        x1 = x[pin - hM1:pin + hM2]  # select frame
        mX, pX = DFT.dftAnal(x1, w, N)  # compute dft
        ploc = UF.peakDetection(mX, t)  # find peaks
        iploc, ipmag, ipphase = UF.peakInterp(
            mX, pX, ploc
        )  # refine peak values		iploc, ipmag, ipphase = UF.peakInterp(mX, pX, ploc)          # refine peak values
        ipfreq = fs * iploc / float(N)  # convert peak locations to Hertz
        ri = pin - hNs - 1  # input sound pointer for residual analysis
        xw2 = x[ri:ri + Ns] * wr  # window the input sound
        fftbuffer = np.zeros(Ns)  # reset buffer
        fftbuffer[:hNs] = xw2[hNs:]  # zero-phase window in fftbuffer
        fftbuffer[hNs:] = xw2[:hNs]
        X2 = fft(fftbuffer)  # compute FFT for residual analysis

        #-----synthesis-----
        Ys = UF.genSpecSines(ipfreq, ipmag, ipphase, Ns,
                             fs)  # generate spec of sinusoidal component
        Xr = X2 - Ys
        # get the residual complex spectrum
        mXr = 20 * np.log10(abs(Xr[:hNs]))  # magnitude spectrum of residual
        mXrenv = resample(
            np.maximum(-200, mXr),
            mXr.size * stocf)  # decimate the magnitude spectrum and avoid -Inf
        stocEnv = resample(mXrenv, hNs)  # interpolate to original size
        pYst = 2 * np.pi * np.random.rand(hNs)  # generate phase random values
        Yst = np.zeros(Ns, dtype=complex)
        Yst[:hNs] = 10**(stocEnv / 20) * np.exp(
            1j * pYst)  # generate positive freq.
        Yst[hNs + 1:] = 10**(stocEnv[:0:-1] / 20) * np.exp(
            -1j * pYst[:0:-1])  # generate negative freq.

        fftbuffer = np.zeros(Ns)
        fftbuffer = np.real(ifft(Ys))  # inverse FFT of harmonic spectrum
        ysw[:hNs - 1] = fftbuffer[hNs + 1:]  # undo zero-phase window
        ysw[hNs - 1:] = fftbuffer[:hNs + 1]

        fftbuffer = np.zeros(Ns)
        fftbuffer = np.real(ifft(Yst))  # inverse FFT of stochastic spectrum
        ystw[:hNs - 1] = fftbuffer[hNs + 1:]  # undo zero-phase window
        ystw[hNs - 1:] = fftbuffer[:hNs + 1]

        ys[ri:ri + Ns] += sw * ysw  # overlap-add for sines
        yst[ri:ri + Ns] += sws * ystw  # overlap-add for stochastic
        pin += H  # advance sound pointer

    y = ys + yst  # sum of sinusoidal and residual components
    return y, ys, yst