idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
23,500
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 ( ...
Mark all the markers from the dataset .
23,501
def mark_stages ( self , start_time , length , stage_name ) : y_pos = BARS [ 'stage' ] [ 'pos0' ] current_stage = STAGES . get ( stage_name , STAGES [ 'Unknown' ] ) old_score = self . scene . itemAt ( start_time + length / 2 , y_pos + current_stage [ 'pos0' ] + current_stage [ 'pos1' ] - 1 , self . transform ( ) ) if o...
Mark stages only add the new ones .
23,502
def mark_quality ( self , start_time , length , qual_name ) : y_pos = BARS [ 'quality' ] [ 'pos0' ] height = 10 old_score = self . scene . itemAt ( start_time + length / 2 , y_pos + height - 1 , self . transform ( ) ) if old_score is not None and old_score . pen ( ) == NoPen : lg . debug ( 'Removing old score at {}' . ...
Mark signal quality only add the new ones .
23,503
def mark_cycles ( self , start_time , length , end = False ) : y_pos = STAGES [ 'cycle' ] [ 'pos0' ] height = STAGES [ 'cycle' ] [ 'pos1' ] color = STAGES [ 'cycle' ] [ 'color' ] old_rect = self . scene . itemAt ( start_time + length / 2 , y_pos + height - 1 , self . transform ( ) ) if old_rect is not None and old_rect...
Mark cycle bound only add the new one .
23,504
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_star...
Jump to window when user clicks on overview .
23,505
def reset ( self ) : self . minimum = None self . maximum = None self . start_time = None 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 .
23,506
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 Non...
Return colors for all the channels based on various inputs .
23,507
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 ) vertex_colors = colors . rgb...
Add surfaces to the visualization .
23,508
def add_chan ( self , chan , color = None , values = None , limits_c = None , colormap = CHAN_COLORMAP , alpha = None , colorbar = False ) : 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 = limi...
Add channels to visualization
23,509
def select ( data , trial = None , invert = False , ** axes_to_select ) : if trial is not None and not isinstance ( trial , Iterable ) : raise TypeError ( 'Trial needs to be iterable.' ) for axis_to_select , values_to_select in axes_to_select . items ( ) : if ( not isinstance ( values_to_select , Iterable ) or isinstan...
Define the selection of trials using ranges or actual values .
23,510
def resample ( data , s_freq = None , axis = 'time' , ftype = 'fir' , n = None ) : output = data . _copy ( ) ratio = int ( data . s_freq / s_freq ) for i in range ( data . number_of ( 'trial' ) ) : output . data [ i ] = decimate ( data . data [ i ] , ratio , axis = data . index_of ( axis ) , zero_phase = True ) n_sampl...
Downsample the data after applying a filter .
23,511
def fetch ( dataset , annot , cat = ( 0 , 0 , 0 , 0 ) , evt_type = None , stage = None , cycle = None , chan_full = None , epoch = None , epoch_dur = 30 , epoch_overlap = 0 , epoch_step = None , reject_epoch = False , reject_artf = False , min_dur = 0 , buffer = 0 ) : bundles = get_times ( annot , evt_type = evt_type ,...
Create instance of Segments for analysis complete with info about stage cycle channel event type . Segments contains only metadata until . read_data is called .
23,512
def get_times ( annot , evt_type = None , stage = None , cycle = None , chan = None , exclude = False , buffer = 0 ) : getter = annot . get_epochs last = annot . last_second if stage is None : stage = ( None , ) if cycle is None : cycle = ( None , ) if chan is None : chan = ( None , ) if evt_type is None : evt_type = (...
Get start and end times for selected segments of data bundled together with info .
23,513
def _longer_than ( segments , min_dur ) : if min_dur <= 0. : return segments long_enough = [ ] for seg in segments : if sum ( [ t [ 1 ] - t [ 0 ] for t in seg [ 'times' ] ] ) >= min_dur : long_enough . append ( seg ) return long_enough
Remove segments longer than min_dur .
23,514
def _concat ( bundles , cat = ( 0 , 0 , 0 , 0 ) ) : chan = sorted ( set ( [ x [ 'chan' ] for x in bundles ] ) ) cycle = sorted ( set ( [ x [ 'cycle' ] for x in bundles ] ) ) stage = sorted ( set ( [ x [ 'stage' ] for x in bundles ] ) ) evt_type = sorted ( set ( [ x [ 'name' ] for x in bundles ] ) ) all_cycle = None all...
Prepare event or epoch start and end times for concatenation .
23,515
def _divide_bundles ( bundles ) : divided = [ ] for bund in bundles : for t in bund [ 'times' ] : new_bund = bund . copy ( ) new_bund [ 'times' ] = [ t ] divided . append ( new_bund ) return divided
Take each subsegment inside a bundle and put it in its own bundle copying the bundle metadata .
23,516
def _find_intervals ( bundles , duration , step ) : segments = [ ] for bund in bundles : beg , end = bund [ 'times' ] [ 0 ] [ 0 ] , bund [ 'times' ] [ - 1 ] [ 1 ] if end - beg >= duration : new_begs = arange ( beg , end - duration , step ) for t in new_begs : seg = bund . copy ( ) seg [ 'times' ] = [ ( t , t + duration...
Divide bundles into segments of a certain duration and a certain step discarding any remainder .
23,517
def _create_data ( data , active_chan , ref_chan = [ ] , grp_name = None ) : output = ChanTime ( ) output . s_freq = data . s_freq output . start_time = data . start_time output . axis [ 'time' ] = data . axis [ 'time' ] output . axis [ 'chan' ] = empty ( 1 , dtype = 'O' ) output . data = empty ( 1 , dtype = 'O' ) outp...
Create data after montage .
23,518
def _select_channels ( data , channels ) : output = data . _copy ( ) chan_list = list ( data . axis [ 'chan' ] [ 0 ] ) idx_chan = [ chan_list . index ( i_chan ) for i_chan in channels ] output . data [ 0 ] = data . data [ 0 ] [ idx_chan , : ] output . axis [ 'chan' ] [ 0 ] = asarray ( channels ) return output
Select channels .
23,519
def create_widgets ( MAIN ) : MAIN . labels = Labels ( MAIN ) MAIN . channels = Channels ( MAIN ) MAIN . notes = Notes ( MAIN ) MAIN . merge_dialog = MergeDialog ( MAIN ) MAIN . export_events_dialog = ExportEventsDialog ( MAIN ) MAIN . export_dataset_dialog = ExportDatasetDialog ( MAIN ) MAIN . spindle_dialog = Spindle...
Create all the widgets and dockwidgets . It also creates actions to toggle views of dockwidgets in dockwidgets .
23,520
def create_actions ( MAIN ) : actions = MAIN . action actions [ 'open_settings' ] = QAction ( QIcon ( ICON [ 'settings' ] ) , 'Settings' , MAIN ) actions [ 'open_settings' ] . triggered . connect ( MAIN . show_settings ) actions [ 'close_wndw' ] = QAction ( QIcon ( ICON [ 'quit' ] ) , 'Quit' , MAIN ) actions [ 'close_w...
Create all the possible actions .
23,521
def create_toolbar ( MAIN ) : actions = MAIN . action toolbar = MAIN . addToolBar ( 'File Management' ) toolbar . setObjectName ( 'File Management' ) toolbar . addAction ( MAIN . info . action [ 'open_dataset' ] ) toolbar . addSeparator ( ) toolbar . addAction ( MAIN . channels . action [ 'load_channels' ] ) toolbar . ...
Create the various toolbars .
23,522
def update_evt_types ( self ) : self . event_types = self . parent . notes . annot . event_types self . idx_evt_type . clear ( ) self . frequency [ 'norm_evt_type' ] . clear ( ) for ev in self . event_types : self . idx_evt_type . addItem ( ev ) self . frequency [ 'norm_evt_type' ] . addItem ( ev )
Update the event types list when dialog is opened .
23,523
def toggle_concatenate ( self ) : if not ( self . chunk [ 'epoch' ] . isChecked ( ) and self . lock_to_staging . get_value ( ) ) : for i , j in zip ( [ self . idx_chan , self . idx_cycle , self . idx_stage , self . idx_evt_type ] , [ self . cat [ 'chan' ] , self . cat [ 'cycle' ] , self . cat [ 'stage' ] , self . cat [...
Enable and disable concatenation options .
23,524
def toggle_pac ( self ) : if Pac is not None : pac_on = self . pac [ 'pac_on' ] . get_value ( ) self . pac [ 'prep' ] . setEnabled ( pac_on ) self . pac [ 'box_metric' ] . setEnabled ( pac_on ) self . pac [ 'box_complex' ] . setEnabled ( pac_on ) self . pac [ 'box_surro' ] . setEnabled ( pac_on ) self . pac [ 'box_opts...
Enable and disable PAC options .
23,525
def update_nseg ( self ) : self . nseg = 0 if self . one_grp : segments = self . get_segments ( ) if segments is not None : self . nseg = len ( segments ) self . show_nseg . setText ( 'Number of segments: ' + str ( self . nseg ) ) times = [ t for seg in segments for t in seg [ 'times' ] ] self . parent . overview . mar...
Update the number of segments displayed in the dialog .
23,526
def check_all_local ( self ) : all_local_chk = self . event [ 'global' ] [ 'all_local' ] . isChecked ( ) for buttons in self . event [ 'local' ] . values ( ) : buttons [ 0 ] . setChecked ( all_local_chk ) buttons [ 1 ] . setEnabled ( buttons [ 0 ] . isChecked ( ) )
Check or uncheck all local event parameters .
23,527
def check_all_local_prep ( self ) : all_local_pp_chk = self . event [ 'global' ] [ 'all_local_prep' ] . isChecked ( ) for buttons in self . event [ 'local' ] . values ( ) : if buttons [ 1 ] . isEnabled ( ) : buttons [ 1 ] . setChecked ( all_local_pp_chk )
Check or uncheck all enabled event pre - processing .
23,528
def uncheck_all_local ( self ) : for buttons in self . event [ 'local' ] . values ( ) : if not buttons [ 0 ] . get_value ( ) : self . event [ 'global' ] [ 'all_local' ] . setChecked ( False ) if buttons [ 1 ] . isEnabled ( ) and not buttons [ 1 ] . get_value ( ) : self . event [ 'global' ] [ 'all_local_prep' ] . setChe...
Uncheck all local box when a local event is unchecked .
23,529
def get_segments ( self ) : chunk = { k : v . isChecked ( ) for k , v in self . chunk . items ( ) } lock_to_staging = self . lock_to_staging . get_value ( ) epoch_dur = self . epoch_param [ 'dur' ] . get_value ( ) epoch_overlap = self . epoch_param [ 'overlap_val' ] . value ( ) epoch_step = None epoch = None if chunk [...
Get segments for analysis . Creates instance of trans . Segments .
23,530
def transform_data ( self , data ) : trans = self . trans differ = trans [ 'diff' ] . get_value ( ) bandpass = trans [ 'bandpass' ] . get_value ( ) notch1 = trans [ 'notch1' ] . get_value ( ) notch2 = trans [ 'notch2' ] . get_value ( ) for seg in data : dat = seg [ 'data' ] if differ : dat = math ( dat , operator = dif...
Apply pre - processing transformation to data and add it to data dict .
23,531
def save_as ( self ) : filename = splitext ( self . parent . notes . annot . xml_file ) [ 0 ] + '_data' filename , _ = QFileDialog . getSaveFileName ( self , 'Export analysis data' , filename , 'CSV (*.csv)' ) if filename == '' : return self . filename = filename short_filename = short_strings ( basename ( self . filen...
Dialog for getting name location of data export file .
23,532
def plot_freq ( self , x , y , title = '' , ylabel = None , scale = 'semilogy' ) : freq = self . frequency scaling = freq [ 'scaling' ] . get_value ( ) if ylabel is None : if freq [ 'complex' ] . get_value ( ) : ylabel = 'Amplitude (uV)' elif 'power' == scaling : ylabel = 'Power spectral density (uV ** 2 / Hz)' elif 'e...
Plot mean frequency spectrum and display in dialog .
23,533
def export_pac ( self , xpac , fpha , famp , desc ) : filename = splitext ( self . filename ) [ 0 ] + '_pac.csv' heading_row_1 = [ 'Segment index' , 'Start time' , 'End time' , 'Duration' , 'Stitch' , 'Stage' , 'Cycle' , 'Event type' , 'Channel' , ] spacer = [ '' ] * ( len ( heading_row_1 ) - 1 ) heading_row_2 = [ ] fo...
Write PAC analysis data to CSV .
23,534
def compute_evt_params ( self ) : ev = self . event glob = { k : v . get_value ( ) for k , v in ev [ 'global' ] . items ( ) } params = { k : v [ 0 ] . get_value ( ) for k , v in ev [ 'local' ] . items ( ) } prep = { k : v [ 1 ] . get_value ( ) for k , v in ev [ 'local' ] . items ( ) } slopes = { k : v . get_value ( ) f...
Compute event parameters .
23,535
def make_title ( self , chan , cycle , stage , evt_type ) : cyc_str = None if cycle is not None : cyc_str = [ str ( c [ 2 ] ) for c in cycle ] cyc_str [ 0 ] = 'cycle ' + cyc_str [ 0 ] title = [ ' + ' . join ( [ str ( x ) for x in y ] ) for y in [ chan , cyc_str , stage , evt_type ] if y is not None ] return ', ' . join...
Make a title for plots etc .
23,536
def plot ( self , x , y , title , ylabel , scale = 'semilogy' , idx_lim = ( 1 , - 1 ) ) : x = x [ slice ( * idx_lim ) ] y = y [ slice ( * idx_lim ) ] ax = self . figure . add_subplot ( 111 ) ax . set_title ( title ) ax . set_xlabel ( 'Frequency (Hz)' ) ax . set_ylabel ( ylabel ) if 'semilogy' == scale : ax . semilogy (...
Plot the data .
23,537
def create_dialog ( self ) : self . bbox = QDialogButtonBox ( QDialogButtonBox . Close ) self . idx_close = self . bbox . button ( QDialogButtonBox . Close ) self . idx_close . pressed . connect ( self . reject ) btnlayout = QHBoxLayout ( ) btnlayout . addStretch ( 1 ) btnlayout . addWidget ( self . bbox ) layout = QVB...
Create the basic dialog .
23,538
def make_arousals ( events , time , s_freq ) : arousals = [ ] for ev in events : one_ar = { 'start' : time [ ev [ 0 ] ] , 'end' : time [ ev [ 1 ] - 1 ] , 'dur' : ( ev [ 1 ] - ev [ 0 ] ) / s_freq , } arousals . append ( one_ar ) return arousals
Create dict for each arousal based on events of time points .
23,539
def _convert_time_to_sample ( abs_time , dataset ) : if isinstance ( abs_time , datetime ) : abs_time = abs_time - dataset . header [ 'start_time' ] if not isinstance ( abs_time , timedelta ) : try : abs_time = timedelta ( seconds = float ( abs_time ) ) except TypeError as err : if isinstance ( abs_time , int64 ) : abs...
Convert absolute time into samples .
23,540
def detect_format ( filename ) : filename = Path ( filename ) if filename . is_dir ( ) : if list ( filename . glob ( '*.stc' ) ) and list ( filename . glob ( '*.erd' ) ) : return Ktlx elif ( filename / 'patient.info' ) . exists ( ) : return Moberg elif ( filename / 'info.xml' ) . exists ( ) : return EgiMff elif list ( ...
Detect file format .
23,541
def read_videos ( self , begtime = None , endtime = None ) : if isinstance ( begtime , datetime ) : begtime = begtime - self . header [ 'start_time' ] if isinstance ( begtime , timedelta ) : begtime = begtime . total_seconds ( ) if isinstance ( endtime , datetime ) : endtime = endtime - self . header [ 'start_time' ] i...
Return list of videos with start and end times for a period .
23,542
def read_data ( self , chan = None , begtime = None , endtime = None , begsam = None , endsam = None , s_freq = None ) : data = ChanTime ( ) data . start_time = self . header [ 'start_time' ] data . s_freq = s_freq = s_freq if s_freq else self . header [ 's_freq' ] if chan is None : chan = self . header [ 'chan_name' ]...
Read the data and creates a ChanTime instance
23,543
def _read_dat ( x ) : n_smp = int ( len ( x ) / DATA_PRECISION ) dat = zeros ( n_smp ) for i in range ( n_smp ) : i0 = i * DATA_PRECISION i1 = i0 + DATA_PRECISION dat [ i ] = int . from_bytes ( x [ i0 : i1 ] , byteorder = 'little' , signed = True ) return dat
read 24bit binary data and convert them to numpy .
23,544
def _read_chan_name ( orig ) : sensors = orig [ 'sensorLayout' ] [ 1 ] eeg_chan = [ ] for one_sensor in sensors : if one_sensor [ 'type' ] in ( '0' , '1' ) : if one_sensor [ 'name' ] is not None : eeg_chan . append ( one_sensor [ 'name' ] ) else : eeg_chan . append ( one_sensor [ 'number' ] ) pns_chan = [ ] if 'pnsSet'...
Read channel labels which can be across xml files .
23,545
def write_wonambi ( data , filename , subj_id = '' , dtype = 'float64' ) : filename = Path ( filename ) json_file = filename . with_suffix ( '.won' ) memmap_file = filename . with_suffix ( '.dat' ) start_time = data . start_time + timedelta ( seconds = data . axis [ 'time' ] [ 0 ] [ 0 ] ) start_time_str = start_time . ...
Write file in simple Wonambi format .
23,546
def _read_geometry ( surf_file ) : with open ( surf_file , 'rb' ) as f : filebytes = f . read ( ) assert filebytes [ : 3 ] == b'\xff\xff\xfe' i0 = filebytes . index ( b'\x0A\x0A' ) + 2 i1 = i0 + 4 vnum = unpack ( '>i' , filebytes [ i0 : i1 ] ) [ 0 ] i0 = i1 i1 += 4 fnum = unpack ( '>i' , filebytes [ i0 : i1 ] ) [ 0 ] i...
Read a triangular format Freesurfer surface mesh .
23,547
def import_freesurfer_LUT ( fs_lut = None ) : if fs_lut is not None : lg . info ( 'Reading user-specified lookuptable {}' . format ( fs_lut ) ) fs_lut = Path ( fs_lut ) else : try : fs_home = environ [ 'FREESURFER_HOME' ] except KeyError : raise OSError ( 'Freesurfer is not installed or FREESURFER_HOME is ' 'not define...
Import Look - up Table with colors and labels for anatomical regions .
23,548
def find_brain_region ( self , abs_pos , parc_type = 'aparc' , max_approx = None , exclude_regions = None ) : pos = around ( dot ( FS_AFFINE , append ( abs_pos , 1 ) ) ) [ : 3 ] . astype ( int ) lg . debug ( 'Position in the MRI matrix: {}' . format ( pos ) ) mri_dat , _ = self . read_seg ( parc_type ) if max_approx is...
Find the name of the brain region in which an electrode is located .
23,549
def read_seg ( self , parc_type = 'aparc' ) : seg_file = self . dir / 'mri' / ( parc_type + '+aseg.mgz' ) seg_mri = load ( seg_file ) seg_aff = seg_mri . affine seg_dat = seg_mri . get_data ( ) return seg_dat , seg_aff
Read the MRI segmentation .
23,550
def concatenate ( data , axis ) : output = data . _copy ( axis = False ) for dataaxis in data . axis : output . axis [ dataaxis ] = empty ( 1 , dtype = 'O' ) if dataaxis == axis : output . axis [ dataaxis ] [ 0 ] = cat ( data . axis [ dataaxis ] ) else : output . axis [ dataaxis ] [ 0 ] = data . axis [ dataaxis ] [ 0 ]...
Concatenate multiple trials into one trials according to any dimension .
23,551
def return_rri ( self , begsam , endsam ) : interval = endsam - begsam dat = empty ( interval ) k = 0 with open ( self . filename , 'rt' ) as f : [ next ( f ) for x in range ( 12 ) ] for j , datum in enumerate ( f ) : if begsam <= j < endsam : dat [ k ] = float64 ( datum [ : datum . index ( '\t' ) ] ) k += 1 if k == in...
Return raw irregularly - timed RRI .
23,552
def update ( self , checked = False , labels = None , custom_labels = None ) : if labels is not None : self . setEnabled ( True ) self . chan_name = labels self . table . blockSignals ( True ) self . table . clearContents ( ) self . table . setRowCount ( len ( self . chan_name ) ) for i , label in enumerate ( self . ch...
Use this function when we make changes to the list of labels or when we load a new dataset .
23,553
def peaks ( data , method = 'max' , axis = 'time' , limits = None ) : idx_axis = data . index_of ( axis ) output = data . _copy ( ) output . axis . pop ( axis ) for trl in range ( data . number_of ( 'trial' ) ) : values = data . axis [ axis ] [ trl ] dat = data ( trial = trl ) if limits is not None : limits = ( values ...
Return the values of an index where the data is at max or min
23,554
def export_freq ( xfreq , filename , desc = None ) : heading_row_1 = [ 'Segment index' , 'Start time' , 'End time' , 'Duration' , 'Stitches' , 'Stage' , 'Cycle' , 'Event type' , 'Channel' , ] spacer = [ '' ] * ( len ( heading_row_1 ) - 1 ) freq = list ( xfreq [ 0 ] [ 'data' ] . axis [ 'freq' ] [ 0 ] ) with open ( filen...
Write frequency analysis data to CSV .
23,555
def export_freq_band ( xfreq , bands , filename ) : heading_row_1 = [ 'Segment index' , 'Start time' , 'End time' , 'Duration' , 'Stitches' , 'Stage' , 'Cycle' , 'Event type' , 'Channel' , ] spacer = [ '' ] * ( len ( heading_row_1 ) - 1 ) band_hdr = [ str ( b1 ) + '-' + str ( b2 ) for b1 , b2 in bands ] xband = xfreq ....
Write frequency analysis data to CSV by pre - defined band .
23,556
def create_empty_annotations ( xml_file , dataset ) : xml_file = Path ( xml_file ) root = Element ( 'annotations' ) root . set ( 'version' , VERSION ) info = SubElement ( root , 'dataset' ) x = SubElement ( info , 'filename' ) x . text = str ( dataset . filename ) x = SubElement ( info , 'path' ) x . text = str ( datas...
Create an empty annotation file .
23,557
def create_annotation ( xml_file , from_fasst ) : xml_file = Path ( xml_file ) try : mat = loadmat ( str ( from_fasst ) , variable_names = 'D' , struct_as_record = False , squeeze_me = True ) except ValueError : raise UnrecognizedFormat ( str ( from_fasst ) + ' does not look like a FASST .mat file' ) D = mat [ 'D' ] in...
Create annotations by importing from FASST sleep scoring file .
23,558
def update_annotation_version ( xml_file ) : with open ( xml_file , 'r' ) as f : s = f . read ( ) m = search ( '<annotations version="([0-9]*)">' , s ) current = int ( m . groups ( ) [ 0 ] ) if current < 4 : s = sub ( '<marker><name>(.*?)</name><time>(.*?)</time></marker>' , '<marker><marker_name>\g<1></marker_name><ma...
Update the fields that have changed over different versions .
23,559
def load ( self ) : lg . info ( 'Loading ' + str ( self . xml_file ) ) update_annotation_version ( self . xml_file ) xml = parse ( self . xml_file ) return xml . getroot ( )
Load xml from file .
23,560
def save ( self ) : if self . rater is not None : self . rater . set ( 'modified' , datetime . now ( ) . isoformat ( ) ) xml = parseString ( tostring ( self . root ) ) with open ( self . xml_file , 'w' ) as f : f . write ( xml . toxml ( ) )
Save xml to file .
23,561
def add_bookmark ( self , name , time , chan = '' ) : try : bookmarks = self . rater . find ( 'bookmarks' ) except AttributeError : raise IndexError ( 'You need to have at least one rater' ) new_bookmark = SubElement ( bookmarks , 'bookmark' ) bookmark_name = SubElement ( new_bookmark , 'bookmark_name' ) bookmark_name ...
Add a new bookmark
23,562
def remove_bookmark ( self , name = None , time = None , chan = None ) : bookmarks = self . rater . find ( 'bookmarks' ) for m in bookmarks : bookmark_name = m . find ( 'bookmark_name' ) . text bookmark_start = float ( m . find ( 'bookmark_start' ) . text ) bookmark_end = float ( m . find ( 'bookmark_end' ) . text ) bo...
if you call it without arguments it removes ALL the bookmarks .
23,563
def remove_event_type ( self , name ) : if name not in self . event_types : lg . info ( 'Event type ' + name + ' was not found.' ) events = self . rater . find ( 'events' ) for e in list ( events ) : if e . get ( 'type' ) == name : events . remove ( e ) self . save ( )
Remove event type based on name .
23,564
def remove_event ( self , name = None , time = None , chan = None ) : events = self . rater . find ( 'events' ) if name is not None : pattern = "event_type[@type='" + name + "']" else : pattern = "event_type" if chan is not None : if isinstance ( chan , ( tuple , list ) ) : chan = ', ' . join ( chan ) for e_type in lis...
get events inside window .
23,565
def epochs ( self ) : if self . rater is None : raise IndexError ( 'You need to have at least one rater' ) for one_epoch in self . rater . iterfind ( 'stages/epoch' ) : epoch = { 'start' : int ( one_epoch . find ( 'epoch_start' ) . text ) , 'end' : int ( one_epoch . find ( 'epoch_end' ) . text ) , 'stage' : one_epoch ....
Get epochs as generator
23,566
def get_stage_for_epoch ( self , epoch_start , window_length = None , attr = 'stage' ) : for epoch in self . epochs : if epoch [ 'start' ] == epoch_start : return epoch [ attr ] if window_length is not None : epoch_length = epoch [ 'end' ] - epoch [ 'start' ] if logical_and ( window_length < epoch_length , 0 <= ( epoch...
Return stage for one specific epoch .
23,567
def set_stage_for_epoch ( self , epoch_start , name , attr = 'stage' , save = True ) : if self . rater is None : raise IndexError ( 'You need to have at least one rater' ) for one_epoch in self . rater . iterfind ( 'stages/epoch' ) : if int ( one_epoch . find ( 'epoch_start' ) . text ) == epoch_start : one_epoch . find...
Change the stage for one specific epoch .
23,568
def set_cycle_mrkr ( self , epoch_start , end = False ) : if self . rater is None : raise IndexError ( 'You need to have at least one rater' ) bound = 'start' if end : bound = 'end' for one_epoch in self . rater . iterfind ( 'stages/epoch' ) : if int ( one_epoch . find ( 'epoch_start' ) . text ) == epoch_start : cycles...
Mark epoch start as cycle start or end .
23,569
def remove_cycle_mrkr ( self , epoch_start ) : if self . rater is None : raise IndexError ( 'You need to have at least one rater' ) cycles = self . rater . find ( 'cycles' ) for one_mrkr in cycles . iterfind ( 'cyc_start' ) : if int ( one_mrkr . text ) == epoch_start : cycles . remove ( one_mrkr ) self . save ( ) retur...
Remove cycle marker at epoch_start .
23,570
def clear_cycles ( self ) : if self . rater is None : raise IndexError ( 'You need to have at least one rater' ) cycles = self . rater . find ( 'cycles' ) for cyc in list ( cycles ) : cycles . remove ( cyc ) self . save ( )
Remove all cycle markers in current rater .
23,571
def get_cycles ( self ) : cycles = self . rater . find ( 'cycles' ) if not cycles : return None starts = sorted ( [ float ( mrkr . text ) for mrkr in cycles . findall ( 'cyc_start' ) ] ) ends = sorted ( [ float ( mrkr . text ) for mrkr in cycles . findall ( 'cyc_end' ) ] ) cyc_list = [ ] if not starts or not ends : ret...
Return the cycle start and end times .
23,572
def switch ( self , time = None ) : stag_to_int = { 'NREM1' : 1 , 'NREM2' : 2 , 'NREM3' : 3 , 'REM' : 5 , 'Wake' : 0 } hypno = [ stag_to_int [ x [ 'stage' ] ] for x in self . get_epochs ( time = time ) if x [ 'stage' ] in stag_to_int . keys ( ) ] return sum ( asarray ( diff ( hypno ) , dtype = bool ) )
Obtain switch parameter ie number of times the stage shifts .
23,573
def slp_frag ( self , time = None ) : epochs = self . get_epochs ( time = time ) stage_int = { 'Wake' : 0 , 'NREM1' : 1 , 'NREM2' : 2 , 'NREM3' : 3 , 'REM' : 2 } hypno_str = [ x [ 'stage' ] for x in epochs if x [ 'stage' ] in stage_int . keys ( ) ] hypno_int = [ stage_int [ x ] for x in hypno_str ] frag = sum ( asarray...
Obtain sleep fragmentation parameter ie number of stage shifts to a lighter stage .
23,574
def export ( self , file_to_export , xformat = 'csv' ) : if 'csv' == xformat : with open ( file_to_export , 'w' , newline = '' ) as f : csv_file = writer ( f ) csv_file . writerow ( [ 'Wonambi v{}' . format ( __version__ ) ] ) csv_file . writerow ( ( 'clock start time' , 'start' , 'end' , 'stage' ) ) for epoch in self ...
Export epochwise annotations to csv file .
23,575
def create ( self ) : b0 = QGroupBox ( 'Dataset' ) form = QFormLayout ( ) b0 . setLayout ( form ) open_rec = QPushButton ( 'Open Dataset...' ) open_rec . clicked . connect ( self . open_dataset ) open_rec . setToolTip ( 'Click here to open a new recording' ) self . idx_filename = open_rec self . idx_s_freq = QLabel ( '...
Create the widget layout with all the information .
23,576
def open_dataset ( self , recent = None , debug_filename = None , bids = False ) : if recent : filename = recent elif debug_filename is not None : filename = debug_filename else : try : dir_name = dirname ( self . filename ) except ( AttributeError , TypeError ) : dir_name = self . parent . value ( 'recording_dir' ) fi...
Open a new dataset .
23,577
def display_dataset ( self ) : header = self . dataset . header self . parent . setWindowTitle ( basename ( self . filename ) ) short_filename = short_strings ( basename ( self . filename ) ) self . idx_filename . setText ( short_filename ) self . idx_s_freq . setText ( str ( header [ 's_freq' ] ) ) self . idx_n_chan ....
Update the widget with information about the dataset .
23,578
def display_view ( self ) : self . idx_start . setText ( str ( self . parent . value ( 'window_start' ) ) ) self . idx_length . setText ( str ( self . parent . value ( 'window_length' ) ) ) self . idx_scaling . setText ( str ( self . parent . value ( 'y_scale' ) ) ) self . idx_distance . setText ( str ( self . parent ....
Update information about the size of the traces .
23,579
def reset ( self ) : self . filename = None self . dataset = None self . idx_filename . setText ( 'Open Recordings...' ) self . idx_s_freq . setText ( '' ) self . idx_n_chan . setText ( '' ) self . idx_start_time . setText ( '' ) self . idx_end_time . setText ( '' ) self . idx_scaling . setText ( '' ) self . idx_distan...
Reset widget to original state .
23,580
def update ( self ) : self . filename = self . parent . info . dataset . filename self . chan = self . parent . info . dataset . header [ 'chan_name' ] for chan in self . chan : self . idx_chan . addItem ( chan )
Get info from dataset before opening dialog .
23,581
def create_channels ( chan_name = None , n_chan = None ) : if chan_name is not None : n_chan = len ( chan_name ) elif n_chan is not None : chan_name = _make_chan_name ( n_chan ) else : raise TypeError ( 'You need to specify either the channel names (chan_name) or the number of channels (n_chan)' ) xyz = round ( random ...
Create instance of Channels with random xyz coordinates
23,582
def _color_noise ( x , s_freq , coef = 0 ) : y = fft ( x ) ph = angle ( y ) m = abs ( y ) freq = linspace ( 0 , s_freq / 2 , int ( len ( m ) / 2 ) + 1 ) freq = freq [ 1 : - 1 ] m1 = zeros ( len ( m ) ) m1 [ 1 : int ( len ( m ) / 2 ) ] = m [ 1 : int ( len ( m ) / 2 ) ] * f ( freq , coef ) m1 [ int ( len ( m1 ) / 2 + 1 )...
Add some color to the noise by changing the power spectrum .
23,583
def _read_openephys ( openephys_file ) : root = ElementTree . parse ( openephys_file ) . getroot ( ) channels = [ ] for recording in root : s_freq = float ( recording . attrib [ 'samplerate' ] ) for processor in recording : for channel in processor : channels . append ( channel . attrib ) return s_freq , channels
Read the channel labels and their respective files from the Continuous_Data . openephys file
23,584
def _read_date ( settings_file ) : root = ElementTree . parse ( settings_file ) . getroot ( ) for e0 in root : if e0 . tag == 'INFO' : for e1 in e0 : if e1 . tag == 'DATE' : break return datetime . strptime ( e1 . text , '%d %b %Y %H:%M:%S' )
Get the data from the settings . xml file
23,585
def _read_n_samples ( channel_file ) : n_blocks = int ( ( channel_file . stat ( ) . st_size - HDR_LENGTH ) / BLK_SIZE ) n_samples = n_blocks * BLK_LENGTH return n_blocks , n_samples
Calculate the number of samples based on the file size
23,586
def _read_header ( filename ) : with filename . open ( 'rb' ) as f : h = f . read ( HDR_LENGTH ) . decode ( ) header = { } for line in h . split ( '\n' ) : if '=' in line : key , value = line . split ( ' = ' ) key = key . strip ( ) [ 7 : ] value = value . strip ( ) [ : - 1 ] header [ key ] = value return header
Read the text header for each file
23,587
def _check_header ( channel_file , s_freq ) : hdr = _read_header ( channel_file ) assert int ( hdr [ 'header_bytes' ] ) == HDR_LENGTH assert int ( hdr [ 'blockLength' ] ) == BLK_LENGTH assert int ( hdr [ 'sampleRate' ] ) == s_freq return float ( hdr [ 'bitVolts' ] )
For each file make sure that the header is consistent with the information in the text file .
23,588
def all_to_annot ( self , annot , names = [ 'TPd' , 'TPs' , 'FP' , 'FN' ] ) : self . to_annot ( annot , 'tp_det' , names [ 0 ] ) self . to_annot ( annot , 'tp_std' , names [ 1 ] ) self . to_annot ( annot , 'fp' , names [ 2 ] ) self . to_annot ( annot , 'fn' , names [ 3 ] )
Convenience function to write all events to XML by category showing overlapping TP detection and TP standard .
23,589
def convert_sample_to_video_time ( sample , orig_s_freq , sampleStamp , sampleTime ) : if sample < sampleStamp [ 0 ] : s_freq = orig_s_freq id0 = 0 elif sample > sampleStamp [ - 1 ] : s_freq = orig_s_freq id0 = len ( sampleStamp ) - 1 else : id0 = where ( asarray ( sampleStamp ) <= sample ) [ 0 ] [ - 1 ] id1 = where ( ...
Convert sample number to video time using snc information .
23,590
def _find_channels ( note ) : id_ch = note . index ( 'ChanNames' ) chan_beg = note . index ( '(' , id_ch ) chan_end = note . index ( ')' , chan_beg ) note_with_chan = note [ chan_beg + 1 : chan_end ] return [ x . strip ( '" ' ) for x in note_with_chan . split ( ',' ) ]
Find the channel names within a string .
23,591
def _find_start_time ( hdr , s_freq ) : start_time = hdr [ 'stc' ] [ 'creation_time' ] for one_stamp in hdr [ 'stamps' ] : if one_stamp [ 'segment_name' ] . decode ( ) == hdr [ 'erd' ] [ 'filename' ] : offset = one_stamp [ 'start_stamp' ] break erd_time = ( hdr [ 'erd' ] [ 'creation_time' ] - timedelta ( seconds = offs...
Find the start time usually in STC but if that s not correct use ERD
23,592
def _read_ent ( ent_file ) : with ent_file . open ( 'rb' ) as f : f . seek ( 352 ) note_hdr_length = 16 allnote = [ ] while True : note = { } note [ 'type' ] , = unpack ( '<i' , f . read ( 4 ) ) note [ 'length' ] , = unpack ( '<i' , f . read ( 4 ) ) note [ 'prev_length' ] , = unpack ( '<i' , f . read ( 4 ) ) note [ 'un...
Read notes stored in . ent file .
23,593
def _read_packet ( f , pos , n_smp , n_allchan , abs_delta ) : if len ( abs_delta ) == 1 : abs_delta = unpack ( 'b' , abs_delta ) [ 0 ] else : abs_delta = unpack ( 'h' , abs_delta ) [ 0 ] l_deltamask = int ( ceil ( n_allchan / BITS_IN_BYTE ) ) dat = empty ( ( n_allchan , n_smp ) , dtype = int32 ) f . seek ( pos ) for i...
Read a packet of compressed data
23,594
def _read_erd ( erd_file , begsam , endsam ) : hdr = _read_hdr_file ( erd_file ) n_allchan = hdr [ 'num_channels' ] shorted = hdr [ 'shorted' ] n_shorted = sum ( shorted ) if n_shorted > 0 : raise NotImplementedError ( 'shorted channels not tested yet' ) if hdr [ 'file_schema' ] in ( 7 , ) : abs_delta = b'\x80' raise N...
Read the raw data and return a matrix converted to microvolts .
23,595
def _read_etc ( etc_file ) : etc_type = dtype ( [ ( 'offset' , '<i' ) , ( 'samplestamp' , '<i' ) , ( 'sample_num' , '<i' ) , ( 'sample_span' , '<h' ) , ( 'unknown' , '<h' ) ] ) with etc_file . open ( 'rb' ) as f : f . seek ( 352 ) etc = fromfile ( f , dtype = etc_type ) return etc
Return information about table of content for each erd .
23,596
def _read_snc ( snc_file ) : snc_raw_dtype = dtype ( [ ( 'sampleStamp' , '<i' ) , ( 'sampleTime' , '<q' ) ] ) with snc_file . open ( 'rb' ) as f : f . seek ( 352 ) snc_raw = fromfile ( f , dtype = snc_raw_dtype ) sampleStamp = snc_raw [ 'sampleStamp' ] sampleTime = asarray ( [ _filetime_to_dt ( x ) for x in snc_raw [ '...
Read Synchronization File and return sample stamp and time
23,597
def _read_stc ( stc_file ) : hdr = _read_hdr_file ( stc_file ) stc_dtype = dtype ( [ ( 'segment_name' , 'a256' ) , ( 'start_stamp' , '<i' ) , ( 'end_stamp' , '<i' ) , ( 'sample_num' , '<i' ) , ( 'sample_span' , '<i' ) ] ) with stc_file . open ( 'rb' ) as f : f . seek ( 352 ) hdr [ 'next_segment' ] = unpack ( '<i' , f ....
Read Segment Table of Contents file .
23,598
def _read_vtc ( vtc_file ) : with vtc_file . open ( 'rb' ) as f : filebytes = f . read ( ) hdr = { } hdr [ 'file_guid' ] = hexlify ( filebytes [ : 16 ] ) i = 20 mpg_file = [ ] start_time = [ ] end_time = [ ] while i < len ( filebytes ) : mpg_file . append ( _make_str ( unpack ( 'c' * 261 , filebytes [ i : i + 261 ] ) )...
Read the VTC file .
23,599
def _read_hdr_dir ( self ) : foldername = Path ( self . filename ) stc_file = foldername / ( foldername . stem + '.stc' ) if stc_file . exists ( ) : self . _filename = stc_file . with_suffix ( '' ) else : stc_file = list ( foldername . glob ( '*.stc' ) ) if len ( stc_file ) == 1 : self . _filename = foldername / stc_fi...
Read the header for basic information .