Exemple #1
0
def GenerateBLI(sampling_rate=48000.0,
                cutoff=15000.0,
                length=4,
                ppiv=2700,
                beta=8.3,
                apodization_factor=0.5,
                apodization_beta=0.5):
    """
    Generates a bandlimited impulse
    """
    kEpsilon = 1e-7
    points_count = ppiv * length
    xaxis = numpy.linspace(0.0, points_count, points_count)
    x2 = length * 2.0 * (xaxis -
                         (points_count) / 2.0 + kEpsilon) / (points_count)
    x3 = numpy.pi * cutoff / sampling_rate * x2

    brickwall_impulse = numpy.sin(x3) / x3

    kaiser_window = numpy.kaiser(points_count, beta)
    bli_data = numpy.transpose(brickwall_impulse) * kaiser_window

    # Apodization
    apodization_window = (1.0 - apodization_factor) \
                            * numpy.kaiser(points_count,apodization_beta)
    bli_data *= apodization_window

    return bli_data
def GenerateBLI(sampling_rate = 48000.0,
                cutoff = 15000.0,
                length = 4,
                ppiv = 2700,
                beta = 8.3,
                apodization_factor = 0.5,
                apodization_beta = 0.5):
    """
    Generates a bandlimited impulse
    """
    kEpsilon = 1e-7
    points_count = ppiv * length
    xaxis = numpy.linspace(0.0, points_count, points_count)
    x2 = length * 2.0 * (xaxis - (points_count) / 2.0 + kEpsilon) / (points_count)
    x3 = numpy.pi * cutoff / sampling_rate * x2

    brickwall_impulse = numpy.sin(x3) / x3

    kaiser_window = numpy.kaiser(points_count, beta)
    bli_data = numpy.transpose(brickwall_impulse) * kaiser_window

    # Apodization
    apodization_window = (1.0 - apodization_factor) \
                            * numpy.kaiser(points_count,apodization_beta)
    bli_data *= apodization_window

    return bli_data
Exemple #3
0
def plot_fourier(t, y, subplotnums=[[2,1,1],[2,1,2]], savedata="none", kaiserwindowparameter=0):
   ''' Function for plotting fourier series of some given arrays t and y
       :param t         time variable (plotted along the x-axis)
       :param y         variable to be plotted along the y-axis
       :subplotnums     subplotnum for plotting multiple plots in one window
   '''
   if len(subplotnums) - 1 != len(np.atleast_1d(kaiserwindowparameter)):
      print "Bad subplotnum vs kaiserwindowparameter"
      return
   # First check the t array whether it has a constant dt
   dt = t[1] - t[0]
   for i in xrange(len(t)-1):
      if dt != t[i+1] - t[i]:
         print "Gave bad timestep to plot_fourier, the time step in array t must be constant (for now)"
   # Use kaiser window on y
   _y = y*np.kaiser(len(y), np.atleast_1d(kaiserwindowparameter)[0])
   # Plot the raw data as well as the fitted data (fourier series)
   pl.subplot(subplotnums[0][0],subplotnums[0][1],subplotnums[0][2])
   pl.plot(t,_y,'.',color='r')
   # Do FFT on the data
   fourier=np.fft.fft(_y)*(1/(float)(len(t)))
   # Get frequencies of the fourier
   freq=np.fft.fftfreq(len(fourier), d=dt)
   # Declare t2 (Note: This is the same as t but we want the steps to be thicker so the data looks smoother
   dt2=dt*0.01
   t2=np.arange(len(t)*100)*dt2
   # Declare y2
   y2=np.array([np.sum(fourier*np.exp(complex(0,1)*2*np.pi*freq*T)) for T in t2])
   pl.plot(t2,y2,'-',color='b')
   pl.legend(["data", "fourier_fit"])
   # Plot the frequency spectrums
   j = 0
   for i in subplotnums[1:]:
      pl.subplot(i[0],i[1],i[2])
      # Use window function on the data
      _y = y*np.kaiser(len(y), np.atleast_1d(kaiserwindowparameter)[j])
      # Do FFT on the data
      fourier=np.fft.fft(_y)*(1/(float)(len(t)))
      # Get frequencies of the fourier
      freq=np.fft.fftfreq(len(fourier), d=dt)
      # Get the indexes:
      toIndex = (int)((len(freq)/2)/2.0 + 1)
      #maxValue = np.max(np.abs(fourier[1:len(fourier)/2]))
      #while True:
      #   if toIndex <= 2 or np.abs(fourier[toIndex-1]) > 0.02*maxValue:
      #      break
      #   toIndex = toIndex - 1
      #pl.plot(freq[1:len(freq)/2],2*np.abs(fourier[1:len(fourier)/2]), marker='.', linestyle='-', linewidth=0.5)
      if savedata != "none":
         saveplotdata( freq[1:toIndex], np.log(2*np.abs(fourier[1:toIndex])), savedata + "_" + str(j) + ".npy" )
      pl.plot(freq[1:toIndex],2*np.abs(fourier[1:toIndex]), marker='.', linestyle='-', linewidth=0.5)
      pl.legend(["frequency_spectrum"])
      pl.ylim([0,1.05*max(2*np.abs(fourier[1:len(fourier)/2]))])
      #pl.xlim([0, 0.13])
      #xTicks = np.arange(14)/100.0
      #pl.xticks(xTicks)
      # Put interactive mode on and show the plot:
      #pl.ion()
      #pl.show()
      j = j + 1
Exemple #4
0
def BM3D1D_S2(noisySignal, basicEstimate):
    finalEstimate = np.zeros(noisySignal.shape, dtype=complex)
    finalWeight = np.zeros(noisySignal.shape, dtype=complex)
    Window = np.array(
        np.kaiser(S2_blocksize, beta) + 1j * np.kaiser(S2_blocksize, beta),
        dtype=complex) / np.sqrt(2)
    finalKaiser = Window

    BlockDCT_noisy = preDCT1D(noisySignal, S2_blocksize)
    BlockDCT_basic = preDCT1D(basicEstimate, S2_blocksize)
    count = 0
    start_ = time.time()
    all_ = int((basicEstimate.shape[0] - S2_blocksize) / S2_DownScale) + 2

    for i in range(
            int((basicEstimate.shape[0] - S2_blocksize) / S2_DownScale) + 2):
        print('i={}; Processing {}% ({}/{}), consuming {} s'.format(
            i, count * 100 / all_, count, all_,
            time.time() - start_))
        RefPoint = min(S2_DownScale * i,
                       basicEstimate.shape[0] - S2_blocksize - 1)
        BlockPos, BlockGroup_basic, BlockGroup_noisy = S2_Grouping1D(
            basicEstimate, noisySignal, RefPoint, S2_blocksize, S2_Threshold,
            S2_MaxMatch, S2_WindowSize, BlockDCT_basic, BlockDCT_noisy)

        BlockGroup_noisy, WienerWeight = S2_2DFiltering(
            BlockGroup_basic, BlockGroup_noisy)
        S2_Aggregation1D(BlockGroup_noisy, WienerWeight, BlockPos,
                         finalEstimate, finalWeight, finalKaiser)
        count += 1

    finalWeight = np.where(finalWeight == 0, 1, finalWeight)
    finalEstimate[:] /= finalWeight[:]
    return finalEstimate
