numpy.hamming

Here are the examples of the python api numpy.hamming taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

16 Examples 7

Example 1

Project: diyECG-1opAmp Source File: swhear.py
Function: fft
def FFT(data,rate):
    """given some data points and a rate, return [freq,power]"""
    data=data*np.hamming(len(data))
    fft=np.fft.fft(data)
    fft=10*np.log10(np.abs(fft))
    freq=np.fft.fftfreq(len(fft),1/rate)
    return freq[:int(len(freq)/2)],fft[:int(len(fft)/2)]

Example 2

Project: dear Source File: cqt.py
Function: transform
    @staticmethod
    def transform(samples, Q, k_max=None, win_shape=numpy.hamming,
            pre_var=None):
        if not pre_var:
            if not k_max:
                assert 1 < Q <= len(samples) / 2
                k_max = int(numpy.log2(float(len(samples))/Q/2) \
                        / numpy.log2(float(Q+1)/Q))
            pre_var = Spectrum.pre_calculate(Q,k_max,len(samples),win_shape)
        frame = numpy.array(
            [numpy.sum(samples[:wl] * pre) / wl \
                for wl,pre in zip(pre_var.WL, pre_var.PRE)])
        return frame

Example 3

Project: dear Source File: cqt.py
Function: transform
    @staticmethod
    def transform(samples, Q, k_max=None, win_shape=numpy.hamming,
            pre_var=None):
        if not pre_var:
            if not k_max:
                assert 1 < Q <= len(samples) / 2
                k_max = int(numpy.log2(float(len(samples))/Q/2) \
                        / numpy.log2(float(Q+1)/Q))
            pre_var = CQTPowerSpectrum.pre_calculate(Q,k_max,len(samples),win_shape)
        frame = numpy.array(
            [numpy.sum(samples[:wl] * pre) \
                for wl,pre in zip(pre_var.WL, pre_var.PRE)])
        return (frame.real**2 + frame.imag**2) / pre_var.WL

Example 4

Project: dear Source File: dft.py
Function: transform_pre
    @staticmethod
    def transform_pre(samples, win_shape=numpy.hamming, pre_var=None):
        if not pre_var:
            pre_var = Spectrum.pre_calculate(len(samples), win_shape, True)
        frame = samples * pre_var.PRE
        frame = frame.sum(1) / pre_var.WL
        return frame

Example 5

Project: dear Source File: dft.py
Function: transform_pre
    @staticmethod
    def transform_pre(samples, win_shape=numpy.hamming, pre_var=None):
        if not pre_var:
            pre_var = Spectrum.pre_calculate(len(samples), win_shape, True)
        frame = samples * pre_var.PRE
        frame = frame.sum(1)
        return (frame.real**2 + frame.imag**2) / pre_var.WL

Example 6

Project: dear Source File: dft.py
Function: transform
    @staticmethod
    def transform(samples, win_shape=numpy.hamming, pre_var=None):
        if not pre_var:
            pre_var = Spectrum.pre_calculate(len(samples), win_shape, False)
        frame = numpy.fft.rfft(pre_var.W * samples)
        return (frame.real**2 + frame.imag**2) / pre_var.WL

Example 7

Project: pymir Source File: Frame.py
Function: energy
    def energy(self, windowSize = 256):
        """
        Compute the energy of this frame
        """
        N = len(self)

        window = numpy.hamming(windowSize)
        window.shape = (windowSize, 1)
        
        n = N - windowSize #number of windowed samples.
    
        # Create a view of signal who's shape is (n, windowSize). Use stride_tricks such that each stide jumps only one item.
        p = numpy.power(self,2)
        s = stride_tricks.as_strided(p,shape=(n, windowSize), strides=(self.itemsize, self.itemsize))
        e = numpy.dot(s, window) / windowSize
        e.shape = (e.shape[0], )
        return e

Example 8

