def __init__(self, parent=None, helpDialog=None): ''' ''' QtGui.QWidget.__init__(self, parent) self.ui = Ui_Form() self.timer_interval=500 self.ui.jobUpdateTimer = QtCore.QTimer(self) self.ui.jobUpdateTimer.setInterval(self.timer_interval) self.ui.jobUpdateTimer.setSingleShot(False) self.helpDialog=helpDialog self.last_offset=0 self.total_running=0 self.ui.setupUi(self) #self.ui.pushButton.clicked.connect(self.runProgram) self.ui.jobUpdateTimer.timeout.connect(self.on_jobUpdateTimer_timeout) self.ui.jobProgressBar.setMinimum(0) self.ui.jobListView.setModel(QtGui.QStandardItemModel(self)) self.job_status_icons=[QtGui.QIcon(f) for f in [':/mini/mini/clock.png', ':/mini/mini/arrow_refresh.png', ':/mini/mini/tick.png', ':/mini/mini/cross.png']] self.ui.crashReportToolButton.setEnabled(False) #self.text_cursor = QtGui.QTextCursor(self.ui.logTextEdit.document()) self.current_pid = None self.fin = None self.log_file = None self.created = None self.log_text="" self.workflowProcess=None
def addSettings(self, option_list, group_list, values): ''' ''' for group in group_list: if group.is_child(): continue treeView = self.copyTreeView() property.setView(treeView) self.tree_views[group.title] = treeView treeView.model().addOptions(group.get_config_options(), group.option_groups, values) icon = QtGui.QIcon() if treeView.model().totalInvalid() > 0: icon.addPixmap(QtGui.QPixmap(":/mini/mini/exclamation.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.invalid_count += 1 else: icon.addPixmap(QtGui.QPixmap(":/mini/mini/accept.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.model_tab[treeView.model()] = self.count() - 1 self.addTab(treeView, icon, group.title) #if treeView.model().totalInvalid() > 0: treeView.model().propertyValidity.connect(self.updateValid) width = treeView.model().maximumTextWidth(self.fontMetrics(), treeView.indentation()) treeView.setColumnWidth(0, width) #self.ui.propertyTreeView.model().addOptions(option_list, [], values) self.controlValidity.emit(self, self.isValid())
def copyTreeView(self): '''Copy the properties from the original tree view :Returns: treeView : QTreeView Copy of current tree view ''' treeView = QtGui.QTreeView(self) metaObjectFrom = self.ui.propertyTreeView.metaObject() metaObjectTo = treeView.metaObject() while metaObjectFrom is not None: _logger.debug("Class: %s" % metaObjectFrom.className()) if metaObjectFrom.className() == 'QWidget': break for i in xrange(metaObjectFrom.propertyOffset(), metaObjectFrom.propertyCount()): name = metaObjectFrom.property(i).name() if name == 'editTriggers': continue _logger.debug("Copy tree view: " + str(name)) treeView.setProperty(name, self.ui.propertyTreeView.property(name)) metaObjectFrom = metaObjectFrom.superClass() metaObjectTo = metaObjectTo.superClass() treeView.setEditTriggers(self.ui.propertyTreeView.editTriggers()) treeView.setStyleSheet(self.treeViewStyle) return treeView
def read_image(filename, index=None): ''' ''' qimg = QtGui.QImage() if qimg.load(filename): return qimg return ndimage_utility.normalize_min_max( ndimage_file.read_image(filename, index))
def updateValid(self, model, prop, valid): ''' ''' invalid = model.totalInvalid() if self.invalid_count != invalid: if valid: icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap(":/mini/mini/accept.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.setTabIcon(self.model_tab[model], icon) self.invalid_count = invalid else: icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap(":/mini/mini/exclamation.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.setTabIcon(self.model_tab[model], icon) self.invalid_count = invalid self.controlValidity.emit(self, self.isValid())
def openFiles(self, files): ''' Open a collection of files, sort by content type :Parameters: files : list List of input files ''' coordfile = None for filename in files: filename = str(filename) if not ndimage_file.spider.is_readable( filename) and not ndimage_file.mrc.is_readable( filename) and format.is_readable(filename): nameItem = QtGui.QStandardItem(os.path.basename(filename)) nameItem.setData(filename) nameItem.setToolTip(filename) countItem = QtGui.QStandardItem(str(len( format.read(filename)))) countItem.setData(filename) countItem.setToolTip(filename) self.fileListModel.appendRow([nameItem, countItem]) self.coordinates_files.append(filename) if coordfile is None: coordfile = nameItem #coordfile=filename else: self.stack_file = filename self.coordinates_files = list(set(self.coordinates_files)) if coordfile is not None: self.ui.fileTableView.selectionModel().setCurrentIndex( coordfile.index(), QtGui.QItemSelectionModel.Select | QtGui.QItemSelectionModel.Rows) #self.openFile(coordfile) if self.stack_file != "": self.ui.toggleImageDockAction.setEnabled(True) self.ui.imageDockWidget.show() self.ui.canvas.mpl_connect('pick_event', self.displayImage)
def on_contrastSlider_valueChanged(self, value): ''' Called when the user uses the contrast slider ''' if self.color_level is None: return if self.base_level is not None and len( self.base_level) > 0 and not isinstance( self.base_level[0], list): if value != 200: self.color_level = qimage_utility.adjust_level( qimage_utility.change_contrast, self.base_level, value) else: self.color_level = self.base_level for i in xrange(len(self.loaded_images)): self.loaded_images[i].setColorTable(self.color_level) pix = QtGui.QPixmap.fromImage(self.loaded_images[i]) icon = QtGui.QIcon(pix) icon.addPixmap(pix, QtGui.QIcon.Normal) icon.addPixmap(pix, QtGui.QIcon.Selected) self.imageListModel.item(i).setIcon(icon) else: for i in xrange(len(self.loaded_images)): if value != 200: self.color_level = qimage_utility.adjust_level( qimage_utility.change_contrast, self.base_level[i], value) else: self.color_level = self.base_level[i] self.loaded_images[i].setColorTable(self.color_level) pix = QtGui.QPixmap.fromImage(self.loaded_images[i]) icon = QtGui.QIcon(pix) icon.addPixmap(pix, QtGui.QIcon.Normal) icon.addPixmap(pix, QtGui.QIcon.Selected) self.imageListModel.item(i).setIcon(icon)
def __init__(self, program, parent=None): "Initialize screener window" QtGui.QDialog.__init__(self, parent) # Build window _logger.info("Building main window ...") self.ui = Ui_Dialog() self.ui.setupUi(self) self.ui.settingsTabWidget = TabWidget(self) self.ui.configTabLayout = QtGui.QHBoxLayout(self.ui.configTab) self.ui.configTabLayout.addWidget(self.ui.settingsTabWidget) self.ui.settingsTabWidget.controlValidity.connect(self.setValid) self.ui.monitorWidget = MonitorWidget(self) self.ui.runTabLayout = QtGui.QHBoxLayout(self.ui.runTab) self.ui.runTabLayout.addWidget(self.ui.monitorWidget) #self.ui.monitorWidget.runProgram.connect(self.runProgram) #self.ui.monitorWidget.monitorProgram.connect(self.monitorProgram) self.program = program self.ui.settingsTabWidget.addSettings(*program.settings()) self.ui.monitorWidget.setWorkflow(program) self.ui.monitorWidget.setLogFile(program.values.log_file)
def setWorkflow(self, workflow): ''' ''' if not hasattr(workflow, '__iter__'): workflow=[workflow] model = self.ui.jobListView.model() model.clear() mode='w' for mod in workflow: if self.log_file: mod.values.log_file = self.log_file mod.values.log_mode = mode item = QtGui.QStandardItem(self.job_status_icons[0], mod.name()) item.setData(mod, QtCore.Qt.UserRole) model.appendRow(item) if mode != 'a': mode='a'
def __init__(self, parent=None, helpDialog=None): "Initialize LeginonUI widget" QtGui.QWidget.__init__(self, parent) # Build window _logger.info("\rBuilding main window ...") self.ui = Ui_Form() self.ui.setupUi(self) self.login = {} self.helpDialog = helpDialog self.startTabIndex = 0 self.ui.progressDialog = QtGui.QProgressDialog('Loading...', "", 0, 5, self) self.ui.progressDialog.setWindowModality(QtCore.Qt.ApplicationModal) self.ui.progressDialog.findChildren(QtGui.QPushButton)[0].hide() #self.ui.progressDialog.setCancelButton(0) # might work #self.ui.progressDialog.setWindowFlags(self.ui.progressDialog.windowFlags() & ~QtCore.Qt.WindowCloseButtonHint) #v5s self.ui.progressDialog.setWindowFlags(QtCore.Qt.Window | QtCore.Qt.WindowTitleHint | QtCore.Qt.CustomizeWindowHint) self.ui.reloadTableToolButton.clicked.connect( self.queryDatabaseForProjects) self.taskUpdated.connect(self.updateProgress) self.ui.leginonHostnameLineEdit.editingFinished.connect( lambda: self.ui.projectHostnameLineEdit.setText( self.ui.leginonHostnameLineEdit.text()) if self.ui.projectHostnameLineEdit.text() == "" else None) header = [('Session', None), ('Project', None), ('Images', None), ('Voltage', 'voltage'), ('Pixel Size', 'apix'), ('Magnification', None), ('CS', 'cs'), ('Image Name', None), ('Image Path', None), ('Frame Path', None)] self.header = [h[0] for h in header] self.headermap = dict([h for h in header if h[1] is not None]) self.images = [] self.ui.projectTableView.setModel( ListTableModel([], self.header, None, self)) selmodel = self.ui.projectTableView.selectionModel() selmodel.selectionChanged.connect(self.selectionChanged) _logger.info("\rLoading settings ...") self.readSettings() self.on_loginPushButton_clicked()
def __init__(self, parent=None): "Initialize screener window" QtGui.QWidget.__init__(self, parent) self.parent_control = parent # Build window _logger.info("Building main window ...") self.ui = Ui_Form() self.ui.setupUi(self) self.header = ['# Mics', '# Particles', 'Disk', 'Mask', 'Overlap'] self.options = [ self.ui.diskDoubleSpinBox.statusTip(), self.ui.diskDoubleSpinBox.statusTip(), self.ui.diskDoubleSpinBox.statusTip() ] self.data = [] self.micrograph_files = [] self.output = None self.output_base = None self.ui.autopickHistoryTableView.setModel( ListTableModel([], self.header, None, self)) #selmodel=self.ui.autopickHistoryTableView.selectionModel() self.ui.autopickHistoryTableView.doubleClicked.connect( self.on_runPushButton_clicked) #doubleClicked ( const QModelIndex & index ) self.ui.progressDialog = QtGui.QProgressDialog('Running...', "Close", 0, 1, self) self.ui.progressDialog.setWindowModality(QtCore.Qt.ApplicationModal) #self.ui.progressDialog.findChildren(QtGui.QPushButton)[0].hide() self.ui.progressDialog.setWindowFlags(QtCore.Qt.Window | QtCore.Qt.WindowTitleHint | QtCore.Qt.CustomizeWindowHint) self.task = None self.output = None self.taskUpdated.connect(self.updateProgress) self.option_control_map = self._collect_options_controls() self._add_controls()
def on_subsetComboBox_currentIndexChanged(self, index): ''' Called when the user wants to plot only a subset of the data :Parameters: index : int New index in the subset combobox ''' if index > 0: index = self.ui.subsetComboBox.itemData(index) vals = [str(v) for v in numpy.unique(self.data[:, index])] else: vals = [] self.subsetListModel.clear() for name in vals: item = QtGui.QStandardItem(name) item.setCheckState(QtCore.Qt.Checked) item.setCheckable(True) self.subsetListModel.appendRow(item)
def __init__(self, screen_shot_file=None, parent=None): ''' ''' QtGui.QWizard.__init__(self, parent) self.ui = Ui_ProjectWizard() self.ui.setupUi(self) #self.subPages={} self.lastmicpath = str(QtCore.QDir.currentPath()) self.lastgainpath = str(QtCore.QDir.currentPath()) self.micrograph_files = [] self.gain_files = [] self.parameters = [] self.screen_shot_file = screen_shot_file self.helpDialog = HelpDialog(self) self.default_spider_path = '/guam.raid.cluster.software/spider.21.00/' version = arachnid.__version__ n = version.find('_') if n != -1: version = version[:n] self.setWindowTitle("Arachnid - Workflow Creation Wizard - v%s" % version) self.docs_url = "" self.setPixmap( QtGui.QWizard.WatermarkPixmap, QtGui.QPixmap(':/icons/logo/ArachnidLogoWindow_small.png' )) #:/icons/icons/icon256x256.png')) self.setPixmap( QtGui.QWizard.BackgroundPixmap, QtGui.QPixmap(':/icons/logo/ArachnidLogoWindow_small.png' )) #:/icons/icons/icon256x256.png')) ######################################################################################################################################## ###### Introduction Page ######################################################################################################################################## self.ui.introductionPage.setTitle('Welcome to Arachnid - v%s' % version) if screen_shot_file: self.ui.screenShotCheckBox.setCheckState(QtCore.Qt.Checked) self.ui.screenShotCheckBox.setEnabled(False) ######################################################################################################################################## ###### Question Page ######################################################################################################################################## self.currentIdChanged.connect(self.onCurrentIDChanged) self.ui.yesLeginonPushButton.clicked.connect(self.next) self.ui.noLeginonPushButton.clicked.connect(self.next) self.ui.yesReferencePushButton.clicked.connect(self.next) self.ui.noReferencePushButton.clicked.connect(self.next) ######################################################################################################################################## ###### Leginon Page ######################################################################################################################################## self.ui.leginonWidget = LeginonUI(self, self.helpDialog) self.ui.leginonDBLayout.addWidget(self.ui.leginonWidget) #self.subPages[self.idOf(self.ui.leginonDBPage)]=self.ui.leginonWidget self.ui.leginonWidget.registerPage(self.ui.leginonDBPage) #self.ui.leginonWidget.loadFinished.connect(self.next) self.ui.leginonWidget.loadFinished.connect(self.onLeginonLoadFinished) self.ui.leginonWidget.captureScreen.connect(self.captureScreen) ######################################################################################################################################## ###### Reference Page ######################################################################################################################################## self.ui.referenceWidget = ReferenceUI(self, self.helpDialog) self.ui.referenceLayout.addWidget(self.ui.referenceWidget) #self.subPages[self.idOf(self.ui.referencePage)]=self.ui.referenceWidget self.ui.referenceWidget.registerPage(self.ui.referencePage) #self.ui.referencePage.registerField("referenceEdit*", self.ui.referenceWidget.ui.referenceLineEdit) self.ui.referenceWidget.captureScreen.connect(self.captureScreen) self.ui.referenceWidget.updateParticleDiameter.connect( self.ui.particleSizeDoubleSpinBox.setValue) ######################################################################################################################################## ###### Monitor Page ######################################################################################################################################## self.ui.monitorWidget = MonitorUI(self, self.helpDialog) self.ui.monitorLayout.insertWidget(0, self.ui.monitorWidget) self.ui.monitorWidget.programStarted.connect(self.onProgramStarted) self.ui.monitorWidget.programCompleted.connect(self.onProgramCompleted) ######################################################################################################################################## ###### Fine Settings Page ######################################################################################################################################## self.ui.settingsTabWidget = SettingsUI(self) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(2) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.ui.settingsTabWidget.sizePolicy().hasHeightForWidth()) self.ui.settingsTabWidget.setSizePolicy(sizePolicy) self.ui.settingsHorizontalLayout.addWidget(self.ui.settingsTabWidget) self.ui.workflowListView.setModel(self.ui.monitorWidget.model()) selmodel = self.ui.workflowListView.selectionModel() selmodel.currentChanged.connect( self.ui.settingsTabWidget.settingsChanged) ######################################################################################################################################## ###### Manual Settings Page ######################################################################################################################################## self.ui.manualSettingsPage.registerField( self.param("apix*"), self.ui.pixelSizeDoubleSpinBox, "value", QtCore.SIGNAL('valueChanged(double)')) self.ui.manualSettingsPage.registerField( self.param("voltage*"), self.ui.voltageDoubleSpinBox, "value", QtCore.SIGNAL('valueChanged(double)')) self.ui.manualSettingsPage.registerField( self.param("cs*"), self.ui.csDoubleSpinBox, "value", QtCore.SIGNAL('valueChanged(double)')) self.ui.manualSettingsPage.registerField( self.param("input_files*"), self, 'micrographFiles', QtCore.SIGNAL('micrographFilesUpdated()')) self.ui.manualSettingsPage.registerField( self.param("gain_files"), self, 'gainFiles', QtCore.SIGNAL('gainFilesUpdated()')) self.ui.manualSettingsPage.registerField(self.param("gain_file"), self, 'gainFile') self.ui.manualSettingsPage.registerField(self.param("invert"), self.ui.invertCheckBox) self.ui.imageStatTableView.setModel( ListTableModel([], ['Exposure', 'Gain'], ['Width', 'Height', 'Frames', 'Total'], self)) self.ui.importMessageLabel.setVisible(False) ######################################################################################################################################## ###### Additional Settings Page ######################################################################################################################################## if os.path.exists(self.default_spider_path): self.updateSpiderExe(self.default_spider_path, True) self.updateParticleSizeSpinBox = lambda x: self.ui.particleSizeSpinBox.setValue( int(x / self.ui.pixelSizeDoubleSpinBox.value()) if self.ui.pixelSizeDoubleSpinBox.value() > 0 else 0) self.updateWindowSizeSpinBox = lambda x: self.ui.windowSizeSpinBox.setValue( int(x / self.ui.pixelSizeDoubleSpinBox.value()) if self.ui.pixelSizeDoubleSpinBox.value() > 0 else 0) self.updateMaskDiameterSpinBox = lambda x: self.ui.maskDiameterSpinBox.setValue( int(x / self.ui.pixelSizeDoubleSpinBox.value()) if self.ui.pixelSizeDoubleSpinBox.value() > 0 else 0) self.updateParticleSizeDoubleSpinBox = lambda x: self.ui.particleSizeDoubleSpinBox.setValue( float(x * self.ui.pixelSizeDoubleSpinBox.value()) if self.ui.pixelSizeDoubleSpinBox.value() > 0 else 0.0) self.updateWindowSizeDoubleSpinBox = lambda x: self.ui.windowSizeDoubleSpinBox.setValue( float(x * self.ui.pixelSizeDoubleSpinBox.value()) if self.ui.pixelSizeDoubleSpinBox.value() > 0 else 0.0) self.updateMaskDiameterDoubleSpinBox = lambda x: self.ui.maskDiameterDoubleSpinBox.setValue( float(x * self.ui.pixelSizeDoubleSpinBox.value()) if self.ui.pixelSizeDoubleSpinBox.value() > 0 else 0.0) self.ui.particleSizeDoubleSpinBox.valueChanged.connect( self.updateParticleSizeSpinBox) self.ui.windowSizeDoubleSpinBox.valueChanged.connect( self.updateWindowSizeSpinBox) self.ui.maskDiameterDoubleSpinBox.valueChanged.connect( self.updateMaskDiameterSpinBox) self.ui.particleSizeUnitComboBox.currentIndexChanged.connect( self.ui.particleDiameterStackedWidget.setCurrentIndex) self.ui.windowSizeUnitComboBox.currentIndexChanged.connect( self.ui.windowSizeStackedWidget.setCurrentIndex) self.ui.maskDiameterUnitComboBox.currentIndexChanged.connect( self.ui.maskDiameterStackedWidget.setCurrentIndex) self.ui.particleSizeUnitComboBox.currentIndexChanged.connect( functools.partial( connect_visible_spin_box, signals=(self.ui.particleSizeDoubleSpinBox.valueChanged, self.ui.particleSizeSpinBox.valueChanged), slots=(self.updateParticleSizeSpinBox, self.updateParticleSizeDoubleSpinBox))) self.ui.windowSizeUnitComboBox.currentIndexChanged.connect( functools.partial( connect_visible_spin_box, signals=(self.ui.windowSizeDoubleSpinBox.valueChanged, self.ui.windowSizeSpinBox.valueChanged), slots=(self.updateWindowSizeSpinBox, self.updateWindowSizeDoubleSpinBox))) self.ui.maskDiameterUnitComboBox.currentIndexChanged.connect( functools.partial( connect_visible_spin_box, signals=(self.ui.maskDiameterDoubleSpinBox.valueChanged, self.ui.maskDiameterSpinBox.valueChanged), slots=(self.updateMaskDiameterSpinBox, self.updateMaskDiameterDoubleSpinBox))) self.ui.particleSizeDoubleSpinBox.valueChanged.connect( lambda x: self.ui.windowSizeDoubleSpinBox.setValue( ensure_even_window(x * 1.4, self.ui.pixelSizeDoubleSpinBox.value()))) self.ui.particleSizeDoubleSpinBox.valueChanged.connect( lambda x: self.ui.maskDiameterDoubleSpinBox.setValue(x * 1.2)) self.ui.additionalSettingsPage.registerField( self.param("spider_path"), self.ui.spiderExecutableLineEdit) self.ui.particleSizeDoubleSpinBox.valueChanged.connect( self.diameterChanged) self.ui.additionalSettingsPage.registerField( self.param("particle_diameter*"), self.ui.particleSizeDoubleSpinBox, "value", QtCore.SIGNAL('valueChanged(double)')) #self.ui.additionalSettingsPage.registerField(self.param("particle_diameter*"), self, "particleDiameter", QtCore.SIGNAL('diameterChanged(double)')) self.ui.additionalSettingsPage.registerField( self.param("window_actual*"), self.ui.windowSizeDoubleSpinBox, "value", QtCore.SIGNAL('valueChanged(double)')) self.ui.additionalSettingsPage.registerField( self.param("mask_diameter*"), self.ui.maskDiameterDoubleSpinBox, "value", QtCore.SIGNAL('valueChanged(double)')) self.ui.additionalSettingsPage.registerField( self.param('worker_count'), self.ui.workerCountSpinBox) self.ui.additionalSettingsPage.registerField( self.param('thread_count'), self.ui.threadCountSpinBox) self.ui.additionalSettingsPage.registerField(self.param("window"), self, "window") self.ui.additionalSettingsPage.registerField( self.param('enable_stderr'), self.ui.enableStderrCheckBox) self.ui.additionalSettingsPage.registerField(self.param("disk_mult"), self, 'sampleShape') self.ui.additionalSettingsPage.registerField( self.param("overlap_mult"), self, 'sampleDensity') self.ui.additionalSettingsPage.registerField( self.param("threshold_minimum"), self, 'sampleDensityMin') self.ui.sampleShapeComboBox.setItemData(0, 0.6) self.ui.sampleShapeComboBox.setItemData(1, 0.35) self.ui.sampleDensityComboBox.setItemData(0, 1.0) self.ui.sampleDensityComboBox.setItemData(1, 1.2) self.ui.sampleDensityComboBox.setItemData(2, 0.8) thread_count = 1 if openmp.is_openmp_enabled(): thread_count = openmp.get_num_procs() else: try: thread_count = multiprocessing.cpu_count() except: pass # Hack to determine whether CPU supports hyperthreading frac = 1.0 if sys.platform == 'darwin': try: info = dict([ line.strip().split(':') for line in os.popen('sysctl hw').readlines()[1:20] if line.find(':') != -1 ]) frac = float(info['hw.activecpu'].strip()) / float( info['hw.physicalcpu'].strip()) except: pass else: if os.path.exists('/proc/cpuinfo'): info = dict([ (line.strip().split(':')[0].strip(), line.strip().split(':')[1].strip()) for line in open('/proc/cpuinfo', 'r').readlines() if line.find(':') != -1 ]) frac = float(info['siblings'].strip()) / float( info['cpu cores'].strip()) thread_count = int(thread_count / frac) self.ui.workerCountSpinBox.setValue(thread_count) self.ui.selectLeginonInformationLabel.setVisible(False) self.ui.selectReferenceInformationLabel.setVisible(False) _logger.info("\rLoading project settings ...") self.readSettings() self.loadProject()
def saveSelection(self, invert=False, filename=None, prefix=None): ''' ''' if filename is None: filename = self.selection_file self.setEnabled(False) try: progressDialog = QtGui.QProgressDialog('Saving...', "", 0, 5, self) progressDialog.setWindowModality(QtCore.Qt.WindowModal) progressDialog.show() if isinstance(filename, tuple): filename = filename[0] if not filename: return file_index = self.file_index.copy() if invert: sel = file_index[:, 2] > -1 file_index[sel, 2] = numpy.logical_not(file_index[sel, 2] > 0) if filename != "": if self.advanced_settings.relion != "" and os.path.splitext( filename)[1] == '.star': if not (len(self.files) == 1 or len(self.files) == len(file_index)): progressDialog.hide() QtGui.QMessageBox.critical( self, "Saving Relion Selection File", "You have opened more than one class stack. Cannot save a Relion Selection file!", QtGui.QMessageBox.Ok | QtGui.QMessageBox.Default | QtGui.QMessageBox.NoButton) self.setEnabled(True) return progressDialog.setValue(1) _logger.info("Saving Relion selection file to %s" % filename) class_column_name = 'rlnClassNumber' vals = format.read(self.advanced_settings.relion, numeric=True) progressDialog.setValue(2) subset = [] selected = set([v[1] + 1 for v in file_index if v[2] > 0]) progressDialog.setValue(3) for v in vals: id = int(getattr(v, class_column_name)) if id in selected: subset.append(v) progressDialog.setValue(4) format.write(filename, subset, prefix=prefix) progressDialog.setValue(5) #relion_selection.select_class_subset(vals, select, filename) elif len(self.files) == 1 or len( self.files) == len(file_index): progressDialog.setValue(3) _logger.info("Saving single selection file to %s" % filename) if not spider_utility.is_spider_filename( self.files) and len(self.files) > 1: _logger.info( "File names do not conform to SPIDER, writing as star file" ) filename = os.path.splitext(filename)[0] + '.star' vals = [(self.files[v[0]], 1) for v in file_index if v[2] > 0] elif len(self.files) > 1: vals = [(spider_utility.spider_id(self.files[v[0]]), 1) for v in file_index if v[2] > 0] else: vals = [(v[1] + 1, 1) for v in file_index if v[2] > 0] progressDialog.setValue(4) format.write(filename, vals, header='id,select'.split(','), default_format=format.spidersel, prefix=prefix) progressDialog.setValue(5) else: progressDialog.setValue(3) _logger.info( "Saving multiple selection files by stack to %s" % filename) if not spider_utility.is_spider_filename(self.files): _logger.info( "File names do not conform to SPIDER, writing as star file" ) filename = os.path.splitext(filename)[0] + '.star' vals = [(relion_utility.relion_identifier( self.files[v[0]], v[1] + 1), 1) for v in file_index if v[2] > 0] format.write(filename, vals, header='id,select'.split(',')) else: micselect = {} for v in file_index: if v[2] > 0: mic = spider_utility.spider_id( self.files[v[0]]) if mic not in micselect: micselect[mic] = [] micselect[mic].append((v[1] + 1, 1)) for mic, vals in micselect.iteritems(): format.write(filename, numpy.asarray(vals), spiderid=mic, header="id,select".split(','), default_format=format.spidersel, prefix=prefix) progressDialog.setValue(5) finally: self.setEnabled(True) #progressDialog.hide() print 'done'
def iter_images(files, index, template=None, average=False): ''' Wrapper for iterate images that support color PNG files :Parameters: filename : str Input filename :Returns: img : array Image array ''' qimg = QtGui.QImage() if template is not None: filename = spider_utility.spider_filename(template, files[0]) else: filename = files[0] header = {} if qimg.load(filename): if isinstance(index[0], str): files = index else: files = [files[i[0]] for i in index] for filename in files: qimg = QtGui.QImage() if template is not None: filename = spider_utility.spider_filename(template, filename) if not qimg.load(filename): qimg = QtGui.QPixmap(":/mini/mini/cross.png").toImage() _logger.warn("Unable to read image - %s" % filename) #raise IOError, "Unable to read image - %s"%filename yield (filename, 0), qimg, 1.0 else: # todo reorganize with ''' for img in itertools.imap(ndimage_utility.normalize_min_max, ndimage_file.iter_images(filename, index)): ''' if isinstance(index[0], str): for f in index: avg = None if template is not None: f1 = spider_utility.spider_filename(template, f) if os.path.exists(f1): f = f1 else: _logger.warn("Unabled to find alternate image: %s" % f1) for img in ndimage_file.iter_images(f, header=header): if avg is None: avg = img else: avg += img try: img = ndimage_utility.normalize_min_max(avg) except: img = avg yield (f, 0), img, header.get('apix', 1.0) else: for idx in index: f, i = idx[:2] filename = files[f] if template is not None: filename = spider_utility.spider_filename( template, filename) try: img = ndimage_file.read_image(filename, i, header=header) except: _logger.exception("Error while reading!") img = ndimage_file.read_image(filename, header=header) #print f, i, len(files), files[f], template, filename #raise try: img = ndimage_utility.normalize_min_max(img) except: pass yield (filename, i), img, header.get('apix', 1.0) '''
def on_loadImagesPushButton_clicked(self): ''' Load the current batch of images into the list ''' if len(self.files) == 0: return self.imageListModel.clear() index, start = self.imageSubset(self.ui.pageSpinBox.value() - 1, self.ui.imageCountSpinBox.value()) if len(index) == 0: self.ui.pageSpinBox.blockSignals(True) self.ui.pageSpinBox.setValue(0) self.ui.pageSpinBox.blockSignals(False) self.ui.imageCountSpinBox.blockSignals(True) self.ui.imageCountSpinBox.setValue(1) self.ui.imageCountSpinBox.blockSignals(False) index, start = self.imageSubset(0, 1) bin_factor = self.ui.decimateSpinBox.value() nstd = self.ui.clampDoubleSpinBox.value() img = None self.loaded_images = [] self.base_level = None zoom = self.ui.imageZoomDoubleSpinBox.value() masks = {} template = self.get_template() progressDialog = QtGui.QProgressDialog('Opening...', "Cancel", 0, len(index), self) progressDialog.setWindowModality(QtCore.Qt.WindowModal) progressDialog.show() self.ui.imageListView.setModel(None) if not drawing.is_available(): _logger.info("No PIL loaded") self.advanced_settings.mark_image = False if not plotting.is_available(): _logger.info("No matplotlib loaded") self.advanced_settings.mark_image = False current_powerspec = self.advanced_settings.current_powerspec if current_powerspec: if self.advanced_settings.invert: _logger.info("Cannot invert a power spectra") else: if self.advanced_settings.center_mask > 0: _logger.info("Cannot mask micrograph") added_items = [] for i, (imgname, img, pixel_size) in enumerate( iter_images(self.files, index, template)): selimg = None progressDialog.setValue(i + 1) if hasattr(img, 'ndim'): if current_powerspec and self.advanced_settings.center_mask > 0 and img.shape not in masks: masks[img.shape] = ndimage_utility.model_disk( self.advanced_settings.center_mask, img.shape) * -1 + 1 if self.advanced_settings.invert and not current_powerspec: if img.max() != img.min(): ndimage_utility.invert(img, img) img = ndimage_utility.replace_outlier(img, nstd, nstd, replace='mean') if self.advanced_settings.gaussian_high_pass > 0.0: img = ndimage_filter.filter_gaussian_highpass( img, pixel_size / self.advanced_settings.gaussian_high_pass) if self.advanced_settings.gaussian_low_pass > 0.0: img = ndimage_filter.filter_gaussian_lowpass( img, pixel_size / self.advanced_settings.gaussian_low_pass) if current_powerspec and self.advanced_settings.center_mask > 0: #img[numpy.logical_not(masks[img.shape])] = numpy.mean(img[masks[img.shape]]) img *= masks[img.shape] if bin_factor > 1.0: img = ndimage_interpolate.interpolate( img, bin_factor, self.advanced_settings.downsample_type) pixel_size *= bin_factor img = self.display_powerspectra_1D(img, imgname, pixel_size) img = self.display_resolution(img, imgname, pixel_size) img = self.box_particles(img, imgname) if self.advanced_settings.mark_image: imgm = self.imageMarker(img) selimg = qimage_utility.numpy_to_qimage(imgm) qimg = qimage_utility.numpy_to_qimage(img) if img.ndim == 2: if self.base_level is not None: qimg.setColorTable(self.color_level) else: self.base_level = qimg.colorTable() self.color_level = qimage_utility.adjust_level( qimage_utility.change_contrast, self.base_level, self.ui.contrastSlider.value()) qimg.setColorTable(self.color_level) else: if self.base_level is None: self.base_level = [] self.base_level.append(qimg.colorTable()) self.color_level = qimage_utility.adjust_level( qimage_utility.change_contrast, self.base_level[-1], self.ui.contrastSlider.value()) qimg.setColorTable(self.color_level) else: qimg = img.convertToFormat(QtGui.QImage.Format_Indexed8) if self.base_level is None: self.base_level = [] self.base_level.append(qimg.colorTable()) self.color_level = qimage_utility.adjust_level( qimage_utility.change_contrast, self.base_level[-1], self.ui.contrastSlider.value()) qimg.setColorTable(self.color_level) self.loaded_images.append(qimg) pix = QtGui.QPixmap.fromImage(qimg) icon = QtGui.QIcon() icon.addPixmap(pix, QtGui.QIcon.Normal) if selimg is not None: pix = QtGui.QPixmap.fromImage(selimg) icon.addPixmap(pix, QtGui.QIcon.Selected) if self.advanced_settings.show_label: item = QtGui.QStandardItem( icon, "%s/%d" % (os.path.basename(imgname[0]), imgname[1] + 1)) else: item = QtGui.QStandardItem(icon, "") if hasattr(start, '__iter__'): item.setData(start[i], QtCore.Qt.UserRole) else: item.setData(i + start, QtCore.Qt.UserRole) self.addToolTipImage(imgname, item, pixel_size) self.imageListModel.appendRow(item) added_items.append(item) self.ui.imageListView.setModel(self.imageListModel) progressDialog.hide() for item in added_items: self.notify_added_item(item) self.imagesize = img.shape[0] if hasattr(img, 'shape') else img.width() n = max(5, int(self.imagesize * zoom)) self.ui.imageListView.setIconSize(QtCore.QSize(n, n)) batch_count = numpy.ceil( float(self.imageTotal()) / self.ui.imageCountSpinBox.value()) self.ui.pageSpinBox.setSuffix(" of %d" % batch_count) self.ui.pageSpinBox.setMaximum(batch_count) self.ui.actionForward.setEnabled( self.ui.pageSpinBox.value() < batch_count) self.ui.actionBackward.setEnabled(self.ui.pageSpinBox.value() > 0)
def __init__(self, parent=None): "Initialize a image display window" QtGui.QMainWindow.__init__(self, parent) # Setup logging root = logging.getLogger() while len(root.handlers) > 0: root.removeHandler(root.handlers[0]) h = logging.StreamHandler() h.setFormatter(logging.Formatter('%(message)s')) root.addHandler(h) # Build window _logger.info("\rBuilding main window ...") self.ui = Ui_MainWindow() self.ui.setupUi(self) # Setup variables self.lastpath = str(QtCore.QDir.currentPath()) self.loaded_images = [] self.files = [] self.file_index = [] self.color_level = None self.base_level = None self.inifile = '' #'ara_view.ini' self.settings_group = 'ImageViewer' self.imagesize = 0 # Image View self.imageListModel = QtGui.QStandardItemModel(self) self.ui.imageListView.setModel(self.imageListModel) #self.templateListModel = QtGui.QStandardItemModel(self) #self.ui.templateListView.setModel(self.templateListModel) # Empty init self.ui.actionForward.setEnabled(False) self.ui.actionBackward.setEnabled(False) self.setup() self.ui.autopickWidget = AutoPickWidget(self) self.ui.tabWidget.addTab(self.ui.autopickWidget, "AutoPick") self.ui.tabWidget.currentChanged.connect(self.tabValid) # Custom Actions self.ui.dockWidgetAction = self.ui.dockWidget.toggleViewAction() self.ui.whatsThisAction = QtGui.QWhatsThis.createAction(self) icon8 = QtGui.QIcon() icon8.addPixmap(QtGui.QPixmap(":/mini/mini/application_side_list.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.ui.dockWidgetAction.setIcon(icon8) self.ui.dockWidgetAction.setToolTip("Show or hide the controls widget") self.ui.dockWidgetAction.setWhatsThis( QtGui.QApplication.translate( "MainWindow", '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">\n<html><head><meta name="qrichtext" content="1" /><style type="text/css">\np, li { white-space: pre-wrap; }\n</style></head><body style=" font-family:\'Lucida Grande\'; font-size:13pt; font-weight:400; font-style:normal;">\n<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><img src=":/mini/mini/application_side_list.png" /> Display/Hide the controls widget</p>\n<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"></p>\n<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">This widget can be hidden to increase the number of images that can be shown.</p></body></html>', None, QtGui.QApplication.UnicodeUTF8)) self.ui.toolBar.addAction(self.ui.dockWidgetAction) self.ui.toolBar.addAction(self.ui.whatsThisAction) # Create advanced settings property.setView(self.ui.advancedSettingsTreeView) self.advanced_settings, self.advanced_names = self.ui.advancedSettingsTreeView.model( ).addOptionList(self.advancedSettings()) self.ui.advancedSettingsTreeView.setStyleSheet( 'QTreeView::item[readOnly="true"]{ color: #000000; }') for i in xrange( self.ui.advancedSettingsTreeView.model().rowCount() - 1, 0, -1): if self.ui.advancedSettingsTreeView.model().index( i, 0).internalPointer().isReadOnly( ): # Hide widget items (read only) self.ui.advancedSettingsTreeView.setRowHidden( i, QtCore.QModelIndex(), True) # Help system self.helpDialog = HelpDialog(self) _logger.info("\rLoading settings ...") self.loadSettings()
def __init__(self, parent=None): "Initialize a image display window" QtGui.QMainWindow.__init__(self, parent) # Setup logging root = logging.getLogger() while len(root.handlers) > 0: root.removeHandler(root.handlers[0]) h = logging.StreamHandler() h.setFormatter(logging.Formatter('%(message)s')) root.addHandler(h) # Build window _logger.info("\rBuilding main window ...") self.ui = Ui_MainWindow() self.ui.setupUi(self) # Setup variables self.lastpath = str(QtCore.QDir.currentPath()) self.coordinates_files = [] self.stack_file = "" self.inifile = "" #'ara_view.ini' self.data = None self.header = None self.group_indices = None self.label_cols = [] self.rtsq_cols = [] self.select_col = -1 self.markers = ['s', 'o', '^', '>', 'v', 'd', 'p', 'h', '8', '+', 'x'] self.selectedImage = None # Setup Plotting View self.fig = Figure((6.0, 4.0)) #, dpi=self.ui.dpiSpinBox.value()) self.ui.canvas = FigureCanvas(self.fig) self.ui.canvas.setParent(self.ui.centralwidget) self.axes = self.fig.add_subplot(111) self.ui.centralHLayout.addWidget(self.ui.canvas) self.ui.centralHLayout.setStretchFactor(self.ui.canvas, 4) #self.ui.canvas.mpl_connect('motion_notify_event', self.onHover) self.ui.canvas.mpl_connect('pick_event', self.displayLabel) self.annotation = None # Setup Navigation Tool Bar self.ui.mpl_toolbar = NavigationToolbar(self.ui.canvas, self) self.ui.mpl_toolbar.hide() self.addToolBar(QtCore.Qt.TopToolBarArea, self.ui.mpl_toolbar) if not hasattr(self.ui.mpl_toolbar, 'edit_parameters'): self.ui.toolBar.removeAction(self.ui.actionShow_Options) # Custom Actions self.ui.toggleImageDockAction = self.ui.imageDockWidget.toggleViewAction( ) icon8 = QtGui.QIcon() icon8.addPixmap(QtGui.QPixmap(":/mini/mini/image.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.ui.toggleImageDockAction.setIcon(icon8) self.ui.toolBar.insertAction(self.ui.actionShow_Options, self.ui.toggleImageDockAction) self.ui.imageDockWidget.hide() self.ui.toggleImageDockAction.setEnabled(False) action = self.ui.plotDockWidget.toggleViewAction() icon8 = QtGui.QIcon() icon8.addPixmap(QtGui.QPixmap(":/mini/mini/chart_line.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) action.setIcon(icon8) self.ui.toolBar.insertAction(self.ui.actionShow_Options, action) self.ui.toggleAdvancedDockAction = self.ui.advancedDockWidget.toggleViewAction( ) icon8 = QtGui.QIcon() icon8.addPixmap(QtGui.QPixmap(":/mini/mini/cog_edit.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.ui.toggleAdvancedDockAction.setIcon(icon8) self.ui.toolBar.insertAction(self.ui.actionShow_Options, self.ui.toggleAdvancedDockAction) self.ui.advancedDockWidget.hide() action = self.ui.fileDockWidget.toggleViewAction() icon8 = QtGui.QIcon() icon8.addPixmap(QtGui.QPixmap(":/mini/mini/folder_explore.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) action.setIcon(icon8) self.ui.toolBar.insertAction(self.ui.actionShow_Options, action) # Create advanced settings property.setView(self.ui.advancedSettingsTreeView) self.advanced_settings, self.advanced_names = self.ui.advancedSettingsTreeView.model( ).addOptionList(self.advancedSettings()) self.ui.advancedSettingsTreeView.setStyleSheet( 'QTreeView::item[readOnly="true"]{ color: #000000; }') for i in xrange( self.ui.advancedSettingsTreeView.model().rowCount() - 1, 0, -1): if self.ui.advancedSettingsTreeView.model().index( i, 0).internalPointer().isReadOnly( ): # Hide widget items (read only) self.ui.advancedSettingsTreeView.setRowHidden( i, QtCore.QModelIndex(), True) # Subset List self.subsetListModel = QtGui.QStandardItemModel() self.ui.subsetListView.setModel(self.subsetListModel) # File List self.fileListModel = QtGui.QStandardItemModel() self.ui.fileTableView.setModel(self.fileListModel) self.fileListModel.setHorizontalHeaderLabels(['file', 'items']) self.connect( self.ui.fileTableView.selectionModel(), QtCore.SIGNAL( "selectionChanged(const QItemSelection &, const QItemSelection &)" ), self.openSelectedFile) # Plot # Create advanced settings #property.setView(self.ui.advancedSettingsTreeView) #self.advanced_settings, self.advanced_names = self.ui.advancedSettingsTreeView.model().addOptionList(self.advancedSettings()) #self.ui.advancedSettingsTreeView.setStyleSheet('QTreeView::item[readOnly="true"]{ color: #000000; }') #for i in xrange(self.ui.advancedSettingsTreeView.model().rowCount()-1, 0, -1): # if self.ui.advancedSettingsTreeView.model().index(i, 0).internalPointer().isReadOnly(): # Hide widget items (read only) # self.ui.advancedSettingsTreeView.setRowHidden(i, QtCore.QModelIndex(), True) # Load the settings _logger.info("\rLoading settings ...") self.loadSettings()
def __init__(self, parent=None, helpDialog=None): "Initialize ReferenceUI widget" QtGui.QWidget.__init__(self, parent) # Build window _logger.info("\rBuilding main window ...") self.ui = Ui_Form() self.ui.setupUi(self) self.task = None self.lastpath = str(QtCore.QDir.currentPath()) self.helpDialog = helpDialog self.ui.referenceTabWidget.currentChanged.connect( lambda x: self.captureScreen.emit(x + 1)) self.emdbCannedModel = QtGui.QStandardItemModel(self) canned = [ ('Ribosome-40S', '1346', ':/references/reference/1346/emdb_1346_pix32.png', """The eukaryotic translation initiation factors eIF1 and eIF1A induce an open conformation of the 40S ribosome. Passmore LA, Schmeing TM, Maag D, Applefield DJ, Acker MG, Algire MA, Lorsch JR, Ramakrishnan V MOLECULAR CELL (2007) 26, pp. 41-50"""), ('Ribosome-60S', '1705', ':/references/reference/1705/emdb_1705_pix32.png', """Mechanism of eIF6-mediated inhibition of ribosomal subunit joining. Gartmann M, Blau M, Armache JP, Mielke T, Topf M, Beckmann R J.BIOL.CHEM. (2010) 285, pp. 14848-14851"""), ('Ribosome-80S', '2275', ':/references/reference/2275/emdb_2275_pix32.png', """Ribosome structures to near-atomic resolution from thirty thousand cryo-EM particles. Bai XC, Fernandez IS, McMullan G, Scheres SH ELIFE (2013) 2, pp. e00461-e00461"""), ('ATP synthase', '5335', ':/references/reference/5335/emd_5335_pix32.png', """Subnanometre-resolution structure of the intact Thermus thermophilus H+-driven ATP synthase. Lau WC, Rubinstein JL NATURE (2012) 481, pp. 214-218"""), ('Ribosome-70S', '5360', ':/references/reference/5360/emdb_5360_pix32.png', """Structural characterization of mRNA-tRNA translocation intermediates. Agirrezabala X, Liao HY, Schreiner E, Fu J, Ortiz-Meoz RF, Schulten K, Green R, Frank J PROC.NAT.ACAD.SCI.USA (2012) 109, pp. 6094-6099"""), ('Ribosome-30S', '5503', ':/references/reference/5503/emdb_5503_pix512.png', """Dissecting the in vivo assembly of the 30S ribosomal subunit reveals the role of RimM and general features of the assembly process. Guo Q, Goto S, Chen Y, Feng B, Xu Y, Muto A, Himeno H, Deng H, Lei J, Gao N NUCLEIC ACIDS RES. (2013) 41, pp. 2609-2620"""), ('Ribosome-50S', '5787', ':/references/reference/5787/emdb_5787_pix32.png', """Functional domains of the 50S subunit mature late in the assembly process. Jomaa A, Jain N, Davis JH, Williamson JR, Britton RA, Ortega J NUCLEIC ACIDS RES. (2013)"""), ] for entry in canned: icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap(entry[2]), QtGui.QIcon.Normal, QtGui.QIcon.Off) item = QtGui.QStandardItem(icon, entry[0]) item.setData(entry[1], QtCore.Qt.UserRole) item.setData(entry[3], QtCore.Qt.UserRole + 1) self.emdbCannedModel.appendRow(item) self.ui.emdbCannedListView.setModel(self.emdbCannedModel) self.taskFinished.connect(self.onDownloadFromEMDBComplete) self.ui.referenceLineEdit.editingFinished.connect( self.onReferenceEditChanged) self.ui.referenceTabWidget.setCurrentIndex(0) self.ui.referenceTabWidget.setCurrentIndex(1)