Пример #1
0
def load_sound_stims(files,
                     root="",
                     windowtime=0.016,
                     ovl=0.0016,
                     f_min=500,
                     f_max=8000,
                     gammatone=False,
                     dsample=10,
                     sres=15,
                     compress=0):
    stims = []
    durations = []

    for f in files:
        Fs, wave = read(root + f)
        duration = int(1000 * len(wave) / Fs)
        durations.append(duration)
        if gammatone:
            Pxx = gg.gtgram(wave, Fs, windowtime, ovl, sres, f_min)
            Pxx = np.log10(Pxx)

        else:
            w = np.hanning(int(windowtime * Fs))
            Pxx = libtfr.stft(wave, w, int(w.size * .1))
            freqs, ind = libtfr.fgrid(Fs, w.size, [f_min, f_max])
            Pxx = Pxx[ind, :]
            Pxx = np.log10(Pxx + compress)
            Pxx = resample(Pxx, sres)
        Pxx = resample(Pxx, duration / dsample, axis=1)
        stims.append(Pxx)
    return stims, durations
Пример #2
0
    def __init__(self,
                 dataset,
                 t_step_ms=1,
                 win_size=512,
                 window_name='Hann',
                 freq_min=0,
                 freq_max=10000,
                 *args,
                 **kwargs):
        super(spectrogram, self).__init__(*args, **kwargs)
        self.dataset = dataset
        self.selection = None  #contains pg.LinearRegionItem representing selection if not None
        #getting spectrogram settings
        sr = float(dataset.attrs['sampling_rate'])
        t_step = int(float(t_step_ms) * sr / 1000.)  #time step in samples

        if window_name == "Hann":
            window = scipy.signal.hann(win_size)
        elif window_name == "Bartlett":
            window = scipy.signal.bartlett(win_size)
        elif window_name == "Blackman":
            window = scipy.signal.blackman(win_size)
        elif window_name == "Boxcar":
            window = scipy.signal.boxcar(win_size)
        elif window_name == "Hamming":
            window = scipy.signal.hamming(win_size)
        elif window_name == "Parzen":
            window = scipy.signal.parzen(win_size)

        #computing and interpolating image
        Pxx = libtfr.stft(dataset, w=window, step=t_step)
        Pxx[Pxx == 0] = np.min(
            Pxx[Pxx != 0])  #ensures that log won't give -inf
        spec = np.log(Pxx.T)
        res_factor = 1.0  #factor by which resolution is increased
        # spec = interpolate_spectrogram(spec, res_factor=res_factor)
        #making color lookup table
        pos = np.linspace(0, 1, 6)
        color = np.array(
            [[0, 0, 255, 255], [0, 255, 255, 255], [0, 255, 0, 255],
             [255, 255, 0, 255], [255, 0, 0, 255], [100, 0, 0, 255]],
            dtype=np.ubyte)
        color_map = pg.ColorMap(pos, color)
        lut = color_map.getLookupTable(0.0, 1.0, 256)
        self.img = pg.ImageItem(spec, lut=lut)
        #img.setLevels((-5, 10))

        self.addItem(self.img)
        image_scale = t_step / sr / res_factor
        self.img.setScale(image_scale)
        df = sr / float(win_size)
        plot_scale = df / res_factor / image_scale
        self.getAxis('left').setScale(plot_scale)
        xmax = float(dataset.size) / dataset.attrs['sampling_rate']
        self.setXRange(0, xmax)
        self.setYRange(freq_min / plot_scale, freq_max / plot_scale)
        self.setMouseEnabled(x=True, y=False)
        self.win_size = win_size  #saving values for export selection function
        self.t_step = t_step
Пример #3
0
def specgram(x, NFFT=256, shift=128, Fs=1.0, drange=60,
             ax=None, cmap=mplt.cm.gray_r, **kwargs):
    from numpy import hanning
    from libtfr import stft, fgrid, tgrid, dynamic_range
    w = hanning(NFFT)
    S = stft(x, w, shift)
    F,ind = fgrid(Fs,NFFT,(0,Fs/2))
    T = tgrid(x.size, Fs, shift)
    S = nx.log10(dynamic_range(S, drange))
    if ax is None: ax = mplt.gca()
    ax.imshow(S, extent = (T[0],T[-1],F[0]-0.01,F[-1]), cmap=cmap, **kwargs)
    return S