Exemple #5
0
 def make_sense(self,u0):
     st=self.st
     L=numpy.shape(u0)[-1]
     u0dims= numpy.ndim(u0)
     
     rows=numpy.shape(u0)[0]
     cols=numpy.shape(u0)[1]
     # dpss rely on ctypes which are not suitable for cx_freeze 
     #    [dpss_rows, eigens] = spectrum.mtm.dpss(rows, 50, 1)
     #    [dpss_cols, eigens] = spectrum.mtm.dpss(cols, 50, 1)
     dpss_rows = numpy.kaiser(rows, 100)
     dpss_cols = numpy.kaiser(cols, 100)
     
     dpss_rows = numpy.fft.fftshift(dpss_rows)
     dpss_cols = numpy.fft.fftshift(dpss_cols)
     
     dpss_rows = appendmat(dpss_rows,cols)
     dpss_cols  = appendmat(dpss_cols,rows)
     
     
     dpss_fil=dpss_rows*dpss_cols.T # low pass filter
     
     rms=numpy.sqrt(numpy.mean(u0*u0.conj(),-1)) # Root of sum square
     st['sensemap']=numpy.ones(numpy.shape(u0),dtype=numpy.complex64)
     
     #    print('L',L)
     #    print('rms',numpy.shape(rms))
     for ll in numpy.arange(0,L):
         st['sensemap'][:,:,ll]=(u0[:,:,ll]+1e-15)/(rms+1e-15)
         st['sensemap'][:,:,ll]=scipy.fftpack.ifft2(scipy.fftpack.fft2(st['sensemap'][:,:,ll])*dpss_fil)
     return st
Exemple #6
0
def update_properties(sample_rate, number_of_samples, number_of_averages):
    '''Send a control signal to the MCU to change the sample rate or number
    of samples'''
    global window_map, freq_axis, freq_mag_history

    if int(sample_rate) != adc.sample_rate or int(
            number_of_samples) != adc.number_of_samples:
        # Requires board reset so only do if necessary.
        status_reg_f = '\n'.join(
            adc.modify_sample_properties(sample_rate, number_of_samples))
        # rebuild the window map
        window_map = {
            'rect': [1] * adc.number_of_samples,
            'blackman': np.blackman(adc.number_of_samples),
            'kaiser5': np.kaiser(adc.number_of_samples, 5 * np.pi),
            'kaiser7': np.kaiser(adc.number_of_samples, 7 * np.pi),
        }
        # Get, format, and log the status register.
        logging.info(status_reg_f)

    # set the size of the history deque, and in the process clear it..
    freq_mag_history = deque(maxlen=number_of_averages)

    # Create a new frequency axis.
    freq_axis = np.fft.rfftfreq(n=adc.number_of_samples, d=1 / adc.sample_rate)

    return ''
Exemple #7
0
def window_kaiser(N, fade_in, fade_out, fs, beta=3):

    L, M, n_ones = fade_vector_arange(N, fade_in, fade_out, fs)

    w1 = np.kaiser(L, beta)[:L / 2]
    w2 = np.ones(len(n_ones))
    w3 = np.kaiser(M, beta)[M / 2:M]
    return np.concatenate((w1, w2, w3))
Exemple #8
0
    def test_kaiser_1(self):

        a = np.kaiser(12, 14)
        print(a)

        a = np.kaiser(3, 5)
        print(a)

        return
Exemple #9
0
def main():

    x = np.zeros(500)
    x[100:150] = 1

    X = fftpack.fft(x)

    f, (ax0, ax1) = plt.subplots(2, 1, sharex=True)

    ax0.plot(x)
    ax0.set_ylim(-0.1, 1.1)

    ax1.plot(fftpack.fftshift(np.abs(X)))
    ax1.set_ylim(-5, 55)
    plt.show()

    t = np.linspace(0, 1, 500)
    x = np.sin(10 * np.pi * t)

    X = fftpack.fft(x)

    f, (ax0, ax1) = plt.subplots(2, 1)

    ax0.plot(x)
    ax0.set_ylim(-1.1, 1.1)

    ax1.plot(fftpack.fftfreq(len(t)), np.abs(X))
    ax1.set_ylim(0, 190)
    plt.show()

    f, ax = plt.subplots()

    N = 10
    beta_max = 5
    colormap = plt.cm.plasma

    norm = plt.Normalize(vmin=0, vmax=beta_max)

    lines = [
        ax.plot(np.kaiser(100, beta), color=colormap(norm(beta)))
        for beta in np.linspace(0, beta_max, N)
    ]

    sm = plt.cm.ScalarMappable(cmap=colormap, norm=norm)

    sm._A = []

    plt.colorbar(sm).set_label(r'Kaiser $\beta$')
    plt.show()

    win = np.kaiser(len(t), 5)
    X_win = fftpack.fft(x * win)

    plt.plot(fftpack.fftfreq(len(t)), np.abs(X_win))
    plt.ylim(0, 190)
    plt.show()
Exemple #10
0
    def _kaiser_window(self, width, beta):
        """
        Generates a kaiser window

        beta Window shape
        0    Rectangular
        5    Similar to a Hamming
        6    Similar to a Hann
        8.6  Similar to a Blackman
        """
        return np.kaiser(width[0], beta).reshape((-1,1,1)) * np.kaiser(width[1], beta).reshape((-1,1)) * np.kaiser(width[2], beta)
Exemple #11
0
def window(img, beta):
    win = np.outer(np.kaiser(img.shape[0], beta),
                   np.kaiser(img.shape[1], beta))
    img = np.fft.fftshift(img)
    img = np.fft.fft2(img)
    img = np.fft.ifftshift(img)
    img = win * img
    img = np.fft.ifftshift(img)
    img = np.fft.ifft2(img)
    img = np.fft.fftshift(img)
    return np.abs(img)
Exemple #12
0
    def _kaiser_window(self, width, beta):
        """
        Generates a kaiser window

        beta Window shape
        0    Rectangular
        5    Similar to a Hamming
        6    Similar to a Hann
        8.6  Similar to a Blackman
        """
        return np.kaiser(width[0], beta).reshape(
            (-1, 1, 1)) * np.kaiser(width[1], beta).reshape(
                (-1, 1)) * np.kaiser(width[2], beta)
Exemple #13
0
 def smooth(self,
            x=0,
            y=0,
            window='kaiser',
            debug=False):  #smoothes via adjacent averaging
     """
         convolves the signal with a 2D window function
         currently only equipped for kaiser window
         'x' and 'y', both integers, are the nth nearest neighbor that get 
             included in the window
         Decide whether to perform xaxis smoothing or yaxis by setting the 
             boolean true
     """
     # n is the seed of the odd numbers:  n is how many nearest neighbors
     # in each direction
     # make sure n is integer and n < grid dimension
     # account for interpolation using grid factor
     nx = x
     ny = y
     # create the window function
     if window == 'kaiser':
         # beta, a real number, is a form parameter of the kaiser window
         # beta = 5 makes this look approximately gaussian in weighting
         # beta = 5 similar to Hamming window, according to numpy
         # over window (about 0 at end of window)
         beta = 5.0
         wx = np.kaiser(2 * nx + 1, beta)
         wy = np.kaiser(2 * ny + 1, beta)
     # for a 2D array, y is the first index listed
     w = np.zeros((len(wy), len(wx)))
     for i in range(len(wy)):
         for j in range(len(wx)):
             w[i, j] = wy[i] * wx[j]
     # create a padded array of zi
     # numpy 1.7.x required for this to work
     temp_z = np.pad(self.zi, ((ny, ny), (nx, nx)), mode='edge')
     from scipy.signal import convolve
     out = convolve(temp_z, w / w.sum(), mode='valid')
     if debug:
         plt.figure()
         sp1 = plt.subplot(131)
         plt.contourf(self.zi, 100)
         plt.subplot(132, sharex=sp1, sharey=sp1)
         plt.contourf(w, 100)
         plt.subplot(133)
         plt.contourf(out, 100)
     self.z = out
     # reset zmax
     self.zmax = self.z.max()
     self.zmin = self.z.min()
