def importFile(self, filename): if not os.path.exists(filename): qt.QMessageBox.critical(self, "ERROR opening file", "File %s not found" % filename) return 1 Elements.Material.read(filename) error = 0 for material in list(Elements.Material.keys()): keys = list(Elements.Material[material].keys()) compoundList = [] if "CompoundList" in keys: compoundList = Elements.Material[material]["CompoundList"] if "CompoundFraction" in keys: compoundFraction = Elements.Material[material][ "CompoundFraction"] if (compoundList == []) or (compoundFraction == []): #no message? error = 1 del Elements.Material[material] continue #I should try to calculate the attenuation at one energy ... try: Elements.getMaterialMassAttenuationCoefficients( compoundList, compoundFraction, energy=10.0) except: #no message? error = 1 del Elements.Material[material] continue return error
def __init__(self, parent=None, name="Elements Info", fl=0): if qt.qVersion() < '4.0.0': qt.QWidget.__init__(self, parent, name, fl) self.setCaption(name) else: if fl == 0: qt.QWidget.__init__(self, parent) else: qt.QWidget.__init__(self, parent, fl) self.setWindowTitle(name) layout = qt.QVBoxLayout(self) layout.setMargin(0) layout.setSpacing(0) self.energyValue = None self.splitter = qt.QSplitter(self) layout.addWidget(self.splitter) self.splitter.setOrientation(qt.Qt.Horizontal) self.table = QPeriodicTable(self.splitter) self.html = ElementHtml.ElementHtml() self.infoWidget = None if qt.qVersion() < '4.0.0': self.splitter.setResizeMode(self.table, qt.QSplitter.KeepSize) self.connect(self.table, qt.PYSIGNAL("elementClicked"), self.elementClicked) else: self.table.setMinimumSize(500, 400) self.connect(self.table, qt.SIGNAL("elementClicked"), self.elementClicked) self.lastElement = None Elements.registerUpdate(self._updateCallback)
def __nameLineSlot(self): if DEBUG: print("__nameLineSlot(self)") qstring = self.__nameLine.text() text = str(qstring) if self.__toolMode: if len(text): matkey = Elements.getMaterialKey(text) if matkey is not None: self.setCurrent(matkey) #Disable everything self.__disableInput() elif text in Elements.ElementList: self.__disableInput() name = Elements.Element[text]['name'] self._current['Comment'] = name[0].upper() + name[1:] self._current['CompoundList'] = [text + "1"] self._current['CompoundFraction'] = [1.0] self._current['Density'] = Elements.Element[text]['density'] self._fillValues() self._updateCurrent() self.__nameLine.setText("%s" % text) else: self._current['Comment'] = text self.__numberSpin.setEnabled(True) self.__table.setEnabled(True) self.__densityLine.setEnabled(True) self.__thicknessLine.setEnabled(True) else: self._current['Comment'] = text
def _mySlot(self, ddict): if ddict['event'] == "returnPressed": current = str(self.currentText()) current = current.replace(' ', '') if (current == '') or (current.upper() == 'AUTO'): pass elif len(current) == 2: current = current.upper()[0] + current.lower()[1] elif len(current) == 1: current = current.upper()[0] else: msg = qt.QMessageBox(self._lineEdit) msg.setIcon(qt.QMessageBox.Critical) msg.setText("Invalid Element %s" % current) if QTVERSION < '4.0.0': msg.exec_loop() else: msg.exec_() self._lineEdit.setFocus() if not Elements.isValidFormula(current): msg = qt.QMessageBox(self._lineEdit) msg.setIcon(qt.QMessageBox.Critical) msg.setText("Invalid Element %s" % current) if QTVERSION < '4.0.0': msg.exec_loop() else: msg.exec_() self._lineEdit.setFocus() else: self.setCurrentText(current)
def __tableSlot(self, row, col): if self.__fillingValues: return if QTVERSION < '4.0.0': qstring = self.__table.text(row, col) else: item = self.__table.item(row, col) if item is not None: if DEBUG: print("table item is None") qstring = item.text() else: qstring = "" if col == 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(row, col, matkey) 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(row, col) 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(row, col) return self._updateCurrent()
def FindXrays(elsym, energy=60.0, minenergy=1.0, maxenergy=35.0, minrate=0.00010): xr=['K', 'L', 'M'] # chosenxr=[] # chosenxren=[] foundpeaks=[] allpeaksdictlist=[] eltr_quantels=[] for ele in elsym: ElDict={} PyMEl._updateElementDict(ele, ElDict, energy=energy, minenergy=minenergy, minrate=minrate) xray_en_rate=[[x, ElDict[tr]['energy'], ElDict[tr]['rate']] for x in xr for tr in ElDict['%s xrays' %x] if ElDict[tr]['energy']<maxenergy] xraytypes=set([xer[0] for xer in xray_en_rate]) totyieldlist=[] eltrlist=[] for xt in xraytypes: totyield=numpy.float32([v for k, v in PyMEl.Element[ele].iteritems() if k.startswith('omega'+xt.lower())]).sum() totyieldlist+=[totyield] en_rate=[[xer[1], xer[2]] for xer in xray_en_rate if xer[0]==xt] en_rate=numpy.float32(en_rate) enofmaxrate=en_rate[numpy.argmax(en_rate[:, 1]), 0] eltrlist+=[' '.join((ele, xt))] dt={} dt['el']=ele dt['tr']=xt dt['eltr']=' '.join((ele, xt)) dt['repen']=enofmaxrate dt['totyield']=totyield allpeaksdictlist+=[dt] # if len(xraytypes)>1: # tempstr=' and '.join(list(xraytypes)) # print 'XRF ANALYSIS PROBLEM: ', tempstr, ' transitions can be fit but only one will be chosen for', ele if len(xraytypes)==0: print 'XRF ANALYSIS PROBLEM: no valid transitions could be found for ', ele foundpeaks+=[False] else: foundpeaks+=[True] eltr_quantels+=[eltrlist[numpy.argmax(numpy.float32(totyieldlist))]] # xray_en_rate=sorted(xray_en_rate, key=operator.itemgetter(2), reverse=True) # print xray_en_rate # chosenxr+=[' '.join((ele, xray_en_rate[0][0]))] # chosenxren+=[xray_en_rate[0][1]] # return chosenxr, chosenxren, foundpeaks return allpeaksdictlist, eltr_quantels, foundpeaks
def fixup(self, qstring): if qstring is None: return None text = str(qstring) key = Elements.getMaterialKey(text) if key is not None: return qt.QString(key) else: return qstring
def _figureOfMerit(self, element, fluo, fitresult): weight = 0.0 for transitions in fluo[element]['rates'].keys(): if fluo[element]['rates'][transitions] > 0.0: if (transitions[0] == "K") and (Elements.getz(element) > 18): factor = 2.0 elif (transitions[0] == "L") and (Elements.getz(element) > 54): factor = 1.5 else: factor = 1.0 group = element + " " + transitions.split()[0] if group in fitresult['result']['groups']: fitarea = fitresult['result'][group]['fitarea'] weightHelp = fitarea * fluo[element]['rates'][transitions] * factor * \ fluo[element]['mass fraction'] if weightHelp > weight: weight = weightHelp return weight
def validate(self, qstring, pos): text = str(qstring) if text == '-': return (self.Valid, pos) try: # this test is needed even if pyflakes complains! float(text) return (self.Invalid, pos) except: pass if text.endswith(' '): return (self.Invalid, pos) if Elements.isValidFormula(text): return (self.Valid, pos) elif Elements.isValidMaterial(text): return (self.Valid, pos) else: return (self.Invalid, pos)
def _checkDensityThickness(self, text, row): try: currentDensity = float(str(self.text(row, 3))) except: currentDensity = 0.0 try: currentThickness = float(str(self.text(row, 4))) except: currentThickness = 0.0 defaultDensity = -1.0 defaultThickness = -0.1 #check if default density is there if Elements.isValidFormula(text): #check if single element if text in Elements.Element.keys(): defaultDensity = Elements.Element[text]['density'] else: elts = [ w for w in re.split('[0-9]', text) if w != ''] nbs = [ int(w) for w in re.split('[a-zA-Z]', text) if w != ''] if len(elts) == 1 and len(nbs) == 1: defaultDensity = Elements.Element[elts[0]]['density'] elif Elements.isValidMaterial(text): key = Elements.getMaterialKey(text) if key is not None: if 'Density' in Elements.Material[key]: defaultDensity = Elements.Material[key]['Density'] if 'Thickness' in Elements.Material[key]: defaultThickness = Elements.Material[key]['Thickness'] if defaultDensity >= 0.0: self.setText(row, 3, "%g" % defaultDensity) elif currentDensity <= 0: # should not be better to raise an exception if the # entered density or thickness were negative? self.setText(row, 3, "%g" % 1.0) if defaultThickness >= 0.0: self.setText(row, 4, "%g" % defaultThickness) elif currentThickness <= 0.0: # should not be better to raise an exception if the # entered density or thickness were negative? self.setText(row, 4, "%g" % 0.1)
def setSelection(self, symbol=None): if symbol is None: if self.addnone: if qt.qVersion() < '4.0.0': self.setCurrentItem(0) else: self.setCurrentIndex(0) else: idx = self.addnone + Elements.getz(symbol) - 1 if qt.qVersion() < '4.0.0': self.setCurrentItem(idx) else: self.setCurrentIndex(idx)
def _transmissionSlot(self, ddict): try: compoundList = ddict['CompoundList'] fractionList = ddict['CompoundFraction'] density = ddict['Density'] thickness = ddict.get('Thickness', 0.1) energy = numpy.arange(1, 100, 0.1) data = Elements.getMaterialTransmission(compoundList, fractionList, energy, density=density, thickness=thickness, listoutput=False) addButton = False if self.graph is None and (SCANWINDOW): self.graphDialog = qt.QDialog(self) self.graphDialog.mainLayout = qt.QVBoxLayout(self.graphDialog) self.graphDialog.mainLayout.setMargin(0) self.graphDialog.mainLayout.setSpacing(0) self.graph = ScanWindow.ScanWindow(self.graphDialog) self.graphDialog.mainLayout.addWidget(self.graph) self.graph._togglePointsSignal() self.graph.graph.crossPicker.setEnabled(False) addButton = True elif self.graph is None: self.graphDialog = Plot1DMatplotlib.Plot1DMatplotlibDialog() self.graph = self.graphDialog.plot1DWindow addButton = True if addButton: self._addGraphDialogButton() if self.__toolMode: legend = ddict['Comment'] else: legend = str(self.matCombo.currentText()) +\ " with density = %f g/cm3" % density +\ " and thickness = %f cm" % thickness self.graph.newCurve(energy, data['transmission'], legend=legend, xlabel='Energy (keV)', ylabel='Transmission', replace=True) self.graph.setTitle(ddict['Comment']) if self.graphDialog is not None: self.graphDialog.exec_() except: msg = qt.QMessageBox(self) msg.setIcon(qt.QMessageBox.Critical) msg.setText("Error %s" % sys.exc_info()[0]) msg.exec_()
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 _massAttenuationSlot(self, ddict): try: compoundList = ddict['CompoundList'] fractionList = ddict['CompoundFraction'] energy = numpy.arange(1, 100, 0.1) data = Elements.getMaterialMassAttenuationCoefficients( compoundList, fractionList, energy) addButton = False if (self.graph is None) and SCANWINDOW: self.graphDialog = qt.QDialog(self) self.graphDialog.mainLayout = qt.QVBoxLayout(self.graphDialog) self.graphDialog.mainLayout.setMargin(0) self.graphDialog.mainLayout.setSpacing(0) self.graph = ScanWindow.ScanWindow(self.graphDialog) self.graphDialog.mainLayout.addWidget(self.graph) self.graph._togglePointsSignal() self.graph.graph.crossPicker.setEnabled(False) addButton = True elif self.graph is None: self.graphDialog = Plot1DMatplotlib.Plot1DMatplotlibDialog() self.graph = self.graphDialog.plot1DWindow addButton = True if addButton: self._addGraphDialogButton() self.graph.setTitle(ddict['Comment']) legend = 'Coherent' self.graph.newCurve(energy, numpy.array(data[legend.lower()]), legend=legend, xlabel='Energy (keV)', ylabel='Mass Att. (cm2/g)', replace=True) for legend in ['Compton', 'Photo', 'Total']: self.graph.newCurve(energy, numpy.array(data[legend.lower()]), legend=legend, xlabel='Energy (keV)', ylabel='Mass Att. (cm2/g)', replace=False) self.graph.setActiveCurve(legend + ' ' + 'Mass Att. (cm2/g)') self.graph.setTitle(ddict['Comment']) if self.graphDialog is not None: self.graphDialog.exec_() except: msg = qt.QMessageBox(self) msg.setIcon(qt.QMessageBox.Critical) msg.setText("Error %s" % sys.exc_info()[0]) msg.exec_()
def setPeaksDisabled(self, symbol): z = self.__getZ(symbol) if (z > 47) and (Elements.getomegam5('Cd') > 0.0): #we have data available to support that disabled = [] elif z > 66: #self.peaks.setDisabled(['Ka','Kb']) #disabled = ['Ka','Kb'] disabled = [] elif z > 17: #self.peaks.setDisabled(['Ka','Kb','M']) #disabled = ['Ka','Kb','M'] disabled = ['M'] elif z > 2: #self.peaks.setDisabled(['Ka','Kb','L','L1','L2','L3','M']) #disabled = ['Ka','Kb','L','L1','L2','L3','M'] disabled = ['L', 'L1', 'L2', 'L3', 'M'] else: #self.peaks.setDisabled(['K','Ka','Kb','L','L1','L2','L3','M']) #disabled = ['Ka','Kb','L','L1','L2','L3','M'] disabled = ['Ka', 'Kb', 'L', 'L1', 'L2', 'L3', 'M'] ele = symbol if self.energyValue is not None: for peak in ['K', 'Ka', 'Kb', 'L', 'L1', 'L2', 'L3', 'M']: if peak not in disabled: if peak == 'L': if Elements.Element[ele]['binding'][ 'L3'] > self.energyValue: disabled.append(peak) elif peak == 'M': if Elements.Element[ele]['binding'][ 'M5'] > self.energyValue: disabled.append(peak) elif peak == 'Ka': if Elements.Element[ele]['binding'][ 'K'] > self.energyValue: disabled.append(peak) elif peak == 'Kb': if Elements.Element[ele]['binding'][ 'K'] > self.energyValue: disabled.append(peak) elif Elements.Element[ele]['binding'][ peak] > self.energyValue: disabled.append(peak) else: pass self.peaks.setDisabled(disabled)
def myslot(self, *var, **kw): try: energy = float(str(self.energy.text())) except ValueError: msg = qt.QMessageBox(self.energy) msg.setIcon(qt.QMessageBox.Critical) msg.setText("Invalid Energy Value") if QTVERSION < '4.0.0': msg.exec_loop() else: msg.setWindowTitle("Invalid energy") msg.exec_() self.energy.setFocus() return threshold = float(str(self.threshold.text())) / 1000. lines = [] if self.k.isChecked(): lines.append('K') if self.l1.isChecked(): lines.append('L1') if self.l2.isChecked(): lines.append('L2') if self.l3.isChecked(): lines.append('L3') if self.m.isChecked(): lines.append('M') ddict = Elements.getcandidates(energy, threshold, lines)[0] ddict['text'] = self.getHtmlText(ddict) ddict['event'] = 'Candidates' ddict['lines'] = lines if self.__useviewer: if QTVERSION < '4.0.0': self.__browsertext.setText(ddict['text']) else: self.__browsertext.clear() #self.__browsertext.insertHtml("<CENTER>"+dict['text']+\ # "</CENTER>") self.__browsertext.insertHtml(ddict['text']) if QTVERSION < '4.0.0': self.emit(qt.PYSIGNAL('PeakIdentifierSignal'), (ddict, )) else: self.emit(qt.SIGNAL('PeakIdentifierSignal'), ddict)
def setCurrent(self, matkey0): if DEBUG: "setCurrent(self, matkey0) ", matkey0 matkey = Elements.getMaterialKey(matkey0) if matkey is not None: if self.__toolMode: #make sure the material CANNOT be modified self._current = copy.deepcopy(Elements.Material[matkey]) if self.__table.isEnabled(): self.__disableInput() else: self._current = Elements.Material[matkey] else: self._setCurrentDefault() if not self.__toolMode: Elements.Material[matkey0] = self._current self.__numberSpin.setFocus() try: self._fillValues() self._updateCurrent() finally: if self.__toolMode: self.__nameLine.setText("%s" % matkey) self.__fillingValues = False
def processFitResult(self, config=None, fitresult=None, elementsfrommatrix=False, fluorates=None, addinfo=False): # I should check if fit was successful ... if fitresult is None: fitresult = self.fitresult else: self.fitresult = fitresult if config is None: config = self.config else: self.config = config if 'usemultilayersecondary' not in self.config: self.config['usemultilayersecondary'] = 0 if 'usexrfmc' not in self.config: self.config['usexrfmc'] = 0 secondary = self.config['usemultilayersecondary'] xrfmcSecondary = self.config['usexrfmc'] if secondary and xrfmcSecondary: txt = "Only one of built-in secondary and Monte Carlo correction can be used" raise ValueError(txt) # get attenuators and matrix from fit attenuators = [] beamfilters = [] funnyfilters = [] matrix = None detectoratt = None multilayer = None for attenuator in fitresult['result']['config']['attenuators'].keys(): if not fitresult['result']['config']['attenuators'][attenuator][0]: continue if attenuator.upper() == "MATRIX": matrix = fitresult['result']['config']['attenuators'][ attenuator][1:4] alphain = fitresult['result']['config']['attenuators'][ attenuator][4] alphaout = fitresult['result']['config']['attenuators'][ attenuator][5] elif attenuator.upper()[:-1] == "BEAMFILTER": beamfilters.append(fitresult['result']['config']['attenuators']\ [attenuator][1:]) elif attenuator.upper() == "DETECTOR": detectoratt = fitresult['result']['config']['attenuators'][ attenuator][1:] else: if len(fitresult['result']['config']['attenuators'][attenuator] [1:]) == 4: fitresult['result']['config']['attenuators'][ attenuator].append(1.0) if abs(fitresult['result']['config']['attenuators'][attenuator] [4] - 1.0) > 1.0e-10: #funny attenuator funnyfilters.append(fitresult['result']['config']['attenuators']\ [attenuator][1:]) else: attenuators.append(fitresult['result']['config']['attenuators']\ [attenuator][1:]) if matrix is None: raise ValueError("Invalid or undefined sample matrix") if matrix[0].upper() == "MULTILAYER": layerlist = fitresult['result']['config']['multilayer'].keys() layerlist.sort() for layer in layerlist: if fitresult['result']['config']['multilayer'][layer][0]: if multilayer is None: multilayer = [] multilayer.append( fitresult['result']['config']['multilayer'][layer][1:]) if not Elements.isValidMaterial(multilayer[-1][0]): raise ValueError("Material %s is not defined" % multilayer[-1][0]) else: layerlist = ["Layer0"] multilayer = [matrix] if not Elements.isValidMaterial(matrix[0]): raise ValueError("Material %s is not defined" % matrix[0]) if xrfmcSecondary and (len(layerlist) > 1): txt = "Multilayer Monte Carlo correction not implemented yet" raise ValueError(txt) energyList = fitresult['result']['config']['fit']['energy'] if energyList is None: raise ValueError("Invalid energy") if type(energyList) != type([]): energyList = [energyList] flagList = [1] weightList = [1.0] else: flagList = fitresult['result']['config']['fit']['energyflag'] weightList = fitresult['result']['config']['fit']['energyweight'] finalEnergy = [] finalWeight = [] finalFlag = [] for idx in range(len(energyList)): if flagList[idx]: energy = energyList[idx] if energy is None: raise ValueError(\ "Energy %d isn't a valid energy" % idx) if energy <= 0.001: raise ValueError(\ "Energy %d with value %f isn't a valid energy" %\ (idx, energy)) if weightList[idx] is None: raise ValueError(\ "Weight %d isn't a valid weight" % idx) if weightList[idx] < 0.0: raise ValueError(\ "Weight %d with value %f isn't a valid weight" %\ (idx, weightList[idx])) finalEnergy.append(energy) finalWeight.append(weightList[idx]) finalFlag.append(1) totalWeight = sum(weightList) if totalWeight == 0.0: raise ValueError("Sum of energy weights is 0.0") weightList = [x / totalWeight for x in finalWeight] energyList = finalEnergy flagList = finalFlag # get elements list from fit, not from matrix groupsList = fitresult['result']['groups'] * 1 if type(groupsList) != type([]): groupsList = [groupsList] todelete = [] for i in range(len(groupsList)): ele = groupsList[i].split()[0] if len(ele) > 2: todelete.append(i) if len(todelete): todelete.reverse() for i in todelete: del groupsList[i] elements = [] newelements = [] for group in groupsList: splitted = group.split() ele = splitted[0] newelements.append( [Elements.getz(splitted[0]), splitted[0], splitted[1]]) if len(elements): if elements[-1] != ele: elements.append(ele) else: elements.append(ele) newelements.sort() elements.sort() if not config['useattenuators']: attenuators = None funnyfilters = None #import time #t0=time.time() if elementsfrommatrix: newelementsList = [] for ilayer in range(len(multilayer)): pseudomatrix = multilayer[ilayer] eleDict = Elements.getMaterialMassFractions([pseudomatrix[0]], [1.0]) if eleDict == {}: raise ValueError(\ "Invalid layer material %s" % pseudomatrix[0]) keys = eleDict.keys() for ele in keys: for group in newelements: if ele == group[1]: if not group in newelementsList: newelementsList.append(group) newelementsList.sort() fluo0 = Elements.getMultilayerFluorescence( multilayer, energyList, layerList=None, weightList=weightList, flagList=weightList, fulloutput=1, beamfilters=beamfilters * 1, attenuators=attenuators * 1, elementsList=newelementsList * 1, alphain=alphain, alphaout=alphaout, cascade=True, detector=detectoratt, funnyfilters=funnyfilters * 1, forcepresent=0, secondary=secondary) fluototal = fluo0[0] fluolist = fluo0[1:] else: if matrix[0].upper() != "MULTILAYER": multilayer = [matrix * 1] if fluorates is None: fluo0 = Elements.getMultilayerFluorescence( multilayer, energyList, layerList=None, weightList=weightList, flagList=flagList, fulloutput=1, beamfilters=beamfilters * 1, attenuators=attenuators * 1, elementsList=newelements * 1, alphain=alphain, alphaout=alphaout, cascade=True, detector=detectoratt, funnyfilters=funnyfilters * 1, forcepresent=1, secondary=secondary) else: fluo0 = fluorates fluototal = fluo0[0] fluolist = fluo0[1:] #I'll need total fluo element by element at some point #print "getMatrixFluorescence elapsed = ",time.time()-t0 if config['usematrix']: present = [] referenceLayerDict = {} materialComposition = [] for ilayer in range(len(multilayer)): pseudomatrix = multilayer[ilayer] * 1 #get elemental composition from matrix materialComposition.append( Elements.getMaterialMassFractions([pseudomatrix[0]], [1.0])) keys = materialComposition[-1].keys() materialElements = [[Elements.getz(x), x] for x in keys] materialElements.sort() for z, key in materialElements: for ele in elements: if key == ele: present.append(key) if not (ele in referenceLayerDict): referenceLayerDict[ele] = [] referenceLayerDict[ele].append(ilayer) if len(present) == 0: text = "Matrix must contain at least one fitted element\n" text += "in order to estimate flux and efficiency from it." raise ValueError(text) referenceElement = config['reference'].replace(' ', "") if len(referenceElement) and (referenceElement.upper() != 'AUTO'): if Elements.isValidFormula(referenceElement): if len(referenceElement) == 2: referenceElement = referenceElement.upper()[0] +\ referenceElement.lower()[1] elif len(referenceElement) == 1: referenceElement = referenceElement.upper()[0] if not (referenceElement in elements): text = "Element %s not among fitted elements" % referenceElement raise ValueError(text) elif not (referenceElement in present): text = "Element %s not among matrix elements" % referenceElement raise ValueError(text) referenceLayers = referenceLayerDict[referenceElement] else: text = "Element %s not a valid element" % referenceElement raise ValueError(text) elif len(present) == 1: referenceElement = present[0] referenceLayers = referenceLayerDict[referenceElement] else: # how to choose? Best fitted, largest fit area or # greater concentration? or better to give a weight to # the different shells, energies , ...? referenceElement = present[0] fom = self._figureOfMerit(present[0], fluototal, fitresult) for key in present: #if materialComposition[key] > materialComposition[referenceElement]: # referenceElement = key newfom = self._figureOfMerit(key, fluototal, fitresult) if newfom > fom: fom = newfom referenceElement = key referenceLayers = referenceLayerDict[referenceElement] referenceTransitions = None for group in groupsList: item = group.split() element = item[0] if element == referenceElement: transitions = item[1] + " xrays" if referenceTransitions is None: referenceTransitions = transitions referenceGroup = group elif (referenceTransitions[0] == transitions[0]) and\ (referenceTransitions[0] == 'L'): # this prevents selecting L1 and selects L3 although # given the appropriate area, L2 can be a safer choice. referenceGroup = group referenceTransitions = transitions elif referenceTransitions is not None: break theoretical = 0.0 for ilayer in referenceLayers: if elementsfrommatrix: theoretical += fluolist[ilayer][referenceElement]['rates'][referenceTransitions] * \ fluolist[ilayer][referenceElement]['mass fraction'] else: theoretical += materialComposition[ilayer][referenceElement] * \ fluolist[ilayer][referenceElement]['rates'][referenceTransitions] if theoretical <= 0.0: raise ValueError(\ "Theoretical rate is almost 0.0 Impossible to determine flux") else: if (config['distance'] > 0.0) and (config['area'] > 0.0): #solidangle = config['area']/(4.0 * numpy.pi * pow(config['distance'],2)) radius2 = config['area'] / numpy.pi solidangle = 0.5 * ( 1.0 - (config['distance'] / numpy.sqrt(pow(config['distance'], 2) + radius2))) else: solidangle = 1.0 flux = fitresult['result'][referenceGroup]['fitarea'] / ( theoretical * solidangle) else: referenceElement = None referenceTransitions = None #solidangle = config['area']/(4.0 * numpy.pi * pow(config['distance'],2)) radius2 = config['area'] / numpy.pi solidangle = 0.5 * ( 1.0 - (config['distance'] / numpy.sqrt(pow(config['distance'], 2) + radius2))) flux = config['flux'] * config['time'] #print "OBTAINED FLUX * SOLID ANGLE= ",flux * solidangle #print "flux * time = ",flux #print "actual solid angle = ",0.5 * (1.0 - (config['distance']/sqrt(pow(config['distance'],2)+ config['area']/pi))) #print "solid angle factor= ",solidangle #ele = 'Pb' #rays = "L xrays" #print "theoretical = ",fluototal[ele]['rates'][rays] #print "expected = ",flux * solidangle * fluototal[ele]['rates'][rays] #for ilayer in range(len(multilayer)): # print "ilayer = ",ilayer, "theoretical = ",fluolist[ilayer][ele]['rates'][rays] # print "ilayer = ",ilayer, "expected = ",flux * solidangle * fluolist[ilayer][ele]['rates'][rays] ddict = {} ddict['groups'] = groupsList ddict['elements'] = elements ddict['mass fraction'] = {} if 'mmolarflag' in config: if config['mmolarflag']: ddict['mmolar'] = {} else: config['mmolarflag'] = 0 ddict['area'] = {} ddict['fitarea'] = {} ddict['sigmaarea'] = {} fluo = fluototal for group in groupsList: item = group.split() element = item[0] transitions = item[1] + " xrays" if element in fluo.keys(): if transitions in fluo[element]: #this SHOULD be with concentration one theoretical = fluo[element]['rates'][transitions] * 1.0 expected = theoretical * flux * solidangle concentration = fitresult['result'][group][ 'fitarea'] / expected else: theoretical = 0.0 concentration = 0.0 else: theoretical = 0.0 concentration = 0.0 #ddict['area'][group] = theoretical * flux * solidangle * concentration ddict['fitarea'][group] = fitresult['result'][group]['fitarea'] ddict['sigmaarea'][group] = fitresult['result'][group]['sigmaarea'] if elementsfrommatrix: if element in fluo.keys(): ddict['mass fraction'][ group] = 1.0 * fluo[element]['mass fraction'] else: ddict['mass fraction'][group] = 0.0 ddict['area'][group] = theoretical * flux * solidangle *\ ddict['mass fraction'][group] else: ddict['mass fraction'][group] = concentration ddict['area'][group] = theoretical * flux * solidangle if config['mmolarflag']: #mM = (mass_fraction * density)/atomic_weight ddict['mmolar'] [group]= 1000000. *\ (multilayer[0][1] * ddict['mass fraction'][group])/Elements.Element[element]['mass'] #I have the globals/average values now I calculate layer per layer #if necessary ddict['layerlist'] = [] if matrix[0].upper() == "MULTILAYER": ilayer = 0 for layer in layerlist: if fitresult['result']['config']['multilayer'][layer][0]: ddict['layerlist'].append(layer) ddict[layer] = {} dict2 = ddict[layer] dict2['groups'] = groupsList dict2['elements'] = elements dict2['mass fraction'] = {} if config['mmolarflag']: dict2['mmolar'] = {} dict2['area'] = {} dict2['fitarea'] = {} fluo = fluolist[ilayer] for group in groupsList: item = group.split() element = item[0] transitions = item[1] + " xrays" if element in fluo.keys(): if transitions in fluo[element]: theoretical = fluo[element]['rates'][ transitions] * 1 expected = theoretical * flux * solidangle if expected > 0.0: concentration = fitresult['result'][group][ 'fitarea'] / expected else: concentration = -1 else: theoretical = 0.0 concentration = 0.0 else: theoretical = 0.0 concentration = 0.0 dict2['fitarea'][ group] = 1 * fitresult['result'][group]['fitarea'] if elementsfrommatrix: if element in fluo.keys(): dict2['mass fraction'][ group] = 1 * fluo[element]['mass fraction'] else: dict2['mass fraction'][group] = 0.0 #I calculate matrix in optimized form, #so I have to multiply by the mass fraction dict2['area'][group] = theoretical * flux * solidangle *\ dict2['mass fraction'][group] else: dict2['mass fraction'][group] = concentration dict2['area'][ group] = theoretical * flux * solidangle if config['mmolarflag']: #mM = (mass_fraction * density)/atomic_weight dict2['mmolar'][group] = 1000000. *\ (multilayer[ilayer][1] * dict2['mass fraction'][group]) /\ Elements.Element[element]['mass'] #if group == "Pb L": # print "layer", ilayer,'area ', dict2['area'][group] # print "layer", ilayer,'mass fraction =', dict2['mass fraction'][group] ilayer += 1 if elementsfrommatrix: for group in groupsList: ddict['area'][group] = 0.0 for layer in ddict['layerlist']: if group in ddict[layer]['area'].keys(): ddict['area'][group] += ddict[layer]['area'][group] if xrfmcSecondary and (not elementsfrommatrix): xrfmcCorrections = None if 'xrfmc' in fitresult: xrfmcCorrections = fitresult['xrfmc'].get('corrections', None) if xrfmcCorrections is None: if 'xrfmc' in fitresult['result']: xrfmcCorrections = fitresult['result']['xrfmc'].get( 'corrections', None) if xrfmcCorrections is None: # try to see if they were in the configuration if 'xrfmc' in fitresult['result']['config']: xrfmcCorrections = fitresult['result']['config'][ 'xrfmc'].get('corrections', None) if xrfmcCorrections is None: # calculate the corrections xrfmcCorrections = XRFMCHelper.getXRFMCCorrectionFactors( fitresult['result']['config']) if referenceElement is not None: referenceLines = referenceTransitions.split()[0] referenceCorrection = xrfmcCorrections[referenceElement][referenceLines]\ ['correction_factor'][-1] xrfmcCorrections[referenceElement][referenceLines]\ ['correction_factor'][-1] = 1.0 for group in groupsList: item = group.split() element = item[0] lines = item[1] if element in xrfmcCorrections: if element != referenceElement: if lines != referenceLines: xrfmcCorrections[element][lines][ 'correction_factor'][ -1] *= referenceCorrection # now we have to apply the corrections for group in groupsList: item = group.split() element = item[0] lines = item[1] if element in xrfmcCorrections: correction = xrfmcCorrections[element][ item[1]]['correction_factor'][-1] ddict['mass fraction'][group] /= correction if addinfo: addInfo = {} addInfo['ReferenceElement'] = referenceElement addInfo['ReferenceTransitions'] = referenceTransitions addInfo['SolidAngle'] = solidangle if config['time'] > 0.0: addInfo['Time'] = config['time'] else: addInfo['Time'] = 1.0 addInfo['Flux'] = flux / addInfo['Time'] addInfo['I0'] = flux addInfo['DetectorDistance'] = config['distance'] addInfo['DetectorArea'] = config['area'] return ddict, addInfo else: return ddict
fname = sys.argv[1] if os.path.exists(fname): os.remove(fname) if int(sys.argv[2]): BARNS = True else: BARNS = False print("BARNS = %s" % BARNS) outfile = open(fname, 'wb') outfile.write(getHeader(fname)) for i in range(1, 101): ele = Elements.getsymbol(i) print("i = %d element = %s" % (i, ele)) # force data readout dataDict = Elements.getelementmassattcoef(ele) # pure XCOM data dataDict = Elements.Element[ele]['xcom'] # energy (keV) energy = dataDict['energy'] # coherent (cm2/g) cohe = dataDict['coherent'] # incoherent incohe = dataDict['compton']
def continuumEbel(target, e0, e=None, window=None, alphae=None, alphax=None, transmission=None, targetthickness=None, filterlist=None): """ Calculation of X-ray Tube continuum emission spectrum Parameters: ----------- target : list [Symbol, density (g/cm2), thickness(cm)] or atomic ymbol If set to atomic symbol, the program sets density and thickness of 0.1 cm e0 : float Tube Voltage in kV e : float or array of floats Energy of interest. If not given, the program will generate an array of energies from 1 to the given tube voltage minus 1 kV in keV. window : list Tube window [Formula, density, thickness] alphae : float Angle, in degrees, between electron beam and tube target. Normal incidence is 90. alphax : float Angle, in degrees, of X-ray exit beam. Normal exit is 90. transmission : Boolean, default is False If True the X-ray come out of the tube target by the side opposite to the one receiving the exciting electron beam. targetthickness : Target thickness in cm Only considered in transmission case. If not given, the program uses as target thickness the maximal penetration depth of the incident electron beam. filterlist : [list] Additional filters [[Formula, density, thickness], ...] Return: ------- result : Array Spectral flux density. Flux of photons at the given energies in photons/sr/mA/keV/s Reference: H. Ebel, X-Ray Spectrometry 28 (1999) 255-266 Tube voltage from 5 to 50 kV Electron incident angle from 50 to 90 deg. X-Ray take off angle from 90 to 5 deg. """ if type(target) in [type([]), type(list())]: element = target[0] density = target[1] thickness = target[2] else: element = target density = Elements.Element[element]['density'] thickness = 0.1 if e is None: energy = numpy.arange(e0 * 1.0)[1:] elif type(e) == type([]): energy = numpy.array(e, dtype=numpy.float) elif type(e) == numpy.ndarray: energy = numpy.array(e, dtype=numpy.float) else: energy = numpy.array([e], dtype=numpy.float) if alphae is None: alphae = 75.0 if alphax is None: alphax = 15.0 if transmission is None: transmission = False sinalphae = math.sin(math.radians(alphae)) sinalphax = math.sin(math.radians(alphax)) sinfactor = sinalphae / sinalphax z = Elements.getz(element) const = 1.35e+09 x = 1.109 - 0.00435 * z + 0.00175 * e0 # calculate intermediate constants from formulae (4) in Ebel's paper # eta in Ebel's paper m = 0.1382 - 0.9211 / math.sqrt(z) logz = math.log(z) eta = 0.1904 - 0.2236 * logz + 0.1292 * pow(logz, 2) - \ 0.0149 * pow(logz, 3) eta = eta * pow(e0, m) # dephmax? in Ebel's paper p3 = 0.787e-05 * math.sqrt(0.0135 * z) * pow(e0, 1.5) + \ 0.735e-06 * pow(e0, 2) rhozmax = (Elements.Element[element]['mass'] / z) * p3 # print "max depth = ",2 * rhozmax # and finally we get rhoz u0 = e0 / energy logu0 = numpy.log(u0) p1 = logu0 * (0.49269 - 1.09870 * eta + 0.78557 * pow(eta, 2)) p2 = 0.70256 - 1.09865 * eta + 1.00460 * pow(eta, 2) + logu0 rhoz = rhozmax * (p1 / p2) # the term dealing with the photoelectric absorption of the Bremsstrahlung tau = numpy.array( Elements.getMaterialMassAttenuationCoefficients(element, 1.0, energy)['photo']) if not transmission: rhelp = tau * 2.0 * rhoz * sinfactor if len(numpy.nonzero(rhelp <= 0.0)[0]): result = numpy.zeros(rhelp.shape, numpy.float) for i in range(len(rhelp)): if rhelp[i] > 0.0: result[i] = const * z * pow(u0[i] - 1.0, x) * \ (1.0 - numpy.exp(-rhelp[i])) / rhelp[i] else: result = const * z * pow(u0 - 1.0, x) * \ (1.0 - numpy.exp(-rhelp)) / rhelp # the term dealing with absorption in tube's window if window is not None: if window[2] != 0: w = Elements.getMaterialTransmission( window[0], 1.0, energy, density=window[1], thickness=window[2], listoutput=False)['transmission'] result *= w if filterlist is not None: w = 1 for fwindow in filterlist: if fwindow[2] == 0: continue w *= Elements.getMaterialTransmission( fwindow[0], 1.0, energy, density=fwindow[1], thickness=fwindow[2], listoutput=False)['transmission'] result *= w return result # transmission case if targetthickness is None: #d = Elements.Element[target]['density'] d = density ttarget = 2 * rhozmax print( "WARNING target thickness assumed equal to maximum depth of %f cm" % (ttarget / d)) else: #ttarget = targetthickness * Elements.Element[target]['density'] ttarget = targetthickness * density # generationdepth = min(ttarget, 2 * rhozmax) rhelp = tau * 2.0 * rhoz * sinfactor if len(numpy.nonzero(rhelp <= 0.0)[0]): result = numpy.zeros(rhelp.shape, numpy.float) for i in range(len(rhelp)): if rhelp[i] > 0.0: result[i] = const * z * pow(u0[i] - 1.0, x) * \ (numpy.exp(-tau[i] *(ttarget - 2.0 * rhoz[i]) / sinalphax) - \ numpy.exp(-tau[i] * ttarget / sinalphax)) / rhelp[i] else: result = const * z * pow(u0 - 1.0, x) * \ (numpy.exp(-tau *(ttarget - 2.0 * rhoz) / sinalphax) - \ numpy.exp(-tau * ttarget / sinalphax)) / rhelp # the term dealing with absorption in tube's window if window is not None: if window[2] != 0.0: w = Elements.getMaterialTransmission( window[0], 1.0, energy, density=window[1], thickness=window[2] / sinalphax, listoutput=False)['transmission'] result *= w if filterlist is not None: for fwindow in filterlist: if fwindow[2] == 0: continue w = Elements.getMaterialTransmission( fwindow[0], 1.0, energy, density=fwindow[1], thickness=fwindow[2], listoutput=False)['transmission'] result *= w return result
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 characteristicEbel(target, e0, window=None, alphae=None, alphax=None, transmission=None, targetthickness=None, filterlist=None): """ Calculation of target characteritic lines and intensities Parameters: ----------- target : list [Symbol, density (g/cm2), thickness(cm)] or atomic ymbol If set to atomic symbol, the program sets density and thickness of 0.1 cm e0 : float Tube Voltage in kV e : float Energy of interest window : list Tube window [Formula, density, thickness] alphae : float Angle, in degrees, between electron beam and tube target. Normal incidence is 90. alphax : float Angle, in degrees, of X-ray exit beam. Normal exit is 90. transmission : Boolean, default is False If True the X-ray come out of the tube target by the side opposite to the one receiving the exciting electron beam. targetthickness : Target thickness in cm Only considered in transmission case. If not given, the program uses as target thickness the maximal penetration depth of the incident electron beam. filterlist : [list] Additional filters [[Formula, density, thickness], ...] Result: list Characteristic lines and intensities in the form [[energy0, intensity0, name0], [energy1, intensity1, name1], ...] Energies in keV Intensities in photons/sr/mA/keV/s """ if type(target) == type([]): element = target[0] density = target[1] thickness = target[2] if targetthickness is None: targetthickness = target[2] else: element = target density = Elements.Element[element]['density'] thickness = 0.1 if alphae is None: alphae = 75.0 if alphax is None: alphax = 15.0 if transmission is None: transmission = False sinalphae = math.sin(math.radians(alphae)) sinalphax = math.sin(math.radians(alphax)) sinfactor = sinalphae / sinalphax z = Elements.getz(element) const = 6.0e+13 # K Shell energy = Elements.Element[element]['binding']['K'] # get the energy of the characteristic lines lines = Elements._getUnfilteredElementDict(element, None, photoweights=True) if 0: # L shell lines will have to be entered directly by the user # L shell lpeaks = [] for label in lines['L xrays']: lpeaks.append([ lines[label]['energy'], lines[label]['rate'], element + ' ' + label ]) lfluo = Elements._filterPeaks(lpeaks, ethreshold=0.020, ithreshold=0.001, nthreshold=6, absoluteithreshold=False, keeptotalrate=True) lfluo.sort() peaklist = [] rays = 'K xrays' if rays in lines.keys(): #K shell for label in lines[rays]: peaklist.append([ lines[label]['energy'], lines[label]['rate'], element + ' ' + label ]) fl = Elements._filterPeaks(peaklist, ethreshold=0.020, ithreshold=0.001, nthreshold=4, absoluteithreshold=False, keeptotalrate=True) fl.sort() if (energy > 0) and (e0 > energy): zk = 2.0 bk = 0.35 else: for i in range(len(fl)): fl[i][1] = 0.00 return fl u0 = e0 / energy logu0 = numpy.log(u0) # stopping factor oneovers = (numpy.sqrt(u0) * logu0 + 2 * (1.0 - numpy.sqrt(u0))) oneovers /= u0 * logu0 + 1.0 - u0 oneovers = 1.0 + 16.05 * numpy.sqrt(0.0135 * z / energy) * oneovers oneovers *= (zk * bk / z) * (u0 * logu0 + 1.0 - u0) # backscattering factor r = 1.0 - 0.0081517 * z + 3.613e-05 * z * z +\ 0.009583 * z * numpy.exp(-u0) + 0.001141 * e0 # Absorption correction # calculate intermediate constants from formulae (4) in Ebel's paper # eta in Ebel's paper m = 0.1382 - 0.9211 / numpy.sqrt(z) logz = numpy.log(z) eta = 0.1904 - 0.2236 * logz + 0.1292 * pow(logz, 2) - 0.0149 * pow( logz, 3) eta = eta * pow(e0, m) # depmax? in Ebel's paper p3 = 0.787e-05 * numpy.sqrt(0.0135 * z) * pow(e0, 1.5) + \ 0.735e-06 * pow(e0, 2) rhozmax = (Elements.Element[element]['mass'] / z) * p3 # and finally we get rhoz p1 = logu0 * (0.49269 - 1.09870 * eta + 0.78557 * pow(eta, 2)) p2 = 0.70256 - 1.09865 * eta + 1.00460 * pow(eta, 2) + logu0 rhoz = rhozmax * (p1 / p2) # the term dealing with the photoelectric absorption energylist = [] for i in range(len(fl)): energylist.append(fl[i][0]) tau = numpy.array( Elements.getMaterialMassAttenuationCoefficients( element, 1.0, energylist)['photo']) if not transmission: rhelp = tau * 2.0 * rhoz * sinfactor w = None if window is not None: if window[2] != 0.0: w = Elements.getMaterialTransmission( window[0], 1.0, energylist, density=window[1], thickness=window[2], listoutput=False)['transmission'] if filterlist is not None: for fwindow in filterlist: if fwindow[2] == 0: continue if w is None: w = Elements.getMaterialTransmission( fwindow[0], 1.0, energylist, density=fwindow[1], thickness=fwindow[2], listoutput=False)['transmission'] else: w *= Elements.getMaterialTransmission( fwindow[0], 1.0, energylist, density=fwindow[1], thickness=fwindow[2], listoutput=False)['transmission'] for i in range(len(fl)): if rhelp[i] > 0.0: rhelp[i] = (1.0 - numpy.exp(-rhelp[i])) / rhelp[i] else: rhelp[i] = 0.0 intensity = const * oneovers * r * Elements.getomegak( element) * rhelp[i] #the term dealing with absorption in tube's window if w is not None: intensity = intensity * w[i] fl[i][1] = intensity * fl[i][1] return fl #transmission case if targetthickness is None: d = density ttarget = 2 * rhozmax print( "WARNING target thickness assumed equal to maximum depth of %f cm" % (ttarget / d)) else: ttarget = targetthickness * density #generationdepth = min(ttarget, 2 * rhozmax) rhelp = tau * 2.0 * rhoz * sinfactor w = None if (window is not None) or (filterlist is not None): if window is not None: if window[2] != 0.0: w = Elements.getMaterialTransmission( window[0], 1.0, energylist, density=window[1], thickness=window[2] / sinalphax, listoutput=False)['transmission'] if filterlist is not None: for fwindow in filterlist: if w is None: w = Elements.getMaterialTransmission( fwindow[0], 1.0, energylist, density=fwindow[1], thickness=fwindow[2], listoutput=False)['transmission'] else: w *= Elements.getMaterialTransmission( fwindow[0], 1.0, energylist, density=fwindow[1], thickness=fwindow[2], listoutput=False)['transmission'] for i in range(len(fl)): if rhelp[i] > 0.0: rhelp[i] = ( numpy.exp(-tau[i] * (ttarget - 2.0 * rhoz) / sinalphax) - numpy.exp(-tau[i] * ttarget / sinalphax)) / rhelp[i] else: rhelp[i] = 0.0 intensity = const * oneovers * r * Elements.getomegak( element) * rhelp[i] if w is not None: intensity = intensity * w[i] fl[i][1] = intensity * fl[i][1] return fl
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()