Exemplo n.º 1
0
def phi(entry):
    # Likelihood fonction
    A = MesFonctions.matrice_A(entry[0:size].reshape((NbLigne, NbColonne)), methode="3")
    x_ = (
        floue.reshape(size) - MesFonctions.conv_matrices(A, entry[size:2 * size].reshape((NbLigne, NbColonne)),
                                                         "vecteur",
                                                         "coin"))
    likelihood = np.dot(np.dot(x_, C_noise_inv), x_.transpose())
    # Regularization term
    image_ = entry[0:size]  # /sum(sum(im))
    PSF_ = entry[size:2 * size]  # /sum(sum(PSF))
    if regularization == "spectral":
        fy_ = np.fft(image_)
        y_ = 0
        for i in range(0, size):
            y_ = y_ + i * i * abs(fy_[i]) * abs(fy_[i])
        regularization_im = y_
        fz_ = np.fft(PSF_)
        z_ = 0
        for i in range(0, size):
            z_ = z_ + i * i * abs(fz_[i]) * abs(fz_[i])
        regularization_PSF = z_
    elif regularization == "Tikhonov":
        y_ = sum(image_ * image_)
        regularization_im = math.sqrt(y_)
        z_ = sum(PSF_ * PSF_)
        regularization_PSF = math.sqrt(z_)

    t_ = likelihood + regularization_im + regularization_PSF
    return t_
Exemplo n.º 2
0
	def process2ch(self,inputbuffers,timestamp):
		if not self.update() : return None

		fftsize = self.m_blockSize
		
		audioSamples0 = inputbuffers[0]
		audioSamples1 = inputbuffers[1]

		complexSpectrum0 = fft(self.window*audioSamples0,fftsize)
		complexSpectrum1 = fft(self.window*audioSamples1,fftsize)
		
		magnitudeSpectrum0 = abs(complexSpectrum0)[0:fftsize/2] / (fftsize/2)
		magnitudeSpectrum1 = abs(complexSpectrum1)[0:fftsize/2] / (fftsize/2)
		
		# do the computation
		melSpectrum0 = self.warpSpectrum(magnitudeSpectrum0)
		melCepstrum0 = self.getMFCCs(melSpectrum0,cn=True)
		melSpectrum1 = self.warpSpectrum(magnitudeSpectrum1)
		melCepstrum1 = self.getMFCCs(melSpectrum1,cn=True)
		
		outputs = FeatureSet()
		outputs[0] = Feature(hstack((melCepstrum1[self.cnull:],melCepstrum0[self.cnull:])))
		outputs[1] = Feature(hstack((melSpectrum1,melSpectrum0)))
		
		return outputs
Exemplo n.º 3
0
    def calculate_FROG(self):
        
        self.FROGxmin   = self.t[0]
        self.FROGxmax   = self.t[-1]
        self.FROGdeltax = (self.t[-1]-self.t[0])/self.NT
        self.FROGymin   = self.frequencies[0]
        self.FROGymax   = self.frequencies[-1]
        self.FROGdeltay = (self.frequencies[-1]-self.frequencies[0])/self.NT
        return
#negative delay
        for i in xrange(self.NT/2):
            self.field     =  zeros((self.NT))
            self.field[i:] = (self.ElectricField[:self.NT-i]*self.ElectricField[i:])**2
            self.field_fft = fft(self.field)       
            self.field_fft[:self.NT/2] = zeros((self.NT/2))   #no negative freq
            self.FROG[:,self.NT/2-i] = abs(self.field_fft[self.NT/2:])**2#fftshift(abs(self.field_fft[self.NT/2:])**2)
            
#positive delay
        for i in xrange(self.NT/2):
            self.field     = zeros((self.NT))
            self.field[i:] = (self.ElectricField[i:]*self.ElectricField[:self.NT-i])**2
            self.field_fft = fft(self.field)  
            self.field_fft[:self.NT/2] = zeros((self.NT/2))      #no negative freq
            self.FROG[:,self.NT/2+i] = abs(self.field_fft[self.NT/2:])**2#fftshift(abs(self.field_fft[self.NT/2:])**2)
            
        self.FROG /= ma.max(abs(self.FROG))
Exemplo n.º 4
0
    def calculate_FROG(self):
        
        self.FROGxmin   = self.t[0]
        self.FROGxmax   = self.t[-1]
        self.FROGymin   = self.get_frequencies()[0]
        self.FROGymax   = self.get_frequencies()[-1]
        
        ElectricField = real(self.ElectricField)
        # complex field
        
