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) if QTVERSION < '4.0.0': msg.exec_loop() else: msg.exec_() if DEBUG: raise return dataInfoWidget= SpecFileDataInfo.SpecFileDataInfo(info) if "Header" in info: if info['Header'] is not None: if QTVERSION > '4.0.0': dataInfoWidget.setWindowTitle(info['Header'][0]) else: dataInfoWidget.setCaption(info['Header'][0]) dataInfoWidget.show() wid = id(dataInfoWidget) self.dataInfoWidgetDict[wid] = dataInfoWidget if QTVERSION < '4.0.0': self.connect(dataInfoWidget, qt.PYSIGNAL('SpecFileDataInfoSignal'), self._dataInfoClosed) else: dataInfoWidget.notifyCloseEventToWidget(self)
def _energySlot(self): qstring = self.energy.text() try: value = float(str(qstring)) self.energyvalue = value self.myslot(event='coeff') self.energy.setPaletteBackgroundColor(qt.Qt.white) if QTVERSION > '4.0.0': cursor = self.__browsertext.textCursor() cursor.movePosition(qt.QTextCursor.Start) self.__browsertext.setTextCursor(cursor) self.threshold.setFocus() except: msg = qt.QMessageBox(self.energy) msg.setIcon(qt.QMessageBox.Critical) msg.setText("Invalid Float") if QTVERSION < '4.0.0': msg.exec_loop() else: msg.setWindowTitle("Invalid entry") msg.exec_() self.energy.setFocus() return
def estimate(self): self.setStatus("Estimate started") self.statusWidget.chi2Line.setText("") try: x = self.fitModule._x y = self.fitModule._y if hasattr(self.graph, "addCurve"): self.graph.addCurve(x, y, 'Data') elif hasattr(self.graph, "newCurve"): self.graph.newCurve('Data', x, y) self.graph.removeCurve("Fit") self.graph.removeCurve("Background", replot=True) self.fitModule.estimate() self.setStatus() self.parametersTable.fillTableFromFit(self.fitModule.paramlist) except: if DEBUG: raise text = "%s:%s" % (sys.exc_info()[0], sys.exc_info()[1]) msg = qt.QMessageBox(self) msg.setIcon(qt.QMessageBox.Critical) msg.setText(text) msg.exec_() self.setStatus("Ready (after estimate error)")
def _energySlot(self): string = str(self.energy.text()) if len(string): try: value = float(string) except: msg = qt.QMessageBox(self.energy) msg.setIcon(qt.QMessageBox.Critical) msg.setText("Invalid Float") msg.exec_loop() self.energy.setFocus() return if self.energyValue is not None: if value != self.energyValue: self.energyValue = value Elements.updateDict(energy=value) else: self.energyValue = value Elements.updateDict(energy=value) self.energy.setPaletteBackgroundColor(qt.QColor('white')) self.infoWidget.setFocus() else: self.energyValue = None self.energy.setText("")
def __mySlot(self): qstring = self.text() text = str(qstring) try: if len(text): value = float(str(qstring)) ddict = {} ddict['event'] = 'returnPressed' ddict['value'] = value ddict['text'] = text ddict['qstring'] = qstring if QTVERSION < '4.0.0': self.emit(qt.PYSIGNAL('MyQLineEditSignal'), (ddict, )) else: self.emit(qt.SIGNAL('MyQLineEditSignal'), ddict) except: msg = qt.QMessageBox(self) msg.setIcon(qt.QMessageBox.Critical) msg.setText("Invalid Float") if QTVERSION < '4.0.0': msg.exec_loop() else: msg.exec_() self.setFocus()
def showMessage(self, text): msg = qt.QMessageBox(self) msg.setIcon(qt.QMessageBox.Information) msg.setText(text) msg.exec_()
def returnZonesForEqualize(zones,data): if len(zones) == 1: x1 = zones[-1][0] x2 = zones[-1][3] y1 = zones[-1][1] y2 = zones[-1][4] z1 = zones[-1][2] z2 = zones[-1][5] elif len(zones) > 1: x1 = zones[-2][0] x2 = zones[-2][3] y1 = zones[-2][1] y2 = zones[-2][4] z1 = zones[-2][2] z2 = zones[-2][5] if z2<z1: zs= z1 z1 = z2 z2 = zs if y2<y1: ys= y1 y1 = y2 y2 = ys if x2<x1: xs= x1 x1 = x2 x2 = xs if z1< 0: z1 = 0 elif z1> data.shape[0]: msgBox = qt.QMessageBox() msgBox.setText('Out of Volume') msgBox.exec_() if z2 < 0: msgBox = qt.QMessageBox() msgBox.setText('Out of Volume') msgBox.exec_() elif z2 > data.shape[0]: z2 = data.shape[0] -1 if y1< 0: y1 = 0 elif y1> data.shape[1]: msgBox = qt.QMessageBox() msgBox.setText('Out of Volume') msgBox.exec_() if y2 < 0: msgBox = qt.QMessageBox() msgBox.setText('Out of Volume') msgBox.exec_() elif y2 > data.shape[1]: y2 = data.shape[1] -1 if x1< 0: x1 = 0 elif x1> data.shape[2]: msgBox = qt.QMessageBox() msgBox.setText('Out of Volume') msgBox.exec_() if x2 < 0: msgBox = qt.QMessageBox() msgBox.setText('Out of Volume') msgBox.exec_() elif x2 > data.shape[2]: x2 = data.shape[2] -1 if len(zones) == 1: zones_in = [[z1,y1,x1,z2,y2,x2]] elif len(zones) > 1: x12 = zones[-1][0] x22 = zones[-1][3] y12 = zones[-1][1] y22 = zones[-1][4] z12 = zones[-1][2] z22 = zones[-1][5] if z22<z12: zs= z12 z12 = z22 z22 = zs if y22<y12: ys= y12 y12 = y22 y22 = ys if x22<x12: xs= x12 x12 = x22 x22 = xs if z12< 0: z12 = 0 elif z12> data.shape[0]: msgBox = qt.QMessageBox() msgBox.setText('Out of Volume') msgBox.exec_() if z22 < 0: msgBox = qt.QMessageBox() msgBox.setText('Out of Volume') msgBox.exec_() elif z22 > data.shape[0]: z22 = data.shape[0] -1 if y12< 0: y12 = 0 elif y12> data.shape[1]: msgBox = qt.QMessageBox() msgBox.setText('Out of Volume') msgBox.exec_() if y22 < 0: msgBox = qt.QMessageBox() msgBox.setText('Out of Volume') msgBox.exec_() elif y22 > data.shape[1]: y22 = data.shape[1] -1 if x12< 0: x12 = 0 elif x12> data.shape[2]: msgBox = qt.QMessageBox() msgBox.setText('Out of Volume') msgBox.exec_() if x22 < 0: msgBox = qt.QMessageBox() msgBox.setText('Out of Volume') msgBox.exec_() elif x22 > data.shape[2]: x22 = data.shape[2] -1 zones_in = [[z1,y1,z1,z2,y2,x2],[z12,y12,z12,z22,y22,x22]] return zones_in
def _mySignal(self, qstring0): qstring = qstring0 text = str(qstring0) if text == '-': return (result, index) = self.ownValidator.validate(qstring, 0) if result != self.ownValidator.Valid: qstring = self.ownValidator.fixup(qstring) (result, index) = self.ownValidator.validate(qstring, 0) if result != self.ownValidator.Valid: text = str(qstring) if text.endswith(" "): msg = qt.QMessageBox(self) msg.setIcon(qt.QMessageBox.Critical) msg.setText("Invalid Material Name '%s'\n" % text + \ "It ends with a space character.\n") msg.exec_() msg = qt.QMessageBox.No else: try: # this test is needed even if pyflakes complains float(text) msg = qt.QMessageBox(self) msg.setIcon(qt.QMessageBox.Critical) msg.setText("Invalid Material Name %s\n" % text + \ "You cannot use a number as material name.\n" +\ "Hint: You can use _%s_" % text) if QTVERSION < '4.0.0': msg.exec_loop() else: msg.exec_() msg = qt.QMessageBox.No except: msg=qt.QMessageBox.information( self, "Invalid Material %s" % str(qstring), "The material %s is not a valid Formula " \ "nor a valid Material.\n" \ "Do you want to define the material %s\n" % \ (str(qstring), str(qstring)), qt.QMessageBox.Yes,qt.QMessageBox.No) if msg == qt.QMessageBox.No: if QTVERSION < '4.0.0': self.setCurrentItem(0) else: self.setCurrentIndex(0) for i in range(self.count()): if QTVERSION < '4.0.0': selftext = self.text(i) else: selftext = self.itemText(i) if selftext == qstring0: self.removeItem(i) return else: qstring = qstring0 text = str(qstring) if Elements.isValidFormula(text): msg = qt.QMessageBox(self) msg.setIcon(qt.QMessageBox.Critical) msg.setText("Invalid Material Name %s\n" % text + \ "The material is a valid Formula.\n " \ "There is no need to define it.") if QTVERSION < '4.0.0': msg.exec_loop() else: msg.exec_() if QTVERSION < '4.0.0': self.setCurrentItem(0) else: self.setCurrentIndex(0) for i in range(self.count()): if QTVERSION < '4.0.0': selftext = self.text(i) else: selftext = self.itemText(i) if selftext == qstring0: self.removeItem(i) break return self.setCurrentText(text) dict = {} dict['event'] = 'activated' dict['row'] = self.row dict['col'] = self.col dict['text'] = text if qstring0 != qstring: self.removeItem(self.count() - 1) insert = True for i in range(self.count()): if QTVERSION < '4.0.0': selftext = self.text(i) else: selftext = self.itemText(i) if qstring == selftext: insert = False if insert: if QTVERSION < '4.0.0': self.insertItem(qstring, -1) else: self.insertItem(self.count(), qstring) if self.lineEdit() is not None: if QTVERSION < '4.0.0': self.lineEdit().setPaletteBackgroundColor(qt.QColor("white")) if QTVERSION < '4.0.0': self.emit(qt.PYSIGNAL('MaterialComboBoxSignal'), (dict, )) else: self.emit(qt.SIGNAL('MaterialComboBoxSignal'), (dict))
def __tableSlot2(self, row, col): if self.__fillingValues: return if self.__lastRow is None: self.__lastRow = row if self.__lastColumn is None: self.__lastColumn = col if QTVERSION < '4.0.0': qstring = self.__table.text(self.__lastRow, self.__lastColumn) else: item = self.__table.item(self.__lastRow, self.__lastColumn) if item is None: item = qt.QTableWidgetItem("", qt.QTableWidgetItem.Type) self.__table.setItem(self.__lastRow, self.__lastColumn, item) qstring = item.text() if self.__lastColumn == 0: compound = str(qstring) if Elements.isValidFormula(compound): pass else: matkey = Elements.getMaterialKey(compound) if matkey is not None: if QTVERSION < '4.0.0': self.__table.setText(self.__lastRow, self.__lastColumn, matkey) else: item = self.__table.item(self.__lastRow, self.__lastColumn) if item is None: item = qt.QTableWidgetItem( matkey, qt.QTableWidgetItem.Type) self.__table.setItem(self.__lastRow, self.__lastColumn, item) else: item.setText(matkey) else: msg = qt.QMessageBox(self.__table) msg.setIcon(qt.QMessageBox.Critical) msg.setText("Invalid Formula %s" % compound) if QTVERSION < '4.0.0': msg.exec_loop() else: msg.exec_() self.__table.setCurrentCell(self.__lastRow, self.__lastColumn) return else: try: float(str(qstring)) except: msg = qt.QMessageBox(self.__table) msg.setIcon(qt.QMessageBox.Critical) msg.setText("Invalid Float") if QTVERSION < '4.0.0': msg.exec_loop() else: msg.exec_() self.__table.setCurrentCell(self.__lastRow, self.__lastColumn) return self._updateCurrent()
def _addSelectionSlot(self, sel_list, event=None): if DEBUG: print("_addSelectionSlot") print("sel_list = ", sel_list) if event is None: event = "addSelection" for sel in sel_list: #The dispatcher should be a singleton to work properly #implement a patch targetwidgetid = sel.get('targetwidgetid', None) if targetwidgetid not in [None, id(self)]: continue #find the source sourcelist = sel['SourceName'] for source in self.sourceList: if source.sourceName == sourcelist: ddict = {} ddict.update(sel) ddict["event"] = 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": if DEBUG: dataObject = source.getDataObject( sel['Key'], selection=sel['selection']) else: try: dataObject = source.getDataObject( sel['Key'], selection=sel['selection']) except: 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 ddict['dataobject'] = dataObject if QTVERSION < '4.0.0': self.emit(qt.PYSIGNAL(event), (ddict, )) else: self.emit(qt.SIGNAL(event), 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) if QTVERSION < '4.0.0': self.emit(qt.PYSIGNAL(event), (ddict, )) else: self.emit(qt.SIGNAL(event), ddict)
def applyShifts(self): ''' Generic shift method. The method shifts curves according to the shift stored in self.shiftDict and executes the method stored in self.shiftMethod. Curves are sorted with respect to their legend, the values of self.shiftDict are sorted with respect to their key. ''' if len(self.shiftDict) == 0: msg = qt.QMessageBox(None) msg.setWindowTitle('Alignment Error') msg.setText('No shift data present.') msg.setStandardButtons(qt.QMessageBox.Ok) msg.exec_() return False # Check if interpolation is needed if self.shiftMethod == self.fftShift: curves = self.interpolate() else: curves = self.getAllCurves() if len(self.shiftList) != len(curves): msg = qt.QMessageBox(None) msg.setWindowTitle('Alignment Error') msg.setText( '''Number of shifts does not match the number of curves. Do you want to continue anyway?''') msg.setStandardButtons(qt.QMessageBox.Ok) msg.setStandardButtons(qt.QMessageBox.Ok | qt.QMessageBox.Cancel) msg.setDefaultButton(qt.QMessageBox.Ok) if msg.exec_() != qt.QMessageBox.Ok: return False if DEBUG: print('applyShifts -- Shifting ...') for idx, (x,y,legend,info) in enumerate(curves): shift = self.shiftDict[legend] if shift is None: if DEBUG: print('\tCurve \'%s\' not found in shiftDict\n%s'\ %(legend,str(self.shiftDict))) continue if shift == float('NaN'): if DEBUG: print('\tCurve \'%s\' has NaN shift'%legend) continue # Limit shift to zoomed in area xmin, xmax = self.getGraphXLimits() mask = numpy.nonzero((xmin<=x) & (x<=xmax))[0] # Execute method stored in self.shiftMethod xShifted, yShifted = self.shiftMethod(shift, x[mask], y[mask]) if idx == 0: replace, replot = True, False elif idx == (len(curves)-1): replace, replot = False, True else: replace, replot = False, False # Check if scan number is adopted by new curve if DEBUG: print('\'%s\' -- shifts -> \'%s\' by %f'%(self.shiftList[idx], legend, shift)) selectionlegend = info.get('selectionlegend',legend) self.addCurve(xShifted, yShifted, (selectionlegend + ' SHIFT'), info, replace, replot) return True
def _loadImageFiles(self): if self.getStackDataObject() is None: return getfilter = True fileTypeList = [ "PNG Files (*png)", "JPEG Files (*jpg *jpeg)", "IMAGE Files (*)", "EDF Files (*edf)", "EDF Files (*ccd)", "EDF Files (*)" ] message = "Open image file" filenamelist, filefilter = PyMcaFileDialogs.getFileList( parent=None, filetypelist=fileTypeList, message=message, getfilter=getfilter, single=False, currentfilter=None) if len(filenamelist) < 1: return imagelist = [] imagenames = [] mask = self.getStackSelectionMask() if mask is None: r, n = self.getStackROIImagesAndNames() shape = r[0].shape else: shape = mask.shape if filefilter.split()[0] in ["EDF"]: for filename in filenamelist: #read the edf file edf = EDFStack.EdfFileDataSource.EdfFileDataSource(filename) #the list of images keylist = edf.getSourceInfo()['KeyList'] if len(keylist) < 1: msg = qt.QMessageBox(None) msg.setIcon(qt.QMessageBox.Critical) msg.setText("Cannot read image from file") msg.exec_() return for key in keylist: #get the data dataObject = edf.getDataObject(key) data = dataObject.data if data.shape[0] not in shape: continue if data.shape[1] not in shape: continue imagename = dataObject.info.get('Title', "") if imagename != "": imagename += " " imagename += os.path.basename(filename) + " " + key imagelist.append(data) imagenames.append(imagename) if len(imagelist) == 0: msg = qt.QMessageBox(None) msg.setIcon(qt.QMessageBox.Critical) msg.setText("Cannot read a valid image from the file") msg.exec_() return crop = False self.widget = StackPluginResultsWindow.StackPluginResultsWindow( parent=None, usetab=False) self.widget.buildAndConnectImageButtonBox() qt.QObject.connect(self.widget, qt.SIGNAL('MaskImageWidgetSignal'), self.mySlot) self.widget.setStackPluginResults(imagelist, image_names=imagenames) self._showWidget() return else: #Try pure Image formats for filename in filenamelist: image = qt.QImage(filename) if image.isNull(): msg = qt.QMessageBox(self) msg.setIcon(qt.QMessageBox.Critical) msg.setText("Cannot read file %s as an image" % filename) msg.exec_() return imagelist.append(image) imagenames.append(os.path.basename(filename)) if len(imagelist) == 0: msg = qt.QMessageBox(None) msg.setIcon(qt.QMessageBox.Critical) msg.setText("Cannot read a valid image from the file") msg.exec_() return self.widget = ExternalImagesWindow.ExternalImagesWindow( parent=None, rgbwidget=None, selection=True, colormap=True, imageicons=True, standalonesave=True) self.widget.buildAndConnectImageButtonBox() qt.QObject.connect(self.widget, qt.SIGNAL('MaskImageWidgetSignal'), self.mySlot) self.widget.setImageData(None) self.widget.setQImageList(imagelist, shape[1], shape[0], clearmask=False, data=None, imagenames=imagenames) #data=self.__stackImageData) self._showWidget() return
def _pluginClicked(self): actionList = [] menu = qt.QMenu(self) text = qt.QString("Reload") menu.addAction(text) actionList.append(text) menu.addSeparator() callableKeys = ["Dummy"] for m in self.pluginList: if m == "PyMcaPlugins.Plugin1DBase": continue module = sys.modules[m] if hasattr(module, 'MENU_TEXT'): text = qt.QString(module.MENU_TEXT) else: text = os.path.basename(module.__file__) if text.endswith('.pyc'): text = text[:-4] elif text.endswith('.py'): text = text[:-3] text = qt.QString(text) methods = self.pluginInstanceDict[m].getMethods(plottype="SCAN") if not len(methods): continue menu.addAction(text) actionList.append(text) callableKeys.append(m) a = menu.exec_(qt.QCursor.pos()) if a is None: return None idx = actionList.index(a.text()) if idx == 0: n = self.getPlugins() if n < 1: msg = qt.QMessageBox(self) msg.setIcon(qt.QMessageBox.Information) msg.setText("Problem loading plugins") msg.exec_() return key = callableKeys[idx] methods = self.pluginInstanceDict[key].getMethods(plottype="SCAN") if len(methods) == 1: idx = 0 else: actionList = [] methods.sort() menu = qt.QMenu(self) for method in methods: text = qt.QString(method) pixmap = self.pluginInstanceDict[key].getMethodPixmap(method) tip = qt.QString( self.pluginInstanceDict[key].getMethodToolTip(method)) if pixmap is not None: action = qt.QAction(qt.QIcon(qt.QPixmap(pixmap)), text, self) else: action = qt.QAction(text, self) if tip is not None: action.setToolTip(tip) menu.addAction(action) actionList.append((text, pixmap, tip, action)) qt.QObject.connect(menu, qt.SIGNAL("hovered(QAction *)"), self._actionHovered) a = menu.exec_(qt.QCursor.pos()) if a is None: return None idx = -1 for action in actionList: if a.text() == action[0]: idx = actionList.index(action) try: self.pluginInstanceDict[key].applyMethod(methods[idx]) except: msg = qt.QMessageBox(self) msg.setIcon(qt.QMessageBox.Critical) if QTVERSION < '4.0.0': msg.setText("%s" % sys.exc_info()[1]) else: msg.setWindowTitle("Plugin error") msg.setText("An error has occured while executing the plugin:") msg.setInformativeText(str(sys.exc_info()[1])) msg.setDetailedText(traceback.format_exc()) msg.exec_()
def _calculateSlot(self): if self._data is None: msg = qt.QMessageBox(self) msg.setWindowTitle("No data") msg.setIcon(qt.QMessageBox.Information) msg.setText("No data to perform calculation") msg.exec_() return if self.nnmaParametersDialog is None: self.nnmaParametersDialog = NNMAWindow.NNMAParametersDialog(self) self.nnmaParametersDialog.nPC.setMaximum(self._spectrumLength) self.nnmaParametersDialog.nPC.setValue( min(10, self._spectrumLength)) ddict = { 'options': self._binningOptions, 'binning': 1, 'method': 0 } self.nnmaParametersDialog.setParameters(ddict) ret = self.nnmaParametersDialog.exec_() if ret: if DEBUG: t0 = time.time() nnmaParameters = self.nnmaParametersDialog.getParameters() self.nnmaParametersDialog.close() function = nnmaParameters['function'] binning = nnmaParameters['binning'] npc = nnmaParameters['npc'] kw = nnmaParameters['kw'] data = self._data old_shape = self._data.shape if DEBUG: images, eigenvalues, eigenvectors = function(data, npc, binning=binning, **kw) else: try: threadResult = self._submitThread(function, data, npc, binning=binning, **kw) if type(threadResult) == type((1, )): if len(threadResult): if threadResult[0] == "Exception": raise Exception(threadResult[1], threadResult[2]) images, eigenvalues, eigenvectors = threadResult except: if isinstance(data, numpy.ndarray): self._data.shape = old_shape msg = qt.QMessageBox(self) msg.setIcon(qt.QMessageBox.Critical) msg.setText("%s" % sys.exc_info()[1]) msg.exec_() return if isinstance(self._data, numpy.ndarray): self._data.shape = old_shape if DEBUG: print("NNMA Elapsed = ", time.time() - t0) self.nnmaWindow.setPCAData(images, eigenvalues, eigenvectors) self.nnmaWindow.show() self.nnmaWindow.raise_()
def __printps(self, text): msg = qt.QMessageBox(self) msg.setIcon(qt.QMessageBox.Critical) msg.setText("Sorry, Qt4 printing not implemented yet") msg.exec_()
def estimate(self): if self.specfit.fitconfig['McaMode']: try: mcaresult=self.specfit.mcafit() except: msg = qt.QMessageBox(self) msg.setIcon(qt.QMessageBox.Critical) msg.setText("Error on mcafit") if QTVERSION < '4.0.0':msg.exec_loop() else: msg.exec_() ddict={} ddict['event'] = 'FitError' if QTVERSION < '4.0.0': self.emit(qt.PYSIGNAL('SpecfitGUISignal'),(ddict,)) else: self.emit(qt.SIGNAL('SpecfitGUISignal'), ddict) if DEBUG: raise return self.guiparameters.fillfrommca(mcaresult) ddict={} ddict['event'] = 'McaFitFinished' ddict['data'] = mcaresult if QTVERSION < '4.0.0': self.emit(qt.PYSIGNAL('SpecfitGUISignal'),(ddict,)) else: self.emit(qt.SIGNAL('SpecfitGUISignal'), ddict) #self.guiparameters.removeallviews(keep='Region 1') else: try: if self.specfit.theorydict[self.specfit.fitconfig['fittheory']][2] is not None: self.specfit.estimate() else: msg = qt.QMessageBox(self) msg.setIcon(qt.QMessageBox.Information) text = "Function does not define a way to estimate\n" text += "the initial parameters. Please, fill them\n" text += "yourself in the table and press Start Fit\n" msg.setText(text) if QTVERSION < '4.0.0': msg.exec_loop() else: msg.setWindowTitle('SpecfitGUI Message') msg.exec_() return except: if DEBUG: raise msg = qt.QMessageBox(self) msg.setIcon(qt.QMessageBox.Critical) msg.setText("Error on estimate: %s" % sys.exc_info()[1]) if QTVERSION < '4.0.0': msg.exec_loop() else: msg.exec_() return self.guiparameters.fillfromfit(self.specfit.paramlist,current='Fit') self.guiparameters.removeallviews(keep='Fit') ddict={} ddict['event'] = 'EstimateFinished' ddict['data'] = self.specfit.paramlist if QTVERSION < '4.0.0': self.emit(qt.PYSIGNAL('SpecfitGUISignal'),(ddict,)) else: self.emit(qt.SIGNAL('SpecfitGUISignal'), ddict) return
def getStack(self, filelist=None, imagestack=None): if filelist in [None, []]: filelist, filefilter = self._getStackOfFiles(getfilter=True) else: filefilter = "" if not len(filelist): return None if filefilter == "": if HDF5: if h5py.is_hdf5(filelist[0]): filefilter = "HDF5" fileindex = 0 begin = None end = None aifirafile = False if len(filelist): PyMcaDirs.inputDir = os.path.dirname(filelist[0]) #if we are dealing with HDF5, no more tests needed if not filefilter.upper().startswith('HDF5'): f = open(filelist[0], 'rb') #read 10 characters if sys.version < '3.0': line = f.read(10) else: line = str(f.read(10).decode()) f.close() omnicfile = False if filefilter.upper().startswith('HDF5'): stack = QHDF5Stack1D.QHDF5Stack1D(filelist) omnicfile = True elif filefilter.upper().startswith('OPUS-DPT'): stack = OpusDPTMap.OpusDPTMap(filelist[0]) omnicfile = True elif filefilter.upper().startswith("AIFIRA"): stack = AifiraMap.AifiraMap(filelist[0]) omnicfile = True aifirafile = True elif filefilter.upper().startswith("SUPAVISIO"): stack = SupaVisioMap.SupaVisioMap(filelist[0]) omnicfile = True elif filefilter.upper().startswith("TEXTIMAGE"): imagestack = True fileindex = 0 stack = TextImageStack.TextImageStack(imagestack=True) elif filefilter.upper().startswith("IMAGE") and\ (filelist[0].upper().endswith("TIF") or\ filelist[0].upper().endswith("TIFF")): stack = TiffStack.TiffStack(imagestack=True) elif filefilter == "" and\ (filelist[0].upper().endswith("TIF") or\ filelist[0].upper().endswith("TIFF")): stack = TiffStack.TiffStack(imagestack=True) elif filefilter.upper().startswith("IMAGE"): if imagestack is None: imagestack = True fileindex = 0 stack = QStack(imagestack=imagestack) elif line[0] == "{": if filelist[0].upper().endswith("RAW"): if imagestack is None: imagestack = True stack = QStack(imagestack=imagestack) elif line[0:2] in ["II", "MM"]: if imagestack is None: imagestack = True stack = QStack(imagestack=imagestack) elif line.startswith('Spectral'): stack = OmnicMap.OmnicMap(filelist[0]) omnicfile = True elif line.startswith('#\tDate'): stack = LuciaMap.LuciaMap(filelist[0]) omnicfile = True elif filelist[0].upper().endswith("RAW.GZ")or\ filelist[0].upper().endswith("EDF.GZ")or\ filelist[0].upper().endswith("CCD.GZ")or\ filelist[0].upper().endswith("RAW.BZ2")or\ filelist[0].upper().endswith("EDF.BZ2")or\ filelist[0].upper().endswith("CCD.BZ2"): if imagestack is None: imagestack = True stack = QStack(imagestack=imagestack) elif filelist[0][-4:].upper() in ["PIGE", "PIGE"]: stack = SupaVisioMap.SupaVisioMap(filelist[0]) omnicfile = True elif filelist[0][-3:].upper() in ["RBS"]: stack = SupaVisioMap.SupaVisioMap(filelist[0]) omnicfile = True elif filelist[0][-3:].upper() in ["SPE"] and\ (line[0] not in ['$', '#']): #Roper Scientific format #handle it as MarCCD stack stack = QStack(imagestack=True) else: stack = QSpecFileStack() if len(filelist) == 1: if not omnicfile: try: stack.loadIndexedStack(filelist[0], begin, end, fileindex=fileindex) except: msg = qt.QMessageBox() msg.setIcon(qt.QMessageBox.Critical) msg.setText("%s" % sys.exc_info()[1]) if QTVERSION < '4.0.0': msg.exec_loop() else: msg.exec_() if DEBUG: raise elif len(filelist): if not omnicfile: try: stack.loadFileList(filelist, fileindex=fileindex) except: msg = qt.QMessageBox() msg.setIcon(qt.QMessageBox.Critical) msg.setText("%s" % sys.exc_info()[1]) if QTVERSION < '4.0.0': msg.exec_loop() else: msg.exec_() if DEBUG: raise if aifirafile: masterStack = DataObject.DataObject() masterStack.info = copy.deepcopy(stack.info) masterStack.data = stack.data[:, :, 0:1024] masterStack.info['Dim_2'] = int(masterStack.info['Dim_2'] / 2) slaveStack = DataObject.DataObject() slaveStack.info = copy.deepcopy(stack.info) slaveStack.data = stack.data[:, :, 1024:] slaveStack.info['Dim_2'] = int(slaveStack.info['Dim_2'] / 2) return [masterStack, slaveStack] else: return stack
def __init__(self, parent = None, printer = None, name = "PyMcaPrintPreview", \ modal = 0, fl = 0): qt.QDialog.__init__(self, parent) self.setWindowTitle(name) self.setModal(modal) self.resize(400, 500) self.printDialog = None if printer is None: printer = qt.QPrinter(qt.QPrinter.HighResolution) printer.setPageSize(qt.QPrinter.A4) printerName = "%s" % printer.printerName() if printerName in ['id24b2u']: #id24 printer very slow in color mode printer.setColorMode(qt.QPrinter.GrayScale) printer.setFullPage(True) if (printer.width() <= 0) or (printer.height() <= 0): if QTVERSION < '4.2.0': #this is impossible (no QGraphicsView) filename = "PyMCA_print.pdf" else: filename = "PyMCA_print.ps" if sys.platform == 'win32': home = os.getenv('USERPROFILE') try: l = len(home) directory = os.path.join(home, "My Documents") except: home = '\\' directory = '\\' if os.path.isdir('%s' % directory): directory = os.path.join(directory, "PyMca") else: directory = os.path.join(home, "PyMca") if not os.path.exists('%s' % directory): os.mkdir('%s' % directory) finalfile = os.path.join(directory, filename) else: home = os.getenv('HOME') directory = os.path.join(home, "PyMca") if not os.path.exists('%s' % directory): os.mkdir('%s' % directory) finalfile = os.path.join(directory, filename) printer.setOutputFileName(finalfile) printer.setColorMode(qt.QPrinter.Color) if (printer.width() <= 0) or (printer.height() <= 0): self.message = qt.QMessageBox(self) self.message.setIcon(qt.QMessageBox.Critical) self.message.setText( "Unknown library error \non printer initialization") self.message.setWindowTitle("Library Error") self.message.setModal(0) self.badNews = True self.printer = None return else: self.badNews = False self.printer = printer self.mainLayout = qt.QVBoxLayout(self) self.mainLayout.setMargin(0) self.mainLayout.setSpacing(0) self._buildToolbar() self.scene = qt.QGraphicsScene() self.scene.setBackgroundBrush(qt.QColor(qt.Qt.lightGray)) self.page = qt.QGraphicsRectItem(0, 0, printer.width(), printer.height()) self.page.setBrush(qt.QColor(qt.Qt.white)) self.scene.setSceneRect( qt.QRectF(0, 0, printer.width(), printer.height())) self.scene.addItem(self.page) self.view = qt.QGraphicsView(self.scene) self.mainLayout.addWidget(self.view) self._buildStatusBar() self.view.fitInView(self.page.rect(), qt.Qt.KeepAspectRatio) self._viewScale = 1.00
def calculateShiftsFit(self, derivative=False, thr=30): retDict = {} retList = [] curves = self.getAllCurves() nCurves = len(curves) if nCurves < 2: raise ValueError("At least 2 curves needed") return # Check if scan window is zoomed in xmin, xmax = self.getGraphXLimits() # Determine largest overlap between curves xmin0, xmax0 = self.getXLimits(x for (x,y,leg,info) in curves) if xmin0 > xmin: xmin = xmin0 if xmax0 < xmax: xmax = xmax0 if DEBUG: print('calculateShiftsFit -- xmin = %.3f, xmax = %.3f'%(xmin, xmax)) # Get active curve activeCurve = self.getActiveCurve() if activeCurve is None: # If active curve is not set, continue with first curve activeCurve = curves[0] else: activeLegend = activeCurve[2] idx = list.index([curve[2] for curve in curves], activeLegend) activeCurve = curves[idx] x0, y0 = activeCurve[0], activeCurve[1] idx = numpy.nonzero((xmin <= x0) & (x0 <= xmax))[0] x0 = numpy.take(x0, idx) y0 = numpy.take(y0, idx) if derivative: # Take first derivative y0 = numpy.diff(y0)/numpy.diff(x0) x0 = .5 * (x0[1:] + x0[:-1]) peak0 = self.findPeaks(x0, y0, .80, derivative) if peak0: xp0, yp0, fwhm0, fitrange0 = peak0 else: raise ValueError("No peak identified in '%s'"%activeCurve[2]) fitp0, chisq0, sigma0 = LSF(gauss, numpy.asarray([yp0, xp0, fwhm0]), xdata=x0[fitrange0], ydata=y0[fitrange0]) if DEBUG: if derivative: print('calculateShiftsFit -- Results (Leg, PeakPos, Shift):') else: print('calculateShiftsFitDerivative -- Results (Leg, PeakPos, Shift):') for x,y,legend,info in curves: idx = numpy.nonzero((xmin <= x) & (x <= xmax))[0] x = numpy.take(x, idx) y = numpy.take(y, idx) if derivative: # Take first derivative y = numpy.diff(y)/numpy.diff(x) x = .5 * (x[1:] + x[:-1]) peak = self.findPeaks(x, y, .80, derivative) if peak: xp, yp, fwhm, fitrange = peak else: raise ValueError("No peak identified in '%s'"%activeCurve[2]) try: fitp, chisq, sigma = LSF(gauss, numpy.asarray([yp, xp, fwhm]), xdata=x[fitrange], ydata=y[fitrange]) # Shift is difference in peak's x position shift = fitp0[1] - fitp[1] except numpy.linalg.linalg.LinAlgError: msg = qt.QMessageBox(None) msg.setWindowTitle('Alignment Error') msg.setText('Singular matrix encountered during least squares fit.') msg.setStandardButtons(qt.QMessageBox.Ok) msg.exec_() shift = float('NaN') key = legend retList.append(key) retDict[key] = shift if DEBUG: print( '\t%s\t%.3f\t%.3f'%(legend, fitp[1], shift)) return retList, retDict
def updateGraph(self, ddict): self.__lastDict = ddict edgeEnergy = ddict['edge_energy'] preRegions = ddict['pre_edge']['regions'] postRegions = ddict['post_edge']['regions'] event = ddict.get('event', None) if event == "AutoEdgeEnergyClicked": try: # recalculate edge energy following region limits xmin = edgeEnergy + preRegions[0][0] xmax = edgeEnergy + postRegions[0][1] idx = numpy.nonzero((self.energy >= xmin) &\ (self.energy <= xmax))[0] x = numpy.take(self.energy, idx) y = numpy.take(self.spectrum, idx) edgeEnergy = XASNormalization.estimateXANESEdge(y, energy=x, full=False) self.parametersWidget.setEdgeEnergy(edgeEnergy, emin=self.energy.min(), emax=self.energy.max()) self.__lastDict['edge_energy'] = edgeEnergy except: pass parameters = {} parameters['pre_edge_order'] = ddict['pre_edge']['polynomial'] parameters['post_edge_order'] = ddict['post_edge']['polynomial'] algorithm = 'polynomial' if self.__markerHandling: self.updateMarkers(edgeEnergy, preRegions, postRegions, edge_auto=ddict['auto_edge']) else: self.graph.addCurve( [edgeEnergy, edgeEnergy], [self.spectrum.min(), self.spectrum.max()], legend="Edge Position", replace=False) try: normalizationResult = XASNormalization.XASNormalization( self.spectrum, self.energy, edge=edgeEnergy, pre_edge_regions=preRegions, post_edge_regions=postRegions, algorithm=algorithm, algorithm_parameters=parameters) except: msg = qt.QMessageBox(self) msg.setIcon(qt.QMessageBox.Critical) msg.setWindowTitle("Normalization Error") msg.setText("An error has occured while normalizing the data") msg.setInformativeText(str(sys.exc_info()[1])) msg.setDetailedText(traceback.format_exc()) msg.exec_() return nEnergy, nSpectrum, usedEdge, jump = normalizationResult[0:4] preEdgeFunction, preEdgeParameters = normalizationResult[4:6] postEdgeFunction, postEdgeParameters = normalizationResult[6:8] idx = self.energy > (usedEdge + preRegions[0][0]) x = self.energy[idx] yPre = preEdgeFunction(preEdgeParameters, x) yPost = postEdgeFunction(postEdgeParameters, x) self.graph.addCurve(x, yPre, legend="Pre-edge Polynomial", replace=False) self.graph.addCurve(x, yPost + yPre, legend="Post-edge Polynomial", replace=False, replot=True)
def saveClicked(self): outfile = qt.QFileDialog(self) outfile.setModal(1) if self.lastOutputDir is None: self.lastOutputDir = PyMcaDirs.outputDir outfile.setWindowTitle("Output File Selection") if hasattr(qt, "QStringList"): strlist = qt.QStringList() else: strlist = [] format_list = [] format_list.append('Graphics PNG *.png') format_list.append('Graphics EPS *.eps') format_list.append('Graphics SVG *.svg') for f in format_list: strlist.append(f) outfile.setFilters(strlist) outfile.setFileMode(outfile.AnyFile) outfile.setAcceptMode(qt.QFileDialog.AcceptSave) outfile.setDirectory(self.lastOutputDir) ret = outfile.exec_() if ret: filterused = qt.safe_str(outfile.selectedFilter()).split() filedescription = filterused[0] filetype = filterused[1] extension = filterused[2] try: outstr = qt.safe_str(outfile.selectedFiles()[0]) except: msg = qt.QMessageBox(self) msg.setIcon(qt.QMessageBox.Critical) msg.setText("Error saving image: %s" % sys.exc_info()[1]) msg.setWindowTitle('Matplotlib Save Image') msg.exec_() try: outputDir = os.path.dirname(outstr) self.lastOutputDir = outputDir PyMcaDirs.outputDir = outputDir except: outputDir = "." try: outputFile = os.path.basename(outstr) except: outputFile = outstr outfile.close() del outfile else: outfile.close() del outfile return #always overwrite for the time being if len(outputFile) < len(extension[1:]): outputFile += extension[1:] elif outputFile[-4:] != extension[1:]: outputFile += extension[1:] finalFile = os.path.join(outputDir, outputFile) if os.path.exists(finalFile): try: os.remove(finalFile) except: msg = qt.QMessageBox(self) msg.setIcon(qt.QMessageBox.Critical) msg.setText("Cannot overwrite file: %s" % sys.exc_info()[1]) msg.setWindowTitle('Matplotlib Save Image') msg.exec_() return try: self.imageWidget.print_figure(finalFile, edgecolor='w', facecolor='w', format=finalFile[-3:], dpi=self.imageWidget.config['outputdpi']) except: print("WARNING: trying to save using obsolete method") config = self.imageWidget.getParameters() try: s=PyMcaMatplotlibSave.PyMcaMatplotlibSaveImage(self.imageWidget.imageData) if self.imageWidget.pixmapImage is not None: s.setPixmapImage(self.imageWidget.pixmapImage) s.setParameters(config) s.saveImage(finalFile) except: msg = qt.QMessageBox(self) msg.setIcon(qt.QMessageBox.Critical) msg.setText("Error saving file: %s" % sys.exc_info()[1]) msg.setWindowTitle('Matplotlib Save Image') msg.exec_()
def _calculateSlot(self): if self._data is None: msg = qt.QMessageBox(self) msg.setWindowTitle("No data") msg.setIcon(qt.QMessageBox.Information) msg.setText("No data to perform calculation") msg.exec_() return if not self.pcaParametersDialogInitialized: self.pcaParametersDialog.nPC.setMaximum(self._spectrumLength) self.pcaParametersDialog.nPC.setValue( min(10, self._spectrumLength)) ddict = {'options': self._binningOptions, 'binning': 1, 'method': 0} self.pcaParametersDialog.setParameters(ddict) self.pcaParametersDialogInitialized = True ret = self.pcaParametersDialog.exec_() if ret: if DEBUG: t0 = time.time() pcaParameters = self.pcaParametersDialog.getParameters() self.pcaParametersDialog.close() function = pcaParameters['function'] binning = pcaParameters['binning'] npc = pcaParameters['npc'] mask = pcaParameters['mask'] kw = pcaParameters.get('kw', {}) data = self._data old_shape = self._data.shape if mask is not None: if mask.sum() < npc: msg = qt.QMessageBox(self) msg.setWindowTitle("Not enough data") msg.setIcon(qt.QMessageBox.Information) msg.setText("Number of components too high") msg.exec_() return if DEBUG: images, eigenvalues, eigenvectors = function(data, npc, binning=binning, mask=mask, **kw) else: try: threadResult = self._submitThread(function, data, npc, binning=binning, mask=mask, **kw) if type(threadResult) == type((1,)): if len(threadResult): if threadResult[0] == "Exception": raise Exception(threadResult[1], threadResult[2]) images, eigenvalues, eigenvectors = threadResult except: if isinstance(data, numpy.ndarray): self._data.shape = old_shape msg = qt.QMessageBox(self) msg.setIcon(qt.QMessageBox.Critical) msg.setText("%s" % sys.exc_info()[1]) msg.exec_() return if isinstance(self._data, numpy.ndarray): self._data.shape = old_shape if DEBUG: print("PCA Elapsed = ", time.time() - t0) methodlabel = pcaParameters.get('methodlabel', "") imagenames = None vectornames = None if " ICA " in methodlabel: nimages = images.shape[0] imagenames = [] vectornames = [] itmp = int(nimages / 2) for i in range(itmp): imagenames.append("ICAimage %02d" % i) vectornames.append("ICAvector %02d" % i) for i in range(itmp): imagenames.append("Eigenimage %02d" % i) vectornames.append("Eigenvector %02d" % i) self.pcaWindow.setPCAData(images, eigenvalues, eigenvectors, imagenames=imagenames, vectornames=vectornames) self.pcaWindow.show() self.pcaWindow.raise_()