Esempio n. 1
0
def convertToMSSpectrum(input_):
    spectrum = pyopenms.MSSpectrum()
    for p in input_:
        rp = pyopenms.Peak1D()
        rp.setMZ(p.getMZ())
        rp.setIntensity(p.getIntensity())
        spectrum.push_back(rp)
    return spectrum
    def testMSSpectrum(self):
        spec = pyopenms.MSSpectrum()
        p = pyopenms.Peak1D()
        p.setMZ(500.0)
        p.setIntensity(1e5)
        spec.push_back(p)

        p_back, = list(spec)
        assert isinstance(p_back, pyopenms.Peak1D)
        assert p_back.getMZ() == 500.0
        assert p_back.getIntensity() == 1e5
Esempio n. 3
0
def testPeak():
    """
    @tests:
     Peak1D.__init__
     Peak1D.getIntensity
     Peak1D.getMZ
     Peak1D.setIntensity
     Peak1D.setMZ
     Peak1D.__eq__
     Peak1D.__ge__
     Peak1D.__gt__
     Peak1D.__le__
     Peak1D.__lt__
     Peak1D.__ne__
     Peak2D.__init__
     Peak2D.getIntensity
     Peak2D.getMZ
     Peak2D.getRT
     Peak2D.setIntensity
     Peak2D.setMZ
     Peak2D.setRT
     Peak2D.__eq__
     Peak2D.__ge__
     Peak2D.__gt__
     Peak2D.__le__
     Peak2D.__lt__
     Peak2D.__ne__
    """
    p1 = pyopenms.Peak1D()
    p1.setIntensity(12.0)
    assert p1.getIntensity() == 12.0
    p1.setMZ(13.0)
    assert p1.getMZ() == 13.0

    assert p1 == p1
    assert not p1 != p1

    p2 = pyopenms.Peak2D()
    assert p2 == p2
    assert not p2 != p2
    p2.setIntensity(22.0)
    assert p2.getIntensity() == 22.0
    p2.setMZ(23.0)
    assert p2.getMZ() == 23.0
    p2.setRT(45.0)
    assert p2.getRT() == 45.0
    def testMSSpectrum(self):
        spec = pyopenms.MSSpectrum()
        p = pyopenms.Peak1D()
        p.setMZ(500.0)
        p.setIntensity(1e5)
        spec.push_back(p)

        p_back, = list(spec)
        assert isinstance(p_back, pyopenms.Peak1D)
        assert p_back.getMZ() == 500.0
        assert p_back.getIntensity() == 1e5

        spec.updateRanges()
        assert isinstance(spec.getMinMZ(), float)
        assert isinstance(spec.getMaxMZ(), float)
        assert isinstance(spec.getMinIntensity(), float)
        assert isinstance(spec.getMaxIntensity(), float)

        assert spec.getMinIntensity() == 1e5
        assert spec.getMaxIntensity() == 1e5
