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_pushButtonRemoveSubject_clicked(self, checked=None): """ Completely removes selected subjects from the experiment """ if checked is None: return selIndexes = self.ui.listWidgetSubjects.selectedIndexes() if selIndexes == []: return message = 'Permanently remove the selected subjects and the related files?' reply = QtWidgets.QMessageBox.question( self, 'Delete selected subjects', message, QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No, QtWidgets.QMessageBox.No) failures = [] if reply == QtWidgets.QMessageBox.Yes: for index in selIndexes: subject_name = index.data() try: self.experiment.remove_subject(subject_name) except Exception: failures.append(subject_name) if failures: msg = ''.join([ 'Could not remove the contents of the subject ', 'folder for following subjects: ', '\n'.join(failures) ]) messagebox(self, msg) self.experiment.save_experiment_settings() self.initialize_ui()
def _open_mne_coreg(window, on_close, raw_path, subjects_dir): """ Opens mne coreg with some small changes. """ # Open the mne coregistration UI open_message = ( "An external coregistration GUI is now opened. You should " "fit the digization points to the scalp and then click save " "on the right panel. The trans file should be saved as " "`experiment_folder`/`subject_name`/coregistrations/" "`coreg_name`/`subject_name`-trans.fif") messagebox(window, open_message) logging.getLogger('ui_logger').info('Opening coregistration utility.') gui = mne.gui.coregistration(inst=raw_path, subject='fsaverage', subjects_dir=subjects_dir) def close_wrapper(*args, **kwargs): if not gui._accept_close_event: return logging.getLogger('ui_logger').info('Coregistration utility closed.') on_close() gui._renderer._window_close_connect(close_wrapper)
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): 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()
def on_pushButtonActivateSubject_clicked(self, checked=None): if checked is None: return items = self.ui.listWidgetSubjects.selectedItems() if not items: return subject_name = items[0].text() if self.experiment.active_subject: if subject_name == self.experiment.active_subject.name: return previous_subject = self.experiment.active_subject try: @threaded def activate(subject_name): self.experiment.activate_subject(subject_name) activate(subject_name, do_meanwhile=self.update_ui) self.reconstruct_tabs() except Exception as exc: self.experiment.active_subject = None messagebox(self, "Could not activate the subject.") if previous_subject: message = "Couldn't activate the subject, resuming to previous one." logging.getLogger('ui_logger').info(message) self.experiment.activate_subject(previous_subject.name) self.initialize_ui()
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()
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 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()
def handler(self, subject, params): raw = subject.get_raw() if not raw.info['projs']: messagebox(self.window, "Data does not contain any projection vectors") return fig = raw.plot_projs_topomap() elems = ['projections', subject.name] fig.canvas.set_window_title('_'.join(elems)) fig.suptitle(' '.join(elems))
def on_actionShowLog_triggered(self, checked=None): if checked is None: return if not self.experiment: message = 'Please open an experiment first.' messagebox(self, message) return dialog = LogDialog(self) dialog.show()
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 on_pushButtonAddSubjects_clicked(self, checked=None): if checked is None: return # Check that we have an experiment that we can add a subject to if not self.experiment: msg = ('No active experiment to add a subject to. Load an ' 'experiment or make a new one, then try again.') messagebox(self, msg) return dialog = AddSubjectDialog(self) dialog.show()
def on_actionCreateExperiment_triggered(self, checked=None): if checked is None: return if not self.prefs.workspace: messagebox(self, "Please set up a workspace " "(a place where experiments are stored) in preferences " "before creating experiments") dialog = PreferencesDialog(self) dialog.show() else: dialog = CreateExperimentDialog(self) dialog.show()
def projections(experiment, data, window): """ """ subject = experiment.active_subject raw = subject.get_raw() if not raw.info['projs']: messagebox(window, "Raw contains no projection vectors") return fig = raw.plot_projs_topomap() title = 'projections_{0}'.format(subject.name) fig.canvas.set_window_title(title) fig.suptitle(title)
def cleanup(self, parent=None): if len(self.failed_subjects) > 0: rows = [] rows.append('Failed calculation for subjects:') for subject, message in self.failed_subjects: rows.append(subject.name + ' (' + message + ')') if not parent: parent = self.parent.parent messagebox(parent, '\n'.join(rows)) self.failed_subjects = [] self.ui.checkBoxBatch.setChecked(False) self.ui.functionalityWidget.hide()
def on_actionCreateExperiment_triggered(self, checked=None): """ """ if checked is None: return if not self.preferencesHandler.working_directory: messagebox( self, "Please set up a working directory before creating experiments" ) self.check_workspace() else: dialog = CreateExperimentDialog(self) dialog.experimentCreated.connect(self.set_experiment) dialog.show()
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 cleanup(self): """ Cleans the batching widget after use. """ if len(self.failed_subjects) > 0: rows = [] rows.append('Failed calculation for subjects:') for subject, message in self.failed_subjects: rows.append(subject.name + ' (' + message + ')') parent = self.parent.parent messagebox(parent, '\n'.join(rows)) self.failed_subjects = [] self.ui.checkBoxBatch.setChecked(False) self.ui.functionalityWidget.hide()
def accept(self): n_successful = 0 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, raw_path) _create_subject(do_meanwhile=self.parent.update_ui) n_successful += 1 except Exception as exc: logging.getLogger('ui_logger').exception('') try: self.parent.experiment.save_experiment_settings() except Exception as exc: exc_messagebox(self, exc) return n_total = self.ui.listWidgetFileNames.count() if n_total != n_successful: message = ("Only {0} / {1} subjects added successfully. " "Please check console below for details.") messagebox(self.parent, message.format(n_successful, n_total)) message = ('{0} / {1} subjects added successfully.').format( n_successful, n_total) logging.getLogger('ui_logger').info(message) self.parent.initialize_ui() self.close()
def on_treeWidgetActions_itemDoubleClicked(self, item): if item.childCount() == 0: # try creating a pretty formatted details dialog try: match = re.compile("([a-zA-Z0-9_]*): (.*)").match(item.text(0)) if not match: return key = match.group(1) val = match.group(2) try: obj = json.loads(val) except Exception as exc: obj = val message = pformat(obj) messagebox(self, message) except Exception as exc: logging.getLogger('ui_logger').exception("") return
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 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 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 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 accept(self): """Send parameters to experimentHandler for the creation of a new experiment.""" if self.ui.lineEditExperimentName.text() == '': message = 'Give experiment a name.' messagebox(self.parent, message) return expDict = { 'name': self.ui.lineEditExperimentName.text(), 'author': self.ui.lineEditAuthor.text(), } try: experiment = self.parent.experimentHandler.initialize_new_experiment( expDict, ) except Exception as exc: exc_messagebox(self, exc) return self.experimentCreated.emit(experiment) self.close()
def on_pushButtonReset_clicked(self, checked=None): if checked is None: return subject = self.parent.experiment.active_subject if not subject: messagebox(self.parent, 'To reset, active subject is needed') return info = subject.get_raw().info if self.ui.radioButtonEEG.isChecked(): self.eeg_channel_groups = get_default_channel_groups(info, 'eeg') self.ui.listWidgetChannelGroups.clear() for ch_name in sorted(self.eeg_channel_groups.keys()): self.ui.listWidgetChannelGroups.addItem(ch_name) else: meg_defaults = get_default_channel_groups(info, 'meg') self.meg_channel_groups = meg_defaults self.ui.listWidgetChannelGroups.clear() for ch_name in sorted(self.meg_channel_groups.keys()): self.ui.listWidgetChannelGroups.addItem(ch_name)
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 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 run(self): """ Called when action is initiated """ messagebox("Running action " + self.action_spec['id'])
def on_pushButtonSetChannels_clicked(self, checked=None): if checked is None: return subject = self.parent.experiment.active_subject if not subject: messagebox(self.parent, 'To set channels, active subject is needed') return try: selected_item = self.ui.listWidgetChannelGroups.selectedItems()[0] except IndexError: messagebox(self.parent, 'Select a channel group first') return info = subject.get_raw().info if self.ui.radioButtonEEG.isChecked(): if mne.pick_types(info, meg=False, eeg=True).size == 0: messagebox(self.parent, 'No EEG channels found') return ch_names = self.eeg_channel_groups[selected_item.text()] try: ch_idxs = [info['ch_names'].index(ch_name) for ch_name in ch_names] except ValueError: messagebox(self.parent, "Channel names in the group " "and the current subject don't match") return ch_groups = [[], ch_idxs] try: fig, selection = mne.viz.plot_sensors(info, kind='select', ch_type='eeg', ch_groups=ch_groups, show=False) except RuntimeError: messagebox(self.parent, 'Could not plot sensors. Is the montage set?') return else: if mne.pick_types(info, meg=True, eeg=False).size == 0: messagebox(self.parent, 'No MEG channels found') return ch_names = self.meg_channel_groups[selected_item.text()] try: ch_idxs = [info['ch_names'].index(ch_name) for ch_name in ch_names] except ValueError: messagebox(self.parent, "Channel names in the group " "and the current subject don't match") return ch_groups = [[], ch_idxs] fig, selection = mne.viz.plot_sensors(info, kind='select', ch_type='mag', ch_groups=ch_groups, show=False) # make markers bigger for child in fig.axes[0].get_children(): if isinstance(child, mpl.collections.PathCollection): child.set_sizes([100]) child.set_lw([1]) break plt.show(block=True) if self.ui.radioButtonMEG.isChecked(): if selection: all_megs = [] for ch_name in selection: all_megs.extend(get_triplet_from_mag(info, ch_name)) self.meg_channel_groups[selected_item.text()] = all_megs else: if selection: self.eeg_channel_groups[selected_item.text()] = selection