/
crosslink.py
2096 lines (1883 loc) · 84.8 KB
/
crosslink.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
"""@namespace IMP.pmi.io.crosslink
Handles cross-link data sets.
Utilities are also provided to help in the analysis of models that
contain cross-links.
"""
from __future__ import print_function
import IMP
import IMP.pmi
import IMP.pmi.output
import IMP.pmi.alphabets
import IMP.atom
import IMP.core
import IMP.algebra
import IMP.rmf
import RMF
import IMP.display
import operator
import math
import sys
import ihm.location
import ihm.dataset
from collections import defaultdict
import numpy
# json default serializations
def set_json_default(obj):
if isinstance(obj, set):
return list(obj)
if isinstance(obj, IMP.pmi.topology.Molecule):
return str(obj)
raise TypeError
# Handle and return data that must be a string
if sys.version_info[0] >= 3:
def _handle_string_input(inp):
if not isinstance(inp, str):
raise TypeError("expecting a string")
return inp
else:
def _handle_string_input(inp):
if not isinstance(inp, (str, unicode)): # noqa: F821
raise TypeError("expecting a string or unicode")
# Coerce to non-unicode representation (str)
if isinstance(inp, unicode): # noqa: F821
return str(inp)
else:
return inp
class _CrossLinkDataBaseStandardKeys(object):
'''
This class setup all the standard keys needed to
identify the cross-link features from the data sets
'''
def __init__(self):
self.type = {}
self.protein1_key = "Protein1"
self.type[self.protein1_key] = str
self.protein2_key = "Protein2"
self.type[self.protein2_key] = str
self.residue1_key = "Residue1"
self.type[self.residue1_key] = int
self.residue2_key = "Residue2"
self.type[self.residue2_key] = int
self.residue1_amino_acid_key = "Residue1AminoAcid"
self.type[self.residue1_amino_acid_key] = str
self.residue2_amino_acid_key = "Residue2AminoAcid"
self.type[self.residue2_amino_acid_key] = str
self.residue1_moiety_key = "Residue1Moiety"
self.type[self.residue1_moiety_key] = str
self.residue2_moiety_key = "Residue2Moiety"
self.type[self.residue2_moiety_key] = str
self.site_pairs_key = "SitePairs"
self.type[self.site_pairs_key] = str
self.unique_id_key = "XLUniqueID"
self.type[self.unique_id_key] = str
self.unique_sub_index_key = "XLUniqueSubIndex"
self.type[self.unique_sub_index_key] = int
self.unique_sub_id_key = "XLUniqueSubID"
self.type[self.unique_sub_id_key] = str
self.data_set_name_key = "DataSetName"
self.type[self.data_set_name_key] = str
self.cross_linker_chemical_key = "CrossLinkerChemical"
self.type[self.cross_linker_chemical_key] = str
self.id_score_key = "IDScore"
self.type[self.id_score_key] = float
self.fdr_key = "FDR"
self.type[self.fdr_key] = float
self.quantitation_key = "Quantitation"
self.type[self.quantitation_key] = float
self.redundancy_key = "Redundancy"
self.type[self.redundancy_key] = int
self.redundancy_list_key = "RedundancyList"
self.type[self.redundancy_key] = list
self.ambiguity_key = "Ambiguity"
self.type[self.ambiguity_key] = int
self.residue1_links_number_key = "Residue1LinksNumber"
self.type[self.residue1_links_number_key] = int
self.residue2_links_number_key = "Residue2LinksNumber"
self.type[self.residue2_links_number_key] = int
self.type[self.ambiguity_key] = int
self.state_key = "State"
self.type[self.state_key] = int
self.sigma1_key = "Sigma1"
self.type[self.sigma1_key] = str
self.sigma2_key = "Sigma2"
self.type[self.sigma2_key] = str
self.psi_key = "Psi"
self.type[self.psi_key] = str
self.distance_key = "Distance"
self.type[self.distance_key] = float
self.min_ambiguous_distance_key = "MinAmbiguousDistance"
self.type[self.distance_key] = float
# link types are either Monolink, Intralink or Interlink
self.link_type_key = "LinkType"
self.type[self.link_type_key] = str
self.ordered_key_list = [
self.data_set_name_key, self.unique_id_key,
self.unique_sub_index_key, self.unique_sub_id_key,
self.protein1_key, self.protein2_key, self.residue1_key,
self.residue2_key, self.residue1_amino_acid_key,
self.residue2_amino_acid_key, self.residue1_moiety_key,
self.residue2_moiety_key, self.cross_linker_chemical_key,
self.id_score_key, self.fdr_key, self.quantitation_key,
self.redundancy_key, self.redundancy_list_key, self.state_key,
self.sigma1_key, self.sigma2_key, self.psi_key, self.distance_key,
self.min_ambiguous_distance_key, self.link_type_key]
class _ProteinsResiduesArray(tuple):
'''
This class is inherits from tuple, and it is a shorthand for a cross-link
(p1,p2,r1,r2) or a monolink (p1,r1) where p1 and p2 are protein1
and protein2, r1 and r2 are residue1 and residue2.
'''
def __new__(self, input_data):
'''
@input_data can be a dict or a tuple
'''
self.cldbsk = _CrossLinkDataBaseStandardKeys()
if type(input_data) is dict:
monolink = False
p1 = input_data[self.cldbsk.protein1_key]
try:
p2 = input_data[self.cldbsk.protein2_key]
except KeyError:
monolink = True
r1 = input_data[self.cldbsk.residue1_key]
try:
r2 = input_data[self.cldbsk.residue2_key]
except KeyError:
monolink = True
if not monolink:
t = (p1, p2, r1, r2)
else:
t = (p1, "", r1, None)
elif type(input_data) is tuple:
if len(input_data) > 4 or len(input_data) == 3 \
or len(input_data) == 1:
raise TypeError(
"_ProteinsResiduesArray: must have only 4 elements")
if len(input_data) == 4:
p1 = _handle_string_input(input_data[0])
p2 = _handle_string_input(input_data[1])
r1 = input_data[2]
r2 = input_data[3]
if (type(r1) is not int) and (r1 is not None):
raise TypeError(
"_ProteinsResiduesArray: residue1 must be a integer")
if (type(r2) is not int) and (r1 is not None):
raise TypeError(
"_ProteinsResiduesArray: residue2 must be a integer")
t = (p1, p2, r1, r2)
if len(input_data) == 2:
p1 = _handle_string_input(input_data[0])
r1 = input_data[1]
if type(r1) is not int:
raise TypeError(
"_ProteinsResiduesArray: residue1 must be a integer")
t = (p1, "", r1, None)
else:
raise TypeError(
"_ProteinsResiduesArray: input must be a dict or tuple")
return tuple.__new__(_ProteinsResiduesArray, t)
def get_inverted(self):
'''
Returns a _ProteinsResiduesArray instance with protein1 and
protein2 inverted
'''
return _ProteinsResiduesArray((self[1], self[0], self[3], self[2]))
def __repr__(self):
outstr = self.cldbsk.protein1_key + " " + str(self[0])
outstr += " " + self.cldbsk.protein2_key + " " + str(self[1])
outstr += " " + self.cldbsk.residue1_key + " " + str(self[2])
outstr += " " + self.cldbsk.residue2_key + " " + str(self[3])
return outstr
def __str__(self):
outstr = str(self[0]) + "." + str(self[2]) + "-" + str(self[1]) \
+ "." + str(self[3])
return outstr
class FilterOperator(object):
'''
This class allows to create filter functions that can be passed to
the CrossLinkDataBase in this way:
fo=FilterOperator(cldb.protein1_key,operator.eq,"AAA")|FilterOperator(cldb.protein2_key,operator.eq,"BBB")
where cldb is CrossLinkDataBase instance and it is only needed to get
the standard keywords
A filter operator can be evaluate on a CrossLinkDataBase item xl and
returns a boolean
fo.evaluate(xl)
and it is used to filter the database
'''
def __init__(self, argument1, operator, argument2):
'''
(argument1,operator,argument2) can be either a
(keyword,operator.eq|lt|gt...,value)
or (FilterOperator1,operator.or|and...,FilterOperator2)
'''
if isinstance(argument1, FilterOperator):
self.operations = [argument1, operator, argument2]
else:
self.operations = []
self.values = (argument1, operator, argument2)
def __or__(self, FilterOperator2):
return FilterOperator(self, operator.or_, FilterOperator2)
def __and__(self, FilterOperator2):
return FilterOperator(self, operator.and_, FilterOperator2)
def __invert__(self):
return FilterOperator(self, operator.not_, None)
def evaluate(self, xl_item):
if len(self.operations) == 0:
keyword, operator, value = self.values
return operator(xl_item[keyword], value)
FilterOperator1, op, FilterOperator2 = self.operations
if FilterOperator2 is None:
return op(FilterOperator1.evaluate(xl_item))
else:
return op(FilterOperator1.evaluate(xl_item),
FilterOperator2.evaluate(xl_item))
class CrossLinkDataBaseKeywordsConverter(_CrossLinkDataBaseStandardKeys):
'''
This class is needed to convert the keywords from a generic database
to the standard ones
'''
def __init__(self, list_parser=None):
'''
@param list_parser an instance of ResiduePairListParser, if any
is needed
'''
self.converter = {}
self.backward_converter = {}
_CrossLinkDataBaseStandardKeys.__init__(self)
self.rplp = list_parser
if self.rplp is None:
# either you have protein1, protein2, residue1, residue2
self.compulsory_keys = set([self.protein1_key,
self.protein2_key,
self.residue1_key,
self.residue2_key])
else:
self.compulsory_keys = self.rplp.get_compulsory_keys()
self.setup_keys = set()
def check_keys(self):
'''
Is a function that check whether necessary keys are setup
'''
setup_keys = set(self.get_setup_keys())
if self.compulsory_keys & setup_keys != self.compulsory_keys:
raise KeyError("CrossLinkDataBaseKeywordsConverter: must setup "
"all necessary keys")
def get_setup_keys(self):
'''
Returns the keys that have been setup so far
'''
return self.backward_converter.keys()
def set_standard_keys(self):
"""
This sets up the standard compulsory keys as defined by
_CrossLinkDataBaseStandardKeys
"""
for ck in self.compulsory_keys:
self.converter[ck] = ck
self.backward_converter[ck] = ck
def set_unique_id_key(self, origin_key):
self.converter[origin_key] = self.unique_id_key
self.backward_converter[self.unique_id_key] = origin_key
def set_protein1_key(self, origin_key):
self.converter[origin_key] = self.protein1_key
self.backward_converter[self.protein1_key] = origin_key
def set_protein2_key(self, origin_key):
self.converter[origin_key] = self.protein2_key
self.backward_converter[self.protein2_key] = origin_key
def set_residue1_key(self, origin_key):
self.converter[origin_key] = self.residue1_key
self.backward_converter[self.residue1_key] = origin_key
def set_residue2_key(self, origin_key):
self.converter[origin_key] = self.residue2_key
self.backward_converter[self.residue2_key] = origin_key
def set_residue1_amino_acid_key(self, origin_key):
self.converter[origin_key] = self.residue1_amino_acid_key
self.backward_converter[self.residue1_amino_acid_key] = origin_key
def set_residue2_amino_acid_key(self, origin_key):
self.converter[origin_key] = self.residue2_amino_acid_key
self.backward_converter[self.residue2_amino_acid_key] = origin_key
def set_residue1_moiety_key(self, origin_key):
self.converter[origin_key] = self.residue1_moiety_key
self.backward_converter[self.residue1_moiety_key] = origin_key
def set_residue2_moiety_key(self, origin_key):
self.converter[origin_key] = self.residue2_moiety_key
self.backward_converter[self.residue2_moiety_key] = origin_key
def set_site_pairs_key(self, origin_key):
self.converter[origin_key] = self.site_pairs_key
self.backward_converter[self.site_pairs_key] = origin_key
def set_id_score_key(self, origin_key):
self.converter[origin_key] = self.id_score_key
self.backward_converter[self.id_score_key] = origin_key
def set_fdr_key(self, origin_key):
self.converter[origin_key] = self.fdr_key
self.backward_converter[self.fdr_key] = origin_key
def set_quantitation_key(self, origin_key):
self.converter[origin_key] = self.quantitation_key
self.backward_converter[self.quantitation_key] = origin_key
def set_psi_key(self, origin_key):
self.converter[origin_key] = self.psi_key
self.backward_converter[self.psi_key] = origin_key
def set_link_type_key(self, link_type_key):
self.converter[link_type_key] = self.link_type_key
self.backward_converter[self.link_type_key] = link_type_key
def get_converter(self):
'''
Returns the dictionary that convert the old keywords to the new ones
'''
self.check_keys()
return self.converter
def get_backward_converter(self):
'''
Returns the dictionary that convert the new keywords to the old ones
'''
self.check_keys()
return self.backward_converter
class ResiduePairListParser(_CrossLinkDataBaseStandardKeys):
'''
A class to handle different styles of site pairs parsers.
Implemented styles:
MSSTUDIO: [Y3-S756;Y3-K759;K4-S756;K4-K759] for cross-links
[Y3-;K4-] for dead-ends
QUANTITATION: sp|P33298|PRS6B_YEAST:280:x:sp|P33298|PRS6B_YEAST:337
QUANTITATION (with ambiguity separator :|:): Fbw7:107:|:StrepII2x-Fbw7fl:408:x:Nedd8:48
LAN_HUANG: PROT1:C88-PROT2:C448 ambiguous separators | or ;
''' # noqa: E501
import re
def __init__(self, style):
_CrossLinkDataBaseStandardKeys.__init__(self)
if style == "MSSTUDIO":
self.style = style
self.compulsory_keys = set([self.protein1_key,
self.protein2_key,
self.site_pairs_key])
elif style == "XTRACT" or style == "QUANTITATION":
self.style = style
self.compulsory_keys = set([self.site_pairs_key])
elif style == "LAN_HUANG":
self.style = style
self.compulsory_keys = set([self.site_pairs_key])
else:
raise Exception("ResiduePairListParser: unknown list parser style")
def get_compulsory_keys(self):
return self.compulsory_keys
def get_list(self, input_string):
'''
This function returns a list of cross-linked residues and the
corresponding list of cross-linked chains. The latter list can be
empty, if the style doesn't have the corresponding information.
'''
if self.style == "MSSTUDIO":
input_string = input_string.replace("[", "")
input_string = input_string.replace("]", "")
input_string_pairs = input_string.split(";")
residue_pair_indexes = []
chain_pair_indexes = []
for s in input_string_pairs:
m1 = self.re.search(
r'^(A|C|D|E|F|G|H|I|K|L|M|N|O|P|Q|R|S|T|Y|X|W)'
r'(\d+)-(A|C|D|E|F|G|H|I|K|L|M|N|O|P|Q|R|S|T|Y|X|W)(\d+)$',
s)
m2 = self.re.search(
r'^(A|C|D|E|F|G|H|I|K|L|M|N|O|P|Q|R|S|T|Y|X|W)(\d+)-$', s)
if m1:
# cross-link
(residue_type_1, residue_index_1, residue_type_2,
residue_index_2) = m1.group(1, 2, 3, 4)
residue_pair_indexes.append((residue_index_1,
residue_index_2))
elif m2:
# dead end
residue_type_1, residue_index_1 = m2.group(1, 2)
# at this stage chain_pair_indexes is empty
return residue_pair_indexes, chain_pair_indexes
if self.style == "XTRACT" or self.style == "QUANTITATION":
if ":x:" in input_string:
# if it is a cross-link....
input_strings = input_string.split(":x:")
first_peptides = input_strings[0].split(":|:")
second_peptides = input_strings[1].split(":|:")
first_peptides_identifiers = [
(f.split(":")[0],
f.split(":")[1]) for f in first_peptides]
second_peptides_identifiers = [
(f.split(":")[0],
f.split(":")[1]) for f in second_peptides]
residue_pair_indexes = []
chain_pair_indexes = []
for fpi in first_peptides_identifiers:
for spi in second_peptides_identifiers:
chain1 = fpi[0]
chain2 = spi[0]
residue1 = fpi[1]
residue2 = spi[1]
residue_pair_indexes.append((residue1, residue2))
chain_pair_indexes.append((chain1, chain2))
return residue_pair_indexes, chain_pair_indexes
else:
# if it is a monolink....
first_peptides = input_string.split(":|:")
first_peptides_identifiers = [
(f.split(":")[0], f.split(":")[1]) for f in first_peptides]
residue_indexes = []
chain_indexes = []
for fpi in first_peptides_identifiers:
chain1 = fpi[0]
residue1 = fpi[1]
residue_indexes.append((residue1,))
chain_indexes.append((chain1,))
return residue_indexes, chain_indexes
if self.style == "LAN_HUANG":
input_strings = input_string.split("-")
chain1, first_series = input_strings[0].split(":")
chain2, second_series = input_strings[1].split(":")
first_residues = first_series.replace(";", "|").split("|")
second_residues = second_series.replace(";", "|").split("|")
residue_pair_indexes = []
chain_pair_indexes = []
for fpi in first_residues:
for spi in second_residues:
residue1 = self.re.sub("[^0-9]", "", fpi)
residue2 = self.re.sub("[^0-9]", "", spi)
residue_pair_indexes.append((residue1, residue2))
chain_pair_indexes.append((chain1, chain2))
return residue_pair_indexes, chain_pair_indexes
class FixedFormatParser(_CrossLinkDataBaseStandardKeys):
'''
A class to handle different XL format with fixed format
currently support ProXL
'''
def __init__(self, format):
_CrossLinkDataBaseStandardKeys.__init__(self)
if format == "PROXL":
self.format = format
else:
raise Exception("FixedFormatParser: unknown list format name")
def get_data(self, input_string):
if self.format == "PROXL":
tokens = input_string.split("\t")
xl = {}
if tokens[0] == "SEARCH ID(S)":
return None
else:
xl[self.protein1_key] = tokens[2]
xl[self.protein2_key] = tokens[4]
xl[self.residue1_key] = int(tokens[3])
xl[self.residue2_key] = int(tokens[5])
return xl
class CrossLinkDataBase(_CrossLinkDataBaseStandardKeys):
'''
this class handles a cross-link dataset and do filtering
operations, adding cross-links, merge datasets...
'''
def __init__(self, converter=None, data_base=None, fasta_seq=None,
linkable_aa=('K',)):
'''
Constructor.
@param converter an instance of CrossLinkDataBaseKeywordsConverter
@param data_base an instance of CrossLinkDataBase to build the
new database on
@param fasta_seq an instance of IMP.pmi.topology.Sequences containing
protein fasta sequences to check cross-link consistency.
If not given consistency will not be checked
@param linkable_aa a tuple containing one-letter amino acids which
are linkable by the cross-linker; only used if the database
DOES NOT provide a value for a certain residueX_amino_acid_key
and if a fasta_seq is given
'''
if data_base is None:
self.data_base = {}
else:
self.data_base = data_base
_CrossLinkDataBaseStandardKeys.__init__(self)
if converter is not None:
self.cldbkc = converter # type: CrossLinkDataBaseKeywordsConverter
self.list_parser = self.cldbkc.rplp
self.converter = converter.get_converter()
else:
self.cldbkc = None # type: CrossLinkDataBaseKeywordsConverter
self.list_parser = None
self.converter = None
# default amino acids considered to be 'linkable' if none are given
self.def_aa_tuple = linkable_aa
self.fasta_seq = fasta_seq # type: IMP.pmi.topology.Sequences
self.dataset = None
self.name = None
self._update()
def _update(self):
'''
Update the whole dataset after changes
'''
self.update_cross_link_unique_sub_index()
self.update_cross_link_redundancy()
self.update_residues_links_number()
self.check_cross_link_consistency()
def __iter__(self):
sorted_ids = sorted(self.data_base.keys())
for k in sorted_ids:
for xl in self.data_base[k]:
yield xl
def xlid_iterator(self):
sorted_ids = sorted(self.data_base.keys())
for xlid in sorted_ids:
yield xlid
def __getitem__(self, xlid):
return self.data_base[xlid]
def __len__(self):
return len([xl for xl in self])
def get_name(self):
return self.name
def set_name(self, name):
new_data_base = {}
for k in self.data_base:
new_data_base[k + "." + name] = self.data_base[k]
self.data_base = new_data_base
self.name = name
self._update()
def get_number_of_xlid(self):
return len(self.data_base)
def create_set_from_file(self, file_name, converter=None,
FixedFormatParser=None, encoding=None):
'''
if FixedFormatParser is not specified, the file is
comma-separated-values
@param file_name a txt file to be parsed
@param converter an instance of CrossLinkDataBaseKeywordsConverter
@param FixedFormatParser a parser for a fixed format
@param encoding the encoding of the file, if not the locale
default (usually UTF-8)
'''
if not FixedFormatParser:
xl_list = IMP.pmi.tools.get_db_from_csv(file_name, encoding)
if converter is not None:
self.cldbkc = converter
self.list_parser = self.cldbkc.rplp
self.converter = converter.get_converter()
if not self.list_parser:
# normal procedure without a list_parser
# each line is a cross-link
new_xl_dict = {}
for nxl, xl in enumerate(xl_list):
new_xl = {}
for k in xl:
if k in self.converter:
new_xl[self.converter[k]] = \
self.type[self.converter[k]](xl[k])
else:
new_xl[k] = xl[k]
if self.unique_id_key in self.cldbkc.get_setup_keys():
if new_xl[self.unique_id_key] not in new_xl_dict:
new_xl_dict[new_xl[self.unique_id_key]] = [new_xl]
else:
new_xl_dict[new_xl[self.unique_id_key]].append(
new_xl)
else:
if str(nxl) not in new_xl_dict:
new_xl_dict[str(nxl)] = [new_xl]
else:
new_xl_dict[str(nxl)].append(new_xl)
else:
# with a list_parser, a line can be a list of ambiguous
# cross-links
new_xl_dict = {}
for nxl, entry in enumerate(xl_list):
# first get the translated keywords
new_dict = {}
if self.site_pairs_key not in self.cldbkc.get_setup_keys():
raise Exception(
"CrossLinkDataBase: expecting a site_pairs_key "
"for the site pair list parser")
for k in entry:
if k in self.converter:
new_dict[self.converter[k]] = \
self.type[self.converter[k]](entry[k])
else:
new_dict[k] = entry[k]
(residue_pair_list,
chain_pair_list) = self.list_parser.get_list(
new_dict[self.site_pairs_key])
# then create the cross-links
for n, p in enumerate(residue_pair_list):
is_monolink = False
if len(p) == 1:
is_monolink = True
new_xl = {}
for k in new_dict:
new_xl[k] = new_dict[k]
new_xl[self.residue1_key] = \
self.type[self.residue1_key](p[0])
if not is_monolink:
new_xl[self.residue2_key] = \
self.type[self.residue2_key](p[1])
if len(chain_pair_list) == len(residue_pair_list):
new_xl[self.protein1_key] = \
self.type[self.protein1_key](
chain_pair_list[n][0])
if not is_monolink:
new_xl[self.protein2_key] = \
self.type[self.protein2_key](
chain_pair_list[n][1])
if not is_monolink:
new_xl[self.link_type_key] = "CROSSLINK"
else:
new_xl[self.link_type_key] = "MONOLINK"
if self.unique_id_key in self.cldbkc.get_setup_keys():
if new_xl[self.unique_id_key] not in new_xl_dict:
new_xl_dict[new_xl[self.unique_id_key]] = \
[new_xl]
else:
new_xl_dict[new_xl[self.unique_id_key]].append(
new_xl)
else:
if str(nxl) not in new_xl_dict:
new_xl[self.unique_id_key] = str(nxl+1)
new_xl_dict[str(nxl)] = [new_xl]
else:
new_xl[self.unique_id_key] = str(nxl+1)
new_xl_dict[str(nxl)].append(new_xl)
else:
'''
if FixedFormatParser is defined
'''
if sys.version_info[0] == 2:
def open_with_encoding(fname, mode, encoding):
return open(fname, mode)
else:
open_with_encoding = open
new_xl_dict = {}
nxl = 0
with open_with_encoding(file_name, "r", encoding=encoding) as f:
for line in f:
xl = FixedFormatParser.get_data(line)
if xl:
xl[self.unique_id_key] = str(nxl+1)
new_xl_dict[str(nxl)] = [xl]
nxl += 1
self.data_base = new_xl_dict
self.name = file_name
loc = ihm.location.InputFileLocation(file_name, details='Crosslinks')
self.dataset = ihm.dataset.CXMSDataset(loc)
self._update()
def update_cross_link_unique_sub_index(self):
for k in self.data_base:
for n, xl in enumerate(self.data_base[k]):
xl[self.ambiguity_key] = len(self.data_base[k])
xl[self.unique_sub_index_key] = n+1
xl[self.unique_sub_id_key] = k + "." + str(n+1)
def update_cross_link_redundancy(self):
redundancy_data_base = {}
for xl in self:
pra = _ProteinsResiduesArray(xl)
if pra not in redundancy_data_base:
redundancy_data_base[pra] = [xl[self.unique_sub_id_key]]
redundancy_data_base[pra.get_inverted()] = \
[xl[self.unique_sub_id_key]]
else:
redundancy_data_base[pra].append(xl[self.unique_sub_id_key])
redundancy_data_base[pra.get_inverted()].append(
xl[self.unique_sub_id_key])
for xl in self:
pra = _ProteinsResiduesArray(xl)
xl[self.redundancy_key] = len(redundancy_data_base[pra])
xl[self.redundancy_list_key] = redundancy_data_base[pra]
def update_residues_links_number(self):
residue_links = {}
for xl in self:
(p1, p2, r1, r2) = _ProteinsResiduesArray(xl)
if (p1, r1) not in residue_links:
residue_links[(p1, r1)] = set([(p2, r2)])
else:
residue_links[(p1, r1)].add((p2, r2))
if (p2, r2) not in residue_links:
residue_links[(p2, r2)] = set([(p1, r1)])
else:
residue_links[(p2, r2)].add((p1, r1))
for xl in self:
(p1, p2, r1, r2) = _ProteinsResiduesArray(xl)
xl[self.residue1_links_number_key] = len(residue_links[(p1, r1)])
xl[self.residue2_links_number_key] = len(residue_links[(p2, r2)])
def check_cross_link_consistency(self):
"""This function checks the consistency of the dataset with the
amino acid sequence"""
if self.cldbkc and self.fasta_seq:
cnt_matched, cnt_matched_file = 0, 0
matched = {}
non_matched = {}
for xl in self:
(p1, p2, r1, r2) = _ProteinsResiduesArray(xl)
b_matched_file = False
if self.residue1_amino_acid_key in xl:
# either you know the residue type and aa_tuple is
# a single entry
aa_from_file = (xl[self.residue1_amino_acid_key].upper(),)
b_matched = self._match_xlinks(p1, r1, aa_from_file)
b_matched_file = b_matched
else:
# or pass the possible list of types that can be
# cross-linked
b_matched = self._match_xlinks(p1, r1, self.def_aa_tuple)
matched, non_matched = self._update_matched_xlinks(
b_matched, p1, r1, matched, non_matched)
if self.residue2_amino_acid_key in xl:
aa_from_file = (xl[self.residue2_amino_acid_key].upper(), )
b_matched = self._match_xlinks(p2, r2, aa_from_file)
b_matched_file = b_matched
else:
b_matched = self._match_xlinks(p2, r2, self.def_aa_tuple)
matched, non_matched = self._update_matched_xlinks(
b_matched, p2, r2, matched, non_matched)
if b_matched:
cnt_matched += 1
if b_matched_file:
cnt_matched_file += 1
if len(self) > 0:
percentage_matched = round(100*cnt_matched/len(self), 1)
percentage_matched_file = round(
100 * cnt_matched_file / len(self), 1)
if matched or non_matched:
print(
"check_cross_link_consistency: Out of %d cross-links "
"%d were matched to the fasta sequence (%f %%).\n "
"%d were matched by using the cross-link file (%f %%)."
% (len(self), cnt_matched, percentage_matched,
cnt_matched_file, percentage_matched_file))
if non_matched:
print("check_cross_link_consistency: Warning: Non "
"matched xlinks:",
[(prot_name, sorted(list(non_matched[prot_name])))
for prot_name in non_matched])
return matched, non_matched
def _match_xlinks(self, prot_name, res_index, aa_tuple):
# returns Boolean whether given aa matches a position in the fasta file
# cross-link files usually start counting at 1 and not 0; therefore
# subtract -1 to compare with fasta
amino_dict = IMP.pmi.alphabets.amino_acid
res_index -= 1
for amino_acid in aa_tuple:
if len(amino_acid) == 3:
amino_acid = amino_dict.get_one_letter_code_from_residue_type(
amino_acid.upper())
if prot_name in self.fasta_seq.sequences:
seq = self.fasta_seq.sequences[prot_name]
# if we are looking at the first amino acid in a given
# sequence always return a match
# the first aa should always be the n-terminal aa
# which may form a cross-link in any case (for BS3-like
# cross-linkers)
# for some data sets the first aa is at position 1;
# todo: check why this is the case
if res_index == 0 or res_index == 1:
return True
if res_index < len(seq):
if amino_acid == seq[res_index]:
return True
return False
def _update_matched_xlinks(self, b_matched, prot, res, matched,
non_matched):
if b_matched:
if prot in matched:
matched[prot].add(res)
else:
matched[prot] = set([res])
else:
if prot in non_matched:
non_matched[prot].add(res)
else:
non_matched[prot] = set([res])
return matched, non_matched
def get_cross_link_string(self, xl):
string = '|'
for k in self.ordered_key_list:
try:
string += str(k) + ":" + str(xl[k]) + "|"
except KeyError:
continue
for k in xl:
if k not in self.ordered_key_list:
string += str(k) + ":" + str(xl[k]) + "|"
return string
def get_short_cross_link_string(self, xl):
string = '|'
list_of_keys = [self.data_set_name_key,
self.unique_sub_id_key,
self.protein1_key,
self.residue1_key,
self.protein2_key,
self.residue2_key,
self.state_key,
self.psi_key]
for k in list_of_keys:
try:
string += str(xl[k]) + "|"
except KeyError:
continue
return string
def filter(self, FilterOperator):
new_xl_dict = {}
for id in self.data_base.keys():
for xl in self.data_base[id]:
if FilterOperator.evaluate(xl):
if id not in new_xl_dict:
new_xl_dict[id] = [xl]
else:
new_xl_dict[id].append(xl)
self._update()
cdb = CrossLinkDataBase(self.cldbkc, new_xl_dict)
cdb.dataset = self.dataset
cdb.name = self.name
return cdb
def filter_score(self, score):
'''Get all cross-links with score greater than an input value'''
FilterOperator = IMP.pmi.io.crosslink.FilterOperator(
self.id_score_key, operator.gt, score)
return self.filter(FilterOperator)
def merge(self, CrossLinkDataBase1, CrossLinkDataBase2):
'''
This function merges two cross-link datasets so that if two
conflicting cross-links have the same cross-link UniqueIDS,
the cross-links will be appended under the same UniqueID slots
with different SubIDs
'''
raise NotImplementedError()
def append_database(self, db):
"""Append cross-link dataset to this one."""
new_data_base = {}
for k in self.data_base:
new_data_base[k] = self.data_base[k]
for k in db.data_base:
new_data_base[k] = db.data_base[k]
self.data_base = new_data_base
self._update()
def __iadd__(self, db):
self.append_database(db)
return self
def set_value(self, key, new_value, filter_operator=None):
'''
This function changes the value for a given key in the database
For instance one can change the name of a protein
@param key: the key in the database that must be changed
@param new_value: the new value of the key
@param filter_operator: optional FilterOperator to change the value to
a subset of the database
example: `cldb1.set_value(cldb1.protein1_key, 'FFF',
FO(cldb.protein1_key, operator.eq, "AAA"))`
'''
for xl in self:
if filter_operator is not None:
if filter_operator.evaluate(xl):
xl[key] = new_value
else:
xl[key] = new_value
self._update()
def get_values(self, key):
'''
this function returns the list of values for a given key in the
database alphanumerically sorted
'''
values = set()
for xl in self:
values.add(xl[key])
return sorted(list(values))
def offset_residue_index(self, protein_name, offset):
'''
This function offset the residue indexes of a given protein by