#negative delay
        for i in xrange(self.NT/2):
            self.field     =  zeros((self.NT))
            self.field[i:] = (ElectricField[:self.NT-i]*ElectricField[i:])**2
            self.field_fft = fft(self.field)       
            self.FROG[:,self.NT/2-i] = fftshift(abs(self.field_fft)**2)
            
#positive delay
        for i in xrange(self.NT/2):
            self.field     = zeros((self.NT))
            self.field[i:] = (ElectricField[i:]*ElectricField[:self.NT-i])**2
            self.field_fft = fft(self.field)  
            self.FROG[:,self.NT/2+i] = fftshift(abs(self.field_fft)**2)
            
        self.FROG /= ma.max(abs(self.FROG))
Exemplo n.º 5
0
    def myFFT(self,x):
        tt,xx,uu = self.Traj(x,U=1,fast=0)
        n,gn=len(tt),len(uu)
        grsU = [TGraph(n,tt,uu[i]) for i in range(5)]         
        ffts = [fft(uu[i]).real for i in range(5)]
        ffts2= [fft(uu[i]).imag for i in range(5)]
        fftUt = [array('d') for i in range(5)]
        fftUt2 = [array('d') for i in range(5)]
        for i in range(5):
            for j in range(n):
                fftUt[i].append(ffts[i][j]**2+ffts2[i][j]**2)
                fftUt2[i].append(ffts[i][j])
        fftUr = [TGraph(n,tt,fftUt[i]) for i in range(5)]         
        fftUi = [TGraph(n,tt,fftUt2[i]) for i in range(5)]         
        c1 = TCanvas()
        c1.Divide(3,2)
        for i in range(5):
            c1.cd(i+1)
            fftUi[i].Draw("APE")
 
        fftsx1 = [fft(xx[i]).real for i in range(3)]
        fftsx2= [fft(xx[i]).imag for i in range(3)]
        fftsxA = [array('d') for i in range(3)]
        for i in range(3):
            for j in range(n):
                fftsxA[i].append(fftsx1[i][j])
        fftxr = [TGraph(n,tt,fftsxA[i]) for i in range(3)]         
        
        c2 = TCanvas()
        c2.Divide(3)
        
        for i in range(3):
            c2.cd(i+1)
            fftxr[i].Draw("APE")
        zwom = input("numbers continue")
Exemplo n.º 6
0
def length_shift(signalin, tscale):
  L = len(signalin)
  # signal blocks for processing and output
  phi  = zeros(N)
  out = zeros(N, dtype=complex)
  sigout = zeros(L/tscale+N)

  # max input amp, window
  amp = max(signalin)
  win = hanning(N)
  p = 0
  pp = 0
  while p < L-(N+H):
    print p, ',', (L-N-H)

    # take the spectra of two consecutive windows
    p1 = int(p)
    spec1 =  fft(win*signalin[p1:p1+N])
    spec2 =  fft(win*signalin[p1+H:p1+N+H])
    # take their phase difference and integrate
    phi += (angle(spec2) - angle(spec1))
    # bring the phase back to between pi and -pi
    for i in phi:
      while i < -pi: i += 2*pi
      while i >= pi: i -= 2*pi
    out.real, out.imag = cos(phi), sin(phi)
    # inverse FFT and overlap-add
    sigout[pp:pp+N] += (win*ifft(abs(spec2)*out)).real
    pp += H
    p += H*tscale
  return array(amp * sigout / max(sigout))
Exemplo n.º 7
0
def fft_sheet(f, t):
    # Transform along y
    fk = fft(f, axis=0)
    # Phase shift (to make periodic in x)
    fk *= exp(1j * S * t * ky * x)
    # Transform along x
    return fft(fk, axis=1)