Exemple #14
0
def periodogram(x,y,z,t,name):
    vel=x*x+y*y
    components=[vel,z*z]
    F=[]
    A=[]

    for i in range(0,len(components)):
        window=np.kaiser(components[i].shape[-1],5)
        vel=components[i]*window
        f,a=DO_FFT(vel,20)
        F.append(f)
        A.append(a)

    
    plt.figure(1,figsize=(11,7))
    plt.title("Spectral Gap - LiCor Fontanella1 Precampagna")
    plt.subplot(121)
    plt.title("FFT horizontal velocity")
    plt.xlabel("Frequency [Hz]")
    plt.ylabel("Power Spectrum [dB]")
    plt.loglog(F[0],A[0],'k', markersize=0.1)

    plt.subplot(122)
    plt.title("FFT vertical velocity")
    plt.xlabel("Frequency [Hz]")
    plt.ylabel("Power Spectrum [dB]")
    plt.loglog(F[1],A[1],'r',markersize=0.1)

    try:
        plt.savefig("graph/"+name+"_FFT.png", figuresize=(8,6), dpi=320, format="png")
        print_ok("Graph saved in: "+"graph/"+name+"_FFT.png")
    except IOError as IoE:
        print_fail("I/O Error! Erro number = {0}; {1}".format(IoE.errno,IoE.strerror))
        exit(IoE.errno)
Exemple #15
0
def plotWindowFunc():
	plt.clf()
	plt.plot(np.arange(20), np.kaiser(20,3.5))
	plt.plot(np.arange(20), np.bartlett(20))
	plt.plot(np.arange(20), np.blackman(20))
	plt.plot(np.arange(20), np.hamming(20))
	plt.plot(np.arange(20), np.hanning(20))
Exemple #16
0
def main():
    import sys
    from scipy import misc
    softness = 2
    r_scale = 3
    windowmaker = lambda x: np.kaiser(x, softness)
    for infilename in sys.argv[1:]:
        print("File: %s" % infilename)
        array = misc.imread(infilename)
        circles = get_circles(array, 5)
        l_pnoise, l_order, c_order, r_order, r_pnoise = circles

        window = get_holed_window(windowmaker, l_order[2] * r_scale, 10)
        mask = get_mask(array.shape, window, l_order[1])
        window = windowmaker(l_pnoise[2] * r_scale)
        mask *= 1 - get_mask(array.shape, window, l_pnoise[1])
        window = windowmaker(c_order[2] * r_scale)
        mask *= 1 - get_mask(array.shape, window, c_order[1])
        #        showimage(mask * 255)
        #        showimage(logscale(mask * array))

        window = get_holed_window(windowmaker, r_order[2] * r_scale, 10)
        mask = get_mask(array.shape, window, r_order[1])
        window = windowmaker(r_pnoise[2] * r_scale)
        mask *= 1 - get_mask(array.shape, window, r_pnoise[1])
        window = windowmaker(c_order[2] * r_scale)
        mask *= 1 - get_mask(array.shape, window, c_order[1])
 def signal_filter(self, channel, freqs=(1, 15)):
     """Filter signal from specific channel. A FFT is performed in
     the signal, and the result is multiplied by a window function
     (kaiser function), which nulls the undesired beating
     frequencies, that are outside of 'freqs'. The signal is then
     recreated with an IFFT."""
     # zero padding size:
     zer_pad_filter = 4
     # alias for sweep_size
     N = int(self.sweep_size)
     # FFT with zero padding
     fft = np.fft.rfft(self.single_sweep_data[channel], zer_pad_filter * N)
     # bp=fft[:] #used for other plot functions
     fmin, fmax = freqs
     # creates the beating frequency axis, and finds the position of
     # the frequency limits in the axis
     fft_freq = np.linspace(0, self.rate / 2., num=zer_pad_filter * N / 2)
     cmin = (abs(fft_freq - fmin)).argmin()
     cmax = (abs(fft_freq - fmax)).argmin()
     # creates window function for filter. Second argument of kaiser
     # function must be float
     window_func = np.concatenate(
         (np.zeros(cmin + 1), np.kaiser(cmax - cmin, 2.),
          np.zeros(zer_pad_filter * N / 2 - cmax)))
     # multiply the window by the signal's FFT.
     bp = np.multiply(fft, window_func)
     # Since the signal is REAL, we use IRFFT, and takes only the
     # first half, since the other half is symmetric.
     newsig = np.fft.irfft(bp)[:N]
     return newsig
Exemple #18
0
def get_kaiserWindow(kHW):
    '''
        返回kaiser窗
    '''
    k = np.kaiser(kHW, 2)
    k_2d = k[:, np.newaxis] @ k[np.newaxis, :]
    return k_2d
Exemple #19
0
def test_snr(param, freq):
    """Test the SNR using a test tone at the given frequency.

    This works by computing the FFT of the result, zeroing the FFT
    corresponding to the test tone, and comparing the signal power
    with the signal power of the output signal.  Returns the SNR ratio
    (as a ratio, not dB).
    """
    w = 2 * math.pi * freq / param.RATE_IN
    length = param.TEST_LENGTH
    beta = param.TEST_BETA
    indata = (0.5 * numpy.sin(w * numpy.arange(length, dtype='float64')))
    outdata = resample_arr(param, indata)
    window = numpy.kaiser(len(outdata), beta)
    outdata *= window
    fft = numpy.fft.rfft(outdata)

    nbins = NBINS
    fbin = round(freq * len(outdata) / param.RATE_OUT)
    bin0 = min(max(fbin - nbins / 2, 0), len(fft))
    bin1 = min(max(fbin - nbins / 2 + nbins, 0), len(fft))
    fft[bin0:bin1] = 0
    noise = numpy.std(fft) / math.sqrt(len(outdata))
    signal = numpy.average(window)

    return signal / noise
Exemple #20
0
def Myfft(df,time,value,windowname,dst,feature,count):
  ## Add time interpolate
  x = time - time[0]
  y = value
  x_new = np.arange(x[0],x[0]+x[len(x)-1],dst)
  f = interpolate.interp1d(x,y,kind='slinear')
  #'linear', 'nearest', 'zero', 'slinear', 'quadratic', 'cubic'
  y_new = f(x_new)
  # 采样率
  Fs = len(x_new)/x_new[len(x_new)-1]
  # 添加自定义噪声
  nx = np.linspace(0,x[len(x)-1],x[len(x)-1]*1/dst) #100采样率
  sinu1 = 8*np.cos(2*np.pi*0.3*Fs*nx-np.pi*30/180) 
  sinu2 = 5*np.cos(2*np.pi*0.2*Fs*nx-np.pi*30/180)
  noise = sinu1 + sinu2
  y_new = y_new + noise
  # 数据长度
  L = len(x_new)
  # 删减数据为fft做准备
  NFFT = int(math.pow(2,ceillog2(L+1)-1))
  use_y = y_new[0:NFFT] 
  windowdata = 0
  if windowname == 'Hamming':
    windowdata = np.hamming(NFFT)
  elif windowname == 'Kaiser': #需要两个输入参数
    windowdata = np.kaiser(NFFT)
  elif windowname == 'Blackman':
    windowdata = np.blackman(NFFT)
  elif windowname == 'Hanning':
    windowdata = np.hanning(NFFT)
  else:
    windowdata = np.ones(1,NFFT)
  use_y = use_y*windowdata
  # fft
  Y = np.fft.fft(use_y,n=NFFT)/NFFT
  Y = 2*abs(Y[0:NFFT/2+1])
  f = np.linspace(0,Fs/2,NFFT/2+1)
  [Pxx,F] = plt.psd(use_y,NFFT=NFFT,Fs = Fs)
  col = []
  for columns in df:
    col.append(columns)
  sta = df.iloc[:,1:2].describe()  #只分析前一列。可修改
  sta.loc['range'] = sta.loc['max']-sta.loc['min']#极差
  sta.loc['var'] = sta.loc['std']/sta.loc['mean']#变异系数
  sta.loc['dis'] = sta.loc['75%']-sta.loc['25%']#四分位数间距
  sta.loc['peak']=time_feature.peak(use_y)
  sta.loc['rms']=time_feature.rms(use_y)
  sta.loc['pfactor']=time_feature.pfactor(use_y)
  sta.loc['kfactor']=time_feature.kfactor(use_y)
  sta.loc['pulse']=time_feature.pulse(use_y)
  sta.loc['margin']=time_feature.margin(use_y)
  sta.loc['waveform']=time_feature.waveform(use_y)
  sta.loc['sqa']=time_feature.sqa(use_y)
  sta.loc['absma']=time_feature.absma(use_y)
  sta.loc['skewness']=time_feature.skewness(use_y)
  sta.loc['kurtosis']=time_feature.kurtosis(use_y)
  sta.loc['controid_f']=freq_feature.centroid_f(Pxx,F)
  sta.loc['f_variance']=freq_feature.f_variance(Pxx,F)
  sta.loc['ms_f']=freq_feature.ms_f(Pxx,F)
  feature['Speed%d'%(count)] = sta['Speed']