Пример #4
0
def specgram(x, NFFT=256, shift=128, Fs=1.0, drange=60,
             ax=None, cmap=mplt.cm.gray_r, **kwargs):
    from numpy import hanning
    from libtfr import stft, fgrid, tgrid, dynamic_range
    w = hanning(NFFT)
    S = stft(x, w, shift)
    F,ind = fgrid(Fs,NFFT,(0,Fs/2))
    T = tgrid(x.size, Fs, shift)
    S = nx.log10(dynamic_range(S, drange))
    if ax is None: ax = mplt.gca()
    ax.imshow(S, extent = (T[0],T[-1],F[0]-0.01,F[-1]), cmap=cmap, **kwargs)
    return S
Пример #5
0
    def __init__(self, dataset, t_step_ms=1, win_size=512, window_name='Hann', freq_min=0, 
                 freq_max=10000, *args, **kwargs):
        super(spectrogram, self).__init__(*args, **kwargs)
        self.dataset = dataset
        self.selection = None #contains pg.LinearRegionItem representing selection if not None
                #getting spectrogram settings
        sr = float(dataset.attrs['sampling_rate'])
        t_step = int(float(t_step_ms) * sr/1000.)  #time step in samples    

        if window_name == "Hann":
            window = scipy.signal.hann(win_size)
        elif window_name == "Bartlett":
            window = scipy.signal.bartlett(win_size)
        elif window_name == "Blackman":
            window = scipy.signal.blackman(win_size)
        elif window_name == "Boxcar":
            window = scipy.signal.boxcar(win_size)
        elif window_name == "Hamming":
            window = scipy.signal.hamming(win_size)
        elif window_name == "Parzen":
            window = scipy.signal.parzen(win_size)

        #computing and interpolating image
        Pxx = libtfr.stft(dataset,w=window,step=t_step)
        Pxx[Pxx==0] = np.min(Pxx[Pxx!=0]) #ensures that log won't give -inf
        spec = np.log(Pxx.T)
        res_factor = 1.0 #factor by which resolution is increased
        # spec = interpolate_spectrogram(spec, res_factor=res_factor)
        #making color lookup table
        pos = np.linspace(0,1,6)
        color = np.array([[0,0,255,255],[0,255,255,255],[0,255,0,255],
                          [255,255,0,255],[255,0,0,255],[100,0,0,255]], dtype=np.ubyte)
        color_map = pg.ColorMap(pos,color)
        lut = color_map.getLookupTable(0.0,1.0,256)
        self.img = pg.ImageItem(spec,lut=lut)
        #img.setLevels((-5, 10))

        self.addItem(self.img)
        image_scale = t_step/sr/res_factor
        self.img.setScale(image_scale)
        df = sr/float(win_size)
        plot_scale = df/res_factor/image_scale
        self.getAxis('left').setScale(plot_scale)
        xmax = float(dataset.size)/dataset.attrs['sampling_rate']
        self.setXRange(0, xmax)
        self.setYRange(freq_min/plot_scale, freq_max/plot_scale)
        self.setMouseEnabled(x=True, y=False)
        self.win_size = win_size #saving values for export selection function
        self.t_step = t_step 
