Specter_Standalone.py 31.8 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
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

Ryan Peckner's avatar
Ryan Peckner committed
27
28
29
def RegressSpectraOntoLibrary(DIASpectrumIndex,mzmlPath,Library,headerPath,outputPath,tol,maxWindowOffset):
            
            Run = pymzml.run.Reader(mzmlPath)    
Ryan Peckner's avatar
Ryan Peckner committed
30
31
32
33
34
35
36
37
38
39
40
            spec = Run[DIASpectrumIndex]
            if spec['ms level'] != 2.0:
                pass
            else:
                precMZ = float(spec['precursors'][0]['mz'])    
                precRT = float(spec['MS:1000016'])  #MS2 scan retention time, in minutes
                index = DIASpectrumIndex
                #windowWidth = DIASpectrum[4]
                windowWidth = 10
                with open(headerPath, "ab") as f:
                    writer = csv.writer(f)
Ryan Peckner's avatar
Ryan Peckner committed
41
                    writer.writerow([precMZ,precRT,index])  
Ryan Peckner's avatar
Ryan Peckner committed
42
                
Ryan Peckner's avatar
Ryan Peckner committed
43
44
                DIASpectrum = np.array(Run[DIASpectrumIndex].peaks)
                RefSpectraLibrary = Library
Ryan Peckner's avatar
Ryan Peckner committed
45

Ryan Peckner's avatar
Ryan Peckner committed
46
                LibraryCoeffs = []
Ryan Peckner's avatar
Ryan Peckner committed
47
                
Ryan Peckner's avatar
Ryan Peckner committed
48
                if len(DIASpectrum.shape) == 2:
Ryan Peckner's avatar
Ryan Peckner committed
49
                    
Ryan Peckner's avatar
Ryan Peckner committed
50
51
52
53
54
55
56
57
58
59
                    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]
Ryan Peckner's avatar
Ryan Peckner committed
60
                    
Ryan Peckner's avatar
Ryan Peckner committed
61
62
63
64
65
66
67
68
69
70

                    #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)
Ryan Peckner's avatar
Ryan Peckner committed
71
                    
Ryan Peckner's avatar
Ryan Peckner committed
72
73
74
75
76
77
78
                    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))]                          
Ryan Peckner's avatar
Ryan Peckner committed
79
                    
Ryan Peckner's avatar
Ryan Peckner committed
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
                    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
Ryan Peckner's avatar
Ryan Peckner committed
124
                
Ryan Peckner's avatar
Ryan Peckner committed
125
126
127
128
129
                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))]
Ryan Peckner's avatar
Ryan Peckner committed
130
131
                    #output = [[output[i][j][0],output[i][j][1],output[i][j][2],output[i][j][3],
                    #                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
132
133
134
                    with open(outputPath, "ab") as f:
                        writer = csv.writer(f)
                        writer.writerows(Output) 
Ryan Peckner's avatar
Ryan Peckner committed
135

Ryan Peckner's avatar
Ryan Peckner committed
136
def RegressSpectraOntoLibraryWithDecoys(DIASpectrum,Library,tol,maxWindowOffset):
Ryan Peckner's avatar
Ryan Peckner committed
137
138
           
        
Ryan Peckner's avatar
Ryan Peckner committed
139
140
141
142
            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
143
            
Ryan Peckner's avatar
Ryan Peckner committed
144
            DIASpectrum = np.array(DIASpectrum[0])
Ryan Peckner's avatar
Ryan Peckner committed
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169

            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
170
171
172
173
174
175
176
                
                #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
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
209
210
211
212
213
214
215
216
217
218
219
                #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
220
                    UniqueRowIndices = np.unique(np.concatenate((RefSpectraLibrarySparseRowIndices,DecoyLibrarySparseRowIndices)))
Ryan Peckner's avatar
Ryan Peckner committed
221
                    UniqueRowIndices = np.array(np.sort(UniqueRowIndices),dtype=int)
Ryan Peckner's avatar
Ryan Peckner committed
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
                    
                    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'    
Ryan Peckner's avatar
Ryan Peckner committed
304
    if len(args) >= 7:
Ryan Peckner's avatar
Ryan Peckner committed
305
306
307
308
309
310
        instrument=args[6]

    delta = 10
    if len(args) == 8:
    	delta=float(args[7])
        
Ryan Peckner's avatar
Ryan Peckner committed
311
312
313
314
    width = 0
    if len(args) == 9:
        width = float(args[8])    
        
Ryan Peckner's avatar
Ryan Peckner committed
315
316
317
318
319
    #Cast the spectral library as a dictionary  
        
    start = time.time()
    
    libPath = os.path.expanduser(libName+'.blib')
Ryan Peckner's avatar
Ryan Peckner committed
320
    if os.path.exists(libPath) and not os.path.exists(libName+'_PythonLibrary'):
Ryan Peckner's avatar
Ryan Peckner committed
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
        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]
355
356
357
358
359
360
361
362
            elif len(zlib.decompress(SpectrumMZ)) == 8*NumPeaks and len(zlib.decompress(SpectrumIntensities)) == 4*NumPeaks:
                SpectraLibrary.setdefault(precursorKey,{})
                SpectrumMZ = struct.unpack('d'*NumPeaks,zlib.decompress(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]
                
Ryan Peckner's avatar
Ryan Peckner committed
363
    else:
Ryan Peckner's avatar
Ryan Peckner committed
364
        SpectraLibrary = pickle.load(open(libName+'_PythonLibrary',"rb"))
Ryan Peckner's avatar
Ryan Peckner committed
365
366
367
368
369
        
    print "Library loaded in {} minutes".format(round((time.time()-start)/60,1))
    
    path = os.path.expanduser(mzMLname+'.mzML')  
    DIArun = pymzml.run.Reader(path)
Ryan Peckner's avatar
Ryan Peckner committed
370
    # E = enumerate(DIArun)
Ryan Peckner's avatar
Ryan Peckner committed
371

Ryan Peckner's avatar
Ryan Peckner committed
372
    # start = time.time()     
Ryan Peckner's avatar
Ryan Peckner committed
373

Ryan Peckner's avatar
Ryan Peckner committed
374
375
376
377
378
379
380
381
382
383
    # 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]
Ryan Peckner's avatar
Ryan Peckner committed
384
385


Ryan Peckner's avatar
Ryan Peckner committed
386
    # print "Loaded {} MS2 spectra from {} in {} minutes.".format(len(res),path,round((time.time()-start)/60,1))
Ryan Peckner's avatar
Ryan Peckner committed
387
    
Ryan Peckner's avatar
Ryan Peckner committed
388
389
390
391
    # 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)]
    # if width > 0:
    #     res=[(res[i][0],float(res[i][1]),float(res[i][2]),float(res[i][3]),width) for i in range(len(res)-1)]
    # header=[[x[1],x[2],x[3]] for x in res]
Ryan Peckner's avatar
Ryan Peckner committed
392

393
394
395
396
    absolutePath = os.path.dirname(mzMLname)
    noPathName = os.path.basename(mzMLname)
    libName = os.path.basename(libName)
    
Ryan Peckner's avatar
Ryan Peckner committed
397
    outputDir = os.path.expanduser(os.path.join(absolutePath, 'SpecterStreamingResults'))
Ryan Peckner's avatar
Ryan Peckner committed
398
399
400
    if not os.path.exists(outputDir):
    	os.makedirs(outputDir)

Ryan Peckner's avatar
Ryan Peckner committed
401
    headerPath = os.path.expanduser(os.path.join(absolutePath, 'SpecterStreamingResults',
402
                                                 '%s_%s_header.csv' % (noPathName, libName)))
Ryan Peckner's avatar
Ryan Peckner committed
403
    
Ryan Peckner's avatar
Ryan Peckner committed
404
405
406
    #with open(headerPath, "ab") as f:
    #    writer = csv.writer(f)
    #    writer.writerows(header)      
Ryan Peckner's avatar
Ryan Peckner committed
407
           
Ryan Peckner's avatar
Ryan Peckner committed
408
    #print "Header written to {}.".format(headerPath)
Ryan Peckner's avatar
Ryan Peckner committed
409
    print "Analyzing MS2 spectra:"
Ryan Peckner's avatar
Ryan Peckner committed
410

Ryan Peckner's avatar
Ryan Peckner committed
411
412
    #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]))
Ryan Peckner's avatar
Ryan Peckner committed
413
    MaxOffset = 10
Ryan Peckner's avatar
Ryan Peckner committed
414
    #SpectraLibrary = {k:SpectraLibrary[k] for k in SpectraLibrary if SpectraLibrary[k]['PrecursorMZ'] < MaxWindowPrecMZ}
Ryan Peckner's avatar
Ryan Peckner committed
415

Ryan Peckner's avatar
Ryan Peckner committed
416
    numSpectra = DIArun.info['spectrum_count']
Ryan Peckner's avatar
Ryan Peckner committed
417
418
    outputPath = os.path.expanduser(os.path.join(absolutePath, 'SpecterStreamingResults',
                                                 '%s_%s_SpecterStreamingCoeffs.csv' % (noPathName, libName)))
Ryan Peckner's avatar
Ryan Peckner committed
419
    pool = multiprocessing.Pool(numProcessors)
Ryan Peckner's avatar
Ryan Peckner committed
420
421
    output = list(tqdm.tqdm(pool.imap(partial(RegressSpectraOntoLibrary,mzmlPath=path,Library=SpectraLibrary,headerPath=headerPath,
                            outputPath=outputPath,tol=delta*1e-6,maxWindowOffset=MaxOffset), range(1,numSpectra)), total=numSpectra))
Ryan Peckner's avatar
Ryan Peckner committed
422
423
        #output = [[output[i][j][0],output[i][j][1],output[i][j][2],output[i][j][3],
        #                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
424
425
    pool.close()
    pool.join()
Ryan Peckner's avatar
Ryan Peckner committed
426
        
Ryan Peckner's avatar
Ryan Peckner committed
427
428
429
    #for i in tqdm.tqdm(range(1,numSpectra+1)):
    #    RegressSpectraOntoLibrary(i,mzmlPath=path,Library=SpectraLibrary,headerPath=headerPath,
    #                               outputPath=outputPath,tol=delta*1e-6,maxWindowOffset=MaxOffset)      
Ryan Peckner's avatar
Ryan Peckner committed
430
    print "Output written to {}.".format(outputPath)
Ryan Peckner's avatar
Ryan Peckner committed
431
    #print "Analyzing MS2 spectra with decoys:"
Ryan Peckner's avatar
Ryan Peckner committed
432

Ryan Peckner's avatar
Ryan Peckner committed
433
434
435
436
437
438
    #pool = multiprocessing.Pool(numProcessors)
    # with closing(pool) as p:
    #     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],
    #                     output[i][j][4],output[i][j][5]] for i in range(len(output)) for j in range(len(output[i]))]
    #     p.terminate()
Ryan Peckner's avatar
Ryan Peckner committed
439
    
Ryan Peckner's avatar
Ryan Peckner committed
440
441
    # outputPath = os.path.expanduser(os.path.join(absolutePath, 'SpecterResults',
    #                                              '%s_%s_SpecterCoeffsDecoys.csv' % (noPathName, libName)))
Ryan Peckner's avatar
Ryan Peckner committed
442
    
Ryan Peckner's avatar
Ryan Peckner committed
443
444
445
    # with open(outputPath, "ab") as f:
    #     writer = csv.writer(f)
    #     writer.writerows(output)      
Ryan Peckner's avatar
Ryan Peckner committed
446
           
Ryan Peckner's avatar
Ryan Peckner committed
447
    # print "Output written to {}.".format(outputPath)