Project: friture Source File: filter_design_fir.py
def main():
	from matplotlib.pyplot import semilogx, plot, show, xlim, ylim, figure, legend, subplot, bar
	from numpy.fft import fft, fftfreq, fftshift, ifft
	from numpy import log10, linspace, interp, angle, array, concatenate, hamming

	N = 2**12
	fs = 44100.
	Nchannels = 20
	low_freq = 20.

	#impulse = zeros(N)
	#impulse[N/2] = 1
	f = 70.
	impulse = sin(2*pi*f*arange(0, N/fs, 1./fs))*hamming(N)

	#[ERBforward, ERBfeedback] = MakeERBFilters(fs, Nchannels, low_freq)
	#y = ERBFilterBank(ERBforward, ERBfeedback, impulse)

	BandsPerOctave = 24
	Nbands = NOCTAVE*BandsPerOctave
	
	[B, A, fi, fl, fh] = octave_filters(Nbands, BandsPerOctave)
	y, zfs = octave_filter_bank(B, A, impulse)
	print("Filter lengths without decimation")
	for b, a in zip(B, A):
		print(len(b), len(a))
	
	
	response = 20.*log10(abs(fft(y)))
	freqScale = fftfreq(N, 1./fs)
	
	figure()
	subplot(211)
	
	for i in range(0, response.shape[0]):
		semilogx(freqScale[0:N/2],response[i, 0:N/2])
		
	xlim(fs/2000, fs)
	ylim(-70, 10)
	
	subplot(212)
	m = 0
	for f in fi:
		p = 10.*log10((y[m]**2).mean())
		m += 1
		semilogx(f, p, 'ko')
	
	Ndec = 3
	fc = 0.5
	# other possibilities
	#(bdec, adec) = ellip(Ndec, 0.05, 30, fc)
	#print bdec
	#(bdec, adec) = cheby1(Ndec, 0.05, fc)
	#(bdec, adec) = butter(Ndec, fc)
	(bdec, adec) = iirdesign(0.48, 0.50, 0.05, 70, analog=0, ftype='ellip', output='ba')
	#bdec = firwin(30, fc)
	#adec = [1.]
	
	figure()
	subplot(211)
	
	response = 20.*log10(abs(fft(impulse)))
	plot(fftshift(freqScale), fftshift(response), label="impulse")
	
	y = lfilter(bdec, adec, impulse)
	response = 20.*log10(abs(fft(y)))
	plot(fftshift(freqScale), fftshift(response), label="lowpass")
	
	ydec = y[::2].repeat(2)
	response = 20.*log10(abs(fft(ydec)))
	plot(fftshift(freqScale), fftshift(response), label="lowpass + dec2 + repeat2")
	
	ydec2 = interp(list(range(0, len(y))), list(range(0, len(y), 2)), y[::2])
	response = 20.*log10(abs(fft(ydec2)))
	plot(fftshift(freqScale), fftshift(response), label="lowpass + dec2 + interp2")
	
	ydec3 = y[::2]
	response = 20.*log10(abs(fft(ydec3)))
	freqScale2 = fftfreq(N/2, 2./fs)
	plot(fftshift(freqScale2),fftshift(response), label="lowpass + dec2")
	
	legend(loc="lower left")
	
	subplot(212)
	plot(list(range(0, len(impulse))), impulse, label="impulse")
	plot(list(range(0, len(impulse))), y, label="lowpass")
	plot(list(range(0, len(impulse))), ydec, label="lowpass + dec2 + repeat2")
	plot(list(range(0, len(impulse))), ydec2, label="lowpass + dec2 + interp2")
	plot(list(range(0, len(impulse), 2)), ydec3, label="lowpass + dec2")
	legend()
	
	[boct, aoct, fi, flow, fhigh] = octave_filters_oneoctave(Nbands, BandsPerOctave)
	y, dec, zfs = octave_filter_bank_decimation(bdec, adec, boct, aoct, impulse)
	print("Filter lengths with decimation")
	print(len(bdec), len(adec))
	for b, a in zip(boct, aoct):
		print(len(b), len(a))

	figure()
	subplot(211)
	
	for yone, d in zip(y, dec):
		response = 20.*log10(abs(fft(yone))*d)
		freqScale = fftfreq(N/d, 1./(fs/d))
		semilogx(freqScale[0:N/(2*d)],response[0:N/(2*d)])
	
	xlim(fs/2000, fs)
	ylim(-70, 10)
	
	subplot(212)
	m = 0
	for i in range(0, NOCTAVE):
		for f in fi:
			p = 10.*log10((y[m]**2).mean())
			semilogx(f/dec[m], p, 'ko')
			m += 1

	[B, A, fi, fl, fh] = octave_filters(Nbands, BandsPerOctave)
	y1, zfs = octave_filter_bank(B, A, impulse[0:N/2])
	y2, zfs = octave_filter_bank(B, A, impulse[N/2:], zis=zfs)
	#[boct, aoct, fi, flow, fhigh] = octave_filters_oneoctave(Nbands, BandsPerOctave)
	#y1, dec, zfs = octave_filter_bank(bdec, adec, boct, aoct, impulse[0:N/2])
	#y2, dec, zfs = octave_filter_bank(bdec, adec, boct, aoct, impulse)	
	
	y = []
	for y1one, y2one in zip(y1,y2):
		y += [concatenate((y1one,y2one))]
		
	figure()
	plot(impulse[0:N/2])
	#for y0 in y1:
		#plot(y0)
	plot(y1[-1])

	figure()
	subplot(211)
	
	for yone in y:
		response = 20.*log10(abs(fft(yone)))
		freqScale = fftfreq(N, 1./fs)
		semilogx(freqScale[0:N/2],response[0:N/2])
	
	xlim(fs/2000, fs)
	ylim(-70, 10)
	
	subplot(212)
	m = 0
	for f in fi:
		p = 10.*log10((y[m]**2).mean())
		semilogx(f, p, 'ko')
		m += 1
	
	generate_filters_params()

	show()

