def getPixmap(): """ Open an image file and return the filename and the data. Return ``None, None`` in case of failure. """ fileTypeList = [ 'Picture Files (*jpg *jpeg *tif *tiff *png)', 'EDF Files (*edf)', 'EDF Files (*ccd)', 'ADSC Files (*img)', 'EDF Files (*)' ] fileList, filterUsed = PyMcaFileDialogs.getFileList( parent=None, filetypelist=fileTypeList, message="Please select one object data file", mode="OPEN", getfilter=True) if not fileList: return None, None fname = fileList[0] if filterUsed.split()[0] == "Picture": qimage = qt.QImage(fname) if qimage.isNull(): msg = qt.QMessageBox() msg.setIcon(qt.QMessageBox.Critical) msg.setText("Cannot read file %s as an image" % fname) msg.exec() return None, None return os.path.basename(fname), convertQImageToArray(qimage) if filterUsed.split()[0] in ["EDF", "ADSC"]: edf = EdfFile.EdfFile(fname) data = edf.GetData(0) return os.path.basename(fname), data return None, None
def getChimeraStack(): """ Open an chimera file and return the filename and the data. Return ``None, None`` in case the user cancelled the file dialog. :raise IOError: If the data is not a 3D stack """ fileTypeList = ['Chimera Stack (*cmp)', 'Chimera Stack (*)'] old = PyMcaFileDialogs.PyMcaDirs.nativeFileDialogs * 1 fileList, filterUsed = PyMcaFileDialogs.getFileList( parent=None, filetypelist=fileTypeList, message="Please select the object file(s)", mode="OPEN", getfilter=True) PyMcaFileDialogs.PyMcaDirs.nativeFileDialogs = old if not fileList: return None, None filename = fileList[0] with h5py.File(filename, mode='r') as f: stack = f['Image/data'][...] if not isinstance(stack, numpy.ndarray) or stack.ndim != 3: raise IOError("Problem reading stack.") return os.path.basename(filename), stack
def getMesh(): """ Read an image data file (EDF, ADSC), return the data and image name. This is then used to display the image as a height map. Returns *None, None* if the file dialog is cancelled or loaing fails. :return: legend, data """ fileTypeList = [ 'EDF Files (*edf)', 'EDF Files (*ccd)', 'ADSC Files (*img)', 'All Files (*)' ] old = PyMcaFileDialogs.PyMcaDirs.nativeFileDialogs * 1 PyMcaFileDialogs.PyMcaDirs.nativeFileDialogs = False fileList, filterUsed = PyMcaFileDialogs.getFileList( parent=None, filetypelist=fileTypeList, message="Please select one object data file", mode="OPEN", getfilter=True) PyMcaFileDialogs.PyMcaDirs.nativeFileDialogs = old if not fileList: return None, None filename = fileList[0] edf = EdfFile.EdfFile(filename, access='rb') data = edf.GetData(0).astype(numpy.float32) return os.path.basename(filename), data
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" windir = self.lastInputDir if windir is None: windir = "" filelist, filefilter = PyMcaFileDialogs.getFileList( self, filetypelist=["Calibration files (*.calib)"], message="Save a new calibration file", currentdir=windir, mode="SAVE", single=True, getfilter=True, currentfilter=self.lastInputFilter) if not len(filelist): return filename = qt.safe_str(filelist[0]) 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 getInputFilename(self): if self._dir is None: inidir = PyMcaDirs.inputDir else: inidir = self._dir if not os.path.exists(inidir): inidir = os.getcwd() fileList = PyMcaFileDialogs.getFileList(parent=self, filetypelist=["ini files (*.ini)"], message="Select a .ini file", currentdir=inidir, mode="OPEN", getfilter=False) if len(fileList): ret = fileList[0] else: ret = "" if len(ret): self._dir = os.path.dirname(ret) PyMcaDirs.inputDir = os.path.dirname(ret) return ret
def importFunctions(self, functionsfile=None): if functionsfile is None: filetypelist = ['Python files (*.py)', 'All Files (*)'] fileList = PyMcaFileDialogs.getFileList(self, filetypelist=filetypelist, message="Select input functions file", currentdir=None, mode="OPEN", getfilter=None, single=True, currentfilter=filetypelist[0], native=None) if len(fileList): functionsfile= qt.safe_str(fileList[0]) else: functionsfile = "" if not len(functionsfile): return try: self.fitModule.importFunctions(functionsfile) except: if _logger.getEffectiveLevel() == logging.DEBUG: raise msg = qt.QMessageBox() msg.setWindowTitle("SimpleFitGui error") msg.setIcon(qt.QMessageBox.Critical) msg.setInformativeText("Function not imported %s" % \ str(sys.exc_info()[1])) msg.setDetailedText(traceback.format_exc()) msg.exec() config = self.fitModule.getConfiguration() self.topWidget.setFunctions(config['fit']['functions'])
def getPixmap(): """ Open an image file and return the filename and the data. Return ``None, None`` in case of failure. """ fileTypeList = ['Picture Files (*jpg *jpeg *tif *tiff *png)', 'EDF Files (*edf)', 'EDF Files (*ccd)', 'ADSC Files (*img)', 'EDF Files (*)'] fileList, filterUsed = PyMcaFileDialogs.getFileList( parent=None, filetypelist=fileTypeList, message="Please select one object data file", mode="OPEN", getfilter=True) if not fileList: return None, None fname = fileList[0] if filterUsed.split()[0] == "Picture": qimage = qt.QImage(fname) if qimage.isNull(): msg = qt.QMessageBox() msg.setIcon(qt.QMessageBox.Critical) msg.setText("Cannot read file %s as an image" % fname) msg.exec_() return None, None return os.path.basename(fname), convertQImageToArray(qimage) if filterUsed.split()[0] in ["EDF", "ADSC"]: edf = EdfFile.EdfFile(fname) data = edf.GetData(0) return os.path.basename(fname), data return None, None
def getMesh(): """ Read an image data file (EDF, ADSC), return the data and image name. This is then used to display the image as a height map. Returns *None, None* if the file dialog is cancelled or loaing fails. :return: legend, data """ fileTypeList = ['EDF Files (*edf)', 'EDF Files (*ccd)', 'ADSC Files (*img)', 'All Files (*)'] old = PyMcaFileDialogs.PyMcaDirs.nativeFileDialogs * 1 PyMcaFileDialogs.PyMcaDirs.nativeFileDialogs = False fileList, filterUsed = PyMcaFileDialogs.getFileList( parent=None, filetypelist=fileTypeList, message="Please select one object data file", mode="OPEN", getfilter=True) PyMcaFileDialogs.PyMcaDirs.nativeFileDialogs = old if not fileList: return None, None filename = fileList[0] edf = EdfFile.EdfFile(filename, access='rb') data = edf.GetData(0).astype(numpy.float32) return os.path.basename(filename), data
def getChimeraStack(): """ Open an chimera file and return the filename and the data. Return ``None, None`` in case the user cancelled the file dialog. :raise IOError: If the data is not a 3D stack """ fileTypeList = ['Chimera Stack (*cmp)', 'Chimera Stack (*)'] old = PyMcaFileDialogs.PyMcaDirs.nativeFileDialogs * 1 fileList, filterUsed = PyMcaFileDialogs.getFileList( parent=None, filetypelist=fileTypeList, message="Please select the object file(s)", mode="OPEN", getfilter=True) PyMcaFileDialogs.PyMcaDirs.nativeFileDialogs = old if not fileList: return None, None filename = fileList[0] with h5py.File(filename) as f: stack = f['Image/data'][...] if not isinstance(stack, numpy.ndarray) or stack.ndim != 3: raise IOError("Problem reading stack.") return os.path.basename(filename), stack
def saveAllSpectra(self): fltrs = ['Raw ASCII *.txt', '","-separated CSV *.csv', '";"-separated CSV *.csv', '"tab"-separated CSV *.csv', 'OMNIC CSV *.csv'] message = "Enter file name to be used as root" fileList, fileFilter = PyMcaFileDialogs.getFileList(parent=self, filetypelist=fltrs, message=message, currentdir=None, mode="SAVE", getfilter=True, single=True, currentfilter=None, native=None) if not len(fileList): return fileroot = fileList[0] dirname = os.path.dirname(fileroot) root, ext = os.path.splitext(os.path.basename(fileroot)) if ext not in [".txt", ".csv"]: root = root + ext ext = "" # get appropriate extensions and separators filterused = fileFilter.split() if filterused[0].startswith("Raw"): csv = False ext = "txt" csvseparator = " " elif filterused[0].startswith("OMNIC"): # extension is csv but saved as ASCII csv = False ext = "csv" csvseparator = "," else: csv = True ext = "csv" if "," in filterused[0]: csvseparator = "," elif ";" in filterused[0]: csvseparator = ";" elif "OMNIC" in filterused[0]: csvseparator = "," else: csvseparator = "\t" nSpectra = len(self.spectrumList) n = int(numpy.log10(nSpectra)) + 1 fmt = "_%" + "0%dd" % n + ".%s" for index in range(nSpectra): legend = self.spectrumNames[index] x = self.xValues[index] y = self.spectrumList[index] filename = os.path.join(dirname, root + fmt % (index, ext)) ArraySave.saveXY(x, y, filename, ylabel=legend, csv=csv, csvseparator=csvseparator)
def browseConfigurationFile(self): f = PyMcaFileDialogs.getFileList(parent=self, filetypelist=["Configuration files (*.ini)", "Configuration files (*.cfg)"], message="Open a XAS configuration file", mode="OPEN", single=True) if len(f): self._configLine.setText(f[0])
def _getOutputFileNameAndFilter(self, format_list=None): """ returns outputfile, file type and filter used """ # get outputfile self.outputDir = PyMcaDirs.outputDir if self.outputDir is None: self.outputDir = os.getcwd() wdir = os.getcwd() elif os.path.exists(self.outputDir): wdir = self.outputDir else: self.outputDir = os.getcwd() wdir = self.outputDir if format_list is None: format_list = ['Specfile MCA *.mca', 'Specfile Scan *.dat'] if self._plotType != "MCA": format_list += ['Specfile MultiScan *.dat'] format_list += [ 'Raw ASCII *.txt', '","-separated CSV *.csv', '";"-separated CSV *.csv', '"tab"-separated CSV *.csv', 'OMNIC CSV *.csv', 'Widget PNG *.png', 'Widget JPG *.jpg', 'Graphics PNG *.png', 'Graphics EPS *.eps', 'Graphics SVG *.svg' ] if self.outputFilter is None: self.outputFilter = format_list[0] fileList, fileFilter = PyMcaFileDialogs.getFileList( self, filetypelist=format_list, message="Output File Selection", currentdir=wdir, single=True, mode="SAVE", getfilter=True, currentfilter=self.outputFilter) if not len(fileList): return self.outputFilter = fileFilter filterused = self.outputFilter.split() filetype = filterused[1] extension = filterused[2] outdir = qt.safe_str(fileList[0]) try: self.outputDir = os.path.dirname(outdir) PyMcaDirs.outputDir = os.path.dirname(outdir) except: self.outputDir = "." try: outputFile = os.path.basename(outdir) except: outputFile = outdir if len(outputFile) < 5: outputFile = outputFile + extension[-4:] elif outputFile[-4:] != extension[-4:]: outputFile = outputFile + extension[-4:] return os.path.join(self.outputDir, outputFile), fileFilter
def __addFiles(self): files = PyMcaFileDialogs.getFileList(self, filetypelist=["Edf Files (*.edf)", "All Files (*)"], message="Add XIA Edf Files", getfilter=False, mode="OPEN", single=False) for name in files: self.__addInFileList("file", name)
def _getFileList(self, fileTypeList, message=None, getfilter=None): if message is None: message = "Please select a file" if getfilter is None: getfilter = False wdir = PyMcaDirs.inputDir filterused = None if getfilter: filelist, filterused = PyMcaFileDialogs.getFileList( self.parent, filetypelist=fileTypeList, mode="OPEN", message=message, currentdir=wdir, getfilter=True, single=False, native=True) else: filelist = PyMcaFileDialogs.getFileList(self.parent, filetypelist=fileTypeList, mode="OPEN", message=message, currentdir=wdir, getfilter=False, single=False, native=True) if not (len(filelist)): return [] PyMcaDirs.inputDir = os.path.dirname(filelist[0]) if PyMcaDirs.outputDir is None: PyMcaDirs.outputDir = os.path.dirname(filelist[0]) if getfilter: return filelist, filterused else: return filelist
def _getFilenameDialog(parent=None): """Open a dialog to select a file in a filesystem tree view. Return the selected filename.""" from PyMca5.PyMcaGui.io import PyMcaFileDialogs fileTypeList = ['HDF5 Files (*.h5 *.nxs *.hdf)', 'HDF5 Files (*)'] message = "Open HDF5 file" filenamelist, ffilter = PyMcaFileDialogs.getFileList(parent=parent, filetypelist=fileTypeList, message=message, getfilter=True, single=True, currentfilter=None) if len(filenamelist) < 1: return None return filenamelist[0]
def _getFilenameDialog(parent=None): """Open a dialog to select a file in a filesystem tree view. Return the selected filename.""" from PyMca5.PyMcaGui.io import PyMcaFileDialogs fileTypeList = ['HDF5 Files (*.h5 *.nxs *.hdf)', 'HDF5 Files (*)'] message = "Open HDF5 file" filenamelist, ffilter = PyMcaFileDialogs.getFileList( parent=parent, filetypelist=fileTypeList, message=message, getfilter=True, single=True, currentfilter=None) if len(filenamelist) < 1: return None return filenamelist[0]
def get4DStack(): """ Open a stack of image files in EDF or TIFF format, and return the data with metadata. :returns: legend, data, xScale, yScale, fileindex Legend and data are both ``None`` in case of failure. Scales are 2-tuples (originX, deltaX). fileindex indicates the dimension/axis in the data corresponding to the Z-axis. :raise IOError: If the data could not be read """ fileTypeList = [ 'EDF Z Stack (*edf *ccd)', 'EDF X Stack (*edf *ccd)', 'TIFF Stack (*tif *tiff)' ] old = PyMcaFileDialogs.PyMcaDirs.nativeFileDialogs * 1 PyMcaFileDialogs.PyMcaDirs.nativeFileDialogs = False fileList, filterUsed = PyMcaFileDialogs.getFileList( parent=None, filetypelist=fileTypeList, message="Please select the object file(s)", mode="OPEN", getfilter=True) PyMcaFileDialogs.PyMcaDirs.nativeFileDialogs = old if not fileList: return None, None if filterUsed.startswith('EDF Z'): fileindex = 2 else: fileindex = 1 filename = fileList[0] legend = os.path.basename(filename) if filterUsed.startswith('TIFF'): stack = TiffStack.TiffStack(dtype=numpy.float32, imagestack=False) stack.loadFileList(fileList, fileindex=1) else: stack = EDFStack.EDFStack(dtype=numpy.float32, imagestack=False) if len(fileList) == 1: stack.loadIndexedStack(filename, fileindex=fileindex) else: stack.loadFileList(fileList, fileindex=fileindex) if stack is None: raise IOError("Problem reading stack.") xScale = stack.info.get("xScale") yScale = stack.info.get("yScale") return legend, stack.data, xScale, yScale, fileindex
def get4DStack(): """ Open a stack of image files in EDF or TIFF format, and return the data with metadata. :returns: legend, data, xScale, yScale, fileindex Legend and data are both ``None`` in case of failure. Scales are 2-tuples (originX, deltaX). fileindex indicates the dimension/axis in the data corresponding to the Z-axis. :raise IOError: If the data could not be read """ fileTypeList = ['EDF Z Stack (*edf *ccd)', 'EDF X Stack (*edf *ccd)', 'TIFF Stack (*tif *tiff)'] old = PyMcaFileDialogs.PyMcaDirs.nativeFileDialogs * 1 PyMcaFileDialogs.PyMcaDirs.nativeFileDialogs = False fileList, filterUsed = PyMcaFileDialogs.getFileList( parent=None, filetypelist=fileTypeList, message="Please select the object file(s)", mode="OPEN", getfilter=True) PyMcaFileDialogs.PyMcaDirs.nativeFileDialogs = old if not fileList: return None, None if filterUsed.startswith('EDF Z'): fileindex = 2 else: fileindex = 1 filename = fileList[0] legend = os.path.basename(filename) if filterUsed.startswith('TIFF'): stack = TiffStack.TiffStack(dtype=numpy.float32, imagestack=False) stack.loadFileList(fileList, fileindex=1) else: stack = EDFStack.EDFStack(dtype=numpy.float32, imagestack=False) if len(fileList) == 1: stack.loadIndexedStack(filename, fileindex=fileindex) else: stack.loadFileList(fileList, fileindex=fileindex) if stack is None: raise IOError("Problem reading stack.") xScale = stack.info.get("xScale") yScale = stack.info.get("yScale") return legend, stack.data, xScale, yScale, fileindex
def save(self): if self.initDir is None: self.initDir = PyMcaDirs.outputDir filetypelist = ["Fit configuration files (*.cfg)"] message = "Enter ouput fit configuration file" initdir = self.initDir fileList = PyMcaFileDialogs.getFileList(parent=self, filetypelist=filetypelist, message=message, currentdir=initdir, mode="SAVE", getfilter=False, single=True, currentfilter=None, native=None) if len(fileList): filename = fileList[0] self.saveConfiguration(filename) self.initDir = os.path.dirname(filename) return
def load(self): filetypelist = ["Fit configuration files (*.cfg)"] message = "Choose fit configuration file" initdir = os.path.curdir if self.initDir is not None: if os.path.isdir(self.initDir): initdir = self.initDir fileList = PyMcaFileDialogs.getFileList(parent=self, filetypelist=filetypelist, message=message, currentdir=initdir, mode="OPEN", getfilter=False, single=True, currentfilter=None, native=None) if len(fileList): filename = fileList[0] self.loadConfiguration(filename) self.initDir = os.path.dirname(filename) return
def replace1DAxisWithASCII(self): stack = self.getStackDataObject() mcaIndex = stack.info.get('McaIndex', -1) nPoints = stack.data.shape[mcaIndex] fileList = PyMcaFileDialogs.getFileList(None, filetypelist=["ASCII files (*)"], message="Select ASCII file", mode="OPEN", getfilter=False, single=True) if not len(fileList): return filename = fileList[0] data = numpy.loadtxt(filename) data.shape = -1 if data.size != nPoints: raise ValueError("Number of read values not equal to %d" % nPoints) else: stack.x = [data] self.setStack(stack, mcaindex=mcaIndex)
def _loadExternalData(self): getfilter = True fileTypeList = ["EDF Files (*edf *ccd *tif)"] if HDF5: fileTypeList.append('HDF5 Files (*.h5 *.nxs *.hdf *.hdf5)') fileTypeList.append('ASCII Files (*)') fileTypeList.append("EDF Files (*)") message = "Open data file" filenamelist, ffilter = PyMcaFileDialogs.getFileList( parent=None, filetypelist=fileTypeList, message=message, getfilter=getfilter, single=True, currentfilter=None) if len(filenamelist) < 1: return filename = filenamelist[0] if ffilter.startswith('HDF5'): data = HDF5Widget.getDatasetValueDialog( filename=filename, message='Select your data set by a double click') elif ffilter.startswith("EDF"): edf = EdfFile.EdfFile(filename, "rb") if edf.GetNumImages() > 1: # TODO: A dialog showing the different images # based on the external images browser needed _logger.warning("WARNING: Taking first image") data = edf.GetData(0) edf = None elif ffilter.startswith("ASCII"): #data=numpy.loadtxt(filename) sf = specfilewrapper.Specfile(filename) targetScan = sf[0] data = numpy.array(targetScan.data().T, copy=True) targetScan = None sf = None return data
def getConfigurationFilePath(parent=None, filetypelist=None, message=None, currentdir=None, mode="OPEN", getfilter=None, single=True, currentfilter=None, native=None): if filetypelist is None: filetypelist = ["Configuration from .ini files (*.ini)"] if HAS_H5PY: filetypelist.append( "Configuration from HDF5 file (*%s)" % " *".join(_HDF5_EXTENSIONS)) filetypelist.append("All files (*)") if message is None: message = "Choose configuration file" fileList = PyMcaFileDialogs.getFileList(parent=parent, filetypelist=filetypelist, message=message, currentdir=currentdir, mode="OPEN", # input ignored getfilter=getfilter, single=single, currentfilter=currentfilter, native=native) if getfilter: fileList, usedfilter = fileList if HAS_H5PY: newList = [] for filename in fileList: if is_hdf5(filename): # we have to select a dataset msg = 'Select the configuration dataset by a double click' uri = getDatasetUri(parent=parent, filename=filename, message=msg) if uri: newList.append(uri) else: newList.append(filename) fileList = newList if getfilter: return fileList, usedfilter else: return fileList
def openFile(self, filename=None, justloaded=None, specsession=False): _logger.debug("openfile = %s", filename) staticDialog = False if specsession == "bliss": specsession = False session = filename node = RedisTools.get_node(session) if not node: txt = "No REDIS information retrieved from session %s" % \ session raise IOError(txt) filename = RedisTools.get_session_filename(node) if not len(filename): txt = "Cannot retrieve last output filename from session %s" % \ session raise IOError(txt) if not os.path.exists(filename): txt = "Last output file <%s> does not exist" % filename raise IOError(txt) filename = [filename] key = os.path.basename(filename[0]) try: self._emitSourceSelectedOrReloaded(filename, key) except: _logger.error("Problem opening %s" % filename[0]) key = "%s" % session self._emitSourceSelectedOrReloaded([session], key) return if not specsession: if justloaded is None: justloaded = True if filename is None: if self.lastInputDir is not None: if not os.path.exists(self.lastInputDir): self.lastInputDir = None wdir = self.lastInputDir filelist, fileFilter = PyMcaFileDialogs.getFileList( self, filetypelist=self.fileTypeList, message="Open a new source file", currentdir=wdir, mode="OPEN", getfilter=True, single=False, currentfilter=self.lastFileFilter) if not len(filelist): return if not len(filelist[0]): return filename = [] for f in filelist: filename.append(qt.safe_str(f)) if not len(filename): return if len(filename): self.lastInputDir = os.path.dirname(filename[0]) PyMcaDirs.inputDir = os.path.dirname(filename[0]) self.lastFileFilter = fileFilter justloaded = True if justloaded: if type(filename) != type([]): filename = [filename] if not os.path.exists(filename[0]): if '%' not in filename[0]: raise IOError("File %s does not exist" % filename[0]) #check if it is a stack if len(filename) > 1: key = "STACK from %s to %s" % (filename[0], filename[-1]) else: key = os.path.basename(filename[0]) else: key = filename if key not in sps.getspeclist(): qt.QMessageBox.critical( self, "SPS Error", "No shared memory source named %s" % key) return self._emitSourceSelectedOrReloaded(filename, key)
def _getOutputFileNameAndFilter(self, format_list=None): """ returns outputfile, file type and filter used """ # get outputfile self.outputDir = PyMcaDirs.outputDir if self.outputDir is None: self.outputDir = os.getcwd() wdir = os.getcwd() elif os.path.exists(self.outputDir): wdir = self.outputDir else: self.outputDir = os.getcwd() wdir = self.outputDir if format_list is None: format_list = ['Specfile MCA *.mca', 'Specfile Scan *.dat'] if self._plotType != "MCA": format_list += ['Specfile MultiScan *.dat'] format_list += ['Raw ASCII *.txt', '","-separated CSV *.csv', '";"-separated CSV *.csv', '"tab"-separated CSV *.csv', 'OMNIC CSV *.csv', 'Widget PNG *.png', 'Widget JPG *.jpg', 'Graphics PNG *.png', 'Graphics EPS *.eps', 'Graphics SVG *.svg'] if self.outputFilter is None: self.outputFilter = format_list[0] fileList, fileFilter = PyMcaFileDialogs.getFileList( self, filetypelist=format_list, message="Output File Selection", currentdir=wdir, single=True, mode="SAVE", getfilter=True, currentfilter=self.outputFilter) if not len(fileList): return self.outputFilter = fileFilter filterused = self.outputFilter.split() filetype = filterused[1] extension = filterused[2] outdir = qt.safe_str(fileList[0]) try: self.outputDir = os.path.dirname(outdir) PyMcaDirs.outputDir = os.path.dirname(outdir) except: self.outputDir = "." try: outputFile = os.path.basename(outdir) except: outputFile = outdir if len(outputFile) < 5: outputFile = outputFile + extension[-4:] elif outputFile[-4:] != extension[-4:]: outputFile = outputFile + extension[-4:] return os.path.join(self.outputDir, outputFile), fileFilter
def openFile(self, filename=None, justloaded=None, specsession = False): _logger.debug("openfile = %s", filename) staticDialog = False if not specsession: if justloaded is None: justloaded = True if filename is None: if self.lastInputDir is not None: if not os.path.exists(self.lastInputDir): self.lastInputDir = None wdir = self.lastInputDir filelist, fileFilter = PyMcaFileDialogs.getFileList(self, filetypelist=self.fileTypeList, message="Open a new source file", currentdir=wdir, mode="OPEN", getfilter=True, single=False, currentfilter=self.lastFileFilter) if not len(filelist): return if not len(filelist[0]): return filename=[] for f in filelist: filename.append(qt.safe_str(f)) if not len(filename): return if len(filename): self.lastInputDir = os.path.dirname(filename[0]) PyMcaDirs.inputDir = os.path.dirname(filename[0]) self.lastFileFilter = fileFilter justloaded = True if justloaded: if type(filename) != type([]): filename = [filename] if not os.path.exists(filename[0]): if '%' not in filename[0]: raise IOError("File %s does not exist" % filename[0]) #check if it is a stack if len(filename) > 1: key = "STACK from %s to %s" % (filename[0], filename[-1]) else: key = os.path.basename(filename[0]) else: key = filename if key not in sps.getspeclist(): qt.QMessageBox.critical(self, "SPS Error", "No shared memory source named %s" % key) return ddict = {} ddict["event"] = "NewSourceSelected" if key in self.mapCombo.keys(): if self.mapCombo[key] == filename: #Reloaded event ddict["event"] = "SourceReloaded" else: i = 0 while key in self.mapCombo.keys(): key += "_%d" % i ddict["combokey"] = key ddict["sourcelist"] = filename self.mapCombo[key] = filename if ddict["event"] =="NewSourceSelected": nitems = self.fileCombo.count() self.fileCombo.insertItem(nitems, key) self.fileCombo.setCurrentIndex(nitems) else: if hasattr(qt, "QString"): nitem = self.fileCombo.findText(qt.QString(key)) else: nitem = self.fileCombo.findText(key) self.fileCombo.setCurrentIndex(nitem) self.sigSourceSelectorSignal.emit(ddict)
def __addDirectory(self): directory = PyMcaFileDialogs.getExistingDirectory(self, message="Add Full Directory", mode="OPEN") if directory not in [None, ""]: self.__addInFileList("directory", directory)
def openFile(self, filename=None, justloaded=None, specsession=False): if DEBUG: print("openfile = ", filename) staticDialog = False if not specsession: if justloaded is None: justloaded = True if filename is None: if self.lastInputDir is not None: if not os.path.exists(self.lastInputDir): self.lastInputDir = None wdir = self.lastInputDir filelist, fileFilter = PyMcaFileDialogs.getFileList( self, filetypelist=self.fileTypeList, message="Open a new source file", currentdir=wdir, mode="OPEN", getfilter=True, single=False, currentfilter=self.lastFileFilter) if not len(filelist): return if not len(filelist[0]): return filename = [] for f in filelist: filename.append(qt.safe_str(f)) if not len(filename): return if len(filename): self.lastInputDir = os.path.dirname(filename[0]) PyMcaDirs.inputDir = os.path.dirname(filename[0]) self.lastFileFilter = fileFilter justloaded = True if justloaded: if type(filename) != type([]): filename = [filename] if not os.path.exists(filename[0]): if '%' not in filename[0]: raise IOError("File %s does not exist" % filename[0]) #check if it is a stack if len(filename) > 1: key = "STACK from %s to %s" % (filename[0], filename[-1]) else: key = os.path.basename(filename[0]) else: key = filename if key not in sps.getspeclist(): qt.QMessageBox.critical( self, "SPS Error", "No shared memory source named %s" % key) return ddict = {} ddict["event"] = "NewSourceSelected" if key in self.mapCombo.keys(): if self.mapCombo[key] == filename: #Reloaded event ddict["event"] = "SourceReloaded" else: i = 0 while key in self.mapCombo.keys(): key += "_%d" % i ddict["combokey"] = key ddict["sourcelist"] = filename self.mapCombo[key] = filename if ddict["event"] == "NewSourceSelected": nitems = self.fileCombo.count() self.fileCombo.insertItem(nitems, key) self.fileCombo.setCurrentIndex(nitems) else: if hasattr(qt, "QString"): nitem = self.fileCombo.findText(qt.QString(key)) else: nitem = self.fileCombo.findText(key) self.fileCombo.setCurrentIndex(nitem) self.sigSourceSelectorSignal.emit(ddict)
def browseOutputDir(self): f = PyMcaFileDialogs.getExistingDirectory(parent=self, message="Please select output directory", mode="OPEN") if len(f): self._outdirLine.setText(f)
def _loadImageFiles(self): if self.getStackDataObject() is None: return getfilter = True fileTypeList = [ "PNG Files (*png)", "JPEG Files (*jpg *jpeg)", "IMAGE Files (*)", "DAT Files (*dat)", "CSV Files (*csv)", "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 not filenamelist: return imagelist = [] imagenames = [] mask = self.getStackSelectionMask() if mask is None: r, n = self.getStackROIImagesAndNames() shape = r[0].shape else: shape = mask.shape extension = qt.safe_str(os.path.splitext(filenamelist[0])[1]) if filefilter.startswith("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 or data.shape[1] not in shape: # print("Ignoring %s (inconsistent shape)" % key) continue imagename = dataObject.info.get('Title', "") if imagename != "": imagename += " " imagename += os.path.basename(filename) + " " + key imagelist.append(data) imagenames.append(imagename) if not imagelist: msg = qt.QMessageBox(None) msg.setIcon(qt.QMessageBox.Critical) msg.setText("Cannot read a valid image from the file") msg.exec_() return elif extension.lower() in [".csv", ".dat"]: # what to do if more than one file selected ? from PyMca5.PyMca import specfilewrapper as Specfile sf = Specfile.Specfile(filenamelist[0]) scan = sf[0] labels = scan.alllabels() data = scan.data() scan = None sf = None if "column" in labels: offset = labels.index("column") ncols = int(data[offset].max() + 1) offset += 1 else: raise IOError("Only images exported as csv supported") imagelist = [] imagenames = [] for i in range(offset, len(labels)): if labels[i].startswith("s("): continue tmpData = data[i] tmpData.shape = -1, ncols imagelist.append(tmpData) imagenames.append(labels[i]) 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 not imagelist: msg = qt.QMessageBox(None) msg.setIcon(qt.QMessageBox.Critical) msg.setText("Cannot read a valid image from the file") msg.exec_() return for i, image in enumerate(imagelist): imagelist[i] = self.qImageToRgba(image) image_shape = self._getStackImageShape() origin, delta = self._getStackOriginDelta() h = delta[1] * image_shape[0] w = delta[0] * image_shape[1] for bgimg, bglabel in zip(imagelist, imagenames): if bglabel not in self.windows: self.windows[ bglabel] = SilxExternalImagesWindow.SilxExternalImagesWindow( ) self.windows[bglabel].sigMaskImageWidget.connect( self.onWidgetSignal) self.windows[bglabel].show() # add the stack image for mask operation self.windows[bglabel].setImages([self.getStackOriginalImage()], labels=["stack data"], origin=origin, width=w, height=h) self.windows[bglabel].plot.getImage("current").setAlpha(0) # add the external image self.windows[bglabel].setBackgroundImages([bgimg], labels=[bglabel], origins=[origin], widths=[w], heights=[h]) self.windows[bglabel].plot.setGraphTitle(bglabel) self._showWidget(bglabel)
def _loadImageFiles(self): if self.getStackDataObject() is None: return getfilter = True fileTypeList = ["PNG Files (*png)", "JPEG Files (*jpg *jpeg)", "IMAGE Files (*)", "DAT Files (*dat)", "CSV Files (*csv)", "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 not filenamelist: return imagelist = [] imagenames = [] mask = self.getStackSelectionMask() if mask is None: r, n = self.getStackROIImagesAndNames() shape = r[0].shape else: shape = mask.shape extension = qt.safe_str(os.path.splitext(filenamelist[0])[1]) if filefilter.startswith("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 or data.shape[1] not in shape: # print("Ignoring %s (inconsistent shape)" % key) continue imagename = dataObject.info.get('Title', "") if imagename != "": imagename += " " imagename += os.path.basename(filename) + " " + key imagelist.append(data) imagenames.append(imagename) if not imagelist: msg = qt.QMessageBox(None) msg.setIcon(qt.QMessageBox.Critical) msg.setText("Cannot read a valid image from the file") msg.exec_() return elif extension.lower() in [".csv", ".dat"]: # what to do if more than one file selected ? from PyMca5.PyMca import specfilewrapper as Specfile sf = Specfile.Specfile(filenamelist[0]) scan = sf[0] labels = scan.alllabels() data = scan.data() scan = None sf = None if "column" in labels: offset = labels.index("column") ncols = int(data[offset].max() + 1) offset += 1 else: raise IOError("Only images exported as csv supported") imagelist = [] imagenames= [] for i in range(offset, len(labels)): if labels[i].startswith("s("): continue tmpData = data[i] tmpData.shape = -1, ncols imagelist.append(tmpData) imagenames.append(labels[i]) 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 not imagelist: msg = qt.QMessageBox(None) msg.setIcon(qt.QMessageBox.Critical) msg.setText("Cannot read a valid image from the file") msg.exec_() return for i, image in enumerate(imagelist): imagelist[i] = self.qImageToRgba(image) image_shape = self._getStackImageShape() origin, delta = self._getStackOriginDelta() h = delta[1] * image_shape[0] w = delta[0] * image_shape[1] stack_images, stack_names = self.getStackROIImagesAndNames() stack_info = self.getStackInfo() if "bgimages" not in stack_info: stack_info["bgimages"] = {} for bgimg, bglabel in zip(imagelist, imagenames): if bglabel not in self.windows: self.windows[bglabel] = SilxExternalImagesWindow.SilxExternalImagesWindow() self.windows[bglabel].sigMaskImageWidget.connect( self.onWidgetSignal) self.windows[bglabel].show() # add the stack image for mask operation self.windows[bglabel].setImages([stack_images[0]], labels=[stack_names[0]], origin=origin, width=w, height=h) self.windows[bglabel].plot.getImage("current").setAlpha(0) # add the external image self.windows[bglabel].setBackgroundImages([bgimg], labels=[bglabel], origins=[origin], widths=[w], heights=[h]) self.windows[bglabel].plot.setGraphTitle(bglabel) # also store bg images as a stack info attribute stack_info["bgimages"][bglabel] = {"data": bgimg, "origin": origin, "width": w, "height": h} self._showWidget(bglabel)