def calibrationFigure(self,fig,calibrationObj,spToDisplay=0,autoAxesLimits=1,colourList=0,**kwargs): # TODO(gns) - This can probably be removed only used in: # 121207_test_SpecialFigureCalibration.py, 121209_test_SpecialFigureCalibration2.py if not spToDisplay: spToDisplay = calibrationObj.calibrants.keys()[0] if not colourList: colourList = utils.colourList sps = calibrationObj.calibrants.keys() bandColour = colourList[sps.index(spToDisplay)] calibrant = calibrationObj.calibrants[spToDisplay] ax = fig.add_subplot(311) # mass spectrum calibrant.plotMsAndExtractionLimits(ax,bandColour,**kwargs) if autoAxesLimits: mzs = [utils.get_mz(calibrant.approxMass, z) for z in calibrant.charges] plt.xlim([min(mzs)*0.5,max(mzs)*2]) ax = fig.add_subplot(312) # atds calibrant.plotChargeStateAtds(ax,colourList=colourList) calibrant.plotCalibrantTdPeaks(ax,colourList=colourList) if autoAxesLimits: tdPrimes = [calibrant.tdsDoublePrime[z] for z in calibrant.charges] plt.xlim([min(tdPrimes)*0.5,max(tdPrimes)*2.0]) ax = fig.add_subplot(313) # fit calibrationObj.plotCalibrationCurve(ax,colourList,**kwargs)
def plotTheoreticalMzs(self,ax,xvals,yvals,absolute=0,mass=0,**kwargs): """Used to draw the positions of calculated charge state peaks. If a value for absolute is given, it is used as the y axis position for charge state labels. All matplotlib.pyplot.plot() arguments are allowed in **kwargs. """ if not mass: mass = self.mass oneDone = False for i,z in enumerate(np.arange(100)+1): mz = utils.get_mz(mass, z) if xvals[0] < mz < xvals[-1]: # the line if not oneDone: ax.axvline(mz, label="%s - %.1f Da +/- %.1f" %(self.name,self.mass,self.calcMassError), **kwargs) else: ax.axvline(mz, **kwargs) oneDone = True # annotation if z/2 == float(z)/2: lift = .1 * yvals.max() else: lift = .2 * yvals.max() if not 'color' in kwargs: color = 'blue' else: color = kwargs['color'] if not absolute: ax.text(mz,lift,'+%d' %z, color=color) else: ax.text(mz,absolute,'+%d' %z, color=color)
def _getMzLimits(self, species, charge): """Get the m/z value upper and lower limits for extracting arrival time data. :parameter species: Name of molecular species (species) :parameter charge: Charge state (int) """ mz = utils.get_mz(self.atrOb.simulatedSpecies[species].mass, charge) fwhm = self.atrOb.simulatedSpecies[species].peakFwhm left = (self.widthL * fwhm) / 2. right = (self.widthR * fwhm) / 2. return [mz - left, mz + right]
def _getMzLimits(self,species,charge): """Get the m/z value upper and lower limits for extracting arrival time data. :parameter species: Name of molecular species (species) :parameter charge: Charge state (int) """ mz = utils.get_mz(self.atrOb.simulatedSpecies[species].mass,charge) fwhm = self.atrOb.simulatedSpecies[species].peakFwhm left = (self.widthL*fwhm)/2. right = (self.widthR*fwhm)/2. return [mz-left,mz+right]
def getTotalIntensity(self, xvals, yvals): """Using the supplied data, sum the intensity of the highest point of the data at the m/z value for each charge state in self.charges using self.mass as the mass. """ '''Gets experimental intensity''' intensity = 0 for charge in self.charges: mz = utils.get_mz(self.mass, charge) i = utils.closest(mz, xvals) intensity += yvals[i] return intensity
def getTotalIntensity(self,xvals,yvals): """Using the supplied data, sum the intensity of the highest point of the data at the m/z value for each charge state in self.charges using self.mass as the mass. """ '''Gets experimental intensity''' intensity = 0 for charge in self.charges: mz = utils.get_mz(self.mass, charge) i = utils.closest(mz, xvals) intensity += yvals[i] return intensity
def eventAddCalibrant( self, event, autoAxesLimits=1): # wxGlade: CalibrationGui.<event_handler> """Add a calibrant to the calibration. Opens calibrant using path textbox, processes it and recalculates the calibration curve. """ # please wait dialog bi = wx.BusyInfo("Working, please wait", self) wx.Yield() if self.textCtrlPath.GetValue() != "": self.settings.setCalPath(self.textCtrlPath.GetValue()) calibrantName = self.settings.getCalNameCurrent() # Mass Spectrum panel calibrant = Calibrant(calibrantName, self.settings.calPath) calibrant.plotMsAndExtractionLimits(self.getAxMS()) if autoAxesLimits: mzs = [ utils.get_mz(calibrant.approxMass, z) for z in calibrant.charges ] self.settings.xlimsMs[calibrantName] = [ min(mzs) * 0.5, max(mzs) * 2 ] self.figure.axMs.set_xlim(self.settings.xlimsMs[calibrantName]) self.settings.ylimsMs[calibrantName] = self.figure.axMs.get_ylim() self.figure.axMs.set_xlim(self.settings.xlimsMs[calibrantName]) self.figure.axMs.set_yticks([]) # Tds panel calibrant.plotChargeStateAtds(self.getAxTds()) calibrant.plotCalibrantTdPeaks(self.getAxTds(clear=0)) if autoAxesLimits: tds = [calibrant.tds[z] for z in calibrant.charges][:] self.settings.xlimsTds[calibrantName] = [ min(tds) * 0.5, max(tds) * 2.0 ] self.settings.ylimsTds[calibrantName] = self.figure.axTds.get_ylim( ) self.figure.axTds.set_xlim(self.settings.xlimsTds[calibrantName]) # Fill in the grid self.panelCalibrantListCtrl.setData(calibrant) self.calibrants[calibrantName] = calibrant self.calibrantCharges[calibrantName] = calibrant.charges[:] self.createCalibration() self.draw() bi.Destroy()
def __init__(self, mass, charge, speciesAllCharges): # self.mass = None # self.charge = None # self.species = None self.mass = mass self.charge = charge self.speciesAllCharges = sorted(speciesAllCharges, reverse=True) self.mz = utils.get_mz(self.mass, self.charge) self.limits = [None, None]
def simulateSpecies(self,xvals,peakShape='hybrid'): """Simulates a mass spectrum using the object's attributes Valid peak shapes are: 'hybrid', 'gaussian' & 'lorentzian if one_fwhh is to be used be sure to set self.peakFwhm before calling this function. """ combined = np.zeros(len(xvals),dtype='float') for z in self.charges: centre = utils.get_mz(self.mass, z) amplitude = self.zGauss.calculateAmplitude(centre) combined += utils.draw_peaks[peakShape](xvals,amplitude,centre,self.peakFwhm) return combined
def simulateSpecies(self, xvals, peakShape='hybrid'): """Simulates a mass spectrum using the object's attributes Valid peak shapes are: 'hybrid', 'gaussian' & 'lorentzian if one_fwhh is to be used be sure to set self.peakFwhm before calling this function. """ combined = np.zeros(len(xvals), dtype='float') for z in self.charges: centre = utils.get_mz(self.mass, z) amplitude = self.zGauss.calculateAmplitude(centre) combined += utils.draw_peaks[peakShape](xvals, amplitude, centre, self.peakFwhm) return combined
def plotAtroposSelectionAutoWidth(self,ax,limitsD): """Uses limits generated by: getAutoPeakLimits() instead of relative to atropos generated fwhm values. :parameter ax: Matplotlib Axes object to use :parameter limitsD: Set to True to use automatic maximum width size for extraction """ ylims = ax.get_ylim() for sp,d in limitsD.items(): mass = self.settings.imOb.species[sp].mass for z,limits in d.items(): mz = utils.get_mz(mass,z) ax.fill_betweenx(ylims,limits[0], limits[1],color='red',alpha=0.1)
def generateCorrectedTdsAndCcss(self,waveVelocity,gas='Nitrogen'): """Calculate td prime and CCS prime, using the calibration equations including the reduced mass equation. :parameter waveVelocity: Velocity in m/s :parameter gas: Mobililty gas used (default: 'Nitrogen') """ for i,charge in enumerate(self.charges): mz = utils.get_mz(self.approxMass, charge) # td tdPrime = utils._calculateTdPrime(self.tds[charge], waveVelocity) self.tdsDoublePrime[charge] = utils._calculateTdDoublePrime(tdPrime, mz) #CCS reducedMass = utils._calculateReducedMass(mz, charge, gas) self.CcssPrime[charge] = utils._calculateOmegaPrime(self.publishedCcss[charge], charge, reducedMass)
def setSpeciesGivenMass(self, mass, xvals, yvals, peakFwhm, zs): """Similar to Species.setSpecies(). Except that instead of using gPeaks, the Species() object is setup automatically when given values for mass and the charges to be analysed. """ self.mass = mass self.charges = zs pseudogPeaks = {} for z in zs: xval = utils.get_mz(self.mass, z) i = utils.closest(xval, xvals) yval = yvals[i] pseudogPeaks[z] = [xval, yval] self.setSpecies(pseudogPeaks, peakFwhm)
def setSpeciesGivenMass(self,mass,xvals,yvals,peakFwhm,zs): """Similar to Species.setSpecies(). Except that instead of using gPeaks, the Species() object is setup automatically when given values for mass and the charges to be analysed. """ self.mass = mass self.charges = zs pseudogPeaks = {} for z in zs: xval = utils.get_mz(self.mass, z) i = utils.closest(xval, xvals) yval = yvals[i] pseudogPeaks[z] = [xval,yval] self.setSpecies(pseudogPeaks, peakFwhm)
def getPeakWidthLimits(self,name,charge,leftMultiplier=1,rightMultiplier=1): """Calculate the lower and upper m/z limits for a particular peak in relation to the multiplier values. (only use after calculating the mass spectrum fit). :parameter name: Species name :parameter charge: Charge to display :parameter leftMultiplier: Value to multiply the peak fwhm below the mean :parameter rightMultiplier: Value to multiply the peak fwhm above the mean :returns: m/z limits when using multiplier as [lowerLimit,upperLimit] """ mass = self.species[name].mass fwhm = self.species[name].peakFwhm mz = utils.get_mz(mass,charge) leftLim = mz - (fwhm/2 * leftMultiplier) rightLim = mz + (fwhm/2 * rightMultiplier) return [leftLim,rightLim]
def plotAtroposSelectionAutoWidth(self, ax, limitsD): """Uses limits generated by: getAutoPeakLimits() instead of relative to atropos generated fwhm values. :parameter ax: Matplotlib Axes object to use :parameter limitsD: Set to True to use automatic maximum width size for extraction """ ylims = ax.get_ylim() for sp, d in limitsD.items(): mass = self.settings.imOb.species[sp].mass for z, limits in d.items(): mz = utils.get_mz(mass, z) ax.fill_betweenx(ylims, limits[0], limits[1], color='red', alpha=0.1)
def _estimateCharges(self,limit=1): """Estimate charges to be simulated by fitting the charge state Gaussian distribution. Used as a subfunction for self.setSpecies() Limit is given as a percentage of the total height of the Gaussian and is used as the cutoff point for whether a charge state is to be included or discarded. """ # TODO(gns) - perhaps lower the limit for atropos at least # probably the default value as well. zs = np.arange(1,151) charges = [] for z in zs: xval = utils.get_mz(self.mass, z) height = self.zGauss.calculateAmplitude(xval) if height > self.zGauss.amplitude*(float(limit)/100): charges.append(z) return charges
def _estimateCharges(self, limit=1): """Estimate charges to be simulated by fitting the charge state Gaussian distribution. Used as a subfunction for self.setSpecies() Limit is given as a percentage of the total height of the Gaussian and is used as the cutoff point for whether a charge state is to be included or discarded. """ # TODO(gns) - perhaps lower the limit for atropos at least # probably the default value as well. zs = np.arange(1, 151) charges = [] for z in zs: xval = utils.get_mz(self.mass, z) height = self.zGauss.calculateAmplitude(xval) if height > self.zGauss.amplitude * (float(limit) / 100): charges.append(z) return charges
def eventAddCalibrant(self, event,autoAxesLimits=1): # wxGlade: CalibrationGui.<event_handler> """Add a calibrant to the calibration. Opens calibrant using path textbox, processes it and recalculates the calibration curve. """ # please wait dialog bi = wx.BusyInfo("Working, please wait", self) wx.Yield() if self.textCtrlPath.GetValue() != "": self.settings.setCalPath(self.textCtrlPath.GetValue()) calibrantName = self.settings.getCalNameCurrent() # Mass Spectrum panel calibrant = Calibrant(calibrantName,self.settings.calPath) calibrant.plotMsAndExtractionLimits(self.getAxMS()) if autoAxesLimits: mzs = [utils.get_mz(calibrant.approxMass, z) for z in calibrant.charges] self.settings.xlimsMs[calibrantName] = [min(mzs)*0.5,max(mzs)*2] self.figure.axMs.set_xlim(self.settings.xlimsMs[calibrantName]) self.settings.ylimsMs[calibrantName] = self.figure.axMs.get_ylim() self.figure.axMs.set_xlim(self.settings.xlimsMs[calibrantName]) self.figure.axMs.set_yticks([]) # Tds panel calibrant.plotChargeStateAtds(self.getAxTds()) calibrant.plotCalibrantTdPeaks(self.getAxTds(clear=0)) if autoAxesLimits: tds = [calibrant.tds[z] for z in calibrant.charges][:] self.settings.xlimsTds[calibrantName] = [min(tds)*0.5,max(tds)*2.0] self.settings.ylimsTds[calibrantName] = self.figure.axTds.get_ylim() self.figure.axTds.set_xlim(self.settings.xlimsTds[calibrantName]) # Fill in the grid self.panelCalibrantListCtrl.setData(calibrant) self.calibrants[calibrantName] = calibrant self.calibrantCharges[calibrantName] = calibrant.charges[:] self.createCalibration() self.draw() bi.Destroy()
def forLeastSquaresOptimisation(self,p0,xvals,zs,oneFwhm): """Creates the simulated mass spectrum for MassSpectrum.leastSquaresOptimisation(). p0 - parameters to be used in simulation zs - charges to be simulated oneFwhm - if True use same FWHM for each species. """ ps = self._splitPs(p0) combined = np.zeros(len(xvals)) zGauss = Gaussian() for i,p in enumerate(ps): zGauss.setParameters(p[1], p[2], p[3]) for j,z in enumerate(zs[i]): centre = utils.get_mz(p[0], z) amplitude = zGauss.calculateAmplitude(centre) if oneFwhm: combined += utils.draw_peaks['hybrid'](xvals,amplitude,centre,p0[4]) else: combined += utils.draw_peaks['hybrid'](xvals,amplitude,centre,p[4]) return combined
def _updateSpecies(self,speciesObj=0,peakFwhm=0,leftMultiplier=0,rightMultiplier=0,updateApex=1): """Update the settings of the species object. :parameter speciesObj: msClasses.Species() object (or 0 to use self.speciesObj) :parameter peakFwhm: m/z width to use when extracting arrival time data :parameter leftMultiplier: Multiply by the peak width lower than the mean :parameter rightMultiplier: Multiply by the peak width above the mean :parameter updateApex: If True, recalculate the td apex """ if peakFwhm: self.peakFwhm = peakFwhm if leftMultiplier: self.leftMultiplier = leftMultiplier if rightMultiplier: self.rightMultiplier = rightMultiplier if not speciesObj: speciesObj = self.speciesObj # check charges are within the mass spectrum limits zs = [] left = self.peakFwhm * self.leftMultiplier right = self.peakFwhm * self.rightMultiplier for z in self.charges: mz = utils.get_mz(self.approxMass,z) if self.imObj.xaxis.min()+left < mz < self.imObj.xaxis.max()-right: zs.append(z) else: print 'charge outside m/z range' self.charges = zs self.speciesObj.charges = self.charges self.imObj.setSpecies(self.speciesObj) self.imObj.generateSpeciesSlicesFwhm(self.name, self.leftMultiplier, self.rightMultiplier) if updateApex: self.tds = collections.OrderedDict() for z in self.charges: self.imObj.dataSlices[self.name][z].atd.smoothingSG(window_len=3, smoothes=1, poly_order=1) td = self.imObj.dataSlices[self.name][z].getAtdApex() self.tds[z] = td
def getPeakWidthLimits(self, name, charge, leftMultiplier=1, rightMultiplier=1): """Calculate the lower and upper m/z limits for a particular peak in relation to the multiplier values. (only use after calculating the mass spectrum fit). :parameter name: Species name :parameter charge: Charge to display :parameter leftMultiplier: Value to multiply the peak fwhm below the mean :parameter rightMultiplier: Value to multiply the peak fwhm above the mean :returns: m/z limits when using multiplier as [lowerLimit,upperLimit] """ mass = self.species[name].mass fwhm = self.species[name].peakFwhm mz = utils.get_mz(mass, charge) leftLim = mz - (fwhm / 2 * leftMultiplier) rightLim = mz + (fwhm / 2 * rightMultiplier) return [leftLim, rightLim]
def getAutoPeakLimits(self): # Get all the mzs of the various species charge states zsD,massD = self.settings.getChargeAndMassDictionaries() mzsD = OrderedDict() chargeStatePeakObs = [] allMzs = [] for sp, zs in zsD.items(): mzsD[sp] = [] for z in zs: mz = utils.get_mz(massD[sp],z) mzsD[sp].append(mz) allMzs.append(mz) # See if they overlap limitsD = OrderedDict() for sp,zs in zsD.items(): limitsD[sp] = OrderedDict() for z in zs: csOb = ChargeStatePeak.ChargeStatePeak(massD[sp],z,zs) limits = csOb.getLimits(allMzs) limitsD[sp][z] = limits return limitsD
def getAutoPeakLimits(self): # Get all the mzs of the various species charge states zsD, massD = self.settings.getChargeAndMassDictionaries() mzsD = OrderedDict() chargeStatePeakObs = [] allMzs = [] for sp, zs in zsD.items(): mzsD[sp] = [] for z in zs: mz = utils.get_mz(massD[sp], z) mzsD[sp].append(mz) allMzs.append(mz) # See if they overlap limitsD = OrderedDict() for sp, zs in zsD.items(): limitsD[sp] = OrderedDict() for z in zs: csOb = ChargeStatePeak.ChargeStatePeak(massD[sp], z, zs) limits = csOb.getLimits(allMzs) limitsD[sp][z] = limits return limitsD
def forLeastSquaresOptimisation(self, p0, xvals, zs, oneFwhm): """Creates the simulated mass spectrum for MassSpectrum.leastSquaresOptimisation(). p0 - parameters to be used in simulation zs - charges to be simulated oneFwhm - if True use same FWHM for each species. """ ps = self._splitPs(p0) combined = np.zeros(len(xvals)) zGauss = Gaussian() for i, p in enumerate(ps): zGauss.setParameters(p[1], p[2], p[3]) for j, z in enumerate(zs[i]): centre = utils.get_mz(p[0], z) amplitude = zGauss.calculateAmplitude(centre) if oneFwhm: combined += utils.draw_peaks['hybrid'](xvals, amplitude, centre, p0[4]) else: combined += utils.draw_peaks['hybrid'](xvals, amplitude, centre, p[4]) return combined
def plotTheoreticalMzs(self, ax, xvals, yvals, absolute=0, mass=0, **kwargs): """Used to draw the positions of calculated charge state peaks. If a value for absolute is given, it is used as the y axis position for charge state labels. All matplotlib.pyplot.plot() arguments are allowed in **kwargs. """ if not mass: mass = self.mass oneDone = False for i, z in enumerate(np.arange(100) + 1): mz = utils.get_mz(mass, z) if xvals[0] < mz < xvals[-1]: # the line if not oneDone: ax.axvline(mz, label="%s - %.1f Da +/- %.1f" % (self.name, self.mass, self.calcMassError), **kwargs) else: ax.axvline(mz, **kwargs) oneDone = True # annotation if z / 2 == float(z) / 2: lift = .1 * yvals.max() else: lift = .2 * yvals.max() if not 'color' in kwargs: color = 'blue' else: color = kwargs['color'] if not absolute: ax.text(mz, lift, '+%d' % z, color=color) else: ax.text(mz, absolute, '+%d' % z, color=color)
def calibrationFigure(self, fig, calibrationObj, spToDisplay=0, autoAxesLimits=1, colourList=0, **kwargs): # TODO(gns) - This can probably be removed only used in: # 121207_test_SpecialFigureCalibration.py, 121209_test_SpecialFigureCalibration2.py if not spToDisplay: spToDisplay = calibrationObj.calibrants.keys()[0] if not colourList: colourList = utils.colourList sps = calibrationObj.calibrants.keys() bandColour = colourList[sps.index(spToDisplay)] calibrant = calibrationObj.calibrants[spToDisplay] ax = fig.add_subplot(311) # mass spectrum calibrant.plotMsAndExtractionLimits(ax, bandColour, **kwargs) if autoAxesLimits: mzs = [ utils.get_mz(calibrant.approxMass, z) for z in calibrant.charges ] plt.xlim([min(mzs) * 0.5, max(mzs) * 2]) ax = fig.add_subplot(312) # atds calibrant.plotChargeStateAtds(ax, colourList=colourList) calibrant.plotCalibrantTdPeaks(ax, colourList=colourList) if autoAxesLimits: tdPrimes = [calibrant.tdsDoublePrime[z] for z in calibrant.charges] plt.xlim([min(tdPrimes) * 0.5, max(tdPrimes) * 2.0]) ax = fig.add_subplot(313) # fit calibrationObj.plotCalibrationCurve(ax, colourList, **kwargs)
def getMz(self,z): """Calculate the m/z value for a given charge state using the mass from self.mass """ return utils.get_mz(self.mass, z)
def getMz(self, z): """Calculate the m/z value for a given charge state using the mass from self.mass """ return utils.get_mz(self.mass, z)