Пример #1
0
    def onOK(self, evt=None):
        """Get label."""

        # get data
        label = self.label_value.GetValue()
        formula = self.formula_value.GetValue()
        theoretical = self.theoreticalMZ_value.GetValue()
        charge = self.charge_value.GetValue()
        radical = self.radical_check.GetValue()

        # check label
        if label:
            self.notation.label = label
        else:
            wx.Bell()
            return

        # get formula
        if formula:
            try:
                mspy.compound(formula)
                self.notation.formula = formula
            except:
                wx.Bell()
                return
        else:
            self.notation.formula = None

        # get m/z
        if theoretical:
            try:
                self.notation.theoretical = float(theoretical)
            except:
                wx.Bell()
                return
        else:
            self.notation.theoretical = None

        # get charge
        if charge:
            try:
                self.notation.charge = int(charge)
            except:
                wx.Bell()
                return
        else:
            self.notation.charge = None

        # get radical
        if radical:
            self.notation.radical = 1
        else:
            self.notation.radical = 0

        # close dialog
        self.EndModal(wx.ID_OK)
Пример #2
0
 def onOK(self, evt=None):
     """Get label."""
     
     # get data
     label = self.label_value.GetValue()
     formula = self.formula_value.GetValue()
     theoretical = self.theoreticalMZ_value.GetValue()
     charge = self.charge_value.GetValue()
     radical = self.radical_check.GetValue()
     
     # check label
     if label:
         self.notation.label = label
     else:
         wx.Bell()
         return
     
     # get formula
     if formula:
         try:
             mspy.compound(formula)
             self.notation.formula = formula
         except:
             wx.Bell()
             return
     else:
         self.notation.formula = None
     
     # get m/z
     if theoretical:
         try:
             self.notation.theoretical = float(theoretical)
         except:
             wx.Bell()
             return
     else:
         self.notation.theoretical = None
     
     # get charge
     if charge:
         try:
             self.notation.charge = int(charge)
         except:
             wx.Bell()
             return
     else:
         self.notation.charge = None
     
     # get radical
     if radical:
         self.notation.radical = 1
     else:
         self.notation.radical = 0
     
     # close dialog
     self.EndModal(wx.ID_OK)
Пример #3
0
def loadCompounds(path=os.path.join(config.confdir, 'compounds.xml'), clear=True):
    """Parse compounds XML and get data."""
    
    container = {}
    
    # parse XML
    document = xml.dom.minidom.parse(path)
    
    # get references
    groupTags = document.getElementsByTagName('group')
    if groupTags:
        for groupTag in groupTags:
            groupName = groupTag.getAttribute('name')
            container[groupName] = {}
            
            compoundTags = groupTag.getElementsByTagName('compound')
            if compoundTags:
                for compoundTag in compoundTags:
                    try:
                        name = compoundTag.getAttribute('name')
                        compound = mspy.compound(compoundTag.getAttribute('formula'))
                        compound.description = _getNodeText(compoundTag)
                        container[groupName][name] = compound
                    except:
                        pass
    
    # update current lib
    if container and clear:
        compounds.clear()
    for group in container:
        compounds[group] = container[group]
Пример #4
0
    def readLibraryXML(self, path):
        """Read xml library."""

        compounds = {}

        # parse XML file
        try:
            document = xml.dom.minidom.parse(path)
        except:
            return False

        if not document.getElementsByTagName("mMassCompounds"):
            return False

        # read data
        groupTags = document.getElementsByTagName("group")
        if groupTags:
            for groupTag in groupTags:
                groupName = groupTag.getAttribute("name")
                compounds[groupName] = {}
                compoundTags = groupTag.getElementsByTagName("compound")
                if compoundTags:
                    for compoundTag in compoundTags:
                        try:
                            name = compoundTag.getAttribute("name")
                            compound = mspy.compound(compoundTag.getAttribute("formula"))
                            compound.description = self._getNodeText(compoundTag)
                            compounds[groupName][name] = compound
                        except:
                            pass

        return compounds
Пример #5
0
    def readLibraryXML(self, path):
        """Read xml library."""

        compounds = {}

        # parse XML file
        try:
            document = xml.dom.minidom.parse(path)
        except:
            return False

        if not document.getElementsByTagName('mMassCompounds'):
            return False

        # read data
        groupTags = document.getElementsByTagName('group')
        if groupTags:
            for groupTag in groupTags:
                groupName = groupTag.getAttribute('name')
                compounds[groupName] = {}
                compoundTags = groupTag.getElementsByTagName('compound')
                if compoundTags:
                    for compoundTag in compoundTags:
                        try:
                            name = compoundTag.getAttribute('name')
                            compound = mspy.compound(
                                compoundTag.getAttribute('formula'))
                            compound.description = self._getNodeText(
                                compoundTag)
                            compounds[groupName][name] = compound
                        except:
                            pass

        return compounds
Пример #6
0
def loadCompounds(path=os.path.join(config.confdir, "compounds.xml"), clear=True):
    """Parse compounds XML and get data."""

    container = {}

    # parse XML
    document = xml.dom.minidom.parse(path)

    # get references
    groupTags = document.getElementsByTagName("group")
    if groupTags:
        for groupTag in groupTags:
            groupName = groupTag.getAttribute("name")
            container[groupName] = {}

            compoundTags = groupTag.getElementsByTagName("compound")
            if compoundTags:
                for compoundTag in compoundTags:
                    try:
                        name = compoundTag.getAttribute("name")
                        compound = mspy.compound(compoundTag.getAttribute("formula"))
                        compound.description = _getNodeText(compoundTag)
                        container[groupName][name] = compound
                    except:
                        pass

    # update current lib
    if container and clear:
        compounds.clear()
    for group in container:
        compounds[group] = container[group]