Esempio n. 5
0
def testMSSpectrum():
    """
    @tests:
     MSSpectrum.clear
     MSSpectrum.clearMetaInfo
     MSSpectrum.findNearest
     MSSpectrum.getAcquisitionInfo
     MSSpectrum.getComment
     MSSpectrum.getDataProcessing
     MSSpectrum.getInstrumentSettings
     MSSpectrum.getKeys
     MSSpectrum.getMSLevel
     MSSpectrum.getMetaValue
     MSSpectrum.getName
     MSSpectrum.getNativeID
     MSSpectrum.getPeptideIdentifications
     MSSpectrum.getPrecursors
     MSSpectrum.getProducts
     MSSpectrum.getRT
     MSSpectrum.getSourceFile
     MSSpectrum.getType
     MSSpectrum.get_peaks
     MSSpectrum.intensityInRange
     MSSpectrum.isMetaEmpty
     MSSpectrum.metaValueExists
     MSSpectrum.push_back
     MSSpectrum.removeMetaValue
     MSSpectrum.setAcquisitionInfo
     MSSpectrum.setComment
     MSSpectrum.setDataProcessing
     MSSpectrum.setInstrumentSettings
     MSSpectrum.setMSLevel
     MSSpectrum.setMetaValue
     MSSpectrum.setName
     MSSpectrum.setNativeID
     MSSpectrum.setPeptideIdentifications
     MSSpectrum.setPrecursors
     MSSpectrum.setProducts
     MSSpectrum.setRT
     MSSpectrum.setSourceFile
     MSSpectrum.setType
     MSSpectrum.set_peaks
     MSSpectrum.size
     MSSpectrum.unify
     MSSpectrum.updateRanges
     MSSpectrum.__eq__
     MSSpectrum.__ge__
     MSSpectrum.__getitem__
     MSSpectrum.__gt__
     MSSpectrum.__le__
     MSSpectrum.__lt__
     MSSpectrum.__ne__
     """
    spec = pyopenms.MSSpectrum()
    _testMetaInfoInterface(spec)

    testSpectrumSetting(spec)

    spec.setRT(3.0)
    assert spec.getRT() == 3.0
    spec.setMSLevel(2)
    assert spec.getMSLevel() == 2
    spec.setName("spec")
    assert spec.getName() == "spec"

    p = pyopenms.Peak1D()
    p.setMZ(1000.0)
    p.setIntensity(200.0)

    spec.push_back(p)
    assert spec.size() == 1
    assert spec[0] == p

    spec.updateRanges()
    assert isinstance(spec.findNearest(0.0), int)

    assert spec == spec
    assert not spec != spec

    assert spec.get_peaks().shape == (1, 2), spec.get_peaks().shape
    def pick_spectra(self, spec: ms.MSSpectrum, peak_radius: int = 1, window_radius: float = 0.015,
                     pp_mode: str = 'int', min_int_mult: float = 0.10, strict: bool = True) -> ms.MSSpectrum():
        """Peak picks a single spectrum.

        Keyword arguments:
        spec: the spectrum to peak pick
        peak_radius: the minimum peak radius of a peak set
        window_radius: the maximum m/z window radius of a peak set
        pp_mode: the mode to use ('ltr' or 'int')
        min_int_mult: a multiplier to the maximum peak intensity in a set (for differentiating
            between signal and noise)
        strict: if False, allow a single increase in intensity in either direction

        Returns: the peak picked spectrum.
        """
        num_peaks = spec.size()
        spec.sortByPosition()

        peak_idx = []  # Intensity lookup table
        picked = [False] * num_peaks

        if pp_mode == 'int':
            for i in range(num_peaks):
                peak_idx.append([spec[i].getIntensity(), i])
            peak_idx = sorted(peak_idx, reverse=True)

        picked_spec = ms.MSSpectrum()
        picked_spec.setMSLevel(1)
        picked_spec.setRT(spec.getRT())

        for idx in range(num_peaks):  # Begin peak picking
            i = idx if pp_mode == 'ltr' else peak_idx[idx][1]
            if picked[i]:
                continue

            init_intensity = spec[i].getIntensity()
            total_intensity = spec[i].getIntensity()
            init_position = spec[i].getPos()
            left_picked, right_picked = 0, 0
            low_bound, high_bound = i, i

            sFlag = False  # Flag for when strict is False
            threshold = peak_radius

            for j in range(i - 1, -1, -1):  # Walk left
                if picked[j] or abs(spec[j].getPos() - init_position) > window_radius:
                    break

                if spec[j].getIntensity() > spec[j + 1].getIntensity():
                    if strict or sFlag or j + 1 == i:  # Don't start with an abnormal peak
                        break
                    sFlag = True
                    threshold += 1  # End the peak set with a lower peak ("increase peak_radius")

                total_intensity += spec[j].getIntensity()
                left_picked += 1
                low_bound -= 1

                if left_picked >= threshold and spec[j].getIntensity() <= init_intensity * min_int_mult:
                    break

            if left_picked < threshold:
                continue
            sFlag = False
            threshold = peak_radius

            for j in range(i + 1, num_peaks):  # Walk right
                if picked[j] or abs(spec[j].getPos() - init_position) > window_radius:
                    break

                if spec[j].getIntensity() > spec[j - 1].getIntensity():
                    if strict or sFlag or j - 1 == i:
                        break
                    sFlag = True
                    threshold += 1

                total_intensity += spec[j].getIntensity()
                right_picked += 1
                high_bound += 1

                if right_picked >= threshold and spec[j].getIntensity() <= init_intensity * min_int_mult:
                    break

            if right_picked < threshold:
                continue

            total_position = 0
            for j in range(low_bound, high_bound + 1):
                picked[j] = True
                if total_intensity != 0:
                    total_position += spec[j].getPos() * (spec[j].getIntensity() / total_intensity)

            p = ms.Peak1D()
            p.setIntensity(total_intensity)
            p.setPos(total_position)
            picked_spec.push_back(p)

        return picked_spec
