forked from EngelsI/ClassiCOL
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ClassiCOL.py
3119 lines (2950 loc) · 114 KB
/
ClassiCOL.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 Thu Aug 22 09:57:08 2024
@author: iaengels
"""
# Classicol_version_1_0_0.py
# System utilities
import argparse
import csv
import os
import random
import re
import time
import warnings
# Data manipulation
import numpy as np
import pandas as pd
from scipy.cluster.hierarchy import fcluster, linkage
from scipy.spatial.distance import braycurtis
# Bioinformatics libraries
from Bio import SeqIO, Align
from Bio.Seq import Seq
from Bio.Phylo.TreeConstruction import DistanceCalculator
from Bio.SeqRecord import SeqRecord
from Bio.Align import MultipleSeqAlignment, substitution_matrices
# Parallelism
import multiprocessing
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor, as_completed
# Visualization libraries
import plotly.graph_objs as go
import plotly.figure_factory as ff
import plotly.express as px
# External tools
import taxoniq
import maxquant
# Suppress warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)
def crap_f(path, add_fasta): # done
print("making database")
crap = {}
files_own = []
for fastafile in os.walk(path + "/BoneDB"):
for i in fastafile[-1]:
if i.endswith(".txt") or i.endswith(".fasta") or i.endswith(".fa"):
files_own.append(path + "/BoneDB/" + i)
if add_fasta != None:
for fastafile in os.walk(add_fasta):
for i in fastafile[-1]:
if i.endswith(".txt") or i.endswith(".fasta") or i.endswith(".fa"):
files_own.append(add_fasta + "/" + i)
done = ""
for i in files_own:
print(i.split("/")[-1])
for record in SeqIO.parse(i, "fasta"):
if str(record.description) in done:
continue
if "J" in record.seq or "O" in record.seq:
print("skip", record.description)
continue
add = record.seq
while add in crap:
add = Seq(str(add) + "&") # if seq the same as relative
done += str(record.description)
crap[add] = record.description
return crap
def do_unimod(path, ptms): # done
raw_unimod = pd.DataFrame()
ptm_list = []
for ptm in ptms:
if len(ptm) > 0:
temp = ptm.split("(")
if "N-term" in temp[1].split(")")[0]:
ptm_list.append((temp[0].replace(" ", ""), "N-term"))
if "C-term" in temp[1].split(")")[0]:
ptm_list.append((temp[0].replace(" ", ""), "C-term"))
for a in temp[1].split(")")[0]:
ptm_list.append((temp[0].replace(" ", ""), a))
with open(path + "/MISC/unimod.txt") as r:
for line in r:
line = line.replace("=", ",")
line = line.strip()
array = np.array(line.split(",")).reshape(1, -1)
df_add = pd.DataFrame(array)
raw_unimod = pd.concat([raw_unimod, df_add], ignore_index=True)
AAs = []
for aa, locaa in raw_unimod[[1, 4]].values:
if "[" in aa:
i = aa.split("]")
else:
AAs.append(aa)
continue
if "".join(c for c in i[1] if c.isdigit() == False) != i[1]:
add = (
"".join(c for c in i[1] if c.isdigit() == False) + "_!"
) # can change ! with locaa
while add in AAs:
add = add + "!"
AAs.append(add)
else:
AAs.append(i[1])
raw_unimod[1] = np.array(AAs)
temp_unimod = pd.DataFrame()
temp_unimod["PTM"] = raw_unimod[1].values[2:]
temp_unimod["delta_mass"] = raw_unimod[2].values[2:]
unimod = {}
for i, u in temp_unimod[["PTM", "delta_mass"]].values:
unimod[i] = u
unimod["AA"] = "0"
for i, u in AA_codes.items():
unimod[i] = str(u)
unimod_db = raw_unimod.iloc[2:]
unimod_db = unimod_db.drop([0, 3], axis=1)
unimod_db.columns = ["PTM", "mass", "AA", "type"]
unimod_db["mass"] = np.array([float(m) for m in unimod_db["mass"].values])
unimod_db["PTM"] = np.array([num.split("]")[-1] for num in unimod_db["PTM"].values])
unimod_db = unimod_db[unimod_db["PTM"] != ""]
unimod_db = unimod_db[unimod_db["type"] != "Manual"]
drop = [
(
False
if "".join(c for c in element if c.isdigit() == False) != element
else True
)
for element in unimod_db["PTM"].values
]
unimod_db["digit"] = np.array(drop)
unimod_db = unimod_db[unimod_db["digit"] == True]
drop = []
for p, aa in unimod_db[["PTM", "AA"]].values:
added = False
for ptm, aas in ptm_list: # We only check for ptms that mascot searched for
if ptm == p and aas == aa:
drop.append(True)
added = True
break
if added == False:
drop.append(False)
unimod_db["digit"] = np.array(drop)
unimod_db = unimod_db[unimod_db["digit"] == True]
return unimod_db, unimod
def find_mass(
peptide, AA_codes
): # sums the masses of the amino acid sequence inputed #done
mass = 0
for AA in peptide:
mass += AA_codes[AA]
return mass
def make_matrix(codes, uni): # done
doubles = [] # making all pairs of amino acids, here the ptms are also included
for element1 in list(codes.keys()):
for element2 in codes.keys():
doubles.append(element1 + "|" + element2)
names = (
list(codes.keys()) + doubles
) # Add together all amino acids, ptms, doubles and if wanted triples, although the triples take long to compute.
reduced_matrix = []
for element in names:
m_el1 = find_mass(element.split("|"), codes)
for element2 in names:
m_el2 = find_mass(element2.split("|"), codes)
if -0.01 <= (m_el2 - m_el1) <= 0.01:
if element != element2:
reduced_matrix.append((element2, element, m_el2 - m_el1))
return reduced_matrix
def load_files_mascot(path, name_file): # done
print("open file {}".format(name_file))
found = False
header_row = 0
while found == False:
try:
df = pd.read_csv(name_file, header=header_row)
if "pep_seq" in df.columns:
found = True
else:
header_row += 1
except:
header_row += 1
if header_row > 1000:
break
df = df.fillna("")
charges = df["pep_exp_z"].values
df = df[
["prot_desc", "pep_seq", "pep_var_mod", "pep_var_mod_pos", "pep_scan_title"]
]
df["pep_scan_title"] = [
num.replace("~", '"') for num in df["pep_scan_title"].values
]
df_4_uni = df
df2 = df
protein = {}
unimod_db, unimod = do_unimod(path, df_4_uni["pep_var_mod"].values)
ids = {}
for p, a, m in unimod_db[["PTM", "AA", "mass"]].values:
if a == "N-term":
a = "!"
elif a == "C-term":
a = "*"
add = "?"
while add + a in AA_codes.keys():
add += "?"
if a == "!" or a == "*":
AA_codes[add + a] = float(m)
else:
AA_codes[add + a] = AA_codes[a] + float(m)
ids[add + a] = p
adj_pep = []
for i, peptide in enumerate(df2["pep_seq"].values):
adjusted_pept = ""
for AA in peptide:
adjusted_pept += AA + "|"
adj_pep.append(adjusted_pept[:-1])
df2["adj"] = np.array(adj_pep)
df2["charge"] = charges
return df, df2, unimod_db, protein, ids, adj_pep
def load_files_maxquant(path, name_file): # done
print("open benchmark file")
# name_file = name of the file benchmark
MQ_file = maxquant.io.read_maxquant(name_file)
MQ_file = MQ_file[
["Sequence", "Modified sequence", "Raw file", "Charge", "Modifications"]
]
MQ_file.columns = ["pep_seq", "pep_var_mod_pos", "pep_scan_title", "charge", "mods"]
MQ_file = MQ_file.fillna("")
MQ_file["prot_tax_str"] = ["no species"] * len(MQ_file)
MQ_file["prot_desc"] = ["no description"] * len(MQ_file)
MQ_file["prot_seq"] = ["no seq"] * len(MQ_file)
add_mods = []
change_position = []
for m, mp in MQ_file[["mods", "pep_var_mod_pos"]].values:
if m == "Unmodified":
m = ""
m = str(m)
if "Hydroxyproline" in m:
m = m.replace("Hydroxyproline", "Oxidation (P)")
if "," in m:
m = m.replace(",", "; ")
if "Deamidation" in m:
m = m.replace("Deamidation", "Deamidated")
if "Glu->pyro-Glu" in m:
m = m.replace("Glu->pyro-Glu", "Glu->pyro-Glu (E)")
if "Gln->pyro-Glu" in m:
m = m.replace("Gln->pyro-Glu", "Gln->pyro-Glu (Q)")
add_mods.append(m)
temp = ""
mp = mp.replace("_(", "&")
for t in mp.split("("):
if ")" in t:
t = t.split(")")
for t2 in t:
if t2.lower() == t2:
temp += "&"
else:
temp += t2
else:
temp += t
mp = temp
temp = ""
for i in range(0, len(mp)):
if i == 0 and mp[i] == "_":
temp += "0."
elif i == 0 and mp[i] == "&":
temp += "1."
elif i == len(mp) - 1 and mp[i] == "_":
temp += ".0"
elif mp[i] == "&":
temp += "1"
else:
temp += "0"
change_position.append(temp)
MQ_file["pep_var_mod_pos_old"] = MQ_file["pep_var_mod_pos"].values
MQ_file["pep_var_mod_pos"] = change_position
MQ_file["pep_var_mod"] = add_mods
df = MQ_file
# pep_var_mod aanpassen
# add pep_var_mod_pos
df_4_uni = df[
[
"prot_tax_str",
"prot_desc",
"prot_seq",
"pep_seq",
"pep_var_mod",
"pep_var_mod_pos",
]
]
df2 = MQ_file
protein = {}
unimod_db, unimod = do_unimod(path, df_4_uni["pep_var_mod"].values)
ids = {}
for p, a, m in unimod_db[["PTM", "AA", "mass"]].values:
if a == "N-term":
a = "!"
elif a == "C-term":
a = "&"
add = "?"
while add + a in AA_codes.keys():
add += "?"
if a == "!" or a == "&":
AA_codes[add + a] = float(m)
else:
AA_codes[add + a] = AA_codes[a] + float(m)
ids[add + a] = p
adj_pep = []
for i, peptide in enumerate(df2["pep_seq"].values):
adjusted_pept = ""
for AA in peptide:
adjusted_pept += AA + "|"
adj_pep.append(adjusted_pept[:-1])
df2["adj"] = np.array(adj_pep)
return df, df2, unimod_db, protein, ids, adj_pep
def animals_from_db_input(sequence_db, lim_t, demo): # done
if lim_t == None:
print("searching against all species in the database")
else:
print("Making selection of {} and random other species".format(lim_t))
lim_t = lim_t.split("|")
input_animals = ["Pseudomonas aeruginosa", "Sus scrofa"]
skip_animals = []
Class = {}
for sequence, name in sequence_db.items():
if "OS=" in name:
anim = name.split("OS=")[-1]
anim = anim.split(" OX=")[0]
elif "[" in name:
anim = name.split("[")[1]
anim = anim.split("]")[0]
elif "|" in name:
anim = name.split("|")[1]
else:
print("{} has no species".format(name))
if anim not in input_animals and anim not in skip_animals:
if lim_t == None:
input_animals.append(anim)
continue
ncbi_animal = anim
found = False
while found == False:
try:
taxon = taxoniq.Taxon(scientific_name=ncbi_animal)
found = True
taxon = [(t.rank.name, t.scientific_name) for t in taxon.lineage]
added_to_input = False
added_to_random = False
for tax in taxon:
for lt in lim_t:
if lt in tax:
added_to_input = True
print(
"Adding {} because it is within {}".format(
anim, lim_t
)
)
input_animals.append(anim)
added_to_random = True
if "class" in tax and added_to_random == False:
added_to_random = True
if tax[1] not in Class.keys():
Class[tax[1]] = []
Class[tax[1]] = Class[tax[1]] + [anim]
if added_to_input == False:
skip_animals.append(anim)
except:
ncbi_animal = " ".join(ncbi_animal.split(" ")[:-1])
if len(ncbi_animal) == 0:
found = True
print("Species {} has no taxonomy".format(anim))
skip_animals.append(anim)
if (lim_t != None and demo == False) or (demo == True and lim_t != "Pecora"):
for k, v in Class.items():
print(k)
random.shuffle(v)
random_animals = v[:15]
input_animals = list(set(input_animals) | set(random_animals))
skip_animals = list(set(skip_animals) ^ set(random_animals))
return list(set(input_animals)), list(set(skip_animals))
def find_mass_matches(sequence, p_mass, mods, pep, unimod_db, AA_codes, uncertain):
start = 0
end = len(sequence)
possible = []
temp = 1
unimod_masses = [0]
# for mass,mod,aa in unimod_db[['mass','PTM','AA']].values:#seach for peptide seq that explain masses of ptms+seq
# if mod+'_'+aa in mods.keys() and aa in pep: #only if PTM also in sequence
# for i in range(1,mods[mod+'_'+aa]+1):
# unimod_masses.append(float(mass)*i)#PTM-> no PTM
unimod_masses = unimod_masses + [
num - t for num in unimod_masses for t in unimod_db["mass"].values
] # ptms added is lower backbone mass
unimod_masses = unimod_masses + [
num - t for num in unimod_masses for t in unimod_db["mass"].values
] # 2 ptms added is lower backbone mass
unimod_masses = set(unimod_masses)
while start + temp <= end:
test_seq = sequence[start : start + temp] # stepwise window slide
if len(test_seq) > len(pep) + 1:
start += 1
temp -= 1
continue
unkown = False
if (
str(re.search("[" + "".join(uncertain.keys()) + "]", str(test_seq)))
!= "None"
or len(set(test_seq) & set(uncertain.keys())) > 0
):
keep_seq = test_seq
other_seq = "".join([el for el in test_seq if el in uncertain.keys()])
test_seq = "".join([el for el in test_seq if el not in uncertain.keys()])
unkown = True
test = find_mass(test_seq, AA_codes)
if unkown == True:
missing_mass = p_mass - test
missing_mass = [missing_mass - num for num in unimod_masses]
checks = other_seq
other_seq = [uncertain[el] for el in other_seq]
poss_seqs = []
if (
len(other_seq) < 2 or checks.count("X") <= 1
): # only allow 1 X else everything will start to fit and to many possibilities
for l in range(0, (len(other_seq))):
if len(poss_seqs) == 0:
poss_seqs = [num for num in other_seq[l]]
else:
poss_seqs = [
num + el for num in poss_seqs for el in other_seq[l]
]
added = False
mass_too_much = False
for x in poss_seqs:
if True in [
(
True
if num - 0.015
<= (test - p_mass + find_mass(x, AA_codes))
<= num + 0.015
else False
)
for num in unimod_masses
]:
new_seq = "".join(
[num if num in AA_codes.keys() else "!" for num in keep_seq]
)
add_seq = ""
count_x = 0
for m in new_seq:
if m == "!":
add_seq += x[count_x]
count_x += 1
else:
add_seq += m
possible.append((add_seq, (start, start + temp)))
if added == False:
start += 1
temp = 1
added = True
elif p_mass > (test + find_mass(x, AA_codes)):
mass_too_much = True
if added == False and mass_too_much == True:
temp += 1
elif added == False:
start += 1
temp -= 1
elif True in [
True if num - 0.015 <= test - p_mass <= num + 0.015 else False
for num in unimod_masses
]: # go if same mass or with a new ptm or without an existing one
possible.append((test_seq, (start, start + temp)))
start += 1
temp = 1
elif test < p_mass: # slide like a caterpilar
temp += 1
else:
start += 1
temp -= 1
return possible
def assign_pairs(index_to2, seq_real, check_seq):
seq_real += "-"
check_seq += "-"
seq_real_new = []
for i in index_to2:
seq_real_new.append((seq_real[i], (i - 1, i)))
seq_real_new.append((seq_real[i], (i, i + 1)))
if i > 1 and i < len(seq_real) - 3:
extra = 0
extra2 = 0
extra3 = 0
if seq_real[i + 1] == "-":
extra = 1
if check_seq[i + 1 + extra] == "-":
extra2 = 1
if check_seq[i + 2 + extra] == "-":
extra3 = 1
seq_real_new.append(
(seq_real[i] + seq_real[i + 1 + extra], (i, i + 1 + extra + extra2))
) # recht 1
seq_real_new.append(
(seq_real[i] + seq_real[i + 2 + extra], (i, i + 2 + extra + extra3))
) # rechts 2
extra = 0
extra2 = 0
extra3 = 0
if seq_real[i - 1] == "-":
extra = 1
if check_seq[i - 1 - extra] == "-":
extra2 = 1
if check_seq[i - 2 - extra] == "-":
extra3 = 1
seq_real_new.append(
(seq_real[i - 1 - extra] + seq_real[i], (i - extra - 1 - extra2, i))
) # links 1
seq_real_new.append(
(seq_real[i - 2 - extra] + seq_real[i], (i - extra - 2 - extra3, i))
) # links 2
elif i == 0:
extra = 0
extra2 = 0
extra3 = 0
if seq_real[i + 1] == "-":
extra = 1
if check_seq[i + 1 + extra] == "-":
extra2 = 1
if check_seq[i + 2 + extra] == "-":
extra3 = 1
seq_real_new.append(
(seq_real[i] + seq_real[i + 1 + extra], (i, i + 1 + extra + extra2))
) # rechts 1
seq_real_new.append(
(seq_real[i] + seq_real[i + 2 + extra], (i, i + 2 + extra + extra3))
) # rechts 2
elif i == len(seq_real) - 1:
extra = 0
extra2 = 0
extra3 = 0
if seq_real[i - 1] == "-":
extra = 1
if check_seq[i - 1 - extra] == "-":
extra2 = 1
if check_seq[i - 2 - extra] == "-":
extra3 = 1
seq_real_new.append(
(seq_real[i - 1 - extra] + seq_real[i], (i - extra - 1 - extra2, i))
) # links 1
seq_real_new.append(
(seq_real[i - 2 - extra] + seq_real[i], (i - extra - 2 - extra3, i))
) # links 2
elif i == 1:
extra = 0
extra2 = 0
extra3 = 0
if seq_real[i + 1] == "-":
extra = 1
if check_seq[i + 1 + extra] == "-":
extra2 = 1
if check_seq[i + 2 + extra] == "-":
extra3 = 1
seq_real_new.append(
(seq_real[i] + seq_real[i + 1 + extra], (i, i + 1 + extra + extra2))
) # rechts 1
seq_real_new.append(
(seq_real[i] + seq_real[i + 2 + extra], (i, i + 2 + extra + extra3))
) # rechts 2
if seq_real[0] != "-":
seq_real_new.append(
(seq_real[i - 1] + seq_real[i], (i - 1, i))
) # links 1
elif i == len(seq_real) - 2:
extra = 0
extra2 = 0
extra3 = 0
if seq_real[i - 1] == "-":
extra = 1
if check_seq[i - 1 - extra] == "-":
extra2 = 1
if check_seq[i - 2 - extra] == "-":
extra3 = 1
seq_real_new.append(
(seq_real[i - 1 - extra] + seq_real[i], (i - extra - 1 - extra2, i))
) # links 1
seq_real_new.append(
(seq_real[i - 2 - extra] + seq_real[i], (i - extra - 2 - extra3, i))
) # links 2
extra = 0
if seq_real[-1] != "-":
seq_real_new.append(
(seq_real[i] + seq_real[i + 1 + extra], (i, i + 1 + extra))
) # recht 1
return seq_real_new
def program(
seq_db, seq_real, peptides, mass_matrix
): # compare in-silico peptide with the found peptide
# code below looks for where the differences are between the sequences, and includes adjecent amino acids to check aswel
seq_db_new = []
index_to2 = [loc for loc in range(0, len(seq_db)) if seq_db[loc] == "-"]
index_to1 = [loc for loc in range(0, len(seq_real)) if seq_real[loc] == "-"]
if (
len(index_to2) > 4 or len(index_to1) > 4
): # more than 5 different locations is too much
return False, [], [], []
seq_real_new = assign_pairs(index_to2, seq_real, seq_db)
seq_db_new = assign_pairs(index_to1, seq_db, seq_db)
seq_1 = [num for num, loc in seq_db_new]
seq_2 = [num for num, loc in seq_real_new]
adaptation_db = []
adaptation_real = []
combo = []
for (
l,
r,
m,
) in mass_matrix: # check for all diferences if they explain isobaric changes
l1 = l.replace("|", "")
r1 = r.replace("|", "")
if "?" in l1:
l1 = l1.replace("?", "")
if "?" in r1:
r1 = r1.replace("?", "")
if l1 not in seq_1:
continue
if l1 in seq_1 and r1 in seq_2:
adaptation_real.append(r1) # find isobaric
adaptation_db.append(l1)
combo.append((l, r))
if len(adaptation_real) == 0 or len(adaptation_db) == 0:
return False, [], [], []
adaptation_real = [num for num in seq_real_new if num[0] in adaptation_real]
adaptation_db = [num for num in seq_db_new if num[0] in adaptation_db]
return True, adaptation_real, adaptation_db, combo
def do_alignment(s1, s2): # observed, db
# align the sequences based on perfect matching, is quicker and better for our purposes than global alignment van de Bio package
s1 = [num for num in s1]
s2 = [num for num in s2]
s1_align = ""
s2_align = ""
loc_s2 = 0
loc_s1 = 0
while loc_s2 < min(len(s2), len(s1)) and loc_s1 < min(len(s2), len(s1)):
if s1[loc_s1] == s2[loc_s2]:
s1_align += s1[loc_s1]
s2_align += s2[loc_s2]
elif loc_s1 < len(s1) - 1 and loc_s2 < len(s2) - 1:
if s1[loc_s1 + 1] == s2[loc_s2]:
s1_align += s1[loc_s1] + s1[loc_s1 + 1]
s2_align += "-" + s2[loc_s2]
loc_s1 += 1
elif s1[loc_s1] == s2[loc_s2 + 1]:
s2_align += s2[loc_s2] + s2[loc_s2 + 1]
s1_align += "-" + s1[loc_s1]
loc_s2 += 1
else:
s1_align += s1[loc_s1] + "-"
s2_align += "-" + s2[loc_s2]
else:
s1_align += "-" + s1[loc_s1]
s2_align += s2[loc_s2] + "-"
loc_s1 += 1
loc_s2 += 1
while loc_s1 != len(s1):
s1_align += s1[loc_s1]
s2_align += "-"
loc_s1 += 1
while loc_s2 != len(s2):
s2_align += s2[loc_s2]
s1_align += "-"
loc_s2 += 1
return (s1_align, s2_align)
def locate_switches(adapt_observed, adapt_db, seq_observed, seq_db, combo):
# of all possibilities found, check if the isobaric switch can occur at the location AND chose the smallest isobaric switch
covering_seq = ""
for i in range(
0, len(seq_db)
): # make one lin sequence that is like a stitched version of both sequences
if seq_db[i] == "-":
covering_seq += seq_observed[i]
else:
covering_seq += seq_db[i]
adapt_observed = sorted(
adapt_observed, key=lambda x: len(x[0])
) # 1 amino acid switches are preferred to multiple
adapt_db = sorted(adapt_db, key=lambda x: len(x[0]))
index_to1 = [
loc for loc in range(0, len(seq_observed)) if seq_observed[loc] == "-"
] # all indexes that are gaps in seq_observed
possible = []
include_ptm = []
fixed_it = {}
for i in index_to1: # find an explanation for each of the gaps
fixed = False
fixed_it[i] = False
for (
n
) in (
adapt_db
): # for each of the isobaric switches in adapt_db look if they fit the gap
if i in n[1] and fixed == False:
new_loc = [x for x in n[1] if x != i]
for t in adapt_observed:
if (
new_loc[0] in t[1]
and -1 not in t[1]
and len(covering_seq) not in t[1]
):
annot_check = [
(
True
if "".join([x for x in num[0] if x.isalpha()]) == n[0]
and "".join([x for x in num[1] if x.isalpha()]) == t[0]
else False
)
for num in combo
]
if True not in annot_check:
continue
annot = [
num
for loc_annot, num in enumerate(combo)
if annot_check[loc_annot] == True
]
if n[1] == t[1] and len(n[0]) == 1: # 1 VS 1
test1 = n[0] + t[0]
test2 = t[0] + n[0]
if (
test1[0] == covering_seq[new_loc[0]]
and test1[1] == covering_seq[i]
):
fixed = True
fixed_it[i] = True
possible.append(
"from " + annot[0][0] + " to " + annot[0][1]
)
if "?" in annot[0][0] or "?" in annot[0][1]:
include_ptm.append(
(annot[0][0], annot[0][1], (new_loc[0], i))
)
break
else:
test2[0] == covering_seq[new_loc[0]] and test2[
1
] == covering_seq[i]
fixed = True
fixed_it[i] = True
possible.append(
"from " + annot[0][1] + " to " + annot[0][0]
)
if "?" in annot[0][0] or "?" in annot[0][1]:
include_ptm.append(
(annot[0][1], annot[0][0], (new_loc[0], i))
)
break
else: # >=1 VS >1
temp = ""
for z in range(0, len(covering_seq)):
if z in n[1]:
if len(n[0]) == 1:
search = 0
else:
search = n[1].index(z)
temp += n[0][search]
elif z in t[1]:
if len(t[0]) == 1:
search = 0
else:
search = t[1].index(z)
temp += t[0][search]
else:
temp += covering_seq[z]
if temp == covering_seq:
possible.append(
"from " + annot[0][1] + " to " + annot[0][0]
)
fixed = True
fixed_it[i] = True
if "?" in annot[0][0] or "?" in annot[0][1]:
include_ptm.append(
(annot[0][1], annot[0][0], (new_loc[0], i))
)
break
if (
False in fixed_it.values() or len(possible) == 0
): # means that the sequences was not filled in properly
return [], False, ""
# return the good annotations
return possible, True, include_ptm
def find_ptm_location(ptm, seq, unimod_db, mascot_pos, ids, ptm2=[]):
if len(mascot_pos) > 0:
mascot_pos = mascot_pos.split(".")[1]
else:
mascot_pos = "0" * len(seq)
loc_str = ""
minus = []
extra_mass = 0
if len(ptm2) > 0:
for i in ptm2:
if "?" in i[1]:
temp = seq[min(i[2]) - 2 : max(i[2])]
temp_lo = ""
for z in i[1]:
if z == "?":
temp_lo += "?"
elif "?" in temp_lo:
lo = z
temp_lo += z
if lo not in temp:
return False, False
found = temp.index(lo)
loc_str += str(found + min(i[2]) - 1) + "|" + ids[temp_lo] + "|"
extra_mass += float(
unimod_db["mass"][
(unimod_db["PTM"] == ids[temp_lo])
& (unimod_db["AA"] == z)
].values
)
temp_lo = ""
if "?" in i[0]:
temp_lo = ""
for z in i[0]:
if z == "?":
temp_lo += z
elif "?" in temp_lo:
temp_lo += z
minus.append((ids[temp_lo], temp_lo))
temp_lo = ""
if len(ptm) > 0:
ptm = ptm.split(";")
for i in ptm:
count = [x for x in i if x.isdigit() == True]
if len(count) > 0:
count = int(count[0])
else:
count = 1
temp = i.split(" (")
for aa, p in unimod_db[["AA", "PTM"]].values:
if p in temp[0] and aa in temp[1]:
if aa == "N-term":
loc_str = "0|" + p + "|" + loc_str
elif aa == "C-term":
loc_str = loc_str + "-1|" + p + "|"
count -= minus.count((p, aa))
if count < 0:
return False, False
if count > 0:
for locs, t in enumerate(seq):
if (
locs > len(mascot_pos) - 1
): # if there is a difference in length
count -= 1
continue
if (
t == aa
and str(locs + 1) not in loc_str.split("|")
and count > 0
and int(mascot_pos[locs]) != 0
):
loc_str += str(locs + 1) + "|" + p + "|"
count -= 1
extra_mass += float(
unimod_db["mass"][
(unimod_db["PTM"] == p)
& (unimod_db["AA"] == aa)
].values
)
temp = loc_str[:-1].split("|")
temps = sorted(
[
(int(temp[i]), (temp[i + 1]))
for i in range(0, len(temp) - 1, 2)
if temp[i] != "-1"
],
key=lambda x: x[0],
)
temps = ["|".join([str(num[0]), num[1]]) for num in temps]
if "-1" in temp:
temps.append("-1|" + temp[temp.index("-1") + 1])
return "|".join(temps), extra_mass
def check_ptms_mascot(
ad, ptm, ids
): # location of ptm in mascot output? If mascot for example doesn't find a deamidation, it means that no deamidation isobaric switch can occur.
checks = []
amount = {}
temp = ptm.split(";")
if len(temp) > 0:
for i in temp:
digit_temp = "".join([num for num in temp if num.isdigit() == True])
if len(digit_temp) > 0:
digit_temp = int(digit_temp)
else:
digit_temp = 1
other = "".join([num for num in temp if num.isdigit() == False])
for k, v in ids.items():
if "".join([num for num in k if num != "?"]) in other and v in other:
amount[k] = digit_temp
for i in ad:
i = i.split("to")[0]
if "?" not in i:
checks.append(True)
else:
temp = ""
for t in i:
if t == "?":
temp += t
elif "?" in temp:
temp += t
test = ids[temp]
if temp not in amount:
checks.append(False)
elif test in ptm and amount[temp] != 0:
checks.append(True)
amount[temp] = amount[temp] - 1
else:
checks.append(False)
temp = ""
if False in checks:
# if len(ptm)>0:
# print('found one that is not possible:',ad,ptm)
# else:
# print('found one that is not possible:',ad,'no mascot ptm')
return False
return True
def ptm_mass(ptm, unimod_db): # add this mass to the mass of the normal sequence
mass = 0
PTMs = {}
if len(ptm) > 0:
for i in ptm.split(";"):
for p, a, m in unimod_db[["PTM", "AA", "mass"]].values:
if p in i and a in i.split("(")[1]:
temp = [x for x in i if x.isdigit() == True]
if len(temp) > 0:
mass += int(temp[0]) * float(m)
PTMs[p + "_" + a] = int(temp[0])
break
else:
mass += float(m)
PTMs[p + "_" + a] = 1
break
return mass, PTMs
def massblast(
db,
ids,
PTMs,
peptides,
p_adjs,