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()
Example #2
0
    def accept(self):
        """ Add new subjects. """
        for i in range(self.ui.listWidgetFileNames.count()):
            item = self.ui.listWidgetFileNames.item(i)
            raw_path = item.text()
            basename = os.path.basename(raw_path)
            subject_name = basename.split('.')[0]
            experiment = self.parent.experiment
            old_names = experiment.subjects.keys()

            try:
                subject_name = next_available_name(old_names, subject_name)

                @threaded
                def _create_subject():
                    experiment.create_subject(subject_name, basename,
                                              raw_path)
                
                _create_subject(do_meanwhile=self.parent.update_ui)

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

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

        self.close()
    def accept(self):
        workspace = self.ui.LineEditFilePath.text()
        if not os.path.isdir(workspace):
            message = 'Workspace must be set to proper path.'
            messagebox(self.parent, message)
            return
        self.prefs.workspace = workspace

        if self.ui.checkBoxAutomaticOpenPreviousExperiment.isChecked():
            autoLoadLastOpenExp = True
        else:
            autoLoadLastOpenExp = False
        self.prefs.auto_load_last_open_experiment = autoLoadLastOpenExp  # noqa

        self.prefs.active_plugins = self.active_plugins

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

        # Plugins can add new actions to existing pipelines.
        self.parent.reconstruct_tabs()
        self.parent.initialize_ui()

        self.close()
Example #4
0
    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)
Example #5
0
    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()
Example #6
0
    def run(self):

        subject = self.experiment.active_subject
        try:
            self.handler(subject, {})
        except Exception as exc:
            exc_messagebox(self.window, exc)
Example #7
0
    def accept(self):
        if not self.ica:
            return

        raw = self.experiment.active_subject.get_raw()

        indices = [self.component_info[name] for name in self.removed]

        try:

            @threaded
            def apply_ica_wrapper():
                self.ica.apply(raw, exclude=indices)

            apply_ica_wrapper(do_meanwhile=self.parent.update_ui)

            self.experiment.active_subject.save()
            self.experiment.active_subject.ica_applied = True
            self.experiment.save_experiment_settings()

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

        self.parent.initialize_ui()

        # for logging purposes, call the handler
        if self.on_apply:
            self.params['exclude'] = indices
            self.on_apply(self.experiment.active_subject, self.params)

        self._reset()
        self.close()
Example #8
0
    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()
Example #9
0
    def __init__(self, application):
        QtWidgets.QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        
        # set default ratio of splitter
        self.ui.splitterTopBottom.setStretchFactor(0, 2)
        self.ui.splitterTopBottom.setStretchFactor(1, 1)

        self.experiment = None

        self._setup_loggers()

        # Direct output to console
        if not sys.argv[-1] == 'debug':
            self._direct_output()

        # For storing and handling program wide preferences.
        self.prefs = PreferencesHandler()

        auto_load = self.prefs.auto_load_last_open_experiment
        previous_name = self.prefs.previous_experiment_name
        if auto_load and previous_name:
            try:
                exp = open_existing_experiment(self.prefs)
                self.experiment = exp
                self.prefs.previous_experiment_name = exp.path
                self.prefs.write_preferences_to_disk()
                logging.getLogger('ui_logger').info('Opening experiment ' + exp.path)
            except Exception as exc:
                self.prefs.previous_experiment_name = ''
                exc_messagebox(self, exc)

        self.reconstruct_tabs()
        self.initialize_ui()
Example #10
0
        def handler(accepted):
            if not accepted:
                return
            
            n_successful = 0
            for index in selIndexes:
                subject_name = index.data()
                try:
                    self.experiment.remove_subject(subject_name)
                    n_successful += 1
                except Exception:
                    logging.getLogger('ui_logger').exception('')


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

            n_total = len(selIndexes)

            if n_successful != n_total:
                message = ("Could not remove all subjects completely. "
                           "Please check console below for details.")
                messagebox(self, message)

            self.initialize_ui()
Example #11
0
    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()
