Specter_Standalone.py 29.3 KB
Newer Older
Ryan Peckner's avatar
Ryan Peckner committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
import sys 
import time
import pandas as pd
import pymzml
import numpy as np
from numpy import linalg
from scipy import stats
from scipy import integrate
from scipy import sparse
from scipy.optimize import fsolve
from scipy.stats import mvn
import os
import random
import itertools
import cPickle as pickle
from functools import partial
import sparse_nnls 
import multiprocessing
import sqlite3
import struct
import zlib
import csv
import re
import tqdm
from contextlib import closing

def RegressSpectraOntoLibrary(DIASpectrum,Library,tol,maxWindowOffset):     
        
            precMZ = float(DIASpectrum[1])     
            precRT = float(DIASpectrum[2])  #MS2 scan retention time, in minutes
            index = DIASpectrum[3]
            windowWidth = DIASpectrum[4]
            
            DIASpectrum = np.array(DIASpectrum[0])
            
            RefSpectraLibrary = Library

            LibraryCoeffs = []
            
            if len(DIASpectrum.shape) == 2:
                
                if windowWidth > 0:
                    CandidateRefSpectraLibrary = [spectrum['Spectrum'] for key,spectrum in RefSpectraLibrary.iteritems() if 
                                                                abs(float(spectrum['PrecursorMZ']) - precMZ) < windowWidth/2]
                    MassWindowCandidates = [key for key,spectrum in RefSpectraLibrary.iteritems() if 
                                                                abs(float(spectrum['PrecursorMZ']) - precMZ) < windowWidth/2]
                else:
                    CandidateRefSpectraLibrary = [spectrum['Spectrum'] for key,spectrum in RefSpectraLibrary.iteritems() if 
                                                                        float(spectrum['PrecursorMZ']) > precMZ - maxWindowOffset/2]   
                    MassWindowCandidates = [key for key,spectrum in RefSpectraLibrary.iteritems() if 
                                                                        float(spectrum['PrecursorMZ']) > precMZ - maxWindowOffset/2]
                

                #MERGING OF POINTS IN ACQUIRED SPECTRUM WITH NEARBY M/Z COORDINATES
                MergedDIASpecCoordIndices = np.searchsorted(DIASpectrum[:,0]+tol*DIASpectrum[:,0],DIASpectrum[:,0])
                MergedDIASpecCoords = DIASpectrum[np.unique(MergedDIASpecCoordIndices),0]
                MergedDIASpecIntensities = [np.mean(DIASpectrum[np.where(MergedDIASpecCoordIndices == i)[0],1]) for i in np.unique(MergedDIASpecCoordIndices)]
                DIASpectrum = np.array((MergedDIASpecCoords,MergedDIASpecIntensities)).transpose()
              
                #FILTER LIBRARY SPECTRA BY THE CONDITION THAT SOME NUMBER OF THEIR 10 MOST INTENSE PEAKS BELONG TO THE DIA SPECTRUM
                CentroidBreaks = np.concatenate((DIASpectrum[:,0]-tol*DIASpectrum[:,0],DIASpectrum[:,0]+tol*DIASpectrum[:,0]))               
                CentroidBreaks = np.sort(CentroidBreaks)
                
                LocateReferenceCoordsInDIA = [np.searchsorted(CentroidBreaks,M[:,0]) for M in CandidateRefSpectraLibrary]
                   
                TopTenPeaksCoordsInDIA = [np.searchsorted(CentroidBreaks,M[np.argsort(-M[:,1])[0:min(10,M.shape[0])],0]) for M in CandidateRefSpectraLibrary] 
                ReferencePeaksInDIA = [i for i in range(len(MassWindowCandidates)) if 
                                            len([a for a in TopTenPeaksCoordsInDIA[i] if a % 2 == 1]) > 5] #min(3,CandidateRefSpectraLibrary[i].shape[0])]     
                ProportionOfReferencePeaksInDIA = [len([a for a in TopTenPeaksCoordsInDIA[i] if a % 2 == 1])/CandidateRefSpectraLibrary[i].shape[0]
                                                             for i in range(len(MassWindowCandidates))]                          
                
                RefPeptideCandidatesLocations = [LocateReferenceCoordsInDIA[i] for i in ReferencePeaksInDIA]   
                RefPeptideCandidateList = [CandidateRefSpectraLibrary[i] for i in ReferencePeaksInDIA]               
                RefPeptideCandidates = [MassWindowCandidates[i] for i in ReferencePeaksInDIA]                
                NormalizedRefPeptideCandidateList = [M[:,1]/sum(M[:,1]) for M in RefPeptideCandidateList]
                           
                RefSpectraLibrarySparseRowIndices = (np.array([i for v in RefPeptideCandidatesLocations for i in v if i % 2 == 1]) + 1)/2                 
                RefSpectraLibrarySparseRowIndices = RefSpectraLibrarySparseRowIndices - 1 #Respect the 0-indexing                
                RefSpectraLibrarySparseColumnIndices = np.array([i for j in range(len(RefPeptideCandidates)) for i in [j]*len([k for k in RefPeptideCandidatesLocations[j] if k % 2 == 1])]) 
                RefSpectraLibrarySparseMatrixEntries = np.array([NormalizedRefPeptideCandidateList[k][i] for k in range(len(NormalizedRefPeptideCandidateList)) for i in range(len(NormalizedRefPeptideCandidateList[k])) 
                                                                         if RefPeptideCandidatesLocations[k][i] % 2 == 1])
                
                if (len(RefSpectraLibrarySparseRowIndices) > 0 and len(RefSpectraLibrarySparseColumnIndices) > 0 and len(RefSpectraLibrarySparseMatrixEntries) > 0):                                                             
                      
                    UniqueRowIndices = [i for i in set(RefSpectraLibrarySparseRowIndices)]
                    UniqueRowIndices.sort()
                    
                    DIASpectrumIntensities=DIASpectrum[UniqueRowIndices,1]  #Project the spectrum to those m/z bins at which at least one column of the coefficient matrix has a nonzero entry
                    DIASpectrumIntensities=np.append(DIASpectrumIntensities,[0])    #Add a zero to the end of the DIA data vector to penalize 
                                                                                    #peaks of library spectra not present in the DIA spectrum                
                    
                    
                    #AUGMENT THE LIBRARY MATRIX WITH TOTAL ION INTENSITIES OF PEAKS OF LIBRARY SPECTRA THAT DON'T CORRESPOND TO PEAKS IN DIA SPECTRUM
                    ReferencePeaksNotInDIA = np.array([k for v in RefPeptideCandidatesLocations for k in range(len(v)) if v[k] % 2 == 0])                             
                    SparseColumnIndicesForPeaksNotInDIA = np.arange(len(RefPeptideCandidates))
                    NumRowsOfLibraryMatrix = max(UniqueRowIndices)
                    SparseRowIndicesForPeaksNotInDIA = [NumRowsOfLibraryMatrix+1]*len(SparseColumnIndicesForPeaksNotInDIA)                                   
                    #Duplicate (i,j) entries are summed together, yielding total ion intensities                
                    SparseMatrixEntriesForPeaksNotInDIA = np.array([np.sum([NormalizedRefPeptideCandidateList[j][k] 
                                                                for k in range(len(NormalizedRefPeptideCandidateList[j])) 
                                                                if RefPeptideCandidatesLocations[j][k] % 2 == 0]) 
                                                                for j in range(len(NormalizedRefPeptideCandidateList))])
                    
                    SparseRowIndices=np.append(RefSpectraLibrarySparseRowIndices,SparseRowIndicesForPeaksNotInDIA)
                    SparseColumnIndices=np.append(RefSpectraLibrarySparseColumnIndices,SparseColumnIndicesForPeaksNotInDIA)
                    SparseMatrixEntries=np.append(RefSpectraLibrarySparseMatrixEntries,SparseMatrixEntriesForPeaksNotInDIA)    
                                  
                    SparseRowIndices = stats.rankdata(SparseRowIndices,method='dense').astype(int) - 1 #Renumber the row indices according to the projected spectrum,
                                                                                                    #respecting the 0-indexing                
                    LibrarySparseMatrix = sparse.coo_matrix((SparseMatrixEntries,(SparseRowIndices,SparseColumnIndices)))
                    LibraryCoeffs = sparse_nnls.lsqnonneg(LibrarySparseMatrix,DIASpectrumIntensities,{'show_progress': False})               
                    LibraryCoeffs = LibraryCoeffs['x']
                                
            NonzeroCoeffs = [c for c in LibraryCoeffs if c != 0]
            NonzeroCoeffsAboveThreshold = NonzeroCoeffs
            
            Output = [[0,index,0,0,0,0]]   
        
            if len(NonzeroCoeffs) > 0:        
                RefSpectraIDs = [RefPeptideCandidates[j] for j in range(len(RefPeptideCandidates)) if LibraryCoeffs[j] != 0]
                Output = [[NonzeroCoeffsAboveThreshold[i],index,RefSpectraIDs[i][0],RefSpectraIDs[i][1],precMZ,precRT] for i in range(len(NonzeroCoeffsAboveThreshold))]
                
            return Output