Пример #7
0
    def updateFormulaMass(self):
        """Update formula mass."""

        # get formula
        gain = self.itemGainFormula_value.GetValue()
        loss = self.itemLossFormula_value.GetValue()

        # show formula masses
        try:
            gain = mspy.compound(gain)
            loss = mspy.compound(loss)
            gainMass = gain.mass()
            lossMass = loss.mass()
            self.itemMoMass_value.SetValue(str(gainMass[0] - lossMass[0]))
            self.itemAvMass_value.SetValue(str(gainMass[1] - lossMass[1]))
        except:
            wx.Bell()
            self.itemMoMass_value.SetValue('')
            self.itemAvMass_value.SetValue('')
Пример #8
0
 def _checkFormula(self):
     """Check current formula."""
     
     try:
         formula = mspy.compound(self.GetValue())
         self.SetBackgroundColour(wx.NullColour)
     except:
         self.SetBackgroundColour((250,100,100))
     
     self.Refresh()
 def updateFormulaMass(self):
     """Update formula mass."""
     
     # get formula
     gain = self.itemGainFormula_value.GetValue()
     loss = self.itemLossFormula_value.GetValue()
     
     # show formula masses
     try:
         gain = mspy.compound(gain)
         loss = mspy.compound(loss)
         gainMass = gain.mass()
         lossMass = loss.mass()
         self.itemMoMass_value.SetValue(str(gainMass[0] - lossMass[0]))
         self.itemAvMass_value.SetValue(str(gainMass[1] - lossMass[1]))
     except:
         wx.Bell()
         self.itemMoMass_value.SetValue('')
         self.itemAvMass_value.SetValue('')
Пример #10
0
    def getParams(self):
        """Get all params from dialog."""

        # try to get values
        try:

            formula = self.formula_value.GetValue()
            loss = self.exchangeLoss_value.GetValue()
            gain = self.exchangeGain_value.GetValue()

            if not formula or not loss or not gain:
                raise ValueError

            self.currentCompound = mspy.compound(formula)
            lossCmpd = mspy.compound(loss)
            gainCmpd = mspy.compound(gain)

            config.envelopeFit["loss"] = str(loss)
            config.envelopeFit["gain"] = str(gain)

            config.envelopeFit["fit"] = "peaklist"
            if self.fitToSpectrum_radio.GetValue():
                config.envelopeFit["fit"] = "spectrum"

            config.envelopeFit["charge"] = int(self.charge_value.GetValue())
            config.envelopeFit["scaleMin"] = int(
                self.scaleMin_value.GetValue())
            config.envelopeFit["scaleMax"] = int(
                self.scaleMax_value.GetValue())
            config.envelopeFit["fwhm"] = float(self.fwhm_value.GetValue())
            config.envelopeFit["forceFwhm"] = self.forceFwhm_check.GetValue()
            config.envelopeFit["autoAlign"] = self.autoAlign_check.GetValue()
            config.envelopeFit["relThreshold"] = (
                float(self.relThreshold_value.GetValue()) / 100.0)

            return True

        except:
            wx.Bell()
            return False
Пример #11
0
    def getParams(self):
        """Get all params from dialog."""

        # try to get values
        try:

            formula = self.formula_value.GetValue()
            loss = self.exchangeLoss_value.GetValue()
            gain = self.exchangeGain_value.GetValue()

            if not formula or not loss or not gain:
                raise ValueError

            self.currentCompound = mspy.compound(formula)
            lossCmpd = mspy.compound(loss)
            gainCmpd = mspy.compound(gain)

            config.envelopeFit["loss"] = str(loss)
            config.envelopeFit["gain"] = str(gain)

            config.envelopeFit["fit"] = "peaklist"
            if self.fitToSpectrum_radio.GetValue():
                config.envelopeFit["fit"] = "spectrum"

            config.envelopeFit["charge"] = int(self.charge_value.GetValue())
            config.envelopeFit["scaleMin"] = int(self.scaleMin_value.GetValue())
            config.envelopeFit["scaleMax"] = int(self.scaleMax_value.GetValue())
            config.envelopeFit["fwhm"] = float(self.fwhm_value.GetValue())
            config.envelopeFit["forceFwhm"] = self.forceFwhm_check.GetValue()
            config.envelopeFit["autoAlign"] = self.autoAlign_check.GetValue()
            config.envelopeFit["relThreshold"] = float(self.relThreshold_value.GetValue()) / 100.0

            return True

        except:
            wx.Bell()
            return False