Example #12
0
    def accept(self):
        if self.ui.lineEditExperimentName.text() == '':
            message = 'Give experiment a name.'
            messagebox(self.parent, message)
            return

        selected_pipeline = ""
        for button_idx, radio_button in enumerate(self.pipeline_buttons):
            if radio_button.isChecked():
                selected_pipeline = self.pipelines[button_idx][0]
                break

        try:
            experiment = initialize_new_experiment(
                self.ui.lineEditExperimentName.text(),
                self.ui.lineEditAuthor.text(), self.parent.prefs)

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

        self.parent.experiment = experiment
        self.parent.reconstruct_tabs()
        self.parent.initialize_ui()
        self.close()
Example #13
0
    def on_actionOpenExperiment_triggered(self, checked=None):
        """
        """
        if checked is None:
            return

        if self.experiment is not None:
            directory = self.experiment.workspace
        else:
            directory = ''

        path = QtCore.QDir.toNativeSeparators(
            str(
                QtWidgets.QFileDialog.getExistingDirectory(
                    self, "Select experiment directory", directory)))

        if path == '':
            return

        logging.getLogger('ui_logger').info('Opening experiment ' + path)

        try:
            exp = self.experimentHandler.open_existing_experiment(
                self.preferencesHandler, path=path)
            self.experiment = exp
            self.initialize_ui()
        except Exception as exc:
            exc_messagebox(self, exc)

        self.preferencesHandler.write_preferences_to_disk()
    def accept(self, *args, **kwargs):
        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()
        params['intervals'] = intervals
        params['name'] = spectrum_name

        try:
            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

        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 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()
Example #17
0
    def on_pushButtonCompute_clicked(self, checked=None):
        """
        """
        if checked is None:
            return

        # start by clearing out the previous things
        self.reset()

        n_components = self.ui.doubleSpinBoxNComponents.value()
        method = 'fastica'
        max_iter = self.ui.spinBoxMaxIter.value()

        raw = self.experiment.active_subject.get_raw()

        @threaded
        def _compute_ica():
            return compute_ica(raw, n_components, method, max_iter)

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

        for idx in range(self.ica.n_components_):
            label = 'Component ' + str(idx)
            self.ui.listWidgetNotRemoved.addItem(label)
            self.component_info[label] = idx
            self.not_removed.append(label)

        logging.getLogger('ui_logger').info('ICA finished.')
Example #18
0
    def handler(ch_name, title, legend, ylim, window, window_len):
        try:
            ch_idx = info['ch_names'].index(ch_name)

            # create new evoked based on old
            new_evokeds = {}
            for key, evoked in content.items():
                new_evoked = evoked.copy()

                # smoothen
                if window:
                    try:
                        new_evoked.data[ch_idx] = smooth_signal(
                            new_evoked.data[ch_idx],
                            window_len=window_len,
                            window=window)
                    except ValueError as exc:
                        exc_messagebox(window, exc)

                new_evoked.comment = legend[key]
                new_evokeds[legend[key]] = new_evoked

            ylim = {ch_types[ch_name]: ylim}

            mne.viz.plot_compare_evokeds(new_evokeds,
                                         title=title,
                                         picks=[ch_idx],
                                         colors=colors,
                                         ylim=ylim,
                                         show_sensors=False)
        except Exception as exc:
            exc_messagebox(window, exc)
Example #19
0
        def evs_from_annots():
            try:
                events_from_annotations(subject, self.items)
            except Exception as exc:
                exc_messagebox(self, exc)
                return

            subject.save()
Example #20
0
 def handler(selected_option):
     try:
         if selected_option == 'channel_averages':
             _plot_evoked_averages(experiment, evoked)
         else:
             _plot_evoked_topo(experiment, evoked)
     except Exception as exc:
         exc_messagebox(window, exc)
Example #21
0
        def option_handler(params):
            params['channel_groups'] = self.experiment.channel_groups
            params['name'] = selected_name

            try:
                self.handler(self.experiment.active_subject, params)
            except Exception as exc:
                exc_messagebox(self.window, exc)
Example #22
0
 def option_handler(selected_option):
     params = {'name': selected_name, 
               'output_option': selected_option,
               'channel_groups': self.experiment.channel_groups}
     try:
         self.handler(self.experiment.active_subject, params)
     except Exception as exc:
         exc_messagebox(self.window, exc)