Ryan Peckner's avatar
Ryan Peckner committed
125
def RegressSpectraOntoLibraryWithDecoys(DIASpectrum,Library,tol,maxWindowOffset):
Ryan Peckner's avatar
Ryan Peckner committed
126
127
           
        
Ryan Peckner's avatar
Ryan Peckner committed
128
129
130
131
            precMZ = float(DIASpectrum[1])     
            precRT = float(DIASpectrum[2])  #MS2 scan retention time, in minutes
            index = DIASpectrum[3]
            windowWidth = DIASpectrum[4]            
Ryan Peckner's avatar
Ryan Peckner committed
132
            
Ryan Peckner's avatar
Ryan Peckner committed
133
            DIASpectrum = np.array(DIASpectrum[0])
Ryan Peckner's avatar
Ryan Peckner committed
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158

            RefSpectraLibrary = Library
            
            LibraryCoeffs = []
            
            if len(DIASpectrum.shape) == 2:
                
                if windowWidth > 0:
                    CandidateRefSpectraLibrary = [spectrum['Spectrum'] for key,spectrum in RefSpectraLibrary.iteritems() if 
                                                                abs(float(spectrum['PrecursorMZ']) - precMZ) < windowWidth/2]
                    MassWindowCandidates = [key for key,spectrum in RefSpectraLibrary.iteritems() if 
                                                                abs(float(spectrum['PrecursorMZ']) - precMZ) < windowWidth/2]
                    CandidateDecoyLibrary = [spectrum['Spectrum'] for key,spectrum in RefSpectraLibrary.iteritems() if 
                                                                        windowWidth/2 <= abs(float(spectrum['PrecursorMZ']) - precMZ) <= windowWidth]
                    MassWindowDecoyCandidates = [("DECOY_"+key[0],key[1]) for key,spectrum in RefSpectraLibrary.iteritems() if 
                                                                        windowWidth/2 <= abs(float(spectrum['PrecursorMZ']) - precMZ) <= windowWidth]
                else:
                    CandidateRefSpectraLibrary = [spectrum['Spectrum'] for key,spectrum in RefSpectraLibrary.iteritems() if 
                                                                        float(spectrum['PrecursorMZ']) > precMZ - maxWindowOffset/2]
                    MassWindowCandidates = [key for key,spectrum in RefSpectraLibrary.iteritems() if 
                                                                        float(spectrum['PrecursorMZ']) > precMZ - maxWindowOffset/2]
                    CandidateDecoyLibrary = [spectrum['Spectrum'] for key,spectrum in RefSpectraLibrary.iteritems() if 
                                                                       precMZ - maxWindowOffset <= float(spectrum['PrecursorMZ']) <= precMZ - maxWindowOffset/2]                 
                    MassWindowDecoyCandidates = [("DECOY_"+key[0],key[1]) for key,spectrum in RefSpectraLibrary.iteritems() if 
                                                                        precMZ - maxWindowOffset <= float(spectrum['PrecursorMZ']) <= precMZ - maxWindowOffset/2]