Пример #12
0
 def getParams(self):
     """Get all params from dialog."""
     
     # try to get values
     try:
         
         formula = self.formula_value.GetValue()
         loss = self.exchangeLoss_value.GetValue()
         gain = self.exchangeGain_value.GetValue()
         
         if not formula or not loss or not gain:
             raise ValueError
         
         self.currentCompound = mspy.compound(formula)
         lossCmpd = mspy.compound(loss)
         gainCmpd = mspy.compound(gain)
         
         config.envelopeFit['loss'] = str(loss)
         config.envelopeFit['gain'] = str(gain)
         
         config.envelopeFit['fit'] = 'peaklist'
         if self.fitToSpectrum_radio.GetValue():
             config.envelopeFit['fit'] = 'spectrum'
         
         config.envelopeFit['charge'] = int(self.charge_value.GetValue())
         config.envelopeFit['scaleMin'] = int(self.scaleMin_value.GetValue())
         config.envelopeFit['scaleMax'] = int(self.scaleMax_value.GetValue())
         config.envelopeFit['fwhm'] = float(self.fwhm_value.GetValue())
         config.envelopeFit['forceFwhm'] = self.forceFwhm_check.GetValue()
         config.envelopeFit['autoAlign'] = self.autoAlign_check.GetValue()
         config.envelopeFit['relThreshold'] = float(self.relThreshold_value.GetValue())/100.
         
         return True
         
     except:
         wx.Bell()
         return False
Пример #13
0
 def updateFormulaMass(self):
     """Update formula mass."""
     
     # get formula
     formula = self.itemFormula_value.GetValue()
     
     # show formula masses
     try:
         formula = mspy.compound(formula)
         mass = formula.mass()
         self.itemMoMass_value.SetValue(str(mass[0]))
         self.itemAvMass_value.SetValue(str(mass[1]))
     except:
         self.itemMoMass_value.SetValue('')
         self.itemAvMass_value.SetValue('')
Пример #14
0
    def updateFormulaMass(self):
        """Update formula mass."""

        # get formula
        formula = self.itemFormula_value.GetValue()

        # show formula masses
        try:
            formula = mspy.compound(formula)
            mass = formula.mass()
            self.itemMoMass_value.SetValue(str(mass[0]))
            self.itemAvMass_value.SetValue(str(mass[1]))
        except:
            self.itemMoMass_value.SetValue("")
            self.itemAvMass_value.SetValue("")
Пример #15
0
    def calcDataPoints(self, peaks, polarity=1):
        """Calculate requested mass and mass defect."""

        buff = []

        # init Kendrick formula
        kendrickFormula = mspy.compound(
            config.massDefectPlot["kendrickFormula"])

        # calculate data points
        for peak in peaks:

            mass = peak[0]
            if not config.massDefectPlot["ignoreCharge"] and peak[1]:
                mass = mspy.mz(peak[0],
                               1 * polarity,
                               peak[1],
                               agentFormula="H",
                               agentCharge=1)

            # calc mass defect
            md = mspy.md(
                mass=mass,
                mdType=config.massDefectPlot["yAxis"],
                kendrickFormula=kendrickFormula,
                rounding=config.massDefectPlot["nominalMass"],
            )

            # re-calculate selected mass
            if config.massDefectPlot["xAxis"] == "mz":
                mass = peak[0]

            elif config.massDefectPlot["xAxis"] == "nominal":
                mass = mspy.nominalmass(peak[0],
                                        config.massDefectPlot["nominalMass"])

            elif config.massDefectPlot["xAxis"] == "kendrick":
                mass = mspy.nominalmass(peak[0] *
                                        kendrickFormula.nominalmass() /
                                        kendrickFormula.mass(0))

            else:
                mass = peak[0]

            # append point
            buff.append((mass, md))

        return buff
Пример #16
0
    def updateLossFormulaMass(self):
        """Update loss formula mass."""

        # erase old value
        self.itemLossMoMass_value.SetValue("")

        # get current item
        focus = self.FindFocus()
        for x in range(4):
            item = self.itemLosses_values[x]

            # found focused item
            if item is focus:
                try:
                    formula = item.GetValue()
                    formula = mspy.compound(formula)
                    mass = formula.mass()
                    self.itemLossMoMass_value.SetValue(str(mass[0]))
                except:
                    pass
Пример #17
0
 def updateLossFormulaMass(self):
     """Update loss formula mass."""
     
     # erase old value
     self.itemLossMoMass_value.SetValue('')
     
     # get current item
     focus = self.FindFocus()
     for x in range(4):
         item = self.itemLosses_values[x]
         
         # found focused item
         if item is focus:
             try:
                 formula = item.GetValue()
                 formula = mspy.compound(formula)
                 mass = formula.mass()
                 self.itemLossMoMass_value.SetValue(str(mass[0]))
             except:
                 pass
Пример #18
0
    def getItemData(self):
        """Get formated item data."""

        # get data
        name = self.itemName_value.GetValue()
        description = self.itemDescription_value.GetValue()
        formula = self.itemFormula_value.GetValue()

        # check values
        if not name or not formula:
            wx.Bell()
            return False

        # make compound
        try:
            compound = mspy.compound(formula)
            compound.name = name
            compound.description = description
        except:
            wx.Bell()
            return False

        return compound
Пример #19
0
    def getItemData(self):
        """Get formated item data."""

        # get data
        name = self.itemName_value.GetValue()
        description = self.itemDescription_value.GetValue()
        formula = self.itemFormula_value.GetValue()

        # check values
        if not name or not formula:
            wx.Bell()
            return False

        # make compound
        try:
            compound = mspy.compound(formula)
            compound.name = name
            compound.description = description
        except:
            wx.Bell()
            return False

        return compound