Example 9

Project: pyAudioAnalysis Source File: audioFeatureExtraction.py
def phormants(x, Fs):
    N = len(x)
    w = numpy.hamming(N)

    # Apply window and high pass filter.
    x1 = x * w   
    x1 = lfilter([1], [1., 0.63], x1)
    
    # Get LPC.    
    ncoeff = 2 + Fs / 1000
    A, e, k = lpc(x1, ncoeff)    
    #A, e, k = lpc(x1, 8)

    # Get roots.
    rts = numpy.roots(A)
    rts = [r for r in rts if numpy.imag(r) >= 0]

    # Get angles.
    angz = numpy.arctan2(numpy.imag(rts), numpy.real(rts))

    # Get frequencies.    
    frqs = sorted(angz * (Fs / (2 * math.pi)))

    return frqs

Example 10

Project: radiotool Source File: novelty.py
def novelty(song, k=64, wlen_ms=100, start=0, duration=None, nchangepoints=5, feature="rms"):
    """Return points of high "novelty" in a song
    (e.g., significant musical transitions)

    :param song: Song to analyze
    :type song: :py:class:`radiotool.composer.Song`
    :param k: Width of comparison kernel (larger kernel finds coarser differences in music)
    :type k: int
    :param wlen_ms: Analysis window length in milliseconds
    :type wlen_ms: int
    :param start: Where to start analysis within the song (in seconds)
    :type start: float
    :param duration: How long of a chunk of the song to analyze (None analyzes the entire song after start)
    :type duration: float
    :param nchangepoints: How many novel change points to return
    :type nchangepoints: int
    :param feature: Music feature to use for novelty analysis
    :type feature: "rms" or "mfcc" (will support "chroma" eventually)
    :returns: List of change points (in seconds)
    :rtype: list of floats
    """

    if feature != "rms" and feature != "mfcc":
        raise ValueError, "novelty currently only supports 'rms' and 'mfcc' features"

    if feature == "rms":
        frames = song.all_as_mono()

        wlen_samples = int(wlen_ms * song.samplerate / 1000)

        if duration is None:
            frames = frames[start * song.samplerate:]
        else:
            frames = frames[start * song.samplerate:(start + duration) *
                 song.samplerate]
                 
        # Compute energies
        hamming = np.hamming(wlen_samples)
        nwindows = int(2 * song.duration / wlen_samples - 1)
        energies = np.empty(nwindows)
        for i in range(nwindows):
            energies[i] = RMS_energy(
                hamming *
                frames[i * wlen_samples / 2:
                       i * wlen_samples / 2 + wlen_samples]
            )

        energies_list = [[x] for x in energies]
    elif feature == "mfcc":
        analysis = song.analysis
        energies_list = np.array(analysis["timbres"])
    
    # Compute similarities
    S_matrix = 1 - scipy.spatial.distance.squareform(
        scipy.spatial.distance.pdist(energies_list, 'euclidean'))
                    
    # smooth the C matrix with a gaussian taper
    C_matrix = np.kron(np.eye(2), np.ones((k,k))) -\
               np.kron([[0, 1], [1, 0]], np.ones((k,k)))
    g = scipy.signal.gaussian(2*k, k)
    C_matrix = np.multiply(C_matrix, np.multiply.outer(g.T, g))
    
    # Created checkerboard kernel
    
    N_vec = np.zeros(np.shape(S_matrix)[0])
    for i in xrange(k, len(N_vec) - k):
        S_part = S_matrix[i - k:i + k, i - k:i + k]
        N_vec[i] = np.sum(np.multiply(S_part, C_matrix))
        
    # Computed checkerboard response

    peaks = naive_peaks(N_vec, k=k / 2 + 1)
    out_peaks = []
    
    if feature == "rms":
        # ensure that the points we return are more exciting
        # after the change point than before the change point
        for p in peaks:
            frame = p[0]
            if frame > k:
                left_frames = frames[int((frame - k) * wlen_samples / 2):
                                     int(frame * wlen_samples / 2)]
                right_frames = frames[int(frame * wlen_samples / 2):
                                      int((frame + k) * wlen_samples / 2)]
                if RMS_energy(left_frames) <\
                   RMS_energy(right_frames):
                   out_peaks.append(p)

        out_peaks = [(x[0] * wlen_ms / 2000.0, x[1]) for x in out_peaks]
        for i, p in enumerate(out_peaks):
            if i == nchangepoints:
                break
        
        return [x[0] for x in out_peaks[:nchangepoints]]

    elif feature == "mfcc":
        beats = analysis["beats"]
        return [beats[int(b[0])] for b in peaks[:nchangepoints]]

