-
Notifications
You must be signed in to change notification settings - Fork 0
/
gLabel_GP.py
1544 lines (1344 loc) · 71.6 KB
/
gLabel_GP.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
#coding=utf-8
'''
Created on 2013.12.13
@author: dell
'''
import numpy as np
import matplotlib
# matplotlib.use('Qt5Agg')
# matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import SpecReader
import AAMass
import os
import wx
import copy
import datetime, time, sys
import traceback
import yaml
from alpharaw.match.match_utils import match_closest_peaks
from chemical import replace_element_and_calc_mass
from math import log10
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
def load_yaml(yaml):
with open(yaml) as f:
return yaml.load(f, Loader=yaml.FullLoader)
aamass = AAMass.AAMass()
def GetRawScanFromSpec(spec):
items = spec.split(".")
if len(items) < 6: return ".".join(items[:-1]), items[-1]
else: return ".".join(items[:-5]), items[-4]
class Marker:
def __init__(self, glyco = "H", shape = "o", color = "green", marker = "", alt = "white", fill = "full", label = []):
self.glyco = glyco
self.shape = shape
self.color = color
self.alt = alt
self.fill = fill
if not marker: self.oxonium_ions = []
else:
self.oxonium_ions = []
for i in marker.strip().split(";"):
if i[0].isdigit(): self.oxonium_ions.append(eval(i))
else:
self.oxonium_ions.append(replace_element_and_calc_mass(i, label)[1]+aamass.mass_proton)
fillstyles = ["right","top","left","bottom"]
def fill_rotation(fill, rotation = 90):
rotation = int(rotation/90)
if fill == "full" or fill == "none": return fill
elif fill == "right": return fillstyles[rotation%4]
elif fill == "top": return fillstyles[(1+rotation)%4]
elif fill == "left": return fillstyles[(2+rotation)%4]
elif fill == "bottom": return fillstyles[(3+rotation)%4]
else: return fill
class CGlobalConfig:
def __init__(self):
self.glycandb = "./pGlyco.gdb"
self.glycan_type = 'N'
self.activation_type = "HCD"
self.ResultHasFragments = 1
self.plotDecoyPeptide = 1
self.plotDecoyGlycan = 0
self.plotMaxGlycanFDR = 1
self.plotMaxPeptideFDR = 1
self.plotMaxTotalFDR = 1
self.plotMinGlycanScore = 0
self.plotMinPeptideScore = 0
self.plotMinTotalScore = 0
self.isPlot = 1
self.isBatchPlot = 0
self.glyco_as_text = 0
self.max_oxonium_mz = 400
self.glycoini = ""
self.modini = ""
self.aaini = ""
self.dpi = 120
self.label = []
self.SetDefault()
self.settings = {}
self.ReadConfig()
def SetDefault(self):
self.used_markers = []
self.used_markers.append(Marker('H', 'o', 'green', '145.0495347452;163.0600994315;366.1394719645'))
self.used_markers.append(Marker('N', 's', 'blue', '138.0552587690;168.0655191604;186.0760838467;204.0866485330'))
self.used_markers.append(Marker('A', 'D', 'purple', '274.0921278414;292.1026925277;657.2348884922'))
self.used_markers.append(Marker('G', 'D', 'cyan', '290.08704246349997;308.0976071497999;673.2298031143'))
self.used_markers.append(Marker('F', '^', 'red', '147.0651848094;350.1445573424'))
self.used_glyco = ['H','N', 'A', 'G', 'F']
# self.used_shape = ["o","s","D","D","^"]
# self.used_color = ["g","b","purple","cyan","r"]
# self.used_alt = ["white"]*5
# self.used_fill = ["full"]*5
# self.used_marker = [[145.0495347452, 163.0600994315, 366.1394719645], #Hex
# [138.0552587690, 168.0655191604, 186.0760838467, 204.0866485330], #HexNAc
# [274.0921278414, 292.1026925277, 657.2348884922], #NeuAc
# [290.08704246349997, 308.0976071497999, 673.2298031143], #NeuGc
# [146.0579088094+aamass.mass_proton, 146.0579088094+204.0866485330]] #dHex
self.GetCoreFrags()
def num_format(self, glycocomp):
return "(" + ",".join([str(g) for g in glycocomp]) + ")"
def short_format(self, glycocomp):
if sum(glycocomp) == 0: return ""
ret = ""
for i in range(len(glycocomp)):
if glycocomp[i] > 0: ret += "%s(%d)"%(self.used_glyco[i],glycocomp[i])
return ret
def FormatGlycan(self, glycocomp):
return self.short_format(glycocomp)
def GetCoreFrags(self):
if self.glycan_type == 'N': self.GetNLinkedCoreFrags()
else: self.GetOtherCoreFrags()
def GetOtherCoreFrags(self):
self.core_frags = []
self.core_fuc = []
def ExtendCoreFrags(self, glycan, gly_list):
for g in self.core_frags:
if np.all(np.array(g) <= np.array(glycan)):
gly_list.append(g)
try:
idx_F = self.used_glyco.index('F')
if glycan[idx_F] > 0:
for g in self.core_fuc:
if np.all(np.array(g) <= np.array(glycan)):
gly_list.append(g)
except:
pass
def GetNLinkedCoreFrags(self):
self.core_frags = []
self.core_fuc = []
try:
idx_N = self.used_glyco.index('N')
Y1 = [0]*len(self.used_glyco)
Y1[idx_N] = 1
self.core_frags.append(tuple(Y1))
Y2 = [0]*len(self.used_glyco)
Y2[idx_N] = 2
self.core_frags.append(tuple(Y2))
try:
idx_H = self.used_glyco.index('H')
Y3 = copy.deepcopy(Y2)
Y3[idx_H] = 1
self.core_frags.append(tuple(Y3))
Y4 = copy.deepcopy(Y2)
Y4[idx_H] = 2
self.core_frags.append(tuple(Y4))
Y5 = copy.deepcopy(Y2)
Y5[idx_H] = 3
self.core_frags.append(tuple(Y5))
except:
pass
try:
idx_F = self.used_glyco.index('F')
Y2_fuc = copy.deepcopy(Y1)
Y2_fuc[idx_F] = 1
self.core_fuc.append(tuple(Y2_fuc))
Y3_fuc = copy.deepcopy(Y2)
Y3_fuc[idx_F] = 1
self.core_fuc.append(tuple(Y3_fuc))
except:
pass
except:
pass
def UseGlyco(self, glyco):
old_glyco = copy.deepcopy(config.used_glyco)
self.RearrangeGlyco(glyco)
return old_glyco
def RearrangeGlyco(self, glyco):
new_glyco = glyco
new_markers = []
# new_col = []
# new_marker = []
# new_alt = []
# new_fill = []
for g in glyco:
try:
idx = self.glyco.index(g)
new_markers.append(self.marker_list[idx])
# new_col.append(self.glyco_col[idx])
# new_marker.append(self.oxonium_markers[idx])
except:
print('{} is not a glyco unit in glabel.gconf (units = {})'.format(g, ','.join(self.glyco)))
print('please add {} into glabel.gconf, and then click "Load gLabel config"'.format(g))
self.used_glyco = new_glyco
self.used_markers = new_markers
# self.used_shape = new_shape
# self.used_color = new_col
# self.used_marker = new_marker
self.GetCoreFrags()
def ReadConfig(self, conf_file = "glabel.gconf"):
f = open(conf_file)
lines = f.readlines()
f.close()
self.marker_list = []
self.glyco = []
# self.glyco_shape = []
# self.glyco_col = []
# self.oxonium_markers = []
def glyco_shape_color(line):
items = line.split("=")
g = items[0].strip()
items = items[1].split(",")
items = [item.split(":") for item in items]
kargs = dict([(key.strip(),val.strip()) for key, val in items])
kargs['glyco'] = g
kargs['label'] = self.label
self.marker_list.append(Marker(**kargs))
# items = items[1][items[1].find("shape:")+len("shape:"):items[1].find(",color")].strip()
# color = items[1][items[1].find("color:")+len("color:"):items[1].find(",marker")].strip()
# markers = items[1][items[1].find("marker:")+len("marker:"):].strip()
# markers = [float(marker) for marker in markers.split(',') if marker != ""]
self.glyco.append(g)
# self.glyco_shape.append(shape)
# self.glyco_col.append(color)
# self.oxonium_markers.append(markers)
for line in lines:
if line.startswith("#"): continue
elif line.startswith("label"):
self.label = [item.split("~") for item in line[line.find("=")+1:].strip().split(",")]
elif line.startswith("glycandb"):
self.glycandb = line[line.find("=")+1:].strip()
elif line.startswith("glycan_type"):
self.glycan_type = line[line.find("=")+1:].strip()
elif line.startswith("result_has_fragments"):
self.ResultHasFragments = int(line[line.find("=")+1:].strip())
elif line.startswith("plot_decoy_peptide"):
self.plotDecoyPeptide = int(line[line.find("=")+1:].strip())
elif line.startswith("plot_decoy_glycan"):
self.plotDecoyGlycan = int(line[line.find("=")+1:].strip())
elif line.startswith("plot_max_glycan_FDR"):
self.plotMaxGlycanFDR = float(line[line.find("=")+1:].strip())
elif line.startswith("plot_max_peptide_FDR"):
self.plotMaxPeptideFDR = float(line[line.find("=")+1:].strip())
elif line.startswith("plot_max_total_FDR"):
self.plotMaxTotalFDR = float(line[line.find("=")+1:].strip())
elif line.startswith("plot_min_glycan_score"):
self.plotMinGlycanScore = float(line[line.find("=")+1:].strip())
elif line.startswith("plot_min_peptide_score"):
self.plotMinPeptideScore = float(line[line.find("=")+1:].strip())
elif line.startswith("plot_min_total_score"):
self.plotMinTotalScore = float(line[line.find("=")+1:].strip())
elif line.startswith("is_batch_plot"):
self.isBatchPlot = int(line[line.find("=")+1:].strip())
elif line.startswith("glyco_as_text"):
self.glyco_as_text = int(line[line.find("=")+1:].strip())
elif line.startswith("activation_type"):
self.activation_type = line[line.find("=")+1:].strip()
elif line.startswith("save_dpi"):
self.dpi = int(line[line.find("=")+1:].strip())
elif line.startswith("glycoini"):
self.glycoini = line[line.find("=")+1:].strip()
elif line.startswith("aaini"):
self.aaini = line[line.find("=")+1:].strip()
elif line.startswith("modini"):
self.modini = line[line.find("=")+1:].strip()
# elif line.startswith("AA"):
# items = line[line.find("=")+1:].strip().split(":")
# aamass.aa_mass_dict[items[0].strip()] = float(items[1].strip())
elif "shape:" in line and "color:" in line:
glyco_shape_color(line)
self.RearrangeGlyco(self.used_glyco)
if self.glycoini: aamass.__read_glyco_ini__(self.glycoini)
if self.modini: aamass.__read_mod_ini__(self.modini)
if self.aaini: aamass.__read_aa_ini__(self.aaini)
config = CGlobalConfig()
fontsize = 12
markersize = 8
hfactor = 0.08
vfactor = 0.025
match_lw = 1
unmatch_lw = 0.5
oxonium_tol = 0.03
#end parameters
#
def CalcPepMass(peptide, modlist):
if peptide[0].isdigit(): return float(peptide)
pep_mass = aamass.mass_H2O
modmass = [0]*(len(peptide)+2)
for mod in modlist:
modmass[mod[0]] = aamass.mod_mass_dict[mod[1]]
for char in peptide:
pep_mass += aamass.aa_mass_dict[char]
for mass in modmass:
pep_mass += mass
return pep_mass
def GetModList(modstr):
if modstr == "" or modstr.lower() == "null": return []
modinfo = modstr.strip(';').split(";")
modlist = []
for mod in modinfo:
site, modname = mod.split(",")
site = int(site)
modlist.append((site, modname))
modlist.sort(key = lambda x : x[0])
return modlist
#
def CalcGlycanMass(glycan_comp):
glycanmass = 0
for i in range(len(config.used_glyco)):
glycanmass += glycan_comp[i]*aamass.glyco_mass_dict[config.used_glyco[i]]
return glycanmass
#
class gPSM:
def __init__(self, spec="", peptide="", glycan=None, glycan_list=[]):
self.spec = spec
self.peptide = peptide
self.glycan = glycan
self.charge = 0
self.glycan_list = glycan_list
self.glycan_decoy = False
self.mod = ""
self.modlist = []
self.glysite = -1
self.site_group = ""
self.precursor_mz = 0
self.ETD_scan = ""
def DeleteDuplicated(self):
self.glycan_list = list(set(self.glycan_list))
class gPSMList:
def __init__(self, db_file = config.glycandb):
self.GlycanCol = 'Glycan'
self.psmlist = {}
self.ETDspec_dict = {}
def ReadDenovoRes(self, psm_file):
self.psmlist = {}
f = open(psm_file)
line = f.readline()
items = [item.strip('"') for item in line[:-1].split("\t")]
item_idx = {}
for i in range(len(items)):
item_idx[items[i]] = i
if items[i].startswith('Glycan('):
self.GlycanCol = items[i]
glystr = self.GlycanCol[self.GlycanCol.find('(')+1:self.GlycanCol.find(')')]
config.RearrangeGlyco(glystr.split(','))
for i in range(len(items)):
item_idx[items[i]] = i
while True:
line = f.readline()
if line == "": break
items = line.split("\t")
if items[item_idx["Rank"]] != "1": continue
if config.plotDecoyPeptide == 0 and items[item_idx["GlyDecoy"]] == "1": continue
if config.plotDecoyPeptide == 0 and items[item_idx["PepDecoy"]] == "1": continue
if "GlycanFDR" in item_idx and config.plotMaxGlycanFDR != 1 and float(items[item_idx["GlycanFDR"]]) > config.plotMaxGlycanFDR: continue
if "PeptideFDR" in item_idx and config.plotMaxPeptideFDR != 1 and float(items[item_idx["PeptideFDR"]]) > config.plotMaxPeptideFDR: continue
if "GlyScore" in item_idx and float(items[item_idx["GlyScore"]]) < config.plotMinGlycanScore: continue
if "PepScore" in item_idx and float(items[item_idx["PepScore"]]) < config.plotMinPeptideScore: continue
if "TotalScore" in item_idx and float(items[item_idx["TotalScore"]]) < config.plotMinTotalScore: continue
gpsm = gPSM()
gpsm.spec = items[item_idx["PepSpec"]]
glyspec = items[item_idx["GlySpec"]]
gpsm.peptide = items[item_idx["Peptide"]]
gpsm.glysite = int(items[item_idx["GlySite"]]) - 1
if "Charge" in item_idx: gpsm.charge = int(items[item_idx["Charge"]])
else: gpsm.charge = int(glyspec.split('.')[-3])
gpsm.mod = items[item_idx["Mod"]].strip('"')
gpsm.modlist = GetModList(gpsm.mod)
if "PrecursorMZ" in item_idx: gpsm.precursor_mz = float(items[item_idx["PrecursorMZ"]])
glycos = items[item_idx[self.GlycanCol]].strip().split(" ")
gpsm.glycan = tuple(int(glyco) for glyco in glycos)
glycan_list = items[item_idx["GlyFrag"]].strip(';').split(";")
gpsm.glycan_list = []
for glycan in glycan_list:
if len(glycan) < len(config.used_glyco): continue
glycos = glycan.strip().split(" ")
iglycan = tuple( int(glycos[i]) for i in range(len(glycos)) )
gpsm.glycan_list.append(iglycan)
config.ExtendCoreFrags(gpsm.glycan,gpsm.glycan_list)
gpsm.DeleteDuplicated()
if "LocalizedSiteGroups" in item_idx:
gpsm.site_group = items[item_idx["LocalizedSiteGroups"]]
if 'ETDScan' in item_idx and item_idx["ETDScan"] != '-1':
gpsm.ETD_scan = items[item_idx["ETDScan"]]
self.psmlist[gpsm.spec] = gpsm
if 'Scan' in item_idx and 'RawName' in item_idx:
gpsm = copy.deepcopy(gpsm)
gpsm.spec = '%s.%s'%(items[item_idx['RawName']],items[item_idx['Scan']])
self.psmlist[gpsm.spec] = gpsm
if gpsm.spec != glyspec:
gpsm = copy.deepcopy(gpsm)
gpsm.spec = glyspec
self.psmlist[gpsm.spec] = gpsm
if "ETDScan" in item_idx and item_idx["ETDScan"] != '-1':
gpsm.ETD_scan = items[item_idx["ETDScan"]]
if 'RawName' in item_idx:
gpsm = copy.deepcopy(gpsm)
gpsm.spec = '%s.%s'%(items[item_idx['RawName']],items[item_idx['ETDScan']])
self.psmlist[gpsm.spec] = gpsm
gpsm = copy.deepcopy(gpsm)
gpsm.spec = glyspec.replace('.'+items[item_idx['Scan']]+'.'+items[item_idx['Scan']]+'.', '.'+items[item_idx['ETDScan']]+'.'+items[item_idx['ETDScan']]+'.')
self.psmlist[gpsm.spec] = gpsm
f.close()
#
class Label(object):
'''
classdocs
'''
# def __del__(self):
# if self.output_info:
# self.outmsg.close()
def __init__(self, tol, tol_type="Da"):
'''
Constructor
'''
self.tol = tol
self.tol_type = tol_type
self.reader = None
self.gpsms = gPSMList()
self.output_info = False
self.plot_peptide = True
self.plot_glycan = True
self.specfile = None
self.colory = "orange"
self.colorb = "cadetblue"
self.colorz = "magenta"
self.colorc = "green"
self.show_mass = False
self.use_pGlycoSite = False
self.max_plot_mz = 4100.0
self.save_format = "eps"
def ReadMGF(self, input_file):
self.input_spec = os.path.split(input_file)[1]
if self.specfile is not None: self.specfile.close()
pf2 = input_file[:-3]+'pf2'
if input_file.endswith('.raw'):
self.spec_type = 'raw'
self.specfile = SpecReader.RawFileReader(input_file)
self.specfile.close = self.specfile.Close
self.reader = SpecReader.RawReader(input_file)
elif os.path.isfile(pf2):
self.spec_type = 'pf2'
self.specfile = open(pf2, 'rb')
self.reader = SpecReader.PF2Reader(pf2)
else:
self.spec_type = 'mgf'
self.specfile = open(input_file)
self.reader = SpecReader.MGFReader(input_file)
self.reader.ReadAll()
def SeeOnePlot_new(self, gpsm, xmz=None, yint=None):
print("%s: %s-%s"%(gpsm.spec, gpsm.peptide, config.FormatGlycan(gpsm.glycan)))
if not self.reader.Has_Spec(gpsm.spec):
print("no spectrum named \'%s\' in spectrum files" %gpsm.spec)
return False
ms2 = self.reader.Get_MS2(gpsm.spec)
ms2.mz_ints = self.reader.ReadMS2ByIdx(ms2, self.specfile)
if ms2.charge == 0:
pre_charge = gpsm.charge
else:
pre_charge = ms2.charge
############### init plot ###############
mz_ints = np.array(ms2.mz_ints)
if xmz is None:
xmz = mz_ints[:,0]
yint = mz_ints[:,1]
max_inten_real = np.max(yint)
max_factor = 1.1
basepeak_after_mz = np.max(yint[xmz >= config.max_oxonium_mz])
max_inten = basepeak_after_mz * max_factor
max_plot_mz = min(np.max(xmz),self.max_plot_mz)
yint[yint > max_inten] = max_inten
yint = yint[xmz <= max_plot_mz]
xmz = xmz[xmz <= max_plot_mz]
max_plot_mz += 50 # for plot margin
mz_ints = np.append(xmz.reshape(-1,1), yint.reshape(-1,1), axis=1)
margin_Y = 0.6 # 0.9
margin_by = 0.4 # 0.7
if config.isPlot:
gs = gridspec.GridSpec(3, 1, height_ratios=[2,8,1])
self.fig = plt.figure(figsize=(16,10)) #
ax3 = self.fig.add_subplot(gs[0,0])
ax1 = self.fig.add_subplot(gs[1,0])
ax2 = self.fig.add_subplot(gs[2,0])
ax1.vlines([0,max_plot_mz],[0.2,0],[max_inten*(1+margin_Y*2+margin_by*2),max_inten*(1+margin_Y*2+margin_by*2)],color="w")
ax1.hlines(0,0,max_plot_mz)
#ax1.set_ylim([0,max_inten])
ax1.vlines(xmz, [0]*len(yint), yint, color='dimgrey', linewidth=unmatch_lw)
############### end init plot ###############
############### glycan and peptide mass ###############
pepmass = CalcPepMass(gpsm.peptide, gpsm.modlist)
glycan_mass = CalcGlycanMass(gpsm.glycan)
gp_mass = pepmass + glycan_mass
delta = (ms2.pepmass-aamass.mass_proton)*pre_charge-gp_mass
peplen = len(gpsm.peptide)
print("precursor mass=%.3f, pepmass=%.3f, glymass=%.3f" %((ms2.pepmass-aamass.mass_proton)*pre_charge, pepmass, glycan_mass))
############### end glycan and peptide mass ###############
glyfrag_mass = []
for _gly_frag in gpsm.glycan_list:
glyfrag_mass.append(CalcGlycanMass(_gly_frag))
glyfrag_comp = np.array(gpsm.glycan_list, dtype=np.int32)#
glyfrag_mass = np.array(glyfrag_mass)
self.glycan_0 = np.array([0]*len(config.used_glyco), dtype=np.int32).reshape((1, len(config.used_glyco)))
def add_ions(ion, ion_type, glycan_comp = None):
if glycan_comp is None: glycan_comp = np.repeat(self.glycan_0, len(ion), axis=0)
if self.ions is None:
self.ions = ion
self.ion_types = ion_type
self.glycan_comps = glycan_comp
else:
self.ions = np.append(self.ions, ion)
self.ion_types = np.append(self.ion_types, ion_type)
self.glycan_comps = np.append(self.glycan_comps, glycan_comp, axis = 0)
def add_charged_ions(ion, ion_type, charge, glycan_comp = None):
if glycan_comp is None: glycan_comp = np.repeat(self.glycan_0, len(ion), axis=0)
if self.charged_ions is None:
self.charged_ions = np.array(ion) + aamass.mass_proton
self.charged_ion_types = ion_type.copy()
self.charged_glycan_comps = glycan_comp.copy()
self.charges = np.array([1]*len(ion))
for i in range(2, charge+1):
self.charged_ions = np.append(self.charged_ions, np.array(ion)/i + aamass.mass_proton)
self.charged_ion_types = np.append(self.charged_ion_types, ion_type)
self.charged_glycan_comps = np.append(self.charged_glycan_comps, glycan_comp, axis = 0)
self.charges = np.append(self.charges, np.array([i]*len(ion)))
else:
for i in range(1, charge+1):
self.charged_ions = np.append(self.charged_ions, np.array(ion)/i + aamass.mass_proton)
self.charged_ion_types = np.append(self.charged_ion_types, ion_type)
self.charged_glycan_comps = np.append(self.charged_glycan_comps, glycan_comp, axis = 0)
self.charges = np.append(self.charges, np.array([i]*len(ion)))
by_max_charge = 1 if pre_charge <= 2 else 2
cz_max_charge = 1 if pre_charge <= 2 else 2
Y_max_charge = pre_charge - 1
M_max_charge = pre_charge
self.ions = None
self.charged_ions = None
############### Y ions ###############
if len(glyfrag_mass) > 0:
add_ions(glyfrag_mass + pepmass, np.array(['Y']*len(glyfrag_mass)), glyfrag_comp)
add_charged_ions(self.ions, self.ion_types, Y_max_charge, self.glycan_comps)
else:
#empty Y ions
add_ions(np.array([0]), np.array(['']), self.glycan_0)
if gpsm.peptide != "Z":
Y0_ion = [pepmass]
Y0_ion_type = ['Y0']
add_ions(Y0_ion, Y0_ion_type)
add_charged_ions(Y0_ion, Y0_ion_type, Y_max_charge)
M_ion = [gp_mass]
M_ion_type = ['M']
add_ions(M_ion, M_ion_type)
add_charged_ions(M_ion, M_ion_type, M_max_charge)
############### end Y ions ###############
if gpsm.peptide == "Z":
############### B ions ###############
B_ions = glyfrag_mass
B_ion_types = np.array(['B']*len(glyfrag_mass))
add_ions(B_ions, B_ion_types, glyfrag_comp)
add_charged_ions(B_ions, B_ion_types, Y_max_charge, glyfrag_comp)
M_ion = [glycan_mass]
M_ion_type = ['M-H2O']
add_ions(M_ion, M_ion_type)
add_charged_ions(M_ion, M_ion_type, M_max_charge)
############### end Y ions ###############
############### base b/y, c/z mass ###############
if config.activation_type.upper() == "ETHCD" or config.activation_type.upper() == "HCDPDETXXD":
has_by = True
has_cz = True
elif config.activation_type.upper() == "ETD":
has_by = False
has_cz = True
else:
has_by = True
has_cz = False
if gpsm.peptide == "Z":
has_by = False
has_cz = False
modmass = [0]*(len(gpsm.peptide)+2)
for mod in gpsm.modlist:
modmass[mod[0]] += aamass.mod_mass_dict[mod[1]]
def get_b_y_ions():
bion = []
yion = []
mass_nterm = modmass[0]
i = 1
for char in gpsm.peptide[:-1]:
mass_nterm += aamass.aa_mass_dict[char] + modmass[i]
i += 1
bion.append(mass_nterm)
yion.append(pepmass - mass_nterm)
return np.array(bion), np.array(yion)
bion, yion = get_b_y_ions()
max_glyco_in_by = 1
if has_by:
# self.glycan_comps = np.repeat(self.glycan_0, len(bion), axis=0)
b_ion_type = ["b%d"%(i+1) for i in range(len(bion))]
add_ions(bion, b_ion_type)
add_charged_ions(bion, b_ion_type, by_max_charge)
y_ion_type = ["y%d"%(peplen-i-1) for i in range(len(yion))]
add_ions(yion, y_ion_type)
add_charged_ions(yion, y_ion_type, by_max_charge)
if config.glycan_type == 'N':
############### b/y + $ (cxr = cross-ring) ###############
_cxr_mass = 83.03711
bion_cxr = bion[gpsm.glysite:] + _cxr_mass
bion_cxr_type = ["b$%d"%(i+1) for i in range(gpsm.glysite,len(bion))]
add_ions(bion_cxr, bion_cxr_type)
add_charged_ions(bion_cxr, bion_cxr_type, by_max_charge)
yion_cxr = yion[:gpsm.glysite] + _cxr_mass
yion_cxr_type = ["y$%d"%(peplen-i-1) for i in range(gpsm.glysite)]
add_ions(yion_cxr, yion_cxr_type)
add_charged_ions(yion_cxr, yion_cxr_type, by_max_charge)
add_ions([pepmass + _cxr_mass], ['Y$'])
add_charged_ions([pepmass + _cxr_mass], ['Y$'], Y_max_charge)
############### end b/y + $ (cxr = cross-ring) ###############
############### b/y + glyco unit ###############
for _comp,_mass in zip(glyfrag_comp, glyfrag_mass):
if np.sum(_comp) <= max_glyco_in_by:
bion_add_glyco = bion[gpsm.glysite:] + _mass
bion_add_glyco_type = ["b%d"%(i+1) for i in range(gpsm.glysite,len(bion))]
bion_add_glyco_comp = np.repeat(_comp.reshape(1,-1), len(bion_add_glyco), axis=0)
add_ions(bion_add_glyco, bion_add_glyco_type, bion_add_glyco_comp)
add_charged_ions(bion_add_glyco, bion_add_glyco_type, by_max_charge, bion_add_glyco_comp)
yion_add_glyco = yion[:gpsm.glysite] + _mass
yion_add_glyco_type = ["y%d"%(peplen-i-1) for i in range(gpsm.glysite)]
yion_add_glyco_comp = np.repeat(_comp.reshape(1,-1), len(yion_add_glyco), axis=0)
add_ions(yion_add_glyco, yion_add_glyco_type, yion_add_glyco_comp)
add_charged_ions(yion_add_glyco, yion_add_glyco_type, by_max_charge, yion_add_glyco_comp)
############### end b/y + glyco unit ###############
if self.use_pGlycoSite and gpsm.site_group:
if "{" in gpsm.site_group: site_groups = gpsm.site_group.strip("}").split("}")
else: site_groups = gpsm.site_group.strip(";").split(";")
sites = []
site_glycans = []
site_probs = []
site_glymasses = [0]*len(gpsm.peptide)
for site_group in site_groups:
if "{" in gpsm.site_group: items = site_group.strip("{").split(",")
else: items = site_group.split(",")
sites.append((int(items[0][1:])-1, int(items[1][1:])-1))
site_glycans.append([int(glyco) for glyco in items[2][1:-1].split(' ')])
site_probs.append(items[3])
site_glymasses[sites[-1][0]] = CalcGlycanMass(site_glycans[-1])
site_glymasses = np.cumsum(site_glymasses)
if has_cz and self.use_pGlycoSite and gpsm.site_group:
cion = bion + aamass.mass_NH3 + site_glymasses[:-1]
cion_type = ["c%d"%(i+1) for i in range(len(cion))]
add_ions(cion, cion_type)
add_charged_ions(cion, cion_type, cz_max_charge)
zion = pepmass + glycan_mass + aamass.mass_H - cion
zion_type = ["z%d"%(peplen-i-1) for i in range(len(zion))]
add_ions(zion, zion_type)
add_charged_ions(zion, zion_type, cz_max_charge)
# c_minus_H_ion = cion - aamass.mass_H
# cH_ion_type = ["c%d-H"%(i+1) for i in range(len(cion))]
# add_ions(c_minus_H_ion, cH_ion_type)
# add_charged_ions(c_minus_H_ion, cH_ion_type, cz_max_charge)
z_plus_H_ion = zion + aamass.mass_H
zH_ion_type = ["z%d+H"%(peplen-i-1) for i in range(len(zion))]
add_ions(z_plus_H_ion, zH_ion_type)
add_charged_ions(z_plus_H_ion, zH_ion_type, cz_max_charge)
elif has_cz:
cion = bion + aamass.mass_NH3
cion[gpsm.glysite:] += glycan_mass
cion_type = ["c%d"%(i+1) for i in range(len(cion))]
add_ions(cion, cion_type)
add_charged_ions(cion, cion_type, cz_max_charge)
zion = yion - aamass.mass_NH3 + aamass.mass_H
zion[:gpsm.glysite] += glycan_mass
zion_type = ["z%d"%(peplen-i-1) for i in range(len(zion))]
add_ions(zion, zion_type)
add_charged_ions(zion, zion_type, cz_max_charge)
# c_minus_H_ion = cion - aamass.mass_H
# cH_ion_type = ["c%d-H"%(i+1) for i in range(len(cion))]
# add_ions(c_minus_H_ion, cH_ion_type)
# add_charged_ions(c_minus_H_ion, cH_ion_type, cz_max_charge)
z_plus_H_ion = zion + aamass.mass_H
zH_ion_type = ["z%d+H"%(peplen-i-1) for i in range(len(zion))]
add_ions(z_plus_H_ion, zH_ion_type)
add_charged_ions(z_plus_H_ion, zH_ion_type, cz_max_charge)
############### base b/y, c/z mass ###############
if self.output_info:
#spec\tpeptide\tmodinfo\tglycan(%s)\tformula\tglysite\tcharge\ttheo_ion\tmatched_ion
self.outmsg.write("%s\t%s\t%s" %(gpsm.spec, gpsm.peptide, gpsm.mod))
self.outmsg.write("\t%s"%",".join([str(g) for g in gpsm.glycan]))
self.outmsg.write("\t%s"%config.FormatGlycan(gpsm.glycan))
if self.use_pGlycoSite and gpsm.site_group:
self.outmsg.write("\t%s"%gpsm.site_group)
else:
self.outmsg.write("\t%d"%(gpsm.glysite+1))
self.outmsg.write("\t%d"%(gpsm.charge))
output_strs = []
for i in range(len(self.ions)):
if self.ion_types[i] != "Y" and (sum(self.glycan_comps[i]) > max_glyco_in_by): continue
gly_format = config.FormatGlycan(self.glycan_comps[i])
if gly_format != "": gly_format = '-' + gly_format
output_strs.append("%s%s"%(self.ion_types[i],gly_format))
self.outmsg.write("\t%s;"%(";".join(output_strs)))
clip = self.charged_ions <= (self.max_plot_mz + 1)
ions = self.charged_ions[clip]
glycan_comps = self.charged_glycan_comps[clip]
ion_types = self.charged_ion_types[clip]
charges = self.charges[clip]
idx, mass_tol = self.MatchPeak(mz_ints, ions)
idx = np.array(idx)
mass_tol = np.array(mass_tol)
ions = ions[idx != -1]
glycan_comps = glycan_comps[idx != -1]
ion_types = ion_types[idx != -1]
charges = charges[idx != -1]
mass_tol = mass_tol[idx != -1]
idx = idx[idx != -1]
# output the matched ion type
if self.output_info:
output_strs = []
for i in range(len(ions)):
if ion_types[i] != "Y" and (sum(glycan_comps[i]) > max_glyco_in_by): continue
gly_format = config.FormatGlycan(glycan_comps[i])
if gly_format != "": gly_format = '-' + gly_format
output_strs.append("%s%s+%d=%.3f,%.1f" %(ion_types[i],gly_format, charges[i], xmz[idx[i]], yint[idx[i]]))
self.outmsg.write("\t%s"%(";".join(output_strs)))
def _match_oxonium(num, markers, color):
tol = oxonium_tol
output_strs = []
matched_oxonium = []
if num > 0:
for mass in markers:
matched_idx = -1
for i in range(len(mz_ints)):
if mz_ints[i,0] > mass+tol: break
elif abs(mass - mz_ints[i,0]) <= tol:
if matched_idx == -1 or mz_ints[matched_idx,1] < mz_ints[i,1]:
matched_idx = i
i = matched_idx
if i != -1:
output_strs.append("%.2f=%.1f"%(mz_ints[i,0], mz_ints[i,1]))
matched_oxonium.append((mz_ints[i,0], mz_ints[i,1], color))
if self.output_info:
self.outmsg.write("\t%s"%(";".join(output_strs)))
return matched_oxonium
matched_oxoniums = []
for i in range(len(config.used_markers)):
matched_oxoniums.append(_match_oxonium(gpsm.glycan[i], config.used_markers[i].oxonium_ions, config.used_markers[i].color))
if self.output_info:
self.outmsg.write("\n")
self.outmsg.flush()
if config.isPlot:
########## plot
order = np.argsort(idx)
mass_tol = mass_tol[order]
ions = ions[order]
glycan_comps = glycan_comps[order]
ion_types = ion_types[order]
charges = charges[order]
idx = idx[order]
peptide = gpsm.peptide
plotpeptide = peptide
peplen = len(peptide)
plotmod = "Mod: "
for modidx, modname in gpsm.modlist:
if modidx == 0: plotmod += "NTerm" + aamass.mod_to_mass[modname] + ";"
elif modidx == peplen+1: plotmod += "CTerm" + aamass.mod_to_mass[modname] + ";"
else: plotmod += gpsm.peptide[modidx-1] + str(modidx) + aamass.mod_to_mass[modname] + ";"
modidx = modidx - peplen
if modidx >= 0:
peptide = peptide + aamass.mod_to_mass[modname]
else:
peptide = peptide[-len(peptide):modidx] + aamass.mod_to_mass[modname] + peptide[modidx:]
if len(gpsm.modlist) == 0:
plotmod = "noPepMod"
xmztol = xmz
xmz = xmz[idx]
yint = yint[idx]
#
b_ion_set = set()
y_ion_set = set()
if self.plot_glycan and self.plot_peptide:
baseheights = [max_inten, max_inten*(1+margin_Y)]
bybaseheights = [max_inten*(1+margin_Y*2+margin_by), max_inten*(1+margin_Y*2)]
elif self.plot_glycan:
baseheights = [max_inten*(1+margin_Y*0.1), max_inten*(1+margin_Y*1.3)]
else:
baseheights = [max_inten, max_inten*(1+margin_Y*0.5)]
bybaseheights = baseheights
count = 0
countby = 0
text_offset = 0
text_to_mark = .95
# plot oxoniums
for oxonium in matched_oxoniums:
for mz,inten,color in oxonium:
ax1.text(mz*(1+text_offset),inten+hfactor*max_inten,
"%.2f" %mz, rotation = 90, color = color,
horizontalalignment="center",verticalalignment="bottom")
ax1.plot([mz, mz], [0, inten], color = color, linewidth=match_lw)
cz_set = set()
for i in range(len(ions)):
height = 0.1
if ion_types[i][0] == "Y" or ion_types[i][0] == "B":
if not self.plot_glycan: continue
elif ion_types[i][0] == "B" and xmz[i] < config.max_oxonium_mz: continue
baseheight = baseheights[count%2]
count += 1
ax1.plot([xmz[i],xmz[i]],[yint[i], baseheight], dashes=[4, 4], color="gray", linewidth=0.2)
if not config.glyco_as_text:
for igly in range(len(config.used_markers)):
if glycan_comps[i][igly] > 0:
ax1.plot(xmz[i],baseheight+height*hfactor*max_inten,
marker=config.used_markers[igly].shape, markerfacecolor=config.used_markers[igly].color, markersize=markersize, markeredgecolor="black", fillstyle=fill_rotation(config.used_markers[igly].fill), markerfacecoloralt=config.used_markers[igly].alt)
ax1.text(xmz[i],baseheight+((height+text_to_mark)*hfactor)*max_inten,
str(glycan_comps[i][igly]),rotation=90, fontsize=fontsize,
horizontalalignment="center",verticalalignment="bottom")
height += int(log10(glycan_comps[i][igly])+1)*1.3 + 1.5
ax1.text(xmz[i],baseheight+((height)*hfactor)*max_inten,
"%s /%d+%s"%(ion_types[i],charges[i]," %.2f"%xmz[i] if self.show_mass else ""), rotation=90, fontsize=fontsize,
horizontalalignment="center",verticalalignment="bottom")
else:
gly_str = config.short_format(glycan_comps[i])
if gly_str != "": gly_str = "--" + gly_str
gly_str = "%s%s /%d+" %(ion_types[i], gly_str, charges[i])
ax1.text(xmz[i], baseheight+height*hfactor*max_inten, gly_str, rotation=90, fontsize=fontsize, horizontalalignment="center",verticalalignment="bottom")
ax1.plot([xmz[i],xmz[i]],[0, yint[i]], color="red", linewidth=match_lw)
ax2.plot(xmz[i], mass_tol[i], color="red", marker = ".")
elif ion_types[i][0] == "M":
baseheight = baseheights[count % 2]
count += 1
ax1.plot([xmz[i],xmz[i]],[yint[i], baseheight], dashes=[4, 4], color="gray", linewidth=0.2)
ax1.text(xmz[i]*(1+text_offset),baseheight+((height)*hfactor)*max_inten,
"%s /%d+%s"%(ion_types[i],charges[i]," %.2f"%xmz[i] if self.show_mass else ""),rotation=90, fontsize=fontsize,
horizontalalignment="center",verticalalignment="bottom")
ax1.plot([xmz[i],xmz[i]],[0, yint[i]], color="blue", linewidth=match_lw)
ax2.plot(xmz[i], mass_tol[i], color="blue", marker = ".")
else: #b, y ions
#Just plot Y1 fragment b,y ions
if not self.plot_peptide: continue
if sum(glycan_comps[i]) > max_glyco_in_by: continue
baseheight = bybaseheights[count % 2]
if ion_types[i].startswith('z'):
if ion_types[i].endswith('H'):
ch_ion = ion_types[i][1:-2] + str(charges[i])
else:
ch_ion = ion_types[i][1:] + str(charges[i])
if ch_ion in cz_set:
continue
else:
cz_set.add(ch_ion)
count += 1
ax1.plot([xmz[i],xmz[i]],[yint[i], baseheight], dashes=[4, 4], color="gray", linewidth=0.2)
if not config.glyco_as_text:
for igly in range(len(config.used_markers)):
if glycan_comps[i][igly] > 0:
ax1.plot(xmz[i],baseheight+height*hfactor*max_inten,
marker=config.used_markers[igly].shape, markerfacecolor=config.used_markers[igly].color, markersize=markersize, markeredgecolor="black", fillstyle=fill_rotation(config.used_markers[igly].fill), markerfacecoloralt=config.used_markers[igly].alt)
ax1.text(xmz[i]*(1+text_offset),baseheight+((height+text_to_mark)*hfactor)*max_inten,
str(glycan_comps[i][igly]),rotation=90, fontsize=fontsize,
horizontalalignment="center",verticalalignment="bottom")
#horizontalalignment="center",verticalalignment="top")
height += 2.5
ax1.text(xmz[i]*(1+text_offset),baseheight+((height)*hfactor)*max_inten, "%s /%d+%s"%(ion_types[i],charges[i]," %.2f"%xmz[i] if self.show_mass else ""),rotation=90, fontsize=fontsize, horizontalalignment="center",verticalalignment="bottom")
else:
gly_str = config.short_format(glycan_comps[i])
if gly_str != "": gly_str = "--" + gly_str
gly_str = "%s%s /%d+" %(ion_types[i], gly_str, charges[i])
ax1.text(xmz[i], baseheight+height*hfactor*max_inten, gly_str, rotation=90, fontsize=fontsize, horizontalalignment="center",verticalalignment="bottom")
if ion_types[i][:2] == "b$":
b_ion_set.add(int(ion_types[i][2:]))
ax1.plot([xmz[i],xmz[i]],[0, yint[i]], color=self.colorb, linewidth=match_lw)
ax2.plot(xmz[i], mass_tol[i], color=self.colorb, marker = ".")
elif ion_types[i][0] == "b":
b_ion_set.add(int(ion_types[i][1:]))
ax1.plot([xmz[i],xmz[i]],[0, yint[i]], color=self.colorb, linewidth=match_lw)
ax2.plot(xmz[i], mass_tol[i], color=self.colorb, marker = ".")
elif ion_types[i][:2] == "y$":
y_ion_set.add(int(ion_types[i][2:]))
ax1.plot([xmz[i],xmz[i]],[0, yint[i]], color=self.colory, linewidth=match_lw)
ax2.plot(xmz[i], mass_tol[i], color=self.colory, marker = ".")
elif ion_types[i][0] == "y":
y_ion_set.add(int(ion_types[i][1:]))
ax1.plot([xmz[i],xmz[i]],[0, yint[i]], color=self.colory, linewidth=match_lw)
ax2.plot(xmz[i], mass_tol[i], color=self.colory, marker = ".")
elif ion_types[i][0] == "c":
if ion_types[i][-1] == "H":
b_ion_set.add(int(ion_types[i][1:-2]))
else:
b_ion_set.add(int(ion_types[i][1:]))
ax1.plot([xmz[i],xmz[i]],[0, yint[i]], color=self.colorc, linewidth=match_lw)
ax2.plot(xmz[i], mass_tol[i], color=self.colorc, marker = ".")
elif ion_types[i][0] == "z":
if ion_types[i][-1] == "H":
y_ion_set.add(int(ion_types[i][1:-2]))
else:
y_ion_set.add(int(ion_types[i][1:]))
ax1.plot([xmz[i],xmz[i]],[0, yint[i]], color=self.colorz, linewidth=match_lw)
ax2.plot(xmz[i], mass_tol[i], color=self.colorz, marker = ".")