Ryan Peckner's avatar
Ryan Peckner committed
159
160
161
162
163
164
165
                
                #MERGING OF POINTS IN ACQUIRED SPECTRUM WITH NEARBY M/Z COORDINATES
                MergedDIASpecCoordIndices = np.searchsorted(DIASpectrum[:,0]+tol*DIASpectrum[:,0],DIASpectrum[:,0])
                MergedDIASpecCoords = DIASpectrum[np.unique(MergedDIASpecCoordIndices),0]
                MergedDIASpecIntensities = [np.mean(DIASpectrum[np.where(MergedDIASpecCoordIndices == i)[0],1]) for i in np.unique(MergedDIASpecCoordIndices)]
                DIASpectrum = np.array((MergedDIASpecCoords,MergedDIASpecIntensities)).transpose()
                
Ryan Peckner's avatar
Ryan Peckner committed
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
                #FILTER LIBRARY SPECTRA BY THE CONDITION THAT SOME NUMBER OF THEIR 10 MOST INTENSE PEAKS BELONG TO THE DIA SPECTRUM
                CentroidBreaks = np.concatenate((DIASpectrum[:,0]-tol*DIASpectrum[:,0],DIASpectrum[:,0]+tol*DIASpectrum[:,0]))               
                CentroidBreaks.sort()
                
                LocateReferenceCoordsInDIA = [np.searchsorted(CentroidBreaks,M[:,0]) for M in CandidateRefSpectraLibrary]
                #Hard cutoff - at least 5 of the 10 most intense peaks (or all peaks if there are fewer than 3) of reference spectrum must appear in acquired spectrum
                
                TopTenPeaksCoordsInDIA = [np.searchsorted(CentroidBreaks,M[np.argsort(-M[:,1])[0:min(10,M.shape[0])],0]) for M in CandidateRefSpectraLibrary] 
                ReferencePeaksInDIA = [i for i in range(len(MassWindowCandidates)) if 
                                            len([a for a in TopTenPeaksCoordsInDIA[i] if a % 2 == 1]) > 5] #min(3,CandidateRefSpectraLibrary[i].shape[0])]     
                

                #SHIFT ALL FRAGMENT ION PEAKS OF ALL DECOY SPECTRA BY 20 M/Z TO ENSURE DISSIMILARITY FROM REAL SPECTRA
                LocateDecoyCoordsInDIA = [np.searchsorted(CentroidBreaks,M[:,0]+20) for M in CandidateDecoyLibrary]
                TopTenPeaksCoordsInDIA = [np.searchsorted(CentroidBreaks,M[np.argsort(-M[:,1])[0:min(10,M.shape[0])],0]+20) for M in CandidateDecoyLibrary]
                DecoyPeaksInDIA = [i for i in range(len(MassWindowDecoyCandidates)) if 
                                            len([a for a in TopTenPeaksCoordsInDIA[i] if a % 2 == 1]) > 5] #min(3,CandidateRefSpectraLibrary[i].shape[0])]     
                               
                
                RefPeptideCandidatesLocations = [LocateReferenceCoordsInDIA[i] for i in ReferencePeaksInDIA]   
                RefPeptideCandidateList = [CandidateRefSpectraLibrary[i] for i in ReferencePeaksInDIA]               
                RefPeptideCandidates = [MassWindowCandidates[i] for i in ReferencePeaksInDIA]                
                NormalizedRefPeptideCandidateList = [M[:,1]/sum(M[:,1]) for M in RefPeptideCandidateList]
                
                DecoyCandidatesLocations = [LocateDecoyCoordsInDIA[i] for i in DecoyPeaksInDIA]
                DecoyCandidateList = [CandidateDecoyLibrary[i] for i in DecoyPeaksInDIA]               
                DecoyCandidates = [MassWindowDecoyCandidates[i] for i in DecoyPeaksInDIA]                
                NormalizedDecoyCandidateList = [M[:,1]/sum(M[:,1]) for M in DecoyCandidateList]
                
                RefSpectraLibrarySparseRowIndices = (np.array([i for v in RefPeptideCandidatesLocations for i in v if i % 2 == 1]) + 1)/2                 
                RefSpectraLibrarySparseRowIndices = RefSpectraLibrarySparseRowIndices - 1 #Respect the 0-indexing                
                RefSpectraLibrarySparseColumnIndices = np.array([i for j in range(len(RefPeptideCandidates)) for i in [j]*len([k for k in RefPeptideCandidatesLocations[j] if k % 2 == 1])]) 
                RefSpectraLibrarySparseMatrixEntries = np.array([NormalizedRefPeptideCandidateList[k][i] for k in range(len(NormalizedRefPeptideCandidateList)) for i in range(len(NormalizedRefPeptideCandidateList[k])) 
                                                                         if RefPeptideCandidatesLocations[k][i] % 2 == 1])
                
                if (len(RefSpectraLibrarySparseRowIndices) > 0 and len(RefSpectraLibrarySparseColumnIndices) > 0 and len(RefSpectraLibrarySparseMatrixEntries) > 0):                                                             
                    DecoyLibrarySparseRowIndices = (np.array([i for v in DecoyCandidatesLocations for i in v if i % 2 == 1]) + 1)/2                 
                    DecoyLibrarySparseRowIndices = DecoyLibrarySparseRowIndices - 1 #Respect the 0-indexing                
                    DecoyLibrarySparseColumnIndices = max(RefSpectraLibrarySparseColumnIndices) + 1 + np.array([i for j in range(len(DecoyCandidates)) for i in [j]*len([k for k in DecoyCandidatesLocations[j] if k % 2 == 1])]) 
                    DecoyLibrarySparseMatrixEntries = np.array([NormalizedDecoyCandidateList[k][i] for k in range(len(NormalizedDecoyCandidateList)) for i in range(len(DecoyCandidatesLocations[k])) 
                                                                             if DecoyCandidatesLocations[k][i] % 2 == 1])
                                                                 
                             
