def call_cutout(self): self.spec_path = self.spectra_user_input.text() if self.spec_path == "": self.spectra_user_input.setStyleSheet( "background-color: rgba(255, 0, 0, 128);") info = QMessageBox.information( self, "Error", "Please provide directory containing NIRSpec spectra files.") return else: self.spectra_user_input.setStyleSheet("") if not os.path.isdir(self.spec_path): self.spectra_user_input.setStyleSheet( "background-color: rgba(255, 0, 0, 128);") info = QMessageBox.information( self, "Error", "Broken path:\n\n" + self.spec_path) return try: path = "/Users/rgeda/config.py" os.system("Python %s" % (path)) #self.abspath, self.postage_path = cutout(self.spec_path) #self.postage_path_display.setText(self.postage_path) except: info = QMessageBox.critical(self, "Error", "Cutout tool failed: " + str(e))
def onItemClick(self): text = self.ui.stocks_tree.currentItem().text(0) stock_name_pattern = re.compile("([\u4e00-\u9fa5]{3,})-.*") stock_id_pattern = re.compile("(s[h|z]\d{6})-.*") stock_id = stock_id_pattern.search(text) stock_name = stock_name_pattern.search(text) QMessageBox.information(self, "股票提示", text) width = self.ui.webView.width() height = self.ui.webView.height() start_date = self.ui.start_date_edit.date() start_date = start_date.toPyDate() start_date = start_date.strftime("%Y/%m/%d") end_date = self.ui.end_date_edit.date() end_date = end_date.toPyDate() end_date = end_date.strftime("%Y/%m/%d") action = self.ui.stock_option_combobox.currentText() action = str(action) interval = self.ui.interval_combobox.currentText() interval = str(interval) stock_info = stock_name.group(1) + '-' + stock_id.group( 1) + '-' + self.choice stock_render_page(stock_info, start_date, end_date, interval, width, height) self.ui.webView.reload() self.ui.webView.repaint() self.ui.webView.update()
def verify_input(self): """ Process information in the input boxes. Checks if user inputs are functional. Returns ------- success : bool True if no input errors, False otherwise. """ self.statusBar().showMessage("Reading input") success = True self.spec_path = self.spectra_user_input.text() self.save_file_name = self.filename_user_input.text() if self.spec_path == "": self.spectra_user_input.setStyleSheet( "background-color: rgba(255, 0, 0, 128);") success = False else: self.spectra_user_input.setStyleSheet("") if self.save_file_name == "" or "/" in self.save_file_name or "\\" in self.save_file_name: self.filename_user_input.setStyleSheet( "background-color: rgba(255, 0, 0, 128);") success = False else: self.filename_user_input.setStyleSheet("") if self.add_postage_radio.isChecked(): self.postage_path = self.postage_path_display.text() if self.postage_path == "": self.postage_path_display.setStyleSheet( "background-color: rgba(255, 0, 0, 128);") success = False else: self.postage_path_display.setStyleSheet( "background-color: rgba(255, 255, 255, 0);") if success: if not os.path.isdir(self.spec_path): info = QMessageBox.information( self, "Error", "Broken path:\n\n" + self.spec_path) self.spectra_user_input.setStyleSheet( "background-color: rgba(255, 0, 0, 128);") success = False else: if not self.abs_path and not self.custom_save_path: self.save_file_dir = self.spec_path if self.add_postage_radio.isChecked(): if not os.path.isdir(self.postage_path): info = QMessageBox.information( self, "Error", "Broken path:\n\n" + self.postage_path) self.postage_path_display.setStyleSheet( "background-color: rgba(255, 0, 0, 128);") success = False return success
def createItemFromLabel(self, label): if self.count() >= 1000: QMessageBox.information(self, 'Warning', '标签数量需小于1000.') return item = QtWidgets.QListWidgetItem() item.setData(Qt.UserRole, label) return item
def show_help(self): QMessageBox.information( self, _('How to use'), _("The project console provides API to the project.<br>" "For example, try run myprint(self.database).<br>" "Due to Cython compiler, use myprint() for print().<br>" "<b>TODO</b> add more.<br>"))
def mask_manager(self): if self.settings.roi is None: QMessageBox.information(self, "No segmentation", "Cannot create mask without segmentation") return dial = MaskDialog(self.settings) dial.exec_()
def addChoice(self): if len(self._possible_items) == 0: QMessageBox.information( self, "No items", "No items available for selection!" ) else: item, ok = QInputDialog.getItem( self, "Select a case", "Select a case to add to the case list:", self._possible_items, ) if ok: item = str(item).strip() text = str(self._list_edit_line.text()).rstrip() if len(text) == 0: text = item + ", " elif text.endswith(","): text += " " + item else: text += ", " + item self._list_edit_line.setText(text)
def set_umr_namelist(self): """Set UMR excluded modules name list""" arguments, valid = QInputDialog.getText(self, _('UMR'), _("Set the list of excluded modules as " "this: <i>numpy, scipy</i>"), QLineEdit.Normal, ", ".join(self.get_option('umr/namelist'))) if valid: arguments = to_text_string(arguments) if arguments: namelist = arguments.replace(' ', '').split(',') fixed_namelist = [module_name for module_name in namelist if programs.is_module_installed(module_name)] invalid = ", ".join(set(namelist)-set(fixed_namelist)) if invalid: QMessageBox.warning(self, _('UMR'), _("The following modules are not " "installed on your machine:\n%s" ) % invalid, QMessageBox.Ok) QMessageBox.information(self, _('UMR'), _("Please note that these changes will " "be applied only to new Python/IPython " "consoles"), QMessageBox.Ok) else: fixed_namelist = [] self.set_option('umr/namelist', fixed_namelist)
def add_dataset(self, _e): while True: name, ok = QInputDialog.getText( self, 'New Dataset', 'Enter the name of the new dataset:') if ok: try: # TODO: how to set defaults? self.model.add_dataset(Dataset(name=name)) #parameter=0)) except IntegrityError: self.model.session.rollback() QMessageBox.information( self, "Cannot proceed", "This dataset name already exists, \ please select a different one (or cancel).", defaultButton=QMessageBox.Ok) else: self.tableViewDataset.model().change_layout() self.statusBar().showMessage('Added dataset.') # self.tableViewDataset.selectRow(len(self.model.dataset) - 1) break else: # cancel self.statusBar().showMessage('Cancelled.') return # exit loop if len(self.model.get_dataset()) == 1: # first entry after being empty self.tableViewDataset.selectRow(0)
def call_cutout(self): self.spec_path = self.spectra_user_input.text() if self.spec_path == "": self.spectra_user_input.setStyleSheet( "background-color: rgba(255, 0, 0, 128);") info = QMessageBox.information( self, "Error", "Please provide directory containing NIRSpec spectra files.") return else: self.spectra_user_input.setStyleSheet("") if not os.path.isdir(self.spec_path): self.spectra_user_input.setStyleSheet( "background-color: rgba(255, 0, 0, 128);") info = QMessageBox.information( self, "Error", "Broken path:\n\n" + self.spec_path) return if self.CutoutTool is not None: if self.CutoutTool.isVisible(): info = QMessageBox.information( self, "Status", "Error: Cutout tool is still running.") self.CutoutTool.raise_() return else: self.CutoutTool = None try: self.CutoutTool = NIRSpecCutoutTool(self.parent.session, parent=self, spec_path=self.spec_path, TableGen=self) except: info = QMessageBox.critical(self, "Error", "Cutout tool failed: " + str(e))
def read_files(self): """Read file and save in database.""" table_name = self.twg_database.get_current_table_name() if table_name is None: return object_class = self._table_object_dict[table_name] fns = _QFileDialog.getOpenFileNames( self, caption='Read files', directory=self.directory, filter="Text files (*.txt *.dat)") if isinstance(fns, tuple): fns = fns[0] if len(fns) == 0: return try: idns = [] for filename in fns: obj = object_class( database_name=self.database_name, mongo=self.mongo, server=self.server) obj.read_file(filename) idn = obj.db_save() idns.append(idn) msg = 'Added to database table.\nIDs: ' + str(idns) self.update_database_tables() _QMessageBox.information(self, 'Information', msg, _QMessageBox.Ok) except Exception: _traceback.print_exc(file=_sys.stdout) msg = 'Failed to read files and save values in database.' _QMessageBox.critical(self, 'Failure', msg, _QMessageBox.Ok) return
def call_cutout(self): self.spec_path = self.spectra_user_input.text() if self.spec_path == "": self.spectra_user_input.setStyleSheet("background-color: rgba(255, 0, 0, 128);") info = QMessageBox.information(self, "Error", "Please provide directory containing NIRSpec spectra files.") return else: self.spectra_user_input.setStyleSheet("") if not os.path.isdir(self.spec_path): self.spectra_user_input.setStyleSheet("background-color: rgba(255, 0, 0, 128);") info = QMessageBox.information(self, "Error", "Broken path:\n\n"+self.spec_path) return if self.CutoutTool is not None: if self.CutoutTool.isVisible(): info = QMessageBox.information(self, "Status", "Error: Cutout tool is still running.") self.CutoutTool.raise_() return else: self.CutoutTool = None try: self.CutoutTool = NIRSpecCutoutTool(self.parent.session, parent=self, spec_path=self.spec_path, TableGen=self) except Exception as e: info = QMessageBox.critical(self, "Error", "Cutout tool failed: "+str(e))
def _show_help(self): """Show the help menu.""" QMessageBox.information( self, 'Help', "Help:\n" "'+'/'-': zoom\nleft/right arrow: left/right\n" "up/down arrow: superior/inferior\n" "left angle bracket/right angle bracket: anterior/posterior")
def __from_mechanism(self) -> None: """From a generalized mechanism of main canvas.""" if self.vpoints and self.vlinks: graph, _, _, _, _, _ = self.get_graph() else: graph = Graph([]) if graph.edges: self.edges_text.setText(str(list(graph.edges))) else: self.edges_text.setText("") keep_dof_checked = self.keep_dof.isChecked() self.keep_dof.setChecked(False) self.nl_input.setValue(len(graph.vertices)) self.nj_input.setValue(len(graph.edges)) self.keep_dof.setChecked(keep_dof_checked) # Show attributes QMessageBox.information( self, "Generalization", f"Link assortment:\n{link_assortment(graph)}\n" f"Contracted link assortment:\n{contracted_link_assortment(graph)}" if graph.edges else "Is a empty graph." )
def save_register_new_loader(self, filename): """ Save and register new loader file to specutils loader directory. If a loader with the current name already exists it will be deleted. Parameters ---------- filename: str Loader filename. If filename does not end in ".py", ".py" will be appended to the end of the string. """ filename = "{}.py".format( filename) if not filename.endswith(".py") else filename string = self.as_new_loader() with open(filename, 'w') as f: f.write(string) # If a loader by this name exists, delete it if self.new_loader_dict['name'] in registry.get_formats()['Format']: registry.unregister_reader(self.new_loader_dict['name'], Spectrum1D) registry.unregister_identifier(self.new_loader_dict['name'], Spectrum1D) # Add new loader to registry spec = importlib.util.spec_from_file_location( os.path.basename(filename)[:-3], filename) mod = importlib.util.module_from_spec(spec) spec.loader.exec_module(mod) QMessageBox.information(self, "Loader saved successful.", "Custom loader was saved successfully.")
def add_file(self, _e): sm = self.tableViewDataset.selectionModel() if sm.hasSelection(): q_index = sm.selectedRows() if len(q_index): dataset_qry = self.tableViewDataset.model().qry # dataset_id = dataset_qry[q_index[0].row()].id while True: paths = QFileDialog.getOpenFileNames( self, "Select one or more files", '', "All Files (*)")[0] if len(paths): dataset_id = dataset_qry[q_index[0].row()].id files = [File(path=path) for path in paths] try: self.model.add_files(dataset_id, files) except IntegrityError as e: # this should not be happening self.model.session.rollback() QMessageBox.information( self, "Integrity Error", e, defaultButton=QMessageBox.Ok) else: self.tableViewFile.model().change_layout() self.statusBar().showMessage('Added file(s).') break else: # cancel self.statusBar().showMessage('Cancelled.') return # exit loop
def apply(self): try: self.metabolite.id = self.id.text() except ValueError: turn_red(self.id) QMessageBox.information( self, 'Invalid id', 'Could not apply changes identifier ' + self.id.text()+' already used.') else: self.metabolite.name = self.name.text() self.metabolite.formula = self.formula.text() if self.charge.text() == "": self.metabolite.charge = None else: self.metabolite.charge = int(self.charge.text()) self.metabolite.compartment = self.compartment.text() self.metabolite.annotation = {} rows = self.annotation.rowCount() for i in range(0, rows): key = self.annotation.item(i, 0).text() if self.annotation.item(i, 1) is None: value = "" else: value = self.annotation.item(i, 1).text() self.metabolite.annotation[key] = value self.changed = False self.metaboliteChanged.emit(self.metabolite)
def set_segmentation_result(self, result: ROIExtractionResult): if (result.file_path is not None and result.file_path != "" and result.file_path != self.image.file_path): # pragma: no cover if self._parent is not None: # TODO change to non disrupting popup QMessageBox().warning( self._parent, "Result file bug", "It looks like one try to set ROI form another file.") return if self._parent and len( result.roi_info.bound_info) == 0: # pragma: no cover QMessageBox.information( self._parent, "No result", "Segmentation contains no component, check parameters, especially chosen channel.", ) if result.info_text and self._parent is not None: # pragma: no cover QMessageBox().information(self._parent, "Algorithm info", result.info_text) parameters_dict = defaultdict(lambda: deepcopy(result.parameters)) self._additional_layers = result.additional_layers self.additional_layers_changed.emit() self.last_executed_algorithm = result.parameters.algorithm self.set(f"algorithms.{result.parameters.algorithm}", result.parameters.values) self._set_roi_info(result.roi_info, True, [], parameters_dict) if result.points is not None: self.points = result.points
def save_loader_script(self, event=None, output_directory=None): """ oputput_directory parameter is strictly for use in tests. """ if not self.save_loader_check(): return specutils_dir = os.path.join(os.path.expanduser('~'), '.specutils') if not os.path.exists(specutils_dir): os.mkdir(specutils_dir) loader_name = self.ui.loader_name.text() # If the loader name already exists in the registry, raise a warning # and ask the user to pick another name if loader_name in registry.get_formats(Spectrum1D, 'Read')['Format']: QMessageBox.information( self, "Loader name already exists.", "A loader with the name '{}' already exists in the registry. " "Please choose a different name.".format(loader_name)) return out_path = os.path.join(specutils_dir, loader_name) filename = compat.getsavefilename(parent=self, caption='Export loader to .py file', basedir=out_path)[0] if filename == '': return self.save_register_new_loader(filename)
def folder_dialog(self, *args, **kwargs): dialog = QFileDialog(self) if not self._is_file_dialog_opened: # set the initial directory to HOME dialog.setDirectory(os.path.expanduser("~")) self._is_file_dialog_opened = True dir_name = None dialog.setWindowTitle("Open .edi Directory...") dialog.setFileMode(QFileDialog.DirectoryOnly) while dir_name is None: if dialog.exec_() == QDialog.Accepted: dir_name = dialog.selectedFiles()[0] dir_name = str(dir_name) file_list = [ os.path.join(dir_name, edi) for edi in os.listdir(dir_name) if edi.endswith("edi") ] if not file_list: # empty list QMessageBox.information( self, "NOTE", "Directory does not contain any .edi file, please select again." ) dir_name = None # will read again else: self._progress_bar.setMaximumValue(len(file_list)) self._progress_bar.onStart() self._add_files(file_list, os.path.basename(dir_name)) self._update_tree_view() self._progress_bar.onFinished() else: break
def workflowStoppedByUser(self): workflow_name = self.getCurrentWorkflowName() QMessageBox.information( self, "Workflow killed!", "The workflow '%s' was killed successfully!" % workflow_name) self._running_workflow_dialog.reject() self._running_workflow_dialog = None
def action_released(self): """ """ model = self.source_model model_index = self._model_index_clicked if model_index: column = model_index.column() if column == const.INSTALL and model.is_removable(model_index): column = const.REMOVE self.source_model.update_row_icon(model_index.row(), column) if self.valid: row_data = self.source_model.row(model_index.row()) type_ = row_data[const.PACKAGE_TYPE] name = row_data[const.NAME] versions = self.source_model.get_package_versions(name) version = self.source_model.get_package_version(name) if type_ == const.CONDA: self._parent._run_action(name, column, version, versions) elif type_ == const.PIP: QMessageBox.information(self, "Remove pip package: " "{0}".format(name), "This functionality is not yet " "available.") else: pass
def __match(self) -> None: """Fitting function.""" length = len(self.path) if length == 0: return index = list(range(length)) def poly_fit(x: List[float], y: List[float], d: int) -> Tuple[Callable[[float], float], float]: """Return a 2D fitting equation.""" coefficient = np.polyfit(x, y, d) # Fit values and mean. y_hat = np.poly1d(coefficient)(x) y_bar: np.ndarray = np.sum(y) / len(y) def func(t: float) -> float: """Return y(x) function.""" return sum(c * t**p for p, c in enumerate(reversed(coefficient))) yh_yb = y_hat - y_bar y_yb = y - y_bar return func, np.sum(yh_yb * yh_yb) / np.sum(y_yb * y_yb) x_func, x_accuracy = poly_fit(index, [x for x, y in self.path], 4) y_func, y_accuracy = poly_fit(index, [y for x, y in self.path], 4) QMessageBox.information( self, "Curve fitting", f"Accuracy:\nx: {x_accuracy:.02f}%\ny: {y_accuracy:.02f}%") m = self.match_num.value() self.r_path = [(x_func(i / m * length), y_func(i / m * length)) for i in range(m)] self.accept()
def _check_connected(self, control): if control in ['trims', 'cycle']: leds = [self.ticonn_led, self.psconn_led] elif 'timing' in control: leds = [ self.ticonn_led, ] else: leds = [ self.psconn_led, ] for led in leds: pvs_disconnected = set() for ch, v in led.channels2conn.items(): if not v: pvs_disconnected.add(ch) if pvs_disconnected: sttr = '' for item in pvs_disconnected: sttr += item + '\n' QMessageBox.information( self, 'Message', 'The following PVs are not connected:\n' + sttr) return False return True
def set_limits(self): """Set positions limits.""" try: if self.ui.le_limit_min_X.text() == '': self.config.limit_min_X = None else: self.config.limit_min_X = float(self.ui.le_limit_min_X.text()) if self.ui.le_limit_max_X.text() == '': self.config.limit_max_X = None else: self.config.limit_max_X = float(self.ui.le_limit_max_X.text()) if self.ui.le_limit_min_Y.text() == '': self.config.limit_min_Y = None else: self.config.limit_min_Y = float(self.ui.le_limit_min_Y.text()) if self.ui.le_limit_max_Y.text() == '': self.config.limit_max_Y = None else: self.config.limit_max_Y = float(self.ui.le_limit_max_Y.text()) _QMessageBox.information(self, 'Information', 'Limits configured successfully!', _QMessageBox.Ok) except Exception: _traceback.print_exc(file=_sys.stdout) _QMessageBox.warning( self, 'Warning', 'Could not configure the limits.\n' 'Please, check the inputs.', _QMessageBox.Ok)
def save_register_new_loader(self, filename): """ Save and register new loader file to specutils loader directory. If a loader with the current name already exists it will be deleted. Parameters ---------- filename: str Loader filename. If filename does not end in ".py", ".py" will be appended to the end of the string. """ filename = "{}.py".format(filename) if not filename.endswith(".py") else filename string = self.as_new_loader() with open(filename, 'w') as f: f.write(string) # If a loader by this name exists, delete it if self.new_loader_dict['name'] in registry.get_formats()['Format']: registry.unregister_reader(self.new_loader_dict['name'], Spectrum1D) registry.unregister_identifier(self.new_loader_dict['name'], Spectrum1D) # Add new loader to registry spec = importlib.util.spec_from_file_location(os.path.basename(filename)[:-3], filename) mod = importlib.util.module_from_spec(spec) spec.loader.exec_module(mod) QMessageBox.information(self, "Loader saved successful.", "Custom loader was saved successfully.")
def add_calculation_plan(self, text=None): if text is None or isinstance(text, bool): text, ok = QInputDialog.getText(self, "Plan title", "Set plan title") else: text, ok = QInputDialog.getText( self, "Plan title", f"Set plan title. Previous ({text}) is already in use", text=text ) text = text.strip() if ok: if text == "": QMessageBox.information( self, "Name cannot be empty", "Name cannot be empty, Please set correct name", QMessageBox.Ok ) self.add_calculation_plan() return if text in self.settings.batch_plans: res = QMessageBox.information( self, "Name already in use", "Name already in use. Would like to overwrite?", QMessageBox.Yes | QMessageBox.No, ) if res == QMessageBox.No: self.add_calculation_plan(text) return plan = copy(self.calculation_plan) plan.set_name(text) self.settings.batch_plans[text] = plan self.settings.dump() self.plan_created.emit()
def __edges2atlas(self) -> None: """Turn the text files into a atlas image. This operation will load all edges to list widget first. """ file_names = self.input_from_multiple("edges data", ["Text file (*.txt)"]) if not file_names: return read_data = [] for file_name in file_names: with open(file_name, 'r', encoding='utf-8') as f: for line in f: read_data.append(line) answer = [] for edges in read_data: try: g = Graph(eval(edges)) except (SyntaxError, TypeError): QMessageBox.warning(self, "Wrong format", "Please check text format.") else: answer.append(g) if not answer: QMessageBox.information(self, "No data", "The graph data is empty.") return self.answer = answer self.__set_time_count(0, len(answer)) self.__reload_atlas() self.__save_atlas()
def apply(self): try: self.reaction.id = self.id.text() except ValueError: turn_red(self.id) QMessageBox.information( self, 'Invalid id', 'Could not apply changes identifier ' + self.id.text() + ' already used.') else: self.reaction.name = self.name.text() self.reaction.build_reaction_from_string(self.equation.text()) self.reaction.lower_bound = float(self.lower_bound.text()) self.reaction.upper_bound = float(self.upper_bound.text()) self.reaction.objective_coefficient = float(self.coefficent.text()) self.reaction.gene_reaction_rule = self.gene_reaction_rule.text() self.reaction.annotation = {} rows = self.annotation.rowCount() for i in range(0, rows): key = self.annotation.item(i, 0).text() if self.annotation.item(i, 1) is None: value = "" else: value = self.annotation.item(i, 1).text() self.reaction.annotation[key] = value self.changed = False self.reactionChanged.emit(self.reaction)
def show_message(is_checked): if is_checked or not msg_if_enabled: if msg_warning is not None: QMessageBox.warning(self, self.get_name(), msg_warning, QMessageBox.Ok) if msg_info is not None: QMessageBox.information(self, self.get_name(), msg_info, QMessageBox.Ok)
def pop_one_button_dialog(self, message): """ Pop up a one-button dialog :param message: :return: """ assert isinstance(message, str), 'Input message %s must a string but not %s.' \ '' % (str(message), type(message)) QMessageBox.information(self, '4-circle Data Reduction', message)
def restart_message(self): """ Print a restart message when the client is connected to an external kernel """ message = _("Kernel process is either remote or unspecified. " "Cannot restart.") QMessageBox.information(self, "IPython", message)
def save_reply_box(self, title: str, file_name: str) -> None: """Show message when successfully saved.""" size = size_format(QFileInfo(file_name).size()) QMessageBox.information( self, f"Initial Saved: {title}", f"Successfully saved:\n{file_name}\n" f"Size: {size}") logger.info(f"Saved: [\"{file_name}\"] ({size})")
def on_eval_test(self): """ 点击计算按钮,弹出对话框显示计算结果。 :return: """ val = self.get_value() QMessageBox.information(self, self.tr('Result'), repr(val), QMessageBox.Ok)
def on_mouseDownEvent(self, event): """ Respond to pick up a value with mouse down event """ x = event.xdata y = event.ydata if x is not None and y is not None: msg = "You've clicked on a bar with coords:\n %f, %f" % (x, y) QMessageBox.information(self, "Click!", msg)
def focusInEvent(self, event): if self.handle_focus: self.handle_focus = False tab = self.ui.tabWidget.currentWidget() if tab is not None and tab.is_modified(): msg = 'The file \'%s\' has been changed on the file system. Do you want to replace the editor contents with these changes?' % tab.filename msg += "\n\n" + "\n".join(["Diff in line %d:\nIn script: %s\nIn file: %s\n" % (lnr, l1, l2) for lnr, (l1, l2) in enumerate(zip(tab.get_script().split("\n"), tab.saved().split("\n"))) if l1.strip() != l2.strip()][:5]) if QMessageBox.information(self, 'File changed', msg, QMessageBox.Yes | QMessageBox.No) == QMessageBox.Yes: tab.reload() else: tab.filemodified = os.path.getmtime(tab.filename) self.handle_focus = True
def set_umr_namelist(self): """Set UMR excluded modules name list""" arguments, valid = QInputDialog.getText(self, _('UMR'), _("Set the list of excluded modules as " "this: <i>numpy, scipy</i>"), QLineEdit.Normal, ", ".join(self.get_option('umr/namelist'))) if valid: arguments = to_text_string(arguments) if arguments: namelist = arguments.replace(' ', '').split(',') fixed_namelist = [] non_ascii_namelist = [] for module_name in namelist: if PY2: if all(ord(c) < 128 for c in module_name): if programs.is_module_installed(module_name): fixed_namelist.append(module_name) else: QMessageBox.warning(self, _('Warning'), _("You are working with Python 2, this means that " "you can not import a module that contains non-" "ascii characters."), QMessageBox.Ok) non_ascii_namelist.append(module_name) elif programs.is_module_installed(module_name): fixed_namelist.append(module_name) invalid = ", ".join(set(namelist)-set(fixed_namelist)- set(non_ascii_namelist)) if invalid: QMessageBox.warning(self, _('UMR'), _("The following modules are not " "installed on your machine:\n%s" ) % invalid, QMessageBox.Ok) QMessageBox.information(self, _('UMR'), _("Please note that these changes will " "be applied only to new Python/IPython " "consoles"), QMessageBox.Ok) else: fixed_namelist = [] self.set_option('umr/namelist', fixed_namelist)
def _on_save_model(self, interactive=True): model_editor_model = self.hub.data_item.model_editor_model # There are no models to save if not model_editor_model.fittable_models: QMessageBox.warning(self, 'No model available', 'No model exists to be saved.') return default_name = os.path.join(os.path.curdir, 'new_model.smf') outfile = QFileDialog.getSaveFileName( self, caption='Save Model', directory=default_name, filter=SPECVIZ_MODEL_FILE_FILTER)[0] # No file was selected; the user hit "Cancel" if not outfile: return self._save_models(outfile) QMessageBox.information(self, 'Model saved', 'Model successfully saved to {}'.format(outfile))
def _write_skipped(self, skipped): """ Save a list of skipped spectra files to file. """ name = ".".join(self.save_file_name.split(".")[:-1]) file_name = "skipped_files_%s.txt" %name with open(file_name, "w") as f: for items in skipped: line = " : ".join(items)+"\n" f.write(line) info = QMessageBox.information(self, "Info", "Some spectra files were not included in the generated MOSViz Table." " A list of the these files and the reason they were skipped has been saved to\n\n " " %s. " %file_name)
def update_comments(self, pastSelection = False): """ Process comment and flag changes and save to file. Parameters ---------- pastSelection : bool True when updating past selections. Used when user forgets to save. """ if self.input_flag.text() == "": self.input_flag.setStyleSheet("background-color: rgba(255, 0, 0);") return i = None try: i = int(self.input_flag.text()) except ValueError: self.input_flag.setStyleSheet("background-color: rgba(255, 0, 0);") info = QMessageBox.information(self, "Status:", "Flag must be an int!") return self.input_flag.setStyleSheet("background-color: rgba(255, 255, 255);") idx = self.data_idx if pastSelection: i = self.textChangedAt self.textChangedAt = None else: i = self.toolbar.source_select.currentIndex() i = self._index_hash(i) data = self.session.data_collection[idx] comp = data.get_component("comments") comp.labels.flags.writeable = True comp.labels[i] = self.input_comments.toPlainText() comp = data.get_component("flag") comp.labels.flags.writeable = True comp.labels[i] = self.input_flag.text() self.send_NumericalDataChangedMessage() self.write_comments() self.textChangedAt = None
def change_save_path(self): """ User specified save path. Renders paths in output absolute. Can also revert to default. """ if self.change_save_path_button.text() == "Change": info = QMessageBox.information(self, "Info", "Changing the save destination will generate a MOSViz Table" " that is unique to your computer (you will not be able to share it).") if self.custom_save_path == False: browse_input = compat.getexistingdirectory() self.raise_() if browse_input == "": return self.save_file_dir = browse_input self.save_path_display.setText(self.save_file_dir) self.change_save_path_button.setText("Revert") self.custom_save_path = True else: self.custom_save_path = False self.change_save_path_button.setText("Change") self.default_save_dir()
def call_main(self): """ Calls the main function and handles exceptions. """ if self.CutoutTool is not None: if self.CutoutTool.isVisible(): info = QMessageBox.information(self, "Status", "Error: Cutout tool is still running.") self.CutoutTool.raise_() return else: self.CutoutTool = None cwd = os.getcwd() try: self.main() os.chdir(cwd) except Exception as e: info = QMessageBox.critical(self, "Error", str(e)) self.close() os.chdir(cwd) raise
def main(self): """ Main metod that will take input from the user, make a MOSViz Table and save it to a file. It will use the information in the headers of the spectra files to fill in rows of the table. If the user has cutout, it will look for an image file with the corresponding object name and add it to the Table. """ success = self.verify_input() if not success: self.statusBar().showMessage("Input error") return self.generate_table_button.setDisabled(True) self.statusBar().showMessage("Making Table") QApplication.processEvents() output_path = os.path.join(self.save_file_dir, self.save_file_name) source_catalog = nirspec_table_generator(self.spec_path, cutout_path=self.cutout_path, output_path=output_path) self.statusBar().showMessage("DONE!") info = QMessageBox.information(self, "Status", "Catalog saved at:\n"+output_path) if self.session is not None: usr_ans = QMessageBox.question(self, '', "Would you like to open {}?".format(self.save_file_name), QMessageBox.Yes | QMessageBox.No) if usr_ans == QMessageBox.Yes: self.hide() data = load_data(output_path) self.session.data_collection.append(data) self.session.application.new_data_viewer(MOSVizViewer, data=self.session.data_collection[-1]) self.close() return
def custom_path(self): """ User specified save path. Renders paths in output absolute when using MOSViz TableGen. Can also revert to default. """ if self.change_save_button.text() == "Change" and self.tableGen: info = QMessageBox.information(self, "Info", "Changing the save destination will generate a MOSViz Table" " that is unique to your computer (you will not be able to share it).") if not self.custom_save_path: self.save_path = compat.getexistingdirectory() self.raise_() if self.save_path == "": return directory = self.output_dir_format.format("<programName>") self.save_path_display.setText( os.path.join(self.save_path, directory, "<ObjectName>.fits") ) self.change_save_button.setText("Revert") self.custom_save_path = True else: self.custom_save_path = False self.change_save_button.setText("Change") self.update_save()
def prompt_restart_required(self): """Prompt the user with a request to restart.""" restart_opts = self.restart_options changed_opts = self.changed_options options = [restart_opts[o] for o in changed_opts if o in restart_opts] if len(options) == 1: msg_start = _("Spyder needs to restart to change the following " "setting:") else: msg_start = _("Spyder needs to restart to change the following " "settings:") msg_end = _("Do you wish to restart now?") msg_options = u"" for option in options: msg_options += u"<li>{0}</li>".format(option) msg_title = _("Information") msg = u"{0}<ul>{1}</ul><br>{2}".format(msg_start, msg_options, msg_end) answer = QMessageBox.information(self, msg_title, msg, QMessageBox.Yes | QMessageBox.No) if answer == QMessageBox.Yes: self.restart()
def verify_input(self): """ Process information in the input boxes. Checks if user inputs are functional. Returns ------- success : bool True if no input errors, False otherwise. """ self.statusBar().showMessage("Reading input") success = True self.spec_path = self.spectra_user_input.text() self.save_file_name = self.filename_user_input.text() if self.spec_path == "": self.spectra_user_input.setStyleSheet("background-color: rgba(255, 0, 0, 128);") success = False else: self.spectra_user_input.setStyleSheet("") if self.save_file_name == "" or "/" in self.save_file_name or "\\" in self.save_file_name: self.filename_user_input.setStyleSheet("background-color: rgba(255, 0, 0, 128);") success = False else: self.filename_user_input.setStyleSheet("") if self.add_cutout_radio.isChecked(): self.cutout_path = self.cutout_path_display.text() if self.cutout_path == "": self.cutout_path_display.setStyleSheet("background-color: rgba(255, 0, 0, 128);") success = False else: self.cutout_path_display.setStyleSheet("background-color: rgba(255, 255, 255, 0);") if success: if not os.path.isdir(self.spec_path): info = QMessageBox.information(self, "Error", "Broken path:\n\n"+self.spec_path) self.spectra_user_input.setStyleSheet("background-color: rgba(255, 0, 0, 128);") success = False else: if not self.custom_save_path: self.save_file_dir = self.spec_path if self.add_cutout_radio.isChecked(): if not os.path.isdir(self.cutout_path): info = QMessageBox.information(self, "Error", "Broken path:\n\n"+self.cutout_path) self.cutout_path_display.setStyleSheet("background-color: rgba(255, 0, 0, 128);") success = False if (not os.path.samefile(self.spec_path, os.path.dirname(self.cutout_path)) and not self.abs_path and not self.cutout_path): usr_ans = QMessageBox.question(self, "Path Warning", "The cutout directory is not in the spectra directory, " "this will generate a MOSViz Table " "that is unique to your computer " "(you will not be able to share it). Continue?", QMessageBox.Yes | QMessageBox.No) if usr_ans == QMessageBox.Yes: self.abs_path = True else: success = False return success
def main(self): """ Construct a catalog and make cutouts. """ success = self.verify_input() if not success: self.statusBar().showMessage("Please fill in all fields") return # self.start_button.setText("Abort") # self.start_button.clicked.disconnect() # self.start_button.clicked.connect(self.abort) # temporary fix for non-existing abort functionality. self.start_button.setText("Working...") self.start_button.setEnabled(False) self.statusBar().showMessage("Making a list of files") QApplication.processEvents() t = self.make_catalog_table() #Change working path to save path cwd = os.getcwd() os.chdir(self.save_path) self.statusBar().showMessage("Making catalog") programName, file_extension = os.path.splitext(self.img_path) programName = os.path.basename(programName) #Make cutouts using info in catalog. self.statusBar().showMessage("Making cutouts") fits_cutouts, success_counter, success_table = go_make_cutouts( t, self.img_path, programName, output_file_format=self.output_file_format, output_dir_format=self.output_dir_format, clobber=True, apply_rotation=True, report=self.report) if self.kill: self.kill = False self.progress_bar.reset() self.statusBar().showMessage("Waiting for user input") return self.statusBar().showMessage("DONE!") directory = self.output_dir_format.format(programName) output_path = os.path.abspath( os.path.join(self.save_path, directory)) #Give notice to user on status. string = "Cutouts were made for %s out of %s files\n\nSaved at: %s" %( success_counter, len(t), output_path) #If some spectra files do not have a cutout, a list of their names will be saved to # 'skipped_cutout_files.txt' in the save dir as the MOSViz Table file. if success_counter != len(t): self.write_skipped(t, success_table) string += "\n\nA list of spectra files" string += "without cutouts is saved in" string += "'skipped_cutout_files.txt'" string += "\n\nSaved at: %s" % os.path.join( self.save_path, "skipped_cutout_files.txt") info = QMessageBox.information(self, "Status:", string) #Change back dir. os.chdir(cwd) usr_ans = QMessageBox.question(self, '', "Would you like to load all generated cutouts into glue?", QMessageBox.Yes | QMessageBox.No) if usr_ans == QMessageBox.Yes: os.chdir(self.save_path) data = [] for i, flag in enumerate(success_table): if flag: path = self.output_dir_format.format(programName) this_id = t["id"][i] fname = os.path.join( path, self.output_file_format.format(this_id, programName)) data.append(load_data(fname)) self.session.data_collection.merge(*data, label="%s_Cutouts" %programName) os.chdir(cwd) self.close() return
def verify_input(self): """ Process information in the input boxes. Checks if user inputs are functional. Returns ------- success : bool True if no input errors, False otherwise. """ self.statusBar().showMessage("Reading input") success = True #Inputs to setStyleSheet failed = "background-color: rgba(255, 0, 0, 128);" works = "" self.target_file_path = self.target_user_input.text() self.img_path = self.image_user_input.text() if not self.custom_save_path: #Just in case save_path = self.target_user_input.text() self.save_path = os.path.dirname(save_path) try: self.cutout_x_size = float(self.x_user_input.text()) except ValueError: self.cutout_x_size = -1 if self.cutout_x_size > 0: self.x_user_input.setStyleSheet(works) else: self.x_user_input.setStyleSheet(failed) success = False try: self.cutout_y_size = float(self.y_user_input.text()) except ValueError: self.cutout_y_size = -1 if self.cutout_y_size > 0: self.y_user_input.setStyleSheet(works) else: self.y_user_input.setStyleSheet(failed) success = False if self.target_file_path == "": self.target_user_input.setStyleSheet(failed) success = False else: self.target_user_input.setStyleSheet(works) if self.img_path == "": self.image_user_input.setStyleSheet(failed) success = False else: self.image_user_input.setStyleSheet(works) #Check if success to reduce pop-ups: if success: if not os.path.isfile(self.target_file_path): info = QMessageBox.information(self, "Status:", "Broken path:\n\n"+self.target_file_path) self.target_user_input.setStyleSheet(failed) success = False if not os.path.isfile(self.img_path): info = QMessageBox.information(self, "Status:", "Broken path:\n\n"+self.img_path) self.image_user_input.setStyleSheet(failed) success = False return success
def main(self): """ Main function that uses information provided by the user and in the headers of spectra files to construct a catalog and make cutouts. """ success = self.verify_input() if not success: self.statusBar().showMessage("Please fill in all fields") return # self.start_button.setText("Abort") # self.start_button.clicked.disconnect() # self.start_button.clicked.connect(self.abort) # temporary fix for non-existing abort functionality. self.start_button.setText("Working...") self.start_button.setEnabled(False) self.statusBar().showMessage("Making a list of files") QApplication.processEvents() t = self.make_catalog_table() if t is None: raise Exception("Spectra files were not found.") # Make cutouts using info in catalog. self.statusBar().showMessage("Making cutouts") output_path = os.path.join(self.save_path, self.output_dir_format) fits_cutouts, success_counter, success_table = go_make_cutouts( t, self.img_path, "cutouts", output_file_format=self.output_file_format, output_dir_format=output_path, clobber=True, apply_rotation=True, report=self.report) self.statusBar().showMessage("DONE!") # Give notice to user on status. string = "Cutouts were made for %s out of %s files\n\nSaved at: %s" %( success_counter, len(t), output_path) # save a list of failed cutouts if success_counter != len(t): self.write_skipped(t, success_table) string += "\n\nA list of spectra files " string += "without cutouts is saved in " string += "'skipped_cutout_files.txt' " string += "\n\nSaved at: %s" %os.path.join( self.save_path, "skipped_cutout_files.txt") info = QMessageBox.information(self, "Status:", string) if success_counter == 0: usr_ans = QMessageBox.question(self, '', "Would you like to load all generated cutouts into glue?", QMessageBox.Yes | QMessageBox.No) if usr_ans == QMessageBox.Yes: data = [] for i, flag in enumerate(success_table): if flag: path = output_path this_id = t["id"][i] fname = os.path.join( path, self.output_file_format.format(this_id)) data.append(load_data(fname)) self.session.data_collection.merge(*data, label=self.output_dir_format) if self.tableGen and self.TableGen is not None: self.TableGen.cutout_response(output_path, self.custom_save_path) self.close() return