Пример #20
0
 def onFormula(self, evt=None):
     """Check formula and calculate m/z."""
     
     if evt != None:
         evt.Skip()
     
     # user-defined m/z
     if self.mzByUser_radio.GetValue():
         return
     
     # get data
     formula = self.formula_value.GetValue()
     charge = self.charge_value.GetValue()
     radical = self.radical_check.GetValue()
     if not formula or not charge:
         self.theoreticalMZ_value.SetValue('')
         return
     
     # get m/z from formula
     try:
         compound = mspy.compound(formula)
         charge = int(charge)
         if radical:
             mz = compound.mz(charge=charge, agentFormula='e', agentCharge=-1)
         else:
             mz = compound.mz(charge=charge, agentFormula='H', agentCharge=1)
     except:
         self.theoreticalMZ_value.SetValue('')
         return
     
     # set formula
     if self.mzByFormulaMo_radio.GetValue():
         theoretical = '%0.6f' % mz[0]
         self.theoreticalMZ_value.SetValue(theoretical)
     elif self.mzByFormulaAv_radio.GetValue():
         theoretical = '%0.6f' % mz[1]
         self.theoreticalMZ_value.SetValue(theoretical)
Пример #21
0
    def onFormula(self, evt=None):
        """Check formula and calculate m/z."""

        if evt is not None:
            evt.Skip()

        # user-defined m/z
        if self.mzByUser_radio.GetValue():
            return

        # get data
        formula = self.formula_value.GetValue()
        charge = self.charge_value.GetValue()
        radical = self.radical_check.GetValue()
        if not formula or not charge:
            self.theoreticalMZ_value.SetValue("")
            return

        # get m/z from formula
        try:
            compound = mspy.compound(formula)
            charge = int(charge)
            if radical:
                mz = compound.mz(charge=charge, agentFormula="e", agentCharge=-1)
            else:
                mz = compound.mz(charge=charge, agentFormula="H", agentCharge=1)
        except:
            self.theoreticalMZ_value.SetValue("")
            return

        # set formula
        if self.mzByFormulaMo_radio.GetValue():
            theoretical = "%0.6f" % mz[0]
            self.theoreticalMZ_value.SetValue(theoretical)
        elif self.mzByFormulaAv_radio.GetValue():
            theoretical = "%0.6f" % mz[1]
            self.theoreticalMZ_value.SetValue(theoretical)
Пример #22
0
    def getParams(self):
        """Get all params from dialog."""

        # try to get values
        try:

            choices = ["fraction", "standard", "relative", "kendrick"]
            config.massDefectPlot["yAxis"] = choices[
                self.yAxis_choice.GetSelection()]

            config.massDefectPlot[
                "nominalMass"] = self.nominalMass_choice.GetStringSelection(
                ).lower()
            config.massDefectPlot["relIntCutoff"] = (
                float(self.relIntCutoff_value.GetValue()) / 100.0)
            config.massDefectPlot[
                "removeIsotopes"] = self.removeIsotopes_check.GetValue()
            config.massDefectPlot[
                "ignoreCharge"] = self.ignoreCharge_check.GetValue()
            config.massDefectPlot[
                "showNotations"] = self.showNotations_check.GetValue()
            config.massDefectPlot[
                "showAllDocuments"] = self.showAllDocuments_check.GetValue()

            formula = self.kendrickFormula_value.GetValue()
            cmpd = mspy.compound(formula)
            config.massDefectPlot["kendrickFormula"] = str(formula)
            if config.massDefectPlot["yAxis"] == "kendrick" and cmpd.mass(
                    0) == 0:
                raise ValueError

            return True

        except:
            wx.Bell()
            return False
Пример #23
0
    def getParams(self):
        """Get all params from dialog."""

        # try to get values
        try:

            choices = ['fraction', 'standard', 'relative', 'kendrick']
            config.massDefectPlot['yAxis'] = choices[
                self.yAxis_choice.GetSelection()]

            config.massDefectPlot[
                'nominalMass'] = self.nominalMass_choice.GetStringSelection(
                ).lower()
            config.massDefectPlot['relIntCutoff'] = float(
                self.relIntCutoff_value.GetValue()) / 100.
            config.massDefectPlot[
                'removeIsotopes'] = self.removeIsotopes_check.GetValue()
            config.massDefectPlot[
                'ignoreCharge'] = self.ignoreCharge_check.GetValue()
            config.massDefectPlot[
                'showNotations'] = self.showNotations_check.GetValue()
            config.massDefectPlot[
                'showAllDocuments'] = self.showAllDocuments_check.GetValue()

            formula = self.kendrickFormula_value.GetValue()
            cmpd = mspy.compound(formula)
            config.massDefectPlot['kendrickFormula'] = str(formula)
            if config.massDefectPlot['yAxis'] == 'kendrick' and cmpd.mass(
                    0) == 0:
                raise ValueError

            return True

        except:
            wx.Bell()
            return False