Пример #6
0
 def linspect(self, signal, Fs, nfft=None):
     """ Calculate the spectrogram on a linear power scale.  """
     import numpy as nx
     from libtfr import stft, tfr_spec, tgrid
     shift = int(self.options['window_shift'] * Fs)
     if not nfft:
         Np = int(Fs * self.options['window_len'])
         nfft = int(2 ** nx.ceil(nx.log2(Np)))
     else:
         Np = nfft
     if self.options['spec_method'] == 'tfr':
         S = tfr_spec(signal, nfft, shift, Np,
                      K=self.options['tfr_order'], tm=self.options['tfr_tm'],
                      flock=self.options['tfr_flock'], tlock=self.options['tfr_tlock'])
     else:
         try:
             wfun = getattr(nx, self.options['spec_method'])
             w = wfun(Np)
         except Exception, e:
             raise Error("invalid window function {}: {}".format(self.options['spec_method'], e))
         S = stft(signal, w, shift, nfft)
Пример #7
0
    def plot_dataset_list(self, dataset_list, data_layout, append=False):
        ''' plots a list of datasets to a data layout'''
        data_layout.clear()
        if not append:
            self.subplots = []
        # rasterQPainterPath = QtGui.QPainterPath().addRect(-.1,-5,.2,1)  # TODO make a better raster
        # shape that works

        toes = []
        for dataset in dataset_list:
            print(dataset)
            if 'datatype' not in dataset.attrs.keys():
                print('{} is not an arf dataset'.format(repr(dataset)))
                if os.path.basename(dataset.name) == 'jill_log':
                    print(dataset.value)
                continue

            '''sampled data'''
            if dataset.attrs['datatype'] < 1000: # sampled data
                if (self.settings_panel.oscillogram_check.checkState()
                    ==QtCore.Qt.Checked): 
                    
                    pl = downsamplePlot(dataset, title=dataset.name,
                                        name=str(len(self.subplots)))
                    data_layout.addItem(pl,row=len(self.subplots), col=0)
                    pl.setXRange(0, dataset.size/float(dataset.attrs['sampling_rate']))
                    pl.setYRange(np.min(dataset), np.max(dataset))                    
                    self.subplots.append(pl)
                    pl.showGrid(x=True, y=True)

                ''' simple events '''
            elif utils.is_simple_event(dataset):
                if dataset.attrs['units'] == 'ms':
                    data = dataset.value / 1000.
                elif dataset.attrs['units'] == 'samples':
                    data = dataset.value / dataset.attrs['sampling_rate']
                else:
                    data = dataset.value
                if (self.settings_panel.raster_check.checkState()==QtCore.Qt.Checked or
                    self.settings_panel.psth_check.checkState()==QtCore.Qt.Checked or
                    self.settings_panel.isi_check.checkState()==QtCore.Qt.Checked):                    
                    toes.append(data)
                continue

                ''' complex event '''
            elif utils.is_complex_event(dataset):
                if (self.settings_panel.label_check.checkState()
                    ==QtCore.Qt.Checked):
                
                    #creating new extensible dataset if not extensible
                    if dataset.maxshape != (None,):
                        data = dataset[:]
                        name = dataset.name
                        group= dataset.parent
                        attributes = dataset.attrs
                        del group[name]
                        del dataset
                        dataset = arf.create_dataset(group, name, data,
                                                     maxshape=(None,),**attributes)

                    pl = labelPlot(dataset, title=dataset.name, name=str(len(self.subplots)))
                    data_layout.addItem(pl, row=len(self.subplots), col=0) 
                    pl.showLabel('left', show=False)
                    self.subplots.append(pl)

            else:
                print('I don\'t know how to plot {} of type {} \
                with datatype {}'.format(dataset,
                                         type(dataset),
                                         dataset.attrs['datatype']))
                continue

            '''adding spectrograms'''
            if dataset.attrs['datatype'] in [0, 1]: # show spectrogram
                if (self.settings_panel.spectrogram_check.checkState()
                    ==QtCore.Qt.Checked):
                    #getting spectrogram settings
                    sr = float(dataset.attrs['sampling_rate'])
                    win_size_text = self.settings_panel.win_size.text()
                    t_step_text = self.settings_panel.step.text()
                    min_text = self.settings_panel.freq_min.text()
                    max_text = self.settings_panel.freq_max.text()

                    if win_size_text:
                        win_size = int(float(win_size_text))
                    else:
                        win_size = self.settings_panel.defaults['win_size']
                        self.settings_panel.win_size.setText(str(win_size))
                    if t_step_text:
                        t_step = int(float(t_step_text) * sr/1000.)
                    else:
                        t_step = self.settings_panel.defaults['step']
                        self.settings_panel.win_size.setText(str(int(tstep*1000)))
                    if min_text:
                        freq_min = int(min_text)
                    else:
                        freq_min = self.settings_panel.defaults['freq_min']
                        self.settings_panel.freq_min.setText(str(freq_min))
                    if max_text:
                        freq_max = int(max_text)
                    else:
                        freq_max = self.settings_panel.defaults['freq_max']
                        self.settings_panel.freq_max.setText(str(freq_max))                                        
                    
                    window_name = self.settings_panel.window.currentText()                
                    if window_name == "Hann":
                        window = scipy.signal.hann(win_size)
                    elif window_name == "Bartlett":
                        window = scipy.signal.bartlett(win_size)
                    elif window_name == "Blackman":
                        window = scipy.signal.blackman(win_size)
                    elif window_name == "Boxcar":
                        window = scipy.signal.boxcar(win_size)
                    elif window_name == "Hamming":
                        window = scipy.signal.hamming(win_size)
                    elif window_name == "Parzen":
                        window = scipy.signal.parzen(win_size)
                    
                    #computing and interpolating image
                    Pxx = libtfr.stft(dataset,w=window,step=t_step)
                    spec = np.log(Pxx.T)
                    res_factor = 1.0 #factor by which resolution is increased
