Exemplo n.º 1
0
    def __init__(self,
                 experiment,
                 parent,
                 default_name,
                 handler,
                 batching=True,
                 title='Simple dialog'):
        QtWidgets.QDialog.__init__(self, parent)
        self.ui = Ui_SimpleDialog()
        self.ui.setupUi(self)

        self.parent = parent
        self.experiment = experiment
        self.handler = handler

        self.setWindowTitle('Meggie - ' + title)

        if batching:
            self.batching_widget = BatchingWidget(
                experiment_getter=self._experiment_getter,
                parent=self,
                container=self.ui.groupBoxBatching,
                geometry=self.ui.batchingWidgetPlaceholder.geometry())
            self.ui.gridLayoutBatching.addWidget(self.batching_widget, 0, 0, 1,
                                                 1)
        else:
            self.ui.groupBoxBatching.hide()
            self.ui.pushButtonBatch.hide()

        self.ui.lineEditName.setText(default_name)
Exemplo n.º 2
0
    def __init__(self, parent, experiment, handler):
        QtWidgets.QDialog.__init__(self, parent)
        self.ui = Ui_montageDialog()
        self.ui.setupUi(self)

        self.parent = parent
        self.experiment = experiment
        self.handler = handler

        montage_dir = pkg_resources.resource_filename(
            'mne', os.path.join('channels', 'data', 'montages'))

        for fname in sorted(os.listdir(montage_dir)):
            self.ui.comboBoxSelectFromList.addItem(fname)

        self.current_montage_fname = None
        self.ui.radioButtonMontageFromList.setChecked(True)

        # find out if montage already set.

        self.batching_widget = BatchingWidget(
            experiment_getter=self._experiment_getter,
            parent=self,
            container=self.ui.groupBoxBatching,
            geometry=self.ui.batchingWidgetPlaceholder.geometry())
        self.ui.gridLayoutBatching.addWidget(self.batching_widget, 0, 0, 1, 1)
    def __init__(self, experiment, parent, selected_spectrum, default_name,
                 handler):
        """
        """
        QtWidgets.QDialog.__init__(self, parent)
        self.ui = Ui_CreateReportDialog()
        self.ui.setupUi(self)

        self.parent = parent
        self.experiment = experiment
        self.handler = handler
        self.selected_spectrum = selected_spectrum

        # initialize frequency limits from spectrum data
        spectrum_item = experiment.active_subject.spectrum[selected_spectrum]
        minfreq = spectrum_item.freqs[0]
        maxfreq = spectrum_item.freqs[-1]
        self.ui.doubleSpinBoxFreqMin.setValue(minfreq)
        self.ui.doubleSpinBoxFreqMax.setValue(maxfreq)

        # add a general batching widget to dialog
        self.batching_widget = BatchingWidget(
            experiment_getter=self.experiment_getter,
            parent=self,
            container=self.ui.groupBoxBatching,
            geometry=self.ui.batchingWidgetPlaceholder.geometry())
        self.ui.gridLayoutBatching.addWidget(self.batching_widget, 0, 0, 1, 1)

        self.ui.lineEditName.setText(default_name)
Exemplo n.º 4
0
    def __init__(self, parent, experiment, handler):
        QtWidgets.QDialog.__init__(self, parent)
        self.ui = Ui_rereferencingDialog()
        self.ui.setupUi(self)

        self.experiment = experiment
        self.parent = parent
        self.handler = handler

        subject = self.experiment.active_subject
        raw = subject.get_raw()
        sfreq = raw.info['sfreq']

        # fill the combobox
        picks = mne.pick_types(raw.info, eeg=True, meg=False, eog=True)
        ch_names = [
            ch_name for ch_idx, ch_name in enumerate(raw.info['ch_names'])
            if ch_idx in picks
        ]

        for ch_name in ch_names:
            self.ui.comboBoxChannel.addItem(ch_name)

        self.batching_widget = BatchingWidget(
            experiment_getter=self._experiment_getter,
            parent=self,
            container=self.ui.groupBoxBatching,
            geometry=self.ui.batchingWidgetPlaceholder.geometry())
        self.ui.gridLayoutBatching.addWidget(self.batching_widget, 0, 0, 1, 1)
Exemplo n.º 5
0
    def __init__(self, parent, experiment):
        QtWidgets.QDialog.__init__(self, parent)
        self.ui = Ui_DialogFilter()
        self.ui.setupUi(self)

        self.parent = parent
        self.experiment = experiment

        self.batching_widget = BatchingWidget(
            experiment_getter=self.experiment_getter,
            parent=self,
            container=self.ui.groupBoxBatching,
            geometry=self.ui.batchingWidgetPlaceholder.geometry())
        self.ui.gridLayoutBatching.addWidget(self.batching_widget, 0, 0, 1, 1)
Exemplo n.º 6
0
    def __init__(self, experiment, parent, epoch_names, default_name):
        """
        """
        QtWidgets.QDialog.__init__(self, parent)
        self.ui = Ui_TFRDialog()
        self.ui.setupUi(self)

        self.parent = parent
        self.epoch_names = epoch_names
        self.experiment = experiment

        subject = experiment.active_subject
        epochs = subject.epochs[epoch_names[0]].content

        self.ui.lineEditEpochName.setText(', '.join(epoch_names))

        if epochs.info.get('highpass'):
            self.ui.doubleSpinBoxMinFreq.setValue(
                max(int(np.ceil(epochs.info['highpass'])),
                    self.ui.doubleSpinBoxMinFreq.value()))

        if epochs.info.get('lowpass'):
            self.ui.doubleSpinBoxMaxFreq.setValue(
                min(int(np.floor(epochs.info['lowpass'])),
                    self.ui.doubleSpinBoxMaxFreq.value()))

        epoch_length = epochs.times[-1] - epochs.times[0]

        # try to use as many cycles as possible
        # (window ~= 10 * (n_cycles / (2.0 * np.pi * freq))
        minfreq = self.ui.doubleSpinBoxMinFreq.value()
        n_cycles = epoch_length * 2.0 * np.pi * minfreq / 10.0
        n_cycles = max(np.floor(n_cycles), 1)

        self.ui.doubleSpinBoxNcycles.setValue(n_cycles)

        # select factor such that minfreq / factor = n_cycles,
        # and then ceil
        factor = np.ceil(minfreq / float(n_cycles))
        self.ui.doubleSpinBoxCycleFactor.setValue(factor)

        self.batching_widget = BatchingWidget(
            experiment_getter=self.experiment_getter,
            parent=self,
            container=self.ui.groupBoxBatching,
            geometry=self.ui.batchingWidgetPlaceholder.geometry())
        self.ui.gridLayoutBatching.addWidget(self.batching_widget, 0, 0, 1, 1)

        self.ui.lineEditTFRName.setText(default_name)
Exemplo n.º 7
0
    def __init__(self, experiment, parent, default_name):
        """
        """
        QtWidgets.QDialog.__init__(self, parent)
        self.ui = Ui_PowerSpectrumDialog()
        self.ui.setupUi(self)

        self.parent = parent
        self.experiment = experiment

        self.intervals = []

        raw = self.experiment.active_subject.get_raw()

        tmax = np.floor(raw.times[raw.n_times - 1]) - 0.1
        self.ui.doubleSpinBoxTmin.setValue(0)
        self.ui.doubleSpinBoxTmax.setValue(tmax)
        self.ui.doubleSpinBoxTmin.setMaximum(tmax)
        self.ui.doubleSpinBoxTmax.setMaximum(tmax)

        # set nfft initially to ~2 seconds and overlap to ~1 seconds
        sfreq = raw.info['sfreq']
        window_in_seconds = 2
        nfft = int(
            np.power(2,
                     np.ceil(np.log(sfreq * window_in_seconds) / np.log(2))))
        overlap = nfft / 2

        self.ui.spinBoxNfft.setValue(nfft)
        self.ui.spinBoxOverlap.setValue(overlap)

        if raw.info.get('highpass'):
            if self.ui.spinBoxFmin.value() < raw.info['highpass']:
                self.ui.spinBoxFmin.setValue(int(np.ceil(
                    raw.info['highpass'])))

        if raw.info.get('lowpass'):
            if self.ui.spinBoxFmax.value() > raw.info['lowpass']:
                self.ui.spinBoxFmax.setValue(int(raw.info['lowpass']))

        self.batching_widget = BatchingWidget(
            experiment_getter=self.experiment_getter,
            parent=self,
            container=self.ui.groupBoxBatching,
            geometry=self.ui.batchingWidgetPlaceholder.geometry())
        self.ui.gridLayoutBatching.addWidget(self.batching_widget, 0, 0, 1, 1)

        self.ui.lineEditName.setText(default_name)
    def __init__(self, experiment, parent, default_name, handler):
        QtWidgets.QDialog.__init__(self, parent)
        self.ui = Ui_CreateEpochsFromEventsDialog()
        self.ui.setupUi(self)

        self.parent = parent
        self.experiment = experiment
        self.handler = handler

        self.events = []

        self.batching_widget = BatchingWidget(
            experiment_getter=self._experiment_getter,
            parent=self,
            container=self.ui.groupBoxBatching,
            geometry=self.ui.batchingWidgetPlaceholder.geometry())
        self.ui.gridLayoutBatching.addWidget(self.batching_widget, 0, 0, 1, 1)

        self.ui.lineEditCollectionName.setText(default_name)
