def keyPressEvent(self, event): #print(event.key()) # cursor to the right if event.key() == 16777236: if self.index < self.nbin - 5: self.index += 1 self.K[self.index] = 1 self.plot_eeg() self.plot_treck(self.tscale) if self.pcollect_index == 1: self.index_list.append(self.index) else: self.index_list = [self.index] # cursor to the left elif event.key() == 16777234: if self.index >= 3: self.index -= 1 self.K[self.index] = 1 self.plot_eeg() self.plot_treck(self.tscale) if self.pcollect_index == True: self.index_list.append(self.index) else: self.index_list = [self.index] # r - REM elif event.key() == 82: self.M_old = self.M.copy() self.M[0, self.index_range()] = 1 self.index_list = [self.index] self.pcollect_index = False self.plot_brainstate(self.tscale) self.plot_eeg() # w - Wake elif event.key() == 87: self.M_old = self.M.copy() self.M[0, self.index_range()] = 2 self.index_list = [self.index] self.pcollect_index = False self.plot_eeg() self.plot_brainstate(self.tscale) # s or n - SWS/NREM elif event.key() == 78 or event.key() == 83: self.M_old = self.M.copy() self.M[0, self.index_range()] = 3 self.index_list = [self.index] self.pcollect_index = False self.plot_eeg() self.plot_brainstate(self.tscale) # z - revert back to previous annotation elif event.key() == 90: self.M = self.M_old.copy() self.plot_eeg() self.plot_brainstate(self.tscale) # x - undefined state elif event.key() == QtCore.Qt.Key_X: #self.M[0,self.index] = 0 self.M_old = self.M.copy() self.M[0, self.index_range()] = 0 self.index_list = [self.index] self.pcollect_index = False self.plot_eeg() self.plot_brainstate(self.tscale) # space: once space is pressed collect indices starting from space that # are visited with cursor elif event.key() == 32: self.pcollect_index = True self.index_list = [self.index] # cursor down elif event.key() == 16777237: self.color_max -= self.color_max / 10 self.image_spectrum.setLevels((0, self.color_max)) # cursor up elif event.key() == 16777235: self.color_max += self.color_max / 10 self.image_spectrum.setLevels((0, self.color_max)) # 1 - seconds scale elif event.key() == 49: self.tscale = 1.0 self.tunit = 's' self.plot_session(scale=1, scale_unit='s') self.plot_brainstate(scale=1) self.plot_treck(scale=1) # 2 - mintues scale elif event.key() == 50: self.tscale = 1 / 60.0 self.tunit = 'min' self.plot_session(scale=1 / 60.0, scale_unit='min') self.plot_brainstate(scale=1 / 60.0) self.plot_treck(scale=1 / 60.0) # 3 - hours scale elif event.key() == 51: self.tscale = 1 / 3600.0 self.tunit = 'h' self.plot_session(scale=1 / 3600.0, scale_unit='h') self.plot_brainstate(scale=1 / 3600.0) self.plot_treck(scale=1 / 3600.0) # f - save file elif event.key() == 70: rewrite_remidx(self.M, self.K, self.ppath, self.name, mode=0) self.plot_brainstate(self.tscale) self.plot_eeg() # h - help elif event.key() == 72: self.print_help() # e - switch EEG channel elif event.key() == 69: self.lfp_pointer = -1 num_eeg = len(self.EEG_list) if self.eeg_pointer < num_eeg - 1: self.eeg_pointer += 1 else: self.eeg_pointer = 0 self.EEG = self.EEG_list[self.eeg_pointer] self.eeg_spec = self.eeg_spec_list[self.eeg_pointer] self.plot_eeg() #self.plot_treck(self.tscale) self.plot_session(scale=self.tscale, scale_unit=self.tunit) # m - switch EMG channel elif event.key() == 77: num_emg = len(self.EMG_list) if self.emg_pointer < num_emg - 1: self.emg_pointer += 1 else: self.emg_pointer = 0 self.EMG = self.EMG_list[self.emg_pointer] self.EMGAmpl = self.EMGAmpl_list[self.emg_pointer] self.plot_eeg() self.plot_session(scale=self.tscale, scale_unit=self.tunit) # p - switch on/off laser [p]ulses elif event.key() == 80: if self.pplot_laser == True: self.pplot_laser = False else: self.pplot_laser = True self.plot_eeg() self.plot_treck(self.tscale) # l - turn on lfp channel elif event.key() == 76: self.eeg_pointer = -1 if len(self.LFP_list) > 0: num_lfp = len(self.LFP_list) if self.lfp_pointer < num_lfp - 1: self.lfp_pointer += 1 else: self.lfp_pointer = 0 self.EEG = self.LFP_list[self.lfp_pointer] self.plot_eeg() elif event.key() == QtCore.Qt.Key_I: self.print_info() # $ elif event.key() == QtCore.Qt.Key_Dollar: self.break_index[1] = len(self.K) - 1 if not self.pbreak: self.pbreak = True else: self.K[self.break_index[0]:self.break_index[1] + 1] = -1 self.pbreak = False self.plot_treck(scale=self.tscale) # ^ elif event.key() == 94: self.break_index[0] = 0 if not self.pbreak: self.pbreak = True else: self.K[self.break_index[0]:self.break_index[1] + 1] = -1 self.pbreak = False self.plot_treck(scale=self.tscale) # [ open break elif event.key() == 91: self.break_index[0] = int(self.index) if not self.pbreak: self.pbreak = True else: self.K[self.break_index[0]:self.break_index[1] + 1] = -1 self.pbreak = False self.plot_treck(scale=self.tscale) # ] elif event.key() == 93: self.break_index[1] = int(self.index) if not self.pbreak: self.pbreak = True else: self.K[self.break_index[0]:self.break_index[1] + 1] = -1 self.pbreak = False self.plot_treck(scale=self.tscale) # * elif event.key() == 42: use_idx = np.where(self.K >= 0)[0] print("Re-calculating sleep annotation") sleepy.sleep_state(ppath, name, th_delta_std=1, mu_std=0, sf=1, sf_delta=3, pwrite=1, pplot=True, pemg=1, vmax=2.5, use_idx=use_idx) # reload sleep state K_old = self.K.copy() (A, self.K) = load_stateidx(self.ppath, self.name) # set undefined states to 4 #A[np.where(A==0)] = 4 # needs to be packed into 1 x nbin matrix for display self.M = np.zeros((1, self.nbin)) self.M[0, :] = A # backup for brainstate in case somethin goes wrong self.M_old = self.M.copy() self.K[np.where(K_old < 0)] = -1 self.plot_treck(scale=self.tscale) self.plot_session(scale=self.tscale, scale_unit=self.tunit) event.accept()
def load_recording(self): """ load recording: spectrograms, EEG, EMG, time information etc. """ if self.name == '': self.openFileNameDialog() # set title for window self.setWindowTitle(self.name) # load EEG/EMG self.eeg_pointer = 0 self.emg_pointer = 0 self.EEG_list = [] self.EMG_list = [] self.EMGAmpl_list = [] self.eeg_spec_list = [] #self.eeg_amp_list = [] # load EEG1 and EMG1 EEG1 = np.squeeze( so.loadmat(os.path.join(self.ppath, self.name, 'EEG.mat'))['EEG']) self.EEG_list.append(EEG1) EMG1 = np.squeeze( so.loadmat(os.path.join(self.ppath, self.name, 'EMG.mat'))['EMG']) self.EMG_list.append(EMG1) # if existing, also load EEG2 and EMG2 if os.path.isfile(os.path.join(self.ppath, self.name, 'EEG2.mat')): EEG2 = np.squeeze( so.loadmat(os.path.join(self.ppath, self.name, 'EEG2.mat'))['EEG2']) self.EEG_list.append(EEG2) # and the same for EMG2 if os.path.isfile(os.path.join(self.ppath, self.name, 'EMG2.mat')): EMG2 = np.squeeze( so.loadmat(os.path.join(self.ppath, self.name, 'EMG2.mat'))['EMG2']) self.EMG_list.append(EMG2) self.EEG = self.EEG_list[0] self.EMG = self.EMG_list[0] # median of EEG signal to scale the laser signal self.eeg_amp = np.median(np.abs(self.EEG)) # load spectrogram / EMG amplitude if not (os.path.isfile( os.path.join(self.ppath, self.name, 'sp_' + self.name + '.mat'))): # spectrogram does not exist, generate it sleepy.calculate_spectrum(self.ppath, self.name, fres=0.5) print("Calculating spectrogram for recording %s\n" % self.name) spec = so.loadmat( os.path.join(self.ppath, self.name, 'sp_' + self.name + '.mat')) self.eeg_spec_list.append(spec['SP']) if 'SP2' in spec: self.eeg_spec_list.append(spec['SP2']) #else: # self.eeg_spec_list.append(spec['SP']) self.eeg_spec = self.eeg_spec_list[0] self.ftime = spec['t'][0] self.fdt = spec['dt'][0][0] freq = np.squeeze(spec['freq']) self.ifreq = np.where(freq <= 25)[0][-1] self.fdx = freq[1] - freq[0] self.mfreq = np.where((freq >= 10) & (freq <= 500))[0] self.freq = freq #correct self.emg_spec = so.loadmat( os.path.join(self.ppath, self.name, 'msp_' + self.name + '.mat')) EMGAmpl1 = np.sqrt(self.emg_spec['mSP'][self.mfreq, :].sum(axis=0)) self.EMGAmpl_list.append(EMGAmpl1) if 'mSP2' in self.emg_spec: EMGAmpl2 = np.sqrt( self.emg_spec['mSP2'][self.mfreq, :].sum(axis=0)) self.EMGAmpl_list.append(EMGAmpl2) #else: # self.EMGAmpl_list.append(EMGAmpl1) self.EMGAmpl = self.EMGAmpl_list[0] # load LFP signals # get all LFP files self.lfp_pointer = -1 self.LFP_list = [] lfp_files = [ f for f in os.listdir(os.path.join(self.ppath, self.name)) if re.match('^LFP', f) ] lfp_files.sort() if len(lfp_files) > 0: self.lfp_pointer = -1 for f in lfp_files: #pdb.set_trace() key = re.split('\\.', f)[0] LFP = so.loadmat(os.path.join(self.ppath, self.name, f), squeeze_me=True)[key] self.LFP_list.append(LFP) #self.LFP_list.append((self.LFP_list[0]-self.LFP_list[1])) # set time bins, sampling rates etc. self.nbin = len(self.ftime) #number of bins in fourier time self.SR = get_snr(self.ppath, self.name) self.dt = 1 / self.SR self.fbin = np.round( (1 / self.dt) * self.fdt) # number of sampled point for one fourier bin if self.fbin % 2 == 1: self.fbin += 1 # load brain state if not (os.path.isfile( os.path.join(self.ppath, self.name, 'remidx_' + self.name + '.txt'))): # predict brain state M, S = sleepy.sleep_state(self.ppath, self.name, pwrite=1, pplot=0) (A, self.K) = load_stateidx(self.ppath, self.name) # set undefined states to 4 #A[np.where(A==0)] = 4 # needs to be packed into 1 x nbin matrix for display self.M = np.zeros((1, self.nbin)) self.M[0, :] = A # backup for brainstate in case somethin goes wrong self.M_old = self.M.copy() # load laser # laser signal in brainstate time self.laser = np.zeros((self.nbin, )) # plot laser? self.pplot_laser = False # supplementary treck signal; for exampal trigger signal from REM-online detection self.suppl_treck = [] self.psuppl = False if os.path.isfile( os.path.join(self.ppath, self.name, 'laser_' + self.name + '.mat')): lsr = load_laser(self.ppath, self.name) (start_idx, end_idx) = laser_start_end(lsr) # laser signal in EEG time self.laser_raw = lsr self.pplot_laser = True if len(start_idx) > 0: for (i, j) in zip(start_idx, end_idx): i = int(np.round(i / self.fbin)) j = int(np.round(j / self.fbin)) self.laser[i:j + 1] = 1 # recording with REM online: #### if os.path.isfile( os.path.join(self.ppath, self.name, 'rem_trig_' + self.name + '.mat')): self.psuppl = True self.suppl_treck = np.zeros((self.nbin, )) trig = load_trigger(self.ppath, self.name) (start_idx, end_idx) = laser_start_end(trig) if len(start_idx) > 0: for (i, j) in zip(start_idx, end_idx): i = int(np.round(i / self.fbin)) j = int(np.round(j / self.fbin)) self.suppl_treck[i:j + 1] = 1 ################################## else: self.laser_raw = np.zeros((len(self.EEG), )) # load information of light/dark cycles self.dark_cycle = get_cycles(self.ppath, self.name)['dark'] # max color for spectrogram self.color_max = np.max(self.eeg_spec)
def load_session(self): self.SR_eeg = sleepy.get_snr(self.ppath, self.name) self.dt = 1/self.SR_eeg # number of sampled point for one fourier bin #self.fbin = np.round((1/self.dt) * 2.5) # graphs going into dock_session self.graph_activity = pg.PlotWidget() self.graph_brainstate = pg.PlotWidget() self.graph_eegspec = pg.PlotWidget() self.graph_emgampl = pg.PlotWidget() # graphs for dock EEG/EMG self.graph_eeg = pg.PlotWidget() self.graph_emg = pg.PlotWidget() # load data ########################################################### # load EEG/EMG self.eeg_pointer = 0 self.emg_pointer = 0 self.EEG_list = [] self.EMG_list = [] self.eeg_spec_list = [] self.emg_amp_list = [] EEG = np.squeeze(so.loadmat(os.path.join(self.ppath, self.name, 'EEG.mat'))['EEG']) self.EEG_list.append(EEG) if os.path.isfile(os.path.join(self.ppath, self.name, 'EEG2.mat')): EEG2 = np.squeeze(so.loadmat(os.path.join(self.ppath, self.name, 'EEG2.mat'))['EEG2']) self.EEG_list.append(EEG2) self.EEG = self.EEG_list[0] EMG = np.squeeze(so.loadmat(os.path.join(self.ppath, self.name, 'EMG.mat'))['EMG']) self.EMG_list.append(EMG) if os.path.isfile(os.path.join(self.ppath, self.name, 'EMG2.mat')): EMG2 = np.squeeze(so.loadmat(os.path.join(self.ppath, self.name, 'EMG2.mat'))['EMG2']) self.EMG_list.append(EMG2) self.EMG = self.EMG_list[0] # load spectrogram / EMG amplitude if not(os.path.isfile(os.path.join(self.ppath, self.name, 'sp_' + self.name + '.mat'))): # spectrogram does not exist, generate it sleepy.calculate_spectrum(self.ppath, self.name, fres=0.5) print("Calculating spectrogram for recording %s\n" % self.name) spec = so.loadmat(os.path.join(self.ppath, self.name, 'sp_' + self.name + '.mat')) self.ftime = spec['t'][0] self.fdt = spec['dt'][0][0] # the first time bin of the spectrogram goes from 0 to 5s; therefore # I add the self.fdt (= 2.5 s) #self.ftime += self.fdt # New lines self.fbin = np.round((1 / self.dt) * self.fdt) if self.fbin % 2 == 1: self.fbin += 1 # END new lines self.eeg_spec = spec['SP'] self.eeg_spec_list.append(spec['SP']) if 'SP2' in spec: self.eeg_spec_list.append(spec['SP2']) # max color for spectrogram color-range self.color_max = np.max(self.eeg_spec) freq = np.squeeze(spec['freq']) self.ifreq = np.where(freq <= 25)[0][-1] self.fdx = freq[1]-freq[0] self.mfreq = np.where((freq>=10) & (freq <= 200))[0] emg_spec = so.loadmat(os.path.join(self.ppath, self.name, 'msp_' + self.name + '.mat')) EMGAmpl = np.sqrt(emg_spec['mSP'][self.mfreq,:].sum(axis=0)) self.EMGAmpl = EMGAmpl self.emg_amp_list.append(EMGAmpl) if 'mSP2' in emg_spec: EMGAmpl2 = np.sqrt(emg_spec['mSP2'][self.mfreq,:].sum(axis=0)) self.emg_amp_list.append(EMGAmpl2) self.nbin = len(self.ftime) #number of bins in fourier time self.len_eeg = len(self.EEG) # load brain state if not(os.path.isfile(os.path.join(self.ppath, self.name, 'remidx_' + self.name + '.txt'))): # predict brain state M,S = sleepy.sleep_state(self.ppath, self.name, pwrite=1, pplot=0) (A,self.K) = sleepy.load_stateidx(self.ppath, self.name) # needs to be packed into 1 x nbin matrix for display self.M = np.zeros((1,self.nbin)) self.M[0,:] = A # load laser self.laser = np.zeros((self.nbin,)) laser_file = os.path.join(self.ppath, self.name, 'laser_' + self.name + '.mat') if os.path.isfile(laser_file): try: self.laser = np.squeeze(so.loadmat(laser_file)['laser']) except: self.laser = np.squeeze(np.array(h5py.File(laser_file,'r').get('laser'))) # downsample laser to brainstate time (idxs, idxe) = laser_start_end(self.laser, SR=self.SR_eeg) # downsample EEG time to spectrogram time idxs = [int(i/self.fbin) for i in idxs] idxe = [int(i/self.fbin) for i in idxe] self.laser_dn = np.zeros((self.nbin,)) for (i,j) in zip(idxs, idxe): self.laser_dn[i:j+1] = 1 # max color for spectrogram self.color_max = np.max(self.eeg_spec) ### END load data ############################################################# # Plot whole session self.dock_session.addWidget(self.graph_treck, row=0, col=0, rowspan=1) self.dock_session.addWidget(self.graph_activity, row=1, col=0, rowspan=1) self.dock_session.addWidget(self.graph_brainstate, row=2, col=0) self.dock_session.addWidget(self.graph_eegspec, row=3, col=0, rowspan=1) self.dock_session.addWidget(self.graph_emgampl, row=4, col=0) # display data # mix colormaps pos = np.array([0, 0.2, 0.4, 0.6, 0.8]) #color = np.array([[0,255,255,255], [255,0,255, 255], [192,192,192,255], (0, 0, 0, 255), (255,255,0, 255)], dtype=np.ubyte) color = np.array([[0,255,255,255], [150,0,255, 255], [192,192,192,255], (0, 0, 0, 255), (255,255,0, 255)], dtype=np.ubyte) cmap = pg.ColorMap(pos, color) self.lut_brainstate = cmap.getLookupTable(0.0, 1.0, 5) pos = np.array([0., 0.05, .2, .4, .6, .9]) color = np.array([[0, 0, 0, 255], [0,0,128,255], [0,255,0,255], [255,255,0, 255], (255,165,0,255), (255,0,0, 255)], dtype=np.ubyte) cmap = pg.ColorMap(pos, color) self.lut_spectrum = cmap.getLookupTable(0.0, 1.0, 256) # plot brainstate self.image_brainstate = pg.ImageItem() self.graph_brainstate.addItem(self.image_brainstate) self.image_brainstate.setImage(self.M.T) self.image_brainstate.scale(self.fdt,1) self.graph_brainstate.setMouseEnabled(x=True, y=False) #self.graph_brainstate.setXLink(self.graph_eegspec) limits = {'xMin': 0*self.fdt, 'xMax': self.ftime[-1], 'yMin': 0, 'yMax': 1} self.graph_brainstate.setLimits(**limits) ax = self.graph_brainstate.getAxis(name='left') labelStyle = {'color': '#FFF', 'font-size': '10pt'} ax.setLabel('Brainstate', units='', **labelStyle) ax.setTicks([[(0, ''), (1, '')]]) ax = self.graph_brainstate.getAxis(name='bottom') ax.setTicks([[]]) self.image_brainstate.setLookupTable(self.lut_brainstate) self.image_brainstate.setLevels([1, 5]) # plot EEG spectrum # clear plot and then reload ImageItem self.graph_eegspec.clear() self.image_eegspec = pg.ImageItem() self.graph_eegspec.addItem(self.image_eegspec) ax = self.graph_eegspec.getAxis(name='bottom') ax.setTicks([[]]) # scale image to seconds, minutes or hours self.image_eegspec.setImage(self.eeg_spec[0:self.ifreq,:].T) self.image_eegspec.scale(self.fdt, 1.0*self.fdx) # mousescroll only allowed along x axis self.graph_eegspec.setMouseEnabled(x=True, y=False) limits = {'xMin': 0*self.fdt, 'xMax': self.ftime[-1], 'yMin': 0, 'yMax': 20} self.graph_eegspec.setLimits(**limits) # label for y-axis ax = self.graph_eegspec.getAxis(name='left') labelStyle = {'color': '#FFF', 'font-size': '10pt'} ax.setLabel('Freq', units='Hz', **labelStyle) # xTicks ax.setTicks([[(0, '0'), (10, '10')]]) # colormap self.image_eegspec.setLookupTable(self.lut_spectrum) # link graph with self.graph_brainstate # and link all other graphs together self.graph_eegspec.setXLink(self.graph_brainstate) self.graph_brainstate.setXLink(self.graph_eegspec) self.graph_eegspec.setXLink(self.graph_treck) # plot EMG ampl self.graph_emgampl.clear() self.graph_emgampl.plot(self.ftime, self.EMGAmpl) self.graph_emgampl.setMouseEnabled(x=False, y=True) self.graph_emgampl.setXLink(self.graph_eegspec) limits = {'xMin': 0, 'xMax': self.ftime[-1]} self.graph_emgampl.setLimits(**limits) # y-axis ax = self.graph_emgampl.getAxis(name='left') labelStyle = {'color': '#FFF', 'font-size': '10pt'} ax.setLabel('EMG', units='uV', **labelStyle) ax.enableAutoSIPrefix(enable=False) # x-axis ax = self.graph_emgampl.getAxis(name='bottom') labelStyle = {'color': '#FFF', 'font-size': '10pt'} ax.setLabel('Time', units='s', **labelStyle) self.graph_eegspec.scene().sigMouseClicked.connect(self.mouse_pressed) self.graph_brainstate.scene().sigMouseClicked.connect(self.mouse_pressed) self.graph_treck.scene().sigMouseClicked.connect(self.mouse_pressed) self.graph_activity.scene().sigMouseClicked.connect(self.mouse_pressed) # setup graph_treck ########################################################### self.graph_treck.setMouseEnabled(x=True, y=False) limits = {'xMin': 0, 'xMax': self.ftime[-1]} self.graph_treck.setLimits(**limits) self.graph_treck.setXLink(self.graph_eegspec) ax = self.graph_treck.getAxis(name='left') labelStyle = {'color': '#FFF', 'font-size': '10pt'} ax.setLabel('Behavior', units='', **labelStyle) ax = self.graph_treck.getAxis(name='bottom') ax.setTicks([[]]) ax = self.graph_treck.getAxis(name='left') label_style = {'color': '#FFF', 'font-size': '10pt'} ax.setLabel('Behavior', units='', **label_style) ax.setTicks([self.ticks]) # END setup graph_treck ####################################################### # setup graph_activity ######################################################## ax = self.graph_activity.getAxis(name='left') limits = {'xMin': 0, 'xMax': self.ftime[-1]} self.graph_activity.setLimits(**limits) labelStyle = {'color': '#FFF', 'font-size': '10pt'} ax.setLabel('Activity', units='', **labelStyle) ax = self.graph_activity.getAxis(name='bottom') ax.setTicks([[]]) #self.graph_activity.setMouseEnabled(x=False, y=True) self.graph_activity.setXLink(self.graph_treck) # END setup graph_activity ##################################################### # Done With dock "Session" #################################################### # plot raw EEG, EMG in dock EEG/EMG (dock_eeg) self.graph_eeg.setXLink(self.graph_emg) self.graph_eeg.setMouseEnabled(x=True, y=True) self.graph_emg.setMouseEnabled(x=True, y=True) self.graph_eeg.setXRange(self.curr_time-self.twin_view/2, self.curr_time+self.twin_view/2, padding=0) # setup graph_eeg ax = self.graph_eeg.getAxis(name='left') labelStyle = {'color': '#FFF', 'font-size': '12pt'} ax.setLabel('EEG', units='uV', **labelStyle) ax = self.graph_eeg.getAxis(name='bottom') ax.setTicks([[]]) ax = self.graph_eeg.getAxis(name='bottom') # setup graph_emg ax = self.graph_emg.getAxis(name='left') labelStyle = {'color': '#FFF', 'font-size': '12pt'} ax.setLabel('EMG', units='uV', **labelStyle) ax = self.graph_eeg.getAxis(name='bottom') ax.setTicks([[]]) ax = self.graph_emg.getAxis(name='bottom') labelStyle = {'color': '#FFF', 'font-size': '10pt'} ax.setLabel('Time', units='s', **labelStyle) self.dock_eeg.addWidget(self.graph_eeg, row=0, col=0) self.dock_eeg.addWidget(self.graph_emg, row=1, col=0)