Exemple #21
0
def _resample_window_oct(p, q):
    """Port of Octave code to Python"""

    gcd = np.gcd(p, q)
    if gcd > 1:
        p /= gcd
        q /= gcd

    # Properties of the antialiasing filter
    log10_rejection = -3.0
    stopband_cutoff_f = 1. / (2 * max(p, q))
    roll_off_width = stopband_cutoff_f / 10

    # Determine filter length
    rejection_dB = -20 * log10_rejection
    L = np.ceil((rejection_dB - 8) / (28.714 * roll_off_width))

    # Ideal sinc filter
    t = np.arange(-L, L + 1)
    ideal_filter = 2 * p * stopband_cutoff_f \
        * np.sinc(2 * stopband_cutoff_f * t)

    # Determine parameter of Kaiser window
    if (rejection_dB >= 21) and (rejection_dB <= 50):
        beta = 0.5842 * (rejection_dB - 21)**0.4 \
            + 0.07886 * (rejection_dB - 21)
    elif rejection_dB > 50:
        beta = 0.1102 * (rejection_dB - 8.7)
    else:
        beta = 0.0

    # Apodize ideal filter response
    h = np.kaiser(2 * L + 1, beta) * ideal_filter

    return h
Exemple #22
0
def kaiser(x, width=None, weights=None, do_fit_edges=False):
    """Smooth the values in `x` with the Kaiser windowed filter.

    See: https://en.wikipedia.org/wiki/Kaiser_window

    Parameters
    ----------
    x : array-like
        1-dimensional numeric data set.
    width : float
        Fraction of x's total length to include in the rolling window (i.e. the
        proportional window width), or the integer size of the window.
    """
    if len(x) < 2:
        return x
    if width is None:
        width = guess_window_size(x, weights)
    x, wing, signal = check_inputs(x, width, False)
    # Apply signal smoothing
    window = np.kaiser(2 * wing + 1, 14)
    if weights is not None:
        y, _w = convolve_weighted(window, signal, weights)
    else:
        y = convolve_unweighted(window, signal, wing)
    if do_fit_edges:
        _fit_edges(x, y, wing)  # In-place
    return y
def init(img, _blk_size, _Beta_Kaiser):
    m_shape = img.shape
    m_img = numpy.matrix(numpy.zeros(m_shape, dtype=float))
    m_wight = numpy.matrix(numpy.zeros(m_shape, dtype=float))
    K = numpy.matrix(numpy.kaiser(_blk_size, _Beta_Kaiser))
    m_Kaiser = numpy.array(K.T * K)
    return m_img, m_wight, m_Kaiser
Exemple #24
0
def kaiser(active):
    """Kaiser tapering window."""
    idx = _windowidx(active)
    # compute coefficients
    window = np.zeros(active.shape)
    window[idx] = np.kaiser(len(idx), 2)
    return window
 def create_windowing_function(
         self,
         a_len: int,
         key='hann',
         sigma: int = None,
         is_show_info_prints: bool = False) -> np.ndarray:
     """ Creates a real-valued (float64) vector for i.e. spectrally shaping an A-scan """
     if sigma is None:
         sigma = a_len // 10
     if key.lower() == 'hann':
         return np.asarray(np.hanning(a_len))
     elif key.lower() == 'hamm':
         if is_show_info_prints:
             print("[INFO:] Using Hamming-Window - not Hanning-window")
         return np.asarray(np.hamming(a_len))
     elif key.lower() == 'kaiser':
         if is_show_info_prints:
             print("[INFO:] Using Kaiser-Window - not Hanning-window")
         return np.asarray(np.kaiser(a_len, beta=sigma))
     elif key.lower() == 'gauss':
         if is_show_info_prints:
             print("[INFO:] Using Gaussian-Window - not Hanning-window")
         return np.asarray(signal.gaussian(a_len, sigma))
     else:
         raise ValueError(
             "You have passed an unrecognized key for the windowing-parameter"
         )
Exemple #26
0
def tunedhps(x,
             fs=44100,
             lf=255,
             harmonics=3,
             precision=1,
             window=lambda x: _np.kaiser(x, 7.14285)):
    """ Estimates the pitch (fundamental frequency) of the given sample array by an HPS implementation that evaluates
        the spectrum only in tuned note frequencies (e.g. frequencies of notes in an assumed tuning). """
    x -= _np.mean(x)
    N = x.size
    w = x * window(N)

    if fs / N > precision:
        delta = int(fs / precision) - N
        w = _np.append(w, _np.zeros(delta))
        N = w.size

    frequencies = [
        f for f in _mt.notes if f >= lf and f < fs / (2 * harmonics)
    ]

    X = _np.log(_np.abs(_np.fft.rfft(w)))
    Y = _np.ones(len(frequencies))
    for i in range(0, len(frequencies)):
        for h in range(1, harmonics + 1):
            f_idx = int(round(frequencies[i] * h / 2) * 2 * N / fs)
            Y[i] += X[f_idx] * (0.9**(h - 1))

    arg_peak = _np.argmax(Y)
    return frequencies[arg_peak]
Exemple #27
0
def sfdr(x, fs):  # attempt of a python version of MATLABs sfdr function
    xw = x * np.kaiser(len(x), beta=38) / len(x)
    xw -= np.mean(xw)
    Y = np.fft.rfft(xw)
    freqs = np.fft.rfftfreq(len(xw), d=1.0 / fs)
    mag = np.abs(Y)
    YdB = 20 * np.log10(mag)
    peakind = find_peaks(YdB, distance=5)
    pksf = freqs[peakind[0]]
    pksY = YdB[peakind[0]]
    isorted = np.argsort(pksY)
    sfdrval = pksY[isorted[-1]] - pksY[isorted[-2]]
    #fig, ax = plt.subplots()
    ax = plt.gca()
    pkfa = pksf[isorted[-1]]
    pkYa = pksY[isorted[-1]]
    pkfb = pksf[isorted[-2]]
    pkYb = pksY[isorted[-2]]
    plt.fill_between((0, fs / 2), (pkYb, pkYb), (pkYa, pkYa),
                     label='SFDR',
                     color="lightblue")
    ax.plot(pkfa, pkYa, marker="s", label='fundamental')
    ax.plot(pkfb, pkYb, marker="s", label='spurs')
    ax.plot(freqs, YdB)
    ax.set(xlabel='Frequency (Hz)',
           ylabel='Power (dB)',
           title="SFDR %.2f dB" % sfdrval)
    ax.set_xlim(0, fs / 2)
    ax.set_ylim(-400, 10)
    ax.legend(loc="upper right")
    return sfdrval