Пример #24
0
    def runGenerateIons(self, compounds):
        """Calculate compounds ions."""

        # run task
        try:

            # set adducts
            adducts = {
                "Na": "Na",
                "K": "K",
                "Li": "Li",
                "NH4": "NH4",
                "-H2O": "H-2O-1",
                "ACN": "CH3CN",
                "MeOH": "CH3OH",
            }

            # get max charge and polarity
            polarity = 1
            if config.compoundsSearch["maxCharge"] < 0:
                polarity = -1
            maxCharge = abs(config.compoundsSearch["maxCharge"]) + 1

            # generate compounds ions
            self.currentCompounds = []
            for name, compound in sorted(compounds.items()):

                # check compound
                if not compound.isvalid():
                    continue

                # walk in charges
                for z in range(1, maxCharge):

                    # 0 name, 1 m/z, 2 z, 3 adduct, 4 formula, 5 error, 6 matches

                    # main ion
                    mz = compound.mz(
                        z * polarity)[config.compoundsSearch["massType"]]
                    self.currentCompounds.append([
                        name, mz, z * polarity, None, compound.expression,
                        None, []
                    ])

                    # radicals
                    if config.compoundsSearch["radicals"]:
                        mz = compound.mz(
                            z * polarity, agentFormula="e",
                            agentCharge=-1)[config.compoundsSearch["massType"]]
                        self.currentCompounds.append([
                            name,
                            mz,
                            z * polarity,
                            "radical",
                            compound.expression,
                            None,
                            [],
                        ])

                    mspy.CHECK_FORCE_QUIT()

                    # add adducts
                    for item in config.compoundsSearch["adducts"]:

                        if item in ("Na", "K", "Li", "NH4", "ACN", "MeOH"):
                            formula = "%s(%s)(H-1)" % (
                                compound.expression,
                                adducts[item],
                            )
                        elif item in ("-H2O"):
                            formula = "%s(%s)" % (compound.expression,
                                                  adducts[item])

                        formula = mspy.compound(formula)
                        if formula.isvalid():
                            mz = formula.mz(
                                z *
                                polarity)[config.compoundsSearch["massType"]]
                            self.currentCompounds.append([
                                name,
                                mz,
                                z * polarity,
                                item,
                                formula.expression,
                                None,
                                [],
                            ])

                    mspy.CHECK_FORCE_QUIT()

                    # add combinations
                    for item1 in ("Na", "K", "Li", "NH4"):
                        if item1 in config.compoundsSearch["adducts"]:
                            for item2 in ("ACN", "MeOH", "-H2O"):
                                if item2 in config.compoundsSearch["adducts"]:

                                    if item2 in ("ACN", "MeOH"):
                                        adduct = "%s+%s" % (item1, item2)
                                        formula = "%s(%s)(%s)(H-2)" % (
                                            compound.expression,
                                            adducts[item1],
                                            adducts[item2],
                                        )
                                    elif item2 in ("-H2O"):
                                        adduct = "%s%s" % (item1, item2)
                                        formula = "%s(%s)(%s)(H-1)" % (
                                            compound.expression,
                                            adducts[item1],
                                            adducts[item2],
                                        )

                                    formula = mspy.compound(formula)
                                    if formula.isvalid():
                                        mz = formula.mz(z * polarity)[
                                            config.compoundsSearch["massType"]]
                                        self.currentCompounds.append([
                                            name,
                                            mz,
                                            z * polarity,
                                            adduct,
                                            formula.expression,
                                            None,
                                            [],
                                        ])

        # task canceled
        except mspy.ForceQuit:
            self.currentCompounds = []
            return
Пример #25
0
    def runGenerateIons(self, compounds):
        """Calculate compounds ions."""

        # run task
        try:

            # set adducts
            adducts = {
                'Na': 'Na',
                'K': 'K',
                'Li': 'Li',
                'NH4': 'NH4',
                '-H2O': 'H-2O-1',
                'ACN': 'CH3CN',
                'MeOH': 'CH3OH'
            }

            # get max charge and polarity
            polarity = 1
            if config.compoundsSearch['maxCharge'] < 0:
                polarity = -1
            maxCharge = abs(config.compoundsSearch['maxCharge']) + 1

            # generate compounds ions
            self.currentCompounds = []
            for name, compound in sorted(compounds.items()):

                # check compound
                if not compound.isvalid():
                    continue

                # walk in charges
                for z in range(1, maxCharge):

                    # 0 name, 1 m/z, 2 z, 3 adduct, 4 formula, 5 error, 6 matches

                    # main ion
                    mz = compound.mz(
                        z * polarity)[config.compoundsSearch['massType']]
                    self.currentCompounds.append([
                        name, mz, z * polarity, None, compound.expression,
                        None, []
                    ])

                    # radicals
                    if config.compoundsSearch['radicals']:
                        mz = compound.mz(
                            z * polarity, agentFormula='e',
                            agentCharge=-1)[config.compoundsSearch['massType']]
                        self.currentCompounds.append([
                            name, mz, z * polarity, 'radical',
                            compound.expression, None, []
                        ])

                    mspy.CHECK_FORCE_QUIT()

                    # add adducts
                    for item in config.compoundsSearch['adducts']:

                        if item in ('Na', 'K', 'Li', 'NH4', 'ACN', 'MeOH'):
                            formula = '%s(%s)(H-1)' % (compound.expression,
                                                       adducts[item])
                        elif item in ('-H2O'):
                            formula = '%s(%s)' % (compound.expression,
                                                  adducts[item])

                        formula = mspy.compound(formula)
                        if formula.isvalid():
                            mz = formula.mz(
                                z *
                                polarity)[config.compoundsSearch['massType']]
                            self.currentCompounds.append([
                                name, mz, z * polarity, item,
                                formula.expression, None, []
                            ])

                    mspy.CHECK_FORCE_QUIT()

                    # add combinations
                    for item1 in ('Na', 'K', 'Li', 'NH4'):
                        if item1 in config.compoundsSearch['adducts']:
                            for item2 in ('ACN', 'MeOH', '-H2O'):
                                if item2 in config.compoundsSearch['adducts']:

                                    if item2 in ('ACN', 'MeOH'):
                                        adduct = '%s+%s' % (item1, item2)
                                        formula = '%s(%s)(%s)(H-2)' % (
                                            compound.expression,
                                            adducts[item1], adducts[item2])
                                    elif item2 in ('-H2O'):
                                        adduct = '%s%s' % (item1, item2)
                                        formula = '%s(%s)(%s)(H-1)' % (
                                            compound.expression,
                                            adducts[item1], adducts[item2])

                                    formula = mspy.compound(formula)
                                    if formula.isvalid():
                                        mz = formula.mz(z * polarity)[
                                            config.compoundsSearch['massType']]
                                        self.currentCompounds.append([
                                            name, mz, z * polarity, adduct,
                                            formula.expression, None, []
                                        ])

        # task canceled
        except mspy.ForceQuit:
            self.currentCompounds = []
            return
