-
Notifications
You must be signed in to change notification settings - Fork 1
/
RNAnet.py
executable file
·3254 lines (2815 loc) · 159 KB
/
RNAnet.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/python3
# check Python version before everything
import platform
a = ["3.8", platform.python_version()]
a.sort()
if a[0] != "3.8":
print(f"Python is too old: {platform.python_version()}")
print("Please use version 3.8 or newer.")
exit(1)
import Bio.PDB as pdb
import concurrent.futures
import getopt
import gzip
import io
import json
import numpy as np
import os
import pandas as pd
import pickle
import psutil
import re
import requests
import signal
import sqlalchemy
import sqlite3
import subprocess
import sys
import time
import traceback
import warnings
from functools import partial, wraps
from multiprocessing import Pool, Manager, Value
from time import sleep
from tqdm import tqdm
from setproctitle import setproctitle
from Bio import AlignIO, SeqIO
from Bio.SeqIO.FastaIO import FastaIterator, SimpleFastaParser
from Bio.Seq import MutableSeq
from Bio.SeqRecord import SeqRecord
from Bio.Align import MultipleSeqAlignment
from collections import defaultdict
from Bio.PDB.PDBIO import Select
runDir = os.getcwd()
def trace_unhandled_exceptions(func):
"""
Captures exceptions even in parallel sections of the code and child processes,
and throws logs in red to stderr and to errors.txt.
Should be defined before the classes that use it.
"""
@wraps(func)
def wrapped_func(*args, **kwargs):
try:
return func(*args, **kwargs)
except:
s = traceback.format_exc()
if not "KeyboardInterrupt" in s:
with open(runDir + "/errors.txt", "a") as f:
f.write("Exception in "+func.__name__+"\n")
f.write(s)
f.write("\n\n")
warn('Exception in '+func.__name__, error=True)
print(s)
return wrapped_func
pd.set_option('display.max_rows', None)
sqlite3.enable_callback_tracebacks(True)
sqlite3.register_adapter(np.int64, lambda val: int(val)) # Tell Sqlite what to do with <class numpy.int64> objects ---> convert to int
sqlite3.register_adapter(np.float64, lambda val: float(val)) # Tell Sqlite what to do with <class numpy.float64> objects ---> convert to float
n_launched = Value('i', 0)
n_finished = Value('i', 0)
n_skipped = Value('i', 0)
path_to_3D_data = "tobedefinedbyoptions"
path_to_seq_data = "tobedefinedbyoptions"
python_executable = "python"+".".join(platform.python_version().split('.')[:2]) # Cuts python3.8.1 into python3.8 for example.
validsymb = '\U00002705'
warnsymb = '\U000026A0'
errsymb = '\U0000274C'
LSU_set = {"RF00002", "RF02540", "RF02541", "RF02543", "RF02546"} # From Rfam CLAN 00112
SSU_set = {"RF00177", "RF02542", "RF02545", "RF01959", "RF01960"} # From Rfam CLAN 00111
no_nts_set = set()
weird_mappings = set()
class MutableFastaIterator(FastaIterator):
"""
Same as Biopython's FastaIterator, but uses Bio.Seq.MutableSeq objects instead of Bio.Seq.Seq.
"""
def iterate(self, handle):
"""Parse the file and generate SeqRecord objects."""
title2ids = self.title2ids
if title2ids:
for title, sequence in SimpleFastaParser(handle):
id, name, descr = title2ids(title)
yield SeqRecord(MutableSeq(sequence), id=id, name=name, description=descr)
else:
for title, sequence in SimpleFastaParser(handle):
try:
first_word = title.split(None, 1)[0]
except IndexError:
assert not title, repr(title)
first_word = ""
yield SeqRecord(MutableSeq(sequence), id=first_word, name=first_word, description=title)
class SelectivePortionSelector(object):
"""Class passed to MMCIFIO to select some chain portions in an MMCIF file.
Validates every chain, residue, nucleotide, to say if it is in the selection or not.
The primary use is to select the portion of a chain which is mapped to a family.
"""
def __init__(self, model_id, chain_id, valid_resnums, khetatm):
self.chain_id = chain_id
self.resnums = valid_resnums # list of strings, that are mostly ints
self.pdb_model_id = model_id
self.hydrogen_regex = re.compile("[123 ]*H.*")
self.keep_hetatm = khetatm
def accept_model(self, model):
return int(model.get_id() == self.pdb_model_id)
def accept_chain(self, chain):
return int(chain.get_id() == self.chain_id)
def accept_residue(self, residue):
hetatm_flag, resseq, icode = residue.get_id()
# Refuse waters and magnesium ions
if hetatm_flag in ["W", "H_MG"]:
return int(self.keep_hetatm)
# Accept the residue if it is in the right interval:
if icode == " " and len(self.resnums):
return int(str(resseq) in self.resnums)
elif icode != " " and len(self.resnums):
return int(str(resseq)+icode in self.resnums)
else: # len(resnum) == 0, we don't use mappings (--no-homology option)
return 1
def accept_atom(self, atom):
# Refuse hydrogens
if self.hydrogen_regex.match(atom.get_id()):
return 0
# Refuse the first two phosohate groups when residue is a triphosphate
if atom.get_id() in ['O3B', 'O2B', 'O1B', 'PB', 'O3G', 'O2G', 'O1G', 'PG' ]:
return 0
# Accept all atoms otherwise.
return 1
class Chain:
"""
The object which stores all our data and the methods to process it.
Chains accumulate information through this scipt, and are saved to files at the end of major steps.
"""
def __init__(self, pdb_id, pdb_model, pdb_chain_id, chain_label, eq_class, rfam="", inferred=False, pdb_start=None, pdb_end=None):
self.pdb_id = pdb_id # PDB ID
self.pdb_model = int(pdb_model) # model ID, starting at 1
self.pdb_chain_id = pdb_chain_id # chain ID (mmCIF), multiple letters
if len(rfam):
self.mapping = Mapping(chain_label, rfam, pdb_start, pdb_end, inferred)
else:
self.mapping = None
self.eq_class = eq_class # BGSU NR list class id
self.chain_label = chain_label # chain pretty name
self.file = "" # path to the 3D PDB file
self.seq = "" # sequence with modified nts
self.seq_to_align = "" # sequence with modified nts replaced by N, but gaps can exist
self.length = -1 # length of the sequence (missing residues are not counted)
self.full_length = -1 # length of the chain extracted from source structure ([start; stop] interval, or a subset for inferred mappings)
self.delete_me = False # an error occured during production/parsing
self.error_messages = "" # Error message(s) if any
self.db_chain_id = -1 # index of the RNA chain in the SQL database, table chain
def __str__(self):
if self.mapping is None:
return self.pdb_id + '[' + str(self.pdb_model) + "]-" + self.pdb_chain_id
else:
return self.pdb_id + '[' + str(self.pdb_model) + "]-" + self.pdb_chain_id + "-" + self.mapping.rfam_acc
def __eq__(self, other):
return self.chain_label == other.chain_label and str(self) == str(other)
def __hash__(self):
return hash((self.pdb_id, self.pdb_model, self.pdb_chain_id, self.chain_label))
def extract(self, df, khetatm) -> None:
""" Extract the part which is mapped to Rfam from the main CIF file and save it to another file.
"""
setproctitle(f"RNANet.py {self.chain_label} extract()")
if self.mapping is not None:
status = f"Extract {self.mapping.nt_start}-{self.mapping.nt_end} atoms from {self.pdb_id}-{self.pdb_chain_id}"
self.file = path_to_3D_data+"rna_mapped_to_Rfam/"+self.chain_label+".cif"
else:
status = f"Extract {self.pdb_id}-{self.pdb_chain_id}"
self.file = path_to_3D_data+"rna_only/"+self.chain_label+".cif"
# Check if file exists, if yes, abort (do not recompute)
if os.path.exists(self.file):
notify(status, "using previous file")
return
model_idx = self.pdb_model - (self.pdb_model > 0) # because arrays start at 0, models start at 1
with warnings.catch_warnings():
# Ignore the PDB problems. This mostly warns that some chain is discontinuous.
warnings.simplefilter('ignore', pdb.PDBExceptions.PDBConstructionWarning)
warnings.simplefilter('ignore', pdb.PDBExceptions.BiopythonWarning)
# Load the whole mmCIF into a Biopython structure object:
mmcif_parser = pdb.MMCIFParser()
try:
s = mmcif_parser.get_structure(self.pdb_id, path_to_3D_data + "RNAcifs/"+self.pdb_id+".cif")
except ValueError as e:
warn(f"ValueError in {self.chain_label} CIF file: {e}")
self.delete_me = True
return
except IndexError as e:
warn(f"IndexError in {self.chain_label} CIF file: {e}")
self.delete_me = True
return
if self.mapping is not None:
valid_set = set(df.old_nt_resnum)
else:
valid_set = set()
# Define a selection
sel = SelectivePortionSelector(model_idx, self.pdb_chain_id, valid_set, khetatm)
# save the selection sel into a new structure
new_s=pdb.Structure.Structure(s.get_id())
for model in s:
if sel.accept_model(model):
new_model=pdb.Model.Model(model.get_id())
for chain in model:
if sel.accept_chain(chain):
new_chain=pdb.Chain.Chain(chain.get_id())
for res in chain:
if sel.accept_residue(res):
res_atoms=res.get_atoms()
new_residu=pdb.Residue.Residue(res.get_id(), res.get_resname(), res.get_segid())
for atom in list(res.get_atoms()):
if sel.accept_atom(atom):
new_atom=atom.copy()
new_residu.add(new_atom)
new_chain.add(new_residu)
new_model.add(new_chain)
new_s.add(new_model)
# renumber this structure (portion of the original) with the index_chain and save it in a cif file
t = pdb.Structure.Structure(new_s.get_id())
for model in new_s:
new_model_t=pdb.Model.Model(model.get_id())
for chain in model:
nums=df[["index_chain", "old_nt_resnum", "nt_name"]]
new_chain_t=pdb.Chain.Chain(chain.get_id())
for i in nums.index:
resseq=nums.at[i, 'old_nt_resnum']
icode_res=' '
if type(resseq) is str:
if resseq=='not resolved':
continue
if resseq[0] != '-' :
while resseq.isdigit() is False:
l=len(resseq)
if icode_res==' ':
icode_res=resseq[l-1]
else :
icode_res=resseq[l-1]+icode_res
resseq=resseq[:l-1]
resseq=int(resseq)
index_chain=nums.at[i, "index_chain"]
nt=nums.at[i, "nt_name"]
# particular case 6n5s_1_A, residue 201 in the original cif file (resname = G and HETATM = H_G)
if nt == 'A' or (nt == 'G' and (self.chain_label != '6n5s_1_A' or resseq != 201)) or nt == 'C' or nt == 'U' or nt in ['DG', 'DU', 'DC', 'DA', 'DI', 'DT' ] or nt == 'N' or nt == 'I' :
res=chain[(' ', resseq, icode_res)]
else : # modified nucleotides (e.g. chain 5l4o_1_A)
het='H_' + nt
res=chain[(het, resseq, icode_res)]
res_id=res.get_id()
res_id=list(res_id)
res_id[1]=index_chain
res_id[2]=' '
res_id[0]=' '
res_id=tuple(res_id)
if nt in ['ATP', 'GTP', 'CTP', 'UTP']:
res_name = res.get_resname()[0]
else :
res_name=res.get_resname()
res_atoms=res.get_atoms()
new_residu_t=pdb.Residue.Residue(res_id, res_name, res.get_segid())
for atom in list(res.get_atoms()):
# rename the remaining phosphate group to P, OP1, OP2, OP3
if atom.get_name() in ['PA', 'O1A', 'O2A', 'O3A'] and res_name != 'RIA':
# RIA is a residue made up of 2 riboses and 2 phosphates,
# so it has an O2A atom between the C2A and C1 'atoms,
# and it also has an OP2 atom attached to one of its phosphates
# (see chains 6fyx_1_1, 6zu9_1_1, 6fyy_1_1, 6gsm_1_1 , 3jaq_1_1 and 1yfg_1_A)
# we do not modify the atom names of RIA residue
if atom.get_name() == 'PA':
atom_name = 'P'
if atom.get_name() == 'O1A':
atom_name = 'OP1'
if atom.get_name() == 'O2A':
atom_name = 'OP2'
if atom.get_name() == 'O3A':
atom_name = 'OP3'
new_atom_t = pdb.Atom.Atom(atom_name, atom.get_coord(), atom.get_bfactor(), atom.get_occupancy(), atom.get_altloc(), atom_name, atom.get_serial_number())
else:
new_atom_t=atom.copy()
new_residu_t.add(new_atom_t)
new_chain_t.add(new_residu_t)
new_model_t.add(new_chain_t)
t.add(new_model_t)
# Save that renumbered selection on the mmCIF object s to file
ioobj = pdb.MMCIFIO()
ioobj.set_structure(t)
save_mmcif(ioobj, self.file)
notify(status)
@trace_unhandled_exceptions
def extract_3D_data(self, save_logs=True):
""" Maps DSSR annotations to the chain. """
setproctitle(f"RNANet.py {self.chain_label} extract_3D_data()")
############################################
# Load the mmCIF annotations from file
############################################
try:
with open(path_to_3D_data + "annotations/" + self.pdb_id + ".json", 'r') as json_file:
json_object = json.load(json_file)
notify(f"Read {self.pdb_id} DSSR annotations")
except json.decoder.JSONDecodeError as e:
warn("Could not load "+self.pdb_id+f".json with JSON package: {e}", error=True)
self.delete_me = True
self.error_messages = f"Could not load existing {self.pdb_id}.json file: {e}"
return None
# Print eventual warnings given by DSSR, and abort if there are some
if "warning" in json_object.keys():
warn(f"found DSSR warning in annotation {self.pdb_id}.json: {json_object['warning']}. Ignoring {self.chain_label}.")
if "no nucleotides" in json_object['warning']:
no_nts_set.add(self.pdb_id)
self.delete_me = True
self.error_messages = f"DSSR warning {self.pdb_id}.json: {json_object['warning']}. Ignoring {self.chain_label}."
return None
############################################
# Create the data-frame
############################################
try:
# Create the Pandas DataFrame for the nucleotides of the right chain
nts = json_object["nts"] # sub-json-object
df = pd.DataFrame(nts) # conversion to dataframe
df = df[df.chain_name == self.pdb_chain_id] # keeping only this chain's nucleotides
# Assert nucleotides of the chain are found
if df.empty:
warn(f"Could not find nucleotides of chain {self.pdb_chain_id} in annotation {self.pdb_id}.json. Ignoring chain {self.chain_label}.")
no_nts_set.add(self.pdb_id)
self.delete_me = True
self.error_messages = f"Could not find nucleotides of chain {self.pdb_chain_id} in annotation {self.pdb_id}.json. Either there is a problem with {self.pdb_id} mmCIF download, or the bases are not resolved in the structure. Delete it and retry."
return None
# Remove low pertinence or undocumented descriptors
cols_we_keep = ["index_chain", "nt_resnum", "nt_name", "nt_code", "nt_id", "dbn", "alpha", "beta", "gamma", "delta", "epsilon", "zeta",
"epsilon_zeta", "bb_type", "chi", "glyco_bond", "form", "ssZp", "Dp", "eta", "theta", "eta_prime", "theta_prime", "eta_base", "theta_base",
"v0", "v1", "v2", "v3", "v4", "amplitude", "phase_angle", "puckering"]
df = df[cols_we_keep]
except KeyError as e:
warn(f"Error while parsing DSSR {self.pdb_id}.json output:{e}", error=True)
self.delete_me = True
self.error_messages = f"Error while parsing DSSR's json output:\n{e}"
return None
#############################################
# Select the nucleotides we need
#############################################
# Remove nucleotides of the chain that are outside the Rfam mapping, if any
if self.mapping is not None:
if self.mapping.nt_start > self.mapping.nt_end:
warn(f"Mapping is reversed, this case is not supported (yet). Ignoring chain {self.chain_label}.")
self.delete_me = True
self.error_messages = f"Mapping is reversed, this case is not supported (yet)."
return None
df = self.mapping.filter_df(df)
# Duplicate residue numbers : shift numbering
while True in df.duplicated(['nt_resnum']).values:
i = df.duplicated(['nt_resnum']).values.tolist().index(True)
duplicates = df[df.nt_resnum == df.iloc[i, 1]]
n_dup = len(duplicates.nt_resnum)
index_last_dup = duplicates.index_chain.iloc[-1] - 1
if self.mapping is not None:
self.mapping.log(f"Shifting nt_resnum numbering because of {n_dup} duplicate residues {df.iloc[i,1]}")
try:
if i > 0 and index_last_dup + 1 < len(df.index) and df.iloc[i, 1] == df.iloc[i-1, 1] and df.iloc[index_last_dup + 1, 1] - 1 > df.iloc[index_last_dup, 1]:
# The redundant nts are consecutive in the chain (at the begining at least), and there is a gap at the end
if duplicates.iloc[n_dup-1, 0] - duplicates.iloc[0, 0] + 1 == n_dup:
# They are all contiguous in the chain
# 4v9n-DA case (and similar ones) : 610-611-611A-611B-611C-611D-611E-611F-611G-617-618...
# there is a redundancy (611) followed by a gap (611-617).
# We want the redundancy to fill the gap.
df.iloc[i:i+n_dup-1, 1] += 1
else:
# We solve the problem continous component by continuous component
for j in range(1, n_dup+1):
if duplicates.iloc[j, 0] == 1 + duplicates.iloc[j-1, 0]: # continuous
df.iloc[i+j-1, 1] += 1
else:
break
elif df.iloc[i, 1] == df.iloc[i-1, 1]:
# Common 4v9q-DV case (and similar ones) : e.g. chains contains 17 and 17A which are both read 17 by DSSR.
# Solution : we shift the numbering of 17A (to 18) and the following residues.
df.iloc[i:, 1] += 1
elif duplicates.iloc[0, 0] == 1 and df.iloc[i, 0] == 3:
# 4wzo_1_1J case, there is a residue numbered -1 and read as 1 before the number 0.
df.iloc[1:, 1] += 1
df.iloc[0, 1] = 0
else:
# 4v9k-DA case (and similar ones) : the nt_id is not the full nt_resnum: ... 1629 > 1630 > 163B > 1631 > ...
# Here the 163B is read 163 by DSSR, but there already is a residue 163.
# Solution : set nt_resnum[i] to nt_resnum[i-1] + 1, and shift the following by 1.
df.iloc[i, 1] = 1 + df.iloc[i-1, 1]
df.iloc[i+1:, 1] += 1
except:
warn(f"Error with parsing of {self.chain_label} duplicate residue numbers. Ignoring it.")
self.delete_me = True
self.error_messages = f"Error with parsing of duplicate residues numbers."
return None
# Search for ligands at the end of the selection
# Drop ligands detected as residues by DSSR, by detecting several markers
while (
len(df.index_chain) and df.iloc[-1, 2] not in ["A", "C", "G", "U"]
and (
(df.iloc[[-1]][["alpha", "beta", "gamma", "delta", "epsilon",
"zeta", "v0", "v1", "v2", "v3", "v4"]].isna().values).all()
or (df.iloc[[-1]].puckering == '').any()
)
# large nt_resnum gap between the two last residues
or (len(df.index_chain) >= 2 and df.iloc[-1, 1] > 50 + df.iloc[-2, 1])
or (len(df.index_chain) and df.iloc[-1, 2] in ["GNG", "E2C", "OHX", "IRI", "MPD", "8UZ"])
):
if self.mapping is not None:
self.mapping.log("Droping ligand:")
self.mapping.log(df.tail(1))
df = df.head(-1)
# Duplicates in index_chain : drop, they are ligands
# e.g. 3iwn_1_B_1-91, ligand C2E has index_chain 1 (and nt_resnum 601)
duplicates = [ index for index, element in enumerate(df.duplicated(['index_chain']).values) if element ]
if len(duplicates):
for i in duplicates:
warn(f"Found duplicated index_chain {df.iloc[i,0]} in {self.chain_label}. Keeping only the first.")
if self.mapping is not None:
self.mapping.log(f"Found duplicated index_chain {df.iloc[i,0]}. Keeping only the first.")
df = df.drop_duplicates("index_chain", keep="first") # drop doublons in index_chain
# drop eventual nts with index_chain < the first residue,
# now negative because we renumber to 1 (usually, ligands)
ligands = df[df.index_chain < 0]
if len(ligands.index_chain):
if self.mapping is not None:
for line in ligands.iterrows():
self.mapping.log("Droping ligand:")
self.mapping.log(line)
df = df.drop(ligands.index)
# Find missing index_chain values
# This happens because of resolved nucleotides that have a
# strange nt_resnum value. Thanks, biologists ! :@ :(
# e.g. 4v49-AA, position 5'- 1003 -> 2003 -> 1004 - 3'
diff = set(range(df.shape[0])).difference(df['index_chain'] - 1)
if len(diff) and self.mapping is not None:
# warn(f"Missing residues in chain numbering: {[1+i for i in sorted(diff)]}")
for i in sorted(diff):
# check if a nucleotide with the correct index_chain exists in the nts object
found = None
for nt in nts: # nts is the object from the loaded JSON and contains all nts
if nt['chain_name'] != self.pdb_chain_id:
continue
if nt['index_chain'] == i + 1 + self.mapping.st:
found = nt # Retrieves old angle values from the JSON !
break
if found:
self.mapping.log(f"Residue {i+1+self.mapping.st}-{self.mapping.st} = {i+1} has been saved and renumbered {df.iloc[i,1]} instead of {found['nt_id'].replace(found['chain_name']+ '.' + found['nt_name'], '').replace('^','')}")
df_row = pd.DataFrame([found], index=[i])[df.columns.values]
df_row.iloc[0, 0] = i+1 # index_chain
df_row.iloc[0, 1] = df.iloc[i, 1] # nt_resnum
df = pd.concat([df.iloc[:i], df_row, df.iloc[i:]])
df.iloc[i+1:, 1] += 1
else:
warn(f"Missing index_chain {i} in {self.chain_label} !")
# Assert some nucleotides still exist
try:
# update length of chain from nt_resnum point of view
l = df.iloc[-1, 1] - df.iloc[0, 1] + 1
except IndexError:
warn(f"Could not find real nucleotides of chain {self.pdb_chain_id} between {self.mapping.nt_start} and "
f"{self.mapping.nt_end} ({'not ' if not self.mapping.inferred else ''}inferred). Ignoring chain {self.chain_label}.")
no_nts_set.add(self.pdb_id)
self.delete_me = True
self.error_messages = f"Could not find nucleotides of chain {self.pdb_chain_id} in annotation {self.pdb_id}.json. Either there is a problem with {self.pdb_id} mmCIF download, or the bases are not resolved in the structure. Delete it and retry."
return None
# Add eventual missing rows because of unsolved residues in the chain.
# Sometimes, the 3D structure is REALLY shorter than the family it's mapped to,
# especially with inferred mappings (e.g. 6hcf chain 82 to RF02543)
#
# There are several numbering scales in use here:
# nt_numbering: the residue numbers in the RNA molecule. It can be any range. Unresolved residues count for 1.
# index_chain and self.length: the nucleotides positions within the 3D chain. It starts at 1, and unresolved residues are skipped.
# pdb_start/pdb_end: the RNA molecule portion to extract and map to Rfam. it is related to the index_chain scale.
#
# example on 6hcf chain 82:
# RNA molecule 1 |------------------------------------------- ... ----------| theoretic length of a large subunit.
# portion solved in 3D 1 |--------------|79 85|------------| 156
# Rfam mapping 3 |------------------------------------------ ... -------| 3353 (yes larger, 'cause it could be inferred)
# nt resnum 3 |--------------------------------| 156
# index_chain 1 |-------------|77 83|------------| 154
# expected data point 1 |--------------------------------| 154
#
if l != len(df['index_chain']): # if some residues are missing, len(df['index_chain']) < l
resnum_start = df.iloc[0, 1]
# the rowIDs the missing nucleotides would have (rowID = index_chain - 1 = nt_resnum - resnum_start)
diff = set(range(l)).difference(df['nt_resnum'] - resnum_start)
for i in sorted(diff):
# Add a row at position i
df = pd.concat([df.iloc[:i],
pd.DataFrame({"index_chain": i+1, "nt_resnum": i+resnum_start,
"nt_id": "not resolved", "nt_code": '-', "nt_name": '-'}, index=[i]),
df.iloc[i:]])
# Increase the index_chain of all following lines
df.iloc[i+1:, 0] += 1
df = df.reset_index(drop=True)
self.full_length = len(df.index_chain)
#######################################
# Compute new features
#######################################
# Convert angles
df.loc[:, ['alpha', 'beta', 'gamma', 'delta', 'epsilon', 'zeta', 'epsilon_zeta', 'chi', 'v0', 'v1', 'v2', 'v3', 'v4', # Conversion to radians
'eta', 'theta', 'eta_prime', 'theta_prime', 'eta_base', 'theta_base', 'phase_angle']] *= np.pi/180.0
df.loc[:, ['alpha', 'beta', 'gamma', 'delta', 'epsilon', 'zeta', 'epsilon_zeta', 'chi', 'v0', 'v1', 'v2', 'v3', 'v4', # mapping [-pi, pi] into [0, 2pi]
'eta', 'theta', 'eta_prime', 'theta_prime', 'eta_base', 'theta_base', 'phase_angle']] %= (2.0*np.pi)
# Add a sequence column just for the alignments
df['nt_align_code'] = [str(x).upper()
.replace('NAN', '-') # Unresolved nucleotides are gaps
.replace('?', 'N') # Unidentified residues, let's delete them
.replace('T', 'U') # 5MU are modified to t by DSSR, which gives T
.replace('P', 'U') # Pseudo-uridines, but it is not really right to change them to U, see DSSR paper, Fig 2
for x in df['nt_code']]
df['nt_align_code'] = [ x if x in "ACGU-" else 'N' for x in df['nt_align_code'] ] # All other modified nucleotides are transformed to N
# One-hot encoding sequence
df["is_A"] = [1 if x == "A" else 0 for x in df["nt_code"]]
df["is_C"] = [1 if x == "C" else 0 for x in df["nt_code"]]
df["is_G"] = [1 if x == "G" else 0 for x in df["nt_code"]]
df["is_U"] = [1 if x == "U" else 0 for x in df["nt_code"]]
df["is_other"] = [0 if x in "ACGU" else 1 for x in df["nt_code"]]
df["nt_position"] = [ float(i+1)/self.full_length for i in range(self.full_length) ]
# Iterate over pairs to identify base-base interactions
res_ids = list(df['nt_id']) # things like "chainID.C4, chainID.U5"
paired = [''] * self.full_length
pair_type_LW = [''] * self.full_length
pair_type_DSSR = [''] * self.full_length
interacts = [0] * self.full_length
if "pairs" in json_object.keys():
pairs = json_object["pairs"]
for p in pairs:
nt1 = p["nt1"]
nt2 = p["nt2"]
lw_pair = p["LW"]
dssr_pair = p["DSSR"]
if nt1 in res_ids:
nt1_idx = res_ids.index(nt1)
else:
nt1_idx = -1
if nt2 in res_ids:
nt2_idx = res_ids.index(nt2)
else:
nt2_idx = -1
# set nucleotide 1
if nt1 in res_ids:
interacts[nt1_idx] += 1
if paired[nt1_idx] == "":
pair_type_LW[nt1_idx] = lw_pair
pair_type_DSSR[nt1_idx] = dssr_pair
paired[nt1_idx] = str(nt2_idx + 1) # index + 1 is actually index_chain.
else:
pair_type_LW[nt1_idx] += ',' + lw_pair
pair_type_DSSR[nt1_idx] += ',' + dssr_pair
paired[nt1_idx] += ',' + str(nt2_idx + 1) # index + 1 is actually index_chain.
# set nucleotide 2 with the opposite base-pair
if nt2 in res_ids:
interacts[nt2_idx] += 1
if paired[nt2_idx] == "":
if lw_pair != "--":
pair_type_LW[nt2_idx] = lw_pair[0] + lw_pair[2] + lw_pair[1]
else:
pair_type_LW[nt2_idx] = "--"
if dssr_pair != "--":
pair_type_DSSR[nt2_idx] = dssr_pair[0] + dssr_pair[3] + dssr_pair[2] + dssr_pair[1]
else:
pair_type_DSSR[nt2_idx] = "--"
paired[nt2_idx] = str(nt1_idx + 1)
else:
if lw_pair != "--":
pair_type_LW[nt2_idx] += ',' + lw_pair[0] + lw_pair[2] + lw_pair[1]
else:
pair_type_LW[nt2_idx] += ",--"
if dssr_pair != "--":
pair_type_DSSR[nt2_idx] += ',' + dssr_pair[0] + dssr_pair[3] + dssr_pair[2] + dssr_pair[1]
else:
pair_type_DSSR[nt2_idx] += ",--"
paired[nt2_idx] += ',' + str(nt1_idx + 1)
# transform nt_id to shorter values
df['old_nt_resnum'] = [ n.replace(self.pdb_chain_id+'.'+name, '').replace('^', '').replace('/', '') for n, name in zip(df.nt_id, df.nt_name) ]
df['paired'] = paired
df['pair_type_LW'] = pair_type_LW
df['pair_type_DSSR'] = pair_type_DSSR
df['nb_interact'] = interacts
# remove now useless descriptors
df = df.drop(['nt_id', 'nt_resnum'], axis=1)
self.seq = "".join(df.nt_code)
self.seq_to_align = "".join(df.nt_align_code)
self.length = len([x for x in self.seq_to_align if x != "-"])
# Remove too short chains
if self.length < 5:
warn(f"{self.chain_label} sequence is too short, let's ignore it.\t")
self.delete_me = True
self.error_messages = "Sequence is too short. (< 5 resolved nts)"
return None
# Log chain info to file
if save_logs and self.mapping is not None:
self.mapping.to_file(self.chain_label+".log")
return df
def register_chain(self, df):
"""
Saves the extracted 3D data to the database.
"""
setproctitle(f"RNANet.py {self.chain_label} register_chain()")
with sqlite3.connect(runDir+"/results/RNANet.db", timeout=10.0) as conn:
conn.execute('pragma journal_mode=wal') # Allow multiple other readers to ask things while we execute this writing query
# Register the chain in table chain
if self.mapping is not None:
sql_execute(conn, f""" INSERT INTO chain
(structure_id, chain_name, pdb_start, pdb_end, rfam_acc, eq_class, inferred, issue)
VALUES
(?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(structure_id, chain_name, rfam_acc) DO
UPDATE SET pdb_start=excluded.pdb_start,
pdb_end=excluded.pdb_end,
eq_class=excluded.eq_class,
inferred=excluded.inferred,
issue=excluded.issue;""",
data=(str(self.pdb_id), str(self.pdb_chain_id),
int(self.mapping.nt_start), int(self.mapping.nt_end),
str(self.mapping.rfam_acc), str(self.eq_class),
int(self.mapping.inferred), int(self.delete_me)))
# get the chain id
self.db_chain_id = sql_ask_database(conn, f"""SELECT (chain_id) FROM chain
WHERE structure_id='{self.pdb_id}'
AND chain_name='{self.pdb_chain_id}'
AND rfam_acc='{self.mapping.rfam_acc}'
AND eq_class='{self.eq_class}';"""
)[0][0]
else:
sql_execute(conn, """INSERT INTO chain (structure_id, chain_name, rfam_acc, eq_class, issue) VALUES (?, ?, 'unmappd', ?, ?)
ON CONFLICT(structure_id, chain_name, rfam_acc) DO UPDATE SET issue=excluded.issue, eq_class=excluded.eq_class;""",
data=(str(self.pdb_id), str(self.pdb_chain_id), str(self.eq_class), int(self.delete_me)))
self.db_chain_id = sql_ask_database(conn, f"""SELECT (chain_id) FROM chain
WHERE structure_id='{self.pdb_id}'
AND chain_name='{self.pdb_chain_id}'
AND eq_class='{self.eq_class}'
AND rfam_acc = 'unmappd';"""
)[0][0]
# Add the nucleotides if the chain is not an issue
if df is not None and not self.delete_me: # double condition is theoretically redundant here, but you never know
sql_execute(conn, f"""INSERT OR IGNORE INTO nucleotide
(chain_id, index_chain, nt_name, nt_code, dbn, alpha, beta, gamma, delta, epsilon, zeta,
epsilon_zeta, bb_type, chi, glyco_bond, form, ssZp, Dp, eta, theta, eta_prime, theta_prime, eta_base, theta_base,
v0, v1, v2, v3, v4, amplitude, phase_angle, puckering, nt_align_code, is_A, is_C, is_G, is_U, is_other, nt_position,
old_nt_resnum, paired, pair_type_LW, pair_type_DSSR, nb_interact)
VALUES ({self.db_chain_id}, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);""",
many=True, data=list(df.to_records(index=False)), warn_every=10)
class Job:
""" This class contains information about a task to run later.
This could be a system command or the execution of a Python function.
Time and memory usage of a job can be monitored.
"""
def __init__(self, results="", command=[], function=None, args=[], how_many_in_parallel=0, priority=1, timeout=None, checkFunc=None, checkArgs=[], label=""):
self.cmd_ = command # A system command to run
self.func_ = function # A python function to run
self.args_ = args # The args tuple of the function to run
self.checkFunc_ = checkFunc # A function to check if the Job as already been executed before (and abort execution if yes)
self.checkArgs_ = checkArgs # Arguments for the checkFunc
self.results_file = results # A filename where the job stores its results, to check for existence before execution
self.priority_ = priority # Priority of the job in a list of jobs (Jobs with priority 1 are processed first, then priority 2, etc. Unrelated to processes priority.)
self.timeout_ = timeout # Abort the job if taking too long
self.comp_time = -1 # Time to completion of the job. -1 means 'not executed yet'
self.max_mem = -1 # Peak RAM+Swap usage of the job. -1 means 'not executed yet'
self.label = label # Title
# Deploy the job on a Pool() started using 'how_many_in_parallel' CPUs.
if not how_many_in_parallel:
self.nthreads = read_cpu_number()
elif how_many_in_parallel == -1:
self.nthreads = read_cpu_number() - 1
else:
self.nthreads = how_many_in_parallel
def __str__(self):
if self.func_ is None:
s = f"{self.priority_}({self.nthreads}) [{self.comp_time}]\t{self.label:25}" + " ".join(self.cmd_)
else:
s = f"{self.priority_}({self.nthreads}) [{self.comp_time}]\t{self.label:25}{self.func_.__name__}(" \
+ " ".join([ str(a) for a in self.args_ ]) + ")"
return s
class Monitor:
""" A job that simply watches the memory usage of another process.
Checks the RAM+Swap usage of monitored process and its children every 0.1 sec.
Returns the peak value at the end.
"""
def __init__(self, pid):
self.keep_watching = True
self.target_pid = pid
def check_mem_usage(self):
# Get the process object
target_process = psutil.Process(self.target_pid)
# Start watching
max_mem = -1
while self.keep_watching:
try:
# read memory usage
info = target_process.memory_full_info()
mem = info.rss + info.swap
# Do the same for every child process
for p in target_process.children(recursive=True):
info = p.memory_full_info()
mem += info.rss + info.swap
except psutil.NoSuchProcess:
# The process that we watch is finished, dead, or killed.
self.keep_watching = False
finally:
# Update the peak value
if mem > max_mem:
max_mem = mem
# Wait 100 ms and loop
sleep(0.1)
# The watch has ended
return max_mem
class Downloader:
"""
An object with methods to download public data from the internet.
"""
def download_Rfam_PDB_mappings(self):
"""Query the Rfam public MySQL database for mappings between their RNA families and PDB structures.
"""
setproctitle(f"RNANet.py download_Rfam_PDB_mappings()")
# Download PDB mappings to Rfam family
print("> Fetching latest PDB mappings from Rfam..." + " " * 29, end='', flush=True)
try:
db_connection = sqlalchemy.create_engine('mysql+pymysql://rfamro@mysql-rfam-public.ebi.ac.uk:4497/Rfam')
mappings = pd.read_sql('SELECT rfam_acc, pdb_id, chain, pdb_start, pdb_end, bit_score, evalue_score, cm_start, cm_end, hex_colour FROM pdb_full_region WHERE is_significant=1;',
con=db_connection)
mappings.to_csv(runDir + "/data/Rfam-PDB-mappings.csv")
print(f"\t{validsymb}")
except sqlalchemy.exc.OperationalError: # Cannot connect :'(
print(f"\t{errsymb}")
# Check if a previous run succeeded (if file exists, use it)
if os.path.isfile(runDir + "/data/Rfam-PDB-mappings.csv"):
print("\t> Using previous version.")
mappings = pd.read_csv(runDir + "/data/Rfam-PDB-mappings.csv")
else: # otherwise, abort.
print("Can't do anything without data. Exiting.")
raise Exception("Can't reach mysql-rfam-public.ebi.ac.uk on port 4497. Is it open on your system ?")
return mappings
def download_Rfam_cm(self):
""" Download the covariance models from Rfam.
Does not download if already there.
"""
setproctitle(f"RNANet.py download_Rfam_cm()")
print(f"\t> Download Rfam.cm.gz from Rfam..." + " " * 37, end='', flush=True)
if not os.path.isfile(path_to_seq_data + "Rfam.cm"):
try:
subprocess.run(["wget", "ftp://ftp.ebi.ac.uk/pub/databases/Rfam/CURRENT/Rfam.cm.gz", "-O", path_to_seq_data + "Rfam.cm.gz"])
print(f"\t{validsymb}", flush=True)
print(f"\t\t> Uncompressing Rfam.cm...", end='', flush=True)
subprocess.run(["gunzip", path_to_seq_data + "Rfam.cm.gz"], stdout=subprocess.DEVNULL)
print(f"\t{validsymb}", flush=True)
except:
warn(f"Error downloading and/or extracting Rfam.cm !\t", error=True)
else:
print(f"{validsymb}\t(no need)", flush=True)
def download_Rfam_family_stats(self, list_of_families):
"""Query the Rfam public MySQL database for statistics about their RNA families.
Family ID, number of sequences identified, maximum length of those sequences.
SETS family in the database (partially)
"""
setproctitle(f"RNANet.py download_Rfam_family_stats()")
try:
db_connection = sqlalchemy.create_engine('mysql+pymysql://rfamro@mysql-rfam-public.ebi.ac.uk:4497/Rfam')
# Prepare the SQL query. It computes the length of the chains and gets the maximum length by family.
q = """SELECT stats.rfam_acc, k.description, stats.maxlength FROM
(SELECT fr.rfam_acc, MAX(
(CASE WHEN fr.seq_start > fr.seq_end THEN fr.seq_start
ELSE fr.seq_end
END)
-
(CASE WHEN fr.seq_start > fr.seq_end THEN fr.seq_end
ELSE fr.seq_start
END) + 1
) AS 'maxlength'
FROM full_region fr
GROUP BY fr.rfam_acc
) as stats
NATURAL JOIN
(SELECT rfam_acc, description FROM keywords) as k;
"""
# Query the public database
d = pd.read_sql(q, con=db_connection)
# filter the results to families we are interested in
d = d[d["rfam_acc"].isin(list_of_families)]
print(d)
with sqlite3.connect(runDir + "/results/RNANet.db", timeout=20.0) as conn:
conn.execute('pragma journal_mode=wal') # Allow multiple other readers to ask things while we execute this writing query
# We use the REPLACE keyword to get the latest information
sql_execute(conn, """INSERT OR REPLACE INTO family (rfam_acc, description, max_len)
VALUES (?, ?, ?);""",
many=True,
data=list(d.to_records(index=False))
)
except sqlalchemy.exc.OperationalError:
warn("Something's wrong with the SQL database. Check mysql-rfam-public.ebi.ac.uk status and try again later. Not printing statistics.")
def download_Rfam_sequences(self, rfam_acc):
""" Downloads the unaligned sequences known related to a given RNA family.
Actually gets a FASTA archive from the public Rfam FTP. Does not download if already there."""
setproctitle(f"RNANet.py download_Rfam_sequences({rfam_acc})")
if not os.path.isfile(path_to_seq_data + f"rfam_sequences/fasta/{rfam_acc}.fa.gz"):
for _ in range(10): # retry 100 times if it fails
try:
subprocess.run(["wget", f'ftp://ftp.ebi.ac.uk/pub/databases/Rfam/CURRENT/fasta_files/{rfam_acc}.fa.gz', "-O",
path_to_seq_data + f"rfam_sequences/fasta/{rfam_acc}.fa.gz"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
notify(f"Downloaded {rfam_acc}.fa.gz from Rfam")
return # if it worked, no need to retry
except Exception as e:
warn(f"Error downloading {rfam_acc}.fa.gz: {e}")
warn("retrying in 0.2s (worker " + str(os.getpid()) + f', try {_+1}/100)')
time.sleep(0.2)
warn("Tried to reach Rfam FTP 100 times and failed. Aborting.", error=True)
else:
notify(f"Downloaded {rfam_acc}.fa.gz from Rfam", "already there")
def download_BGSU_NR_list(self, res):
""" Downloads a list of RNA 3D structures proposed by Bowling Green State University RNA research group.
The chosen list is the one with resolution threshold just above the desired one.
Does not remove structural redundancy.
"""
setproctitle(f"RNANet.py download_BGSU_NR_list({res})")
nr_code = min([i for i in [1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 20.0] if i >= res])
print(f"> Fetching latest list of RNA files at {nr_code} A resolution from BGSU website...", end='', flush=True)
# Download latest BGSU non-redundant list
try:
s = requests.get(f"http://rna.bgsu.edu/rna3dhub/nrlist/download/current/{nr_code}A/csv").content
nr = open(path_to_3D_data + f"latest_nr_list_{nr_code}A.csv", 'w')
nr.write("class,representative,class_members\n")
nr.write(io.StringIO(s.decode('utf-8')).getvalue())
nr.close()
except:
warn("Error downloading NR list !\t", error=True)
# Try to read previous file
if os.path.isfile(path_to_3D_data + f"latest_nr_list_{nr_code}A.csv"):
print("\t> Use of the previous version.\t", end="", flush=True)
else:
return pd.DataFrame([], columns=["class","representative","class_members"])
nrlist = pd.read_csv(path_to_3D_data + f"latest_nr_list_{nr_code}A.csv")
full_structures_list = [ tuple(i[1]) for i in nrlist[["class","representative","class_members"]].iterrows() ]
print(f"\t{validsymb}", flush=True)
# The beginning of an adventure.
return full_structures_list # list of ( str (class), str(representative),str (class_members) )
def download_from_SILVA(self, unit):
setproctitle(f"RNANet.py download_from_SILVA({unit})")
if not os.path.isfile(path_to_seq_data + f"realigned/{unit}.arb"):
try:
print(f"Downloading {unit} from SILVA...", end='', flush=True)
if unit == "LSU":
subprocess.run(["wget", "-nv", "https://www.arb-silva.de/fileadmin/arb_web_db/release_138_1/ARB_files/SILVA_138.1_LSURef_opt.arb.gz",
"-O", path_to_seq_data + "realigned/LSU.arb.gz"])
else:
subprocess.run(["wget", "-nv", "https://www.arb-silva.de/fileadmin/arb_web_db/release_138_1/ARB_files/SILVA_138.1_SSURef_opt.arb.gz",
"-O", path_to_seq_data + "realigned/SSU.arb.gz"])
except:
warn(f"Error downloading the {unit} database from SILVA", error=True)
exit(1)
subprocess.run(["gunzip", path_to_seq_data + f"realigned/{unit}.arb.gz"], stdout=subprocess.DEVNULL)
print('\t'+validsymb)
else:
notify(f"Downloaded and extracted {unit} database from SILVA", "used previous file")
class Mapping:
"""
A custom class to store more information about nucleotide mappings.