-
Notifications
You must be signed in to change notification settings - Fork 7
/
deepnovo_main_modules.py
2340 lines (1957 loc) · 82.6 KB
/
deepnovo_main_modules.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
# Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
# ==============================================================================
# Copyright 2017 Hieu Tran. All Rights Reserved.
#
# DeepNovo is publicly available for non-commercial uses.
#
# The source code in this file originated from the sequence-to-sequence tutorial
# of TensorFlow, Google Inc. I have modified the entire code to solve the
# problem of peptide sequencing. The copyright notice of Google is attached
# above as required by its Apache License.
# ==============================================================================
"""TODO(nh2tran): docstring."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
import os
import random
# ~ random.seed(4)
import sys
import time
import re
import resource
import numpy as np
# ~ cimport numpy as np
# ~ ctypedef np.float32_t C_float32
# ~ ctypedef np.int32_t C_int32
from six.moves import xrange # pylint: disable=redefined-builtin
import tensorflow as tf
from multiprocessing import Pool
# from pathos.multiprocessing import ProcessingPool as Pool
from functools import partial
import traceback
import gc
import deepnovo_config
import deepnovo_model
from deepnovo_worker_io import WorkerIO, WorkerI
import deepnovo_worker_io
from deepnovo_cython_modules import process_spectrum, get_candidate_intensity
def inspect_file_location(data_format, input_file):
"""TODO(nh2tran): docstring."""
print("inspect_file_location(), input_file = ", input_file)
if data_format == "msp":
keyword = "Name"
elif data_format == "mgf":
keyword = "BEGIN IONS"
spectra_file_location = []
with open(input_file, mode="r") as file_handle:
line = True
while line:
file_location = file_handle.tell()
line = file_handle.readline()
if keyword in line:
spectra_file_location.append(file_location)
return spectra_file_location
def read_single_spectrum(feature_index, worker_i, feature_fr, spectrum_fr):
spectrum_list = worker_i.get_spectrum([feature_index], feature_fr, spectrum_fr)
if not spectrum_list:
return None
spectrum = spectrum_list[0]
feature_id = spectrum["feature_id"]
raw_sequence = spectrum["raw_sequence"]
precursor_mass = spectrum["precursor_mass"]
spectrum_holder = spectrum["spectrum_holder"] if deepnovo_config.FLAGS.use_lstm else None
spectrum_original_forward = spectrum["spectrum_original_forward"]
spectrum_original_backward = spectrum["spectrum_original_backward"]
ms1_profile = spectrum["ms1_profile"]
### parse peptide sequence
# unlabelled spectra with empty raw_sequence can be used as neighbors,
# but not as main spectrum for training >> skip empty raw_sequence
if not raw_sequence:
status = 'empty'
return None, None, status
# parse peptide sequence, skip if unknown_modification
raw_sequence_len = len(raw_sequence)
peptide = []
index = 0
unknown_modification = False
while index < raw_sequence_len:
if raw_sequence[index] == "(":
if peptide[-1] == "C" and raw_sequence[index:index + 8] == "(+57.02)":
peptide[-1] = "C(Carbamidomethylation)"
index += 8
elif peptide[-1] == 'M' and raw_sequence[index:index + 8] == "(+15.99)":
peptide[-1] = 'M(Oxidation)'
index += 8
elif peptide[-1] == 'N' and raw_sequence[index:index + 6] == "(+.98)":
peptide[-1] = 'N(Deamidation)'
index += 6
elif peptide[-1] == 'Q' and raw_sequence[index:index + 6] == "(+.98)":
peptide[-1] = 'Q(Deamidation)'
index += 6
else: # unknown modification
# ~ elif ("".join(raw_sequence[index:index+8])=="(+42.01)"):
# ~ print("ERROR: unknown modification!")
# ~ print("raw_sequence = ", raw_sequence)
# ~ sys.exit()
unknown_modification = True
break
else:
peptide.append(raw_sequence[index])
index += 1
if unknown_modification:
status = 'mod'
return None, None, status
# skip if peptide length > MAX_LEN (train: 30; decode:50)
peptide_len = len(peptide)
if peptide_len > deepnovo_config.MAX_LEN:
status = 'length'
return None, None, status
# DEPRECATED quality control: precursor_mass & sequence_mass
# this can only be applied in train/valid/test, not in real application;
# but training data is from PEAKS DB with ppm control (except DIA),
# so this quality control is not needed.
# ~ sequence_mass = sum(deepnovo_config.mass_AA[aa] for aa in peptide)
# ~ sequence_mass += deepnovo_config.mass_N_terminus + deepnovo_config.mass_C_terminus
# ~ print(str(abs(precursor_mass-sequence_mass)/sequence_mass), file=test_handle, end="\n")
# ~ if (abs(precursor_mass-sequence_mass)/sequence_mass > deepnovo_config.precursor_mass_ppm):
# ~ counter_skipped_mass_precision += 1
# ~ print(abs(precursor_mass-sequence_mass))
# ~ print(sequence_mass)
# all mass and sequence filters passed
# counter_read += 1
### prepare forward, backward, and padding
for bucket_id, target_size in enumerate(deepnovo_config._buckets):
if peptide_len + 2 <= target_size: # +2 to include GO and EOS
break
decoder_size = deepnovo_config._buckets[bucket_id]
# parse peptide AA sequence to list of ids
peptide_ids = [deepnovo_config.vocab[x] for x in peptide]
# padding
pad_size = decoder_size - (len(peptide_ids) + 2)
# forward
if deepnovo_config.FLAGS.direction == 0 or deepnovo_config.FLAGS.direction == 2:
peptide_ids_forward = peptide_ids[:]
peptide_ids_forward.insert(0, deepnovo_config.GO_ID)
peptide_ids_forward.append(deepnovo_config.EOS_ID)
peptide_ids_forward += [deepnovo_config.PAD_ID] * pad_size
# backward
if deepnovo_config.FLAGS.direction == 1 or deepnovo_config.FLAGS.direction == 2:
peptide_ids_backward = peptide_ids[::-1]
peptide_ids_backward.insert(0, deepnovo_config.EOS_ID)
peptide_ids_backward.append(deepnovo_config.GO_ID)
peptide_ids_backward += [deepnovo_config.PAD_ID] * pad_size
### retrieve candidate_intensity for test/decode_true_feeding
if not deepnovo_config.FLAGS.beam_search:
# forward
if deepnovo_config.FLAGS.direction == 0 or deepnovo_config.FLAGS.direction == 2:
candidate_intensity_list_forward = []
prefix_mass = 0.0
for index in xrange(decoder_size):
prefix_mass += deepnovo_config.mass_ID[peptide_ids_forward[index]]
candidate_intensity = get_candidate_intensity(
spectrum_original_forward,
precursor_mass,
prefix_mass,
0)
candidate_intensity_list_forward.append(candidate_intensity)
# backward
if deepnovo_config.FLAGS.direction == 1 or deepnovo_config.FLAGS.direction == 2:
candidate_intensity_list_backward = []
suffix_mass = 0.0
for index in xrange(decoder_size):
suffix_mass += deepnovo_config.mass_ID[peptide_ids_backward[index]]
candidate_intensity = get_candidate_intensity(
spectrum_original_backward,
precursor_mass,
suffix_mass,
1)
candidate_intensity_list_backward.append(candidate_intensity)
### assign data to buckets
if deepnovo_config.FLAGS.beam_search:
if deepnovo_config.FLAGS.direction == 0:
data = [feature_id,
spectrum_holder,
spectrum_original_forward,
precursor_mass,
peptide_ids_forward]
elif deepnovo_config.FLAGS.direction == 1:
data = [feature_id,
spectrum_holder,
spectrum_original_backward,
precursor_mass,
peptide_ids_backward]
else:
data = [feature_id,
spectrum_holder,
spectrum_original_forward,
spectrum_original_backward,
precursor_mass,
peptide_ids_forward,
peptide_ids_backward]
else:
if deepnovo_config.FLAGS.direction == 0:
data = [spectrum_holder,
candidate_intensity_list_forward,
peptide_ids_forward]
elif deepnovo_config.FLAGS.direction == 1:
data = [spectrum_holder,
candidate_intensity_list_backward,
peptide_ids_backward]
else:
data = [spectrum_holder,
candidate_intensity_list_forward,
candidate_intensity_list_backward,
peptide_ids_forward,
peptide_ids_backward,
ms1_profile]
return data, bucket_id, 'OK'
def _prepare_data(feature_index, worker_i):
"""
:param feature_index:
:param get_spectrum: a callable, takes in [feature)index] and result spectrum_list
:return: None if the input feature is not valid
data, bucket_id, status_code
"""
### retrieve spectrum information
# read spectrum, skip if precursor_mass > MZ_MAX, pre-process spectrum
try:
with open(worker_i.input_feature_file, 'r') as feature_fr :
with open(worker_i.input_spectrum_file, 'r') as spectrum_fr:
return read_single_spectrum(feature_index, worker_i, feature_fr, spectrum_fr)
except Exception:
print("exception in _prepare_data: ")
traceback.print_exc()
raise
def read_spectra(worker_io, feature_index_list):
"""TODO(nh2tran): docstring."""
print("".join(["="] * 80)) # section-separating line
print("read_spectra()")
# assign spectrum into buckets according to peptide length
data_set = [[] for _ in deepnovo_config._buckets]
# use single/multi processor to read data during training
worker_i = WorkerI(worker_io)
if deepnovo_config.FLAGS.multiprocessor == 1:
with open(worker_i.input_feature_file, 'r') as feature_fr :
with open(worker_i.input_spectrum_file, 'r') as spectrum_fr:
result_list = [read_single_spectrum(feature_index, worker_i, feature_fr, spectrum_fr)
for feature_index in feature_index_list]
else:
mp_func = partial(_prepare_data, worker_i=worker_i)
gc.collect()
pool = Pool(processes=deepnovo_config.FLAGS.multiprocessor)
try:
result_list = pool.map_async(mp_func, feature_index_list).get(9999)
pool.close()
pool.join()
except KeyboardInterrupt:
pool.terminate()
pool.join()
sys.exit(1)
counter = len(feature_index_list)
# worker_io is designed for both prediction and training, hence it does not
# check raw_sequence for empty/mod/len because raw_sequence is only provided
# in training.
counter_skipped_empty = 0
counter_skipped_mod = 0
counter_skipped_len = 0
counter_read = 0
# ~ counter_skipped_mass_precision = 0
for result in result_list:
if result is None:
continue
data, bucket_id, status = result
if data:
counter_read += 1
data_set[bucket_id].append(data)
elif status == 'empty':
counter_skipped_empty += 1
elif status == 'mod':
counter_skipped_mod += 1
elif status == 'length':
counter_skipped_len += 1
worker_io.feature_count["read"] += len(result_list)
counter_skipped_mass = worker_i.feature_count["skipped_mass"]
counter_skipped = counter_skipped_mass + counter_skipped_empty + counter_skipped_mod + counter_skipped_len
print(" total peptide %d" % counter)
print(" peptide read %d" % counter_read)
print(" peptide skipped %d" % counter_skipped)
print(" peptide skipped by mass %d" % counter_skipped_mass)
print(" peptide skipped by empty %d" % counter_skipped_empty)
print(" peptide skipped by mod %d" % counter_skipped_mod)
print(" peptide skipped by len %d" % counter_skipped_len)
# ~ print(counter_skipped_mass_precision)
# ~ print(abc)
del result_list
del worker_i
gc.collect()
return data_set, counter_read
def read_random_stack(worker_io, feature_index_list, stack_size):
"""TODO(nh2tran): docstring."""
print("read_random_stack()")
random_index_list = random.sample(feature_index_list,
min(stack_size, len(feature_index_list)))
return read_spectra(worker_io, random_index_list)
def get_batch_01(index_list, data_set, bucket_id):
"""TODO(nh2tran): docstring."""
# ~ print("get_batch()")
batch_size = len(index_list)
spectra_list = []
candidate_intensity_lists = []
decoder_inputs = []
for index in index_list:
# Get a random entry of encoder and decoder inputs from data,
(spectrum_holder,
candidate_intensity_list,
decoder_input) = data_set[bucket_id][index]
if spectrum_holder is None: # spectrum_holder is not provided if not use_lstm
spectrum_holder = np.zeros(shape=(deepnovo_config.neighbor_size, deepnovo_config.MZ_SIZE),
dtype=np.float32)
spectra_list.append(spectrum_holder)
candidate_intensity_lists.append(candidate_intensity_list)
decoder_inputs.append(decoder_input)
batch_encoder_inputs = [np.array(spectra_list)]
batch_intensity_inputs = []
batch_decoder_inputs = []
batch_weights = []
decoder_size = deepnovo_config._buckets[bucket_id]
for length_idx in xrange(decoder_size):
# batch_intensity_inputs and batch_decoder_inputs are just re-indexed.
batch_intensity_inputs.append(
np.array([candidate_intensity_lists[batch_idx][length_idx]
for batch_idx in xrange(batch_size)], dtype=np.float32))
batch_decoder_inputs.append(
np.array([decoder_inputs[batch_idx][length_idx]
for batch_idx in xrange(batch_size)], dtype=np.int32))
# Create target_weights to be 0 for targets that are padding.
batch_weight = np.ones(batch_size, dtype=np.float32)
for batch_idx in xrange(batch_size):
# The corresponding target is decoder_input shifted by 1 forward.
if length_idx < decoder_size - 1:
target = decoder_inputs[batch_idx][length_idx + 1]
# We set weight to 0 if the corresponding target is a PAD symbol.
if (length_idx == decoder_size - 1
or target == deepnovo_config.EOS_ID
or target == deepnovo_config.GO_ID
or target == deepnovo_config.PAD_ID):
batch_weight[batch_idx] = 0.0
batch_weights.append(batch_weight)
return (batch_encoder_inputs,
batch_intensity_inputs,
batch_decoder_inputs,
batch_weights)
def get_batch_2(index_list, data_set, bucket_id):
"""TODO(nh2tran): docstring."""
# ~ print("get_batch()")
batch_size = len(index_list)
spectrum_holder_list = []
ms1_profile_list = []
candidate_intensity_lists_forward = []
candidate_intensity_lists_backward = []
decoder_inputs_forward = []
decoder_inputs_backward = []
for index in index_list:
# Get a random entry of encoder and decoder inputs from data,
(spectrum_holder,
candidate_intensity_list_forward,
candidate_intensity_list_backward,
decoder_input_forward,
decoder_input_backward,
ms1_profile) = data_set[bucket_id][index]
if spectrum_holder is None: # spectrum_holder is not provided if not use_lstm
spectrum_holder = np.zeros(shape=(deepnovo_config.neighbor_size, deepnovo_config.MZ_SIZE),
dtype=np.float32)
spectrum_holder_list.append(spectrum_holder)
ms1_profile_list.append(ms1_profile)
candidate_intensity_lists_forward.append(candidate_intensity_list_forward)
candidate_intensity_lists_backward.append(candidate_intensity_list_backward)
decoder_inputs_forward.append(decoder_input_forward)
decoder_inputs_backward.append(decoder_input_backward)
batch_spectrum_holder = np.array(spectrum_holder_list)
batch_ms1_profile = np.array(ms1_profile_list)
batch_intensity_inputs_forward = []
batch_intensity_inputs_backward = []
batch_decoder_inputs_forward = []
batch_decoder_inputs_backward = []
batch_weights = []
decoder_size = deepnovo_config._buckets[bucket_id]
for length_idx in xrange(decoder_size):
# batch_intensity_inputs and batch_decoder_inputs are re-indexed.
batch_intensity_inputs_forward.append(
np.array([candidate_intensity_lists_forward[batch_idx][length_idx]
for batch_idx in xrange(batch_size)], dtype=np.float32))
batch_intensity_inputs_backward.append(
np.array([candidate_intensity_lists_backward[batch_idx][length_idx]
for batch_idx in xrange(batch_size)], dtype=np.float32))
batch_decoder_inputs_forward.append(
np.array([decoder_inputs_forward[batch_idx][length_idx]
for batch_idx in xrange(batch_size)], dtype=np.int32))
batch_decoder_inputs_backward.append(
np.array([decoder_inputs_backward[batch_idx][length_idx]
for batch_idx in xrange(batch_size)], dtype=np.int32))
# Create target_weights to be 0 for targets that are padding.
batch_weight = np.ones(batch_size, dtype=np.float32)
for batch_idx in xrange(batch_size):
# The corresponding target is decoder_input shifted by 1 forward.
if length_idx < decoder_size - 1:
target = decoder_inputs_forward[batch_idx][length_idx + 1]
# We set weight to 0 if the corresponding target is a PAD symbol.
if (length_idx == decoder_size - 1
or target == deepnovo_config.EOS_ID
or target == deepnovo_config.GO_ID
or target == deepnovo_config.PAD_ID):
batch_weight[batch_idx] = 0.0
batch_weights.append(batch_weight)
return (batch_spectrum_holder,
batch_ms1_profile,
batch_intensity_inputs_forward,
batch_intensity_inputs_backward,
batch_decoder_inputs_forward,
batch_decoder_inputs_backward,
batch_weights)
def trim_decoder_input(decoder_input, direction):
"""TODO(nh2tran): docstring."""
if direction == 0:
LAST_LABEL = deepnovo_config.EOS_ID
elif direction == 1:
LAST_LABEL = deepnovo_config.GO_ID
# excluding FIRST_LABEL, LAST_LABEL & PAD
return decoder_input[1:decoder_input.index(LAST_LABEL)]
def print_AA_basic(output_file_handle,
feature_id,
decoder_input,
output,
direction,
accuracy_AA,
len_AA,
exact_match):
"""TODO(nh2tran): docstring."""
if direction == 0:
LAST_LABEL = deepnovo_config.EOS_ID
elif direction == 1:
LAST_LABEL = deepnovo_config.GO_ID
decoder_input = trim_decoder_input(decoder_input, direction)
decoder_input_AA = [deepnovo_config.vocab_reverse[x] for x in decoder_input]
output_seq, output_score = output
output_len = output_seq.index(LAST_LABEL) if LAST_LABEL in output_seq else 0
output_AA = [deepnovo_config.vocab_reverse[x] for x in output_seq[:output_len]]
if direction == 1:
decoder_input_AA = decoder_input_AA[::-1]
output_AA = output_AA[::-1]
print("%s\t%s\t%s\t%.2f\t%d\t%d\t%d\n"
% (feature_id,
",".join(decoder_input_AA),
",".join(output_AA),
output_score,
accuracy_AA,
len_AA,
exact_match),
file=output_file_handle,
end="")
def test_AA_match_1by1(decoder_input, output):
"""TODO(nh2tran): docstring."""
decoder_input_len = len(decoder_input)
num_match = 0
index_aa = 0
while index_aa < decoder_input_len:
# ~ if decoder_input[index_aa]==output[index_aa]:
if (abs(deepnovo_config.mass_ID[decoder_input[index_aa]]
- deepnovo_config.mass_ID[output[index_aa]])
< deepnovo_config.AA_MATCH_PRECISION):
num_match += 1
index_aa += 1
return num_match
def test_AA_match_novor(decoder_input, output):
"""TODO(nh2tran): docstring."""
decoder_input_len = len(decoder_input)
output_len = len(output)
decoder_input_mass = [deepnovo_config.mass_ID[x] for x in decoder_input]
decoder_input_mass_cum = np.cumsum(decoder_input_mass)
output_mass = [deepnovo_config.mass_ID[x] for x in output]
output_mass_cum = np.cumsum(output_mass)
num_match = 0
i = 0
j = 0
while i < decoder_input_len and j < output_len:
if abs(decoder_input_mass_cum[i] - output_mass_cum[j]) < 0.5:
if abs(decoder_input_mass[i] - output_mass[j]) < 0.1:
num_match += 1
i += 1
j += 1
elif decoder_input_mass_cum[i] < output_mass_cum[j]:
i += 1
else:
j += 1
return num_match
def test_AA_decode_single(decoder_input, output, direction):
"""TODO(nh2tran): docstring."""
accuracy_AA = 0.0
len_AA = 0.0
exact_match = 0.0
len_match = 0.0
if direction == 0:
LAST_LABEL = deepnovo_config.EOS_ID
elif direction == 1:
LAST_LABEL = deepnovo_config.GO_ID
# decoder_input = [AA]; output = [AA]
decoder_input = trim_decoder_input(decoder_input, direction)
decoder_input_len = len(decoder_input)
output_len = output.index(LAST_LABEL) if LAST_LABEL in output else 0
output = output[:output_len]
# measure accuracy
num_match = test_AA_match_novor(decoder_input, output)
# ~ accuracy_AA = num_match / decoder_input_len
accuracy_AA = num_match
len_AA = decoder_input_len
len_decode = output_len
if num_match == decoder_input_len:
exact_match = 1.0
if output_len == decoder_input_len:
len_match = 1.0
# testing
# ~ print(decoder_input_AA)
# ~ print(output_AA)
# ~ print(num_match)
# ~ print(batch_accuracy_AA)
# ~ print(num_exact_match)
# ~ print(num_len_match)
# ~ sys.exit()
return accuracy_AA, len_AA, len_decode, exact_match, len_match
def test_AA_true_feeding_single(decoder_input, output, direction):
"""TODO(nh2tran): docstring."""
accuracy_AA = 0.0
len_AA = 0.0
exact_match = 0.0
len_match = 0.0
# decoder_input = [AA]; output = [AA...]
decoder_input = trim_decoder_input(decoder_input, direction)
decoder_input_len = len(decoder_input)
# measure accuracy
num_match = test_AA_match_1by1(decoder_input, output)
# ~ accuracy_AA = num_match / decoder_input_len
accuracy_AA = num_match
len_AA = decoder_input_len
if num_match == decoder_input_len:
exact_match = 1.0
# ~ if output_len == decoder_input_len:
# ~ len_match = 1.0
return accuracy_AA, len_AA, exact_match, len_match
def test_AA_decode_batch(scans,
decoder_inputs,
outputs,
direction,
output_file_handle):
"""TODO(nh2tran): docstring."""
batch_accuracy_AA = 0.0
batch_len_AA = 0.0
batch_len_decode = 0.0
num_exact_match = 0.0
num_len_match = 0.0
# ~ batch_size = len(decoder_inputs)
for index in xrange(len(scans)):
# ~ # for testing
# ~ for index in xrange(15,20):
scan = scans[index]
decoder_input = decoder_inputs[index]
output = outputs[index]
output_seq, _ = output
(accuracy_AA,
len_AA,
len_decode,
exact_match,
len_match) = test_AA_decode_single(decoder_input, output_seq, direction)
# ~ # for testing
# ~ print([deepnovo_config.vocab_reverse[x] for x in decoder_input[1:]])
# ~ print([deepnovo_config.vocab_reverse[x] for x in output_seq])
# ~ print(accuracy_AA)
# ~ print(exact_match)
# ~ print(len_match)
# print to output file
print_AA_basic(output_file_handle,
scan,
decoder_input,
output,
direction,
accuracy_AA,
len_AA,
exact_match)
batch_accuracy_AA += accuracy_AA
batch_len_AA += len_AA
batch_len_decode += len_decode
num_exact_match += exact_match
num_len_match += len_match
# ~ return (batch_accuracy_AA/batch_size,
# ~ num_exact_match/batch_size,
# ~ num_len_match/batch_size)
# ~ return (batch_accuracy_AA/batch_len_AA,
# ~ num_exact_match/batch_size,
# ~ num_len_match/batch_size)
return (batch_accuracy_AA,
batch_len_AA,
batch_len_decode,
num_exact_match,
num_len_match)
def test_logit_single_01(decoder_input, output_logit):
"""TODO(nh2tran): docstring."""
output = [np.argmax(x) for x in output_logit]
return test_AA_true_feeding_single(decoder_input,
output,
deepnovo_config.FLAGS.direction)
def test_logit_single_2(decoder_input_forward,
decoder_input_backward,
output_logit_forward,
output_logit_backward):
"""TODO(nh2tran): docstring."""
# length excluding FIRST_LABEL & LAST_LABEL
decoder_input_len = decoder_input_forward[1:].index(deepnovo_config.EOS_ID)
# average forward-backward prediction logit
logit_forward = output_logit_forward[:decoder_input_len]
logit_backward = output_logit_backward[:decoder_input_len]
logit_backward = logit_backward[::-1]
output = []
for x, y in zip(logit_forward, logit_backward):
prob_forward = np.exp(x) / np.sum(np.exp(x))
prob_backward = np.exp(y) / np.sum(np.exp(y))
output.append(np.argmax(prob_forward * prob_backward))
output.append(deepnovo_config.EOS_ID)
return test_AA_true_feeding_single(decoder_input_forward, output, direction=0)
def test_logit_batch_01(decoder_inputs, output_logits):
"""TODO(nh2tran): docstring."""
batch_accuracy_AA = 0.0
batch_len_AA = 0.0
num_exact_match = 0.0
num_len_match = 0.0
batch_size = len(decoder_inputs[0])
for batch in xrange(batch_size):
decoder_input = [x[batch] for x in decoder_inputs]
output_logit = [x[batch] for x in output_logits]
accuracy_AA, len_AA, exact_match, len_match = test_logit_single_01(
decoder_input,
output_logit)
# for testing
# ~ if (exact_match==0):
# ~ print(batch)
# ~ print([deepnovo_config.vocab_reverse[x] for x in decoder_input[1:]])
# ~ print([deepnovo_config.vocab_reverse[np.argmax(x)] for x in output_logit])
# ~ print(accuracy_AA)
# ~ print(exact_match)
# ~ print(len_match)
# ~ sys.exit()
batch_accuracy_AA += accuracy_AA
batch_len_AA += len_AA
num_exact_match += exact_match
num_len_match += len_match
# ~ return (batch_accuracy_AA/batch_size,
# ~ num_exact_match/batch_size,
# ~ num_len_match/batch_size)
# ~ return (batch_accuracy_AA/batch_len_AA,
# ~ num_exact_match/batch_size,
# ~ num_len_match/batch_size)
return batch_accuracy_AA, batch_len_AA, num_exact_match, num_len_match
def test_logit_batch_2(decoder_inputs_forward,
decoder_inputs_backward,
output_logits_forward,
output_logits_backward):
"""TODO(nh2tran): docstring."""
batch_accuracy_AA = 0.0
batch_len_AA = 0.0
num_exact_match = 0.0
num_len_match = 0.0
batch_size = len(decoder_inputs_forward[0])
for batch in xrange(batch_size):
decoder_input_forward = [x[batch] for x in decoder_inputs_forward]
decoder_input_backward = [x[batch] for x in decoder_inputs_backward]
output_logit_forward = [x[batch] for x in output_logits_forward]
output_logit_backward = [x[batch] for x in output_logits_backward]
accuracy_AA, len_AA, exact_match, len_match = test_logit_single_2(
decoder_input_forward,
decoder_input_backward,
output_logit_forward,
output_logit_backward)
batch_accuracy_AA += accuracy_AA
batch_len_AA += len_AA
num_exact_match += exact_match
num_len_match += len_match
# ~ return (batch_accuracy_AA/batch_size,
# ~ num_exact_match/batch_size,
# ~ num_len_match/batch_size)
# ~ return (batch_accuracy_AA/batch_len_AA,
# ~ num_exact_match/batch_size,
# ~ num_len_match/batch_size)
return batch_accuracy_AA, batch_len_AA, num_exact_match, num_len_match
def test_accuracy(sess, model, data_set, bucket_id, print_summary=True):
"""TODO(nh2tran): docstring."""
spectrum_time = 0.0
avg_loss = 0.0
avg_loss_classification = 0.0
avg_accuracy_AA = 0.0
avg_len_AA = 0.0
avg_accuracy_peptide = 0.0
avg_accuracy_len = 0.0
data_set_len = len(data_set[bucket_id])
data_set_index_list = range(data_set_len)
data_set_index_chunk_list = [data_set_index_list[i:i + deepnovo_config.batch_size]
for i in range(0,
data_set_len,
deepnovo_config.batch_size)]
for chunk in data_set_index_chunk_list:
start_time = time.time()
# get_batch_01/2
if deepnovo_config.FLAGS.direction == 0 or deepnovo_config.FLAGS.direction == 1:
(encoder_inputs,
intensity_inputs,
decoder_inputs,
target_weights) = get_batch_01(chunk, data_set, bucket_id)
else:
(spectrum_holder,
ms1_profile,
intensity_inputs_forward,
intensity_inputs_backward,
decoder_inputs_forward,
decoder_inputs_backward,
target_weights) = get_batch_2(chunk, data_set, bucket_id)
# model_step
if deepnovo_config.FLAGS.direction == 0:
loss, loss_classification, output_logits = model.step(
sess,
encoder_inputs,
intensity_inputs_forward=intensity_inputs,
decoder_inputs_forward=decoder_inputs,
target_weights=target_weights,
bucket_id=bucket_id,
training_mode=False)
elif deepnovo_config.FLAGS.direction == 1:
loss, loss_classification, output_logits = model.step(
sess,
encoder_inputs,
intensity_inputs_backward=intensity_inputs,
decoder_inputs_backward=decoder_inputs,
target_weights=target_weights,
bucket_id=bucket_id,
training_mode=False)
else:
loss, loss_classification, output_logits_forward, output_logits_backward = model.step(
sess,
spectrum_holder,
ms1_profile,
intensity_inputs_forward=intensity_inputs_forward,
intensity_inputs_backward=intensity_inputs_backward,
decoder_inputs_forward=decoder_inputs_forward,
decoder_inputs_backward=decoder_inputs_backward,
target_weights=target_weights,
bucket_id=bucket_id,
training_mode=False)
spectrum_time += time.time() - start_time
# test_logit_batch_01/2
if deepnovo_config.FLAGS.direction == 0 or deepnovo_config.FLAGS.direction == 1:
(batch_accuracy_AA,
batch_len_AA,
num_exact_match,
num_len_match) = test_logit_batch_01(decoder_inputs, output_logits)
else:
(batch_accuracy_AA,
batch_len_AA,
num_exact_match,
num_len_match) = test_logit_batch_2(decoder_inputs_forward,
decoder_inputs_backward,
output_logits_forward,
output_logits_backward)
avg_loss += loss * len(chunk) # because the loss was averaged by batch_size
avg_loss_classification += loss_classification * len(chunk)
avg_accuracy_AA += batch_accuracy_AA
avg_len_AA += batch_len_AA
avg_accuracy_peptide += num_exact_match
avg_accuracy_len += num_len_match
spectrum_time /= data_set_len
avg_loss /= data_set_len
avg_loss_classification /= data_set_len
avg_accuracy_AA /= avg_len_AA
avg_accuracy_peptide /= data_set_len
avg_accuracy_len /= data_set_len
eval_ppx = math.exp(avg_loss) if avg_loss < 300 else float('inf')
eval_ppx_classification = math.exp(avg_loss_classification) if avg_loss_classification < 300 else float('inf')
if print_summary:
print("test_accuracy()")
print(" bucket %d spectrum_time %.4f" % (bucket_id, spectrum_time))
print(" bucket %d perplexity %.2f" % (bucket_id, eval_ppx))
print(" bucket %d perplexity classification %.2f" % (bucket_id, eval_ppx_classification))
print(" bucket %d avg_accuracy_AA %.4f" % (bucket_id, avg_accuracy_AA))
print(" bucket %d avg_accuracy_peptide %.4f"
% (bucket_id, avg_accuracy_peptide))
print(" bucket %d avg_accuracy_len %.4f" % (bucket_id, avg_accuracy_len))
return avg_loss, avg_accuracy_AA, avg_accuracy_peptide, avg_accuracy_len
def knapsack_example():
"""TODO(nh2tran): docstring."""
peptide_mass = 11
print("peptide_mass = ", peptide_mass)
mass_aa = [2, 3, 4, 5]
print("mass_aa = ", mass_aa)
knapsack_matrix = np.zeros(shape=(4, 11), dtype=bool)
for aa_id in xrange(4):
for col in xrange(peptide_mass):
current_mass = col + 1
if current_mass < mass_aa[aa_id]:
knapsack_matrix[aa_id, col] = False
if current_mass == mass_aa[aa_id]:
knapsack_matrix[aa_id, col] = True
if current_mass > mass_aa[aa_id]:
sub_mass = current_mass - mass_aa[aa_id]
sub_col = sub_mass - 1
if np.sum(knapsack_matrix[:, sub_col]) > 0:
knapsack_matrix[aa_id, col] = True
knapsack_matrix[:, col] = np.logical_or(knapsack_matrix[:, col],
knapsack_matrix[:, sub_col])
else:
knapsack_matrix[aa_id, col] = False
print("mass_aa[{0}] = {1}".format(aa_id, mass_aa[aa_id]))
print(knapsack_matrix)
def knapsack_build():
"""TODO(nh2tran): docstring."""
peptide_mass = deepnovo_config.MZ_MAX
peptide_mass = peptide_mass - (deepnovo_config.mass_C_terminus + deepnovo_config.mass_H)
print("peptide_mass = ", peptide_mass)
peptide_mass_round = int(round(peptide_mass
* deepnovo_config.KNAPSACK_AA_RESOLUTION))
print("peptide_mass_round = ", peptide_mass_round)
# ~ peptide_mass_upperbound = (peptide_mass_round
# ~ + deepnovo_config.KNAPSACK_MASS_PRECISION_TOLERANCE)
peptide_mass_upperbound = (peptide_mass_round
+ deepnovo_config.KNAPSACK_AA_RESOLUTION)
knapsack_matrix = np.zeros(shape=(deepnovo_config.vocab_size,
peptide_mass_upperbound),
dtype=bool)
for aa_id in xrange(3, deepnovo_config.vocab_size): # excluding PAD, GO, EOS
mass_aa_round = int(round(deepnovo_config.mass_ID[aa_id]
* deepnovo_config.KNAPSACK_AA_RESOLUTION))
print(deepnovo_config.vocab_reverse[aa_id], mass_aa_round)
for col in xrange(peptide_mass_upperbound):