Пример #26
0
    def onGenerate(self, evt=None):
        """Generate compounds ions."""

        # check processing
        if self.processing:
            return

        # clear recent
        self.currentCompounds = None
        compounds = {}

        # clear match panel
        if self.matchPanel:
            self.matchPanel.clear()

        # get params
        if not self.getParams():
            self.updateCompoundsList()
            return

        # get compounds from selected group or formula
        if self.currentTool == 'compounds':
            group = self.compounds_choice.GetStringSelection()
            if group and group in libs.compounds:
                compounds = libs.compounds[group]
        else:
            formula = self.formula_value.GetValue()
            if formula:
                try:
                    compounds[formula] = mspy.compound(formula)
                except:
                    wx.Bell()

        # check compounds
        if not compounds:
            self.updateCompoundsList()
            return

        # show processing gauge
        self.onProcessing(True)
        self.generate_butt.Enable(False)
        self.match_butt.Enable(False)
        self.annotate_butt.Enable(False)

        # do processing
        self.processing = threading.Thread(target=self.runGenerateIons,
                                           kwargs={'compounds': compounds})
        self.processing.start()

        # pulse gauge while working
        while self.processing and self.processing.isAlive():
            self.gauge.pulse()

        # update compounds list
        self._compoundsFilter = 0
        self.updateCompoundsList()

        # hide processing gauge
        self.onProcessing(False)
        self.generate_butt.Enable(True)
        self.match_butt.Enable(True)
        self.annotate_butt.Enable(True)

        # send data to match panel
        if self.matchPanel:
            self.matchPanel.setData(self.currentCompounds)
Пример #27
0
 def getParams(self):
     """Get all params from dialog."""
     
     # try to get values
     try:
         
         # compound
         compound = self.compound_value.GetValue()
         if not compound:
             return False
         
         # charging agent
         ionseriesAgent = self.ionseriesAgentFormula_value.GetValue()
         if not ionseriesAgent:
             return False
         
         # ionseries
         config.massCalculator['ionseriesAgentCharge'] = int(self.ionseriesAgentCharge_value.GetValue())
         if self.ionseriesNegative_radio.GetValue():
             config.massCalculator['ionseriesPolarity'] = -1
         else:
             config.massCalculator['ionseriesPolarity'] = 1
         
         # pattern
         patternFwhm = float(self.patternFwhm_value.GetValue())
         patternIntensity = float(self.patternIntensity_value.GetValue())
         patternBaseline = float(self.patternBaseline_value.GetValue())
         patternShift = float(self.patternShift_value.GetValue())
         config.massCalculator['patternShowPeaks'] = self.showPeaks_check.GetValue()
         
         config.massCalculator['patternPeakShape'] = 'gaussian'
         if self.patternPeakShape_choice.GetStringSelection() == 'Asymmetrical':
             config.massCalculator['patternPeakShape'] = 'gausslorentzian'
     
     except:
         wx.Bell()
         return False
     
     # check compound
     try:
         self.currentCompound = mspy.compound(compound)
     except:
         return False
     
     if not self.currentCompound.isvalid():
         wx.Bell()
         return False
     
     # check charging agent
     try:
         if ionseriesAgent != 'e':
             agent = mspy.compound(ionseriesAgent)
         config.massCalculator['ionseriesAgent'] = ionseriesAgent
     except:
         return False
     
     if ionseriesAgent == 'e':
         config.massCalculator['ionseriesAgentCharge'] = -1
         self.ionseriesAgentCharge_value.ChangeValue('-1')
     
     # check pattern values
     if patternFwhm < 0.001 \
         or patternIntensity < 1 \
         or patternBaseline >= patternIntensity:
         wx.Bell()
         return False
     else:
         config.massCalculator['patternFwhm'] = patternFwhm
         config.massCalculator['patternIntensity'] = patternIntensity
         config.massCalculator['patternBaseline'] = patternBaseline
         config.massCalculator['patternShift'] = patternShift
     
     return True