Ryan Peckner's avatar
Ryan Peckner committed
209
                    UniqueRowIndices = np.unique(np.concatenate((RefSpectraLibrarySparseRowIndices,DecoyLibrarySparseRowIndices)))
Ryan Peckner's avatar
Ryan Peckner committed
210
                    UniqueRowIndices = np.array(np.sort(UniqueRowIndices),dtype=int)
Ryan Peckner's avatar
Ryan Peckner committed
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
                    
                    DIASpectrumIntensities=DIASpectrum[UniqueRowIndices,1]  #Project the spectrum to those m/z bins at which at least one column of the coefficient matrix has a nonzero entry

                    DIASpectrumIntensities=np.append(DIASpectrumIntensities,[0])    #Add a zero to the end of the DIA data vector to penalize 
                                                                                    #peaks of library spectra not present in the DIA spectrum                
                       
                    #AUGMENT THE LIBRARY MATRIX WITH TOTAL ION INTENSITIES OF PEAKS OF LIBRARY SPECTRA THAT DON'T CORRESPOND TO PEAKS IN DIA SPECTRUM
                    ReferencePeaksNotInDIA = np.array([k for v in RefPeptideCandidatesLocations for k in range(len(v)) if v[k] % 2 == 0])                             
                    SparseColumnIndicesForPeaksNotInDIA = np.arange(len(RefPeptideCandidates))
                    NumRowsOfLibraryMatrix = max(UniqueRowIndices)
                    SparseRowIndicesForPeaksNotInDIA = [NumRowsOfLibraryMatrix+1]*len(SparseColumnIndicesForPeaksNotInDIA)                                   
                    #Duplicate (i,j) entries are summed together, yielding total ion intensities                
                    SparseMatrixEntriesForPeaksNotInDIA = np.array([np.sum([NormalizedRefPeptideCandidateList[j][k] 
                                                                for k in range(len(NormalizedRefPeptideCandidateList[j])) 
                                                                if RefPeptideCandidatesLocations[j][k] % 2 == 0]) 
                                                                for j in range(len(NormalizedRefPeptideCandidateList))])
                    
                    RefSpectraLibrarySparseRowIndices=np.append(RefSpectraLibrarySparseRowIndices,SparseRowIndicesForPeaksNotInDIA)
                    RefSpectraLibrarySparseColumnIndices=np.append(RefSpectraLibrarySparseColumnIndices,SparseColumnIndicesForPeaksNotInDIA)
                    RefSpectraLibrarySparseMatrixEntries=np.append(RefSpectraLibrarySparseMatrixEntries,SparseMatrixEntriesForPeaksNotInDIA)    
                    
                    DecoyPeaksNotInDIA = np.array([k for v in DecoyCandidatesLocations for k in range(len(v)) if v[k] % 2 == 0])                             
                    SparseColumnIndicesForDecoyPeaksNotInDIA = np.arange(len(DecoyCandidates))
                    NumRowsOfLibraryMatrix = max(UniqueRowIndices)
                    SparseRowIndicesForDecoyPeaksNotInDIA = [NumRowsOfLibraryMatrix+1]*len(SparseColumnIndicesForDecoyPeaksNotInDIA)                                   
                    #Duplicate (i,j) entries are summed together, yielding total ion intensities                
                    SparseMatrixEntriesForDecoyPeaksNotInDIA = np.array([np.sum([NormalizedDecoyCandidateList[j][k] 
                                                                for k in range(len(NormalizedDecoyCandidateList[j])) 
                                                                if DecoyCandidatesLocations[j][k] % 2 == 0]) 
                                                                for j in range(len(NormalizedDecoyCandidateList))])
                   
                    DecoyLibrarySparseRowIndices = np.append(DecoyLibrarySparseRowIndices,SparseRowIndicesForDecoyPeaksNotInDIA) 
                    DecoyLibrarySparseColumnIndices=np.append(DecoyLibrarySparseColumnIndices,max(RefSpectraLibrarySparseColumnIndices)+SparseColumnIndicesForDecoyPeaksNotInDIA + 1)
                    DecoyLibrarySparseMatrixEntries=np.append(DecoyLibrarySparseMatrixEntries,SparseMatrixEntriesForDecoyPeaksNotInDIA) 
                    
                    SparseRowIndices = np.concatenate((RefSpectraLibrarySparseRowIndices,DecoyLibrarySparseRowIndices))
                    SparseColumnIndices = np.concatenate((RefSpectraLibrarySparseColumnIndices,DecoyLibrarySparseColumnIndices))
                    SparseMatrixEntries = np.concatenate((RefSpectraLibrarySparseMatrixEntries,DecoyLibrarySparseMatrixEntries))
                    
                    SparseRowIndices = stats.rankdata(SparseRowIndices,method='dense').astype(int) - 1 #Renumber the row indices according to the projected spectrum,
                                                                                                    #respecting the 0-indexing
                  
                    LibrarySparseMatrix = sparse.coo_matrix((SparseMatrixEntries,(SparseRowIndices,SparseColumnIndices)))
                    LibraryCoeffs = sparse_nnls.lsqnonneg(LibrarySparseMatrix,DIASpectrumIntensities,{'show_progress': False})               
                    LibraryCoeffs = LibraryCoeffs['x']
                             
            NonzeroCoeffs = [c for c in LibraryCoeffs if c != 0]
            NonzeroCoeffsAboveThreshold = NonzeroCoeffs
            
            Output = [[0,index,0,0,0,0]]   
        
            if len(NonzeroCoeffs) > 0:        
                RefSpectraIDs = [RefPeptideCandidates[j] for j in range(len(RefPeptideCandidates)) if LibraryCoeffs[j] != 0]
                DecoyIDs = [DecoyCandidates[j] for j in range(len(DecoyCandidates)) if LibraryCoeffs[max(RefSpectraLibrarySparseColumnIndices)+1+j] != 0]
                
                RefSpectraIDs = RefSpectraIDs+DecoyIDs
                Output = [[NonzeroCoeffsAboveThreshold[i],index,RefSpectraIDs[i][0],RefSpectraIDs[i][1],precMZ,precRT] for i in range(len(NonzeroCoeffsAboveThreshold))]
                
            return Output