Exemplo n.º 8
0
def fft_covariance(sample):
    '''
        returns the covariance matrix and index of each item for a dimension-list of sample-lists
        [d0, d1, ...,dd] where d0 is the first dimension containing n samples.
        n.b. numpy 1.7rc1 has numpy.pad to pad array.  currently running 1.6.2 (released version)
        so imported rc1 version.
    '''
        
    A = numpy.array(sample)
    d, n = A.shape
    Q = numpy.ones(1) if(d==2) else numpy.ones((d, d))
    idx = [[1]] if(d==2) else [list([1.] * d) for i in range(d)]
    nm1 = float(n - 1)
    #prep for fft
    A =  (A.transpose() - numpy.mean(A, axis=1)).transpose()
    A = npp.pad(A,(0,len(pad(n))), 'constant', constant_values=(0,0))[:d, : ]
    #2x2return
    if (d == 2):
        corr = ifft(fft(A[0, :]) * np.conjugate(fft(A[1, :])))
        maxcorr = getmax(corr)
        Q[0] =  maxcorr[0] / nm1
        idx[0] = maxcorr[1]
    else:
        for i in range(d):
            for j in range(i, d):
                corr = ifft(fft(A[i, :]) * np.conjugate(fft(A[j, : ])))
                maxcorr = getmax(corr)
                Q[i][j] = maxcorr[0] / nm1 
                idx[i][j] = maxcorr[1]
                if i != j:
                    Q[j][i] = Q[i][j]
    return Q, idx
Exemplo n.º 9
0
def FFT_Correlation(x,y):
    """
    FFT-based correlation, much faster than numpy autocorr.
    x and y are row-based vectors of arbitrary lengths.
    This is a vectorized implementation of O(N*log(N)) flops.
    """

    lengthx = x.shape[0]
    lengthy = y.shape[0]

    x = np.reshape(x,(1,lengthx))
    y = np.reshape(y,(1,lengthy))

    length = np.array([lengthx, lengthy]).min()
    
    x = x[:length]
    y = y[:length]
    
    fftx = fft(x, 2 * length - 1, axis=1) #pad with zeros
    ffty = fft(y, 2 * length - 1, axis=1)

    corr_xy = fft.ifft(fftx * np.conjugate(ffty), axis=1)
    corr_xy = np.real(fft.fftshift(corr_xy, axes=1)) #should be no imaginary part

    corr_yx = fft.ifft(ffty * np.conjugate(fftx), axis=1)
    corr_yx = np.real(fft.fftshift(corr_yx, axes=1))

    corr = 0.5 * (corr_xy[:,length:] + corr_yx[:,length:]) / range(1,length)[::-1]
    return np.reshape(corr,corr.shape[1])
Exemplo n.º 10
0
 def diff_spectrum(self, ref_mic):
     ref_signal = self.microphones[ref_mic[0]][ref_mic[1]].signal
     min_sig_len = min(ref_signal.shape[0], self.signal.shape[0])
     wnd = 0.54 - 0.46*numpy.cos(2*pi*numpy.arange(min_sig_len)/min_sig_len)
     fft_sum  = fftshift(fft(self.signal[0:min_sig_len]*wnd))/min_sig_len
     fft_ref = fftshift(fft(ref_signal[0:min_sig_len]*wnd))/min_sig_len
     fft_rel  = (fft_sum / fft_ref).real
     fft_freq = numpy.linspace(-self.samplerate/2, self.samplerate/2, min_sig_len);
     return {"x":fft_freq, "y":fft_rel}
Exemplo n.º 11
0
def fftconv(x, y):
    """ Convolution of x and y using the FFT convolution theorem. """
    N = len(x)
    n = int(2 ** np.ceil(np.log2(N))) + 1
    X, Y, x_y = fft(x, n), fft(y, n), []
    for i in range(n):
        x_y.append(X[i] * Y[i])

    # Returns the inverse Fourier transform with padding correction
    return fft.ifft(x_y)[4:N+4]
def conv(x,y):
    x1=np.zeros(x.size) 
    x1[0:x.size]=x  #added zeros

    y1=np.zeros(y.size)
    y1[0:y.size]=y #added zeros
    x1ft=np.fft(x1)
    y1ft=np.fft(y1)
    vect1=np.real(np.ifft(x1ft*y1ft))
    return vect1[0:x.size]
Exemplo n.º 13
0
def my_fft(sample, inverse=False):
    n = len(sample)
    if n == 1:
        return sample
    else:
        Feven = fft([sample[i] for i in xrange(0, n, 2)])
        Fodd = fft([sample[i] for i in xrange(1, n, 2)])

        combined = [0] * n
        for m in xrange(n/2):
            combined[m] = Feven[m] + omega(n, -m, inverse) * Fodd[m]
            combined[m + n/2] = Feven[m] - omega(n, -m, inverse) * Fodd[m]

        return combined