Пример #28
0
    def runGenerator(self):
        """Generate formula for given mass."""

        # run task
        try:

            self.currentFormulae = []

            # get agent charge
            agentCharge = 1
            if config.massToFormula["ionization"] == "e":
                agentCharge = -1

            # approximate CHNO composition from neutral mass
            mass = mspy.mz(
                mass=self.currentMass,
                charge=0,
                currentCharge=config.massToFormula["charge"],
                agentFormula=config.massToFormula["ionization"],
                agentCharge=agentCharge,
            )

            composition = {}
            if config.massToFormula["autoCHNO"]:
                if mass < 500:
                    composition = {
                        "C": [0, 40],
                        "H": [0, 80],
                        "N": [0, 20],
                        "O": [0, 20],
                    }
                elif mass < 1000:
                    composition = {
                        "C": [0, 80],
                        "H": [0, 130],
                        "N": [0, 30],
                        "O": [0, 30],
                    }
                elif mass < 2000:
                    composition = {
                        "C": [0, 160],
                        "H": [0, 250],
                        "N": [0, 40],
                        "O": [0, 70],
                    }
                else:
                    composition = {
                        "C": [0, 180],
                        "H": [0, 300],
                        "N": [0, 60],
                        "O": [0, 90],
                    }

            # add user-specified compositions
            minComposition = mspy.compound(
                config.massToFormula["formulaMin"]).composition()
            for el in minComposition:
                if el in composition:
                    composition[el][0] = minComposition[el]
                else:
                    composition[el] = [minComposition[el], minComposition[el]]

            maxComposition = mspy.compound(
                config.massToFormula["formulaMax"]).composition()
            for el in maxComposition:
                if el in composition:
                    composition[el][1] = maxComposition[el]
                else:
                    composition[el] = [0, maxComposition[el]]

            # calculate formulae
            formulae = mspy.formulator(
                mz=self.currentMass,
                charge=config.massToFormula["charge"],
                tolerance=config.massToFormula["tolerance"],
                units=config.massToFormula["units"],
                composition=composition,
                agentFormula=config.massToFormula["ionization"],
                agentCharge=agentCharge,
                limit=config.massToFormula["countLimit"],
            )

            # make compounds
            buff = []
            for formula in formulae:

                # make compound
                cmpd = mspy.compound(formula)
                mass = cmpd.mass(0)
                mz = cmpd.mz(
                    config.massToFormula["charge"],
                    config.massToFormula["ionization"],
                    1,
                )[0]
                error = mspy.delta(self.currentMass, mz,
                                   config.massToFormula["units"])
                errorDa = mspy.delta(self.currentMass, mz, "Da")

                # compare isotopic pattern
                similarity = None
                if config.massToFormula["checkPattern"] and cmpd.isvalid(
                        charge=config.massToFormula["charge"],
                        agentFormula=config.massToFormula["ionization"],
                ):
                    similarity = self.compareIsotopicPattern(
                        cmpd,
                        config.massToFormula["charge"],
                        config.massToFormula["ionization"],
                        errorDa,
                    )

                # count ratios
                countC = float(cmpd.count("C", groupIsotopes=True))
                countH = float(cmpd.count("H", groupIsotopes=True))
                hc = None
                if countC:
                    hc = countH / countC

                # count rdbe
                rdbe = cmpd.rdbe()

                # add item
                buff.append([
                    cmpd.formula(), mass, mz, error, hc, rdbe, similarity, cmpd
                ])

            self.currentFormulae = buff

        # task canceled
        except mspy.ForceQuit:
            return
Пример #29
0
    def getParams(self):
        """Get all params from dialog."""

        # try to get values
        try:

            # compound
            compound = self.compound_value.GetValue()
            if not compound:
                return False

            # charging agent
            ionseriesAgent = self.ionseriesAgentFormula_value.GetValue()
            if not ionseriesAgent:
                return False

            # ionseries
            config.massCalculator['ionseriesAgentCharge'] = int(
                self.ionseriesAgentCharge_value.GetValue())
            if self.ionseriesNegative_radio.GetValue():
                config.massCalculator['ionseriesPolarity'] = -1
            else:
                config.massCalculator['ionseriesPolarity'] = 1

            # pattern
            patternFwhm = float(self.patternFwhm_value.GetValue())
            patternIntensity = float(self.patternIntensity_value.GetValue())
            patternBaseline = float(self.patternBaseline_value.GetValue())
            patternShift = float(self.patternShift_value.GetValue())
            config.massCalculator[
                'patternShowPeaks'] = self.showPeaks_check.GetValue()

            config.massCalculator['patternPeakShape'] = 'gaussian'
            if self.patternPeakShape_choice.GetStringSelection(
            ) == 'Asymmetrical':
                config.massCalculator['patternPeakShape'] = 'gausslorentzian'

        except:
            wx.Bell()
            return False

        # check compound
        try:
            self.currentCompound = mspy.compound(compound)
        except:
            return False

        if not self.currentCompound.isvalid():
            wx.Bell()
            return False

        # check charging agent
        try:
            if ionseriesAgent != 'e':
                agent = mspy.compound(ionseriesAgent)
            config.massCalculator['ionseriesAgent'] = ionseriesAgent
        except:
            return False

        if ionseriesAgent == 'e':
            config.massCalculator['ionseriesAgentCharge'] = -1
            self.ionseriesAgentCharge_value.ChangeValue('-1')

        # check pattern values
        if patternFwhm < 0.001 \
            or patternIntensity < 1 \
            or patternBaseline >= patternIntensity:
            wx.Bell()
            return False
        else:
            config.massCalculator['patternFwhm'] = patternFwhm
            config.massCalculator['patternIntensity'] = patternIntensity
            config.massCalculator['patternBaseline'] = patternBaseline
            config.massCalculator['patternShift'] = patternShift

        return True
