-
Notifications
You must be signed in to change notification settings - Fork 2
/
Recplot.R
2973 lines (2089 loc) · 126 KB
/
Recplot.R
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
#Package check and install.
{
check <- suppressWarnings(suppressMessages(require(reticulate)))
if(!check){
install.packages("reticulate")
library(reticulate)
}
check <- suppressWarnings(suppressMessages(require(ggplot2)))
if(!check){
install.packages("ggplot2")
library(ggplot2)
}
check <- suppressWarnings(suppressMessages(require(shiny)))
if(!check){
install.packages("shiny")
library(shiny)
}
check <- suppressWarnings(suppressMessages(require(data.table)))
if(!check){
install.packages("data.table")
library(data.table)
}
check <- suppressWarnings(suppressMessages(require(plotly)))
if(!check){
install.packages("plotly")
library(plotly)
}
check <- suppressWarnings(suppressMessages(require(cowplot)))
if(!check){
install.packages("cowplot")
library(cowplot)
}
check <- suppressWarnings(suppressMessages(require(enveomics.R)))
if(!check){
install.packages("enveomics.R")
library(enveomics.R)
}
check <- suppressWarnings(suppressMessages(require(shinyBS)))
if(!check){
install.packages("shinyBS")
library(shinyBS)
}
check <- suppressWarnings(suppressMessages(require(hms)))
if(!check){
install.packages("hms")
library(hms)
}
check <- suppressWarnings(suppressMessages(require(easycsv)))
if(!check){
install.packages("easycsv")
library(easycsv)
}
check <- suppressWarnings(suppressMessages(require(shinyalert)))
if(!check){
install.packages("shinyalert")
library(shinyalert)
}
check <- suppressWarnings(suppressMessages(require(htmlwidgets)))
if(!check){
install.packages("htmlwidgets")
library(htmlwidgets)
}
}
#Helper functions
{
#This will download whatever the current python script is. You have to run it before landing page.
get_python <- function(){
source_python("https://raw.githubusercontent.com/KGerhardt/Recplot_4/master/Recplot.py", envir = globalenv())
}
#Checks for necessary setup steps and makes the requisite installs as needed.
prepare_environment <- function(){
cat("Checking for Miniconda and installing if necessary...\n")
try({
install_miniconda()
})
#Checking for first-time use of recplots
if(!"recruitment_plots" %in% conda_list()$name){
cat("Creating Miniconda environment: 'recruitment_plots'\n")
conda_create(envname = "recruitment_plots")
}
use_miniconda(condaenv = "recruitment_plots", required = T)
if(get_sys() != "Windows"){
if(py_module_available("pysam")){
cat("Attempting to install pysam to recruitment_plots... ")
try({
py_install(packages = "pysam", envname = "recruitment_plots", pip = T)
cat("Done!\n")
})
}else{
cat("Pysam already installed. You probably shouldn't be seeing this warning. Did you call prepare_environment() twice?\n")
}
get_python()
}
}
#Prepares the background miniconda env if necessary; otherwise, sets the environment and loads the python script functions
initiate <- function(){
cat("Initiating recruitment plot environment. Please wait a moment. ")
tryCatch({
use_miniconda(condaenv = "recruitment_plots", required = T )
get_python()
}, error = function(cond){
cat("\nPerforming first-time setup. Wait a moment, please.\n")
prepare_environment()
return("Environment prepared.")
} )
}
#The python import is a space-efficient, but strcutrually awkward data object
#List of 2 items: list of lists of contig starts, stops, assoc. counts per %ID bin, and %ID bins.
#This function converts the structure into a recplot-ready data.table with appropriate labelling and returns some other key values for building the plots.
pydat_to_recplot_dat <- function(extracted_MAG, contig_names){
id_breaks <- unlist(extracted_MAG[[2]])
#id_breaks <- paste0(id_breaks - id_width, "-", id_breaks)
extracted_MAG <- extracted_MAG[[1]]
names(extracted_MAG) = contig_names
ends <- lapply(extracted_MAG, function(x){
return(x[[2]])
})
maximum_table <- data.table(contig = names(ends), length = lapply(ends, max))
maximum_table[, relative_end := cumsum(length) + 1:nrow(maximum_table) - 1]
pos.max <- maximum_table$relative_end[nrow(maximum_table)]
bp_unit <- c("(bp)", "(Kbp)", "(Mbp)", "(Gbp)")[findInterval(log10(pos.max), c(0,3,6,9,12,Inf))]
bp_div <- c(1, 1e3, 1e6, 1e9)[findInterval(log10(pos.max), c(0,3,6,9,12,Inf))]
ends <- unlist(ends)
bins <- rbindlist(lapply(extracted_MAG, function(x){
return(data.table(cbind(do.call(rbind, x[[3]]))))
}))
colnames(bins) = as.character(id_breaks)
starts <- lapply(extracted_MAG, function(x){
return(x[[1]])
})
#needs start, end, contig name for annotation, rel.pos absolute for plotting
bins[, Start := unlist(starts)]
bins[, End := ends]
bins[, seq_pos := seq(1/bp_div, pos.max/bp_div , length.out = nrow(bins))]
bins[, contig := rep(names(starts), times = lengths(starts))]
bins <- melt.data.table(bins, id.vars = c("contig", "Start", "End", "seq_pos"))
colnames(bins)[5:6] = c("Pct_ID_bin", "bp_count")
bins[, Pct_ID_bin := as.numeric(levels(bins$Pct_ID_bin))[bins$Pct_ID_bin]]
#return(bins)
return(list(bins, bp_unit,bp_div, pos.max))
}
create_static_plot <- function(base, bp_unit, bp_div, pos_max, in_grp_min, id_break, width, linear, showpeaks, ends, trunc_behavior = "ends", trunc_degree = as.integer(75), ...){
group.colors <- c(depth.in = "darkblue", depth.out = "lightblue", depth.in.nil = "darkblue", depth.out.nil = "lightblue")
#This seems to be working.
#Sets any starts < trunc degree to trunc_degree
base <- base[Start < trunc_degree, Start := trunc_degree]
base[, contig_len := max(End), by = contig]
base[End == contig_len, End := End - trunc_degree, ]
#Selects the bins at the end of each contig and subtracts trunc degree from it
#base[base[, End > (max(End)-trunc_degree), by = contig]$V1, End := (End - trunc_degree),]
#If the final bin was too small, removes it as unplottable.
base <- base[Start <= End,]
#fwrite(ends, "endings.txt", sep = "\t")
#b2 <- base
#setkeyv(b2, c("contig", "Start", "Pct_ID_bin"))
#fwrite(b2, "base_inital_mod.txt", sep = "\t")
#Allows for count normalization by bin width across all bins
norm_factor <- min(base$End-base$Start) + 1
#Lower left panel
{
p <- ggplot(base, aes(x = seq_pos, y = Pct_ID_bin, fill=log10((bp_count * (norm_factor/(End-Start+1))))))+
scale_fill_gradient(low = "white", high = "black", na.value = "#EEF7FA")+
ylab("Percent Identity") +
xlab(paste("Position in Genome", bp_unit)) +
scale_y_continuous(expand = c(0, 0)) +
scale_x_continuous(expand = c(0, 0), limits = c(0, pos_max/bp_div), breaks = scales::pretty_breaks(n = 10)) +
theme(legend.position = "none",
axis.line = element_line(colour = "black"),
axis.title = element_text(size = 14),
axis.text = element_text(size = 14)) +
geom_raster()
p <- p + annotate("rect", xmin = 0, xmax = pos_max/bp_div,
ymin = in_grp_min,
ymax = 100, fill = "darkblue", alpha = .15)
read_rec_plot <- p + geom_vline(xintercept = ends$V1/bp_div[-nrow(ends)], col = "#AAAAAA40")
}
base[, group_label := ifelse(base$Pct_ID_bin-id_break >= in_grp_min, "depth.in", "depth.out")]
setkeyv(base, c("group_label", "seq_pos"))
#upper left panel
{
depth_data <- base[, sum(bp_count/(End-Start+1), na.rm = T), by = key(base)]
colnames(depth_data)[3] = "count"
ddSave <- base[, sum(bp_count, na.rm = T), by = key(base)]
nil_depth_data <- depth_data[count == 0]
nil_depth_data$group_label <- ifelse(nil_depth_data$group_label == "depth.in", "depth.in.nil", "depth.out.nil")
seg_upper_bound <- min(depth_data$count[depth_data$count > 0])
depth_data$count[depth_data$count == 0] <- NA
seq_depth_chart <- ggplot(depth_data, aes(x = seq_pos, y = count, colour=group_label, group = group_label))+
geom_step(alpha = 0.75) +
scale_y_continuous(trans = "log10", labels = scales::scientific) +
scale_x_continuous(expand=c(0,0), limits = c(0, pos_max/bp_div), breaks = scales::pretty_breaks(n = 10))+
theme(legend.position = "none",
panel.border = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.line = element_line(colour = "black"),
panel.background = element_blank(),
axis.title.x = element_blank(),
#axis.text.y = element_text(angle = 90, hjust = 0.5),
axis.title = element_text(size = 14),
axis.text = element_text(size = 14)) +
scale_color_manual(values = group.colors) +
ylab("Depth")
if(nrow(nil_depth_data) > 0){
seq_depth_chart <- seq_depth_chart + geom_segment(data = nil_depth_data, aes(x = seq_pos, xend = seq_pos, y = 0, yend = seg_upper_bound, color = group_label, group = group_label))
}
}
#Seq. depth histograms (top right panel)
{
depth_data <- depth_data[count > 0]
seqdepth.lim <- range(c(depth_data$count[depth_data[,group_label == "depth.in"]], depth_data$count[depth_data[,group_label == "depth.out"]])) * c(1/2, 2)
hist_binwidth <- (log10(seqdepth.lim[2]/2) - log10(seqdepth.lim[1] * 2))/199
depth_data[,count := log10(count)]
depth_data$group_label <-factor(depth_data$group_label, levels = c("depth.out", "depth.in"))
depth_data <- depth_data[order(group_label),]
p4 <- ggplot(depth_data, aes(x = count, fill = group_label)) +
geom_histogram(binwidth = hist_binwidth) +
scale_fill_manual(values = group.colors) +
scale_y_continuous(expand=c(0,0)) +
theme(legend.position = "none",
panel.border = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.line = element_line(colour = "black"),
panel.background = element_blank(),
axis.ticks.y = element_blank(),
axis.text.y = element_blank(),
axis.text.x = element_text(colour = "white"),
axis.ticks.x = element_blank(),
axis.title = element_text(size = 14),
axis.text = element_text(size = 14)) +
xlab(label = element_blank()) +
ylab(label = element_blank())
if(showpeaks){
enve.recplot2.__peakHist <- function
### Internal ancilliary function (see `enve.RecPlot2.Peak`).
(x, mids, counts=TRUE){
d.o <- x$param.hat
if(length(x$log)==0) x$log <- FALSE
if(x$log){
d.o$x <- log(mids)
}else{
d.o$x <- mids
}
prob <- do.call(paste('d', x$dist, sep=''), d.o)
if(!counts) return(prob)
if(length(x$values)>0) return(prob*length(x$values)/sum(prob))
return(prob*x$n.hat/sum(prob))
}
h.breaks <- seq(log10(seqdepth.lim[1] * 2), log10(seqdepth.lim[2]/2),
length.out = 200)
h.mids <- (10^h.breaks[-1] + 10^h.breaks[-length(h.breaks)])/2
min_info <- list()
if(nrow(ends) > 1){
ends[, adjust := c(-1, V1[1:nrow(ends)-1])+1]
}else{
ends[, adjust := 0]
}
base[, contiguous_end := End + ends$adjust[match(contig, ends$contig)]]
min_info$pos.breaks = c(0, base$contiguous_end[match(ddSave$seq_pos[ddSave$group_label == "depth.in"], base$seq_pos)])
min_info$pos.counts.in = ddSave$V1[ddSave$group_label == "depth.in"]
#This is finicky
try({
peaks <- enve.recplot2.findPeaks(min_info)
dpt <- signif(as.numeric(lapply(peaks, function(x) x$seq.depth)), 2)
frx <- signif(100 * as.numeric(lapply(peaks,function(x) ifelse(length(x$values) == 0, x$n.hat, length(x$values))/x$n.total)), 2)
if (peaks[[1]]$err.res < 0) {
err <- paste(", LL:", signif(peaks[[1]]$err.res,3))
} else {
err <- paste(", err:", signif(as.numeric(lapply(peaks, function(x) x$err.res)), 2))
}
labels <- paste(letters[1:length(peaks)], ". ", dpt, "X (", frx, "%", err, ")", sep = "")
peak_counts <- lapply(peaks, enve.recplot2.__peakHist, h.mids)
plot_breaks = h.breaks[-length(h.breaks)]
gg_peak_info <- data.table(plot_breaks = rep(plot_breaks, length(peak_counts)), count = unlist(peak_counts), grp = rep(labels, each = length(plot_breaks)))
p4 <- p4 + geom_line(data = gg_peak_info, aes(x = plot_breaks, y = count, color = grp, group = grp), inherit.aes = F, color = "red", lwd = 1.13)
})
}
p4 <- p4 + coord_flip()
if(showpeaks){
try({
o_max <- max(table(findInterval(depth_data$count[depth_data$group_label == "depth.in"], h.breaks)))*.75
x_start = 0
if(length(labels) > 0){
for(i in labels){
p4 <- p4 + annotate("text", label = i, y = o_max, x = x_start, size = 3)
x_start = x_start - .185
}
}
})
}
seq_depth_hist <- p4
rm(p4)
}
#bp counts histogram (bottom right panel)
{
bp_data <- base[,sum(bp_count, na.rm = T), by = Pct_ID_bin]
if(linear == 1){
p4 <- ggplot(data = bp_data, aes(y = V1, x = Pct_ID_bin-(id_break))) +
geom_step() +
scale_y_continuous(expand = c(0,0), breaks = scales::pretty_breaks(n = 3)) +
scale_x_continuous(expand = c(0,0)) +
theme(legend.position = "none",
panel.border = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.line = element_line(colour = "black"),
panel.background = element_rect(fill = "#EEF7FA"),
axis.text.y = element_blank(),
axis.title.y = element_blank(),
axis.ticks.y = element_blank(),
axis.title = element_text(size = 14),
axis.text = element_text(size = 14))+
ylab("Base Pair Count by % ID")
} else {
p4 <- ggplot(data = bp_data, aes(y = V1, x = Pct_ID_bin-(id_break))) +
geom_step() +
scale_y_continuous(expand = c(0,0), trans = "log10", breaks = scales::log_breaks(n = 4)) +
scale_x_continuous(expand = c(0,0)) +
theme(legend.position = "none",
panel.border = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.line = element_line(colour = "black"),
panel.background = element_rect(fill = "#EEF7FA"),
axis.text.y = element_blank(),
axis.title.y = element_blank(),
axis.ticks.y = element_blank(),
axis.title = element_text(size = 14),
axis.text = element_text(size = 14))+
ylab("Base Pair Count by % ID")
}
bp_count_hist <- p4 + annotate("rect", xmin = in_grp_min, xmax = 100, ymin = 0, ymax = Inf, fill = "darkblue", alpha = .15) + coord_flip()
rm(p4)
}
#I worry that the modify in place permanently whoopsies things, so I change it back just in case
base[End == contig_len-trunc_degree, End := End + trunc_degree, ]
base[, contig_len := NULL, ]
overall_plot <- plot_grid(seq_depth_chart, seq_depth_hist, read_rec_plot, bp_count_hist, align = "hv", ncol = 2, rel_widths = c(2.7, 1), rel_heights = c(1, 2.3))
return(overall_plot)
}
create_static_data <- function(base, bp_unit, bp_div, pos_max, in_grp_min, id_break, width, linear, showpeaks, ends, trunc_behavior = "ends", trunc_degree = as.integer(75), ...){
setkeyv(base, c("contig", "Start", "Pct_ID_bin"))
base[, contig_len := max(End), by = contig]
base[End == contig_len, End := End - trunc_degree, ]
returnable_base <- base
#fwrite(base, "base_print_data.txt", sep = "\t")
if("gene_name" %in% colnames(returnable_base)){
#Allows for count normalization by bin width across all bins
norm_factor <- min(returnable_base$End-returnable_base$Start) + 1
returnable_base[, normalized_count := bp_count * (norm_factor/(End-Start+1)),]
returnable_base[, seq_pos := NULL,]
returnable_base[, id_lower := Pct_ID_bin - id_break, ]
returnable_base[, group_label := ifelse(returnable_base$Pct_ID_bin-id_break >= in_grp_min, "in_group", "out_group"), ]
returnable_base <- returnable_base[, list(contig, Start, End, id_lower, Pct_ID_bin, bp_count, normalized_count, group_label, gene_name, gene_start, gene_end, gene_strand, gene_annotation),]
colnames(returnable_base)[1:8] = c("contig_name", "start_pos_in_contig", "end_pos_in_contig", "lower_pct_id", "upper_pct_id", "raw_count_of_bp_in_bin", "normalized_count_of_bp_in_bin", "pct_id_group")
setkeyv(returnable_base, c("contig_name", "start_pos_in_contig", "end_pos_in_contig", "lower_pct_id", "upper_pct_id", "pct_id_group"))
setkeyv(returnable_base, c("contig_name", "start_pos_in_contig", "pct_id_group"))
#upper left panel
depth_data <- returnable_base[, list(sum(raw_count_of_bp_in_bin/(end_pos_in_contig-start_pos_in_contig + 1), na.rm = T), unique(gene_name), unique(gene_start), unique(gene_end), unique(gene_strand), unique(gene_annotation)), by = key(returnable_base)]
colnames(depth_data)[4:9] = c("average_sequencing_depth", "gene_name", "gene_start", "gene_end", "gene_strand", "gene_annotation")
setkeyv(depth_data, c("contig_name", "pct_id_group", "start_pos_in_contig"))
}else{
#Allows for count normalization by bin width across all bins
norm_factor <- min(returnable_base$End-returnable_base$Start) + 1
returnable_base[, normalized_count := bp_count * (norm_factor/(End-Start+1)),]
returnable_base[, seq_pos := NULL,]
returnable_base[, id_lower := Pct_ID_bin - id_break, ]
returnable_base[, group_label := ifelse(returnable_base$Pct_ID_bin-id_break >= in_grp_min, "in_group", "out_group"), ]
returnable_base <- returnable_base[, list(contig, Start, End, id_lower, Pct_ID_bin, bp_count, normalized_count, group_label),]
#todo
#fwrite(returnable_base, "returnable_base_reorg.txt", sep = "\t")
colnames(returnable_base) = c("contig_name", "start_pos_in_contig", "end_pos_in_contig", "lower_pct_id", "upper_pct_id", "raw_count_of_bp_in_bin", "normalized_count_of_bp_in_bin", "pct_id_group")
setkeyv(returnable_base, c("contig_name", "start_pos_in_contig", "end_pos_in_contig", "lower_pct_id", "upper_pct_id", "pct_id_group"))
setkeyv(returnable_base, c("contig_name", "start_pos_in_contig", "pct_id_group"))
#upper left panel
depth_data <- returnable_base[, sum(raw_count_of_bp_in_bin/(end_pos_in_contig-start_pos_in_contig + 1), na.rm = T), by = key(returnable_base)]
colnames(depth_data)[ncol(depth_data)] = "average_sequencing_depth"
setkeyv(depth_data, c("contig_name", "pct_id_group", "start_pos_in_contig"))
}
#I worry that the modify in place permanently whoopsies things, so I change it back just in case
base[End == contig_len-trunc_degree, End := End + trunc_degree, ]
base[, contig_len := NULL, ]
return(list(returnable_base, depth_data))
}
gene_pydat_to_recplot_dat_prodigal <- function(prodigal_gene_mess){
contigs <- names(prodigal_gene_mess)
lengths <- unname(unlist(lapply(prodigal_gene_mess, function(x){
return(length(x[[1]]))
})))
pretty_data <- data.table(contig = rep(contigs, times = lengths))
pretty_data[, gene_name := unname(unlist(lapply(prodigal_gene_mess, function(x){
return(x[[1]])
}))) ]
pretty_data[, gene_start := unname(unlist(lapply(prodigal_gene_mess, function(x){
return(x[[2]])
}))) ]
pretty_data[, gene_end := unname(unlist(lapply(prodigal_gene_mess, function(x){
return(x[[3]])
}))) ]
pretty_data[, strand := unname(unlist(lapply(prodigal_gene_mess, function(x){
return(x[[4]])
}))) ]
pretty_data[, annotation := unname(unlist(lapply(prodigal_gene_mess, function(x){
return(x[[5]])
}))) ]
return(pretty_data)
}
#Wish I could add captions to the unix/osx versions
choose_directory = function(caption = 'Select data directory') {
if (exists('choose.dir')) {
choose.dir(caption = caption)
} else {
easycsv::choose_dir()
}
}
#Wish I could add captions to the unix/osx versions
choose_file = function(caption) {
if (exists('choose.files')) {
choose.files(caption = caption, multi = F)
} else {
file.choose(new = F)
}
}
path_simplifier <- function(working_directory, file_path){
file_path_t <- gsub("\\\\", "/", file_path)
working_directory <- gsub("\\\\", "/", working_directory)
working_directory <- paste0(working_directory, "/")
if(substr(working_directory, 1, 12) == "Working in: "){
working_directory <- substr(working_directory, 13, nchar(working_directory))
}
if(grepl(working_directory, file_path_t)){
return(gsub(working_directory, "", file_path_t))
}else{
return(file_path)
}
}
}
#This is the GUI function
recplot_UI <- function(){
#System/choices issue
{
system <- get_sys()
format_choices <- c("Tabular BLAST" = "blast", "SAM" = "sam")
if(system == "Windows"){
format_choices <- c("Tabular BLAST" = "blast", "SAM" = "sam", "BAM" = "bam")
}else{
if(py_module_available("pysam") == T){
format_choices <- c("Tabular BLAST" = "blast", "SAM" = "sam", "BAM" = "bam")
}else{
cat("Your OS supports pysam, but you do not have it installed. Recruitment Plots tries to install this, but it seems to have failed. Try 'pip install pysam' on the command line.\n")
}
}
gene_choices <- c("Prodigal GFF" = "prodigal")
}
#UI
{
ui <- fluidPage(
tags$head(
tags$style(
HTML(".shiny-notification {
height: 100px;
width: 800px;
position:fixed;
top: calc(50% - 50px);;
left: calc(50% - 400px);;
}
"
)
)
),
useShinyalert(),
tabsetPanel(id = "tabs",
tabPanel("Database Creation",
fluidRow(
#todo
column(1),
column(4,
h2("Create a new Database"),
actionButton('dir', '(1) Choose Directory', icon = icon("folder-open")),
textInput("cur_dir",label = NULL, value = paste("Working in:", getwd()), width = '100%'),
br(),
actionButton('contigs', '(2) Select Reference Genomes', icon = icon("file-upload")),
checkboxInput("one_mag", label = "This is a single binned genome.", value = F),
textInput("contig_file",label = NULL, value = "No genomes selected.", width = '100%'),
br(),
actionButton('reads', '(3) Select Mapped Reads', icon = icon("file-upload")),
textInput("read_file",label = NULL, value = "No mapped read file selected.", width = '100%'),
selectInput('fmt', 'Mapped Read Format', selected = "Tabular BLAST", choices = format_choices, width = '100%'),
br(),
actionButton('mags', '(Optional) Association File', icon = icon("file-upload")),
actionButton("what_are_mags", "Info", icon = icon("question-circle")),
textInput("mag_file",label = NULL, value = "No association file selected.", width = '100%'),
br(),
textInput("dbname",label = "(4) Name the database", value = "Enter name here.", width = '100%'),
br(),
actionButton('db' , "(5) Create database", icon("coins")),
#Tooltips
bsTooltip("dir", "(Optional) Select a working directory. The database and any saved plots will be placed here.", placement = "right"),
bsTooltip("contigs", "Select a FASTA format file containing genome sequences or contigs.", placement = "right"),
bsTooltip("one_mag", "If you binned an assembly and have a single multi-FASTA containing the sequences for this MAG as your reference genomes, check this box, leave the association file blank, and they will all appear on a single plot.", placement = "right"),
bsTooltip("mags", "Select an association file. This is a file designed to support the visualization of genomes divided into multiple contigs. Click the info button to learn more.", placement = "right"),
bsTooltip("reads", "Select a mapped read file. These reads should be mapped to the genomes in the reference genomes file selected above.", placement = "right"),
bsTooltip("fmt", "Select the format of the mapped reads to be added to the new database.", placement = "right"),
bsTooltip("dbname", "Name your database. A .db extension will be added to the end of the name you give it.", placement = "right"),
bsTooltip("db", "Click me after selecting all input files to create your database.", placement = "right")
),
column(1),
column(5,
h2("Build Report"),
verbatimTextOutput("message")
),
column(1)
)
),
tabPanel("Database Management",
fluidRow(
column(1),
column(4,
h2("Work with an existing database"),
actionButton('exist_db', 'Select an existing DB', icon = icon("coins")),
textInput("exist_dbname",label = NULL, value = "No DB currently selected", width = '100%'),
br(),
h4("Add More Reads"),
actionButton('add_sample', 'Select another sample to add?', icon = icon("file-upload")),
actionButton("show_samps", "Show Samples", icon = icon("question-circle")),
textInput("add_samp",label = NULL, value = "No new sample to add.", width = '100%'),
selectInput('fmt_add', 'Mapped Read Format', selected = "Tabular BLAST", choices = format_choices, width = '100%'),
actionButton('new_samp_commit', "Add this sample to the DB", icon = icon("coins")),
br(),
br(),
h4("Add Genes"),
actionButton('add_genes', 'Add genes to database?', icon = icon("file-upload")),
textInput("add_gen", label = NULL, value = "No genes to add.", width = '100%'),
selectInput('fmt_gen', 'Gene format', selected = "Prodigal GFF", choices = gene_choices, width = '100%'),
actionButton('genes_commit', "Add these genes to the DB", icon = icon("coins")),
actionButton('check_for_genes', "Check if genes have been added.", icon = icon("question-circle")),
br(),
br(),
selectInput('task', 'Plot contigs or plot genes?', selected = "Contigs", choices = c("Contigs" = "contigs", "Genes" = "genes"), width = '100%'),
bsTooltip("exist_db", "Select a database previously created with Recruitment Plot.", placement = "right"),
bsTooltip("add_sample", "(Optional) Select another set of reads mapped to the same genomes to be added to the database.", placement = "right"),
bsTooltip("fmt_add", "Select the format of the mapped reads to be added to the existing database.", placement = "right"),
bsTooltip("add_genes", "(Optional) Add genes for existing genomes.", placement = "right"),
bsTooltip("fmt_gen", "Select the format of the genes to be added to the existing database. Currently only Prodigal GFF format is supported.", placement = "right"),
bsTooltip("new_samp_commit", "Once you have selected another set of mapped reads to add and chosen the format, click this to add the sample. The sample will not be added until you do.", placement = "right"),
bsTooltip("genes_commit", "Once you have selected a set of genes to add and chosen the format (currently only Prodigal GFF), click this to add the genes. The genes will not be added until you do.", placement = "right"),
bsTooltip("show_samps", "Display all samples currently in the selected database. Requires a database to be selected first.", placement = "right"),
bsTooltip("check_for_genes", "Query the database for the presence of genes on the genomes.", placement = "right")
),
column(1),
column(5,
h2("Database Status"),
verbatimTextOutput("message2")
),
column(1)
)
),
tabPanel("Recruitment Plot",
sidebarPanel(
width = 3,
h4("Choose a Genome"),
selectInput("samples", "(1) Select a sample in the database", selected = NULL, choices = NULL),
selectInput("mags_in_db", "(2) Select a genome in the sample", selected = NULL, choices = NULL),
h4("Select Bin Resolution"),
numericInput("height", "(3) Pct. ID Resolution", min = 0.05, max = 3, value = 0.5),
#numericInput("low_bound", "(4) Minimum Pct. ID", min = 50, max = 95, value = 70),
conditionalPanel(condition = "input.task == 'contigs'",
numericInput("width", "(4) Genome Resolution", min = 75, max = 5000, value = 1000)
),
conditionalPanel(condition = "input.task == 'genes'",
selectInput("regions_stat", "(4) Display Control", choices = c("Genes Only" = 1, "Intergenic Regions Only" = 2, "Genes and long IGR" = 3, "All Regions" = 4), selected = 1)
),
h4("Load Selected Genome"),
actionButton('get_a_mag', '(5) View Selected Genome', icon = icon("jedi-order")),
h4("Fine Tuning (Interactive)"),
numericInput("in_group_min_stat", "(6) In-Group Pct. ID", min = 50, max = 99.5, value = 95),
selectInput("linear_stat", "(7) BP Histogram Scale", choices = c("Linear" = 1, "Logarithmic" = 2), selected = 1),
checkboxInput("show_peaks", "(8) Display Depth Peaks?"),
textInput("pdf_name", "Name and save current plot."),
actionButton("print_stat", "Save to PDF", icon = icon("save")),
#todo
actionButton("output_data_stat", "Save raw data", icon = icon("file")),
bsTooltip("samples", "This menu contains a list of samples within the database. Select one, and the genome field will be populated with the genomes found in that sample.", placement = "right"),
bsTooltip("mags_in_db", "This menu contains the set of genomes in currently selected sample. Select one, then select resolution parameters.", placement = "right"),
bsTooltip("width", "Approximate number of base pairs in each genome window. The Recruitment Plot attempts to normalize bin width for each contig to this size. Lower values = higher resolution, but is slower. Higher values = lower resolution, but is faster.", placement = "right"),
bsTooltip("height", "Controls the resolution of percent identity to the reference. Lower values here will result in finer resolution, but will be slower. Hint: The default 0.5% window means a resolution of 1 base pair mismatch per 200 bases; finer resolution is probably uneccessary.", placement = "right"),
#bsTooltip("low_bound", "Reads mapping below this percent identity will not be included in the current recruitment plot.", placement = "right"),
bsTooltip("get_a_mag", "Click this to load the current Genome into the viewer and plot it. Please wait for the plot to appear after clicking this. This loads the data for all tabs.", placement = "right"),
bsTooltip("in_group_min_stat", "Controls the lower edge of the shaded region in the recruitment plot's lower panels. Reads mapping at or above this percent identity are regarded as the \"in-group\" for the Recruitment Plot, and are represented by the dark blue lines in the upper panels.", placement = "right"),
bsTooltip("linear_stat", "Causes the lower right panel to display base pair counts per percent identity bin in linear scale or log scale.", placement = "right"),
bsTooltip("print_stat", "After loading a plot (meaning you should be able to see it), add a name in the associated text box and then click this to print a PDF of the current plot", placement = "right"),
#todo
bsTooltip("output_data_stat", "Outputs the data for the current plots to 2 tab-separated files corresponding to the bottom left and top left panels (recruitment and sequencing depth information).", placement = "right"),
bsTooltip("show_peaks", "Calculate and overlay peaks for the depth of coverage histogram (top right panel)", placement = "right"),
bsTooltip("regions_stat", "Controls the display of intergenic regions. Default shows only genes, IGR = InterGenic Region. 'Long IGRs' are intergenic regions > 6 bp in length.", placement = "right"),
bsTooltip("recplot_main", "Bottom left panel: a 2-D histogram of the counts of base pairs falling into a bin defined by position in the genome (x-axis) and percent identity (y-axis) Bins are as wide as the genome resolution parameter if viewing contigs, and cover genes & intergenic regions in contiguous chunks if viewing genes. The shaded section is the current in-group, which is the dark blue line on the top two plots Top left panel: Average sequencing depth for each x-axis bin on in the bottom left panel. Dark blue corresponds to depth of coverage for bins in the in-group, and light blue to the out-group. Segments at the bottom of the plot have zero coverage. Top right panel: a histogram of the depths of coverage observed in the corresponding in/out group in the sequencing depths chart (top left). If peaks are selected, they correspond to the estimates of the genome's average sequencing depth. Bottom right panel: a histogram of the number of bases falling into each percent identity bin across the entire genome, displayed in linear or log scale depending on your selection.", trigger = "click", placement = "left")
),
mainPanel(id = "recplot_main",
#Spacing
fluidRow(
column(12,
div(style = "height:60px;background-color: white;", "")
)
),
fluidRow(
plotOutput("read_recruitment_plot", height = "850px")
)
)
),
tabPanel("Interactive Plot",
sidebarPanel(
width = 3,
h3("Choose a Genome"),
selectInput("samples_interact", "(1) Select a sample in the database", selected = NULL, choices = NULL),
selectInput("mags_in_db_interact", "(2) Select a Genome in the sample", selected = NULL, choices = NULL),
h3("Select Bin Resolution"),
numericInput("height_interact", "(3) Pct. ID Resolution", min = 0.05, max = 3, value = 0.5),
#numericInput("low_bound_interact", "(4) Minimum Pct. ID", min = 50, max = 95, value = 70),
conditionalPanel(condition = "input.task == 'contigs'",
numericInput("width_interact", "(4) Genome Resolution", min = 75, max = 5000, value = 1000)
),
conditionalPanel(condition = "input.task == 'genes'",
selectInput("regions_interact", "(4) Display Control", choices = c("Genes Only" = 1, "IGR Only" = 2, "Genes and long IGR" = 3, "All Regions" = 4), selected = 1)
),
h3("Load Selected Genome"),
actionButton('get_a_mag_interact', '(5) View selected Genome', icon = icon("jedi-order")),
h3("Fine Tuning (Interactive)"),
numericInput("in_group_min_interact", "(6) In-Group Pct. ID", min = 50, max = 99.5, value = 95),
textInput("pdf_name_interact", "Name and save current plot."),
actionButton("print_interact", "Save interactive HTML", icon = icon("save")),
bsTooltip("pdf_name_interact", "Name the current interactive plot as an HTML page before saving it.", placement = "right"),
bsTooltip("print_interact", "After loading a plot (meaning you should be able to see it), add a name in the associated text box and then click this to save an HTML of the current", placement = "right"),
bsTooltip("samples_interact", "This menu contains a list of samples within the database. Select one, and the genome field will be populated with the genomes found in that sample.", placement = "right"),
bsTooltip("mags_in_db_interact", "This menu contains the set of genomes in currently selected sample. Select one, then select resolution parameters.", placement = "right"),
bsTooltip("width_interact", "Approximate number of base pairs in each genome window. The Recruitment Plot attempts to normalize bin width for each contig to this size. Lower values = higher resolution, but is slower. Higher values = lower resolution, but is faster.", placement = "right"),
bsTooltip("height_interact", "Controls the resolution of percent identity to the reference. Lower values here will result in finer resolution, but will be slower. Hint: The default 0.5% window means a resolution of 1 base pair mismatch per 200 bases; finer resolution is probably uneccessary.", placement = "right"),
bsTooltip("low_bound_interact", "Reads mapping below this percent identity will not be included in the current recruitment plot.", placement = "right"),
bsTooltip("regions_interact", "Controls the display of intergenic regions. Default shows only genes, IGR = InterGenic Region. 'Long IGRs' are intergenic regions > 6 bp in length.", placement = "right"),
bsTooltip("get_a_mag_interact", "Click this to load the current genome into the viewer and plot it. Please wait for the plot to appear after clicking this.", placement = "right"),
bsTooltip("in_group_min_interact", "Controls the lower edge of the shaded region in the recruitment plot's lower panels. Reads mapping at or above this percent identity are regarded as the \"in-group\" for the Recruitment Plot, and are represented by the dark blue lines in the upper panel.", placement = "right")
),
mainPanel(
column(12,
plotlyOutput("Plotly_interactive", height = "850px")
)
)
)
)
#End fluid page
)
}
return(ui)
}
recplot_server <- function(input, output, session) {
initial_message <- "Welcome to Recruitment Plot!\nThis page allows you to take contigs and reads and create a database.\nPlease select the appropriate files using the options on the left.\nFile selection windows may pop up in the background, so please check!\n\nWhen you create your database, the Build Report will grey out for a short time - this is not an error.\nYour database is being built and the report will notify you when it has completed.\nIf the whole screen greys out, an error has occurred."
initial_message2 <- "This page is for selecting an existing database to plot, or modifying an existing one.\nIf you just created a database, it should be loaded here.\nYou can add more mapped reads or genes to the database here."
output$message <- renderText(initial_message)
output$message2 <- renderText(initial_message2)
directory <- "No directory selected. Try again?"
reads <- "No reads selected. Try again?"
contigs <- "No genomes selected. Try again?"
mags <- "No association file selected. Try again?"
new_samp <- "No new sample. Try again?"
db <- "No existing database selected. Try again?"
new_genes <- "No genes selected. Try again?"
plotting_materials <- NA
gene_data <- NA
exist_db <- "No existing database selected. Try again?"
samples_in_db <- "No database selected or built yet."
#TODO - this is the contig end cutoff that removes the first & last 75 bp from consideration in avg. depth.
#These will need to be later incorporated into the interactive inputs
trunc_degree <- as.integer(75)
#Database building
observeEvent(input$what_are_mags, {
initial_message <<- paste0(initial_message, "\n\nRecruitment plots were originally designed with metagenomes in mind.\nIn the case that a genome of interest is divided into several discrete genome\nsegments, the segments must be associated with the genome they all belong to.\nThe association file tells the recruitment plot that it should place these segments on the same plot.\nCheck the documentation for help with creating an association file for your contigs.\nIf you don't supply an association file, then a placeholder will be generated from your contigs\nand the recruitment plot will still function. Note: you still need to select contigs first.\n")
output$message <- renderText(initial_message)
})
observeEvent(input$show_samps, {
if(input$exist_dbname == "No existing database selected. Try again?" | input$exist_dbname == "No DB currently selected" | input$exist_dbname == "" ){
initial_message2 <<- paste0(initial_message2, "\nYou need to select a database before I can show you the samples inside it.")
output$message2 <- renderText(initial_message2)
}else{
samps <- unlist(assess_samples(input$exist_dbname))
samps <- paste0(samps, collapse = "\n")
initial_message2 <<- paste0(initial_message2, "\n\nSamples currently in the database:\n", samps)
output$message2 <- renderText(initial_message2)