Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

merged ms2_recal fixed scientific annotation bug for peaks and some code cleanup #4

Open
wants to merge 23 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions Pipfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
[[source]]
name = "pypi"
url = "https://pypi.org/simple"
verify_ssl = true

[dev-packages]

[packages]
kiwisolver = ">=1.0.1"
lxml = ">=4.2.3"
matplotlib = ">=2.2.2"
numpy = ">=1.14.5"
pandas = ">=0.23.3"
pyopenms = ">=2.3.0.4"
pyparsing = ">=2.2.0"
pyteomics = ">=3.5.1"
python-dateutil = ">=2.7.3"
pytz = ">=2018.5"
scipy = ">=1.1.0"
seaborn = ">=0.9.0"
six = ">=1.11.0"
subprocess32 = ">=3.5.2"
"backports.functools_lru_cache" = ">=1.5"
Cycler = ">=0.10.0"

[requires]
python_version = "3.7"
267 changes: 267 additions & 0 deletions Pipfile.lock

Large diffs are not rendered by default.

159 changes: 143 additions & 16 deletions ProteoFileReader.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,125 @@
import numpy as np
import sys
import pyopenms as oms
import io
import os


def read_mgf(mgf_file):
mgf_reader = io.open(mgf_file, "r")

spectra = []
peaks = []
RT, pep_mz, pep_int, charge, scanID, ms2id = -1, -1, -1, -1, -1, -1
title, detector, fragmethod = "", "", ""
peak_re = re.compile(r'^([0-9.e+\-]+)\s([0-9.e+\-]+)')

for line in mgf_reader:
if len(line.strip()) == 0:
continue
if re.match(peak_re, line):
mz_int_list = re.match(peak_re, line).groups()
peaks.append([float(x) for x in mz_int_list])
elif line.startswith("TITLE"):
title = line.replace('TITLE=', '').strip()
# scan_match = re.search("^TITLE=[^.]*.([0-9]+).", line)
# ms2id_scan_match = re.search("ms2_scanId=([0-9]+)", line)
# scanID = int(scan_match.groups()[0])
# if ms2id_scan_match:
# ms2id = int(ms2id_scan_match.groups()[0])
# else:
# ms2id = -1

elif line.startswith("RTINSECONDS"):
RT = float(re.search("RTINSECONDS=(.*)", line).groups()[0])

elif line.startswith("PEPMASS"):
precursor = re.search("PEPMASS=(.*)", line).groups()[0].split()
pep_mz = float(precursor[0])
try:
pep_int = float(precursor[1])
except:
pep_int = -1.0

elif line.startswith("CHARGE"):
charge = float(re.search("CHARGE=(-?\d)", line).groups()[0])

elif line.startswith("DETECTOR"):
detector = re.search("DETECTOR=(.*)", line).groups()[0].strip()

elif line.startswith("FRAGMETHOD"):
fragmethod = re.search("FRAGMETHOD=(.*)", line).groups()[0].strip()

elif "END IONS" in line:
spectra.append(
MS2_spectrum(title, RT, pep_mz, pep_int, charge, peaks, detector=detector, fragmethod=fragmethod)
)
peaks = []
title, detector, fragmethod = "", "", ""
RT, pep_mz, pep_int, charge, scanID, ms2id = -1, -1, -1, -1, -1, -1

return spectra


def write_mgf(spectra, outfile):
out_writer = open(os.path.join(outfile), "w")
out_writer.write('MASS=Monoisotopic\n')
for spectrum in spectra:
title = spectrum.getTitle()
# scan = re.search('scan=[0-9]*', title).group(0)[5:]
# try:
# title = re.match('([A-Z])[0-9]{6}_[0-9]{2}.+?( )', title).group(0)[:-1]
# except AttributeError:
# title = re.match('[0-9]{8}_[0-9]{2}.+?( )', title).group(0)[:-1]
# title = '.'.join([title, scan, scan, str(int(spectrum.charge))])
if 'ms2_scanId' in spectrum.getTitle():
try:
ms2_parent = re.search('ms2_scanId=.*scan=([0-9]+)', spectrum.getTitle()).groups()[0]
except AttributeError:
ms2_parent = 0
title += ' ms2_scanId=%s' % ms2_parent
stavrox_mgf = """
BEGIN IONS
TITLE={}
PEPMASS={} {}
CHARGE={}+
RTINSECONDS={}
DETECTOR={}
FRAGMETHOD={}
{}
END IONS""".format(
title,
spectrum.getPrecursorMZ(),
spectrum.getPrecursorIntensity() if spectrum.getPrecursorIntensity() > 0 else 0,
int(spectrum.charge),
spectrum.getRT(),
spectrum.getDetector(),
spectrum.getFragMethod(),
"\n".join([f"{mz} {i}" for mz, i in spectrum.peaks if i > 0])
)
out_writer.write(stavrox_mgf)