if __name__ == "__main__":
    
    args = sys.argv

    mzMLname = args[1]  #dirName = args[1]
    
    libName = args[2]
    
    Index = 0       
    if len(args) >= 4:
        Index = int(args[3])
    
    StartOrEnd = "start" 
    if len(args) >= 5:
        StartOrEnd = args[4]
    
    numProcessors = multiprocessing.cpu_count()
    if len(args) >= 6:
        numProcessors = int(args[5])
    
    instrument = 'orbitrap'    
    if len(args) == 7:
        instrument=args[6]

    delta = 10
    if len(args) == 8:
    	delta=float(args[7])
        
    #Cast the spectral library as a dictionary  
        
    start = time.time()
    
    libPath = os.path.expanduser(libName+'.blib')
Ryan Peckner's avatar
Ryan Peckner committed
305
    if os.path.exists(libPath) and not os.path.exists(libName+'_PythonLibrary'):
Ryan Peckner's avatar
Ryan Peckner committed
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
        Lib = sqlite3.connect(libPath)
        LibPrecursorInfo = pd.read_sql("SELECT * FROM RefSpectra",Lib)
    
        SpectraLibrary = {}
    
        for i in range(len(LibPrecursorInfo)):
            precursorID = str(LibPrecursorInfo['id'][i])
            precursorKey = (LibPrecursorInfo['peptideModSeq'][i],LibPrecursorInfo['precursorCharge'][i]) 
            NumPeaks = pd.read_sql("SELECT numPeaks FROM RefSpectra WHERE id = "+precursorID,Lib)['numPeaks'][0]
            
            SpectrumMZ = pd.read_sql("SELECT peakMZ FROM RefSpectraPeaks WHERE RefSpectraID = " + precursorID,Lib)['peakMZ'][0]
            SpectrumIntensities = pd.read_sql("SELECT peakIntensity FROM RefSpectraPeaks WHERE RefSpectraID = "+precursorID,Lib)['peakIntensity'][0]
            
            if len(SpectrumMZ) == 8*NumPeaks and len(SpectrumIntensities) == 4*NumPeaks:
                SpectraLibrary.setdefault(precursorKey,{})
                SpectrumMZ = struct.unpack('d'*NumPeaks,SpectrumMZ)
                SpectrumIntensities = struct.unpack('f'*NumPeaks,SpectrumIntensities)
                SpectraLibrary[precursorKey]['Spectrum'] = np.array((SpectrumMZ,SpectrumIntensities)).T
                SpectraLibrary[precursorKey]['PrecursorMZ'] = LibPrecursorInfo['precursorMZ'][i]
                SpectraLibrary[precursorKey]['PrecursorRT'] = LibPrecursorInfo['retentionTime'][i]      #The library retention time is given in minutes
            elif len(SpectrumIntensities) == 4*NumPeaks:
                SpectraLibrary.setdefault(precursorKey,{})
                SpectrumMZ = struct.unpack('d'*NumPeaks,zlib.decompress(SpectrumMZ))
                SpectrumIntensities = struct.unpack('f'*NumPeaks,SpectrumIntensities)
                SpectraLibrary[precursorKey]['Spectrum'] = np.array((SpectrumMZ,SpectrumIntensities)).T
                SpectraLibrary[precursorKey]['PrecursorMZ'] = LibPrecursorInfo['precursorMZ'][i]
                SpectraLibrary[precursorKey]['PrecursorRT'] = LibPrecursorInfo['retentionTime'][i]
            elif len(SpectrumMZ) == 8*NumPeaks:
                SpectraLibrary.setdefault(precursorKey,{})
                SpectrumMZ = struct.unpack('d'*NumPeaks,SpectrumMZ)
                SpectrumIntensities = struct.unpack('f'*NumPeaks,zlib.decompress(SpectrumIntensities))
                SpectraLibrary[precursorKey]['Spectrum'] = np.array((SpectrumMZ,SpectrumIntensities)).T
                SpectraLibrary[precursorKey]['PrecursorMZ'] = LibPrecursorInfo['precursorMZ'][i]
                SpectraLibrary[precursorKey]['PrecursorRT'] = LibPrecursorInfo['retentionTime'][i]

    else:
