id
int32
0
252k
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
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
24,900
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): 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
24,901
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): 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
24,902
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): 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
24,903
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): 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
24,904
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): 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
24,905
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): 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
24,906
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): 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
24,907
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): 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
24,908
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): 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
24,909
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): 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
24,910
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): 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
24,911
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): """ ------ 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
24,912
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): 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
24,913
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): 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
24,914
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): 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
24,915
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): 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
24,916
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): 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
24,917
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): 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
24,918
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): 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
24,919
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): 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
24,920
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 = 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
24,921
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): 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
24,922
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): 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
24,923
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): 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
24,924
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): 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
24,925
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): 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
24,926
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): 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
24,927
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): 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
24,928
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): 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
24,929
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): 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
24,930
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): 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
24,931
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): 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
24,932
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): 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
24,933
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): 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
24,934
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): 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
24,935
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): 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
24,936
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): 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
24,937
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): 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
24,938
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): 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
24,939
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): 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
24,940
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): 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
24,941
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): 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
24,942
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): 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
24,943
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): 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
24,944
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): 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
24,945
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): 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
24,946
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): 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
24,947
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): 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
24,948
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): 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
24,949
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): 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
24,950
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): 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
24,951
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): 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
24,952
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): 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
24,953
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): 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
24,954
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): 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
24,955
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): 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
24,956
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): 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
24,957
wonambi-python/wonambi
wonambi/widgets/overview.py
Overview.display_markers
def display_markers(self): """Mark all the markers, from the dataset. This function should be called only when we load the dataset or when we change the settings. """ for rect in self.idx_markers: self.scene.removeItem(rect) self.idx_markers = [] markers = [] if self.parent.info.markers is not None: if self.parent.value('marker_show'): markers = self.parent.info.markers for mrk in markers: rect = QGraphicsRectItem(mrk['start'], BARS['markers']['pos0'], mrk['end'] - mrk['start'], BARS['markers']['pos1']) self.scene.addItem(rect) color = self.parent.value('marker_color') rect.setPen(QPen(QColor(color))) rect.setBrush(QBrush(QColor(color))) rect.setZValue(-5) self.idx_markers.append(rect)
python
def display_markers(self): for rect in self.idx_markers: self.scene.removeItem(rect) self.idx_markers = [] markers = [] if self.parent.info.markers is not None: if self.parent.value('marker_show'): markers = self.parent.info.markers for mrk in markers: rect = QGraphicsRectItem(mrk['start'], BARS['markers']['pos0'], mrk['end'] - mrk['start'], BARS['markers']['pos1']) self.scene.addItem(rect) color = self.parent.value('marker_color') rect.setPen(QPen(QColor(color))) rect.setBrush(QBrush(QColor(color))) rect.setZValue(-5) self.idx_markers.append(rect)
[ "def", "display_markers", "(", "self", ")", ":", "for", "rect", "in", "self", ".", "idx_markers", ":", "self", ".", "scene", ".", "removeItem", "(", "rect", ")", "self", ".", "idx_markers", "=", "[", "]", "markers", "=", "[", "]", "if", "self", ".", ...
Mark all the markers, from the dataset. This function should be called only when we load the dataset or when we change the settings.
[ "Mark", "all", "the", "markers", "from", "the", "dataset", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/overview.py#L267-L293
24,958
wonambi-python/wonambi
wonambi/widgets/overview.py
Overview.mark_stages
def mark_stages(self, start_time, length, stage_name): """Mark stages, only add the new ones. Parameters ---------- start_time : int start time in s of the epoch being scored. length : int duration in s of the epoch being scored. stage_name : str one of the stages defined in global stages. """ y_pos = BARS['stage']['pos0'] current_stage = STAGES.get(stage_name, STAGES['Unknown']) # the -1 is really important, otherwise we stay on the edge of the rect old_score = self.scene.itemAt(start_time + length / 2, y_pos + current_stage['pos0'] + current_stage['pos1'] - 1, self.transform()) # check we are not removing the black border if old_score is not None and old_score.pen() == NoPen: lg.debug('Removing old score at {}'.format(start_time)) self.scene.removeItem(old_score) self.idx_annot.remove(old_score) rect = QGraphicsRectItem(start_time, y_pos + current_stage['pos0'], length, current_stage['pos1']) rect.setPen(NoPen) rect.setBrush(current_stage['color']) self.scene.addItem(rect) self.idx_annot.append(rect)
python
def mark_stages(self, start_time, length, stage_name): y_pos = BARS['stage']['pos0'] current_stage = STAGES.get(stage_name, STAGES['Unknown']) # the -1 is really important, otherwise we stay on the edge of the rect old_score = self.scene.itemAt(start_time + length / 2, y_pos + current_stage['pos0'] + current_stage['pos1'] - 1, self.transform()) # check we are not removing the black border if old_score is not None and old_score.pen() == NoPen: lg.debug('Removing old score at {}'.format(start_time)) self.scene.removeItem(old_score) self.idx_annot.remove(old_score) rect = QGraphicsRectItem(start_time, y_pos + current_stage['pos0'], length, current_stage['pos1']) rect.setPen(NoPen) rect.setBrush(current_stage['color']) self.scene.addItem(rect) self.idx_annot.append(rect)
[ "def", "mark_stages", "(", "self", ",", "start_time", ",", "length", ",", "stage_name", ")", ":", "y_pos", "=", "BARS", "[", "'stage'", "]", "[", "'pos0'", "]", "current_stage", "=", "STAGES", ".", "get", "(", "stage_name", ",", "STAGES", "[", "'Unknown'...
Mark stages, only add the new ones. Parameters ---------- start_time : int start time in s of the epoch being scored. length : int duration in s of the epoch being scored. stage_name : str one of the stages defined in global stages.
[ "Mark", "stages", "only", "add", "the", "new", "ones", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/overview.py#L351-L386
24,959
wonambi-python/wonambi
wonambi/widgets/overview.py
Overview.mark_quality
def mark_quality(self, start_time, length, qual_name): """Mark signal quality, only add the new ones. Parameters ---------- start_time : int start time in s of the epoch being scored. length : int duration in s of the epoch being scored. qual_name : str one of the stages defined in global stages. """ y_pos = BARS['quality']['pos0'] height = 10 # the -1 is really important, otherwise we stay on the edge of the rect old_score = self.scene.itemAt(start_time + length / 2, y_pos + height - 1, self.transform()) # check we are not removing the black border if old_score is not None and old_score.pen() == NoPen: lg.debug('Removing old score at {}'.format(start_time)) self.scene.removeItem(old_score) self.idx_annot.remove(old_score) if qual_name == 'Poor': rect = QGraphicsRectItem(start_time, y_pos, length, height) rect.setPen(NoPen) rect.setBrush(Qt.black) self.scene.addItem(rect) self.idx_annot.append(rect)
python
def mark_quality(self, start_time, length, qual_name): y_pos = BARS['quality']['pos0'] height = 10 # the -1 is really important, otherwise we stay on the edge of the rect old_score = self.scene.itemAt(start_time + length / 2, y_pos + height - 1, self.transform()) # check we are not removing the black border if old_score is not None and old_score.pen() == NoPen: lg.debug('Removing old score at {}'.format(start_time)) self.scene.removeItem(old_score) self.idx_annot.remove(old_score) if qual_name == 'Poor': rect = QGraphicsRectItem(start_time, y_pos, length, height) rect.setPen(NoPen) rect.setBrush(Qt.black) self.scene.addItem(rect) self.idx_annot.append(rect)
[ "def", "mark_quality", "(", "self", ",", "start_time", ",", "length", ",", "qual_name", ")", ":", "y_pos", "=", "BARS", "[", "'quality'", "]", "[", "'pos0'", "]", "height", "=", "10", "# the -1 is really important, otherwise we stay on the edge of the rect", "old_sc...
Mark signal quality, only add the new ones. Parameters ---------- start_time : int start time in s of the epoch being scored. length : int duration in s of the epoch being scored. qual_name : str one of the stages defined in global stages.
[ "Mark", "signal", "quality", "only", "add", "the", "new", "ones", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/overview.py#L388-L419
24,960
wonambi-python/wonambi
wonambi/widgets/overview.py
Overview.mark_cycles
def mark_cycles(self, start_time, length, end=False): """Mark cycle bound, only add the new one. Parameters ---------- start_time: int start time in s of the bounding epoch length : int duration in s of the epoch being scored. end: bool If True, marker will be a cycle end marker; otherwise, it's start. """ y_pos = STAGES['cycle']['pos0'] height = STAGES['cycle']['pos1'] color = STAGES['cycle']['color'] # the -1 is really important, otherwise we stay on the edge of the rect old_rect = self.scene.itemAt(start_time + length / 2, y_pos + height - 1, self.transform()) # check we are not removing the black border if old_rect is not None and old_rect.pen() == NoPen: lg.debug('Removing old score at {}'.format(start_time)) self.scene.removeItem(old_rect) self.idx_annot.remove(old_rect) rect = QGraphicsRectItem(start_time, y_pos, 30, height) rect.setPen(NoPen) rect.setBrush(color) self.scene.addItem(rect) self.idx_annot.append(rect) if end: start_time -= 120 kink_hi = QGraphicsRectItem(start_time, y_pos, 150, 1) kink_hi.setPen(NoPen) kink_hi.setBrush(color) self.scene.addItem(kink_hi) self.idx_annot.append(kink_hi) kink_lo = QGraphicsRectItem(start_time, y_pos + height, 150, 1) kink_lo.setPen(NoPen) kink_lo.setBrush(color) self.scene.addItem(kink_lo) self.idx_annot.append(kink_lo)
python
def mark_cycles(self, start_time, length, end=False): y_pos = STAGES['cycle']['pos0'] height = STAGES['cycle']['pos1'] color = STAGES['cycle']['color'] # the -1 is really important, otherwise we stay on the edge of the rect old_rect = self.scene.itemAt(start_time + length / 2, y_pos + height - 1, self.transform()) # check we are not removing the black border if old_rect is not None and old_rect.pen() == NoPen: lg.debug('Removing old score at {}'.format(start_time)) self.scene.removeItem(old_rect) self.idx_annot.remove(old_rect) rect = QGraphicsRectItem(start_time, y_pos, 30, height) rect.setPen(NoPen) rect.setBrush(color) self.scene.addItem(rect) self.idx_annot.append(rect) if end: start_time -= 120 kink_hi = QGraphicsRectItem(start_time, y_pos, 150, 1) kink_hi.setPen(NoPen) kink_hi.setBrush(color) self.scene.addItem(kink_hi) self.idx_annot.append(kink_hi) kink_lo = QGraphicsRectItem(start_time, y_pos + height, 150, 1) kink_lo.setPen(NoPen) kink_lo.setBrush(color) self.scene.addItem(kink_lo) self.idx_annot.append(kink_lo)
[ "def", "mark_cycles", "(", "self", ",", "start_time", ",", "length", ",", "end", "=", "False", ")", ":", "y_pos", "=", "STAGES", "[", "'cycle'", "]", "[", "'pos0'", "]", "height", "=", "STAGES", "[", "'cycle'", "]", "[", "'pos1'", "]", "color", "=", ...
Mark cycle bound, only add the new one. Parameters ---------- start_time: int start time in s of the bounding epoch length : int duration in s of the epoch being scored. end: bool If True, marker will be a cycle end marker; otherwise, it's start.
[ "Mark", "cycle", "bound", "only", "add", "the", "new", "one", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/overview.py#L421-L467
24,961
wonambi-python/wonambi
wonambi/widgets/overview.py
Overview.mousePressEvent
def mousePressEvent(self, event): """Jump to window when user clicks on overview. Parameters ---------- event : instance of QtCore.QEvent it contains the position that was clicked. """ if self.scene is not None: x_in_scene = self.mapToScene(event.pos()).x() window_length = self.parent.value('window_length') window_start = int(floor(x_in_scene / window_length) * window_length) if self.parent.notes.annot is not None: window_start = self.parent.notes.annot.get_epoch_start( window_start) self.update_position(window_start)
python
def mousePressEvent(self, event): if self.scene is not None: x_in_scene = self.mapToScene(event.pos()).x() window_length = self.parent.value('window_length') window_start = int(floor(x_in_scene / window_length) * window_length) if self.parent.notes.annot is not None: window_start = self.parent.notes.annot.get_epoch_start( window_start) self.update_position(window_start)
[ "def", "mousePressEvent", "(", "self", ",", "event", ")", ":", "if", "self", ".", "scene", "is", "not", "None", ":", "x_in_scene", "=", "self", ".", "mapToScene", "(", "event", ".", "pos", "(", ")", ")", ".", "x", "(", ")", "window_length", "=", "s...
Jump to window when user clicks on overview. Parameters ---------- event : instance of QtCore.QEvent it contains the position that was clicked.
[ "Jump", "to", "window", "when", "user", "clicks", "on", "overview", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/overview.py#L494-L510
24,962
wonambi-python/wonambi
wonambi/widgets/overview.py
Overview.reset
def reset(self): """Reset the widget, and clear the scene.""" self.minimum = None self.maximum = None self.start_time = None # datetime, absolute start time self.idx_current = None self.idx_markers = [] self.idx_annot = [] if self.scene is not None: self.scene.clear() self.scene = None
python
def reset(self): self.minimum = None self.maximum = None self.start_time = None # datetime, absolute start time self.idx_current = None self.idx_markers = [] self.idx_annot = [] if self.scene is not None: self.scene.clear() self.scene = None
[ "def", "reset", "(", "self", ")", ":", "self", ".", "minimum", "=", "None", "self", ".", "maximum", "=", "None", "self", ".", "start_time", "=", "None", "# datetime, absolute start time", "self", ".", "idx_current", "=", "None", "self", ".", "idx_markers", ...
Reset the widget, and clear the scene.
[ "Reset", "the", "widget", "and", "clear", "the", "scene", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/overview.py#L512-L524
24,963
wonambi-python/wonambi
wonambi/viz/plot_3d.py
_prepare_colors
def _prepare_colors(color, values, limits_c, colormap, alpha, chan=None): """Return colors for all the channels based on various inputs. Parameters ---------- color : tuple 3-, 4-element tuple, representing RGB and alpha, between 0 and 1 values : ndarray array with values for each channel limits_c : tuple of 2 floats, optional min and max values to normalize the color colormap : str one of the colormaps in vispy alpha : float transparency (0 = transparent, 1 = opaque) chan : instance of Channels use labels to create channel groups Returns ------- 1d / 2d array colors for all the channels or for each channel individually tuple of two float or None limits for the values """ if values is not None: if limits_c is None: limits_c = array([-1, 1]) * nanmax(abs(values)) norm_values = normalize(values, *limits_c) cm = get_colormap(colormap) colors = cm[norm_values] elif color is not None: colors = ColorArray(color) else: cm = get_colormap('hsl') group_idx = _chan_groups_to_index(chan) colors = cm[group_idx] if alpha is not None: colors.alpha = alpha return colors, limits_c
python
def _prepare_colors(color, values, limits_c, colormap, alpha, chan=None): if values is not None: if limits_c is None: limits_c = array([-1, 1]) * nanmax(abs(values)) norm_values = normalize(values, *limits_c) cm = get_colormap(colormap) colors = cm[norm_values] elif color is not None: colors = ColorArray(color) else: cm = get_colormap('hsl') group_idx = _chan_groups_to_index(chan) colors = cm[group_idx] if alpha is not None: colors.alpha = alpha return colors, limits_c
[ "def", "_prepare_colors", "(", "color", ",", "values", ",", "limits_c", ",", "colormap", ",", "alpha", ",", "chan", "=", "None", ")", ":", "if", "values", "is", "not", "None", ":", "if", "limits_c", "is", "None", ":", "limits_c", "=", "array", "(", "...
Return colors for all the channels based on various inputs. Parameters ---------- color : tuple 3-, 4-element tuple, representing RGB and alpha, between 0 and 1 values : ndarray array with values for each channel limits_c : tuple of 2 floats, optional min and max values to normalize the color colormap : str one of the colormaps in vispy alpha : float transparency (0 = transparent, 1 = opaque) chan : instance of Channels use labels to create channel groups Returns ------- 1d / 2d array colors for all the channels or for each channel individually tuple of two float or None limits for the values
[ "Return", "colors", "for", "all", "the", "channels", "based", "on", "various", "inputs", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/viz/plot_3d.py#L146-L191
24,964
wonambi-python/wonambi
wonambi/viz/plot_3d.py
Viz3.add_surf
def add_surf(self, surf, color=SKIN_COLOR, vertex_colors=None, values=None, limits_c=None, colormap=COLORMAP, alpha=1, colorbar=False): """Add surfaces to the visualization. Parameters ---------- surf : instance of wonambi.attr.anat.Surf surface to be plotted color : tuple or ndarray, optional 4-element tuple, representing RGB and alpha, between 0 and 1 vertex_colors : ndarray ndarray with n vertices x 4 to specify color of each vertex values : ndarray, optional vector with values for each vertex limits_c : tuple of 2 floats, optional min and max values to normalize the color colormap : str one of the colormaps in vispy alpha : float transparency (1 = opaque) colorbar : bool add a colorbar at the back of the surface """ colors, limits = _prepare_colors(color=color, values=values, limits_c=limits_c, colormap=colormap, alpha=alpha) # meshdata uses numpy array, in the correct dimension vertex_colors = colors.rgba if vertex_colors.shape[0] == 1: vertex_colors = tile(vertex_colors, (surf.n_vert, 1)) meshdata = MeshData(vertices=surf.vert, faces=surf.tri, vertex_colors=vertex_colors) mesh = SurfaceMesh(meshdata) self._add_mesh(mesh) # adjust camera surf_center = mean(surf.vert, axis=0) if surf_center[0] < 0: azimuth = 270 else: azimuth = 90 self._view.camera.azimuth = azimuth self._view.camera.center = surf_center self._surf.append(mesh) if colorbar: self._view.add(_colorbar_for_surf(colormap, limits))
python
def add_surf(self, surf, color=SKIN_COLOR, vertex_colors=None, values=None, limits_c=None, colormap=COLORMAP, alpha=1, colorbar=False): colors, limits = _prepare_colors(color=color, values=values, limits_c=limits_c, colormap=colormap, alpha=alpha) # meshdata uses numpy array, in the correct dimension vertex_colors = colors.rgba if vertex_colors.shape[0] == 1: vertex_colors = tile(vertex_colors, (surf.n_vert, 1)) meshdata = MeshData(vertices=surf.vert, faces=surf.tri, vertex_colors=vertex_colors) mesh = SurfaceMesh(meshdata) self._add_mesh(mesh) # adjust camera surf_center = mean(surf.vert, axis=0) if surf_center[0] < 0: azimuth = 270 else: azimuth = 90 self._view.camera.azimuth = azimuth self._view.camera.center = surf_center self._surf.append(mesh) if colorbar: self._view.add(_colorbar_for_surf(colormap, limits))
[ "def", "add_surf", "(", "self", ",", "surf", ",", "color", "=", "SKIN_COLOR", ",", "vertex_colors", "=", "None", ",", "values", "=", "None", ",", "limits_c", "=", "None", ",", "colormap", "=", "COLORMAP", ",", "alpha", "=", "1", ",", "colorbar", "=", ...
Add surfaces to the visualization. Parameters ---------- surf : instance of wonambi.attr.anat.Surf surface to be plotted color : tuple or ndarray, optional 4-element tuple, representing RGB and alpha, between 0 and 1 vertex_colors : ndarray ndarray with n vertices x 4 to specify color of each vertex values : ndarray, optional vector with values for each vertex limits_c : tuple of 2 floats, optional min and max values to normalize the color colormap : str one of the colormaps in vispy alpha : float transparency (1 = opaque) colorbar : bool add a colorbar at the back of the surface
[ "Add", "surfaces", "to", "the", "visualization", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/viz/plot_3d.py#L42-L93
24,965
wonambi-python/wonambi
wonambi/viz/plot_3d.py
Viz3.add_chan
def add_chan(self, chan, color=None, values=None, limits_c=None, colormap=CHAN_COLORMAP, alpha=None, colorbar=False): """Add channels to visualization Parameters ---------- chan : instance of Channels channels to plot color : tuple 3-, 4-element tuple, representing RGB and alpha, between 0 and 1 values : ndarray array with values for each channel limits_c : tuple of 2 floats, optional min and max values to normalize the color colormap : str one of the colormaps in vispy alpha : float transparency (0 = transparent, 1 = opaque) colorbar : bool add a colorbar at the back of the surface """ # reuse previous limits if limits_c is None and self._chan_limits is not None: limits_c = self._chan_limits chan_colors, limits = _prepare_colors(color=color, values=values, limits_c=limits_c, colormap=colormap, alpha=alpha, chan=chan) self._chan_limits = limits xyz = chan.return_xyz() marker = Markers() marker.set_data(pos=xyz, size=CHAN_SIZE, face_color=chan_colors) self._add_mesh(marker) if colorbar: self._view.add(_colorbar_for_surf(colormap, limits))
python
def add_chan(self, chan, color=None, values=None, limits_c=None, colormap=CHAN_COLORMAP, alpha=None, colorbar=False): # reuse previous limits if limits_c is None and self._chan_limits is not None: limits_c = self._chan_limits chan_colors, limits = _prepare_colors(color=color, values=values, limits_c=limits_c, colormap=colormap, alpha=alpha, chan=chan) self._chan_limits = limits xyz = chan.return_xyz() marker = Markers() marker.set_data(pos=xyz, size=CHAN_SIZE, face_color=chan_colors) self._add_mesh(marker) if colorbar: self._view.add(_colorbar_for_surf(colormap, limits))
[ "def", "add_chan", "(", "self", ",", "chan", ",", "color", "=", "None", ",", "values", "=", "None", ",", "limits_c", "=", "None", ",", "colormap", "=", "CHAN_COLORMAP", ",", "alpha", "=", "None", ",", "colorbar", "=", "False", ")", ":", "# reuse previo...
Add channels to visualization Parameters ---------- chan : instance of Channels channels to plot color : tuple 3-, 4-element tuple, representing RGB and alpha, between 0 and 1 values : ndarray array with values for each channel limits_c : tuple of 2 floats, optional min and max values to normalize the color colormap : str one of the colormaps in vispy alpha : float transparency (0 = transparent, 1 = opaque) colorbar : bool add a colorbar at the back of the surface
[ "Add", "channels", "to", "visualization" ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/viz/plot_3d.py#L95-L133
24,966
wonambi-python/wonambi
wonambi/trans/select.py
select
def select(data, trial=None, invert=False, **axes_to_select): """Define the selection of trials, using ranges or actual values. Parameters ---------- data : instance of Data data to select from. trial : list of int or ndarray (dtype='i'), optional index of trials of interest **axes_to_select, optional Values need to be tuple or list. If the values in one axis are string, then you need to specify all the strings that you want. If the values are numeric, then you should specify the range (you cannot specify single values, nor multiple values). To select only up to one point, you can use (None, value_of_interest) invert : bool take the opposite selection Returns ------- instance, same class as input data where selection has been applied. """ if trial is not None and not isinstance(trial, Iterable): raise TypeError('Trial needs to be iterable.') for axis_to_select, values_to_select in axes_to_select.items(): if (not isinstance(values_to_select, Iterable) or isinstance(values_to_select, str)): raise TypeError(axis_to_select + ' needs to be iterable.') if trial is None: trial = range(data.number_of('trial')) else: trial = trial if invert: trial = setdiff1d(range(data.number_of('trial')), trial) # create empty axis output = data._copy(axis=False) for one_axis in output.axis: output.axis[one_axis] = empty(len(trial), dtype='O') output.data = empty(len(trial), dtype='O') to_select = {} for cnt, i in enumerate(trial): lg.debug('Selection on trial {0: 6}'.format(i)) for one_axis in output.axis: values = data.axis[one_axis][i] if one_axis in axes_to_select.keys(): values_to_select = axes_to_select[one_axis] if len(values_to_select) == 0: selected_values = () elif isinstance(values_to_select[0], str): selected_values = asarray(values_to_select, dtype='U') else: if (values_to_select[0] is None and values_to_select[1] is None): bool_values = ones(len(values), dtype=bool) elif values_to_select[0] is None: bool_values = values < values_to_select[1] elif values_to_select[1] is None: bool_values = values_to_select[0] <= values else: bool_values = ((values_to_select[0] <= values) & (values < values_to_select[1])) selected_values = values[bool_values] if invert: selected_values = setdiff1d(values, selected_values) lg.debug('In axis {0}, selecting {1: 6} ' 'values'.format(one_axis, len(selected_values))) to_select[one_axis] = selected_values else: lg.debug('In axis ' + one_axis + ', selecting all the ' 'values') selected_values = data.axis[one_axis][i] output.axis[one_axis][cnt] = selected_values output.data[cnt] = data(trial=i, **to_select) return output
python
def select(data, trial=None, invert=False, **axes_to_select): if trial is not None and not isinstance(trial, Iterable): raise TypeError('Trial needs to be iterable.') for axis_to_select, values_to_select in axes_to_select.items(): if (not isinstance(values_to_select, Iterable) or isinstance(values_to_select, str)): raise TypeError(axis_to_select + ' needs to be iterable.') if trial is None: trial = range(data.number_of('trial')) else: trial = trial if invert: trial = setdiff1d(range(data.number_of('trial')), trial) # create empty axis output = data._copy(axis=False) for one_axis in output.axis: output.axis[one_axis] = empty(len(trial), dtype='O') output.data = empty(len(trial), dtype='O') to_select = {} for cnt, i in enumerate(trial): lg.debug('Selection on trial {0: 6}'.format(i)) for one_axis in output.axis: values = data.axis[one_axis][i] if one_axis in axes_to_select.keys(): values_to_select = axes_to_select[one_axis] if len(values_to_select) == 0: selected_values = () elif isinstance(values_to_select[0], str): selected_values = asarray(values_to_select, dtype='U') else: if (values_to_select[0] is None and values_to_select[1] is None): bool_values = ones(len(values), dtype=bool) elif values_to_select[0] is None: bool_values = values < values_to_select[1] elif values_to_select[1] is None: bool_values = values_to_select[0] <= values else: bool_values = ((values_to_select[0] <= values) & (values < values_to_select[1])) selected_values = values[bool_values] if invert: selected_values = setdiff1d(values, selected_values) lg.debug('In axis {0}, selecting {1: 6} ' 'values'.format(one_axis, len(selected_values))) to_select[one_axis] = selected_values else: lg.debug('In axis ' + one_axis + ', selecting all the ' 'values') selected_values = data.axis[one_axis][i] output.axis[one_axis][cnt] = selected_values output.data[cnt] = data(trial=i, **to_select) return output
[ "def", "select", "(", "data", ",", "trial", "=", "None", ",", "invert", "=", "False", ",", "*", "*", "axes_to_select", ")", ":", "if", "trial", "is", "not", "None", "and", "not", "isinstance", "(", "trial", ",", "Iterable", ")", ":", "raise", "TypeEr...
Define the selection of trials, using ranges or actual values. Parameters ---------- data : instance of Data data to select from. trial : list of int or ndarray (dtype='i'), optional index of trials of interest **axes_to_select, optional Values need to be tuple or list. If the values in one axis are string, then you need to specify all the strings that you want. If the values are numeric, then you should specify the range (you cannot specify single values, nor multiple values). To select only up to one point, you can use (None, value_of_interest) invert : bool take the opposite selection Returns ------- instance, same class as input data where selection has been applied.
[ "Define", "the", "selection", "of", "trials", "using", "ranges", "or", "actual", "values", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/trans/select.py#L179-L267
24,967
wonambi-python/wonambi
wonambi/trans/select.py
resample
def resample(data, s_freq=None, axis='time', ftype='fir', n=None): """Downsample the data after applying a filter. Parameters ---------- data : instance of Data data to downsample s_freq : int or float desired sampling frequency axis : str axis you want to apply downsample on (most likely 'time') ftype : str filter type to apply. The default here is 'fir', like Matlab but unlike the default in scipy, because it works better n : int The order of the filter (1 less than the length for ‘fir’). Returns ------- instance of Data downsampled data """ output = data._copy() ratio = int(data.s_freq / s_freq) for i in range(data.number_of('trial')): output.data[i] = decimate(data.data[i], ratio, axis=data.index_of(axis), zero_phase=True) n_samples = output.data[i].shape[data.index_of(axis)] output.axis[axis][i] = linspace(data.axis[axis][i][0], data.axis[axis][i][-1] + 1 / data.s_freq, n_samples) output.s_freq = s_freq return output
python
def resample(data, s_freq=None, axis='time', ftype='fir', n=None): output = data._copy() ratio = int(data.s_freq / s_freq) for i in range(data.number_of('trial')): output.data[i] = decimate(data.data[i], ratio, axis=data.index_of(axis), zero_phase=True) n_samples = output.data[i].shape[data.index_of(axis)] output.axis[axis][i] = linspace(data.axis[axis][i][0], data.axis[axis][i][-1] + 1 / data.s_freq, n_samples) output.s_freq = s_freq return output
[ "def", "resample", "(", "data", ",", "s_freq", "=", "None", ",", "axis", "=", "'time'", ",", "ftype", "=", "'fir'", ",", "n", "=", "None", ")", ":", "output", "=", "data", ".", "_copy", "(", ")", "ratio", "=", "int", "(", "data", ".", "s_freq", ...
Downsample the data after applying a filter. Parameters ---------- data : instance of Data data to downsample s_freq : int or float desired sampling frequency axis : str axis you want to apply downsample on (most likely 'time') ftype : str filter type to apply. The default here is 'fir', like Matlab but unlike the default in scipy, because it works better n : int The order of the filter (1 less than the length for ‘fir’). Returns ------- instance of Data downsampled data
[ "Downsample", "the", "data", "after", "applying", "a", "filter", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/trans/select.py#L270-L308
24,968
wonambi-python/wonambi
wonambi/trans/select.py
fetch
def fetch(dataset, annot, cat=(0, 0, 0, 0), evt_type=None, stage=None, cycle=None, chan_full=None, epoch=None, epoch_dur=30, epoch_overlap=0, epoch_step=None, reject_epoch=False, reject_artf=False, min_dur=0, buffer=0): """Create instance of Segments for analysis, complete with info about stage, cycle, channel, event type. Segments contains only metadata until .read_data is called. Parameters ---------- dataset : instance of Dataset info about record annot : instance of Annotations scoring info cat : tuple of int Determines where the signal is concatenated. If cat[0] is 1, cycles will be concatenated. If cat[1] is 1, different stages will be concatenated. If cat[2] is 1, discontinuous signal within a same condition (stage, cycle, event type) will be concatenated. If cat[3] is 1, events of different types will be concatenated. 0 in any position indicates no concatenation. evt_type: list of str, optional Enter a list of event types to get events; otherwise, epochs will be returned. stage: list of str, optional Stage(s) of interest. If None, stage is ignored. cycle: list of tuple of two float, optional Cycle(s) of interest, as start and end times in seconds from record start. If None, cycles are ignored. chan_full: list of str or None Channel(s) of interest, only used for events (epochs have no channel). Channel format is 'chan_name (group_name)'. If used for epochs, separate segments will be returned for each channel; this is necessary for channel-specific artefact removal (see reject_artf below). If None, channel is ignored. epoch : str, optional If 'locked', returns epochs locked to staging. If 'unlocked', divides signal (with specified concatenation) into epochs of duration epoch_dur starting at first sample of every segment and discarding any remainder. If None, longest run of signal is returned. epoch_dur : float only for epoch='unlocked'. Duration of epochs returned, in seconds. epoch_overlap : float only for epoch='unlocked'. Ratio of overlap between two consecutive segments. Value between 0 and 1. Overriden by step. epoch_step : float only for epoch='unlocked'. Time between consecutive epoch starts, in seconds. Overrides epoch_overlap/ reject_epoch: bool If True, epochs marked as 'Poor' quality or staged as 'Artefact' will be rejected (and the signal segmented in consequence). Has no effect on event selection. reject_artf : bool If True, excludes events marked as 'Artefact'. If chan_full is specified, only artefacts marked on a given channel are removed from that channel. Signal is segmented in consequence. If None, Artefact events are ignored. min_dur : float Minimum duration of segments returned, in seconds. buffer : float adds this many seconds of signal before and after each segment Returns ------- instance of Segments metadata for all analysis segments """ bundles = get_times(annot, evt_type=evt_type, stage=stage, cycle=cycle, chan=chan_full, exclude=reject_epoch, buffer=buffer) # Remove artefacts if reject_artf and bundles: for bund in bundles: bund['times'] = remove_artf_evts(bund['times'], annot, bund['chan'], min_dur=0) # Divide bundles into segments to be concatenated if bundles: if 'locked' == epoch: bundles = _divide_bundles(bundles) elif 'unlocked' == epoch: if epoch_step is not None: step = epoch_step else: step = epoch_dur - (epoch_dur * epoch_overlap) bundles = _concat(bundles, cat) bundles = _find_intervals(bundles, epoch_dur, step) elif not epoch: bundles = _concat(bundles, cat) # Minimum duration bundles = _longer_than(bundles, min_dur) segments = Segments(dataset) segments.segments = bundles return segments
python
def fetch(dataset, annot, cat=(0, 0, 0, 0), evt_type=None, stage=None, cycle=None, chan_full=None, epoch=None, epoch_dur=30, epoch_overlap=0, epoch_step=None, reject_epoch=False, reject_artf=False, min_dur=0, buffer=0): bundles = get_times(annot, evt_type=evt_type, stage=stage, cycle=cycle, chan=chan_full, exclude=reject_epoch, buffer=buffer) # Remove artefacts if reject_artf and bundles: for bund in bundles: bund['times'] = remove_artf_evts(bund['times'], annot, bund['chan'], min_dur=0) # Divide bundles into segments to be concatenated if bundles: if 'locked' == epoch: bundles = _divide_bundles(bundles) elif 'unlocked' == epoch: if epoch_step is not None: step = epoch_step else: step = epoch_dur - (epoch_dur * epoch_overlap) bundles = _concat(bundles, cat) bundles = _find_intervals(bundles, epoch_dur, step) elif not epoch: bundles = _concat(bundles, cat) # Minimum duration bundles = _longer_than(bundles, min_dur) segments = Segments(dataset) segments.segments = bundles return segments
[ "def", "fetch", "(", "dataset", ",", "annot", ",", "cat", "=", "(", "0", ",", "0", ",", "0", ",", "0", ")", ",", "evt_type", "=", "None", ",", "stage", "=", "None", ",", "cycle", "=", "None", ",", "chan_full", "=", "None", ",", "epoch", "=", ...
Create instance of Segments for analysis, complete with info about stage, cycle, channel, event type. Segments contains only metadata until .read_data is called. Parameters ---------- dataset : instance of Dataset info about record annot : instance of Annotations scoring info cat : tuple of int Determines where the signal is concatenated. If cat[0] is 1, cycles will be concatenated. If cat[1] is 1, different stages will be concatenated. If cat[2] is 1, discontinuous signal within a same condition (stage, cycle, event type) will be concatenated. If cat[3] is 1, events of different types will be concatenated. 0 in any position indicates no concatenation. evt_type: list of str, optional Enter a list of event types to get events; otherwise, epochs will be returned. stage: list of str, optional Stage(s) of interest. If None, stage is ignored. cycle: list of tuple of two float, optional Cycle(s) of interest, as start and end times in seconds from record start. If None, cycles are ignored. chan_full: list of str or None Channel(s) of interest, only used for events (epochs have no channel). Channel format is 'chan_name (group_name)'. If used for epochs, separate segments will be returned for each channel; this is necessary for channel-specific artefact removal (see reject_artf below). If None, channel is ignored. epoch : str, optional If 'locked', returns epochs locked to staging. If 'unlocked', divides signal (with specified concatenation) into epochs of duration epoch_dur starting at first sample of every segment and discarding any remainder. If None, longest run of signal is returned. epoch_dur : float only for epoch='unlocked'. Duration of epochs returned, in seconds. epoch_overlap : float only for epoch='unlocked'. Ratio of overlap between two consecutive segments. Value between 0 and 1. Overriden by step. epoch_step : float only for epoch='unlocked'. Time between consecutive epoch starts, in seconds. Overrides epoch_overlap/ reject_epoch: bool If True, epochs marked as 'Poor' quality or staged as 'Artefact' will be rejected (and the signal segmented in consequence). Has no effect on event selection. reject_artf : bool If True, excludes events marked as 'Artefact'. If chan_full is specified, only artefacts marked on a given channel are removed from that channel. Signal is segmented in consequence. If None, Artefact events are ignored. min_dur : float Minimum duration of segments returned, in seconds. buffer : float adds this many seconds of signal before and after each segment Returns ------- instance of Segments metadata for all analysis segments
[ "Create", "instance", "of", "Segments", "for", "analysis", "complete", "with", "info", "about", "stage", "cycle", "channel", "event", "type", ".", "Segments", "contains", "only", "metadata", "until", ".", "read_data", "is", "called", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/trans/select.py#L311-L413
24,969
wonambi-python/wonambi
wonambi/trans/select.py
get_times
def get_times(annot, evt_type=None, stage=None, cycle=None, chan=None, exclude=False, buffer=0): """Get start and end times for selected segments of data, bundled together with info. Parameters ---------- annot: instance of Annotations The annotation file containing events and epochs evt_type: list of str, optional Enter a list of event types to get events; otherwise, epochs will be returned. stage: list of str, optional Stage(s) of interest. If None, stage is ignored. cycle: list of tuple of two float, optional Cycle(s) of interest, as start and end times in seconds from record start. If None, cycles are ignored. chan: list of str or tuple of None Channel(s) of interest. Channel format is 'chan_name (group_name)'. If None, channel is ignored. exclude: bool Exclude epochs by quality. If True, epochs marked as 'Poor' quality or staged as 'Artefact' will be rejected (and the signal segmented in consequence). Has no effect on event selection. buffer : float adds this many seconds of signal before and after each segment Returns ------- list of dict Each dict has times (the start and end times of each segment, as list of tuple of float), stage, cycle, chan, name (event type, if applicable) Notes ----- This function returns epoch or event start and end times, bundled together according to the specified parameters. Presently, setting exclude to True does not exclude events found in Poor signal epochs. The rationale is that events would never be marked in Poor signal epochs. If they were automatically detected, these epochs would have been left out during detection. If they were manually marked, then it must have been Good signal. At the moment, in the GUI, the exclude epoch option is disabled when analyzing events, but we could fix the code if we find a use case for rejecting events based on the quality of the epoch signal. """ getter = annot.get_epochs last = annot.last_second if stage is None: stage = (None,) if cycle is None: cycle = (None,) if chan is None: chan = (None,) if evt_type is None: evt_type = (None,) elif isinstance(evt_type[0], str): getter = annot.get_events if chan != (None,): chan.append('') # also retrieve events marked on all channels else: lg.error('Event type must be list/tuple of str or None') qual = None if exclude: qual = 'Good' bundles = [] for et in evt_type: for ch in chan: for cyc in cycle: for ss in stage: st_input = ss if ss is not None: st_input = (ss,) evochs = getter(name=et, time=cyc, chan=(ch,), stage=st_input, qual=qual) if evochs: times = [( max(e['start'] - buffer, 0), min(e['end'] + buffer, last)) for e in evochs] times = sorted(times, key=lambda x: x[0]) one_bundle = {'times': times, 'stage': ss, 'cycle': cyc, 'chan': ch, 'name': et} bundles.append(one_bundle) return bundles
python
def get_times(annot, evt_type=None, stage=None, cycle=None, chan=None, exclude=False, buffer=0): getter = annot.get_epochs last = annot.last_second if stage is None: stage = (None,) if cycle is None: cycle = (None,) if chan is None: chan = (None,) if evt_type is None: evt_type = (None,) elif isinstance(evt_type[0], str): getter = annot.get_events if chan != (None,): chan.append('') # also retrieve events marked on all channels else: lg.error('Event type must be list/tuple of str or None') qual = None if exclude: qual = 'Good' bundles = [] for et in evt_type: for ch in chan: for cyc in cycle: for ss in stage: st_input = ss if ss is not None: st_input = (ss,) evochs = getter(name=et, time=cyc, chan=(ch,), stage=st_input, qual=qual) if evochs: times = [( max(e['start'] - buffer, 0), min(e['end'] + buffer, last)) for e in evochs] times = sorted(times, key=lambda x: x[0]) one_bundle = {'times': times, 'stage': ss, 'cycle': cyc, 'chan': ch, 'name': et} bundles.append(one_bundle) return bundles
[ "def", "get_times", "(", "annot", ",", "evt_type", "=", "None", ",", "stage", "=", "None", ",", "cycle", "=", "None", ",", "chan", "=", "None", ",", "exclude", "=", "False", ",", "buffer", "=", "0", ")", ":", "getter", "=", "annot", ".", "get_epoch...
Get start and end times for selected segments of data, bundled together with info. Parameters ---------- annot: instance of Annotations The annotation file containing events and epochs evt_type: list of str, optional Enter a list of event types to get events; otherwise, epochs will be returned. stage: list of str, optional Stage(s) of interest. If None, stage is ignored. cycle: list of tuple of two float, optional Cycle(s) of interest, as start and end times in seconds from record start. If None, cycles are ignored. chan: list of str or tuple of None Channel(s) of interest. Channel format is 'chan_name (group_name)'. If None, channel is ignored. exclude: bool Exclude epochs by quality. If True, epochs marked as 'Poor' quality or staged as 'Artefact' will be rejected (and the signal segmented in consequence). Has no effect on event selection. buffer : float adds this many seconds of signal before and after each segment Returns ------- list of dict Each dict has times (the start and end times of each segment, as list of tuple of float), stage, cycle, chan, name (event type, if applicable) Notes ----- This function returns epoch or event start and end times, bundled together according to the specified parameters. Presently, setting exclude to True does not exclude events found in Poor signal epochs. The rationale is that events would never be marked in Poor signal epochs. If they were automatically detected, these epochs would have been left out during detection. If they were manually marked, then it must have been Good signal. At the moment, in the GUI, the exclude epoch option is disabled when analyzing events, but we could fix the code if we find a use case for rejecting events based on the quality of the epoch signal.
[ "Get", "start", "and", "end", "times", "for", "selected", "segments", "of", "data", "bundled", "together", "with", "info", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/trans/select.py#L416-L512
24,970
wonambi-python/wonambi
wonambi/trans/select.py
_longer_than
def _longer_than(segments, min_dur): """Remove segments longer than min_dur.""" if min_dur <= 0.: return segments long_enough = [] for seg in segments: if sum([t[1] - t[0] for t in seg['times']]) >= min_dur: long_enough.append(seg) return long_enough
python
def _longer_than(segments, min_dur): if min_dur <= 0.: return segments long_enough = [] for seg in segments: if sum([t[1] - t[0] for t in seg['times']]) >= min_dur: long_enough.append(seg) return long_enough
[ "def", "_longer_than", "(", "segments", ",", "min_dur", ")", ":", "if", "min_dur", "<=", "0.", ":", "return", "segments", "long_enough", "=", "[", "]", "for", "seg", "in", "segments", ":", "if", "sum", "(", "[", "t", "[", "1", "]", "-", "t", "[", ...
Remove segments longer than min_dur.
[ "Remove", "segments", "longer", "than", "min_dur", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/trans/select.py#L515-L526
24,971
wonambi-python/wonambi
wonambi/trans/select.py
_concat
def _concat(bundles, cat=(0, 0, 0, 0)): """Prepare event or epoch start and end times for concatenation.""" chan = sorted(set([x['chan'] for x in bundles])) cycle = sorted(set([x['cycle'] for x in bundles])) stage = sorted(set([x['stage'] for x in bundles])) evt_type = sorted(set([x['name'] for x in bundles])) all_cycle = None all_stage = None all_evt_type = None if cycle[0] is not None: all_cycle = ', '.join([str(c) for c in cycle]) if stage[0] is not None: all_stage = ', '.join(stage) if evt_type[0] is not None: all_evt_type = ', '.join(evt_type) if cat[0]: cycle = [all_cycle] if cat[1]: stage = [all_stage] if cat[3]: evt_type = [all_evt_type] to_concat = [] for ch in chan: for cyc in cycle: for st in stage: for et in evt_type: new_times = [] for bund in bundles: chan_cond = ch == bund['chan'] cyc_cond = cyc in (bund['cycle'], all_cycle) st_cond = st in (bund['stage'], all_stage) et_cond = et in (bund['name'], all_evt_type) if chan_cond and cyc_cond and st_cond and et_cond: new_times.extend(bund['times']) new_times = sorted(new_times, key=lambda x: x[0]) new_bund = {'times': new_times, 'chan': ch, 'cycle': cyc, 'stage': st, 'name': et } to_concat.append(new_bund) if not cat[2]: to_concat_new = [] for bund in to_concat: last = None bund['times'].append((inf,inf)) start = 0 for i, j in enumerate(bund['times']): if last is not None: if not isclose(j[0], last, abs_tol=0.01): new_times = bund['times'][start:i] new_bund = bund.copy() new_bund['times'] = new_times to_concat_new.append(new_bund) start = i last = j[1] to_concat = to_concat_new to_concat = [x for x in to_concat if x['times']] return to_concat
python
def _concat(bundles, cat=(0, 0, 0, 0)): chan = sorted(set([x['chan'] for x in bundles])) cycle = sorted(set([x['cycle'] for x in bundles])) stage = sorted(set([x['stage'] for x in bundles])) evt_type = sorted(set([x['name'] for x in bundles])) all_cycle = None all_stage = None all_evt_type = None if cycle[0] is not None: all_cycle = ', '.join([str(c) for c in cycle]) if stage[0] is not None: all_stage = ', '.join(stage) if evt_type[0] is not None: all_evt_type = ', '.join(evt_type) if cat[0]: cycle = [all_cycle] if cat[1]: stage = [all_stage] if cat[3]: evt_type = [all_evt_type] to_concat = [] for ch in chan: for cyc in cycle: for st in stage: for et in evt_type: new_times = [] for bund in bundles: chan_cond = ch == bund['chan'] cyc_cond = cyc in (bund['cycle'], all_cycle) st_cond = st in (bund['stage'], all_stage) et_cond = et in (bund['name'], all_evt_type) if chan_cond and cyc_cond and st_cond and et_cond: new_times.extend(bund['times']) new_times = sorted(new_times, key=lambda x: x[0]) new_bund = {'times': new_times, 'chan': ch, 'cycle': cyc, 'stage': st, 'name': et } to_concat.append(new_bund) if not cat[2]: to_concat_new = [] for bund in to_concat: last = None bund['times'].append((inf,inf)) start = 0 for i, j in enumerate(bund['times']): if last is not None: if not isclose(j[0], last, abs_tol=0.01): new_times = bund['times'][start:i] new_bund = bund.copy() new_bund['times'] = new_times to_concat_new.append(new_bund) start = i last = j[1] to_concat = to_concat_new to_concat = [x for x in to_concat if x['times']] return to_concat
[ "def", "_concat", "(", "bundles", ",", "cat", "=", "(", "0", ",", "0", ",", "0", ",", "0", ")", ")", ":", "chan", "=", "sorted", "(", "set", "(", "[", "x", "[", "'chan'", "]", "for", "x", "in", "bundles", "]", ")", ")", "cycle", "=", "sorte...
Prepare event or epoch start and end times for concatenation.
[ "Prepare", "event", "or", "epoch", "start", "and", "end", "times", "for", "concatenation", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/trans/select.py#L529-L607
24,972
wonambi-python/wonambi
wonambi/trans/select.py
_divide_bundles
def _divide_bundles(bundles): """Take each subsegment inside a bundle and put it in its own bundle, copying the bundle metadata.""" divided = [] for bund in bundles: for t in bund['times']: new_bund = bund.copy() new_bund['times'] = [t] divided.append(new_bund) return divided
python
def _divide_bundles(bundles): divided = [] for bund in bundles: for t in bund['times']: new_bund = bund.copy() new_bund['times'] = [t] divided.append(new_bund) return divided
[ "def", "_divide_bundles", "(", "bundles", ")", ":", "divided", "=", "[", "]", "for", "bund", "in", "bundles", ":", "for", "t", "in", "bund", "[", "'times'", "]", ":", "new_bund", "=", "bund", ".", "copy", "(", ")", "new_bund", "[", "'times'", "]", ...
Take each subsegment inside a bundle and put it in its own bundle, copying the bundle metadata.
[ "Take", "each", "subsegment", "inside", "a", "bundle", "and", "put", "it", "in", "its", "own", "bundle", "copying", "the", "bundle", "metadata", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/trans/select.py#L610-L621
24,973
wonambi-python/wonambi
wonambi/trans/select.py
_find_intervals
def _find_intervals(bundles, duration, step): """Divide bundles into segments of a certain duration and a certain step, discarding any remainder.""" segments = [] for bund in bundles: beg, end = bund['times'][0][0], bund['times'][-1][1] if end - beg >= duration: new_begs = arange(beg, end - duration, step) for t in new_begs: seg = bund.copy() seg['times'] = [(t, t + duration)] segments.append(seg) return segments
python
def _find_intervals(bundles, duration, step): segments = [] for bund in bundles: beg, end = bund['times'][0][0], bund['times'][-1][1] if end - beg >= duration: new_begs = arange(beg, end - duration, step) for t in new_begs: seg = bund.copy() seg['times'] = [(t, t + duration)] segments.append(seg) return segments
[ "def", "_find_intervals", "(", "bundles", ",", "duration", ",", "step", ")", ":", "segments", "=", "[", "]", "for", "bund", "in", "bundles", ":", "beg", ",", "end", "=", "bund", "[", "'times'", "]", "[", "0", "]", "[", "0", "]", ",", "bund", "[",...
Divide bundles into segments of a certain duration and a certain step, discarding any remainder.
[ "Divide", "bundles", "into", "segments", "of", "a", "certain", "duration", "and", "a", "certain", "step", "discarding", "any", "remainder", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/trans/select.py#L624-L639
24,974
wonambi-python/wonambi
wonambi/trans/select.py
_create_data
def _create_data(data, active_chan, ref_chan=[], grp_name=None): """Create data after montage. Parameters ---------- data : instance of ChanTime the raw data active_chan : list of str the channel(s) of interest, without reference or group ref_chan : list of str reference channel(s), without group grp_name : str name of channel group, if applicable Returns ------- instance of ChanTime the re-referenced data """ output = ChanTime() output.s_freq = data.s_freq output.start_time = data.start_time output.axis['time'] = data.axis['time'] output.axis['chan'] = empty(1, dtype='O') output.data = empty(1, dtype='O') output.data[0] = empty((len(active_chan), data.number_of('time')[0]), dtype='f') sel_data = _select_channels(data, active_chan + ref_chan) data1 = montage(sel_data, ref_chan=ref_chan) data1.data[0] = nan_to_num(data1.data[0]) all_chan_grp_name = [] for i, chan in enumerate(active_chan): chan_grp_name = chan if grp_name: chan_grp_name = chan + ' (' + grp_name + ')' all_chan_grp_name.append(chan_grp_name) dat = data1(chan=chan, trial=0) output.data[0][i, :] = dat output.axis['chan'][0] = asarray(all_chan_grp_name, dtype='U') return output
python
def _create_data(data, active_chan, ref_chan=[], grp_name=None): output = ChanTime() output.s_freq = data.s_freq output.start_time = data.start_time output.axis['time'] = data.axis['time'] output.axis['chan'] = empty(1, dtype='O') output.data = empty(1, dtype='O') output.data[0] = empty((len(active_chan), data.number_of('time')[0]), dtype='f') sel_data = _select_channels(data, active_chan + ref_chan) data1 = montage(sel_data, ref_chan=ref_chan) data1.data[0] = nan_to_num(data1.data[0]) all_chan_grp_name = [] for i, chan in enumerate(active_chan): chan_grp_name = chan if grp_name: chan_grp_name = chan + ' (' + grp_name + ')' all_chan_grp_name.append(chan_grp_name) dat = data1(chan=chan, trial=0) output.data[0][i, :] = dat output.axis['chan'][0] = asarray(all_chan_grp_name, dtype='U') return output
[ "def", "_create_data", "(", "data", ",", "active_chan", ",", "ref_chan", "=", "[", "]", ",", "grp_name", "=", "None", ")", ":", "output", "=", "ChanTime", "(", ")", "output", ".", "s_freq", "=", "data", ".", "s_freq", "output", ".", "start_time", "=", ...
Create data after montage. Parameters ---------- data : instance of ChanTime the raw data active_chan : list of str the channel(s) of interest, without reference or group ref_chan : list of str reference channel(s), without group grp_name : str name of channel group, if applicable Returns ------- instance of ChanTime the re-referenced data
[ "Create", "data", "after", "montage", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/trans/select.py#L642-L687
24,975
wonambi-python/wonambi
wonambi/trans/select.py
_select_channels
def _select_channels(data, channels): """Select channels. Parameters ---------- data : instance of ChanTime data with all the channels channels : list channels of interest Returns ------- instance of ChanTime data with only channels of interest Notes ----- This function does the same as wonambi.trans.select, but it's much faster. wonambi.trans.Select needs to flexible for any data type, here we assume that we have one trial, and that channel is the first dimension. """ output = data._copy() chan_list = list(data.axis['chan'][0]) idx_chan = [chan_list.index(i_chan) for i_chan in channels] output.data[0] = data.data[0][idx_chan, :] output.axis['chan'][0] = asarray(channels) return output
python
def _select_channels(data, channels): output = data._copy() chan_list = list(data.axis['chan'][0]) idx_chan = [chan_list.index(i_chan) for i_chan in channels] output.data[0] = data.data[0][idx_chan, :] output.axis['chan'][0] = asarray(channels) return output
[ "def", "_select_channels", "(", "data", ",", "channels", ")", ":", "output", "=", "data", ".", "_copy", "(", ")", "chan_list", "=", "list", "(", "data", ".", "axis", "[", "'chan'", "]", "[", "0", "]", ")", "idx_chan", "=", "[", "chan_list", ".", "i...
Select channels. Parameters ---------- data : instance of ChanTime data with all the channels channels : list channels of interest Returns ------- instance of ChanTime data with only channels of interest Notes ----- This function does the same as wonambi.trans.select, but it's much faster. wonambi.trans.Select needs to flexible for any data type, here we assume that we have one trial, and that channel is the first dimension.
[ "Select", "channels", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/trans/select.py#L718-L746
24,976
wonambi-python/wonambi
wonambi/widgets/creation.py
create_widgets
def create_widgets(MAIN): """Create all the widgets and dockwidgets. It also creates actions to toggle views of dockwidgets in dockwidgets. """ """ ------ CREATE WIDGETS ------ """ MAIN.labels = Labels(MAIN) MAIN.channels = Channels(MAIN) MAIN.notes = Notes(MAIN) MAIN.merge_dialog = MergeDialog(MAIN) MAIN.export_events_dialog = ExportEventsDialog(MAIN) MAIN.export_dataset_dialog = ExportDatasetDialog(MAIN) MAIN.spindle_dialog = SpindleDialog(MAIN) MAIN.slow_wave_dialog = SWDialog(MAIN) MAIN.analysis_dialog = AnalysisDialog(MAIN) #MAIN.plot_dialog = PlotDialog(MAIN) MAIN.overview = Overview(MAIN) MAIN.spectrum = Spectrum(MAIN) MAIN.traces = Traces(MAIN) MAIN.video = Video(MAIN) MAIN.settings = Settings(MAIN) # depends on all widgets apart from Info MAIN.info = Info(MAIN) # this has to be the last, it depends on settings MAIN.setCentralWidget(MAIN.traces) """ ------ LIST DOCKWIDGETS ------ """ new_docks = [{'name': 'Information', 'widget': MAIN.info, 'main_area': Qt.LeftDockWidgetArea, 'extra_area': Qt.RightDockWidgetArea, }, {'name': 'Labels', 'widget': MAIN.labels, 'main_area': Qt.RightDockWidgetArea, 'extra_area': Qt.LeftDockWidgetArea, }, {'name': 'Channels', 'widget': MAIN.channels, 'main_area': Qt.RightDockWidgetArea, 'extra_area': Qt.LeftDockWidgetArea, }, {'name': 'Spectrum', 'widget': MAIN.spectrum, 'main_area': Qt.RightDockWidgetArea, 'extra_area': Qt.LeftDockWidgetArea, }, {'name': 'Annotations', 'widget': MAIN.notes, 'main_area': Qt.LeftDockWidgetArea, 'extra_area': Qt.RightDockWidgetArea, }, {'name': 'Video', 'widget': MAIN.video, 'main_area': Qt.LeftDockWidgetArea, 'extra_area': Qt.RightDockWidgetArea, }, {'name': 'Overview', 'widget': MAIN.overview, 'main_area': Qt.BottomDockWidgetArea, 'extra_area': Qt.TopDockWidgetArea, }, ] """ ------ CREATE DOCKWIDGETS ------ """ idx_docks = {} actions = MAIN.action actions['dockwidgets'] = [] for dock in new_docks: dockwidget = QDockWidget(dock['name'], MAIN) dockwidget.setWidget(dock['widget']) dockwidget.setAllowedAreas(dock['main_area'] | dock['extra_area']) dockwidget.setObjectName(dock['name']) # savestate idx_docks[dock['name']] = dockwidget MAIN.addDockWidget(dock['main_area'], dockwidget) dockwidget_action = dockwidget.toggleViewAction() dockwidget_action.setIcon(QIcon(ICON['widget'])) actions['dockwidgets'].append(dockwidget_action) """ ------ ORGANIZE DOCKWIDGETS ------ """ MAIN.tabifyDockWidget(idx_docks['Information'], idx_docks['Video']) MAIN.tabifyDockWidget(idx_docks['Channels'], idx_docks['Labels']) idx_docks['Information'].raise_()
python
def create_widgets(MAIN): """ ------ CREATE WIDGETS ------ """ MAIN.labels = Labels(MAIN) MAIN.channels = Channels(MAIN) MAIN.notes = Notes(MAIN) MAIN.merge_dialog = MergeDialog(MAIN) MAIN.export_events_dialog = ExportEventsDialog(MAIN) MAIN.export_dataset_dialog = ExportDatasetDialog(MAIN) MAIN.spindle_dialog = SpindleDialog(MAIN) MAIN.slow_wave_dialog = SWDialog(MAIN) MAIN.analysis_dialog = AnalysisDialog(MAIN) #MAIN.plot_dialog = PlotDialog(MAIN) MAIN.overview = Overview(MAIN) MAIN.spectrum = Spectrum(MAIN) MAIN.traces = Traces(MAIN) MAIN.video = Video(MAIN) MAIN.settings = Settings(MAIN) # depends on all widgets apart from Info MAIN.info = Info(MAIN) # this has to be the last, it depends on settings MAIN.setCentralWidget(MAIN.traces) """ ------ LIST DOCKWIDGETS ------ """ new_docks = [{'name': 'Information', 'widget': MAIN.info, 'main_area': Qt.LeftDockWidgetArea, 'extra_area': Qt.RightDockWidgetArea, }, {'name': 'Labels', 'widget': MAIN.labels, 'main_area': Qt.RightDockWidgetArea, 'extra_area': Qt.LeftDockWidgetArea, }, {'name': 'Channels', 'widget': MAIN.channels, 'main_area': Qt.RightDockWidgetArea, 'extra_area': Qt.LeftDockWidgetArea, }, {'name': 'Spectrum', 'widget': MAIN.spectrum, 'main_area': Qt.RightDockWidgetArea, 'extra_area': Qt.LeftDockWidgetArea, }, {'name': 'Annotations', 'widget': MAIN.notes, 'main_area': Qt.LeftDockWidgetArea, 'extra_area': Qt.RightDockWidgetArea, }, {'name': 'Video', 'widget': MAIN.video, 'main_area': Qt.LeftDockWidgetArea, 'extra_area': Qt.RightDockWidgetArea, }, {'name': 'Overview', 'widget': MAIN.overview, 'main_area': Qt.BottomDockWidgetArea, 'extra_area': Qt.TopDockWidgetArea, }, ] """ ------ CREATE DOCKWIDGETS ------ """ idx_docks = {} actions = MAIN.action actions['dockwidgets'] = [] for dock in new_docks: dockwidget = QDockWidget(dock['name'], MAIN) dockwidget.setWidget(dock['widget']) dockwidget.setAllowedAreas(dock['main_area'] | dock['extra_area']) dockwidget.setObjectName(dock['name']) # savestate idx_docks[dock['name']] = dockwidget MAIN.addDockWidget(dock['main_area'], dockwidget) dockwidget_action = dockwidget.toggleViewAction() dockwidget_action.setIcon(QIcon(ICON['widget'])) actions['dockwidgets'].append(dockwidget_action) """ ------ ORGANIZE DOCKWIDGETS ------ """ MAIN.tabifyDockWidget(idx_docks['Information'], idx_docks['Video']) MAIN.tabifyDockWidget(idx_docks['Channels'], idx_docks['Labels']) idx_docks['Information'].raise_()
[ "def", "create_widgets", "(", "MAIN", ")", ":", "\"\"\" ------ CREATE WIDGETS ------ \"\"\"", "MAIN", ".", "labels", "=", "Labels", "(", "MAIN", ")", "MAIN", ".", "channels", "=", "Channels", "(", "MAIN", ")", "MAIN", ".", "notes", "=", "Notes", "(", "MAIN",...
Create all the widgets and dockwidgets. It also creates actions to toggle views of dockwidgets in dockwidgets.
[ "Create", "all", "the", "widgets", "and", "dockwidgets", ".", "It", "also", "creates", "actions", "to", "toggle", "views", "of", "dockwidgets", "in", "dockwidgets", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/creation.py#L31-L118
24,977
wonambi-python/wonambi
wonambi/widgets/creation.py
create_actions
def create_actions(MAIN): """Create all the possible actions.""" actions = MAIN.action # actions was already taken """ ------ OPEN SETTINGS ------ """ actions['open_settings'] = QAction(QIcon(ICON['settings']), 'Settings', MAIN) actions['open_settings'].triggered.connect(MAIN.show_settings) """ ------ CLOSE WINDOW ------ """ actions['close_wndw'] = QAction(QIcon(ICON['quit']), 'Quit', MAIN) actions['close_wndw'].triggered.connect(MAIN.close) """ ------ ABOUT ------ """ actions['about'] = QAction('About WONAMBI', MAIN) actions['about'].triggered.connect(MAIN.about) actions['aboutqt'] = QAction('About Qt', MAIN) actions['aboutqt'].triggered.connect(lambda: QMessageBox.aboutQt(MAIN))
python
def create_actions(MAIN): actions = MAIN.action # actions was already taken """ ------ OPEN SETTINGS ------ """ actions['open_settings'] = QAction(QIcon(ICON['settings']), 'Settings', MAIN) actions['open_settings'].triggered.connect(MAIN.show_settings) """ ------ CLOSE WINDOW ------ """ actions['close_wndw'] = QAction(QIcon(ICON['quit']), 'Quit', MAIN) actions['close_wndw'].triggered.connect(MAIN.close) """ ------ ABOUT ------ """ actions['about'] = QAction('About WONAMBI', MAIN) actions['about'].triggered.connect(MAIN.about) actions['aboutqt'] = QAction('About Qt', MAIN) actions['aboutqt'].triggered.connect(lambda: QMessageBox.aboutQt(MAIN))
[ "def", "create_actions", "(", "MAIN", ")", ":", "actions", "=", "MAIN", ".", "action", "# actions was already taken", "\"\"\" ------ OPEN SETTINGS ------ \"\"\"", "actions", "[", "'open_settings'", "]", "=", "QAction", "(", "QIcon", "(", "ICON", "[", "'settings'", "...
Create all the possible actions.
[ "Create", "all", "the", "possible", "actions", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/creation.py#L121-L139
24,978
wonambi-python/wonambi
wonambi/widgets/creation.py
create_toolbar
def create_toolbar(MAIN): """Create the various toolbars.""" actions = MAIN.action toolbar = MAIN.addToolBar('File Management') toolbar.setObjectName('File Management') # for savestate toolbar.addAction(MAIN.info.action['open_dataset']) toolbar.addSeparator() toolbar.addAction(MAIN.channels.action['load_channels']) toolbar.addAction(MAIN.channels.action['save_channels']) toolbar.addSeparator() toolbar.addAction(MAIN.notes.action['new_annot']) toolbar.addAction(MAIN.notes.action['load_annot']) """ ------ SCROLL ------ """ actions = MAIN.traces.action toolbar = MAIN.addToolBar('Scroll') toolbar.setObjectName('Scroll') # for savestate toolbar.addAction(actions['step_prev']) toolbar.addAction(actions['step_next']) toolbar.addAction(actions['page_prev']) toolbar.addAction(actions['page_next']) toolbar.addSeparator() toolbar.addAction(actions['X_more']) toolbar.addAction(actions['X_less']) toolbar.addSeparator() toolbar.addAction(actions['Y_less']) toolbar.addAction(actions['Y_more']) toolbar.addAction(actions['Y_wider']) toolbar.addAction(actions['Y_tighter']) """ ------ ANNOTATIONS ------ """ actions = MAIN.notes.action toolbar = MAIN.addToolBar('Annotations') toolbar.setObjectName('Annotations') toolbar.addAction(actions['new_bookmark']) toolbar.addSeparator() toolbar.addAction(actions['new_event']) toolbar.addWidget(MAIN.notes.idx_eventtype) toolbar.addSeparator() toolbar.addWidget(MAIN.notes.idx_stage) toolbar.addWidget(MAIN.notes.idx_quality)
python
def create_toolbar(MAIN): actions = MAIN.action toolbar = MAIN.addToolBar('File Management') toolbar.setObjectName('File Management') # for savestate toolbar.addAction(MAIN.info.action['open_dataset']) toolbar.addSeparator() toolbar.addAction(MAIN.channels.action['load_channels']) toolbar.addAction(MAIN.channels.action['save_channels']) toolbar.addSeparator() toolbar.addAction(MAIN.notes.action['new_annot']) toolbar.addAction(MAIN.notes.action['load_annot']) """ ------ SCROLL ------ """ actions = MAIN.traces.action toolbar = MAIN.addToolBar('Scroll') toolbar.setObjectName('Scroll') # for savestate toolbar.addAction(actions['step_prev']) toolbar.addAction(actions['step_next']) toolbar.addAction(actions['page_prev']) toolbar.addAction(actions['page_next']) toolbar.addSeparator() toolbar.addAction(actions['X_more']) toolbar.addAction(actions['X_less']) toolbar.addSeparator() toolbar.addAction(actions['Y_less']) toolbar.addAction(actions['Y_more']) toolbar.addAction(actions['Y_wider']) toolbar.addAction(actions['Y_tighter']) """ ------ ANNOTATIONS ------ """ actions = MAIN.notes.action toolbar = MAIN.addToolBar('Annotations') toolbar.setObjectName('Annotations') toolbar.addAction(actions['new_bookmark']) toolbar.addSeparator() toolbar.addAction(actions['new_event']) toolbar.addWidget(MAIN.notes.idx_eventtype) toolbar.addSeparator() toolbar.addWidget(MAIN.notes.idx_stage) toolbar.addWidget(MAIN.notes.idx_quality)
[ "def", "create_toolbar", "(", "MAIN", ")", ":", "actions", "=", "MAIN", ".", "action", "toolbar", "=", "MAIN", ".", "addToolBar", "(", "'File Management'", ")", "toolbar", ".", "setObjectName", "(", "'File Management'", ")", "# for savestate", "toolbar", ".", ...
Create the various toolbars.
[ "Create", "the", "various", "toolbars", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/creation.py#L327-L371
24,979
wonambi-python/wonambi
wonambi/widgets/analysis.py
AnalysisDialog.update_evt_types
def update_evt_types(self): """Update the event types list when dialog is opened.""" self.event_types = self.parent.notes.annot.event_types self.idx_evt_type.clear() self.frequency['norm_evt_type'].clear() for ev in self.event_types: self.idx_evt_type.addItem(ev) self.frequency['norm_evt_type'].addItem(ev)
python
def update_evt_types(self): self.event_types = self.parent.notes.annot.event_types self.idx_evt_type.clear() self.frequency['norm_evt_type'].clear() for ev in self.event_types: self.idx_evt_type.addItem(ev) self.frequency['norm_evt_type'].addItem(ev)
[ "def", "update_evt_types", "(", "self", ")", ":", "self", ".", "event_types", "=", "self", ".", "parent", ".", "notes", ".", "annot", ".", "event_types", "self", ".", "idx_evt_type", ".", "clear", "(", ")", "self", ".", "frequency", "[", "'norm_evt_type'",...
Update the event types list when dialog is opened.
[ "Update", "the", "event", "types", "list", "when", "dialog", "is", "opened", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/analysis.py#L843-L850
24,980
wonambi-python/wonambi
wonambi/widgets/analysis.py
AnalysisDialog.toggle_concatenate
def toggle_concatenate(self): """Enable and disable concatenation options.""" if not (self.chunk['epoch'].isChecked() and self.lock_to_staging.get_value()): for i,j in zip([self.idx_chan, self.idx_cycle, self.idx_stage, self.idx_evt_type], [self.cat['chan'], self.cat['cycle'], self.cat['stage'], self.cat['evt_type']]): if len(i.selectedItems()) > 1: j.setEnabled(True) else: j.setEnabled(False) j.setChecked(False) if not self.chunk['event'].isChecked(): self.cat['evt_type'].setEnabled(False) if not self.cat['discontinuous'].get_value(): self.cat['chan'].setEnabled(False) self.cat['chan'].setChecked(False) self.update_nseg()
python
def toggle_concatenate(self): if not (self.chunk['epoch'].isChecked() and self.lock_to_staging.get_value()): for i,j in zip([self.idx_chan, self.idx_cycle, self.idx_stage, self.idx_evt_type], [self.cat['chan'], self.cat['cycle'], self.cat['stage'], self.cat['evt_type']]): if len(i.selectedItems()) > 1: j.setEnabled(True) else: j.setEnabled(False) j.setChecked(False) if not self.chunk['event'].isChecked(): self.cat['evt_type'].setEnabled(False) if not self.cat['discontinuous'].get_value(): self.cat['chan'].setEnabled(False) self.cat['chan'].setChecked(False) self.update_nseg()
[ "def", "toggle_concatenate", "(", "self", ")", ":", "if", "not", "(", "self", ".", "chunk", "[", "'epoch'", "]", ".", "isChecked", "(", ")", "and", "self", ".", "lock_to_staging", ".", "get_value", "(", ")", ")", ":", "for", "i", ",", "j", "in", "z...
Enable and disable concatenation options.
[ "Enable", "and", "disable", "concatenation", "options", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/analysis.py#L934-L955
24,981
wonambi-python/wonambi
wonambi/widgets/analysis.py
AnalysisDialog.toggle_pac
def toggle_pac(self): """Enable and disable PAC options.""" if Pac is not None: pac_on = self.pac['pac_on'].get_value() self.pac['prep'].setEnabled(pac_on) self.pac['box_metric'].setEnabled(pac_on) self.pac['box_complex'].setEnabled(pac_on) self.pac['box_surro'].setEnabled(pac_on) self.pac['box_opts'].setEnabled(pac_on) if not pac_on: self.pac['prep'].set_value(False) if Pac is not None and pac_on: pac = self.pac hilb_on = pac['hilbert_on'].isChecked() wav_on = pac['wavelet_on'].isChecked() for button in pac['hilbert'].values(): button[0].setEnabled(hilb_on) if button[1] is not None: button[1].setEnabled(hilb_on) pac['wav_width'][0].setEnabled(wav_on) pac['wav_width'][1].setEnabled(wav_on) if pac['metric'].get_value() in [ 'Kullback-Leibler Distance', 'Heights ratio']: pac['nbin'][0].setEnabled(True) pac['nbin'][1].setEnabled(True) else: pac['nbin'][0].setEnabled(False) pac['nbin'][1].setEnabled(False) if pac['metric'] == 'ndPac': for button in pac['surro'].values(): button[0].setEnabled(False) if button[1] is not None: button[1].setEnabled(False) pac['surro']['pval'][0].setEnabled(True) ndpac_on = pac['metric'].get_value() == 'ndPac' surro_on = logical_and(pac['surro_method'].get_value() != '' 'No surrogates', not ndpac_on) norm_on = pac['surro_norm'].get_value() != 'No normalization' blocks_on = 'across time' in pac['surro_method'].get_value() pac['surro_method'].setEnabled(not ndpac_on) for button in pac['surro'].values(): button[0].setEnabled(surro_on and norm_on) if button[1] is not None: button[1].setEnabled(surro_on and norm_on) pac['surro']['nblocks'][0].setEnabled(blocks_on) pac['surro']['nblocks'][1].setEnabled(blocks_on) if ndpac_on: pac['surro_method'].set_value('No surrogates') pac['surro']['pval'][0].setEnabled(True)
python
def toggle_pac(self): if Pac is not None: pac_on = self.pac['pac_on'].get_value() self.pac['prep'].setEnabled(pac_on) self.pac['box_metric'].setEnabled(pac_on) self.pac['box_complex'].setEnabled(pac_on) self.pac['box_surro'].setEnabled(pac_on) self.pac['box_opts'].setEnabled(pac_on) if not pac_on: self.pac['prep'].set_value(False) if Pac is not None and pac_on: pac = self.pac hilb_on = pac['hilbert_on'].isChecked() wav_on = pac['wavelet_on'].isChecked() for button in pac['hilbert'].values(): button[0].setEnabled(hilb_on) if button[1] is not None: button[1].setEnabled(hilb_on) pac['wav_width'][0].setEnabled(wav_on) pac['wav_width'][1].setEnabled(wav_on) if pac['metric'].get_value() in [ 'Kullback-Leibler Distance', 'Heights ratio']: pac['nbin'][0].setEnabled(True) pac['nbin'][1].setEnabled(True) else: pac['nbin'][0].setEnabled(False) pac['nbin'][1].setEnabled(False) if pac['metric'] == 'ndPac': for button in pac['surro'].values(): button[0].setEnabled(False) if button[1] is not None: button[1].setEnabled(False) pac['surro']['pval'][0].setEnabled(True) ndpac_on = pac['metric'].get_value() == 'ndPac' surro_on = logical_and(pac['surro_method'].get_value() != '' 'No surrogates', not ndpac_on) norm_on = pac['surro_norm'].get_value() != 'No normalization' blocks_on = 'across time' in pac['surro_method'].get_value() pac['surro_method'].setEnabled(not ndpac_on) for button in pac['surro'].values(): button[0].setEnabled(surro_on and norm_on) if button[1] is not None: button[1].setEnabled(surro_on and norm_on) pac['surro']['nblocks'][0].setEnabled(blocks_on) pac['surro']['nblocks'][1].setEnabled(blocks_on) if ndpac_on: pac['surro_method'].set_value('No surrogates') pac['surro']['pval'][0].setEnabled(True)
[ "def", "toggle_pac", "(", "self", ")", ":", "if", "Pac", "is", "not", "None", ":", "pac_on", "=", "self", ".", "pac", "[", "'pac_on'", "]", ".", "get_value", "(", ")", "self", ".", "pac", "[", "'prep'", "]", ".", "setEnabled", "(", "pac_on", ")", ...
Enable and disable PAC options.
[ "Enable", "and", "disable", "PAC", "options", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/analysis.py#L1043-L1098
24,982
wonambi-python/wonambi
wonambi/widgets/analysis.py
AnalysisDialog.update_nseg
def update_nseg(self): """Update the number of segments, displayed in the dialog.""" self.nseg = 0 if self.one_grp: segments = self.get_segments() if segments is not None: self.nseg = len(segments) self.show_nseg.setText('Number of segments: ' + str(self.nseg)) times = [t for seg in segments for t in seg['times']] self.parent.overview.mark_poi(times) else: self.show_nseg.setText('No valid segments') self.toggle_freq()
python
def update_nseg(self): self.nseg = 0 if self.one_grp: segments = self.get_segments() if segments is not None: self.nseg = len(segments) self.show_nseg.setText('Number of segments: ' + str(self.nseg)) times = [t for seg in segments for t in seg['times']] self.parent.overview.mark_poi(times) else: self.show_nseg.setText('No valid segments') self.toggle_freq()
[ "def", "update_nseg", "(", "self", ")", ":", "self", ".", "nseg", "=", "0", "if", "self", ".", "one_grp", ":", "segments", "=", "self", ".", "get_segments", "(", ")", "if", "segments", "is", "not", "None", ":", "self", ".", "nseg", "=", "len", "(",...
Update the number of segments, displayed in the dialog.
[ "Update", "the", "number", "of", "segments", "displayed", "in", "the", "dialog", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/analysis.py#L1123-L1138
24,983
wonambi-python/wonambi
wonambi/widgets/analysis.py
AnalysisDialog.check_all_local
def check_all_local(self): """Check or uncheck all local event parameters.""" all_local_chk = self.event['global']['all_local'].isChecked() for buttons in self.event['local'].values(): buttons[0].setChecked(all_local_chk) buttons[1].setEnabled(buttons[0].isChecked())
python
def check_all_local(self): all_local_chk = self.event['global']['all_local'].isChecked() for buttons in self.event['local'].values(): buttons[0].setChecked(all_local_chk) buttons[1].setEnabled(buttons[0].isChecked())
[ "def", "check_all_local", "(", "self", ")", ":", "all_local_chk", "=", "self", ".", "event", "[", "'global'", "]", "[", "'all_local'", "]", ".", "isChecked", "(", ")", "for", "buttons", "in", "self", ".", "event", "[", "'local'", "]", ".", "values", "(...
Check or uncheck all local event parameters.
[ "Check", "or", "uncheck", "all", "local", "event", "parameters", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/analysis.py#L1140-L1145
24,984
wonambi-python/wonambi
wonambi/widgets/analysis.py
AnalysisDialog.check_all_local_prep
def check_all_local_prep(self): """Check or uncheck all enabled event pre-processing.""" all_local_pp_chk = self.event['global']['all_local_prep'].isChecked() for buttons in self.event['local'].values(): if buttons[1].isEnabled(): buttons[1].setChecked(all_local_pp_chk)
python
def check_all_local_prep(self): all_local_pp_chk = self.event['global']['all_local_prep'].isChecked() for buttons in self.event['local'].values(): if buttons[1].isEnabled(): buttons[1].setChecked(all_local_pp_chk)
[ "def", "check_all_local_prep", "(", "self", ")", ":", "all_local_pp_chk", "=", "self", ".", "event", "[", "'global'", "]", "[", "'all_local_prep'", "]", ".", "isChecked", "(", ")", "for", "buttons", "in", "self", ".", "event", "[", "'local'", "]", ".", "...
Check or uncheck all enabled event pre-processing.
[ "Check", "or", "uncheck", "all", "enabled", "event", "pre", "-", "processing", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/analysis.py#L1147-L1152
24,985
wonambi-python/wonambi
wonambi/widgets/analysis.py
AnalysisDialog.uncheck_all_local
def uncheck_all_local(self): """Uncheck 'all local' box when a local event is unchecked.""" for buttons in self.event['local'].values(): if not buttons[0].get_value(): self.event['global']['all_local'].setChecked(False) if buttons[1].isEnabled() and not buttons[1].get_value(): self.event['global']['all_local_prep'].setChecked(False)
python
def uncheck_all_local(self): for buttons in self.event['local'].values(): if not buttons[0].get_value(): self.event['global']['all_local'].setChecked(False) if buttons[1].isEnabled() and not buttons[1].get_value(): self.event['global']['all_local_prep'].setChecked(False)
[ "def", "uncheck_all_local", "(", "self", ")", ":", "for", "buttons", "in", "self", ".", "event", "[", "'local'", "]", ".", "values", "(", ")", ":", "if", "not", "buttons", "[", "0", "]", ".", "get_value", "(", ")", ":", "self", ".", "event", "[", ...
Uncheck 'all local' box when a local event is unchecked.
[ "Uncheck", "all", "local", "box", "when", "a", "local", "event", "is", "unchecked", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/analysis.py#L1154-L1160
24,986
wonambi-python/wonambi
wonambi/widgets/analysis.py
AnalysisDialog.get_segments
def get_segments(self): """Get segments for analysis. Creates instance of trans.Segments.""" # Chunking chunk = {k: v.isChecked() for k, v in self.chunk.items()} lock_to_staging = self.lock_to_staging.get_value() epoch_dur = self.epoch_param['dur'].get_value() epoch_overlap = self.epoch_param['overlap_val'].value() epoch_step = None epoch = None if chunk['epoch']: if lock_to_staging: epoch = 'locked' else: epoch = 'unlocked' if self.epoch_param['step'].isChecked(): epoch_step = self.epoch_param['step_val'].get_value() if epoch_step <= 0: epoch_step = 0.1 # Which channel(s) self.chan = self.get_channels() # chan name without group if not self.chan: return # Which event type(s) chan_full = None evt_type = None if chunk['event']: if self.evt_chan_only.get_value(): chan_full = [i + ' (' + self.idx_group.currentText() + '' ')' for i in self.chan] evt_type = self.idx_evt_type.selectedItems() if not evt_type: return else: evt_type = [x.text() for x in evt_type] # Which cycle(s) cycle = self.cycle = self.get_cycles() # Which stage(s) stage = self.idx_stage.selectedItems() if not stage: stage = self.stage = None else: stage = self.stage = [ x.text() for x in self.idx_stage.selectedItems()] # Concatenation cat = {k: v.get_value() for k, v in self.cat.items()} cat = (int(cat['cycle']), int(cat['stage']), int(cat['discontinuous']), int(cat['evt_type'])) # Artefact event rejection reject_event = self.reject_event.get_value() if reject_event == 'channel-specific': chan_full = [i + ' (' + self.idx_group.currentText() + '' ')' for i in self.chan] reject_artf = True elif reject_event == 'from any channel': reject_artf = True else: reject_artf = False # Other options min_dur = self.min_dur.get_value() reject_epoch = self.reject_epoch.get_value() # Generate title for summary plot self.title = self.make_title(chan_full, cycle, stage, evt_type) segments = fetch(self.parent.info.dataset, self.parent.notes.annot, cat=cat, evt_type=evt_type, stage=stage, cycle=cycle, chan_full=chan_full, epoch=epoch, epoch_dur=epoch_dur, epoch_overlap=epoch_overlap, epoch_step=epoch_step, reject_epoch=reject_epoch, reject_artf=reject_artf, min_dur=min_dur) return segments
python
def get_segments(self): # Chunking chunk = {k: v.isChecked() for k, v in self.chunk.items()} lock_to_staging = self.lock_to_staging.get_value() epoch_dur = self.epoch_param['dur'].get_value() epoch_overlap = self.epoch_param['overlap_val'].value() epoch_step = None epoch = None if chunk['epoch']: if lock_to_staging: epoch = 'locked' else: epoch = 'unlocked' if self.epoch_param['step'].isChecked(): epoch_step = self.epoch_param['step_val'].get_value() if epoch_step <= 0: epoch_step = 0.1 # Which channel(s) self.chan = self.get_channels() # chan name without group if not self.chan: return # Which event type(s) chan_full = None evt_type = None if chunk['event']: if self.evt_chan_only.get_value(): chan_full = [i + ' (' + self.idx_group.currentText() + '' ')' for i in self.chan] evt_type = self.idx_evt_type.selectedItems() if not evt_type: return else: evt_type = [x.text() for x in evt_type] # Which cycle(s) cycle = self.cycle = self.get_cycles() # Which stage(s) stage = self.idx_stage.selectedItems() if not stage: stage = self.stage = None else: stage = self.stage = [ x.text() for x in self.idx_stage.selectedItems()] # Concatenation cat = {k: v.get_value() for k, v in self.cat.items()} cat = (int(cat['cycle']), int(cat['stage']), int(cat['discontinuous']), int(cat['evt_type'])) # Artefact event rejection reject_event = self.reject_event.get_value() if reject_event == 'channel-specific': chan_full = [i + ' (' + self.idx_group.currentText() + '' ')' for i in self.chan] reject_artf = True elif reject_event == 'from any channel': reject_artf = True else: reject_artf = False # Other options min_dur = self.min_dur.get_value() reject_epoch = self.reject_epoch.get_value() # Generate title for summary plot self.title = self.make_title(chan_full, cycle, stage, evt_type) segments = fetch(self.parent.info.dataset, self.parent.notes.annot, cat=cat, evt_type=evt_type, stage=stage, cycle=cycle, chan_full=chan_full, epoch=epoch, epoch_dur=epoch_dur, epoch_overlap=epoch_overlap, epoch_step=epoch_step, reject_epoch=reject_epoch, reject_artf=reject_artf, min_dur=min_dur) return segments
[ "def", "get_segments", "(", "self", ")", ":", "# Chunking", "chunk", "=", "{", "k", ":", "v", ".", "isChecked", "(", ")", "for", "k", ",", "v", "in", "self", ".", "chunk", ".", "items", "(", ")", "}", "lock_to_staging", "=", "self", ".", "lock_to_s...
Get segments for analysis. Creates instance of trans.Segments.
[ "Get", "segments", "for", "analysis", ".", "Creates", "instance", "of", "trans", ".", "Segments", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/analysis.py#L1391-L1476
24,987
wonambi-python/wonambi
wonambi/widgets/analysis.py
AnalysisDialog.transform_data
def transform_data(self, data): """Apply pre-processing transformation to data, and add it to data dict. Parameters --------- data : instance of Segments segments including 'data' (ChanTime) Returns ------- instance of Segments same object with transformed data as 'trans_data' (ChanTime) """ trans = self.trans differ = trans['diff'].get_value() bandpass = trans['bandpass'].get_value() notch1 = trans['notch1'].get_value() notch2 = trans['notch2'].get_value() for seg in data: dat = seg['data'] if differ: dat = math(dat, operator=diff, axis='time') if bandpass != 'none': order = trans['bp']['order'][1].get_value() f1 = trans['bp']['f1'][1].get_value() f2 = trans['bp']['f2'][1].get_value() if f1 == '': f1 = None if f2 == '': f2 = None dat = filter_(dat, low_cut=f1, high_cut=f2, order=order, ftype=bandpass) if notch1 != 'none': order = trans['n1']['order'][1].get_value() cf = trans['n1']['cf'][1].get_value() hbw = trans['n1']['bw'][1].get_value() / 2.0 lo_pass = cf - hbw hi_pass = cf + hbw dat = filter_(dat, low_cut=hi_pass, order=order, ftype=notch1) dat = filter_(dat, high_cut=lo_pass, order=order, ftype=notch1) if notch2 != 'none': order = trans['n2']['order'][1].get_value() cf = trans['n2']['cf'][1].get_value() hbw = trans['n2']['bw'][1].get_value() / 2.0 lo_pass = cf - hbw hi_pass = cf + hbw dat = filter_(dat, low_cut=hi_pass, order=order, ftype=notch1) dat = filter_(dat, high_cut=lo_pass, order=order, ftype=notch1) seg['trans_data'] = dat return data
python
def transform_data(self, data): trans = self.trans differ = trans['diff'].get_value() bandpass = trans['bandpass'].get_value() notch1 = trans['notch1'].get_value() notch2 = trans['notch2'].get_value() for seg in data: dat = seg['data'] if differ: dat = math(dat, operator=diff, axis='time') if bandpass != 'none': order = trans['bp']['order'][1].get_value() f1 = trans['bp']['f1'][1].get_value() f2 = trans['bp']['f2'][1].get_value() if f1 == '': f1 = None if f2 == '': f2 = None dat = filter_(dat, low_cut=f1, high_cut=f2, order=order, ftype=bandpass) if notch1 != 'none': order = trans['n1']['order'][1].get_value() cf = trans['n1']['cf'][1].get_value() hbw = trans['n1']['bw'][1].get_value() / 2.0 lo_pass = cf - hbw hi_pass = cf + hbw dat = filter_(dat, low_cut=hi_pass, order=order, ftype=notch1) dat = filter_(dat, high_cut=lo_pass, order=order, ftype=notch1) if notch2 != 'none': order = trans['n2']['order'][1].get_value() cf = trans['n2']['cf'][1].get_value() hbw = trans['n2']['bw'][1].get_value() / 2.0 lo_pass = cf - hbw hi_pass = cf + hbw dat = filter_(dat, low_cut=hi_pass, order=order, ftype=notch1) dat = filter_(dat, high_cut=lo_pass, order=order, ftype=notch1) seg['trans_data'] = dat return data
[ "def", "transform_data", "(", "self", ",", "data", ")", ":", "trans", "=", "self", ".", "trans", "differ", "=", "trans", "[", "'diff'", "]", ".", "get_value", "(", ")", "bandpass", "=", "trans", "[", "'bandpass'", "]", ".", "get_value", "(", ")", "no...
Apply pre-processing transformation to data, and add it to data dict. Parameters --------- data : instance of Segments segments including 'data' (ChanTime) Returns ------- instance of Segments same object with transformed data as 'trans_data' (ChanTime)
[ "Apply", "pre", "-", "processing", "transformation", "to", "data", "and", "add", "it", "to", "data", "dict", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/analysis.py#L1478-L1537
24,988
wonambi-python/wonambi
wonambi/widgets/analysis.py
AnalysisDialog.save_as
def save_as(self): """Dialog for getting name, location of data export file.""" filename = splitext( self.parent.notes.annot.xml_file)[0] + '_data' filename, _ = QFileDialog.getSaveFileName(self, 'Export analysis data', filename, 'CSV (*.csv)') if filename == '': return self.filename = filename short_filename = short_strings(basename(self.filename)) self.idx_filename.setText(short_filename)
python
def save_as(self): filename = splitext( self.parent.notes.annot.xml_file)[0] + '_data' filename, _ = QFileDialog.getSaveFileName(self, 'Export analysis data', filename, 'CSV (*.csv)') if filename == '': return self.filename = filename short_filename = short_strings(basename(self.filename)) self.idx_filename.setText(short_filename)
[ "def", "save_as", "(", "self", ")", ":", "filename", "=", "splitext", "(", "self", ".", "parent", ".", "notes", ".", "annot", ".", "xml_file", ")", "[", "0", "]", "+", "'_data'", "filename", ",", "_", "=", "QFileDialog", ".", "getSaveFileName", "(", ...
Dialog for getting name, location of data export file.
[ "Dialog", "for", "getting", "name", "location", "of", "data", "export", "file", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/analysis.py#L1539-L1551
24,989
wonambi-python/wonambi
wonambi/widgets/analysis.py
AnalysisDialog.plot_freq
def plot_freq(self, x, y, title='', ylabel=None, scale='semilogy'): """Plot mean frequency spectrum and display in dialog. Parameters ---------- x : list vector with frequencies y : ndarray vector with amplitudes title : str plot title ylabel : str plot y label scale : str semilogy, loglog or linear """ freq = self.frequency scaling = freq['scaling'].get_value() if ylabel is None: if freq['complex'].get_value(): ylabel = 'Amplitude (uV)' elif 'power' == scaling: ylabel = 'Power spectral density (uV ** 2 / Hz)' elif 'energy' == scaling: ylabel = 'Energy spectral density (uV ** 2)' self.parent.plot_dialog = PlotDialog(self.parent) self.parent.plot_dialog.canvas.plot(x, y, title, ylabel, scale=scale) self.parent.show_plot_dialog()
python
def plot_freq(self, x, y, title='', ylabel=None, scale='semilogy'): freq = self.frequency scaling = freq['scaling'].get_value() if ylabel is None: if freq['complex'].get_value(): ylabel = 'Amplitude (uV)' elif 'power' == scaling: ylabel = 'Power spectral density (uV ** 2 / Hz)' elif 'energy' == scaling: ylabel = 'Energy spectral density (uV ** 2)' self.parent.plot_dialog = PlotDialog(self.parent) self.parent.plot_dialog.canvas.plot(x, y, title, ylabel, scale=scale) self.parent.show_plot_dialog()
[ "def", "plot_freq", "(", "self", ",", "x", ",", "y", ",", "title", "=", "''", ",", "ylabel", "=", "None", ",", "scale", "=", "'semilogy'", ")", ":", "freq", "=", "self", ".", "frequency", "scaling", "=", "freq", "[", "'scaling'", "]", ".", "get_val...
Plot mean frequency spectrum and display in dialog. Parameters ---------- x : list vector with frequencies y : ndarray vector with amplitudes title : str plot title ylabel : str plot y label scale : str semilogy, loglog or linear
[ "Plot", "mean", "frequency", "spectrum", "and", "display", "in", "dialog", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/analysis.py#L1880-L1909
24,990
wonambi-python/wonambi
wonambi/widgets/analysis.py
AnalysisDialog.export_pac
def export_pac(self, xpac, fpha, famp, desc): """Write PAC analysis data to CSV.""" filename = splitext(self.filename)[0] + '_pac.csv' heading_row_1 = ['Segment index', 'Start time', 'End time', 'Duration', 'Stitch', 'Stage', 'Cycle', 'Event type', 'Channel', ] spacer = [''] * (len(heading_row_1) - 1) heading_row_2 = [] for fp in fpha: fp_str = str(fp[0]) + '-' + str(fp[1]) for fa in famp: fa_str = str(fa[0]) + '-' + str(fa[1]) heading_row_2.append(fp_str + '_' + fa_str + '_pac') if 'pval' in xpac[list(xpac.keys())[0]].keys(): heading_row_3 = [x[:-4] + '_pval' for x in heading_row_2] heading_row_2.extend(heading_row_3) with open(filename, 'w', newline='') as f: lg.info('Writing to ' + str(filename)) csv_file = writer(f) csv_file.writerow(['Wonambi v{}'.format(__version__)]) csv_file.writerow(heading_row_1 + heading_row_2) csv_file.writerow(['Mean'] + spacer + list(desc['mean'])) csv_file.writerow(['SD'] + spacer + list(desc['sd'])) csv_file.writerow(['Mean of ln'] + spacer + list(desc['mean_log'])) csv_file.writerow(['SD of ln'] + spacer + list(desc['sd_log'])) idx = 0 for chan in xpac.keys(): for i, j in enumerate(xpac[chan]['times']): idx += 1 cyc = None if xpac[chan]['cycle'][i] is not None: cyc = xpac[chan]['cycle'][i][2] data_row = list(ravel(xpac[chan]['data'][i, :, :])) pval_row = [] if 'pval' in xpac[chan]: pval_row = list(ravel(xpac[chan]['pval'][i, :, :])) csv_file.writerow([idx, j[0], j[1], xpac[chan]['duration'][i], xpac[chan]['n_stitch'][i], xpac[chan]['stage'][i], cyc, xpac[chan]['name'][i], chan, ] + data_row + pval_row)
python
def export_pac(self, xpac, fpha, famp, desc): filename = splitext(self.filename)[0] + '_pac.csv' heading_row_1 = ['Segment index', 'Start time', 'End time', 'Duration', 'Stitch', 'Stage', 'Cycle', 'Event type', 'Channel', ] spacer = [''] * (len(heading_row_1) - 1) heading_row_2 = [] for fp in fpha: fp_str = str(fp[0]) + '-' + str(fp[1]) for fa in famp: fa_str = str(fa[0]) + '-' + str(fa[1]) heading_row_2.append(fp_str + '_' + fa_str + '_pac') if 'pval' in xpac[list(xpac.keys())[0]].keys(): heading_row_3 = [x[:-4] + '_pval' for x in heading_row_2] heading_row_2.extend(heading_row_3) with open(filename, 'w', newline='') as f: lg.info('Writing to ' + str(filename)) csv_file = writer(f) csv_file.writerow(['Wonambi v{}'.format(__version__)]) csv_file.writerow(heading_row_1 + heading_row_2) csv_file.writerow(['Mean'] + spacer + list(desc['mean'])) csv_file.writerow(['SD'] + spacer + list(desc['sd'])) csv_file.writerow(['Mean of ln'] + spacer + list(desc['mean_log'])) csv_file.writerow(['SD of ln'] + spacer + list(desc['sd_log'])) idx = 0 for chan in xpac.keys(): for i, j in enumerate(xpac[chan]['times']): idx += 1 cyc = None if xpac[chan]['cycle'][i] is not None: cyc = xpac[chan]['cycle'][i][2] data_row = list(ravel(xpac[chan]['data'][i, :, :])) pval_row = [] if 'pval' in xpac[chan]: pval_row = list(ravel(xpac[chan]['pval'][i, :, :])) csv_file.writerow([idx, j[0], j[1], xpac[chan]['duration'][i], xpac[chan]['n_stitch'][i], xpac[chan]['stage'][i], cyc, xpac[chan]['name'][i], chan, ] + data_row + pval_row)
[ "def", "export_pac", "(", "self", ",", "xpac", ",", "fpha", ",", "famp", ",", "desc", ")", ":", "filename", "=", "splitext", "(", "self", ".", "filename", ")", "[", "0", "]", "+", "'_pac.csv'", "heading_row_1", "=", "[", "'Segment index'", ",", "'Start...
Write PAC analysis data to CSV.
[ "Write", "PAC", "analysis", "data", "to", "CSV", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/analysis.py#L2135-L2198
24,991
wonambi-python/wonambi
wonambi/widgets/analysis.py
AnalysisDialog.compute_evt_params
def compute_evt_params(self): """Compute event parameters.""" ev = self.event glob = {k: v.get_value() for k, v in ev['global'].items()} params = {k: v[0].get_value() for k, v in ev['local'].items()} prep = {k: v[1].get_value() for k, v in ev['local'].items()} slopes = {k: v.get_value() for k, v in ev['sw'].items()} f1 = ev['f1'].get_value() f2 = ev['f2'].get_value() if not f2: f2 = None band = (f1, f2) if not (slopes['avg_slope'] or slopes['max_slope']): slopes = None evt_dat = event_params(self.data, params, band=band, slopes=slopes, prep=prep, parent=self) count = None density = None if glob['count']: count = len(self.data) if glob['density']: epoch_dur = glob['density_per'] # get period of interest based on stage and cycle selection poi = get_times(self.parent.notes.annot, stage=self.stage, cycle=self.cycle, exclude=True) total_dur = sum([x[1] - x[0] for y in poi for x in y['times']]) density = len(self.data) / (total_dur / epoch_dur) return evt_dat, count, density
python
def compute_evt_params(self): ev = self.event glob = {k: v.get_value() for k, v in ev['global'].items()} params = {k: v[0].get_value() for k, v in ev['local'].items()} prep = {k: v[1].get_value() for k, v in ev['local'].items()} slopes = {k: v.get_value() for k, v in ev['sw'].items()} f1 = ev['f1'].get_value() f2 = ev['f2'].get_value() if not f2: f2 = None band = (f1, f2) if not (slopes['avg_slope'] or slopes['max_slope']): slopes = None evt_dat = event_params(self.data, params, band=band, slopes=slopes, prep=prep, parent=self) count = None density = None if glob['count']: count = len(self.data) if glob['density']: epoch_dur = glob['density_per'] # get period of interest based on stage and cycle selection poi = get_times(self.parent.notes.annot, stage=self.stage, cycle=self.cycle, exclude=True) total_dur = sum([x[1] - x[0] for y in poi for x in y['times']]) density = len(self.data) / (total_dur / epoch_dur) return evt_dat, count, density
[ "def", "compute_evt_params", "(", "self", ")", ":", "ev", "=", "self", ".", "event", "glob", "=", "{", "k", ":", "v", ".", "get_value", "(", ")", "for", "k", ",", "v", "in", "ev", "[", "'global'", "]", ".", "items", "(", ")", "}", "params", "="...
Compute event parameters.
[ "Compute", "event", "parameters", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/analysis.py#L2200-L2231
24,992
wonambi-python/wonambi
wonambi/widgets/analysis.py
AnalysisDialog.make_title
def make_title(self, chan, cycle, stage, evt_type): """Make a title for plots, etc.""" cyc_str = None if cycle is not None: cyc_str = [str(c[2]) for c in cycle] cyc_str[0] = 'cycle ' + cyc_str[0] title = [' + '.join([str(x) for x in y]) for y in [chan, cyc_str, stage, evt_type] if y is not None] return ', '.join(title)
python
def make_title(self, chan, cycle, stage, evt_type): cyc_str = None if cycle is not None: cyc_str = [str(c[2]) for c in cycle] cyc_str[0] = 'cycle ' + cyc_str[0] title = [' + '.join([str(x) for x in y]) for y in [chan, cyc_str, stage, evt_type] if y is not None] return ', '.join(title)
[ "def", "make_title", "(", "self", ",", "chan", ",", "cycle", ",", "stage", ",", "evt_type", ")", ":", "cyc_str", "=", "None", "if", "cycle", "is", "not", "None", ":", "cyc_str", "=", "[", "str", "(", "c", "[", "2", "]", ")", "for", "c", "in", "...
Make a title for plots, etc.
[ "Make", "a", "title", "for", "plots", "etc", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/analysis.py#L2233-L2243
24,993
wonambi-python/wonambi
wonambi/widgets/analysis.py
PlotCanvas.plot
def plot(self, x, y, title, ylabel, scale='semilogy', idx_lim=(1, -1)): """Plot the data. Parameters ---------- x : ndarray vector with frequencies y : ndarray vector with amplitudes title : str title of the plot, to appear above it ylabel : str label for the y-axis scale : str 'log y-axis', 'log both axes' or 'linear', to set axis scaling idx_lim : tuple of (int or None) indices of the data to plot. by default, the first value is left out, because of assymptotic tendencies near 0 Hz. """ x = x[slice(*idx_lim)] y = y[slice(*idx_lim)] ax = self.figure.add_subplot(111) ax.set_title(title) ax.set_xlabel('Frequency (Hz)') ax.set_ylabel(ylabel) if 'semilogy' == scale: ax.semilogy(x, y, 'r-') elif 'loglog' == scale: ax.loglog(x, y, 'r-') elif 'linear' == scale: ax.plot(x, y, 'r-')
python
def plot(self, x, y, title, ylabel, scale='semilogy', idx_lim=(1, -1)): x = x[slice(*idx_lim)] y = y[slice(*idx_lim)] ax = self.figure.add_subplot(111) ax.set_title(title) ax.set_xlabel('Frequency (Hz)') ax.set_ylabel(ylabel) if 'semilogy' == scale: ax.semilogy(x, y, 'r-') elif 'loglog' == scale: ax.loglog(x, y, 'r-') elif 'linear' == scale: ax.plot(x, y, 'r-')
[ "def", "plot", "(", "self", ",", "x", ",", "y", ",", "title", ",", "ylabel", ",", "scale", "=", "'semilogy'", ",", "idx_lim", "=", "(", "1", ",", "-", "1", ")", ")", ":", "x", "=", "x", "[", "slice", "(", "*", "idx_lim", ")", "]", "y", "=",...
Plot the data. Parameters ---------- x : ndarray vector with frequencies y : ndarray vector with amplitudes title : str title of the plot, to appear above it ylabel : str label for the y-axis scale : str 'log y-axis', 'log both axes' or 'linear', to set axis scaling idx_lim : tuple of (int or None) indices of the data to plot. by default, the first value is left out, because of assymptotic tendencies near 0 Hz.
[ "Plot", "the", "data", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/analysis.py#L2262-L2293
24,994
wonambi-python/wonambi
wonambi/widgets/analysis.py
PlotDialog.create_dialog
def create_dialog(self): """Create the basic dialog.""" self.bbox = QDialogButtonBox(QDialogButtonBox.Close) self.idx_close = self.bbox.button(QDialogButtonBox.Close) self.idx_close.pressed.connect(self.reject) btnlayout = QHBoxLayout() btnlayout.addStretch(1) btnlayout.addWidget(self.bbox) layout = QVBoxLayout() layout.addWidget(self.toolbar) layout.addWidget(self.canvas) layout.addLayout(btnlayout) layout.addStretch(1) self.setLayout(layout)
python
def create_dialog(self): self.bbox = QDialogButtonBox(QDialogButtonBox.Close) self.idx_close = self.bbox.button(QDialogButtonBox.Close) self.idx_close.pressed.connect(self.reject) btnlayout = QHBoxLayout() btnlayout.addStretch(1) btnlayout.addWidget(self.bbox) layout = QVBoxLayout() layout.addWidget(self.toolbar) layout.addWidget(self.canvas) layout.addLayout(btnlayout) layout.addStretch(1) self.setLayout(layout)
[ "def", "create_dialog", "(", "self", ")", ":", "self", ".", "bbox", "=", "QDialogButtonBox", "(", "QDialogButtonBox", ".", "Close", ")", "self", ".", "idx_close", "=", "self", ".", "bbox", ".", "button", "(", "QDialogButtonBox", ".", "Close", ")", "self", ...
Create the basic dialog.
[ "Create", "the", "basic", "dialog", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/analysis.py#L2310-L2325
24,995
wonambi-python/wonambi
wonambi/detect/arousal.py
make_arousals
def make_arousals(events, time, s_freq): """Create dict for each arousal, based on events of time points. Parameters ---------- events : ndarray (dtype='int') N x 5 matrix with start, 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 arousals, with information about start, end, duration (s), """ arousals = [] for ev in events: one_ar = {'start': time[ev[0]], 'end': time[ev[1] - 1], 'dur': (ev[1] - ev[0]) / s_freq, } arousals.append(one_ar) return arousals
python
def make_arousals(events, time, s_freq): arousals = [] for ev in events: one_ar = {'start': time[ev[0]], 'end': time[ev[1] - 1], 'dur': (ev[1] - ev[0]) / s_freq, } arousals.append(one_ar) return arousals
[ "def", "make_arousals", "(", "events", ",", "time", ",", "s_freq", ")", ":", "arousals", "=", "[", "]", "for", "ev", "in", "events", ":", "one_ar", "=", "{", "'start'", ":", "time", "[", "ev", "[", "0", "]", "]", ",", "'end'", ":", "time", "[", ...
Create dict for each arousal, based on events of time points. Parameters ---------- events : ndarray (dtype='int') N x 5 matrix with start, 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 arousals, with information about start, end, duration (s),
[ "Create", "dict", "for", "each", "arousal", "based", "on", "events", "of", "time", "points", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/detect/arousal.py#L233-L261
24,996
wonambi-python/wonambi
wonambi/dataset.py
_convert_time_to_sample
def _convert_time_to_sample(abs_time, dataset): """Convert absolute time into samples. Parameters ---------- abs_time : dat if it's int or float, it's assumed it's s; if it's timedelta, it's assumed from the start of the recording; if it's datetime, it's assumed it's absolute time. dataset : instance of wonambi.Dataset dataset to get sampling frequency and start time Returns ------- int sample (from the starting of the recording). """ if isinstance(abs_time, datetime): abs_time = abs_time - dataset.header['start_time'] if not isinstance(abs_time, timedelta): try: abs_time = timedelta(seconds=float(abs_time)) except TypeError as err: if isinstance(abs_time, int64): # timedelta and int64: http://bugs.python.org/issue5476 abs_time = timedelta(seconds=int(abs_time)) else: raise err sample = int(ceil(abs_time.total_seconds() * dataset.header['s_freq'])) return sample
python
def _convert_time_to_sample(abs_time, dataset): if isinstance(abs_time, datetime): abs_time = abs_time - dataset.header['start_time'] if not isinstance(abs_time, timedelta): try: abs_time = timedelta(seconds=float(abs_time)) except TypeError as err: if isinstance(abs_time, int64): # timedelta and int64: http://bugs.python.org/issue5476 abs_time = timedelta(seconds=int(abs_time)) else: raise err sample = int(ceil(abs_time.total_seconds() * dataset.header['s_freq'])) return sample
[ "def", "_convert_time_to_sample", "(", "abs_time", ",", "dataset", ")", ":", "if", "isinstance", "(", "abs_time", ",", "datetime", ")", ":", "abs_time", "=", "abs_time", "-", "dataset", ".", "header", "[", "'start_time'", "]", "if", "not", "isinstance", "(",...
Convert absolute time into samples. Parameters ---------- abs_time : dat if it's int or float, it's assumed it's s; if it's timedelta, it's assumed from the start of the recording; if it's datetime, it's assumed it's absolute time. dataset : instance of wonambi.Dataset dataset to get sampling frequency and start time Returns ------- int sample (from the starting of the recording).
[ "Convert", "absolute", "time", "into", "samples", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/dataset.py#L36-L67
24,997
wonambi-python/wonambi
wonambi/dataset.py
detect_format
def detect_format(filename): """Detect file format. Parameters ---------- filename : str or Path name of the filename or directory. Returns ------- class used to read the data. """ filename = Path(filename) if filename.is_dir(): if list(filename.glob('*.stc')) and list(filename.glob('*.erd')): return Ktlx elif (filename / 'patient.info').exists(): return Moberg elif (filename / 'info.xml').exists(): return EgiMff elif list(filename.glob('*.openephys')): return OpenEphys elif list(filename.glob('*.txt')): return Text else: raise UnrecognizedFormat('Unrecognized format for directory ' + str(filename)) else: if filename.suffix == '.won': return Wonambi if filename.suffix.lower() == '.trc': return Micromed if filename.suffix == '.set': return EEGLAB if filename.suffix == '.edf': return Edf if filename.suffix == '.abf': return Abf if filename.suffix == '.vhdr' or filename.suffix == '.eeg': return BrainVision if filename.suffix == '.dat': # very general try: _read_header_length(filename) except (AttributeError, ValueError): # there is no HeaderLen pass else: return BCI2000 with filename.open('rb') as f: file_header = f.read(8) if file_header in (b'NEURALCD', b'NEURALSG', b'NEURALEV'): return BlackRock elif file_header[:6] == b'MATLAB': # we might need to read more return FieldTrip if filename.suffix.lower() == '.txt': with filename.open('rt') as f: first_line = f.readline() if '.rr' in first_line[-4:]: return LyonRRI else: raise UnrecognizedFormat('Unrecognized format for file ' + str(filename))
python
def detect_format(filename): filename = Path(filename) if filename.is_dir(): if list(filename.glob('*.stc')) and list(filename.glob('*.erd')): return Ktlx elif (filename / 'patient.info').exists(): return Moberg elif (filename / 'info.xml').exists(): return EgiMff elif list(filename.glob('*.openephys')): return OpenEphys elif list(filename.glob('*.txt')): return Text else: raise UnrecognizedFormat('Unrecognized format for directory ' + str(filename)) else: if filename.suffix == '.won': return Wonambi if filename.suffix.lower() == '.trc': return Micromed if filename.suffix == '.set': return EEGLAB if filename.suffix == '.edf': return Edf if filename.suffix == '.abf': return Abf if filename.suffix == '.vhdr' or filename.suffix == '.eeg': return BrainVision if filename.suffix == '.dat': # very general try: _read_header_length(filename) except (AttributeError, ValueError): # there is no HeaderLen pass else: return BCI2000 with filename.open('rb') as f: file_header = f.read(8) if file_header in (b'NEURALCD', b'NEURALSG', b'NEURALEV'): return BlackRock elif file_header[:6] == b'MATLAB': # we might need to read more return FieldTrip if filename.suffix.lower() == '.txt': with filename.open('rt') as f: first_line = f.readline() if '.rr' in first_line[-4:]: return LyonRRI else: raise UnrecognizedFormat('Unrecognized format for file ' + str(filename))
[ "def", "detect_format", "(", "filename", ")", ":", "filename", "=", "Path", "(", "filename", ")", "if", "filename", ".", "is_dir", "(", ")", ":", "if", "list", "(", "filename", ".", "glob", "(", "'*.stc'", ")", ")", "and", "list", "(", "filename", "....
Detect file format. Parameters ---------- filename : str or Path name of the filename or directory. Returns ------- class used to read the data.
[ "Detect", "file", "format", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/dataset.py#L70-L142
24,998
wonambi-python/wonambi
wonambi/dataset.py
Dataset.read_videos
def read_videos(self, begtime=None, endtime=None): """Return list of videos with start and end times for a period. Parameters ---------- begtime : int or datedelta or datetime or list start of the data to read; if it's int, it's assumed it's s; if it's datedelta, it's assumed from the start of the recording; if it's datetime, it's assumed it's absolute time. It can also be a list of any of the above type. endtime : int or datedelta or datetime end of the data to read; if it's int, it's assumed it's s; if it's datedelta, it's assumed from the start of the recording; if it's datetime, it's assumed it's absolute time. It can also be a list of any of the above type. Returns ------- list of path list of absolute paths (as str) to the movie files float time in s from the beginning of the first movie when the part of interest starts float time in s from the beginning of the last movie when the part of interest ends Raises ------ OSError when there are no video files at all IndexError when there are video files, but the interval of interest is not in the list of files. """ if isinstance(begtime, datetime): begtime = begtime - self.header['start_time'] if isinstance(begtime, timedelta): begtime = begtime.total_seconds() if isinstance(endtime, datetime): endtime = endtime - self.header['start_time'] if isinstance(endtime, timedelta): endtime = endtime.total_seconds() videos = self.dataset.return_videos(begtime, endtime) """ try except AttributeError: lg.debug('This format does not have video') videos = None """ return videos
python
def read_videos(self, begtime=None, endtime=None): if isinstance(begtime, datetime): begtime = begtime - self.header['start_time'] if isinstance(begtime, timedelta): begtime = begtime.total_seconds() if isinstance(endtime, datetime): endtime = endtime - self.header['start_time'] if isinstance(endtime, timedelta): endtime = endtime.total_seconds() videos = self.dataset.return_videos(begtime, endtime) """ try except AttributeError: lg.debug('This format does not have video') videos = None """ return videos
[ "def", "read_videos", "(", "self", ",", "begtime", "=", "None", ",", "endtime", "=", "None", ")", ":", "if", "isinstance", "(", "begtime", ",", "datetime", ")", ":", "begtime", "=", "begtime", "-", "self", ".", "header", "[", "'start_time'", "]", "if",...
Return list of videos with start and end times for a period. Parameters ---------- begtime : int or datedelta or datetime or list start of the data to read; if it's int, it's assumed it's s; if it's datedelta, it's assumed from the start of the recording; if it's datetime, it's assumed it's absolute time. It can also be a list of any of the above type. endtime : int or datedelta or datetime end of the data to read; if it's int, it's assumed it's s; if it's datedelta, it's assumed from the start of the recording; if it's datetime, it's assumed it's absolute time. It can also be a list of any of the above type. Returns ------- list of path list of absolute paths (as str) to the movie files float time in s from the beginning of the first movie when the part of interest starts float time in s from the beginning of the last movie when the part of interest ends Raises ------ OSError when there are no video files at all IndexError when there are video files, but the interval of interest is not in the list of files.
[ "Return", "list", "of", "videos", "with", "start", "and", "end", "times", "for", "a", "period", "." ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/dataset.py#L219-L272
24,999
wonambi-python/wonambi
wonambi/dataset.py
Dataset.read_data
def read_data(self, chan=None, begtime=None, endtime=None, begsam=None, endsam=None, s_freq=None): """Read the data and creates a ChanTime instance Parameters ---------- chan : list of strings names of the channels to read begtime : int or datedelta or datetime or list start of the data to read; if it's int or float, it's assumed it's s; if it's timedelta, it's assumed from the start of the recording; if it's datetime, it's assumed it's absolute time. It can also be a list of any of the above type. endtime : int or datedelta or datetime end of the data to read; if it's int or float, it's assumed it's s; if it's timedelta, it's assumed from the start of the recording; if it's datetime, it's assumed it's absolute time. It can also be a list of any of the above type. begsam : int first sample (this sample will be included) endsam : int last sample (this sample will NOT be included) s_freq : int sampling frequency of the data Returns ------- An instance of ChanTime Notes ----- begsam and endsam follow Python convention, which starts at zero, includes begsam but DOES NOT include endsam. If begtime and endtime are a list, they both need the exact same length and the data will be stored in trials. If neither begtime or begsam are specified, it starts from the first sample. If neither endtime or endsam are specified, it reads until the end. """ data = ChanTime() data.start_time = self.header['start_time'] data.s_freq = s_freq = s_freq if s_freq else self.header['s_freq'] if chan is None: chan = self.header['chan_name'] if not (isinstance(chan, list) or isinstance(chan, tuple)): raise TypeError('Parameter "chan" should be a list') add_ref = False if '_REF' in chan: add_ref = True chan[:] = [x for x in chan if x != '_REF'] idx_chan = [self.header['chan_name'].index(x) for x in chan] if begtime is None and begsam is None: begsam = 0 if endtime is None and endsam is None: endsam = self.header['n_samples'] if begtime is not None: if not isinstance(begtime, list): begtime = [begtime] begsam = [] for one_begtime in begtime: begsam.append(_convert_time_to_sample(one_begtime, self)) if endtime is not None: if not isinstance(endtime, list): endtime = [endtime] endsam = [] for one_endtime in endtime: endsam.append(_convert_time_to_sample(one_endtime, self)) if not isinstance(begsam, list): begsam = [begsam] if not isinstance(endsam, list): endsam = [endsam] if len(begsam) != len(endsam): raise ValueError('There should be the same number of start and ' + 'end point') n_trl = len(begsam) data.axis['chan'] = empty(n_trl, dtype='O') data.axis['time'] = empty(n_trl, dtype='O') data.data = empty(n_trl, dtype='O') for i, one_begsam, one_endsam in zip(range(n_trl), begsam, endsam): dataset = self.dataset lg.debug('begsam {0: 6}, endsam {1: 6}'.format(one_begsam, one_endsam)) dat = dataset.return_dat(idx_chan, one_begsam, one_endsam) chan_in_dat = chan if add_ref: zero_ref = zeros((1, one_endsam - one_begsam)) dat = concatenate((dat, zero_ref), axis=0) chan_in_dat.append('_REF') data.data[i] = dat data.axis['chan'][i] = asarray(chan_in_dat, dtype='U') data.axis['time'][i] = (arange(one_begsam, one_endsam) / s_freq) return data
python
def read_data(self, chan=None, begtime=None, endtime=None, begsam=None, endsam=None, s_freq=None): data = ChanTime() data.start_time = self.header['start_time'] data.s_freq = s_freq = s_freq if s_freq else self.header['s_freq'] if chan is None: chan = self.header['chan_name'] if not (isinstance(chan, list) or isinstance(chan, tuple)): raise TypeError('Parameter "chan" should be a list') add_ref = False if '_REF' in chan: add_ref = True chan[:] = [x for x in chan if x != '_REF'] idx_chan = [self.header['chan_name'].index(x) for x in chan] if begtime is None and begsam is None: begsam = 0 if endtime is None and endsam is None: endsam = self.header['n_samples'] if begtime is not None: if not isinstance(begtime, list): begtime = [begtime] begsam = [] for one_begtime in begtime: begsam.append(_convert_time_to_sample(one_begtime, self)) if endtime is not None: if not isinstance(endtime, list): endtime = [endtime] endsam = [] for one_endtime in endtime: endsam.append(_convert_time_to_sample(one_endtime, self)) if not isinstance(begsam, list): begsam = [begsam] if not isinstance(endsam, list): endsam = [endsam] if len(begsam) != len(endsam): raise ValueError('There should be the same number of start and ' + 'end point') n_trl = len(begsam) data.axis['chan'] = empty(n_trl, dtype='O') data.axis['time'] = empty(n_trl, dtype='O') data.data = empty(n_trl, dtype='O') for i, one_begsam, one_endsam in zip(range(n_trl), begsam, endsam): dataset = self.dataset lg.debug('begsam {0: 6}, endsam {1: 6}'.format(one_begsam, one_endsam)) dat = dataset.return_dat(idx_chan, one_begsam, one_endsam) chan_in_dat = chan if add_ref: zero_ref = zeros((1, one_endsam - one_begsam)) dat = concatenate((dat, zero_ref), axis=0) chan_in_dat.append('_REF') data.data[i] = dat data.axis['chan'][i] = asarray(chan_in_dat, dtype='U') data.axis['time'][i] = (arange(one_begsam, one_endsam) / s_freq) return data
[ "def", "read_data", "(", "self", ",", "chan", "=", "None", ",", "begtime", "=", "None", ",", "endtime", "=", "None", ",", "begsam", "=", "None", ",", "endsam", "=", "None", ",", "s_freq", "=", "None", ")", ":", "data", "=", "ChanTime", "(", ")", ...
Read the data and creates a ChanTime instance Parameters ---------- chan : list of strings names of the channels to read begtime : int or datedelta or datetime or list start of the data to read; if it's int or float, it's assumed it's s; if it's timedelta, it's assumed from the start of the recording; if it's datetime, it's assumed it's absolute time. It can also be a list of any of the above type. endtime : int or datedelta or datetime end of the data to read; if it's int or float, it's assumed it's s; if it's timedelta, it's assumed from the start of the recording; if it's datetime, it's assumed it's absolute time. It can also be a list of any of the above type. begsam : int first sample (this sample will be included) endsam : int last sample (this sample will NOT be included) s_freq : int sampling frequency of the data Returns ------- An instance of ChanTime Notes ----- begsam and endsam follow Python convention, which starts at zero, includes begsam but DOES NOT include endsam. If begtime and endtime are a list, they both need the exact same length and the data will be stored in trials. If neither begtime or begsam are specified, it starts from the first sample. If neither endtime or endsam are specified, it reads until the end.
[ "Read", "the", "data", "and", "creates", "a", "ChanTime", "instance" ]
1d8e3d7e53df8017c199f703bcab582914676e76
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/dataset.py#L274-L379