Exemplo n.º 9
0
    def __init__(self, experiment, parent, selected_epochs, default_name):
        """
        """
        QtWidgets.QDialog.__init__(self, parent)
        self.ui = Ui_CreateEvokedDialog()
        self.ui.setupUi(self)

        self.parent = parent
        self.experiment = experiment

        self.selected_epochs = selected_epochs

        self.batching_widget = BatchingWidget(
            experiment_getter=self.experiment_getter,
            parent=self,
            container=self.ui.groupBoxBatching,
            geometry=self.ui.batchingWidgetPlaceholder.geometry())
        self.ui.gridLayoutBatching.addWidget(self.batching_widget, 0, 0, 1, 1)

        self.ui.lineEditName.setText(default_name)
Exemplo n.º 10
0
    def __init__(self, parent, experiment, handler):
        QtWidgets.QDialog.__init__(self, parent)
        self.ui = Ui_resamplingDialog()
        self.ui.setupUi(self)

        self.experiment = experiment
        self.parent = parent
        self.handler = handler

        subject = self.experiment.active_subject
        raw = subject.get_raw()
        sfreq = raw.info['sfreq']

        self.ui.labelCurrentRateValue.setText(str(sfreq))

        self.batching_widget = BatchingWidget(
            experiment_getter=self._experiment_getter,
            parent=self,
            container=self.ui.groupBoxBatching,
            geometry=self.ui.batchingWidgetPlaceholder.geometry())
        self.ui.gridLayoutBatching.addWidget(self.batching_widget, 0, 0, 1, 1)
Exemplo n.º 11
0
    def __init__(self, parent, experiment, handler):
        QtWidgets.QDialog.__init__(self, parent)
        self.ui = Ui_EventsFromAnnotationsDialog()
        self.ui.setupUi(self)

        self.experiment = experiment
        self.parent = parent
        self.handler = handler

        self.items = []

        subject = self.experiment.active_subject
        raw = subject.get_raw()

        for annotation_name in sorted(list(set(raw.annotations.description))):
            self.ui.comboBoxAnnotation.addItem(annotation_name)

        self.batching_widget = BatchingWidget(
            experiment_getter=self._experiment_getter,
            parent=self,
            container=self.ui.groupBoxBatching,
            geometry=self.ui.batchingWidgetPlaceholder.geometry())
        self.ui.gridLayoutBatching.addWidget(self.batching_widget, 0, 0, 1, 1)
Exemplo n.º 12
0
class RereferencingDialog(QtWidgets.QDialog):
    """ Contains logic for the rereferencing dialog.
    """
    def __init__(self, parent, experiment, handler):
        QtWidgets.QDialog.__init__(self, parent)
        self.ui = Ui_rereferencingDialog()
        self.ui.setupUi(self)

        self.experiment = experiment
        self.parent = parent
        self.handler = handler

        subject = self.experiment.active_subject
        raw = subject.get_raw()
        sfreq = raw.info['sfreq']

        # fill the combobox
        picks = mne.pick_types(raw.info, eeg=True, meg=False, eog=True)
        ch_names = [
            ch_name for ch_idx, ch_name in enumerate(raw.info['ch_names'])
            if ch_idx in picks
        ]

        for ch_name in ch_names:
            self.ui.comboBoxChannel.addItem(ch_name)

        self.batching_widget = BatchingWidget(
            experiment_getter=self._experiment_getter,
            parent=self,
            container=self.ui.groupBoxBatching,
            geometry=self.ui.batchingWidgetPlaceholder.geometry())
        self.ui.gridLayoutBatching.addWidget(self.batching_widget, 0, 0, 1, 1)

    def _experiment_getter(self):
        return self.experiment

    def accept(self):
        experiment = self.experiment
        subject = experiment.active_subject

        selection = self.ui.comboBoxChannel.currentText()

        try:
            params = {'selection': selection}
            self.handler(subject, params)
            experiment.save_experiment_settings()
        except Exception as exc:
            exc_messagebox(self.parent, exc)
            return

        self.parent.initialize_ui()
        self.close()

    def acceptBatch(self):
        experiment = self.experiment
        selection = self.ui.comboBoxChannel.currentText()

        selected_subject_names = self.batching_widget.selected_subjects

        for name, subject in experiment.subjects.items():
            if name in selected_subject_names:
                try:
                    params = {'selection': selection}
                    self.handler(subject, params)
                    subject.release_memory()
                except Exception as exc:
                    self.batching_widget.failed_subjects.append(
                        (subject, str(exc)))
                    logging.getLogger('ui_logger').exception('')

        self.batching_widget.cleanup()

        try:
            experiment.save_experiment_settings()
        except Exception as exc:
            exc_messagebox(self.parent, exc)

        self.parent.initialize_ui()

        self.close()
Exemplo n.º 13
0
class FilterDialog(QtWidgets.QDialog):
    """ Contains logic for filter dialog.
    """

    def __init__(self, parent, experiment, handler):
        QtWidgets.QDialog.__init__(self, parent)
        self.ui = Ui_DialogFilter()
        self.ui.setupUi(self)

        self.parent = parent
        self.experiment = experiment
        self.handler = handler

        self.batching_widget = BatchingWidget(
            experiment_getter=self._experiment_getter,
            parent=self,
            container=self.ui.groupBoxBatching,
            geometry=self.ui.batchingWidgetPlaceholder.geometry())
        self.ui.gridLayoutBatching.addWidget(self.batching_widget, 0, 0, 1, 1)

    def _experiment_getter(self):
        return self.experiment

    def on_pushButtonPreview_clicked(self, checked=None):
        if checked is None:
            return

        params = self._collect_parameter_values()
        if not params:
            message = 'No filter(s) selected.'
            messagebox(self.parent, message)
            return

        subject = self.experiment.active_subject

        try:
            raw_to = filter_data(subject,
                                 params,
                                 preview=True)
            raw_from = subject.get_raw()
            compare_raws(raw_from, raw_to)
        except Exception as exc:
            exc_messagebox(self.parent, exc)

    def accept(self):
        subject = self.experiment.active_subject
        params = self._collect_parameter_values()
        if not params:
            message = 'No filter(s) selected'
            messagebox(self.parent, message)
            return

        try:
            self.handler(subject, params)
        except Exception as exc:
            exc_messagebox(self.parent, exc)
            return

        self.parent.initialize_ui()
        self.close()

    def acceptBatch(self):
        subject_names = self.batching_widget.selected_subjects
        params = self._collect_parameter_values()
        if not params:
            message = 'No filter(s) selected'
            messagebox(self.parent, message)
            return

        for name, subject in self.experiment.subjects.items():
            if name in subject_names:
                try:
                    self.handler(subject, params)
                    subject.release_memory()
                except Exception as exc:
                    logging.getLogger('ui_logger').exception('')
                    self.batching_widget.failed_subjects.append(
                        (subject, str(exc)))

        self.batching_widget.cleanup()
        self.parent.initialize_ui()
        self.close()

    def _collect_parameter_values(self):
        is_empty = True
        dictionary = {}

        length = str(self.ui.doubleSpinBoxLength.value()) + 's'
        dictionary['length'] = length

        dictionary['trans_bw'] = self.ui.doubleSpinBoxTransBandwidth.value()

        dictionary['lowpass'] = self.ui.checkBoxLowpass.isChecked()
        if dictionary['lowpass']:
            is_empty = False
            dictionary['low_cutoff_freq'] = \
                self.ui.doubleSpinBoxLowpassCutoff.value()

        dictionary['highpass'] = self.ui.checkBoxHighpass.isChecked()
        if dictionary['highpass']:
            is_empty = False
            dictionary['high_cutoff_freq'] = \
                self.ui.doubleSpinBoxHighpassCutoff.value()

        dictionary['bandstop1'] = self.ui.checkBoxBandstop.isChecked()
        if dictionary['bandstop1']:
            is_empty = False
            dictionary['bandstop1_freq'] = \
                self.ui.doubleSpinBoxBandstopFreq.value()

        dictionary['bandstop2'] = self.ui.checkBoxBandstop2.isChecked()
        if dictionary['bandstop2']:
            is_empty = False
            dictionary['bandstop2_freq'] = \
                self.ui.doubleSpinBoxBandstopFreq2.value()

        dictionary['bandstop_bw'] = self.ui.doubleSpinBoxBandstopWidth.value()
        dictionary['bandstop_transbw'] = self.ui.doubleSpinBoxNotchTransBw.value()  # noqa

        length = str(self.ui.doubleSpinBoxBandStopLength.value()) + 's'
        dictionary['bandstop_length'] = length

        return dictionary