Example #23
0
 def handler(selected_option):
     try:
         if selected_option == 'channel_averages':
             save_channel_averages(experiment, selected_name)
         else:
             save_all_channels(experiment, selected_name)
     except Exception as exc:
         exc_messagebox(window, exc)
Example #24
0
 def handler(selected_option):
     try:
         if selected_option == 'channel_averages':
             plot_spectrum_averages(experiment, selected_name)
         else:
             plot_spectrum_topo(experiment, selected_name)
     except Exception as exc:
         exc_messagebox(window, exc)
Example #25
0
 def group_handler(groups):
     params = {'based_on': selected_name, 
               'name': name,
               'groups': groups}
     try:
         self.handler(self.experiment.active_subject, params)
         self.experiment.save_experiment_settings()
         self.window.initialize_ui()
     except Exception as exc:
         exc_messagebox(self.window, exc)
Example #26
0
    def update_contents(self):
        try:
            logfile_path = os.path.join(self.parent.experiment.workspace,
                                        self.parent.experiment.name, 'meggie.log')
            log_file = open(logfile_path, 'r')

            # logging.getLogger('ui_logger').info(
            #     'Showing last 10000 lines of ' + logfile_path)

            last_lines = filemanager.tail(log_file, lines=self.lines)

            # track lines that start log entries as there can be multiline
            # entries.

            meggie_idxs = []
            mne_idxs = []
            mne_call_idxs = []
            all_idxs = []
            for line_idx, line in enumerate(last_lines):
                if line.startswith('Meggie:'):
                    meggie_idxs.append(line_idx)
                    all_idxs.append(line_idx)
                elif line.startswith('MNE call:'):
                    mne_call_idxs.append(line_idx)
                    all_idxs.append(line_idx)
                elif line.startswith('MNE:'):
                    mne_idxs.append(line_idx)
                    all_idxs.append(line_idx)

            self.ui.textEditBrowser.clear()

            selected_lines = []
            for idx_idx, line_idx in enumerate(all_idxs):
                if idx_idx != len(all_idxs) - 1:
                    next_idx = all_idxs[idx_idx + 1]
                else:
                    next_idx = -1
                if line_idx in meggie_idxs:
                    if self.show_meggie:
                        selected_lines.extend(
                            last_lines[line_idx:next_idx])
                elif line_idx in mne_idxs:
                    if self.show_mne:
                        selected_lines.extend(
                            last_lines[line_idx:next_idx])
                elif line_idx in mne_call_idxs:
                    if self.show_mne_call:
                        selected_lines.extend(
                            last_lines[line_idx:next_idx])

            for line in selected_lines:
                self.ui.textEditBrowser.append(line.strip('\n'))

        except Exception as exc:
            exc_messagebox(self, exc)
Example #27
0
    def on_pushButtonPlotTopographies_clicked(self, checked=None):
        if checked is None:
            return

        raw = self.experiment.active_subject.get_raw()

        try:
            plot_topographies(self.ica, len(self.component_info))
        except Exception as exc:
            exc_messagebox(self, exc)
            return
Example #28
0
    def on_pushButtonPlotSources_clicked(self, checked=None):
        if checked is None:
            return

        raw = self.experiment.active_subject.get_raw()

        try:
            plot_sources(raw, self.ica)
        except Exception as exc:
            exc_messagebox(self, exc)
            return
Example #29
0
    def run(self):

        try:
            selected_name = self.data['outputs']['epochs'][0]
        except IndexError as exc:
            return

        subject = self.experiment.active_subject
        try:
            self.handler(subject, {'name': selected_name})
        except Exception as exc:
            exc_messagebox(self.window, exc)
Example #30
0
 def handler(output, condition, blmode, blstart, blend, tmin, tmax, fmin,
             fmax):
     try:
         if output == 'all_channels':
             save_tse_all_channels(experiment, selected_name, blmode,
                                   blstart, blend, tmin, tmax, fmin, fmax)
         else:
             save_tse_channel_averages(experiment, selected_name, blmode,
                                       blstart, blend, tmin, tmax, fmin,
                                       fmax)
     except Exception as exc:
         exc_messagebox(window, exc)