Пример #30
0
 def onGenerate(self, evt=None):
     """Generate compounds ions."""
     
     # check processing
     if self.processing:
         return
     
     # clear recent
     self.currentCompounds = None
     compounds = {}
     
     # clear match panel
     if self.matchPanel:
         self.matchPanel.clear()
     
     # get params
     if not self.getParams():
         self.updateCompoundsList()
         return
     
     # get compounds from selected group or formula
     if self.currentTool == 'compounds':
         group = self.compounds_choice.GetStringSelection()
         if group and group in libs.compounds:
             compounds = libs.compounds[group]
     else:
         formula = self.formula_value.GetValue()
         if formula:
             try:
                 compounds[formula] = mspy.compound(formula)
             except:
                 wx.Bell()
     
     # check compounds
     if not compounds:
         self.updateCompoundsList()
         return
     
     # show processing gauge
     self.onProcessing(True)
     self.generate_butt.Enable(False)
     self.match_butt.Enable(False)
     self.annotate_butt.Enable(False)
     
     # do processing
     self.processing = threading.Thread(target=self.runGenerateIons, kwargs={'compounds':compounds})
     self.processing.start()
     
     # pulse gauge while working
     while self.processing and self.processing.isAlive():
         self.gauge.pulse()
     
     # update compounds list
     self._compoundsFilter = 0
     self.updateCompoundsList()
     
     # hide processing gauge
     self.onProcessing(False)
     self.generate_butt.Enable(True)
     self.match_butt.Enable(True)
     self.annotate_butt.Enable(True)
     
     # send data to match panel
     if self.matchPanel:
         self.matchPanel.setData(self.currentCompounds)
Пример #31
0
 def runGenerateIons(self, compounds):
     """Calculate compounds ions."""
     
     # run task
     try:
         
         # set adducts
         adducts = {'Na':'Na', 'K':'K', 'Li':'Li', 'NH4':'NH4', '-H2O':'H-2O-1', 'ACN':'CH3CN', 'MeOH':'CH3OH'}
         
         # get max charge and polarity
         polarity = 1
         if config.compoundsSearch['maxCharge'] < 0:
             polarity = -1
         maxCharge = abs(config.compoundsSearch['maxCharge'])+1
         
         # generate compounds ions
         self.currentCompounds = []
         for name, compound in sorted(compounds.items()):
             
             # check compound
             if not compound.isvalid():
                 continue
             
             # walk in charges
             for z in range(1, maxCharge):
                 
                 # 0 name, 1 m/z, 2 z, 3 adduct, 4 formula, 5 error, 6 matches
                 
                 # main ion
                 mz = compound.mz(z*polarity)[config.compoundsSearch['massType']]
                 self.currentCompounds.append([name, mz, z*polarity, None, compound.expression, None, []])
                 
                 # radicals
                 if config.compoundsSearch['radicals']:
                     mz = compound.mz(z*polarity, agentFormula='e', agentCharge=-1)[config.compoundsSearch['massType']]
                     self.currentCompounds.append([name, mz, z*polarity, 'radical', compound.expression, None, []])
                 
                 mspy.CHECK_FORCE_QUIT()
                 
                 # add adducts
                 for item in config.compoundsSearch['adducts']:
                     
                     if item in ('Na', 'K', 'Li', 'NH4', 'ACN', 'MeOH'):
                         formula = '%s(%s)(H-1)' % (compound.expression, adducts[item])
                     elif item in ('-H2O'):
                         formula = '%s(%s)' % (compound.expression, adducts[item])
                     
                     formula = mspy.compound(formula)
                     if formula.isvalid():
                         mz = formula.mz(z*polarity)[config.compoundsSearch['massType']]
                         self.currentCompounds.append([name, mz, z*polarity, item, formula.expression, None, []])
                 
                 mspy.CHECK_FORCE_QUIT()
                 
                 # add combinations
                 for item1 in ('Na', 'K', 'Li', 'NH4'):
                     if item1 in config.compoundsSearch['adducts']:
                         for item2 in ('ACN', 'MeOH', '-H2O'):
                             if item2 in config.compoundsSearch['adducts']:
                                 
                                 if item2 in ('ACN', 'MeOH'):
                                     adduct = '%s+%s' % (item1, item2)
                                     formula = '%s(%s)(%s)(H-2)' % (compound.expression, adducts[item1], adducts[item2])
                                 elif item2 in ('-H2O'):
                                     adduct = '%s%s' % (item1, item2)
                                     formula = '%s(%s)(%s)(H-1)' % (compound.expression, adducts[item1], adducts[item2])
                                 
                                 formula = mspy.compound(formula)
                                 if formula.isvalid():
                                     mz = formula.mz(z*polarity)[config.compoundsSearch['massType']]
                                     self.currentCompounds.append([name, mz, z*polarity, adduct, formula.expression, None, []])
     
     # task canceled
     except mspy.ForceQuit:
         self.currentCompounds = []
         return