Ryan Peckner's avatar
Ryan Peckner committed
342
        SpectraLibrary = pickle.load(open(libName+'_PythonLibrary',"rb"))
Ryan Peckner's avatar
Ryan Peckner committed
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
        
    print "Library loaded in {} minutes".format(round((time.time()-start)/60,1))
    
    path = os.path.expanduser(mzMLname+'.mzML')  
    DIArun = pymzml.run.Reader(path)
    E = enumerate(DIArun)

    start = time.time()     

    if StartOrEnd == "end":
        if instrument == 'orbitrap':
                res = [[spectrum.peaks,spectrum['precursors'][0]['mz'],spectrum['MS:1000016'],i] for i,spectrum in E if spectrum['ms level'] == 2.0 and i < Index]
        if instrument == 'tof':
                res = [[spectrum.peaks,spectrum['precursors'][0]['mz'],spectrum['MS:1000016'],i] for i,spectrum in E if 'precursors' in spectrum.keys() and i < Index]
    else:
        if instrument == 'orbitrap':
                res = [[spectrum.peaks,spectrum['precursors'][0]['mz'],spectrum['MS:1000016'],i] for i,spectrum in E if spectrum['ms level'] == 2.0 and i >= Index]
        if instrument == 'tof':
                res = [[spectrum.peaks,spectrum['precursors'][0]['mz'],spectrum['MS:1000016'],i] for i,spectrum in E if 'precursors' in spectrum.keys() and i >= Index]


    print "Loaded {} MS2 spectra from {} in {} minutes.".format(len(res),path,round((time.time()-start)/60,1))
    
    res=[(res[i][0],float(res[i][1]),float(res[i][2]),float(res[i][3]),float(res[i+1][1]) - float(res[i][1])) for i in range(len(res)-1)]
    header=[[x[1],x[2],x[3]] for x in res]

    absolutePath = mzMLname.rsplit('/',1)[0]
    noPathName = mzMLname.rsplit('/',1)[1]
    if '/' in libName:
        libName = libName.rsplit('/',1)[1]

    outputDir = os.path.expanduser(absolutePath+'/SpecterResults')
    if not os.path.exists(outputDir):
    	os.makedirs(outputDir)

    headerPath = os.path.expanduser(absolutePath+'/SpecterResults/'+noPathName+'_'+libName+'_header.csv')     
    
    with open(headerPath, "ab") as f:
        writer = csv.writer(f)
        writer.writerows(header)      
           
    print "Header written to {}.".format(headerPath)