def split_mgf_methods(mgf_in_file):
ms2_spectra = read_mgf(mgf_in_file)

methods = [
"CID",
"HCD",
"ETD",
"ETciD",
"EThcD"
]

for method in methods:
split_spectra = [spectrum for spectrum in ms2_spectra if spectrum.getFragMethod() == method]

if len(split_spectra) > 0:
out_file_name = '%s_%s' % (method, os.path.split(mgf_in_file)[1])
out_file_path = os.path.join(os.path.split(mgf_in_file)[0], out_file_name)

write_mgf(split_spectra, out_file_path)


def mzMLReader(in_file):
"""
Expand All @@ -26,7 +145,8 @@ def mzMLReader(in_file):
file = oms.MzMLFile()
exp = oms.MSExperiment()
file.load(in_file, exp)
return(exp)
return exp


class MS2_spectrum():
"""
Expand All @@ -50,64 +170,71 @@ class MS2_spectrum():
charge array for the peaks

"""
def __init__(self, title, RT, pepmass, pepint, charge, peaks, peakcharge=[]):
def __init__(self, title, RT, pepmz, pepint, charge, peaks, peakcharge=[], fragmethod='', detector=''):
self.title = title
self.RT = RT
self.pepmz = pepmass
self.pepmz = pepmz
self.pepint = pepint
self.charge = charge
self.peaks = peaks
self.peakcharge = peakcharge
self.fragMethod = fragmethod
self.detector = detector

def getPrecursorMZ(self):
"""
Returns the precursor mass
"""
return(self.pepmz)
return self.pepmz

def getPrecursorIntensity(self):
"""
Returns the precursor intensity
"""
return(self.pepint)
return self.pepint

def getRT(self):
"""
Returns the precursor RT
"""
return(self.RT)
return self.RT

def getTitle(self):
"""
Returns the precursor mass
"""
return(self.title)
return self.title

def getPeaks(self):
"""
Returns the spectrum peaks
"""
return(self.peaks)
return self.peaks

def getMZ(self):
"""
Returns the mz of the MS2
"""
return(self.peaks[:,0])
return self.peaks[:, 0]

def getIntensities(self):
"""
Returns the MS2 peak intensities
"""
return(self.peaks[:,1])
return self.peaks[:, 1]

def getUnchargedMass(self):
"""
Computs the uncharged mass of a fragment:
uncharged_mass = (mz * z ) - z
TODO: fix Hydrogen mass!
uncharged_mass = (mz - hydrogen mass) * z
"""
return( (self.pepmass * self.charge) - self.charge)
return (self.pepmz - 1.007276466879) * self.charge

def getFragMethod(self):
return self.fragMethod

def getDetector(self):
return self.detector

def printf(self):
print ("Title, RT, PEPMASS, PEPINT, CHARGE")
Expand All @@ -117,7 +244,7 @@ def to_mgf(self):
# need dummy values in case no peak charges are in the data
if len(self.peakcharge) == 0:
self.peakcharge = [""]*self.peaks.shape[0]
mgf_str="""
mgf_str = """
BEGIN IONS
TITLE=%s
RTINSECONDS=%s
Expand All @@ -126,7 +253,7 @@ def to_mgf(self):
%s
END IONS
""" % (self.title, self.RT, self.pepmz, self.pepint, self.charge, "\r\n".join(["%s %s %s" % (i[0], i[1], j, ) for i,j in zip(self.peaks, self.peakcharge)]))
return(mgf_str)
return mgf_str


#==============================================================================
Expand Down Expand Up @@ -343,6 +470,6 @@ def store(self, out_file, ms_list):
charge=%s
%s
peaklist end
""" % (ms.title, ms.pepmass, ms.charge, "\r\n".join(["%s %s" % (i, j ) for i,j in ms.peaks]))
""" % (ms.title, ms.pepmass, ms.charge, "\r\n".join(["%s %s" % (i, j) for i,j in ms.peaks]))
out_mgf.write(mgf_str)
out_mgf.close()
39 changes: 0 additions & 39 deletions gui.py

This file was deleted.

Loading