Exemplo n.º 14
0
 def solve(self, x, rho):
     Nx, = rho.shape
     k = fftfreq(Nx) * 2*np.pi*Nx
     k[0] = 1.0
     rhohat = fft(rho)
     rhobar = rhohat[0] / rho.size
     phihat = rhohat / -k**2 + fft(0.5 * rhobar * x**2)
     gphhat = 1.j * k * phihat
     phi = ifft(phihat).real
     gph = ifft(1.j * k * phihat).real
     soln = np.zeros(rho.shape + (4,))
     soln[:,0] = phi
     soln[:,1] = gph
     return soln
Exemplo n.º 15
0
def getHNR(y, Fs, F0, Nfreqs):
    print 'holla'
    NBins = len(y)
    N0 = round(Fs/F0)
    N0_delta = round(N0 * 0.1)
    
    y = [x*z for x,z in zip(np.hamming(len(y)),y)]
    fftY = np.fft(y, NBins)
    aY = np.log10(abs(fftY))
    ay = np.ifft(aY)
    
    peakinx = np.zeros(np.floor(len(y))/2/N0)
    for k in range(1, len(peakinx)):
        ayseg = ay[k*N0 - N0_delta : k*N0 + N0_delta]
        val, inx = max(abs(ayseg)) #MAX does not behave the same - doesn't return inx??
        peakinx[k] = inx + (k * N0) - N0_delta - 1
        
        s_ayseg = np.sign(np.diff(ayseg))
        
        l_inx = inx - np.find((np.sign(s_ayseg[inx-1:-1:1]) != np.sign(inx)))[0] + 1
        r_inx = inx + np.find(np.sign(s_ayseg[inx+1:]) == np.sign(inx))[0]
        
        l_inx = l_inx + k*N0 - N0_delta - 1
        r_inx = r_inx + k*N0 - N0_delta - 1
        
        for num in range(l_inx, r_inx):
            ay[num] = 0
        
    midL = round(len(y)/2)+1
    ay[midL:] = ay[midL-1: -1 : midL-1-(len(ay)-midL)]
    
    Nap = np.real(np.fft(ay))
    N = Nap #???? why?
    Ha = aY - Nap #change these names ffs
    
    Hdelta = F0/Fs * len(y)
    for f in [num+0.0001 for num in range(Hdelta, round(len(y)/2), Hdelta)]:
        fstart = np.ceil(f - Hdelta)
        Bdf = abs(min(Ha[fstart:round(f)]))
        N[fstart:round(f)] = N[fstart:round(f)] - Bdf
        
    H = aY - N
    n = np.zeros(len(Nfreqs))
    
    for k in range(1, len(Nfreqs)):
        Ef = round(Nfreqs[k] / Fs * len(y))
        n[k] = (20 * np.mean(H[1:Ef])) - (20 * np.mean(N[1:Ef]))
        
    return n
Exemplo n.º 16
0
def showResponse(x, f, a, w0, Q):
	fmax = 200.0
	
	# smooth it out with averaging:
	df = 1.0
	fatf = arange(0,fmax,df)
	n = len(fatf)
	fatX = zeros(n)

	print '\nfft\'ing to find the frequency response...'
	X = fft(x)
	for i in range(n):
		fslice = where(abs(f-fatf[i])<df/2)[0]
		fatX[i] = mean(abs(X[fslice]))

	norm = mean(fatX[0:10])
	fatX = fatX/norm

	# plot the response with the theoretical curve overlaid:
	plot(fatf, fatX, 'k.', label = 'simulated data')
	title('response of damping system')
	xlabel('frequency (Hz)')
	ylabel('abs(fft(x)) normalized to low f')

	Omega = 2*pi*fatf/w0
	zeta = 1.0/2.0/Q
	theory = 1/sqrt( (1-Omega**2)**2 + (2*zeta*Omega)**2 )
	
	semilogy(fatf, theory, label = 'theory')
	legend()
	show()
Exemplo n.º 17
0
def find_frequency(x,y):		# Returns the fundamental frequency using FFT
	tx,ty = fft(y, x[1]-x[0])
	index = find_peak(ty)
	if index == 0:
		return None
	else:
		return tx[index]
Exemplo n.º 18
0
def fft_squid(path):
    squid_model = model.NoisySquid(path)
    squid_model.getContext().setClock(3, 20e-3, 0)
    squid_model.currentInjection.min = 0.0e-6
    squid_model.currentInjection.max = 0.1e-6
    squid_model.getContext().reset()
    squid_model.run(200e-3)
    signal = array(squid_model.vmTable)
    squid_model.save_all_plots()