Ryan Peckner's avatar
Ryan Peckner committed
385
    print "Analyzing MS2 spectra:"
Ryan Peckner's avatar
Ryan Peckner committed
386
387
388
389
390
391
392
393

    MaxWindowPrecMZ = max(np.array([x[1] for x in res])) + max(np.array([x[4] for x in res]))
    MaxOffset = max(np.array([x[4] for x in res]))

    SpectraLibrary = {k:SpectraLibrary[k] for k in SpectraLibrary if SpectraLibrary[k]['PrecursorMZ'] < MaxWindowPrecMZ}

    pool = multiprocessing.Pool(numProcessors)
    with closing(pool) as p:
Ryan Peckner's avatar
Ryan Peckner committed
394
395
        output = list(tqdm.tqdm(p.imap(partial(RegressSpectraOntoLibrary,Library=SpectraLibrary,tol=delta*1e-6,maxWindowOffset=MaxOffset), res), total=len(res)))
        output = [[output[i][j][0],output[i][j][1],output[i][j][2],output[i][j][3],
Ryan Peckner's avatar
Ryan Peckner committed
396
                        output[i][j][4],output[i][j][5]] for i in range(len(output)) for j in range(len(output[i]))]
Ryan Peckner's avatar
Ryan Peckner committed
397
        p.terminate()  