Exemple #28
0
def main():
    import sys
    from scipy import misc
    softness = 2
    r_scale = 3
    windowmaker = lambda x: np.kaiser(x, softness)
    for infilename in sys.argv[1:]:
        print("File: %s" % infilename)
        array = misc.imread(infilename)
        circles = get_circles(array, 5)
        l_pnoise, l_order, c_order, r_order, r_pnoise = circles

        window = get_holed_window(windowmaker, l_order[2] * r_scale, 10)
        mask = get_mask(array.shape, window, l_order[1])
        window = windowmaker(l_pnoise[2] * r_scale)
        mask *= 1 - get_mask(array.shape, window, l_pnoise[1])
        window = windowmaker(c_order[2] * r_scale)
        mask *= 1 - get_mask(array.shape, window, c_order[1])
#        showimage(mask * 255)
#        showimage(logscale(mask * array))

        window = get_holed_window(windowmaker, r_order[2] * r_scale, 10)
        mask = get_mask(array.shape, window, r_order[1])
        window = windowmaker(r_pnoise[2] * r_scale)
        mask *= 1 - get_mask(array.shape, window, r_pnoise[1])
        window = windowmaker(c_order[2] * r_scale)
        mask *= 1 - get_mask(array.shape, window, c_order[1])
def resample(s, p, q, h=None):
    """Change sampling rate by rational factor. This implementation is based on
    the Octave implementation of the resample function. It designs the 
    anti-aliasing filter using the window approach applying a Kaiser window with
    the beta term calculated as specified by [2].
    
    Ref [1] J. G. Proakis and D. G. Manolakis,
    Digital Signal Processing: Principles, Algorithms, and Applications,
    4th ed., Prentice Hall, 2007. Chap. 6
    Ref [2] A. V. Oppenheim, R. W. Schafer and J. R. Buck, 
    Discrete-time signal processing, Signal processing series,
    Prentice-Hall, 1999
    """
    gcd = fractions.gcd(p,q)
    if gcd>1:
        p=p/gcd
        q=q/gcd
    
    if h is None: #design filter
        #properties of the antialiasing filter
        log10_rejection = -3.0
        stopband_cutoff_f = 1.0/(2.0 * max(p,q))
        roll_off_width = stopband_cutoff_f / 10.0
    
        #determine filter length
        #use empirical formula from [2] Chap 7, Eq. (7.63) p 476
        rejection_db = -20.0*log10_rejection;
        l = numpy.ceil((rejection_db-8.0) / (28.714 * roll_off_width))
  
        #ideal sinc filter
        t = numpy.arange(-l, l + 1)
        ideal_filter=2*p*stopband_cutoff_f*numpy.sinc(2*stopband_cutoff_f*t)  
  
        #determine parameter of Kaiser window
        #use empirical formula from [2] Chap 7, Eq. (7.62) p 474
        beta = signal.kaiser_beta(rejection_db)
          
        #apodize ideal filter response
        h = numpy.kaiser(2*l+1, beta)*ideal_filter

    ls = len(s)
    lh = len(h)

    l = (lh - 1)/2.0
    ly = numpy.ceil(ls*p/float(q))

    #pre and postpad filter response
    nz_pre = numpy.floor(q - numpy.mod(l,q))
    hpad = h[-lh+nz_pre:]

    offset = numpy.floor((l+nz_pre)/q)
    nz_post = 0;
    while numpy.ceil(((ls-1)*p + nz_pre + lh + nz_post )/q ) - offset < ly:
        nz_post += 1
    hpad = hpad[:lh + nz_pre + nz_post]

    #filtering
    xfilt = upfirdn(s, hpad, p, q)

    return xfilt[offset-1:offset-1+ly]
 def signal_filter(self, channel, freqs=(1, 15)):
     """Filter signal from specific channel. A FFT is performed in
     the signal, and the result is multiplied by a window function
     (kaiser function), which nulls the undesired beating
     frequencies, that are outside of 'freqs'. The signal is then
     recreated with an IFFT."""
     # zero padding size:
     zer_pad_filter = 4
     # alias for sweep_size
     N = int(self.sweep_size)
     # FFT with zero padding
     fft = np.fft.rfft(self.single_sweep_data[channel], zer_pad_filter * N)
     # bp=fft[:] #used for other plot functions
     fmin, fmax = freqs
     # creates the beating frequency axis, and finds the position of
     # the frequency limits in the axis
     fft_freq = np.linspace(0, self.rate  / 2.,
                            num=zer_pad_filter * N / 2)
     cmin = (abs(fft_freq - fmin)).argmin()
     cmax = (abs(fft_freq - fmax)).argmin()
     # creates window function for filter. Second argument of kaiser
     # function must be float
     window_func = np.concatenate((np.zeros(cmin + 1),
                                   np.kaiser(cmax - cmin, 2.), np.zeros(zer_pad_filter * N / 2 - cmax)))
     # multiply the window by the signal's FFT.
     bp = np.multiply(fft, window_func)
     # Since the signal is REAL, we use IRFFT, and takes only the
     # first half, since the other half is symmetric.
     newsig = np.fft.irfft(bp)[:N]
     return newsig
Exemple #31
0
    def lowpass_filter(self,x,width):
        #wndw = np.sinc(np.r_[-15:16]/np.pi)/np.pi
        wndw = np.kaiser(width,6)
        wndw /= np.sum(wndw)
        new_array = signal.fftconvolve(x, wndw)

        return new_array[int(width/2):x.size+int(width/2)]
Exemple #32
0
def smooth(x,beta):
    """ kaiser window smoothing """
    window_len=11
    s = numpy.r_[x[window_len-1:0:-1],x,x[-1:-window_len:-1]]
    w = numpy.kaiser(window_len,beta)
    y = numpy.convolve(w/w.sum(),s,mode='valid')
    return y[5:len(y)-5]
Exemple #33
0
def fourier_array(t, y, kaiserwindowparameter=0):
    ''' Function for returning fourier series of some given arrays t and y
       :param t         time variable (along the x-axis)
       :param y         variable along the y-axis
       :returns         numpy array of the fourier series [t2, y2] and frequency [freq]: np.array([t2,y2], freq)
   '''
    # First check the t array whether it has a constant dt
    dt = t[1] - t[0]
    for i in range(len(t) - 1):
        if dt != t[i + 1] - t[i]:
            print(
                "Gave bad timestep to plot_fourier, the time step in array t must be constant (for now)"
            )
    # Use kaiser window on y
    y = y * np.kaiser(len(y), kaiserwindowparameter)
    # Do FFT on the data
    fourier = np.fft.fft(y) * (1 / (float)(len(t)))
    # Get frequencies of the fourier
    freq = np.fft.fftfreq(len(fourier), d=dt)
    # Declare t2 (Note: This is the same as t but we want the steps to be thicker so the data looks smoother
    dt2 = dt * 0.01
    t2 = np.arange(len(t) * 100) * dt2
    # Declare y2
    y2 = np.array([
        np.sum(fourier * np.exp(complex(0, 1) * 2 * np.pi * freq * T))
        for T in t2
    ])
    return np.array([[t2, y2], freq])
Exemple #34
0
def single_taper_spectrum(data, delta, taper_name=None):
    """
    Returns the spectrum and the corresponding frequencies for data with the
    given taper.
    """
    length = len(data)
    good_length = length // 2 + 1
    # Create the frequencies.
    # XXX: This might be some kind of hack
    freq = abs(np.fft.fftfreq(length, delta)[:good_length])
    # Create the tapers.
    if taper_name == 'bartlett':
        taper = np.bartlett(length)
    elif taper_name == 'blackman':
        taper = np.blackman(length)
    elif taper_name == 'boxcar':
        taper = np.ones(length)
    elif taper_name == 'hamming':
        taper = np.hamming(length)
    elif taper_name == 'hanning':
        taper = np.hanning(length)
    elif 'kaiser' in taper_name:
        taper = np.kaiser(length, beta=14)
    # Should never happen.
    else:
        msg = 'Something went wrong.'
        raise Exception(msg)
    # Detrend the data.
    data = detrend(data)
    # Apply the taper.
    data *= taper
    spec = abs(np.fft.rfft(data)) ** 2
    return spec, freq