Exemplo n.º 14
0
class CreateEvokedDialog(QtWidgets.QDialog):
    """
    """
    def __init__(self, experiment, parent, selected_epochs, default_name):
        """
        """
        QtWidgets.QDialog.__init__(self, parent)
        self.ui = Ui_CreateEvokedDialog()
        self.ui.setupUi(self)

        self.parent = parent
        self.experiment = experiment

        self.selected_epochs = selected_epochs

        self.batching_widget = BatchingWidget(
            experiment_getter=self.experiment_getter,
            parent=self,
            container=self.ui.groupBoxBatching,
            geometry=self.ui.batchingWidgetPlaceholder.geometry())
        self.ui.gridLayoutBatching.addWidget(self.batching_widget, 0, 0, 1, 1)

        self.ui.lineEditName.setText(default_name)

    def experiment_getter(self):
        return self.experiment

    def create_evoked(self, subject, selected_epochs):

        time_arrays = []
        for name in selected_epochs:
            epochs = subject.epochs.get(name)
            if epochs:
                time_arrays.append(epochs.content.times)

        assert_arrays_same(time_arrays)

        evokeds = {}
        for name in selected_epochs:
            try:
                epochs = subject.epochs[name]
            except KeyError:
                raise KeyError('No epoch collection called ' + str(name))

            mne_epochs = epochs.content

            @threaded
            def average():
                return mne_epochs.average()

            mne_evoked = average(do_meanwhile=self.parent.update_ui)

            mne_evoked.comment = name
            evokeds[name] = mne_evoked

        evoked_name = validate_name(self.ui.lineEditName.text())

        params = {'conditions': selected_epochs}

        evoked_directory = subject.evoked_directory
        evoked = Evoked(evoked_name, evoked_directory, params, content=evokeds)
        evoked.save_content()
        subject.add(evoked, 'evoked')

    def accept(self):
        subject = self.experiment.active_subject
        selected_epochs = self.selected_epochs

        try:
            self.create_evoked(subject, selected_epochs)
        except Exception as exc:
            exc_messagebox(self, exc)
            return

        self.experiment.save_experiment_settings()
        self.parent.initialize_ui()

        logging.getLogger('ui_logger').info('Finished.')

        self.close()

    def acceptBatch(self):
        selected_epochs = self.selected_epochs
        experiment = self.experiment

        selected_subject_names = self.batching_widget.selected_subjects

        for name, subject in self.experiment.subjects.items():
            if name in selected_subject_names:
                try:
                    self.create_evoked(subject, selected_epochs)
                    subject.release_memory()
                except Exception as exc:
                    self.batching_widget.failed_subjects.append(
                        (subject, str(exc)))
                    logging.getLogger('ui_logger').exception(str(exc))

        self.batching_widget.cleanup()
        self.experiment.save_experiment_settings()
        self.parent.initialize_ui()

        logging.getLogger('ui_logger').info('Finished.')

        self.close()
Exemplo n.º 15
0
class SimpleDialog(QtWidgets.QDialog):
    """ Contains logic for simple reusable dialog.
    """
    def __init__(self,
                 experiment,
                 parent,
                 default_name,
                 handler,
                 batching=True,
                 title='Simple dialog'):
        QtWidgets.QDialog.__init__(self, parent)
        self.ui = Ui_SimpleDialog()
        self.ui.setupUi(self)

        self.parent = parent
        self.experiment = experiment
        self.handler = handler

        self.setWindowTitle('Meggie - ' + title)

        if batching:
            self.batching_widget = BatchingWidget(
                experiment_getter=self._experiment_getter,
                parent=self,
                container=self.ui.groupBoxBatching,
                geometry=self.ui.batchingWidgetPlaceholder.geometry())
            self.ui.gridLayoutBatching.addWidget(self.batching_widget, 0, 0, 1,
                                                 1)
        else:
            self.ui.groupBoxBatching.hide()
            self.ui.pushButtonBatch.hide()

        self.ui.lineEditName.setText(default_name)

    def _experiment_getter(self):
        return self.experiment

    def accept(self):
        subject = self.experiment.active_subject

        try:
            evoked_name = validate_name(self.ui.lineEditName.text())
        except Exception as exc:
            exc_messagebox(self, exc)
            return

        try:
            params = {'name': evoked_name}
            self.handler(subject, params)
            self.experiment.save_experiment_settings()
        except Exception as exc:
            exc_messagebox(self, exc)
            return

        self.parent.initialize_ui()
        self.close()

    def acceptBatch(self):

        experiment = self.experiment

        try:
            evoked_name = validate_name(self.ui.lineEditName.text())
        except Exception as exc:
            exc_messagebox(self, exc)
            return

        selected_subject_names = self.batching_widget.selected_subjects

        params = {'name': evoked_name}

        for name, subject in self.experiment.subjects.items():
            if name in selected_subject_names:
                try:
                    self.handler(subject, params)
                    subject.release_memory()
                except Exception as exc:
                    self.batching_widget.failed_subjects.append(
                        (subject, str(exc)))
                    logging.getLogger('ui_logger').exception('')

        self.batching_widget.cleanup()

        try:
            self.experiment.save_experiment_settings()
        except Exception as exc:
            exc_messagebox(self, exc)
            return

        self.parent.initialize_ui()
        self.close()