Example 11

Project: cloud-asr Source File: mfcc.py
    def init_hamming(self):
        self.hamming = np.hamming(self.framesize)

Example 12

Project: smacpy Source File: smacpy.py
	def file_to_features(self, wavpath):
		"Reads through a mono WAV file, converting each frame to the required features. Returns a 2D array."
		if verbose: print("Reading %s" % wavpath)
		if not os.path.isfile(wavpath): raise ValueError("path %s not found" % wavpath)
		sf = Sndfile(wavpath, "r")
		#if (sf.channels != 1) and verbose: print(" Sound file has multiple channels (%i) - channels will be mixed to mono." % sf.channels)
		if sf.samplerate != fs:         raise ValueError("wanted sample rate %g - got %g." % (fs, sf.samplerate))
		window = np.hamming(framelen)
		features = []
		while(True):
			try:
				chunk = sf.read_frames(framelen, dtype=np.float32)
				if len(chunk) != framelen:
					print("Not read sufficient samples - returning")
					break
				if sf.channels != 1:
					chunk = np.mean(chunk, 1) # mixdown
				framespectrum = np.fft.fft(window * chunk)
				magspec = abs(framespectrum[:framelen/2])

				# do the frequency warping and MFCC computation
				melSpectrum = self.mfccMaker.warpSpectrum(magspec)
				melCepstrum = self.mfccMaker.getMFCCs(melSpectrum,cn=True)
				melCepstrum = melCepstrum[1:]   # exclude zeroth coefficient
				melCepstrum = melCepstrum[:13] # limit to lower MFCCs

				framefeatures = melCepstrum   # todo: include deltas? that can be your homework.

				features.append(framefeatures)
			except RuntimeError:
				break
		sf.close()
		return np.array(features)