Exemple #35
0
def test_snr(param, freq):
    """Test the SNR using a test tone at the given frequency.

    This works by computing the FFT of the result, zeroing the FFT
    corresponding to the test tone, and comparing the signal power
    with the signal power of the output signal.  Returns the SNR ratio
    (as a ratio, not dB).
    """
    w = 2 * math.pi * freq / param.RATE_IN
    length = param.TEST_LENGTH
    beta = param.TEST_BETA
    indata = (
        0.5 * numpy.sin(w * numpy.arange(length, dtype='float64')))
    outdata = resample_arr(param, indata)
    window = numpy.kaiser(len(outdata), beta)
    outdata *= window
    fft = numpy.fft.rfft(outdata)

    nbins = NBINS
    fbin = round(freq * len(outdata) / param.RATE_OUT)
    bin0 = min(max(fbin-nbins/2, 0), len(fft))
    bin1 = min(max(fbin-nbins/2 + nbins, 0), len(fft))
    fft[bin0:bin1] = 0
    noise = numpy.std(fft) / math.sqrt(len(outdata))
    signal = numpy.average(window)

    return signal / noise
Exemple #36
0
 def fft_1d(self, window_length=1000, n_offset=0, padding_ratio=0, window=None, beta=None):
     '''
     simply calculate the 1D fast Fourier transform of the provided signal in a least intervened way
     window_length:  length of the tapering window
     n_offset:       number of IQ pairs to be skipped over
     padding_ratio:  >= 1, ratio of the full frame length after zero padding to the window length
                     note that the final frame length will be rounded up to the next power of base 2
                     any illegal values disable zero padding
     window:         to be chosen from ["bartlett", "blackman", "hamming", "hanning", "kaiser"]
                     if None, a rectangular window is implied
                     if "kaiser" is given, an additional argument of beta is expected
     '''
     # handling various windows
     if window is None:
         window_sequence = np.ones(window_length)
     elif window == "kaiser":
         if beta is None:
             raise ValueError("additional argument beta is empty!")
         else:
             window_sequence = np.kaiser(window_length, beta)
     else:
         window_function = getattr(np, window)
         window_sequence = window_function(window_length)
     # round the padded frame length up to the next radix-2 power
     n_point = int( np.power(2, np.ceil(np.log2(window_length*padding_ratio))) ) if padding_ratio >= 1 else window_length
     # build the frequency sequence
     frequencies = np.linspace(-self.sampling_rate/2, self.sampling_rate/2, n_point+1)[:-1] # Hz
     if n_point % 2 == 1: frequencies += self.sampling_rate / (2*n_point)
     # load the data, apply the window function
     signal = super().load(window_length, n_offset)[1] * window_sequence
     # create an FFT plan
     dummy = pyfftw.empty_aligned(window_length)
     fft = pyfftw.builders.fft(dummy, n=n_point, overwrite_input=True, threads=self.n_thread)
     spectrum = np.fft.fftshift(fft(signal)) # V, complex-valued, orth-ordered Fourier transform
     return frequencies*1e-3, spectrum # kHz, V
Exemple #37
0
def plot_Temperature(fig_size=None):
	#{{{
	N = 256
	hammingWindow = np.hamming(N)
	hanningWindow = np.hanning(N)
	kaiserWindow = np.kaiser(N,5)
	fig = plt.figure()
	if fig_size != None:
		fig.set_size_inches(fig_size[0], fig_size[1])
	for i in range(0,10):
		Time = Array[i-1][:,0]
		PlData1 = Array[i-1][:, 5]
		PlData2 = Array[i-1][:, 6]
		PlData3 = Array[i-1][:, 7]
		PlData4 = Array[i-1][:, 8]
		PlData5 = Array[i-1][:, 9]
		PlData6 = Array[i-1][:,10]
		PlData7 = Array[i-1][:,16]
		ax = fig.add_subplot(5,2,i)
		#plt.legend((NameIndex[5],NameIndex[6],NameIndex[7],NameIndex[8],NameIndex[9],NameIndex[10]),'upper left')
		#plt.plot(Time,PlData1,label=' 5-OriTemp')
		#plt.plot(Time,PlData2,label=' 6-InjTemp')
		#plt.plot(Time,PlData3,label=' 7-NUWTemp')
		plt.plot(Time,PlData4,label=' 8-NUCTemp')
		plt.plot(Time,PlData5,label=' 9-NDCTemp')
		plt.plot(Time,PlData6,label='10-FrnTemp')
		plt.plot(Time,PlData7,label='16-MixBoil')
		plt.legend(fontsize=15,loc = 'upper right')
		plt.xlabel('Time[s]')
		plt.ylabel('Temperature[K]')
		plt.xlim(0,10)
		plt.ylim(-200,1400)
Exemple #38
0
def hps(x, fs=44100, lf=255, harmonics=3, precision=2, window=lambda l:_np.kaiser(l, 7.14285)):
    """ Estimates the pitch (fundamental frequency) of the given sample array by a standard HPS implementation. """
    x -= _np.mean(x)
    N = x.size
    w = x*window(N)

    # Append zeros to the end of the window so that each bin has at least the desired precision.
    if fs/N > precision:
        delta = int(fs/precision) - N
        w = _np.append(w, _np.zeros(delta))
        N = w.size

    X = _np.log(_np.abs(_np.fft.rfft(w)))

    # Sequentially decimate 'X' 'harmonics' times and add it to itself.
    # 'precision < fs/N' must hold, lest the decimation loses all the precision we'd gain.
    hps = _np.copy(X)
    for h in range(2, 2 + harmonics):
        dec = _sig.decimate(X, h)
        hps[:dec.size] += dec*(0.8**h)

    # Find the bin corresponding to the lowest detectable frequency.
    lb = lf*N/fs

    # And then the bin with the highest spectral content.
    arg_peak = lb + _np.argmax(hps[lb:dec.size])

    # TODO: Return the full array? A ranked list of identified notes?
    return fs*arg_peak/N
Exemple #39
0
def kaiser():
    from numpy import kaiser
    from matplotlib.pyplot import plot, show

    window = kaiser(42, 14)
    plot(window)
    show()
def preprocess(X, y=None, box_width=256, overlap=32, pad_width=0):
    X = pre_flow(X)
    
    out_X = []
    out_y = []
    m = int(X.shape[0] / box_width) * box_width
    
    w = np.kaiser(box_width + pad_width, 14)

    for start in range(0, m, overlap):
        end = start + box_width
        if end >= len(X):
            break
        
        x = X[start:end,]

        if pad_width > 0:
            x = np.vstack([x, np.zeros((pad_width, x.shape[1]))])

        x = (x.T * w).T

        psd = abs(np.fft.rfft(x, axis=0))

        #freqs, psd = signal.welch(X[start:end,], axis=0)
    
        out_X.append(psd.flatten())
        if y != None:
            out_y.append(stats.mode(y[start:end])[0][0])

    if y != None:
        return np.array(out_X), np.array(out_y)
    else:
        return np.array(out_X)
Exemple #41
0
    def construct_window(width, family, scale):
        if family == 'bartlett':
            return numpy.bartlett(width) * scale

        if family == 'blackman':
            return numpy.blackman(width) * scale

        if family == 'hamming':
            return numpy.hamming(width) * scale

        if family == 'hann':
            import scipy.signal
            return scipy.signal.hann(width) * scale

        if family == 'hanning':
            return numpy.hanning(width) * scale

        if family == 'kaiser':
            beta = 14
            return numpy.kaiser(width, beta) * scale

        if family == 'tukey':
            import scipy.signal
            return scipy.signal.tukey(width) * scale

        print('window family %s not supported' % family)