Exemplo n.º 16
0
class MontageDialog(QtWidgets.QDialog):
    """ Contains logic for montage dialog.
    """
    def __init__(self, parent, experiment, handler):
        QtWidgets.QDialog.__init__(self, parent)
        self.ui = Ui_montageDialog()
        self.ui.setupUi(self)

        self.parent = parent
        self.experiment = experiment
        self.handler = handler

        montage_dir = pkg_resources.resource_filename(
            'mne', os.path.join('channels', 'data', 'montages'))

        for fname in sorted(os.listdir(montage_dir)):
            self.ui.comboBoxSelectFromList.addItem(fname)

        self.current_montage_fname = None
        self.ui.radioButtonMontageFromList.setChecked(True)

        # find out if montage already set.

        self.batching_widget = BatchingWidget(
            experiment_getter=self._experiment_getter,
            parent=self,
            container=self.ui.groupBoxBatching,
            geometry=self.ui.batchingWidgetPlaceholder.geometry())
        self.ui.gridLayoutBatching.addWidget(self.batching_widget, 0, 0, 1, 1)

    def _experiment_getter(self):
        return self.experiment

    def on_pushButtonSelectFromFile_clicked(self, checked=None):
        if checked is None:
            return

        home = filemanager.homepath()

        fname = QtCore.QDir.toNativeSeparators(
            str(
                QtWidgets.QFileDialog.getOpenFileName(
                    self, 'Open file', home,
                    "Montage-files (*.txt *.elc *.sfp);;"
                    "All files (*.*)")[0]))

        self.current_montage_fname = fname
        if self.ui.radioButtonMontageFromFile.isChecked():
            self.ui.labelCurrentContent.setText(self.current_montage_fname)

    def on_radioButtonMontageFromFile_toggled(self, checked):
        if checked:
            self.ui.labelCurrentContent.setText(self.current_montage_fname)

    def on_comboBoxSelectFromList_currentIndexChanged(self, item):
        if self.ui.radioButtonMontageFromList.isChecked():
            self.ui.labelCurrentContent.setText(str(item))

    def on_radioButtonMontageFromList_toggled(self, checked):
        if checked:
            selection = self.ui.comboBoxSelectFromList.currentText()
            self.ui.labelCurrentContent.setText(selection)

    def _get_params(self):
        params = {}
        head_size = float(self.ui.doubleSpinBoxHeadSize.value())
        if self.ui.radioButtonMontageFromList.isChecked():
            selection = self.ui.comboBoxSelectFromList.currentText()
            selection = os.path.splitext(selection)[0]
            params['custom'] = False
            params['selection'] = selection
        else:
            params['custom'] = True
            params['selection'] = self.current_montage_fname

        params['head_size'] = head_size

        return params

    def accept(self):
        subject = self.experiment.active_subject

        params = self._get_params()

        try:
            self.handler(subject, params)
        except Exception as exc:
            exc_messagebox(self, exc)
            return

        self.parent.initialize_ui()
        self.close()

    def acceptBatch(self):
        experiment = self.experiment
        selected_subject_names = self.batching_widget.selected_subjects

        params = self._get_params()

        for name, subject in self.experiment.subjects.items():
            if name in selected_subject_names:
                try:
                    self.handler(subject, params)
                except Exception as exc:
                    self.batching_widget.failed_subjects.append(
                        (subject, str(exc)))
                    logging.getLogger('ui_logger').exception('')

        self.batching_widget.cleanup()

        self.parent.initialize_ui()
        self.close()
Exemplo n.º 17
0
class ResamplingDialog(QtWidgets.QDialog):
    """ Contains logic for the resampling dialog.
    """
    def __init__(self, parent, experiment, handler):
        QtWidgets.QDialog.__init__(self, parent)
        self.ui = Ui_resamplingDialog()
        self.ui.setupUi(self)

        self.experiment = experiment
        self.parent = parent
        self.handler = handler

        subject = self.experiment.active_subject
        raw = subject.get_raw()
        sfreq = raw.info['sfreq']

        self.ui.labelCurrentRateValue.setText(str(sfreq))

        self.batching_widget = BatchingWidget(
            experiment_getter=self._experiment_getter,
            parent=self,
            container=self.ui.groupBoxBatching,
            geometry=self.ui.batchingWidgetPlaceholder.geometry())
        self.ui.gridLayoutBatching.addWidget(self.batching_widget, 0, 0, 1, 1)

    def _experiment_getter(self):
        return self.experiment

    def accept(self):
        subject = self.experiment.active_subject
        raw = subject.get_raw()

        old_rate = raw.info['sfreq']
        rate = self.ui.doubleSpinBoxNewRate.value()

        params = {'rate': rate}

        try:
            self.handler(subject, params)
        except Exception as exc:
            exc_messagebox(self.parent, exc)
            return

        self.parent.initialize_ui()
        self.close()

    def acceptBatch(self):
        experiment = self.experiment

        selected_subject_names = self.batching_widget.selected_subjects

        for name, subject in self.experiment.subjects.items():
            if name in selected_subject_names:
                try:
                    raw = subject.get_raw()
                    old_rate = raw.info['sfreq']
                    rate = self.ui.doubleSpinBoxNewRate.value()

                    params = {'rate': rate}
                    self.handler(subject, params)
                    subject.release_memory()
                except Exception as exc:
                    self.batching_widget.failed_subjects.append(
                        (subject, str(exc)))
                    logging.getLogger('ui_logger').exception('')
        self.batching_widget.cleanup()

        self.parent.initialize_ui()
        self.close()
Exemplo n.º 18
0
class FilterDialog(QtWidgets.QDialog):
    """
    """
    def __init__(self, parent, experiment):
        QtWidgets.QDialog.__init__(self, parent)
        self.ui = Ui_DialogFilter()
        self.ui.setupUi(self)

        self.parent = parent
        self.experiment = experiment

        self.batching_widget = BatchingWidget(
            experiment_getter=self.experiment_getter,
            parent=self,
            container=self.ui.groupBoxBatching,
            geometry=self.ui.batchingWidgetPlaceholder.geometry())
        self.ui.gridLayoutBatching.addWidget(self.batching_widget, 0, 0, 1, 1)

    def experiment_getter(self):
        return self.experiment

    def on_pushButtonPreview_clicked(self, checked=None):
        """
        Draws the preview.
        """
        if checked is None:
            return

        params = self.collect_parameter_values()
        if not params:
            message = 'No filter(s) selected.'
            messagebox(self.parent, message)
            return

        subject = self.experiment.active_subject

        # mne-python's filter_data takes filter_length in human-readable format
        params = deepcopy(params)
        params['length'] = params['length'] + 's'
        params['bandstop_length'] = params['bandstop_length'] + 's'

        try:
            raw_to = filter_data(params,
                                 subject,
                                 preview=True,
                                 do_meanwhile=self.parent.update_ui)
            raw_from = subject.get_raw()
            compare_raws(raw_from, raw_to)
        except Exception as exc:
            exc_messagebox(self.parent, exc)

    def accept(self):
        """
        Get the parameters dictionary and relay it to filter_data to
        actually do the filtering.
        """
        subject = self.experiment.active_subject
        params = self.collect_parameter_values()
        if not params:
            message = 'No filter(s) selected'
            messagebox(self.parent, message)
            return

        try:
            self.filter(subject, params)
        except Exception as exc:
            exc_messagebox(self.parent, exc)
            logging.getLogger('ui_logger').exception(str(exc))

        self.parent.initialize_ui()
        self.close()

    def acceptBatch(self):
        """
        """
        subject_names = self.batching_widget.selected_subjects
        params = self.collect_parameter_values()
        if not params:
            message = 'No filter(s) selected'
            messagebox(self.parent, message)
            return

        for name, subject in self.experiment.subjects.items():
            if name in subject_names:
                try:
                    self.filter(subject, params)
                    subject.release_memory()
                except Exception as exc:
                    logging.getLogger('ui_logger').exception(str(exc))
                    self.batching_widget.failed_subjects.append(
                        (subject, str(exc)))

        self.batching_widget.cleanup()

        self.parent.initialize_ui()
        self.close()

    def collect_parameter_values(self):
        """
        Gets the filtering parameters from the UI fields and performs
        rudimentary sanity checks on them.
        """
        is_empty = True
        dictionary = {}

        length = str(self.ui.doubleSpinBoxLength.value())
        dictionary['length'] = length

        dictionary['trans_bw'] = self.ui.doubleSpinBoxTransBandwidth.value()

        dictionary['lowpass'] = self.ui.checkBoxLowpass.isChecked()
        if dictionary['lowpass']:
            is_empty = False
            dictionary['low_cutoff_freq'] = \
                self.ui.doubleSpinBoxLowpassCutoff.value()

        dictionary['highpass'] = self.ui.checkBoxHighpass.isChecked()
        if dictionary['highpass']:
            is_empty = False
            dictionary['high_cutoff_freq'] = \
                self.ui.doubleSpinBoxHighpassCutoff.value()

        dictionary['bandstop1'] = self.ui.checkBoxBandstop.isChecked()
        if dictionary['bandstop1']:
            is_empty = False
            dictionary['bandstop1_freq'] = \
                self.ui.doubleSpinBoxBandstopFreq.value()

        dictionary['bandstop2'] = self.ui.checkBoxBandstop2.isChecked()
        if dictionary['bandstop2']:
            is_empty = False
            dictionary['bandstop2_freq'] = \
                self.ui.doubleSpinBoxBandstopFreq2.value()

        dictionary['bandstop_bw'] = self.ui.doubleSpinBoxBandstopWidth.value()
        dictionary[
            'bandstop_transbw'] = self.ui.doubleSpinBoxNotchTransBw.value(
            )  # noqa

        length = str(self.ui.doubleSpinBoxBandStopLength.value())
        dictionary['bandstop_length'] = length

        return dictionary

    def filter(self, subject, params):
        """
        """
        # mne-python wants the lengths to be human-readable values
        params = deepcopy(params)
        params['length'] = params['length'] + 's'
        params['bandstop_length'] = params['bandstop_length'] + 's'

        filter_data(params, subject, do_meanwhile=self.parent.update_ui)