Example 13

Project: dear Source File: dft.py
Function: transform
    @staticmethod
    def transform(samples, win_shape=numpy.hamming, pre_var=None):
        if not pre_var:
            pre_var = Spectrum.pre_calculate(len(samples), win_shape, False)
        return numpy.fft.rfft(pre_var.W * samples) / pre_var.WL

Example 14

Project: an-analysis-of-unsupervised-pre-training-iclr-2015 Source File: train.py
def conv_orthogonalize(w, k=1.0):
    # Reshape filters into a matrix
    channels, width, height, filters = w.shape
    w = w.reshape(channels*width*height, filters).transpose(1, 0)

    # Orthogonalize the matrix
    w = orthogonalize(w)

    # Contruct 2D hamming window
    hamming1 = numpy.hamming(width)
    hamming2 = numpy.hamming(height)
    hamming = numpy.outer(hamming1, hamming2)

    # Use it to mask the input to w
    mask = numpy.tile(hamming[None, :, :], (channels, 1, 1))
    mask = mask.reshape(channels*width*height)*k
    m = numpy.diag(mask)
    w = numpy.dot(w, m)

    # Reshape the matrix into filters
    w = w.transpose(1, 0)
    w = w.reshape(channels, width, height, filters)
    w = numpy.float32(w)
    return w

Example 15

Project: pymir Source File: Energy.py
Function: energy
def energy(audioData, windowSize = 256):
    """
    Compute the energy of the given audio data, using the given windowSize

    Example:
    >>> from test import chirp
    >>> s = chirp()
    >>> e = energy(s)
    >>> e
    array([ 0.26917694,  0.26901879,  0.26918094, ...,  0.18757919,
            0.18656895,  0.18561012])
    """
    N = len(audioData)

    window = numpy.hamming(windowSize)
    window.shape = (windowSize, 1)
    
    n = N - windowSize # number of windowed samples.

    # Create a view of audioData who's shape is (n, windowSize). Use stride_tricks such that each stide jumps only one item.
    p = numpy.power(audioData, 2)
    s = stride_tricks.as_strided(p, shape=(n, windowSize), strides=(audioData.itemsize, audioData.itemsize))
    e = numpy.dot(s, window) / windowSize
    e.shape = (e.shape[0], )
    return e

Example 16

Project: vad Source File: _vad.py
Function: init
    def __init__(self, fs, markov_params=(0.5, 0.1), alpha=0.99, NFFT=2048,
                 n_iters=10, win_size_sec=0.05, win_hop_sec=0.025,
                 max_est_iter=-1, epsilon=1e-6):
        """ Voice Activity Detection

        Parameters
        ----------
        fs : int
            sampling rate
        markov_params : (int, int)
            parameters for the hangover scheme
        alpha : float
            SNR estimate coefficient
        NFFT : int
            size of the FFT
        n_iters : int
            number of iterations in noise estimation
        win_size_sec : float
            window size in seconds
        win_hop_sec : float
            window shift in seconds
        epsilon : float
            convergence threshold
        """
        self.fs = fs
        self.a01, self.a10 = markov_params
        self.a00 = 1 - self.a01
        self.a11 = 1 - self.a10
        self.alpha = alpha
        self.NFFT = NFFT
        self.win_size_sec = win_size_sec
        self.win_hop_sec = win_hop_sec
        self.epsilon = epsilon
        self.n_iters = n_iters
        self.max_est_iter = max_est_iter

        self.wlen = int(fs * self.win_size_sec)
        self.fshift = int(fs * self.win_hop_sec)
        self.win = hamming(self.wlen)