-
Notifications
You must be signed in to change notification settings - Fork 0
/
complete_information.py
2589 lines (2301 loc) · 121 KB
/
complete_information.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
# Name:
# Language: python3
# Libraries:
# Description:
# Author: Edoardo Sarti
# Date:
from supporting_functions import *
def calc_seqid_up(aln, bn, en, seq, unp_seq, fmt='biopython'):
# aln: [intervals1, intervals2]
# intervals: (interval1, interval2, ..., intervalN)
# interval: (begin, end)
# intervals1 and intervals2 contain the same number of intervals, and corresponding ones
# have the same length (end - begin), and are in fact the matched-mismatched regions
opts = [[x[1]-1 - x[0], x[1]-1 - bn, en - x[0], en - bn] for x in aln.aligned[1]]
norm = sum([min([max(0,x+1) for x in y]) for y in opts])
seqid = 0
strb, stre = -1, -1
if norm != 0:
for i in range(len(aln.aligned[0])):
ix, iy = aln.aligned[0][i], aln.aligned[1][i]
if strb == -1:
strb = ix[0]
stre = ix[1]
for j in range(ix[1] - ix[0]):
if seq[ix[0]+j] == unp_seq[iy[0]+j] and iy[0]+j >= bn and iy[0]+j <= en:
seqid += 1
seqid /= norm
return seqid, strb, stre
def map_retrieve(ids2map, source_fmt='ACC+ID', target_fmt='ACC', output_fmt='tab'):
'''
Retrieves ACC from IDs
Supported output formats:
- 'tab' : returns a dictionary of ID -> ACC codes
- 'fasta' : returns a dictionary of ID -> sequence
'''
BASE = 'http://www.uniprot.org'
KB_ENDPOINT = '/uniprot/'
TOOL_ENDPOINT = '/uploadlists/'
lenids = len(ids2map)
if output_fmt in ['tab', 'fasta']:
nope = {}
else:
nope = []
if type(ids2map) != list:
ids2map = ids2map.split()
REPEAT = 5
rep = 0
results = {'results' : {}}
while (not results['results']) and rep<REPEAT:
job_id = uniprot_requests.submit_id_mapping(
from_db="UniProtKB_AC-ID", to_db="UniProtKB", ids=ids2map
)
if uniprot_requests.check_id_mapping_results_ready(job_id):
link = uniprot_requests.get_id_mapping_results_link(job_id)
results = uniprot_requests.get_id_mapping_results_search(link)
rep += 1
d = {}
if output_fmt == 'tab':
for r in results['results']:
d[r['from']] = r['to']['primaryAccession']
elif output_fmt == 'fasta':
for r in results['results']:
if 'sequence' in r['to']:
d[r['from']] = r['to']['sequence']['value']
return d
def uniprot_sifts(locations, str_data):
# SIFTS file must be done like this:
# PDB CHAIN ACC BEGINRES_NUM ENDRES_NUM BEGINRES_PDBIDX ENDRES_PDBIDX BEGINRES_UNIPROT ENDRES_UNIPROT
up_data = {}
up_set = set()
if not os.path.exists(locations['SYSFILES']['sifts_uniprot']):
url = "ftp://ftp.ebi.ac.uk/pub/databases/msd/sifts/flatfiles/tsv/pdb_chain_uniprot.tsv.gz"
local_filename = locations['SYSFILES']['sifts_uniprot']
reiterated_gzip_download(url, local_filename)
with open(locations['SYSFILES']['sifts_uniprot']) as f:
for line in f:
if line.strip().startswith("#"):
continue
pdbi, ch, acc, begnum, endnum, begpdb, endpdb, begp, endp = line.split()
if pdbi in str_data:
if pdbi not in up_data:
up_data[pdbi] = []
if acc not in up_data[pdbi]:
up_data[pdbi].append((acc, int(begp)-1, int(endp)-1))
up_set.add(acc)
return up_data, up_set
def assign_uniprot_acc(locations, str_data, eq):
"""Needs:
- biopython
- str_data[pdbi]['ENCOMPASS']['structure']['chains'][ich]['sequence']
- str_data[pdbi]['ENCOMPASS']['structure']['chains'][ich]['TM_regions']['TM_regions_extrema']
"""
EXTR = 1000000
# Statistics
local_stats = {
'no_conversion' : [],
'up_codes' : [],
'short_sequence' : [],
'antibody' : [],
'best_just_below_thr' : [],
'no_up_codes' : [],
'best_much_below_thr' : [],
'#codes' : {},
'no_up_TM' : [],
'up_sifts_only' : [],
'up_sifts&json' : []
}
# Searches in PDB json files and compiles a UniProt list dictionary
# that can also accommodate for starting and ending points of thee struct chain
uniprot_codes = set()
uniprot_dict = {} # UniProt list dictionary for 3-tuples (acc, init, end)
for pdbi in str_data:
pdbjson_fn = locations['FSYSPATH']['PDBjsons'] + pdbi + '.json'
uniprot_code_list = []
if os.path.exists(pdbjson_fn):
with codecs.open(pdbjson_fn, 'r+', encoding="utf-8") as json_file:
js = json.load(json_file, encoding='utf-8')
for x in js['polymer_entities']:
ul = x['rcsb_polymer_entity_container_identifiers']['uniprot_ids']
if ul:
uniprot_codes |= set(ul)
uniprot_code_list += ul
# init and end are defaulted at some extreme value
uniprot_dict[pdbi] = [(acc, -EXTR, EXTR) for acc in sorted(list(set(uniprot_code_list)))]
# Look into the SIFTS database for completing the data
up_data_sifts, up_set_sifts = uniprot_sifts(locations, str_data)
# Merge the UniProt codes found
uniprot_codes |= up_set_sifts
# If the code has been found in SIFTS, add init and end
for pdbi in up_data_sifts:
if pdbi not in uniprot_dict:
local_stats['up_sifts_only'].append(pdbi)
uniprot_dict[pdbi] = up_data_sifts[pdbi]
else:
# If the code has been found in SIFTS, delete the current entry
# and replace it with the SIFTS one
for acc, bn, en in up_data_sifts[pdbi]:
if (acc, -EXTR, EXTR) in uniprot_dict[pdbi]:
local_stats['up_sifts&json'].append(pdbi)
delid = uniprot_dict[pdbi].index((acc, -EXTR, EXTR))
del uniprot_dict[pdbi][delid]
if (acc, bn, en) not in uniprot_dict[pdbi]:
uniprot_dict[pdbi].append((acc, bn, en)) # Replace in any case
# Retrieve the sequences corresponding to the uniprot codes
binsize = 100
unp_seqs = {}
for i in range(0, len(uniprot_codes)//binsize + 1):
partial_l = sorted(list(uniprot_codes))[binsize*i:binsize*(i+1)]
d = map_retrieve(partial_l, output_fmt='fasta')
for e in d:
unp_seqs[e] = d[e]
aligner = init_pairwise_alignment()
SEQID_THR = 0.95
for pdbi in [x for x in str_data]:
for ich, ch in enumerate(str_data[pdbi]['ENCOMPASS']['structure']['kchains']):
resids = str_data[pdbi]['ENCOMPASS']['structure']['chains'][ich]['residues']
seq = "".join([from3to1(x[1]) for x in resids])
ticket = []
if len(seq) <= 15:
local_stats['short_sequence'].append((pdbi, ch))
if 'antibody' in str_data[pdbi]['ENCOMPASS']['name'].lower()\
or 'antibody' in str_data[pdbi]['FROM_PDB']['name'].lower():
local_stats['antibody'].append((pdbi, ch))
# Couple the chain with pertinent UniProt accs
# If the alignment between the chain and the UniProt sequence has seqid>0.95,
# then add the acc to the list. If the list remains empty and the best seqid is >0.9,
# then add the corresponding acc.
right_acc_name = [] # List of UniProt codes associated to a chain
bestid, bestaln, bestname, bestextr, bestupextr = 0, [], '', (-1, -1), (-1, -1)
status = {}
for name, bn, en in uniprot_dict[pdbi]:
try:
unp_seq = unp_seqs[name] # name can not be in unp_seqs if seq has not been retrieved
result = aligner.align(seq, unp_seq) # biopython can fail for whatever reason
if not result: # when result is called, biopython can still fail for too many optimal solutions
status[pdbi+"_"+ch] = 'BIOPYTHON ERROR - NULL'
continue
except:
if name not in unp_seqs:
status[pdbi+"_"+ch] = 'UNIPROT ERROR - NO SEQUENCE'
else:
status[pdbi+"_"+ch] = 'BIOPYTHON ERROR - FAILED'
continue
if result:
aln = result[0]
seqid, strb, stre = calc_seqid_up(aln, bn, en, seq, unp_seq, fmt='biopython')
if seqid > SEQID_THR:
right_acc_name.append((name, (bn, en), (resids[strb][0][0], resids[stre-1][0][0])))
if seqid > bestid:
bestid = seqid
bestaln = aln
bestname = name
if strb == -1 or stre == -1:
bestextr = (-1, -1)
else:
bestextr = (resids[strb][0][0], resids[stre-1][0][0])
bestupextr = (bn, en)
if not right_acc_name:
if pdbi+"_"+ch not in status:
if bestid > 0.9:
right_acc_name.append((bestname, bestupextr, bestextr))
local_stats['best_just_below_thr'].append((pdbi, ch, bestname))
elif not uniprot_dict[pdbi]:
local_stats['no_up_codes'].append((pdbi, ch))
else:
local_stats['best_much_below_thr'].append((pdbi, ch, bestname))
ran = ",".join([x[0] for x in right_acc_name])
str_data[pdbi]['ENCOMPASS']['structure']['chains'][ich]['UniProt_acc'] = right_acc_name # This is a list
if ran not in str_data[pdbi]['ENCOMPASS']['structure']['UniProt_stoichiometry']:
str_data[pdbi]['ENCOMPASS']['structure']['UniProt_stoichiometry'][ran] = []
str_data[pdbi]['ENCOMPASS']['structure']['UniProt_stoichiometry'][ran].append(ch)
n = len(right_acc_name)
if n not in local_stats['#codes']:
local_stats['#codes'][n] = []
local_stats['#codes'][n].append(pdbi)
# If some equivalent chain has the UniProt code, transfer it
# 1) Equivalence dictionary already present in variable eq
# 2) Transfer UniProt codes between equivalent chains
# NEEDS TM analysis!
for pdbi in sorted([x for x in str_data]):
for ich, ch in enumerate(sorted(str_data[pdbi]['ENCOMPASS']['structure']['kchains'])):
ENCchain = str_data[pdbi]['ENCOMPASS']['structure']['chains'][ich]
if len(ENCchain['TM_regions']['TM_regions_extrema'])>0\
and (not ENCchain['UniProt_acc']):
pdbi_ch1 = pdbi + '_' + ch
if pdbi_ch1 not in eq:
continue
for pdbi_ch2 in eq[pdbi_ch1]:
pdbi2, ch2 = pdbi_ch2.split('_')
if ch2 in str_data[pdbi2]['ENCOMPASS']['structure']['kchains']:
ich2 = str_data[pdbi2]['ENCOMPASS']['structure']['kchains'].index(ch2)
else:
continue
ENCchain2 = str_data[pdbi2]['ENCOMPASS']['structure']['chains'][ich2]
if ENCchain2['UniProt_acc']:
ENCchain['UniProt_acc'] = ENCchain2['UniProt_acc']
break
if len(ENCchain['TM_regions']['TM_regions_extrema'])>0 and (not ENCchain['UniProt_acc']):
local_stats['no_up_TM'].append((pdbi, ch))
# Show statistics
for x in sorted(local_stats):
if type(local_stats[x]) is list:
print("STATS", "assign_uniprot_acc", x, len(local_stats[x]), local_stats[x])
elif type(local_stats[x]) is dict:
for y in sorted(local_stats[x]):
print("STATS", "assign_uniprot_acc", x, y, len(local_stats[x][y]), local_stats[x][y])
print("STATS", "assign_uniprot_acc", "Finished", "time", time.ctime(), "\n")
return str_data
def aln_and_seqid(seq1, seq2, sn1, sn2, muscle_path='', cache_path=''):
"""Calculcates pairwise alignment and sequence identity
Low-level function: independent of EncDS
"""
if type(seq1) == list:
seq1 = ''.join([x for x in seq1])
if type(seq2) == list:
seq2 = ''.join([x for x in seq2])
# If MUSCLE will be used, cache_path must be specified
if (muscle_path and not cache_path) or (cache_path and not muscle_path):
print("ERROR1010")
exit(1)
# MUSCLE is the preferred method
muscle_failed = False
if muscle_path:
# Cache name with random label
signature = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(10))
muscle_in_filename = cache_path + 'muscle_in_' + signature + '.fa'
muscle_out_filename = cache_path + 'muscle_out_' + signature + '.fa'
muscle_stdout = cache_path + 'muscle_' + signature + '.out'
muscle_stderr = cache_path + 'muscle_' + signature + '.err'
# Write input fasta file
with open(muscle_in_filename, 'w') as f:
f.write('>{0}\n{1}\n>{2}\n{3}\n'.format(sn1, seq1, sn2, seq2))
# Execute same MUSCLE job 3 times before giving up
muscle_plist = muscle_path.split()
i = 0
while (not os.path.exists(muscle_out_filename)) and i<3:
if i>0:
print("Muscle output {0} not found. Try number {1}".format(sn1+":"+sn2, i+1))
try:
subprocess.check_call(muscle_plist + ['-in', muscle_in_filename, '-out', muscle_out_filename], stdout=open(muscle_stdout, 'w'), stderr=open(muscle_stderr, 'w'))
except:
print("Muscle failed on {0}".format(sn1+":"+sn2))
i += 1
# Check if, after at most 3 tries, the output is there
# If so, parse out put and create alignment
if os.path.exists(muscle_out_filename):
with open(muscle_out_filename) as f:
aseqs = []
aseq = ''
for line in f:
if not line:
continue
if line.startswith('>'):
if aseq:
aseqs.append(aseq)
aseq = ''
continue
aseq += line.strip()
if aseq:
aseqs.append(aseq)
aln = list(zip(aseqs[0], aseqs[1]))
os.remove(muscle_in_filename)
os.remove(muscle_out_filename)
os.remove(muscle_stdout)
os.remove(muscle_stderr)
else:
muscle_failed = True
# Calculate seqid
norm = len([x for x in aln if '-' not in x])
if norm == 0:
seqid = 0
else:
seqid = len([x for x in aln if x[0] == x[1]])/norm
return aln, seqid
def find_copies_of_chains(coord_dict_pdbi, analysis_pdbi, pdbi, pdb_data_pdbi={}, pdb_bioassembly_group=-1): #, thr_log_status="ERROR"):
"""
Checks if chains with coordinates are exact copies
pdb_bioassembly_group : assembly number to consider (-1 equals "all")
"""
# annotate the copies in this way: [list_of_equals1, list_of_equals2, ...]
# Note: in case of an OPM sturcure, this data cannot be trusted. The only way is to do the seq_from_structure approach
this_name = find_copies_of_chains.__name__
if pdb_bioassembly_group != -1:
if not pdb_data_pdbi:
print("ERROR")
exit(1)
elif pdb_bioassembly_group < 0 or len(pdb_data_pdbi['biological_assemblies'].show_list(quiet=True)) <= pdb_bioassembly_group:
print("ERROR2")
print(pdb_bioassembly_group)
print(pdb_data_pdbi['biological_assemblies'].show_list())
exit(1)
chains_to_consider = []
if pdb_bioassembly_group != -1:
for transf in pdb_data_pdbi['biological_assemblies'][pdb_bioassembly_group]['transformations']:
for c in transf['chains']:
if c not in chains_to_consider:
chains_to_consider.append(c)
else:
chains_to_consider = [x for x in coord_dict_pdbi['COORDS']]
if len(chains_to_consider) < 2:
if len(chains_to_consider) == 0:
print("ERROR2020")
exit(1)
return False, [chains_to_consider] # list of one list
seqs = {}
# Make a list of sequences that have to be compared. In case of a bioassembly, only take the ones mentioned in the bioassembly
# if [1 for x in str_data_pdbi['PASSPORT'] if 'chain_noba' in x['location'] or 'chain_banoc' in x['location']]: (use this code for the "not in agreement" part)
for c in chains_to_consider:
seqs[c] = [from3to1(x[1]) for x in coord_dict_pdbi['COORDS'][c]]
inds_to_consider = [analysis_pdbi['seqid_legend'].index(c) for c in chains_to_consider]
seqids = np.array(analysis_pdbi['seqid_mtx'])
# Make a list of lists of chains having a Seq. Id. >= 95%
pairs = set()
sn = pdbi + "_"
for ic1, (c1, i1) in enumerate(list(zip(chains_to_consider, inds_to_consider))):
for c2, i2 in list(zip(chains_to_consider, inds_to_consider))[ic1:]:
if i1 > -1 and i2 > -1 and seqids[i1, i2] >= 0.95:
pairs.add((c1, c2))
copies_list = sorted(merge(pairs, sorted_lists=True))
for c in sorted(list(seqs.keys())):
c_found = False
for cl in copies_list:
if c in cl:
c_found = True
break
if not c_found:
for cli, cl in enumerate(copies_list):
if sorted([c, cl[0]])[0] == c:
copies_list = copies_list[:cli] + [c] + copies_list[cli:]
break
has_copies_of_chains = False
for c in copies_list:
if len(c) > 1:
has_copies_of_chains = True
break
return has_copies_of_chains, copies_list
def generate_full_structure(str_data_pdbi, pdbi, coords={}, bioassembly=0): #, thr_log_status="ERROR"):
this_name = generate_full_structure.__name__
IDmtx = np.array([[1,0,0],[0,1,0],[0,0,1]])
IDvec = np.array([0,0,0])
# 1. Build the np matrices for rotation and translation
rotmatrices = []
tarrays = []
translrots = str_data_pdbi['FROM_PDB']['translrots']
ktranslrots = str_data_pdbi['FROM_PDB']['ktranslrots']
for nmat in range(len(translrots)):
rotmatrices.append(np.array(translrots[nmat]['matrix']))
tarrays.append(np.array(translrots[nmat]['vector']))
# 2. Generate structure
if not coords:
coords, _ = retrieve_coords_from_CIF(str_data_pdbi['FROM_PDB']['cache_coordinate_file'])
chain_sets = {} # Sets of repeated chains (their union could be smaller than the set of all chains contained in the pdb)
used_chains = set() # Names of already used chains, and initialization
transfs = str_data_pdbi['FROM_PDB']['biological_assemblies'][bioassembly]['transformations']
for x in range(len(transfs)):
for c in transfs[x]['chains']:
used_chains.add(c)
alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890' # Alphabetical order used to assign names to new chains
alphabetical = list(alphabet)
for x in alphabet:
alphabetical += ["{0}{1}".format(x,y) for y in alphabet]
new_coords = {}
for nop in range(len(transfs)):
ops = transfs[nop]['operators'] # Operators are individual rototranslation functions. They can combine multiple rototranslators. Example: [(M1,v1),(M2,v2)] is the function v -> (M2*((M1*v)+v1))+v2
for chain in [x for x in coords if x in transfs[nop]['chains']]: # DANGER
for iop in range(len(ops)): # each chain might be applied to multiple operators
op = ops[iop]
is_identity = False
# If it is the identity operator, do not change chain names
if len(op) == 1:
tr = op[0]
itr = ktranslrots.index(tr)
if (rotmatrices[itr] == IDmtx.tolist()).all() and (tarrays[itr] == IDvec.tolist()).all(): # DANGER
used_chains.add(chain)
if nop not in chain_sets:
chain_sets[(nop,iop)] = []
chain_sets[(nop,iop)].append(chain)
new_chain = chain
new_coords[new_chain] = coords[chain]
is_identity = True
# If it isn't, change chain name
if not is_identity:
for chid in alphabetical:
if chid not in used_chains and chid not in coords:
# Choose a new chain name
used_chains.add(chid)
if nop not in chain_sets:
chain_sets[(nop,iop)] = []
chain_sets[(nop,iop)].append(chid)
new_chain = chid
# Initialize the coords of the new chain
new_coords[new_chain] = {}
for resid_name in coords[chain]:
new_coords[new_chain][resid_name] = {}
break
# Apply operator, transf by transf
for tr in op: # each non-ID operator might be a combination of transformations
itr = ktranslrots.index(tr)
for resid_name in coords[chain]:
resid, resname = resid_name
if resname == "DUM":
continue
for atid in coords[chain][resid_name]:
new_coords[new_chain][resid_name][atid] = np.dot(rotmatrices[itr], coords[chain][resid_name][atid]) + tarrays[itr]
coords[new_chain] = new_coords[new_chain]
return new_coords, chain_sets
def calc_consensus_PDB(str_data, pdbi, pdb_bioassembly_group=0):
bioassembly = 0
PDB_coords = retrieve_coords_from_CIF(str_data[pdbi]['FROM_PDB']['cache_coordinate_file'])
has_copies_of_chains_PDB, copies_ch_PDB = find_copies_of_chains(PDB_coords, str_data[pdbi]['FROM_PDB']['analysis'], pdbi, pdb_data_pdbi=str_data[pdbi]['FROM_PDB'], pdb_bioassembly_group=pdb_bioassembly_group)
transfs = str_data[pdbi]['FROM_PDB']['biological_assemblies'][bioassembly]['transformations']
chain_signature_PDB = find_gcd([len(x) for x in copies_ch_PDB]) * len(transfs)
return chain_signature_PDB
def calc_rotation_axis(rotmtx):
axis_of_rotation = np.array([rotmtx[2][1] - rotmtx[1][2], rotmtx[0][2] - rotmtx[2][0], rotmtx[1][0] - rotmtx[0][1]])
if np.linalg.norm(axis_of_rotation) == 0 and sum([rotmtx[x][x] for x in range(3)]) == -1:
aor = []
for x in range(3):
if rotmtx[x][x] == 1:
aor.append(1)
else:
aor.append(0)
axis_of_rotation = np.array(aor)
if np.linalg.norm(axis_of_rotation) > config.epsilon:
axis_of_rotation = np.array(axis_of_rotation)/np.linalg.norm(axis_of_rotation)
return axis_of_rotation
def select_biological_assembly(data):
this_name = select_biological_assembly.__name__
local_stats = {
'add_identity_transf' : [],
'sameseq' : [],
'1chain0transf' : [],
'PDB!=OPM' : [],
'PDB?=OPM' : [],
'weirdtransf' : [],
'biomatrix_error' : [],
'undecided' : [],
'unsafe' : [],
'safe' : [],
'null_rotax' : []
}
# It ONLY takes pdbis for which the safety is UNDECIDED
options, locations, str_data = data
bioassembly = 0
# Evaluates safety of OPM groups instead of single structures
if options['PARAMETERS'][('', 'consensus_signature_PDB')]:
consensus_signature_PDB = {}
visited_pdbi = set()
for pdbi in str_data:
if pdbi in visited_pdbi:
continue
visited_pdbi.add(pdbi)
pdb_signatures = [] # List for studying the consensus
# Calculates PDB signature as: (greatest common divisor of copies of present chains) * (biomatrix transformations)
# Example: a complex A,B,C,D,E,F where A,B are identical and C,D,E,F are identical has gcd = 2 (there are 2 full copies of the A,2*C unit)
# If to that complex we add the non-identical chain G, theh gcd=1 (there is only one copy of the unit 2*A,4*C,G)
if not ({'eliminated', 'pdb_eliminated', 'opm_eliminated'} & set(str_data[pdbi]['status'])):
pdb_signatures.append(calc_consensus_PDB(str_data, pdbi, pdb_bioassembly_group=0))
else:
str_data[pdbi]['PASSPORT'].append(passport_entry(this_name+'_jump', pdbi, "This entry has been deemed very problematic, and thus will not undergo comparative biological assembly analyses."))
for sec_pdbi in [x['pdbid'] for x in str_data[pdbi]['FROM_OPM']['secondary_representations'] if x['pdbid'] in str_data]:
visited_pdbi.add(sec_pdbi)
if not ({'eliminated', 'pdb_eliminated'} & set(str_data[sec_pdbi]['status'])):
pdb_signatures.append(calc_consensus_PDB(str_data, sec_pdbi, pdb_bioassembly_group=0))
else:
str_data[sec_pdbi]['PASSPORT'].append(passport_entry(this_name+'_jump2', pdbi, "This entry has been deemed very problematic, and thus will not undergo comparative biological assembly analyses."))
if not pdb_signatures: # It means the entries were eliminated
continue
# Sort signatures by number of recurrences and form consensus
sigd = {i:pdb_signatures.count(i) for i in pdb_signatures}
invsigd = {}
for i in sigd:
if sigd[i] not in invsigd:
invsigd[sigd[i]] = []
invsigd[sigd[i]].append(i)
maxi = sorted([i for i in invsigd])[-1]
# If two signatures are equally voted, then put a signature value that will be catched hereafter (-1)
multiplicity = len(invsigd[maxi])
if multiplicity > 1:
val = -1
else:
val = invsigd[maxi][0]
consensus_signature_PDB[pdbi] = val
# Update consensus for the whole group
for sec_pdbi in [x['pdbid'] for x in str_data[pdbi]['FROM_OPM']['secondary_representations'] if x['pdbid'] in str_data]:
consensus_signature_PDB[sec_pdbi] = val # can be -1 !! Catch it!
# Decision
decsn = {'SAFE' : {}, 'UNSAFE' : {}}
status = {} # Shortcut for str_data[pdbi]['status']
passport = {} # Shortcut for str_data[pdbi]['PASSPORT']
to_be_checked = False
IDmtx = np.array([[1,0,0],[0,1,0],[0,0,1]])
IDvec = np.array([0,0,0])
for pdbi in str_data:
if config.debug:
print("CBA", pdbi)
status[pdbi] = str_data[pdbi]['status']
passport[pdbi] = str_data[pdbi]['PASSPORT']
# If there is the PDB structure, the transformations are taken from there. Otherwise, it is the identity
PDB_coords = retrieve_coords_from_CIF(str_data[pdbi]['FROM_PDB']['cache_coordinate_file'])
PDB_seqs = get_sequence_from_CIF(str_data[pdbi]['FROM_PDB']['cache_coordinate_file'])
OPMpdb_coords = retrieve_coords_from_CIF(str_data[pdbi]['FROM_OPM']['cache_coordinate_file'])
# Preparation: fill in missing transformation sets
# Case 1: broken PDB but working OPM. Transformations = identity
if ('pdb_eliminated' in status[pdbi] and 'opm_eliminated' not in status[pdbi]) or\
('pdb_eliminated' not in status[pdbi] and len(str_data[pdbi]['FROM_PDB']['biological_assemblies'][bioassembly]['transformations']) == 0):
from_pdb = str_data[pdbi]['FROM_PDB']
trd = FixedDict(from_pdb['translrots'].get_fdict_template())
trd['matrix'] = IDmtx.tolist()
trd['vector'] = IDvec.tolist()
from_pdb['translrots'].append(trd)
from_pdb['ktranslrots'].append('1')
# Get transformation set
# Case 1: broken PDB but working OPM. Transformations = identity
if ('pdb_eliminated' in status[pdbi] and 'opm_eliminated' not in status[pdbi]) or\
('pdb_eliminated' not in status[pdbi] and len(str_data[pdbi]['FROM_PDB']['biological_assemblies'][bioassembly]['transformations']) == 0):
#has_copies_of_chains_OPM, copies_ch_OPM = find_copies_of_chains(OPMpdb_coords, str_data[pdbi]['FROM_OPM']['analysis'], pdbi, pdb_data_pdbi=str_data[pdbi]['FROM_PDB'], pdb_bioassembly_group=-1)
from_pdb = str_data[pdbi]['FROM_PDB']
trd = FixedDict(from_pdb['translrots'].get_fdict_template())
trd['matrix'] = IDmtx.tolist()
trd['vector'] = IDvec.tolist()
from_pdb['translrots'].append(trd)
from_pdb['ktranslrots'].append('1')
bafd = FixedDict(from_pdb['biological_assemblies'].get_fdict_template())
tfd = FixedDict(bafd['transformations'].get_fdict_template())
tfd['chains'] = sorted([c for c in OPMpdb_coords])
tfd['operator'] = ['1']
bafd['transformations'].append(tfd)
from_pdb['biological_assemblies'].append(bafd)
passport[pdbi].append(passport_entry(this_name+'_topmc', pdbi, "This structure does not have reliable biological assembly records coming from the PDB database. The coordinate file coming from the OPM database will be used, along with the implicit identity transformation matrix."))
local_stats['add_identity_transf'].append(pdbi)
# Case 2: working PDB and broken OPM. Take transformations from PDB
if 'opm_eliminated' in status[pdbi] and 'pdb_eliminated' not in status[pdbi]:
passport[pdbi].append(passport_entry(this_name+'_tpdbc', pdbi, "This structure has reliable biological assembly records coming from the PDB database: the related transformation matrices will be used to generate the whole biological assembly"))
# Safety decision
PDB_conditions = {
'sameseq' : None,
'1chain0transf' : None,
'PDB!=OPM' : None,
'weirdtransf' : None
}
# Condition 1: in PDB, two or more chains with coordinates have the exact same sequence
seqset = {PDB_seqs[ch] for ch in PDB_seqs}
if len(seqset) < len(PDB_seqs):
PDB_conditions['sameseq'] = True
local_stats['sameseq'].append(pdbi)
elif len(seqset) == len(PDB_seqs):
PDB_conditions['sameseq'] = False
else:
print_log((
"ERROR",
this_name,
("sequence set: {0}\n"
"chains with coordinates list: {1}")\
.format("\n".join(list(seqset)), PDB_seqs)
))
# Condition 2: in PDB, only 1 chain and the identity transf
translrots = str_data[pdbi]['FROM_PDB']['translrots']
#print(pdbi, [ch for ch in PDB_seqs])
#print(pdbi, len(PDB_seqs), len(translrots), translrots[0]['matrix'], translrots[0]['vector'], translrots[0]['matrix'] == IDmtx.tolist(), translrots[0]['vector'] == IDvec.tolist())
if len(PDB_seqs) == 1 and len(translrots) == 1 and translrots[0]['matrix'] == IDmtx.tolist() and translrots[0]['vector'] == IDvec.tolist():
PDB_conditions['1chain0transf'] = True
local_stats['1chain0transf'].append(pdbi)
else:
PDB_conditions['1chain0transf'] = False
# Condition 3: OPM and PDB signatures differ
# Case 1: both PDB and OPM working.
# If the structure is from OPM, nothing in the structure will be changed or used for changing other structures
# BUT it gets checked for consistency of copies of chains. If it has the same number of copies of all chains as the one suggested by PDB, ok, otherwise
# we trust PDB better than OPM and we update the OPM status in monitored.
if not ({'eliminated', 'pdb_eliminated', 'opm_eliminated'} & set(status[pdbi])):
# The signature indicates the greatest common divisor among the repeated chains.
# ex: the signature of [[A, B, C], [D, E, F], [G, H], [I, L]] is 1, of [[A, B, C, K], [D, E, F, J], [G, H], [I, L]] is 2, of [[A, B, C], [D, E, F], [G, H], [I]] is 1)
# Ideally, the PDB signature should always be 1 * n_of_transformations
# and the OPM signature should coincide with that, demonstrating an agreement on the BA.
transfs = str_data[pdbi]['FROM_PDB']['biological_assemblies'][0]['transformations']
# OPM signature
OPMpdb_coords = retrieve_coords_from_CIF(str_data[pdbi]['FROM_OPM']['cache_coordinate_file'])
has_copies_of_chains_OPM, copies_ch_OPM = find_copies_of_chains(OPMpdb_coords, str_data[pdbi]['FROM_OPM']['analysis'], pdbi, pdb_data_pdbi=str_data[pdbi]['FROM_PDB'], pdb_bioassembly_group=-1)
chain_signature_OPM = find_gcd([len(x) for x in copies_ch_OPM])
# PDB signature
# Catch problematic group signatures and revert, for this case, to individually-calculated signature
if options['PARAMETERS'][('', 'consensus_signature_PDB')] and consensus_signature_PDB[pdbi] != -1:
chain_signature_PDB = consensus_signature_PDB[pdbi]
print("IF")
else:
PDB_coords = retrieve_coords_from_CIF(str_data[pdbi]['FROM_PDB']['cache_coordinate_file'])
has_copies_of_chains_PDB, copies_ch_PDB = find_copies_of_chains(PDB_coords, str_data[pdbi]['FROM_PDB']['analysis'], pdbi, pdb_data_pdbi=str_data[pdbi]['FROM_PDB'], pdb_bioassembly_group=0)
# transfs = str_data[pdbi]['FROM_PDB']['biological_assemblies'][0]['transformations']
chain_signature_PDB = find_gcd([len(x) for x in copies_ch_PDB]) * len(transfs)
print("ELSE")
# OPM <-> PDB signatures
sig_msg = ('NOTICE', this_name, "The structure {0} is characterized by the following chain signatures:\nPDB: {1}\nOPM: {2}".format(pdbi, chain_signature_PDB, chain_signature_OPM))
print_log(sig_msg)
if chain_signature_OPM != chain_signature_PDB:
PDB_conditions['PDB!=OPM'] = True
#status[pdbi].append('opm_monitored')
#status[pdbi].append('pdb_unsafe')
#passport[pdbi].append(passport_entry(this_name+'_chsigneq', pdbi, "This entry displays inconsistencies regarding its quaternary structure. The coordinate file coming from the OPM database is thus considered problematic, and the entry is classified as unreliable (it will not be used to amend other structures)".format(chain_signature_PDB, chain_signature_OPM)))
passport[pdbi].append(passport_entry(this_name+'_chsigneq_followup', pdbi, "The structure displays two different subunit signatures: PDB {0}; OPM {1}.".format(chain_signature_PDB, chain_signature_OPM)))
else:
PDB_conditions['PDB!=OPM'] = False
else:
local_stats['PDB?=OPM'].append(pdbi)
# Condition 4: Translation parallel to axis of rotation
transfs = str_data[pdbi]['FROM_PDB']['biological_assemblies'][bioassembly]['transformations']
t_opers = []
for t in transfs:
t_opers.append(t['operators'])
trs = set()
#print(t_opers)
for ops in t_opers:
for op in ops:
trs |= set(op)
delta = 0.1
ktranslrots = str_data[pdbi]['FROM_PDB']['ktranslrots']
for tr in trs:
itr = ktranslrots.index(tr)
if translrots[itr]['matrix'] == IDmtx.tolist():
continue
rotax = calc_rotation_axis(translrots[itr]['matrix'])
if np.linalg.norm(rotax) < config.epsilon:
local_stats['null_rotax'].append((pdbi, itr, translrots[itr]['matrix']))
#print("NULL ROTATION AXIS", pdbi, itr, translrots[itr]['matrix'], rotax)
trv = np.array(translrots[itr]['vector'])
if not (trv==np.zeros(3)).all():
trv /= np.linalg.norm(trv)
if abs(np.dot(rotax, trv)) > 1 - delta:
PDB_conditions['weirdtransf'] = True
local_stats['weirdtransf'].append(pdbi)
break
if PDB_conditions['weirdtransf'] is None:
PDB_conditions['weirdtransf'] = False
# Decision on conditions 1-4
is_safe = True
if PDB_conditions['sameseq']: # None is caught before
is_safe = False
passport[pdbi].append(passport_entry(
this_name+'_sameseq',
pdbi,
("This entry's PDB coordinate file contains two or more "
"identical sequences.")
))
else:
passport[pdbi].append(passport_entry(
this_name+'_nosameseq',
pdbi,
("This entry's PDB coordinate file contains only unique "
"sequences")
))
if PDB_conditions['1chain0transf']: # None is not possible
is_safe = False
passport[pdbi].append(passport_entry(
this_name+'_1chain0transf',
pdbi,
("This entry's PDB coordinate file contains only one "
"subunit and no bioassembly transformation "
"(excecpt the identity).")
))
else:
passport[pdbi].append(passport_entry(
this_name+'_no1chain0transf',
pdbi,
("This entry's PDB coordinate file contains either "
"multiple subunits of at least one nontrivial "
"biological assembly transformation.")
))
if PDB_conditions['PDB!=OPM'] is None:
passport[pdbi].append(passport_entry(
this_name+'_skipPDBvsOPM',
pdbi,
("The comparison between PDB and OPM biological assemblies "
"could not be done.")
))
is_safe = None
elif PDB_conditions['PDB!=OPM']:
is_safe = False
passport[pdbi].append(passport_entry(
this_name+'_PDB!=OPM',
pdbi,
("The biological assemblies in PDB and OPM records "
"are not identical.")
))
else:
passport[pdbi].append(passport_entry(
this_name+'_PDB==OPM',
pdbi,
("The biological assemblies in PDB and OPM records "
"are identical.")
))
if PDB_conditions['weirdtransf']: # None is not possible
is_safe = False
passport[pdbi].append(passport_entry(
this_name+'_weirdtransf',
pdbi,
("The PDB biological assembly transformations contain at "
"least one translation that is parallel to the axis of "
"the associated rotation")
))
else:
passport[pdbi].append(passport_entry(
this_name+'_noweirdtransf',
pdbi,
("The PDB biological assembly transformations do not contain "
"translations that are parallel to the axis of "
"the associated rotation")
))
if is_safe is None or is_safe:
# Conndition 5: Detached subunits
# Generate full structure
full_coords_PDB, equivalent_chain_sets = generate_full_structure(str_data[pdbi], pdbi, coords=PDB_coords['COORDS'])
passport[pdbi].append(passport_entry(
this_name+'_geneqch',
pdbi,
("The full biological assembly as described in the coordinate "
"file coming from the PDB database was generated from the "
"corresponding transformation matrices, resulting in the "
"following sets of equivalent chains: {0}")\
.format(equivalent_chain_sets)
))
# Last check: if SAFE, then try to generate. Then mark as SAFE or UNSAFE
# If structure wasn't deemed unsafe, it is because the OPM structure agrees with the PDB one, and thus we chose the OPM structure over the PDB one.
# We now have to compile a list of safe structures to remedy the unsafe ones: we start from the OPM-chosen and we see if their full PDB structure is actually reliable.
# If it isn't, that's ok, if it is, they are chosen as SAFE.
if 'pdb_unsafe' not in status[pdbi] and 'pdb_safety_not_available' not in status[pdbi]:
# Check on the generation of the full PDB structure, to see if the transformations are really ok
if not PDB_coords:
PDB_coords = retrieve_coords_from_CIF(str_data[pdbi]['FROM_PDB']['cache_coordinate_file'])
# Generate full structure
full_coords_PDB, equivalent_chain_sets = generate_full_structure(str_data[pdbi], pdbi, coords=PDB_coords['COORDS'])
passport[pdbi].append(passport_entry(
this_name+'_geneqch',
pdbi,
("The full biological assembly as described in the coordinate "
"file coming from the PDB database was generated from the "
"corresponding transformation matrices, resulting in the "
"following sets of equivalent chains: {0}")\
.format(equivalent_chain_sets)
))
# Check for errors
pass_entry, biomatrix_error = check_PDB_biomatrix_errors(options, equivalent_chain_sets, full_coords_PDB, pdbi)
# Conndition 5: Detached subunits
if biomatrix_error:
is_safe = False
local_stats['biomatrix_error'].append(pdbi)
passport[pdbi].append(pass_entry)
if is_safe is None:
status[pdbi].append('pdb_undecided')
passport[pdbi].append(passport_entry(
this_name+'_undecided',
pdbi,
("This entry does not present biological assembly faults "
"but due to incomplete records it will not be taken as "
"a reference for correcting biological assembly defects "
"in other entries")
))
local_stats['undecided'].append(pdbi)
elif not is_safe:
has_copies_of_chains_PDB, copies_ch_PDB = find_copies_of_chains(PDB_coords, str_data[pdbi]['FROM_PDB']['analysis'], pdbi, pdb_data_pdbi=str_data[pdbi]['FROM_PDB'], pdb_bioassembly_group=0)
decsn['UNSAFE'][pdbi] = [sorted(x)[0] for x in copies_ch_PDB]
status[pdbi].append('pdb_unsafe')
passport[pdbi].append(passport_entry(
this_name+'_unsafe',
pdbi,
("This entry presents biological assembly defects and will "
"undergo a correction procedure")
))
local_stats['unsafe'].append(pdbi)
else:
decsn['SAFE'][pdbi] = str_data[pdbi]['FROM_PDB']
status[pdbi].append('pdb_safe')
passport[pdbi].append(passport_entry(
this_name+'_safe',
pdbi,
("This entry does not present biological assembly defects "
"and its records are complete: it will be used as a reference "
"for correcting biological assembly defects in other entries")
))
local_stats['safe'].append(pdbi)
return decsn, status, passport, [x for x in str_data], local_stats
def PDBTM_download(locations, pdbi):
pdb_url = 'http://pdbtm.enzim.hu/data/database/{0}/{1}.trpdb.gz'.format(pdbi[1:3], pdbi)
pdb_filename = locations['FSYSPATH']['PDBTMpdbs'] + pdbi + '_PDBTM.pdb'
pdb_downloaded = reiterated_gzip_download(pdb_url, pdb_filename)
xml_url = 'http://pdbtm.enzim.hu/data/database/{0}/{1}.xml'.format(pdbi[1:3], pdbi)
xml_filename = locations['FSYSPATH']['PDBTMxmls'] + pdbi + '_PDBTM.xml'
xml_downloaded = reiterated_simple_download(xml_url, xml_filename)
return pdb_downloaded and xml_downloaded
def get_sequence_from_CIF(cache_path):
this_name = get_sequence_from_CIF.__name__
with open(cache_path) as cache_file:
loop_descr = False
descriptors = []
column_res = -1
column_ch = -1
old_resid = -99999
sequence = {}
for line in cache_file:
if not line.strip() or line.startswith("#"):
continue
if line.startswith("loop"):
loop_descr = True
continue
if loop_descr:
if line.startswith("_"):
descriptors.append(line.strip())
else:
loop_descr = False
if "_atom_site.label_comp_id" in descriptors:
column_res = descriptors.index("_atom_site.label_comp_id")
if "_atom_site.label_asym_id" in descriptors:
column_ch = descriptors.index("_atom_site.label_asym_id")
if "_atom_site.label_seq_id" in descriptors:
column_resid = descriptors.index("_atom_site.label_seq_id")
continue
else:
if column_res < 0 or column_ch < 0:
continue
resid = int(line.split()[column_resid])
ch = line.split()[column_ch]
if ch not in sequence:
sequence[ch] = ''
old_resid = -999999
if resid > old_resid:
sequence[ch] += from3to1(line.split()[column_res])
old_resid = resid
if not sequence:
print_log((
"ERROR",
this_name,
"No sequences found in {0}".format(cache_path)
))
for ch in sequence:
if not sequence[ch]:
print_log((
"ERROR",
this_name,
"Empty sequence for chain {0} in {1}".format(ch, cache_path)
))
return sequence
def apply_rotation(c_dict, R):
new_c_dict = {'COORDS' : {}, 'DUMMIES' : []}
for ch in c_dict['COORDS']:
new_c_dict['COORDS'][ch] = {}
for resid_name in c_dict['COORDS'][ch]:
new_c_dict['COORDS'][ch][resid_name] = {}
for at in c_dict['COORDS'][ch][resid_name]:
new_c_dict['COORDS'][ch][resid_name][at] = np.dot(R, c_dict['COORDS'][ch][resid_name][at])
for at, c in c_dict['DUMMIES']:
new_c_dict['DUMMIES'].append((at, tuple(np.dot(R, c))))
return new_c_dict
def add_DUM_to_coord_dict(c_dict, z):