Exemplo n.º 19
0
class ResamplingDialog(QtWidgets.QDialog):

    def __init__(self, parent, experiment):
        """
        """
        QtWidgets.QDialog.__init__(self, parent)
        self.ui = Ui_resamplingDialog()
        self.ui.setupUi(self)

        self.experiment = experiment
        self.parent = parent

        subject = self.experiment.active_subject
        raw = subject.get_raw()
        sfreq = raw.info['sfreq']

        self.ui.labelCurrentRateValue.setText(str(sfreq))

        self.batching_widget = BatchingWidget(
            experiment_getter=self.experiment_getter,
            parent=self,
            container=self.ui.groupBoxBatching,
            geometry=self.ui.batchingWidgetPlaceholder.geometry())
        self.ui.gridLayoutBatching.addWidget(self.batching_widget, 0, 0, 1, 1)

    def experiment_getter(self):
        return self.experiment

    def accept(self):
        subject = self.experiment.active_subject
        raw = subject.get_raw()

        old_rate = raw.info['sfreq']
        rate = self.ui.doubleSpinBoxNewRate.value()

        @threaded
        def resample_fun():
            raw.resample(rate)
            subject.save()

        resample_fun(do_meanwhile=self.parent.update_ui)

        self.parent.initialize_ui()

        logging.getLogger('ui_logger').info('Finished.')
        self.close()

    def acceptBatch(self):

        experiment = self.experiment

        selected_subject_names = self.batching_widget.selected_subjects

        for name, subject in self.experiment.subjects.items():
            if name in selected_subject_names:
                try:
                    raw = subject.get_raw()
                    old_rate = raw.info['sfreq']
                    rate = self.ui.doubleSpinBoxNewRate.value()

                    @threaded
                    def resample_fun():
                        raw.resample(rate)
                        subject.save()
                        subject.release_memory()

                    resample_fun(do_meanwhile=self.parent.update_ui)
                except Exception as exc:
                    self.batching_widget.failed_subjects.append(
                        (subject, str(exc)))
                    logging.getLogger('ui_logger').exception(str(exc))

        self.batching_widget.cleanup()

        self.parent.initialize_ui()

        logging.getLogger('ui_logger').info('Finished.')
        self.close()
Exemplo n.º 20
0
class PowerSpectrumDialog(QtWidgets.QDialog):
    def __init__(self, experiment, parent, default_name):
        """
        """
        QtWidgets.QDialog.__init__(self, parent)
        self.ui = Ui_PowerSpectrumDialog()
        self.ui.setupUi(self)

        self.parent = parent
        self.experiment = experiment

        self.intervals = []

        raw = self.experiment.active_subject.get_raw()

        tmax = np.floor(raw.times[raw.n_times - 1]) - 0.1
        self.ui.doubleSpinBoxTmin.setValue(0)
        self.ui.doubleSpinBoxTmax.setValue(tmax)
        self.ui.doubleSpinBoxTmin.setMaximum(tmax)
        self.ui.doubleSpinBoxTmax.setMaximum(tmax)

        # set nfft initially to ~2 seconds and overlap to ~1 seconds
        sfreq = raw.info['sfreq']
        window_in_seconds = 2
        nfft = int(
            np.power(2,
                     np.ceil(np.log(sfreq * window_in_seconds) / np.log(2))))
        overlap = nfft / 2

        self.ui.spinBoxNfft.setValue(nfft)
        self.ui.spinBoxOverlap.setValue(overlap)

        if raw.info.get('highpass'):
            if self.ui.spinBoxFmin.value() < raw.info['highpass']:
                self.ui.spinBoxFmin.setValue(int(np.ceil(
                    raw.info['highpass'])))

        if raw.info.get('lowpass'):
            if self.ui.spinBoxFmax.value() > raw.info['lowpass']:
                self.ui.spinBoxFmax.setValue(int(raw.info['lowpass']))

        self.batching_widget = BatchingWidget(
            experiment_getter=self.experiment_getter,
            parent=self,
            container=self.ui.groupBoxBatching,
            geometry=self.ui.batchingWidgetPlaceholder.geometry())
        self.ui.gridLayoutBatching.addWidget(self.batching_widget, 0, 0, 1, 1)

        self.ui.lineEditName.setText(default_name)

    def experiment_getter(self):
        return self.experiment

    def on_pushButtonAdd_clicked(self, checked=None):
        if checked is None:
            return
        group = str(self.ui.comboBoxAvgGroup.currentText())
        tmin = self.ui.doubleSpinBoxTmin.value()
        tmax = self.ui.doubleSpinBoxTmax.value()
        if tmin >= tmax:
            messagebox(self.parent,
                       "End time must be higher than the starting time")
            return

        self.add_intervals([('fixed', (group, tmin, tmax))])

    def add_intervals(self, intervals):
        for ival_type, interval in intervals:
            self.intervals.append((ival_type, interval))
            if ival_type == 'fixed':
                item = QtWidgets.QListWidgetItem(
                    '%s: %s - %s s (fixed)' %
                    (interval[0], round(interval[1], 4), round(interval[2],
                                                               4)))
            else:
                item_string = str(interval[0]) + ': ['
                if interval[1][0] == 'events':
                    item_string += ', '.join(
                        [str(elem) for elem in interval[1][1:]])
                elif interval[1][0] == 'start':
                    item_string += 'start, ' + str(interval[1][3])
                elif interval[1][0] == 'end':
                    item_string += 'end, ' + str(interval[1][3])

                item_string += '] – ['

                if interval[2][0] == 'events':
                    item_string += ', '.join(
                        [str(elem) for elem in interval[2][1:]])
                elif interval[2][0] == 'start':
                    item_string += 'start, ' + str(interval[2][3])

                elif interval[2][0] == 'end':
                    item_string += 'end, ' + str(interval[2][3])

                item_string += '] (dynamic)'

                item = QtWidgets.QListWidgetItem(item_string)
            self.ui.listWidgetIntervals.addItem(item)

    def on_pushButtonClear_clicked(self, checked=None):
        if checked is None:
            return
        self.intervals = []
        self.ui.listWidgetIntervals.clear()

    def on_pushButtonClearRow_clicked(self, checked=None):
        if checked is None:
            return

        current_row = self.ui.listWidgetIntervals.currentRow()
        if current_row == -1:
            return

        self.ui.listWidgetIntervals.takeItem(current_row)
        self.intervals.pop(current_row)

    def on_pushButtonAddAdvanced_clicked(self, checked=None):
        if checked is None:
            return
        dialog = PowerSpectrumAddAdvancedDialog(self)
        dialog.show()

    def accept(self, *args, **kwargs):
        """ Starts the computation.
        """

        try:
            spectrum_name = validate_name(self.ui.lineEditName.text())
        except Exception as exc:
            exc_messagebox(self, exc)
            return

        intervals = self.intervals
        if not intervals:
            return

        fmin = self.ui.spinBoxFmin.value()
        fmax = self.ui.spinBoxFmax.value()

        subject = self.experiment.active_subject

        update_ui = self.parent.update_ui

        params = dict()
        params['fmin'] = fmin
        params['fmax'] = fmax
        params['nfft'] = self.ui.spinBoxNfft.value()
        params['overlap'] = self.ui.spinBoxOverlap.value()

        try:
            create_power_spectrum(subject,
                                  spectrum_name,
                                  params,
                                  intervals,
                                  do_meanwhile=update_ui)
        except Exception as exc:
            exc_messagebox(self, exc)
            return

        self.experiment.save_experiment_settings()
        self.parent.initialize_ui()

        logging.getLogger('ui_logger').info('Finished.')

        self.close()

    def acceptBatch(self, *args):

        try:
            spectrum_name = validate_name(self.ui.lineEditName.text())
        except Exception as exc:
            exc_messagebox(self, exc)
            return

        intervals = self.intervals
        if not intervals:
            return

        fmin = self.ui.spinBoxFmin.value()
        fmax = self.ui.spinBoxFmax.value()

        subject = self.experiment.active_subject

        params = dict()
        params['fmin'] = fmin
        params['fmax'] = fmax
        params['nfft'] = self.ui.spinBoxNfft.value()
        params['overlap'] = self.ui.spinBoxOverlap.value()

        update_ui = self.parent.update_ui

        selected_subject_names = self.batching_widget.selected_subjects
        for name, subject in self.experiment.subjects.items():
            if name in selected_subject_names:
                try:
                    create_power_spectrum(subject,
                                          spectrum_name,
                                          params,
                                          intervals,
                                          do_meanwhile=update_ui)
                    subject.release_memory()
                except Exception as exc:
                    self.batching_widget.failed_subjects.append(
                        (subject, str(exc)))
                    logging.getLogger('ui_logger').exception(str(exc))

        self.batching_widget.cleanup()
        self.experiment.save_experiment_settings()
        self.parent.initialize_ui()

        logging.getLogger('ui_logger').info('Finished.')

        self.close()
