idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
23,300 | def peak_in_power ( events , dat , s_freq , method , value = None ) : dat = diff ( dat ) # remove 1/f peak = empty ( events . shape [ 0 ] ) peak . fill ( nan ) if method is not None : for i , one_event in enumerate ( events ) : if method == 'peak' : x0 = one_event [ 1 ] - value / 2 * s_freq x1 = one_event [ 1 ] + value / 2 * s_freq elif method == 'interval' : x0 = one_event [ 0 ] x1 = one_event [ 2 ] if x0 < 0 or x1 >= len ( dat ) : peak [ i ] = nan else : f , Pxx = periodogram ( dat [ x0 : x1 ] , s_freq ) idx_peak = Pxx [ f < MAX_FREQUENCY_OF_INTEREST ] . argmax ( ) peak [ i ] = f [ idx_peak ] return peak | Define peak in power of the signal . | 225 | 9 |
23,301 | def power_in_band ( events , dat , s_freq , frequency ) : dat = diff ( dat ) # remove 1/f pw = empty ( events . shape [ 0 ] ) pw . fill ( nan ) for i , one_event in enumerate ( events ) : x0 = one_event [ 0 ] x1 = one_event [ 2 ] if x0 < 0 or x1 >= len ( dat ) : pw [ i ] = nan else : sf , Pxx = periodogram ( dat [ x0 : x1 ] , s_freq ) # find nearest frequencies in sf b0 = asarray ( [ abs ( x - frequency [ 0 ] ) for x in sf ] ) . argmin ( ) b1 = asarray ( [ abs ( x - frequency [ 1 ] ) for x in sf ] ) . argmin ( ) pw [ i ] = mean ( Pxx [ b0 : b1 ] ) return pw | Define power of the signal within frequency band . | 210 | 10 |
23,302 | def make_spindles ( events , power_peaks , powers , dat_det , dat_orig , time , s_freq ) : i , events = _remove_duplicate ( events , dat_det ) power_peaks = power_peaks [ i ] spindles = [ ] for i , one_peak , one_pwr in zip ( events , power_peaks , powers ) : one_spindle = { 'start' : time [ i [ 0 ] ] , 'end' : time [ i [ 2 ] - 1 ] , 'peak_time' : time [ i [ 1 ] ] , 'peak_val_det' : dat_det [ i [ 1 ] ] , 'peak_val_orig' : dat_orig [ i [ 1 ] ] , 'dur' : ( i [ 2 ] - i [ 0 ] ) / s_freq , 'auc_det' : sum ( dat_det [ i [ 0 ] : i [ 2 ] ] ) / s_freq , 'auc_orig' : sum ( dat_orig [ i [ 0 ] : i [ 2 ] ] ) / s_freq , 'rms_det' : sqrt ( mean ( square ( dat_det [ i [ 0 ] : i [ 2 ] ] ) ) ) , 'rms_orig' : sqrt ( mean ( square ( dat_orig [ i [ 0 ] : i [ 2 ] ] ) ) ) , 'power_orig' : one_pwr , 'peak_freq' : one_peak , 'ptp_det' : ptp ( dat_det [ i [ 0 ] : i [ 2 ] ] ) , 'ptp_orig' : ptp ( dat_orig [ i [ 0 ] : i [ 2 ] ] ) } spindles . append ( one_spindle ) return spindles | Create dict for each spindle based on events of time points . | 406 | 13 |
23,303 | def _remove_duplicate ( old_events , dat ) : diff_events = diff ( old_events , axis = 0 ) dupl = where ( ( diff_events [ : , 0 ] == 0 ) & ( diff_events [ : , 2 ] == 0 ) ) [ 0 ] dupl += 1 # more convenient, it copies old_event first and then compares n_nondupl_events = old_events . shape [ 0 ] - len ( dupl ) new_events = zeros ( ( n_nondupl_events , old_events . shape [ 1 ] ) , dtype = 'int' ) if len ( dupl ) : lg . debug ( 'Removing ' + str ( len ( dupl ) ) + ' duplicate events' ) i = 0 indices = [ ] for i_old , one_old_event in enumerate ( old_events ) : if i_old not in dupl : new_events [ i , : ] = one_old_event i += 1 indices . append ( i_old ) else : peak_0 = new_events [ i - 1 , 1 ] peak_1 = one_old_event [ 1 ] if dat [ peak_0 ] >= dat [ peak_1 ] : new_events [ i - 1 , 1 ] = peak_0 else : new_events [ i - 1 , 1 ] = peak_1 return indices , new_events | Remove duplicates from the events . | 301 | 7 |
23,304 | def _detect_start_end ( true_values ) : neg = zeros ( ( 1 ) , dtype = 'bool' ) int_values = asarray ( concatenate ( ( neg , true_values [ : - 1 ] , neg ) ) , dtype = 'int' ) # must discard last value to avoid axis out of bounds cross_threshold = diff ( int_values ) event_starts = where ( cross_threshold == 1 ) [ 0 ] event_ends = where ( cross_threshold == - 1 ) [ 0 ] if len ( event_starts ) : events = vstack ( ( event_starts , event_ends ) ) . T else : events = None return events | From ndarray of bool values return intervals of True values . | 154 | 13 |
23,305 | def _merge_close ( dat , events , time , min_interval ) : if not events . any ( ) : return events no_merge = time [ events [ 1 : , 0 ] - 1 ] - time [ events [ : - 1 , 2 ] ] >= min_interval if no_merge . any ( ) : begs = concatenate ( [ [ events [ 0 , 0 ] ] , events [ 1 : , 0 ] [ no_merge ] ] ) ends = concatenate ( [ events [ : - 1 , 2 ] [ no_merge ] , [ events [ - 1 , 2 ] ] ] ) new_events = vstack ( ( begs , ends ) ) . T else : new_events = asarray ( [ [ events [ 0 , 0 ] , events [ - 1 , 2 ] ] ] ) # add the location of the peak in the middle new_events = insert ( new_events , 1 , 0 , axis = 1 ) for i in new_events : if i [ 2 ] - i [ 0 ] >= 1 : i [ 1 ] = i [ 0 ] + argmax ( dat [ i [ 0 ] : i [ 2 ] ] ) return new_events | Merge together events separated by less than a minimum interval . | 258 | 12 |
23,306 | def _wmorlet ( f0 , sd , sampling_rate , ns = 5 ) : st = 1. / ( 2. * pi * sd ) w_sz = float ( int ( ns * st * sampling_rate ) ) # half time window size t = arange ( - w_sz , w_sz + 1 , dtype = float ) / sampling_rate w = ( exp ( - t ** 2 / ( 2. * st ** 2 ) ) * exp ( 2j * pi * f0 * t ) / sqrt ( sqrt ( pi ) * st * sampling_rate ) ) return w | adapted from nitime | 134 | 5 |
23,307 | def _realwavelets ( s_freq , freqs , dur , width ) : x = arange ( - dur / 2 , dur / 2 , 1 / s_freq ) wavelets = empty ( ( len ( freqs ) , len ( x ) ) ) g = exp ( - ( pi * x ** 2 ) / width ** 2 ) for i , one_freq in enumerate ( freqs ) : y = cos ( 2 * pi * x * one_freq ) wavelets [ i , : ] = y * g return wavelets | Create real wavelets for UCSD . | 119 | 8 |
23,308 | def count_channels ( self ) : merge = self . index [ 'merge' ] if len ( self . idx_chan . selectedItems ( ) ) > 1 : if merge . isEnabled ( ) : return else : merge . setEnabled ( True ) else : self . index [ 'merge' ] . setCheckState ( Qt . Unchecked ) self . index [ 'merge' ] . setEnabled ( False ) | If more than one channel selected activate merge checkbox . | 91 | 11 |
23,309 | def math ( data , operator = None , operator_name = None , axis = None ) : if operator is not None and operator_name is not None : raise TypeError ( 'Parameters "operator" and "operator_name" are ' 'mutually exclusive' ) # turn input into a tuple of functions in operators if operator_name is not None : if isinstance ( operator_name , str ) : operator_name = ( operator_name , ) operators = [ ] for one_operator_name in operator_name : operators . append ( eval ( one_operator_name ) ) operator = tuple ( operators ) # make it an iterable if callable ( operator ) : operator = ( operator , ) operations = [ ] for one_operator in operator : on_axis = False keepdims = True try : args = getfullargspec ( one_operator ) . args except TypeError : lg . debug ( 'func ' + str ( one_operator ) + ' is not a Python ' 'function' ) else : if 'axis' in args : on_axis = True if axis is None : raise TypeError ( 'You need to specify an axis if you ' 'use ' + one_operator . __name__ + ' (which applies to an axis)' ) if 'keepdims' in args or one_operator in NOKEEPDIM : keepdims = False operations . append ( { 'name' : one_operator . __name__ , 'func' : one_operator , 'on_axis' : on_axis , 'keepdims' : keepdims , } ) output = data . _copy ( ) if axis is not None : idx_axis = data . index_of ( axis ) first_op = True for op in operations : #lg.info('running operator: ' + op['name']) func = op [ 'func' ] if func == mode : func = lambda x , axis : mode ( x , axis = axis ) [ 0 ] for i in range ( output . number_of ( 'trial' ) ) : # don't copy original data, but use data if it's the first operation if first_op : x = data ( trial = i ) else : x = output ( trial = i ) if op [ 'on_axis' ] : lg . debug ( 'running ' + op [ 'name' ] + ' on ' + str ( idx_axis ) ) try : if func == diff : lg . debug ( 'Diff has one-point of zero padding' ) x = _pad_one_axis_one_value ( x , idx_axis ) output . data [ i ] = func ( x , axis = idx_axis ) except IndexError : raise ValueError ( 'The axis ' + axis + ' does not ' 'exist in [' + ', ' . join ( list ( data . axis . keys ( ) ) ) + ']' ) else : lg . debug ( 'running ' + op [ 'name' ] + ' on each datapoint' ) output . data [ i ] = func ( x ) first_op = False if op [ 'on_axis' ] and not op [ 'keepdims' ] : del output . axis [ axis ] return output | Apply mathematical operation to each trial and channel individually . | 693 | 10 |
23,310 | def get_descriptives ( data ) : output = { } dat_log = log ( abs ( data ) ) output [ 'mean' ] = nanmean ( data , axis = 0 ) output [ 'sd' ] = nanstd ( data , axis = 0 ) output [ 'mean_log' ] = nanmean ( dat_log , axis = 0 ) output [ 'sd_log' ] = nanstd ( dat_log , axis = 0 ) return output | Get mean SD and mean and SD of log values . | 99 | 11 |
23,311 | def _read_info_as_dict ( fid , values ) : output = { } for key , fmt in values : val = unpack ( fmt , fid . read ( calcsize ( fmt ) ) ) if len ( val ) == 1 : output [ key ] = val [ 0 ] else : output [ key ] = val return output | Convenience function to read info in axon data to a nicely organized dict . | 72 | 17 |
23,312 | def read_settings ( widget , value_name ) : setting_name = widget + '/' + value_name default_value = DEFAULTS [ widget ] [ value_name ] default_type = type ( default_value ) if default_type is list : default_type = type ( default_value [ 0 ] ) val = settings . value ( setting_name , default_value , type = default_type ) return val | Read Settings information either from INI or from default values . | 91 | 12 |
23,313 | def create_settings ( self ) : bbox = QDialogButtonBox ( QDialogButtonBox . Ok | QDialogButtonBox . Apply | QDialogButtonBox . Cancel ) self . idx_ok = bbox . button ( QDialogButtonBox . Ok ) self . idx_apply = bbox . button ( QDialogButtonBox . Apply ) self . idx_cancel = bbox . button ( QDialogButtonBox . Cancel ) bbox . clicked . connect ( self . button_clicked ) page_list = QListWidget ( ) page_list . setSpacing ( 1 ) page_list . currentRowChanged . connect ( self . change_widget ) pages = [ 'General' , 'Overview' , 'Signals' , 'Channels' , 'Spectrum' , 'Notes' , 'Video' ] for one_page in pages : page_list . addItem ( one_page ) self . stacked = QStackedWidget ( ) self . stacked . addWidget ( self . config ) self . stacked . addWidget ( self . parent . overview . config ) self . stacked . addWidget ( self . parent . traces . config ) self . stacked . addWidget ( self . parent . channels . config ) self . stacked . addWidget ( self . parent . spectrum . config ) self . stacked . addWidget ( self . parent . notes . config ) self . stacked . addWidget ( self . parent . video . config ) hsplitter = QSplitter ( ) hsplitter . addWidget ( page_list ) hsplitter . addWidget ( self . stacked ) btnlayout = QHBoxLayout ( ) btnlayout . addStretch ( 1 ) btnlayout . addWidget ( bbox ) vlayout = QVBoxLayout ( ) vlayout . addWidget ( hsplitter ) vlayout . addLayout ( btnlayout ) self . setLayout ( vlayout ) | Create the widget organized in two parts . | 404 | 8 |
23,314 | def create_values ( self , value_names ) : output = { } for value_name in value_names : output [ value_name ] = read_settings ( self . widget , value_name ) return output | Read original values from the settings or the defaults . | 46 | 10 |
23,315 | def get_values ( self ) : for value_name , widget in self . index . items ( ) : self . value [ value_name ] = widget . get_value ( self . value [ value_name ] ) setting_name = self . widget + '/' + value_name settings . setValue ( setting_name , self . value [ value_name ] ) | Get values from the GUI and save them in preference file . | 79 | 12 |
23,316 | def put_values ( self ) : for value_name , widget in self . index . items ( ) : widget . set_value ( self . value [ value_name ] ) widget . connect ( self . set_modified ) | Put values to the GUI . | 48 | 6 |
23,317 | def _get_indices ( values , selected , tolerance ) : idx_data = [ ] idx_output = [ ] for idx_of_selected , one_selected in enumerate ( selected ) : if tolerance is None or values . dtype . kind == 'U' : idx_of_data = where ( values == one_selected ) [ 0 ] else : idx_of_data = where ( abs ( values - one_selected ) <= tolerance ) [ 0 ] # actual use min if len ( idx_of_data ) > 0 : idx_data . append ( idx_of_data [ 0 ] ) idx_output . append ( idx_of_selected ) return idx_data , idx_output | Get indices based on user - selected values . | 163 | 9 |
23,318 | def number_of ( self , axis ) : if axis == 'trial' : return len ( self . data ) else : n_trial = self . number_of ( 'trial' ) output = empty ( n_trial , dtype = 'int' ) for i in range ( n_trial ) : output [ i ] = len ( self . axis [ axis ] [ i ] ) return output | Return the number of in one axis as generally as possible . | 84 | 12 |
23,319 | def _copy ( self , axis = True , attr = True , data = False ) : cdata = type ( self ) ( ) # create instance of the same class cdata . s_freq = self . s_freq cdata . start_time = self . start_time if axis : cdata . axis = deepcopy ( self . axis ) else : cdata_axis = OrderedDict ( ) for axis_name in self . axis : cdata_axis [ axis_name ] = array ( [ ] , dtype = 'O' ) cdata . axis = cdata_axis if attr : cdata . attr = deepcopy ( self . attr ) if data : cdata . data = deepcopy ( self . data ) else : # empty data with the correct number of trials cdata . data = empty ( self . number_of ( 'trial' ) , dtype = 'O' ) return cdata | Create a new instance of Data but does not copy the data necessarily . | 202 | 14 |
23,320 | def export ( self , filename , export_format = 'FieldTrip' , * * options ) : filename = Path ( filename ) filename . parent . mkdir ( parents = True , exist_ok = True ) export_format = export_format . lower ( ) if export_format == 'edf' : from . ioeeg import write_edf # avoid circular import write_edf ( self , filename , * * options ) elif export_format == 'fieldtrip' : from . ioeeg import write_fieldtrip # avoid circular import write_fieldtrip ( self , filename ) elif export_format == 'mnefiff' : from . ioeeg import write_mnefiff write_mnefiff ( self , filename ) elif export_format == 'wonambi' : from . ioeeg import write_wonambi write_wonambi ( self , filename , * * options ) elif export_format == 'brainvision' : from . ioeeg import write_brainvision write_brainvision ( self , filename , * * options ) elif export_format == 'bids' : from . ioeeg import write_bids write_bids ( self , filename , * * options ) else : raise ValueError ( 'Cannot export to ' + export_format ) | Export data in other formats . | 285 | 6 |
23,321 | def highlight_channels ( self , l , selected_chan ) : for row in range ( l . count ( ) ) : item = l . item ( row ) if item . text ( ) in selected_chan : item . setSelected ( True ) else : item . setSelected ( False ) | Highlight channels in the list of channels . | 64 | 9 |
23,322 | def rereference ( self ) : selectedItems = self . idx_l0 . selectedItems ( ) chan_to_plot = [ ] for selected in selectedItems : chan_to_plot . append ( selected . text ( ) ) self . highlight_channels ( self . idx_l1 , chan_to_plot ) | Automatically highlight channels to use as reference based on selected channels . | 74 | 13 |
23,323 | def get_info ( self ) : selectedItems = self . idx_l0 . selectedItems ( ) selected_chan = [ x . text ( ) for x in selectedItems ] chan_to_plot = [ ] for chan in self . chan_name + [ '_REF' ] : if chan in selected_chan : chan_to_plot . append ( chan ) selectedItems = self . idx_l1 . selectedItems ( ) ref_chan = [ ] for selected in selectedItems : ref_chan . append ( selected . text ( ) ) hp = self . idx_hp . value ( ) if hp == 0 : low_cut = None else : low_cut = hp lp = self . idx_lp . value ( ) if lp == 0 : high_cut = None else : high_cut = lp scale = self . idx_scale . value ( ) group_info = { 'name' : self . group_name , 'chan_to_plot' : chan_to_plot , 'ref_chan' : ref_chan , 'hp' : low_cut , 'lp' : high_cut , 'scale' : float ( scale ) , 'color' : self . idx_color } return group_info | Get the information about the channel groups . | 278 | 8 |
23,324 | def create ( self ) : add_button = QPushButton ( 'New' ) add_button . clicked . connect ( self . new_group ) color_button = QPushButton ( 'Color' ) color_button . clicked . connect ( self . color_group ) del_button = QPushButton ( 'Delete' ) del_button . clicked . connect ( self . del_group ) apply_button = QPushButton ( 'Apply' ) apply_button . clicked . connect ( self . apply ) self . button_add = add_button self . button_color = color_button self . button_del = del_button self . button_apply = apply_button buttons = QGridLayout ( ) buttons . addWidget ( add_button , 0 , 0 ) buttons . addWidget ( color_button , 1 , 0 ) buttons . addWidget ( del_button , 0 , 1 ) buttons . addWidget ( apply_button , 1 , 1 ) self . tabs = QTabWidget ( ) layout = QVBoxLayout ( ) layout . addLayout ( buttons ) layout . addWidget ( self . tabs ) self . setLayout ( layout ) self . setEnabled ( False ) self . button_color . setEnabled ( False ) self . button_del . setEnabled ( False ) self . button_apply . setEnabled ( False ) | Create Channels Widget | 283 | 5 |
23,325 | def create_action ( self ) : actions = { } act = QAction ( 'Load Montage...' , self ) act . triggered . connect ( self . load_channels ) act . setEnabled ( False ) actions [ 'load_channels' ] = act act = QAction ( 'Save Montage...' , self ) act . triggered . connect ( self . save_channels ) act . setEnabled ( False ) actions [ 'save_channels' ] = act self . action = actions | Create actions related to channel selection . | 107 | 7 |
23,326 | def new_group ( self , checked = False , test_name = None ) : chan_name = self . parent . labels . chan_name if chan_name is None : msg = 'No dataset loaded' self . parent . statusBar ( ) . showMessage ( msg ) lg . debug ( msg ) else : if test_name is None : new_name = QInputDialog . getText ( self , 'New Channel Group' , 'Enter Name' ) else : new_name = [ test_name , True ] # like output of getText if new_name [ 1 ] : s_freq = self . parent . info . dataset . header [ 's_freq' ] group = ChannelsGroup ( chan_name , new_name [ 0 ] , self . config . value , s_freq ) self . tabs . addTab ( group , new_name [ 0 ] ) self . tabs . setCurrentIndex ( self . tabs . currentIndex ( ) + 1 ) # activate buttons self . button_color . setEnabled ( True ) self . button_del . setEnabled ( True ) self . button_apply . setEnabled ( True ) | Create a new channel group . | 251 | 6 |
23,327 | def color_group ( self , checked = False , test_color = None ) : group = self . tabs . currentWidget ( ) if test_color is None : newcolor = QColorDialog . getColor ( group . idx_color ) else : newcolor = test_color group . idx_color = newcolor self . apply ( ) | Change the color of the group . | 74 | 7 |
23,328 | def del_group ( self ) : idx = self . tabs . currentIndex ( ) self . tabs . removeTab ( idx ) self . apply ( ) | Delete current group . | 34 | 4 |
23,329 | def apply ( self ) : self . read_group_info ( ) if self . tabs . count ( ) == 0 : # disactivate buttons self . button_color . setEnabled ( False ) self . button_del . setEnabled ( False ) self . button_apply . setEnabled ( False ) else : # activate buttons self . button_color . setEnabled ( True ) self . button_del . setEnabled ( True ) self . button_apply . setEnabled ( True ) if self . groups : self . parent . overview . update_position ( ) self . parent . spectrum . update ( ) self . parent . notes . enable_events ( ) else : self . parent . traces . reset ( ) self . parent . spectrum . reset ( ) self . parent . notes . enable_events ( ) | Apply changes to the plots . | 168 | 6 |
23,330 | def read_group_info ( self ) : self . groups = [ ] for i in range ( self . tabs . count ( ) ) : one_group = self . tabs . widget ( i ) . get_info ( ) # one_group['name'] = self.tabs.tabText(i) self . groups . append ( one_group ) | Get information about groups directly from the widget . | 76 | 9 |
23,331 | def load_channels ( self , checked = False , test_name = None ) : chan_name = self . parent . labels . chan_name if self . filename is not None : filename = self . filename elif self . parent . info . filename is not None : filename = ( splitext ( self . parent . info . filename ) [ 0 ] + '_channels.json' ) else : filename = None if test_name is None : filename , _ = QFileDialog . getOpenFileName ( self , 'Open Channels Montage' , filename , 'Channels File (*.json)' ) else : filename = test_name if filename == '' : return self . filename = filename with open ( filename , 'r' ) as outfile : groups = load ( outfile ) s_freq = self . parent . info . dataset . header [ 's_freq' ] no_in_dataset = [ ] for one_grp in groups : no_in_dataset . extend ( set ( one_grp [ 'chan_to_plot' ] ) - set ( chan_name ) ) chan_to_plot = set ( chan_name ) & set ( one_grp [ 'chan_to_plot' ] ) ref_chan = set ( chan_name ) & set ( one_grp [ 'ref_chan' ] ) group = ChannelsGroup ( chan_name , one_grp [ 'name' ] , one_grp , s_freq ) group . highlight_channels ( group . idx_l0 , chan_to_plot ) group . highlight_channels ( group . idx_l1 , ref_chan ) self . tabs . addTab ( group , one_grp [ 'name' ] ) if no_in_dataset : msg = 'Channels not present in the dataset: ' + ', ' . join ( no_in_dataset ) self . parent . statusBar ( ) . showMessage ( msg ) lg . debug ( msg ) self . apply ( ) | Load channel groups from file . | 455 | 6 |
23,332 | def save_channels ( self , checked = False , test_name = None ) : self . read_group_info ( ) if self . filename is not None : filename = self . filename elif self . parent . info . filename is not None : filename = ( splitext ( self . parent . info . filename ) [ 0 ] + '_channels.json' ) else : filename = None if test_name is None : filename , _ = QFileDialog . getSaveFileName ( self , 'Save Channels Montage' , filename , 'Channels File (*.json)' ) else : filename = test_name if filename == '' : return self . filename = filename groups = deepcopy ( self . groups ) for one_grp in groups : one_grp [ 'color' ] = one_grp [ 'color' ] . rgba ( ) with open ( filename , 'w' ) as outfile : dump ( groups , outfile , indent = ' ' ) | Save channel groups to file . | 211 | 6 |
23,333 | def reset ( self ) : self . filename = None self . groups = [ ] self . tabs . clear ( ) self . setEnabled ( False ) self . button_color . setEnabled ( False ) self . button_del . setEnabled ( False ) self . button_apply . setEnabled ( False ) self . action [ 'load_channels' ] . setEnabled ( False ) self . action [ 'save_channels' ] . setEnabled ( False ) | Reset all the information of this widget . | 98 | 9 |
23,334 | def create ( self ) : self . idx_chan = QComboBox ( ) self . idx_chan . activated . connect ( self . display_window ) self . idx_fig = QGraphicsView ( self ) self . idx_fig . scale ( 1 , - 1 ) layout = QVBoxLayout ( ) layout . addWidget ( self . idx_chan ) layout . addWidget ( self . idx_fig ) self . setLayout ( layout ) self . resizeEvent ( None ) | Create empty scene for power spectrum . | 109 | 7 |
23,335 | def update ( self ) : self . idx_chan . clear ( ) for chan_name in self . parent . traces . chan : self . idx_chan . addItem ( chan_name ) if self . selected_chan is not None : self . idx_chan . setCurrentIndex ( self . selected_chan ) self . selected_chan = None | Add channel names to the combobox . | 80 | 9 |
23,336 | def display_window ( self ) : if self . idx_chan . count ( ) == 0 : self . update ( ) chan_name = self . idx_chan . currentText ( ) lg . debug ( 'Power spectrum for channel ' + chan_name ) if chan_name : trial = 0 data = self . parent . traces . data ( trial = trial , chan = chan_name ) self . display ( data ) else : self . scene . clear ( ) | Read the channel name from QComboBox and plot its spectrum . | 106 | 14 |
23,337 | def display ( self , data ) : value = self . config . value self . scene = QGraphicsScene ( value [ 'x_min' ] , value [ 'y_min' ] , value [ 'x_max' ] - value [ 'x_min' ] , value [ 'y_max' ] - value [ 'y_min' ] ) self . idx_fig . setScene ( self . scene ) self . add_grid ( ) self . resizeEvent ( None ) s_freq = self . parent . traces . data . s_freq f , Pxx = welch ( data , fs = s_freq , nperseg = int ( min ( ( s_freq , len ( data ) ) ) ) ) # force int freq_limit = ( value [ 'x_min' ] <= f ) & ( f <= value [ 'x_max' ] ) if self . config . value [ 'log' ] : Pxx_to_plot = log ( Pxx [ freq_limit ] ) else : Pxx_to_plot = Pxx [ freq_limit ] self . scene . addPath ( Path ( f [ freq_limit ] , Pxx_to_plot ) , QPen ( QColor ( LINE_COLOR ) , LINE_WIDTH ) ) | Make graphicsitem for spectrum figure . | 284 | 7 |
23,338 | def add_grid ( self ) : value = self . config . value # X-AXIS # x-bottom self . scene . addLine ( value [ 'x_min' ] , value [ 'y_min' ] , value [ 'x_min' ] , value [ 'y_max' ] , QPen ( QColor ( LINE_COLOR ) , LINE_WIDTH ) ) # at y = 0, dashed self . scene . addLine ( value [ 'x_min' ] , 0 , value [ 'x_max' ] , 0 , QPen ( QColor ( LINE_COLOR ) , LINE_WIDTH , Qt . DashLine ) ) # ticks on y-axis y_high = int ( floor ( value [ 'y_max' ] ) ) y_low = int ( ceil ( value [ 'y_min' ] ) ) x_length = ( value [ 'x_max' ] - value [ 'x_min' ] ) / value [ 'x_tick' ] for y in range ( y_low , y_high ) : self . scene . addLine ( value [ 'x_min' ] , y , value [ 'x_min' ] + x_length , y , QPen ( QColor ( LINE_COLOR ) , LINE_WIDTH ) ) # Y-AXIS # left axis self . scene . addLine ( value [ 'x_min' ] , value [ 'y_min' ] , value [ 'x_max' ] , value [ 'y_min' ] , QPen ( QColor ( LINE_COLOR ) , LINE_WIDTH ) ) # larger ticks on x-axis every 10 Hz x_high = int ( floor ( value [ 'x_max' ] ) ) x_low = int ( ceil ( value [ 'x_min' ] ) ) y_length = ( value [ 'y_max' ] - value [ 'y_min' ] ) / value [ 'y_tick' ] for x in range ( x_low , x_high , 10 ) : self . scene . addLine ( x , value [ 'y_min' ] , x , value [ 'y_min' ] + y_length , QPen ( QColor ( LINE_COLOR ) , LINE_WIDTH ) ) # smaller ticks on x-axis every 10 Hz y_length = ( value [ 'y_max' ] - value [ 'y_min' ] ) / value [ 'y_tick' ] / 2 for x in range ( x_low , x_high , 5 ) : self . scene . addLine ( x , value [ 'y_min' ] , x , value [ 'y_min' ] + y_length , QPen ( QColor ( LINE_COLOR ) , LINE_WIDTH ) ) | Add axis and ticks to figure . | 610 | 7 |
23,339 | def resizeEvent ( self , event ) : value = self . config . value self . idx_fig . fitInView ( value [ 'x_min' ] , value [ 'y_min' ] , value [ 'x_max' ] - value [ 'x_min' ] , value [ 'y_max' ] - value [ 'y_min' ] ) | Fit the whole scene in view . | 81 | 7 |
23,340 | def reset ( self ) : self . idx_chan . clear ( ) if self . scene is not None : self . scene . clear ( ) self . scene = None | Reset widget as new | 36 | 5 |
23,341 | def detect_Massimini2004 ( dat_orig , s_freq , time , opts ) : if opts . invert : dat_orig = - dat_orig dat_det = transform_signal ( dat_orig , s_freq , 'double_butter' , opts . det_filt ) above_zero = detect_events ( dat_det , 'above_thresh' , value = 0. ) sw_in_chan = [ ] if above_zero is not None : troughs = within_duration ( above_zero , time , opts . trough_duration ) #lg.info('troughs within duration: ' + str(troughs.shape)) if troughs is not None : troughs = select_peaks ( dat_det , troughs , opts . max_trough_amp ) #lg.info('troughs deep enough: ' + str(troughs.shape)) if troughs is not None : events = _add_halfwave ( dat_det , troughs , s_freq , opts ) #lg.info('SWs high enough: ' + str(events.shape)) if len ( events ) : events = within_duration ( events , time , opts . duration ) events = remove_straddlers ( events , time , s_freq ) #lg.info('SWs within duration: ' + str(events.shape)) sw_in_chan = make_slow_waves ( events , dat_det , time , s_freq ) if len ( sw_in_chan ) == 0 : lg . info ( 'No slow wave found' ) return sw_in_chan | Slow wave detection based on Massimini et al . 2004 . | 368 | 13 |
23,342 | def select_peaks ( data , events , limit ) : selected = abs ( data [ events [ : , 1 ] ] ) >= abs ( limit ) return events [ selected , : ] | Check whether event satisfies amplitude limit . | 39 | 7 |
23,343 | def make_slow_waves ( events , data , time , s_freq ) : slow_waves = [ ] for ev in events : one_sw = { 'start' : time [ ev [ 0 ] ] , 'trough_time' : time [ ev [ 1 ] ] , 'zero_time' : time [ ev [ 2 ] ] , 'peak_time' : time [ ev [ 3 ] ] , 'end' : time [ ev [ 4 ] - 1 ] , 'trough_val' : data [ ev [ 1 ] ] , 'peak_val' : data [ ev [ 3 ] ] , 'dur' : ( ev [ 4 ] - ev [ 0 ] ) / s_freq , 'ptp' : abs ( ev [ 3 ] - ev [ 1 ] ) } slow_waves . append ( one_sw ) return slow_waves | Create dict for each slow wave based on events of time points . | 187 | 13 |
23,344 | def _add_halfwave ( data , events , s_freq , opts ) : max_dur = opts . duration [ 1 ] if max_dur is None : max_dur = MAXIMUM_DURATION window = int ( s_freq * max_dur ) peak_and_end = zeros ( ( events . shape [ 0 ] , 2 ) , dtype = 'int' ) events = concatenate ( ( events , peak_and_end ) , axis = 1 ) selected = [ ] for ev in events : zero_crossings = where ( diff ( sign ( data [ ev [ 2 ] : ev [ 0 ] + window ] ) ) ) [ 0 ] if zero_crossings . any ( ) : ev [ 4 ] = ev [ 2 ] + zero_crossings [ 0 ] + 1 #lg.info('0cross is at ' + str(ev[4])) else : selected . append ( False ) #lg.info('no 0cross, rejected') continue ev [ 3 ] = ev [ 2 ] + argmin ( data [ ev [ 2 ] : ev [ 4 ] ] ) if abs ( data [ ev [ 1 ] ] - data [ ev [ 3 ] ] ) < opts . min_ptp : selected . append ( False ) #lg.info('ptp too low, rejected: ' + str(abs(data[ev[1]] - data[ev[3]]))) continue selected . append ( True ) #lg.info('SW checks out, accepted! ptp is ' + str(abs(data[ev[1]] - data[ev[3]]))) return events [ selected , : ] | Find the next zero crossing and the intervening peak and add them to events . If no zero found before max_dur event is discarded . If peak - to - peak is smaller than min_ptp the event is discarded . | 364 | 46 |
23,345 | def create ( self ) : """ ------ MARKERS ------ """ tab0 = QTableWidget ( ) self . idx_marker = tab0 tab0 . setColumnCount ( 3 ) tab0 . horizontalHeader ( ) . setStretchLastSection ( True ) tab0 . setSelectionBehavior ( QAbstractItemView . SelectRows ) tab0 . setEditTriggers ( QAbstractItemView . NoEditTriggers ) go_to_marker = lambda r , c : self . go_to_marker ( r , c , 'dataset' ) tab0 . cellDoubleClicked . connect ( go_to_marker ) tab0 . setHorizontalHeaderLabels ( [ 'Start' , 'Duration' , 'Text' ] ) """ ------ SUMMARY ------ """ tab1 = QWidget ( ) self . idx_eventtype = QComboBox ( self ) self . idx_stage = QComboBox ( self ) self . idx_stage . activated . connect ( self . get_sleepstage ) self . idx_quality = QComboBox ( self ) self . idx_quality . activated . connect ( self . get_quality ) self . idx_annotations = QPushButton ( 'Load Annotation File...' ) self . idx_annotations . clicked . connect ( self . load_annot ) self . idx_rater = QLabel ( '' ) b0 = QGroupBox ( 'Info' ) form = QFormLayout ( ) b0 . setLayout ( form ) form . addRow ( 'File:' , self . idx_annotations ) form . addRow ( 'Rater:' , self . idx_rater ) b1 = QGroupBox ( 'Staging' ) b2 = QGroupBox ( 'Signal quality' ) layout = QVBoxLayout ( ) layout . addWidget ( b0 ) layout . addWidget ( b1 ) layout . addWidget ( b2 ) self . idx_summary = layout tab1 . setLayout ( layout ) """ ------ ANNOTATIONS ------ """ tab2 = QWidget ( ) tab_annot = QTableWidget ( ) self . idx_annot_list = tab_annot delete_row = QPushButton ( 'Delete' ) delete_row . clicked . connect ( self . delete_row ) scroll = QScrollArea ( tab2 ) scroll . setWidgetResizable ( True ) evttype_group = QGroupBox ( 'Event Types' ) scroll . setWidget ( evttype_group ) self . idx_eventtype_scroll = scroll tab_annot . setColumnCount ( 5 ) tab_annot . setHorizontalHeaderLabels ( [ 'Start' , 'Duration' , 'Text' , 'Type' , 'Channel' ] ) tab_annot . horizontalHeader ( ) . setStretchLastSection ( True ) tab_annot . setSelectionBehavior ( QAbstractItemView . SelectRows ) tab_annot . setEditTriggers ( QAbstractItemView . NoEditTriggers ) go_to_annot = lambda r , c : self . go_to_marker ( r , c , 'annot' ) tab_annot . cellDoubleClicked . connect ( go_to_annot ) tab_annot . cellDoubleClicked . connect ( self . reset_current_row ) layout = QVBoxLayout ( ) layout . addWidget ( self . idx_eventtype_scroll , stretch = 1 ) layout . addWidget ( self . idx_annot_list ) layout . addWidget ( delete_row ) tab2 . setLayout ( layout ) """ ------ TABS ------ """ self . addTab ( tab0 , 'Markers' ) self . addTab ( tab1 , 'Summary' ) # disable self . addTab ( tab2 , 'Annotations' ) | Create the widget layout with all the annotations . | 824 | 9 |
23,346 | def update_notes ( self , xml_file , new = False ) : if new : create_empty_annotations ( xml_file , self . parent . info . dataset ) self . annot = Annotations ( xml_file ) else : self . annot = Annotations ( xml_file ) self . enable_events ( ) self . parent . create_menubar ( ) self . idx_stage . clear ( ) for one_stage in STAGE_NAME : self . idx_stage . addItem ( one_stage ) self . idx_stage . setCurrentIndex ( - 1 ) self . idx_quality . clear ( ) for one_qual in QUALIFIERS : self . idx_quality . addItem ( one_qual ) self . idx_quality . setCurrentIndex ( - 1 ) w1 = self . idx_summary . takeAt ( 1 ) . widget ( ) w2 = self . idx_summary . takeAt ( 1 ) . widget ( ) self . idx_summary . removeWidget ( w1 ) self . idx_summary . removeWidget ( w2 ) w1 . deleteLater ( ) w2 . deleteLater ( ) b1 = QGroupBox ( 'Staging' ) layout = QFormLayout ( ) for one_stage in STAGE_NAME : layout . addRow ( one_stage , QLabel ( '' ) ) b1 . setLayout ( layout ) self . idx_summary . addWidget ( b1 ) self . idx_stage_stats = layout b2 = QGroupBox ( 'Signal quality' ) layout = QFormLayout ( ) for one_qual in QUALIFIERS : layout . addRow ( one_qual , QLabel ( '' ) ) b2 . setLayout ( layout ) self . idx_summary . addWidget ( b2 ) self . idx_qual_stats = layout self . display_notes ( ) | Update information about the sleep scoring . | 412 | 7 |
23,347 | def enable_events ( self ) : if self . annot is not None and self . parent . channels . groups : self . action [ 'spindle' ] . setEnabled ( True ) self . action [ 'slow_wave' ] . setEnabled ( True ) self . action [ 'analyze' ] . setEnabled ( True ) else : self . action [ 'spindle' ] . setEnabled ( False ) self . action [ 'slow_wave' ] . setEnabled ( False ) self . action [ 'analyze' ] . setEnabled ( False ) | enable slow wave and spindle detection if both annotations and channels are active . | 118 | 15 |
23,348 | def display_notes ( self ) : if self . annot is not None : short_xml_file = short_strings ( basename ( self . annot . xml_file ) ) self . idx_annotations . setText ( short_xml_file ) # if annotations were loaded without dataset if self . parent . overview . scene is None : self . parent . overview . update ( ) if not self . annot . raters : self . new_rater ( ) self . idx_rater . setText ( self . annot . current_rater ) self . display_eventtype ( ) self . update_annotations ( ) self . display_stats ( ) self . epoch_length = self . annot . epoch_length | Display information about scores and raters . | 155 | 8 |
23,349 | def display_stats ( self ) : for i , one_stage in enumerate ( STAGE_NAME ) : second_in_stage = self . annot . time_in_stage ( one_stage ) time_in_stage = str ( timedelta ( seconds = second_in_stage ) ) label = self . idx_stage_stats . itemAt ( i , QFormLayout . FieldRole ) . widget ( ) label . setText ( time_in_stage ) for i , one_qual in enumerate ( QUALIFIERS ) : second_in_qual = self . annot . time_in_stage ( one_qual , attr = 'quality' ) time_in_qual = str ( timedelta ( seconds = second_in_qual ) ) label = self . idx_qual_stats . itemAt ( i , QFormLayout . FieldRole ) . widget ( ) label . setText ( time_in_qual ) | Display summary statistics about duration in each stage . | 204 | 9 |
23,350 | def add_bookmark ( self , time ) : if self . annot is None : # remove if buttons are disabled msg = 'No score file loaded' lg . debug ( msg ) error_dialog = QErrorMessage ( ) error_dialog . setWindowTitle ( 'Error adding bookmark' ) error_dialog . showMessage ( msg ) error_dialog . exec ( ) return answer = QInputDialog . getText ( self , 'New Bookmark' , 'Enter bookmark\'s name' ) if answer [ 1 ] : name = answer [ 0 ] self . annot . add_bookmark ( name , time ) lg . info ( 'Added Bookmark ' + name + 'at ' + str ( time ) ) self . update_annotations ( ) | Run this function when user adds a new bookmark . | 163 | 10 |
23,351 | def remove_bookmark ( self , time ) : self . annot . remove_bookmark ( time = time ) self . update_annotations ( ) | User removes bookmark . | 32 | 4 |
23,352 | def update_dataset_marker ( self ) : start_time = self . parent . overview . start_time markers = [ ] if self . parent . info . markers is not None : markers = self . parent . info . markers self . idx_marker . clearContents ( ) self . idx_marker . setRowCount ( len ( markers ) ) for i , mrk in enumerate ( markers ) : abs_time = ( start_time + timedelta ( seconds = mrk [ 'start' ] ) ) . strftime ( '%H:%M:%S' ) dur = timedelta ( seconds = mrk [ 'end' ] - mrk [ 'start' ] ) duration = '{0:02d}.{1:03d}' . format ( dur . seconds , round ( dur . microseconds / 1000 ) ) item_time = QTableWidgetItem ( abs_time ) item_duration = QTableWidgetItem ( duration ) item_name = QTableWidgetItem ( mrk [ 'name' ] ) color = self . parent . value ( 'marker_color' ) item_time . setForeground ( QColor ( color ) ) item_duration . setForeground ( QColor ( color ) ) item_name . setForeground ( QColor ( color ) ) self . idx_marker . setItem ( i , 0 , item_time ) self . idx_marker . setItem ( i , 1 , item_duration ) self . idx_marker . setItem ( i , 2 , item_name ) # store information about the time as list (easy to access) marker_start = [ mrk [ 'start' ] for mrk in markers ] marker_end = [ mrk [ 'end' ] for mrk in markers ] self . idx_marker . setProperty ( 'start' , marker_start ) self . idx_marker . setProperty ( 'end' , marker_end ) if self . parent . traces . data is not None : self . parent . traces . display ( ) self . parent . overview . display_markers ( ) | Update markers which are in the dataset . It always updates the list of events . Depending on the settings it might add the markers to overview and traces . | 470 | 30 |
23,353 | def display_eventtype ( self ) : if self . annot is not None : event_types = sorted ( self . annot . event_types , key = str . lower ) else : event_types = [ ] self . idx_eventtype . clear ( ) evttype_group = QGroupBox ( 'Event Types' ) layout = QVBoxLayout ( ) evttype_group . setLayout ( layout ) self . check_all_eventtype = check_all = QCheckBox ( 'All event types' ) check_all . setCheckState ( Qt . Checked ) check_all . clicked . connect ( self . toggle_eventtype ) layout . addWidget ( check_all ) self . idx_eventtype_list = [ ] for one_eventtype in event_types : self . idx_eventtype . addItem ( one_eventtype ) item = QCheckBox ( one_eventtype ) layout . addWidget ( item ) item . setCheckState ( Qt . Checked ) item . stateChanged . connect ( self . update_annotations ) item . stateChanged . connect ( self . toggle_check_all_eventtype ) self . idx_eventtype_list . append ( item ) self . idx_eventtype_scroll . setWidget ( evttype_group ) | Read the list of event types in the annotations and update widgets . | 282 | 13 |
23,354 | def toggle_eventtype ( self ) : check = self . check_all_eventtype . isChecked ( ) for btn in self . idx_eventtype_list : btn . setChecked ( check ) | Check or uncheck all event types in event type scroll . | 48 | 12 |
23,355 | def toggle_check_all_eventtype ( self ) : checklist = asarray ( [ btn . isChecked for btn in self . idx_eventtype_list ] ) if not checklist . all ( ) : self . check_all_eventtype . setChecked ( False ) | Check All if all event types are checked in event type scroll . | 63 | 13 |
23,356 | def get_selected_events ( self , time_selection = None ) : events = [ ] for checkbox in self . idx_eventtype_list : if checkbox . checkState ( ) == Qt . Checked : events . extend ( self . annot . get_events ( name = checkbox . text ( ) , time = time_selection ) ) return events | Returns which events are present in one time window . | 78 | 10 |
23,357 | def update_annotations ( self ) : start_time = self . parent . overview . start_time if self . parent . notes . annot is None : all_annot = [ ] else : bookmarks = self . parent . notes . annot . get_bookmarks ( ) events = self . get_selected_events ( ) all_annot = bookmarks + events all_annot = sorted ( all_annot , key = lambda x : x [ 'start' ] ) self . idx_annot_list . clearContents ( ) self . idx_annot_list . setRowCount ( len ( all_annot ) ) for i , mrk in enumerate ( all_annot ) : abs_time = ( start_time + timedelta ( seconds = mrk [ 'start' ] ) ) . strftime ( '%H:%M:%S' ) dur = timedelta ( seconds = mrk [ 'end' ] - mrk [ 'start' ] ) duration = '{0:02d}.{1:03d}' . format ( dur . seconds , round ( dur . microseconds / 1000 ) ) item_time = QTableWidgetItem ( abs_time ) item_duration = QTableWidgetItem ( duration ) item_name = QTableWidgetItem ( mrk [ 'name' ] ) if mrk in bookmarks : item_type = QTableWidgetItem ( 'bookmark' ) color = self . parent . value ( 'annot_bookmark_color' ) else : item_type = QTableWidgetItem ( 'event' ) color = convert_name_to_color ( mrk [ 'name' ] ) chan = mrk [ 'chan' ] if isinstance ( chan , ( tuple , list ) ) : chan = ', ' . join ( chan ) item_chan = QTableWidgetItem ( chan ) item_time . setForeground ( QColor ( color ) ) item_duration . setForeground ( QColor ( color ) ) item_name . setForeground ( QColor ( color ) ) item_type . setForeground ( QColor ( color ) ) item_chan . setForeground ( QColor ( color ) ) self . idx_annot_list . setItem ( i , 0 , item_time ) self . idx_annot_list . setItem ( i , 1 , item_duration ) self . idx_annot_list . setItem ( i , 2 , item_name ) self . idx_annot_list . setItem ( i , 3 , item_type ) self . idx_annot_list . setItem ( i , 4 , item_chan ) # store information about the time as list (easy to access) annot_start = [ ann [ 'start' ] for ann in all_annot ] annot_end = [ ann [ 'end' ] for ann in all_annot ] annot_name = [ ann [ 'name' ] for ann in all_annot ] self . idx_annot_list . setProperty ( 'start' , annot_start ) self . idx_annot_list . setProperty ( 'end' , annot_end ) self . idx_annot_list . setProperty ( 'name' , annot_name ) if self . parent . traces . data is not None : self . parent . traces . display_annotations ( ) self . parent . overview . display_annotations ( ) | Update annotations made by the user including bookmarks and events . Depending on the settings it might add the bookmarks to overview and traces . | 740 | 27 |
23,358 | def delete_row ( self ) : sel_model = self . idx_annot_list . selectionModel ( ) for row in sel_model . selectedRows ( ) : i = row . row ( ) start = self . idx_annot_list . property ( 'start' ) [ i ] end = self . idx_annot_list . property ( 'end' ) [ i ] name = self . idx_annot_list . item ( i , 2 ) . text ( ) marker_event = self . idx_annot_list . item ( i , 3 ) . text ( ) if marker_event == 'bookmark' : self . annot . remove_bookmark ( name = name , time = ( start , end ) ) else : self . annot . remove_event ( name = name , time = ( start , end ) ) highlight = self . parent . traces . highlight if highlight : self . parent . traces . scene . removeItem ( highlight ) highlight = None self . parent . traces . event_sel = None self . update_annotations ( ) | Delete bookmarks or event from annotations based on row . | 231 | 11 |
23,359 | def go_to_marker ( self , row , col , table_type ) : if table_type == 'dataset' : marker_time = self . idx_marker . property ( 'start' ) [ row ] marker_end_time = self . idx_marker . property ( 'end' ) [ row ] else : marker_time = self . idx_annot_list . property ( 'start' ) [ row ] marker_end_time = self . idx_annot_list . property ( 'end' ) [ row ] window_length = self . parent . value ( 'window_length' ) if self . parent . traces . action [ 'centre_event' ] . isChecked ( ) : window_start = ( marker_time + marker_end_time - window_length ) / 2 else : window_start = floor ( marker_time / window_length ) * window_length self . parent . overview . update_position ( window_start ) if table_type == 'annot' : for annot in self . parent . traces . idx_annot : if annot . marker . x ( ) == marker_time : self . parent . traces . highlight_event ( annot ) break | Move to point in time marked by the marker . | 265 | 10 |
23,360 | def get_sleepstage ( self , stage_idx = None ) : if self . annot is None : # remove if buttons are disabled error_dialog = QErrorMessage ( ) error_dialog . setWindowTitle ( 'Error getting sleep stage' ) error_dialog . showMessage ( 'No score file loaded' ) error_dialog . exec ( ) return window_start = self . parent . value ( 'window_start' ) window_length = self . parent . value ( 'window_length' ) if window_length != self . epoch_length : msg = ( 'Zoom to ' + str ( self . epoch_length ) + ' (epoch length) ' + 'for sleep scoring.' ) error_dialog = QErrorMessage ( ) error_dialog . setWindowTitle ( 'Error getting sleep stage' ) error_dialog . showMessage ( msg ) error_dialog . exec ( ) lg . debug ( msg ) return try : self . annot . set_stage_for_epoch ( window_start , STAGE_NAME [ stage_idx ] ) except KeyError : msg = ( 'The start of the window does not correspond to any epoch ' + 'in sleep scoring file.\n\n' 'Switch to the appropriate window length in View, then use ' 'Navigation --> Line Up with Epoch to line up the window.' ) error_dialog = QErrorMessage ( ) error_dialog . setWindowTitle ( 'Error getting sleep stage' ) error_dialog . showMessage ( msg ) error_dialog . exec ( ) lg . debug ( msg ) else : lg . debug ( 'User staged ' + str ( window_start ) + ' as ' + STAGE_NAME [ stage_idx ] ) self . set_stage_index ( ) self . parent . overview . mark_stages ( window_start , window_length , STAGE_NAME [ stage_idx ] ) self . display_stats ( ) self . parent . traces . page_next ( ) | Score the sleep stage using shortcuts or combobox . | 439 | 11 |
23,361 | def get_quality ( self , qual_idx = None ) : if self . annot is None : # remove if buttons are disabled msg = 'No score file loaded' error_dialog = QErrorMessage ( ) error_dialog . setWindowTitle ( 'Error getting quality' ) error_dialog . showMessage ( msg ) error_dialog . exec ( ) lg . debug ( msg ) return window_start = self . parent . value ( 'window_start' ) window_length = self . parent . value ( 'window_length' ) try : self . annot . set_stage_for_epoch ( window_start , QUALIFIERS [ qual_idx ] , attr = 'quality' ) except KeyError : msg = ( 'The start of the window does not correspond to any epoch ' + 'in sleep scoring file' ) error_dialog = QErrorMessage ( ) error_dialog . setWindowTitle ( 'Error getting quality' ) error_dialog . showMessage ( msg ) error_dialog . exec ( ) lg . debug ( msg ) else : lg . debug ( 'User staged ' + str ( window_start ) + ' as ' + QUALIFIERS [ qual_idx ] ) self . set_quality_index ( ) self . parent . overview . mark_quality ( window_start , window_length , QUALIFIERS [ qual_idx ] ) self . display_stats ( ) self . parent . traces . page_next ( ) | Get the signal qualifier using shortcuts or combobox . | 327 | 11 |
23,362 | def get_cycle_mrkr ( self , end = False ) : if self . annot is None : # remove if buttons are disabled self . parent . statusBar ( ) . showMessage ( 'No score file loaded' ) return window_start = self . parent . value ( 'window_start' ) window_length = self . parent . value ( 'window_length' ) try : self . annot . set_cycle_mrkr ( window_start , end = end ) except KeyError : msg = ( 'The start of the window does not correspond to any epoch ' 'in sleep scoring file' ) self . parent . statusBar ( ) . showMessage ( msg ) lg . debug ( msg ) else : bound = 'start' if end : bound = 'end' lg . info ( 'User marked ' + str ( window_start ) + ' as cycle ' + bound ) self . parent . overview . mark_cycles ( window_start , window_length , end = end ) | Mark cycle start or end . | 210 | 6 |
23,363 | def remove_cycle_mrkr ( self ) : window_start = self . parent . value ( 'window_start' ) try : self . annot . remove_cycle_mrkr ( window_start ) except KeyError : msg = ( 'The start of the window does not correspond to any cycle ' 'marker in sleep scoring file' ) self . parent . statusBar ( ) . showMessage ( msg ) lg . debug ( msg ) else : lg . debug ( 'User removed cycle marker at' + str ( window_start ) ) #self.trace self . parent . overview . update ( reset = False ) self . parent . overview . display_annotations ( ) | Remove cycle marker . | 144 | 4 |
23,364 | def clear_cycle_mrkrs ( self , test = False ) : if not test : msgBox = QMessageBox ( QMessageBox . Question , 'Clear Cycle Markers' , 'Are you sure you want to remove all cycle ' 'markers for this rater?' ) msgBox . setStandardButtons ( QMessageBox . Yes | QMessageBox . No ) msgBox . setDefaultButton ( QMessageBox . Yes ) response = msgBox . exec_ ( ) if response == QMessageBox . No : return self . annot . clear_cycles ( ) self . parent . overview . display ( ) self . parent . overview . display_annotations ( ) | Remove all cycle markers . | 142 | 5 |
23,365 | def set_stage_index ( self ) : window_start = self . parent . value ( 'window_start' ) window_length = self . parent . value ( 'window_length' ) stage = self . annot . get_stage_for_epoch ( window_start , window_length ) #lg.info('winstart: ' + str(window_start) + ', stage: ' + str(stage)) if stage is None : self . idx_stage . setCurrentIndex ( - 1 ) else : self . idx_stage . setCurrentIndex ( STAGE_NAME . index ( stage ) ) | Set the current stage in combobox . | 134 | 9 |
23,366 | def set_quality_index ( self ) : window_start = self . parent . value ( 'window_start' ) window_length = self . parent . value ( 'window_length' ) qual = self . annot . get_stage_for_epoch ( window_start , window_length , attr = 'quality' ) #lg.info('winstart: ' + str(window_start) + ', quality: ' + str(qual)) if qual is None : self . idx_quality . setCurrentIndex ( - 1 ) else : self . idx_quality . setCurrentIndex ( QUALIFIERS . index ( qual ) ) | Set the current signal quality in combobox . | 142 | 10 |
23,367 | def markers_to_events ( self , keep_name = False ) : markers = self . parent . info . markers if markers is None : self . parent . statusBar . showMessage ( 'No markers in dataset.' ) return if not keep_name : name , ok = self . new_eventtype ( ) if not ok : return else : name = None self . annot . add_events ( markers , name = name , chan = '' ) if keep_name : self . display_eventtype ( ) n_eventtype = self . idx_eventtype . count ( ) self . idx_eventtype . setCurrentIndex ( n_eventtype - 1 ) self . update_annotations ( ) | Copy all markers in dataset to event type . | 151 | 9 |
23,368 | def reset ( self ) : self . idx_annotations . setText ( 'Load Annotation File...' ) self . idx_rater . setText ( '' ) self . annot = None self . dataset_markers = None # remove dataset marker self . idx_marker . clearContents ( ) self . idx_marker . setRowCount ( 0 ) # remove summary statistics w1 = self . idx_summary . takeAt ( 1 ) . widget ( ) w2 = self . idx_summary . takeAt ( 1 ) . widget ( ) self . idx_summary . removeWidget ( w1 ) self . idx_summary . removeWidget ( w2 ) w1 . deleteLater ( ) w2 . deleteLater ( ) b1 = QGroupBox ( 'Staging' ) b2 = QGroupBox ( 'Signal quality' ) self . idx_summary . addWidget ( b1 ) self . idx_summary . addWidget ( b2 ) # remove annotations self . display_eventtype ( ) self . update_annotations ( ) self . parent . create_menubar ( ) | Remove all annotations from window . | 244 | 6 |
23,369 | def update_event_types ( self ) : self . idx_evt_type . clear ( ) self . idx_evt_type . setSelectionMode ( QAbstractItemView . ExtendedSelection ) event_types = sorted ( self . parent . notes . annot . event_types , key = str . lower ) for ty in event_types : item = QListWidgetItem ( ty ) self . idx_evt_type . addItem ( item ) | Update event types in event type box . | 102 | 8 |
23,370 | def update ( self ) : self . filename = self . parent . notes . annot . xml_file self . event_types = self . parent . notes . annot . event_types self . idx_evt_type . clear ( ) for ev in self . event_types : self . idx_evt_type . addItem ( ev ) | Update the event types list info when dialog is opened . | 75 | 11 |
23,371 | def save_as ( self ) : filename = splitext ( self . filename ) [ 0 ] filename , _ = QFileDialog . getSaveFileName ( self , 'Export events' , filename ) if filename == '' : return self . filename = filename short_filename = short_strings ( basename ( self . filename ) ) self . idx_filename . setText ( short_filename ) | Dialog for getting name location of dataset export . | 84 | 9 |
23,372 | def _convert_unit ( unit ) : if unit is None : return '' prefix = None suffix = None if unit [ : 5 ] . lower ( ) == 'milli' : prefix = 'm' unit = unit [ 5 : ] elif unit [ : 5 ] . lower ( ) == 'micro' : prefix = mu unit = unit [ 5 : ] elif unit [ : 2 ] . lower ( ) == 'mu' : prefix = mu unit = unit [ 2 : ] if unit [ - 4 : ] . lower ( ) == 'volt' : suffix = 'V' unit = unit [ : - 4 ] if prefix is None and suffix is None : unit = unit elif prefix is None and suffix is not None : unit = unit + suffix elif prefix is not None and suffix is None : unit = prefix + unit else : unit = prefix + suffix return unit | Convert different names into SI units . | 185 | 8 |
23,373 | def detect_format ( filename ) : filename = Path ( filename ) if filename . suffix == '.csv' : recformat = 'csv' elif filename . suffix == '.sfp' : recformat = 'sfp' else : recformat = 'unknown' return recformat | Detect file format of the channels based on extension . | 58 | 10 |
23,374 | def assign_region_to_channels ( channels , anat , parc_type = 'aparc' , max_approx = 3 , exclude_regions = None ) : for one_chan in channels . chan : one_region , approx = anat . find_brain_region ( one_chan . xyz , parc_type , max_approx , exclude_regions ) one_chan . attr . update ( { 'region' : one_region , 'approx' : approx } ) return channels | Assign a brain region based on the channel location . | 113 | 11 |
23,375 | def find_chan_in_region ( channels , anat , region_name ) : if 'region' not in channels . chan [ 0 ] . attr . keys ( ) : lg . info ( 'Computing region for each channel.' ) channels = assign_region_to_channels ( channels , anat ) chan_in_region = [ ] for one_chan in channels . chan : if region_name in one_chan . attr [ 'region' ] : chan_in_region . append ( one_chan . label ) return chan_in_region | Find which channels are in a specific region . | 126 | 9 |
23,376 | def create_sphere_around_elec ( xyz , template_mri , distance = 8 , freesurfer = None ) : if freesurfer is None : shift = 0 else : shift = freesurfer . surface_ras_shift if isinstance ( template_mri , str ) or isinstance ( template_mri , Path ) : template_mri = nload ( str ( template_mri ) ) mask = zeros ( template_mri . shape , dtype = 'bool' ) for vox in ndindex ( template_mri . shape ) : vox_ras = apply_affine ( template_mri . affine , vox ) - shift if norm ( xyz - vox_ras ) <= distance : mask [ vox ] = True return mask | Create an MRI mask around an electrode location | 176 | 8 |
23,377 | def return_attr ( self , attr , labels = None ) : all_labels = self . return_label ( ) if labels is None : labels = all_labels all_attr = [ ] for one_label in labels : idx = all_labels . index ( one_label ) try : all_attr . append ( self . chan [ idx ] . attr [ attr ] ) except KeyError : possible_attr = ', ' . join ( self . chan [ idx ] . attr . keys ( ) ) lg . debug ( 'key "{}" not found, ' . format ( attr ) + 'possible keys are {}' . format ( possible_attr ) ) all_attr . append ( None ) return all_attr | return the attributes for each channels . | 165 | 7 |
23,378 | def export ( self , elec_file ) : elec_file = Path ( elec_file ) if elec_file . suffix == '.csv' : sep = ', ' elif elec_file . suffix == '.sfp' : sep = ' ' with elec_file . open ( 'w' ) as f : for one_chan in self . chan : values = ( [ one_chan . label , ] + [ '{:.3f}' . format ( x ) for x in one_chan . xyz ] ) line = sep . join ( values ) + '\n' f . write ( line ) | Export channel name and location to file . | 138 | 8 |
23,379 | def filter_ ( data , axis = 'time' , low_cut = None , high_cut = None , order = 4 , ftype = 'butter' , Rs = None , notchfreq = 50 , notchquality = 25 ) : nyquist = data . s_freq / 2. btype = None if low_cut is not None and high_cut is not None : if low_cut > nyquist or high_cut > nyquist : raise ValueError ( 'cutoff has to be less than Nyquist ' 'frequency' ) btype = 'bandpass' Wn = ( low_cut / nyquist , high_cut / nyquist ) elif low_cut is not None : if low_cut > nyquist : raise ValueError ( 'cutoff has to be less than Nyquist ' 'frequency' ) btype = 'highpass' Wn = low_cut / nyquist elif high_cut is not None : if high_cut > nyquist : raise ValueError ( 'cutoff has to be less than Nyquist ' 'frequency' ) btype = 'lowpass' Wn = high_cut / nyquist if btype is None and ftype != 'notch' : raise TypeError ( 'You should specify at least low_cut or high_cut' ) if Rs is None : Rs = 40 if ftype == 'notch' : b_a = [ iirnotch ( w0 / nyquist , notchquality ) for w0 in arange ( notchfreq , nyquist , notchfreq ) ] else : lg . debug ( 'order {0: 2}, Wn {1}, btype {2}, ftype {3}' '' . format ( order , str ( Wn ) , btype , ftype ) ) b_a = [ iirfilter ( order , Wn , btype = btype , ftype = ftype , rs = Rs ) , ] fdata = data . _copy ( ) for i in range ( data . number_of ( 'trial' ) ) : x = data . data [ i ] for b , a in b_a : x = filtfilt ( b , a , x , axis = data . index_of ( axis ) ) fdata . data [ i ] = x return fdata | Design filter and apply it . | 504 | 6 |
23,380 | def convolve ( data , window , axis = 'time' , length = 1 ) : taper = get_window ( window , int ( length * data . s_freq ) ) taper = taper / sum ( taper ) fdata = data . _copy ( ) idx_axis = data . index_of ( axis ) for i in range ( data . number_of ( 'trial' ) ) : orig_dat = data . data [ i ] sel_dim = [ ] i_dim = [ ] dat = empty ( orig_dat . shape , dtype = orig_dat . dtype ) for i_axis , one_axis in enumerate ( data . list_of_axes ) : if one_axis != axis : i_dim . append ( i_axis ) sel_dim . append ( range ( data . number_of ( one_axis ) [ i ] ) ) for one_iter in product ( * sel_dim ) : # create the numpy indices for one value per dimension, # except for the dimension of interest idx = [ [ x ] for x in one_iter ] idx . insert ( idx_axis , range ( data . number_of ( axis ) [ i ] ) ) indices = ix_ ( * idx ) d_1dim = squeeze ( orig_dat [ indices ] , axis = i_dim ) d_1dim = fftconvolve ( d_1dim , taper , 'same' ) for to_squeeze in i_dim : d_1dim = expand_dims ( d_1dim , axis = to_squeeze ) dat [ indices ] = d_1dim fdata . data [ 0 ] = dat return fdata | Design taper and convolve it with the signal . | 375 | 11 |
23,381 | def normalize ( x , min_value , max_value ) : x = ( x - min_value ) / ( max_value - min_value ) return clip ( x , 0 , 1 ) | Normalize value between min and max values . It also clips the values so that you cannot have values higher or lower than 0 - 1 . | 43 | 28 |
23,382 | def _repr_png_ ( self ) : app . process_events ( ) QApplication . processEvents ( ) img = read_pixels ( ) return bytes ( _make_png ( img ) ) | This is used by ipython to plot inline . | 44 | 10 |
23,383 | def save ( self , png_file ) : with open ( png_file , 'wb' ) as f : f . write ( self . _repr_png_ ( ) ) | Save png to disk . | 41 | 6 |
23,384 | def _make_timestamps ( start_time , minimum , maximum , steps ) : t0 = start_time + timedelta ( seconds = minimum ) t1 = start_time + timedelta ( seconds = maximum ) t0_midnight = t0 . replace ( hour = 0 , minute = 0 , second = 0 , microsecond = 0 ) d0 = t0 - t0_midnight d1 = t1 - t0_midnight first_stamp = ceil ( d0 . total_seconds ( ) / steps ) * steps last_stamp = ceil ( d1 . total_seconds ( ) / steps ) * steps stamp_label = [ ] stamp_time = [ ] for stamp in range ( first_stamp , last_stamp , steps ) : stamp_as_datetime = t0_midnight + timedelta ( seconds = stamp ) stamp_label . append ( stamp_as_datetime . strftime ( '%H:%M' ) ) stamp_time . append ( stamp - d0 . total_seconds ( ) ) return stamp_label , stamp_time | Create timestamps on x - axis every so often . | 239 | 12 |
23,385 | def update ( self , reset = True ) : if self . parent . info . dataset is not None : # read from the dataset, if available header = self . parent . info . dataset . header maximum = header [ 'n_samples' ] / header [ 's_freq' ] # in s self . minimum = 0 self . maximum = maximum self . start_time = self . parent . info . dataset . header [ 'start_time' ] elif self . parent . notes . annot is not None : # read from annotations annot = self . parent . notes . annot self . minimum = annot . first_second self . maximum = annot . last_second self . start_time = annot . start_time # make it time-zone unaware self . start_time = self . start_time . replace ( tzinfo = None ) if reset : self . parent . value ( 'window_start' , 0 ) # the only value that is reset self . display ( ) | Read full duration and update maximum . | 208 | 7 |
23,386 | def display ( self ) : lg . debug ( 'GraphicsScene is between {}s and {}s' . format ( self . minimum , self . maximum ) ) x_scale = 1 / self . parent . value ( 'overview_scale' ) lg . debug ( 'Set scene x-scaling to {}' . format ( x_scale ) ) self . scale ( 1 / self . transform ( ) . m11 ( ) , 1 ) # reset to 1 self . scale ( x_scale , 1 ) self . scene = QGraphicsScene ( self . minimum , 0 , self . maximum , TOTAL_HEIGHT ) self . setScene ( self . scene ) # reset annotations self . idx_markers = [ ] self . idx_annot = [ ] self . display_current ( ) for name , pos in BARS . items ( ) : item = QGraphicsRectItem ( self . minimum , pos [ 'pos0' ] , self . maximum , pos [ 'pos1' ] ) item . setToolTip ( pos [ 'tip' ] ) self . scene . addItem ( item ) self . add_timestamps ( ) | Updates the widgets especially based on length of recordings . | 244 | 11 |
23,387 | def add_timestamps ( self ) : transform , _ = self . transform ( ) . inverted ( ) stamps = _make_timestamps ( self . start_time , self . minimum , self . maximum , self . parent . value ( 'timestamp_steps' ) ) for stamp , xpos in zip ( * stamps ) : text = self . scene . addSimpleText ( stamp ) text . setFlag ( QGraphicsItem . ItemIgnoresTransformations ) # set xpos and adjust for text width text_width = text . boundingRect ( ) . width ( ) * transform . m11 ( ) text . setPos ( xpos - text_width / 2 , TIME_HEIGHT ) | Add timestamps at the bottom of the overview . | 149 | 11 |
23,388 | def update_settings ( self ) : self . display ( ) self . display_markers ( ) if self . parent . notes . annot is not None : self . parent . notes . display_notes ( ) | After changing the settings we need to recreate the whole image . | 44 | 12 |
23,389 | def update_position ( self , new_position = None ) : if new_position is not None : lg . debug ( 'Updating position to {}' . format ( new_position ) ) self . parent . value ( 'window_start' , new_position ) self . idx_current . setPos ( new_position , 0 ) current_time = ( self . start_time + timedelta ( seconds = new_position ) ) msg = 'Current time: ' + current_time . strftime ( '%H:%M:%S' ) msg2 = f' ({new_position} seconds from start)' self . parent . statusBar ( ) . showMessage ( msg + msg2 ) lg . debug ( msg ) else : lg . debug ( 'Updating position at {}' '' . format ( self . parent . value ( 'window_start' ) ) ) if self . parent . info . dataset is not None : self . parent . traces . read_data ( ) if self . parent . traces . data is not None : self . parent . traces . display ( ) self . parent . spectrum . display_window ( ) if self . parent . notes . annot is not None : self . parent . notes . set_stage_index ( ) self . parent . notes . set_quality_index ( ) self . display_current ( ) | Update the cursor position and much more . | 291 | 8 |
23,390 | def display_current ( self ) : if self . idx_current in self . scene . items ( ) : self . scene . removeItem ( self . idx_current ) item = QGraphicsRectItem ( 0 , CURR [ 'pos0' ] , self . parent . value ( 'window_length' ) , CURR [ 'pos1' ] ) # it's necessary to create rect first, and then move it item . setPos ( self . parent . value ( 'window_start' ) , 0 ) item . setPen ( QPen ( Qt . lightGray ) ) item . setBrush ( QBrush ( Qt . lightGray ) ) item . setZValue ( - 10 ) self . scene . addItem ( item ) self . idx_current = item | Create a rectangle showing the current window . | 167 | 8 |
23,391 | def display_markers ( self ) : for rect in self . idx_markers : self . scene . removeItem ( rect ) self . idx_markers = [ ] markers = [ ] if self . parent . info . markers is not None : if self . parent . value ( 'marker_show' ) : markers = self . parent . info . markers for mrk in markers : rect = QGraphicsRectItem ( mrk [ 'start' ] , BARS [ 'markers' ] [ 'pos0' ] , mrk [ 'end' ] - mrk [ 'start' ] , BARS [ 'markers' ] [ 'pos1' ] ) self . scene . addItem ( rect ) color = self . parent . value ( 'marker_color' ) rect . setPen ( QPen ( QColor ( color ) ) ) rect . setBrush ( QBrush ( QColor ( color ) ) ) rect . setZValue ( - 5 ) self . idx_markers . append ( rect ) | Mark all the markers from the dataset . | 227 | 8 |
23,392 | def mark_stages ( self , start_time , length , stage_name ) : y_pos = BARS [ 'stage' ] [ 'pos0' ] current_stage = STAGES . get ( stage_name , STAGES [ 'Unknown' ] ) # the -1 is really important, otherwise we stay on the edge of the rect old_score = self . scene . itemAt ( start_time + length / 2 , y_pos + current_stage [ 'pos0' ] + current_stage [ 'pos1' ] - 1 , self . transform ( ) ) # check we are not removing the black border if old_score is not None and old_score . pen ( ) == NoPen : lg . debug ( 'Removing old score at {}' . format ( start_time ) ) self . scene . removeItem ( old_score ) self . idx_annot . remove ( old_score ) rect = QGraphicsRectItem ( start_time , y_pos + current_stage [ 'pos0' ] , length , current_stage [ 'pos1' ] ) rect . setPen ( NoPen ) rect . setBrush ( current_stage [ 'color' ] ) self . scene . addItem ( rect ) self . idx_annot . append ( rect ) | Mark stages only add the new ones . | 278 | 8 |
23,393 | def mark_quality ( self , start_time , length , qual_name ) : y_pos = BARS [ 'quality' ] [ 'pos0' ] height = 10 # the -1 is really important, otherwise we stay on the edge of the rect old_score = self . scene . itemAt ( start_time + length / 2 , y_pos + height - 1 , self . transform ( ) ) # check we are not removing the black border if old_score is not None and old_score . pen ( ) == NoPen : lg . debug ( 'Removing old score at {}' . format ( start_time ) ) self . scene . removeItem ( old_score ) self . idx_annot . remove ( old_score ) if qual_name == 'Poor' : rect = QGraphicsRectItem ( start_time , y_pos , length , height ) rect . setPen ( NoPen ) rect . setBrush ( Qt . black ) self . scene . addItem ( rect ) self . idx_annot . append ( rect ) | Mark signal quality only add the new ones . | 227 | 9 |
23,394 | def mark_cycles ( self , start_time , length , end = False ) : y_pos = STAGES [ 'cycle' ] [ 'pos0' ] height = STAGES [ 'cycle' ] [ 'pos1' ] color = STAGES [ 'cycle' ] [ 'color' ] # the -1 is really important, otherwise we stay on the edge of the rect old_rect = self . scene . itemAt ( start_time + length / 2 , y_pos + height - 1 , self . transform ( ) ) # check we are not removing the black border if old_rect is not None and old_rect . pen ( ) == NoPen : lg . debug ( 'Removing old score at {}' . format ( start_time ) ) self . scene . removeItem ( old_rect ) self . idx_annot . remove ( old_rect ) rect = QGraphicsRectItem ( start_time , y_pos , 30 , height ) rect . setPen ( NoPen ) rect . setBrush ( color ) self . scene . addItem ( rect ) self . idx_annot . append ( rect ) if end : start_time -= 120 kink_hi = QGraphicsRectItem ( start_time , y_pos , 150 , 1 ) kink_hi . setPen ( NoPen ) kink_hi . setBrush ( color ) self . scene . addItem ( kink_hi ) self . idx_annot . append ( kink_hi ) kink_lo = QGraphicsRectItem ( start_time , y_pos + height , 150 , 1 ) kink_lo . setPen ( NoPen ) kink_lo . setBrush ( color ) self . scene . addItem ( kink_lo ) self . idx_annot . append ( kink_lo ) | Mark cycle bound only add the new one . | 392 | 9 |
23,395 | def mousePressEvent ( self , event ) : if self . scene is not None : x_in_scene = self . mapToScene ( event . pos ( ) ) . x ( ) window_length = self . parent . value ( 'window_length' ) window_start = int ( floor ( x_in_scene / window_length ) * window_length ) if self . parent . notes . annot is not None : window_start = self . parent . notes . annot . get_epoch_start ( window_start ) self . update_position ( window_start ) | Jump to window when user clicks on overview . | 124 | 9 |
23,396 | def reset ( self ) : self . minimum = None self . maximum = None self . start_time = None # datetime, absolute start time self . idx_current = None self . idx_markers = [ ] self . idx_annot = [ ] if self . scene is not None : self . scene . clear ( ) self . scene = None | Reset the widget and clear the scene . | 77 | 9 |
23,397 | def _prepare_colors ( color , values , limits_c , colormap , alpha , chan = None ) : if values is not None : if limits_c is None : limits_c = array ( [ - 1 , 1 ] ) * nanmax ( abs ( values ) ) norm_values = normalize ( values , * limits_c ) cm = get_colormap ( colormap ) colors = cm [ norm_values ] elif color is not None : colors = ColorArray ( color ) else : cm = get_colormap ( 'hsl' ) group_idx = _chan_groups_to_index ( chan ) colors = cm [ group_idx ] if alpha is not None : colors . alpha = alpha return colors , limits_c | Return colors for all the channels based on various inputs . | 169 | 11 |
23,398 | def add_surf ( self , surf , color = SKIN_COLOR , vertex_colors = None , values = None , limits_c = None , colormap = COLORMAP , alpha = 1 , colorbar = False ) : colors , limits = _prepare_colors ( color = color , values = values , limits_c = limits_c , colormap = colormap , alpha = alpha ) # meshdata uses numpy array, in the correct dimension vertex_colors = colors . rgba if vertex_colors . shape [ 0 ] == 1 : vertex_colors = tile ( vertex_colors , ( surf . n_vert , 1 ) ) meshdata = MeshData ( vertices = surf . vert , faces = surf . tri , vertex_colors = vertex_colors ) mesh = SurfaceMesh ( meshdata ) self . _add_mesh ( mesh ) # adjust camera surf_center = mean ( surf . vert , axis = 0 ) if surf_center [ 0 ] < 0 : azimuth = 270 else : azimuth = 90 self . _view . camera . azimuth = azimuth self . _view . camera . center = surf_center self . _surf . append ( mesh ) if colorbar : self . _view . add ( _colorbar_for_surf ( colormap , limits ) ) | Add surfaces to the visualization . | 296 | 6 |
23,399 | def add_chan ( self , chan , color = None , values = None , limits_c = None , colormap = CHAN_COLORMAP , alpha = None , colorbar = False ) : # reuse previous limits if limits_c is None and self . _chan_limits is not None : limits_c = self . _chan_limits chan_colors , limits = _prepare_colors ( color = color , values = values , limits_c = limits_c , colormap = colormap , alpha = alpha , chan = chan ) self . _chan_limits = limits xyz = chan . return_xyz ( ) marker = Markers ( ) marker . set_data ( pos = xyz , size = CHAN_SIZE , face_color = chan_colors ) self . _add_mesh ( marker ) if colorbar : self . _view . add ( _colorbar_for_surf ( colormap , limits ) ) | Add channels to visualization | 215 | 4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.