Example #1
2
def problem4():
	# read in tada.wav
	rate, tada = wavfile.read('tada.wav')
	
	# upon inspection, we find that tada.wav is a stereo audio file. 
	# we create stereo white noise that lasts 10 seconds
	L_white = sp.int16(sp.random.randint(-32767,32767,rate*10))
	R_white = sp.int16(sp.random.randint(-32767,32767,rate*10))
	white = sp.zeros((len(L_white),2))
	white[:,0] = L_white
	white[:,1] = R_white
	
	# pad tada signal with zeros
	padded_tada = sp.zeros_like(white)
	padded_tada[:len(tada)] = tada
	ptada = padded_tada
	
	# fourier transforms
	ftada = sp.fft(ptada,axis=0)
	fwhite = sp.fft(white,axis=0)
	
	# inverse transform of convolution
	out = sp.ifft((ftada*fwhite),axis=0)
	
	# prepping output and writing file
	out = sp.real(out)
	scaled = sp.int16(out / sp.absolute(out).max() * 32767)
	wavfile.write('my_tada_conv.wav',rate,scaled)
Example #2
1
def get_envelope(R,dim=1):
    """
    Returns the complex version of the input signal R.
    @param R: The input data matrix.
    @param dim: The dimension along which the envelope is to be taken. default: dim=1
    """
    if dim==0:
        R=R.T
    if len(R.shape)==1:
        freqs=scipy.fft(R)
        length=len(R)/2
        freqs[length:]=0
        freqs[1:length]=2*freqs[1:length]
        ## freqs[1:length]=freqs[1:length]
        
        env=scipy.ifft(freqs)
    else:
        freqs=scipy.fft(R)
        length=R.shape[dim]/2
        #Something is fishy here:
        freqs[:,length:]=0
        freqs[:,1:length]=2*freqs[0,1:length]
        ## freqs[:,1:length]=freqs[0,1:length]
        
        env=scipy.ifft(freqs)
        if dim==0:
            return env.T

    return env
Example #3
0
def test_fft_function():
    # Many NumPy symbols are imported into the scipy namespace, including
    # numpy.fft.fft as scipy.fft, conflicting with this module (gh-10253)
    np.random.seed(1234)

    # Callable before scipy.fft is imported
    import scipy
    x = np.random.randn(10) + 1j * np.random.randn(10)
    with pytest.deprecated_call(match=r'1\.5\.0'):
        X = scipy.fft(x)
    with pytest.deprecated_call(match=r'2\.0\.0'):
        y = scipy.ifft(X)
    assert_allclose(y, x)

    # Callable after scipy.fft is imported
    import scipy.fft
    assert_allclose(X, scipy.fft.fft(x))
    with pytest.deprecated_call(match=r'1\.5\.0'):
        X = scipy.fft(x)
    assert_allclose(X, scipy.fft.fft(x))
    with pytest.deprecated_call(match=r'2\.0\.0'):
        y = scipy.ifft(X)
    assert_allclose(y, x)

    # Callable when imported using from
    from scipy import fft
    with pytest.deprecated_call(match=r'1\.5\.0'):
        X = fft(x)
    with pytest.deprecated_call(match=r'2\.0\.0'):
        y = scipy.ifft(X)
    assert_allclose(y, x)