Exemplo n.º 21
0
class EventsFromAnnotationsDialog(QtWidgets.QDialog):
    """ Contains logic for events from annotations dialog.
    """
    def __init__(self, parent, experiment, handler):
        QtWidgets.QDialog.__init__(self, parent)
        self.ui = Ui_EventsFromAnnotationsDialog()
        self.ui.setupUi(self)

        self.experiment = experiment
        self.parent = parent
        self.handler = handler

        self.items = []

        subject = self.experiment.active_subject
        raw = subject.get_raw()

        for annotation_name in sorted(list(set(raw.annotations.description))):
            self.ui.comboBoxAnnotation.addItem(annotation_name)

        self.batching_widget = BatchingWidget(
            experiment_getter=self._experiment_getter,
            parent=self,
            container=self.ui.groupBoxBatching,
            geometry=self.ui.batchingWidgetPlaceholder.geometry())
        self.ui.gridLayoutBatching.addWidget(self.batching_widget, 0, 0, 1, 1)

    def _experiment_getter(self):
        return self.experiment

    def on_pushButtonAdd_clicked(self, checked=None):
        if checked is None:
            return

        annotation_name = self.ui.comboBoxAnnotation.currentText()
        event_id = self.ui.spinBoxEventID.value()
        use_start = True if self.ui.radioButtonStart.isChecked() else False

        self.items.append((annotation_name, event_id, use_start))
        self._update_list()

    def on_pushButtonClear_clicked(self, checked=None):
        if checked is None:
            return

        self.items = []
        self._update_list()

    def _update_list(self):
        self.ui.listWidgetItems.clear()

        for item in self.items:
            text = 'Annotation: ' + str(item[0]) + ', event id: ' + str(
                item[1]) + ', '
            if item[2]:
                text = text + 'use start'
            else:
                text = text + 'use end'

            item = QtWidgets.QListWidgetItem(str(text))
            self.ui.listWidgetItems.addItem(item)

    def accept(self):
        subject = self.experiment.active_subject

        try:
            params = {'items': self.items}
            self.handler(subject, params)
        except Exception as exc:
            exc_messagebox(self.parent, exc)
            return

        self.parent.initialize_ui()
        self.close()

    def acceptBatch(self):
        experiment = self.experiment

        selected_subject_names = self.batching_widget.selected_subjects

        for name, subject in self.experiment.subjects.items():
            if name in selected_subject_names:
                try:
                    params = {'items': self.items}
                    self.handler(subject, params)
                    subject.release_memory()
                except Exception as exc:
                    self.batching_widget.failed_subjects.append(
                        (subject, str(exc)))
                    logging.getLogger('ui_logger').exception('')

        self.batching_widget.cleanup()

        self.parent.initialize_ui()
        self.close()
Exemplo n.º 22
0
class RereferencingDialog(QtWidgets.QDialog):
    def __init__(self, parent, experiment):
        """
        """
        QtWidgets.QDialog.__init__(self, parent)
        self.ui = Ui_rereferencingDialog()
        self.ui.setupUi(self)

        self.experiment = experiment
        self.parent = parent

        subject = self.experiment.active_subject
        raw = subject.get_raw()
        sfreq = raw.info['sfreq']

        # fill the combobox
        picks = mne.pick_types(raw.info, eeg=True, meg=False, eog=True)
        ch_names = [
            ch_name for ch_idx, ch_name in enumerate(raw.info['ch_names'])
            if ch_idx in picks
        ]

        for ch_name in ch_names:
            self.ui.comboBoxChannel.addItem(ch_name)

        self.batching_widget = BatchingWidget(
            experiment_getter=self.experiment_getter,
            parent=self,
            container=self.ui.groupBoxBatching,
            geometry=self.ui.batchingWidgetPlaceholder.geometry())
        self.ui.gridLayoutBatching.addWidget(self.batching_widget, 0, 0, 1, 1)

    def experiment_getter(self):
        return self.experiment

    def accept(self):
        """
        """
        experiment = self.experiment

        raw = experiment.active_subject.get_raw()
        selection = self.ui.comboBoxChannel.currentText()

        @threaded
        def rereference_fun():
            if selection == 'Use average':
                raw.set_eeg_reference(ref_channels='average', projection=False)
            elif selection == '':
                raise Exception('Empty selection')
            else:
                raw.set_eeg_reference(ref_channels=[selection])

        try:
            rereference_fun(do_meanwhile=self.parent.update_ui)
        except Exception as exc:
            exc_messagebox(self.parent, exc)
            self.close()
            return

        experiment.active_subject.save()
        experiment.active_subject.rereferenced = True

        experiment.save_experiment_settings()
        self.parent.initialize_ui()

        logging.getLogger('ui_logger').info('Finished.')
        self.close()

    def acceptBatch(self):
        """
        """
        experiment = self.experiment
        selection = self.ui.comboBoxChannel.currentText()

        selected_subject_names = self.batching_widget.selected_subjects

        for name, subject in experiment.subjects.items():
            if name in selected_subject_names:
                try:
                    raw = subject.get_raw()

                    @threaded
                    def rereference_fun():
                        if selection == 'Use average':
                            raw.set_eeg_reference(ref_channels='average',
                                                  projection=False)
                        elif selection == '':
                            raise Exception('Empty selection')
                        else:
                            raw.set_eeg_reference(ref_channels=[selection])

                    rereference_fun(do_meanwhile=self.parent.update_ui)
                    subject.save()
                    subject.rereferenced = True
                    subject.release_memory()

                except Exception as exc:
                    self.batching_widget.failed_subjects.append(
                        (subject, str(exc)))
                    logging.getLogger('ui_logger').exception(str(exc))

        self.batching_widget.cleanup()

        experiment.save_experiment_settings()
        self.parent.initialize_ui()

        logging.getLogger('ui_logger').info('Finished.')
        self.close()
