def browseOutputDir(self): if self.outputDir is None: self.outputDir = PyMcaDirs.outputDir if not os.path.exists(self.outputDir): self.outputDir = os.getcwd() wdir = self.outputDir if QTVERSION < '4.0.0': outfile = qt.QFileDialog(self,"Output Directory Selection",1) outfile.setMode(outfile.DirectoryOnly) outfile.setDir(wdir) ret = outfile.exec_loop() else: outfile = qt.QFileDialog(self) outfile.setWindowTitle("Output Directory Selection") outfile.setModal(1) outfile.setDirectory(wdir) outfile.setFileMode(outfile.DirectoryOnly) ret = outfile.exec_() if ret: if QTVERSION < '4.0.0': outdir = qt.safe_str(outfile.selectedFile()) else: outdir = qt.safe_str(outfile.selectedFiles()[0]) outfile.close() del outfile self.setOutputDir(outdir) else: # pyflakes http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=666494 outfile.close() del outfile if QTVERSION < '4.0.0': self.raiseW() else: self.raise_()
def __createTable(self, rows, head_par, head_val): if qt.qVersion() < '4.0.0': table= QTable(self) else: table= QTable() table.setColumnCount(2) table.setRowCount(rows) if qt.qVersion() < '4.0.0': table.setReadOnly(1) table.setSelectionMode(QTable.SingleRow) else: table.setSelectionMode(qt.QTableWidget.NoSelection) table.verticalHeader().hide() if qt.qVersion() < '4.0.0': table.setLeftMargin(0) table.horizontalHeader().setLabel(0, head_par) table.horizontalHeader().setLabel(1, head_val) else: labels = [head_par, head_val] for i in range(len(labels)): item = table.horizontalHeaderItem(i) if item is None: item = qt.QTableWidgetItem(labels[i], qt.QTableWidgetItem.Type) item.setText(labels[i]) table.setHorizontalHeaderItem(i,item) return table
def togglePointsAction(self): modelIndex = self.currentIdx() legend = qt.safe_str(convertToPyObject(modelIndex.data(qt.Qt.DisplayRole))) ddict = { 'legend' : legend, 'label' : legend, 'selected' : convertToPyObject(modelIndex.data(qt.Qt.CheckStateRole)), 'type' : qt.safe_str(convertToPyObject(modelIndex.data())), } flag = convertToPyObject(modelIndex.data(LegendModel.showSymbolRole)) symbol = convertToPyObject(modelIndex.data(LegendModel.iconSymbolRole)) if flag and (symbol is not None): if DEBUG == 1: print('togglePointsAction -- Symbols turned off') ddict['event'] = "togglePoints" ddict['points'] = False self.sigContextMenu.emit(ddict) self.model.setData(modelIndex, False, LegendModel.showSymbolRole) else: if DEBUG == 1: print('togglePointsAction -- Symbols turned on') ddict['event'] = "togglePoints" ddict['points'] = True self.sigContextMenu.emit(ddict) self.model.setData(modelIndex, True, LegendModel.showSymbolRole)
def selectionTableSlot(self, ddict): legendKey = qt.safe_str(self.table.horizontalHeaderItem(0).text()).lower() xKey = qt.safe_str(self.table.horizontalHeaderItem(1).text()).lower() yKey = qt.safe_str(self.table.horizontalHeaderItem(2).text()).lower() x0 = self._itemList[ddict[xKey][0]] y0 = self._itemList[ddict[yKey][0]] x = x0[:] x.shape = -1 y = y0[:] y.shape = -1 xLabel = self._itemLabels[ddict[xKey][0]] yLabel = self._itemLabels[ddict[yKey][0]] # active curve handling is disabled self.setGraphXLabel(xLabel) self.setGraphYLabel(yLabel) self.setSelectionCurveData(x, y, legend=None, color="k", symbol=".", replot=False, replace=True, xlabel=xLabel, ylabel=yLabel, selectable=False) self._updatePlot(replot=False, replace=True) #matplotlib needs a zoom reset to update the scales # that problem does not seem to be present with OpenGL self.resetZoom()
def addSelectableItem(self, item, label=None, copy=True): # we always keep a copy by default item = numpy.array(item, dtype=numpy.float32, copy=copy) if label is None: label = "Unnamed 00" i = 0 while(label in self._itemLabels): i += 1 label = "Unnamed %02d" % i if len(self._itemList): if item.size != self._itemList[0].size: raise IndexError("Invalid size") if label in self._itemLabels: self._itemList[self._itemLabels.index(label)] = item else: self._itemList.append(item) self._itemLabels.append(label) nItems = len(self._itemList) self.table.setRowCount(nItems) self.table.fillLine(nItems - 1, [label, "", ""]) self.table.resizeColumnToContents(0) self.table.resizeColumnToContents(1) self.table.resizeColumnToContents(2) ddict = self.table.getSelection() index = self._itemLabels.index(label) xKey = qt.safe_str(self.table.horizontalHeaderItem(1).text()).lower() yKey = qt.safe_str(self.table.horizontalHeaderItem(2).text()).lower() if index in (ddict[xKey] + ddict[yKey]): self.selectionTableSlot(ddict)
def getParameters(self): ddict = {} i = 0 for label in self.keyList: if i == self.labelList.index('Contour Levels'): ddict[label] = self.comboBoxList[i].value() elif i == self.labelList.index('Contour Line Width'): ddict[label] = self.comboBoxList[i].value() elif i > self.labelList.index('Image Background'): text = qt.safe_str(self.comboBoxList[i].text()) if len(text): if label in ['Output dpi', "N X Labels", "N Y Labels"]: if ddict[label] in ['Auto', 'auto', '0', 0]: ddict['label'] = 0 else: ddict[label] = int(text) else: ddict[label] = float(text) else: ddict[label] = None else: ddict[label] = qt.safe_str(self.comboBoxList[i].currentText()).lower() if (ddict[label] == 'none') or (ddict[label] == 'default'): ddict[label] = None i = i + 1 return ddict
def load(self): if PyMcaDirs.nativeFileDialogs: filedialog = qt.QFileDialog(self) filedialog.setFileMode(filedialog.ExistingFiles) filedialog.setWindowIcon(qt.QIcon(qt.QPixmap(Icons.IconDict["gioconda16"]))) initdir = os.path.curdir if self.initDir is not None: if os.path.isdir(self.initDir): initdir = self.initDir filename = filedialog.getOpenFileName( self, "Choose fit configuration file", initdir, "Fit configuration files (*.cfg)\nAll Files (*)") filename = qt.safe_str(filename) if len(filename): self.loadConfiguration(filename) self.initDir = os.path.dirname(filename) else: filedialog = qt.QFileDialog(self) filedialog.setFileMode(filedialog.ExistingFiles) filedialog.setWindowIcon(qt.QIcon(qt.QPixmap(Icons.IconDict["gioconda16"]))) initdir = os.path.curdir if self.initDir is not None: if os.path.isdir(self.initDir): initdir = self.initDir filename = filedialog.getOpenFileName( self, "Choose fit configuration file", initdir, "Fit configuration files (*.cfg)\nAll Files (*)") filename = qt.safe_str(filename) if len(filename): self.loadConfiguration(filename) self.initDir = os.path.dirname(filename)
def _savesignal(self): if self.lastInputDir is None: self.lastInputDir = PyMcaDirs.outputDir if self.lastInputDir is not None: if not os.path.exists(self.lastInputDir): self.lastInputDir = None self.lastInputFilter = "Calibration files (*.calib)\n" if sys.platform == "win32": windir = self.lastInputDir if windir is None: windir = "" filename= qt.safe_str(qt.QFileDialog.getSaveFileName(self, "Save a new calibration file", windir, self.lastInputFilter)) else: windir = self.lastInputDir if windir is None:windir = os.getcwd() filename = qt.QFileDialog(self) filename.setWindowTitle("Save a new calibration file") filename.setModal(1) if hasattr(qt, "QStringList"): strlist = qt.QStringList() else: strlist = [] tmp = [self.lastInputFilter.replace("\n","")] for filetype in tmp: strlist.append(filetype.replace("(","").replace(")","")) if hasattr(filename, "setFilters"): filename.setFilters(strlist) else: filename.setNameFilters(strlist) filename.setFileMode(qt.QFileDialog.AnyFile) filename.setDirectory(windir) ret = filename.exec_() if ret: if len(filename.selectedFiles()): filename = qt.safe_str(filename.selectedFiles()[0]) else: return else: return if not len(filename): return if len(filename) < 6: filename = filename + ".calib" elif filename[-6:] != ".calib": filename = filename + ".calib" self.lastInputDir = os.path.dirname(filename) PyMcaDirs.outputDir = os.path.dirname(filename) comboitem,combotext = self.calbox.getCurrent() self._emitpysignal(button="CalibrationSave", box=[comboitem,combotext], line_edit = filename, event='clicked')
def getParameters(self): ddict = {} ddict['configuration'] = qt.safe_str(self._configLine.text()) ddict['output_dir'] = qt.safe_str(self._outLine.text()) ddict['file_root'] = qt.safe_str(self._fileLine.text()) if self._maskBox.isChecked(): ddict['mask'] = 1 else: ddict['mask'] = 0 return ddict
def getParameters(self): ddict = {} ddict['configuration'] = qt.safe_str(self._configLine.text()) ddict['output_dir'] = qt.safe_str(self._outLine.text()) ddict['file_root'] = qt.safe_str(self._fileLine.text()) if self._concentrationsBox.isChecked(): ddict['concentrations'] = 1 else: ddict['concentrations'] = 0 ddict['weight_policy'] = self._weightButtonGroup.checkedId() return ddict
def getOutputFileNameFilter(self): """Open a file dialog to get the output file name, and return the file name and the selected format filter. Remember output directory in attribute :attr:`outputDir`""" if os.path.exists(self.outputDir): initdir = self.outputDir else: # folder deleted, reset initdir = PyMcaDirs.outputDir filedialog = qt.QFileDialog(self.maskImageWidget) filedialog.setFileMode(filedialog.AnyFile) filedialog.setAcceptMode(qt.QFileDialog.AcceptSave) filedialog.setWindowIcon(qt.QIcon(qt.QPixmap(IconDict["gioconda16"]))) formatlist = ["TIFF Files *.tif", "ASCII Files *.dat", "EDF Files *.edf", 'CSV(, separated) Files *.csv', 'CSV(; separated) Files *.csv', 'CSV(tab separated) Files *.csv'] if hasattr(qt, "QStringList"): strlist = qt.QStringList() else: strlist = [] for f in formatlist: strlist.append(f) saveFilter = formatlist[0] if hasattr(filedialog, "setFilters"): filedialog.setFilters(strlist) filedialog.selectFilter(saveFilter) else: filedialog.setNameFilters(strlist) filedialog.selectNameFilter(saveFilter) filedialog.setDirectory(initdir) ret = filedialog.exec_() if not ret: return "", "" filename = filedialog.selectedFiles()[0] if filename: filename = qt.safe_str(filename) self.outputDir = os.path.dirname(filename) if hasattr(filedialog, "selectedFilter"): saveFilter = qt.safe_str(filedialog.selectedFilter()) else: saveFilter = qt.safe_str(filedialog.selectedNameFilter()) filterused = "." + saveFilter[-3:] PyMcaDirs.outputDir = os.path.dirname(filename) if len(filename) < 4 or filename[-4:] != filterused: filename += filterused else: filename = "" return filename, saveFilter
def saveStackAsNeXus(self, dtype=None, interpretation=None, compression=False): mcaIndex = self._stack.info.get('McaIndex', -1) if interpretation is None: if mcaIndex in [0]: interpretation = "image" else: interpretation = "spectrum" if interpretation not in ["spectrum", "image"]: raise ValueError("Unknown data interpretation %s" % interpretation) filename = self._getOutputHDF5Filename() if not len(filename): return # get only the seen stack portion view = self._getCroppedView() # the current graph axis is saved axes = [None] * len(self._stack.data.shape) labels = [None] * len(self._stack.data.shape) try: xLabel = qt.safe_str(self.mcaWidget.graph.getGraphXLabel()) except: xLabel = None try: xData, y, legend, info = self.mcaWidget.getActiveCurve()[:4] except: xData = self._mcaData0.x[0] xLabel = 'Channels' if interpretation == 'image': labels[0] = xLabel axes[0] = xData else: labels[-1] = xLabel axes[-1] = xData try: ArraySave.save3DArrayAsHDF5(view, filename, axes=axes, labels=labels, dtype=dtype, mode='nexus', mcaindex=mcaIndex, interpretation=interpretation, compression=compression) except: msg = qt.QMessageBox(self) msg.setIcon(qt.QMessageBox.Critical) msg.setWindowTitle("Save error") msg.setText("An error has occured while saving the data:") msg.setInformativeText(qt.safe_str(sys.exc_info()[1])) msg.setDetailedText(traceback.format_exc()) msg.exec_()
def addFileList(self, filelist): """ Expected to work just with EDF files """ text = qt.safe_str(self.windowTitle()) if len(filelist) == 1: text += ": " + qt.safe_str(os.path.basename(filelist[0])) else: text += ": from " + qt.safe_str(os.path.basename(filelist[0])) + \ " to " + qt.safe_str(os.path.basename(filelist[-1])) self.setWindowTitle(text) self.controller.addFileList(filelist)
def setActiveAction(self): modelIndex = self.currentIdx() legend = qt.safe_str(convertToPyObject(modelIndex.data(qt.Qt.DisplayRole))) if DEBUG: print('setActiveAction -- active curve:',legend) ddict = { 'legend' : legend, 'label' : legend, 'selected' : convertToPyObject(modelIndex.data(qt.Qt.CheckStateRole)), 'type' : qt.safe_str(convertToPyObject(modelIndex.data())), 'event': "setActiveCurve", } self.sigContextMenu.emit(ddict)
def mapToRightAction(self): if DEBUG: print('LegendListContextMenu.mapToRightAction called') modelIndex = self.currentIdx() legend = qt.safe_str(convertToPyObject(modelIndex.data(qt.Qt.DisplayRole))) ddict = { 'legend' : legend, 'label' : legend, 'selected' : convertToPyObject(modelIndex.data(qt.Qt.CheckStateRole)), 'type' : qt.safe_str(convertToPyObject(modelIndex.data())), 'event': "mapToRight" } self.sigContextMenu.emit(ddict)
def saveWaterfall(self, signal): if not signal['key'] == 'save': return # Get output filename outfile = qt.QFileDialog(self) outfile.setWindowTitle("Output File Selection") outfile.setModal(1) filterlist = ['*.png', '*.dat'] if hasattr(outfile, "setFilters"): outfile.setFilters(filterlist) else: outfile.setNameFilters(filterlist) outfile.setFileMode(outfile.AnyFile) outfile.setAcceptMode(outfile.AcceptSave) ret = outfile.exec_() if not ret: return None if hasattr(outfile, "selectedFilter"): outputFilter = qt.safe_str(outfile.selectedFilter()) else: outputFilter = qt.safe_str(outfile.selectedNameFilter()) outputFile = qt.safe_str(outfile.selectedFiles()[0]) outfile.close() del outfile extension = outputFilter[-4:] if len(outputFile) < 5: outputFile = outputFile + extension elif outputFile[-4:] != extension: outputFile = outputFile + extension if outputFile is None: return # Save map if extension == '.png': self.waterfallPlotWindow.saveGraph(outputFile, fileFormat='png', dpi=150) print('Plot saved to %s' % outputFile) elif extension == '.dat': for i, q in enumerate(sorted(self.qvals)): index = self.qvals.index(q) if i == 0: x = self.xvals[index] array2export = np.zeros((len(x), len(self.qvals)+1)) array2export[:,0] = x array2export[:,i+1] = np.interp( x, self.xvals[index], self.yvals[index]) header = '--- ' + ' '.join(np.asarray(sorted(self.qvals), dtype='string').tolist()) np.savetxt(outputFile, array2export, fmt='%f', header=header) print('Data saved to %s' % outputFile) return
def removeItemAction(self): if DEBUG == 1: print('LegendListContextMenu.removeCurveAction called') modelIndex = self.currentIdx() legend = qt.safe_str(convertToPyObject(modelIndex.data(qt.Qt.DisplayRole))) ddict = { 'legend' : legend, 'label' : legend, 'selected' : convertToPyObject(modelIndex.data(qt.Qt.CheckStateRole)), 'type' : qt.safe_str(convertToPyObject(modelIndex.data())), 'event': "removeCurve" } self.sigContextMenu.emit(ddict) self.model.removeRow(modelIndex.row())
def setFunctions(self, functionList): currentFunction = qt.safe_str(self.fitFunctionCombo.currentText()) currentBackground = qt.safe_str(self.backgroundCombo.currentText()) self.fitFunctionCombo.clear() self.backgroundCombo.clear() self.fitFunctionCombo.addItem('None') self.backgroundCombo.addItem('None') for key in functionList: self.fitFunctionCombo.addItem(qt.safe_str(key)) self.backgroundCombo.addItem(qt.safe_str(key)) #restore previous values idx = self.fitFunctionCombo.findText(currentFunction) self.fitFunctionCombo.setCurrentIndex(idx) idx = self.backgroundCombo.findText(currentBackground) self.backgroundCombo.setCurrentIndex(idx)
def _getOutputTiffFilename(self): fileTypes = "TIFF Files (*.tif *.tiff *.TIF *.TIFF)" message = "Enter output filename" wdir = PyMcaDirs.outputDir filename = PyMcaFileDialogs.getFileList(self, message=message, mode="SAVE", currentdir=wdir, filetypelist=[fileTypes], getfilter=False, single=True) if len(filename): filename = filename[0] if len(filename): try: fname = qt.safe_str(filename) if fname.endswith('.tif') or\ fname.endswith('.tiff') or\ fname.endswith('.TIF') or\ fname.endswith('.TIFF'): return fname else: return fname + ".tif" except UnicodeEncodeError: msg = qt.QMessageBox(self) msg.setWindowTitle("Encoding error") msg.setIcon(qt.QMessageBox.Critical) msg.setText("Please use ASCII characters in file name and path") msg.exec_() return ""
def setOptions(self,options=['1','2','3']): self.clear() if qt.qVersion() < '4.0.0': self.insertStrList(options) else: for item in options: self.addItem(item)
def getParameters(self): ddict = {} i = 0 for label in self.keyList: ddict[label] = qt.safe_str(self.lineEditList[i].text()) i = i + 1 return ddict
def _browseList(self, filetypes="All Files (*)"): self.inputDir = xrfmc_dirs.inputDir if not os.path.exists(self.inputDir): self.inputDir = os.getcwd() wdir = self.inputDir filedialog = qt.QFileDialog(self) if sys.platform == "darwin": filedialog.setWindowTitle("Select XMI-MSIM application bundle") else: filedialog.setWindowTitle("Select xmimsim-pymca executable") filedialog.setDirectory(wdir) filedialog.setModal(1) filedialog.setFileMode(filedialog.ExistingFiles) if sys.platform == 'darwin': filelist = filedialog.exec_() if filelist: filelist = filedialog.selectedFiles() filelist = filelist[0] xmimsim = os.path.join(qt.safe_str(filelist), "Contents", "Resources", "xmimsim-pymca") filelist = [xmimsim] else: filelist = qt.QFileDialog.getOpenFileName(self, "Selec xmimsim-pymca executable", wdir, filetypes, None) if len(filelist): filelist = [filelist] self.setFileList(filelist)
def __adjustTable(self, table): for col in range(table.columnCount()): table.resizeColumnToContents(col) if qt.qVersion() > '4.0.0': rheight = table.horizontalHeader().sizeHint().height() for row in range(table.rowCount()): table.setRowHeight(row, rheight)
def mySlot(self, energy=None): if energy is None: try: energy = float(qt.safe_str(self.energy.text())) except ValueError: msg=qt.QMessageBox(self.energy) msg.setIcon(qt.QMessageBox.Critical) msg.setText("Invalid Energy Value") msg.setWindowTitle("Invalid energy") msg.exec_() self.energy.setFocus() return threshold = float(self.threshold.value())/1000. lines=[] if self.k.isChecked(): lines.append('K') if self.l1.isChecked(): lines.append('L1') if self.l2.isChecked(): lines.append('L2') if self.l3.isChecked(): lines.append('L3') if self.m.isChecked(): lines.append('M') ddict=Elements.getcandidates(energy,threshold,lines)[0] ddict['text'] =self.getHtmlText(ddict) ddict['event']='Candidates' ddict['lines']=lines if self.__useviewer: self.__browsertext.clear() #self.__browsertext.insertHtml("<CENTER>"+dict['text']+\ # "</CENTER>") self.__browsertext.insertHtml(ddict['text']) self.sigPeakIdentifierSignal.emit(ddict)
def __valueChanged(self, row, col): if col==0: item = self.sumTable.item(row, col) if item is None: item = qt.QTableWidgetItem("", qt.QTableWidgetItem.Type) self.sumTable.setItem(row, col, item) text= qt.safe_str(item.text()) if text.find("All")!=-1 or text.find("all")!=-1 or text.find("-1")!=-1: item.setText("All") else: detsplit= text.replace(",", " ") detsplit= detsplit.replace(";", " ") detsplit= detsplit.replace(":", " ") detsplit= detsplit.split() dets= [] for det in detsplit: try: detno= int(det) except: detno= -1 if detno>=0: dets.append(det) if len(dets): item.setText(' '.join(dets)) else: item.setText("All")
def _save(self): if self.roiDir is None: self.roiDir = PyMcaDirs.outputDir elif not os.path.isdir(self.roiDir): self.roiDir = PyMcaDirs.outputDir outfile = qt.QFileDialog(self) outfile.setFilter('PyMca *.ini') outfile.setFileMode(outfile.AnyFile) outfile.setAcceptMode(qt.QFileDialog.AcceptSave) outfile.setDirectory(self.roiDir) ret = outfile.exec_() if not ret: outfile.close() del outfile return # pyflakes bug http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=666494 outputFile = qt.safe_str(outfile.selectedFiles()[0]) extension = ".ini" outfile.close() del outfile if len(outputFile) < len(extension[:]): outputFile += extension[:] elif outputFile[-4:] != extension[:]: outputFile += extension[:] if os.path.exists(outputFile): try: os.remove(outputFile) except IOError: msg = qt.QMessageBox(self) msg.setIcon(qt.QMessageBox.Critical) msg.setText("Input Output Error: %s" % (sys.exc_info()[1])) msg.exec_() return self.roiDir = os.path.dirname(outputFile) self.save(outputFile)
def getOutputFileName(self): """Open a FileDialog to get the image filename to save to.""" # Copied from PyMca5.PyMcaGui.plotting.MaskImageWidget initdir = PyMcaDirs.outputDir if self.outputDir is not None: if os.path.exists(self.outputDir): initdir = self.outputDir filedialog = qt.QFileDialog(self) filedialog.setFileMode(filedialog.AnyFile) filedialog.setAcceptMode(qt.QFileDialog.AcceptSave) filedialog.setWindowIcon(qt.QIcon(qt.QPixmap(IconDict["gioconda16"]))) formatlist = ["ASCII Files *.dat", "EDF Files *.edf", 'CSV(, separated) Files *.csv', 'CSV(; separated) Files *.csv', 'CSV(tab separated) Files *.csv', # Added from PlotWindow._getOutputFileName for snapshot 'Widget PNG *.png', 'Widget JPG *.jpg'] if hasattr(qt, "QStringList"): strlist = qt.QStringList() else: strlist = [] for f in formatlist: strlist.append(f) if self._saveFilter is None: self._saveFilter = formatlist[0] filedialog.setFilters(strlist) filedialog.selectFilter(self._saveFilter) filedialog.setDirectory(initdir) ret = filedialog.exec_() if not ret: return "" filename = filedialog.selectedFiles()[0] if len(filename): filename = qt.safe_str(filename) self.outputDir = os.path.dirname(filename) self._saveFilter = qt.safe_str(filedialog.selectedFilter()) filterused = "." + self._saveFilter[-3:] PyMcaDirs.outputDir = os.path.dirname(filename) if len(filename) < 4: filename = filename + filterused elif filename[-4:] != filterused: filename = filename + filterused else: filename = "" return filename
def _calboxactivated(self, item=None): if DEBUG: item = qt.safe_str(item) print("Calibration box activated %s" % item) comboitem, combotext = self.calbox.getCurrent() self._emitpysignal(box=[comboitem,combotext], boxname='Calibration', event='activated')
def __init__(self, parent=None): qt.QWidget.__init__(self, parent) self.mainLayout = qt.QGridLayout(self) self.mainLayout.setContentsMargins(2, 2, 2, 2) self.mainLayout.setSpacing(2) font = qt.QFont(self.font()) font.setBold(True) #Function handling self.functionLabel = qt.QLabel(self) self.functionLabel.setFont(font) self.functionLabel.setText("Function:") self.addFunctionButton = qt.QPushButton(self) self.addFunctionButton.setText("ADD") #fit function self.fitFunctionLabel = qt.QLabel(self) self.fitFunctionLabel.setFont(font) self.fitFunctionLabel.setText("Fit:") self.fitFunctionCombo = qt.QComboBox(self) self.fitFunctionCombo.addItem(qt.safe_str("None")) self.fitFunctionCombo.setSizeAdjustPolicy(qt.QComboBox.AdjustToContents) self.fitFunctionCombo.setMinimumWidth(100) #background function self.backgroundLabel = qt.QLabel(self) self.backgroundLabel.setFont(font) self.backgroundLabel.setText("Background:") self.backgroundCombo = qt.QComboBox(self) self.backgroundCombo.addItem(qt.safe_str("None")) self.backgroundCombo.setSizeAdjustPolicy(qt.QComboBox.AdjustToContents) self.backgroundCombo.setMinimumWidth(100) #arrange everything self.mainLayout.addWidget(self.functionLabel, 0, 0) self.mainLayout.addWidget(self.addFunctionButton, 0, 1) self.mainLayout.addWidget(qt.HorizontalSpacer(self), 0, 2) self.mainLayout.addWidget(self.fitFunctionLabel, 0, 3) self.mainLayout.addWidget(self.fitFunctionCombo, 0, 4) self.mainLayout.addWidget(qt.HorizontalSpacer(self), 0, 5) self.mainLayout.addWidget(self.backgroundLabel, 0, 6) self.mainLayout.addWidget(self.backgroundCombo, 0, 7) self.configureButton = qt.QPushButton(self) self.configureButton.setText("CONFIGURE") self.mainLayout.addWidget(self.configureButton, 0, 8)
def __addInFileList(self, type, name): itemname= "%s:%s"%(type, name) for i in range(self.listFiles.count()): item = self.listFiles.item(i) if qt.safe_str(item.text())==itemname: return 0 self.listFiles.addItem(itemname) return 1
class RegionsWidget(qt.QGroupBox): sigRegionsWidgetSignal = qt.pyqtSignal(object) def __init__(self, parent=None, nregions=10, limits=[0.0, 1000.]): qt.QGroupBox.__init__(self, parent) self.setTitle('Spectral Regions') self.mainLayout = qt.QGridLayout(self) self.mainLayout.setContentsMargins(0, 0, 0, 0) self.mainLayout.setSpacing(2) if nregions % 2: nregions += 1 self.nRegions = nregions self.regionList = [] self.__limits = [limits[0], limits[1]] # Nice hint -> What about: # self.regionList.extend([[limits[0], limits[1]] * self.nRegions) # instead of this loop with the useless i? for i in range(self.nRegions): self.regionList.append([limits[0], limits[1]]) self.nRegionsLabel = qt.QLabel(self) self.nRegionsLabel.setText("Number of Regions:") self.nRegionsSpinBox = qt.QSpinBox(self) self.nRegionsSpinBox.setMinimum(0) self.nRegionsSpinBox.setValue(0) self.nRegionsSpinBox.setMaximum(self.nRegions) self.mainLayout.addWidget(self.nRegionsLabel, 0, 0) self.mainLayout.addWidget(self.nRegionsSpinBox, 0, 1) self.nRegionsSpinBox.valueChanged[int].connect(self._regionsChanged) self.currentRegionLabel = qt.QLabel(self) self.currentRegionLabel.setText("Current Region:") self.currentRegionSpinBox = qt.QSpinBox(self) self.currentRegionSpinBox.setMinimum(1) self.currentRegionSpinBox.setValue(1) self.currentRegionSpinBox.setMaximum(1) self.mainLayout.addWidget(self.currentRegionLabel, 0, 2) self.mainLayout.addWidget(self.currentRegionSpinBox, 0, 3) self.currentRegionSpinBox.valueChanged[int].connect(self._currentRegionChanged) label = qt.QLabel(self) label.setText("From:") self.fromLine = qt.QLineEdit(self) self.fromLine.setText("%f" % limits[0]) self.fromLine._v = qt.QDoubleValidator(self.fromLine) self.fromLine.setValidator(self.fromLine._v) self.mainLayout.addWidget(label, 0, 4) self.mainLayout.addWidget(self.fromLine, 0, 5) self.fromLine.editingFinished[()].connect(self._editingSlot) label = qt.QLabel(self) label.setText("To:") self.toLine = qt.QLineEdit(self) self.toLine.setText("%f" % limits[1]) self.toLine._v = qt.QDoubleValidator(self.toLine) self.toLine.setValidator(self.toLine._v) self.mainLayout.addWidget(label, 0, 6) self.mainLayout.addWidget(self.toLine, 0, 7) self.toLine.editingFinished[()].connect(self._editingSlot) self._regionsChanged(0) def setLimits(self, xmin, xmax): for i in range(len(self.regionList)): self.regionList[i][0] = max(self.regionList[i][0], xmin) self.regionList[i][1] = min(self.regionList[i][1], xmax) self.__limits = [xmin, xmax] current = self.currentRegionSpinBox.value() self._currentRegionChanged(current) def _regionsChanged(self, value): if value == 0: self.toLine.setDisabled(True) self.fromLine.setDisabled(True) self.currentRegionSpinBox.setDisabled(True) else: current = self.currentRegionSpinBox.value() self.currentRegionSpinBox.setMaximum(value) self.toLine.setDisabled(False) self.fromLine.setDisabled(False) self.currentRegionSpinBox.setDisabled(False) if current > value: self.currentRegionSpinBox.setValue(value) self._currentRegionChanged(value) def _currentRegionChanged(self, value): if value > 0: fromValue, toValue = self.regionList[value - 1] self.fromLine.setText("%f" % fromValue) self.toLine.setText("%f" % toValue) self.mySignal() def _editingSlot(self, signal=True): current = self.currentRegionSpinBox.value() - 1 self.regionList[current][0] = float(str(self.fromLine.text())) self.regionList[current][1] = float(str(self.toLine.text())) if self.regionList[current][0] < self.__limits[0]: self.regionList[current][0] = self.__limits[0] if self.regionList[current][1] > self.__limits[1]: self.regionList[current][1] = self.__limits[1] if signal: self.mySignal() def mySignal(self): current = self.currentRegionSpinBox.value() - 1 ddict={} ddict['event'] = 'regionChanged' ddict['nRegions'] = self.nRegionsSpinBox.value() ddict['current'] = current if current >= 0: ddict['from'] = self.regionList[current][0] ddict['to'] = self.regionList[current][1] self.sigRegionsWidgetSignal.emit(ddict) def getRegions(self): nRegions = self.nRegionsSpinBox.value() regions = [] if nRegions > 0: for i in range(nRegions): regions.append(self.regionList[i]) return regions def setRegions(self, regionList=None): """ :param regionList: List of couple of "from" and to "values" :type param: List """ if regionList is None: regionList = [] nRegions = len(regionList) # the number of regions is small so, we can afford to loop # instead of a direct copy self.regionList = [] for i in range(nRegions): fromValue, toValue = regionList[i] self.regionList.append([fromValue, toValue]) self.currentRegionSpinBox.setValue(nRegions) if nRegions > 0: self._editingSlot(signal=False) self._regionsChanged(self, nRegions)
#############################################################################*/ __author__ = "V. Armando Sole - ESRF Data Analysis" __contact__ = "*****@*****.**" __license__ = "MIT" __copyright__ = "European Synchrotron Radiation Facility, Grenoble, France" import logging from PyMca5.PyMcaPhysics import Elements from PyMca5.PyMcaPhysics import XRayTubeEbel import numpy from PyMca5.PyMcaGui import PyMcaQt as qt from PyMca5.PyMcaGui.PluginsToolButton import PluginsToolButton from silx.gui.plot import PlotWindow _logger = logging.getLogger(__name__) if qt.qVersion() > '4.0.0': class QGridLayout(qt.QGridLayout): def addMultiCellWidget(self, w, r0, r1, c0, c1, *var): self.addWidget(w, r0, c0, 1 + r1 - r0, 1 + c1 - c0) class QXTube(qt.QWidget): sigQXTubeSignal = qt.pyqtSignal(object) def __init__(self, parent=None, initdict=None): qt.QWidget.__init__(self, parent) self.l = qt.QVBoxLayout(self) self.l.setContentsMargins(0, 0, 0, 0) self.l.setSpacing(0)
def __init__(self, parent=None, nregions=10, limits=[0.0, 1000.]): qt.QGroupBox.__init__(self, parent) self.setTitle('Spectral Regions') self.mainLayout = qt.QGridLayout(self) self.mainLayout.setContentsMargins(0, 0, 0, 0) self.mainLayout.setSpacing(2) if nregions % 2: nregions += 1 self.nRegions = nregions self.regionList = [] self.__limits = [limits[0], limits[1]] # Nice hint -> What about: # self.regionList.extend([[limits[0], limits[1]] * self.nRegions) # instead of this loop with the useless i? for i in range(self.nRegions): self.regionList.append([limits[0], limits[1]]) self.nRegionsLabel = qt.QLabel(self) self.nRegionsLabel.setText("Number of Regions:") self.nRegionsSpinBox = qt.QSpinBox(self) self.nRegionsSpinBox.setMinimum(0) self.nRegionsSpinBox.setValue(0) self.nRegionsSpinBox.setMaximum(self.nRegions) self.mainLayout.addWidget(self.nRegionsLabel, 0, 0) self.mainLayout.addWidget(self.nRegionsSpinBox, 0, 1) self.nRegionsSpinBox.valueChanged[int].connect(self._regionsChanged) self.currentRegionLabel = qt.QLabel(self) self.currentRegionLabel.setText("Current Region:") self.currentRegionSpinBox = qt.QSpinBox(self) self.currentRegionSpinBox.setMinimum(1) self.currentRegionSpinBox.setValue(1) self.currentRegionSpinBox.setMaximum(1) self.mainLayout.addWidget(self.currentRegionLabel, 0, 2) self.mainLayout.addWidget(self.currentRegionSpinBox, 0, 3) self.currentRegionSpinBox.valueChanged[int].connect(self._currentRegionChanged) label = qt.QLabel(self) label.setText("From:") self.fromLine = qt.QLineEdit(self) self.fromLine.setText("%f" % limits[0]) self.fromLine._v = qt.QDoubleValidator(self.fromLine) self.fromLine.setValidator(self.fromLine._v) self.mainLayout.addWidget(label, 0, 4) self.mainLayout.addWidget(self.fromLine, 0, 5) self.fromLine.editingFinished[()].connect(self._editingSlot) label = qt.QLabel(self) label.setText("To:") self.toLine = qt.QLineEdit(self) self.toLine.setText("%f" % limits[1]) self.toLine._v = qt.QDoubleValidator(self.toLine) self.toLine.setValidator(self.toLine._v) self.mainLayout.addWidget(label, 0, 6) self.mainLayout.addWidget(self.toLine, 0, 7) self.toLine.editingFinished[()].connect(self._editingSlot) self._regionsChanged(0)
def __init__(self, parent=None, options=[1, 2, 3, 4, 5, 10], regions=False, index=-1): qt.QDialog.__init__(self, parent) self.setWindowTitle("PCA Configuration Dialog") self.mainLayout = qt.QVBoxLayout(self) self.mainLayout.setContentsMargins(11, 11, 11, 11) self.mainLayout.setSpacing(0) self.methodOptions = qt.QGroupBox(self) self.methodOptions.setTitle('PCA Method to use') self.methods = ['Covariance', 'Expectation Max.', 'Cov. Multiple Arrays'] self.functions = [PCAModule.numpyPCA, PCAModule.expectationMaximizationPCA, PCAModule.multipleArrayPCA] self.methodOptions.mainLayout = qt.QGridLayout(self.methodOptions) self.methodOptions.mainLayout.setContentsMargins(0, 0, 0, 0) self.methodOptions.mainLayout.setSpacing(2) #this does not seem to bring any advantage if 0: self.methods.append("Covariance Numpy") self.functions.append(PCAModule.numpyPCA) if MDP and (index != 0): #self.methods.append("MDP (PCA + ICA)") self.methods.append("MDP (SVD float32)") self.methods.append("MDP (SVD float64)") self.methods.append("MDP ICA (float32)") self.methods.append("MDP ICA (float64)") self.functions.append(PCAModule.mdpPCASVDFloat32) self.functions.append(PCAModule.mdpPCASVDFloat64) self.functions.append(PCAModule.mdpICAFloat32) self.functions.append(PCAModule.mdpICAFloat64) self.buttonGroup = qt.QButtonGroup(self.methodOptions) i = 0 for item in self.methods: rButton = qt.QRadioButton(self.methodOptions) self.methodOptions.mainLayout.addWidget(rButton, 0, i) #self.l.setAlignment(rButton, qt.Qt.AlignHCenter) if i == 1: rButton.setChecked(True) rButton.setText(item) self.buttonGroup.addButton(rButton) self.buttonGroup.setId(rButton, i) i += 1 self.buttonGroup.buttonPressed[int].connect(self._slot) self.mainLayout.addWidget(self.methodOptions) #built in speed options self.speedOptions = qt.QGroupBox(self) self.speedOptions.setTitle("Speed Options") self.speedOptions.mainLayout = qt.QGridLayout(self.speedOptions) self.speedOptions.mainLayout.setContentsMargins(0, 0, 0, 0) self.speedOptions.mainLayout.setSpacing(2) labelPC = qt.QLabel(self) labelPC.setText("Number of PC:") self.nPC = qt.QSpinBox(self.speedOptions) self.nPC.setMinimum(0) self.nPC.setValue(10) self.nPC.setMaximum(40) self.binningLabel = qt.QLabel(self.speedOptions) self.binningLabel.setText("Spectral Binning:") self.binningCombo = qt.QComboBox(self.speedOptions) for option in options: self.binningCombo.addItem("%d" % option) self.speedOptions.mainLayout.addWidget(labelPC, 0, 0) self.speedOptions.mainLayout.addWidget(self.nPC, 0, 1) #self.speedOptions.mainLayout.addWidget(qt.HorizontalSpacer(self), 0, 2) self.speedOptions.mainLayout.addWidget(self.binningLabel, 1, 0) self.speedOptions.mainLayout.addWidget(self.binningCombo, 1, 1) self.binningCombo.setEnabled(False) self.binningCombo.activated[int].connect( \ self._updatePlotFromBinningCombo) if regions: self.__regions = True self.__addRegionsWidget() else: self.__regions = False #the optional plot self.graph = None #the OK button hbox = qt.QWidget(self) hboxLayout = qt.QHBoxLayout(hbox) hboxLayout.setContentsMargins(0, 0, 0, 0) hboxLayout.setSpacing(0) self.okButton = qt.QPushButton(hbox) self.okButton.setText("Accept") self.okButton.setAutoDefault(False) hboxLayout.addWidget(qt.HorizontalSpacer(hbox)) hboxLayout.addWidget(self.okButton) hboxLayout.addWidget(qt.HorizontalSpacer(hbox)) self.mainLayout.addWidget(self.speedOptions) if regions: self.mainLayout.addWidget(self.regionsWidget) self.mainLayout.addWidget(hbox) if self.graph is not None: self.mainLayout.addWidget(self.graph) self.okButton.clicked.connect(self.accept)
def __init__(self, *var, **kw): ddict = {} ddict['usetab'] = True ddict.update(kw) ddict['standalonesave'] = False MaskImageWidget.MaskImageWidget.__init__(self, *var, **ddict) self.slider = qt.QSlider(self) self.slider.setOrientation(qt.Qt.Horizontal) self.slider.setMinimum(0) self.slider.setMaximum(0) # The 1D graph self.vectorGraph = ScanWindow.ScanWindow(self) self.mainTab.addTab(self.vectorGraph, "VECTORS") self.mainLayout.addWidget(self.slider) self.slider.valueChanged[int].connect(self._showImage) self.imageList = None self.imageNames=None self.eigenValues = None self.eigenVectors = None self.vectorNames = None self.vectorGraphTitles = None standalonesave = kw.get("standalonesave", True) if standalonesave: self.graphWidget.saveToolButton.clicked.connect( \ self._saveToolButtonSignal) self._saveMenu = qt.QMenu() self._saveMenu.addAction(QString("Image Data"), self.saveImageList) self._saveMenu.addAction(QString("Standard Graphics"), self.graphWidget._saveIconSignal) if MATPLOTLIB: self._saveMenu.addAction(QString("Matplotlib") , self._saveMatplotlibImage) self.multiplyIcon = qt.QIcon(qt.QPixmap(IconDict["swapsign"])) infotext = "Multiply image by -1" self.multiplyButton = self.graphWidget._addToolButton(\ self.multiplyIcon, self._multiplyIconChecked, infotext, toggle=False, position=12) # The density plot widget self.scatterPlotWidget = ScatterPlotCorrelatorWidget.ScatterPlotCorrelatorWidget(None, labels=["Legend", "X", "Y"], types=["Text", "RadioButton", "RadioButton"], maxNRois=1) self.__scatterPlotWidgetDataToUpdate = True self.__maskToScatterConnected = True self.sigMaskImageWidgetSignal.connect(self._internalSlot) self.scatterPlotWidget.sigMaskScatterWidgetSignal.connect( \ self._internalSlot) # add the command to show it to the menu if hasattr(self, "_additionalSelectionMenu"): self.additionalSelectionMenu().addAction(\ QString("Show scatter plot"), self.showScatterPlot)
def sizeHint(self): return qt.QSize(1.5 * qt.QWidget.sizeHint(self).width(), qt.QWidget.sizeHint(self).height())
def sizeHint(self): return qt.QSize(400, 400)
def focusInEvent(self, event): self.setPaletteBackgroundColor(qt.QColor('yellow'))
def _saveIconSignal(self): self.saveDirectory = PyMcaDirs.outputDir fileTypeList = ["Image *.png", "Image *.jpg", "ZoomedImage *.png", "ZoomedImage *.jpg", "Widget *.png", "Widget *.jpg"] outfile = qt.QFileDialog(self) outfile.setModal(1) outfile.setWindowTitle("Output File Selection") if hasattr(qt, "QStringList"): strlist = qt.QStringList() else: strlist = [] for f in fileTypeList: strlist.append(f) if hasattr(outfile, "setFilters"): outfile.setFilters(strlist) else: outfile.setNameFilters(strlist) outfile.setFileMode(outfile.AnyFile) outfile.setAcceptMode(qt.QFileDialog.AcceptSave) outfile.setDirectory(self.saveDirectory) ret = outfile.exec() if not ret: return if hasattr(outfile, "selectedFilter"): filterused = qt.safe_str(outfile.selectedFilter()).split() else: filterused = qt.safe_str(outfile.selectedNameFilter()).split() filetype = filterused[0] extension = filterused[1] outstr = qt.safe_str(outfile.selectedFiles()[0]) try: outputFile = os.path.basename(outstr) except: outputFile = outstr outputDir = os.path.dirname(outstr) self.saveDirectory = outputDir PyMcaDirs.outputDir = outputDir #always overwrite for the time being if len(outputFile) < len(extension[1:]): outputFile += extension[1:] elif outputFile[-4:] != extension[1:]: outputFile += extension[1:] outputFile = os.path.join(outputDir, outputFile) if os.path.exists(outputFile): try: os.remove(outputFile) except: qt.QMessageBox.critical(self, "Save Error", "Cannot overwrite existing file") return if filetype.upper() == "IMAGE": self.saveGraphImage(outputFile, original=True) elif filetype.upper() == "ZOOMEDIMAGE": self.saveGraphImage(outputFile, original=False) else: self.saveGraphWidget(outputFile)
def focusOutEvent(self, event): self.setPaletteBackgroundColor(qt.QColor('white')) self.sigFocusOut.emit()
class HDF5CounterTable(qt.QTableWidget): sigHDF5CounterTableSignal = qt.pyqtSignal(object) def __init__(self, parent=None): qt.QTableWidget.__init__(self, parent) self.cntList = [] self.aliasList = [] self.mcaList = [] self.xSelection = [] self.ySelection = [] self.monSelection = [] self.__oldSelection = self.getCounterSelection() self.__is3DEnabled = False self.__is2DEnabled = False labels = ['Dataset', 'Axes', 'Signals', 'Monitor', 'Alias'] self.setColumnCount(len(labels)) for i in range(len(labels)): item = self.horizontalHeaderItem(i) if item is None: item = qt.QTableWidgetItem(labels[i], qt.QTableWidgetItem.Type) item.setText(labels[i]) self.setHorizontalHeaderItem(i, item) """ #the cell is not the same as the check box #but I wonder about the checkboxes being destroyed """ self.cellChanged[int, int].connect(self._aliasSlot) def build(self, cntlist, aliaslist=None): self.__building = True if len(cntlist): if len(self.cntList): self.__oldSelection = self.getCounterSelection() if aliaslist is None: aliaslist = [] for item in cntlist: aliaslist.append(posixpath.basename(item)) if len(cntlist) != len(aliaslist): raise ValueError( "Alias list and counter list must have same length") self.cntList = cntlist self.aliasList = aliaslist n = len(cntlist) self.setRowCount(n) if n > 0: self.setRowCount(n) rheight = self.horizontalHeader().sizeHint().height() # check if we need the complete description useFullPath = [] for i in range(n): iName = posixpath.basename(cntlist[i]) for j in range(i + 1, n): if posixpath.basename(cntlist[j]) == iName: if i not in useFullPath: useFullPath.append(i) if j not in useFullPath: useFullPath.append(j) for i in range(n): self.setRowHeight(i, rheight) if i in useFullPath: self.__addLine(i, cntlist[i]) else: self.__addLine(i, posixpath.basename(cntlist[i])) for j in range(1, 4, 1): widget = self.cellWidget(i, j) widget.setEnabled(True) else: self.setRowCount(0) self.resizeColumnToContents(1) self.resizeColumnToContents(2) self.resizeColumnToContents(3) self.setCounterSelection(self.__oldSelection) self.__building = False def __addLine(self, i, cntlabel): #the counter name item = self.item(i, 0) if item is None: item = qt.QTableWidgetItem(cntlabel, qt.QTableWidgetItem.Type) item.setTextAlignment(qt.Qt.AlignHCenter | qt.Qt.AlignVCenter) self.setItem(i, 0, item) else: item.setText(cntlabel) #item is just enabled (not selectable) item.setFlags(qt.Qt.ItemIsEnabled) #the checkboxes for j in range(1, 4, 1): widget = self.cellWidget(i, j) if widget is None: widget = CheckBoxItem(self, i, j) self.setCellWidget(i, j, widget) widget.sigCheckBoxItemSignal.connect(self._mySlot) else: pass #the alias item = self.item(i, 4) alias = self.aliasList[i] if item is None: item = qt.QTableWidgetItem(alias, qt.QTableWidgetItem.Type) item.setTextAlignment(qt.Qt.AlignHCenter | qt.Qt.AlignVCenter) self.setItem(i, 4, item) else: item.setText(alias) def set3DEnabled(self, value, emit=True): if value: self.__is3DEnabled = True self.__is2DEnabled = True else: self.__is3DEnabled = False if len(self.xSelection) > 1: self.xSelection = self.xSelection[-1:] self._update(emit=emit) def set2DEnabled(self, value, emit=True): if value: self.__is2DEnabled = True self.__is3DEnabled = False if len(self.xSelection) > 2: self.xSelection = self.xSelection[-2:] else: self.__is2DEnabled = False if len(self.xSelection) > 1: self.xSelection = self.xSelection[-1:] self._update(emit=emit) def _aliasSlot(self, row, col): if self.__building: return if col != 4: return item = self.item(row, 4) self.aliasList[row] = safe_str(item.text()) def _mySlot(self, ddict): row = ddict["row"] col = ddict["col"] if col == 1: if ddict["state"]: if row not in self.xSelection: self.xSelection.append(row) else: if row in self.xSelection: del self.xSelection[self.xSelection.index(row)] if self.__is3DEnabled: if len(self.xSelection) > 3: self.xSelection = self.xSelection[-3:] elif self.__is2DEnabled: if len(self.xSelection) > 2: self.xSelection = self.xSelection[-2:] else: if len(self.xSelection) > 1: self.xSelection = self.xSelection[-1:] if col == 2: if ddict["state"]: if row not in self.ySelection: self.ySelection.append(row) else: if row in self.ySelection: del self.ySelection[self.ySelection.index(row)] if col == 3: if ddict["state"]: if row not in self.monSelection: self.monSelection.append(row) else: if row in self.monSelection: del self.monSelection[self.monSelection.index(row)] if len(self.monSelection) > 1: self.monSelection = self.monSelection[-1:] self._update() def _update(self, emit=True): axisLabels = ['X', 'Y', 'Z'] for i in range(self.rowCount()): j = 1 widget = self.cellWidget(i, j) if i in self.xSelection: if not widget.isChecked(): widget.setChecked(True) widget.setText(axisLabels[self.xSelection.index(i)]) else: if widget.isChecked(): widget.setChecked(False) widget.setText("") j = 2 widget = self.cellWidget(i, j) if i in self.ySelection: if not widget.isChecked(): widget.setChecked(True) else: if widget.isChecked(): widget.setChecked(False) j = 3 widget = self.cellWidget(i, j) if i in self.monSelection: if not widget.isChecked(): widget.setChecked(True) else: if widget.isChecked(): widget.setChecked(False) if emit: ddict = {} ddict["event"] = "updated" self.sigHDF5CounterTableSignal.emit(ddict) def getCounterSelection(self): ddict = {} ddict['cntlist'] = self.cntList * 1 ddict['aliaslist'] = self.aliasList * 1 ddict['x'] = self.xSelection * 1 ddict['y'] = self.ySelection * 1 ddict['m'] = self.monSelection * 1 return ddict def setCounterSelection(self, ddict): _logger.debug("HDF5CounterTable.setCounterSelection %s", ddict) keys = ddict.keys() if 'cntlist' in keys: cntlist = ddict['cntlist'] else: cntlist = self.cntList * 1 # no selection based on aliaslist or counterlist (yet?) if 0: if 'aliaslist' in keys: aliaslist = ddict['aliaslist'] elif len(self.aliasList) == len(cntlist): aliaslist = self.aliasList * 1 else: aliaslist = self.cntList * 1 if 'x' in keys: x = ddict['x'] else: x = [] if 'y' in keys: y = ddict['y'] else: y = [] if 'm' in keys: monitor = ddict['m'] else: monitor = [] self.xSelection = [] for item in x: if item < len(cntlist): counter = cntlist[item] if counter in self.cntList: # counter name based selection self.xSelection.append(self.cntList.index(counter)) elif item < len(self.cntList): # index based selection self.xSelection.append(item) self.ySelection = [] for item in y: if item < len(cntlist): counter = cntlist[item] if counter in self.cntList: self.ySelection.append(self.cntList.index(counter)) self.monSelection = [] for item in monitor: if item < len(cntlist): counter = cntlist[item] if counter in self.cntList: self.monSelection.append(self.cntList.index(counter)) self._update()
def getParameters(self): ddict = {} ddict['file_use'] = self.checkBox.isChecked() ddict['file_name'] = qt.safe_str(self.fileName.text()) return ddict
class RGBCorrelatorGraph(qt.QWidget): sigProfileSignal = qt.pyqtSignal(object) def __init__(self, parent = None, backend=None, selection=False, aspect=True, colormap=False, imageicons=False, standalonesave=True, standalonezoom=True, profileselection=False, polygon=False): qt.QWidget.__init__(self, parent) self.mainLayout = qt.QVBoxLayout(self) self.mainLayout.setContentsMargins(0, 0, 0, 0) self.mainLayout.setSpacing(0) self._keepDataAspectRatioFlag = False self.graph = PlotWidget(parent=self, backend=backend) self.graph.setGraphXLabel("Column") self.graph.setGraphYLabel("Row") self.graph.setYAxisAutoScale(True) self.graph.setXAxisAutoScale(True) plotArea = self.graph.getWidgetHandle() plotArea.setContextMenuPolicy(qt.Qt.CustomContextMenu) plotArea.customContextMenuRequested.connect(self._zoomBack) self._buildToolBar(selection, colormap, imageicons, standalonesave, standalonezoom=standalonezoom, profileselection=profileselection, aspect=aspect, polygon=polygon) if profileselection: if len(self._pickerSelectionButtons): self.graph.sigPlotSignal.connect(\ self._graphPolygonSignalReceived) self._pickerSelectionWidthValue.valueChanged[int].connect( \ self.setPickerSelectionWith) self.saveDirectory = os.getcwd() self.mainLayout.addWidget(self.graph) def sizeHint(self): return qt.QSize(1.5 * qt.QWidget.sizeHint(self).width(), qt.QWidget.sizeHint(self).height()) def _buildToolBar(self, selection=False, colormap=False, imageicons=False, standalonesave=True, standalonezoom=True, profileselection=False, aspect=False, polygon=False): self.solidCircleIcon = qt.QIcon(qt.QPixmap(IconDict["solidcircle"])) self.solidEllipseIcon = qt.QIcon(qt.QPixmap(IconDict["solidellipse"])) self.colormapIcon = qt.QIcon(qt.QPixmap(IconDict["colormap"])) self.selectionIcon = qt.QIcon(qt.QPixmap(IconDict["normal"])) self.zoomResetIcon = qt.QIcon(qt.QPixmap(IconDict["zoomreset"])) self.polygonIcon = qt.QIcon(qt.QPixmap(IconDict["polygon"])) self.printIcon = qt.QIcon(qt.QPixmap(IconDict["fileprint"])) self.saveIcon = qt.QIcon(qt.QPixmap(IconDict["filesave"])) self.xAutoIcon = qt.QIcon(qt.QPixmap(IconDict["xauto"])) self.yAutoIcon = qt.QIcon(qt.QPixmap(IconDict["yauto"])) self.hFlipIcon = qt.QIcon(qt.QPixmap(IconDict["gioconda16mirror"])) self.imageIcon = qt.QIcon(qt.QPixmap(IconDict["image"])) self.eraseSelectionIcon = qt.QIcon(qt.QPixmap(IconDict["eraseselect"])) self.rectSelectionIcon = qt.QIcon(qt.QPixmap(IconDict["boxselect"])) self.brushSelectionIcon = qt.QIcon(qt.QPixmap(IconDict["brushselect"])) self.brushIcon = qt.QIcon(qt.QPixmap(IconDict["brush"])) self.additionalIcon = qt.QIcon(qt.QPixmap(IconDict["additionalselect"])) self.hLineIcon = qt.QIcon(qt.QPixmap(IconDict["horizontal"])) self.vLineIcon = qt.QIcon(qt.QPixmap(IconDict["vertical"])) self.lineIcon = qt.QIcon(qt.QPixmap(IconDict["diagonal"])) self.copyIcon = silx_icons.getQIcon("edit-copy") self.toolBar = qt.QWidget(self) self.toolBarLayout = qt.QHBoxLayout(self.toolBar) self.toolBarLayout.setContentsMargins(0, 0, 0, 0) self.toolBarLayout.setSpacing(0) self.mainLayout.addWidget(self.toolBar) #Autoscale if standalonezoom: tb = self._addToolButton(self.zoomResetIcon, self.__zoomReset, 'Auto-Scale the Graph') else: tb = self._addToolButton(self.zoomResetIcon, None, 'Auto-Scale the Graph') self.zoomResetToolButton = tb #y Autoscale tb = self._addToolButton(self.yAutoIcon, self._yAutoScaleToggle, 'Toggle Autoscale Y Axis (On/Off)', toggle = True, state=True) tb.setDown(True) self.yAutoScaleToolButton = tb tb.setDown(True) #x Autoscale tb = self._addToolButton(self.xAutoIcon, self._xAutoScaleToggle, 'Toggle Autoscale X Axis (On/Off)', toggle = True, state=True) self.xAutoScaleToolButton = tb tb.setDown(True) #Aspect ratio if aspect: self.aspectButton = self._addToolButton(self.solidCircleIcon, self._aspectButtonSignal, 'Keep data aspect ratio', toggle=False) self.aspectButton.setChecked(False) #colormap if colormap: tb = self._addToolButton(self.colormapIcon, None, 'Change Colormap') self.colormapToolButton = tb #flip tb = self._addToolButton(self.hFlipIcon, None, 'Flip Horizontal') self.hFlipToolButton = tb #save if standalonesave: tb = self._addToolButton(self.saveIcon, self._saveIconSignal, 'Save Graph') else: tb = self._addToolButton(self.saveIcon, None, 'Save') self.saveToolButton = tb self.copyToolButton = self._addToolButton(self.copyIcon, self._copyIconSignal, "Copy graph to clipboard") #Selection if selection: tb = self._addToolButton(self.selectionIcon, None, 'Toggle Selection Mode', toggle = True, state = False) tb.setDown(False) self.selectionToolButton = tb #image selection icons if imageicons: tb = self._addToolButton(self.imageIcon, None, 'Reset') self.imageToolButton = tb tb = self._addToolButton(self.eraseSelectionIcon, None, 'Erase Selection') self.eraseSelectionToolButton = tb tb = self._addToolButton(self.rectSelectionIcon, None, 'Rectangular Selection') self.rectSelectionToolButton = tb tb = self._addToolButton(self.brushSelectionIcon, None, 'Brush Selection') self.brushSelectionToolButton = tb tb = self._addToolButton(self.brushIcon, None, 'Select Brush') self.brushToolButton = tb if polygon: tb = self._addToolButton(self.polygonIcon, None, 'Polygon selection\nRight click to finish') self.polygonSelectionToolButton = tb tb = self._addToolButton(self.additionalIcon, None, 'Additional Selections Menu') self.additionalSelectionToolButton = tb else: if polygon: tb = self._addToolButton(self.polygonIcon, None, 'Polygon selection\nRight click to finish') self.polygonSelectionToolButton = tb self.imageToolButton = None #picker selection self._pickerSelectionButtons = [] if profileselection: self._profileSelection = True self._polygonSelection = False self._pickerSelectionButtons = [] if self._profileSelection: tb = self._addToolButton(self.hLineIcon, self._hLineProfileClicked, 'Horizontal Profile Selection', toggle=True, state=False) self.hLineProfileButton = tb self._pickerSelectionButtons.append(tb) tb = self._addToolButton(self.vLineIcon, self._vLineProfileClicked, 'Vertical Profile Selection', toggle=True, state=False) self.vLineProfileButton = tb self._pickerSelectionButtons.append(tb) tb = self._addToolButton(self.lineIcon, self._lineProfileClicked, 'Line Profile Selection', toggle=True, state=False) self.lineProfileButton = tb self._pickerSelectionButtons.append(tb) self._pickerSelectionWidthLabel = qt.QLabel(self.toolBar) self._pickerSelectionWidthLabel.setText("W:") self.toolBar.layout().addWidget(self._pickerSelectionWidthLabel) self._pickerSelectionWidthValue = qt.QSpinBox(self.toolBar) self._pickerSelectionWidthValue.setMinimum(0) self._pickerSelectionWidthValue.setMaximum(1000) self._pickerSelectionWidthValue.setValue(1) self.toolBar.layout().addWidget(self._pickerSelectionWidthValue) #tb = self._addToolButton(None, # self._lineProfileClicked, # 'Line Profile Selection', # toggle=True, # state=False) #tb.setText = "W:" #self.lineWidthProfileButton = tb #self._pickerSelectionButtons.append(tb) if self._polygonSelection: _logger.info("Polygon selection not implemented yet") #hide profile selection buttons if imageicons: for button in self._pickerSelectionButtons: button.hide() self.infoWidget = qt.QWidget(self.toolBar) self.infoWidget.mainLayout = qt.QHBoxLayout(self.infoWidget) self.infoWidget.mainLayout.setContentsMargins(0, 0, 0, 0) self.infoWidget.mainLayout.setSpacing(0) self.infoWidget.label = qt.QLabel(self.infoWidget) self.infoWidget.label.setText("X = ???? Y = ???? Z = ????") self.infoWidget.mainLayout.addWidget(self.infoWidget.label) self.toolBarLayout.addWidget(self.infoWidget) self.infoWidget.hide() self.toolBarLayout.addWidget(qt.HorizontalSpacer(self.toolBar)) # ---print self.printPreview = SingletonPrintPreviewToolButton(parent=self, plot=self.graph) self.printPreview.setIcon(self.printIcon) self.toolBarLayout.addWidget(self.printPreview) def _aspectButtonSignal(self): _logger.debug("_aspectButtonSignal") if self._keepDataAspectRatioFlag: self.keepDataAspectRatio(False) else: self.keepDataAspectRatio(True) def keepDataAspectRatio(self, flag=True): if flag: self._keepDataAspectRatioFlag = True self.aspectButton.setIcon(self.solidEllipseIcon) self.aspectButton.setToolTip("Set free data aspect ratio") else: self._keepDataAspectRatioFlag = False self.aspectButton.setIcon(self.solidCircleIcon) self.aspectButton.setToolTip("Keep data aspect ratio") self.graph.setKeepDataAspectRatio(self._keepDataAspectRatioFlag) def showInfo(self): self.infoWidget.show() def hideInfo(self): self.infoWidget.hide() def setInfoText(self, text): self.infoWidget.label.setText(text) def setMouseText(self, text=""): try: if len(text): qt.QToolTip.showText(self.cursor().pos(), text, self, qt.QRect()) else: qt.QToolTip.hideText() except: _logger.warning("Error trying to show mouse text <%s>" % text) def focusOutEvent(self, ev): qt.QToolTip.hideText() def infoText(self): return self.infoWidget.label.text() def setXLabel(self, label="Column"): return self.graph.setGraphXLabel(label) def setYLabel(self, label="Row"): return self.graph.setGraphYLabel(label) def getXLabel(self): return self.graph.getGraphXLabel() def getYLabel(self): return self.graph.getGraphYLabel() def hideImageIcons(self): if self.imageToolButton is None:return self.imageToolButton.hide() self.eraseSelectionToolButton.hide() self.rectSelectionToolButton.hide() self.brushSelectionToolButton.hide() self.brushToolButton.hide() if hasattr(self, "polygonSelectionToolButton"): self.polygonSelectionToolButton.hide() self.additionalSelectionToolButton.hide() def showImageIcons(self): if self.imageToolButton is None:return self.imageToolButton.show() self.eraseSelectionToolButton.show() self.rectSelectionToolButton.show() self.brushSelectionToolButton.show() self.brushToolButton.show() if hasattr(self, "polygonSelectionToolButton"): self.polygonSelectionToolButton.show() self.additionalSelectionToolButton.show() def _hLineProfileClicked(self): for button in self._pickerSelectionButtons: if button != self.hLineProfileButton: button.setChecked(False) if self.hLineProfileButton.isChecked(): self._setPickerSelectionMode("HORIZONTAL") else: self._setPickerSelectionMode(None) def _vLineProfileClicked(self): for button in self._pickerSelectionButtons: if button != self.vLineProfileButton: button.setChecked(False) if self.vLineProfileButton.isChecked(): self._setPickerSelectionMode("VERTICAL") else: self._setPickerSelectionMode(None) def _lineProfileClicked(self): for button in self._pickerSelectionButtons: if button != self.lineProfileButton: button.setChecked(False) if self.lineProfileButton.isChecked(): self._setPickerSelectionMode("LINE") else: self._setPickerSelectionMode(None) def setPickerSelectionWith(self, intValue): self._pickerSelectionWidthValue.setValue(intValue) #get the current mode mode = "NONE" for button in self._pickerSelectionButtons: if button.isChecked(): if button == self.hLineProfileButton: mode = "HORIZONTAL" elif button == self.vLineProfileButton: mode = "VERTICAL" elif button == self.lineProfileButton: mode = "LINE" ddict = {} ddict['event'] = "profileWidthChanged" ddict['pixelwidth'] = self._pickerSelectionWidthValue.value() ddict['mode'] = mode self.sigProfileSignal.emit(ddict) def hideProfileSelectionIcons(self): if not len(self._pickerSelectionButtons): return for button in self._pickerSelectionButtons: button.setChecked(False) button.hide() self._pickerSelectionWidthLabel.hide() self._pickerSelectionWidthValue.hide() if self.graph.getInteractiveMode()['mode'] == 'draw': self.graph.setInteractiveMode('select') def showProfileSelectionIcons(self): if not len(self._pickerSelectionButtons): return for button in self._pickerSelectionButtons: button.show() self._pickerSelectionWidthLabel.show() self._pickerSelectionWidthValue.show() def getPickerSelectionMode(self): if not len(self._pickerSelectionButtons): return None if self.hLineProfileButton.isChecked(): return "HORIZONTAL" if self.vLineProfileButton.isChecked(): return "VERTICAL" if self.lineProfileButton.isChecked(): return "LINE" return None def _setPickerSelectionMode(self, mode=None): if mode is None: self.graph.setInteractiveMode('zoom') else: if mode == "HORIZONTAL": shape = "hline" elif mode == "VERTICAL": shape = "vline" else: shape = "line" self.graph.setInteractiveMode('draw', shape=shape, label=mode) ddict = {} if mode is None: mode = "NONE" ddict['event'] = "profileModeChanged" ddict['mode'] = mode self.sigProfileSignal.emit(ddict) def _graphPolygonSignalReceived(self, ddict): _logger.debug("PolygonSignal Received") for key in ddict.keys(): _logger.debug("%s: %s", key, ddict[key]) if ddict['event'] not in ['drawingProgress', 'drawingFinished']: return label = ddict['parameters']['label'] if label not in ['HORIZONTAL', 'VERTICAL', 'LINE']: return ddict['mode'] = label ddict['pixelwidth'] = self._pickerSelectionWidthValue.value() self.sigProfileSignal.emit(ddict) def _addToolButton(self, icon, action, tip, toggle=None, state=None, position=None): tb = qt.QToolButton(self.toolBar) if icon is not None: tb.setIcon(icon) tb.setToolTip(tip) if toggle is not None: if toggle: tb.setCheckable(1) if state is not None: if state: tb.setChecked(state) else: tb.setChecked(False) if position is not None: self.toolBarLayout.insertWidget(position, tb) else: self.toolBarLayout.addWidget(tb) if action is not None: tb.clicked.connect(action) return tb def __zoomReset(self): self._zoomReset() def _zoomReset(self, replot=None): _logger.debug("_zoomReset") if self.graph is not None: self.graph.resetZoom() def _yAutoScaleToggle(self): if self.graph is not None: self.yAutoScaleToolButton.setDown( not self.graph.isYAxisAutoScale()) self.graph.setYAxisAutoScale( not self.graph.isYAxisAutoScale()) def _xAutoScaleToggle(self): if self.graph is not None: self.xAutoScaleToolButton.setDown( not self.graph.isXAxisAutoScale()) self.graph.setXAxisAutoScale( not self.graph.isXAxisAutoScale()) def _copyIconSignal(self): pngFile = BytesIO() self.graph.saveGraph(pngFile, fileFormat='png') pngFile.flush() pngFile.seek(0) pngData = pngFile.read() pngFile.close() image = qt.QImage.fromData(pngData, 'png') qt.QApplication.clipboard().setImage(image) def _saveIconSignal(self): self.saveDirectory = PyMcaDirs.outputDir fileTypeList = ["Image *.png", "Image *.jpg", "ZoomedImage *.png", "ZoomedImage *.jpg", "Widget *.png", "Widget *.jpg"] outfile = qt.QFileDialog(self) outfile.setModal(1) outfile.setWindowTitle("Output File Selection") if hasattr(qt, "QStringList"): strlist = qt.QStringList() else: strlist = [] for f in fileTypeList: strlist.append(f) if hasattr(outfile, "setFilters"): outfile.setFilters(strlist) else: outfile.setNameFilters(strlist) outfile.setFileMode(outfile.AnyFile) outfile.setAcceptMode(qt.QFileDialog.AcceptSave) outfile.setDirectory(self.saveDirectory) ret = outfile.exec() if not ret: return if hasattr(outfile, "selectedFilter"): filterused = qt.safe_str(outfile.selectedFilter()).split() else: filterused = qt.safe_str(outfile.selectedNameFilter()).split() filetype = filterused[0] extension = filterused[1] outstr = qt.safe_str(outfile.selectedFiles()[0]) try: outputFile = os.path.basename(outstr) except: outputFile = outstr outputDir = os.path.dirname(outstr) self.saveDirectory = outputDir PyMcaDirs.outputDir = outputDir #always overwrite for the time being if len(outputFile) < len(extension[1:]): outputFile += extension[1:] elif outputFile[-4:] != extension[1:]: outputFile += extension[1:] outputFile = os.path.join(outputDir, outputFile) if os.path.exists(outputFile): try: os.remove(outputFile) except: qt.QMessageBox.critical(self, "Save Error", "Cannot overwrite existing file") return if filetype.upper() == "IMAGE": self.saveGraphImage(outputFile, original=True) elif filetype.upper() == "ZOOMEDIMAGE": self.saveGraphImage(outputFile, original=False) else: self.saveGraphWidget(outputFile) def saveGraphImage(self, filename, original=False): format_ = filename[-3:].upper() activeImage = self.graph.getActiveImage() rgbdata = activeImage.getRgbaImageData() # silx to pymca scale convention (a + b x) xScale = activeImage.getOrigin()[0], activeImage.getScale()[0] yScale = activeImage.getOrigin()[1], activeImage.getScale()[1] if original: # save whole image bgradata = numpy.array(rgbdata, copy=True) bgradata[:, :, 0] = rgbdata[:, :, 2] bgradata[:, :, 2] = rgbdata[:, :, 0] else: shape = rgbdata.shape[:2] xmin, xmax = self.graph.getGraphXLimits() ymin, ymax = self.graph.getGraphYLimits() # save zoomed image, for that we have to get the limits r0, c0 = convertToRowAndColumn(xmin, ymin, shape, xScale=xScale, yScale=yScale, safe=True) r1, c1 = convertToRowAndColumn(xmax, ymax, shape, xScale=xScale, yScale=yScale, safe=True) row0 = int(min(r0, r1)) row1 = int(max(r0, r1)) col0 = int(min(c0, c1)) col1 = int(max(c0, c1)) if row1 < shape[0]: row1 += 1 if col1 < shape[1]: col1 += 1 tmpArray = rgbdata[row0:row1, col0:col1, :] bgradata = numpy.array(tmpArray, copy=True, dtype=rgbdata.dtype) bgradata[:, :, 0] = tmpArray[:, :, 2] bgradata[:, :, 2] = tmpArray[:, :, 0] if self.graph.isYAxisInverted(): qImage = qt.QImage(bgradata, bgradata.shape[1], bgradata.shape[0], qt.QImage.Format_ARGB32) else: qImage = qt.QImage(bgradata, bgradata.shape[1], bgradata.shape[0], qt.QImage.Format_ARGB32).mirrored(False, True) pixmap = qt.QPixmap.fromImage(qImage) if pixmap.save(filename, format_): return else: qt.QMessageBox.critical(self, "Save Error", "%s" % sys.exc_info()[1]) return def saveGraphWidget(self, filename): format_ = filename[-3:].upper() if hasattr(qt.QPixmap, "grabWidget"): # Qt4 pixmap = qt.QPixmap.grabWidget(self.graph.getWidgetHandle()) else: # Qt5 pixmap = self.graph.getWidgetHandle().grab() if pixmap.save(filename, format_): return else: qt.QMessageBox.critical(self, "Save Error", "%s" % sys.exc_info()[1]) return def setSaveDirectory(self, wdir): if os.path.exists(wdir): self.saveDirectory = wdir return True else: return False def selectColormap(self): qt.QMessageBox.information(self, "Open", "Not implemented (yet)") def _zoomBack(self, pos): self.graph.getLimitsHistory().pop()
def _build(self): layout = qt.QVBoxLayout(self) layout.setContentsMargins(11, 11, 11, 11) gridwidget = qt.QWidget(self) grid = QGridLayout(gridwidget) grid.setContentsMargins(0, 0, 0, 0) grid.setSpacing(6) self.transmissionCheckBox = qt.QCheckBox(gridwidget) self.transmissionCheckBox.setText("Transmission Tube") voltage = qt.QLabel(gridwidget) voltage.setText("Voltage") self.voltage = qt.QLineEdit(gridwidget) grid.addMultiCellWidget(self.transmissionCheckBox, 0, 0, 0, 1) grid.addWidget(voltage, 0, 2) grid.addWidget(self.voltage, 0, 3) #materials mlabel = qt.QLabel(gridwidget) mlabel.setText("Material") dlabel = qt.QLabel(gridwidget) dlabel.setText("Density (g/cm3)") tlabel = qt.QLabel(gridwidget) tlabel.setText("Thickness (cm)") #anode anodelabel = qt.QLabel(gridwidget) anodelabel.setText("Anode") self.anodeCombo = MyQComboBox(gridwidget, options=Elements.ElementList) self.anodeDensity = qt.QLineEdit(gridwidget) self.anodeThickness = qt.QLineEdit(gridwidget) #window windowlabel = qt.QLabel(gridwidget) windowlabel.setText("Window") self.windowCombo = MyQComboBox(gridwidget, options=Elements.ElementList) self.windowDensity = qt.QLineEdit(gridwidget) self.windowThickness = qt.QLineEdit(gridwidget) grid.addWidget(mlabel, 1, 1) grid.addWidget(dlabel, 1, 2) grid.addWidget(tlabel, 1, 3) grid.addWidget(anodelabel, 2, 0) grid.addWidget(self.anodeCombo, 2, 1) grid.addWidget(self.anodeDensity, 2, 2) grid.addWidget(self.anodeThickness, 2, 3) grid.addWidget(windowlabel, 3, 0) grid.addWidget(self.windowCombo, 3, 1) grid.addWidget(self.windowDensity, 3, 2) grid.addWidget(self.windowThickness, 3, 3) #filter1 filter1label = qt.QLabel(gridwidget) filter1label.setText("Filter") self.filter1Combo = MyQComboBox(gridwidget, options=Elements.ElementList) self.filter1Density = qt.QLineEdit(gridwidget) self.filter1Thickness = qt.QLineEdit(gridwidget) grid.addWidget(filter1label, 4, 0) grid.addWidget(self.filter1Combo, 4, 1) grid.addWidget(self.filter1Density, 4, 2) grid.addWidget(self.filter1Thickness, 4, 3) #angles alphaelabel = qt.QLabel(gridwidget) alphaelabel.setText("Alpha electron") self.alphaE = qt.QLineEdit(gridwidget) alphaxlabel = qt.QLabel(gridwidget) alphaxlabel.setText("Alpha x-ray") self.alphaX = qt.QLineEdit(gridwidget) grid.addWidget(alphaelabel, 5, 2) grid.addWidget(self.alphaE, 5, 3) grid.addWidget(alphaxlabel, 6, 2) grid.addWidget(self.alphaX, 6, 3) #delta energy deltalabel = qt.QLabel(gridwidget) deltalabel.setText("Delta energy (keV) just for plotting") self.delta = qt.QLineEdit(gridwidget) grid.addMultiCellWidget(deltalabel, 7, 7, 0, 3) grid.addWidget(self.delta, 7, 3) layout.addWidget(gridwidget)
def __createInfoWidget(self, symbol=""): #Dock window like widget frame = qt.QWidget(self.splitter) layout = qt.QVBoxLayout(frame) layout.setContentsMargins(0, 0, 0, 0) layout.setSpacing(0) #The dock functionnality toolbar = qt.QWidget(frame) layout.addWidget(toolbar) layout1 = qt.QHBoxLayout(toolbar) layout1.setContentsMargins(0, 0, 0, 0) layout1.setSpacing(0) # --- the line self.line1 = Line(toolbar) self.line1.setFrameShape(qt.QFrame.HLine) self.line1.setFrameShadow(qt.QFrame.Sunken) self.line1.setFrameShape(qt.QFrame.HLine) layout1.addWidget(self.line1) # --- the close button self.closelabel = PixmapLabel(toolbar) self.closelabel.setPixmap(qt.QPixmap(CLOSE_ICON)) layout1.addWidget(self.closelabel) self.closelabel.setSizePolicy( qt.QSizePolicy(qt.QSizePolicy.Fixed, qt.QSizePolicy.Fixed)) # --- connections self.line1.sigLineDoubleClickEvent.connect(self.infoReparent) self.closelabel.sigPixmapLabelMousePressEvent.connect(self.infoToggle) # --- The text edit widget w = qt.QWidget(frame) layout.addWidget(w) l = qt.QVBoxLayout(w) l.setContentsMargins(0, 0, 0, 0) l.setSpacing(0) hbox = qt.QWidget(w) hbox.layout = qt.QHBoxLayout(hbox) hbox.layout.setContentsMargins(0, 0, 0, 0) hbox.layout.setSpacing(0) l.addWidget(hbox) hbox.layout.addWidget(qt.HorizontalSpacer(hbox)) l1 = qt.QLabel(hbox) l1.setText('<b><nobr>Excitation Energy (keV)</nobr></b>') self.energy = MyQLineEdit(hbox) self.energy.setFixedWidth(self.energy.fontMetrics().width('#####.###')) self.energy.setText("") hbox.layout.addWidget(l1) hbox.layout.addWidget(self.energy) hbox.layout.addWidget(qt.HorizontalSpacer(hbox)) self.energy.editingFinished[()].connect(self._energySlot) #if both signals are emitted and there is an error then we are in an #endless loop #self.connect(self.energy, qt.SIGNAL('focusOut'), self._energySlot) self.infoText = qt.QTextEdit(w) self.infoText.setReadOnly(1) self.infoText.clear() self.infoText.insertHtml(self.html.gethtml(symbol)) l.addWidget(self.infoText) w.show() self.infoWidget = frame frame.show()
"Please provide a valid output file name") return return qt.QDialog.accept(self) def reject(self): self.setDummyStack() return qt.QDialog.reject(self) def closeEvent(self, ev): self.setDummyStack() return qt.QDialog.closeEvent(self, ev) if __name__ == "__main__": #create a dummy stack nrows = 100 ncols = 200 nchannels = 1024 a = numpy.ones((nrows, ncols), numpy.float64) stackData = numpy.zeros((nrows, ncols, nchannels), numpy.float64) for i in range(nchannels): stackData[:, :, i] = a * i app = qt.QApplication([]) app.lastWindowClosed.connect(app.quit) w = SIFTAlignmentDialog() w.setStack(stackData, index=0) ret = w.exec() if ret: print(w.getParameters())
def _build(self): #self.layout= qt.QVBoxLayout(self) self.splitter = qt.QSplitter(self) self.splitter.setOrientation(qt.Qt.Vertical) self.list = qt.QTreeWidget(self.splitter) self.list.setSelectionMode(qt.QAbstractItemView.ExtendedSelection) self.mainTab = qt.QTabWidget(self.splitter) self.cntTable = SpecFileCntTable.SpecFileCntTable() self.mcaTable = SpecFileMcaTable.SpecFileMcaTable() self.mainTab.addTab(self.cntTable, str("Counters")) self.mainTab.addTab(self.mcaTable, str("MCA")) self.mainTab.setCurrentWidget(self.mcaTable) autoBox = qt.QWidget(self) autoBoxLayout = qt.QGridLayout(autoBox) autoBoxLayout.setContentsMargins(0, 0, 0, 0) autoBoxLayout.setSpacing(0) self.autoOffBox = qt.QCheckBox(autoBox) self.autoOffBox.setText("Auto OFF") self.autoAddBox = qt.QCheckBox(autoBox) self.autoAddBox.setText("Auto ADD") self.autoReplaceBox = qt.QCheckBox(autoBox) self.autoReplaceBox.setText("Auto REPLACE") row = 0 autoBoxLayout.addWidget(self.autoOffBox, row, 0) autoBoxLayout.addWidget(self.autoAddBox, row, 1) autoBoxLayout.addWidget(self.autoReplaceBox, row, 2) if self.autoReplace: self.autoAddBox.setChecked(False) self.autoReplaceBox.setChecked(True) else: self.autoAddBox.setChecked(True) self.autoReplaceBox.setChecked(False) row += 1 if OBJECT3D: self.object3DBox = qt.QCheckBox(autoBox) self.object3DBox.setText("3D On") autoBoxLayout.addWidget(self.object3DBox, row, 0) self.mcaTable.sigMcaDeviceSelected.connect(self.mcaDeviceSelected) self.meshBox = qt.QCheckBox(autoBox) self.meshBox.setText("Mesh") self.meshBox.setToolTip("Consider selection as a regular mesh") autoBoxLayout.addWidget(self.meshBox, row, 1) self.forceMcaBox = qt.QCheckBox(autoBox) self.forceMcaBox.setText("Force MCA") autoBoxLayout.addWidget(self.forceMcaBox, row, 2) self.mainLayout.addWidget(self.splitter) self.mainLayout.addWidget(autoBox) # --- list headers labels = ["X", "S#", "Command", "Points", "Nb. Mca"] ncols = len(labels) self.list.setColumnCount(ncols) self.list.setHeaderLabels(labels) #size=50 #self.list.header().resizeSection(0, size) #self.list.header().resizeSection(1, size) #self.list.header().resizeSection(2, 4 * size) #self.list.header().resizeSection(3, size) #self.list.header().resizeSection(4, size) self.list.header().setStretchLastSection(False) if QTVERSION > '5.0.0': self.list.header().setSectionResizeMode( 0, qt.QHeaderView.ResizeToContents) self.list.header().setSectionResizeMode( 1, qt.QHeaderView.ResizeToContents) self.list.header().setSectionResizeMode(2, qt.QHeaderView.Interactive) self.list.header().setSectionResizeMode( 3, qt.QHeaderView.ResizeToContents) self.list.header().setSectionResizeMode( 4, qt.QHeaderView.ResizeToContents) elif QTVERSION < '4.2.0': self.list.header().setResizeMode(0, qt.QHeaderView.Stretch) self.list.header().setResizeMode(1, qt.QHeaderView.Stretch) self.list.header().setResizeMode(2, qt.QHeaderView.Interactive) self.list.header().setResizeMode(3, qt.QHeaderView.Stretch) self.list.header().setResizeMode(4, qt.QHeaderView.Stretch) else: self.list.header().setResizeMode(0, qt.QHeaderView.ResizeToContents) self.list.header().setResizeMode(1, qt.QHeaderView.ResizeToContents) self.list.header().setResizeMode(2, qt.QHeaderView.Interactive) self.list.header().setResizeMode(3, qt.QHeaderView.ResizeToContents) self.list.header().setResizeMode(4, qt.QHeaderView.ResizeToContents) # --- signal handling self.list.itemSelectionChanged.connect(self.__selectionChanged) self.list.setContextMenuPolicy(qt.Qt.CustomContextMenu) self.list.customContextMenuRequested.connect(self.__contextMenu) self.list.itemDoubleClicked[qt.QTreeWidgetItem, int].connect( \ self.__doubleClicked) self.cntTable.sigSpecFileCntTableSignal.connect(self._cntSignal) if QTVERSION > '4.2.0': self.list.setSortingEnabled(False) self.list.header().sectionDoubleClicked[int].connect( \ self.__headerSectionDoubleClicked) if OBJECT3D: self.object3DBox.clicked.connect(self._setObject3DBox) if hasattr(self, 'meshBox'): self.meshBox.clicked.connect(self._setMeshBox) self.autoOffBox.clicked.connect(self._setAutoOff) self.autoAddBox.clicked.connect(self._setAutoAdd) self.autoReplaceBox.clicked.connect(self._setAutoReplace) self.forceMcaBox.clicked.connect(self._setForcedMca) self.mainTab.currentChanged[int].connect(self._tabChanged) self.disableMca = 0 #(type=="scan") self.disableScan = 0 #(type=="mca") # --- context menu self.data = None self.scans = []
class QSpecFileWidget(QSelectorWidget.QSelectorWidget): sigAddSelection = qt.pyqtSignal(object) sigRemoveSelection = qt.pyqtSignal(object) sigReplaceSelection = qt.pyqtSignal(object) sigOtherSignals = qt.pyqtSignal(object) sigScanSelection = qt.pyqtSignal(object) sigScanDoubleClicked = qt.pyqtSignal(object) def __init__(self, parent=None, autoreplace=False): self.autoReplace = autoreplace if self.autoReplace: self.autoAdd = False else: self.autoAdd = True self._oldCntSelection = None QSelectorWidget.QSelectorWidget.__init__(self, parent) self.dataInfoWidgetDict = {} def _build(self): #self.layout= qt.QVBoxLayout(self) self.splitter = qt.QSplitter(self) self.splitter.setOrientation(qt.Qt.Vertical) self.list = qt.QTreeWidget(self.splitter) self.list.setSelectionMode(qt.QAbstractItemView.ExtendedSelection) self.mainTab = qt.QTabWidget(self.splitter) self.cntTable = SpecFileCntTable.SpecFileCntTable() self.mcaTable = SpecFileMcaTable.SpecFileMcaTable() self.mainTab.addTab(self.cntTable, str("Counters")) self.mainTab.addTab(self.mcaTable, str("MCA")) self.mainTab.setCurrentWidget(self.mcaTable) autoBox = qt.QWidget(self) autoBoxLayout = qt.QGridLayout(autoBox) autoBoxLayout.setContentsMargins(0, 0, 0, 0) autoBoxLayout.setSpacing(0) self.autoOffBox = qt.QCheckBox(autoBox) self.autoOffBox.setText("Auto OFF") self.autoAddBox = qt.QCheckBox(autoBox) self.autoAddBox.setText("Auto ADD") self.autoReplaceBox = qt.QCheckBox(autoBox) self.autoReplaceBox.setText("Auto REPLACE") row = 0 autoBoxLayout.addWidget(self.autoOffBox, row, 0) autoBoxLayout.addWidget(self.autoAddBox, row, 1) autoBoxLayout.addWidget(self.autoReplaceBox, row, 2) if self.autoReplace: self.autoAddBox.setChecked(False) self.autoReplaceBox.setChecked(True) else: self.autoAddBox.setChecked(True) self.autoReplaceBox.setChecked(False) row += 1 if OBJECT3D: self.object3DBox = qt.QCheckBox(autoBox) self.object3DBox.setText("3D On") autoBoxLayout.addWidget(self.object3DBox, row, 0) self.mcaTable.sigMcaDeviceSelected.connect(self.mcaDeviceSelected) self.meshBox = qt.QCheckBox(autoBox) self.meshBox.setText("Mesh") self.meshBox.setToolTip("Consider selection as a regular mesh") autoBoxLayout.addWidget(self.meshBox, row, 1) self.forceMcaBox = qt.QCheckBox(autoBox) self.forceMcaBox.setText("Force MCA") autoBoxLayout.addWidget(self.forceMcaBox, row, 2) self.mainLayout.addWidget(self.splitter) self.mainLayout.addWidget(autoBox) # --- list headers labels = ["X", "S#", "Command", "Points", "Nb. Mca"] ncols = len(labels) self.list.setColumnCount(ncols) self.list.setHeaderLabels(labels) #size=50 #self.list.header().resizeSection(0, size) #self.list.header().resizeSection(1, size) #self.list.header().resizeSection(2, 4 * size) #self.list.header().resizeSection(3, size) #self.list.header().resizeSection(4, size) self.list.header().setStretchLastSection(False) if QTVERSION > '5.0.0': self.list.header().setSectionResizeMode( 0, qt.QHeaderView.ResizeToContents) self.list.header().setSectionResizeMode( 1, qt.QHeaderView.ResizeToContents) self.list.header().setSectionResizeMode(2, qt.QHeaderView.Interactive) self.list.header().setSectionResizeMode( 3, qt.QHeaderView.ResizeToContents) self.list.header().setSectionResizeMode( 4, qt.QHeaderView.ResizeToContents) elif QTVERSION < '4.2.0': self.list.header().setResizeMode(0, qt.QHeaderView.Stretch) self.list.header().setResizeMode(1, qt.QHeaderView.Stretch) self.list.header().setResizeMode(2, qt.QHeaderView.Interactive) self.list.header().setResizeMode(3, qt.QHeaderView.Stretch) self.list.header().setResizeMode(4, qt.QHeaderView.Stretch) else: self.list.header().setResizeMode(0, qt.QHeaderView.ResizeToContents) self.list.header().setResizeMode(1, qt.QHeaderView.ResizeToContents) self.list.header().setResizeMode(2, qt.QHeaderView.Interactive) self.list.header().setResizeMode(3, qt.QHeaderView.ResizeToContents) self.list.header().setResizeMode(4, qt.QHeaderView.ResizeToContents) # --- signal handling self.list.itemSelectionChanged.connect(self.__selectionChanged) self.list.setContextMenuPolicy(qt.Qt.CustomContextMenu) self.list.customContextMenuRequested.connect(self.__contextMenu) self.list.itemDoubleClicked[qt.QTreeWidgetItem, int].connect( \ self.__doubleClicked) self.cntTable.sigSpecFileCntTableSignal.connect(self._cntSignal) if QTVERSION > '4.2.0': self.list.setSortingEnabled(False) self.list.header().sectionDoubleClicked[int].connect( \ self.__headerSectionDoubleClicked) if OBJECT3D: self.object3DBox.clicked.connect(self._setObject3DBox) if hasattr(self, 'meshBox'): self.meshBox.clicked.connect(self._setMeshBox) self.autoOffBox.clicked.connect(self._setAutoOff) self.autoAddBox.clicked.connect(self._setAutoAdd) self.autoReplaceBox.clicked.connect(self._setAutoReplace) self.forceMcaBox.clicked.connect(self._setForcedMca) self.mainTab.currentChanged[int].connect(self._tabChanged) self.disableMca = 0 #(type=="scan") self.disableScan = 0 #(type=="mca") # --- context menu self.data = None self.scans = [] def _setObject3DBox(self): self.autoAddBox.setChecked(False) self.meshBox.setChecked(False) self.autoReplaceBox.setChecked(False) self.autoOffBox.setChecked(False) self.cntTable.set3DEnabled(True) self.object3DBox.setChecked(True) def _setMeshBox(self): self.autoAddBox.setChecked(False) self.autoReplaceBox.setChecked(False) self.autoOffBox.setChecked(False) self.cntTable.set2DEnabled(True) if hasattr(self, "object3DBox"): self.object3DBox.setChecked(False) self.meshBox.setChecked(True) def _setAutoOff(self): if OBJECT3D: self.cntTable.set3DEnabled(False) self.object3DBox.setChecked(False) if hasattr(self, "meshBox"): self.cntTable.set2DEnabled(False) self.meshBox.setChecked(False) self.autoAddBox.setChecked(False) self.autoReplaceBox.setChecked(False) self.autoOffBox.setChecked(True) def _setAutoAdd(self): if OBJECT3D: self.cntTable.set3DEnabled(False) self.object3DBox.setChecked(False) if hasattr(self, "meshBox"): self.meshBox.setChecked(False) self.cntTable.set2DEnabled(False) self.autoOffBox.setChecked(False) self.autoReplaceBox.setChecked(False) self.autoAddBox.setChecked(True) def _setAutoReplace(self): if OBJECT3D: self.cntTable.set3DEnabled(False) self.object3DBox.setChecked(False) if hasattr(self, "meshBox"): self.cntTable.set2DEnabled(False) self.meshBox.setChecked(False) self.autoOffBox.setChecked(False) self.autoAddBox.setChecked(False) self.autoReplaceBox.setChecked(True) def _setForcedMca(self): if self.forceMcaBox.isChecked(): if OBJECT3D: self.object3DBox.setChecked(False) self.object3DBox.setEnabled(False) if hasattr(self, "meshBox"): self.meshBox.setChecked(False) self.meshBox.setEnabled(False) else: if OBJECT3D: self.object3DBox.setEnabled(True) if hasattr(self, "meshBox"): self.meshBox.setEnabled(True) # # Data management # #NEW data management def setDataSource(self, datasource): if DEBUG: print("setDataSource(self, datasource) called") print("datasource = ", datasource) self.data = datasource self.refresh() if not self.autoAddBox.isChecked(): return #If there is only one mca containing scan # and we are in auto add mode, I plot it. if len(self.scans) == 1: item = self.list.itemAt(qt.QPoint(0, 0)) if item is not None: item.setSelected(True) self.__selectionChanged() #OLD data management def setData(self, specfiledata): if DEBUG: print("setData(self, specfiledata) called") print("specfiledata = ", specfiledata) self.data = specfiledata self.refresh() def refresh(self): self.list.clear() if self.data is None: return try: if self.data.sourceName is None: return except: if self.data.SourceName is None: return try: #new info = self.data.getSourceInfo() except: #old if not hasattr(self.data, "GetSourceInfo"): raise info = self.data.GetSourceInfo() self.scans = [] after = None i = 0 for (sn, cmd, pts, mca) in zip(info["KeyList"], info["Commands"], info["NumPts"], info["NumMca"]): if after is not None: #print "after is not none" #item= qt.QTreeWidgetItem(self.list, [after, "", sn, cmd, str(pts), str(mca)]) item = MyQTreeWidgetItem( self.list, ["", sn, cmd, str(pts), str(mca)]) else: item = MyQTreeWidgetItem( self.list, ["", sn, cmd, str(pts), str(mca)]) if (self.disableMca and not mca) or (self.disableScan and not pts): item.setSelectable(0) #XXX: not possible to put in italic: other solutions ?? self.scans.append(sn) after = item i = i + 1 def clear(self): self.list.clear() self.data = None self.scans = [] def markScanSelected(self, scanlist): for sn in self.scans: item = self.list.findItem(sn, 1) if item is not None: if sn in scanlist: item.setText(0, "X") else: item.setText(0, "") def _autoReplace(self, scanlist=None): if DEBUG: print("autoreplace called with ", scanlist) if self.autoReplaceBox.isChecked(): self._replaceClicked() elif self.autoAddBox.isChecked(): self._addClicked() # # signal/slot handling # def _cntSignal(self, ddict): if ddict["event"] == "updated": itemlist = self.list.selectedItems() sel = [str(item.text(1)) for item in itemlist] self._autoReplace(sel) def __selectionChanged(self): if DEBUG: print("__selectionChanged") itemlist = self.list.selectedItems() sel = [str(item.text(1)) for item in itemlist] if DEBUG: print("selection = ", sel) if not len(sel): return info = self.data.getKeyInfo(sel[0]) self.mcaTable.build(info) if False: # This does not work properly yet # TODO: mca as function of other parameter NbMca = info.get('NbMcaDet', 0) self.cntTable.build(info['LabelNames'], nmca=NbMca) else: self.cntTable.build(info['LabelNames'], nmca=0) autoReplaceCall = True if (info['Lines'] > 0) and len(info['LabelNames']): if self._oldCntSelection is not None: if len(self._oldCntSelection['y']): self.cntTable.setCounterSelection(self._oldCntSelection) else: if len(self.cntTable.cntList): self.cntTable.setCounterSelection({ 'x': [0], 'y': [-1], 'cntlist': info['LabelNames'] * 1 }) else: if len(self.cntTable.cntList): self.cntTable.setCounterSelection({ 'x': [0], 'y': [-1], 'cntlist': info['LabelNames'] * 1 }) # That already emitted a signal, no need to repeat with # autoreplace autoReplaceCall = False # Emit this signal for the case someone else uses it ... self.sigScanSelection.emit((sel)) if (info['NbMca'] > 0) and (info['Lines'] > 0): pass elif (info['NbMca'] > 0) and (info['Lines'] == 0): self.mainTab.setCurrentWidget(self.mcaTable) elif (info['NbMca'] == 0) and (info['Lines'] > 0): self.mainTab.setCurrentWidget(self.cntTable) else: pass # Next call is needed to handle the direct opening of MCAs # when using a single scan, single mca file. if autoReplaceCall: self._autoReplace(sel) def __headerSectionDoubleClicked(self, index): if index == 0: return else: self.list.sortItems(index, qt.Qt.AscendingOrder) #print "index = ", index def __doubleClicked(self, item): if DEBUG: print("__doubleClicked") if item is not None: sn = str(item.text(1)) ddict = {} ddict['Key'] = sn ddict['Command'] = str(item.text(2)) ddict['NbPoints'] = int(str(item.text(3))) ddict['NbMca'] = int(str(item.text(4))) self.sigScanDoubleClicked.emit(ddict) #shortcut selec + remove? #for the time being just add self._addClicked() def __contextMenu(self, point): if DEBUG: print("__contextMenu", point) item = self.list.itemAt(point) if item is not None: sn = str(item.text(1)) self.menu = qt.QMenu() self.menu.addAction("Show scan header", self.__showScanInfo) self.menu_idx = self.scans.index(sn) self.menu.popup(self.cursor().pos()) def mcaDeviceSelected(self, ddict): action, actiontype = ddict['action'].split() mca = ddict['mca'] + 1 sel_list = [] itemlist = self.list.selectedItems() scan_sel = [str(item.text(1)) for item in itemlist] for scan in scan_sel: sel = {} sel['SourceName'] = self.data.sourceName sel['SourceType'] = self.data.sourceType sel['Key'] = "%s.%d" % (scan, mca) #sel['selection'] = None sel['selection'] = {} if actiontype.upper() == "STACK": sel['selection']['selectiontype'] = "STACK" sel['imageselection'] = False else: sel['selection']['selectiontype'] = "2D" sel['imageselection'] = True sel['scanselection'] = False sel['mcaselection'] = False sel['legend'] = os.path.basename( sel['SourceName'][0]) + " " + sel['Key'] sel_list.append(sel) if len(scan_sel): if action == 'ADD': self.sigAddSelection.emit(sel_list) elif action == 'REMOVE': self.sigRemoveSelection.emit(sel_list) elif action == 'REPLACE': self.sigReplaceSelection.emit(sel_list) def __showScanInfo(self, idx=None): if idx is None: if QTVERSION > '4.0.0': idx = self.menu_idx if DEBUG: print("Scan information:") try: info = self.data.getDataObject(self.scans[idx]).info except: msg = qt.QMessageBox(self) msg.setIcon(qt.QMessageBox.Critical) text = "Error: %s\n accessing scan information." % ( sys.exc_info()[1]) msg.setText(text) msg.exec_() if DEBUG: raise return dataInfoWidget = SpecFileDataInfo.SpecFileDataInfo(info) if "Header" in info: if info['Header'] is not None: dataInfoWidget.setWindowTitle(info['Header'][0]) dataInfoWidget.show() wid = id(dataInfoWidget) self.dataInfoWidgetDict[wid] = dataInfoWidget dataInfoWidget.notifyCloseEventToWidget(self) def _dataInfoClosed(self, ddict): if ddict['event'] == "SpecFileDataInfoClosed": del self.dataInfoWidgetDict[ddict['id']] def customEvent(self, event): if hasattr(event, 'dict'): ddict = event.dict self._dataInfoClosed(ddict) def _addClicked(self, emit=True): if DEBUG: print("Overwritten _addClicked method") #get selected scan keys if QTVERSION < '4.0.0': scan_sel = [ sn for sn in self.scans if self.list.findItem(sn, 1).isSelected() ] else: itemlist = self.list.selectedItems() scan_sel = [str(item.text(1)) for item in itemlist] #get selected counter keys cnt_sel = self.cntTable.getCounterSelection() if len(cnt_sel['cntlist']): if len(cnt_sel['y']): self._oldCntSelection = cnt_sel mca_sel = self.mcaTable.getCurrentlySelectedMca() sel_list = [] #build the appropriate selection for mca's for scan in scan_sel: for mca in mca_sel: sel = {} sel['SourceName'] = self.data.sourceName sel['SourceType'] = self.data.sourceType sel['Key'] = scan sel['Key'] += "." + mca sel['selection'] = None #for the future #sel['scanselection'] = False sel['legend'] = os.path.basename( sel['SourceName'][0]) + " " + sel['Key'] sel_list.append(sel) if len(cnt_sel['cntlist']): if len(cnt_sel['y']): #if there is something to plot sel = {} sel['SourceName'] = self.data.sourceName sel['SourceType'] = self.data.sourceType sel['Key'] = scan sel['selection'] = {} if self.forceMcaBox.isChecked(): sel['scanselection'] = "MCA" else: sel['scanselection'] = True sel['selection']['x'] = cnt_sel['x'] if len(sel['selection']['x']) == 2: if self.meshBox.isChecked(): sel['selection']['selectiontype'] = "2D" sel['selection']['y'] = cnt_sel['y'] sel['selection']['m'] = cnt_sel['m'] sel['selection']['cntlist'] = cnt_sel['cntlist'] sel['legend'] = os.path.basename( sel['SourceName'][0]) + " " + sel['Key'] if cnt_sel['y'][0] >= len(cnt_sel['cntlist']): if 'mcalist' in cnt_sel: sel['selection']['mcalist'] = cnt_sel['mcalist'] else: # I could rise the exception here # but I let the data source to rise it. pass sel_list.append(sel) if emit: if len(sel_list): self.sigAddSelection.emit(sel_list) else: return sel_list def currentSelectionList(self): return self._addClicked(emit=False) def _removeClicked(self): if DEBUG: print("Overwritten _removeClicked method") #get selected scan keys itemlist = self.list.selectedItems() scan_sel = [str(item.text(1)) for item in itemlist] #get selected counter keys cnt_sel = self.cntTable.getCounterSelection() mca_sel = self.mcaTable.getCurrentlySelectedMca() sel_list = [] #build the appropriate selection for mca's for scan in scan_sel: for mca in mca_sel: sel = {} sel['SourceName'] = self.data.sourceName sel['SourceType'] = self.data.sourceType sel['Key'] = scan sel['Key'] += "." + mca sel['selection'] = None #for the future #sel['scanselection'] = False sel['legend'] = os.path.basename( sel['SourceName'][0]) + " " + sel['Key'] sel_list.append(sel) if len(cnt_sel['cntlist']): if len(cnt_sel['y']): #if there is something to plot sel = {} sel['SourceName'] = self.data.sourceName sel['SourceType'] = self.data.sourceType sel['Key'] = scan sel['selection'] = {} if self.forceMcaBox.isChecked(): sel['scanselection'] = "MCA" else: sel['scanselection'] = True sel['selection']['x'] = cnt_sel['x'] if len(sel['selection']['x']) == 2: if self.meshBox.isChecked(): sel['selection']['selectiontype'] = "2D" sel['selection']['y'] = cnt_sel['y'] sel['selection']['m'] = cnt_sel['m'] sel['selection']['cntlist'] = cnt_sel['cntlist'] sel['legend'] = os.path.basename( sel['SourceName'][0]) + " " + sel['Key'] sel_list.append(sel) if len(sel_list): self.sigRemoveSelection.emit(sel_list) def _replaceClicked(self): if DEBUG: print("Overwritten _replaceClicked method") #get selected scan keys itemlist = self.list.selectedItems() scan_sel = [str(item.text(1)) for item in itemlist] #get selected counter keys cnt_sel = self.cntTable.getCounterSelection() if len(cnt_sel['cntlist']): if len(cnt_sel['y']): self._oldCntSelection = cnt_sel mca_sel = self.mcaTable.getCurrentlySelectedMca() sel_list = [] #build the appropriate selection for mca's for scan in scan_sel: for mca in mca_sel: sel = {} sel['SourceName'] = self.data.sourceName sel['SourceType'] = self.data.sourceType sel['Key'] = scan sel['Key'] += "." + mca sel['selection'] = None #for the future #sel['scanselection'] = False #This could also be MCA sel['legend'] = os.path.basename( sel['SourceName'][0]) + " " + sel['Key'] sel_list.append(sel) if len(cnt_sel['cntlist']): sel = {} sel['SourceName'] = self.data.sourceName sel['SourceType'] = self.data.sourceType sel['Key'] = scan if len(cnt_sel['y']): #if there is something to plot if self.forceMcaBox.isChecked(): sel['scanselection'] = "MCA" else: sel['scanselection'] = True #This could also be SCAN sel['selection'] = {} sel['selection']['x'] = cnt_sel['x'] if len(sel['selection']['x']) == 2: if self.meshBox.isChecked(): sel['selection']['selectiontype'] = "2D" sel['selection']['y'] = cnt_sel['y'] sel['selection']['m'] = cnt_sel['m'] sel['selection']['cntlist'] = cnt_sel['cntlist'] sel['legend'] = os.path.basename( sel['SourceName'][0]) + " " + sel['Key'] if cnt_sel['y'][0] >= len(cnt_sel['cntlist']): if 'mcalist' in cnt_sel: sel['selection']['mcalist'] = cnt_sel['mcalist'] else: # I could rise the exception here # but I let the data source to rise it. pass sel_list.append(sel) if len(sel_list): self.sigReplaceSelection.emit(sel_list) def _tabChanged(self, value): if DEBUG: print("self._tabChanged(value), value = ", value) text = str(self.mainTab.tabText(value)) if self.data is None: return ddict = {} ddict['SourceName'] = self.data.sourceName ddict['SourceType'] = self.data.sourceType ddict['event'] = "SelectionTypeChanged" ddict['SelectionType'] = text self.sigOtherSignals.emit(ddict)
def _addSelectionSlot(self, sel_list, event=None): _logger.debug("QDispatcher._addSelectionSlot") _logger.debug("sel_list = %s", sel_list) if event is None: event = "addSelection" i = 0 indices = [] index = [] affectedSources = [] for sel in sel_list: sourceName = sel['SourceName'] if not len(affectedSources): index += [i] elif sourceName == affectedSources[-1]: index += [i] else: indices.append(index) affectedSources.append(sourceName) index = [i] i += 1 indices.append(index) affectedSources.append(sourceName) affectedSourceIndex = -1 for affectedSource in affectedSources: affectedSourceIndex += 1 selectionList = [] lastEvent = None for source in self.sourceList: if source.sourceName == affectedSource: for selIndex in indices[affectedSourceIndex]: sel = sel_list[selIndex] #The dispatcher should be a singleton to work properly #implement a patch to make sure it is the targeted widget targetwidgetid = sel.get('targetwidgetid', None) if targetwidgetid not in [None, id(self)]: continue ddict = {} ddict.update(sel) ddict["event"] = event if lastEvent is None: lastEvent = event #we have found the source #this recovers the data and the info if True: #this creates a data object that is passed to everybody so #there is only one read out. #I should create a weakref to it in order to be informed #about its deletion. if source.sourceType != "SPS": try: dataObject = source.getDataObject( sel['Key'], selection=sel['selection']) except: if _logger.getEffectiveLevel( ) == logging.DEBUG: raise error = sys.exc_info() text = "Failed to read data source.\n" text += "Source: %s\n" % source.sourceName text += "Key: %s\n" % sel['Key'] text += "Error: %s" % error[1] if QTVERSION < '4.0.0': qt.QMessageBox.critical( self, "%s" % error[0], text) else: msg = qt.QMessageBox(self) msg.setWindowTitle('Source Error') msg.setIcon(qt.QMessageBox.Critical) msg.setInformativeText(text) msg.setDetailedText(\ traceback.format_exc()) continue else: dataObject = source.getDataObject( sel['Key'], selection=sel['selection'], poll=False) if dataObject is not None: dataObject.info['legend'] = sel['legend'] dataObject.info[ 'targetwidgetid'] = targetwidgetid source.addToPoller(dataObject) else: #this may happen on deletion?? return if sel['Key'] == "SCAN_D": # I have to inform the widget about any possible # change in the associated environment #print source.sourceType #print source.sourceName #print sel['Key'] #print self.selectorWidget[source.sourceType] pass ddict['dataobject'] = dataObject selectionList.append(ddict) else: #this creates a weak reference to the source object #the clients will be able to retrieve the data #the problem is that 10 clients will requiere #10 read outs ddict["sourcereference"] = weakref.ref(source) selectionList.append(ddict) if lastEvent != event: if event.lower() == "addselection": self.sigAddSelection.emit(selectionList) selectionList = [] elif event.lower() == "replaceselection": self.sigReplaceSelection.emit(selectionList) selectionList = [] elif event.lower() == "removeselection": self.sigRemoveSelection.emit(selectionList) selectionList = [] else: _logger.warning( "Unhandled dispatcher event = %s", event) del selectionList[-1] if len(selectionList): if event.lower() == "addselection": self.sigAddSelection.emit(selectionList) elif event.lower() == "replaceselection": self.sigReplaceSelection.emit(selectionList) elif event.lower() == "removeselection": self.sigRemoveSelection.emit(selectionList) lastEvent = None
def _buildToolBar(self, selection=False, colormap=False, imageicons=False, standalonesave=True, standalonezoom=True, profileselection=False, aspect=False, polygon=False): self.solidCircleIcon = qt.QIcon(qt.QPixmap(IconDict["solidcircle"])) self.solidEllipseIcon = qt.QIcon(qt.QPixmap(IconDict["solidellipse"])) self.colormapIcon = qt.QIcon(qt.QPixmap(IconDict["colormap"])) self.selectionIcon = qt.QIcon(qt.QPixmap(IconDict["normal"])) self.zoomResetIcon = qt.QIcon(qt.QPixmap(IconDict["zoomreset"])) self.polygonIcon = qt.QIcon(qt.QPixmap(IconDict["polygon"])) self.printIcon = qt.QIcon(qt.QPixmap(IconDict["fileprint"])) self.saveIcon = qt.QIcon(qt.QPixmap(IconDict["filesave"])) self.xAutoIcon = qt.QIcon(qt.QPixmap(IconDict["xauto"])) self.yAutoIcon = qt.QIcon(qt.QPixmap(IconDict["yauto"])) self.hFlipIcon = qt.QIcon(qt.QPixmap(IconDict["gioconda16mirror"])) self.imageIcon = qt.QIcon(qt.QPixmap(IconDict["image"])) self.eraseSelectionIcon = qt.QIcon(qt.QPixmap(IconDict["eraseselect"])) self.rectSelectionIcon = qt.QIcon(qt.QPixmap(IconDict["boxselect"])) self.brushSelectionIcon = qt.QIcon(qt.QPixmap(IconDict["brushselect"])) self.brushIcon = qt.QIcon(qt.QPixmap(IconDict["brush"])) self.additionalIcon = qt.QIcon(qt.QPixmap(IconDict["additionalselect"])) self.hLineIcon = qt.QIcon(qt.QPixmap(IconDict["horizontal"])) self.vLineIcon = qt.QIcon(qt.QPixmap(IconDict["vertical"])) self.lineIcon = qt.QIcon(qt.QPixmap(IconDict["diagonal"])) self.copyIcon = silx_icons.getQIcon("edit-copy") self.toolBar = qt.QWidget(self) self.toolBarLayout = qt.QHBoxLayout(self.toolBar) self.toolBarLayout.setContentsMargins(0, 0, 0, 0) self.toolBarLayout.setSpacing(0) self.mainLayout.addWidget(self.toolBar) #Autoscale if standalonezoom: tb = self._addToolButton(self.zoomResetIcon, self.__zoomReset, 'Auto-Scale the Graph') else: tb = self._addToolButton(self.zoomResetIcon, None, 'Auto-Scale the Graph') self.zoomResetToolButton = tb #y Autoscale tb = self._addToolButton(self.yAutoIcon, self._yAutoScaleToggle, 'Toggle Autoscale Y Axis (On/Off)', toggle = True, state=True) tb.setDown(True) self.yAutoScaleToolButton = tb tb.setDown(True) #x Autoscale tb = self._addToolButton(self.xAutoIcon, self._xAutoScaleToggle, 'Toggle Autoscale X Axis (On/Off)', toggle = True, state=True) self.xAutoScaleToolButton = tb tb.setDown(True) #Aspect ratio if aspect: self.aspectButton = self._addToolButton(self.solidCircleIcon, self._aspectButtonSignal, 'Keep data aspect ratio', toggle=False) self.aspectButton.setChecked(False) #colormap if colormap: tb = self._addToolButton(self.colormapIcon, None, 'Change Colormap') self.colormapToolButton = tb #flip tb = self._addToolButton(self.hFlipIcon, None, 'Flip Horizontal') self.hFlipToolButton = tb #save if standalonesave: tb = self._addToolButton(self.saveIcon, self._saveIconSignal, 'Save Graph') else: tb = self._addToolButton(self.saveIcon, None, 'Save') self.saveToolButton = tb self.copyToolButton = self._addToolButton(self.copyIcon, self._copyIconSignal, "Copy graph to clipboard") #Selection if selection: tb = self._addToolButton(self.selectionIcon, None, 'Toggle Selection Mode', toggle = True, state = False) tb.setDown(False) self.selectionToolButton = tb #image selection icons if imageicons: tb = self._addToolButton(self.imageIcon, None, 'Reset') self.imageToolButton = tb tb = self._addToolButton(self.eraseSelectionIcon, None, 'Erase Selection') self.eraseSelectionToolButton = tb tb = self._addToolButton(self.rectSelectionIcon, None, 'Rectangular Selection') self.rectSelectionToolButton = tb tb = self._addToolButton(self.brushSelectionIcon, None, 'Brush Selection') self.brushSelectionToolButton = tb tb = self._addToolButton(self.brushIcon, None, 'Select Brush') self.brushToolButton = tb if polygon: tb = self._addToolButton(self.polygonIcon, None, 'Polygon selection\nRight click to finish') self.polygonSelectionToolButton = tb tb = self._addToolButton(self.additionalIcon, None, 'Additional Selections Menu') self.additionalSelectionToolButton = tb else: if polygon: tb = self._addToolButton(self.polygonIcon, None, 'Polygon selection\nRight click to finish') self.polygonSelectionToolButton = tb self.imageToolButton = None #picker selection self._pickerSelectionButtons = [] if profileselection: self._profileSelection = True self._polygonSelection = False self._pickerSelectionButtons = [] if self._profileSelection: tb = self._addToolButton(self.hLineIcon, self._hLineProfileClicked, 'Horizontal Profile Selection', toggle=True, state=False) self.hLineProfileButton = tb self._pickerSelectionButtons.append(tb) tb = self._addToolButton(self.vLineIcon, self._vLineProfileClicked, 'Vertical Profile Selection', toggle=True, state=False) self.vLineProfileButton = tb self._pickerSelectionButtons.append(tb) tb = self._addToolButton(self.lineIcon, self._lineProfileClicked, 'Line Profile Selection', toggle=True, state=False) self.lineProfileButton = tb self._pickerSelectionButtons.append(tb) self._pickerSelectionWidthLabel = qt.QLabel(self.toolBar) self._pickerSelectionWidthLabel.setText("W:") self.toolBar.layout().addWidget(self._pickerSelectionWidthLabel) self._pickerSelectionWidthValue = qt.QSpinBox(self.toolBar) self._pickerSelectionWidthValue.setMinimum(0) self._pickerSelectionWidthValue.setMaximum(1000) self._pickerSelectionWidthValue.setValue(1) self.toolBar.layout().addWidget(self._pickerSelectionWidthValue) #tb = self._addToolButton(None, # self._lineProfileClicked, # 'Line Profile Selection', # toggle=True, # state=False) #tb.setText = "W:" #self.lineWidthProfileButton = tb #self._pickerSelectionButtons.append(tb) if self._polygonSelection: _logger.info("Polygon selection not implemented yet") #hide profile selection buttons if imageicons: for button in self._pickerSelectionButtons: button.hide() self.infoWidget = qt.QWidget(self.toolBar) self.infoWidget.mainLayout = qt.QHBoxLayout(self.infoWidget) self.infoWidget.mainLayout.setContentsMargins(0, 0, 0, 0) self.infoWidget.mainLayout.setSpacing(0) self.infoWidget.label = qt.QLabel(self.infoWidget) self.infoWidget.label.setText("X = ???? Y = ???? Z = ????") self.infoWidget.mainLayout.addWidget(self.infoWidget.label) self.toolBarLayout.addWidget(self.infoWidget) self.infoWidget.hide() self.toolBarLayout.addWidget(qt.HorizontalSpacer(self.toolBar)) # ---print self.printPreview = SingletonPrintPreviewToolButton(parent=self, plot=self.graph) self.printPreview.setIcon(self.printIcon) self.toolBarLayout.addWidget(self.printPreview)
def __init__(self, parent=None, name="ScanFit", specfit=None, fl=0): #fl=qt.Qt.WDestructiveClose): qt.QWidget.__init__(self, parent) self.setWindowTitle(name) if specfit is None: self.specfit = Specfit.Specfit() else: self.specfit = specfit self.info = None layout = qt.QVBoxLayout(self) layout.setContentsMargins(0, 0, 0, 0) layout.setSpacing(0) ############## self.headerlabel = qt.QLabel(self) self.headerlabel.setAlignment(qt.Qt.AlignHCenter) self.setHeader('<b>Fit of XXXXXXXXXX from X XXXXX to XXXX<\b>') ############## if not len(self.specfit.theorylist): funsFile = "SpecfitFunctions.py" if not os.path.exists(funsFile): funsFile = os.path.join(os.path.dirname(Specfit.__file__), funsFile) self.specfit.importfun(funsFile) if 'Area Gaussians' not in self.specfit.theorylist: funsFile = "SpecfitFunctions.py" if not os.path.exists(funsFile): funsFile = os.path.join(os.path.dirname(Specfit.__file__), funsFile) self.specfit.importfun(funsFile) self.specfit.settheory('Area Gaussians') self.specfit.setbackground('Linear') fitconfig = {} fitconfig.update(self.specfit.fitconfig) fitconfig['WeightFlag'] = 0 fitconfig['ForcePeakPresence'] = 1 fitconfig['McaMode'] = 0 self.specfit.configure(**fitconfig) self.specfitGui = SpecfitGui.SpecfitGui(self, config=1, status=1, buttons=0, specfit=self.specfit, eh=self.specfit.eh) #self.specfitGui.updateGui(configuration=fitconfig) #self.setdata = self.specfit.setdata self.specfitGui.guiconfig.MCACheckBox.setEnabled(1) palette = self.specfitGui.guiconfig.MCACheckBox.palette() ############## hbox = qt.QWidget(self) hboxlayout = qt.QHBoxLayout(hbox) hboxlayout.setContentsMargins(0, 0, 0, 0) hboxlayout.setSpacing(0) self.estimatebutton = qt.QPushButton(hbox) self.estimatebutton.setText("Estimate") self.fitbutton = qt.QPushButton(hbox) self.fitbutton.setText("Fit") hboxlayout.addWidget(self.estimatebutton) hboxlayout.addWidget(qt.HorizontalSpacer(hbox)) hboxlayout.addWidget(self.fitbutton) self.dismissbutton = qt.QPushButton(hbox) self.dismissbutton.setText("Dismiss") self.estimatebutton.clicked.connect(self.estimate) self.fitbutton.clicked.connect(self.fit) self.dismissbutton.clicked.connect(self.dismiss) self.specfitGui.sigSpecfitGuiSignal.connect(self._specfitGuiSignal) hboxlayout.addWidget(qt.HorizontalSpacer(hbox)) hboxlayout.addWidget(self.dismissbutton) layout.addWidget(self.headerlabel) layout.addWidget(self.specfitGui) layout.addWidget(hbox)
class QDispatcher(qt.QWidget): sigAddSelection = qt.pyqtSignal(object) sigRemoveSelection = qt.pyqtSignal(object) sigReplaceSelection = qt.pyqtSignal(object) sigOtherSignals = qt.pyqtSignal(object) def __init__(self, parent=None, pluginsIcon=False): qt.QWidget.__init__(self, parent) self.mainLayout = qt.QVBoxLayout(self) self.mainLayout.setContentsMargins(0, 0, 0, 0) self.mainLayout.setSpacing(0) self.sourceList = [] fileTypeList = [ "Spec Files (*mca)", "Spec Files (*dat)", "Spec Files (*spec)", "SPE Files (*SPE *spe)", "EDF Files (*edf)", "EDF Files (*ccd)", "TIFF Files (*.tif *.tiff *.TIF *.TIFF)", "CSV Files (*csv)", "JCAMP-DX Files (*.jdx *.JDX *.dx *.DX)" ] if QDataSource.NEXUS: fileTypeList.append("HDF5 Files (*.nxs *.hdf *.h5 *.hdf5)") fileTypeList.append("All Files (*)") self.sourceSelector = QSourceSelector.QSourceSelector( self, filetypelist=fileTypeList, pluginsIcon=pluginsIcon) if pluginsIcon: self.sourceSelector.pluginsButton.clicked.connect( self._pluginsClicked) self.pluginsCallback = None self.selectorWidget = {} self.tabWidget = qt.QTabWidget(self) #for the time being just files for src_widget in QDataSource.source_widgets.keys(): self.selectorWidget[src_widget] = QDataSource.source_widgets[ src_widget]() self.tabWidget.addTab(self.selectorWidget[src_widget], src_widget) self.selectorWidget[src_widget].sigAddSelection.connect( \ self._addSelectionSlot) self.selectorWidget[src_widget].sigRemoveSelection.connect( \ self._removeSelectionSlot) self.selectorWidget[src_widget].sigReplaceSelection.connect( \ self._replaceSelectionSlot) if src_widget not in ['EdfFile']: self.selectorWidget[src_widget].sigOtherSignals.connect( \ self._otherSignalsSlot) self.mainLayout.addWidget(self.sourceSelector) self.mainLayout.addWidget(self.tabWidget) self.sourceSelector.sigSourceSelectorSignal.connect( \ self._sourceSelectorSlot) self.tabWidget.currentChanged[int].connect(self._tabChanged) def _addSelectionSlot(self, sel_list, event=None): _logger.debug("QDispatcher._addSelectionSlot") _logger.debug("sel_list = %s", sel_list) if event is None: event = "addSelection" i = 0 indices = [] index = [] affectedSources = [] for sel in sel_list: sourceName = sel['SourceName'] if not len(affectedSources): index += [i] elif sourceName == affectedSources[-1]: index += [i] else: indices.append(index) affectedSources.append(sourceName) index = [i] i += 1 indices.append(index) affectedSources.append(sourceName) affectedSourceIndex = -1 for affectedSource in affectedSources: affectedSourceIndex += 1 selectionList = [] lastEvent = None for source in self.sourceList: if source.sourceName == affectedSource: for selIndex in indices[affectedSourceIndex]: sel = sel_list[selIndex] #The dispatcher should be a singleton to work properly #implement a patch to make sure it is the targeted widget targetwidgetid = sel.get('targetwidgetid', None) if targetwidgetid not in [None, id(self)]: continue ddict = {} ddict.update(sel) ddict["event"] = event if lastEvent is None: lastEvent = event #we have found the source #this recovers the data and the info if True: #this creates a data object that is passed to everybody so #there is only one read out. #I should create a weakref to it in order to be informed #about its deletion. if source.sourceType != "SPS": try: dataObject = source.getDataObject( sel['Key'], selection=sel['selection']) except: if _logger.getEffectiveLevel( ) == logging.DEBUG: raise error = sys.exc_info() text = "Failed to read data source.\n" text += "Source: %s\n" % source.sourceName text += "Key: %s\n" % sel['Key'] text += "Error: %s" % error[1] if QTVERSION < '4.0.0': qt.QMessageBox.critical( self, "%s" % error[0], text) else: msg = qt.QMessageBox(self) msg.setWindowTitle('Source Error') msg.setIcon(qt.QMessageBox.Critical) msg.setInformativeText(text) msg.setDetailedText(\ traceback.format_exc()) continue else: dataObject = source.getDataObject( sel['Key'], selection=sel['selection'], poll=False) if dataObject is not None: dataObject.info['legend'] = sel['legend'] dataObject.info[ 'targetwidgetid'] = targetwidgetid source.addToPoller(dataObject) else: #this may happen on deletion?? return if sel['Key'] == "SCAN_D": # I have to inform the widget about any possible # change in the associated environment #print source.sourceType #print source.sourceName #print sel['Key'] #print self.selectorWidget[source.sourceType] pass ddict['dataobject'] = dataObject selectionList.append(ddict) else: #this creates a weak reference to the source object #the clients will be able to retrieve the data #the problem is that 10 clients will requiere #10 read outs ddict["sourcereference"] = weakref.ref(source) selectionList.append(ddict) if lastEvent != event: if event.lower() == "addselection": self.sigAddSelection.emit(selectionList) selectionList = [] elif event.lower() == "replaceselection": self.sigReplaceSelection.emit(selectionList) selectionList = [] elif event.lower() == "removeselection": self.sigRemoveSelection.emit(selectionList) selectionList = [] else: _logger.warning( "Unhandled dispatcher event = %s", event) del selectionList[-1] if len(selectionList): if event.lower() == "addselection": self.sigAddSelection.emit(selectionList) elif event.lower() == "replaceselection": self.sigReplaceSelection.emit(selectionList) elif event.lower() == "removeselection": self.sigRemoveSelection.emit(selectionList) lastEvent = None def _removeSelectionSlot(self, sel_list): _logger.debug("_removeSelectionSlot") _logger.debug("sel_list = %s", sel_list) for sel in sel_list: ddict = {} ddict.update(sel) ddict["event"] = "removeSelection" self.sigRemoveSelection.emit(ddict) def _replaceSelectionSlot(self, sel_list): _logger.debug("_replaceSelectionSlot") _logger.debug("sel_list = %s", sel_list) if len(sel_list) == 1: self._addSelectionSlot([sel_list[0]], event="replaceSelection") elif len(sel_list) > 1: self._addSelectionSlot([sel_list[0]], event="replaceSelection") self._addSelectionSlot(sel_list[1:], event="addSelection") def _otherSignalsSlot(self, ddict): self.sigOtherSignals.emit(ddict) def _sourceSelectorSlot(self, ddict): _logger.debug("_sourceSelectorSlot(self, ddict)") _logger.debug("ddict = %s", ddict) if ddict["event"] == "NewSourceSelected": source = QDataSource.QDataSource(ddict["sourcelist"]) self.sourceList.append(source) sourceType = source.sourceType self.selectorWidget[sourceType].setDataSource(source) self.tabWidget.setCurrentWidget(self.selectorWidget[sourceType]) if sourceType == "SPS": source.sigUpdated.connect(self._selectionUpdatedSlot) elif (ddict["event"] == "SourceSelected") or \ (ddict["event"] == "SourceReloaded"): found = 0 for source in self.sourceList: if source.sourceName == ddict["sourcelist"]: found = 1 break if not found: _logger.debug("WARNING: source not found") return sourceType = source.sourceType if ddict["event"] == "SourceReloaded": source.refresh() self.selectorWidget[sourceType].setDataSource(source) self.tabWidget.setCurrentWidget(self.selectorWidget[sourceType]) elif ddict["event"] == "SourceClosed": found = 0 for source in self.sourceList: if source.sourceName == ddict["sourcelist"]: found = 1 break if not found: _logger.debug("WARNING: source not found") return sourceType = source.sourceType del self.sourceList[self.sourceList.index(source)] for source in self.sourceList: if sourceType == source.sourceType: self.selectorWidget[sourceType].setDataSource(source) self.tabWidget.setCurrentWidget( self.selectorWidget[sourceType]) return #there is no other selection of that type if len(self.sourceList): source = self.sourceList[0] sourceType = source.sourceType self.selectorWidget[sourceType].setDataSource(source) else: self.selectorWidget[sourceType].setDataSource(None) self.tabWidget.setCurrentWidget(self.selectorWidget[sourceType]) elif ddict["event"] == "SourceClosed": _logger.debug("not implemented yet") def _selectionUpdatedSlot(self, ddict): _logger.debug("_selectionUpdatedSlot(self, dict=%s)") if 'selectionlist' in ddict: sel_list = ddict['selectionlist'] else: sel_list = [] for objectReference in ddict["id"]: targetwidgetid = ddict.get('targetwidgetid', None) if targetwidgetid not in [None, id(self)]: continue sel = {} sel['SourceName'] = ddict['SourceName'] sel['SourceType'] = ddict['SourceType'] sel['Key'] = ddict['Key'] if 0: sel['selection'] = objectReference.info['selection'] sel['legend'] = objectReference.info['legend'] if 'scanselection' in objectReference.info.keys(): sel['scanselection'] = objectReference.info[ 'scanselection'] else: sel['selection'] = ddict['selection'] sel['legend'] = ddict['legend'] sel['scanselection'] = ddict['scanselection'] sel['imageselection'] = ddict['imageselection'] sel_list.append(sel) self._addSelectionSlot(sel_list) def _tabChanged(self, value): _logger.debug("self._tabChanged(value), value = %s", value) text = str(self.tabWidget.tabText(value)) ddict = {} ddict['SourceType'] = text if self.selectorWidget[text].data is not None: ddict['SourceType'] = self.selectorWidget[text].data.sourceType ddict['SourceName'] = self.selectorWidget[text].data.sourceName else: ddict['SourceName'] = None ddict['event'] = "SourceTypeChanged" self.sigOtherSignals.emit(ddict) def _pluginsClicked(self): ddict = {} value = self.tabWidget.currentIndex() text = str(self.tabWidget.tabText(value)) ddict['SourceType'] = text if self.selectorWidget[text].data is not None: ddict['SourceType'] = self.selectorWidget[text].data.sourceType ddict['SourceName'] = self.selectorWidget[text].data.sourceName else: ddict['SourceName'] = None _logger.info("%s", ddict) _logger.info("===========================") for source in self.sourceList: _logger.info(source) _logger.info(source.sourceType) sourceType = source.sourceType _logger.info( self.selectorWidget[sourceType].currentSelectionList())
def getFileList(parent=None, filetypelist=None, message=None, currentdir=None, mode=None, getfilter=None, single=False, currentfilter=None, native=None): if filetypelist is None: fileTypeList = ['All Files (*)'] else: fileTypeList = filetypelist if currentfilter not in filetypelist: currentfilter = None if currentfilter is None: currentfilter = filetypelist[0] if message is None: if single: message = "Please select one file" else: message = "Please select one or more files" if mode is None: mode = "OPEN" else: mode = mode.upper() if currentdir is None: if mode == "OPEN": wdir = PyMcaDirs.inputDir else: wdir = PyMcaDirs.outputDir else: wdir = currentdir if native is None: nativeFileDialogs = PyMcaDirs.nativeFileDialogs else: nativeFileDialogs = native if getfilter is None: getfilter = False if getfilter: if QTVERSION < '4.5.1': native_possible = False else: native_possible = True else: native_possible = True filterused = None if native_possible and nativeFileDialogs: filetypes = currentfilter for filetype in fileTypeList: if filetype != currentfilter: filetypes += ";;" + filetype if getfilter: if mode == "OPEN": if single and hasattr(qt.QFileDialog, "getOpenFileNameAndFilter"): filelist, filterused = qt.QFileDialog.getOpenFileNameAndFilter(parent, message, wdir, filetypes, currentfilter) filelist =[filelist] elif single: # PyQt5 filelist, filterused = qt.QFileDialog.getOpenFileName(parent, message, wdir, filetypes, currentfilter) filelist =[filelist] elif hasattr(qt.QFileDialog, "getOpenFileNamesAndFilter"): filelist, filterused = qt.QFileDialog.getOpenFileNamesAndFilter(parent, message, wdir, filetypes, currentfilter) else: # PyQt5 filelist, filterused = qt.QFileDialog.getOpenFileNames(parent, message, wdir, filetypes, currentfilter) filterused = qt.safe_str(filterused) else: if QTVERSION < '5.0.0': filelist = qt.QFileDialog.getSaveFileNameAndFilter(parent, message, wdir, filetypes) else: filelist = qt.QFileDialog.getSaveFileName(parent, message, wdir, filetypes) if len(filelist[0]): filterused = qt.safe_str(filelist[1]) filelist=[filelist[0]] else: filelist = [] else: if mode == "OPEN": if single: if QTVERSION < '5.0.0': filelist = [qt.QFileDialog.getOpenFileName(parent, message, wdir, filetypes)] else: filelist, filterused = qt.QFileDialog.getOpenFileName(parent, message, wdir, filetypes) filelist = [filelist] else: filelist = qt.QFileDialog.getOpenFileNames(parent, message, wdir, filetypes) else: if QTVERSION < '5.0.0': filelist = qt.QFileDialog.getSaveFileName(parent, message, wdir, filetypes) else: filelist, filterused = qt.QFileDialog.getSaveFileName(parent, message, wdir, filetypes) filelist = qt.safe_str(filelist) if len(filelist): filelist = [filelist] else: filelist = [] if not len(filelist): if getfilter: return [], filterused else: return [] elif filterused is None: sample = qt.safe_str(filelist[0]) for filetype in fileTypeList: ftype = filetype.replace("(", "") ftype = ftype.replace(")", "") extensions = ftype.split()[2:] for extension in extensions: if sample.endswith(extension[-3:]): filterused = filetype break else: fdialog = qt.QFileDialog(parent) fdialog.setModal(True) fdialog.setWindowTitle(message) if hasattr(qt, "QStringList"): strlist = qt.QStringList() else: strlist = [] strlist.append(currentfilter) for filetype in fileTypeList: if filetype != currentfilter: strlist.append(filetype) if hasattr(fdialog, "setFilters"): fdialog.setFilters(strlist) else: fdialog.setNameFilters(strlist) if mode == "OPEN": fdialog.setFileMode(fdialog.ExistingFiles) else: fdialog.setAcceptMode(fdialog.AcceptSave) fdialog.setFileMode(fdialog.AnyFile) fdialog.setDirectory(wdir) if QTVERSION > '4.3.0': history = fdialog.history() if len(history) > 6: fdialog.setHistory(history[-6:]) ret = fdialog.exec_() if ret != qt.QDialog.Accepted: fdialog.close() del fdialog if getfilter: return [], filterused else: return [] else: filelist = fdialog.selectedFiles() if single: filelist = [filelist[0]] if QTVERSION < "5.0.0": filterused = qt.safe_str(fdialog.selectedFilter()) else: filterused = qt.safe_str(fdialog.selectedNameFilter()) if mode != "OPEN": if "." in filterused: extension = filterused.replace(")", "") if "(" in extension: extension = extension.split("(")[-1] extensionList = extension.split() txt = qt.safe_str(filelist[0]) for extension in extensionList: extension = extension.split(".")[-1] if extension != "*": txt = qt.safe_str(filelist[0]) if txt.endswith(extension): break else: txt = txt+"."+extension filelist[0] = txt fdialog.close() del fdialog filelist = [qt.safe_str(x) for x in filelist] if not(len(filelist)): return [] if mode == "OPEN": PyMcaDirs.inputDir = os.path.dirname(filelist[0]) if PyMcaDirs.outputDir is None: PyMcaDirs.outputDir = os.path.dirname(filelist[0]) else: PyMcaDirs.outputDir = os.path.dirname(filelist[0]) if PyMcaDirs.inputDir is None: PyMcaDirs.inputDir = os.path.dirname(filelist[0]) #do not sort file list in order to allow the user other choices #filelist.sort() if getfilter: return filelist, filterused else: return filelist
import numpy import logging from PyMca5.PyMcaGui import PyMcaQt as qt from silx.gui.plot import PlotWidget from silx.gui.plot.PrintPreviewToolButton import SingletonPrintPreviewToolButton from .PyMca_Icons import IconDict from PyMca5.PyMcaCore import PyMcaDirs from silx.gui import icons as silx_icons if sys.version_info[0] == 3: from io import BytesIO else: import cStringIO as _StringIO BytesIO = _StringIO.StringIO QTVERSION = qt.qVersion() _logger = logging.getLogger(__name__) def convertToRowAndColumn(x, y, shape, xScale=None, yScale=None, safe=True): if xScale is None: c = x else: c = (x - xScale[0]) / xScale[1] if yScale is None: r = y else: r = ( y - yScale[0]) / yScale[1] if safe:
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # #############################################################################*/ __author__ = "V.A. Sole - ESRF Data Analysis" __contact__ = "*****@*****.**" __license__ = "MIT" __copyright__ = "European Synchrotron Radiation Facility, Grenoble, France" import os from PyMca5.PyMcaGui import PyMcaQt as qt from PyMca5 import PyMcaDirs QTVERSION = qt.qVersion() def getExistingDirectory(parent=None, message=None, mode=None): if message is None: message = "Please select a directory" if mode is None: mode = "OPEN" else: mode = mode.upper() if mode == "OPEN": wdir = PyMcaDirs.inputDir else: wdir = PyMcaDirs.outputDir if PyMcaDirs.nativeFileDialogs: outdir = qt.safe_str(qt.QFileDialog.getExistingDirectory(parent, message,
def _QWarning(msg, parent=None): """Print a warning message in a QMessageBox""" mb = qt.QMessageBox(parent) mb.setIcon(qt.QMessageBox.Warning) mb.setText(msg) mb.exec()
class ScanFit(qt.QWidget): sigScanFitSignal = qt.pyqtSignal(object) def __init__(self, parent=None, name="ScanFit", specfit=None, fl=0): #fl=qt.Qt.WDestructiveClose): qt.QWidget.__init__(self, parent) self.setWindowTitle(name) if specfit is None: self.specfit = Specfit.Specfit() else: self.specfit = specfit self.info = None layout = qt.QVBoxLayout(self) layout.setContentsMargins(0, 0, 0, 0) layout.setSpacing(0) ############## self.headerlabel = qt.QLabel(self) self.headerlabel.setAlignment(qt.Qt.AlignHCenter) self.setHeader('<b>Fit of XXXXXXXXXX from X XXXXX to XXXX<\b>') ############## if not len(self.specfit.theorylist): funsFile = "SpecfitFunctions.py" if not os.path.exists(funsFile): funsFile = os.path.join(os.path.dirname(Specfit.__file__), funsFile) self.specfit.importfun(funsFile) if 'Area Gaussians' not in self.specfit.theorylist: funsFile = "SpecfitFunctions.py" if not os.path.exists(funsFile): funsFile = os.path.join(os.path.dirname(Specfit.__file__), funsFile) self.specfit.importfun(funsFile) self.specfit.settheory('Area Gaussians') self.specfit.setbackground('Linear') fitconfig = {} fitconfig.update(self.specfit.fitconfig) fitconfig['WeightFlag'] = 0 fitconfig['ForcePeakPresence'] = 1 fitconfig['McaMode'] = 0 self.specfit.configure(**fitconfig) self.specfitGui = SpecfitGui.SpecfitGui(self, config=1, status=1, buttons=0, specfit=self.specfit, eh=self.specfit.eh) #self.specfitGui.updateGui(configuration=fitconfig) #self.setdata = self.specfit.setdata self.specfitGui.guiconfig.MCACheckBox.setEnabled(1) palette = self.specfitGui.guiconfig.MCACheckBox.palette() ############## hbox = qt.QWidget(self) hboxlayout = qt.QHBoxLayout(hbox) hboxlayout.setContentsMargins(0, 0, 0, 0) hboxlayout.setSpacing(0) self.estimatebutton = qt.QPushButton(hbox) self.estimatebutton.setText("Estimate") self.fitbutton = qt.QPushButton(hbox) self.fitbutton.setText("Fit") hboxlayout.addWidget(self.estimatebutton) hboxlayout.addWidget(qt.HorizontalSpacer(hbox)) hboxlayout.addWidget(self.fitbutton) self.dismissbutton = qt.QPushButton(hbox) self.dismissbutton.setText("Dismiss") self.estimatebutton.clicked.connect(self.estimate) self.fitbutton.clicked.connect(self.fit) self.dismissbutton.clicked.connect(self.dismiss) self.specfitGui.sigSpecfitGuiSignal.connect(self._specfitGuiSignal) hboxlayout.addWidget(qt.HorizontalSpacer(hbox)) hboxlayout.addWidget(self.dismissbutton) layout.addWidget(self.headerlabel) layout.addWidget(self.specfitGui) layout.addWidget(hbox) def setData(self, *var, **kw): self.info = {} if 'legend' in kw: self.info['legend'] = kw['legend'] del kw['legend'] else: self.info['legend'] = 'Unknown Origin' if 'xlabel' in kw: self.info['xlabel'] = kw['xlabel'] del kw['xlabel'] else: self.info['xlabel'] = 'X' self.specfit.setdata(var, **kw) try: self.info['xmin'] = "%.3f" % self.specfit.xdata[0] except: self.info['xmin'] = 'First' try: self.info['xmax'] = "%.3f" % self.specfit.xdata[-1] except: self.info['xmax'] = 'Last' self.setHeader(text="Fit of %s from %s %s to %s" % (self.info['legend'], self.info['xlabel'], self.info['xmin'], self.info['xmax'])) def setheader(self, *var, **kw): return self.setHeader(*var, **kw) def setHeader(self, *var, **kw): if len(var): text = var[0] elif 'text' in kw: text = kw['text'] elif 'header' in kw: text = kw['header'] else: text = "" self.headerlabel.setText("<b>%s<\b>" % text) def fit(self): if self.specfit.fitconfig['McaMode']: fitconfig = {} fitconfig.update(self.specfit.fitconfig) self.specfitGui.updateGui(configuration=fitconfig) #the Gui already takes care of mcafit self.specfitGui.estimate() else: #exception handler to be implemented #self.specfitGui.estimate() self.specfitGui.startfit() def estimate(self): fitconfig = {} fitconfig.update(self.specfit.fitconfig) self.specfitGui.updateGui(configuration=fitconfig) self.specfitGui.estimate() def _specfitGuiSignal(self, ddict): if not hasattr(ddict, "keys"): return if 'event' in ddict: if ddict['event'].upper() == "PRINT": h = self.__htmlheader() if __name__ == "__main__": self.__print(h + ddict['text']) else: ndict = {} ndict['event'] = "ScanFitPrint" ndict['text' ] = h + ddict['text'] ndict['info' ] = {} ndict['info'].update(self.info) self.sigScanFitSignal.emit(ndict) else: if self.info is None: self.info = {} ddict['info'] = {} ddict['info'].update(self.info) self.sigScanFitSignal.emit(ddict) def dismiss(self): self.close() def __htmlheader(self): try: header = "Fit of %s from %s %s to %s" % (self.info['legend'], self.info['xlabel'], self.info['xmin'], self.info['xmax']) except: # I cannot afford any unicode, key or whatever error, so, # provide a default value for the label. header = 'Fit of XXXXXXXXXX from Channel XXXXX to XXXX' if self.specfit.fitconfig['WeightFlag']: weight = "YES" else: weight = "NO" if self.specfit.fitconfig['McaMode']: mode = "YES" else: mode = "NO" theory = self.specfit.fitconfig['fittheory'] bkg = self.specfit.fitconfig['fitbkg'] fwhm = self.specfit.fitconfig['FwhmPoints'] scaling = self.specfit.fitconfig['Yscaling'] h = "" h += " <CENTER>" h += "<B>%s</B>" % header h += "<BR></BR>" h += "<TABLE>" h += "<TR>" h += " <TD ALIGN=LEFT><B>Function</B></TD>" h += " <TD><B>:</B></TD>" h += " <TD ALIGN=LEFT>%s</TD>" % theory h += " <TD><SPACER TYPE=BLOCK WIDTH=50></TD>" h += " <TD ALIGN=RIGHT><B>Weight</B></TD>" h += " <TD><B>:</B></TD>" h += " <TD ALIGN=LEFT>%s</TD>" % weight h += " <TD><SPACER TYPE=BLOCK WIDTH=10></B></TD>" h += " <TD ALIGN=RIGHT><B>FWHM</B></TD>" h += " <TD><B>:</B></TD></TD>" h += " <TD ALIGN=LEFT>%d</TD>" % fwhm h += "</TR>" h += "<TR>" h += " <TD ALIGN=LEFT><B>Background</B></TH>" h += " <TD><B>:</B></TD>" h += " <TD ALIGN=LEFT>%s</TD>" % bkg h += " <TD><SPACER TYPE=BLOCK WIDTH=50></B></TD>" h += " <TD ALIGN=RIGHT><B>MCA Mode</B></TD>" h += " <TD><B>:</B></TD>" h += " <TD ALIGN=LEFT>%s</TD>" % mode h += " <TD><SPACER TYPE=BLOCK WIDTH=10></B></TD>" h += " <TD ALIGN=RIGHT><B>Scaling</B></TD>" h += " <TD><B>:</B></TD>" h += " <TD ALIGN=LEFT>%g</TD>" % scaling h += "</TR>" h += "</TABLE>" h += "</CENTER>" return h def __print(self, text): printer = qt.QPrinter() if printer.setup(self): painter = qt.QPainter() if not(painter.begin(printer)): return 0 try: metrics = qt.QPaintDeviceMetrics(printer) dpiy = metrics.logicalDpiY() margin = int((2 / 2.54) * dpiy) # 2cm margin body = qt.QRect(0.5 * margin, margin, metrics.width() - margin, metrics.height() - 2 * margin) richtext = qt.QSimpleRichText(text, qt.QFont(), qt.QString(""), #0, qt.QStyleSheet.defaultSheet(), qt.QMimeSourceFactory.defaultFactory(), body.height()) view = qt.QRect(body) richtext.setWidth(painter,view.width()) page = 1 while(1): richtext.draw(painter,body.left(),body.top(), view,qt.QColorGroup()) view.moveBy(0, body.height()) painter.translate(0, -body.height()) painter.drawText(view.right() - painter.fontMetrics().width(qt.QString.number(page)), view.bottom() - painter.fontMetrics().ascent() + 5,qt.QString.number(page)) if view.top() >= richtext.height(): break printer.newPage() page += 1 painter.end() except: painter.end() msg = qt.QMessageBox(self) msg.setIcon(qt.QMessageBox.Critical) msg.setText("%s" % sys.exc_info()[1]) msg.exec_loop() def getText(self): try: header = "Fit of %s from %s %s to %s" % (self.info['legend'], self.info['xlabel'], self.info['xmin'], self.info['xmax']) except: # I cannot afford any unicode, key or whatever error, so, # provide a default value for the header text. header = 'Fit of XXXXXXXXXX from Channel XXXXX to XXXX' text = header + "\n" if self.specfit.fitconfig['WeightFlag']: weight = "YES" else: weight = "NO" if self.specfit.fitconfig['McaMode']: mode = "YES" else: mode = "NO" theory = self.specfit.fitconfig['fittheory'] bkg = self.specfit.fitconfig['fitbkg'] fwhm = self.specfit.fitconfig['FwhmPoints'] scaling = self.specfit.fitconfig['Yscaling'] text += "Fit Function: %s\n" % theory text += "Background: %s\n" % bkg text += "Weight: %s McaMode: %s FWHM: %d Yscaling: %f\n" % (weight[0], mode[0], fwhm, scaling) text += self.specfitGui.guiparameters.getText() return text def getConfiguration(self): return self.specfit.configure() def setConfiguration(self, fitconfig): self.specfit.configure(**fitconfig) self.specfitGui.updateGui(configuration=fitconfig)
class QXTube(qt.QWidget): sigQXTubeSignal = qt.pyqtSignal(object) def __init__(self, parent=None, initdict=None): qt.QWidget.__init__(self, parent) self.l = qt.QVBoxLayout(self) self.l.setContentsMargins(0, 0, 0, 0) self.l.setSpacing(0) self.tubeWidget = TubeWidget(self, initdict=initdict) self.setParameters = self.tubeWidget.setParameters self.getParameters = self.tubeWidget.getParameters label = qt.QLabel(self) hbox = qt.QWidget(self) hboxl = qt.QHBoxLayout(hbox) hboxl.setContentsMargins(0, 0, 0, 0) hboxl.setSpacing(0) self.plotButton = qt.QPushButton(hbox) self.plotButton.setText("Plot Continuum") self.exportButton = qt.QPushButton(hbox) self.exportButton.setText("Export to Fit") #grid.addWidget(self.plotButton, 7, 1) #grid.addWidget(self.exportButton, 7, 3) hboxl.addWidget(self.plotButton) hboxl.addWidget(self.exportButton) self.l.addWidget(self.tubeWidget) f = label.font() f.setItalic(1) label.setFont(f) label.setAlignment(qt.Qt.AlignRight) label.setText("H. Ebel, X-Ray Spectrometry 28 (1999) 255-266 ") self.l.addWidget(label) self.l.addWidget(hbox) self.graph = PlotWindow(self, colormap=False, yInverted=False, aspectRatio=False, control=False, position=False, roi=False, mask=False, fit=False) self.pluginsToolButton = PluginsToolButton(plot=self.graph) self.graph.toolBar().addWidget(self.pluginsToolButton) self.graph.getInteractiveModeToolBar().getZoomModeAction().setVisible( False) self.graph.getInteractiveModeToolBar().getPanModeAction().setVisible( False) self.l.addWidget(self.graph) self.graph.setGraphXLabel("Energy (keV)") self.graph.setGraphYLabel("photons/sr/mA/keV/s") self.plotButton.clicked.connect(self.plot) self.exportButton.clicked.connect(self._export) def plot(self): d = self.tubeWidget.getParameters() transmission = d["transmission"] anode = d["anode"] anodedensity = d["anodedensity"] anodethickness = d["anodethickness"] voltage = d["voltage"] wele = d["window"] wdensity = d["windowdensity"] wthickness = d["windowthickness"] fele = d["filter1"] fdensity = d["filter1density"] fthickness = d["filter1thickness"] filterlist = [[fele, fdensity, fthickness]] alphae = d["alphae"] alphax = d["alphax"] delta = d["deltaplotting"] e = numpy.arange(1, voltage, delta) if __name__ == "__main__": continuumR = XRayTubeEbel.continuumEbel( [anode, anodedensity, anodethickness], voltage, e, [wele, wdensity, wthickness], alphae=alphae, alphax=alphax, transmission=0, targetthickness=anodethickness, filterlist=filterlist) continuumT = XRayTubeEbel.continuumEbel( [anode, anodedensity, anodethickness], voltage, e, [wele, wdensity, wthickness], alphae=alphae, alphax=alphax, transmission=1, targetthickness=anodethickness, filterlist=filterlist) self.graph.addCurve(e, continuumR, "continuumR") self.graph.addCurve(e, continuumT, "continuumT") else: continuum = XRayTubeEbel.continuumEbel( [anode, anodedensity, anodethickness], voltage, e, [wele, wdensity, wthickness], alphae=alphae, alphax=alphax, transmission=transmission, targetthickness=anodethickness, filterlist=filterlist) self.graph.addCurve(e, continuum, "continuum") self.graph.setActiveCurve("continuum") self.graph.resetZoom() def _export(self): d = self.tubeWidget.getParameters() transmission = d["transmission"] anode = d["anode"] anodedensity = d["anodedensity"] anodethickness = d["anodethickness"] voltage = d["voltage"] wele = d["window"] wdensity = d["windowdensity"] wthickness = d["windowthickness"] fele = d["filter1"] fdensity = d["filter1density"] fthickness = d["filter1thickness"] filterlist = [[fele, fdensity, fthickness]] alphae = d["alphae"] alphax = d["alphax"] delta = d["deltaplotting"] e = numpy.arange(1, voltage, delta) d["event"] = "TubeUpdated" d["energyplot"] = e d["continuum"] = XRayTubeEbel.continuumEbel( [anode, anodedensity, anodethickness], voltage, e, [wele, wdensity, wthickness], alphae=alphae, alphax=alphax, transmission=transmission, targetthickness=anodethickness, filterlist=filterlist) fllines = XRayTubeEbel.characteristicEbel( [anode, anodedensity, anodethickness], voltage, [wele, wdensity, wthickness], alphae=alphae, alphax=alphax, transmission=transmission, targetthickness=anodethickness, filterlist=filterlist) d["characteristic"] = fllines fsum = 0.0 for l in fllines: _logger.debug("%s %.4f %.3e", l[2], l[0], l[1]) fsum += l[1] _logger.debug("%s", fsum) energy, energyweight, energyscatter = XRayTubeEbel.generateLists( [anode, anodedensity, anodethickness], voltage, window=[wele, wdensity, wthickness], alphae=alphae, alphax=alphax, transmission=transmission, targetthickness=anodethickness, filterlist=filterlist) d["energylist"] = energy d["weightlist"] = energyweight d["scatterlist"] = energyscatter d["flaglist"] = numpy.ones(len(energy)) self.sigQXTubeSignal.emit(d)
class ParametersWidget(qt.QWidget): parametersWidgetSignal = qt.pyqtSignal(object) def __init__(self, parent=None, ndim=2): qt.QWidget.__init__(self, parent) self._nDimensions = 2 self._shape = 3000, 3000 self._settingShape = False self._build() devices = self.getOpenCLDevices() if len(devices): self.deviceSelector.clear() for device in devices: self.deviceSelector.addItem("(%d, %d) %s" % (device[0], device[1], device[2])) def _build(self): self.mainLayout = qt.QGridLayout(self) self.mainLayout.setContentsMargins(0, 0, 0, 0) #self.aboutSiftButton = qt.QPushButton(self) #self.aboutSiftButton.setText("Please read prior to use!") #self.aboutSiftButton.clicked.connect(self._showInfo) # info self._infoDocument = qt.QTextEdit() self._infoDocument.setReadOnly(True) self._infoDocument.setMaximumHeight(150) self._infoDocument.setText(__doc__) #self._infoDocument.hide() label = qt.QLabel(self) label.setText("OpenCL Device:") self.deviceSelector = qt.QComboBox(self) self.deviceSelector.addItem("(-1, -1) No OpenCL device found") #self.mainLayout.addWidget(self.aboutSiftButton, 0, 0, 1, 2) self.mainLayout.addWidget(self._infoDocument, 0, 0, 2, 2) self.mainLayout.addWidget(label, 2, 0) self.mainLayout.addWidget(self.deviceSelector, 2, 1) def emitParametersWidgetSignal(self, event="ParametersChanged"): ddict = self.getParameters() ddict['event'] = "ParametersChanged" self.parametersWidgetSignal.emit(ddict) def _showInfo(self): if self._infoDocument.isHidden(): self._infoDocument.show() else: self._infoDocument.hide() def getOpenCLDevices(self): devices = [] if silx.opencl.ocl is not None: for platformid, platform in enumerate(silx.opencl.ocl.platforms): for deviceid, dev in enumerate(platform.devices): devices.append((platformid, deviceid, dev.name)) return devices def getParameters(self): txt = str(self.deviceSelector.currentText()).split(")")[0] txt = txt[1:].split(",") device = (int(txt[0]), int(txt[1])) return {'opencl_device': device}
def test(): app = qt.QApplication([]) w = QDispatcher() w.show() app.lastWindowClosed.connect(app.quit) app.exec_()