-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcreate_spectral_library.py
1573 lines (1383 loc) · 64.9 KB
/
create_spectral_library.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
# MS ANNIKA SPECTRAL LIBRARY EXPORTER
# 2023 (c) Micha Johannes Birklbauer
# https://github.com/michabirklbauer/
# version tracking
__version = "1.4.4"
__date = "2024-12-06"
# REQUIREMENTS
# pip install pandas
# pip install openpyxl
# pip install pyteomics
##### PARAMETERS #####
from config import SPECTRA_FILE
from config import CSMS_FILE
from config import RUN_NAME
from config import CROSSLINKER
from config import MODIFICATIONS
from config import MODIFICATIONS_XI
from config import ION_TYPES
from config import MAX_CHARGE
from config import MATCH_TOLERANCE
from config import iRT_PARAMS
from config import ORGANISM
from config import PARSER_PATTERN
######################
# import packages
import re
import pandas as pd
from pyteomics import mgf, mass
from typing import Dict
from typing import List
from typing import Tuple
from typing import Set
from typing import Union
from typing import BinaryIO
from typing import Any
import warnings
##################### FILE READERS #####################
def parse_xi(result_file: str, spectra: Dict[str, Any]) -> pd.DataFrame:
"""Parses the xiFDR CSM result file and returns it in MS Annika format for
spectral library creation.
"""
xi = pd.read_csv(result_file)
## needed cols
# Sequence A
# Modifications A
# Sequence B
# Modifications B
# First Scan
# Spectrum File
# A in protein
# B in protein
# Crosslinker Position A
# Crosslinker Position B
# Accession A
# Accession B
# Charge
# m/z [Da]
# Crosslink Strategy
# RT [min]
# Compensation Voltage
ms_annika_struc = {"Sequence A": [],
"Modifications A": [],
"Sequence B": [],
"Modifications B": [],
"First Scan": [],
"Spectrum File": [],
"A in protein": [],
"B in protein": [],
"Crosslinker Position A": [],
"Crosslinker Position B": [],
"Accession A": [],
"Accession B": [],
"Charge": [],
"m/z [Da]": [],
"Crosslink Strategy": [],
"RT [min]": [],
"Compensation Voltage": []}
# parsing functions
def xi_get_sequence(row: pd.Series, alpha: bool = True) -> str:
seq = str(row["PepSeq1"]).strip() if alpha else str(row["PepSeq2"]).strip()
seq_a = ""
for aa in seq:
if aa.isupper():
seq_a += aa
return seq_a
def xi_get_modifications(row: pd.Series, alpha: bool = True) -> str:
seq = str(row["PepSeq1"]).strip() if alpha else str(row["PepSeq2"]).strip()
clean_seq = xi_get_sequence(row, alpha)
xl_pos = int(row["LinkPos1"]) if alpha else int(row["LinkPos2"])
if len(MODIFICATIONS_XI) > 10:
msg = "Found more than 10 possible modifications for xi. " + \
"Maximum number of modifications supported is 10. " + \
"Please update MODIFICATIONS_XI in the config file!"
raise RuntimeError(msg)
mod_map = dict()
mod_map_rev = dict()
for i, key in enumerate(MODIFICATIONS_XI.keys()):
mod_map[str(i)] = key
mod_map_rev[key] = str(i)
for mod in MODIFICATIONS_XI.keys():
seq = seq.replace(mod, mod_map_rev[mod])
mod_str = ""
for i, aa in enumerate(seq):
if aa in mod_map:
mod_str += f"{MODIFICATIONS_XI[mod_map[aa]][0]}{i+1}({MODIFICATIONS_XI[mod_map[aa]][1]});"
mod_str += f"{clean_seq[xl_pos-1]}{xl_pos}({str(row['Crosslinker']).strip()})"
return mod_str
def xi_get_rt(row: pd.Series, spectra: Dict[str, Any]) -> float:
spec_file_name = ".".join(str(row["PeakListFileName"]).split(".")[:-1]).strip()
rt = spectra[spec_file_name][int(row["scan"])]["rt"]
return rt / 60.0
def xi_get_cv(row: pd.Series, spectra: Dict[str, Any]) -> float:
# I don't think we get this from the MGF file?
return 0.0
for i, row in xi.iterrows():
if row["isDecoy"]:
continue
ms_annika_struc["Sequence A"].append(xi_get_sequence(row, True))
ms_annika_struc["Sequence B"].append(xi_get_sequence(row, False))
ms_annika_struc["Modifications A"].append(xi_get_modifications(row, True))
ms_annika_struc["Modifications B"].append(xi_get_modifications(row, False))
ms_annika_struc["First Scan"].append(int(row["scan"]))
ms_annika_struc["Spectrum File"].append(str(row["PeakListFileName"]).strip())
ms_annika_struc["A in protein"].append(int(row["PepPos1"])-1)
ms_annika_struc["B in protein"].append(int(row["PepPos2"])-1)
ms_annika_struc["Crosslinker Position A"].append(int(row["LinkPos1"]))
ms_annika_struc["Crosslinker Position B"].append(int(row["LinkPos2"]))
ms_annika_struc["Accession A"].append(str(row["Protein1"]).strip())
ms_annika_struc["Accession B"].append(str(row["Protein2"]).strip())
ms_annika_struc["Charge"].append(int(row["exp charge"]))
ms_annika_struc["m/z [Da]"].append(float(row["exp m/z"]))
ms_annika_struc["Crosslink Strategy"].append("xi")
ms_annika_struc["RT [min]"].append(xi_get_rt(row, spectra))
ms_annika_struc["Compensation Voltage"].append(xi_get_cv(row, spectra))
return pd.DataFrame(ms_annika_struc)
############### SPECTRAL LIBRARY CREATOR ###############
# parse scan number from pyteomics mgf params
def parse_scannr(params: Dict, pattern: str = PARSER_PATTERN, i: int = 0) -> Tuple[int, int]:
"""Parses the scan number from the params dictionary of the pyteomics mgf
spectrum.
Parameters
----------
params : Dict
The "params" dictionary of the pyteomics mgf spectrum.
pattern : str
Regex pattern to use for parsing the scan number from the title if it
can't be infered otherwise.
i : int
The scan number to be returned in case of failure.
Returns
-------
(exit_code, scan_nr) : Tuple
A tuple with the exit code (0 if successful, 1 if parsing failed) at the
first position [0] and the scan number at the second position [1].
"""
# prefer scans attr over title attr
if "scans" in params:
try:
return (0, int(params["scans"]))
except:
pass
# try parse title
if "title" in params:
# if there is a scan token in the title, try parse scan_nr
if "scan" in params["title"]:
try:
return (0, int(params["title"].split("scan=")[1].strip("\"")))
except:
pass
# else try to parse by pattern
try:
scan_nr = re.findall(pattern, params["title"])[0]
scan_nr = re.sub(r"[^0-9]", "", scan_nr)
if len(scan_nr) > 0:
return (0, int(scan_nr))
except:
pass
# else try parse whole title
try:
return (0, int(params["title"]))
except:
pass
# return unsuccessful parse
return (1, i)
# reading spectra
# def read_spectra(filename: str | BinaryIO) -> Dict[int, Dict]:
# for backward compatibility >>
def read_spectra(filename: Union[str, BinaryIO]) -> Dict[int, Dict]:
"""
Returns a dictionary that maps scan numbers to spectra:
Dict[int -> Dict["precursor" -> float
"charge" -> int
"rt" -> float
"max_intensity" -> float
"peaks" -> Dict[m/z -> intensity]]
"""
result_dict = dict()
with mgf.read(filename) as reader:
for spectrum in reader:
parser_result = parse_scannr(spectrum["params"])
if parser_result[0] != 0:
raise RuntimeError(f"Could not parse scan number for spectrum {spectrum}. Please adjust PARSER_PATTERN in the config file!")
scan_nr = parser_result[1]
spectrum_dict = dict()
spectrum_dict["precursor"] = spectrum["params"]["pepmass"]
spectrum_dict["charge"] = spectrum["params"]["charge"]
spectrum_dict["rt"] = spectrum["params"]["rtinseconds"] if "rtinseconds" in spectrum["params"] else 0.0
spectrum_dict["max_intensity"] = float(max(spectrum["intensity array"])) if len(spectrum["intensity array"]) > 0 else 0.0
peaks = dict()
for i, mz in enumerate(spectrum["m/z array"]):
peaks[mz] = spectrum["intensity array"][i]
spectrum_dict["peaks"] = peaks
result_dict[scan_nr] = spectrum_dict
reader.close()
return result_dict
# read multiple spectra files
def read_multiple_spectra(filenames: List[str]) -> Dict[str, Dict[int, Dict]]:
"""
Returns a dictionary that maps filenames to scan numbers to spectra:
Dict[str -> Dict[int -> Dict["precursor" -> float
"charge" -> int
"max_intensity" -> float
"peaks" -> Dict[m/z -> intensity]]
"""
result_dict = dict()
for filename in filenames:
current_spectra_file = ".".join(filename.split(".")[:-1]).strip()
result_dict[current_spectra_file] = read_spectra(filename)
return result_dict
# read multiple spectra files - streamlit version
def read_multiple_spectra_streamlit(st_files) -> Dict[str, Dict[int, Dict]]:
"""
Returns a dictionary that maps filenames to scan numbers to spectra:
Dict[str -> Dict[int -> Dict["precursor" -> float
"charge" -> int
"max_intensity" -> float
"peaks" -> Dict[m/z -> intensity]]
"""
result_dict = dict()
for st_file in st_files:
current_spectra_file = ".".join(st_file.name.split(".")[:-1]).strip()
result_dict[current_spectra_file] = read_spectra(st_file)
return result_dict
# generate a position to modification mass mapping
def generate_modifications_dict(peptide: str,
modification_str: str,
possible_modifications: Dict[str, List[float]] = MODIFICATIONS) -> Dict[int, List[float]]:
"""
Returns a mapping of peptide positions (0 based) to possible modification masses.
modification_str is the modification string as returned by MS Annika e.g. K5(DSSO);M7(Oxidation)
the modification in braces has to be defined in MODIFICATIONS
"""
modifications_dict = dict()
modifications = modification_str.split(";")
for modification in modifications:
# remove possible white spaces
modification = modification.strip()
# get modified amino acid and modification position
aa_and_pos = modification.split("(")[0]
# get modification type
mod = modification.split("(")[1].rstrip(")")
if aa_and_pos == "Nterm":
pos = -1
elif aa_and_pos == "Cterm":
pos = len(peptide)
else:
pos = int(aa_and_pos[1:]) - 1
if mod in possible_modifications:
modifications_dict[pos] = possible_modifications[mod]
else:
warnings.warn("Modification '" + mod + "' not found!")
return modifications_dict
# generate all theoretical fragments
# adapted from https://pyteomics.readthedocs.io/en/latest/examples/example_msms.html
def generate_theoretical_fragments(peptide: str,
modifications: Dict[int, List[float]],
ion_types: Tuple[str] = ("b", "y"),
max_charge: int = 1) -> Dict[float, str]:
"""
Generates a set of theoretical fragment ion masses of the specified peptide with the modifications.
"""
fragments = dict()
for i in range(1, len(peptide)):
for ion_type in ion_types:
for charge in range(1, max_charge + 1):
if ion_type[0] in "abc":
frag_mass = mass.fast_mass(peptide[:i], ion_type = ion_type, charge = charge)
mass_possibilites = set()
for mod_pos in modifications.keys():
# if the modification is within the fragment:
if mod_pos < i:
# add the modification mass / charge if its a normal modification
if len(modifications[mod_pos]) == 1:
frag_mass += modifications[mod_pos][0] / charge
else:
# if it's a crosslinking modification we add the crosslinker fragment masses
# to a set of possible modification mass additions to generate a fragment mass
# for every crosslinker fragment
for modification in modifications[mod_pos]:
mass_possibilites.add(modification / charge)
# we add all possible fragment masses including all crosslinker fragment possibilites
if len(mass_possibilites) == 0:
if frag_mass not in fragments:
fragments[frag_mass] = ion_type + str(i) + "+" + str(charge) + ": " + peptide[:i]
else:
for mass_possibility in mass_possibilites:
if frag_mass + mass_possibility not in fragments:
fragments[frag_mass + mass_possibility] = ion_type + str(i) + "+" + str(charge) + ": " + peptide[:i]
else:
frag_mass = mass.fast_mass(peptide[i:], ion_type = ion_type, charge = charge)
mass_possibilites = set()
for mod_pos in modifications.keys():
if mod_pos >= i:
if len(modifications[mod_pos]) == 1:
frag_mass += modifications[mod_pos][0] / charge
else:
for modification in modifications[mod_pos]:
mass_possibilites.add(modification / charge)
if len(mass_possibilites) == 0:
if frag_mass not in fragments:
fragments[frag_mass] = ion_type + str(len(peptide) - i) + "+" + str(charge) + ": " + peptide[i:]
else:
for mass_possibility in mass_possibilites:
if frag_mass + mass_possibility not in fragments:
fragments[frag_mass + mass_possibility] = ion_type + str(len(peptide) - i) + "+" + str(charge) + ": " + peptide[i:]
return fragments
# get all fragments and their annotations
def get_fragments(row: pd.Series,
alpha: bool,
spectra: Dict[str, Dict[int, Dict]],
crosslinker: str = CROSSLINKER,
possible_modifications: Dict[str, List[float]] = MODIFICATIONS,
ion_types: Tuple[str] = ION_TYPES,
max_charge: int = MAX_CHARGE,
match_tolerance: float = MATCH_TOLERANCE) -> List[Dict]:
"""
Generates all fragments with the necessary spectral library annotations for a given CSM peptide.
"""
# function to check if the fragment contains the crosslinker
def check_if_xl_in_frag(row, alpha, ion_type, fragment, crosslinker):
if alpha:
peptide = row["Sequence A"]
mods = row["Modifications A"]
else:
peptide = row["Sequence B"]
mods = row["Modifications B"]
pos = 0
mods_list = mods.split(";")
for mod_in_list in mods_list:
aa_and_pos = mod_in_list.strip().split("(")[0]
mod = mod_in_list.strip().split("(")[1].rstrip(")")
if mod == crosslinker:
if aa_and_pos == "Nterm":
pos = -1
elif aa_and_pos == "Cterm":
pos = len(peptide)
else:
pos = int(aa_and_pos[1:]) - 1
break
if ion_type in "abc":
if len(fragment) > pos:
return True
else:
if len(peptide) - len(fragment) <= pos:
return True
return False
# end function
fragments = list()
scan_nr = row["First Scan"]
if alpha:
sequence = row["Sequence A"]
modifications = row["Modifications A"]
else:
sequence = row["Sequence B"]
modifications = row["Modifications B"]
current_spectra_file = ".".join(row["Spectrum File"].split(".")[:-1]).strip()
spectrum = spectra[current_spectra_file][scan_nr]
modifications_processed = generate_modifications_dict(sequence, modifications, possible_modifications)
theoretical_fragments = generate_theoretical_fragments(sequence, modifications_processed, ion_types, max_charge)
matched_fragments = dict()
# match fragments
for peak_mz in spectrum["peaks"].keys():
for fragment in theoretical_fragments.keys():
if round(peak_mz, 4) < round(fragment + match_tolerance, 4) and round(peak_mz, 4) > round(fragment - match_tolerance, 4):
matched_fragments[peak_mz] = theoretical_fragments[fragment]
break
# get annotations
for match in matched_fragments.keys():
fragment_charge = int(matched_fragments[match].split("+")[1].split(":")[0])
fragment_type = str(matched_fragments[match][0])
fragment_number = int(matched_fragments[match].split("+")[0][1:])
fragment_pep_id = 0 if alpha else 1
fragment_mz = match
fragment_rel_intensity = float(spectrum["peaks"][match] / spectrum["max_intensity"])
fragment_loss_type = ""
fragment_contains_xl = check_if_xl_in_frag(row, alpha, fragment_type, matched_fragments[match].split(":")[1].strip(), crosslinker)
fragment_lossy = False
fragments.append({"FragmentCharge": fragment_charge,
"FragmentType": fragment_type,
"FragmentNumber": fragment_number,
"FragmentPepId": fragment_pep_id,
"FragmentMz": fragment_mz,
"RelativeIntensity": fragment_rel_intensity,
"FragmentLossType": fragment_loss_type,
"CLContainingFragment": fragment_contains_xl,
"LossyFragment": fragment_lossy
})
return fragments
# get crosslink position in proteins
def get_positions_in_protein(row: pd.Series) -> Dict[str, int]:
"""
Returns the crosslink position of the first protein of peptide alpha and the first protein of peptide beta.
"""
pep_pos_A = int(row["A in protein"]) if ";" not in str(row["A in protein"]) else int(row["A in protein"].split(";")[0])
pep_pos_B = int(row["B in protein"]) if ";" not in str(row["B in protein"]) else int(row["B in protein"].split(";")[0])
xl_pos_A = int(row["Crosslinker Position A"])
xl_pos_B = int(row["Crosslinker Position B"])
return {"A": pep_pos_A + xl_pos_A, "B": pep_pos_B + xl_pos_B}
##### DECOY GENERATION #####
# decoy generation implemented as described by Zhang et al. here: https://doi.org/10.1021/acs.jproteome.7b00614
def generate_decoy_csm_dd(row: pd.Series, crosslinker: str = CROSSLINKER) -> pd.Series:
"""
"""
decoy_csm = row.copy(deep = True)
# decoy seq
seq_a = str(decoy_csm["Sequence A"]).strip()
decoy_seq_a = seq_a[:-1][::-1] + seq_a[-1]
seq_b = str(decoy_csm["Sequence B"]).strip()
decoy_seq_b = seq_b[:-1][::-1] + seq_b[-1]
decoy_csm["Sequence A"] = decoy_seq_a
decoy_csm["Sequence B"] = decoy_seq_b
# decoy mods
## <calculate_new_position>
def calculate_new_position(csm, alpha, modification):
sequence = csm["Sequence B"]
if alpha:
sequence = csm["Sequence A"]
if "Nterm" in modification:
return modification
if "Cterm" in modification:
return modification
pos = int(modification.split("(")[0][1:]) - 1
aa = modification.split("(")[0][0].strip()
ptm = modification.split("(")[1].split(")")[0].strip()
if pos == (len(sequence) - 1):
return modification
new_pos = len(sequence) - 2 - pos
if aa != sequence[new_pos]:
warnings.warn(f"Target and decoy modification positions may to match (decoy position may be incorrect)!", UserWarning)
#assert aa == sequence[new_pos]
if ptm == crosslinker:
if alpha:
csm["Crosslinker Position A"] = new_pos + 1
else:
csm["Crosslinker Position B"] = new_pos + 1
return f"{aa}{new_pos + 1}({ptm})"
## </calculate_new_position>
decoy_mods_a = [calculate_new_position(decoy_csm, True, mod.strip()) for mod in str(decoy_csm["Modifications A"]).split(";")]
decoy_mods_b = [calculate_new_position(decoy_csm, False, mod.strip()) for mod in str(decoy_csm["Modifications B"]).split(";")]
decoy_csm["Modifications A"] = ";".join(decoy_mods_a)
decoy_csm["Modifications B"] = ";".join(decoy_mods_b)
return decoy_csm
def generate_decoy_csm_td(row: pd.Series, crosslinker: str = CROSSLINKER) -> pd.Series:
"""
"""
decoy_csm = row.copy(deep = True)
# decoy seq
seq_b = str(decoy_csm["Sequence B"]).strip()
decoy_seq_b = seq_b[:-1][::-1] + seq_b[-1]
decoy_csm["Sequence B"] = decoy_seq_b
# decoy mods
## <calculate_new_position>
def calculate_new_position(csm, alpha, modification):
sequence = csm["Sequence B"]
if alpha:
sequence = csm["Sequence A"]
if "Nterm" in modification:
return modification
if "Cterm" in modification:
return modification
pos = int(modification.split("(")[0][1:]) - 1
aa = modification.split("(")[0][0].strip()
ptm = modification.split("(")[1].split(")")[0].strip()
if pos == (len(sequence) - 1):
return modification
new_pos = len(sequence) - 2 - pos
if aa != sequence[new_pos]:
warnings.warn(f"Target and decoy modification positions may to match (decoy position may be incorrect)!", UserWarning)
#assert aa == sequence[new_pos]
if ptm == crosslinker:
if alpha:
csm["Crosslinker Position A"] = new_pos + 1
else:
csm["Crosslinker Position B"] = new_pos + 1
return f"{aa}{new_pos + 1}({ptm})"
## </calculate_new_position>
decoy_mods_b = [calculate_new_position(decoy_csm, False, mod.strip()) for mod in str(decoy_csm["Modifications B"]).split(";")]
decoy_csm["Modifications B"] = ";".join(decoy_mods_b)
return decoy_csm
def generate_decoy_csm_dt(row: pd.Series, crosslinker: str = CROSSLINKER) -> pd.Series:
"""
"""
decoy_csm = row.copy(deep = True)
# decoy seq
seq_a = str(decoy_csm["Sequence A"]).strip()
decoy_seq_a = seq_a[:-1][::-1] + seq_a[-1]
decoy_csm["Sequence A"] = decoy_seq_a
# decoy mods
## <calculate_new_position>
def calculate_new_position(csm, alpha, modification):
sequence = csm["Sequence B"]
if alpha:
sequence = csm["Sequence A"]
if "Nterm" in modification:
return modification
if "Cterm" in modification:
return modification
pos = int(modification.split("(")[0][1:]) - 1
aa = modification.split("(")[0][0].strip()
ptm = modification.split("(")[1].split(")")[0].strip()
if pos == (len(sequence) - 1):
return modification
new_pos = len(sequence) - 2 - pos
if aa != sequence[new_pos]:
warnings.warn(f"Target and decoy modification positions may to match (decoy position may be incorrect)!", UserWarning)
#assert aa == sequence[new_pos]
if ptm == crosslinker:
if alpha:
csm["Crosslinker Position A"] = new_pos + 1
else:
csm["Crosslinker Position B"] = new_pos + 1
return f"{aa}{new_pos + 1}({ptm})"
## </calculate_new_position>
decoy_mods_a = [calculate_new_position(decoy_csm, True, mod.strip()) for mod in str(decoy_csm["Modifications A"]).split(";")]
decoy_csm["Modifications A"] = ";".join(decoy_mods_a)
return decoy_csm
def get_decoy_fragments(decoy_csm: pd.Series,
target_fragments: List[Dict],
possible_modifications: Dict[str, List[float]] = MODIFICATIONS,
crosslinker: str = CROSSLINKER) -> List[Dict]:
"""
"""
decoy_fragments = list()
## <get_decoy_mzs>
def get_decoy_mzs(decoy_csm, pep_id, ion_type, ion_number, charge, possible_modifications) -> List[float]:
decoy_mzs = list()
seq = decoy_csm["Sequence A"]
mods_str = decoy_csm["Modifications A"]
if pep_id == 1:
seq = decoy_csm["Sequence B"]
mods_str = decoy_csm["Modifications B"]
mods = generate_modifications_dict(seq, mods_str, possible_modifications)
if ion_type in "abc":
end_pos = ion_number
frag_mass = mass.fast_mass(seq[:end_pos], ion_type = ion_type, charge = charge)
mz_possibilites = set()
for mod_pos in mods.keys():
# if the modification is within the fragment:
if mod_pos < end_pos:
# add the modification mass / charge if its a normal modification
if len(mods[mod_pos]) == 1:
frag_mass += mods[mod_pos][0] / charge
else:
# if it's a crosslinking modification we add the crosslinker fragment masses
# to a set of possible modification mass additions to generate a fragment mass
# for every crosslinker fragment
for mod in mods[mod_pos]:
mz_possibilites.add(mod / charge)
# we add all possible fragment masses including all crosslinker fragment possibilites
if len(mz_possibilites) == 0:
if frag_mass not in decoy_mzs:
decoy_mzs.append(frag_mass)
else:
for mz_possibility in mz_possibilites:
if frag_mass + mz_possibility not in decoy_mzs:
decoy_mzs.append(frag_mass + mz_possibility)
return decoy_mzs
else:
start_pos = len(seq) - ion_number
frag_mass = mass.fast_mass(seq[start_pos:], ion_type = ion_type, charge = charge)
mz_possibilites = set()
for mod_pos in mods.keys():
if mod_pos >= start_pos:
if len(mods[mod_pos]) == 1:
frag_mass += mods[mod_pos][0] / charge
else:
for mod in mods[mod_pos]:
mz_possibilites.add(mod / charge)
if len(mz_possibilites) == 0:
if frag_mass not in decoy_mzs:
decoy_mzs.append(frag_mass)
else:
for mz_possibility in mz_possibilites:
if frag_mass + mz_possibility not in decoy_mzs:
decoy_mzs.append(frag_mass + mz_possibility)
return decoy_mzs
## </get_decoy_mzs>
## <check_if_xl_in_frag>
def check_if_xl_in_frag(decoy_csm, pep_id, ion_type, ion_number, crosslinker) -> bool:
if pep_id == 0:
peptide = decoy_csm["Sequence A"]
mods = decoy_csm["Modifications A"]
else:
peptide = decoy_csm["Sequence B"]
mods = decoy_csm["Modifications B"]
pos = 0
mods_list = mods.split(";")
for mod_in_list in mods_list:
aa_and_pos = mod_in_list.strip().split("(")[0]
mod = mod_in_list.strip().split("(")[1].rstrip(")")
if mod == crosslinker:
if aa_and_pos == "Nterm":
pos = -1
elif aa_and_pos == "Cterm":
pos = len(peptide)
else:
pos = int(aa_and_pos[1:]) - 1
break
if ion_type in "abc":
if ion_number > pos:
return True
else:
if len(peptide) - ion_number <= pos:
return True
return False
## </check_if_xl_in_frag>
for fragment in target_fragments:
fragment_charge = fragment["FragmentCharge"]
fragment_type = fragment["FragmentType"]
fragment_number = fragment["FragmentNumber"]
fragment_pep_id = fragment["FragmentPepId"]
fragment_mzs = get_decoy_mzs(decoy_csm, fragment_pep_id, fragment_type, fragment_number, fragment_charge, possible_modifications)
fragment_rel_intensity = fragment["RelativeIntensity"]
fragment_loss_type = ""
fragment_contains_xl = check_if_xl_in_frag(decoy_csm, fragment_pep_id, fragment_type, fragment_number, crosslinker)
fragment_lossy = False
for fragment_mz in fragment_mzs:
decoy_fragments.append({"FragmentCharge": fragment_charge,
"FragmentType": fragment_type,
"FragmentNumber": fragment_number,
"FragmentPepId": fragment_pep_id,
"FragmentMz": fragment_mz,
"RelativeIntensity": fragment_rel_intensity,
"FragmentLossType": fragment_loss_type,
"CLContainingFragment": fragment_contains_xl,
"LossyFragment": fragment_lossy
})
return decoy_fragments
##### SPECTRAL LIBRARY COLUMNS #####
# get the linkId value
def get_linkId(row: pd.Series) -> str:
"""
Returns the first accession of the alpha peptide and the first accession of the beta peptide + the corresponding crosslink positions.
"""
positions = get_positions_in_protein(row)
accession_a = row["Accession A"] if ";" not in row["Accession A"] else row["Accession A"].split(";")[0]
accession_b = row["Accession B"] if ";" not in row["Accession B"] else row["Accession B"].split(";")[0]
return str(accession_a) + "_" + str(accession_b) + "-" + str(positions["A"]) + "_" + str(positions["B"])
# get the ProteinID value
def get_ProteinID(row: pd.Series) -> str:
"""
Returns the first accession of the alpha peptide and the first accession of the beta peptide.
"""
accession_a = row["Accession A"] if ";" not in row["Accession A"] else row["Accession A"].split(";")[0]
accession_b = row["Accession B"] if ";" not in row["Accession B"] else row["Accession B"].split(";")[0]
return str(accession_a) + "_" + str(accession_b)
def get_Organism() -> str:
"""
Returns the organism of the sample.
"""
return str(ORGANISM)
# get the StrippedPeptide value
def get_StrippedPeptide(row: pd.Series) -> str:
"""
Returns the sequences of the cross-linked peptides concatenated.
"""
return str(row["Sequence A"]) + str(row["Sequence B"])
# get the FragmentGroupId value
def get_FragmentGroupId(row: pd.Series) -> str:
"""
Returns 'SequenceA_SequenceB-CrosslinkerPositionA_CrosslinkerPositionB:Charge'.
"""
return str(row["Sequence A"]) + "_" + str(row["Sequence B"]) + "-" + str(row["Crosslinker Position A"]) + "_" + str(row["Crosslinker Position B"]) + ":" + str(row["Charge"])
# get the PrecursorCharge value
def get_PrecursorCharge(row: pd.Series) -> int:
"""
Returns the precursor charge.
"""
return int(row["Charge"])
# get the PrecursorMz value
def get_PrecursorMz(row: pd.Series) -> float:
"""
Returns the precursor m/z.
"""
return float(row["m/z [Da]"])
# get the ModifiedPeptide value
def get_ModifiedPeptide(row: pd.Series,
crosslinker: str = CROSSLINKER) -> str:
"""
Returns SequenceA with modification annotations (without crosslinker) _ SequenceB with modification annotations (without crosslinker).
"""
# helper function to parse MS Annika modification string
def parse_mod_str(peptide, mod_str, crosslinker):
modifications_dict = dict()
modifications = mod_str.split(";")
for modification in modifications:
aa_and_pos = modification.strip().split("(")[0]
mod = modification.strip().split("(")[1].rstrip(")")
if mod == crosslinker:
continue
if aa_and_pos == "Nterm":
pos = 0
elif aa_and_pos == "Cterm":
pos = len(peptide)
else:
pos = int(aa_and_pos[1:])
if pos in modifications_dict:
modifications_dict[pos].append(mod)
else:
modifications_dict[pos] = [mod]
return modifications_dict
# end function
# helper function to insert string into string
def str_insert(string, index, character):
return string[:index] + character + string[index:]
# end function
mods_A = parse_mod_str(str(row["Sequence A"]), str(row["Modifications A"]), crosslinker)
mods_B = parse_mod_str(str(row["Sequence B"]), str(row["Modifications B"]), crosslinker)
# generate annotation for sequence A
shift = 0
mod_A_template_str = str(row["Sequence A"])
for pos in mods_A.keys():
current_mods = "[" + ", ".join(mods_A[pos]) + "]"
mod_A_template_str = str_insert(mod_A_template_str, pos + shift, current_mods)
shift += len(current_mods)
# generate annotation for sequence B
shift = 0
mod_B_template_str = str(row["Sequence B"])
for pos in mods_B.keys():
current_mods = "[" + ", ".join(mods_B[pos]) + "]"
mod_B_template_str = str_insert(mod_B_template_str, pos + shift, current_mods)
shift += len(current_mods)
return mod_A_template_str + "_" + mod_B_template_str
# get the IsotopeLabel value
def get_IsotopeLabel() -> int:
"""
Dummy function.
"""
return 0
# get the file value
def get_filename(row: pd.Series) -> str:
"""
Returns the filename of the corresponding RAW/MGF of the CSM.
"""
return str(row["Spectrum File"])
# get the scanID value
def get_scanID(row: pd.Series) -> int:
"""
Returns the scan nr. of the CSM.
"""
return int(row["First Scan"])
# get the run value
def get_run(run_name: str = RUN_NAME) -> str:
"""
Returns the run name specified in config.py
"""
return run_name
# get the searchID value
def get_searchID(row: pd.Series) -> str:
"""
Returns the identifying search engine name.
"""
return str(row["Crosslink Strategy"])
# get the crosslinkedResidues value
def get_crosslinkedResidues(row: pd.Series) -> str:
"""
Returns the positions of the cross-linked residues of the first proteins of the cross-linked peptides respectively, seperated by '_'.
"""
positions = get_positions_in_protein(row)
return str(positions["A"]) + "_" + str(positions["B"])
# get the LabeledSequence value
def get_LabeledSequence(row: pd.Series,
crosslinker: str = CROSSLINKER) -> str:
"""
Returns SequenceA with modification annotations (without crosslinker) _ SequenceB with modification annotations (without crosslinker).
"""
return get_ModifiedPeptide(row, crosslinker)
# get the iRT value
def get_iRT(row: pd.Series,
iRT_t: float = iRT_PARAMS["iRT_t"],
iRT_m: float = iRT_PARAMS["iRT_m"]) -> float:
"""
Returns the calculated iRT using the values specified in config.py.
"""
return (float(row["RT [min]"]) - iRT_t) / iRT_m
# get the RT value
def get_RT(row: pd.Series) -> float:
"""
Returns the RT of a CSM.
"""
return float(row["RT [min]"])
# get the CCS value
def get_CCS() -> float:
"""
Dummy function.
"""
return 0.0
# get the IonMobility value
def get_IonMobility(csm: pd.Series) -> float:
"""
Dummy function.
"""
return float(csm["Compensation Voltage"])
# get the values for all fragments of a CSM
def get_fragment_values(csm: pd.Series,
spectra: Dict,
crosslinker: str = CROSSLINKER,
possible_modifications: Dict[str, List[float]] = MODIFICATIONS,
ion_types: Tuple[str] = ION_TYPES,
max_charge: int = MAX_CHARGE,
match_tolerance: float = MATCH_TOLERANCE) -> Dict[str, List]:
"""
Returns the annotated fragments of both cross-linked peptides.
"""
fragments_A = get_fragments(csm, True, spectra, crosslinker, possible_modifications, ion_types, max_charge, match_tolerance)
fragments_B = get_fragments(csm, False, spectra, crosslinker, possible_modifications, ion_types, max_charge, match_tolerance)
return {"Fragments_A": fragments_A, "Fragments_B": fragments_B}
##### MAIN FUNCTION #####
# generates the spectral library
# def main(spectra_file: List[str] | List[BinaryIO] = SPECTRA_FILE,
# csms_file: str | BinaryIO = CSMS_FILE,
# for backward compatibility >>
def main(spectra_file: Union[List[str], List[BinaryIO]] = SPECTRA_FILE,
csms_file: Union[str, BinaryIO] = CSMS_FILE,
run_name: str = RUN_NAME,
crosslinker: str = CROSSLINKER,
modifications: Dict[str, List[float]] = MODIFICATIONS,
ion_types: Tuple[str] = ION_TYPES,
max_charge: int = MAX_CHARGE,