-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathr2dt.py
executable file
·1290 lines (1151 loc) · 38.5 KB
/
r2dt.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Copyright [2009-present] EMBL-European Bioinformatics Institute
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.
"""
# pylint: disable=too-many-lines
import glob
import json
import os
import re
import shutil
import tarfile
import time
import unittest
from pathlib import Path
import click # pylint: disable=import-error
from rich import print as rprint
from tests import tests
from utils import config, core
from utils import generate_cm_library as gcl
from utils import generate_model_info as gmi
from utils import gtrnadb
from utils import list_models as lm
from utils import r2r, rfam
from utils import rna2djsonschema as r2djs
from utils import shared
from utils.rnartist import RnaArtist
from utils.runner import runner
from utils.scale_template import scale_coordinates
class Timer:
"""
Context manager that logs execution time.
"""
def __init__(self, msg: str, quiet: bool = False):
self.msg = msg
self.quiet = quiet
self.start = None
self.end = None
self.interval = None
def __enter__(self):
self.start = time.time()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.end = time.time()
self.interval = self.end - self.start
if not self.quiet:
rprint(
f"[yellow]Elapsed time for {self.msg}[/yellow]: {self.interval:.2f} seconds"
)
@click.group()
def cli():
"""Required click stub function."""
@cli.command()
def version():
"""
Print R2DT version information.
"""
rprint(shared.get_r2dt_version_header())
@cli.command()
def setup():
"""
Generate all templates from scratch.
"""
rprint(shared.get_r2dt_version_header())
if not os.path.exists(config.CM_LIBRARY):
os.makedirs(config.CM_LIBRARY)
crw_setup()
rfam.setup()
gtrnadb.setup()
def crw_setup():
"""Setup CRW CM library."""
if os.path.exists(config.CRW_CM_LIBRARY):
rprint("Deleting old CRW library")
shutil.rmtree(config.CRW_CM_LIBRARY)
# Extract the tar.gz file
rprint("Extracting precomputed CRW archive")
with tarfile.open(os.path.join(config.DATA, "crw-cms.tar.gz"), "r:gz") as tar:
tar.extractall(path=config.DATA)
# Move the directory
source_dir = os.path.join(config.DATA, "crw-cms")
destination_dir = os.path.join(config.CM_LIBRARY, "crw")
if os.path.exists(source_dir):
shutil.move(source_dir, destination_dir)
# read CRW blacklist
crw_blacklist = []
with open(os.path.join(config.DATA, "crw-blacklist.txt")) as f_in:
for line in f_in:
if line.startswith("#"):
continue
crw_blacklist.append(line.strip())
# Delete models from the blacklist
for model in crw_blacklist:
model_file = os.path.join(config.CRW_CM_LIBRARY, model + ".cm")
if os.path.exists(model_file):
os.remove(model_file)
rprint("Generating CRW modelinfo file")
gmi.generate_model_info(cm_library=config.CRW_CM_LIBRARY)
@cli.command()
@click.option("--rnartist", default=False, is_flag=True)
def setup_rfam(rnartist):
"""
Re-generate Rfam templates from scratch.
"""
rprint(shared.get_r2dt_version_header())
if not rnartist:
rprint("Generating Rfam templates")
rfam.setup()
rprint("Setting up RNArtist")
rfam.setup_rnartist(rerun=False)
def get_seq_ids(input_fasta):
"""
Get a list of sequence ids from a fasta file.
"""
seq_ids = set()
with open(input_fasta) as f_in:
for line in f_in:
if line.startswith(">"):
match = re.search(r">(.*?)\s", line)
if match:
seq_ids.add(match.group(1))
return seq_ids
def get_hits(folder):
"""
Get a list of sequence ids found in the hits.txt file by ribovore.
"""
hits = set()
hits_file = os.path.join(folder, "hits.txt")
if not os.path.exists(hits_file):
return hits
with open(hits_file) as f_in:
for line in f_in:
hits.add(line.split("\t")[0])
return hits
def get_subset_fasta(fasta_input, output_filename, seq_ids):
"""
Extract a fasta file named <output_filename> with sequence ids <seq_ids>
from <fasta_input>.
"""
index_filename = output_filename + ".txt"
with open(index_filename, "w") as f_out:
for seq_id in seq_ids:
f_out.write(f"{seq_id}\n")
runner.run(f"esl-sfetch -o {output_filename} -f {fasta_input} {index_filename}")
runner.run(f"esl-sfetch --index {output_filename}")
os.remove(index_filename)
def is_templatefree(fasta_input):
"""Check if the input file is a valid fasta file
with an additional line specifying secondary structure
in dot bracket format (pseudoknots allowed)."""
with open(fasta_input) as f_in:
lines = [line.strip() for line in f_in.readlines() if line.strip()]
if len(lines) != 3:
return False
header, sequence, structure = lines
if not header.startswith(">"):
return False
if len(sequence) != len(structure):
return False
if not re.match(r"^[.()<>{}[\]A-z]+$", structure):
return False
return True
@cli.command()
@click.argument("fasta-input", type=click.Path())
@click.argument("output-folder", type=click.Path())
@click.option(
"--force_template",
type=click.STRING,
default=None,
help="Force sequences into a specific template",
)
@click.option(
"--constraint", default=False, is_flag=True, help="Fold insertions using RNAfold"
)
@click.option("--exclusion", default=None)
@click.option("--fold_type", default=None)
@click.option("--quiet", "-q", default=False, is_flag=True)
@click.option(
"--skip_ribovore_filters",
default=False,
is_flag=True,
help="Ignore ribovore QC checks",
)
@click.pass_context
# pylint: disable-next=too-many-arguments, too-many-locals, too-many-statements, too-many-branches
def draw(
ctx,
fasta_input,
output_folder,
force_template,
constraint,
exclusion,
fold_type,
quiet,
skip_ribovore_filters,
):
"""
Single entry point for visualising 2D for an RNA sequence.
Selects a template and runs Traveler using CRW, LSU, or Rfam libraries.
"""
if not quiet:
rprint(shared.get_r2dt_version_header())
fasta_input = shared.sanitise_fasta(fasta_input)
if is_templatefree(fasta_input):
if not quiet:
rprint("Detected templatefree input.")
ctx.invoke(
templatefree,
fasta_input=fasta_input,
output_folder=output_folder,
quiet=quiet,
)
return
all_seq_ids = get_seq_ids(fasta_input)
if force_template:
for seq_id in all_seq_ids:
force_draw(
force_template,
fasta_input,
output_folder,
seq_id,
constraint,
exclusion,
fold_type,
quiet=True,
)
return
os.makedirs(output_folder, exist_ok=True)
crw_output = os.path.join(output_folder, "crw")
ribovision_ssu_output = os.path.join(output_folder, "ribovision-ssu")
ribovision_lsu_output = os.path.join(output_folder, "ribovision-lsu")
rfam_output = os.path.join(output_folder, "rfam")
gtrnadb_output = os.path.join(output_folder, "gtrnadb")
rfam_trna_output = os.path.join(output_folder, "RF00005")
rnasep_output = os.path.join(output_folder, "rnasep")
tmrna_output = os.path.join(output_folder, "tmrna")
hits = set()
subset_fasta = os.path.join(output_folder, "subset.fasta")
runner.run(f"esl-sfetch --index {fasta_input}")
def get_output_subfolder(method_name):
"""Get folder within the output folder for a given method."""
subfolders = {
"ribovision_draw_ssu": os.path.join(output_folder, "ribovision-ssu"),
"ribovision_draw_lsu": os.path.join(output_folder, "ribovision-lsu"),
"rrna_draw": os.path.join(output_folder, "crw"),
"rnasep_draw": os.path.join(output_folder, "rnasep"),
"tmrna_draw": os.path.join(output_folder, "tmrna"),
}
return subfolders.get(str(method_name), "")
method_list = [
"rnasep_draw",
"tmrna_draw",
"ribovision_draw_ssu",
"ribovision_draw_lsu",
"rrna_draw", # CRW
]
prev_output_subfolder = None
for method_name in method_list:
if prev_output_subfolder:
hits = hits.union(get_hits(prev_output_subfolder))
subset = all_seq_ids.difference(hits)
if subset:
get_subset_fasta(fasta_input, subset_fasta, subset)
else:
subset = all_seq_ids
shutil.copy(fasta_input, subset_fasta)
runner.run(f"esl-sfetch --index {subset_fasta}")
if subset:
with Timer(f"{method_name}", quiet):
if not quiet:
rprint(f"Analysing {len(subset)} sequences with {method_name}")
output_subfolder = get_output_subfolder(method_name)
ctx.invoke(
globals()[method_name],
fasta_input=subset_fasta,
output_folder=output_subfolder,
constraint=constraint,
exclusion=exclusion,
fold_type=fold_type,
quiet=True,
skip_ribovore_filters=skip_ribovore_filters,
)
prev_output_subfolder = output_subfolder
# Rfam
hits = hits.union(get_hits(prev_output_subfolder))
subset = all_seq_ids.difference(hits)
if not quiet:
rprint(f"Analysing {len(subset)} sequences with Rfam")
if subset:
with Timer("Rfam", quiet):
with open(
shared.get_ribotyper_output(
subset_fasta,
rfam_output,
os.path.join(config.CM_LIBRARY, "rfam"),
skip_ribovore_filters,
),
) as f_ribotyper:
for line in f_ribotyper.readlines():
seq_id, model_id, _ = line.split("\t")
core.visualise(
"rfam",
subset_fasta,
rfam_output,
seq_id,
model_id,
constraint,
exclusion,
fold_type,
domain=None,
isotype=None,
start=None,
end=None,
quiet=quiet,
)
# GtRNAdb
hits = hits.union(get_hits(rfam_output))
subset = all_seq_ids.difference(hits)
if subset:
get_subset_fasta(fasta_input, subset_fasta, subset)
with Timer("GtRNAdb", quiet):
if not quiet:
rprint(f"Analysing {len(subset)} sequences with GtRNAdb")
for trna in gtrnadb.classify_trna_sequences(subset_fasta, gtrnadb_output):
core.visualise(
"gtrnadb",
fasta_input,
output_folder + "/gtrnadb",
trna["id"],
None,
constraint,
exclusion,
fold_type,
trna["domain"],
trna["isotype"],
trna["start"],
trna["end"],
quiet,
)
# Rfam tRNA
hits = hits.union(get_hits(gtrnadb_output))
subset = all_seq_ids.difference(hits)
if subset:
get_subset_fasta(fasta_input, subset_fasta, subset)
with Timer("Rfam tRNA", quiet):
if not quiet:
rprint(f"Analysing {len(subset)} sequences with Rfam tRNA")
trna_ids = rfam.cmsearch_nohmm_mode(subset_fasta, output_folder, "RF00005")
if trna_ids:
get_subset_fasta(fasta_input, subset_fasta, trna_ids)
rfam.generate_2d(
"RF00005",
output_folder,
subset_fasta,
constraint,
exclusion,
fold_type,
quiet,
)
# move svg files to the final location
result_folders = [
crw_output,
ribovision_ssu_output,
ribovision_lsu_output,
rfam_output,
gtrnadb_output,
rfam_trna_output,
rnasep_output,
tmrna_output,
]
for folder in result_folders:
organise_results(folder, output_folder)
organise_metadata(output_folder, result_folders)
# clean up
os.system(f"rm {output_folder}/subset*")
os.system(f"rm -f {fasta_input}.ssi")
def organise_results(results_folder, output_folder):
"""Move files to the final folder structure."""
folders = {}
labels = ["svg", "fasta", "json", "thumbnail"]
destination = os.path.join(output_folder, "results")
for label in labels:
folders[label] = os.path.join(destination, label)
os.makedirs(folders[label], exist_ok=True)
svgs = glob.glob(os.path.join(results_folder, "*.svg"))
if not svgs:
return
for svg in svgs:
if "colored" not in svg:
continue
if "enriched" in svg:
continue
with open(svg) as f_svg:
thumbnail = shared.generate_thumbnail(f_svg.read(), svg)
thumbnail_filename = svg.replace(".colored.", ".thumbnail.")
with open(thumbnail_filename, "w") as f_thumbnail:
f_thumbnail.write(thumbnail)
results_path = Path(results_folder)
# Move .thumbnail.svg files
for file in results_path.glob("*.thumbnail.svg"):
shutil.copy(str(file), folders["thumbnail"])
file.unlink()
# Move .colored.svg files
for file in results_path.glob("*.colored.svg"):
shutil.copy(str(file), folders["svg"])
file.unlink()
# Move .enriched.svg files
for file in results_path.glob("*.enriched.svg"):
shutil.copy(str(file), folders["svg"])
file.unlink()
# Move .fasta files
for file in results_path.glob("*.fasta"):
shutil.copy(str(file), folders["fasta"])
file.unlink()
# Move .json files
for file in results_path.glob("*.json"):
shutil.copy(str(file), folders["json"])
file.unlink()
@cli.group("gtrnadb")
def gtrnadb_group():
"""
Use tRNA templates for structure visualisation.
"""
@gtrnadb_group.command("setup")
def gtrnadb_setup():
"""
This will copy all the CM files into place so that drawing will not modify
the data directory.
"""
rprint(shared.get_r2dt_version_header())
gtrnadb.setup()
@gtrnadb_group.command("draw")
@click.option(
"--domain",
default=False,
type=click.STRING,
help="Domain (A for Archaea, B for Bacteria, or E for Eukaryotes)",
)
@click.option(
"--isotype", default=False, type=click.STRING, help="tRNA isotype, for example Thr"
)
@click.option(
"--constraint", default=False, is_flag=True, help="Fold insertions using RNAfold"
)
@click.option("--exclusion", default=None)
@click.option("--fold_type", default=None)
@click.option("--quiet", "-q", is_flag=True, default=False)
@click.argument("fasta-input", type=click.Path())
@click.argument("output-folder", type=click.Path())
def gtrnadb_draw(
fasta_input,
output_folder,
domain="",
isotype="",
constraint=None,
exclusion=None,
fold_type=None,
quiet=False,
):
"""
Visualise sequences using GtRNAdb templates.
"""
# pylint: disable=too-many-arguments
if not quiet:
rprint(shared.get_r2dt_version_header())
os.makedirs(output_folder, exist_ok=True)
fasta_input = shared.sanitise_fasta(fasta_input)
if domain and isotype:
core.visualise_trna(
domain.upper(),
isotype.capitalize(),
fasta_input,
output_folder,
constraint,
exclusion,
fold_type,
quiet,
)
else:
for trna in gtrnadb.classify_trna_sequences(fasta_input, output_folder):
core.visualise(
"gtrnadb",
fasta_input,
output_folder,
trna["id"],
None,
constraint,
exclusion,
fold_type,
trna["domain"],
trna["isotype"],
trna["start"],
trna["end"],
quiet,
)
@cli.group("rnasep")
def rnasep_group():
"""
Use RNAse P templates for structure visualisation.
"""
@rnasep_group.command("draw")
@click.option(
"--constraint", default=False, is_flag=True, help="Fold insertions using RNAfold"
)
@click.option("--exclusion", default=None)
@click.option("--fold_type", default=None)
@click.option(
"--skip_ribovore_filters",
default=False,
is_flag=True,
help="Ignore ribovore QC checks",
)
@click.option("--quiet", "-q", is_flag=True, default=False)
@click.argument("fasta-input", type=click.Path())
@click.argument("output-folder", type=click.Path())
def rnasep_draw(
fasta_input,
output_folder,
constraint,
exclusion,
fold_type,
quiet,
skip_ribovore_filters,
):
"""Draw 2D diagrams using RNAse P templates."""
# pylint: disable=too-many-arguments
if not quiet:
rprint(shared.get_r2dt_version_header())
os.makedirs(output_folder, exist_ok=True)
fasta_input = shared.sanitise_fasta(fasta_input)
with open(
shared.get_ribotyper_output(
fasta_input, output_folder, config.RNASEP_CM_LIBRARY, skip_ribovore_filters
),
) as f_ribotyper:
for line in f_ribotyper.readlines():
rnacentral_id, model_id, _ = line.split("\t")
core.visualise(
"rnasep",
fasta_input,
output_folder,
rnacentral_id,
model_id,
constraint,
exclusion,
fold_type,
domain=None,
isotype=None,
start=None,
end=None,
quiet=quiet,
)
@cli.group("tmrna")
def tmrna_group():
"""
Use tmRNA templates for structure visualisation.
"""
@tmrna_group.command("draw")
@click.option(
"--constraint", default=False, is_flag=True, help="Fold insertions using RNAfold"
)
@click.option("--exclusion", default=None)
@click.option("--fold_type", default=None)
@click.option(
"--skip_ribovore_filters",
default=False,
is_flag=True,
help="Ignore ribovore QC checks",
)
@click.option("--quiet", "-q", is_flag=True, default=False)
@click.argument("fasta-input", type=click.Path())
@click.argument("output-folder", type=click.Path())
def tmrna_draw(
fasta_input,
output_folder,
constraint,
exclusion,
fold_type,
quiet,
skip_ribovore_filters,
):
"""Draw 2D diagrams using tmRNA templates."""
# pylint: disable=too-many-arguments
if not quiet:
rprint(shared.get_r2dt_version_header())
os.makedirs(output_folder, exist_ok=True)
with open(
shared.get_ribotyper_output(
fasta_input, output_folder, config.TMRNA_CM_LIBRARY, skip_ribovore_filters
),
) as f_ribotyper:
for line in f_ribotyper.readlines():
rnacentral_id, model_id, _ = line.split("\t")
core.visualise(
"tmrna",
fasta_input,
output_folder,
rnacentral_id,
model_id,
constraint,
exclusion,
fold_type,
domain=None,
isotype=None,
start=None,
end=None,
quiet=quiet,
)
@cli.group("crw")
def crw_group():
"""
Use CRW templates for structure visualisation.
"""
@crw_group.command("draw")
@click.option(
"--constraint", default=False, is_flag=True, help="Fold insertions using RNAfold"
)
@click.option("--exclusion", default=None)
@click.option("--fold_type", default=None)
@click.option("--quiet", "-q", is_flag=True, default=False)
@click.option(
"--skip_ribovore_filters",
default=False,
is_flag=True,
help="Ignore ribovore QC checks",
)
@click.argument("fasta-input", type=click.Path())
@click.argument("output-folder", type=click.Path())
def rrna_draw(
fasta_input,
output_folder,
constraint,
exclusion,
fold_type,
quiet,
skip_ribovore_filters,
):
"""Draw 2D diagrams using CRW templates."""
# pylint: disable=too-many-arguments
if not quiet:
rprint(shared.get_r2dt_version_header())
os.makedirs(output_folder, exist_ok=True)
fasta_input = shared.sanitise_fasta(fasta_input)
with open(
shared.get_ribotyper_output(
fasta_input, output_folder, config.CRW_CM_LIBRARY, skip_ribovore_filters
),
) as f_ribotyper:
for line in f_ribotyper.readlines():
rnacentral_id, model_id, _ = line.split("\t")
core.visualise(
"crw",
fasta_input,
output_folder,
rnacentral_id,
model_id,
constraint,
exclusion,
fold_type,
domain=None,
isotype=None,
start=None,
end=None,
quiet=quiet,
)
@cli.group("ribovision")
def ribovision_group():
"""
Use RiboVision templates for structure visualisation.
"""
@ribovision_group.command("draw_lsu")
@click.option(
"--constraint", default=False, is_flag=True, help="Fold insertions using RNAfold"
)
@click.option("--exclusion", default=None)
@click.option("--fold_type", default=None)
@click.option("--quiet", "-q", is_flag=True, default=False)
@click.option(
"--skip_ribovore_filters",
default=False,
is_flag=True,
help="Ignore ribovore QC checks",
)
@click.argument("fasta-input", type=click.Path())
@click.argument("output-folder", type=click.Path())
def ribovision_draw_lsu(
fasta_input,
output_folder,
constraint,
exclusion,
fold_type,
quiet,
skip_ribovore_filters,
):
"""Draw 2D diagrams using LSU templates from RiboVision."""
# pylint: disable=too-many-arguments
if not quiet:
rprint(shared.get_r2dt_version_header())
os.makedirs(output_folder, exist_ok=True)
fasta_input = shared.sanitise_fasta(fasta_input)
with open(
shared.get_ribotyper_output(
fasta_input,
output_folder,
config.RIBOVISION_LSU_CM_LIBRARY,
skip_ribovore_filters,
),
) as f_ribotyper:
for line in f_ribotyper.readlines():
rnacentral_id, model_id, _ = line.split("\t")
core.visualise(
"lsu",
fasta_input,
output_folder,
rnacentral_id,
model_id,
constraint,
exclusion,
fold_type,
domain=None,
isotype=None,
start=None,
end=None,
quiet=quiet,
)
@ribovision_group.command("draw_ssu")
@click.option(
"--constraint", default=False, is_flag=True, help="Fold insertions using RNAfold"
)
@click.option("--exclusion", default=None)
@click.option("--fold_type", default=None)
@click.option("--quiet", "-q", is_flag=True, default=False)
@click.option(
"--skip_ribovore_filters",
default=False,
is_flag=True,
help="Ignore ribovore QC checks",
)
@click.argument("fasta-input", type=click.Path())
@click.argument("output-folder", type=click.Path())
def ribovision_draw_ssu(
fasta_input,
output_folder,
constraint,
exclusion,
fold_type,
quiet,
skip_ribovore_filters,
):
"""Draw 2D diagrams using SSU templates from RiboVision."""
# pylint: disable=too-many-arguments
if not quiet:
rprint(shared.get_r2dt_version_header())
os.makedirs(output_folder, exist_ok=True)
fasta_input = shared.sanitise_fasta(fasta_input)
with open(
shared.get_ribotyper_output(
fasta_input,
output_folder,
config.RIBOVISION_SSU_CM_LIBRARY,
skip_ribovore_filters,
),
) as f_ribotyper:
for line in f_ribotyper.readlines():
rnacentral_id, model_id, _ = line.split("\t")
core.visualise(
"ssu",
fasta_input,
output_folder,
rnacentral_id,
model_id,
constraint,
exclusion,
fold_type,
domain=None,
isotype=None,
start=None,
end=None,
quiet=quiet,
)
@cli.group("rfam")
def rfam_group():
"""
Use Rfam templates for structure visualisation.
"""
@rfam_group.command("blacklisted")
def rfam_blacklist():
"""
Show all blacklisted families. These include rRNA families as well as
families that do not have any secondary structure.
"""
for model in sorted(rfam.blacklisted()):
rprint(model)
@rfam_group.command("draw")
@click.option(
"--constraint", default=False, is_flag=True, help="Fold insertions using RNAfold"
)
@click.option("--exclusion", default=None)
@click.option("--fold_type", default=None)
@click.option("--quiet", "-q", is_flag=True, default=False)
@click.option("--rnartist", default=False, is_flag=True)
@click.option("--rscape", default=False, is_flag=True)
@click.argument("rfam_acc", type=click.STRING)
@click.argument("fasta-input", type=click.Path())
@click.argument("output-folder", type=click.Path())
def rfam_draw(
rfam_acc,
fasta_input,
output_folder,
constraint=None,
exclusion=None,
fold_type=None,
quiet=False,
rnartist=False,
rscape=False,
):
"""
Visualise sequences using the Rfam/R-scape consensus structure as template.
RFAM_ACCESSION - Rfam family to process (RF00001, RF00002 etc)
"""
# pylint: disable=too-many-arguments
if not quiet:
rprint(shared.get_r2dt_version_header())
rprint(rfam_acc)
if rnartist and rscape:
rprint("Please specify only one template type")
return
if rnartist:
template_type = "rnartist"
elif rscape:
template_type = "rscape"
else:
template_type = "auto"
fasta_input = shared.sanitise_fasta(fasta_input)
if rfam.has_structure(rfam_acc):
rfam.generate_2d(
rfam_acc,
output_folder,
fasta_input,
constraint,
exclusion,
fold_type,
quiet,
rfam_template_type=template_type,
)
else:
rprint(f"{rfam_acc} does not have a conserved secondary structure")
@rfam_group.command("validate")
@click.argument("rfam_accession", type=click.STRING)
@click.argument("output", type=click.File("w"))
def rfam_validate(rfam_accession, output):
"""
Check if the given Rfam accession is one that should be drawn. If so it will
be output to the given file, otherwise it will not.
"""
if rfam_accession not in rfam.blacklisted():
output.write(f"{rfam_accession}\n")
def organise_metadata(output_folder, result_folders):
"""
Aggregate hits.txt files from all subfolders.
"""
tsv_folder = os.path.join(output_folder, "results", "tsv")
os.makedirs(tsv_folder, exist_ok=True)
with open(os.path.join(tsv_folder, "metadata.tsv"), "w") as f_out:
for folder in result_folders:
hits = os.path.join(folder, "hits.txt")
if not os.path.exists(hits):
continue
with open(hits) as f_hits:
for line in f_hits.readlines():
if "gtrnadb" in folder:
line = line.replace("PASS", "GtRNAdb")
elif "crw" in folder:
line = line.replace("PASS", "CRW").replace("FAIL", "CRW")
elif "rfam" in folder or "RF00005" in folder:
line = line.replace("PASS", "Rfam").replace("FAIL", "Rfam")
elif "ribovision-lsu" in folder or "ribovision-ssu" in folder:
line = line.replace("PASS", "RiboVision").replace(
"FAIL", "RiboVision"
)
elif "rnasep" in folder:
line = line.replace("PASS", "RNAse P Database").replace(
"FAIL", "RNAse P Database"
)
elif "tmrna" in folder:
line = line.replace("PASS", "tmRNA Database").replace(
"FAIL", "tmRNA Database"
)
f_out.write(line)
@cli.command()
@click.argument("cm_library", type=click.Path())