def SetSource(self, source_name=None, source_obj=None): """ Sets a new source for data retrieving, an specfile. If the file exists, self.Source will be the Specfile object associated to this file. Parameters: source_name: name of the specfile """ if source_name == self.SourceName: return 1 if source_name is not None: if source_obj is not None: self.Source = source_obj else: try: self.Source = specfile.Specfile(source_name) except: self.Source = None else: self.Source = None self.SourceInfo = None if self.Source is None: self.SourceName = None return 0 else: self.SourceName = source_name return 1
def loadTransmissionTable(self, filename): # read with our wrapper sf = specfile.Specfile(filename) scan = sf[0] data = scan.data() labels = scan.alllabels() scan = None sf = None nLabels = len(labels) if nLabels not in [2, 3]: txt = "Expected a two column file got %d columns" % nLabels raise IOError(txt) if nLabels == 3 and labels[0].lower().startswith("point"): energyIdx = 1 transmissionIdx = 2 else: energyIdx = 0 transmissionIdx = 1 # sort energies in ascending order energy = data[energyIdx, :] transmission = data[transmissionIdx, :] idx = numpy.argsort(energy) energy = numpy.take(energy, idx) transmission = numpy.take(transmission, idx) ddict = {} ddict["use"] = 1 ddict["energy"] = energy ddict["transmission"] = transmission ddict["name"] = os.path.basename(filename) ddict["comment"] = "" self.setTransmissionTable(ddict, updating=True)
def __init__(self, fname=None, cntx=1, cnty=None, csig=None, cmon=None, csec=None, norm=None): """reads the given specfile""" if (fname == 'DUMMY!'): return if (HAS_SPECFILE is False): print("WARNING: 'specfile' is missing -> check requirements!") return if (fname is None): raise NameError("Provide a SPEC data file to load with full path") elif not os.path.isfile(fname): raise OSError("File not found: '%s'" % fname) else: self.fname = fname if hasattr(self, 'sf'): pass else: self.sf = specfile.Specfile(fname) #sf = specfile file print("Loaded SPEC file: {0}".format(fname)) # print("The total number of scans is: {0}".format(self.sf.scanno()) #if HAS_SIMPLEMATH: self.sm = SimpleMath.SimpleMath() #set common attributes self.cntx = cntx self.cnty = cnty self.csig = csig self.cmon = cmon self.csec = csec self.norm = norm
def compute(self): fileName = xoppy_calc_xxcom(NAME=self.NAME, SUBSTANCE=self.SUBSTANCE, DESCRIPTION=self.DESCRIPTION, FRACTION=self.FRACTION, GRID=self.GRID, GRIDINPUT=self.GRIDINPUT, GRIDDATA=self.GRIDDATA, ELEMENTOUTPUT=self.ELEMENTOUTPUT) #send specfile if fileName == None: print("Nothing to send") else: self.send("xoppy_specfile", fileName) sf = specfile.Specfile(fileName) if sf.scanno() == 1: #load spec file with one scan, # is comment print("Loading file: ", fileName) out = np.loadtxt(fileName) print("data shape: ", out.shape) #get labels txt = open(fileName).readlines() tmp = [line.find("#L") for line in txt] itmp = np.where(np.array(tmp) != (-1)) labels = txt[itmp[0]].replace("#L ", "").split(" ") print("data labels: ", labels) self.send("xoppy_data", out) else: print( "File %s contains %d scans. Cannot send it as xoppy_table" % (fileName, sf.scanno()))
def compute(self): fileName = xoppy_calc_xtubes(ITUBE=self.ITUBE, VOLTAGE=self.VOLTAGE) #send specfile if fileName == None: print("Nothing to send") else: self.send("xoppy_specfile", fileName) sf = specfile.Specfile(fileName) if sf.scanno() == 1: #load spec file with one scan, # is comment print("Loading file: ", fileName) out = np.loadtxt(fileName) print("data shape: ", out.shape) #get labels txt = open(fileName).readlines() tmp = [line.find("#L") for line in txt] itmp = np.where(np.array(tmp) != (-1)) labels = txt[itmp[0]].replace("#L ", "").split(" ") print("data labels: ", labels) self.send("xoppy_data", out) else: print( "File %s contains %d scans. Cannot send it as xoppy_table" % (fileName, sf.scanno()))
def generateXRFData(nRows=5, nColumns=10, nDet=1, nTimes=3, presetTime=1, same=True): """ :param int nRows: :param int nColumns: :param int nDet: :param int nTimes: number of different live times :param int presetTime: exposure time for each spectrum :param bool same: same spectrum in all pixels (add pixel index as constant background otherwise) :returns: data(nRows, nColumns, nChannels), liveTime(nRows*nColumns) """ from PyMca5.PyMcaDataDir import PYMCA_DATA_DIR as dataDir from PyMca5.PyMcaIO import specfilewrapper as specfile spe = os.path.join(dataDir, "Steel.spe") sf = specfile.Specfile(spe) counts = sf[0].mca(1).astype(numpy.int32) #counts = numpy.arange(counts.size, dtype=int) # for testing data = numpy.zeros((nDet, nRows, nColumns, counts.size), dtype=counts.dtype) liveTime = numpy.zeros((nDet, nRows, nColumns), dtype=numpy.float64) nTimes *= nDet initialTime = presetTime mcaIndex = 0 for i in range(nRows): for j in range(nColumns): for k in range(nDet): if same: data[k, i, j] = counts else: data[k, i, j] = counts + mcaIndex*nDet + k liveTime[k, i, j] = initialTime * (1 + mcaIndex % nTimes)/float(nTimes) mcaIndex += 1 return data, liveTime
def compute(self): fileName = xoppy_calc_xraylib_widget(FUNCTION=self.FUNCTION,ELEMENT=self.ELEMENT,ELEMENTORCOMPOUND=self.ELEMENTORCOMPOUND,COMPOUND=self.COMPOUND,TRANSITION_IUPAC_OR_SIEGBAHN=self.TRANSITION_IUPAC_OR_SIEGBAHN,TRANSITION_IUPAC_TO=self.TRANSITION_IUPAC_TO,TRANSITION_IUPAC_FROM=self.TRANSITION_IUPAC_FROM,TRANSITION_SIEGBAHN=self.TRANSITION_SIEGBAHN,SHELL=self.SHELL,ENERGY=self.ENERGY) #send specfile if fileName == None: print("Nothing to send") else: self.send("xoppy_specfile",fileName) sf = specfile.Specfile(fileName) if sf.scanno() == 1: #load spec file with one scan, # is comment print("Loading file: ",fileName) out = np.loadtxt(fileName) print("data shape: ",out.shape) #get labels txt = open(fileName).readlines() tmp = [ line.find("#L") for line in txt] itmp = np.where(np.array(tmp) != (-1)) labels = txt[itmp[0]].replace("#L ","").split(" ") print("data labels: ",labels) # # build and send orange table # domain = Domain([ ContinuousVariable(i) for i in labels ]) table = Table.from_numpy(domain, out) self.send("xoppy_table",table) else: print("File %s contains %d scans. Cannot send it as xoppy_table"%(fileName,sf.scanno()))
def compute(self): fileName = xoppy_calc_xbfield(PERIOD=self.PERIOD, NPER=self.NPER, NPTS=self.NPTS, IMAGNET=self.IMAGNET, ITYPE=self.ITYPE, K=self.K, GAP=self.GAP, GAPTAP=self.GAPTAP, FILE=self.FILE) #send specfile if fileName == None: print("Nothing to send") else: self.send("xoppy_specfile", fileName) sf = specfile.Specfile(fileName) if sf.scanno() == 1: #load spec file with one scan, # is comment print("Loading file: ", fileName) out = np.loadtxt(fileName) print("data shape: ", out.shape) #get labels txt = open(fileName).readlines() tmp = [line.find("#L") for line in txt] itmp = np.where(np.array(tmp) != (-1)) labels = txt[itmp[0]].replace("#L ", "").split(" ") print("data labels: ", labels) self.send("xoppy_data", out) else: print( "File %s contains %d scans. Cannot send it as xoppy_table" % (fileName, sf.scanno()))
def testSimpleSpecfileVersusPyMca(self): import glob import PyMca5 from PyMca5 import PyMcaDataDir from PyMca5.PyMcaIO import specfilewrapper as Specfile fileList = glob.glob( os.path.join(PyMcaDataDir.PYMCA_DATA_DIR, '*.dat')) self.testSimpleSpecfileImport() for filename in fileList: self._sf = self.specfileClass(filename) a = self._sf nScans = a.getNumberOfScans() sf = Specfile.Specfile(filename) for i in range(nScans): scan = sf[i] if PyMca5.version() > "5.1.1": # previous versions of PyMca5 could segfault here labels0 = a.getScanLabels(i) labels1 = scan.alllabels() for j in range(len(labels0)): self.assertEqual(labels0[j], labels1[j], "Read <%s> instead of <%s>" %\ (labels0[j], labels1[j])) data0 = a.getScanData(i) data1 = scan.data().T M = abs(data0 - data1).max() if M > 1.0e-8: raise ValueError("Error reading data")
def testSimpleSpecfileVersusPyMca(self): import glob try: from PyMca5 import PyMcaDataDir from PyMca5.PyMcaIO import specfilewrapper as Specfile except ImportError: print("\n ****** Skipping: PyMca not installed ******* \n") return fileList = glob.glob(os.path.join(PyMcaDataDir.PYMCA_DATA_DIR, '*.dat')) self.testSimpleSpecfileImport() for filename in fileList: self._sf = self.specfileClass(filename) a = self._sf nScans = a.getNumberOfScans() sf = Specfile.Specfile(filename) for i in range(nScans): scan = sf[i] labels0 = a.getScanLabels(i) labels1 = scan.alllabels() for j in range(len(labels0)): self.assertEqual(labels0[j], labels1[j], "Read <%s> instead of <%s>" %\ (labels0[j], labels1[j])) data0 = a.getScanData(i) data1 = scan.data().T M = abs(data0 - data1).max() if M > 1.0e-8: raise ValueError("Error reading data")
def _loadFromFile(self): stack = self.getStackDataObject() if stack is None: return mcaIndex = stack.info.get('McaIndex') if not (mcaIndex in [0, -1, 2]): raise IndexError("1D index must be 0, 2, or -1") # test io dependencies if h5py is None: filefilter = [] else: filefilter = ['HDF5 (*.h5 *.nxs *.hdf *.hdf5)'] filefilter.append('CSV (*.csv *.txt)') if silx_open is not None: filefilter.append('Any (*)') filename, ffilter = PyMcaFileDialogs.\ getFileList(parent=None, filetypelist=filefilter, message='Load', mode='OPEN', single=True, getfilter=True, currentfilter=filefilter[0]) if len(filename): if DEBUG: print("file name = %s file filter = %s" % (filename, ffilter)) else: if DEBUG: print("nothing selected") return filename = filename[0] positioners = {} if not ffilter.startswith('CSV'): h5GroupName = getGroupNameDialog(filename) if h5GroupName is None: return with h5open(filename) as h5f: h5Group = h5f[h5GroupName] positioners = {} for dsname in h5Group: # links and subgroups just ignored for the time being if not is_dataset(h5Group[dsname]): continue positioners[dsname] = h5Group[dsname][()] else: sf = specfilewrapper.Specfile(filename) scan = sf[0] labels = scan.alllabels() data = scan.data() scan = None sf = None for i, label in enumerate(labels): positioners[label] = data[i, :] self._stackWindow.setPositioners(positioners)
def compute(self): fileName = xoppy_calc_xurgent(TITLE=self.TITLE, ENERGY=self.ENERGY, CUR=self.CUR, SIGX=self.SIGX, SIGY=self.SIGY, SIGX1=self.SIGX1, SIGY1=self.SIGY1, ITYPE=self.ITYPE, PERIOD=self.PERIOD, N=self.N, KX=self.KX, KY=self.KY, PHASE=self.PHASE, EMIN=self.EMIN, EMAX=self.EMAX, NENERGY=self.NENERGY, D=self.D, XPC=self.XPC, YPC=self.YPC, XPS=self.XPS, YPS=self.YPS, NXP=self.NXP, NYP=self.NYP, MODE=self.MODE, ICALC=self.ICALC, IHARM=self.IHARM, NPHI=self.NPHI, NSIG=self.NSIG, NALPHA=self.NALPHA, DALPHA=self.DALPHA, NOMEGA=self.NOMEGA, DOMEGA=self.DOMEGA) #send specfile if fileName == None: print("Nothing to send") else: self.send("xoppy_specfile", fileName) sf = specfile.Specfile(fileName) if sf.scanno() == 1: #load spec file with one scan, # is comment print("Loading file: ", fileName) out = np.loadtxt(fileName) print("data shape: ", out.shape) #get labels txt = open(fileName).readlines() tmp = [line.find("#L") for line in txt] itmp = np.where(np.array(tmp) != (-1)) labels = txt[itmp[0]].replace("#L ", "").split(" ") print("data labels: ", labels) self.send("xoppy_data", out) else: print( "File %s contains %d scans. Cannot send it as xoppy_table" % (fileName, sf.scanno()))
def refresh(self): self._sourceObjectList=[] self.__fileHeaderList = [] for name in self.__sourceNameList: if not os.path.exists(name): raise ValueError("File %s does not exists" % name) for name in self.__sourceNameList: self._sourceObjectList.append(specfile.Specfile(name)) self.__fileHeaderList.append(False) self.__lastKeyInfo = {}
def __init__(self, spec_file='/home/qiu/data/ma4171/sixcvertical.spec'): self.spec_file = spec_file self.scan_selector = specfilewrapper.Specfile(spec_file) self.motor_angles = {} self.trans = 1 self.mon = 1 self.potential = None self.current = None self.scan_no = None self.frame_no = None
def compute(self): fileName = xoppy_calc_xtc(TITLE=self.TITLE, ENERGY=self.ENERGY, CUR=self.CUR, SIGE=self.SIGE, TEXT_MACHINE=self.TEXT_MACHINE, SIGX=self.SIGX, SIGY=self.SIGY, SIGX1=self.SIGX1, SIGY1=self.SIGY1, TEXT_BEAM=self.TEXT_BEAM, PERIOD=self.PERIOD, NP=self.NP, TEXT_UNDULATOR=self.TEXT_UNDULATOR, EMIN=self.EMIN, EMAX=self.EMAX, N=self.N, TEXT_ENERGY=self.TEXT_ENERGY, IHMIN=self.IHMIN, IHMAX=self.IHMAX, IHSTEP=self.IHSTEP, TEXT_HARM=self.TEXT_HARM, IHEL=self.IHEL, METHOD=self.METHOD, IK=self.IK, NEKS=self.NEKS, TEXT_PARM=self.TEXT_PARM, RUN_MODE_NAME=self.RUN_MODE_NAME) #send specfile if fileName == None: print("Nothing to send") else: self.send("xoppy_specfile", fileName) sf = specfile.Specfile(fileName) if sf.scanno() == 1: #load spec file with one scan, # is comment print("Loading file: ", fileName) out = np.loadtxt(fileName) print("data shape: ", out.shape) #get labels txt = open(fileName).readlines() tmp = [line.find("#L") for line in txt] itmp = np.where(np.array(tmp) != (-1)) labels = txt[itmp[0]].replace("#L ", "").split(" ") print("data labels: ", labels) self.send("xoppy_data", out) else: print( "File %s contains %d scans. Cannot send it as xoppy_table" % (fileName, sf.scanno()))
def set_params(self, E_keV=0.0, cen=(0, 0), pixelsize=(0, 0), sdd=0.0, spec_filename="", edf_path=""): self.E_keV = E_keV self.wavelength = 12.39854 * self.E_keV self.k0 = 2. * np.pi / self.wavelength self.cen = cen self.pixelsize = pixelsize self.sdd = sdd self.spec = specfilewrapper.Specfile(spec_filename) self.img_loader = edf_image.edf_image_loader(spec_filename, edf_path)
def testStackFastFit(self): # TODO: this is done in PyMcaBatchTest on multiple input formats # so not needed here return from PyMca5.PyMcaIO import specfilewrapper as specfile from PyMca5.PyMcaIO import ConfigDict from PyMca5.PyMcaCore import DataObject spe = os.path.join(self.dataDir, "Steel.spe") cfg = os.path.join(self.dataDir, "Steel.cfg") sf = specfile.Specfile(spe) self.assertTrue(len(sf) == 1, "File %s cannot be read" % spe) self.assertTrue(sf[0].nbmca() == 1, "Spe file should contain MCA data") counts = sf[0].mca(1) channels = numpy.arange(counts.size) sf = None configuration = ConfigDict.ConfigDict() configuration.read(cfg) calibration = configuration["detector"]["zero"], \ configuration["detector"]["gain"], 0.0 initialTime = configuration["concentrations"]["time"] # Fit MCA data with different dimensions: vector, image, stack for ndim in [1, 2, 3]: # create the data imgShape = tuple(range(3, 3 + ndim)) data = numpy.tile(counts, imgShape + (1, )) nTimes = 3 live_time = numpy.arange(numpy.prod(imgShape), dtype=int) live_time = initialTime + (live_time % nTimes) * initialTime # create the stack data object stack = DataObject.DataObject() stack.data = data stack.info = {} stack.info["McaCalib"] = calibration stack.info["McaLiveTime"] = live_time stack.x = [channels] # Test the fast XRF # we need to make sure we use fundamental parameters and # the time read from the file configuration["concentrations"]["usematrix"] = 0 configuration["concentrations"]["useautotime"] = 1 # make sure we use the SNIP background configuration['fit']['stripalgorithm'] = 1 self._verifyFastFit(stack, configuration, live_time, nTimes)
def compute(self): fileName = xoppy_calc_xfilter(EMPTY1=self.EMPTY1, EMPTY2=self.EMPTY2, NELEMENTS=self.NELEMENTS, SOURCE=self.SOURCE, ENER_MIN=self.ENER_MIN, ENER_MAX=self.ENER_MAX, ENER_N=self.ENER_N, SOURCE_FILE=self.SOURCE_FILE, EL1_SYM=self.EL1_SYM, EL1_THI=self.EL1_THI, EL2_SYM=self.EL2_SYM, EL2_THI=self.EL2_THI, EL3_SYM=self.EL3_SYM, EL3_THI=self.EL3_THI, EL4_SYM=self.EL4_SYM, EL4_THI=self.EL4_THI, EL5_SYM=self.EL5_SYM, EL5_THI=self.EL5_THI) #send specfile if fileName == None: print("Nothing to send") else: self.send("xoppy_specfile", fileName) sf = specfile.Specfile(fileName) if sf.scanno() == 1: #load spec file with one scan, # is comment print("Loading file: ", fileName) out = np.loadtxt(fileName) print("data shape: ", out.shape) #get labels txt = open(fileName).readlines() tmp = [line.find("#L") for line in txt] itmp = np.where(np.array(tmp) != (-1)) labels = txt[itmp[0]].replace("#L ", "").split(" ") print("data labels: ", labels) self.send("xoppy_data", out) else: print( "File %s contains %d scans. Cannot send it as xoppy_table" % (fileName, sf.scanno()))
def compute(self): fileName = xoppy_calc_ws(TITLE=self.TITLE, ENERGY=self.ENERGY, CUR=self.CUR, PERIOD=self.PERIOD, N=self.N, KX=self.KX, KY=self.KY, EMIN=self.EMIN, EMAX=self.EMAX, NEE=self.NEE, D=self.D, XPC=self.XPC, YPC=self.YPC, XPS=self.XPS, YPS=self.YPS, NXP=self.NXP, NYP=self.NYP) #send specfile if fileName == None: print("Nothing to send") else: self.send("xoppy_specfile", fileName) sf = specfile.Specfile(fileName) if sf.scanno() == 1: #load spec file with one scan, # is comment print("Loading file: ", fileName) out = np.loadtxt(fileName) print("data shape: ", out.shape) #get labels txt = open(fileName).readlines() tmp = [line.find("#L") for line in txt] itmp = np.where(np.array(tmp) != (-1)) labels = txt[itmp[0]].replace("#L ", "").split(" ") print("data labels: ", labels) self.send("xoppy_data", out) else: print( "File %s contains %d scans. Cannot send it as xoppy_table" % (fileName, sf.scanno()))
def compute(self): fileName = xoppy_calc_bm(TYPE_CALC=self.TYPE_CALC, MACHINE_NAME=self.MACHINE_NAME, RB_CHOICE=self.RB_CHOICE, MACHINE_R_M=self.MACHINE_R_M, BFIELD_T=self.BFIELD_T, BEAM_ENERGY_GEV=self.BEAM_ENERGY_GEV, CURRENT_A=self.CURRENT_A, HOR_DIV_MRAD=self.HOR_DIV_MRAD, VER_DIV=self.VER_DIV, PHOT_ENERGY_MIN=self.PHOT_ENERGY_MIN, PHOT_ENERGY_MAX=self.PHOT_ENERGY_MAX, NPOINTS=self.NPOINTS, LOG_CHOICE=self.LOG_CHOICE, PSI_MRAD_PLOT=self.PSI_MRAD_PLOT, PSI_MIN=self.PSI_MIN, PSI_MAX=self.PSI_MAX, PSI_NPOINTS=self.PSI_NPOINTS) #send specfile if fileName == None: print("Nothing to send") else: self.send("xoppy_specfile", fileName) sf = specfile.Specfile(fileName) if sf.scanno() == 1: #load spec file with one scan, # is comment print("Loading file: ", fileName) out = np.loadtxt(fileName) print("data shape: ", out.shape) #get labels txt = open(fileName).readlines() tmp = [line.find("#L") for line in txt] itmp = np.where(np.array(tmp) != (-1)) labels = txt[itmp[0]].replace("#L ", "").split(" ") print("data labels: ", labels) self.send("xoppy_data", out) else: print( "File %s contains %d scans. Cannot send it as xoppy_table" % (fileName, sf.scanno()))
def compute(self): fileName = xoppy_calc_xf1f2(DATASETS=self.DATASETS, MAT_FLAG=self.MAT_FLAG, MAT_LIST=self.MAT_LIST, DESCRIPTOR=self.DESCRIPTOR, DENSITY=self.DENSITY, CALCULATE=self.CALCULATE, GRID=self.GRID, GRIDSTART=self.GRIDSTART, GRIDEND=self.GRIDEND, GRIDN=self.GRIDN, THETAGRID=self.THETAGRID, ROUGH=self.ROUGH, THETA1=self.THETA1, THETA2=self.THETA2, THETAN=self.THETAN) #send specfile if fileName == None: print("Nothing to send") else: self.send("xoppy_specfile", fileName) sf = specfile.Specfile(fileName) if sf.scanno() == 1: #load spec file with one scan, # is comment print("Loading file: ", fileName) out = np.loadtxt(fileName) print("data shape: ", out.shape) #get labels txt = open(fileName).readlines() tmp = [line.find("#L") for line in txt] itmp = np.where(np.array(tmp) != (-1)) labels = txt[itmp[0]].replace("#L ", "").split(" ") print("data labels: ", labels) self.send("xoppy_data", out) else: print( "File %s contains %d scans. Cannot send it as xoppy_table" % (fileName, sf.scanno()))
def compute(self): fileName = xoppy_calc_mlayer(MODE=self.MODE, SCAN=self.SCAN, F12_FLAG=self.F12_FLAG, SUBSTRATE=self.SUBSTRATE, ODD_MATERIAL=self.ODD_MATERIAL, EVEN_MATERIAL=self.EVEN_MATERIAL, ENERGY=self.ENERGY, THETA=self.THETA, SCAN_STEP=self.SCAN_STEP, NPOINTS=self.NPOINTS, ODD_THICKNESS=self.ODD_THICKNESS, EVEN_THICKNESS=self.EVEN_THICKNESS, NLAYERS=self.NLAYERS, FILE=self.FILE) #send specfile if fileName == None: print("Nothing to send") else: self.send("xoppy_specfile", fileName) sf = specfile.Specfile(fileName) if sf.scanno() == 1: #load spec file with one scan, # is comment print("Loading file: ", fileName) out = np.loadtxt(fileName) print("data shape: ", out.shape) #get labels txt = open(fileName).readlines() tmp = [line.find("#L") for line in txt] itmp = np.where(np.array(tmp) != (-1)) labels = txt[itmp[0]].replace("#L ", "").split(" ") print("data labels: ", labels) self.send("xoppy_data", out) else: print( "File %s contains %d scans. Cannot send it as xoppy_table" % (fileName, sf.scanno()))
def compute(self): fileName = xoppy_calc_xcrystal(FILEF0=self.FILEF0,FILEF1F2=self.FILEF1F2,FILECROSSSEC=self.FILECROSSSEC,CRYSTAL_MATERIAL=self.CRYSTAL_MATERIAL,MILLER_INDEX_H=self.MILLER_INDEX_H,MILLER_INDEX_K=self.MILLER_INDEX_K,MILLER_INDEX_L=self.MILLER_INDEX_L,I_ABSORP=self.I_ABSORP,TEMPER=self.TEMPER,MOSAIC=self.MOSAIC,GEOMETRY=self.GEOMETRY,SCAN=self.SCAN,UNIT=self.UNIT,SCANFROM=self.SCANFROM,SCANTO=self.SCANTO,SCANPOINTS=self.SCANPOINTS,ENERGY=self.ENERGY,ASYMMETRY_ANGLE=self.ASYMMETRY_ANGLE,THICKNESS=self.THICKNESS,MOSAIC_FWHM=self.MOSAIC_FWHM,RSAG=self.RSAG,RMER=self.RMER,ANISOTROPY=self.ANISOTROPY,POISSON=self.POISSON,CUT=self.CUT,FILECOMPLIANCE=self.FILECOMPLIANCE) #send specfile if fileName == None: print("Nothing to send") else: self.send("xoppy_specfile",fileName) sf = specfile.Specfile(fileName) if sf.scanno() == 1: #load spec file with one scan, # is comment print("Loading file: ",fileName) out = np.loadtxt(fileName) print("data shape: ",out.shape) #get labels txt = open(fileName).readlines() tmp = [ line.find("#L") for line in txt] itmp = np.where(np.array(tmp) != (-1)) labels = txt[itmp[0]].replace("#L ","").split(" ") print("data labels: ",labels) self.send("xoppy_data",out) else: print("File %s contains %d scans. Cannot send it as xoppy_table"%(fileName,sf.scanno()))
def compute(self): fileName = xoppy_calc_nsources(TEMPERATURE=self.TEMPERATURE,ZONE=self.ZONE,MAXFLUX_F=self.MAXFLUX_F,MAXFLUX_EPI=self.MAXFLUX_EPI,MAXFLUX_TH=self.MAXFLUX_TH,NPOINTS=self.NPOINTS) #send specfile if fileName == None: print("Nothing to send") else: self.send("xoppy_specfile",fileName) sf = specfile.Specfile(fileName) if sf.scanno() == 1: #load spec file with one scan, # is comment print("Loading file: ",fileName) out = np.loadtxt(fileName) print("data shape: ",out.shape) #get labels txt = open(fileName).readlines() tmp = [ line.find("#L") for line in txt] itmp = np.where(np.array(tmp) != (-1)) labels = txt[itmp[0]].replace("#L ","").split(" ") print("data labels: ",labels) self.send("xoppy_data",out) else: print("File %s contains %d scans. Cannot send it as xoppy_table"%(fileName,sf.scanno()))
def compute(self): fileName = xoppy_calc_xfh(FILEF0=self.FILEF0,FILEF1F2=self.FILEF1F2,FILECROSSSEC=self.FILECROSSSEC,ILATTICE=self.ILATTICE,HMILLER=self.HMILLER,KMILLER=self.KMILLER,LMILLER=self.LMILLER,I_ABSORP=self.I_ABSORP,TEMPER=self.TEMPER,ENERGY=self.ENERGY,ENERGY_END=self.ENERGY_END,NPOINTS=self.NPOINTS) #send specfile if fileName == None: print("Nothing to send") else: self.send("xoppy_specfile",fileName) sf = specfile.Specfile(fileName) if sf.scanno() == 1: #load spec file with one scan, # is comment print("Loading file: ",fileName) out = np.loadtxt(fileName) print("data shape: ",out.shape) #get labels txt = open(fileName).readlines() tmp = [ line.find("#L") for line in txt] itmp = np.where(np.array(tmp) != (-1)) labels = txt[itmp[0]].replace("#L ","").split(" ") print("data labels: ",labels) self.send("xoppy_data",out) else: print("File %s contains %d scans. Cannot send it as xoppy_table"%(fileName,sf.scanno()))
def compute(self): fileName = xoppy_calc_xinpro(CRYSTAL_MATERIAL=self.CRYSTAL_MATERIAL, MODE=self.MODE, ENERGY=self.ENERGY, MILLER_INDEX_H=self.MILLER_INDEX_H, MILLER_INDEX_K=self.MILLER_INDEX_K, MILLER_INDEX_L=self.MILLER_INDEX_L, ASYMMETRY_ANGLE=self.ASYMMETRY_ANGLE, THICKNESS=self.THICKNESS, TEMPERATURE=self.TEMPERATURE, NPOINTS=self.NPOINTS, SCALE=self.SCALE, XFROM=self.XFROM, XTO=self.XTO) #send specfile if fileName == None: print("Nothing to send") else: self.send("xoppy_specfile", fileName) sf = specfile.Specfile(fileName) if sf.scanno() == 1: #load spec file with one scan, # is comment print("Loading file: ", fileName) out = np.loadtxt(fileName) print("data shape: ", out.shape) #get labels txt = open(fileName).readlines() tmp = [line.find("#L") for line in txt] itmp = np.where(np.array(tmp) != (-1)) labels = txt[itmp[0]].replace("#L ", "").split(" ") print("data labels: ", labels) self.send("xoppy_data", out) else: print( "File %s contains %d scans. Cannot send it as xoppy_table" % (fileName, sf.scanno()))
def compute(self): fileName = xoppy_calc_mare(CRYSTAL=self.CRYSTAL, H=self.H, K=self.K, L=self.L, HMAX=self.HMAX, KMAX=self.KMAX, LMAX=self.LMAX, FHEDGE=self.FHEDGE, DISPLAY=self.DISPLAY, LAMBDA=self.LAMBDA, DELTALAMBDA=self.DELTALAMBDA, PHI=self.PHI, DELTAPHI=self.DELTAPHI) #send specfile if fileName == None: print("Nothing to send") else: self.send("xoppy_specfile", fileName) sf = specfile.Specfile(fileName) if sf.scanno() == 1: #load spec file with one scan, # is comment print("Loading file: ", fileName) out = np.loadtxt(fileName) print("data shape: ", out.shape) #get labels txt = open(fileName).readlines() tmp = [line.find("#L") for line in txt] itmp = np.where(np.array(tmp) != (-1)) labels = txt[itmp[0]].replace("#L ", "").split(" ") print("data labels: ", labels) self.send("xoppy_data", out) else: print( "File %s contains %d scans. Cannot send it as xoppy_table" % (fileName, sf.scanno()))
def _parseDatResults(self, filename): """ :param str filename: :returns tuple: list(nparams), ndarray(nparams, nrows, ncolumns) """ from PyMca5.PyMcaIO import specfilewrapper as specfile self.assertTrue(os.path.isfile(filename), "Batch fit result file <%s> not present" % filename) sf = specfile.Specfile(filename) labels = sf[0].alllabels() scanData = sf[0].data() sf = None nParams, nPoints = scanData.shape idxRow = labels.index('row') idxColumn = labels.index('column') nRows = int(numpy.round(max(scanData[idxRow, :]))) + 1 nColumns = int(numpy.round(max(scanData[idxColumn, :]))) + 1 colfast = scanData[idxRow, 0] == scanData[idxRow, 1] if colfast: order = 'C' else: order = 'F' scanData = scanData.reshape((nParams, nRows, nColumns), order=order) return labels, scanData
def __init__(self, filename): DataObject.DataObject.__init__(self) sf = specfile.Specfile(filename) scan = sf[1] data = scan.data() nMca, nchannels = data.shape nMca = nMca - 1 xValues = data[0, :] * 1 xValues.shape = -1 if 0: self.data = numpy.zeros((nMca, nchannels), numpy.float32) self.data[:, :] = data[1:, :] self.data.shape = 1, nMca, nchannels else: self.data = data[1:, :] self.data.shape = 1, nMca, nchannels data = None #perform a least squares adjustment to a line x = numpy.arange(nchannels).astype(numpy.float32) Sxy = numpy.dot(x, xValues.T) Sxx = numpy.dot(x, x.T) Sx = x.sum() Sy = xValues.sum() d = nchannels * Sxx - Sx * Sx zero = (Sxx * Sy - Sx * Sxy) / d gain = (nchannels * Sxy - Sx * Sy) / d #and fill the requested information to be identified as a stack self.info['SourceName'] = [filename] self.info["SourceType"] = "SpecFileStack" self.info["Size"] = 1, nMca, nchannels self.info["NumberOfFiles"] = 1 self.info["FileIndex"] = 0 self.info["McaCalib"] = [zero, gain, 0.0] self.info["Channel0"] = 0.0
def _workOnBackend(self, backend): from PyMca5.PyMcaGui.physics.xrf import McaAdvancedFit from PyMca5.PyMcaGraph.Plot import Plot Plot.defaultBackend = backend widget = McaAdvancedFit.McaAdvancedFit() widget.show() self.qapp.processEvents() # read the data from PyMca5 import PyMcaDataDir dataDir = PyMcaDataDir.PYMCA_DATA_DIR from PyMca5.PyMcaIO import specfilewrapper as specfile from PyMca5.PyMcaPhysics.xrf import ClassMcaTheory from PyMca5.PyMcaPhysics.xrf import ConcentrationsTool from PyMca5.PyMcaIO import ConfigDict dataFile = os.path.join(dataDir, "Steel.spe") self.assertTrue(os.path.isfile(dataFile), "File %s is not an actual file" % dataFile) sf = specfile.Specfile(dataFile) self.assertTrue(len(sf) == 1, "File %s cannot be read" % dataFile) self.assertTrue(sf[0].nbmca() == 1, "Spe file should contain MCA data") y = counts = sf[0].mca(1) x = channels = numpy.arange(y.size).astype(numpy.float) sf = None widget.setData(x, y) self.qapp.processEvents() # read the fit configuration configFile = os.path.join(dataDir, "Steel.cfg") self.assertTrue(os.path.isfile(configFile), "File %s is not an actual file" % configFile) configuration = ConfigDict.ConfigDict() configuration.read(configFile) widget.configure(configuration) self.qapp.processEvents() time.sleep(1) # switch log axis # widget.graphWindow.yLogButton clicked isLogy0 = widget.graphWindow.isYAxisLogarithmic() self.mouseClick(widget.graphWindow.yLogButton, qt.Qt.LeftButton) self.qapp.processEvents() isLogy1 = widget.graphWindow.isYAxisLogarithmic() self.assertTrue(isLogy0 != isLogy1, "Y scale not toggled!") time.sleep(1) # reset zoom widget.graphWindow.resetZoom() # swith energy axis: # widget.graphWindow._energyIconSignal # widget.graphWindow.energyButton clicked label0 = widget.graphWindow.getGraphXLabel() self.mouseClick(widget.graphWindow.energyButton, qt.Qt.LeftButton) self.qapp.processEvents() label1 = widget.graphWindow.getGraphXLabel() self.assertTrue(label0 != label1, "Energy scale not toggled!") self.assertTrue(label0.lower() in ["channel", "energy"], "Unexpected plot X label <%s>" % label0) self.assertTrue(label1.lower() in ["channel", "energy"], "Unexpected plot X label <%s>" % label0) # reset zoom widget.graphWindow.resetZoom() # fit: # callback widget.fit # widget.graphWindow.fitButton clicked # widget.graphWindow._fitIconSignal self.assertTrue(not widget._fitdone(), "Bad fit widget state. Fit should not be finished") self.mouseClick(widget.graphWindow.fitButton, qt.Qt.LeftButton) self.qapp.processEvents() self.assertTrue(widget._fitdone(), "Bad fit widget state. Fit should be finished") # toggle matrix spectrum curveList0 = widget.graphWindow.getAllCurves(just_legend=True) self.mouseClick(widget.matrixSpectrumButton, qt.Qt.LeftButton) self.qapp.processEvents() curveList1 = widget.graphWindow.getAllCurves(just_legend=True) self.assertTrue( abs(len(curveList0) - len(curveList1)) == 1, "Matrix spectrum not working!!") # toggle peaks curveList0 = widget.graphWindow.getAllCurves(just_legend=True) for curve in ["Data", "Fit", "Continuum", "Pile-up"]: self.assertTrue(curve in curveList0, "Curve <%s> expected but not found" % curve) self.mouseClick(widget.peaksSpectrumButton, qt.Qt.LeftButton) self.qapp.processEvents() curveList1 = widget.graphWindow.getAllCurves(just_legend=True) self.assertTrue( len(curveList0) != len(curveList1), "Peaks spectrum not working!!") time.sleep(1) from PyMca5.PyMcaGui.plotting import PyMcaPrintPreview PyMcaPrintPreview.resetSingletonPrintPreview()