Ryan Peckner's avatar
Ryan Peckner committed
398
399
400
401
402
403
404
405
    
    outputPath = os.path.expanduser(absolutePath+'/SpecterResults/'+noPathName+'_'+libName+'_SpecterCoeffs.csv')     
    
    with open(outputPath, "ab") as f:
        writer = csv.writer(f)
        writer.writerows(output)      
           
    print "Output written to {}.".format(outputPath)
Ryan Peckner's avatar
Ryan Peckner committed
406
    print "Analyzing MS2 spectra with decoys:"
Ryan Peckner's avatar
Ryan Peckner committed
407

Ryan Peckner's avatar
Ryan Peckner committed
408
    pool = multiprocessing.Pool(numProcessors)
Ryan Peckner's avatar
Ryan Peckner committed
409
    with closing(pool) as p:
Ryan Peckner's avatar
Ryan Peckner committed
410
411
        output = list(tqdm.tqdm(p.imap(partial(RegressSpectraOntoLibraryWithDecoys,Library=SpectraLibrary,tol=delta*1e-6,maxWindowOffset=MaxOffset), res), total=len(res)))
        output = [[output[i][j][0],output[i][j][1],output[i][j][2],output[i][j][3],
Ryan Peckner's avatar
Ryan Peckner committed
412
                        output[i][j][4],output[i][j][5]] for i in range(len(output)) for j in range(len(output[i]))]
Ryan Peckner's avatar
Ryan Peckner committed
413
        p.terminate()
Ryan Peckner's avatar
Ryan Peckner committed
414
415
416
417
418
419
420
421
    
    outputPath = os.path.expanduser(absolutePath+'/SpecterResults/'+noPathName+'_'+libName+'_SpecterCoeffsDecoys.csv')     
    
    with open(outputPath, "ab") as f:
        writer = csv.writer(f)
        writer.writerows(output)      
           
    print "Output written to {}.".format(outputPath)