#    savetxt('vm.plot', signal)
    transform = fft(signal)
    xx = array(range(len(transform)))
    ax1 = subplot(121)
    #plot(xx / 10.0 , signal * 1e3, 'r')
    savetxt("t_series.plot", xx/10.0)
#     ax1 = axis([0, 0, 0.5, 0.8])
#     xlabel("time (ms)")
#     ylabel("membrane potential (mV)")
#     ax2 = twinx()
#     plot(xx / 10.0 , array(squid_model.iInjectTable) * 1e9, 'b--')
#     ylabel("injection current (nA)")
#     ax2.yaxis.tick_right()
#     title("(A)", fontname="Times New Roman", fontsize=10, fontweight="bold")
#     show()
#     savefig("Vm.jpg", dpi=600)
    
    savetxt('fftreal.plot', transform.real, fmt="%13.12G")
    savetxt('fftimag.plot', transform.imag, fmt="%13.12G")
Exemplo n.º 19
0
 def fourier_projection(self, density):
     
     ft_density = np.fft(density)
     
     # -m wraps around array, but that should be OK....
     # --> self._A_ell_expt[l] is shape (2l+1) x n_q  = (m x q)
     #     ft_coefficients[:,l,:] is shape n_q x (2l+1) = (q x m) (tranposed later)
     ft_coefficients = self._sph_harm_projector(ft_density)
     
     
     # zero out the array, use it to store the next iter
     ft_density[:,:,:] = 0.0 + 1j * 0.0
     
     for l in range(self.order_cutoff):
         
         A_ell_model = ft_coefficients[:,l,:].T # (2l+1) x n_q  = (m x q)
     
         # find U that rotates the experimental vectors into as close
         # agreement as possible as the model vectors
         U = math2.kabsch(self._A_ell_expt[l], A_ell_model)
 
         # update: k --> k+1
         A_ell_prime = np.dot(self._A_ell_expt[l], U)
         ft_density_prime += self._sph_harm_projector.expand_sph_harm_order(A_ell_prime, l)
         
     updated_density = np.ifft(ft_density)
         
     return updated_density
Exemplo n.º 20
0
def process_wav(file, truncate=None, window_size = 2**12):
    """
    spectrum : |windows| by window_size
    |frequencies| = window_size
    |windows| / 2 * |frequencies| ~ |seconds| * sample_rate
    """ 
    print 'processing %s...' % file
    audio, sample_rate = audio_wav(file, truncate=truncate)

    hanning_window = hanning(window_size)

    nWindows = int32(audio.size/window_size *2) # double <- overlap windows

    spectrum = zeros((nWindows,window_size))

    for i in xrange(0,nWindows-1):
        t = int32(i* window_size/2)
        window = audio[t : t+window_size] * hanning_window # elemwise mult
        spectrum[i,:] = fft(window)
        
    """ not invertible, sounds like noise
    iaudio = zeros((int(nWindows/2)-1, window_size))
    hanning_window[hanning_window==0]=min(hanning_window[hanning_window!=0]/4)
    for i in xrange(0,int(nWindows/2)-1):
        iaudio[i,:] = 1/hanning_window * abs(ifft(spectrum[2*i,:]))
    iaudio.dtype='int16'
    wavfile.write('inverse.wav', sample_rate, iaudio)
    """

    return spectrum, sample_rate
Exemplo n.º 21
0
    def processBuffer(self, bounds):
        self.param1 = bounds.height/65536.0
        self.param2 = bounds.height/2.0

        if(self.stop==False):

            Fs = 48000
            nfft= 65536
            self.newest_buffer=self.newest_buffer[0:256]
            self.fftx = fft(self.newest_buffer, 256,-1)

            self.fftx=self.fftx[0:self.freq_range*2]
            self.draw_interval=bounds.width/(self.freq_range*2.)

            NumUniquePts = ceil((nfft+1)/2)
            self.buffers=abs(self.fftx)*0.02
            self.y_mag_bias_multiplier=0.1
            self.scaleX = "hz"
            self.scaleY = ""

        if(len(self.buffers)==0):
            return False

        # Scaling the values
        val = []
        for i in self.buffers:
            temp_val_float = float(self.param1*i*self.y_mag) + self.y_mag_bias_multiplier * self.param2

            if(temp_val_float >= bounds.height):
                temp_val_float = bounds.height-25
            if(temp_val_float <= 0):
                temp_val_float = 25
            val.append( temp_val_float )

        self.peaks = val