#                    spec = interpolate_spectrogram(spec, res_factor=res_factor)

                    #making color lookup table
                    pos = np.linspace(0,1,7)
                    color = np.array([[100,100,255,255],[0,0,255,255],[0,255,255,255],[0,255,0,255],
                                      [255,255,0,255],[255,0,0,255],[100,0,0,255]], dtype=np.ubyte)
                    color_map = pg.ColorMap(pos,color)
                    lut = color_map.getLookupTable(0.0,1.0,256)
                    img = pg.ImageItem(spec,lut=lut)
                    #img.setLevels((-5, 10))

                    pl = data_layout.addPlot(name=str(len(self.subplots)), row=len(self.subplots), col=0)
                    self.subplots.append(pl)

                    pl.addItem(img)
                    image_scale = t_step/sr/res_factor
                    img.setScale(image_scale)
                    df = sr/float(win_size)
                    plot_scale = df/res_factor/image_scale
                    pl.getAxis('left').setScale(plot_scale)
                    pl.setXRange(0, dataset.size / dataset.attrs['sampling_rate'])
                    pl.setYRange(freq_min/plot_scale, freq_max/plot_scale)
                    pl.setMouseEnabled(x=True, y=False)
                    
        if toes:
            if self.settings_panel.raster_check.checkState()==QtCore.Qt.Checked:
                pl= rasterPlot(toes)
                data_layout.addItem(pl, row=len(self.subplots), col=0) 
                pl.showLabel('left', show=False)
                self.subplots.append(pl)

            if self.settings_panel.psth_check.checkState()==QtCore.Qt.Checked:
                all_toes = np.zeros(sum(len(t) for t in toes))
                k=0
                for t in toes:
                    all_toes[k:k+len(t)] = t
                    k += len(t)
                if self.settings_panel.psth_bin_size.text():
                    bin_size = float(self.settings_panel.psth_bin_size.text())/1000.
                else:
                    bin_size = .01
                bins = np.arange(all_toes.min(),all_toes.max()+bin_size,bin_size)
                y,x = np.histogram(all_toes,bins=bins)
                psth = pg.PlotCurveItem(x, y, stepMode=True,
                                        fillLevel=0, brush=(0, 0, 255, 80))

                pl = data_layout.addPlot(row=len(self.subplots), col=0)
                pl.addItem(psth)
                pl.setMouseEnabled(y=False)
                self.subplots.append(pl)
                
        if self.settings_panel.isi_check.checkState()==QtCore.Qt.Checked:
            isis = np.zeros(sum(len(t)-1 for t in toes))
            k=0
            for t in toes:
                isis[k:k+len(t)-1] = np.diff(t)
                k += len(t)-1
            if self.settings_panel.psth_bin_size.text():
                bin_size = float(self.settings_panel.psth_bin_size.text())/1000.
            else:
                bin_size = .01
            bins = np.arange(isis.min(),isis.max()+bin_size,bin_size) 
            y,x = np.histogram(isis,bins=bins,normed=True)
            isi_hist = pg.PlotCurveItem(x, y, stepMode=True,
                                    fillLevel=0, brush=(0, 0, 255, 80))
    
            pl = data_layout.addPlot(row=len(self.subplots), col=0)
            pl.addItem(isi_hist)
            pl.setMouseEnabled(y=False)
            self.subplots.append(pl)

        '''linking x axes'''
        masterXLink = None
        for pl in self.subplots:
            if not masterXLink:
                masterXLink = pl
            pl.setXLink(masterXLink)