class CreateEpochsFromEventsDialog(QtWidgets.QDialog):
    """
    """
    def __init__(self, experiment, parent, default_name):
        """Initialize the event selection dialog.

        """
        QtWidgets.QDialog.__init__(self, parent)
        self.ui = Ui_CreateEpochsFromEventsDialog()
        self.ui.setupUi(self)

        self.parent = parent
        self.experiment = experiment

        self.events = []

        self.batching_widget = BatchingWidget(
            experiment_getter=self.experiment_getter,
            parent=self,
            container=self.ui.groupBoxBatching,
            geometry=self.ui.batchingWidgetPlaceholder.geometry())
        self.ui.gridLayoutBatching.addWidget(self.batching_widget, 0, 0, 1, 1)

        self.ui.lineEditCollectionName.setText(default_name)

    def experiment_getter(self):
        return self.experiment

    def update_events(self):
        """ update event list on UI based on self.events
        """
        self.ui.listWidgetEvents.clear()

        events = self.events

        for event in events:
            item = QtWidgets.QListWidgetItem(
                '%s, %s' %
                ('ID ' + str(event['event_id']), 'mask=' + str(event['mask'])))
            self.ui.listWidgetEvents.addItem(item)

    def collect_parameter_values(self):
        """Collect the parameter values for epoch creation from the ui.
        """
        tmin = float(self.ui.doubleSpinBoxTmin.value())
        tmax = float(self.ui.doubleSpinBoxTmax.value())
        bstart = float(self.ui.doubleSpinBoxBaselineStart.value())
        bend = float(self.ui.doubleSpinBoxBaselineEnd.value())

        mag = self.ui.checkBoxMag.isChecked()
        grad = self.ui.checkBoxGrad.isChecked()
        eeg = self.ui.checkBoxEeg.isChecked()

        collection_name = validate_name(
            str(self.ui.lineEditCollectionName.text()))

        reject = dict()
        if mag:
            reject['mag'] = self.ui.doubleSpinBoxMagReject.value()
        if grad:
            reject['grad'] = self.ui.doubleSpinBoxGradReject.value()
        if eeg:
            reject['eeg'] = self.ui.doubleSpinBoxEEGReject.value()

        params = {
            'mag': mag,
            'grad': grad,
            'eeg': eeg,
            'reject': reject,
            'tmin': float(tmin),
            'tmax': float(tmax),
            'bstart': float(bstart),
            'bend': float(bend),
            'collection_name': collection_name,
            'events': self.events
        }
        return params

    def on_pushButtonAdd_clicked(self, checked=None):
        """
        """
        if checked is None:
            return

        event_params = {
            'mask': self.ui.spinBoxMask.value(),
            'event_id': self.ui.spinBoxEventID.value(),
        }

        if event_params not in self.events:
            self.events.append(event_params)
            self.update_events()

    def on_pushButtonClear_clicked(self, checked=None):
        if checked is None:
            return

        self.events = []
        self.update_events()

    def accept(self):
        """
        """
        if self.ui.listWidgetEvents.count() == 0:
            message = 'Cannot create epochs from empty list.'
            messagebox(self.parent, message)
            return

        try:
            params = self.collect_parameter_values()
        except Exception as exc:
            exc_messagebox(self, exc)
            return

        subject = self.experiment.active_subject

        if params['collection_name'] in subject.epochs:
            message = 'Epoch collection with the name exists.'
            messagebox(self.parent, message)
            return

        try:
            self.calculate_epochs(subject, params)
        except Exception as exc:
            exc_messagebox(self, exc)
            return

        self.experiment.save_experiment_settings()
        self.parent.initialize_ui()

        logging.getLogger('ui_logger').info('Finished.')

        self.close()

    def acceptBatch(self):
        """
        """
        experiment = self.experiment

        if self.ui.listWidgetEvents.count() == 0:
            message = 'Cannot create epochs from empty list.'
            messagebox(self.parent, message)
            return

        try:
            params = self.collect_parameter_values()
        except Exception as exc:
            exc_messagebox(self, exc)
            return

        selected_subject_names = self.batching_widget.selected_subjects
        for name, subject in self.experiment.subjects.items():
            if name in selected_subject_names:
                try:
                    self.calculate_epochs(subject, params)
                    subject.release_memory()
                except Exception as exc:
                    self.batching_widget.failed_subjects.append(
                        (subject, str(exc)))
                    logging.getLogger('ui_logger').exception(str(exc))

        self.batching_widget.cleanup()
        self.experiment.save_experiment_settings()
        self.parent.initialize_ui()

        logging.getLogger('ui_logger').info('Finished.')

        self.close()

    def on_pushButtonEdit_clicked(self, checked=None):
        if checked is None:
            return

        self.bitDialog = BitSelectionDialog(self, self.ui.spinBoxMask,
                                            self.ui.spinBoxEventID)

        self.bitDialog.show()

    def on_pushButtonHelp_clicked(self, checked=None):
        if checked is None:
            return

        help_message = (
            "Events are found in a following way. If only event "
            "id is set, events with exactly the same binary representation as "
            "event id are included in the final event list. If also mask is "
            "set, event list will also include events where binary digits in "
            "the places specified by the mask are not the same as in the "
            "event id, or in other words, only events where the digits we "
            "are interested in are the same as in the list of all events, "
            "are included. Binary representations are assumed to be 16 digits "
            "long. \n\nFor example event id of 0000010000010000 = 1040 and "
            "mask of 0000000000000011 = 3 would mean that first (rightmost) "
            "two digits can be 1 or 0, but anything else must be exactly as "
            "in the event id. Thus events with following id's would be allowed:"
            "\n\n0000010000010000 = 1040\n0000010000010001 = 1041\n"
            "0000010000010010 = 1042\n0000010000010011 = 1043")

        messagebox(self.parent, help_message, 'Mask help')

    def calculate_epochs(self, subject, params):
        experiment = self.experiment

        @threaded
        def create(*args, **kwargs):
            create_epochs_from_events(params, subject)

        create(do_meanwhile=self.parent.update_ui)
Exemplo n.º 24
0
class TFRDialog(QtWidgets.QDialog):
    """
    """

    def __init__(self, experiment, parent, epoch_names, default_name):
        """
        """
        QtWidgets.QDialog.__init__(self, parent)
        self.ui = Ui_TFRDialog()
        self.ui.setupUi(self)

        self.parent = parent
        self.epoch_names = epoch_names
        self.experiment = experiment

        subject = experiment.active_subject
        epochs = subject.epochs[epoch_names[0]].content

        self.ui.lineEditEpochName.setText(', '.join(epoch_names))

        if epochs.info.get('highpass'):
            self.ui.doubleSpinBoxMinFreq.setValue(
                max(int(np.ceil(epochs.info['highpass'])),
                    self.ui.doubleSpinBoxMinFreq.value()))

        if epochs.info.get('lowpass'):
            self.ui.doubleSpinBoxMaxFreq.setValue(
                min(int(np.floor(epochs.info['lowpass'])),
                    self.ui.doubleSpinBoxMaxFreq.value()))

        epoch_length = epochs.times[-1] - epochs.times[0]

        # try to use as many cycles as possible
        # (window ~= 10 * (n_cycles / (2.0 * np.pi * freq))
        minfreq = self.ui.doubleSpinBoxMinFreq.value()
        n_cycles = epoch_length * 2.0 * np.pi * minfreq / 10.0
        n_cycles = max(np.floor(n_cycles), 1)

        self.ui.doubleSpinBoxNcycles.setValue(n_cycles)

        # select factor such that minfreq / factor = n_cycles,
        # and then ceil
        factor = np.ceil(minfreq / float(n_cycles))
        self.ui.doubleSpinBoxCycleFactor.setValue(factor)

        self.batching_widget = BatchingWidget(
            experiment_getter=self.experiment_getter,
            parent=self,
            container=self.ui.groupBoxBatching,
            geometry=self.ui.batchingWidgetPlaceholder.geometry())
        self.ui.gridLayoutBatching.addWidget(self.batching_widget, 0, 0, 1, 1)

        self.ui.lineEditTFRName.setText(default_name)

    def experiment_getter(self):
        return self.experiment

    def accept(self):
        """
        """

        tfr_name = self.ui.lineEditTFRName.text()

        try:
            validate_name(tfr_name)
        except Exception as exc:
            exc_messagebox(self, exc)
            return

        minfreq = self.ui.doubleSpinBoxMinFreq.value()
        maxfreq = self.ui.doubleSpinBoxMaxFreq.value()
        decim = self.ui.spinBoxDecim.value()
        interval = self.ui.doubleSpinBoxFreqInterval.value()
        freqs = np.arange(minfreq, maxfreq, interval)

        subtract_evoked = self.ui.checkBoxSubtractEvoked.isChecked()

        if self.ui.radioButtonFixed.isChecked():
            n_cycles = self.ui.doubleSpinBoxNcycles.value()
        elif self.ui.radioButtonAdapted.isChecked():
            n_cycles = freqs / self.ui.doubleSpinBoxCycleFactor.value()

        experiment = self.experiment
        subject = experiment.active_subject

        try:
            create_tfr(subject, tfr_name, self.epoch_names,
                       freqs=freqs, decim=decim, n_cycles=n_cycles,
                       subtract_evoked=subtract_evoked,
                       do_meanwhile=self.parent.update_ui)

        except Exception as exc:
            exc_messagebox(self.parent, exc)
            return

        experiment.save_experiment_settings()
        self.parent.initialize_ui()

        logging.getLogger('ui_logger').info('Finished.')

        self.close()

    def acceptBatch(self):
        """
        """

        tfr_name = self.ui.lineEditTFRName.text()

        try:
            validate_name(tfr_name)
        except Exception as exc:
            exc_messagebox(self, exc)
            return

        minfreq = self.ui.doubleSpinBoxMinFreq.value()
        maxfreq = self.ui.doubleSpinBoxMaxFreq.value()
        decim = self.ui.spinBoxDecim.value()
        interval = self.ui.doubleSpinBoxFreqInterval.value()
        freqs = np.arange(minfreq, maxfreq, interval)

        subtract_evoked = self.ui.checkBoxSubtractEvoked.isChecked()

        if self.ui.radioButtonFixed.isChecked():
            n_cycles = self.ui.doubleSpinBoxNcycles.value()
        elif self.ui.radioButtonAdapted.isChecked():
            n_cycles = freqs / self.ui.doubleSpinBoxCycleFactor.value()

        experiment = self.experiment

        selected_subject_names = self.batching_widget.selected_subjects
        for name, subject in self.experiment.subjects.items():
            if name in selected_subject_names:
                try:
                    create_tfr(subject, tfr_name,
                               self.epoch_names, freqs=freqs,
                               decim=decim, n_cycles=n_cycles,
                               subtract_evoked=subtract_evoked,
                               do_meanwhile=self.parent.update_ui)
                    subject.release_memory()
                except Exception as exc:
                    self.batching_widget.failed_subjects.append(
                        (subject, str(exc)))
                    logging.getLogger('ui_logger').exception(str(exc))

        self.batching_widget.cleanup()
        experiment.save_experiment_settings()
        self.parent.initialize_ui()

        logging.getLogger('ui_logger').info('Finished')

        self.close()