Exemplo n.º 22
0
def dst(x,axis=-1):
    """Discrete Sine Transform (DST-I)

    Implemented using 2(N+1)-point FFT
    xsym = r_[0,x,0,-x[::-1]]
    DST = (-imag(fft(xsym))/2)[1:(N+1)]

    adjusted to work over an arbitrary axis for entire n-dim array
    """
    n = len(x.shape)
    N = x.shape[axis]
    slices = [None]*3
    for k in range(3):
        slices[k] = []
        for j in range(n):
            slices[k].append(slice(None))
    newshape = list(x.shape)
    newshape[axis] = 2*(N+1)
    xtilde = np.zeros(newshape,np.float64)
    slices[0][axis] = slice(1,N+1)
    slices[1][axis] = slice(N+2,None)
    slices[2][axis] = slice(None,None,-1)
    for k in range(3):
        slices[k] = tuple(slices[k])
    xtilde[slices[0]] = x
    xtilde[slices[1]] = -x[slices[2]]
    Xt = np.fft(xtilde,axis=axis)
    return (-np.imag(Xt)/2)[slices[0]]
	def processN(self,membuffer,frameSampleStart):
		
		# recalculate the filter and DCT matrices if needed
		if not self.update() : return []

		fftsize = self.m_blockSize
		audioSamples = frombuffer(membuffer[0],float32)

		complexSpectrum = fft(self.window*audioSamples,fftsize)
		#complexSpectrum =  frombuffer(membuffer[0],complex64,-1,8)

		magnitudeSpectrum = abs(complexSpectrum)[0:fftsize/2] / (fftsize/2)
		melSpectrum = self.warpSpectrum(magnitudeSpectrum)
		melCepstrum = self.getMFCCs(melSpectrum,cn=True)
		
		output_melCepstrum = [{
		'hasTimestamp':False,
		'values':melCepstrum[self.cnull:].tolist()
		}]

		output_melSpectrum = [{
		'hasTimestamp':False,		
		'values':melSpectrum.tolist()
		}]

		return [output_melCepstrum,output_melSpectrum,[]]
Exemplo n.º 24
0
 def make_unitary(self):
     fft_val = np.fft(self.v)
     fft_imag = fft_val.imag
     fft_real = fft_val.real
     fft_norms = [sqrt(fft_imag[n]**2 + fft_real[n]**2) for n in range(len(self.v))]
     fft_unit = fft_val / fft_norms
     self.v = (np.ifft(fft_unit)).real
Exemplo n.º 25
0
def spectrum(signal):
    """ Returns Fourier-Series coefficients, assuming that 'signal'
        represents one period of an infinitely extended periodic
        signal. """

    # A_{n, FourierSeries} = 1/L*A_{n, FFT}
    return fft(signal)/len(signal)
Exemplo n.º 26
0
	def process(self,inputbuffers,timestamp):
		
		if self.m_channels == 2 and self.two_ch :
			return self.process2ch(inputbuffers,timestamp)
		
		# calculate the filter and DCT matrices, check 
		# if they are computable given a set of parameters
		# (we only do this once, when the process is called first)
		if not self.update() : return None

		fftsize = self.m_blockSize
				
		if self.m_channels > 1 :
			audioSamples = (inputbuffers[0]+inputbuffers[1])/2
		else :
			audioSamples = inputbuffers[0]

		#complexSpectrum =  frombuffer(membuffer[0],complex64,-1,8)
		complexSpectrum = fft(self.window*audioSamples,fftsize)
		magnitudeSpectrum = abs(complexSpectrum)[0:fftsize/2] / (fftsize/2)
		
		# do the computation
		melSpectrum = self.warpSpectrum(magnitudeSpectrum)
		melCepstrum = self.getMFCCs(melSpectrum,cn=True)
		
		# output feature set (the builtin dict type can also be used)
		outputs = FeatureSet()
		outputs[0] = Feature(melCepstrum[self.cnull:])
		outputs[1] = Feature(melSpectrum)
					
		return outputs