Пример #8
0
    def __init__(self, dataset, settings_panel, *args, **kwargs):
        super(spectrogram, self).__init__(*args, **kwargs)
        self.dataset = dataset
        self.settings_panel = settings_panel
                #getting spectrogram settings
        sr = float(dataset.attrs['sampling_rate'])
        win_size_text = settings_panel.win_size.text()
        t_step_text = settings_panel.step.text()
        min_text = settings_panel.freq_min.text()
        max_text = settings_panel.freq_max.text()

        if win_size_text:
            win_size = int(float(win_size_text))
        else:
            win_size = settings_panel.defaults['win_size']
            settings_panel.win_size.setText(str(win_size))
        if t_step_text:
            t_step = int(float(t_step_text) * sr/1000.)
        else:
            t_step = settings_panel.defaults['step']
            settings_panel.win_size.setText(str(int(tstep*1000)))
        if min_text:
            freq_min = int(min_text)
        else:
            freq_min = settings_panel.defaults['freq_min']
            settings_panel.freq_min.setText(str(freq_min))
        if max_text:
            freq_max = int(max_text)
        else:
            freq_max = settings_panel.defaults['freq_max']
            settings_panel.freq_max.setText(str(freq_max))                                     

        window_name = settings_panel.window.currentText()                
        if window_name == "Hann":
            window = scipy.signal.hann(win_size)
        elif window_name == "Bartlett":
            window = scipy.signal.bartlett(win_size)
        elif window_name == "Blackman":
            window = scipy.signal.blackman(win_size)
        elif window_name == "Boxcar":
            window = scipy.signal.boxcar(win_size)
        elif window_name == "Hamming":
            window = scipy.signal.hamming(win_size)
        elif window_name == "Parzen":
            window = scipy.signal.parzen(win_size)

        #computing and interpolating image
        Pxx = libtfr.stft(dataset,w=window,step=t_step)
        spec = np.log(Pxx.T)
        res_factor = 1.0 #factor by which resolution is increased
        # spec = interpolate_spectrogram(spec, res_factor=res_factor)

        #making color lookup table
        pos = np.linspace(0,1,7)
        color = np.array([[100,100,255,255],[0,0,255,255],[0,255,255,255],[0,255,0,255],
                          [255,255,0,255],[255,0,0,255],[100,0,0,255]], dtype=np.ubyte)
        color_map = pg.ColorMap(pos,color)
        lut = color_map.getLookupTable(0.0,1.0,256)
        img = pg.ImageItem(spec,lut=lut)
        #img.setLevels((-5, 10))


        self.addItem(img)
        image_scale = t_step/sr/res_factor
        img.setScale(image_scale)
        df = sr/float(win_size)
        plot_scale = df/res_factor/image_scale
        self.getAxis('left').setScale(plot_scale)
        self.setXRange(0, dataset.size / dataset.attrs['sampling_rate'])
        self.setYRange(freq_min/plot_scale, freq_max/plot_scale)
        self.setMouseEnabled(x=True, y=False)