def calc_specgram(data, axis):
    N = data.shape[0]
    Fs = N / (data[-1, 0] - data[0, 0])
    # Round up to a power of 2 for faster FFT
    M = 1 << int(.5 * Fs - 1).bit_length()
    window = np.kaiser(M, 6.)

    def _specgram(x):
        return matplotlib.mlab.specgram(x,
                                        Fs=Fs,
                                        NFFT=M,
                                        noverlap=M // 2,
                                        window=window,
                                        mode='psd',
                                        detrend='mean',
                                        scale_by_freq=False)

    d = {'x': data[:, 1], 'y': data[:, 2], 'z': data[:, 3]}
    if axis != 'all':
        pdata, bins, t = _specgram(d[axis])
    else:
        pdata, bins, t = _specgram(d['x'])
        for ax in 'yz':
            pdata += _specgram(d[ax])[0]
    return pdata, bins, t
Exemple #43
0
def simple_segmentation( wav_data, sample_rate, db_diff = 17, max_silence = 0.8 ): 

    # filter data
    filtered_data = filter_chain(wav_data, sample_rate, 1000, 0.6)

    # create figure and axis
    f, ax = plt.subplots()

    # get spectograma nd spectogram plot (i.e. STFT)
    NFFT = 1024
    noverlap = 256
    window = np.kaiser(NFFT, 8)
    spectogram, freqs, time_array, im = ax.specgram(filtered_data, NFFT=NFFT,
                                                    Fs=sample_rate, noverlap=noverlap,
                                                    window=window, cmap = 'Greys')
    ax.set_xlim(0, len(wav_data)/float(sample_rate)) # remove empty plot region
    ax.set_ylim(0, sample_rate/2.)                   # remove empty plot region

    syllables = find_syllables(spectogram, time_array, db_diff)

    segments = join_in_segments(syllables, max_silence) 

    # add segments to plot as red shadowed areas
    hspans = []
    for segment in segments:
        hspans.append(ax.axvspan(segment[0], segment[1], facecolor='r', alpha = 0.2))
    
    return segments, f, ax
Exemple #44
0
def gen_map(vals, n=nbins, hue=False):
	# saturation
	fvals = vals.flatten()
	yh, xh, patches = plt.hist(fvals, bins=n, range=(0,1), normed=False , cumulative=False , histtype='step')
	if hue:
		# apply window
		M = 9
		win = np.kaiser(M, 3.0)
		yh = np.insert(yh, 0, np.zeros(M/2))
		yh = np.append(yh, np.zeros(M/2))
		yh = rolling_window(yh.T, M)
		yh = np.dot(yh, win)
	yh /= sum(yh)
	if hue:
		# adapted norm
		#yh = np.minimum(yh, hcut)
		yh[yh<=hcut] = 0
		yh /= sum(yh)
	yh = np.cumsum(yh)

	xhi = np.linspace(0,1,256)
	yhi = np.interp(xhi, yh, xh[1:])
	yhinv = np.interp(xhi, xh[1:], yh)
	#plt.plot(xhi, yhi)
	return (yhi, yhinv)
Exemple #45
0
def smooth_curve(x):
    """손실함수의 그래프를 매끄럽게 하기 위해서 사용한다"""
    window_len = 11
    s = np.r_[x[window_len - 1:0:-1], x, x[-1:-window_len:-1]]
    w = np.kaiser(window_len, 2)
    y = np.convolve(w / w.sum(), s, mode='valid')
    return y[5:len(y) - 5]
Exemple #46
0
def lowpass(cutout, delta_w, atten):
    beta = 0
    if atten > 50:
        beta = 0.1102 * (atten - 8.7)
    elif atten < 21:
        beta = 0
    else:
        beta = 0.5842 * (atten - 21)**0.4 + 0.07886 * (atten - 21)

    length = math.ceil((atten - 8) / (2.285 * delta_w * math.pi)) + 1
    if length % 2 == 0:
        length += 1

    coeffs = np.kaiser(length, beta)

    for i, n in enumerate(
            range(int(-(length - 1) / 2),
                  int((length - 1) / 2) + 1)):

        if n == 0:
            coeffs[i] *= cutout
        else:
            coeffs[i] *= math.sin(n * math.pi * cutout) / (n * math.pi)

    return coeffs
Exemple #47
0
    def SINAD(self,
              samples,
              sample_rate,
              test_tone_frequency=1000,
              freq_range_min=50,
              freq_range_max=15000,
              psophometric_weighting=False):
        '''Return SINAD (signal to noise and distortion) in dB of real-valued sinusoidal signal.

        Arguments:
            samples... a numpy array of input audio samples. This needs at least a few k of samples to ensure the accuracy.
            sample_rate... sampling frequency in Hz
            test_tone_frequency... frequency of the tone (default: 1000)
            freq_range_min... high pass filter cutoff in Hz (default: 50, same as HP8920)
            freq_range_max... low pass filter cutoff in Hz (default: 15000, same as HP8920)
            psophometric_weighting... apply psophometric weighting if True (default: False)
        '''

        # Ensure input is an array of floats
        samples = np.array(samples, np.float)
        n_samples = len(samples)
        samples_w = samples * np.kaiser(n_samples, beta=16.0)
        notch_width = 0.1  # notch width depends on the kaiser Beta coefficient

        # Zero pad to adjust the size to the next power of two
        n_fft = int(2**np.ceil(np.log2(n_samples)))
        samples_w = np.concatenate((samples_w, np.zeros(n_fft - n_samples)))

        # Go to frequency domain
        samples_fft = np.fft.rfft(samples_w)

        # Apply the band pass filter
        samples_fft_filt = samples_fft
        hpf_bin = int(n_fft * float(freq_range_min) / sample_rate)
        samples_fft_filt[:hpf_bin] = 1e-99
        lpf_bin = int(n_fft * float(freq_range_max) / sample_rate)
        samples_fft_filt[lpf_bin:] = 1e-99

        # Apply the psophometric weighting
        if psophometric_weighting:
            samples_fft_filt = self.apply_psophometric_weighting(
                samples_fft_filt, sample_rate)

        # Transform the filtered signal + noise back to time domain and measure the power
        samples_filt = np.fft.irfft(samples_fft_filt)
        signal_plus_noise_power = np.mean(np.absolute(samples_filt)**2)

        # Notch out the test tone
        notch_low_bin = int(n_fft * (1.0 - 0.5 * notch_width) *
                            test_tone_frequency / sample_rate)
        notch_high_bin = int(n_fft * (1.0 + 0.5 * notch_width) *
                             test_tone_frequency / sample_rate)
        samples_fft_filt[notch_low_bin:notch_high_bin] = 1e-99

        # Transform the left over noise (+ distortion) back to time domain and measure the power
        noise_filt = np.fft.irfft(samples_fft_filt)
        noise_power = np.mean(np.absolute(noise_filt)**2)

        # Return the SINAD in dB
        return 10 * np.log10(signal_plus_noise_power / noise_power)