Exemplo n.º 27
0
def newcomplexsmoothing(x, samplerate, width = 1./3, b = .54, onset_safeguard = 0):
    '''
    slightly different version where the linear delay is removed from the phase.
    onset_safeguard kwdargs is IGNORED
    still going back to the time domain doesn't work
    '''
    N = x.shape[0]
    # first step: remove linear part of the phase
    # estimation of the impulse response lag
    onset = onset_detection(x)

    x_ft = fft(x.flatten())
    x_phases = np.angle(x_ft)
    linearpart = fftfreq(len(x_ft))*onset
    x_newphases = exp(1j*(x_phases-linearpart))

    # second step: we compute the smoothed amplitudes
    amps = nonuniform_spectralsmoothing(np.abs(x_ft), samplerate, width = width, b = b)
    # third step: we compute the phases
    # new phases computations
    phases = nonuniform_spectralsmoothing(x_newphases, samplerate, width = width, b = b)
    # and set all the amplitudes to
    phasepart = np.exp(1j*phases)
    # fourth step: the result
    res_ft = amps*phasepart

    res_ft = complete_toneg(res_ft)
    res = ifft(res_ft).real
    return res, onset
Exemplo n.º 28
0
    def run(self):
        schema = schemas.Sensor(many=True)
        ref = self.database.db.accelerometres.find({'ref': ObjectId(self.params.uuid)})
        self.data, errors = schema.dump(ref)

        x = np.array(self.data)
        y = np.fft(x)
        return y
Exemplo n.º 29
0
    def Run(self):
        i = 0
        while self.keepGoing:
            i += 1
            data =self.stream.read(chunk)
            if (i>2):
#            if (i>self.skip):
                i = 0
            #print unpack('B',data[0])
                buff = array(unpack_from('1024h',data))
                #e = buff.std()
                #print "Energy: %f" % e
                #sys.stdout.flush()
             ## use stdev to calculate energy in this buffer (root sum of squared mag)      
            #csum.append(buff.std())
                fourier = fft(buff)
            ## calculate log mag of fft
                logmag = hypot(fourier.real[0:chunk/2],fourier.imag[0:chunk/2])
                if False:
                    self.lmfile=open("logmag.txt","w")
                    logmag.tofile(self.lmfile, sep=" ", format="%s")
                    self.lmfile.close()
                bdata = []
                i = 0
                for b in self.bands:
                    # sum energy in this band
                    bdata.append(logmag[b].mean()*self.scale[i])
                    i += 1

                    # normalize so max energy is 1.0
                localmax = []
                localmax.append(max(bdata))
                localmax.append(self.bmax)
                self.bmax = max(localmax)
                for i in range(len(bdata)):
                    bdata[i] = (bdata[i])*self.gain/self.bmax

                evt = self.UpdateAudioEvent(bands=bdata, value = int(localmax[0]*self.gain/50000))
                #print localmax[0]
                if True:
                    time.sleep(0.01)
                wx.PostEvent(self.win, evt)
                if True:
                    time.sleep(0.01)
                #self.bwfile=open("bands.txt","w")
                #self.bwfile.write(str(bdata))
                #self.bwfile.close()


                #bands = logmag[0:chunk/4]
                #nbands = 16
                #bwidth = chunk/(4*nbands)
                #bsum = mean(bands.reshape(nbands,bwidth),axis=1)
            #line.set_ydata(logmag)
                
            ## convert to 2d array and append to running show. 
            #logmag2 = array(logmag.tolist(),ndmin=2)
        self.running = False
Exemplo n.º 30
0
def fourier_genome(seq):
    xA=[0 for i in range(0,len(seq))]
    xT=[0 for i in range(0,len(seq))]
    xG=[0 for i in range(0,len(seq))]
    xC=[0 for i in range(0,len(seq))]

    for i in range(0,len(seq)):
        if seq[i]=="A":xA[i]=1
        if seq[i]=="T":xT[i]=1
        if seq[i]=="G":xG[i]=1
        if seq[i]=="C":xC[i]=1

    xhatA=abs(fft(xA))
    xhatG=abs(fft(xG))
    xhatT=abs(fft(xT))
    xhatC=abs(fft(xC))
    xhat=[(xhatA[i]**2+xhatT[i]**2+xhatC[i]**2+xhatG[i]**2)*2/len(seq) for i in range(len(xhatA)/2,len(xhatA))]
    return xhat,[float(i)/len(xhat) for i in range(0,len(xhat))]