Example #4
0
def forward_propagation():
    """
    Returns:
        y: received signal (shape = [Nsamp_d, 2], separate real and imaginary part)
        x: symbol vector (shape = [Nsym], complex)
        P: launch power (in W)
    """
    np.random.seed()  # new seed is necessary for multiprocessor
    P = P_W_r[np.random.randint(P_W_r.shape[0])]  # get random launch power
    # [SOURCE] random points from the signal constellation
    if modulation == "QAM":
        x = const[np.random.randint(const.shape[0], size=[1, Nsym])]
    elif modulation == "Gaussian":
        x = (np.random.normal(0, 1, size=[1, Nsym]) +
             1j * np.random.normal(0, 1, size=[1, Nsym])) / np.sqrt(2)
    else:
        raise ValueError("wrong modulation format: " + modulation)
    # [MODULATION] upsample + pulse shaping
    x_up = np.zeros([1, Nsamp_a], dtype=np.complex64)
    x_up[:, ::OS_a] = x * np.sqrt(OS_a)
    u = sp.ifft(sp.fft(x_up) * ps_filter_tx_freq) * np.sqrt(P)
    # [CHANNEL] simulate forward propagation
    for NN in range(Nsp):  # enter a span
        for MM in range(fw.model_steps):  # enter a segment
            u = sp.ifft(fw.get_cd_filter_freq(MM) * sp.fft(u))
            u = u * np.exp(1j * fw.nl_param[MM] * np.abs(u)**2)
            #u = u*np.exp(1j*(8/9)*fw.nl_param[MM]*(np.abs(u[0,:])**2+np.abs(u[1,:])**2))
        # add noise, NOTE: amplifier gain (u = u*np.exp(alpha_lin*Lsp/2.0)) is absorbed in nl_param
        u = u + np.sqrt(sigma2 / 2 / Nsp) * (np.random.randn(1, Nsamp_a) +
                                             1j * np.random.randn(1, Nsamp_a))
    # [RECEIVER] low-pass filter + downsample
    u = sp.ifft(sp.fft(u) * lp_filter_freq)
    y = u[0, ::OS_a // OS_d]
    y = np.stack([np.real(y), np.imag(y)], axis=1)
    return y, x[0, :], P
Example #5
0
def get_envelope(R, dim=1):
    """
    Returns the complex version of the input signal R.
    @param R: The input data matrix.
    @param dim: The dimension along which the envelope is to be taken. default: dim=1
    """
    if dim == 0:
        R = R.T
    if len(R.shape) == 1:
        freqs = scipy.fft(R)
        length = len(R) / 2
        freqs[length:] = 0
        freqs[1:length] = 2 * freqs[1:length]
        ## freqs[1:length]=freqs[1:length]

        env = scipy.ifft(freqs)
    else:
        freqs = scipy.fft(R)
        length = R.shape[dim] / 2
        #Something is fishy here:
        freqs[:, length:] = 0
        freqs[:, 1:length] = 2 * freqs[0, 1:length]
        ## freqs[:,1:length]=freqs[0,1:length]

        env = scipy.ifft(freqs)
        if dim == 0:
            return env.T

    return env
Example #6
0
def GaussianPulseDR(epsilon, Bx, c0, zm, zs, LOG='no'):
    ''' Analytical Propgation of a gaussion pulse near a rigid boundary.
    epsilon : amplitude of the gaussian
    Bx : width of the gaussian
    c0 : celerity of wave
    zm : location of the microphone
    zs : location of the source
    LOG : if LOG=='log', display complementary informations
    '''

    ext = 10
    Nfreq = 2**12
    Npadd = 2**14
    B = np.sqrt(Bx**2/np.log(2))
    k0 = np.sqrt(2)/B
    fmin = 0.00001
    fmax = k0*c0/(2*np.pi)
    r1 = abs(zm-zs)
    r2 = abs(zm+zs)

    # Axes
    k = np.linspace(2*np.pi*fmin/c0, ext*k0, Nfreq)
    f = np.linspace(fmin, ext*fmax, Nfreq)
    df = f[2] - f[1]
    wtime = np.linspace(0, 1/df, Npadd)

    # Puissance de la source % omega
    Sw = 1j*k*np.pi*epsilon*B**2*np.exp(-k**2*B**2/4.)/c0

    # Pression dans le domaine freq.
    Pdw = -1j*Sw*hankel1(0, k*r1)/4.
    Prw = -1j*Sw*hankel1(0, k*r2)/4.

    Ai = fmax*Nfreq/(2*np.pi)
    Pdt = Ai*ifft(Pdw, Npadd)[::-1]
    Prt = Ai*ifft(Prw, Npadd)[::-1]

    if LOG == 'log':
        print('Max. frequency : ' + repr(fmax))
        pl.figure('Source Strenght')
        pl.subplot(311)
        pl.plot(f, abs(Sw), 'k')
        pl.ylabel('Strength $S_w$')
        pl.subplot(312)
        pl.plot(f, abs(Pdw), 'k', label='Direct')
        pl.plot(f, abs(Prw), color='0.5', label='Reflected')
        pl.legend()
        pl.ylabel(r'Pressure $\tilde{p}(r,w)$')
        pl.subplot(313)
        pl.plot(wtime, Pdt.real/Pdt.real.max(), color='0.8', label='Direct')
        pl.plot(wtime, Prt.real/Prt.real.max(), color='0.5', label='Reflected')
        pl.plot(wtime, Pdt.real/Pdt.real.max() + Prt.real/Prt.real.max(), 'k--', linewidth=4, label='Sum')
        pl.legend()
        pl.ylabel(r'Pressure $\tilde{p}(r,t)$')

    return Pdt+Prt, Pdt, Prt, f, wtime
Example #7
0
def start():
    
        global signal
        global heartrate
        global spo2
        
        easypulse = EasyPulse()
        beats = easypulse.readPulse()
        heartrate = easypulse.computeHeartrate(beats)
        spo2 = spo2()
        
        #print ("Number of beats: " + str(len(beats)))
        #print( "Heartrate: " + str(heartrate))
        
        signal=[]
        
        for i in range(1,100):
            
            reading = easypulse.readadc(2, 11, 10, 9, 8)
            signal.append(reading*3.3/1023)
            
        fft=scipy.fft(signal)
        bp=fft[:]
        
        for i in range(len(bp)): 
         if i>=10:bp[i]=0  

        ibp=scipy.ifft(bp)
Example #8
0
def prob4(filename='saw.wav', new_rate = 11025, outfile='prob4.wav'):
    """Down-samples a given .wav file to a new rate and saves the resulting
    signal as another .wav file.
    
    Parameters
    ----------
    filename : string, optional
        The name of the .wav sound file to be down-sampled.
        Defaults to 'saw.wav'.
    new_rate : integer, optional
        The down-sampled rate. Defaults to 11025.
    outfile : string, optional
        The name of the new file. Defaults to prob4.wav.

    Returns
    -------
    None
    """
    old_rate, in_sig = wavfile.read(filename)
    fin = fftw.fft(sp.float32(in_sig))
    # Use if scipy_fftpack is unavailable
    # fin = sp.fft(sp.float32(in_sig))
    nsiz = sp.floor(in_sig.size * new_rate / old_rate)
    nsizh = sp.floor(nsiz / 2)
    fout = sp.zeros(nsiz) + 0j
    fout[0:nsizh] = fin[0:nsizh]
    fout[nsiz-nsizh+1:] = sp.conj(sp.flipud(fout[1:nsizh]))
    out = sp.real(sp.ifft(fout))
    out = sp.int16(out/sp.absolute(out).max() * 32767)
    plot_signal(filename)
    wavfile.write('prob4.wav',new_rate,out)
    print ""; plot_signal('prob4.wav')
Example #9
0
def sampling_reverb(signal_array, impulse_response):
    sigL = len(signal_array)
    irL = len(impulse_response)

    ### インパルス応答の長さ調整
    new_irL = int((2**nextpow2(irL)) * 2)  #2フレーム分
    frameL = new_irL / 2
    #zeros:0で初期化した配列を作成(shape, dtype)
    new_IR = zeros(new_irL, dtype=float64)
    #[:]はスライス.今回の場合は一番最初からirLまでの長さの部分にimpulse_responseを代入
    new_IR[:irL] = impulse_response

    ###入力信号を適度な長さにする.
    frame_num = int(ceil((sigL + frameL) / float(frameL)))
    new_sigL = frameL * frame_num
    new_sig = zeros(new_sigL, dtype=float64)
    new_sig[frameL:frameL + sigL] = signal_array

    ###インパルス応答の畳み込み
    ret = zeros(new_sigL - frame_num, dtype=float64)
    ir_fft = fft(new_IR)  #インパルス応答のFFT
    for ii in xrange(frame_num - 1):
        s_ind = frameL * ii
        e_ind = frameL * (ii + 2)

        sig_fft = fft(new_sig[s_ind:e_ind])  #信号のFFT
        ###畳み込み
        ret[s_ind:s_ind + frameL] = ifft(sig_fft * ir_fft)[frameL:].real

    print(new_irL, sigL, new_sigL)
    print len(sig_fft)
    print len(ir_fft)
    return ret[:sigL]
def IMRpeakAmp(m1, m2, spin1z, spin2z, d):
    """
	IMRpeakAmp finds the peak amplitude of the waveform for a given source parameters and the source distance.
	usage: IMRpeakAmp(m1,m2,spin1z,spin2z,distance)
	e.g.
	spawaveApp.IMRpeakAmp(30,40,0.45,0.5,100)

	"""

    chi = spawaveform.computechi(m1, m2, spin1z, spin2z)
    imrfFinal = spawaveform.imrffinal(m1, m2, chi, 'fcut')
    fLower = 10.0
    order = 7
    dur = 2**numpy.ceil(
        numpy.log2(spawaveform.chirptime(m1, m2, order, fLower)))
    sr = 2**numpy.ceil(numpy.log2(imrfFinal * 2))
    deltaF = 1.0 / dur
    deltaT = 1.0 / sr
    s = numpy.empty(sr * dur, 'complex128')
    spawaveform.imrwaveform(m1, m2, deltaF, fLower, s, spin1z, spin2z)
    s = scipy.ifft(s)
    #s = numpy.abs(s)
    s = numpy.real(s)
    max = numpy.max(s) / d
    return max
    def propagate(self):
        r"""
        Given the wavefunction values :math:`\Psi` at time :math:`t`, calculate new
        values at time :math:`t + \tau`. We perform exactly one timestep :math:`\tau` here.
        """
        # How many states we have
        nst = self.Psi.get_number_components()

        # Read values out of current WaveFunction state
        vals = self.Psi.get_values()

        # Do the propagation
        tmp = [ zeros(vals[0].shape, dtype=complexfloating) for item in vals ]
        for row in xrange(0, nst):
            for col in xrange(0, nst):
                tmp[row] = tmp[row] + self.VE[row*nst+col] * vals[col]

        tmp = tuple([ fft(item) for item in tmp ])

        tmp = tuple([ self.TE * item for item in tmp ])

        tmp = tuple([ ifft(item) for item in tmp ])

        values = [ zeros(tmp[0].shape, dtype=complexfloating) for item in tmp ]
        for row in xrange(0, nst):
            for col in xrange(0, nst):
                values[row] = values[row] + self.VE[row*nst+col] * tmp[col]

        # Write values back to WaveFunction object
        self.Psi.set_values(values)
Example #12
0
    def removenoise(self, data):
        nototalframes = np.floor(
            len(data) / (self.framelength))  # the total no of frames in sound
        dataclean = np.array([])  # storage for final sound

        for i in range(int(nototalframes)):
            start = i * (self.framelength)
            dft = scipy.fft(
                data[start:start +
                     self.framelength])  # no windowing .. required?
            dmag = np.abs(dft)
            dang = np.angle(dft)
            dmag = dmag - (
                SUBTRACTION_FACTOR * self.noiseprofile
            )  # subtract the noise spectrum by 1.5 for greater effect
            #over subtraction    above 2kh
            dmag[self.subfeqlevelmin:self.subfeqlevelmax] = dmag[
                self.subfeqlevelmin:self.subfeqlevelmax] - (
                    OVERSUBTRACTION *
                    self.noiseprofile[self.subfeqlevelmin:self.subfeqlevelmax])
            dmag[dmag < 0] = 0  # because magnitude spectrum cannot be -ve
            new = dmag * np.exp(
                dang *
                1j)  # integrate new magnitude and old phase mag*e^(j*phase)
            idft = scipy.ifft(new)  # time domain
            dataclean = np.append(dataclean, np.real(idft))

        return dataclean
Example #13
0
def istft(spectrogram, w_size, step):
    
    if spectrogram.shape[0] != w_size:
        print ("Mismatch w_size and spectrogram")

    eps = np.finfo(float).eps
    window = np.hanning(w_size)
    # spectrogram.shape = w_size , bins
    spectr_len = spectrogram.shape[1]
    reconst_len = w_size + (spectr_len - 1) * step

    reconst_x = np.zeros(reconst_len, dtype=float)
    windowsum = np.zeros(reconst_len, dtype=float)
    windowsq = window * window

    # Overlap add
    for i in range(0, spectr_len):
        s = i * step
        e = i * step + w_size
        r = ifft(spectrogram[:, i]).real
        # r = abs(ifft(spectrogram[:, i]))

        reconst_x[s:e] += r * window
        windowsum[s:e] += windowsq

    # Normalize by window

    # for i in range(0,reconst_len)
    #     if windowsum[i] > eps
    #         reconst_x[i] /= windowsum[i]
    pos = (windowsum != 0)
    reconst_x[pos] /= windowsum[pos]
    return reconst_x.astype("int16")
Example #14
0
def down_sample(filename, new_rate, outputfile=None):
    """
    Create a down-sampled copy of the provided .wav file.  Unless overridden, the output
        file will be of the form "down_<orginalname>.wav"
        
    Parameters
    ----------
    filename : string
        input .wav file
    new_rate : int
        sample rate of output file
    outputfile : string
        name of output file
    """

    if outputfile is None:
        outputfile = "down_" + filename

    old_rate, in_sig = wavfile.read(filename)
    in_sig = sp.float32(in_sig)
    fin = sp.fft(in_sig)
    nsiz = sp.floor(in_sig.size * new_rate / old_rate)
    nsizh = sp.floor(nsiz / 2)
    fout = sp.zeros(nsiz)
    fout = fout + 0j
    fout[0:nsizh] = fin[0:nsizh]
    fout[nsiz - nsizh + 1 :] = sp.conj(sp.flipud(fout[1:nsizh]))
    out = sp.ifft(fout)
    out = sp.real(out)  # Take the real component of the signal
    out = sp.int16(out / sp.absolute(out).max() * 32767)
    wavfile.write(outputfile, new_rate, out)
Example #15
0
def ffacorr(a):
    """Returns the autocorrelation of a. Expects raw data"""
    z=np.zeros(2*len(a))
    z[:len(a)]=a
    fft=sc.fft(z)
    out=sc.ifft(fft*sc.conj(fft))
    return (out[:len(out)/2])
Example #16
0
def process_data(start, sum_data):
    input_data = read('junk.wav')
    audio_in = input_data[1]
    samples = len(audio_in)
    intvl = start / seg
    k = 0
    var_thres = 2.2
    data_out = []

    #print "intvl = ",intvl,start,seg
    for i in xrange(intvl):
        buffer_out = []
        for j in xrange(seg):
            buffer_out.append(audio_in[k])
            k = k + 1
        cbuffer_out = fft(buffer_out)
        for j in xrange(seg):
            if (abs(cbuffer_out[j]) < var_thres * sum_data[j]):
                cbuffer_out[j] = 0.02 * cbuffer_out[j]
        buf_out = ifft(cbuffer_out)
        for j in xrange(seg):
            data_out.append(buf_out[j].real)

    sar = numpy.array(data_out, dtype=numpy.int16)
    write("junk_out.wav", 44100, sar)
    cmd4 = 'lame junk_out.wav junk_out.mp3 >enc.log 2>&1 '
    os.system(cmd4)
Example #17
0
def cwt_freq(data, wavelet, widths, dt, axis):
    # compute in frequency
    # next highest power of two for padding
    N = data.shape[axis]
    pN = int(2 ** np.ceil(np.log2(N)))
    # N.B. padding in fft adds zeros to the *end* of the array,
    # not equally either end.
    fft_data = scipy.fft(data, n=pN, axis=axis)
    # frequencies
    w_k = np.fft.fftfreq(pN, d=dt) * 2 * np.pi

    # sample wavelet and normalise
    norm = (2 * np.pi * widths / dt) ** .5
    wavelet_data = norm[:, None] * wavelet(w_k, widths[:, None])

    # Convert negative axis. Add one to account for
    # inclusion of widths axis above.
    axis = (axis % data.ndim) + 1

    # perform the convolution in frequency space
    slices = [slice(None)] + [None for _ in data.shape]
    slices[axis] = slice(None)

    out = scipy.ifft(fft_data[None] * wavelet_data.conj()[slices],
                     n=pN, axis=axis)

    # remove zero padding
    slices = [slice(None) for _ in out.shape]
    slices[axis] = slice(None, N)

    if data.ndim == 1:
        return out[slices].squeeze()
    else:
        return out[slices]
Example #18
0
def delayedsignalF(x, t0_pts):
    #==============================================================
    """
     Delay a signal with a non integer value
     (computation in frequency domain)
     
     Synopsis:
              y=delayedsignalF(x,t0_pts)
     
     Inputs: x vector of length N
             t0_pts is a REAL delay
             expressed wrt the sampling time Ts=1:
               t0_pts = 1 corresponds to one time dot
               t0_pts may be positive, negative, non integer
               t0_pts>0: shift to the right
               t0_pts<0: shift to the left
     Rk: the length of FFT is 2^(nextpow2(N)+1
    """
    #
    # M. Charbit, Jan. 2010
    #==============================================================
    N = len(x)
    p = ceil(log2(N)) + 1
    Lfft = int(2.0**p)
    Lffts2 = Lfft / 2
    fftx = fft(x, Lfft)
    ind = concatenate((range(Lffts2 + 1), range(Lffts2 + 1 - Lfft, 0)), axis=0)
    fftdelay = exp(-2j * pi * t0_pts * ind / Lfft)
    fftdelay[Lffts2] = real(fftdelay[Lffts2])
    ifftdelay = ifft(fftx * fftdelay)
    y = ifftdelay[range(N)]
    if isreal(any(x)):
        y = real(y)
    return y
Example #19
0
def istft(X, size):
    x = np.zeros(size)
    framesamp = X.shape[1]
    hopsamp = framesamp / 2
    for n, i in enumerate(range(0, len(x) - framesamp, hopsamp)):
        x[i:i + framesamp] += scipy.real(scipy.ifft(X[n]))
    return x
Example #20
0
def prob4(filename='saw.wav', new_rate=11025, outfile='prob4.wav'):
    """Down-samples a given .wav file to a new rate and saves the resulting
    signal as another .wav file.
    
    Parameters
    ----------
    filename : string, optional
        The name of the .wav sound file to be down-sampled.
        Defaults to 'saw.wav'.
    new_rate : integer, optional
        The down-sampled rate. Defaults to 11025.
    outfile : string, optional
        The name of the new file. Defaults to prob4.wav.

    Returns
    -------
    None
    """
    old_rate, in_sig = wavfile.read(filename)
    fin = fftw.fft(sp.float32(in_sig))
    # Use if scipy_fftpack is unavailable
    # fin = sp.fft(sp.float32(in_sig))
    nsiz = sp.floor(in_sig.size * new_rate / old_rate)
    nsizh = sp.floor(nsiz / 2)
    fout = sp.zeros(nsiz) + 0j
    fout[0:nsizh] = fin[0:nsizh]
    fout[nsiz - nsizh + 1:] = sp.conj(sp.flipud(fout[1:nsizh]))
    out = sp.real(sp.ifft(fout))
    out = sp.int16(out / sp.absolute(out).max() * 32767)
    plot_signal(filename)
    wavfile.write('prob4.wav', new_rate, out)
    print ""
    plot_signal('prob4.wav')
Example #21
0
def ffacorr(a):
 """Returns the autocorrelation of a. Expects raw data"""
 z=np.zeros(2*len(a))
 z[:len(a)]=a
 fft=sc.fft(z)
 out=sc.ifft(fft*sc.conj(fft))
 return (out[:len(out)/2])
Example #22
0
def HT(y):
	"""
	HT(y)

	Computes the Hilbert transform of the array y using the 
	frequency-domain approach, as in
	http://library2.usask.ca/theses/available/etd-09272006-135609/unrestricted/XianglingWang.pdf, pages 36-37

	For a good transform, the following requirements must be satisfied:
	1. The numbers of zeros and local extrema in y must differ by at most one.
	2. y must be symmetric about zero (i.e. the mean value of the envelopes 
		defined the by the local maxima and minima of y must be zero).
	"""

	from scipy import fft, ifft
	from numpy import zeros_like

	#Take the Fourier transform of the function
	ffty = fft(y)

	#Write as the FFT of the Hilbert transform
	Y = zeros_like(ffty)
	N = len(ffty)
	for i in range(-N/2+1,N/2+1):
		Y[i] = -1j*sgn(i)*ffty[i]

	#Take the inverse Fourier transform
	HT = ifft(Y)

	return HT
Example #23
0
def mmse_stsa(infile, outfile, noise_sum):
    signal, params = read_signal(infile, WINSIZE)
    nf = len(signal)/(WINSIZE/2) - 1
    sig_out=sp.zeros(len(signal),sp.float32)

    G = sp.ones(WINSIZE)
    prevGamma = G
    alpha = 0.98
    window = sp.hanning(WINSIZE)
    gamma15=spc.gamma(1.5)
    lambdaD = noise_sum / 5.0
    percentage = 0
    for no in xrange(nf):
        p = int(math.floor(1. * no / nf * 100))
        if (p > percentage):
            percentage = p
            print "{}%".format(p),

        y = get_frame(signal, WINSIZE, no)
        Y = sp.fft(y*window)
        Yr = sp.absolute(Y)
        Yp = sp.angle(Y)
        gamma = Yr**2/lambdaD
        xi = alpha * G**2 * prevGamma + (1-alpha)*sp.maximum(gamma-1, 0)
        prevGamma = gamma
        nu = gamma * xi / (1+xi)
        G = (gamma15 * sp.sqrt(nu) / gamma ) * sp.exp(-nu/2) * ((1+nu)*spc.i0(nu/2)+nu*spc.i1(nu/2))
        idx = sp.isnan(G) + sp.isinf(G)
        G[idx] = xi[idx] / (xi[idx] + 1)
        Yr = G * Yr
        Y = Yr * sp.exp(Yp*1j)
        y_o = sp.real(sp.ifft(Y))
        add_signal(sig_out, y_o, WINSIZE, no)
    
    write_signal(outfile, params, sig_out)
Example #24
0
 def ApplyFiltersWall(self, data, lowFreq, highFreq, SampleFreq=1250000.0):
     '''Applies FFT software filters.
     In -> Data, lowFreq, highFreq
     Out-> filteredSignal
     
     Warning: Appling a blank wall filter is the same as
     convolving with sinc function!!
     THIS PRODUCES RINGING!!
     '''
     #Perform FFT
     fftsigs=numpy.fft.fft(data)
     fftfreqs = numpy.fft.fftfreq(len(data),1.0/SampleFreq)
     
     
     #Apply blank wall filter by cutting off the unwanted frequencies
     if lowFreq is not None:
         lowfreq_pos =  [i for i,x in enumerate(fftfreqs) if lowFreq-10<=x<=lowFreq+10]
         for i in range(lowfreq_pos[0]):
                 fftsigs[i]=0
         #for i in range(len(fftsigs)):
         #    if abs(fftfreqs[i])<=lowFreq:
         #        fftsigs[i]=0
                 
     if highFreq is not None:
         for i in range(len(fftsigs)):
             if fftfreqs[i]>=highFreq:
                 fftsigs[i]=0
     #Regenerate Signal
     return scipy.ifft(fftsigs, n=len(fftsigs)/2)
Example #25
0
def istft(X, win, step):
    """ ISTFT (Short Term Fourie Transform)

    逆一次元短時間フーリエ変換,stft関数の逆変換を行う

    Args:
        X (ndarray): 入力信号(M x N 行列)
        win (int):   窓関数
        step (int):  シフト幅

    Returns:
        ndarray: 逆変換後の信号(l)
        出力信号の長さ: l = [(M - 1) * step + N]

    """

    M, N = X.shape
    assert len(win) == N, "FFT length and window length are different."

    l = int((M - 1) * step + N)
    x = zeros(l, dtype=float64)
    wsum = zeros(l, dtype=float64)
    for m in range(M):
        start = int(step * m)
        ### 滑らかな接続
        x[start:start + N] = x[start:start + N] + ifft(X[m, :]).real * win
        wsum[start:start + N] += win
    pos = wsum != 0
    x_pre = x.copy()
    ### 窓分のスケール合わせ
    x[pos] /= wsum[pos]
    return x
Example #26
0
def timescale(data, scaling=1):
    """Scales the playback_duration of input_filename, while keeping pitch constant."""
    length = len(data)

    phi = scipy.zeros(N)
    out = scipy.zeros(N, dtype=complex)
    sigout = scipy.zeros(length / scaling + N)

    amplitude = max(data)
    window = scipy.hanning(N)

    for index in scipy.arange(0, length - (N + H), H * scaling):
        spec1 = scipy.fft(window * data[index:index + N])
        spec2 = scipy.fft(window * data[index + H:index + N + H])

        phi += scipy.angle(spec2 / spec1)
        phi %= 2 * scipy.pi

        out.real, out.imag = scipy.cos(phi), scipy.sin(phi)

        out_index = int(index / scaling)
        sigout[out_index:out_index +
               N] += (window * scipy.ifft(scipy.absolute(spec2) * out)).real

    sigout *= amplitude / max(sigout)
    return scipy.array(sigout, dtype='int16')
Example #27
0
def istft(X, fs, T, hop):
    x = scipy.zeros(T * fs)
    framesamp = X.shape[1]
    hopsamp = int(hop * fs)
    for n, i in enumerate(range(0, len(x)-framesamp, hopsamp)):
        x[i:i+framesamp] += scipy.real(scipy.ifft(X[n]))
    return x
Example #28
0
def bandpass_ifft(X, Low_cutoff, High_cutoff, F_sample, M=None):
    """Bandpass filtering on a real signal using inverse FFT
    
    Inputs
    =======
    
    X: 1-D numpy array of floats, the real time domain signal (time series) to be filtered
    Low_cutoff: float, frequency components below this frequency will not pass the filter (physical frequency in unit of Hz)
    High_cutoff: float, frequency components above this frequency will not pass the filter (physical frequency in unit of Hz)
    F_sample: float, the sampling frequency of the signal (physical frequency in unit of Hz)    
    
    Notes
    n=====
    1. The input signal must be real, not imaginary nor complex
    2. The Filtered_signal will have only half of original amplitude. Use abs() to restore. 
    3. In Numpy/Scipy, the frequencies goes from 0 to F_sample/2 and then from negative F_sample to 0. 
    
    """        
    import numpy, scipy
   
    if M == None: # if the number of points for FFT is not specified
        M = X.size # let M be the length of the time series
    
    #Spectrum = scipy.fft(X, n=M) 
    Spectrum = X

    [Low_cutoff, High_cutoff, F_sample] = map(float, [Low_cutoff, High_cutoff, F_sample])
    
    #Convert cutoff frequencies into points on spectrum
    #[Low_point, High_point] = map(lambda F: F/F_sample * M /2, [Low_cutoff, High_cutoff])# the division by 2 is because the spectrum is symmetric 
    [Low_point, High_point] = map(lambda F: F/F_sample * M /1, [Low_cutoff, High_cutoff])# the division by 2 is because the spectrum is symmetric 

    Filtered_spectrum = [Spectrum[i] if i >= Low_point and i <= High_point else 0.0 for i in xrange(M)] # Filtering
    Filtered_signal = scipy.ifft(Filtered_spectrum, n=M)  # Construct filtered signal 
    return Spectrum, Filtered_spectrum, Filtered_signal, Low_point, High_point
Example #29
0
def get_noise_freq_domain_1NSD( P , df , inittime , parityN , seed ) :
    """
    returns the noise time-sereis given the power spectral density
    INPUT:
    P --- power spectral density. numpy array
    df --- frequency resolution
    inittime --- initial time of the noise time-series
    parityN --- is the length of the time-series 'Odd' or 'Even'
    seed --- seed for the noise
    OUPUT:
    t --- time [s]
    n --- noise time-series
    """
    Nf = P.shape[0]
    
    if parityN == 'Odd' :
        N = 2 * Nf + 1
    elif parityN == 'Even' :
        N = 2 * ( Nf + 1 ) 
    else :
        raise InputError , "parityN must be either 'Odd' or 'Even'!"
    stime = 1 / ( N*df )
    t = inittime + stime * np.arange( N )
    
    np.random.seed( seed )
    z = ( np.random.standard_normal( P.shape ) + 1j * np.random.standard_normal( P.shape ) ) / np.sqrt( 2 )

    ntilde_fplus = np.sqrt( N / ( 2*stime ) * P ) * z 

    if N % 2 == 0 :
        ntilde = np.array( [0] + list( ntilde_fplus ) + [0] + list( np.flipud(np.conj(ntilde_fplus)) ) )
    else :
        ntilde = np.array( [0] + list( ntilde_fplus ) + list( np.flipud(np.conj(ntilde_fplus)) ) )
    n = np.real( sp.ifft( ntilde ) )
    return t , n
Example #30
0
def istft(X, fs, T, hop):
    x = scipy.zeros(T * fs)
    framesamp = X.shape[1]
    hopsamp = int(hop * fs)
    for n, i in enumerate(range(0, len(x) - framesamp, hopsamp)):
        x[i:i + framesamp] += scipy.real(scipy.ifft(X[n]))
    return x
Example #31
0
def filter_wav(input_file, output_file = "filtered.wav"):
    """ filters input_file and save resulting data to output_file """
    raw = invert(readwave(input_file))  
    fftr = numpy.fft.fft(raw)  
    fft = fftr[:]  
    fftx= numpy.fft.fftfreq(len(raw), d=(1.0/(rate)))
    
    lowfreq = 58
    highfreq = 62
    lowspectrum = [(lowfreq+(item*60)) for item in range(5)]
    highspectrum = [(highfreq+(item*60)) for item in range(5)]

    fft=bandStop(fft,fftx,0,20)
    fft=bandStop(fft,fftx,-20,0)
    for i in range(5):
         fft = bandStop(fft,fftx,lowspectrum[i],highspectrum[i])
    fft=bandStop(fft,fftx,300,max(fftx))

    fix = scipy.ifft(fft)
    smoothed = Hanning(fix)
    gain = 1.0/max(numpy.absolute(smoothed))
    nsamples = len(smoothed)
    asamples = numpy.zeros(nsamples,dtype=numpy.int16)
    numpy.multiply(smoothed,32767.0 * gain,asamples)
    wavfile.write(output_file,rate,asamples)
Example #32
0
def delayedsignalF(x,t0_pts):
#==============================================================
    """
     Delay a signal with a non integer value
     (computation in frequency domain)
     
     Synopsis:
              y=delayedsignalF(x,t0_pts)
     
     Inputs: x vector of length N
             t0_pts is a REAL delay
             expressed wrt the sampling time Ts=1:
               t0_pts = 1 corresponds to one time dot
               t0_pts may be positive, negative, non integer
               t0_pts>0: shift to the right
               t0_pts<0: shift to the left
     Rk: the length of FFT is 2^(nextpow2(N)+1
    """
    #
    # M. Charbit, Jan. 2010
    #==============================================================
    N         = len(x)
    p         = ceil(log2(N))+1;
    Lfft      = int(2.0**p);
    Lffts2    = Lfft/2;
    fftx      = fft(x, Lfft);
    ind       = concatenate((range(Lffts2+1), 
            range(Lffts2+1-Lfft,0)),axis=0)
    fftdelay  = exp(-2j*pi*t0_pts*ind/Lfft);
    fftdelay[Lffts2] = real(fftdelay[Lffts2]);
    ifftdelay        = ifft(fftx*fftdelay);
    y                = ifftdelay[range(N)];
    if isreal(any(x)):
        y=real(y)
    return y
Example #33
0
def cwt_freq(data, wavelet, widths, dt, axis):
    # compute in frequency
    # next highest power of two for padding
    N = data.shape[axis]
    pN = int(2**np.ceil(np.log2(N)))
    # N.B. padding in fft adds zeros to the *end* of the array,
    # not equally either end.
    fft_data = scipy.fft(data, n=pN, axis=axis)
    # frequencies
    w_k = np.fft.fftfreq(pN, d=dt) * 2 * np.pi

    # sample wavelet and normalise
    norm = (2 * np.pi * widths / dt)**.5
    wavelet_data = norm[:, None] * wavelet(w_k, widths[:, None])

    # Convert negative axis. Add one to account for
    # inclusion of widths axis above.
    axis = (axis % data.ndim) + 1

    # perform the convolution in frequency space
    slices = [slice(None)] + [None for _ in data.shape]
    slices[axis] = slice(None)

    out = scipy.ifft(fft_data[None] * wavelet_data.conj()[slices],
                     n=pN,
                     axis=axis)

    # remove zero padding
    slices = [slice(None) for _ in out.shape]
    slices[axis] = slice(None, N)

    if data.ndim == 1:
        return out[slices].squeeze()
    else:
        return out[slices]
Example #34
0
def violent_multi_band_pass(signal, mask):
    """ A filter that lets you define a bunch of bands:
    everything outside of these frequency ranges gets mercylessly filtered"""
    assert(len(signal) == len(mask))
    f = fft(signal)
    filtered = [mask[i] * f[i] for i in range(len(signal))]
    return scipy.ifft(filtered).real.tolist()
Example #35
0
def denoisedSignals(inputData):
    #IMPORTANT !! needs to be computationnally optimized by using the operations shown in the exercises

    normalizedOutput = np.zeros(inputData.shape)
    numberSamples = (np.array(inputData[:, 0, 0])).size
    numberElectrodes = (np.array(inputData[0, :, 0])).size

    for i in range(0, numberSamples):
        for j in range(0, numberElectrodes):
            signal = np.array(inputData[i, j, :])
            data = np.array(signal)

            fft = scipy.fft(data)  #signal denoising
            bp = fft[:]
            for p in range(len(bp)):
                if p >= 10:
                    bp[p] = 0
            ibp = scipy.ifft(bp)

            #ibp = (ibp-ibp[0])/max(max(ibp), abs(min(ibp))) #signal normalization with initial offset suprresion
            ibp = (ibp - np.mean(ibp)) / np.std(
                ibp)  #signal normalization with initial offset suprresion

            normalizedOutput[i, j, :] = ibp.real
    return normalizedOutput
def istft(X, chunk_size, hop, w=None):
    """
    Naively inverts the short time fourier transform using an overlap and add
    method. The overlap is defined by hop

    Args:
      X: STFT windows to invert, overlap and add. 
      chunk_size: size of analysis window.
      hop: hop distance between analysis windows
      w: windowing function to apply. Must be of length chunk_size

    Returns:
      ISTFT of X using an overlap and add method. Windowing used to smooth.

    Raises:
      ValueError if window w is not of size chunk_size
    """

    if not w:
        w = sp.hanning(chunk_size)
    else:
        if len(w) != chunk_size:
            raise ValueError(
                "window w is not of the correct length {0}.".format(
                    chunk_size))

    x = sp.zeros(len(X) * (hop))
    i_p = 0
    for n, i in enumerate(range(0, len(x) - chunk_size, hop)):
        x[i:i + chunk_size] += w * sp.real(sp.ifft(X[n]))
    return x
Example #37
0
def istft(X, chunk_size, hop, w=None):
    """
    Naively inverts the short time fourier transform using an overlap and add
    method. The overlap is defined by hop

    Args:
      X: STFT windows to invert, overlap and add. 
      chunk_size: size of analysis window.
      hop: hop distance between analysis windows
      w: windowing function to apply. Must be of length chunk_size

    Returns:
      ISTFT of X using an overlap and add method. Windowing used to smooth.

    Raises:
      ValueError if window w is not of size chunk_size
    """

    if not w:
        w = sp.hanning(chunk_size)
    else:
        if len(w) != chunk_size:
            raise ValueError("window w is not of the correct length {0}.".format(chunk_size))

    x = sp.zeros(len(X) * (hop))
    i_p = 0
    for n, i in enumerate(range(0, len(x)-chunk_size, hop)):
        x[i:i+chunk_size] += w*sp.real(sp.ifft(X[n]))
    return x
Example #38
0
def time_mod(arr, factor, win_size=1024, hop=None):
    if not hop:
        hop = float(win_size) * 0.25
    window = np.hanning(win_size)
    stft = [
        fft(window * arr[i:i + win_size])
        for i in range(0,
                       len(arr) - win_size, win_size)
    ]
    if len(stft) < 2:
        raise RuntimeError("Win size too large")
    stft = [(stft[i + 1], stft[i]) for i in range(len(stft) - 1)]
    frames = len(stft)
    omegas = [2 * np.pi * np.arange(len(x[0])) / len(x[0]) for x in stft]
    deltas = [np.angle(x[0]) - np.angle(x[1]) for x in stft]
    unwrapped = [deltas[i] - hop * omegas[i] for i in range(frames)]
    rewrapped = [np.mod(x + np.pi, 2 * np.pi) - np.pi for x in unwrapped]
    freqs = [omegas[i] + rewrapped[i] / hop for i in range(frames)]
    phase_acc = list(
        accumulate(freqs, func=lambda acc, x: acc + x * factor * hop))
    cartesians = [
        np.abs(stft[i][0]) * np.exp(phase_acc[i] * 1j) for i in range(frames)
    ]
    corrected = [window * np.real(ifft(x)) for x in cartesians]
    x = np.zeros(int(len(corrected) * hop * factor))
    print(len(x))
    print(len(corrected * win_size))
    for i, j in enumerate(range(0, len(x) - win_size, int(factor * hop))):
        x[j:j + win_size] += corrected[i]
    return x
Example #39
0
def BarkerLag(rawbeams,
              numtype=sp.complex128,
              pulse=GenBarker(13),
              lagtype=None):
    """This will process barker code data by filtering it with a barker code pulse and
    then sum up the pulses.
    Inputs
        rawbeams - A complex numpy array size NpxNs where Np is the number of pulses and
        Ns is the number of samples.
        numtype - The type of numbers being used for processing.
        pulse - The barkercode pulse.
    Outputs
        outdata- A Nrx1 size numpy array that holds the processed data. Nr is the number
        of range gates  """
    # It will be assumed the data will be pulses vs rangne
    rawbeams = rawbeams.transpose()
    (Nr, Np) = rawbeams.shape
    pulsepow = sp.power(sp.absolute(pulse), 2.0).sum()
    # Make matched filter
    filt = sp.fft(pulse[::-1] / sp.sqrt(pulsepow), n=Nr)
    filtmat = sp.repeat(filt[:, sp.newaxis], Np, axis=1)
    rawfreq = sp.fft(rawbeams, axis=0)
    outdata = sp.ifft(filtmat * rawfreq, axis=0)
    outdata = outdata * outdata.conj()
    outdata = sp.sum(outdata, axis=-1)
    #increase the number of axes
    return outdata[len(pulse) - 1:, sp.newaxis]
def test_fft_function():
    # Many NumPy symbols are imported into the scipy namespace, including
    # numpy.fft.fft as scipy.fft, conflicting with this module (gh-10253)
    import scipy
    scipy.random.seed(1234)

    # Callable before scipy.fft is imported
    x = scipy.randn(10) + 1j * scipy.randn(10)
    y = scipy.ifft(scipy.fft(x))
    assert_allclose(y, x)

    import scipy.fft
    # Callable after scipy.fft is imported
    z = scipy.ifft(scipy.fft(x))
    assert_allclose(z, x)
    assert_allclose(scipy.fft(x), scipy.fft.fft(x))
def wiener_deconvolution(signal, kernel, snr):
    "lambd is the SNR"
    from scipy import fft,ifft
    kernel = np.hstack((kernel, np.zeros(len(signal) - len(kernel)))) # zero pad the kernel to same length
    H = fft(kernel)
    deconvolved = np.real(ifft(fft(signal)*np.conj(H)/(H*np.conj(H) + snr**2)))
    return deconvolved
Example #42
0
def pCodePhaseSearch(sample, LOFreq, PRNSpectrumConjugate):

    """ Search in a given LO freq space all the code phases
        at once

    """

    I, Q, _ = generateIQ(sample.size, LOFreq)

    # mix is down with the LO
    sampledMixedI = sample * I
    sampledMixedQ = sample * Q

    # munge them into a single array of complex numbers for the fft
    combinedMixed = sampledMixedI + 1j*sampledMixedQ

    # do the fft
    signalSpectrum = scipy.fft(combinedMixed)

    # circulator correlation in da frequency space
    correlatedSpectrum = signalSpectrum * PRNSpectrumConjugate

    # and back to time domain
    timeDomainReconstructed = np.abs(scipy.ifft(correlatedSpectrum))**2

    return timeDomainReconstructed
Example #43
0
def IMRpeakAmp(m1,m2,spin1z,spin2z,d):

    """
	IMRpeakAmp finds the peak amplitude of the waveform for a given source parameters and the source distance.
	usage: IMRpeakAmp(m1,m2,spin1z,spin2z,distance)
	e.g.
	spawaveApp.IMRpeakAmp(30,40,0.45,0.5,100)

	"""

    chi = spawaveform.computechi(m1, m2, spin1z, spin2z)   
    imrfFinal = spawaveform.imrffinal(m1, m2, chi, 'fcut')
    fLower = 10.0
    order = 7
    dur = 2**numpy.ceil(numpy.log2(spawaveform.chirptime(m1,m2,order,fLower)))
    sr = 2**numpy.ceil(numpy.log2(imrfFinal*2))
    deltaF = 1.0 / dur
    deltaT = 1.0 / sr
    s = numpy.empty(sr * dur, 'complex128')	
    spawaveform.imrwaveform(m1, m2, deltaF, fLower, s, spin1z, spin2z)
    s = scipy.ifft(s)
    #s = numpy.abs(s)
    s = numpy.real(s)
    max = numpy.max(s)/d
    return max
Example #44
0
def gft1d(signal, windowType):

    N = len(signal)

    # Compute the windows signal
    if (windowType == 'gaussian'):
        windowFct = gaussian
    else:
        raise NotImplemented
        #windowFct = &box

    win = windows(N, windowFct)

    # Do the initial FFT of the signal
    signal = fft(signal, N)

    # Apply the windows
    signal = signal * win

    # For each of the GFT frequency bands
    fstart = 0
    for fend in diadicPartitions(N):

        # frequency band that we're working with : signal[fstart*2:(fstart+fend)]
        # inverse FFT to transform to S-space
        signal[fstart:fend] = ifft(signal[fstart:fend], fend - fstart)

        fstart = fend

    return roll(signal, N / 2)
Example #45
0
def process(signal, low, high):
    spectrum = get_spectrum(signal)
    peak = is_there_a_dart(spectrum, low, high)

    filtered = [0] * BUFFER_SIZE
    for i in range(index_from_freq(peak / FACTOR),index_from_freq(peak * FACTOR)):
        filtered[i] = spectrum[i]
    return scipy.ifft(filtered).real.tolist()
def prob5():
    rate, sig = wavfile.read('tada.wav')
    sig = sp.float32(sig)
    noise = sp.float32(sp.random.randint(-32767, 32767, sig.shape))
    out = sp.ifft(sp.fft(sig) * sp.fft(noise))
    out = sp.real(out)
    out = sp.int16(out / sp.absolute(out).max() * 32767)
    wavfile.write('white-conv.wav', rate, out)
Example #47
0
	def cepstrum(self):
		ms1=self.fs/1000.0;           # maximum speech Fx at 1000Hz
		ms20=self.fs/50.0;            # minimum speech Fx at 50Hz
		xfft=scipy.fft(self.frame);
		x_hat=scipy.ifft(numpy.log(numpy.abs(xfft)+EPS));
		x_hat = numpy.real(x_hat[ms1:ms20]);
		q=scipy.r_[ms1:ms20]/float(self.fs);
		return (q,x_hat)
Example #48
0
def prob5():
	rate, sig = wavfile.read('tada.wav')
	sig = sp.float32(sig)
	noise = sp.float32(sp.random.randint(-32767,32767,sig.shape))
	out = sp.ifft(sp.fft(sig)*sp.fft(noise))
	out = sp.real(out)
	out = sp.int16(out/sp.absolute(out).max() * 32767)
	wavfile.write('white-conv.wav',rate,out)
Example #49
0
def low_pass_fft(curve, low_freqs):
    """Filters the curve by setting to zero the high frequencies"""
    center = len(curve) / 2
    a = scp.fft(curve)
    for i in range(0, center - low_freqs):
        a[center + i] = 0
        a[center - i] = 0
    return scp.array(scp.ifft(a))
Example #50
0
def fft_lowpass_filter(signal, min_period=2):
    """Applies a simple as a log FFT lowpass filter to a signal.

    INPUT:

    - ``signal`` -- a list of data representing the sampled signal;

    - ``min_period`` -- a threshold for the lowpass filter (the minimal period
      of the oscillations which should be left intact) expressed in a number of 
      samples per one full oscillation.

    EXAMPLES:

    If you have a sampling frequency equal to 1 Hz (one sample per second)
    and want to filter out all the frequencies higher than 0.5 Hz (two samples 
    per one oscillation period) you should call this function like this::

        sage: fft_lowpass_filter(signal, min_period=2)

    If you, for example, have a sampling frequency of 1 kHz (1000 samples per 
    second) and wish to filter out all frequencies hihger than 50 Hz, you should
    use the value of ``min_period`` = <sampling frequency> / <cutoff frequency> = 1000 Hz / 50 Hz = 20::

        sage: fft_lowpass_filter(signal, min_period=20)

    """
    import scipy

    signal_fft = scipy.fft(signal)
    spectrum_array_length = len(signal_fft)

    i = 0  # This is used instead of ' for i in range()'
    while i < spectrum_array_length:  # because the 'signal' array can be rather long
        if i >= spectrum_array_length / min_period:
            signal_fft[i] = 0
        i += 1

    signal_filtered = scipy.ifft(signal_fft)

    fft_filtered_signal = []

    filtered_signal_length = len(signal_filtered)
    i = 0
    while i < filtered_signal_length:
        fft_filtered_signal.append(float(signal_filtered[i]))
        i += 1

    norm = max(signal) / max(fft_filtered_signal)  # In case we need

    # to renormalize
    fft_filtered_signal_length = len(
        fft_filtered_signal)  # the filtered signal
    i = 0  # in order to obtain
    while i < fft_filtered_signal_length:  # the same amplitude
        fft_filtered_signal[i] *= norm  # as the inintial
        i += 1  # signal had.

    return fft_filtered_signal
Example #51
0
def prob1():
	rate,data = wavfile.read('Noisysignal2.wav')
	fsig = sp.fft(data,axis = 0)
	f = sp.absolute(fsig)
	plt.plot(f[0:f.shape[0]/2])
	for j in xrange(14020,50001):
		fsig[j]=0
		fsig[-j]=0

	newsig=sp.ifft(fsig)
	f = sp.absolute(fsig)
	plt.figure()
	plt.plot(f[0:f.shape[0]/2])
	plt.show()
	plt.close()
	newsig = sp.ifft(fsig).astype(float)
	scaled = sp.int16(newsig/sp.absolute(newsig).max() * 32767)
	wavfile.write('cleansig2.wav',rate,scaled)
Example #52
0
def istft(X, N):
    """ Transform an array of spectra to the original signal
    """
    framesz = X.shape[1]
    hop = int(float(framesz)/2)
    x = scipy.zeros(N + (2*framesz))
    for n,i in enumerate(range(hop, len(x)-(framesz+hop), hop)):
        x[i:i+framesz] += scipy.real(scipy.ifft(X[n]))
    return x[framesz:-framesz]
Example #53
0
def idct(v,axis=-1):
    n = len(v.shape)
    N = v.shape[axis]
    even = (N%2 == 0)
    slices = [None]*4
    for k in range(4):
        slices[k] = []
        for j in range(n):
            slices[k].append(slice(None))    
    k = arange(N)
    if even:
        ak = scipy.r_[1.0,[2]*(N-1)]*exp(1j*pi*k/(2*N))
        newshape = ones(n)
        newshape[axis] = N
        ak.shape = newshape
        xhat = real(scipy.ifft(v*ak,axis=axis))
        x = 0.0*v
        slices[0][axis] = slice(None,None,2)
        slices[1][axis] = slice(None,N/2)
        slices[2][axis] = slice(N,None,-2)
        slices[3][axis] = slice(N/2,None) 
        for k in range(4):
            slices[k] = tuple(slices[k])
        x[slices[0]] = xhat[slices[1]]
        x[slices[2]] = xhat[slices[3]]
        return x
    else:
        ak = 2*scipy.exp(1j*pi*k/(2*N))
        newshape = ones(n)
        newshape[axis] = N
        ak.shape = newshape
        newshape = list(v.shape)
        newshape[axis] = 2*N
        Y = zeros(newshape,scipy.Complex)
        #Y[:N] = ak*v
        #Y[(N+1):] = conj(Y[N:0:-1])
        slices[0][axis] = slice(None,N)
        slices[1][axis] = slice(None,None)
        slices[2][axis] = slice(N+1,None)
        slices[3][axis] = slice((N-1),0,-1)
        Y[slices[0]] = ak*v
        Y[slices[2]] = conj(Y[slices[3]])
        x = scipy.real(scipy.ifft(Y,axis=axis))[slices[0]]
        return x               
Example #54
0
def spec_interp(coef_spec,factor=1,x1=1.0):
    """Interpolate a function"""

    assert isinstance(factor,int) and factor > 0,\
           "factor must be a positive integer"

    npts = len(coef_spec)
    padded_fft = S.zeros(npts*factor,'D')
    padded_fft[:npts] = coef_spec
    return factor*S.ifft(padded_fft).real
Example #55
0
def _istft(X):
	time_blocks = []
	for block in X:
		num_elems = block.shape[0] / 2
		real_chunk = block[0:num_elems]
		imag_chunk = block[num_elems:]
		new_block = real_chunk + 1.0j * imag_chunk
		time_block = scipy.ifft(new_block)
		time_blocks.append(time_block)
	return np.concatenate(time_blocks)
Example #56
0
    def istft(self, X):
        """
        Apply short-time Fourier transform to X

        Parameters
        ----------
        X     : list of lists or ndArrays
        """
        X = np.array([scipy.real(scipy.ifft(x)) for x in X])
        return X