-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathensembl_anno.py
4881 lines (4262 loc) · 162 KB
/
ensembl_anno.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
# pylint: disable=logging-not-lazy, invalid-name, missing-function-docstring, subprocess-run-check, unused-variable, redefined-outer-name, too-many-arguments, too-many-locals, too-many-branches, too-many-statements, unused-argument, no-else-return, undefined-variable, no-else-continue, no-else-raise, missing-docstring, consider-swap-variables, consider-using-in, too-many-lines, unused-import
# See the NOTICE file distributed with this work for additional information
# regarding copyright ownership.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
import argparse
import errno
import gc
import glob
import io
import json
import logging
import logging.config
import math
import multiprocessing
import os
import pathlib
import random
import re
import shutil
import signal
import subprocess
import tempfile
import repeatmasking_utils
import simple_feature_utils
import utils
with open(os.environ["ENSCODE"] + "/ensembl-anno/config.json", "r") as f:
config = json.load(f)
def load_results_to_ensembl_db(
main_script_dir,
load_to_ensembl_db,
genome_file,
main_output_dir,
db_details,
num_threads,
repeatmasker_analysis,
):
db_loading_script = os.path.join(
main_script_dir, "support_scripts_perl", "load_gtf_ensembl.pl"
)
db_loading_dir = utils.create_dir(main_output_dir, "db_loading")
# Should collapse this into a function
annotation_results_gtf_file = os.path.join(
main_output_dir, "annotation_output", "annotation.gtf"
)
if os.path.exists(annotation_results_gtf_file):
logger.info("Loading main geneset to db")
batch_size = 200
load_type = "gene"
analysis_name = "ensembl"
gtf_records = batch_gtf_records(
annotation_results_gtf_file, batch_size, db_loading_dir, load_type
)
generic_load_records_to_ensembl_db(
load_to_ensembl_db,
db_loading_script,
genome_file,
db_details,
db_loading_dir,
load_type,
analysis_name,
gtf_records,
num_threads,
)
else:
logger.error(
"Did not find the main gene annotation file, so not loading. Path checked:\n"
+ annotation_results_gtf_file
)
rfam_results_gtf_file = os.path.join(main_output_dir, "rfam_output", "annotation.gtf")
if os.path.exists(rfam_results_gtf_file):
logger.info("Loading Rfam-based sncRNA genes to db")
batch_size = 500
load_type = "gene"
analysis_name = "ncrna"
gtf_records = batch_gtf_records(
rfam_results_gtf_file, batch_size, db_loading_dir, load_type
)
generic_load_records_to_ensembl_db(
load_to_ensembl_db,
db_loading_script,
genome_file,
db_details,
db_loading_dir,
load_type,
analysis_name,
gtf_records,
num_threads,
)
else:
logger.error(
"Did not find an Rfam annotation file, so not loading. Path checked:\n"
+ rfam_results_gtf_file
)
trnascan_results_gtf_file = os.path.join(
main_output_dir, "trnascan_output", "annotation.gtf"
)
if os.path.exists(trnascan_results_gtf_file):
logger.info("Loading tRNAScan-SE tRNA genes to db")
batch_size = 500
load_type = "gene"
analysis_name = "ncrna"
gtf_records = batch_gtf_records(
trnascan_results_gtf_file, batch_size, db_loading_dir, load_type
)
generic_load_records_to_ensembl_db(
load_to_ensembl_db,
db_loading_script,
genome_file,
db_details,
db_loading_dir,
load_type,
analysis_name,
gtf_records,
num_threads,
)
else:
logger.error(
"Did not find an tRNAScan-SE annotation file, so not loading. Path checked:\n"
+ trnascan_results_gtf_file
)
dust_results_gtf_file = os.path.join(main_output_dir, "dust_output", "annotation.gtf")
if os.path.exists(dust_results_gtf_file):
logger.info("Loading Dust repeats to db")
batch_size = 500
load_type = "single_line_feature"
analysis_name = "dust"
gtf_records = batch_gtf_records(
dust_results_gtf_file, batch_size, db_loading_dir, load_type
)
generic_load_records_to_ensembl_db(
load_to_ensembl_db,
db_loading_script,
genome_file,
db_details,
db_loading_dir,
load_type,
analysis_name,
gtf_records,
num_threads,
)
else:
logger.error(
"Did not find a Dust annotation file, so not loading. Path checked:\n"
+ dust_results_gtf_file
)
red_results_gtf_file = os.path.join(main_output_dir, "red_output", "annotation.gtf")
if os.path.exists(red_results_gtf_file):
logger.info("Loading Red repeats to db")
batch_size = 500
load_type = "single_line_feature"
analysis_name = "repeatdetector"
gtf_records = batch_gtf_records(
red_results_gtf_file, batch_size, db_loading_dir, load_type
)
generic_load_records_to_ensembl_db(
load_to_ensembl_db,
db_loading_script,
genome_file,
db_details,
db_loading_dir,
load_type,
analysis_name,
gtf_records,
num_threads,
)
else:
logger.error(
"Did not find a Red annotation file, so not loading. Path checked:\n"
+ red_results_gtf_file
)
trf_results_gtf_file = os.path.join(main_output_dir, "trf_output", "annotation.gtf")
if os.path.exists(trf_results_gtf_file):
logger.info("Loading TRF repeats to db")
batch_size = 500
load_type = "single_line_feature"
analysis_name = "trf"
gtf_records = batch_gtf_records(
trf_results_gtf_file, batch_size, db_loading_dir, load_type
)
generic_load_records_to_ensembl_db(
load_to_ensembl_db,
db_loading_script,
genome_file,
db_details,
db_loading_dir,
load_type,
analysis_name,
gtf_records,
num_threads,
)
else:
logger.error(
"Did not find a TRF annotation file, so not loading. Path checked:\n"
+ trf_results_gtf_file
)
repeatmasker_results_gtf_file = os.path.join(main_output_dir, "repeatmasker_output", "annotation.gtf")
if os.path.exists(repeatmasker_results_gtf_file):
logger.info("Loading Repeatmasker repeats to db")
batch_size = 500
load_type = "single_line_feature"
analysis_name = repeatmasker_analysis #"repeatmask_repbase_human"
gtf_records = batch_gtf_records(
repeatmasker_results_gtf_file, batch_size, db_loading_dir, load_type
)
generic_load_records_to_ensembl_db(
load_to_ensembl_db,
db_loading_script,
genome_file,
db_details,
db_loading_dir,
load_type,
analysis_name,
gtf_records,
num_threads,
)
else:
logger.error(
"Did not find a Repeatmasker annotation file, so not loading. Path checked:\n"
+ repeatmasker_results_gtf_file
)
cpg_results_gtf_file = os.path.join(main_output_dir, "cpg_output", "annotation.gtf")
if os.path.exists(cpg_results_gtf_file):
logger.info("Loading CpG islands to db")
batch_size = 500
load_type = "single_line_feature"
analysis_name = "cpg"
gtf_records = batch_gtf_records(
cpg_results_gtf_file, batch_size, db_loading_dir, load_type
)
generic_load_records_to_ensembl_db(
load_to_ensembl_db,
db_loading_script,
genome_file,
db_details,
db_loading_dir,
load_type,
analysis_name,
gtf_records,
num_threads,
)
else:
logger.error(
"Did not find a CpG annotation file, so not loading. Path checked:\n"
+ cpg_results_gtf_file
)
eponine_results_gtf_file = os.path.join(
main_output_dir, "eponine_output", "annotation.gtf"
)
if os.path.exists(eponine_results_gtf_file):
logger.info("Loading Eponine repeats to db")
batch_size = 500
load_type = "single_line_feature"
analysis_name = "eponine"
gtf_records = batch_gtf_records(
eponine_results_gtf_file, batch_size, db_loading_dir, load_type
)
generic_load_records_to_ensembl_db(
load_to_ensembl_db,
db_loading_script,
genome_file,
db_details,
db_loading_dir,
load_type,
analysis_name,
gtf_records,
num_threads,
)
else:
logger.error(
"Did not find an Eponine annotation file, so not loading. Path checked:\n"
+ eponine_results_gtf_file
)
logger.info("Finished loading records to db")
def generic_load_records_to_ensembl_db(
load_to_ensembl_db,
db_loading_script,
genome_file,
db_details,
db_loading_dir,
load_type,
analysis_name,
gtf_records,
num_threads,
):
pool = multiprocessing.Pool(int(num_threads))
for record_batch in gtf_records:
pool.apply_async(
multiprocess_load_records_to_ensembl_db,
args=(
load_to_ensembl_db,
db_loading_script,
genome_file,
db_details,
db_loading_dir,
load_type,
analysis_name,
record_batch,
),
)
pool.close()
pool.join()
def multiprocess_load_records_to_ensembl_db(
load_to_ensembl_db,
db_loading_script,
genome_file,
db_details,
output_dir,
load_type,
analysis_name,
record_batch,
):
with tempfile.NamedTemporaryFile(
mode="w+t", delete=False, dir=output_dir
) as gtf_temp_out:
for line in record_batch:
gtf_temp_out.writelines(line)
gtf_temp_file_path = gtf_temp_out.name
(db_name, db_host, db_port, db_user, db_pass) = db_details.split(",")
loading_cmd = [
"perl",
db_loading_script,
"-genome_file",
genome_file,
"-dbname",
db_name,
"-host",
db_host,
"-port",
str(db_port),
"-user",
db_user,
"-pass",
db_pass,
"-gtf_file",
gtf_temp_file_path,
"-analysis_name",
analysis_name,
"-load_type",
load_type,
]
if load_type == "gene" and analysis_name == "ensembl":
loading_cmd.extend(
[
"-protein_coding_biotype",
"anno_protein_coding",
"-non_coding_biotype",
"anno_lncRNA",
]
)
if load_to_ensembl_db == "single_transcript_genes":
loading_cmd.append("-make_single_transcript_genes")
logger.info(" ".join(loading_cmd))
subprocess.run(loading_cmd)
gtf_temp_out.close()
os.remove(gtf_temp_file_path) # doesn't seem to be working
logger.info("Finished: " + gtf_temp_file_path)
gc.collect()
def batch_gtf_records(input_gtf_file, batch_size, output_dir, record_type):
records = []
gtf_in = open(input_gtf_file)
if record_type == "gene":
# NOTE that the neverending variations on GTF reading/writing/merging
# is becoming very messy
# need to create a set of utility methods outside of this script
# This one assumes the file has unique ids for the parent features.
# It then batches them into
# sets of records based on the batch size passed in
record_counter = 0
current_record_batch = []
current_gene_id = ""
line = gtf_in.readline()
while line:
if re.search(r"^#", line):
line = gtf_in.readline()
continue
eles = line.split("\t")
if not len(eles) == 9:
line = gtf_in.readline()
continue
match = re.search(r'gene_id "([^"]+)"', line)
gene_id = match.group(1)
if not current_gene_id:
record_counter += 1
current_gene_id = gene_id
if not gene_id == current_gene_id:
record_counter += 1
if record_counter % batch_size == 0:
records.append(current_record_batch)
current_record_batch = []
current_gene_id = gene_id
current_record_batch.append(line)
line = gtf_in.readline()
records.append(current_record_batch)
elif record_type == "single_line_feature":
record_counter = 0
current_record_batch = []
current_gene_id = ""
line = gtf_in.readline()
while line:
if re.search(r"^#", line):
line = gtf_in.readline()
continue
eles = line.split("\t")
if not len(eles) == 9:
line = gtf_in.readline()
continue
record_counter += 1
if record_counter % batch_size == 0:
records.append(current_record_batch)
current_record_batch = []
current_record_batch.append(line)
line = gtf_in.readline()
records.append(current_record_batch)
gtf_in.close()
return records
def run_find_orfs(genome_file, main_output_dir):
min_orf_length = 600
orf_output_dir = utils.create_dir(main_output_dir, "orf_output")
seq_region_lengths = utils.get_seq_region_lengths(genome_file, 5000)
for region_name in seq_region_lengths:
region_length = seq_region_lengths[region_name]
seq = utils.get_sequence(
region_name, 1, region_length, 1, genome_file, orf_output_dir
)
for phase in range(0, 6):
find_orf_phased_region(
region_name, seq, phase, min_orf_length, orf_output_dir
)
def find_orf_phased_region(region_name, seq, phase, min_orf_length, orf_output_dir):
current_index = phase
orf_counter = 1
if phase > 2:
seq = reverse_complement(seq)
current_index = current_index % 3
orf_file_path = os.path.join(
orf_output_dir, (region_name + ".phase" + str(phase) + ".orf.fa")
)
orf_out = open(orf_file_path, "w+")
while current_index < len(seq):
codon = seq[current_index : current_index + 3]
if codon == "ATG":
orf_seq = codon
for j in range(current_index + 3, len(seq), 3):
next_codon = seq[j : j + 3]
if next_codon == "TAA" or next_codon == "TAG" or next_codon == "TGA":
orf_seq += next_codon
if len(orf_seq) >= min_orf_length:
orf_out.write(
">"
+ region_name
+ "_phase"
+ str(phase)
+ "_orf"
+ str(orf_counter)
+ "\n"
)
orf_out.write(orf_seq + "\n")
orf_counter += 1
orf_seq = ""
break
# If there's another met in phase, then put i to the start of
# the codon after j so that only the longest ORF is found
if next_codon == "ATG":
current_index = j + 3
orf_seq += next_codon
current_index += 3
orf_out.close()
def run_trnascan_regions(
genome_file,
trnascan_path,
trnascan_filter_path,
main_output_dir,
num_threads,
):
if not trnascan_path:
trnascan_path = config["trnascan"]["software"]
logger.info(trnascan_path)
if not trnascan_filter_path:
trnascan_filter_path = config["trnascan"]["filter_path"]
logger.info(trnascan_filter_path)
utils.check_exe(trnascan_path)
logger.info(trnascan_path)
# check_exe(trnascan_filter_path)
check_file(trnascan_filter_path)
logger.info(trnascan_filter_path)
trnascan_output_dir = utils.create_dir(main_output_dir, "trnascan_output")
logger.info("Skip analysis if the gtf file already exists")
output_file = os.path.join(trnascan_output_dir, "annotation.gtf")
if os.path.exists(output_file):
transcript_count = utils.check_gtf_content(output_file, "transcript")
if transcript_count > 0:
logger.info("Trnascan gtf file exists")
return
else:
logger.info("No gtf file, go on with the analysis")
logger.info("Creating list of genomic slices")
seq_region_lengths = utils.get_seq_region_lengths(genome_file, 5000)
slice_ids = utils.create_slice_ids(seq_region_lengths, 1000000, 0, 5000)
generic_trnascan_cmd = [
trnascan_path,
None,
"-o",
None,
"-f",
None,
"-H",
"-q",
"--detail",
"-Q",
]
logger.info("Running tRNAscan-SE")
pool = multiprocessing.Pool(int(num_threads))
tasks = []
for slice_id in slice_ids:
pool.apply_async(
multiprocess_trnascan,
args=(
generic_trnascan_cmd,
slice_id,
genome_file,
trnascan_filter_path,
trnascan_output_dir,
),
)
pool.close()
pool.join()
utils.slice_output_to_gtf(trnascan_output_dir, ".trna.gtf", 1, None, None)
def multiprocess_trnascan(
generic_trnascan_cmd,
slice_id,
genome_file,
trnascan_filter_path,
trnascan_output_dir,
):
region_name = slice_id[0]
start = slice_id[1]
end = slice_id[2]
logger.info(
"Processing slice to find tRNAs using tRNAscan-SE: "
+ region_name
+ ":"
+ str(start)
+ ":"
+ str(end)
)
seq = utils.get_sequence(region_name, start, end, 1, genome_file, trnascan_output_dir)
slice_file_name = region_name + ".rs" + str(start) + ".re" + str(end)
region_fasta_file_name = slice_file_name + ".fa"
region_fasta_file_path = os.path.join(trnascan_output_dir, region_fasta_file_name)
region_fasta_out = open(region_fasta_file_path, "w+")
region_fasta_out.write(">" + region_name + "\n" + seq + "\n")
region_fasta_out.close()
region_results_file_name = slice_file_name + ".trna.gtf"
region_results_file_path = os.path.join(trnascan_output_dir, region_results_file_name)
trnascan_output_file_path = region_fasta_file_path + ".trna"
trnascan_ss_output_file_path = trnascan_output_file_path + ".ss"
# The filter takes an output dir and a prefix
# and then uses those to make a path to a .out file
trnascan_filter_file_prefix = region_fasta_file_name + ".filt"
trnascan_filter_file_name = trnascan_filter_file_prefix + ".out"
trnascan_filter_log_file_name = trnascan_filter_file_prefix + ".log"
trnascan_filter_ss_file_name = trnascan_filter_file_prefix + ".ss"
trnascan_filter_file_path = os.path.join(
trnascan_output_dir, trnascan_filter_file_name
)
trnascan_filter_log_file_path = os.path.join(
trnascan_output_dir, trnascan_filter_log_file_name
)
trnascan_filter_ss_file_path = os.path.join(
trnascan_output_dir, trnascan_filter_ss_file_name
)
trnascan_cmd = generic_trnascan_cmd.copy()
trnascan_cmd[1] = region_fasta_file_path
trnascan_cmd[3] = trnascan_output_file_path
trnascan_cmd[5] = trnascan_ss_output_file_path
logger.info("tRNAscan-SE command:")
logger.info(" ".join(trnascan_cmd))
subprocess.run(trnascan_cmd)
# If we have a blank output file at this point
# we want to stop and remove whatever files
# have been created instead of moving onto the filter
if os.stat(trnascan_output_file_path).st_size == 0:
os.remove(trnascan_output_file_path)
os.remove(region_fasta_file_path)
if os.path.exists(trnascan_ss_output_file_path):
os.remove(trnascan_ss_output_file_path)
return
filter_cmd = [
trnascan_filter_path,
"--result",
trnascan_output_file_path,
"--ss",
trnascan_ss_output_file_path,
"--output",
trnascan_output_dir,
"--prefix",
trnascan_filter_file_prefix,
]
logger.info("tRNAscan-SE filter command:")
logger.info(" ".join(filter_cmd))
subprocess.run(filter_cmd)
create_trnascan_gtf(region_results_file_path, trnascan_filter_file_path, region_name)
if os.path.exists(trnascan_output_file_path):
os.remove(trnascan_output_file_path)
if os.path.exists(trnascan_ss_output_file_path):
os.remove(trnascan_ss_output_file_path)
if os.path.exists(trnascan_filter_file_path):
os.remove(trnascan_filter_file_path)
if os.path.exists(trnascan_filter_log_file_path):
os.remove(trnascan_filter_log_file_path)
if os.path.exists(trnascan_filter_ss_file_path):
os.remove(trnascan_filter_ss_file_path)
if os.path.exists(region_fasta_file_path):
os.remove(region_fasta_file_path)
def create_trnascan_gtf(region_results_file_path, trnascan_filter_file_path, region_name):
trna_in = open(trnascan_filter_file_path, "r")
trna_out = open(region_results_file_path, "w+")
line = trna_in.readline()
gene_counter = 1
while line:
result_match = re.search(r"^" + region_name, line)
if result_match:
results = line.split()
start = int(results[2])
end = int(results[3])
trna_type = results[4]
score = results[8]
strand = "+"
if start > end:
strand = "-"
temp_end = start
start = end
end = temp_end
biotype = "tRNA_pseudogene"
high_confidence_match = re.search(r"high confidence set", line)
if high_confidence_match:
biotype = "tRNA"
transcript_string = (
region_name
+ "\ttRNAscan\ttranscript\t"
+ str(start)
+ "\t"
+ str(end)
+ "\t.\t"
+ strand
+ "\t.\t"
+ 'gene_id "'
+ str(gene_counter)
+ '"; transcript_id "'
+ str(gene_counter)
+ '"; biotype "'
+ biotype
+ '";\n'
)
exon_string = (
region_name
+ "\ttRNAscan\texon\t"
+ str(start)
+ "\t"
+ str(end)
+ "\t.\t"
+ strand
+ "\t.\t"
+ 'gene_id "'
+ str(gene_counter)
+ '"; transcript_id "'
+ str(gene_counter)
+ '"; exon_number "1"; biotype "'
+ biotype
+ '";\n'
)
trna_out.write(transcript_string)
trna_out.write(exon_string)
gene_counter += 1
line = trna_in.readline()
trna_in.close()
trna_out.close()
def run_cmsearch_regions(
genome_file,
cmsearch_path,
rfam_cm_db_path,
rfam_seeds_file_path,
rfam_accession_file,
main_output_dir,
num_threads,
):
if not cmsearch_path:
cmsearch_path = config["cmsearch"]["software"]
utils.check_exe(cmsearch_path)
rfam_output_dir = utils.create_dir(main_output_dir, "rfam_output")
os.chdir(rfam_output_dir)
logger.info("Skip analysis if the gtf file already exists")
output_file = os.path.join(rfam_output_dir, "annotation.gtf")
if os.path.exists(output_file):
transcript_count = utils.check_gtf_content(output_file, "transcript")
if transcript_count > 0:
logger.info("Cmsearch gtf file exists")
return
else:
logger.info("No gtf file, go on with the analysis")
rfam_dbname = config["cmsearch"]["rfam_dbname"]
rfam_user = config["cmsearch"]["rfam_user"]
rfam_host = config["cmsearch"]["rfam_host"]
rfam_port = config["cmsearch"]["rfam_port"]
# rfam_accession_query_cmd = ["mysql -h", rfam_host,"-u",rfam_user,
# "-P",rfam_port,"-NB -e",rfam_dbname,"'select rfam_acc FROM (SELECT DISTINCT
# f.rfam_acc, f.rfam_id, f.type, f.description, f.gathering_cutoff,
# f.trusted_cutoff FROM full_region fr, rfamseq rf, taxonomy tx, family f WHERE
# rf.ncbi_id = tx.ncbi_id AND f.rfam_acc = fr.rfam_acc AND fr.rfamseq_acc = rf.rfamseq_acc
# AND LOWER(tx.tax_string) LIKE \'%" + clade + "%\' AND (f.type LIKE \'%snRNA%\'
# OR f.type LIKE \'%rRNA%\' OR LOWER(f.rfam_id) LIKE \'%rnase%\' OR
# LOWER(f.rfam_id) LIKE \'%vault%\' OR LOWER(f.rfam_id) LIKE \'%y_rna%\'
# OR f.rfam_id LIKE \'%Metazoa_SRP%\') AND is_significant = 1) AS TEMP
# WHERE rfam_id NOT LIKE \'%bacteria%\' AND rfam_id NOT LIKE \'%archaea%\'
# AND rfam_id NOT LIKE \'%microsporidia%\';'"]
# mysql -hmysql-rfam-public.ebi.ac.uk -urfamro -P4497 Rfam -NB -e "select rfam_acc
# FROM (SELECT DISTINCT f.rfam_acc, f.rfam_id, f.type, f.description,
# f.gathering_cutoff, f.trusted_cutoff FROM full_region fr, rfamseq rf,
# taxonomy tx, family f WHERE rf.ncbi_id = tx.ncbi_id AND f.rfam_acc = fr.rfam_acc
# AND fr.rfamseq_acc = rf.rfamseq_acc AND LOWER(tx.tax_string) LIKE '%insect%' AND
# (f.type LIKE '%snRNA%' OR f.type LIKE '%rRNA%' OR LOWER(f.rfam_id) LIKE '%rnase%'
# OR LOWER(f.rfam_id) LIKE '%vault%' OR LOWER(f.rfam_id) LIKE '%y_rna%'
# OR f.rfam_id LIKE '%Metazoa_SRP%') AND is_significant = 1) AS TEMP WHERE rfam_id NOT
# LIKE '%bacteria%' AND rfam_id NOT LIKE '%archaea%' AND rfam_id NOT LIKE '%microsporidia%';"
# rfam_accession_file = '/hps/nobackup2/production/ensembl/fergal/production/
# test_runs/non_verts/butterfly/rfam_insect_ids.txt'
# rfam_accession_file = os.path.join(main_output_dir,'rfam_accessions.txt')
rfam_cm_db_path = config["cmsearch"]["rfam_cm_db_path"]
rfam_seeds_file_path = config["cmsearch"]["rfam_seeds_file_path"]
rfam_selected_models_file = os.path.join(rfam_output_dir, "rfam_models.cm")
with open(rfam_accession_file) as rfam_accessions_in:
rfam_accessions = rfam_accessions_in.read().splitlines()
with open(rfam_cm_db_path, "r") as rfam_cm_in:
rfam_data = rfam_cm_in.read()
rfam_models = rfam_data.split("//\n")
rfam_cm_out = open(rfam_selected_models_file, "w+")
for model in rfam_models:
# The Rfam.cm file has INFERNAL and HMMR models, both are needed at this point
# Later we just want the INFERNAL ones for looking at thresholds
match = re.search(r"(RF\d+)", model)
if match:
model_accession = match.group(1)
if model_accession in rfam_accessions:
rfam_cm_out.write(model + "//\n")
rfam_cm_out.close()
seed_descriptions = get_rfam_seed_descriptions(rfam_seeds_file_path)
cv_models = extract_rfam_metrics(rfam_selected_models_file)
logger.info("Creating list of genomic slices")
seq_region_lengths = utils.get_seq_region_lengths(genome_file, 5000)
slice_ids = utils.create_slice_ids(seq_region_lengths, 100000, 0, 5000)
generic_cmsearch_cmd = [
cmsearch_path,
"--rfam",
"--cpu",
"1",
"--nohmmonly",
"--cut_ga",
"--tblout",
]
logger.info("Running Rfam")
pool = multiprocessing.Pool(int(num_threads))
results = []
failed_slice_ids = []
memory_limit = 3 * 1024**3
for slice_id in slice_ids:
pool.apply_async(
multiprocess_cmsearch,
args=(
generic_cmsearch_cmd,
slice_id,
genome_file,
rfam_output_dir,
rfam_selected_models_file,
cv_models,
seed_descriptions,
memory_limit,
),
)
pool.close()
pool.join()
# Need to figure something more automated out here. At the moment
# it's just limiting to 5 cores and 5GB vram
# Ideally we could look at the amount of mem requested and put something like
# 10GB per core and then figure
# out how many cores to use (obviously not using more than the amount specified)
memory_limit = 5 * 1024**3
if num_threads > 5:
num_threads = 5
pool = multiprocessing.Pool(num_threads)
exception_files = glob.glob(rfam_output_dir + "/*.rfam.except")
for exception_file_path in exception_files:
exception_file_name = os.path.basename(exception_file_path)
logger.info("Running himem job for failed region:\n" + exception_file_path)
match = re.search(r"(.+)\.rs(\d+)\.re(\d+)\.", exception_file_name)
if match:
except_region = match.group(1)
except_start = match.group(2)
except_end = match.group(3)
except_slice_id = [except_region, except_start, except_end]
pool.apply_async(
multiprocess_cmsearch,
args=(
generic_cmsearch_cmd,
except_slice_id,
genome_file,
rfam_output_dir,
rfam_selected_models_file,
cv_models,
seed_descriptions,
memory_limit,
),
)
pool.close()
pool.join()
utils.slice_output_to_gtf(rfam_output_dir, ".rfam.gtf", 1, None, None)
def prlimit_command(command_list, virtual_memory_limit):
"""
Prepend memory limiting arguments to a command list to be run with subprocess.
This method uses the `prlimit` program to set the memory limit.
The `virtual_memory_limit` size is in bytes.
prlimit arguments:
-v, --as[=limits]
Address space limit.
"""
return ["prlimit", f"-v{virtual_memory_limit}"] + command_list
def multiprocess_cmsearch(
generic_cmsearch_cmd,
slice_id,
genome_file,
rfam_output_dir,
rfam_selected_models_file,
cv_models,
seed_descriptions,
memory_limit,
):
region_name = slice_id[0]
start = slice_id[1]
end = slice_id[2]
logger.info(
"Processing Rfam data using cmsearch against slice: "
+ region_name
+ ":"
+ str(start)
+ ":"
+ str(end)
)
seq = utils.get_sequence(region_name, start, end, 1, genome_file, rfam_output_dir)
slice_file_name = region_name + ".rs" + str(start) + ".re" + str(end)
region_fasta_file_name = slice_file_name + ".fa"
region_fasta_file_path = os.path.join(rfam_output_dir, region_fasta_file_name)
region_fasta_out = open(region_fasta_file_path, "w+")
region_fasta_out.write(">" + region_name + "\n" + seq + "\n")
region_fasta_out.close()
region_tblout_file_name = slice_file_name + ".tblout"
region_tblout_file_path = os.path.join(rfam_output_dir, region_tblout_file_name)
region_results_file_name = slice_file_name + ".rfam.gtf"
region_results_file_path = os.path.join(rfam_output_dir, region_results_file_name)
exception_results_file_name = slice_file_name + ".rfam.except"
exception_results_file_path = os.path.join(
rfam_output_dir, exception_results_file_name
)
cmsearch_cmd = generic_cmsearch_cmd.copy()
cmsearch_cmd.append(region_tblout_file_path)
cmsearch_cmd.append(rfam_selected_models_file)
cmsearch_cmd.append(region_fasta_file_path)
logger.info(" ".join(cmsearch_cmd))
if memory_limit is not None:
cmsearch_cmd = prlimit_command(cmsearch_cmd, memory_limit)
logger.info(" ".join(cmsearch_cmd))
return_value = None
try:
return_value = subprocess.check_output(cmsearch_cmd)
except subprocess.CalledProcessError as ex: