-
Notifications
You must be signed in to change notification settings - Fork 0
/
dripTrain.py
executable file
·1410 lines (1209 loc) · 58.3 KB
/
dripTrain.py
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
125
126
127
128
129
130
131
132
133
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
159
160
161
162
163
164
165
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
209
210
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
305
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
342
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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
#
# Written by John Halloran <[email protected]>
#
# Copyright (C) 2016 John Halloran
# Licensed under the Open Software License version 3.0
# See COPYING or http://opensource.org/licenses/OSL-3.0
from __future__ import with_statement
__authors__ = ['John Halloran <[email protected]>' ]
import os
import re
import sys
import argparse
import cPickle as pickle
import pyFiles.digest_fasta as df
import multiprocessing
import shlex
import math
from pyFiles.psm import dripPSM, parse_dripExtract
from pyFiles.gmtkUtils import parse_params
from random import shuffle
from shutil import rmtree
from pyFiles.spectrum import MS2Spectrum
from pyFiles.peptide import Peptide, amino_acids_to_indices
from pyFiles.normalize import pipeline
from pyFiles.pfile.wrapper import PFile
# from pyFiles.args import make_dir_callback
from pyFiles.dripEncoding import (create_drip_structure,
create_drip_master,
triangulate_drip,
write_covar_file,
create_pfile,
drip_peptide_sentence,
drip_spectrum_sentence,
training_spectrum_sentence,
make_master_parameters,
make_master_parameters_lowres,
interleave_b_y_ions,
interleave_b_y_ions_lowres,
filter_theoretical_peaks,
filter_theoretical_peaks_lowres,
create_empty_master,
create_params_no_train,
load_drip_means,
dripMean)
from pyFiles.constants import allPeps
from pyFiles.ioPsmFunctions import load_psm_library
from pyFiles.shard_spectra import (calc_minMaxMz,
pickle_candidate_spectra,
candidate_spectra_generator,
candidate_spectra_memeffic_generator,
load_spectra_ret_dict,
load_target_decoy_db_no_reshuffle)
from subprocess import call, check_output, STDOUT
debug=False
bw = 1.0005079
bo = 0.68
# bw = 1.0
# bo = 0.0
########## would have to rework all code to use below, but this would make working with the DRIP means
########## considerably simpler. However, mean class is overkill as the means are scalars
def load_dripMeansClass(master_file):
""" Load DRIP learned means from master file.
Return dictionary of gmtkMean objects whose keys are the mean names
"""
mean_file = open(master_file)
log = mean_file.read()
mean_file.close()
mean_pattern = '[^%]mean(?P<meanInd>\d+) 1 (?P<meanVal>\S+)'
means = {}
for match in re.finditer(mean_pattern, log):
name = 'mean' + str(match.group('meanInd'))
dimension = 1
val = float(match.group('meanVal'))
currMean = dripMean(name,
val,
int(match.group('meanInd')),
dimension)
means[name] = currMean
means[int(match.group('meanInd'))] = float(match.group('meanVal'))
return means
def process_args(args):
""" Check whether relevant directories already exist (remove them if so), create
necessary directories. Adjust parameters.
pre:
- args has been created by calling parse_args()
post:
- Relevant directories will be first removed then created, boolean parameters
will be adjusted to reflect their boolean command line strings
"""
# check input arguments, create necessary directories,
# set necessary global variables based on input arguments
# constant string
if args.max_obs_mass < 0:
print "Supplied max-mass %d, must be greater than 0, exitting" % args.max_obs_mass
exit(-1)
# check arguments
# create obervation directories
# vit vals output directory
try:
base = os.path.abspath(args.logDir)
if not os.path.exists(base):
os.mkdir(base)
else:
rmtree(base)
os.mkdir(base)
except:
print "Could not create observation directory %s, exitting" % os.path.abspath(args.logDir)
exit(-1)
# top level encode directory
try:
base = os.path.abspath(args.output_dir)
args.output_dir = base
if not os.path.exists(base):
os.mkdir(base)
else:
rmtree(base)
os.mkdir(base)
except:
print "Could not create observation directory %s, exitting" % os.path.abspath(args.output_dir)
exit(-1)
# observation directory
try:
base = os.path.join(os.path.abspath(args.output_dir), args.obs_dir)
os.mkdir(base)
except:
print "Could not create observation directory %s, exitting" % os.path.join(os.path.abspath(args.output_dir), args.obs_dir)
exit(-1)
# Gaussian collection directory
try:
base = os.path.abspath(args.collection_dir)
if not os.path.exists(base):
os.mkdir(base)
else:
rmtree(base)
os.mkdir(base)
except:
print "Could not create observation directory %s, exitting" % os.path.abspath(args.collection_dir)
exit(-1)
args.covar_file = os.path.join(os.path.abspath(args.collection_dir), args.covar_file)
args.mean_file = os.path.join(os.path.abspath(args.collection_dir), args.mean_file)
args.gauss_file = os.path.join(os.path.abspath(args.collection_dir), args.gauss_file)
args.mixture_file = os.path.join(os.path.abspath(args.collection_dir), args.mixture_file)
args.collection_file = os.path.join(os.path.abspath(args.collection_dir), args.collection_file)
args.filt_theo_peaks = True
# set true or false strings to booleans
args.high_res_ms2 = df.check_arg_trueFalse(args.high_res_ms2)
args.num_threads = 1
# # make sure number of input threads does not exceed number of supported threads
# if args.num_threads > multiprocessing.cpu_count():
# args.num_threads = max(multiprocessing.cpu_count()-1,1)
def remove_theoretical_holes(dripMeans, usedTheoPeaks):
""" A theoretical hole is a DRIP mean not accessed by any training PSM
(i.e., such a theoretical peak is not present in any theoretical
spectrum amongst the training PSMs). Such holes will, by definition,
receive zero probability during training and could cause unexpected
behavior due to numerical instability (the EM update for the means
involves the reciprocal of the posterior probability) so it is
best to remove these and add them back in after training.
Note: "theoretical hole" is not to be confused with the notion of a deletion.
A deletion pertains to a peak in a theoretical spectrum where,
given an observed spectrum, a DRIP alignment does not contain
the scoring of any observed peaks with this theoretical peak.
In contrast, a hole pertains to a theoretical peak that is not
contained in any of the union of theoretical spectra amongst
a collection of PSMs.
inputs:
dripMeans - dictionary whose keys are the index of the theoretical peak and whose values are the DRIP mean value
usedTheoPeaks - set of theoretical peaks that are not holes
outputs: None
pre:
-dripMeans is constructed before calling this function (either
read from a file of prior means or initialized to default
values) and should be a python dictionary object
-usedTheoPeaks is constructed and should be a python set object
post:
-theoretical holes are deleted from dripMeans. Note that
dripMeans is passed by reference and adjusted herein
"""
meanKeys = list(dripMeans.iterkeys())
# print sorted(list(set(meanKeys).difference(set(usedTheoPeaks))))
for m in meanKeys:
if m not in usedTheoPeaks:
hole = dripMeans.pop(m, None)
def remap_mean_indices(args, spectra,
dripMeans, usedTheoPeaks, theo_dict):
""" Remap theoretical peaks to indices under collection of
non-theoretical-holes
todo: add high-res ms2 to this, even though learning
high-res ms2 parameters hasn't lead to any
improvements
pre:
-drip means have been loaded into dripMeans and
theoretical holes have been removed
-non-theoretical-holes have been properly denoted
in the set usedTheoPeaks
-dictionary of theoretical spectra have been constructed
but have not been remapped under the collection of
active theoretical peaks
post:
-each theoretical peak in theo_dict is an index
into array of drip means sorted by key in dripMeans
"""
new_theo_index_mapping = {}
for new_ind, old_ind in enumerate(sorted(dripMeans.iterkeys())):
new_theo_index_mapping[old_ind] = new_ind
# spec_considered = set([])
for sid,charge,pep in theo_dict:
# calculate b- and y-ions under new mapping
bNy = theo_dict[sid,charge,pep]
theo_dict[sid,charge,pep] = [new_theo_index_mapping[i] for i in bNy]
def inject_mean_evidence(args, spectra,
dripMeans,
fa_psms, theo_dict, lowProbMeans,
observedHoles):
""" Remap theoretical peaks to indices under collection of
non-theoretical-holes
todo: add high-res ms2 to this, even though learning
high-res ms2 parameters hasn't lead to any
improvements
pre:
-drip means have been loaded into dripMeans and
theoretical holes have been removed
-non-theoretical-holes have been properly denoted
in the set usedTheoPeaks
-dictionary of theoretical spectra have been constructed
but have not been remapped under the collection of
active theoretical peaks
post:
-each theoretical peak in theo_dict is an index
into array of drip means sorted by key in dripMeans
"""
new_theo_index_mapping = {}
new_to_old_mapping = {}
for new_ind, old_ind in enumerate(sorted(dripMeans.iterkeys())):
new_theo_index_mapping[old_ind] = new_ind
new_to_old_mapping[new_ind] = old_ind
remapped_lowProbMeans = set([new_theo_index_mapping[m] for m in observedHoles])
remapped_lowProbMeans |= set([new_theo_index_mapping[m] for m in lowProbMeans])
# remapped_lowProbMeans = set([new_theo_index_mapping[m] for m in lowProbMeans])
for sid,charge,pep in theo_dict:
dripPsm = []
ind = -1
for psm in fa_psms[sid,charge]:
ind += 1
if psm.peptide == pep:
dripPsm = psm
break
assert dripPsm
bNy = set(theo_dict[sid,charge,pep])
bNy_original = [new_to_old_mapping[theoPeak] for theoPeak in theo_dict[sid,charge,pep]]
overlap = bNy & remapped_lowProbMeans
if overlap:
s = spectra[sid]
temp_spec = [(mz, intensity) for mz, intensity in zip(s.real_mz, s.real_intensity)]
for m in overlap:
k = new_to_old_mapping[m]
synthetic_mz = (bw*float(2*k+1)-2*bo)/2
temp_spec.append((synthetic_mz,1.0))
temp_spec.sort(key = lambda r: r[0])
s.mz = [mz for mz, _ in temp_spec]
s.intensity = [intensity for _, intensity in temp_spec]
dripPsm.insertion_sequence = [0 if calc_bin(mz,bo,bw) in bNy_original else 1 for mz in s.mz]
dripPsm.add_obs_spectrum(s)
spectra[sid] = s
fa_psms[sid,charge][ind] = dripPsm
def remap_learned_means(dripMeans_og, learnedMeans):
""" Remap theoretical peaks to indices under collection of
non-theoretical-holes
todo: add high-res ms2 to this, even though learning
high-res ms2 parameters hasn't lead to any
improvements
pre:
-drip means have been loaded into dripMeans and
theoretical holes have been removed
-non-theoretical-holes have been properly denoted
in the set usedTheoPeaks
-dictionary of theoretical spectra have been constructed
but have not been remapped under the collection of
active theoretical peaks
post:
-each theoretical peak in theo_dict is an index
into array of drip means sorted by key in dripMeans
"""
pat = re.compile('\d+')
for m in learnedMeans:
if str(m[0])=='intensity_mean':
continue
oldInd = int(pat.findall(str(m[0]))[0])
assert m[1]==1 and len(m[2])==1, "Learned mean %s has dimension %d, DRIP means should only have dimension 1. Exitting" % (m[0], m[1])
dripMeans_og[oldInd] = m[2][0]
def write_learned_means_covars(learnedMeans, learnedCovars, meanName, covarName):
# meanName = baseName + '.means'
# covarName = baseName + '.covars'
# check that means are increasing in m/z value
prevMean = -1.0
resortedMeans = []
resort = 0
for m in sorted(learnedMeans.iterkeys()):
newMean = learnedMeans[m]
if newMean < prevMean:
resort = 1 # if we have to resort, the indices no longer have meaning
resortedMeans.append(learnedMeans[m])
prevMean = newMean
if resort:
print "Sorting learned means in increasing order"
resortedMeans.sort()
# write mean file
meanFid = open(meanName, 'w')
meanFid.write("%d\n" % len(resortedMeans))
for i,m in enumerate(resortedMeans):
meanFid.write("%d mean%d 1 %.10e\n" % (i,i,m))
meanFid.close()
# write covar file
covarFid = open(covarName, 'w')
covarFid.write("%d\n" % len(learnedCovars))
for i, covar in enumerate(learnedCovars):
covarFid.write("%d %s %d %.10e\n" % (i,covar[0],
covar[1],
covar[2][0]))
covarFid.close()
def inject_mean_evidence_old(args, spectra,
dripMeans,
fa_psms, theo_dict, lowProbMeans):
""" Remap theoretical peaks to indices under collection of
non-theoretical-holes
todo: add high-res ms2 to this, even though learning
high-res ms2 parameters hasn't lead to any
improvements
pre:
-drip means have been loaded into dripMeans and
theoretical holes have been removed
-non-theoretical-holes have been properly denoted
in the set usedTheoPeaks
-dictionary of theoretical spectra have been constructed
but have not been remapped under the collection of
active theoretical peaks
post:
-each theoretical peak in theo_dict is an index
into array of drip means sorted by key in dripMeans
Note: replaced as of 2016-02-11, but may prove useful
in future work
"""
new_theo_index_mapping = {}
new_to_old_mapping = {}
for new_ind, old_ind in enumerate(sorted(dripMeans.iterkeys())):
new_theo_index_mapping[old_ind] = new_ind
new_to_old_mapping[new_ind] = old_ind
remapped_lowProbMeans = set([new_theo_index_mapping[m] for m in lowProbMeans])
for sid,charge,pep in theo_dict:
dripPsm = []
ind = 0
for psm in fa_psms[sid,charge]:
if psm.peptide == pep:
dripPsm = psm
break
ind += 1
assert dripPsm
bNy = set(theo_dict[sid,charge,pep])
overlap = bNy & remapped_lowProbMeans
if overlap:
s = spectra[sid]
temp_spec = [(mz, intensity, ins) for mz, intensity, ins in zip(s.mz, s.intensity, dripPsm.insertion_sequence)]
for m in overlap:
temp_spec.append((dripMeans[new_to_old_mapping[m]],1.0, 0))
temp_spec.sort(key = lambda r: r[0])
s.mz = [mz for mz, intensity, ins in temp_spec]
s.intensity = [intensity for mz, intensity, ins in temp_spec]
dripPsm.insertion_sequence = [ins for mz, intensity, ins in temp_spec]
dripPsm.add_obs_spectrum(s)
spectra[sid] = s
fa_psms[sid,charge][ind] = dripPsm
def calculate_theoretical_dictionary(args, spectra):
"""Dictionary of theoretical spectra for each training PSM
don't run this for high-res; theoretical spectrum
preprocessing is explicitly handled in high-res data
generation
Note: not used as of 2016-02-11, but may prove useful
in future work
"""
assert not args.high_res_ms2, "calculate_theoretical_dictionary shouldn't be called in high-res ms2 mode"
# parse modifications
mods = df.parse_mods(args.mods_spec, True)
print "mods:"
print mods
ntermMods = df.parse_mods(args.nterm_peptide_mods_spec, False)
print "n-term mods:"
print ntermMods
ctermMods = df.parse_mods(args.cterm_peptide_mods_spec, False)
print "c-term mods:"
print ctermMods
target,num_psms = load_psm_library(args.psm_library)
sid_charges = list(target.iterkeys())
theo_dict = {} # keys: sid, charge, peptide string
usedTheoPeaks = set([])
validcharges = args.charges # this should have been updated by loading
# the spectra into memory first
if(args.normalize != 'filter0'):
preprocess = pipeline(args.normalize)
spec_considered = set([])
for sid, charge in sid_charges:
s = spectra[sid]
if sid not in spec_considered:
preprocess(s)
spec_considered.add(sid)
for p in target[sid,charge]:
pep = p.peptide
# calculate theoretical spectra
bNy = interleave_b_y_ions_lowres(Peptide(pep), charge, mods,
ntermMods, ctermMods)
# calculate upper and lower bounds to filter theoretical peaks
# out of observed spectra range
if args.filt_theo_peaks:
if args.per_spectrum_mz_bound:
minMz = s.mz[0]
maxMz = s.mz[-1]
else:
minMz = args.mz_lb
maxMz = args.mz_ub
if args.filt_theo_peaks:
filter_theoretical_peaks(bNy, minMz, maxMz)
theo_dict[sid,charge,pep] = bNy
# update set of active theoretical peaks
usedTheoPeaks |= set(bNy)
return theo_dict, usedTheoPeaks, target, num_psms
def calc_bin(mz, bin_offset = 0.68, bin_width = 1.0005079):
""" Used to estimate forced alignment for training, as well
as observed holes. Both used for training regularization
"""
return int(math.floor(mz/bin_width-bin_offset+1))
def calcTheoDict_estimateFa(args, spectra):
"""Dictionary of theoretical spectra for each training PSM
don't run this for high-res; theoretical spectrum
preprocessing is explicitly handled in high-res data
generation
"""
assert not args.high_res_ms2, "calculate_theoretical_dictionary shouldn't be called in high-res ms2 mode"
# parse modifications
mods = df.parse_mods(args.mods_spec, True)
print "mods:"
print mods
ntermMods = df.parse_mods(args.nterm_peptide_mods_spec, False)
print "n-term mods:"
print ntermMods
ctermMods = df.parse_mods(args.cterm_peptide_mods_spec, False)
print "c-term mods:"
print ctermMods
target,num_psms = load_psm_library(args.psm_library)
sid_charges = list(target.iterkeys())
theo_dict = {} # keys: sid, charge, peptide string
usedTheoPeaks = set([])
validcharges = args.charges # this should have been updated by loading
# the spectra into memory first
if(args.normalize != 'filter0'):
preprocess = pipeline(args.normalize)
max_mass = 2001
not_observed_holes = [0] * max_mass
observedPeaks = set([])
minMz = 0
maxMz = max_mass-1
spec_considered = set([])
for sid, charge in sid_charges:
s = spectra[sid]
if sid not in spec_considered:
preprocess(s)
spec_considered.add(sid)
s.real_mz = list(s.mz)
s.real_intensity = list(s.intensity)
spectra[sid] = s
for p in target[sid,charge]:
pep = p.peptide
# calculate theoretical spectra
bNy = interleave_b_y_ions_lowres(Peptide(pep), charge, mods,
ntermMods, ctermMods)
# calculate complement of observed holes
observedPeaks |= set([calc_bin(mz, bo, bw) for mz in s.mz])
if args.filt_theo_peaks:
filter_theoretical_peaks(bNy, minMz, maxMz)
theo_dict[sid,charge,pep] = bNy
# update set of active theoretical peaks
usedTheoPeaks |= set(bNy)
observedHoles = usedTheoPeaks.difference(observedPeaks)
# create dictionary of charges with sid keys
sidChargeDict = {}
for sid, charge in sid_charges:
if sid in sidChargeDict:
sidChargeDict[sid].append(charge)
else:
sidChargeDict[sid] = [charge]
# add synthetic peaks to observed spectrum holes,
# estimate forced alignment
for sid in sidChargeDict:
s = spectra[sid]
temp_spec = [(mz, intensity) for mz, intensity in zip(s.mz, s.intensity)]
synthetic_peak_locations = set([])
for charge in sidChargeDict[sid]:
for p in target[sid,charge]:
pep = p.peptide
bNy = theo_dict[sid,charge,pep]
synthetic_peak_locations |= set(bNy).intersection(observedHoles)
for mz in synthetic_peak_locations:
synthetic_mz = (bw*float(2*mz+1)-2*bo)/2
temp_spec.append((synthetic_mz, 1.0))
temp_spec.sort(key = lambda r: r[0])
s.mz = [mz for mz, _ in temp_spec]
s.intensity = [intensity for _, intensity in temp_spec]
spectra[sid] = s
fa_psms = {}
# iteratre through new m/z values, estimate forced alignment
for sid in sidChargeDict:
s = spectra[sid]
for charge in sidChargeDict[sid]:
for p in target[sid,charge]:
pep = p.peptide
bNy = set(theo_dict[sid,charge,pep])
curr_ins_seq = [False if calc_bin(mz,bo,bw) in bNy else True for mz in s.mz]
currPsm = dripPSM(pep, 0.0, sid, 't',
charge, len(bNy), [100] * len(curr_ins_seq),
curr_ins_seq)
if (sid, charge) in fa_psms:
fa_psms[sid,charge].append(currPsm)
else:
fa_psms[sid,charge] = [currPsm]
return theo_dict, usedTheoPeaks, target, num_psms, observedHoles, fa_psms
def make_fa_data_highres(args, spectra, target, num_psms, stdo, stde):
"""Generate test data .pfile. and create job scripts for cluster use (if num_jobs > 1).
Decrease number of calls to GMTK by only calling once per spectrum
and running for all charge states in one go.
inputs:
args - output of parsed input arguments (struct)
outputs:
sids - list of scan IDs for the generated data
pre:
- args has been created by parse_args(), directories have been created/checked for existence,
relevant arguments have been processed (Booleans, mods, digesting enzyme, etc)
- data has been created by candidate_spectra_generate() and contains the above mentioned fields
post:
- args.{mean_file, gauss_file, mixture_file, collection_file} will all be adjusted
- args.max_mass will be updated to the size of the number of unique theoretical fragmentation locations (floating point if high-res ms2, integers if low-res ms2)
"""
# parse modifications
mods = df.parse_mods(args.mods_spec, True)
print "mods:"
print mods
ntermMods = df.parse_mods(args.nterm_peptide_mods_spec, False)
print "n-term mods:"
print ntermMods
ctermMods = df.parse_mods(args.cterm_peptide_mods_spec, False)
print "c-term mods:"
print ctermMods
pfile_dir = os.path.join(args.output_dir, args.obs_dir)
sid_charges = list(target.iterkeys())
# assume that we should randomize PSMs for multithreading purposes; only reason
# why we are currently assuming this is that there is already a parameter for dripSearch
# which signifies whether we should shuffle the data
shuffle(sid_charges)
if(args.normalize != 'filter0'):
preprocess = pipeline(args.normalize)
validcharges = args.charges
ion_dict = {} # global dictionary for used fragment ions
theo_spec_dict = {}
numBY_dict_per_sid = {}
# construct ion_dict
for sid in spectra:
s = spectra[sid]
# preprocess(s)
for charge in validcharges:
if (s.spectrum_id, charge) not in target:
continue
# check if we're filtering theoretical peaks outside observed m/z values
if args.filt_theo_peaks:
if args.per_spectrum_mz_bound:
minMz = s.mz[0]
maxMz = s.mz[-1]
else:
minMz = args.mz_lb
maxMz = args.mz_ub
# calculate maximum decoy and target theoretical spectra cardinalities
for p in target[s.spectrum_id, charge]:
pep = p.peptide
bNy = interleave_b_y_ions(Peptide(pep), charge, mods,
ntermMods, ctermMods)
numBY_dict_per_sid[sid, pep] = len(bNy)
if args.filt_theo_peaks:
filter_theoretical_peaks(bNy, minMz, maxMz)
# to be backwards compatible with make_training_data_lowres,
# we must add a dict key charge. This makes sense for training since
# we a high-confidence PSM may be desired to train over different
# charge states. This doesn't make sense for testing (dripSearch/dripExtract)
# since it's impossible that one peptide will be in multiple charge-candidate-peptide-sets
theo_spec_dict[s.spectrum_id, charge, pep] = bNy
for i in bNy:
ion_dict[i] = 1
for d in decoy[s.spectrum_id, charge]:
pep = d.peptide
bNy = interleave_b_y_ions(Peptide(pep), charge, mods,
ntermMods, ctermMods)
numBY_dict_per_sid[sid, pep] = len(bNy)
if args.filt_theo_peaks:
filter_theoretical_peaks(bNy, minMz, maxMz)
theo_spec_dict[s.spectrum_id, charge, pep] = bNy
for i in bNy:
ion_dict[i] = 1
ions = list(ion_dict.iterkeys())
ions.sort()
dripMeans = {}
for i, ion in enumerate(ions):
ion_dict[ion] = i
dripMeans[i] = ion
# make collection per spectrum
make_master_parameters(args, ion_dict, ions)
peptide_pfile = create_pfile(pfile_dir,
'pep-lengths.pfile',
0, 1)
spectrum_pfile = create_pfile(pfile_dir,
'spectrum.pfile',
2,0)
pep_dt = open(os.path.join(args.output_dir, 'iterable.dts'), "w")
pep_dt.write('%d\n\n' % (num_psms))
# write peptide database to parse and identify GMTK segments later
pepdb_list = open(os.path.join(args.output_dir, 'pepDB.txt'), "w")
pepdb_list.write("Kind\tSid\tPeptide\tNumBY\tCharge\n")
spec_dict = {}
pep_num = 0
for sid, charge in sid_charges:
if sid not in spec_dict:
s = spectra[sid]
preprocess(s)
spec_dict[sid] = s
else:
s = spec_dict[sid]
for p in target[sid,charge]:
pep = p.peptide
bNy = theo_spec_dict[s.spectrum_id, charge, pep]
bNy = [ion_dict[bOrY] for bOrY in bNy]
drip_peptide_sentence(pep_dt, pep, bNy,
pep_num, s.spectrum_id, args.max_obs_mass,
peptide_pfile, True, len(bNy)-1)
drip_spectrum_sentence(spectrum_pfile, s.mz, s.intensity)
pepdb_list.write("t\t%d\t%s\t%d\t%d\n" % (sid,
pep,
numBY_dict_per_sid[sid, pep],
charge))
pep_num += 1
if (sid,charge) in decoy:
for d in decoy[sid,charge]:
pep = d.peptide
bNy = theo_spec_dict[s.spectrum_id, charge, pep]
bNy = [ion_dict[bOrY] for bOrY in bNy]
drip_peptide_sentence(pep_dt, pep, bNy,
pep_num, s.spectrum_id, args.max_obs_mass,
peptide_pfile, False, len(bNy)-1)
drip_spectrum_sentence(spectrum_pfile, s.mz, s.intensity)
pepdb_list.write("d\t%d\t%s\t%d\t%d\n" % (sid,
pep,
numBY_dict_per_sid[sid, pep],
charge))
pep_num += 1
theo_spec_dict[s.spectrum_id, charge, pep] = bNy
# close streams for this spectrum
pep_dt.close()
pepdb_list.close()
# compile dt using gmtkDTIndex
call(['gmtkDTindex', '-decisionTreeFiles',
os.path.join(args.output_dir,'iterable.dts')],
stdout = stdo, stderr = stde)
return theo_spec_dict, dripMeans
def make_fa_data_lowres(args, spectra, dripMeans, theo_dict,
target, num_psms, stdo, stde):
"""Generate test data .pfile. and create job scripts for cluster use.
Decrease number of calls to GMTK by only calling once per spectrum
and running for all charge states in one go
"""
# make master file
make_master_parameters_lowres(args, dripMeans)
pfile_dir = os.path.join(args.output_dir, args.obs_dir)
sid_charges = list(target.iterkeys())
# shuffle(sid_charges) # shuffle if we're parallelizing GMTK jobs
validcharges = args.charges
# write peptide database to parse and identify GMTK segments later
pepdb_list = open(os.path.join(args.output_dir, 'pepDB.txt'), "w")
pepdb_list.write("Kind\tSid\tPeptide\tNumBY\tCharge\n")
peptide_pfile = create_pfile(pfile_dir,
'pep-lengths.pfile',
0, 1)
spectrum_pfile = create_pfile(pfile_dir,
'spectrum.pfile',
2,0)
pep_dt = open(os.path.join(args.output_dir, 'iterable.dts'), "w")
pep_dt.write('%d\n\n' % (num_psms))
pep_num = 0
for sid, charge in sid_charges:
s = spectra[sid]
for p in target[sid,charge]:
pep = p.peptide
bNy = theo_dict[sid,charge,pep]
pepdb_list.write("t\t%d\t%s\t%d\t%d\n" % (sid, pep, len(bNy), charge))
drip_peptide_sentence(pep_dt, pep, bNy,
pep_num, s.spectrum_id, args.max_obs_mass,
peptide_pfile, True, len(bNy)-1)
drip_spectrum_sentence(spectrum_pfile, s.mz, s.intensity)
pep_num += 1
# close streams for this spectrum
pep_dt.close()
pepdb_list.close()
# compile dt using gmtkDTIndex
call(['gmtkDTindex', '-decisionTreeFiles',
os.path.join(args.output_dir,'iterable.dts')],
stdout = stdo, stderr = stde)
def make_training_data_highres(args, spectra,
theo_spec_dict, ion_dict,
target, num_psms,
fa_psms, stdo, stde):
"""Generate test data .pfile. and create job scripts for cluster use (if num_jobs > 1).
Decrease number of calls to GMTK by only calling once per spectrum
and running for all charge states in one go.
inputs:
args - output of parsed input arguments (struct)
outputs:
sids - list of scan IDs for the generated data
pre:
- args has been created by parse_args(), directories have been created/checked for existence,
relevant arguments have been processed (Booleans, mods, digesting enzyme, etc)
- data has been created by candidate_spectra_generate() and contains the above mentioned fields
post:
- args.{mean_file, gauss_file, mixture_file, collection_file} will all be adjusted
- args.max_mass will be updated to the size of the number of unique theoretical fragmentation locations (floating point if high-res ms2, integers if low-res ms2)
"""
# parse modifications
mods = df.parse_mods(args.mods_spec, True)
print "mods:"
print mods
ntermMods = df.parse_mods(args.nterm_peptide_mods_spec, False)
print "n-term mods:"
print ntermMods
ctermMods = df.parse_mods(args.cterm_peptide_mods_spec, False)
print "c-term mods:"
print ctermMods
pfile_dir = os.path.join(args.output_dir, args.obs_dir)
sid_charges = list(target.iterkeys())
# assume that we should randomize PSMs for multithreading purposes; only reason
# why we are currently assuming this is that there is already a parameter for dripSearch
# which signifies whether we should shuffle the data
shuffle(sid_charges)
if(args.normalize != 'filter0'):
preprocess = pipeline(args.normalize)
validcharges = args.charges
ions = list(ion_dict.iterkeys())
ions.sort()
for i, ion in enumerate(ions):
ion_dict[ion] = i
# make collection per spectrum
make_master_parameters(args, ion_dict, ions)
peptide_pfile = create_pfile(pfile_dir,
'pep-lengths.pfile',
0, 1)
spectrum_pfile = create_pfile(pfile_dir,
'spectrum.pfile',
2,1)
pep_dt = open(os.path.join(args.output_dir, 'iterable.dts'), "w")
pep_dt.write('%d\n\n' % (num_psms))
pep_num = 0
for sid, charge in sid_charges:
s = spec_dict[sid]
for p in target[sid,charge]:
pep = p.peptide
# look for corresponding dripPSM
dripPsm = []
for t_psm in training_psms[sid,charge]:
if t_psm.peptide == pep:
dripPsm = t_psm
break
assert dripPsm
bNy = theo_spec_dict[s.spectrum_id, pep]
drip_peptide_sentence(pep_dt, pep, bNy,
pep_num, s.spectrum_id, args.max_obs_mass,
peptide_pfile, True, len(bNy)-1)
training_spectrum_sentence(spectrum_pfile, s.mz, s.intensity, dripPsm)
pep_num += 1
# close streams for this spectrum
pep_dt.close()
# compile dt using gmtkDTIndex
call(['gmtkDTindex', '-decisionTreeFiles',
os.path.join(args.output_dir,'iterable.dts')],
stdout = stdo, stderr = stde)
return pep_num
def make_training_data_lowres(args, spectra, dripMeans, theo_dict,
target, num_psms, fa_psms, stdo, stde):
"""Generate .pfiles for each training PSM.
inputs:
args - user input options
spectra - dictionary of spectra loaded into memory
theo_dict - dictionary of theoretical spectra per training PSM
target - training psms, instances of class PSM
num_psms - number of training PSMs
fa_psms - dictionary forced alignment PSMs, each an instance of
class dripPSM and containing sequences of insertions and
deletions per PSM (used for regularization during training)
outputs: None
pre:
args - user inputs have been checked process_args
spectra - spectra have been loaded but not preprocessed
theo_dict - dictionary have theoretical peaks has been created
target - training PSMs have been loaded
fa_psms - a forced alignment has been run and the sequences of
insertions and deletions has been computed
(calculateForcedAlignment has been run)
post:
GMTK training iterable dt will be created
in args.output_dir and training .pfiles will be created
in args.output_dir / args.obs_dir
"""
# make master file
make_master_parameters_lowres(args, dripMeans)
pfile_dir = os.path.join(args.output_dir, args.obs_dir)
sid_charges = list(target.iterkeys())
sid_charges.sort(key = lambda r: r[0])
# # assume that we should randomize PSMs for multithreading purposes; only reason
# # why we are currently assuming this is that there is already a parameter for dripSearch
# # which signifies whether we should shuffle the data
# shuffle(sid_charges)
peptide_pfile = create_pfile(pfile_dir,
'pep-lengths.pfile',
0, 1)
spectrum_pfile = create_pfile(pfile_dir,
'spectrum.pfile',
2,1)
pep_dt = open(os.path.join(args.output_dir, 'iterable.dts'), "w")
pep_dt.write('%d\n\n' % (num_psms))
pep_num = 0
for sid, charge in sid_charges:
s = spectra[sid]
for p in target[sid,charge]:
pep = p.peptide
bNy = theo_dict[sid,charge,pep]
# look for corresponding dripPSM
dripPsm = []
for t_psm in fa_psms[sid,charge]:
if t_psm.peptide == pep:
dripPsm = t_psm
break
assert dripPsm
drip_peptide_sentence(pep_dt, pep, bNy,
pep_num, s.spectrum_id, args.max_obs_mass,
peptide_pfile, True, len(bNy)-1)
training_spectrum_sentence(spectrum_pfile, s.mz, s.intensity,
dripPsm)
pep_num += 1
# close streams for this spectrum
pep_dt.close()
# compile dt using gmtkDTIndex
call(['gmtkDTindex', '-decisionTreeFiles',
os.path.join(args.output_dir,'iterable.dts')],
stdout = stdo, stderr = stde)