class CreateReportDialog(QtWidgets.QDialog):
    """ Implements functionalities for widgets defined in the corresponding UI-file.
    """
    def __init__(self, experiment, parent, selected_spectrum, default_name,
                 handler):
        """
        """
        QtWidgets.QDialog.__init__(self, parent)
        self.ui = Ui_CreateReportDialog()
        self.ui.setupUi(self)

        self.parent = parent
        self.experiment = experiment
        self.handler = handler
        self.selected_spectrum = selected_spectrum

        # initialize frequency limits from spectrum data
        spectrum_item = experiment.active_subject.spectrum[selected_spectrum]
        minfreq = spectrum_item.freqs[0]
        maxfreq = spectrum_item.freqs[-1]
        self.ui.doubleSpinBoxFreqMin.setValue(minfreq)
        self.ui.doubleSpinBoxFreqMax.setValue(maxfreq)

        # add a general batching widget to dialog
        self.batching_widget = BatchingWidget(
            experiment_getter=self.experiment_getter,
            parent=self,
            container=self.ui.groupBoxBatching,
            geometry=self.ui.batchingWidgetPlaceholder.geometry())
        self.ui.gridLayoutBatching.addWidget(self.batching_widget, 0, 0, 1, 1)

        self.ui.lineEditName.setText(default_name)

    def experiment_getter(self):
        return self.experiment

    def create_report(self, subject, selected_spectrum):
        """ Collect parameters from the dialog and creates an FOOOFReport item
        """

        report_name = validate_name(self.ui.lineEditName.text())

        spectrum = subject.spectrum.get(selected_spectrum)

        peak_width_low = self.ui.doubleSpinBoxPeakWidthLow.value()
        peak_width_high = self.ui.doubleSpinBoxPeakWidthHigh.value()
        peak_threshold = self.ui.doubleSpinBoxPeakThreshold.value()
        max_n_peaks = self.ui.spinBoxMaxNPeaks.value()
        aperiodic_mode = self.ui.comboBoxAperiodicMode.currentText()
        minfreq = self.ui.doubleSpinBoxFreqMin.value()
        maxfreq = self.ui.doubleSpinBoxFreqMax.value()

        peak_width_limits = [peak_width_low, peak_width_high]
        peak_threshold = peak_threshold
        max_n_peaks = max_n_peaks
        aperiodic_mode = aperiodic_mode
        freq_range = [minfreq, maxfreq]

        # As meggie spectrum items can contain data for multiple conditions,
        # reports are also created for all those conditions, and dict is used.
        report_content = {}

        for key, data in spectrum.content.items():

            fg = FOOOFGroup(peak_width_limits=peak_width_limits,
                            peak_threshold=peak_threshold,
                            max_n_peaks=max_n_peaks,
                            aperiodic_mode=aperiodic_mode,
                            verbose=False)

            @threaded
            def fit(**kwargs):
                """ Run fitting in a separate thread so that UI stays responsive
                """
                fg.fit(spectrum.freqs, data, freq_range)

            fit(do_meanwhile=self.parent.update_ui)

            logging.getLogger('ui_logger').info('FOOOF results for ' +
                                                subject.name + ', ' +
                                                'condition: ' + key)
            # Log the textual report
            logging.getLogger('ui_logger').info(
                gen_results_fg_str(fg, concise=True))

            report_content[key] = fg

        params = {
            'conditions': list(spectrum.content.keys()),
            'based_on': selected_spectrum,
            'ch_names': spectrum.ch_names,
        }

        fooof_directory = subject.fooof_report_directory

        # Create a container item that meggie understands,
        # and which holds the report data
        report = FOOOFReport(report_name, fooof_directory, params,
                             report_content)

        # save report data to fs
        report.save_content()

        # and add the report item to subject
        subject.add(report, 'fooof_report')

    def accept(self):
        """ Start item creation for current subject
        """
        subject = self.experiment.active_subject
        selected_spectrum = self.selected_spectrum

        params = {}
        try:
            params['name'] = validate_name(self.ui.lineEditName.text())
        except Exception as exc:
            exc_messagebox(self, exc)
            return

        params['peak_width_low'] = self.ui.doubleSpinBoxPeakWidthLow.value()
        params['peak_width_high'] = self.ui.doubleSpinBoxPeakWidthHigh.value()
        params['peak_threshold'] = self.ui.doubleSpinBoxPeakThreshold.value()
        params['max_n_peaks'] = self.ui.spinBoxMaxNPeaks.value()
        params['aperiodic_mode'] = self.ui.comboBoxAperiodicMode.currentText()
        params['minfreq'] = self.ui.doubleSpinBoxFreqMin.value()
        params['maxfreq'] = self.ui.doubleSpinBoxFreqMax.value()

        try:
            self.handler(subject, params)
            self.experiment.save_experiment_settings()
        except Exception as exc:
            exc_messagebox(self, exc)
            return

        # Update experiment file and the window
        self.parent.initialize_ui()

        self.close()

    def acceptBatch(self):
        """ Start item creation of all subjects selected in the batching widget
        """
        selected_spectrum = self.selected_spectrum
        experiment = self.experiment

        params = {}
        try:
            params['name'] = validate_name(self.ui.lineEditName.text())
        except Exception as exc:
            exc_messagebox(self, exc)
            return

        params['peak_width_low'] = self.ui.doubleSpinBoxPeakWidthLow.value()
        params['peak_width_high'] = self.ui.doubleSpinBoxPeakWidthHigh.value()
        params['peak_threshold'] = self.ui.doubleSpinBoxPeakThreshold.value()
        params['max_n_peaks'] = self.ui.spinBoxMaxNPeaks.value()
        params['aperiodic_mode'] = self.ui.comboBoxAperiodicMode.currentText()
        params['minfreq'] = self.ui.doubleSpinBoxFreqMin.value()
        params['maxfreq'] = self.ui.doubleSpinBoxFreqMax.value()

        selected_subject_names = self.batching_widget.selected_subjects

        # Loop through every subject creating items and collecting info from
        # failed cases
        for name, subject in self.experiment.subjects.items():
            if name in selected_subject_names:
                try:
                    self.handler(subject, params)
                    subject.release_memory()
                except Exception as exc:
                    self.batching_widget.failed_subjects.append(
                        (subject, str(exc)))
                    logging.getLogger('ui_logger').exception(str(exc))

        # if any fails, tell user about them
        self.batching_widget.cleanup()

        # and update experiment file and the UI
        try:
            self.experiment.save_experiment_settings()
        except Exception as exc:
            exc_messagebox(self.parent, exc)

        self.parent.initialize_ui()

        self.close()