repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
wonambi-python/wonambi
wonambi/detect/spindle.py
detect_UCSD
def detect_UCSD(dat_orig, s_freq, time, opts): """Spindle detection based on the UCSD method Parameters ---------- dat_orig : ndarray (dtype='float') vector with the data for one channel s_freq : float sampling frequency time : ndarray (dtype='float') vector with the time points for each sample opts : instance of 'DetectSpindle' det_wavelet : dict parameters for 'wavelet_real', det_thres' : float detection threshold sel_thresh : float selection threshold duration : tuple of float min and max duration of spindles frequency : tuple of float low and high frequency of spindle band (for power ratio) ratio_thresh : float ratio between power inside and outside spindle band to accept them Returns ------- list of dict list of detected spindles dict 'det_value_lo' with detection value, 'det_value_hi' with nan, 'sel_value' with selection value float spindle density, per 30-s epoch """ dat_det = transform_signal(dat_orig, s_freq, 'wavelet_real', opts.det_wavelet) det_value = define_threshold(dat_det, s_freq, 'median+std', opts.det_thresh) events = detect_events(dat_det, 'maxima', det_value) dat_sel = transform_signal(dat_orig, s_freq, 'wavelet_real', opts.sel_wavelet) sel_value = define_threshold(dat_sel, s_freq, 'median+std', opts.sel_thresh) events = select_events(dat_sel, events, 'above_thresh', sel_value) events = _merge_close(dat_det, events, time, opts.tolerance) events = within_duration(events, time, opts.duration) events = _merge_close(dat_det, events, time, opts.min_interval) events = remove_straddlers(events, time, s_freq) events = power_ratio(events, dat_orig, s_freq, opts.frequency, opts.ratio_thresh) power_peaks = peak_in_power(events, dat_orig, s_freq, opts.power_peaks) powers = power_in_band(events, dat_orig, s_freq, opts.frequency) sp_in_chan = make_spindles(events, power_peaks, powers, dat_det, dat_orig, time, s_freq) values = {'det_value_lo': det_value, 'sel_value': sel_value} density = len(sp_in_chan) * s_freq * 30 / len(dat_orig) return sp_in_chan, values, density
python
def detect_UCSD(dat_orig, s_freq, time, opts): """Spindle detection based on the UCSD method Parameters ---------- dat_orig : ndarray (dtype='float') vector with the data for one channel s_freq : float sampling frequency time : ndarray (dtype='float') vector with the time points for each sample opts : instance of 'DetectSpindle' det_wavelet : dict parameters for 'wavelet_real', det_thres' : float detection threshold sel_thresh : float selection threshold duration : tuple of float min and max duration of spindles frequency : tuple of float low and high frequency of spindle band (for power ratio) ratio_thresh : float ratio between power inside and outside spindle band to accept them Returns ------- list of dict list of detected spindles dict 'det_value_lo' with detection value, 'det_value_hi' with nan, 'sel_value' with selection value float spindle density, per 30-s epoch """ dat_det = transform_signal(dat_orig, s_freq, 'wavelet_real', opts.det_wavelet) det_value = define_threshold(dat_det, s_freq, 'median+std', opts.det_thresh) events = detect_events(dat_det, 'maxima', det_value) dat_sel = transform_signal(dat_orig, s_freq, 'wavelet_real', opts.sel_wavelet) sel_value = define_threshold(dat_sel, s_freq, 'median+std', opts.sel_thresh) events = select_events(dat_sel, events, 'above_thresh', sel_value) events = _merge_close(dat_det, events, time, opts.tolerance) events = within_duration(events, time, opts.duration) events = _merge_close(dat_det, events, time, opts.min_interval) events = remove_straddlers(events, time, s_freq) events = power_ratio(events, dat_orig, s_freq, opts.frequency, opts.ratio_thresh) power_peaks = peak_in_power(events, dat_orig, s_freq, opts.power_peaks) powers = power_in_band(events, dat_orig, s_freq, opts.frequency) sp_in_chan = make_spindles(events, power_peaks, powers, dat_det, dat_orig, time, s_freq) values = {'det_value_lo': det_value, 'sel_value': sel_value} density = len(sp_in_chan) * s_freq * 30 / len(dat_orig) return sp_in_chan, values, density
[ "def", "detect_UCSD", "(", "dat_orig", ",", "s_freq", ",", "time", ",", "opts", ")", ":", "dat_det", "=", "transform_signal", "(", "dat_orig", ",", "s_freq", ",", "'wavelet_real'", ",", "opts", ".", "det_wavelet", ")", "det_value", "=", "define_threshold", "...
Spindle detection based on the UCSD method Parameters ---------- dat_orig : ndarray (dtype='float') vector with the data for one channel s_freq : float sampling frequency time : ndarray (dtype='float') vector with the time points for each sample opts : instance of 'DetectSpindle' det_wavelet : dict parameters for 'wavelet_real', det_thres' : float detection threshold sel_thresh : float selection threshold duration : tuple of float min and max duration of spindles frequency : tuple of float low and high frequency of spindle band (for power ratio) ratio_thresh : float ratio between power inside and outside spindle band to accept them Returns ------- list of dict list of detected spindles dict 'det_value_lo' with detection value, 'det_value_hi' with nan, 'sel_value' with selection value float spindle density, per 30-s epoch
[ "Spindle", "detection", "based", "on", "the", "UCSD", "method" ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/detect/spindle.py#L984-L1051
train
23,400
wonambi-python/wonambi
wonambi/detect/spindle.py
detect_Concordia
def detect_Concordia(dat_orig, s_freq, time, opts): """Spindle detection, experimental Concordia method. Similar to Moelle 2011 and Nir2011. Parameters ---------- dat_orig : ndarray (dtype='float') vector with the data for one channel s_freq : float sampling frequency opts : instance of 'DetectSpindle' 'det_butter' : dict parameters for 'butter', 'moving_rms' : dict parameters for 'moving_rms' 'smooth' : dict parameters for 'smooth' 'det_thresh' : float low detection threshold 'det_thresh_hi' : float high detection threshold 'sel_thresh' : float selection threshold 'duration' : tuple of float min and max duration of spindles Returns ------- list of dict list of detected spindles dict 'det_value_lo', 'det_value_hi' with detection values, 'sel_value' with selection value float spindle density, per 30-s epoch """ dat_det = transform_signal(dat_orig, s_freq, 'butter', opts.det_butter) dat_det = transform_signal(dat_det, s_freq, 'moving_rms', opts.moving_rms) dat_det = transform_signal(dat_det, s_freq, 'smooth', opts.smooth) det_value_lo = define_threshold(dat_det, s_freq, 'mean+std', opts.det_thresh) det_value_hi = define_threshold(dat_det, s_freq, 'mean+std', opts.det_thresh_hi) sel_value = define_threshold(dat_det, s_freq, 'mean+std', opts.sel_thresh) events = detect_events(dat_det, 'between_thresh', value=(det_value_lo, det_value_hi)) if events is not None: events = _merge_close(dat_det, events, time, opts.tolerance) events = select_events(dat_det, events, 'above_thresh', sel_value) events = within_duration(events, time, opts.duration) events = _merge_close(dat_det, events, time, opts.min_interval) events = remove_straddlers(events, time, s_freq) power_peaks = peak_in_power(events, dat_orig, s_freq, opts.power_peaks) powers = power_in_band(events, dat_orig, s_freq, opts.frequency) sp_in_chan = make_spindles(events, power_peaks, powers, dat_det, dat_orig, time, s_freq) else: lg.info('No spindle found') sp_in_chan = [] values = {'det_value_lo': det_value_lo, 'sel_value': sel_value} density = len(sp_in_chan) * s_freq * 30 / len(dat_orig) return sp_in_chan, values, density
python
def detect_Concordia(dat_orig, s_freq, time, opts): """Spindle detection, experimental Concordia method. Similar to Moelle 2011 and Nir2011. Parameters ---------- dat_orig : ndarray (dtype='float') vector with the data for one channel s_freq : float sampling frequency opts : instance of 'DetectSpindle' 'det_butter' : dict parameters for 'butter', 'moving_rms' : dict parameters for 'moving_rms' 'smooth' : dict parameters for 'smooth' 'det_thresh' : float low detection threshold 'det_thresh_hi' : float high detection threshold 'sel_thresh' : float selection threshold 'duration' : tuple of float min and max duration of spindles Returns ------- list of dict list of detected spindles dict 'det_value_lo', 'det_value_hi' with detection values, 'sel_value' with selection value float spindle density, per 30-s epoch """ dat_det = transform_signal(dat_orig, s_freq, 'butter', opts.det_butter) dat_det = transform_signal(dat_det, s_freq, 'moving_rms', opts.moving_rms) dat_det = transform_signal(dat_det, s_freq, 'smooth', opts.smooth) det_value_lo = define_threshold(dat_det, s_freq, 'mean+std', opts.det_thresh) det_value_hi = define_threshold(dat_det, s_freq, 'mean+std', opts.det_thresh_hi) sel_value = define_threshold(dat_det, s_freq, 'mean+std', opts.sel_thresh) events = detect_events(dat_det, 'between_thresh', value=(det_value_lo, det_value_hi)) if events is not None: events = _merge_close(dat_det, events, time, opts.tolerance) events = select_events(dat_det, events, 'above_thresh', sel_value) events = within_duration(events, time, opts.duration) events = _merge_close(dat_det, events, time, opts.min_interval) events = remove_straddlers(events, time, s_freq) power_peaks = peak_in_power(events, dat_orig, s_freq, opts.power_peaks) powers = power_in_band(events, dat_orig, s_freq, opts.frequency) sp_in_chan = make_spindles(events, power_peaks, powers, dat_det, dat_orig, time, s_freq) else: lg.info('No spindle found') sp_in_chan = [] values = {'det_value_lo': det_value_lo, 'sel_value': sel_value} density = len(sp_in_chan) * s_freq * 30 / len(dat_orig) return sp_in_chan, values, density
[ "def", "detect_Concordia", "(", "dat_orig", ",", "s_freq", ",", "time", ",", "opts", ")", ":", "dat_det", "=", "transform_signal", "(", "dat_orig", ",", "s_freq", ",", "'butter'", ",", "opts", ".", "det_butter", ")", "dat_det", "=", "transform_signal", "(", ...
Spindle detection, experimental Concordia method. Similar to Moelle 2011 and Nir2011. Parameters ---------- dat_orig : ndarray (dtype='float') vector with the data for one channel s_freq : float sampling frequency opts : instance of 'DetectSpindle' 'det_butter' : dict parameters for 'butter', 'moving_rms' : dict parameters for 'moving_rms' 'smooth' : dict parameters for 'smooth' 'det_thresh' : float low detection threshold 'det_thresh_hi' : float high detection threshold 'sel_thresh' : float selection threshold 'duration' : tuple of float min and max duration of spindles Returns ------- list of dict list of detected spindles dict 'det_value_lo', 'det_value_hi' with detection values, 'sel_value' with selection value float spindle density, per 30-s epoch
[ "Spindle", "detection", "experimental", "Concordia", "method", ".", "Similar", "to", "Moelle", "2011", "and", "Nir2011", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/detect/spindle.py#L1054-L1125
train
23,401
wonambi-python/wonambi
wonambi/detect/spindle.py
define_threshold
def define_threshold(dat, s_freq, method, value, nbins=120): """Return the value of the threshold based on relative values. Parameters ---------- dat : ndarray (dtype='float') vector with the data after selection-transformation s_freq : float sampling frequency method : str one of 'mean', 'median', 'std', 'mean+std', 'median+std', 'histmax' value : float value to multiply the values for nbins : int for histmax method, number of bins in the histogram Returns ------- float threshold in useful units. """ if method == 'mean': value = value * mean(dat) elif method == 'median': value = value * median(dat) elif method == 'std': value = value * std(dat) elif method == 'mean+std': value = mean(dat) + value * std(dat) elif method == 'median+std': value = median(dat) + value * std(dat) elif method == 'histmax': hist = histogram(dat, bins=nbins) idx_maxbin = argmax(hist[0]) maxamp = mean((hist[1][idx_maxbin], hist[1][idx_maxbin + 1])) value = value * maxamp return value
python
def define_threshold(dat, s_freq, method, value, nbins=120): """Return the value of the threshold based on relative values. Parameters ---------- dat : ndarray (dtype='float') vector with the data after selection-transformation s_freq : float sampling frequency method : str one of 'mean', 'median', 'std', 'mean+std', 'median+std', 'histmax' value : float value to multiply the values for nbins : int for histmax method, number of bins in the histogram Returns ------- float threshold in useful units. """ if method == 'mean': value = value * mean(dat) elif method == 'median': value = value * median(dat) elif method == 'std': value = value * std(dat) elif method == 'mean+std': value = mean(dat) + value * std(dat) elif method == 'median+std': value = median(dat) + value * std(dat) elif method == 'histmax': hist = histogram(dat, bins=nbins) idx_maxbin = argmax(hist[0]) maxamp = mean((hist[1][idx_maxbin], hist[1][idx_maxbin + 1])) value = value * maxamp return value
[ "def", "define_threshold", "(", "dat", ",", "s_freq", ",", "method", ",", "value", ",", "nbins", "=", "120", ")", ":", "if", "method", "==", "'mean'", ":", "value", "=", "value", "*", "mean", "(", "dat", ")", "elif", "method", "==", "'median'", ":", ...
Return the value of the threshold based on relative values. Parameters ---------- dat : ndarray (dtype='float') vector with the data after selection-transformation s_freq : float sampling frequency method : str one of 'mean', 'median', 'std', 'mean+std', 'median+std', 'histmax' value : float value to multiply the values for nbins : int for histmax method, number of bins in the histogram Returns ------- float threshold in useful units.
[ "Return", "the", "value", "of", "the", "threshold", "based", "on", "relative", "values", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/detect/spindle.py#L1483-L1521
train
23,402
wonambi-python/wonambi
wonambi/detect/spindle.py
detect_events
def detect_events(dat, method, value=None): """Detect events using 'above_thresh', 'below_thresh' or 'maxima' method. Parameters ---------- dat : ndarray (dtype='float') vector with the data after transformation method : str 'above_thresh', 'below_thresh' or 'maxima' value : float or tuple of float for 'above_thresh' or 'below_thresh', it's the value of threshold for the event detection for 'between_thresh', it's the lower and upper threshold as tuple for 'maxima', it's the distance in s from the peak to find a minimum Returns ------- ndarray (dtype='int') N x 3 matrix with start, peak, end samples """ if 'thresh' in method or 'custom' == method: if method == 'above_thresh': above_det = dat >= value detected = _detect_start_end(above_det) if method == 'below_thresh': below_det = dat < value detected = _detect_start_end(below_det) if method == 'between_thresh': above_det = dat >= value[0] below_det = dat < value[1] between_det = logical_and(above_det, below_det) detected = _detect_start_end(between_det) if method == 'custom': detected = _detect_start_end(dat) if detected is None: return None if method in ['above_thresh', 'custom']: # add the location of the peak in the middle detected = insert(detected, 1, 0, axis=1) for i in detected: i[1] = i[0] + argmax(dat[i[0]:i[2]]) if method in ['below_thresh', 'between_thresh']: # add the location of the trough in the middle detected = insert(detected, 1, 0, axis=1) for i in detected: i[1] = i[0] + argmin(dat[i[0]:i[2]]) if method == 'maxima': peaks = argrelmax(dat)[0] detected = vstack((peaks, peaks, peaks)).T if value is not None: detected = detected[dat[peaks] > value, :] return detected
python
def detect_events(dat, method, value=None): """Detect events using 'above_thresh', 'below_thresh' or 'maxima' method. Parameters ---------- dat : ndarray (dtype='float') vector with the data after transformation method : str 'above_thresh', 'below_thresh' or 'maxima' value : float or tuple of float for 'above_thresh' or 'below_thresh', it's the value of threshold for the event detection for 'between_thresh', it's the lower and upper threshold as tuple for 'maxima', it's the distance in s from the peak to find a minimum Returns ------- ndarray (dtype='int') N x 3 matrix with start, peak, end samples """ if 'thresh' in method or 'custom' == method: if method == 'above_thresh': above_det = dat >= value detected = _detect_start_end(above_det) if method == 'below_thresh': below_det = dat < value detected = _detect_start_end(below_det) if method == 'between_thresh': above_det = dat >= value[0] below_det = dat < value[1] between_det = logical_and(above_det, below_det) detected = _detect_start_end(between_det) if method == 'custom': detected = _detect_start_end(dat) if detected is None: return None if method in ['above_thresh', 'custom']: # add the location of the peak in the middle detected = insert(detected, 1, 0, axis=1) for i in detected: i[1] = i[0] + argmax(dat[i[0]:i[2]]) if method in ['below_thresh', 'between_thresh']: # add the location of the trough in the middle detected = insert(detected, 1, 0, axis=1) for i in detected: i[1] = i[0] + argmin(dat[i[0]:i[2]]) if method == 'maxima': peaks = argrelmax(dat)[0] detected = vstack((peaks, peaks, peaks)).T if value is not None: detected = detected[dat[peaks] > value, :] return detected
[ "def", "detect_events", "(", "dat", ",", "method", ",", "value", "=", "None", ")", ":", "if", "'thresh'", "in", "method", "or", "'custom'", "==", "method", ":", "if", "method", "==", "'above_thresh'", ":", "above_det", "=", "dat", ">=", "value", "detecte...
Detect events using 'above_thresh', 'below_thresh' or 'maxima' method. Parameters ---------- dat : ndarray (dtype='float') vector with the data after transformation method : str 'above_thresh', 'below_thresh' or 'maxima' value : float or tuple of float for 'above_thresh' or 'below_thresh', it's the value of threshold for the event detection for 'between_thresh', it's the lower and upper threshold as tuple for 'maxima', it's the distance in s from the peak to find a minimum Returns ------- ndarray (dtype='int') N x 3 matrix with start, peak, end samples
[ "Detect", "events", "using", "above_thresh", "below_thresh", "or", "maxima", "method", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/detect/spindle.py#L1556-L1619
train
23,403
wonambi-python/wonambi
wonambi/detect/spindle.py
select_events
def select_events(dat, detected, method, value): """Select start sample and end sample of the events. Parameters ---------- dat : ndarray (dtype='float') vector with the data after selection-transformation detected : ndarray (dtype='int') N x 3 matrix with start, peak, end samples method : str 'above_thresh', 'below_thresh' value : float for 'threshold', it's the value of threshold for the spindle selection. Returns ------- ndarray (dtype='int') N x 3 matrix with start, peak, end samples """ if method == 'above_thresh': above_sel = dat >= value detected = _select_period(detected, above_sel) elif method == 'below_thresh': below_sel = dat <= value detected = _select_period(detected, below_sel) return detected
python
def select_events(dat, detected, method, value): """Select start sample and end sample of the events. Parameters ---------- dat : ndarray (dtype='float') vector with the data after selection-transformation detected : ndarray (dtype='int') N x 3 matrix with start, peak, end samples method : str 'above_thresh', 'below_thresh' value : float for 'threshold', it's the value of threshold for the spindle selection. Returns ------- ndarray (dtype='int') N x 3 matrix with start, peak, end samples """ if method == 'above_thresh': above_sel = dat >= value detected = _select_period(detected, above_sel) elif method == 'below_thresh': below_sel = dat <= value detected = _select_period(detected, below_sel) return detected
[ "def", "select_events", "(", "dat", ",", "detected", ",", "method", ",", "value", ")", ":", "if", "method", "==", "'above_thresh'", ":", "above_sel", "=", "dat", ">=", "value", "detected", "=", "_select_period", "(", "detected", ",", "above_sel", ")", "eli...
Select start sample and end sample of the events. Parameters ---------- dat : ndarray (dtype='float') vector with the data after selection-transformation detected : ndarray (dtype='int') N x 3 matrix with start, peak, end samples method : str 'above_thresh', 'below_thresh' value : float for 'threshold', it's the value of threshold for the spindle selection. Returns ------- ndarray (dtype='int') N x 3 matrix with start, peak, end samples
[ "Select", "start", "sample", "and", "end", "sample", "of", "the", "events", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/detect/spindle.py#L1622-L1649
train
23,404
wonambi-python/wonambi
wonambi/detect/spindle.py
merge_close
def merge_close(events, min_interval, merge_to_longer=False): """Merge events that are separated by a less than a minimum interval. Parameters ---------- events : list of dict events with 'start' and 'end' times, from one or several channels. **Events must be sorted by their start time.** min_interval : float minimum delay between consecutive events, in seconds merge_to_longer : bool (default: False) If True, info (chan, peak, etc.) from the longer of the 2 events is kept. Otherwise, info from the earlier onset spindle is kept. Returns ------- list of dict original events list with close events merged. """ half_iv = min_interval / 2 merged = [] for higher in events: if not merged: merged.append(higher) else: lower = merged[-1] if higher['start'] - half_iv <= lower['end'] + half_iv: if merge_to_longer and (higher['end'] - higher['start'] > lower['end'] - lower['start']): start = min(lower['start'], higher['start']) higher.update({'start': start}) merged[-1] = higher else: end = max(lower['end'], higher['end']) merged[-1].update({'end': end}) else: merged.append(higher) return merged
python
def merge_close(events, min_interval, merge_to_longer=False): """Merge events that are separated by a less than a minimum interval. Parameters ---------- events : list of dict events with 'start' and 'end' times, from one or several channels. **Events must be sorted by their start time.** min_interval : float minimum delay between consecutive events, in seconds merge_to_longer : bool (default: False) If True, info (chan, peak, etc.) from the longer of the 2 events is kept. Otherwise, info from the earlier onset spindle is kept. Returns ------- list of dict original events list with close events merged. """ half_iv = min_interval / 2 merged = [] for higher in events: if not merged: merged.append(higher) else: lower = merged[-1] if higher['start'] - half_iv <= lower['end'] + half_iv: if merge_to_longer and (higher['end'] - higher['start'] > lower['end'] - lower['start']): start = min(lower['start'], higher['start']) higher.update({'start': start}) merged[-1] = higher else: end = max(lower['end'], higher['end']) merged[-1].update({'end': end}) else: merged.append(higher) return merged
[ "def", "merge_close", "(", "events", ",", "min_interval", ",", "merge_to_longer", "=", "False", ")", ":", "half_iv", "=", "min_interval", "/", "2", "merged", "=", "[", "]", "for", "higher", "in", "events", ":", "if", "not", "merged", ":", "merged", ".", ...
Merge events that are separated by a less than a minimum interval. Parameters ---------- events : list of dict events with 'start' and 'end' times, from one or several channels. **Events must be sorted by their start time.** min_interval : float minimum delay between consecutive events, in seconds merge_to_longer : bool (default: False) If True, info (chan, peak, etc.) from the longer of the 2 events is kept. Otherwise, info from the earlier onset spindle is kept. Returns ------- list of dict original events list with close events merged.
[ "Merge", "events", "that", "are", "separated", "by", "a", "less", "than", "a", "minimum", "interval", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/detect/spindle.py#L1652-L1697
train
23,405
wonambi-python/wonambi
wonambi/detect/spindle.py
within_duration
def within_duration(events, time, limits): """Check whether event is within time limits. Parameters ---------- events : ndarray (dtype='int') N x M matrix with start sample first and end samples last on M time : ndarray (dtype='float') vector with time points limits : tuple of float low and high limit for spindle duration Returns ------- ndarray (dtype='int') N x M matrix with start sample first and end samples last on M """ min_dur = max_dur = ones(events.shape[0], dtype=bool) if limits[0] is not None: min_dur = time[events[:, -1] - 1] - time[events[:, 0]] >= limits[0] if limits[1] is not None: max_dur = time[events[:, -1] - 1] - time[events[:, 0]] <= limits[1] return events[min_dur & max_dur, :]
python
def within_duration(events, time, limits): """Check whether event is within time limits. Parameters ---------- events : ndarray (dtype='int') N x M matrix with start sample first and end samples last on M time : ndarray (dtype='float') vector with time points limits : tuple of float low and high limit for spindle duration Returns ------- ndarray (dtype='int') N x M matrix with start sample first and end samples last on M """ min_dur = max_dur = ones(events.shape[0], dtype=bool) if limits[0] is not None: min_dur = time[events[:, -1] - 1] - time[events[:, 0]] >= limits[0] if limits[1] is not None: max_dur = time[events[:, -1] - 1] - time[events[:, 0]] <= limits[1] return events[min_dur & max_dur, :]
[ "def", "within_duration", "(", "events", ",", "time", ",", "limits", ")", ":", "min_dur", "=", "max_dur", "=", "ones", "(", "events", ".", "shape", "[", "0", "]", ",", "dtype", "=", "bool", ")", "if", "limits", "[", "0", "]", "is", "not", "None", ...
Check whether event is within time limits. Parameters ---------- events : ndarray (dtype='int') N x M matrix with start sample first and end samples last on M time : ndarray (dtype='float') vector with time points limits : tuple of float low and high limit for spindle duration Returns ------- ndarray (dtype='int') N x M matrix with start sample first and end samples last on M
[ "Check", "whether", "event", "is", "within", "time", "limits", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/detect/spindle.py#L1700-L1725
train
23,406
wonambi-python/wonambi
wonambi/detect/spindle.py
remove_straddlers
def remove_straddlers(events, time, s_freq, toler=0.1): """Reject an event if it straddles a stitch, by comparing its duration to its timespan. Parameters ---------- events : ndarray (dtype='int') N x M matrix with start, ..., end samples time : ndarray (dtype='float') vector with time points s_freq : float sampling frequency toler : float, def=0.1 maximum tolerated difference between event duration and timespan Returns ------- ndarray (dtype='int') N x M matrix with start , ..., end samples """ dur = (events[:, -1] - 1 - events[:, 0]) / s_freq continuous = time[events[:, -1] - 1] - time[events[:, 0]] - dur < toler return events[continuous, :]
python
def remove_straddlers(events, time, s_freq, toler=0.1): """Reject an event if it straddles a stitch, by comparing its duration to its timespan. Parameters ---------- events : ndarray (dtype='int') N x M matrix with start, ..., end samples time : ndarray (dtype='float') vector with time points s_freq : float sampling frequency toler : float, def=0.1 maximum tolerated difference between event duration and timespan Returns ------- ndarray (dtype='int') N x M matrix with start , ..., end samples """ dur = (events[:, -1] - 1 - events[:, 0]) / s_freq continuous = time[events[:, -1] - 1] - time[events[:, 0]] - dur < toler return events[continuous, :]
[ "def", "remove_straddlers", "(", "events", ",", "time", ",", "s_freq", ",", "toler", "=", "0.1", ")", ":", "dur", "=", "(", "events", "[", ":", ",", "-", "1", "]", "-", "1", "-", "events", "[", ":", ",", "0", "]", ")", "/", "s_freq", "continuou...
Reject an event if it straddles a stitch, by comparing its duration to its timespan. Parameters ---------- events : ndarray (dtype='int') N x M matrix with start, ..., end samples time : ndarray (dtype='float') vector with time points s_freq : float sampling frequency toler : float, def=0.1 maximum tolerated difference between event duration and timespan Returns ------- ndarray (dtype='int') N x M matrix with start , ..., end samples
[ "Reject", "an", "event", "if", "it", "straddles", "a", "stitch", "by", "comparing", "its", "duration", "to", "its", "timespan", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/detect/spindle.py#L1728-L1751
train
23,407
wonambi-python/wonambi
wonambi/detect/spindle.py
power_ratio
def power_ratio(events, dat, s_freq, limits, ratio_thresh): """Estimate the ratio in power between spindle band and lower frequencies. Parameters ---------- events : ndarray (dtype='int') N x 3 matrix with start, peak, end samples dat : ndarray (dtype='float') vector with the original data s_freq : float sampling frequency limits : tuple of float high and low frequencies for spindle band ratio_thresh : float ratio between spindle vs non-spindle amplitude Returns ------- ndarray (dtype='int') N x 3 matrix with start, peak, end samples Notes ----- In the original matlab script, it uses amplitude, not power. """ ratio = empty(events.shape[0]) for i, one_event in enumerate(events): x0 = one_event[0] x1 = one_event[2] if x0 < 0 or x1 >= len(dat): ratio[i] = 0 else: f, Pxx = periodogram(dat[x0:x1], s_freq, scaling='spectrum') Pxx = sqrt(Pxx) # use amplitude freq_sp = (f >= limits[0]) & (f <= limits[1]) freq_nonsp = (f <= limits[1]) ratio[i] = mean(Pxx[freq_sp]) / mean(Pxx[freq_nonsp]) events = events[ratio > ratio_thresh, :] return events
python
def power_ratio(events, dat, s_freq, limits, ratio_thresh): """Estimate the ratio in power between spindle band and lower frequencies. Parameters ---------- events : ndarray (dtype='int') N x 3 matrix with start, peak, end samples dat : ndarray (dtype='float') vector with the original data s_freq : float sampling frequency limits : tuple of float high and low frequencies for spindle band ratio_thresh : float ratio between spindle vs non-spindle amplitude Returns ------- ndarray (dtype='int') N x 3 matrix with start, peak, end samples Notes ----- In the original matlab script, it uses amplitude, not power. """ ratio = empty(events.shape[0]) for i, one_event in enumerate(events): x0 = one_event[0] x1 = one_event[2] if x0 < 0 or x1 >= len(dat): ratio[i] = 0 else: f, Pxx = periodogram(dat[x0:x1], s_freq, scaling='spectrum') Pxx = sqrt(Pxx) # use amplitude freq_sp = (f >= limits[0]) & (f <= limits[1]) freq_nonsp = (f <= limits[1]) ratio[i] = mean(Pxx[freq_sp]) / mean(Pxx[freq_nonsp]) events = events[ratio > ratio_thresh, :] return events
[ "def", "power_ratio", "(", "events", ",", "dat", ",", "s_freq", ",", "limits", ",", "ratio_thresh", ")", ":", "ratio", "=", "empty", "(", "events", ".", "shape", "[", "0", "]", ")", "for", "i", ",", "one_event", "in", "enumerate", "(", "events", ")",...
Estimate the ratio in power between spindle band and lower frequencies. Parameters ---------- events : ndarray (dtype='int') N x 3 matrix with start, peak, end samples dat : ndarray (dtype='float') vector with the original data s_freq : float sampling frequency limits : tuple of float high and low frequencies for spindle band ratio_thresh : float ratio between spindle vs non-spindle amplitude Returns ------- ndarray (dtype='int') N x 3 matrix with start, peak, end samples Notes ----- In the original matlab script, it uses amplitude, not power.
[ "Estimate", "the", "ratio", "in", "power", "between", "spindle", "band", "and", "lower", "frequencies", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/detect/spindle.py#L1755-L1801
train
23,408
wonambi-python/wonambi
wonambi/detect/spindle.py
peak_in_power
def peak_in_power(events, dat, s_freq, method, value=None): """Define peak in power of the signal. Parameters ---------- events : ndarray (dtype='int') N x 3 matrix with start, peak, end samples dat : ndarray (dtype='float') vector with the original data s_freq : float sampling frequency method : str or None 'peak' or 'interval'. If None, values will be all NaN value : float size of the window around peak, or nothing (for 'interval') Returns ------- ndarray (dtype='float') vector with peak frequency """ 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
python
def peak_in_power(events, dat, s_freq, method, value=None): """Define peak in power of the signal. Parameters ---------- events : ndarray (dtype='int') N x 3 matrix with start, peak, end samples dat : ndarray (dtype='float') vector with the original data s_freq : float sampling frequency method : str or None 'peak' or 'interval'. If None, values will be all NaN value : float size of the window around peak, or nothing (for 'interval') Returns ------- ndarray (dtype='float') vector with peak frequency """ 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
[ "def", "peak_in_power", "(", "events", ",", "dat", ",", "s_freq", ",", "method", ",", "value", "=", "None", ")", ":", "dat", "=", "diff", "(", "dat", ")", "# remove 1/f", "peak", "=", "empty", "(", "events", ".", "shape", "[", "0", "]", ")", "peak"...
Define peak in power of the signal. Parameters ---------- events : ndarray (dtype='int') N x 3 matrix with start, peak, end samples dat : ndarray (dtype='float') vector with the original data s_freq : float sampling frequency method : str or None 'peak' or 'interval'. If None, values will be all NaN value : float size of the window around peak, or nothing (for 'interval') Returns ------- ndarray (dtype='float') vector with peak frequency
[ "Define", "peak", "in", "power", "of", "the", "signal", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/detect/spindle.py#L1804-L1849
train
23,409
wonambi-python/wonambi
wonambi/detect/spindle.py
power_in_band
def power_in_band(events, dat, s_freq, frequency): """Define power of the signal within frequency band. Parameters ---------- events : ndarray (dtype='int') N x 3 matrix with start, peak, end samples dat : ndarray (dtype='float') vector with the original data s_freq : float sampling frequency frequency : tuple of float low and high frequency of spindle band, for window Returns ------- ndarray (dtype='float') vector with power """ 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
python
def power_in_band(events, dat, s_freq, frequency): """Define power of the signal within frequency band. Parameters ---------- events : ndarray (dtype='int') N x 3 matrix with start, peak, end samples dat : ndarray (dtype='float') vector with the original data s_freq : float sampling frequency frequency : tuple of float low and high frequency of spindle band, for window Returns ------- ndarray (dtype='float') vector with power """ 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
[ "def", "power_in_band", "(", "events", ",", "dat", ",", "s_freq", ",", "frequency", ")", ":", "dat", "=", "diff", "(", "dat", ")", "# remove 1/f", "pw", "=", "empty", "(", "events", ".", "shape", "[", "0", "]", ")", "pw", ".", "fill", "(", "nan", ...
Define power of the signal within frequency band. Parameters ---------- events : ndarray (dtype='int') N x 3 matrix with start, peak, end samples dat : ndarray (dtype='float') vector with the original data s_freq : float sampling frequency frequency : tuple of float low and high frequency of spindle band, for window Returns ------- ndarray (dtype='float') vector with power
[ "Define", "power", "of", "the", "signal", "within", "frequency", "band", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/detect/spindle.py#L1852-L1890
train
23,410
wonambi-python/wonambi
wonambi/detect/spindle.py
make_spindles
def make_spindles(events, power_peaks, powers, dat_det, dat_orig, time, s_freq): """Create dict for each spindle, based on events of time points. Parameters ---------- events : ndarray (dtype='int') N x 3 matrix with start, peak, end samples, and peak frequency power_peaks : ndarray (dtype='float') peak in power spectrum for each event powers : ndarray (dtype='float') average power in power spectrum for each event dat_det : ndarray (dtype='float') vector with the data after detection-transformation (to compute peak) dat_orig : ndarray (dtype='float') vector with the raw data on which detection was performed time : ndarray (dtype='float') vector with time points s_freq : float sampling frequency Returns ------- list of dict list of all the spindles, with information about start_time, peak_time, end_time (s), peak_val (signal units), area_under_curve (signal units * s), peak_freq (Hz) """ 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
python
def make_spindles(events, power_peaks, powers, dat_det, dat_orig, time, s_freq): """Create dict for each spindle, based on events of time points. Parameters ---------- events : ndarray (dtype='int') N x 3 matrix with start, peak, end samples, and peak frequency power_peaks : ndarray (dtype='float') peak in power spectrum for each event powers : ndarray (dtype='float') average power in power spectrum for each event dat_det : ndarray (dtype='float') vector with the data after detection-transformation (to compute peak) dat_orig : ndarray (dtype='float') vector with the raw data on which detection was performed time : ndarray (dtype='float') vector with time points s_freq : float sampling frequency Returns ------- list of dict list of all the spindles, with information about start_time, peak_time, end_time (s), peak_val (signal units), area_under_curve (signal units * s), peak_freq (Hz) """ 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
[ "def", "make_spindles", "(", "events", ",", "power_peaks", ",", "powers", ",", "dat_det", ",", "dat_orig", ",", "time", ",", "s_freq", ")", ":", "i", ",", "events", "=", "_remove_duplicate", "(", "events", ",", "dat_det", ")", "power_peaks", "=", "power_pe...
Create dict for each spindle, based on events of time points. Parameters ---------- events : ndarray (dtype='int') N x 3 matrix with start, peak, end samples, and peak frequency power_peaks : ndarray (dtype='float') peak in power spectrum for each event powers : ndarray (dtype='float') average power in power spectrum for each event dat_det : ndarray (dtype='float') vector with the data after detection-transformation (to compute peak) dat_orig : ndarray (dtype='float') vector with the raw data on which detection was performed time : ndarray (dtype='float') vector with time points s_freq : float sampling frequency Returns ------- list of dict list of all the spindles, with information about start_time, peak_time, end_time (s), peak_val (signal units), area_under_curve (signal units * s), peak_freq (Hz)
[ "Create", "dict", "for", "each", "spindle", "based", "on", "events", "of", "time", "points", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/detect/spindle.py#L1893-L1943
train
23,411
wonambi-python/wonambi
wonambi/detect/spindle.py
_remove_duplicate
def _remove_duplicate(old_events, dat): """Remove duplicates from the events. Parameters ---------- old_events : ndarray (dtype='int') N x 3 matrix with start, peak, end samples dat : ndarray (dtype='float') vector with the data after detection-transformation (to compute peak) Returns ------- ndarray (dtype='int') vector of indices of the events to keep ndarray (dtype='int') N x 3 matrix with start, peak, end samples Notes ----- old_events is assumed to be sorted. It only checks for the start time and end time. When two (or more) events have the same start time and the same end time, then it takes the largest peak. There is no tolerance, indices need to be identical. """ 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
python
def _remove_duplicate(old_events, dat): """Remove duplicates from the events. Parameters ---------- old_events : ndarray (dtype='int') N x 3 matrix with start, peak, end samples dat : ndarray (dtype='float') vector with the data after detection-transformation (to compute peak) Returns ------- ndarray (dtype='int') vector of indices of the events to keep ndarray (dtype='int') N x 3 matrix with start, peak, end samples Notes ----- old_events is assumed to be sorted. It only checks for the start time and end time. When two (or more) events have the same start time and the same end time, then it takes the largest peak. There is no tolerance, indices need to be identical. """ 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
[ "def", "_remove_duplicate", "(", "old_events", ",", "dat", ")", ":", "diff_events", "=", "diff", "(", "old_events", ",", "axis", "=", "0", ")", "dupl", "=", "where", "(", "(", "diff_events", "[", ":", ",", "0", "]", "==", "0", ")", "&", "(", "diff_...
Remove duplicates from the events. Parameters ---------- old_events : ndarray (dtype='int') N x 3 matrix with start, peak, end samples dat : ndarray (dtype='float') vector with the data after detection-transformation (to compute peak) Returns ------- ndarray (dtype='int') vector of indices of the events to keep ndarray (dtype='int') N x 3 matrix with start, peak, end samples Notes ----- old_events is assumed to be sorted. It only checks for the start time and end time. When two (or more) events have the same start time and the same end time, then it takes the largest peak. There is no tolerance, indices need to be identical.
[ "Remove", "duplicates", "from", "the", "events", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/detect/spindle.py#L1946-L1995
train
23,412
wonambi-python/wonambi
wonambi/detect/spindle.py
_detect_start_end
def _detect_start_end(true_values): """From ndarray of bool values, return intervals of True values. Parameters ---------- true_values : ndarray (dtype='bool') array with bool values Returns ------- ndarray (dtype='int') N x 2 matrix with starting and ending times. """ 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
python
def _detect_start_end(true_values): """From ndarray of bool values, return intervals of True values. Parameters ---------- true_values : ndarray (dtype='bool') array with bool values Returns ------- ndarray (dtype='int') N x 2 matrix with starting and ending times. """ 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
[ "def", "_detect_start_end", "(", "true_values", ")", ":", "neg", "=", "zeros", "(", "(", "1", ")", ",", "dtype", "=", "'bool'", ")", "int_values", "=", "asarray", "(", "concatenate", "(", "(", "neg", ",", "true_values", "[", ":", "-", "1", "]", ",", ...
From ndarray of bool values, return intervals of True values. Parameters ---------- true_values : ndarray (dtype='bool') array with bool values Returns ------- ndarray (dtype='int') N x 2 matrix with starting and ending times.
[ "From", "ndarray", "of", "bool", "values", "return", "intervals", "of", "True", "values", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/detect/spindle.py#L1998-L2026
train
23,413
wonambi-python/wonambi
wonambi/detect/spindle.py
_merge_close
def _merge_close(dat, events, time, min_interval): """Merge together events separated by less than a minimum interval. Parameters ---------- dat : ndarray (dtype='float') vector with the data after selection-transformation events : ndarray (dtype='int') N x 3 matrix with start, peak, end samples time : ndarray (dtype='float') vector with time points min_interval : float minimum delay between consecutive events, in seconds Returns ------- ndarray (dtype='int') N x 3 matrix with start, peak, end samples """ 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
python
def _merge_close(dat, events, time, min_interval): """Merge together events separated by less than a minimum interval. Parameters ---------- dat : ndarray (dtype='float') vector with the data after selection-transformation events : ndarray (dtype='int') N x 3 matrix with start, peak, end samples time : ndarray (dtype='float') vector with time points min_interval : float minimum delay between consecutive events, in seconds Returns ------- ndarray (dtype='int') N x 3 matrix with start, peak, end samples """ 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
[ "def", "_merge_close", "(", "dat", ",", "events", ",", "time", ",", "min_interval", ")", ":", "if", "not", "events", ".", "any", "(", ")", ":", "return", "events", "no_merge", "=", "time", "[", "events", "[", "1", ":", ",", "0", "]", "-", "1", "]...
Merge together events separated by less than a minimum interval. Parameters ---------- dat : ndarray (dtype='float') vector with the data after selection-transformation events : ndarray (dtype='int') N x 3 matrix with start, peak, end samples time : ndarray (dtype='float') vector with time points min_interval : float minimum delay between consecutive events, in seconds Returns ------- ndarray (dtype='int') N x 3 matrix with start, peak, end samples
[ "Merge", "together", "events", "separated", "by", "less", "than", "a", "minimum", "interval", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/detect/spindle.py#L2068-L2106
train
23,414
wonambi-python/wonambi
wonambi/detect/spindle.py
_wmorlet
def _wmorlet(f0, sd, sampling_rate, ns=5): """ adapted from nitime returns a complex morlet wavelet in the time domain Parameters ---------- f0 : center frequency sd : standard deviation of frequency sampling_rate : samplingrate ns : window length in number of standard deviations """ 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
python
def _wmorlet(f0, sd, sampling_rate, ns=5): """ adapted from nitime returns a complex morlet wavelet in the time domain Parameters ---------- f0 : center frequency sd : standard deviation of frequency sampling_rate : samplingrate ns : window length in number of standard deviations """ 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
[ "def", "_wmorlet", "(", "f0", ",", "sd", ",", "sampling_rate", ",", "ns", "=", "5", ")", ":", "st", "=", "1.", "/", "(", "2.", "*", "pi", "*", "sd", ")", "w_sz", "=", "float", "(", "int", "(", "ns", "*", "st", "*", "sampling_rate", ")", ")", ...
adapted from nitime returns a complex morlet wavelet in the time domain Parameters ---------- f0 : center frequency sd : standard deviation of frequency sampling_rate : samplingrate ns : window length in number of standard deviations
[ "adapted", "from", "nitime" ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/detect/spindle.py#L2109-L2127
train
23,415
wonambi-python/wonambi
wonambi/detect/spindle.py
_realwavelets
def _realwavelets(s_freq, freqs, dur, width): """Create real wavelets, for UCSD. Parameters ---------- s_freq : int sampling frequency freqs : ndarray vector with frequencies of interest dur : float duration of the wavelets in s width : float parameter controlling gaussian shape Returns ------- ndarray wavelets """ 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
python
def _realwavelets(s_freq, freqs, dur, width): """Create real wavelets, for UCSD. Parameters ---------- s_freq : int sampling frequency freqs : ndarray vector with frequencies of interest dur : float duration of the wavelets in s width : float parameter controlling gaussian shape Returns ------- ndarray wavelets """ 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
[ "def", "_realwavelets", "(", "s_freq", ",", "freqs", ",", "dur", ",", "width", ")", ":", "x", "=", "arange", "(", "-", "dur", "/", "2", ",", "dur", "/", "2", ",", "1", "/", "s_freq", ")", "wavelets", "=", "empty", "(", "(", "len", "(", "freqs",...
Create real wavelets, for UCSD. Parameters ---------- s_freq : int sampling frequency freqs : ndarray vector with frequencies of interest dur : float duration of the wavelets in s width : float parameter controlling gaussian shape Returns ------- ndarray wavelets
[ "Create", "real", "wavelets", "for", "UCSD", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/detect/spindle.py#L2130-L2158
train
23,416
wonambi-python/wonambi
wonambi/widgets/detect_dialogs.py
SpindleDialog.count_channels
def count_channels(self): """If more than one channel selected, activate merge checkbox.""" 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)
python
def count_channels(self): """If more than one channel selected, activate merge checkbox.""" 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)
[ "def", "count_channels", "(", "self", ")", ":", "merge", "=", "self", ".", "index", "[", "'merge'", "]", "if", "len", "(", "self", ".", "idx_chan", ".", "selectedItems", "(", ")", ")", ">", "1", ":", "if", "merge", ".", "isEnabled", "(", ")", ":", ...
If more than one channel selected, activate merge checkbox.
[ "If", "more", "than", "one", "channel", "selected", "activate", "merge", "checkbox", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/detect_dialogs.py#L465-L476
train
23,417
wonambi-python/wonambi
wonambi/trans/math.py
math
def math(data, operator=None, operator_name=None, axis=None): """Apply mathematical operation to each trial and channel individually. Parameters ---------- data : instance of DataTime, DataFreq, or DataTimeFreq operator : function or tuple of functions, optional function(s) to run on the data. operator_name : str or tuple of str, optional name of the function(s) to run on the data. axis : str, optional for functions that accept it, which axis you should run it on. Returns ------- instance of Data data where the trials underwent operator. Raises ------ TypeError If you pass both operator and operator_name. ValueError When you try to operate on an axis that has already been removed. Notes ----- operator and operator_name are mutually exclusive. operator_name is given as shortcut for most common operations. If a function accepts an 'axis' argument, you need to pass 'axis' to the constructor. In this way, it'll apply the function to the correct dimension. The possible point-wise operator_name are: 'absolute', 'angle', 'dB' (=10 * log10), 'exp', 'log', 'sqrt', 'square', 'unwrap' The operator_name's that need an axis, but do not remove it: 'hilbert', 'diff', 'detrend' The operator_name's that need an axis and remove it: 'mean', 'median', 'mode', 'std' Examples -------- You can pass a single value or a tuple. The order starts from left to right, so abs of the hilbert transform, should be: >>> rms = math(data, operator_name=('hilbert', 'abs'), axis='time') If you want to pass the power of three, use lambda (or partial): >>> p3 = lambda x: power(x, 3) >>> data_p3 = math(data, operator=p3) Note that lambdas are fine with point-wise operation, but if you want them to operate on axis, you need to pass ''axis'' as well, so that: >>> std_ddof = lambda x, axis: std(x, axis, ddof=1) >>> data_std = math(data, operator=std_ddof) If you don't pass 'axis' in lambda, it'll never know on which axis the function should be applied and you'll get unpredictable results. If you want to pass a function that operates on an axis and removes it (for example, if you want the max value over time), you need to add an argument in your function called ''keepdims'' (the values won't be used): >>> def func(x, axis, keepdims=None): >>> return nanmax(x, axis=axis) """ 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
python
def math(data, operator=None, operator_name=None, axis=None): """Apply mathematical operation to each trial and channel individually. Parameters ---------- data : instance of DataTime, DataFreq, or DataTimeFreq operator : function or tuple of functions, optional function(s) to run on the data. operator_name : str or tuple of str, optional name of the function(s) to run on the data. axis : str, optional for functions that accept it, which axis you should run it on. Returns ------- instance of Data data where the trials underwent operator. Raises ------ TypeError If you pass both operator and operator_name. ValueError When you try to operate on an axis that has already been removed. Notes ----- operator and operator_name are mutually exclusive. operator_name is given as shortcut for most common operations. If a function accepts an 'axis' argument, you need to pass 'axis' to the constructor. In this way, it'll apply the function to the correct dimension. The possible point-wise operator_name are: 'absolute', 'angle', 'dB' (=10 * log10), 'exp', 'log', 'sqrt', 'square', 'unwrap' The operator_name's that need an axis, but do not remove it: 'hilbert', 'diff', 'detrend' The operator_name's that need an axis and remove it: 'mean', 'median', 'mode', 'std' Examples -------- You can pass a single value or a tuple. The order starts from left to right, so abs of the hilbert transform, should be: >>> rms = math(data, operator_name=('hilbert', 'abs'), axis='time') If you want to pass the power of three, use lambda (or partial): >>> p3 = lambda x: power(x, 3) >>> data_p3 = math(data, operator=p3) Note that lambdas are fine with point-wise operation, but if you want them to operate on axis, you need to pass ''axis'' as well, so that: >>> std_ddof = lambda x, axis: std(x, axis, ddof=1) >>> data_std = math(data, operator=std_ddof) If you don't pass 'axis' in lambda, it'll never know on which axis the function should be applied and you'll get unpredictable results. If you want to pass a function that operates on an axis and removes it (for example, if you want the max value over time), you need to add an argument in your function called ''keepdims'' (the values won't be used): >>> def func(x, axis, keepdims=None): >>> return nanmax(x, axis=axis) """ 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
[ "def", "math", "(", "data", ",", "operator", "=", "None", ",", "operator_name", "=", "None", ",", "axis", "=", "None", ")", ":", "if", "operator", "is", "not", "None", "and", "operator_name", "is", "not", "None", ":", "raise", "TypeError", "(", "'Param...
Apply mathematical operation to each trial and channel individually. Parameters ---------- data : instance of DataTime, DataFreq, or DataTimeFreq operator : function or tuple of functions, optional function(s) to run on the data. operator_name : str or tuple of str, optional name of the function(s) to run on the data. axis : str, optional for functions that accept it, which axis you should run it on. Returns ------- instance of Data data where the trials underwent operator. Raises ------ TypeError If you pass both operator and operator_name. ValueError When you try to operate on an axis that has already been removed. Notes ----- operator and operator_name are mutually exclusive. operator_name is given as shortcut for most common operations. If a function accepts an 'axis' argument, you need to pass 'axis' to the constructor. In this way, it'll apply the function to the correct dimension. The possible point-wise operator_name are: 'absolute', 'angle', 'dB' (=10 * log10), 'exp', 'log', 'sqrt', 'square', 'unwrap' The operator_name's that need an axis, but do not remove it: 'hilbert', 'diff', 'detrend' The operator_name's that need an axis and remove it: 'mean', 'median', 'mode', 'std' Examples -------- You can pass a single value or a tuple. The order starts from left to right, so abs of the hilbert transform, should be: >>> rms = math(data, operator_name=('hilbert', 'abs'), axis='time') If you want to pass the power of three, use lambda (or partial): >>> p3 = lambda x: power(x, 3) >>> data_p3 = math(data, operator=p3) Note that lambdas are fine with point-wise operation, but if you want them to operate on axis, you need to pass ''axis'' as well, so that: >>> std_ddof = lambda x, axis: std(x, axis, ddof=1) >>> data_std = math(data, operator=std_ddof) If you don't pass 'axis' in lambda, it'll never know on which axis the function should be applied and you'll get unpredictable results. If you want to pass a function that operates on an axis and removes it (for example, if you want the max value over time), you need to add an argument in your function called ''keepdims'' (the values won't be used): >>> def func(x, axis, keepdims=None): >>> return nanmax(x, axis=axis)
[ "Apply", "mathematical", "operation", "to", "each", "trial", "and", "channel", "individually", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/trans/math.py#L46-L209
train
23,418
wonambi-python/wonambi
wonambi/trans/math.py
get_descriptives
def get_descriptives(data): """Get mean, SD, and mean and SD of log values. Parameters ---------- data : ndarray Data with segment as first dimension and all other dimensions raveled into second dimension. Returns ------- dict of ndarray each entry is a 1-D vector of descriptives over segment dimension """ 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
python
def get_descriptives(data): """Get mean, SD, and mean and SD of log values. Parameters ---------- data : ndarray Data with segment as first dimension and all other dimensions raveled into second dimension. Returns ------- dict of ndarray each entry is a 1-D vector of descriptives over segment dimension """ 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
[ "def", "get_descriptives", "(", "data", ")", ":", "output", "=", "{", "}", "dat_log", "=", "log", "(", "abs", "(", "data", ")", ")", "output", "[", "'mean'", "]", "=", "nanmean", "(", "data", ",", "axis", "=", "0", ")", "output", "[", "'sd'", "]"...
Get mean, SD, and mean and SD of log values. Parameters ---------- data : ndarray Data with segment as first dimension and all other dimensions raveled into second dimension. Returns ------- dict of ndarray each entry is a 1-D vector of descriptives over segment dimension
[ "Get", "mean", "SD", "and", "mean", "and", "SD", "of", "log", "values", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/trans/math.py#L211-L232
train
23,419
wonambi-python/wonambi
wonambi/ioeeg/abf.py
_read_info_as_dict
def _read_info_as_dict(fid, values): """Convenience function to read info in axon data to a nicely organized dict. """ 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
python
def _read_info_as_dict(fid, values): """Convenience function to read info in axon data to a nicely organized dict. """ 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
[ "def", "_read_info_as_dict", "(", "fid", ",", "values", ")", ":", "output", "=", "{", "}", "for", "key", ",", "fmt", "in", "values", ":", "val", "=", "unpack", "(", "fmt", ",", "fid", ".", "read", "(", "calcsize", "(", "fmt", ")", ")", ")", "if",...
Convenience function to read info in axon data to a nicely organized dict.
[ "Convenience", "function", "to", "read", "info", "in", "axon", "data", "to", "a", "nicely", "organized", "dict", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/ioeeg/abf.py#L251-L262
train
23,420
wonambi-python/wonambi
wonambi/widgets/settings.py
read_settings
def read_settings(widget, value_name): """Read Settings information, either from INI or from default values. Parameters ---------- widget : str name of the widget value_name : str name of the value of interest. Returns ------- multiple types type depends on the type in the default values. """ 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
python
def read_settings(widget, value_name): """Read Settings information, either from INI or from default values. Parameters ---------- widget : str name of the widget value_name : str name of the value of interest. Returns ------- multiple types type depends on the type in the default values. """ 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
[ "def", "read_settings", "(", "widget", ",", "value_name", ")", ":", "setting_name", "=", "widget", "+", "'/'", "+", "value_name", "default_value", "=", "DEFAULTS", "[", "widget", "]", "[", "value_name", "]", "default_type", "=", "type", "(", "default_value", ...
Read Settings information, either from INI or from default values. Parameters ---------- widget : str name of the widget value_name : str name of the value of interest. Returns ------- multiple types type depends on the type in the default values.
[ "Read", "Settings", "information", "either", "from", "INI", "or", "from", "default", "values", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/settings.py#L314-L338
train
23,421
wonambi-python/wonambi
wonambi/widgets/settings.py
Settings.create_settings
def create_settings(self): """Create the widget, organized in two parts. Notes ----- When you add widgets in config, remember to update show_settings too """ 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)
python
def create_settings(self): """Create the widget, organized in two parts. Notes ----- When you add widgets in config, remember to update show_settings too """ 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)
[ "def", "create_settings", "(", "self", ")", ":", "bbox", "=", "QDialogButtonBox", "(", "QDialogButtonBox", ".", "Ok", "|", "QDialogButtonBox", ".", "Apply", "|", "QDialogButtonBox", ".", "Cancel", ")", "self", ".", "idx_ok", "=", "bbox", ".", "button", "(", ...
Create the widget, organized in two parts. Notes ----- When you add widgets in config, remember to update show_settings too
[ "Create", "the", "widget", "organized", "in", "two", "parts", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/settings.py#L90-L134
train
23,422
wonambi-python/wonambi
wonambi/widgets/settings.py
Config.create_values
def create_values(self, value_names): """Read original values from the settings or the defaults. Parameters ---------- value_names : list of str list of value names to read Returns ------- dict dictionary with the value names as keys """ output = {} for value_name in value_names: output[value_name] = read_settings(self.widget, value_name) return output
python
def create_values(self, value_names): """Read original values from the settings or the defaults. Parameters ---------- value_names : list of str list of value names to read Returns ------- dict dictionary with the value names as keys """ output = {} for value_name in value_names: output[value_name] = read_settings(self.widget, value_name) return output
[ "def", "create_values", "(", "self", ",", "value_names", ")", ":", "output", "=", "{", "}", "for", "value_name", "in", "value_names", ":", "output", "[", "value_name", "]", "=", "read_settings", "(", "self", ".", "widget", ",", "value_name", ")", "return",...
Read original values from the settings or the defaults. Parameters ---------- value_names : list of str list of value names to read Returns ------- dict dictionary with the value names as keys
[ "Read", "original", "values", "from", "the", "settings", "or", "the", "defaults", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/settings.py#L213-L230
train
23,423
wonambi-python/wonambi
wonambi/widgets/settings.py
Config.get_values
def get_values(self): """Get values from the GUI and save them in preference file.""" 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])
python
def get_values(self): """Get values from the GUI and save them in preference file.""" 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])
[ "def", "get_values", "(", "self", ")", ":", "for", "value_name", ",", "widget", "in", "self", ".", "index", ".", "items", "(", ")", ":", "self", ".", "value", "[", "value_name", "]", "=", "widget", ".", "get_value", "(", "self", ".", "value", "[", ...
Get values from the GUI and save them in preference file.
[ "Get", "values", "from", "the", "GUI", "and", "save", "them", "in", "preference", "file", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/settings.py#L238-L244
train
23,424
wonambi-python/wonambi
wonambi/widgets/settings.py
Config.put_values
def put_values(self): """Put values to the GUI. Notes ----- In addition, when one small widget has been changed, it calls set_modified, so that we know that the preference widget was modified. """ for value_name, widget in self.index.items(): widget.set_value(self.value[value_name]) widget.connect(self.set_modified)
python
def put_values(self): """Put values to the GUI. Notes ----- In addition, when one small widget has been changed, it calls set_modified, so that we know that the preference widget was modified. """ for value_name, widget in self.index.items(): widget.set_value(self.value[value_name]) widget.connect(self.set_modified)
[ "def", "put_values", "(", "self", ")", ":", "for", "value_name", ",", "widget", "in", "self", ".", "index", ".", "items", "(", ")", ":", "widget", ".", "set_value", "(", "self", ".", "value", "[", "value_name", "]", ")", "widget", ".", "connect", "("...
Put values to the GUI. Notes ----- In addition, when one small widget has been changed, it calls set_modified, so that we know that the preference widget was modified.
[ "Put", "values", "to", "the", "GUI", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/settings.py#L246-L257
train
23,425
wonambi-python/wonambi
wonambi/datatype.py
_get_indices
def _get_indices(values, selected, tolerance): """Get indices based on user-selected values. Parameters ---------- values : ndarray (any dtype) values present in the axis. selected : ndarray (any dtype) or tuple or list values selected by the user tolerance : float avoid rounding errors. Returns ------- idx_data : list of int indices of row/column to select the data idx_output : list of int indices of row/column to copy into output Notes ----- This function is probably not very fast, but it's pretty robust. It keeps the order, which is extremely important. If you use values in the self.axis, you don't need to specify tolerance. However, if you specify arbitrary points, floating point errors might affect the actual values. Of course, using tolerance is much slower. Maybe tolerance should be part of Select instead of here. """ 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
python
def _get_indices(values, selected, tolerance): """Get indices based on user-selected values. Parameters ---------- values : ndarray (any dtype) values present in the axis. selected : ndarray (any dtype) or tuple or list values selected by the user tolerance : float avoid rounding errors. Returns ------- idx_data : list of int indices of row/column to select the data idx_output : list of int indices of row/column to copy into output Notes ----- This function is probably not very fast, but it's pretty robust. It keeps the order, which is extremely important. If you use values in the self.axis, you don't need to specify tolerance. However, if you specify arbitrary points, floating point errors might affect the actual values. Of course, using tolerance is much slower. Maybe tolerance should be part of Select instead of here. """ 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
[ "def", "_get_indices", "(", "values", ",", "selected", ",", "tolerance", ")", ":", "idx_data", "=", "[", "]", "idx_output", "=", "[", "]", "for", "idx_of_selected", ",", "one_selected", "in", "enumerate", "(", "selected", ")", ":", "if", "tolerance", "is",...
Get indices based on user-selected values. Parameters ---------- values : ndarray (any dtype) values present in the axis. selected : ndarray (any dtype) or tuple or list values selected by the user tolerance : float avoid rounding errors. Returns ------- idx_data : list of int indices of row/column to select the data idx_output : list of int indices of row/column to copy into output Notes ----- This function is probably not very fast, but it's pretty robust. It keeps the order, which is extremely important. If you use values in the self.axis, you don't need to specify tolerance. However, if you specify arbitrary points, floating point errors might affect the actual values. Of course, using tolerance is much slower. Maybe tolerance should be part of Select instead of here.
[ "Get", "indices", "based", "on", "user", "-", "selected", "values", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/datatype.py#L468-L512
train
23,426
wonambi-python/wonambi
wonambi/datatype.py
Data.number_of
def number_of(self, axis): """Return the number of in one axis, as generally as possible. Parameters ---------- axis : str Name of the axis (such as 'trial', 'time', etc) Returns ------- int or ndarray (dtype='int') number of trial (as int) or number of element in the selected axis (if any of the other axiss) as 1d array. Raises ------ KeyError If the requested axis is not in the data. Notes ----- or is it better to catch the exception? """ 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
python
def number_of(self, axis): """Return the number of in one axis, as generally as possible. Parameters ---------- axis : str Name of the axis (such as 'trial', 'time', etc) Returns ------- int or ndarray (dtype='int') number of trial (as int) or number of element in the selected axis (if any of the other axiss) as 1d array. Raises ------ KeyError If the requested axis is not in the data. Notes ----- or is it better to catch the exception? """ 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
[ "def", "number_of", "(", "self", ",", "axis", ")", ":", "if", "axis", "==", "'trial'", ":", "return", "len", "(", "self", ".", "data", ")", "else", ":", "n_trial", "=", "self", ".", "number_of", "(", "'trial'", ")", "output", "=", "empty", "(", "n_...
Return the number of in one axis, as generally as possible. Parameters ---------- axis : str Name of the axis (such as 'trial', 'time', etc) Returns ------- int or ndarray (dtype='int') number of trial (as int) or number of element in the selected axis (if any of the other axiss) as 1d array. Raises ------ KeyError If the requested axis is not in the data. Notes ----- or is it better to catch the exception?
[ "Return", "the", "number", "of", "in", "one", "axis", "as", "generally", "as", "possible", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/datatype.py#L216-L248
train
23,427
wonambi-python/wonambi
wonambi/datatype.py
Data._copy
def _copy(self, axis=True, attr=True, data=False): """Create a new instance of Data, but does not copy the data necessarily. Parameters ---------- axis : bool, optional deep copy the axes (default: True) attr : bool, optional deep copy the attributes (default: True) data : bool, optional deep copy the data (default: False) Returns ------- instance of Data (or ChanTime, ChanFreq, ChanTimeFreq) copy of the data, but without the actual data Notes ----- It's important that we copy all the relevant information here. If you add new attributes, you should add them here. Remember that it deep-copies all the information, so if you copy data the size might become really large. """ 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
python
def _copy(self, axis=True, attr=True, data=False): """Create a new instance of Data, but does not copy the data necessarily. Parameters ---------- axis : bool, optional deep copy the axes (default: True) attr : bool, optional deep copy the attributes (default: True) data : bool, optional deep copy the data (default: False) Returns ------- instance of Data (or ChanTime, ChanFreq, ChanTimeFreq) copy of the data, but without the actual data Notes ----- It's important that we copy all the relevant information here. If you add new attributes, you should add them here. Remember that it deep-copies all the information, so if you copy data the size might become really large. """ 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
[ "def", "_copy", "(", "self", ",", "axis", "=", "True", ",", "attr", "=", "True", ",", "data", "=", "False", ")", ":", "cdata", "=", "type", "(", "self", ")", "(", ")", "# create instance of the same class", "cdata", ".", "s_freq", "=", "self", ".", "...
Create a new instance of Data, but does not copy the data necessarily. Parameters ---------- axis : bool, optional deep copy the axes (default: True) attr : bool, optional deep copy the attributes (default: True) data : bool, optional deep copy the data (default: False) Returns ------- instance of Data (or ChanTime, ChanFreq, ChanTimeFreq) copy of the data, but without the actual data Notes ----- It's important that we copy all the relevant information here. If you add new attributes, you should add them here. Remember that it deep-copies all the information, so if you copy data the size might become really large.
[ "Create", "a", "new", "instance", "of", "Data", "but", "does", "not", "copy", "the", "data", "necessarily", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/datatype.py#L302-L351
train
23,428
wonambi-python/wonambi
wonambi/datatype.py
Data.export
def export(self, filename, export_format='FieldTrip', **options): """Export data in other formats. Parameters ---------- filename : path to file file to write export_format : str, optional supported export format is currently FieldTrip, EDF, FIFF, Wonambi, BrainVision Notes ----- 'edf' takes an optional argument "physical_max", see write_edf. 'wonambi' takes an optional argument "subj_id", see write_wonambi. wonambi format creates two files, one .won with the dataset info as json file and one .dat with the memmap recordings. 'brainvision' takes an additional argument ("markers") which is a list of dictionaries with fields: "name" : str (name of the marker), "start" : float (start time in seconds) "end" : float (end time in seconds) 'bids' has an optional argument "markers", like in 'brainvision' """ 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)
python
def export(self, filename, export_format='FieldTrip', **options): """Export data in other formats. Parameters ---------- filename : path to file file to write export_format : str, optional supported export format is currently FieldTrip, EDF, FIFF, Wonambi, BrainVision Notes ----- 'edf' takes an optional argument "physical_max", see write_edf. 'wonambi' takes an optional argument "subj_id", see write_wonambi. wonambi format creates two files, one .won with the dataset info as json file and one .dat with the memmap recordings. 'brainvision' takes an additional argument ("markers") which is a list of dictionaries with fields: "name" : str (name of the marker), "start" : float (start time in seconds) "end" : float (end time in seconds) 'bids' has an optional argument "markers", like in 'brainvision' """ 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)
[ "def", "export", "(", "self", ",", "filename", ",", "export_format", "=", "'FieldTrip'", ",", "*", "*", "options", ")", ":", "filename", "=", "Path", "(", "filename", ")", "filename", ".", "parent", ".", "mkdir", "(", "parents", "=", "True", ",", "exis...
Export data in other formats. Parameters ---------- filename : path to file file to write export_format : str, optional supported export format is currently FieldTrip, EDF, FIFF, Wonambi, BrainVision Notes ----- 'edf' takes an optional argument "physical_max", see write_edf. 'wonambi' takes an optional argument "subj_id", see write_wonambi. wonambi format creates two files, one .won with the dataset info as json file and one .dat with the memmap recordings. 'brainvision' takes an additional argument ("markers") which is a list of dictionaries with fields: "name" : str (name of the marker), "start" : float (start time in seconds) "end" : float (end time in seconds) 'bids' has an optional argument "markers", like in 'brainvision'
[ "Export", "data", "in", "other", "formats", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/datatype.py#L353-L410
train
23,429
wonambi-python/wonambi
wonambi/widgets/channels.py
ChannelsGroup.highlight_channels
def highlight_channels(self, l, selected_chan): """Highlight channels in the list of channels. Parameters ---------- selected_chan : list of str channels to indicate as selected. """ for row in range(l.count()): item = l.item(row) if item.text() in selected_chan: item.setSelected(True) else: item.setSelected(False)
python
def highlight_channels(self, l, selected_chan): """Highlight channels in the list of channels. Parameters ---------- selected_chan : list of str channels to indicate as selected. """ for row in range(l.count()): item = l.item(row) if item.text() in selected_chan: item.setSelected(True) else: item.setSelected(False)
[ "def", "highlight_channels", "(", "self", ",", "l", ",", "selected_chan", ")", ":", "for", "row", "in", "range", "(", "l", ".", "count", "(", ")", ")", ":", "item", "=", "l", ".", "item", "(", "row", ")", "if", "item", ".", "text", "(", ")", "i...
Highlight channels in the list of channels. Parameters ---------- selected_chan : list of str channels to indicate as selected.
[ "Highlight", "channels", "in", "the", "list", "of", "channels", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/channels.py#L196-L209
train
23,430
wonambi-python/wonambi
wonambi/widgets/channels.py
ChannelsGroup.rereference
def rereference(self): """Automatically highlight channels to use as reference, based on selected channels.""" 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)
python
def rereference(self): """Automatically highlight channels to use as reference, based on selected channels.""" 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)
[ "def", "rereference", "(", "self", ")", ":", "selectedItems", "=", "self", ".", "idx_l0", ".", "selectedItems", "(", ")", "chan_to_plot", "=", "[", "]", "for", "selected", "in", "selectedItems", ":", "chan_to_plot", ".", "append", "(", "selected", ".", "te...
Automatically highlight channels to use as reference, based on selected channels.
[ "Automatically", "highlight", "channels", "to", "use", "as", "reference", "based", "on", "selected", "channels", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/channels.py#L211-L219
train
23,431
wonambi-python/wonambi
wonambi/widgets/channels.py
ChannelsGroup.get_info
def get_info(self): """Get the information about the channel groups. Returns ------- dict information about this channel group Notes ----- The items in selectedItems() are ordered based on the user's selection (which appears pretty random). It's more consistent to use the same order of the main channel list. That's why the additional for-loop is necessary. We don't care about the order of the reference channels. """ 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
python
def get_info(self): """Get the information about the channel groups. Returns ------- dict information about this channel group Notes ----- The items in selectedItems() are ordered based on the user's selection (which appears pretty random). It's more consistent to use the same order of the main channel list. That's why the additional for-loop is necessary. We don't care about the order of the reference channels. """ 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
[ "def", "get_info", "(", "self", ")", ":", "selectedItems", "=", "self", ".", "idx_l0", ".", "selectedItems", "(", ")", "selected_chan", "=", "[", "x", ".", "text", "(", ")", "for", "x", "in", "selectedItems", "]", "chan_to_plot", "=", "[", "]", "for", ...
Get the information about the channel groups. Returns ------- dict information about this channel group Notes ----- The items in selectedItems() are ordered based on the user's selection (which appears pretty random). It's more consistent to use the same order of the main channel list. That's why the additional for-loop is necessary. We don't care about the order of the reference channels.
[ "Get", "the", "information", "about", "the", "channel", "groups", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/channels.py#L221-L271
train
23,432
wonambi-python/wonambi
wonambi/widgets/channels.py
Channels.create
def create(self): """Create Channels Widget""" 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)
python
def create(self): """Create Channels Widget""" 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)
[ "def", "create", "(", "self", ")", ":", "add_button", "=", "QPushButton", "(", "'New'", ")", "add_button", ".", "clicked", ".", "connect", "(", "self", ".", "new_group", ")", "color_button", "=", "QPushButton", "(", "'Color'", ")", "color_button", ".", "cl...
Create Channels Widget
[ "Create", "Channels", "Widget" ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/channels.py#L305-L338
train
23,433
wonambi-python/wonambi
wonambi/widgets/channels.py
Channels.create_action
def create_action(self): """Create actions related to channel selection.""" 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
python
def create_action(self): """Create actions related to channel selection.""" 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
[ "def", "create_action", "(", "self", ")", ":", "actions", "=", "{", "}", "act", "=", "QAction", "(", "'Load Montage...'", ",", "self", ")", "act", ".", "triggered", ".", "connect", "(", "self", ".", "load_channels", ")", "act", ".", "setEnabled", "(", ...
Create actions related to channel selection.
[ "Create", "actions", "related", "to", "channel", "selection", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/channels.py#L340-L354
train
23,434
wonambi-python/wonambi
wonambi/widgets/channels.py
Channels.new_group
def new_group(self, checked=False, test_name=None): """Create a new channel group. Parameters ---------- checked : bool comes from QAbstractButton.clicked test_name : str used for testing purposes to avoid modal window Notes ----- Don't call self.apply() just yet, only if the user wants it. """ 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)
python
def new_group(self, checked=False, test_name=None): """Create a new channel group. Parameters ---------- checked : bool comes from QAbstractButton.clicked test_name : str used for testing purposes to avoid modal window Notes ----- Don't call self.apply() just yet, only if the user wants it. """ 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)
[ "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'", "se...
Create a new channel group. Parameters ---------- checked : bool comes from QAbstractButton.clicked test_name : str used for testing purposes to avoid modal window Notes ----- Don't call self.apply() just yet, only if the user wants it.
[ "Create", "a", "new", "channel", "group", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/channels.py#L361-L398
train
23,435
wonambi-python/wonambi
wonambi/widgets/channels.py
Channels.color_group
def color_group(self, checked=False, test_color=None): """Change the color of the group.""" 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()
python
def color_group(self, checked=False, test_color=None): """Change the color of the group.""" 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()
[ "def", "color_group", "(", "self", ",", "checked", "=", "False", ",", "test_color", "=", "None", ")", ":", "group", "=", "self", ".", "tabs", ".", "currentWidget", "(", ")", "if", "test_color", "is", "None", ":", "newcolor", "=", "QColorDialog", ".", "...
Change the color of the group.
[ "Change", "the", "color", "of", "the", "group", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/channels.py#L400-L409
train
23,436
wonambi-python/wonambi
wonambi/widgets/channels.py
Channels.del_group
def del_group(self): """Delete current group.""" idx = self.tabs.currentIndex() self.tabs.removeTab(idx) self.apply()
python
def del_group(self): """Delete current group.""" idx = self.tabs.currentIndex() self.tabs.removeTab(idx) self.apply()
[ "def", "del_group", "(", "self", ")", ":", "idx", "=", "self", ".", "tabs", ".", "currentIndex", "(", ")", "self", ".", "tabs", ".", "removeTab", "(", "idx", ")", "self", ".", "apply", "(", ")" ]
Delete current group.
[ "Delete", "current", "group", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/channels.py#L411-L416
train
23,437
wonambi-python/wonambi
wonambi/widgets/channels.py
Channels.apply
def apply(self): """Apply changes to the plots.""" 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()
python
def apply(self): """Apply changes to the plots.""" 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()
[ "def", "apply", "(", "self", ")", ":", "self", ".", "read_group_info", "(", ")", "if", "self", ".", "tabs", ".", "count", "(", ")", "==", "0", ":", "# disactivate buttons", "self", ".", "button_color", ".", "setEnabled", "(", "False", ")", "self", ".",...
Apply changes to the plots.
[ "Apply", "changes", "to", "the", "plots", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/channels.py#L418-L440
train
23,438
wonambi-python/wonambi
wonambi/widgets/channels.py
Channels.read_group_info
def read_group_info(self): """Get information about groups directly from the widget.""" 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)
python
def read_group_info(self): """Get information about groups directly from the widget.""" 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)
[ "def", "read_group_info", "(", "self", ")", ":", "self", ".", "groups", "=", "[", "]", "for", "i", "in", "range", "(", "self", ".", "tabs", ".", "count", "(", ")", ")", ":", "one_group", "=", "self", ".", "tabs", ".", "widget", "(", "i", ")", "...
Get information about groups directly from the widget.
[ "Get", "information", "about", "groups", "directly", "from", "the", "widget", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/channels.py#L442-L448
train
23,439
wonambi-python/wonambi
wonambi/widgets/channels.py
Channels.load_channels
def load_channels(self, checked=False, test_name=None): """Load channel groups from file. Parameters ---------- test_name : path to file when debugging the function, you can open a channels file from the command line """ 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()
python
def load_channels(self, checked=False, test_name=None): """Load channel groups from file. Parameters ---------- test_name : path to file when debugging the function, you can open a channels file from the command line """ 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()
[ "def", "load_channels", "(", "self", ",", "checked", "=", "False", ",", "test_name", "=", "None", ")", ":", "chan_name", "=", "self", ".", "parent", ".", "labels", ".", "chan_name", "if", "self", ".", "filename", "is", "not", "None", ":", "filename", "...
Load channel groups from file. Parameters ---------- test_name : path to file when debugging the function, you can open a channels file from the command line
[ "Load", "channel", "groups", "from", "file", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/channels.py#L450-L502
train
23,440
wonambi-python/wonambi
wonambi/widgets/channels.py
Channels.save_channels
def save_channels(self, checked=False, test_name=None): """Save channel groups to file.""" 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=' ')
python
def save_channels(self, checked=False, test_name=None): """Save channel groups to file.""" 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=' ')
[ "def", "save_channels", "(", "self", ",", "checked", "=", "False", ",", "test_name", "=", "None", ")", ":", "self", ".", "read_group_info", "(", ")", "if", "self", ".", "filename", "is", "not", "None", ":", "filename", "=", "self", ".", "filename", "el...
Save channel groups to file.
[ "Save", "channel", "groups", "to", "file", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/channels.py#L504-L534
train
23,441
wonambi-python/wonambi
wonambi/widgets/channels.py
Channels.reset
def reset(self): """Reset all the information of this widget.""" 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)
python
def reset(self): """Reset all the information of this widget.""" 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)
[ "def", "reset", "(", "self", ")", ":", "self", ".", "filename", "=", "None", "self", ".", "groups", "=", "[", "]", "self", ".", "tabs", ".", "clear", "(", ")", "self", ".", "setEnabled", "(", "False", ")", "self", ".", "button_color", ".", "setEnab...
Reset all the information of this widget.
[ "Reset", "all", "the", "information", "of", "this", "widget", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/channels.py#L536-L548
train
23,442
wonambi-python/wonambi
wonambi/widgets/spectrum.py
Spectrum.create
def create(self): """Create empty scene for power spectrum.""" 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)
python
def create(self): """Create empty scene for power spectrum.""" 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)
[ "def", "create", "(", "self", ")", ":", "self", ".", "idx_chan", "=", "QComboBox", "(", ")", "self", ".", "idx_chan", ".", "activated", ".", "connect", "(", "self", ".", "display_window", ")", "self", ".", "idx_fig", "=", "QGraphicsView", "(", "self", ...
Create empty scene for power spectrum.
[ "Create", "empty", "scene", "for", "power", "spectrum", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/spectrum.py#L104-L117
train
23,443
wonambi-python/wonambi
wonambi/widgets/spectrum.py
Spectrum.update
def update(self): """Add channel names to the combobox.""" 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
python
def update(self): """Add channel names to the combobox.""" 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
[ "def", "update", "(", "self", ")", ":", "self", ".", "idx_chan", ".", "clear", "(", ")", "for", "chan_name", "in", "self", ".", "parent", ".", "traces", ".", "chan", ":", "self", ".", "idx_chan", ".", "addItem", "(", "chan_name", ")", "if", "self", ...
Add channel names to the combobox.
[ "Add", "channel", "names", "to", "the", "combobox", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/spectrum.py#L126-L134
train
23,444
wonambi-python/wonambi
wonambi/widgets/spectrum.py
Spectrum.display_window
def display_window(self): """Read the channel name from QComboBox and plot its spectrum. This function is necessary it reads the data and it sends it to self.display. When the user selects a smaller chunk of data from the visible traces, then we don't need to call this function. """ 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()
python
def display_window(self): """Read the channel name from QComboBox and plot its spectrum. This function is necessary it reads the data and it sends it to self.display. When the user selects a smaller chunk of data from the visible traces, then we don't need to call this function. """ 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()
[ "def", "display_window", "(", "self", ")", ":", "if", "self", ".", "idx_chan", ".", "count", "(", ")", "==", "0", ":", "self", ".", "update", "(", ")", "chan_name", "=", "self", ".", "idx_chan", ".", "currentText", "(", ")", "lg", ".", "debug", "("...
Read the channel name from QComboBox and plot its spectrum. This function is necessary it reads the data and it sends it to self.display. When the user selects a smaller chunk of data from the visible traces, then we don't need to call this function.
[ "Read", "the", "channel", "name", "from", "QComboBox", "and", "plot", "its", "spectrum", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/spectrum.py#L136-L154
train
23,445
wonambi-python/wonambi
wonambi/widgets/spectrum.py
Spectrum.display
def display(self, data): """Make graphicsitem for spectrum figure. Parameters ---------- data : ndarray 1D vector containing the data only This function can be called by self.display_window (which reads the data for the selected channel) or by the mouse-events functions in traces (which read chunks of data from the user-made selection). """ 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))
python
def display(self, data): """Make graphicsitem for spectrum figure. Parameters ---------- data : ndarray 1D vector containing the data only This function can be called by self.display_window (which reads the data for the selected channel) or by the mouse-events functions in traces (which read chunks of data from the user-made selection). """ 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))
[ "def", "display", "(", "self", ",", "data", ")", ":", "value", "=", "self", ".", "config", ".", "value", "self", ".", "scene", "=", "QGraphicsScene", "(", "value", "[", "'x_min'", "]", ",", "value", "[", "'y_min'", "]", ",", "value", "[", "'x_max'", ...
Make graphicsitem for spectrum figure. Parameters ---------- data : ndarray 1D vector containing the data only This function can be called by self.display_window (which reads the data for the selected channel) or by the mouse-events functions in traces (which read chunks of data from the user-made selection).
[ "Make", "graphicsitem", "for", "spectrum", "figure", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/spectrum.py#L156-L189
train
23,446
wonambi-python/wonambi
wonambi/widgets/spectrum.py
Spectrum.add_grid
def add_grid(self): """Add axis and ticks to figure. Notes ----- I know that visvis and pyqtgraphs can do this in much simpler way, but those packages create too large a padding around the figure and this is pretty fast. """ 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))
python
def add_grid(self): """Add axis and ticks to figure. Notes ----- I know that visvis and pyqtgraphs can do this in much simpler way, but those packages create too large a padding around the figure and this is pretty fast. """ 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))
[ "def", "add_grid", "(", "self", ")", ":", "value", "=", "self", ".", "config", ".", "value", "# X-AXIS", "# x-bottom", "self", ".", "scene", ".", "addLine", "(", "value", "[", "'x_min'", "]", ",", "value", "[", "'y_min'", "]", ",", "value", "[", "'x_...
Add axis and ticks to figure. Notes ----- I know that visvis and pyqtgraphs can do this in much simpler way, but those packages create too large a padding around the figure and this is pretty fast.
[ "Add", "axis", "and", "ticks", "to", "figure", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/spectrum.py#L191-L238
train
23,447
wonambi-python/wonambi
wonambi/widgets/spectrum.py
Spectrum.resizeEvent
def resizeEvent(self, event): """Fit the whole scene in view. Parameters ---------- event : instance of Qt.Event not important """ 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'])
python
def resizeEvent(self, event): """Fit the whole scene in view. Parameters ---------- event : instance of Qt.Event not important """ 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'])
[ "def", "resizeEvent", "(", "self", ",", "event", ")", ":", "value", "=", "self", ".", "config", ".", "value", "self", ".", "idx_fig", ".", "fitInView", "(", "value", "[", "'x_min'", "]", ",", "value", "[", "'y_min'", "]", ",", "value", "[", "'x_max'"...
Fit the whole scene in view. Parameters ---------- event : instance of Qt.Event not important
[ "Fit", "the", "whole", "scene", "in", "view", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/spectrum.py#L240-L253
train
23,448
wonambi-python/wonambi
wonambi/widgets/spectrum.py
Spectrum.reset
def reset(self): """Reset widget as new""" self.idx_chan.clear() if self.scene is not None: self.scene.clear() self.scene = None
python
def reset(self): """Reset widget as new""" self.idx_chan.clear() if self.scene is not None: self.scene.clear() self.scene = None
[ "def", "reset", "(", "self", ")", ":", "self", ".", "idx_chan", ".", "clear", "(", ")", "if", "self", ".", "scene", "is", "not", "None", ":", "self", ".", "scene", ".", "clear", "(", ")", "self", ".", "scene", "=", "None" ]
Reset widget as new
[ "Reset", "widget", "as", "new" ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/spectrum.py#L255-L260
train
23,449
wonambi-python/wonambi
wonambi/detect/slowwave.py
detect_Massimini2004
def detect_Massimini2004(dat_orig, s_freq, time, opts): """Slow wave detection based on Massimini et al., 2004. Parameters ---------- dat_orig : ndarray (dtype='float') vector with the data for one channel s_freq : float sampling frequency time : ndarray (dtype='float') vector with the time points for each sample opts : instance of 'DetectSlowWave' 'det_filt' : dict parameters for 'butter', 'duration' : tuple of float min and max duration of SW 'min_ptp' : float min peak-to-peak amplitude 'trough_duration' : tuple of float min and max duration of first half-wave (trough) Returns ------- list of dict list of detected SWs float SW density, per 30-s epoch References ---------- Massimini, M. et al. J Neurosci 24(31) 6862-70 (2004). """ 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
python
def detect_Massimini2004(dat_orig, s_freq, time, opts): """Slow wave detection based on Massimini et al., 2004. Parameters ---------- dat_orig : ndarray (dtype='float') vector with the data for one channel s_freq : float sampling frequency time : ndarray (dtype='float') vector with the time points for each sample opts : instance of 'DetectSlowWave' 'det_filt' : dict parameters for 'butter', 'duration' : tuple of float min and max duration of SW 'min_ptp' : float min peak-to-peak amplitude 'trough_duration' : tuple of float min and max duration of first half-wave (trough) Returns ------- list of dict list of detected SWs float SW density, per 30-s epoch References ---------- Massimini, M. et al. J Neurosci 24(31) 6862-70 (2004). """ 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
[ "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'",...
Slow wave detection based on Massimini et al., 2004. Parameters ---------- dat_orig : ndarray (dtype='float') vector with the data for one channel s_freq : float sampling frequency time : ndarray (dtype='float') vector with the time points for each sample opts : instance of 'DetectSlowWave' 'det_filt' : dict parameters for 'butter', 'duration' : tuple of float min and max duration of SW 'min_ptp' : float min peak-to-peak amplitude 'trough_duration' : tuple of float min and max duration of first half-wave (trough) Returns ------- list of dict list of detected SWs float SW density, per 30-s epoch References ---------- Massimini, M. et al. J Neurosci 24(31) 6862-70 (2004).
[ "Slow", "wave", "detection", "based", "on", "Massimini", "et", "al", ".", "2004", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/detect/slowwave.py#L124-L187
train
23,450
wonambi-python/wonambi
wonambi/detect/slowwave.py
select_peaks
def select_peaks(data, events, limit): """Check whether event satisfies amplitude limit. Parameters ---------- data : ndarray (dtype='float') vector with data events : ndarray (dtype='int') N x 2+ matrix with peak/trough in second position limit : float low and high limit for spindle duration Returns ------- ndarray (dtype='int') N x 2+ matrix with peak/trough in second position """ selected = abs(data[events[:, 1]]) >= abs(limit) return events[selected, :]
python
def select_peaks(data, events, limit): """Check whether event satisfies amplitude limit. Parameters ---------- data : ndarray (dtype='float') vector with data events : ndarray (dtype='int') N x 2+ matrix with peak/trough in second position limit : float low and high limit for spindle duration Returns ------- ndarray (dtype='int') N x 2+ matrix with peak/trough in second position """ selected = abs(data[events[:, 1]]) >= abs(limit) return events[selected, :]
[ "def", "select_peaks", "(", "data", ",", "events", ",", "limit", ")", ":", "selected", "=", "abs", "(", "data", "[", "events", "[", ":", ",", "1", "]", "]", ")", ">=", "abs", "(", "limit", ")", "return", "events", "[", "selected", ",", ":", "]" ]
Check whether event satisfies amplitude limit. Parameters ---------- data : ndarray (dtype='float') vector with data events : ndarray (dtype='int') N x 2+ matrix with peak/trough in second position limit : float low and high limit for spindle duration Returns ------- ndarray (dtype='int') N x 2+ matrix with peak/trough in second position
[ "Check", "whether", "event", "satisfies", "amplitude", "limit", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/detect/slowwave.py#L190-L210
train
23,451
wonambi-python/wonambi
wonambi/detect/slowwave.py
make_slow_waves
def make_slow_waves(events, data, time, s_freq): """Create dict for each slow wave, based on events of time points. Parameters ---------- events : ndarray (dtype='int') N x 5 matrix with start, trough, zero, peak, end samples data : ndarray (dtype='float') vector with the data time : ndarray (dtype='float') vector with time points s_freq : float sampling frequency Returns ------- list of dict list of all the SWs, with information about start, trough_time, zero_time, peak_time, end, duration (s), trough_val, peak_val, peak-to-peak amplitude (signal units), area_under_curve (signal units * s) """ 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
python
def make_slow_waves(events, data, time, s_freq): """Create dict for each slow wave, based on events of time points. Parameters ---------- events : ndarray (dtype='int') N x 5 matrix with start, trough, zero, peak, end samples data : ndarray (dtype='float') vector with the data time : ndarray (dtype='float') vector with time points s_freq : float sampling frequency Returns ------- list of dict list of all the SWs, with information about start, trough_time, zero_time, peak_time, end, duration (s), trough_val, peak_val, peak-to-peak amplitude (signal units), area_under_curve (signal units * s) """ 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
[ "def", "make_slow_waves", "(", "events", ",", "data", ",", "time", ",", "s_freq", ")", ":", "slow_waves", "=", "[", "]", "for", "ev", "in", "events", ":", "one_sw", "=", "{", "'start'", ":", "time", "[", "ev", "[", "0", "]", "]", ",", "'trough_time...
Create dict for each slow wave, based on events of time points. Parameters ---------- events : ndarray (dtype='int') N x 5 matrix with start, trough, zero, peak, end samples data : ndarray (dtype='float') vector with the data time : ndarray (dtype='float') vector with time points s_freq : float sampling frequency Returns ------- list of dict list of all the SWs, with information about start, trough_time, zero_time, peak_time, end, duration (s), trough_val, peak_val, peak-to-peak amplitude (signal units), area_under_curve (signal units * s)
[ "Create", "dict", "for", "each", "slow", "wave", "based", "on", "events", "of", "time", "points", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/detect/slowwave.py#L213-L249
train
23,452
wonambi-python/wonambi
wonambi/detect/slowwave.py
_add_halfwave
def _add_halfwave(data, events, s_freq, opts): """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. Parameters ---------- data : ndarray (dtype='float') vector with the data events : ndarray (dtype='int') N x 3 matrix with start, trough, end samples s_freq : float sampling frequency opts : instance of 'DetectSlowWave' 'duration' : tuple of float min and max duration of SW 'min_ptp' : float min peak-to-peak amplitude Returns ------- ndarray (dtype='int') N x 5 matrix with start, trough, - to + zero crossing, peak, and end samples """ 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, :]
python
def _add_halfwave(data, events, s_freq, opts): """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. Parameters ---------- data : ndarray (dtype='float') vector with the data events : ndarray (dtype='int') N x 3 matrix with start, trough, end samples s_freq : float sampling frequency opts : instance of 'DetectSlowWave' 'duration' : tuple of float min and max duration of SW 'min_ptp' : float min peak-to-peak amplitude Returns ------- ndarray (dtype='int') N x 5 matrix with start, trough, - to + zero crossing, peak, and end samples """ 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, :]
[ "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...
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. Parameters ---------- data : ndarray (dtype='float') vector with the data events : ndarray (dtype='int') N x 3 matrix with start, trough, end samples s_freq : float sampling frequency opts : instance of 'DetectSlowWave' 'duration' : tuple of float min and max duration of SW 'min_ptp' : float min peak-to-peak amplitude Returns ------- ndarray (dtype='int') N x 5 matrix with start, trough, - to + zero crossing, peak, and end samples
[ "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", "s...
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/detect/slowwave.py#L252-L309
train
23,453
wonambi-python/wonambi
wonambi/widgets/notes.py
Notes.create
def create(self): """Create the widget layout with all the annotations.""" """ ------ 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')
python
def create(self): """Create the widget layout with all the annotations.""" """ ------ 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')
[ "def", "create", "(", "self", ")", ":", "\"\"\" ------ MARKERS ------ \"\"\"", "tab0", "=", "QTableWidget", "(", ")", "self", ".", "idx_marker", "=", "tab0", "tab0", ".", "setColumnCount", "(", "3", ")", "tab0", ".", "horizontalHeader", "(", ")", ".", "setSt...
Create the widget layout with all the annotations.
[ "Create", "the", "widget", "layout", "with", "all", "the", "annotations", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/notes.py#L202-L280
train
23,454
wonambi-python/wonambi
wonambi/widgets/notes.py
Notes.update_notes
def update_notes(self, xml_file, new=False): """Update information about the sleep scoring. Parameters ---------- xml_file : str file of the new or existing .xml file new : bool if the xml_file should be a new file or an existing one """ 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()
python
def update_notes(self, xml_file, new=False): """Update information about the sleep scoring. Parameters ---------- xml_file : str file of the new or existing .xml file new : bool if the xml_file should be a new file or an existing one """ 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()
[ "def", "update_notes", "(", "self", ",", "xml_file", ",", "new", "=", "False", ")", ":", "if", "new", ":", "create_empty_annotations", "(", "xml_file", ",", "self", ".", "parent", ".", "info", ".", "dataset", ")", "self", ".", "annot", "=", "Annotations"...
Update information about the sleep scoring. Parameters ---------- xml_file : str file of the new or existing .xml file new : bool if the xml_file should be a new file or an existing one
[ "Update", "information", "about", "the", "sleep", "scoring", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/notes.py#L507-L560
train
23,455
wonambi-python/wonambi
wonambi/widgets/notes.py
Notes.enable_events
def enable_events(self): """enable slow wave and spindle detection if both annotations and channels are active. """ 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)
python
def enable_events(self): """enable slow wave and spindle detection if both annotations and channels are active. """ 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)
[ "def", "enable_events", "(", "self", ")", ":", "if", "self", ".", "annot", "is", "not", "None", "and", "self", ".", "parent", ".", "channels", ".", "groups", ":", "self", ".", "action", "[", "'spindle'", "]", ".", "setEnabled", "(", "True", ")", "sel...
enable slow wave and spindle detection if both annotations and channels are active.
[ "enable", "slow", "wave", "and", "spindle", "detection", "if", "both", "annotations", "and", "channels", "are", "active", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/notes.py#L562-L573
train
23,456
wonambi-python/wonambi
wonambi/widgets/notes.py
Notes.display_notes
def display_notes(self): """Display information about scores and raters. """ 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
python
def display_notes(self): """Display information about scores and raters. """ 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
[ "def", "display_notes", "(", "self", ")", ":", "if", "self", ".", "annot", "is", "not", "None", ":", "short_xml_file", "=", "short_strings", "(", "basename", "(", "self", ".", "annot", ".", "xml_file", ")", ")", "self", ".", "idx_annotations", ".", "setT...
Display information about scores and raters.
[ "Display", "information", "about", "scores", "and", "raters", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/notes.py#L575-L592
train
23,457
wonambi-python/wonambi
wonambi/widgets/notes.py
Notes.display_stats
def display_stats(self): """Display summary statistics about duration in each stage.""" 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)
python
def display_stats(self): """Display summary statistics about duration in each stage.""" 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)
[ "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", "(", "timed...
Display summary statistics about duration in each stage.
[ "Display", "summary", "statistics", "about", "duration", "in", "each", "stage", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/notes.py#L594-L610
train
23,458
wonambi-python/wonambi
wonambi/widgets/notes.py
Notes.add_bookmark
def add_bookmark(self, time): """Run this function when user adds a new bookmark. Parameters ---------- time : tuple of float start and end of the new bookmark, in s """ 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()
python
def add_bookmark(self, time): """Run this function when user adds a new bookmark. Parameters ---------- time : tuple of float start and end of the new bookmark, in s """ 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()
[ "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", "(", ...
Run this function when user adds a new bookmark. Parameters ---------- time : tuple of float start and end of the new bookmark, in s
[ "Run", "this", "function", "when", "user", "adds", "a", "new", "bookmark", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/notes.py#L612-L636
train
23,459
wonambi-python/wonambi
wonambi/widgets/notes.py
Notes.remove_bookmark
def remove_bookmark(self, time): """User removes bookmark. Parameters ---------- time : tuple of float start and end of the new bookmark, in s """ self.annot.remove_bookmark(time=time) self.update_annotations()
python
def remove_bookmark(self, time): """User removes bookmark. Parameters ---------- time : tuple of float start and end of the new bookmark, in s """ self.annot.remove_bookmark(time=time) self.update_annotations()
[ "def", "remove_bookmark", "(", "self", ",", "time", ")", ":", "self", ".", "annot", ".", "remove_bookmark", "(", "time", "=", "time", ")", "self", ".", "update_annotations", "(", ")" ]
User removes bookmark. Parameters ---------- time : tuple of float start and end of the new bookmark, in s
[ "User", "removes", "bookmark", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/notes.py#L638-L647
train
23,460
wonambi-python/wonambi
wonambi/widgets/notes.py
Notes.update_dataset_marker
def update_dataset_marker(self): """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. """ 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()
python
def update_dataset_marker(self): """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. """ 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()
[ "def", "update_dataset_marker", "(", "self", ")", ":", "start_time", "=", "self", ".", "parent", ".", "overview", ".", "start_time", "markers", "=", "[", "]", "if", "self", ".", "parent", ".", "info", ".", "markers", "is", "not", "None", ":", "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.
[ "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", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/notes.py#L649-L691
train
23,461
wonambi-python/wonambi
wonambi/widgets/notes.py
Notes.display_eventtype
def display_eventtype(self): """Read the list of event types in the annotations and update widgets. """ 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)
python
def display_eventtype(self): """Read the list of event types in the annotations and update widgets. """ 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)
[ "def", "display_eventtype", "(", "self", ")", ":", "if", "self", ".", "annot", "is", "not", "None", ":", "event_types", "=", "sorted", "(", "self", ".", "annot", ".", "event_types", ",", "key", "=", "str", ".", "lower", ")", "else", ":", "event_types",...
Read the list of event types in the annotations and update widgets.
[ "Read", "the", "list", "of", "event", "types", "in", "the", "annotations", "and", "update", "widgets", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/notes.py#L693-L722
train
23,462
wonambi-python/wonambi
wonambi/widgets/notes.py
Notes.toggle_eventtype
def toggle_eventtype(self): """Check or uncheck all event types in event type scroll.""" check = self.check_all_eventtype.isChecked() for btn in self.idx_eventtype_list: btn.setChecked(check)
python
def toggle_eventtype(self): """Check or uncheck all event types in event type scroll.""" check = self.check_all_eventtype.isChecked() for btn in self.idx_eventtype_list: btn.setChecked(check)
[ "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.
[ "Check", "or", "uncheck", "all", "event", "types", "in", "event", "type", "scroll", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/notes.py#L724-L729
train
23,463
wonambi-python/wonambi
wonambi/widgets/notes.py
Notes.toggle_check_all_eventtype
def toggle_check_all_eventtype(self): """Check 'All' if all event types are checked in event type scroll.""" checklist = asarray([btn.isChecked for btn in self.idx_eventtype_list]) if not checklist.all(): self.check_all_eventtype.setChecked(False)
python
def toggle_check_all_eventtype(self): """Check 'All' if all event types are checked in event type scroll.""" checklist = asarray([btn.isChecked for btn in self.idx_eventtype_list]) if not checklist.all(): self.check_all_eventtype.setChecked(False)
[ "def", "toggle_check_all_eventtype", "(", "self", ")", ":", "checklist", "=", "asarray", "(", "[", "btn", ".", "isChecked", "for", "btn", "in", "self", ".", "idx_eventtype_list", "]", ")", "if", "not", "checklist", ".", "all", "(", ")", ":", "self", ".",...
Check 'All' if all event types are checked in event type scroll.
[ "Check", "All", "if", "all", "event", "types", "are", "checked", "in", "event", "type", "scroll", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/notes.py#L731-L736
train
23,464
wonambi-python/wonambi
wonambi/widgets/notes.py
Notes.get_selected_events
def get_selected_events(self, time_selection=None): """Returns which events are present in one time window. Parameters ---------- time_selection : tuple of float start and end of the window of interest Returns ------- list of dict list of events in the window of interest """ 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
python
def get_selected_events(self, time_selection=None): """Returns which events are present in one time window. Parameters ---------- time_selection : tuple of float start and end of the window of interest Returns ------- list of dict list of events in the window of interest """ 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
[ "def", "get_selected_events", "(", "self", ",", "time_selection", "=", "None", ")", ":", "events", "=", "[", "]", "for", "checkbox", "in", "self", ".", "idx_eventtype_list", ":", "if", "checkbox", ".", "checkState", "(", ")", "==", "Qt", ".", "Checked", ...
Returns which events are present in one time window. Parameters ---------- time_selection : tuple of float start and end of the window of interest Returns ------- list of dict list of events in the window of interest
[ "Returns", "which", "events", "are", "present", "in", "one", "time", "window", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/notes.py#L738-L757
train
23,465
wonambi-python/wonambi
wonambi/widgets/notes.py
Notes.update_annotations
def update_annotations(self): """Update annotations made by the user, including bookmarks and events. Depending on the settings, it might add the bookmarks to overview and traces. """ 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()
python
def update_annotations(self): """Update annotations made by the user, including bookmarks and events. Depending on the settings, it might add the bookmarks to overview and traces. """ 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()
[ "def", "update_annotations", "(", "self", ")", ":", "start_time", "=", "self", ".", "parent", ".", "overview", ".", "start_time", "if", "self", ".", "parent", ".", "notes", ".", "annot", "is", "None", ":", "all_annot", "=", "[", "]", "else", ":", "book...
Update annotations made by the user, including bookmarks and events. Depending on the settings, it might add the bookmarks to overview and traces.
[ "Update", "annotations", "made", "by", "the", "user", "including", "bookmarks", "and", "events", ".", "Depending", "on", "the", "settings", "it", "might", "add", "the", "bookmarks", "to", "overview", "and", "traces", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/notes.py#L759-L821
train
23,466
wonambi-python/wonambi
wonambi/widgets/notes.py
Notes.delete_row
def delete_row(self): """Delete bookmarks or event from annotations, based on row.""" 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()
python
def delete_row(self): """Delete bookmarks or event from annotations, based on row.""" 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()
[ "def", "delete_row", "(", "self", ")", ":", "sel_model", "=", "self", ".", "idx_annot_list", ".", "selectionModel", "(", ")", "for", "row", "in", "sel_model", ".", "selectedRows", "(", ")", ":", "i", "=", "row", ".", "row", "(", ")", "start", "=", "s...
Delete bookmarks or event from annotations, based on row.
[ "Delete", "bookmarks", "or", "event", "from", "annotations", "based", "on", "row", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/notes.py#L823-L842
train
23,467
wonambi-python/wonambi
wonambi/widgets/notes.py
Notes.go_to_marker
def go_to_marker(self, row, col, table_type): """Move to point in time marked by the marker. Parameters ---------- row : QtCore.int column : QtCore.int table_type : str 'dataset' table or 'annot' table, it works on either """ 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
python
def go_to_marker(self, row, col, table_type): """Move to point in time marked by the marker. Parameters ---------- row : QtCore.int column : QtCore.int table_type : str 'dataset' table or 'annot' table, it works on either """ 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
[ "def", "go_to_marker", "(", "self", ",", "row", ",", "col", ",", "table_type", ")", ":", "if", "table_type", "==", "'dataset'", ":", "marker_time", "=", "self", ".", "idx_marker", ".", "property", "(", "'start'", ")", "[", "row", "]", "marker_end_time", ...
Move to point in time marked by the marker. Parameters ---------- row : QtCore.int column : QtCore.int table_type : str 'dataset' table or 'annot' table, it works on either
[ "Move", "to", "point", "in", "time", "marked", "by", "the", "marker", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/notes.py#L844-L876
train
23,468
wonambi-python/wonambi
wonambi/widgets/notes.py
Notes.get_sleepstage
def get_sleepstage(self, stage_idx=None): """Score the sleep stage, using shortcuts or combobox.""" 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()
python
def get_sleepstage(self, stage_idx=None): """Score the sleep stage, using shortcuts or combobox.""" 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()
[ "def", "get_sleepstage", "(", "self", ",", "stage_idx", "=", "None", ")", ":", "if", "self", ".", "annot", "is", "None", ":", "# remove if buttons are disabled", "error_dialog", "=", "QErrorMessage", "(", ")", "error_dialog", ".", "setWindowTitle", "(", "'Error ...
Score the sleep stage, using shortcuts or combobox.
[ "Score", "the", "sleep", "stage", "using", "shortcuts", "or", "combobox", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/notes.py#L910-L955
train
23,469
wonambi-python/wonambi
wonambi/widgets/notes.py
Notes.get_quality
def get_quality(self, qual_idx=None): """Get the signal qualifier, using shortcuts or combobox.""" 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()
python
def get_quality(self, qual_idx=None): """Get the signal qualifier, using shortcuts or combobox.""" 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()
[ "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", "....
Get the signal qualifier, using shortcuts or combobox.
[ "Get", "the", "signal", "qualifier", "using", "shortcuts", "or", "combobox", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/notes.py#L957-L993
train
23,470
wonambi-python/wonambi
wonambi/widgets/notes.py
Notes.get_cycle_mrkr
def get_cycle_mrkr(self, end=False): """Mark cycle start or end. Parameters ---------- end : bool If True, marks a cycle end; otherwise, it's a cycle start """ 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)
python
def get_cycle_mrkr(self, end=False): """Mark cycle start or end. Parameters ---------- end : bool If True, marks a cycle end; otherwise, it's a cycle start """ 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)
[ "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'", ...
Mark cycle start or end. Parameters ---------- end : bool If True, marks a cycle end; otherwise, it's a cycle start
[ "Mark", "cycle", "start", "or", "end", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/notes.py#L995-L1027
train
23,471
wonambi-python/wonambi
wonambi/widgets/notes.py
Notes.remove_cycle_mrkr
def remove_cycle_mrkr(self): """Remove cycle marker.""" 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()
python
def remove_cycle_mrkr(self): """Remove cycle marker.""" 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()
[ "def", "remove_cycle_mrkr", "(", "self", ")", ":", "window_start", "=", "self", ".", "parent", ".", "value", "(", "'window_start'", ")", "try", ":", "self", ".", "annot", ".", "remove_cycle_mrkr", "(", "window_start", ")", "except", "KeyError", ":", "msg", ...
Remove cycle marker.
[ "Remove", "cycle", "marker", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/notes.py#L1029-L1046
train
23,472
wonambi-python/wonambi
wonambi/widgets/notes.py
Notes.clear_cycle_mrkrs
def clear_cycle_mrkrs(self, test=False): """Remove all cycle markers.""" 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()
python
def clear_cycle_mrkrs(self, test=False): """Remove all cycle markers.""" 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()
[ "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 fo...
Remove all cycle markers.
[ "Remove", "all", "cycle", "markers", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/notes.py#L1048-L1064
train
23,473
wonambi-python/wonambi
wonambi/widgets/notes.py
Notes.set_stage_index
def set_stage_index(self): """Set the current stage in combobox.""" 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))
python
def set_stage_index(self): """Set the current stage in combobox.""" 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))
[ "def", "set_stage_index", "(", "self", ")", ":", "window_start", "=", "self", ".", "parent", ".", "value", "(", "'window_start'", ")", "window_length", "=", "self", ".", "parent", ".", "value", "(", "'window_length'", ")", "stage", "=", "self", ".", "annot...
Set the current stage in combobox.
[ "Set", "the", "current", "stage", "in", "combobox", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/notes.py#L1066-L1076
train
23,474
wonambi-python/wonambi
wonambi/widgets/notes.py
Notes.set_quality_index
def set_quality_index(self): """Set the current signal quality in combobox.""" 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))
python
def set_quality_index(self): """Set the current signal quality in combobox.""" 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))
[ "def", "set_quality_index", "(", "self", ")", ":", "window_start", "=", "self", ".", "parent", ".", "value", "(", "'window_start'", ")", "window_length", "=", "self", ".", "parent", ".", "value", "(", "'window_length'", ")", "qual", "=", "self", ".", "anno...
Set the current signal quality in combobox.
[ "Set", "the", "current", "signal", "quality", "in", "combobox", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/notes.py#L1078-L1089
train
23,475
wonambi-python/wonambi
wonambi/widgets/notes.py
Notes.markers_to_events
def markers_to_events(self, keep_name=False): """Copy all markers in dataset to event type. """ 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()
python
def markers_to_events(self, keep_name=False): """Copy all markers in dataset to event type. """ 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()
[ "def", "markers_to_events", "(", "self", ",", "keep_name", "=", "False", ")", ":", "markers", "=", "self", ".", "parent", ".", "info", ".", "markers", "if", "markers", "is", "None", ":", "self", ".", "parent", ".", "statusBar", ".", "showMessage", "(", ...
Copy all markers in dataset to event type.
[ "Copy", "all", "markers", "in", "dataset", "to", "event", "type", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/notes.py#L1433-L1455
train
23,476
wonambi-python/wonambi
wonambi/widgets/notes.py
Notes.reset
def reset(self): """Remove all annotations from window.""" 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()
python
def reset(self): """Remove all annotations from window.""" 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()
[ "def", "reset", "(", "self", ")", ":", "self", ".", "idx_annotations", ".", "setText", "(", "'Load Annotation File...'", ")", "self", ".", "idx_rater", ".", "setText", "(", "''", ")", "self", ".", "annot", "=", "None", "self", ".", "dataset_markers", "=", ...
Remove all annotations from window.
[ "Remove", "all", "annotations", "from", "window", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/notes.py#L1652-L1680
train
23,477
wonambi-python/wonambi
wonambi/widgets/notes.py
MergeDialog.update_event_types
def update_event_types(self): """Update event types in event type box.""" 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)
python
def update_event_types(self): """Update event types in event type box.""" 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)
[ "def", "update_event_types", "(", "self", ")", ":", "self", ".", "idx_evt_type", ".", "clear", "(", ")", "self", ".", "idx_evt_type", ".", "setSelectionMode", "(", "QAbstractItemView", ".", "ExtendedSelection", ")", "event_types", "=", "sorted", "(", "self", "...
Update event types in event type box.
[ "Update", "event", "types", "in", "event", "type", "box", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/notes.py#L1838-L1847
train
23,478
wonambi-python/wonambi
wonambi/widgets/notes.py
ExportEventsDialog.update
def update(self): """Update the event types list, info, when dialog is opened.""" 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)
python
def update(self): """Update the event types list, info, when dialog is opened.""" 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)
[ "def", "update", "(", "self", ")", ":", "self", ".", "filename", "=", "self", ".", "parent", ".", "notes", ".", "annot", ".", "xml_file", "self", ".", "event_types", "=", "self", ".", "parent", ".", "notes", ".", "annot", ".", "event_types", "self", ...
Update the event types list, info, when dialog is opened.
[ "Update", "the", "event", "types", "list", "info", "when", "dialog", "is", "opened", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/notes.py#L1976-L1983
train
23,479
wonambi-python/wonambi
wonambi/widgets/notes.py
ExportEventsDialog.save_as
def save_as(self): """Dialog for getting name, location of dataset export.""" 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)
python
def save_as(self): """Dialog for getting name, location of dataset export.""" 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)
[ "def", "save_as", "(", "self", ")", ":", "filename", "=", "splitext", "(", "self", ".", "filename", ")", "[", "0", "]", "filename", ",", "_", "=", "QFileDialog", ".", "getSaveFileName", "(", "self", ",", "'Export events'", ",", "filename", ")", "if", "...
Dialog for getting name, location of dataset export.
[ "Dialog", "for", "getting", "name", "location", "of", "dataset", "export", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/notes.py#L1990-L2000
train
23,480
wonambi-python/wonambi
wonambi/attr/chan.py
_convert_unit
def _convert_unit(unit): """Convert different names into SI units. Parameters ---------- unit : str unit to convert to SI Returns ------- str unit in SI format. Notes ----- SI unit such as mV (milliVolt, mVolt), μV (microVolt, muV). """ 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
python
def _convert_unit(unit): """Convert different names into SI units. Parameters ---------- unit : str unit to convert to SI Returns ------- str unit in SI format. Notes ----- SI unit such as mV (milliVolt, mVolt), μV (microVolt, muV). """ 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
[ "def", "_convert_unit", "(", "unit", ")", ":", "if", "unit", "is", "None", ":", "return", "''", "prefix", "=", "None", "suffix", "=", "None", "if", "unit", "[", ":", "5", "]", ".", "lower", "(", ")", "==", "'milli'", ":", "prefix", "=", "'m'", "u...
Convert different names into SI units. Parameters ---------- unit : str unit to convert to SI Returns ------- str unit in SI format. Notes ----- SI unit such as mV (milliVolt, mVolt), μV (microVolt, muV).
[ "Convert", "different", "names", "into", "SI", "units", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/attr/chan.py#L32-L78
train
23,481
wonambi-python/wonambi
wonambi/attr/chan.py
detect_format
def detect_format(filename): """Detect file format of the channels based on extension. Parameters ---------- filename : Path name of the filename Returns ------- str file format """ filename = Path(filename) if filename.suffix == '.csv': recformat = 'csv' elif filename.suffix == '.sfp': recformat = 'sfp' else: recformat = 'unknown' return recformat
python
def detect_format(filename): """Detect file format of the channels based on extension. Parameters ---------- filename : Path name of the filename Returns ------- str file format """ filename = Path(filename) if filename.suffix == '.csv': recformat = 'csv' elif filename.suffix == '.sfp': recformat = 'sfp' else: recformat = 'unknown' return recformat
[ "def", "detect_format", "(", "filename", ")", ":", "filename", "=", "Path", "(", "filename", ")", "if", "filename", ".", "suffix", "==", "'.csv'", ":", "recformat", "=", "'csv'", "elif", "filename", ".", "suffix", "==", "'.sfp'", ":", "recformat", "=", "...
Detect file format of the channels based on extension. Parameters ---------- filename : Path name of the filename Returns ------- str file format
[ "Detect", "file", "format", "of", "the", "channels", "based", "on", "extension", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/attr/chan.py#L105-L128
train
23,482
wonambi-python/wonambi
wonambi/attr/chan.py
assign_region_to_channels
def assign_region_to_channels(channels, anat, parc_type='aparc', max_approx=3, exclude_regions=None): """Assign a brain region based on the channel location. Parameters ---------- channels : instance of wonambi.attr.chan.Channels channels to assign regions to anat : instance of wonambi.attr.anat.Freesurfer anatomical information taken from freesurfer. parc_type : str 'aparc', 'aparc.a2009s', 'BA', 'BA.thresh', or 'aparc.DKTatlas40' 'aparc.DKTatlas40' is only for recent freesurfer versions max_approx : int, optional approximation to define position of the electrode. exclude_regions : list of str or empty list do not report regions if they contain these substrings. None means that it does not exclude any region. For example, to exclude white matter regions and unknown regions you can use exclude_regions=('White', 'WM', 'Unknown') Returns ------- instance of wonambi.attr.chan.Channels same instance as before, now Chan have attr 'region' """ 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
python
def assign_region_to_channels(channels, anat, parc_type='aparc', max_approx=3, exclude_regions=None): """Assign a brain region based on the channel location. Parameters ---------- channels : instance of wonambi.attr.chan.Channels channels to assign regions to anat : instance of wonambi.attr.anat.Freesurfer anatomical information taken from freesurfer. parc_type : str 'aparc', 'aparc.a2009s', 'BA', 'BA.thresh', or 'aparc.DKTatlas40' 'aparc.DKTatlas40' is only for recent freesurfer versions max_approx : int, optional approximation to define position of the electrode. exclude_regions : list of str or empty list do not report regions if they contain these substrings. None means that it does not exclude any region. For example, to exclude white matter regions and unknown regions you can use exclude_regions=('White', 'WM', 'Unknown') Returns ------- instance of wonambi.attr.chan.Channels same instance as before, now Chan have attr 'region' """ 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
[ "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"...
Assign a brain region based on the channel location. Parameters ---------- channels : instance of wonambi.attr.chan.Channels channels to assign regions to anat : instance of wonambi.attr.anat.Freesurfer anatomical information taken from freesurfer. parc_type : str 'aparc', 'aparc.a2009s', 'BA', 'BA.thresh', or 'aparc.DKTatlas40' 'aparc.DKTatlas40' is only for recent freesurfer versions max_approx : int, optional approximation to define position of the electrode. exclude_regions : list of str or empty list do not report regions if they contain these substrings. None means that it does not exclude any region. For example, to exclude white matter regions and unknown regions you can use exclude_regions=('White', 'WM', 'Unknown') Returns ------- instance of wonambi.attr.chan.Channels same instance as before, now Chan have attr 'region'
[ "Assign", "a", "brain", "region", "based", "on", "the", "channel", "location", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/attr/chan.py#L362-L395
train
23,483
wonambi-python/wonambi
wonambi/attr/chan.py
find_chan_in_region
def find_chan_in_region(channels, anat, region_name): """Find which channels are in a specific region. Parameters ---------- channels : instance of wonambi.attr.chan.Channels channels, that have locations anat : instance of wonambi.attr.anat.Freesurfer anatomical information taken from freesurfer. region_name : str the name of the region, according to FreeSurferColorLUT.txt Returns ------- chan_in_region : list of str list of the channels that are in one region. """ 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
python
def find_chan_in_region(channels, anat, region_name): """Find which channels are in a specific region. Parameters ---------- channels : instance of wonambi.attr.chan.Channels channels, that have locations anat : instance of wonambi.attr.anat.Freesurfer anatomical information taken from freesurfer. region_name : str the name of the region, according to FreeSurferColorLUT.txt Returns ------- chan_in_region : list of str list of the channels that are in one region. """ 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
[ "def", "find_chan_in_region", "(", "channels", ",", "anat", ",", "region_name", ")", ":", "if", "'region'", "not", "in", "channels", ".", "chan", "[", "0", "]", ".", "attr", ".", "keys", "(", ")", ":", "lg", ".", "info", "(", "'Computing region for each ...
Find which channels are in a specific region. Parameters ---------- channels : instance of wonambi.attr.chan.Channels channels, that have locations anat : instance of wonambi.attr.anat.Freesurfer anatomical information taken from freesurfer. region_name : str the name of the region, according to FreeSurferColorLUT.txt Returns ------- chan_in_region : list of str list of the channels that are in one region.
[ "Find", "which", "channels", "are", "in", "a", "specific", "region", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/attr/chan.py#L398-L424
train
23,484
wonambi-python/wonambi
wonambi/attr/chan.py
create_sphere_around_elec
def create_sphere_around_elec(xyz, template_mri, distance=8, freesurfer=None): """Create an MRI mask around an electrode location, Parameters ---------- xyz : ndarray 3x0 array template_mri : path or str (as path) or nibabel.Nifti (path to) MRI to be used as template distance : float distance in mm between electrode and selected voxels freesurfer : instance of Freesurfer to adjust RAS coordinates, see Notes Returns ------- 3d bool ndarray mask where True voxels are within selected distance to the electrode Notes ----- Freesurfer uses two coordinate systems: one for volumes ("RAS") and one for surfaces ("tkReg", "tkRAS", and "Surface RAS"), so the electrodes might be stored in one of the two systems. If the electrodes are in surface coordinates (f.e. if you can plot surface and electrodes in the same space), then you need to convert the coordinate system. This is done by passing an instance of Freesurfer. """ 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
python
def create_sphere_around_elec(xyz, template_mri, distance=8, freesurfer=None): """Create an MRI mask around an electrode location, Parameters ---------- xyz : ndarray 3x0 array template_mri : path or str (as path) or nibabel.Nifti (path to) MRI to be used as template distance : float distance in mm between electrode and selected voxels freesurfer : instance of Freesurfer to adjust RAS coordinates, see Notes Returns ------- 3d bool ndarray mask where True voxels are within selected distance to the electrode Notes ----- Freesurfer uses two coordinate systems: one for volumes ("RAS") and one for surfaces ("tkReg", "tkRAS", and "Surface RAS"), so the electrodes might be stored in one of the two systems. If the electrodes are in surface coordinates (f.e. if you can plot surface and electrodes in the same space), then you need to convert the coordinate system. This is done by passing an instance of Freesurfer. """ 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
[ "def", "create_sphere_around_elec", "(", "xyz", ",", "template_mri", ",", "distance", "=", "8", ",", "freesurfer", "=", "None", ")", ":", "if", "freesurfer", "is", "None", ":", "shift", "=", "0", "else", ":", "shift", "=", "freesurfer", ".", "surface_ras_s...
Create an MRI mask around an electrode location, Parameters ---------- xyz : ndarray 3x0 array template_mri : path or str (as path) or nibabel.Nifti (path to) MRI to be used as template distance : float distance in mm between electrode and selected voxels freesurfer : instance of Freesurfer to adjust RAS coordinates, see Notes Returns ------- 3d bool ndarray mask where True voxels are within selected distance to the electrode Notes ----- Freesurfer uses two coordinate systems: one for volumes ("RAS") and one for surfaces ("tkReg", "tkRAS", and "Surface RAS"), so the electrodes might be stored in one of the two systems. If the electrodes are in surface coordinates (f.e. if you can plot surface and electrodes in the same space), then you need to convert the coordinate system. This is done by passing an instance of Freesurfer.
[ "Create", "an", "MRI", "mask", "around", "an", "electrode", "location" ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/attr/chan.py#L453-L495
train
23,485
wonambi-python/wonambi
wonambi/attr/chan.py
Channels.return_attr
def return_attr(self, attr, labels=None): """return the attributes for each channels. Parameters ---------- attr : str attribute specified in Chan.attr.keys() """ 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
python
def return_attr(self, attr, labels=None): """return the attributes for each channels. Parameters ---------- attr : str attribute specified in Chan.attr.keys() """ 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
[ "def", "return_attr", "(", "self", ",", "attr", ",", "labels", "=", "None", ")", ":", "all_labels", "=", "self", ".", "return_label", "(", ")", "if", "labels", "is", "None", ":", "labels", "=", "all_labels", "all_attr", "=", "[", "]", "for", "one_label...
return the attributes for each channels. Parameters ---------- attr : str attribute specified in Chan.attr.keys()
[ "return", "the", "attributes", "for", "each", "channels", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/attr/chan.py#L308-L333
train
23,486
wonambi-python/wonambi
wonambi/attr/chan.py
Channels.export
def export(self, elec_file): """Export channel name and location to file. Parameters ---------- elec_file : Path or str path to file where to save csv """ 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)
python
def export(self, elec_file): """Export channel name and location to file. Parameters ---------- elec_file : Path or str path to file where to save csv """ 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)
[ "def", "export", "(", "self", ",", "elec_file", ")", ":", "elec_file", "=", "Path", "(", "elec_file", ")", "if", "elec_file", ".", "suffix", "==", "'.csv'", ":", "sep", "=", "', '", "elif", "elec_file", ".", "suffix", "==", "'.sfp'", ":", "sep", "=", ...
Export channel name and location to file. Parameters ---------- elec_file : Path or str path to file where to save csv
[ "Export", "channel", "name", "and", "location", "to", "file", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/attr/chan.py#L340-L359
train
23,487
wonambi-python/wonambi
wonambi/trans/filter.py
filter_
def filter_(data, axis='time', low_cut=None, high_cut=None, order=4, ftype='butter', Rs=None, notchfreq=50, notchquality=25): """Design filter and apply it. Parameters ---------- ftype : str 'butter', 'cheby1', 'cheby2', 'ellip', 'bessel', 'diff', or 'notch' axis : str, optional axis to apply the filter on. low_cut : float, optional (not for notch) low cutoff for high-pass filter high_cut : float, optional (not for notch) high cutoff for low-pass filter order : int, optional (not for notch) filter order data : instance of Data (not for notch) the data to filter. notchfreq : float (only for notch) frequency to apply notch filter to (+ harmonics) notchquality : int (only for notch) Quality factor (see scipy.signal.iirnotch) Returns ------- filtered_data : instance of DataRaw filtered data Notes ----- You can specify any filter type as defined by iirfilter. If you specify low_cut only, it generates a high-pass filter. If you specify high_cut only, it generates a low-pass filter. If you specify both, it generates a band-pass filter. low_cut and high_cut should be given as ratio of the Nyquist. But if you specify s_freq, then the ratio will be computed automatically. Raises ------ ValueError if the cutoff frequency is larger than the Nyquist frequency. """ 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
python
def filter_(data, axis='time', low_cut=None, high_cut=None, order=4, ftype='butter', Rs=None, notchfreq=50, notchquality=25): """Design filter and apply it. Parameters ---------- ftype : str 'butter', 'cheby1', 'cheby2', 'ellip', 'bessel', 'diff', or 'notch' axis : str, optional axis to apply the filter on. low_cut : float, optional (not for notch) low cutoff for high-pass filter high_cut : float, optional (not for notch) high cutoff for low-pass filter order : int, optional (not for notch) filter order data : instance of Data (not for notch) the data to filter. notchfreq : float (only for notch) frequency to apply notch filter to (+ harmonics) notchquality : int (only for notch) Quality factor (see scipy.signal.iirnotch) Returns ------- filtered_data : instance of DataRaw filtered data Notes ----- You can specify any filter type as defined by iirfilter. If you specify low_cut only, it generates a high-pass filter. If you specify high_cut only, it generates a low-pass filter. If you specify both, it generates a band-pass filter. low_cut and high_cut should be given as ratio of the Nyquist. But if you specify s_freq, then the ratio will be computed automatically. Raises ------ ValueError if the cutoff frequency is larger than the Nyquist frequency. """ 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
[ "def", "filter_", "(", "data", ",", "axis", "=", "'time'", ",", "low_cut", "=", "None", ",", "high_cut", "=", "None", ",", "order", "=", "4", ",", "ftype", "=", "'butter'", ",", "Rs", "=", "None", ",", "notchfreq", "=", "50", ",", "notchquality", "...
Design filter and apply it. Parameters ---------- ftype : str 'butter', 'cheby1', 'cheby2', 'ellip', 'bessel', 'diff', or 'notch' axis : str, optional axis to apply the filter on. low_cut : float, optional (not for notch) low cutoff for high-pass filter high_cut : float, optional (not for notch) high cutoff for low-pass filter order : int, optional (not for notch) filter order data : instance of Data (not for notch) the data to filter. notchfreq : float (only for notch) frequency to apply notch filter to (+ harmonics) notchquality : int (only for notch) Quality factor (see scipy.signal.iirnotch) Returns ------- filtered_data : instance of DataRaw filtered data Notes ----- You can specify any filter type as defined by iirfilter. If you specify low_cut only, it generates a high-pass filter. If you specify high_cut only, it generates a low-pass filter. If you specify both, it generates a band-pass filter. low_cut and high_cut should be given as ratio of the Nyquist. But if you specify s_freq, then the ratio will be computed automatically. Raises ------ ValueError if the cutoff frequency is larger than the Nyquist frequency.
[ "Design", "filter", "and", "apply", "it", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/trans/filter.py#L18-L108
train
23,488
wonambi-python/wonambi
wonambi/trans/filter.py
convolve
def convolve(data, window, axis='time', length=1): """Design taper and convolve it with the signal. Parameters ---------- data : instance of Data the data to filter. window : str one of the windows in scipy, using get_window length : float, optional length of the window axis : str, optional axis to apply the filter on. Returns ------- instance of DataRaw data after convolution Notes ----- Most of the code is identical to fftconvolve(axis=data.index_of(axis)) but unfortunately fftconvolve in scipy 0.13 doesn't take that argument so we need to redefine it here. It's pretty slow too. Taper is normalized such that the integral of the function remains the same even after convolution. See Also -------- scipy.signal.get_window : function used to create windows """ 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
python
def convolve(data, window, axis='time', length=1): """Design taper and convolve it with the signal. Parameters ---------- data : instance of Data the data to filter. window : str one of the windows in scipy, using get_window length : float, optional length of the window axis : str, optional axis to apply the filter on. Returns ------- instance of DataRaw data after convolution Notes ----- Most of the code is identical to fftconvolve(axis=data.index_of(axis)) but unfortunately fftconvolve in scipy 0.13 doesn't take that argument so we need to redefine it here. It's pretty slow too. Taper is normalized such that the integral of the function remains the same even after convolution. See Also -------- scipy.signal.get_window : function used to create windows """ 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
[ "def", "convolve", "(", "data", ",", "window", ",", "axis", "=", "'time'", ",", "length", "=", "1", ")", ":", "taper", "=", "get_window", "(", "window", ",", "int", "(", "length", "*", "data", ".", "s_freq", ")", ")", "taper", "=", "taper", "/", ...
Design taper and convolve it with the signal. Parameters ---------- data : instance of Data the data to filter. window : str one of the windows in scipy, using get_window length : float, optional length of the window axis : str, optional axis to apply the filter on. Returns ------- instance of DataRaw data after convolution Notes ----- Most of the code is identical to fftconvolve(axis=data.index_of(axis)) but unfortunately fftconvolve in scipy 0.13 doesn't take that argument so we need to redefine it here. It's pretty slow too. Taper is normalized such that the integral of the function remains the same even after convolution. See Also -------- scipy.signal.get_window : function used to create windows
[ "Design", "taper", "and", "convolve", "it", "with", "the", "signal", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/trans/filter.py#L111-L176
train
23,489
wonambi-python/wonambi
wonambi/viz/base.py
normalize
def normalize(x, min_value, max_value): """Normalize value between min and max values. It also clips the values, so that you cannot have values higher or lower than 0 - 1.""" x = (x - min_value) / (max_value - min_value) return clip(x, 0, 1)
python
def normalize(x, min_value, max_value): """Normalize value between min and max values. It also clips the values, so that you cannot have values higher or lower than 0 - 1.""" x = (x - min_value) / (max_value - min_value) return clip(x, 0, 1)
[ "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.
[ "Normalize", "value", "between", "min", "and", "max", "values", ".", "It", "also", "clips", "the", "values", "so", "that", "you", "cannot", "have", "values", "higher", "or", "lower", "than", "0", "-", "1", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/viz/base.py#L55-L60
train
23,490
wonambi-python/wonambi
wonambi/viz/base.py
Viz._repr_png_
def _repr_png_(self): """This is used by ipython to plot inline. """ app.process_events() QApplication.processEvents() img = read_pixels() return bytes(_make_png(img))
python
def _repr_png_(self): """This is used by ipython to plot inline. """ app.process_events() QApplication.processEvents() img = read_pixels() return bytes(_make_png(img))
[ "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.
[ "This", "is", "used", "by", "ipython", "to", "plot", "inline", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/viz/base.py#L30-L37
train
23,491
wonambi-python/wonambi
wonambi/viz/base.py
Viz.save
def save(self, png_file): """Save png to disk. Parameters ---------- png_file : path to file file to write to Notes ----- It relies on _repr_png_, so fix issues there. """ with open(png_file, 'wb') as f: f.write(self._repr_png_())
python
def save(self, png_file): """Save png to disk. Parameters ---------- png_file : path to file file to write to Notes ----- It relies on _repr_png_, so fix issues there. """ with open(png_file, 'wb') as f: f.write(self._repr_png_())
[ "def", "save", "(", "self", ",", "png_file", ")", ":", "with", "open", "(", "png_file", ",", "'wb'", ")", "as", "f", ":", "f", ".", "write", "(", "self", ".", "_repr_png_", "(", ")", ")" ]
Save png to disk. Parameters ---------- png_file : path to file file to write to Notes ----- It relies on _repr_png_, so fix issues there.
[ "Save", "png", "to", "disk", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/viz/base.py#L39-L52
train
23,492
wonambi-python/wonambi
wonambi/widgets/overview.py
_make_timestamps
def _make_timestamps(start_time, minimum, maximum, steps): """Create timestamps on x-axis, every so often. Parameters ---------- start_time : instance of datetime actual start time of the dataset minimum : int start time of the recording from start_time, in s maximum : int end time of the recording from start_time, in s steps : int how often you want a label, in s Returns ------- dict where the key is the label and the value is the time point where the label should be placed. Notes ----- This function takes care that labels are placed at the meaningful time, not at random values. """ 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
python
def _make_timestamps(start_time, minimum, maximum, steps): """Create timestamps on x-axis, every so often. Parameters ---------- start_time : instance of datetime actual start time of the dataset minimum : int start time of the recording from start_time, in s maximum : int end time of the recording from start_time, in s steps : int how often you want a label, in s Returns ------- dict where the key is the label and the value is the time point where the label should be placed. Notes ----- This function takes care that labels are placed at the meaningful time, not at random values. """ 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
[ "def", "_make_timestamps", "(", "start_time", ",", "minimum", ",", "maximum", ",", "steps", ")", ":", "t0", "=", "start_time", "+", "timedelta", "(", "seconds", "=", "minimum", ")", "t1", "=", "start_time", "+", "timedelta", "(", "seconds", "=", "maximum",...
Create timestamps on x-axis, every so often. Parameters ---------- start_time : instance of datetime actual start time of the dataset minimum : int start time of the recording from start_time, in s maximum : int end time of the recording from start_time, in s steps : int how often you want a label, in s Returns ------- dict where the key is the label and the value is the time point where the label should be placed. Notes ----- This function takes care that labels are placed at the meaningful time, not at random values.
[ "Create", "timestamps", "on", "x", "-", "axis", "every", "so", "often", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/overview.py#L527-L570
train
23,493
wonambi-python/wonambi
wonambi/widgets/overview.py
Overview.update
def update(self, reset=True): """Read full duration and update maximum. Parameters ---------- reset: bool If True, current window start time is reset to 0. """ 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()
python
def update(self, reset=True): """Read full duration and update maximum. Parameters ---------- reset: bool If True, current window start time is reset to 0. """ 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()
[ "def", "update", "(", "self", ",", "reset", "=", "True", ")", ":", "if", "self", ".", "parent", ".", "info", ".", "dataset", "is", "not", "None", ":", "# read from the dataset, if available", "header", "=", "self", ".", "parent", ".", "info", ".", "datas...
Read full duration and update maximum. Parameters ---------- reset: bool If True, current window start time is reset to 0.
[ "Read", "full", "duration", "and", "update", "maximum", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/overview.py#L125-L154
train
23,494
wonambi-python/wonambi
wonambi/widgets/overview.py
Overview.display
def display(self): """Updates the widgets, especially based on length of recordings.""" 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()
python
def display(self): """Updates the widgets, especially based on length of recordings.""" 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()
[ "def", "display", "(", "self", ")", ":", "lg", ".", "debug", "(", "'GraphicsScene is between {}s and {}s'", ".", "format", "(", "self", ".", "minimum", ",", "self", ".", "maximum", ")", ")", "x_scale", "=", "1", "/", "self", ".", "parent", ".", "value", ...
Updates the widgets, especially based on length of recordings.
[ "Updates", "the", "widgets", "especially", "based", "on", "length", "of", "recordings", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/overview.py#L156-L184
train
23,495
wonambi-python/wonambi
wonambi/widgets/overview.py
Overview.add_timestamps
def add_timestamps(self): """Add timestamps at the bottom of the overview.""" 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)
python
def add_timestamps(self): """Add timestamps at the bottom of the overview.""" 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)
[ "def", "add_timestamps", "(", "self", ")", ":", "transform", ",", "_", "=", "self", ".", "transform", "(", ")", ".", "inverted", "(", ")", "stamps", "=", "_make_timestamps", "(", "self", ".", "start_time", ",", "self", ".", "minimum", ",", "self", ".",...
Add timestamps at the bottom of the overview.
[ "Add", "timestamps", "at", "the", "bottom", "of", "the", "overview", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/overview.py#L186-L199
train
23,496
wonambi-python/wonambi
wonambi/widgets/overview.py
Overview.update_settings
def update_settings(self): """After changing the settings, we need to recreate the whole image.""" self.display() self.display_markers() if self.parent.notes.annot is not None: self.parent.notes.display_notes()
python
def update_settings(self): """After changing the settings, we need to recreate the whole image.""" self.display() self.display_markers() if self.parent.notes.annot is not None: self.parent.notes.display_notes()
[ "def", "update_settings", "(", "self", ")", ":", "self", ".", "display", "(", ")", "self", ".", "display_markers", "(", ")", "if", "self", ".", "parent", ".", "notes", ".", "annot", "is", "not", "None", ":", "self", ".", "parent", ".", "notes", ".", ...
After changing the settings, we need to recreate the whole image.
[ "After", "changing", "the", "settings", "we", "need", "to", "recreate", "the", "whole", "image", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/overview.py#L201-L206
train
23,497
wonambi-python/wonambi
wonambi/widgets/overview.py
Overview.update_position
def update_position(self, new_position=None): """Update the cursor position and much more. Parameters ---------- new_position : int or float new position in s, for plotting etc. Notes ----- This is a central function. It updates the cursor, then updates the traces, the scores, and the power spectrum. In other words, this function is responsible for keep track of the changes every time the start time of the window changes. """ 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()
python
def update_position(self, new_position=None): """Update the cursor position and much more. Parameters ---------- new_position : int or float new position in s, for plotting etc. Notes ----- This is a central function. It updates the cursor, then updates the traces, the scores, and the power spectrum. In other words, this function is responsible for keep track of the changes every time the start time of the window changes. """ 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()
[ "def", "update_position", "(", "self", ",", "new_position", "=", "None", ")", ":", "if", "new_position", "is", "not", "None", ":", "lg", ".", "debug", "(", "'Updating position to {}'", ".", "format", "(", "new_position", ")", ")", "self", ".", "parent", "....
Update the cursor position and much more. Parameters ---------- new_position : int or float new position in s, for plotting etc. Notes ----- This is a central function. It updates the cursor, then updates the traces, the scores, and the power spectrum. In other words, this function is responsible for keep track of the changes every time the start time of the window changes.
[ "Update", "the", "cursor", "position", "and", "much", "more", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/overview.py#L208-L248
train
23,498
wonambi-python/wonambi
wonambi/widgets/overview.py
Overview.display_current
def display_current(self): """Create a rectangle showing the current window.""" 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
python
def display_current(self): """Create a rectangle showing the current window.""" 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
[ "def", "display_current", "(", "self", ")", ":", "if", "self", ".", "idx_current", "in", "self", ".", "scene", ".", "items", "(", ")", ":", "self", ".", "scene", ".", "removeItem", "(", "self", ".", "idx_current", ")", "item", "=", "QGraphicsRectItem", ...
Create a rectangle showing the current window.
[ "Create", "a", "rectangle", "showing", "the", "current", "window", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/overview.py#L250-L265
train
23,499