Esempio n. 7
0
def findPattern(monomass, charge, peaks, tolerance):
    # make assumtion about Nr of peaks that should occour
    sumP = 0
    pattern = glyxtoolms.masses.calcIsotopicPatternFromMass(
        monomass * charge, 10)
    for N, p in pattern:
        if sumP > 0.99:
            break
        sumP += p

    candidates = []
    for e in range(0, N):
        mass = monomass + e * glyxtoolms.masses.MASS["H+"] / charge
        # find highest peak
        highest = None
        for peak in peaks:
            if peak.getMZ() < mass - tolerance:
                continue
            if peak.getMZ() > mass + tolerance:
                break
            if highest == None or highest.getIntensity() < peak.getIntensity():
                highest = peak
        if highest == None:
            highest = pyopenms.Peak1D()
            highest.setMZ(mass)
            highest.setIntensity(0.0)
        candidates.append(highest)
    if len(candidates) < 2:
        return None
    sumIntensity = sum([p.getIntensity() for p in candidates])
    if sumIntensity == 0:
        return None
    # calculate pattern
    #pattern = glyxtoolms.masses.calcIsotopicPatternFromMass(monomass*charge,len(candidates))
    pattern = pattern[:len(candidates)]
    sumP = sum([b for a, b in pattern])

    error = 0
    x = []
    y = []
    estimate = []
    for a, b in pattern:
        intensity_est = b * sumIntensity
        try:
            intensity_exp = candidates[a].getIntensity()
        except:
            print pattern, candidates
            raise Exception("foo")
        x.append(candidates[a].getMZ())
        y.append(intensity_exp)
        estimate.append(intensity_est)
        error += (intensity_est - intensity_exp)**2
    error = math.sqrt(error)
    error = error / sumIntensity * 100
    result = {}
    result["error"] = error
    result["mass"] = monomass
    result["x"] = x
    result["y"] = y
    result["estimate"] = estimate
    result["sum"] = sumIntensity
    result["charge"] = charge
    return result
Esempio n. 8
0
    def load(self, ifname: str, peakMap: pyopenms.MSExperiment):
        inF = open(ifname, 'r')

        lines = inF.read().splitlines()
        curLine = 0
        nLines = len(lines)

        #generate spectrum list
        spectraList = list()
        while curLine < nLines:
            if lines[curLine] == 'BEGIN IONS':
                spectrum = pyopenms.MSSpectrum()
                spectrum.setMSLevel(2)
                precursor = pyopenms.Precursor()

                curLine += 1
                while curLine < nLines:
                    if lines[curLine][0].isalpha():
                        match = re.search('^([A-Z]+)=(.+)$', lines[curLine])
                        if match.group(1) == 'TITLE':
                            titleData = match.group(2).split(',')

                            for s in titleData:
                                if re.search('^scan[_=]', s):
                                    match = re.search('^scan[_=]([0-9]+)', s)
                                    assert (len(match.groups()) == 1)
                                    spectrum.setNativeID('scan={}'.format(
                                        match.group(1)))

                        elif match.group(1) == 'PEPMASS':
                            preMZ = [
                                float(x) for x in match.group(2).split(' ')
                            ]
                            assert (len(preMZ) <= 2)
                            precursor.setMZ(preMZ[0])
                            if len(preMZ) > 1:
                                precursor.setIntensity(preMZ[1])

                        elif match.group(1) == 'CHARGE':
                            match = re.search('^([0-9])[+-]{0,1}$',
                                              match.group(2))
                            assert (len(match.groups()) == 1)
                            precursor.setCharge(int(match.group(1)))

                        elif match.group(1) == 'RTINSECONDS':
                            spectrum.setRT(float(match.group(2)))

                    elif lines[curLine][0].isnumeric():
                        while curLine < nLines and lines[curLine] != 'END IONS':
                            ion = [float(x) for x in lines[curLine].split(' ')]
                            assert (len(ion) == 2)
                            ion_temp = pyopenms.Peak1D()
                            ion_temp.setMZ(ion[0])
                            ion_temp.setIntensity(ion[1])
                            spectrum.push_back(ion_temp)
                            curLine += 1

                        break

                    curLine += 1
                spectrum.setPrecursors([precursor])
                spectraList.append(spectrum)

            curLine += 1

        peakMap.setSpectra(spectraList)