Exemple #48
0
def smooth(x, beta, window_len=11):
    """ kaiser window smoothing """
    # extending the data at beginning and at the end
    # to apply the window at the borders
    s = numpy.r_[x[window_len - 1 : 0 : -1], x, x[-1:-window_len:-1]]
    w = numpy.kaiser(window_len, beta)
    y = numpy.convolve(w / w.sum(), s, mode="valid")
    return y[(window_len / 2) : -(window_len / 2)]
    def __init__(self,freq,N_samples):

        QtGui.QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.createQtConnections()


        self.sample_rate = 2.4e5 ###1e6
        #self.decim_r1 = 1e6/2e5 # for wideband fm
        self.decim_r2 = 2.4e5/48000 # for baseband recovery
        self.center_freq = freq #+250e3
        self.gain = 38

        self.N_samples = N_samples
        self.is_sampling = False

        self.spectrogram = np.zeros((328,200))
        self.chspectrogram = np.zeros((328,200))
        self.plspectrogram = np.zeros((164,200))

        self.sdr =  RtlSdr()
        #self.sdr.direct_sampling = 1
        self.sdr.sample_rate = self.sample_rate
        self.sdr.center_freq = self.center_freq
        self.sdr.gain = self.gain

        self.pa = pyaudio.PyAudio()
        self.stream = self.pa.open( format = pyaudio.paFloat32,
                                    channels = 2,
                                    rate = 48000,
                                    output = True)

        adj = 0
        hamming = np.kaiser(self.N_samples/4 + adj,1)
        lpf = np.append( np.zeros(self.N_samples*3/8),hamming)
        self.lpf = np.fft.fftshift(np.append(lpf,np.zeros(self.N_samples*3/8))) #,int(-.25*self.N_samples))

        hamming = 10*signal.hamming(self.N_samples/16)
        lpf = np.append(np.zeros(self.N_samples*15/32),hamming)
        self.lpf_s1 = (np.append(lpf,np.zeros(int(self.N_samples*15/32))))
        #self.lpf_s1 = np.roll(temp,int(.5*self.N_samples*67/120))
        #self.lpf_s1 += np.roll(temp,int(-.5*self.N_samples*67/120))
        self.lpf_s1 = np.fft.fftshift(self.lpf_s1)
        #self.lpf_s1 += np.fft.fftshift(self.lpf_s1)

#         fig = plt.figure()
#         ax = fig.add_subplot(111)
#         ax.plot(range(self.lpf_s1.size),self.lpf_s1)
#         fig.show()

        hamming = 10*signal.hamming(self.N_samples/32)
        lpf = np.append(np.zeros(self.N_samples*31/64),hamming)
        self.lpf_s2 = (np.append(lpf,np.zeros(int(self.N_samples*31/64))))
        #self.lpf_s2 = np.roll(temp,int(.5*self.N_samples*92/120))
        #self.lpf_s2 += np.roll(temp,int(-.5*self.N_samples*92/120))
        self.lpf_s2 = np.fft.fftshift(self.lpf_s2)
def smooth(x,beta, window_len):
 """ kaiser window smoothing """
 # extending the data at beginning and at the end
 # to apply the window at the borders
 s = numpy.r_[x[window_len-1:0:-1], x, x[-2:-window_len-1:-1]]
 w = numpy.kaiser(window_len,beta)
 y = numpy.convolve(w/w.sum(), s, mode='valid')
 offset = window_len/2
 return y[offset:len(y)-offset]
Exemple #51
0
def fft(data, sample_rate=1, window=lambda x:np.kaiser(x,2)):
    if window:
        w = window(len(data))
        data = [data[i]*w[i] for i in xrange(len(w))]
    fs = 1/float(sample_rate)
    y = map(abs,np.fft.rfft(data))
    fstep = fs/len(y)
    #return (y,[fstep*i for i in xrange(0,len(y))])
    return y
Exemple #52
0
def smooth(x,beta):
 """ kaiser window smoothing """
 window_len=11
 # extending the data at beginning and at the end
 # to apply the window at the borders
 s = np.r_[x[window_len-1:0:-1],x,x[-1:-window_len:-1]]
 w = np.kaiser(window_len,beta)
 y = np.convolve(w/w.sum(),s,mode='valid')
 return y[5:len(y)-5]
Exemple #53
0
 def smoothWKaiserWindow(self):
     """ 
     kaiser window smoothing 
     """
     # extending the data at beginning and at the end in oder to apply the window at the borders
     s = np.r_[self.flux[self.windowSizeInBin-1:0:-1], self.flux, self.flux[-1:-self.windowSizeInBin:-1]]
     w = np.kaiser(self.windowSizeInBin, self.beta)
     y = np.convolve(w/w.sum(), s, mode='valid')
     return y[(self.windowSizeInBin-1)/2:len(y) - (self.windowSizeInBin-1)/2]
def smooth(x,beta):
  """
  Smooths a spectrum *x* using a Kaiser-Bessel smoothing window of narrowness *beta* (~1 => very smooth, ~100 => not smooth) 
  """
  window_len = 11
  s = np.r_[x[window_len-1:0:-1], x, x[-1:-window_len:-1]]
  w = np.kaiser(window_len,beta)
  y = np.convolve(w/w.sum(), s, mode='valid')
  return y[5:len(y)-5]*(x.unit if hasattr(x, 'unit') else 1)
Exemple #55
0
def smooth_curve(x):
    """손실 함수의 그래프를 매끄럽게 하기 위해 사용
    
    참고:http://glowingpython.blogspot.jp/2012/02/convolution-with-numpy.html
    """
    window_len = 11
    s = np.r_[x[window_len-1:0:-1], x, x[-1:-window_len:-1]]
    w = np.kaiser(window_len, 2)
    y = np.convolve(w/w.sum(), s, mode='valid')
    return y[5:len(y)-5]
 def build_window(size, shape, method='numpy'):
     if method == 'numpy':
         return np.kaiser(size, shape)
     else:
         N = size - 1
         n = np.arange(0, size)
         K = (2 * n * (1/N)) - 1
         A = np.sqrt(1 - (K*K))
         win = zeroeth_order_bessel(shape*A) * (1/zeroeth_order_bessel(shape))
         return win
Exemple #57
0
    def fid_to_spec(self, window_f = ' ', beta = 2, t_start = 0., t_end = 100.0):
        '''
        FFT with zero-padding of the FID.
        Saves the result in self.spec
        
        Parameters
        ----------
        window_f: is the applied window function. The following window functions are
        applicable: hanning, hamming, blackman, bartlett, kaiser (beta (float) is only used
        by the kaiser window)
        t_start (float): specifies the beginning of the FID. The corresponding data points
        will be cut away.
        t_end (float): specifies the end of the FID. The corresponding data points
        will be cut away.
                
        Returns
        -------
        none
        
        Notes
        -----
        none
        '''
        if len(self.fid) != 0:

            fid = slice_fid(self.fid, t_start, t_end)
            window_f = window_f.lower()   # Choose the window function (default: rect / none)    
            
            if window_f == 'hanning':
                fid[:,1] = fid[:,1] * np.hanning(len(fid))
                
            elif window_f == 'hamming':
                fid[:,1] = fid[:,1] * np.hamming(len(fid))
                
            elif window_f == 'blackman':
                fid[:,1] = fid[:,1] * np.blackman(len(fid))
            
            elif window_f == 'bartlett':
                fid[:,1] = fid[:,1] * np.bartlett(len(fid))
                
            elif window_f == 'kaiser':
                fid[:,1] = fid[:,1] * np.kaiser(len(fid), beta)
            
            h = (int(np.sqrt(len(fid))) + 1) ** 2   # Zero padding to n**2 length to enhance computing speed
            spec = np.absolute(np.fft.rfft(fid[:,1], h)) ** 2 / h
            spec = spec[0:int(h/2)]
            freq = np.fft.fftfreq(h, np.abs(fid[2,0] - fid[1,0])) / 1.E6
            freq = freq[0:int(h/2)]  # Combine FFT and frequencies

            self.spec = np.column_stack([freq, spec])
            
            self.spec_params['npoints'] = len(spec)
            self.spec_params['max_f'] = np.max(freq)
            self.spec_params['min_f'] = np.min(freq)
            self.spec_params['delta_f'] = np.abs(freq[1]-freq[0])