-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdenovo_peptide_discovery.py
2228 lines (2087 loc) · 106 KB
/
denovo_peptide_discovery.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 python3
"""
Created on Fri Oct 7 16:00:55 2022
@author: Ian
"""
##################### PACKAGES #######################################
import os
import math
import pandas as pd
from zipfile import ZipFile
from pyteomics import mgf
import matplotlib.pyplot as plt
import numpy as np
from ms2pip.ms2pipC import MS2PIP
from deeplc import DeepLC
from ms2pip.single_prediction import SinglePrediction
import csv
import warnings
from Bio import SeqIO
import re
import time
warnings.filterwarnings("ignore", category=DeprecationWarning)
warnings.filterwarnings('ignore')
#####################################################################
################### Functions #######################################
def insilico_peptide(pep, new_pep, temp, MZ):
new_pep_list = {}
for AA in pep:
for AA2 in new_pep:
if AA2[-1].isdigit()==True and AA[-1].isdigit()==True:
continue
if (MZ-0.01< (AA_code[AA]+new_pep[AA2]) < MZ+0.01):
add = AA2+'|'+AA
temp.add(add)
elif (AA_code[AA]+new_pep[AA2]) < MZ:
new_pep_list[AA2+'|'+AA] = AA_code[AA]+new_pep[AA2]
elif (AA_code[AA]+new_pep[AA2]) > MZ:
temp.add(AA2)
return new_pep_list, temp
def jaccard(list1, list2, pep):
mass = find_mass(pep)
if list(list1).count(0)>1 or len(list1)==0:
return 0
intersection = len(list(set(list1).intersection(list2)))
union = (len(list1) + len(list2)) - intersection
j = ((float(intersection) / union))
return j*mass/len(pep)
def insilico_spectrum(peptides, spectrums, intensity, ion, to_add):
if len(spectrums)==0:
return [], []
if ('k' in peptides.split('|') or 'r' in peptides.split('|') or 'Carbamidomethyl10' in peptides.split('|')) and ('K' in peptides.split('|') or 'R' in peptides.split('|') or 'Carbamidomethyl2' in peptides.split('|')):
final_y_array = [0]*len(spectrums)
return spectrums, np.array(final_y_array)
if ion == 'Y' and ('k' in peptides[1:] or 'r' in peptides[1:]):
final_y_array = [0]*len(spectrums)
return spectrums, np.array(final_y_array)
if ion == 'Y' and 'Gln->pyro-Glu' in peptides or 'Glu->pyro-Glu' in peptides:
return [], []
if ion == 'B' and ('k' in peptides.split('|') or 'r' in peptides.split('|')):
return [], []
x_array = []
x_point = ion_types[ion]+to_add #19 for Y ions, 1 for b ions
for AA in peptides.split('|'):
x_array.append(AA_code[AA]+x_point)
x_point += AA_code[AA]
x_array = sorted(x_array)
if min(spectrums)>max(x_array):
final_y_array = [0]*len(spectrums)
return spectrums, np.array(final_y_array)
pep_spectrum = {}
for loc,num in enumerate(spectrums):
former=0
for value in x_array:
if value-dev <= num <= value+dev:
if intensity[loc]>former:
pep_spectrum[value]=num
# if 3>len(peptides.split('|'))>6:
# double_missing_peak = False
# zero_test = ion_types[ion]
# zero_count = 0
# first = 0
# much_miss = False
# for nummer, amino in enumerate(peptides.split('|')):
# zero_test += AA_code[amino]
# if zero_test not in pep_spectrum.keys() and double_missing_peak == True:
# final_y_array = [0]*len(spectrums)
# return spectrums, np.array(final_y_array)
# elif zero_test not in pep_spectrum.keys() and nummer <= 1:
# first += 1
# elif zero_test not in pep_spectrum.keys():
# double_missing_peak = True
# if much_miss == False:
# much_miss = True
# double_missing_peak = False
# # if first == 1 and nummer ==2:
# # final_y_array = [0]*len(spectrums)
# # return spectrums, np.array(final_y_array)
# zero_count += 1
# else:
# double_missing_peak = False
# much_miss = False
# if zero_count > (abs(math.ceil(len(peptides.split('|'))/3))):
# final_y_array = [0]*len(spectrums)
# return spectrums, np.array(final_y_array)
final_y_array = []
for y_loc, point in enumerate(spectrums):
if point in pep_spectrum.values():
final_y_array.append(intensity[y_loc])
else:
final_y_array.append(1e-15)
return spectrums, np.array(final_y_array)
def pearson_correlation(real_spectra, insilico_spectra, overlap = False, i=0):
# if overlap == 'Overlap' and list(insilico_spectra).count(0)>2:
# corr_matrix = np.corrcoef(real_spectra, insilico_spectra)
# return corr_matrix
if len(real_spectra)<=2:
return[[0,0]]
if list(real_spectra) == list(insilico_spectra):
return [[1,1]]
if list(insilico_spectra).count(0)>1: #or sum(insilico_spectra)/len(insilico_spectra) <= min(insilico_spectra)
return [[0,0]]
#corr_matrix = [[0,np.sum(insilico_spectra)/np.sum(real_spectra)]]
corr_matrix = np.corrcoef(real_spectra, insilico_spectra)
if math.isnan(corr_matrix[0][1]) == True:
return [[0,0]]
return corr_matrix
def find_treshold(pearson_list,MZ=250):
Y = [num[-1] for num in pearson_list if num[-1]>0]
T = Y
Y = sorted(Y)[::-1]
if len(Y)<=500:
print('no threshold')
return 1e-15
much = len(Y)*0.1
Y = Y[int(len(Y)*0.1):]
z=np.polyfit([x for x, a in enumerate(Y)], Y, 1)
if much + len([num for num in Y if num >=z[1]]) <min(MZ*3,1500):
z = [0,z[1]*0.85]
while len([num for num in T if num >= z[1]])>min(MZ*(MZ/420)*3,2500):
z = [0, z[1]*1.01]
print('threshold is', z[1], 'with maximum ', min(MZ*(MZ/420)*3,2500))
return z[1]
def find_treshold_overlap(pearson_list):
#cluster with pearson jaccard score to find best group. Only keep points from top group
points = [[num[1], num[2]*num[3]] for num in pearson_list if num[3]>0.45 and num[2]>0.45]
if len(points)==0:
return []
a = [num[0] for num in points]
pearson_list = [num for num in pearson_list if num[3]>0.45 and num[2]>0.45 and num[1]>=max(a)*0.4]
points = [[num[0],num[1]] for num in points if num[0]>=max(a)*0.4]
if len(points)==0:
return []
a = [num[0] for num in points]
b = [num[1] for num in points]
kmeans_pr = [1 if (num[1]>=max(b)*0.9 and num[0]>=max(a)*0.7) or (num[0]>=max(a)*0.6 and num[1]>=max(b)*0.8) or num[1]>=0.9 or num[0]>=0.85*max(a) else 0 for num in points]
add = 0
while kmeans_pr.count(1)>250 and add<0.1:
to_much_results = int(kmeans_pr.count(1))
print(to_much_results, ' is to much, reducing! ...')
add += 0.01
kmeans_pr = [1 if (num[1]>=max(b)*(0.9+add) and num[0]>=max(a)*(0.75+add)) or (num[0]>=max(a)*(0.75+add) and num[1]>=max(b)*(0.8+add)) or num[1]>=(0.98+add) or num[0]>=(max(a)*(0.9+add)) else 0 for num in points]
plt.scatter(a,b, c=kmeans_pr)
plt.title('Selection of potential peptides \n match score to spectrum')
plt.ylabel('pearson correlation * coverage')
plt.xlabel('Peak counting score')
plt.show()
pearson_list = [pearson_list[i] for i, u in enumerate(kmeans_pr) if u == 1]
pearson_list = [pearson_list[i] for i, u in enumerate(pearson_list) if u[3]>0.45 and u[2]>0.45 and u[1]>=max(a)*0.4]
return pearson_list
def make_plots(xpoints, ypoints, peptide, PC_list, ion):
cut = find_treshold(PC_list)
ylist = []
xlist = []
for a, AA in enumerate(PC_list):
ylist.append(AA[1])
xlist.append(a)
plt.title('Pearson correlation plot')
plt.bar(xlist, ylist)
plt.axhline(cut, c='r', alpha=0.5)
plt.show()
def find_mass(peptide):
mass = 0
for AA in peptide:
mass += AA_code[AA]
return mass
def select_top_scores(PC_list, treshold):
x = {}
for item in PC_list:
if item[-1] >= treshold and item[-1] != 0:
to_add = item[0].split('|')
if int(item[1]) != 0:
x[str(item[1])+'*'+'|'.join(to_add)] = find_mass(to_add)+item[1]
else:
x['|'.join(to_add)] = find_mass(to_add)
# plt.bar([len(PC_list),len(x)], ['possible fingerprints', 'remaining fingerprints'])
# plt.title('Remaining potential TAGs \n after peak counting')
# plt.show()
return x
def find_overlap(y_ions, b_ions, yextra, bextra): #adapt for downstream
y_ions = y_ions.split('|')[::-1]
b_ions = b_ions.split('|')
to = 1+int(len(y_ions)/3)
to_b = 1+int(len(b_ions)/3)
if spectrum['params']['charge'][0]==1:
print('overlap of 1+')
to = len(y_ions)
to_b = 0
if (''.join(b_ions[-1]) not in ''.join(y_ions)[:to]) or (''.join(y_ions[0]) not in ''.join(b_ions)[-to_b:]):
return[]
if 'Methyl' in y_ions or'Gln->pyro-Glu' in y_ions or 'Glu->pyro-Glu' in y_ions:
return []
if 'Methyl' in b_ions[1:] or 'Gln->pyro-Glu' in b_ions[1:] or 'Glu->pyro-Glu' in b_ions[1:] or 'k' in b_ions or 'r' in b_ions or 'Carbamidomethyl10' in b_ions:
return []
for i in range(to_b, len(b_ions)):
b_ions_overlap = b_ions[i:len(b_ions)]
if b_ions_overlap ==y_ions[0:len(b_ions_overlap)]:
massa = find_mass(b_ions[0:i]+y_ions)+yextra+bextra
if pp_mass-1-math.floor(21/spectrum['params']['charge'][0]) <= massa/spectrum['params']['charge'][0] <= pp_mass+1-math.floor(21/spectrum['params']['charge'][0]): #include h3o+ and h+
adding = [b_ions[0:i] + y_ions, yextra, bextra]
result = []
ptm = []
if bextra != 0:
to_ptm = '0|'+N_terms[bextra]
ptm.append(to_ptm)
for loc, element in enumerate(adding[0]):
if element in PTM:
result.append(PTM[element])
to_ptm = str(loc+1)+'|'+''.join(c for c in element if c.isdigit()==False)
ptm.append(to_ptm)
else:
result.append(element)
if ('k' in result or 'r' in result) and ('K' in result or 'R' in result):
return []
return ("".join(result), "|".join(ptm), adding)
return []
def make_overlap_spectrum(y_peptide, b_peptide, spectrum, intensity, yextra, bextra):
original_peak = []
x_array_Y = []
x_point_Y = ion_types['Y'] + yextra
H2O = False
NH3 = False
heavy_kr = False
for AA in y_peptide:
x_array_Y.append(AA_code[AA]+x_point_Y)
original_peak.append(AA_code[AA]+x_point_Y)
if AA in mods['-H2O'] or H2O == True:
H2O = True
x_array_Y.append(AA_code[AA]+x_point_Y-18.010565)
if AA in mods['-NH3'] or NH3 == True:
NH3 = True
if heavy == True and AA in ['k', 'r']:
x_array_Y.append(AA_code[AA]+x_point_Y-18.026549)
heavy_kr = True
elif heavy != True:
x_array_Y.append(AA_code[AA]+x_point_Y-17.026549)
else:
if heavy_kr == True:
x_array_Y.append(AA_code[AA]+x_point_Y-18.026549)
x_array_Y.append(AA_code[AA]+x_point_Y-17.026549)
x_point_Y += AA_code[AA]
x_array_B = []
x_point_B = ion_types['B'] + bextra
H2O = False
NH3 = False
heavy_kr = False
for AA in b_peptide:
x_array_B.append(AA_code[AA]+x_point_B)
original_peak.append(AA_code[AA]+x_point_B)
if AA in mods['-H2O'] or H2O == True:
H2O = True
x_array_B.append(AA_code[AA]+x_point_B-18.010565)
if AA in mods['-NH3'] or NH3 == True:
NH3 = True
if heavy == True and AA.upper() in ['k', 'r']:
x_array_B.append(AA_code[AA]+x_point_B-18.026549)
heavy_kr=True
elif heavy != True:
x_array_B.append(AA_code[AA]+x_point_B-17.026549)
else:
if heavy_kr==True:
x_array_B.append(AA_code[AA]+x_point_B-18.026549)
x_array_B.append(AA_code[AA]+x_point_B-17.026549)
x_point_B += AA_code[AA]
x_array = set(x_array_B + x_array_Y) #takes unique points, otherwise maybe bias
x_array = sorted(x_array)#[num for num in x_array if max(spectrum)+19 >= num >= min(spectrum)])
original_peak = sorted(original_peak)#[num for num in original_peak if max(spectrum)+19 >= num >= min(spectrum)])
to_zero = 0
pep_spectrum ={}
for num in spectrum:
for value in x_array:
if value-dev <= num <= value+dev:
pep_spectrum[value]=num
if value in original_peak:
to_zero += 1
# if to_zero<len(original_peak)/3:
# final_y_array = [0]*len(spectrum)
# return spectrum, np.array(final_y_array)
final_y_array = []
for y_loc, point in enumerate(spectrum):
if point in pep_spectrum.values():
final_y_array.append(intensity[y_loc])
else:
final_y_array.append(1e-15)
return spectrum, np.array(final_y_array)
def make_final_plots(xpoints, ypoints, y_pep, b_pep, PC_list):
d = ypoints
a, c = make_overlap_spectrum(y_pep, b_pep, xpoints, d, 0, 0)
#fig1 = plt.figure()
#ax1 = fig1.add_subplot(111)
# fig1, ax1 = plt.subplots()
#ax2 = ax1.twinx()
plt.stem(xpoints, d, 'b', label='True signal', markerfmt=' ')
plt.stem(a, -c, 'g', label='in-silico', markerfmt=' ')
plt.title('Cleaned spectrum VS theoretical spectrum')
plt.ylabel('Intensity')
plt.xlabel('m/z')
#fig1.tight_layout()
plt.show()
ylist = []
xlist = []
for a, AA in enumerate(PC_list):
ylist.append(AA[1])
xlist.append(a)
plt.plot(xlist, ylist)
plt.show()
def tic_normalize(intensity):
intensity = np.array(intensity)
return intensity / np.sum(intensity)
def find_intensity(item, spectrum, intensity, ms2pip, ptm): #if 0 use ms2pip intensity?
AA_code = extra_AA
true_intensity_B = []
true_intensity_Y = []
loc_ptm = []
which = []
bextra = 0
do = False
for el in ptm.split('|'):
try:
if int(el)==0:
do = True
else:
loc_ptm.append(int(el))
except ValueError:
if do == True:
do = False
for ex, name in N_terms.items():
if name == el:
bextra = ex
else:
which.append(el)
pass
item = item.replace('I', 'L')
item = list(item)
for i, number in enumerate(loc_ptm):
for k,v in PTM.items():
if v==item[number-1] and which[i] == ''.join(c for c in k if c.isdigit()==False):
item[number-1]= k
break
y_peptide = item[::-1][:-1]
b_peptide = item[:-1]
x_array_Y = []
x_point_Y = ion_types['Y']
for AA in y_peptide:
x_array_Y.append(AA_code[AA]+x_point_Y)
x_point_Y += AA_code[AA]
x_array_B = []
x_point_B = ion_types['B'] +bextra
for AA in b_peptide:
x_array_B.append(AA_code[AA]+x_point_B)
x_point_B += AA_code[AA]
pep_spectrum = {}
for loc, value in enumerate(x_array_Y):
done = False
for num in spectrum:
if value-dev <= num <= value+dev:
pep_spectrum[value]=num
done = True
if done == False:
if loc<= 2 or loc>= len(y_peptide)-1:#value < min(spectrum):
pep_spectrum[value] = 'NP'+str(loc)
else:
pep_spectrum[value] = 0
final_y_array = []
for point in sorted(pep_spectrum.keys()):
if pep_spectrum[point] ==0:
final_y_array.append(1e-15)
true_intensity_Y.append(True)
elif 'NP' in str(pep_spectrum[point]):
true_intensity_Y.append(False)
#final_y_array.append(ms2pip[int(pep_spectrum[point][2:])+len(y_peptide)])
else:
itemindex = np.where(spectrum == pep_spectrum[point])[0][0]
final_y_array.append(intensity[itemindex])
true_intensity_Y.append(True)
pep_spectrum = {}
for loc, value in enumerate(x_array_B):
done = False
for num in spectrum:
if value-dev <= num <= value+dev:
pep_spectrum[value]=num
done = True
if done == False:
if loc <= 2 or loc>= len(b_peptide)-1:#value < min(spectrum):
pep_spectrum[value] = 'NP'+str(loc)
else:
pep_spectrum[value] = 0
final_b_array = []
for point in sorted(pep_spectrum.keys()):
if pep_spectrum[point] ==0:
final_b_array.append(1e-15)
true_intensity_B.append(True)
elif 'NP' in str(pep_spectrum[point]):
true_intensity_B.append(False)
#final_b_array.append(ms2pip[int(pep_spectrum[point][2:])])
else:
itemindex = np.where(spectrum == pep_spectrum[point])[0][0]
final_b_array.append(intensity[itemindex])
true_intensity_B.append(True)
final_int = true_intensity_B + true_intensity_Y
ms2pip = np.array(ms2pip)
ms2pip = ms2pip[final_int]
return np.array(final_b_array + final_y_array), ms2pip #tic_normalize(np.array(final_b_array + final_y_array))
def catch_asterix(temp):
new = []
for i in temp:
if '*' in i and len(i)>0:
element = i.split('*')
if element[1][0]=='|':
new.append((element[1][1:], float(element[0])))
else:
new.append((element[1], float(element[0])))
else:
new.append((i,0))
return new
def make_list_pep(MZ, ion, AAs):
temp =set()
pep = list(AAs.keys())
if ion=='B':
new_pep = {}
for i,u in AAs.items():
new_pep[i]=u
for item in N_terms.keys():
new_pep[str(item)+'*']=item
elif ion=='Y':
new_pep = {}
for i,u in AAs.items():
new_pep[i]=u
for item in C_terms.keys():
new_pep[str(item)+'*']=item
print('making the in-silico peptides')
while len(new_pep)!=0:
new_pep, temp = insilico_peptide(pep, new_pep, temp, MZ)
temp = catch_asterix(temp)
return temp
def find_pep_ions_part1(xpoints_data, ypoints_data, MZ, ion, temp):
# MZ_range = xpoints_data#spectrum['m/z array']
# ind = np.argsort(MZ_range)
# MZ_range = MZ_range[ind]
print('Start Pearson Corr')
print(len(temp))
xpoints = xpoints_data[xpoints_data<=(MZ+19)]
ypoints = ypoints_data[0:len(xpoints)]
PC_list =[]
for peptide, extra in temp:
a, c = insilico_spectrum(peptide, xpoints, ypoints, ion, extra)
pc = jaccard(c,ypoints,peptide.split('|'))
# found_intensity = np.sum(c)
# all_intensity = np.sum(ypoints_data)
# pc = pc#*found_intensity/all_intensity
#pc = pearson_correlation(ypoints, c, i=i)[0][1]
add = tuple([peptide, extra, pc])
PC_list.append(add)
PC_list = sorted(PC_list, key=lambda x: x[-1])[::-1]
#make_plots(xpoints, ypoints, PC_list[0][0], PC_list, ion)
return PC_list
def find_pep_ions_iterations(PC_list, MZ, ion):
temp = set()
pep = list(AA_code.keys())
new_pep = select_top_scores(PC_list, find_treshold(PC_list,MZ))
while len(new_pep)!=0:
new_pep, temp = insilico_peptide(pep, new_pep, temp, MZ)
print('Start Pearson Corr')
temp = catch_asterix(temp)
print(len(temp))
if len(temp)>=35e4:
return []
ind = xpoints_data<=(MZ+19)
xpoints = xpoints_data[ind]
ypoints = ypoints_data[ind]
PC_list =[]
for peptide, extra in temp:
a, c = insilico_spectrum(peptide, xpoints, ypoints, ion, extra)
pc = jaccard(c,ypoints, peptide.split('|'))
# found_intensity = np.sum(c)
# all_intensity = np.sum(ypoints_data)
# pc = pc#*found_intensity/all_intensity
#pc = pearson_correlation(ypoints, c, i=i)[0][1]
add = tuple([peptide,extra, pc])
PC_list.append(add)
PC_list = sorted(PC_list, key=lambda x: x[1])[::-1]
#make_plots(xpoints, ypoints, PC_list[0][0], PC_list, ion)
return PC_list
def find_overlap_sequence(Y_list, B_list):
print('start making overlap')
overlap_output = []
for y_ion in Y_list:
for b_ion in B_list:
overlap = find_overlap(y_ion[0], b_ion[0], y_ion[1], b_ion[1])
if len(overlap)>0:
overlap_output.append(overlap)
overlap_output_final = []
for element in overlap_output:
if element not in overlap_output_final:
overlap_output_final.append(element)
# overlap_output = sorted(overlap_output, key=lambda x: x[2])[::-1]
print('found ', len(overlap_output)-len(overlap_output_final), ' double sequences')
print('amount of possible sequences: ',len(overlap_output_final))
plt.bar(['Y-ion fragments', 'B-ion fragments', 'Resulting peptides'],[len(Y_list), len(B_list),len(overlap_output_final)])
plt.title('Amount of overlapping ion fragment to peptide')
plt.show()
return overlap_output_final
def score_overlap(overlap_output, x, y):
print('final pearson correlation')
PC_list =[]
for item in overlap_output:
a, c = make_overlap_spectrum(item[2][0][::-1], item[2][0], x, y, item[2][1], item[2][2])
j = jaccard(y, c, item[2][0])
pc = pearson_correlation(y, c)[0][1]
found_intensity = np.sum(c)
all_intensity = np.sum(y)
add = tuple([item, j, found_intensity/all_intensity, pc]) #j*found_intensity/all_intensity
PC_list.append(add)
# if 'GAYVEVTAk' in item[0]:
# print(make_overlap_spectrum(item[2][::-1], item[2], xpoints_data, ypoints_data))
# print(jaccard(ypoints_data, c, item[0]))
# print(pearson_correlation(ypoints_data, c)[0][1])
# print(np.sum(c))
PC_list = sorted(PC_list, key=lambda x: x[3])[::-1]
if len(PC_list)==0:
return []
begin = len(PC_list)
PC_list = find_treshold_overlap(PC_list)
plt.bar(['Before', 'After'],[begin, len(PC_list)])
plt.title('remaining peptides after peptide to spectrum match scoring')
plt.show()
print('kept ', len(PC_list), 'of ', begin)
combined_peptide_list = set()
for item, j_score, cov, pc in PC_list:
combined_peptide_list = combined_peptide_list| {(item[0], item[1], j_score, cov, pc)}
return combined_peptide_list
def score_pip(combined_peptide_list, xpoints_data, ypoints_data):
pip_score = []
for item, ptm, pc_score, cov in combined_peptide_list:
ms2pip_sp = SinglePrediction()
mz, intensity, annotation = ms2pip_sp.predict(item, '-', spectrum['params']['charge'][0])
y = item[::-1]
b = item
to_test = find_intensity(y[:-1], b[:-1], xpoints_data, ypoints_data, intensity)
if len(to_test)==len(intensity): #If to_test shorter than intensity, this means that the total found peptide cannot be explained by the spectrum as it is larger than measured.
pc = pearson_correlation(to_test, intensity, 'Overlap')[0][1]
pip_score.append([item, ptm, pc, pc_score, cov])
pip_score = sorted(pip_score, key=lambda x: x[2])[::-1]
#plot_pip_score(pip_score)
return pip_score
def plot_pip_score(pip_score):
ylist = []
xlist = []
for a, AA in enumerate(pip_score):
ylist.append(AA[1])
xlist.append(a)
plt.plot(xlist, ylist)
plt.show()
return
def deeplc(title, contamination_file):
print('Start DeepLC')
calibration_file = "./"+contamination_file
peptide_file = "./records_"+title+".csv"
pep_df = pd.read_csv(peptide_file, sep=",")
cal_df = pd.read_csv(calibration_file, sep=",")
cal_df['modifications'] = cal_df['modifications'].fillna("")
pep_df['modifications'] = pep_df['modifications'].fillna("")
dlc = DeepLC(verbose=True)
dlc.calibrate_preds(seq_df=cal_df)
preds = dlc.make_preds(seq_df=pep_df)
print('End of deeplc')
return preds
def crap_f():
print('making database')
crap = {}
files_own = []
crap_concat = {}
for fastafile in os.walk('C:/Users/Gebruiker/Desktop/neolitic_protein_discovery/palaeo_db'):#fasta_db
for i in fastafile[-1]:
if i.endswith('.txt') or i.endswith('.fasta'):
files_own.append('C:/Users/Gebruiker/Desktop/neolitic_protein_discovery/palaeo_db/'+i) #fasta_db
for i in files_own:
concat = ''
print(i.split('/')[-1])
if 'other' not in i:
continue
for record in SeqIO.parse(i, "fasta"):
if 'X' in record.seq or 'B' in record.seq or 'U' in record.seq or 'J' in record.seq or 'O' in record.seq or 'Z' in record.seq:
continue
crap[record.seq]=record.description
concat+=str(record.seq)+'X'
crap_concat[concat]=i.split('/')[-1]
concat=''
for record in SeqIO.parse("C:/Users/Gebruiker/Desktop/neolitic_protein_discovery/crap.fasta.txt", "fasta"):
crap[record.seq]=record.id
concat+=str(record.seq)+'X'
for record in SeqIO.parse('C:/Users/Gebruiker/Desktop/neolitic_protein_discovery/contaminants.fasta', "fasta"):
crap[record.seq]=record.id
concat+=str(record.seq)+'X'
lysyl = 'MHKRTYLNACLVLALAAGASQALAAPGASEMAGDVAVLQASPASTGHARFANPNAAISAAGIHFAAPPARRVARAAPLAPKPGTPLQVGVGLKTATPEIDLTTLEWIDTPDGRHTARFPISAAGAASLRAAIRLETHSGSLPDDVLLHFAGAGKEIFEASGKDLSVNRPYWSPVIEGDTLTVELVLPANLQPGDLRLSVPQVSYFADSLYKAGYRDGFGASGSCEVDAVCATQSGTRAYDNATAAVAKMVFTSSADGGSYICTGTLLNNGNSPKRQLFWSAAHCIEDQATAATLQTIWFYNTTQCYGDASTINQSVTVLTGGANILHRDAKRDTLLLELKRTPPAGVFYQGWSATPIANGSLGHDIHHPRGDAKKYSQGNVSAVGVTYDGHTALTRVDWPSAVVEGGSSGSGLLTVAGDGSYQLRGGLYGGPSYCGAPTSQRNDYFSDFSGVYSQISRYFAP'
crap[lysyl]='lysyl'
concat+=lysyl+'X'
keratin1 = 'MSRQFSSRSGYRSGGGFSSGSAGIINYQRRTTSSSTRRSGGGGGRFSSCGGGGGSFGAGGGFGSRSLVNLGGSKSISISVARGGGRGSGFGGGYGGGGFGGGGFGGGGFGGGGIGGGGFGGFGSGGGGFGGGGFGGGGYGGGYGPVCPPGGIQEVTINQSLLQPLNVEIDPEIQKVKSREREQIKSLNNQFASFIDKVRFLEQQNQVLQTKWELLQQVDTSTRTHNLEPYFESFINNLRRRVDQLKSDQSRLDSELKNMQDMVEDYRNKYEDEINKRTNAENEFVTIKKDVDGAYMTKVDLQAKLDNLQQEIDFLTALYQAELSQMQTQISETNVILSMDNNRSLDLDSIIAEVKAQYEDIAQKSKAEAESLYQSKYEELQITAGRHGDSVRNSKIEISELNRVIQRLRSEIDNVKKQISNLQQSISDAEQRGENALKDAKNKLNDLEDALQQAKEDLARLLRDYQELMNTKLALDLEIATYRTLLEGEESRMSGECAPNVSVSVSTSHTTISGGGSRGGGGGGYGSGGSSYGSGGGSYGSGGGGGGGRGSYGSGGSSYGSGGGSYGSEGGGGGHGSYGSGSSSGGYRGGSGGGGGGSSGGRGSGGGSSGGSIGGRGSSSGGVKSSGGSSSVKFVSTTYSGVTR'
crap[keratin1] = 'keratin1'
concat+=keratin1+'X'
keratin1_2 = 'MSRQFSSRSGYRSGGGFSSGSAGIINYQRRTTSSSTRRSGGGGGRFSSCGGGGGSFGAGGGFGSRSLVNLGGSKSISISVARGGGRGSGFGGGYGGGGFGGGGFGGGGFGGGGIGGGGFGGFGSSGGGGFGGGGFGGGGYGGGYGPVCPPGGIQEVTINQSLLQPLNVEIDPEIQKVKSREREQIKSLNNQFASFIDKVRFLEQQNQVLQTKWELLQQVDTSTRTHNLEPYFESFINNLRRRVDQLKSDQSRLDSELKNMQDMVEDYRNKYEDEINKRTNAENEFVTIKKDVDGAYMTKVDLQAKLDNLQQEIDFLTALYQAELSQMQTQISETNVILSMDNNRSLDLDSIIAEVKAQYEDIAQKSKAEAESLYQSKYEELQITAGRHGDSVRNSKIEISELNRVIQRLRSEIDNVKKQISNLQQSISDAEQRGENALKDAKNKLNDLEDALQQAKEDLARLLRDYQELMNTKLALDLEIATYRTLLEGEESRMSGECAPNVSVSVSTSHTTISGGGSRGGGGGGYGSGGSSYGSGGGSYGSGGGGGGGRGSYGSGGSSYGSGGGSYGSGGGGGGHGSYGSGSSSGGYRGGSGGGGGGSSGGRGSGGGSSGGSIGGRGSSSGGVKSSGGSSSVKFVSTTYSGVTR'
crap[keratin1_2] = 'keratin1_2'
concat+=keratin1_2+'X'
crap_concat[concat]='contamination'
concat=''
for i in ['AETSELHTSLk', 'GAYVEVTAk', 'LGNEQGVSr', 'LVGTPAEEr', 'LDSTSLPVAk', 'AGLLVAEGVTk',
'LGLDFDSFr', 'GFTAYYLPr', 'SGGLLWQLVr', 'AVGANPEQLTr', 'SAEGLDASASLr',
'VFTPELVDVAk','VGNELQYVALr', 'YLELAPGVDNSk', 'DGTFAVDGPGVLAk', 'YDSLNNTEVSGLr',
'SPYVLTGPGVVEYk', 'ALENDLGVPSDATVk', 'AVYFYAPQLPLYANk', 'TVESLFPEEAETPGSAVr', 'STQAALDQLNGK', 'ALLVASGHLK']:
concat += i.upper()+'X'
crap_concat[concat]='pepcal'
return crap_concat, crap
def personal_input(path):
files_own = []
for fastafile in os.walk(path+'/palaeo_db'):
for i in fastafile[-1]:
if i.endswith('.txt') or i.endswith('.fasta'):
files_own.append(path+'/palaeo_db/'+i)
db = {}
for i in files_own:
for record in SeqIO.parse(i, "fasta"):
db[record.seq]=record.description
return db
def filters(title, df):
already = []
spectrum_calibration = {}
print('save in csv file')
with open('records_Calibration.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile, delimiter=',', lineterminator='\n')
writer.writerow(['seq', 'modifications', 'tr'])
ms2pip_sp = SinglePrediction()
df = df.sort_values(by=['rt_time'], ascending=True, ignore_index=True)
for record, ptm, rt, x, y, cs, nr, fn, cov, pc_sc in df[['peptide', 'PTM', 'rt_time', 'xpoints_data', 'ypoints_data', 'charge_state', 'spectrum_nr', 'file_name', 'coverage', 'pc_score']].values:
for sequence in crap.keys():
if record.upper() in sequence and nr != 152:#◘hier wegdoen
mz, intensity, annotation = ms2pip_sp.predict(record.upper(), '-', cs)
intensity = [num if num >0 else 1e-15 for num in intensity]
to_test, new_intensity = find_intensity(record, x, y, intensity, ptm)
if len(to_test)==len(new_intensity):
pc = pearson_correlation(to_test, new_intensity)[0][1]
if (pc < 0.45 and (pc_sc<0.98 or len(record)<6 or pc <0)) or (len(record)<6 and pc_sc != 1):
print(crap[sequence], ' is not a good fit', pc)
break
print(crap[sequence])
if record.upper() not in already:
writer.writerow([record, ptm, rt])
already.append(record)
if nr not in spectrum_calibration.keys():
spectrum_calibration[nr]=[(record, ptm, crap[sequence], pc, fn, cov, nr)]
else:
spectrum_calibration[nr] = spectrum_calibration[nr]+[(record, ptm, crap[sequence], pc, fn, cov, nr)]
elif pc >=0.45:
if nr not in spectrum_calibration.keys():
spectrum_calibration[nr]=[(record, ptm, crap[sequence], pc, fn, cov, nr)]
else:
spectrum_calibration[nr] = spectrum_calibration[nr]+[(record, ptm, crap[sequence], pc, fn, cov, nr)]
break
if len(spectrum_calibration)>50:
print('df length before:',len(df))
df = df.loc[~df['spectrum_nr'].isin(list(spectrum_calibration.keys()))]
to_csv = [[seq.upper(), ptm] for seq, ptm in df[['peptide', 'PTM']].values]
peptides_to_test = write_csv(title, to_csv)
print('kept', len(df), 'comming from spectra ', set(df['spectrum_nr'].values))
preds=deeplc(title, 'records_Calibration.csv')
df['deeplc_preds']=np.array(preds)
difference = []
for real, predicted in df[['rt_time', 'deeplc_preds']].values:
difference.append(abs(real-predicted))
df['difference']=np.array(difference)
print('end of difference')
X = np.array([[i, u] for i, u in df[['deeplc_preds', 'rt_time']].values])
mini = min(df['rt_time'].values)*0.05
Y2 = np.array([1 if i<=mini else 0 for i in df[['difference']].values])
plt.title('plot of all predictions after DeepLC')
plt.scatter([num[0] for i, num in enumerate(X)], [num[1] for i, num in enumerate(X)], c='b', alpha=0.01)
plt.scatter([num[0] for i, num in enumerate(X) if Y2[i]==1], [num[1] for i, num in enumerate(X) if Y2[i]==1], c='g', alpha=0.1)
plt.show()
df['error_interval'] = np.array([mini]*len(df))
df = df[abs(df['difference'])<=mini]
df = df.set_index('peptide', drop=False)
else:
print('not enough for deeplc')
df = df.set_index('peptide', drop=False)
df['difference']=np.array([0]*len(df))
print('save results for ms2pip')
nr = 0
with open('peprec.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile, delimiter=',', lineterminator='\n')
writer.writerow(['spec_id','modifications','peptide','charge'])
for seq, ch, ptm in df[['peptide', 'charge_state', 'PTM']].values:
if ptm == '':
ptm = '-'
ch = int(''.join(c for c in str(ch) if c.isdigit()==True))
writer.writerow([nr, '-', seq, ch])
nr += 1
print('start ms2pip')
params = {
"ms2pip": {
"ptm": [
"Oxidation,15.994915,opt,M",
# "Phospho,79.966331,opt,S",
# "Oxidation,15.994915,opt,P",
# "Carbamyl,43.005814,opt,T",
# "Carbamyl,43.005814,opt,R",
# "kynurenin,3.994915,opt,W",
# "dihydroxy,31.989829,opt,W",
# "Gln->pyro-Glu,-18.010565,opt,Q",
# "Phospho,79.966331,opt,Y",
# "Phospho,79.966331,opt,T",
# "dihydroxy,31.989829,opt,M",
# "Carbonyl,13.979265,opt,K",
# "Carbonyl,13.979265,opt,R",
# "Deamidation,0.984016,opt,N",
# "Deamidation,0.984016,opt,Q"
],
"frag_method": "HCD",
"frag_error": 0.02,
"out": "csv",
"sptm": [], "gptm": [],
}}
ms2pip = MS2PIP("peprec.csv",params = params, return_results=True)
predictions = ms2pip.run()
actual = []
for pred in predictions['prediction']:
actual.append((2**pred)-0.001)
predictions['prediction']=np.array(actual)
print('Start MS2PIP pearson')
print(len(df))
pip_score = []
# ms2pip_sp = SinglePrediction()
nr = 0
for item, ptm, x, y, cs in df[['peptide', 'PTM', 'xpoints_data', 'ypoints_data', 'charge_state']].values:
print(nr+1, ' of the', len(df))
intensity = [num for num in predictions['prediction'][predictions['spec_id']==str(nr)].values]#mz, intensity, annotation = ms2pip_sp.predict(item.upper(), '-', cs)
intensity = [num if num >0 else 1e-15 for num in intensity]
to_test, new_intensity = find_intensity(item, x, y, intensity, ptm)
if len(to_test)==len(new_intensity): #If to_test shorter than intensity, this means that the total found peptide cannot be explained by the spectrum as it is larger than measured.
pc = pearson_correlation(to_test, new_intensity)[0][1]
pip_score.append(pc)
else:
pip_score.append(0)
nr += 1
df['ms2pip_score'] = np.array(pip_score)
plt.plot(sorted(pip_score)[::-1])
plt.title('Peptide to MS2PIP scoring')
plt.xlabel('Peptide number')
plt.ylabel('MS2PIP vs peptide score')
plt.show()
return df, spectrum_calibration
def write_csv(title, combined_peptide_list):
print('save in csv file')
with open('records_'+title+'.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile, delimiter=',', lineterminator='\n')
writer.writerow(['seq', 'modifications'])
for record, ptm in combined_peptide_list:
writer.writerow([record, ptm])
return 0
def set_data(xpoints_data, ypoints_data, pp_mass, charge, spectrum, tag=False):
ind = np.argsort(xpoints_data)
xpoints_data = xpoints_data[ind]
ypoints_data = ypoints_data[ind]
charge = charge[ind]
ypoints_data = tic_normalize(ypoints_data)
if 'charge' in spectrum['params'].keys():
if spectrum['params']['charge'][0] > 2:
print(pp_mass)
pp_mass = pp_mass-((spectrum['params']['charge'][0]-2)**2)/spectrum['params']['charge'][0]#((pp_mass*3)/2)-0.5
print('checking a non-double charged!!', pp_mass)
ind = []
for del_y, i in enumerate(xpoints_data):
if spectrum['params']['pepmass'][0]-0.02 <i< spectrum['params']['pepmass'][0]+0.02:#precursor mass
ind.append(False)
elif spectrum['params']['pepmass'][0]-(18.010565/spectrum['params']['charge'][0])-0.02 <i< spectrum['params']['pepmass'][0]-(18.010565/spectrum['params']['charge'][0])+0.02: #precursor mass - H2O
ind.append(False)
elif spectrum['params']['pepmass'][0]-(17.026549/spectrum['params']['charge'][0])-0.02 <i< spectrum['params']['pepmass'][0]-(17.026549/spectrum['params']['charge'][0])+0.02: #precursor mass - NH4
ind.append(False)
else:
ind.append(True)
xpoints_data = xpoints_data[ind]
ypoints_data = ypoints_data[ind]
charge = charge[ind]
ypoints_data = tic_normalize(ypoints_data)
if len(ypoints_data)>0:
ind = ypoints_data >1e-5
xpoints_data = xpoints_data[ind]
ypoints_data = ypoints_data[ind]
charge = charge[ind]
if tag==True:
dev = 20*(spectrum['params']['charge'][0]*pp_mass)/1e6 #20ppm
if dev <= 0.01:
dev = 0.01
# if dev >0.05:#
# dev = 0.05
else:
dev = 15*(spectrum['params']['charge'][0]*pp_mass)/1e6 #15ppm
if dev <= 0.01:
dev = 0.01
if dev >0.0185:#
dev = 0.0185
if len(xpoints_data)> 1 and tag==False:
plt.stem(xpoints_data, ypoints_data, 'b', markerfmt=' ')
plt.title(title+ ' before mirror')
plt.show()
if len(xpoints_data)<=(spectrum['params']['charge'][0]*pp_mass)/15+25 and tag==False:
print('only ghost performed')
neutral_lossX, neutral_lossY, mdev = mirror_B(xpoints_data, ypoints_data, pp_mass, 1)
elif tag==False:
print('mirroring')
neutral_lossX, neutral_lossY, mdev = mirror_B(xpoints_data, ypoints_data, pp_mass)
print(len(neutral_lossX))
if (spectrum['params']['charge'][0]*pp_mass)/20+30 >= len(xpoints_data):
print('only ghost performed 2')
xpoints_data, ypoints_data, mdev = mirror_A(xpoints_data, ypoints_data, pp_mass,spectrum, 1, tag=tag)
else:
print('mirroring')
xpoints_data, ypoints_data, mdev = mirror_A(xpoints_data, ypoints_data, pp_mass, spectrum, tag=tag)
print(len(xpoints_data))
if tag==False and len(neutral_lossY)>0:
neutral_lossY = tic_normalize(neutral_lossY)
ind = neutral_lossY >1e-4
neutral_lossX = neutral_lossX[ind]
neutral_lossY = neutral_lossY[ind]
ypoints_data = tic_normalize(ypoints_data)
if len(ypoints_data)>0:
ind = ypoints_data>1e-4
xpoints_data = xpoints_data[ind]
ypoints_data = ypoints_data[ind]
if len(xpoints_data)>1 and tag==False:
plt.stem(xpoints_data, ypoints_data, 'b', markerfmt=' ')
plt.title(title+ ' after')
plt.show()
if len(set([int(xs) for xs in xpoints_data]))<=pp_mass*spectrum['params']['charge'][0]/100:
xpoints_data = []
ypoints_data = []
if tag==True:
return xpoints_data, ypoints_data, pp_mass, dev
spectrum_new = spectrum.copy()
spectrum_new['intensity array'] = neutral_lossY
spectrum_new['m/z array'] = neutral_lossX
spectrum_new['charge array'] = np.ma.MaskedArray([1]*len(neutral_lossX))
to_mgf = spectrum_new
return xpoints_data, ypoints_data, pp_mass, dev, to_mgf, neutral_lossX, neutral_lossY
def pip_data(xpoints_data, ypoints_data, charge, pp_mass):
ind = np.argsort(xpoints_data)
xpoints_data = xpoints_data[ind]
ypoints_data = ypoints_data[ind]
charge = charge[ind]
xpoints_data = np.array([num for num in xpoints_data if num <= (((pp_mass)*2))-20])
ind = np.argsort(xpoints_data)
ypoints_data = ypoints_data[ind]
charge = charge[ind]
for del_y, i in enumerate(xpoints_data):
if charge[del_y] >1 and (round(i,2) in [round(num,2) for num in xpoints_data[charge==1]]):
ypoints_data[del_y] = min(ypoints_data)
if pp_mass-0.1 <i< pp_mass+0.1:#precursor mass
ypoints_data[del_y] = min(ypoints_data)
elif pp_mass-(18.010565/2)-0.01 <i< pp_mass-(18.010565/2)+0.01: #precursor mass - H2O
ypoints_data[del_y] = min(ypoints_data)
elif pp_mass-(17.026549/2)-0.01 <i< pp_mass-(17.026549/2)+0.01: #precursor mass - NH4
ypoints_data[del_y] = min(ypoints_data)
ypoints_data = tic_normalize(ypoints_data)
return xpoints_data, ypoints_data
def w_mgf(files):
mgf.write(files, output='./MGF_mirror_test')
def rank_results(pip_results):
print('start ranking')
rank_score = [0 if d < 0.45 else a*b*c*d*(err-abs(e)) for a, b, c, d, e, err in pip_results[['jaccard_score', 'coverage', 'pc_score', 'ms2pip_score', 'difference', 'error_interval']].values]
rank_score = [0 if (score<0) else score for score in rank_score] #score>1 or
pip_results['rank_score'] = np.array(rank_score)
drop_peps = []
column_values = ['peptide', 'PTM', 'spectrum_nr', 'charge_state', 'jaccard_score', 'coverage', 'pc_score', 'ms2pip_score', 'rank_score', 'file_name']
final_df = pd.DataFrame(columns = column_values)
for spectra in set(pip_results['spectrum_nr'].values):
ranking = pip_results['rank_score'][pip_results['spectrum_nr']==spectra].values
ranking = sorted(ranking)[::-1][:5]
ranking = ranking[-1]
peps = pip_results['peptide'][(pip_results['spectrum_nr']==spectra) & (((pip_results['rank_score'] >= ranking)|(pip_results['peptide'][-1]=='K')|(pip_results['peptide'][-1]=='R'))&(pip_results['rank_score'] != 0))].values
for pep in peps:
array = np.array([[pep, ptm, spc, chs, js, cov, pc,pip, rs, fn] for pep, ptm, spc, chs, js, cov, pc,pip, rs, fn in pip_results[['peptide', 'PTM', 'spectrum_nr', 'charge_state', 'jaccard_score', 'coverage', 'pc_score','ms2pip_score', 'rank_score', 'file_name']][(pip_results['spectrum_nr']==spectra) & (pip_results['peptide']==pep)].values])
df_add = pd.DataFrame(data = array, columns = column_values)
final_df = pd.concat([final_df, df_add], ignore_index = True)
# drop_peps.append(pep)
# pip_results = pip_results.loc[~((pip_results['peptide'] == pep) & (pip_results['spectrum_nr'] ==spectra))]
in_db = []
for seq in final_df['peptide']:
to_add = []
for sequence in personal_db.keys():
if seq in sequence:
to_add.append(personal_db[sequence])
for sequence in crap_individual.keys():
if seq in sequence:
to_add.append(crap[sequence])
if len(to_add)>0:
annot = '|'.join(to_add[0:10])
in_db.append('Found '+str(len(to_add))+(' hit(s):')+annot)
else:
in_db.append('unkown')
final_df['ID'] = np.array(in_db)
final_df= final_df.set_index('peptide')
#pip_results = pip_results.drop(drop_peps)
return final_df
def find_consensus(ranked_results): #dit nog aanpassen zodat chimeren 2 uitkomen en niet XXXXXXX
print('making consensus')
fin_pep = [[num[0][0]]*num[1] for num in ranked_results[0:20]]
fin_pep_all = []