-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathtrackplot.R
More file actions
2601 lines (2221 loc) · 102 KB
/
trackplot.R
File metadata and controls
2601 lines (2221 loc) · 102 KB
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
# This R script contains functions for bigWig visualization
#
# Source code: https://github.com/PoisonAlien/trackplot
#
# MIT License
# Copyright (c) 2020 Anand Mayakonda <anandmt3@gmail.com>
#
# Change log:
# Version: 1.6.00 [2024-10-28]
# * Added argument `track_overlay` for a single track with line plot. #14
# * Bug fix: color alpha differs between tracks. Issue: #34
# Version: 1.5.10 [2024-02-14]
# * Added argument `layout_ord` and `bw_ord` to `track_plot()` re-order the overall tracks and bigWig tracks
# * Added `xlab` and `ylab` arguments to `profile_plot()`
# Version: 1.5.01 [2023-10-17]
# * Bug fix parsing loci while parsing GTF
# * Small updates to profile_heatmap()
# Version: 1.5.00 [2023-08-24]
# * Added `read_coldata` to import bigwig and bed files along with metadata. This streamlines all the downstream processes
# * Added `profile_heatmap` for plotting heatmap
# * Added `diffpeak` for minimal differential peak analysis based on peak intensities
# * Added `volcano_plot` for diffpeak results visualization
# * Added `summarize_homer_annots`
# * Support for GTF files with `track_extract`
# * `track_extract` now accepts gene name as input.
# * More customization to `profile_extract` `profile_plot` and `plot_pca`
# * Nicer output with `extract_summary`
# * Update mysql query for UCSC. Added `ideoTblName` argument for `track_extract`. Issue: #19
# Version: 1.4.00 [2023-07-27]
# * Updated track_plot to include chromHMM tracks and top peaks tracks
# * Support to draw narrowPeak or boradPeak files with track_plot
# * Support to query ucsc for chromHMM tracks
# * Additional arguments to track_plot to adjust heights of all the tracks and margins
# * Improved track_extract - (extracts gene models and cytobands to avoid repetitive calling ucsc genome browser)
# * Additional arguments to pca_plot for better plotting
# * Added example datasets
# Version: 1.3.10 [2021-10-06]
# * Support for negative values (Issue: https://github.com/PoisonAlien/trackplot/issues/6 )
# * Added y_min argument to track_plot.
# * Change the default value for collapse_tx to TRUE
# Version: 1.3.05 [2021-06-07]
# * Summarize and groupScaleByCondition tracks by condition. Issue: #4
# * Allow the script to install as a package.
# * Added y_max argument for custom y-axis limits in track_plot.
# Version: 1.3.01 [2021-04-26]
# * Fix gtf bug. Issue: #3
# Version: 1.3.0 [2021-03-26]
# * modularize the code base to avoid repetitive data extraction and better plotting
# Version: 1.2.0 [2020-12-09]
# * Added bwpcaplot()
# Version: 1.1.11 [2020-12-07]
# * Bug fixes in profileplot(): Typo for .check_dt() and startFrom estimation
# Version: 1.1.1 [2020-12-04]
# * trackplot() now plots ideogram of target chromosome
# Version: 1.1.0 [2020-12-01]
# * Added profileplot()
# Version: 1.0.0 [2020-11-27]
# * Initial release
#------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
#'Prepares meta data table from bigWig files.
#'Output from this function is passed to all downstream functions.
#' @param bws path to bigWig files
#' @param sample_names sample names for each input files. Optional. Default NULL - creates one from file names.
#' @param build Reference genome build. Default hg38
#' @param input_type Default `bw`. Can be `bw` or `peak`
#' @examples
#' bigWigs = system.file("extdata", "bw", package = "trackplot") |> list.files(pattern = "\\.bw$", full.names = TRUE)
#' cd = read_coldata(bws = bigWigs, build = "hg19")
#' beds = system.file("extdata", "narrowpeak", package = "trackplot") |> list.files(pattern = "\\.bed$", full.names = TRUE)
#' cd_bed = read_coldata(bws = beds, input_type = "peak", build = "hg19")
#' @export
read_coldata = function(bws = NULL, sample_names = NULL, build = "hg38", input_type = "bw"){
if(is.null(bws)){
stop("Please provide paths to bigWig files")
}
input_type = match.arg(arg = input_type, choices = c("bw", "peak"))
message("Checking for files..")
bws = as.character(bws)
lapply(bws, function(x){
if(!file.exists(x)){
stop(paste0(x, " does not exist!"))
}
})
if(is.null(sample_names)){
bw_sample_names = unlist(data.table::tstrsplit(x = basename(bws), split = "\\.", keep = 1))
}else{
bw_sample_names = as.character(sample_names)
}
if(any(duplicated(bw_sample_names))){
stop("Found duplicates. Samples names must be unique")
}
if(length(bw_sample_names) != length(bws)){
stop("Please provide names for each input file")
}
coldata = data.table::data.table(bw_files = bws, bw_sample_names = bw_sample_names)
attr(coldata, "refbuild") = build
attr(coldata, "is_bw") = input_type == "bw"
message("Input type: ", input_type)
message("Ref genome: ", build)
message("OK!")
coldata
}
#' Extract bigWig track data for the given loci
#' @param colData coldata from \code{read_coldata}
#' @param loci target region to plot. Should be of format "chr:start-end". e.g; chr3:187715903-187752003 OR chr3:187,715,903-187,752,003
#' @param gene gene name. This is mutually exclusive with \code{loci}
#' @param binsize bin size to extract signal. Default 10 (bps).
#' @param nthreads Default 1. Number of threads to use.
#' @param query_ucsc Default TRUE. Queries UCSC and extracts gene models and cytoband for the loci. Requires `mysql` installation.
#' @param gtf Use gtf file or data.frame as source for gene model. Default NULL.
#' @param build Reference genome build. Default hg38
#' @param padding Extend locus on both sides by this many bps.
#' @param ideoTblName Table name for ideogram. Default `cytoBand`
#' @import data.table
#' @examples
#' bigWigs = system.file("extdata", "bw", package = "trackplot") |> list.files(pattern = "\\.bw$", full.names = TRUE)
#' cd = read_coldata(bws = bigWigs, build = "hg19")
#' oct4_loci = "chr6:31125776-31144789"
#' t = track_extract(colData = cd, loci = oct4_loci, build = "hg19")
#' @export
track_extract = function(colData = NULL, loci = NULL, gene = NULL, binsize = 10, nthreads = 1, query_ucsc = TRUE, gtf = NULL, build = "hg38", padding = 0, ideoTblName = "cytoBand"){
if(is.null(colData)){
stop("Missing colData. Use read_coldata() to generate one.")
}
if(all(is.null(loci), is.null(gene))){
stop("Please provide a loci or a gene name!")
}
input_bw = attr(colData, "is_bw")
build = attr(colData, "refbuild")
.check_windows()
if(input_bw){
.check_bwtool()
}
.check_dt()
options(warn = -1)
op_dir = tempdir() #For now
if(!is.null(gene)){
if(!is.null(gtf)){
etbl = .parse_gtf(gtf = gtf, genename = gene)
cyto = NA
start = min(unlist(lapply(etbl,function(x) attr(x, "start"))))
end = max(unlist(lapply(etbl,function(x) attr(x, "end"))))
chr = unique(unlist(lapply(etbl,function(x) attr(x, "chr"))))
}else if(query_ucsc){
message("Querying UCSC genome browser for gene model and cytoband..")
etbl = .extract_geneModel_ucsc_bySymbol(genesymbol = gene, refBuild = build)
chr = unique(as.character(etbl$chr)); start = min(as.numeric(etbl$start)); end = max(as.numeric(etbl$end))
if(length(chr) > 1){
message("Multiple chromosomes found! Using the first one ", chr[1])
etbl = etbl[chr %in% chr[1]]
chr = unique(as.character(etbl$chr)); start = min(as.numeric(etbl$start)); end = max(as.numeric(etbl$end))
}
if(!is.null(etbl)){
etbl = .make_exon_tbl(gene_models = etbl)
}
cyto = .extract_cytoband(chr = chr, refBuild = build)
loci = paste0(chr, ":", start, "-", end)
}else{
cyto = etbl = NA
}
if(is.null(etbl)){
stop("No transcript models found for ", gene)
}
}else{
message("Parsing loci..")
loci_p = .parse_loci(loci = loci)
chr = loci_p$chr; start = loci_p$start; end = loci_p$end
if(start >= end){
stop("End must be larger than Start!")
}
message(" Queried region: ", chr, ":", start, "-", end, " [", end-start, " bps]")
#Extract gene models for this region
if(!is.null(gtf)){
etbl = .parse_gtf(gtf = gtf, chr = chr, start = start, end = end)
cyto = NA
}else if(query_ucsc){
message("Querying UCSC genome browser for gene model and cytoband..")
etbl = .extract_geneModel_ucsc(chr, start = start, end = end, refBuild = build, txname = NULL, genename = NULL)
if(!is.null(etbl)){
etbl = .make_exon_tbl(gene_models = etbl)
}
cyto = .extract_cytoband(chr = chr, refBuild = build, tblName = ideoTblName)
}else{
cyto = etbl = NA
}
}
start = start - as.numeric(padding)
end = end + as.numeric(padding)
loci = paste0(chr, ":", start, "-", end)
input_files = colData$bw_files
custom_names = colData$bw_sample_names
if(input_bw){
windows = .gen_windows(chr = chr, start = start, end = end, window_size = binsize, op_dir = op_dir)
track_summary = .get_summaries(bedSimple = windows, bigWigs = input_files, op_dir = op_dir, nthreads = nthreads)
}else{
track_summary = .get_summaries_narrowPeaks(bigWigs = input_files, nthreads = nthreads, chr, start, end)
}
names(track_summary) = custom_names
attr(track_summary, "meta") = list(etbl = etbl, cyto = cyto, loci = loci)
message("OK!")
list(data = track_summary, colData = colData)
}
#' Summarize tracks per condition
#' @param summary_list Output from track_extract. Required.
#' @param condition a column name in \code{coldata} containing sample conditions. Default NULL.
#' @param stat can be `mean, median`, `max`, `min`. NAs are excluded.
#' @export
track_summarize = function(summary_list = NULL, condition = NULL, stat = "mean"){
if(is.null(summary_list)){
stop("Missing input! Expecting output from track_extract()")
}
stat = match.arg(arg = stat, choices = c("mean", "median", "max", "min"))
meta = attr(summary_list$data, "meta")
loci = meta$loci
etbl = meta$etbl
cyto = meta$cyto
coldata = summary_list$colData
is_bw = attr(coldata, "is_bw")
build = attr(coldata, "refbuild")
if(is.null(condition)){
stop("Please provide a column name containing sample condition!\nHere are available columns.\n", paste(colnames(coldata), collapse = " "))
}
summary_list = summary_list$data
if(!is.null(condition)){
if(!condition %in% colnames(coldata)){
warning(paste0(condition, " does not exists in coldata. Here are available columns."))
print(coldata)
stop()
}else{
colnames(coldata)[which(colnames(coldata) == condition)] = "group_condition"
coldata$group_condition = as.character(coldata$group_condition)
}
condition = as.character(coldata$group_condition)
}
names(summary_list) = condition
summary_list = data.table::rbindlist(l = summary_list, use.names = TRUE, fill = TRUE, idcol = "sample_name")
if(stat == "mean"){
summary_list = summary_list[,mean(max, na.rm = TRUE), .(sample_name, chromosome, start, end)]
}else if (stat == "median"){
summary_list = summary_list[,median(max, na.rm = TRUE), .(sample_name, chromosome, start, end)]
}else if (stat == "max"){
summary_list = summary_list[,max(max, na.rm = TRUE), .(sample_name, chromosome, start, end)]
}else{
summary_list = summary_list[,min(max, na.rm = TRUE), .(sample_name, chromosome, start, end)]
}
colnames(summary_list)[ncol(summary_list)] = "max" #this column name means nothing, just using it for the consistency
summary_list = split(summary_list, summary_list$sample_name)
attr(summary_list, "meta") = meta
list(data = summary_list, colData = coldata)
}
#' Generate IGV style locus tracks with ease
#' @param summary_list Output from track_extract
#' @param draw_gene_track Default FALSE. If TRUE plots gene models overlapping with the queried region
#' @param show_ideogram Default TRUE. If TRUE plots ideogram of the target chromosome with query loci highlighted. Works only when `query_ucsc` is TRUE.
#' @param txname transcript name to draw. Default NULL. Plots all transcripts overlapping with the queried region
#' @param genename gene name to draw. Default NULL. Plots all genes overlapping with the queried region
#' @param collapse_txs Default FALSE. Whether to collapse all transcripts belonging to same gene into a unified gene model
#' @param groupAutoScale Default TRUE
#' @param y_max custom y axis upper limits for each track. Recycled if required.
#' @param y_min custom y axis lower limits for each track. Recycled if required.
#' @param gene_fsize Font size. Default 1
#' @param col Color for tracks. Default `#2f3640`. Multiple colors can be provided for each track
#' @param show_axis Default FALSE
#' @param track_names Default NULL
#' @param track_names_pos Default 0 (corresponds to left corner)
#' @param track_names_to_left If TRUE, track names are shown to the left of the margin. Default FALSE, plots on top as a title
#' @param track_overlay Draws all bigWigs in a single track as a line plot
#' @param regions genomic regions to highlight. A data.frame with at-least three columns containing chr, start and end positions.
#' @param boxcol color for highlighted region. Default "#192A561A"
#' @param boxcolalpha Default 0.5
#' @param ucscChromHMM Name of the chromHMM table. Use .get_ucsc_hmm_tbls() to see the details.
#' @param chromHMM chromHMM data. Can be path to bed files or a list data.frames with first three columns containing chr,start,end and a 4th column containing integer coded state
#' @param chromHMM_names name for the chromHMM track
#' @param chromHMM_cols A named vector for each state (in the 4th column of chromHMM file). Default NULL
#' @param peaks bed file to be highlighted. Can be path to bed files or a list data.frames with first three columns containing chr,start,end.
#' @param peaks_track_names Provide a name for each loci bed file. Default NULL
#' @param cytoband_track_height Default 1
#' @param chromHMM_track_height Default 1
#' @param gene_track_height Default 2
#' @param scale_track_height Default 1
#' @param peaks_track_height Default 2.
#' @param bw_track_height Default 3
#' @param left_mar Space to the left. Default 4
#' @param bw_ord Names of the tracks to be drawn in the provided order. Default NULL.
#' @param layout_ord Plot layout order. Deafult c("p", "b", "h", "g", "c") corresponding to peaks track, bigWig track, chromHmm track, gene track, cytoband track.
#' @examples
#' bigWigs = system.file("extdata", "bw", package = "trackplot") |> list.files(pattern = "\\.bw$", full.names = TRUE)
#' cd = read_coldata(bws = bigWigs, build = "hg19")
#' oct4_loci = "chr6:31125776-31144789"
#' t = track_extract(colData = cd, loci = oct4_loci, build = "hg19")
#' trackplot::track_plot(summary_list = t)
#' @export
track_plot = function(summary_list = NULL,
draw_gene_track = TRUE,
show_ideogram = TRUE,
col = "gray70",
groupAutoScale = FALSE,
y_max = NULL,
y_min = NULL,
txname = NULL,
genename = NULL,
show_axis = FALSE,
gene_fsize = 1,
track_names = NULL,
track_names_pos = 0,
track_names_to_left = FALSE,
track_overlay = FALSE,
regions = NULL,
collapse_txs = TRUE,
boxcol = "#ffc41a",
boxcolalpha = 0.4,
chromHMM = NULL,
chromHMM_cols = NULL,
chromHMM_names = NULL,
ucscChromHMM = NULL,
peaks = NULL,
bw_track_height = 3,
peaks_track_height = 2,
gene_track_height = 2,
scale_track_height = 2,
chromHMM_track_height = 1,
cytoband_track_height = 2,
peaks_track_names = NULL,
left_mar = NULL,
bw_ord = NULL,
layout_ord = c("p", "b", "h", "g", "c")
){
if(is.null(summary_list)){
stop("Missing input! Expecting output from track_extract()")
}
meta = attr(summary_list$data, "meta")
loci = meta$loci
etbl = meta$etbl
cyto = meta$cyto
coldata = summary_list$colData
is_bw = attr(coldata, "is_bw")
build = attr(coldata, "refbuild")
loci_p = .parse_loci(loci = loci)
chr = loci_p$chr; start = loci_p$start; end = loci_p$end
# chr = summary_list$loci[1]
# start = as.numeric(summary_list$loci[2])
# end = as.numeric(summary_list$loci[3])
# etbl = summary_list$etbl
# cyto = summary_list$cyto
# is_bw = attr(summary_list, "is_bw")
# build = attr(summary_list, "refbuild")
summary_list = summary_list$data
#Change the order
if(!is.null(bw_ord)){
bw_ord = intersect(names(summary_list), bw_ord)
if(length(bw_ord) == 0){
stop("None of the provided bw_ord are presnt in the data! Available names:\n", paste(names(summary_list), collapse = ", "))
}
summary_list = summary_list[bw_ord]
coldata = data.table::rbindlist(split(coldata, coldata$bw_sample_names)[bw_ord])
}
if(length(col) != length(summary_list)){
col = rep(x = col, length(summary_list))
}
plot_regions = FALSE
if(!is.null(regions)){
if(is(object = regions, class2 = "data.frame")){
regions = data.table::as.data.table(x = regions)
colnames(regions)[1:3] = c("chromsome", "startpos", "endpos")
regions = regions[chromsome %in% chr]
if(nrow(regions) == 0){
warning("None of the regions are within the requested chromosme: ", chr)
plot_regions = TRUE
}else{
plot_regions = TRUE
}
}else{
stop("'mark_regions' must be a data.frame with first 3 columns containing : chr, start, end")
}
}
if(!is.null(track_names)){
names(summary_list) = track_names
}
groupScaleByCondition = FALSE #For furture
if(groupScaleByCondition){
plot_height = unlist(lapply(summary_list, function(x) max(x$max, na.rm = TRUE)))
plot_height_min = unlist(lapply(summary_list, function(x) min(x$max, na.rm = TRUE)))
plot_height = data.table::data.table(plot_height, plot_height_min, col, names(summary_list))
plot_height$og_ord = 1:nrow(plot_height)
plot_height = plot_height[order(col)]
plot_height_max = plot_height[,.(.N, max(plot_height)), .(col)]
plot_height_min = plot_height[,.(.N, max(plot_height_min)), .(col)]
plot_height$max = rep(plot_height_max$V2, plot_height_max$N)
plot_height$min = rep(plot_height_min$V2, plot_height_min$N)
plot_height_min = plot_height[order(og_ord)][,min]
plot_height = plot_height[order(og_ord)][,max]
}else if(groupAutoScale){
plot_height = max(unlist(lapply(summary_list, function(x) max(x$max, na.rm = TRUE))), na.rm = TRUE)
plot_height_min = min(unlist(lapply(summary_list, function(x) min(x$max, na.rm = TRUE))), na.rm = TRUE)
plot_height = rep(plot_height, length(summary_list))
plot_height_min = rep(plot_height_min, length(summary_list))
}else{
plot_height = unlist(lapply(summary_list, function(x) max(x$max, na.rm = TRUE)))
plot_height_min = unlist(lapply(summary_list, function(x) min(x$max, na.rm = TRUE)))
}
if(!is.null(y_max)){
#If custom ylims are provided
if(length(y_max) != length(summary_list)){
y_max = rep(y_max, length(summary_list))
}
plot_height = y_max
}else{
plot_height = round(plot_height, digits = 2)
}
if(!is.null(y_min)){
#If custom ylims are provided
if(length(y_min) != length(summary_list)){
y_min = rep(y_min, length(summary_list))
}
plot_height_min = y_min
}else{
plot_height_min = round(plot_height_min, digits = 2)
}
if(is_bw & track_overlay){
ntracks = 1
}else{
ntracks = length(summary_list)
}
lo = .make_layout(ntracks = ntracks, ntracks_h = bw_track_height, cytoband = show_ideogram, cytoband_h = cytoband_track_height, genemodel = draw_gene_track,
genemodel_h = gene_track_height, chrHMM = any(!is.null(ucscChromHMM), !is.null(chromHMM)), chrHMM_h = chromHMM_track_height, loci = !is.null(peaks),
loci_h = peaks_track_height, scale_track_height = scale_track_height, lord = layout_ord)
query = data.table::data.table(chr = chr, start = start, end = end)
data.table::setkey(x = query, chr, start, end)
if(is.null(left_mar)){
left_mar = ifelse(test = show_axis, yes = 4, no = 2)
}
#Draw top peaks
if(!is.null(peaks)){
if(is.list(peaks)){
peaks_data = lapply(peaks, function(l){
colnames(l)[1:3] = c("chr", "start", "end")
data.table::setDT(l, key = c("chr", "start", "end"))
l
})
}else{
peaks_data = lapply(peaks, function(l){
l = data.table::fread(file = l)
colnames(l)[1:3] = c("chr", "start", "end")
data.table::setDT(l, key = c("chr", "start", "end"))
l
})
}
if(is.null(peaks_track_names)){
names(peaks_data) = paste0("Bed", 1:length(peaks_data))
}else{
names(peaks_data) = peaks_track_names
}
if(show_axis){
par(mar = c(0.25, left_mar, 0.25, 1))
}else{
par(mar = c(0.25, left_mar, 0.25, 1))
}
plot(NA, xlim = c(start, end), ylim = c(0, length(peaks)), frame.plot = FALSE, axes = FALSE, xlab = NA, ylab = NA)
for(idx in seq_along(peaks_data)){
l_idx = peaks_data[[idx]]
l_idx = data.table::foverlaps(x = query, y = l_idx, type = "any", nomatch = NULL)[,.(chr, start, end)]
rect(xleft = start, ybottom = idx - 0.49, xright = end, ytop = idx - 0.51, col = "gray90", border = NA)
if(nrow(l_idx) > 0){
rect(xleft = l_idx$start, ybottom = idx - 0.9, xright = l_idx$end, ytop = idx - 0.1, col = "#34495e", border = NA)
}
text(x = start, y = idx - 0.5, labels = names(peaks_data)[idx], adj = 1.2, xpd = TRUE)
}
}
#Draw bigWig signals
boxcol = grDevices::adjustcolor(boxcol, alpha.f = boxcolalpha)
if(is_bw){
if(track_overlay){
if(show_axis){
par(mar = c(0.5, left_mar, 2, 1))
}else{
par(mar = c(0.5, left_mar, 2, 1))
}
plot(NA, xlim = c(start, end), ylim = c(min(plot_height_min), max(plot_height)), frame.plot = FALSE, axes = FALSE, xlab = NA, ylab = NA)
for(idx in 1:length(summary_list)){
x = summary_list[[idx]]
if(nrow(x) == 0){
if(track_names_to_left){
text(x = start, y = 0.5, labels = names(summary_list)[idx], adj = 1, cex = gene_fsize, xpd = TRUE)
#mtext(text = names(summary_list)[idx], side = 2, line = -2, outer = TRUE, xpd = TRUE, las = 2, adj = 0)
#title(main = , adj = track_names_pos, font.main = 3)
}else{
title(main = names(summary_list)[idx], adj = track_names_pos, font.main = 3)
}
next
}
points(x = x$start, y = x$max, col = col[idx], type = "l")
}
if(plot_regions){
# boxcol = "#192a56"
if(nrow(x) > 0){
rect(xleft = regions[, startpos], ybottom = 0, xright = regions[, endpos], ytop = max(plot_height), col = boxcol, border = NA, xpd = TRUE)
}
}
if(show_axis){
axis(side = 2, at = c(min(plot_height_min), max(plot_height)), las = 2)
}
legend(x = "topright", legend = names(summary_list), col = col, pch = "-")
}else{
for(idx in 1:length(summary_list)){
x = summary_list[[idx]]
if(show_axis){
par(mar = c(0.5, left_mar, 2, 1))
}else{
par(mar = c(0.5, left_mar, 2, 1))
}
plot(NA, xlim = c(start, end), ylim = c(plot_height_min[idx], plot_height[idx]), frame.plot = FALSE, axes = FALSE, xlab = NA, ylab = NA)
#If there is no signal, just add the track names and go to next
if(nrow(x) == 0){
if(track_names_to_left){
text(x = start, y = 0.5, labels = names(summary_list)[idx], adj = 1, cex = gene_fsize, xpd = TRUE)
#mtext(text = names(summary_list)[idx], side = 2, line = -2, outer = TRUE, xpd = TRUE, las = 2, adj = 0)
#title(main = , adj = track_names_pos, font.main = 3)
}else{
title(main = names(summary_list)[idx], adj = track_names_pos, font.main = 3)
}
next
}
rect(xleft = x$start, ybottom = 0, xright = x$end, ytop = x$max, col = col[idx], border = col[idx])
if(show_axis){
axis(side = 2, at = c(plot_height_min[idx], plot_height[idx]), las = 2)
}else{
text(x = start, y = plot_height[idx], labels = paste0("[", plot_height_min[idx], "-", plot_height[idx], "]"), adj = 0, xpd = TRUE)
}
#plot(NA, xlim = c(start, end), ylim = c(0, nrow(regions)), frame.plot = FALSE, axes = FALSE, xlab = NA, ylab = NA)
if(plot_regions){
# boxcol = "#192a56"
if(nrow(x) > 0){
rect(xleft = regions[, startpos], ybottom = 0, xright = regions[, endpos], ytop = max(plot_height), col = boxcol, border = NA, xpd = TRUE)
}
}
if(track_names_to_left){
text(x = start, y = (plot_height_min[idx] + plot_height[idx])/2, labels = names(summary_list)[idx], adj = 1.1, cex = gene_fsize, xpd = TRUE)
}else{
title(main = names(summary_list)[idx], adj = track_names_pos, font.main = 3)
}
}
}
}else{
for(idx in 1:length(summary_list)){
x = summary_list[[idx]]
if(show_axis){
par(mar = c(0, left_mar, 0, 1))
}else{
par(mar = c(0.5, left_mar, 1, 1))
}
plot(NA, xlim = c(start, end), ylim = c(0, 1), frame.plot = FALSE, axes = FALSE, xlab = NA, ylab = NA)
#If there is no signal, just add the track names and go to next
if(nrow(x) == 0){
if(track_names_to_left){
text(x = start, y = 0.5, labels = names(summary_list)[idx], adj = 1, cex = gene_fsize, xpd = TRUE)
#mtext(text = names(summary_list)[idx], side = 2, line = -2, outer = TRUE, xpd = TRUE, las = 2, adj = 0)
#title(main = , adj = track_names_pos, font.main = 3)
}else{
title(main = names(summary_list)[idx], adj = track_names_pos, font.main = 3)
}
next
}
# add a buff to max(x$max) to avoid duplication.
cols = cut(x$max, breaks = c(0, 166, 277, 389, 500, 612, 723, 834, 945, max(x$max)+1e-8), labels = c("#FFFFFF", "#F0F0F0", "#D9D9D9", "#BDBDBD", "#969696", "#737373",
"#525252", "#252525", "#000000"))
rect(xleft = x$start, ybottom = 0.01, xright = x$end, ytop = 0.99, col = as.character(cols), border = NA)
if(plot_regions){
# boxcol = "#192a56"
boxcol = grDevices::adjustcolor(boxcol, alpha.f = boxcolalpha)
if(nrow(regions) > 0){
if(nrow(x) > 0){
rect(xleft = regions[, startpos], ybottom = 0, xright = regions[, endpos], ytop = max(plot_height), col = boxcol, border = NA, xpd = TRUE)
}
}
}
if(track_names_to_left){
text(x = start, y = 0.5, labels = names(summary_list)[idx], adj = 1, cex = gene_fsize, xpd = TRUE)
#mtext(text = names(summary_list)[idx], side = 2, line = -2, outer = TRUE, xpd = TRUE, las = 2, adj = 0)
#title(main = , adj = track_names_pos, font.main = 3)
}else{
title(main = names(summary_list)[idx], adj = track_names_pos, font.main = 3)
}
}
}
#Draw chrom HMM tracks
plotHMM = FALSE
if(!is.null(chromHMM)){
if(is.list(chromHMM)){
chromHMM = lapply(chromHMM, function(l){
colnames(l)[1:4] = c("chr", "start", "end", "name")
data.table::setDT(l, key = c("chr", "start", "end"))
l
})
}else{
chromHMM = lapply(chromHMM, function(l){
l = data.table::fread(file = l)
colnames(l)[1:4] = c("chr", "start", "end", "name")
data.table::setDT(l, key = c("chr", "start", "end"))
})
}
hmmdata = lapply(chromHMM, function(hmm){
.load_chromHMM(chr = chr, start = start, end = end, ucsc = hmm)
#.extract_chromHmm_ucsc()
})
if(is.null(chromHMM_names)){
names(hmmdata) = paste0("chromHMM_", 1:length(hmmdata))
}else{
names(hmmdata) = chromHMM_names
}
plotHMM = TRUE
}else if(!is.null(ucscChromHMM)){
hmmdata = lapply(ucscChromHMM, function(hmmtbl){
.extract_chromHmm_ucsc(chr = chr, start = start, end = end, refBuild = build, tbl = hmmtbl)
})
names(hmmdata) = ucscChromHMM
plotHMM = TRUE
#return(hmmdata)
}
if(plotHMM){
if(show_axis){
par(mar = c(0.1, left_mar, 0, 1))
}else{
par(mar = c(0.1, left_mar, 0, 1))
}
if(is.null(chromHMM_cols)){
chromHMM_cols = .get_ucsc_hmm_states_cols()
}
.plot_ucsc_chrHmm(d = hmmdata, start = start, end = end, hmm_cols = chromHMM_cols)
}
#Draw gene models
if(draw_gene_track){
#etbl = .make_exon_tbl(gene_models = etbl, txname = txname, genename = genename)
if(!is.null(etbl)){
if(!is.null(genename)){
if(length(etbl[unlist((lapply(etbl, attr, "gene"))) %in% genename]) == 0){
message("Note: Could not find any of the requested gene names! Available genes are:")
print(unique(unlist((lapply(etbl, attr, "gene")))))
}else{
etbl = etbl[unlist((lapply(etbl, attr, "gene"))) %in% genename]
}
}
if(collapse_txs){
etbl = .collapse_tx(etbl)
}
if(show_axis){
par(mar = c(0.25, left_mar, 0, 1))
}else{
par(mar = c(0.25, left_mar, 0, 1))
}
plot(NA, xlim = c(start, end), ylim = c(0, length(etbl)), frame.plot = FALSE, axes = FALSE, xlab = NA, ylab = NA)
exon_col = "#192a56"
for(tx_id in 1:length(etbl)){
txtbl = etbl[[tx_id]]
segments(x0 = attr(txtbl, "start"), y0 = tx_id-0.45, x1 = attr(txtbl, "end"), y1 = tx_id-0.45, col = exon_col, lwd = 1)
name_at = min(c(txtbl[[1]], txtbl[[2]]))
if(is.na(attr(txtbl, "tx"))){
text(x = name_at, y = tx_id-0.45, labels = paste0(attr(txtbl, "gene")), adj = 1, cex = gene_fsize, xpd = TRUE, pos = 2) #x = start for outer margin
}else{
text(x = name_at, y = tx_id-0.45, labels = paste0(attr(txtbl, "tx"), " [", attr(txtbl, "gene"), "]"), cex = gene_fsize, adj = 0, xpd = TRUE, pos = 2)
}
rect(xleft = txtbl[[1]], ybottom = tx_id-0.75, xright = txtbl[[2]], ytop = tx_id-0.25, col = exon_col, border = NA)
if(attr(txtbl, "strand") == "+"){
dirat = pretty(x = c(min(txtbl[[1]]), max(txtbl[[2]])))
dirat[1] = min(txtbl[[1]]) #Avoid drawing arrows outside gene length
dirat[length(dirat)] = max(txtbl[[2]])
points(x = dirat, y = rep(tx_id-0.45, length(dirat)), pch = ">", col = exon_col)
}else{
dirat = pretty(x = c(min(txtbl[[1]]), max(txtbl[[2]])))
dirat[1] = min(txtbl[[1]]) #Avoid drawing arrows outside gene length
dirat[length(dirat)] = max(txtbl[[2]])
points(x = dirat, y = rep(tx_id-0.45, length(dirat)), pch = "<", col = exon_col)
}
}
}
}
#Draw scale
if(show_axis){
par(mar = c(0, left_mar, 0, 1))
}else{
par(mar = c(0, left_mar, 0, 1))
}
lab_at = pretty(c(start, end))
lab_at_lab = ifelse(test = lab_at > 1e6, yes = paste0(lab_at/1e6, "M"), no = ifelse(lab_at > 100000, yes = paste0(lab_at/1e5, "K"), no = lab_at))
plot(NA, xlim = c(start, end), ylim = c(0, 1), frame.plot = FALSE, axes = FALSE, xlab = NA, ylab = NA)
rect(xleft = start, ybottom = 0.5, xright = end, ytop = 0.5, lty = 2, xpd = TRUE)
rect(xleft = lab_at, ybottom = 0.45, xright = lab_at, ytop = 0.5, xpd = TRUE)
text(x = lab_at, y = 0.2, labels = lab_at_lab, xpd = FALSE)
#axis(side = 1, at = lab_at, lty = 2, line = -3)
text(x = end, y = 0.9, labels = paste0(chr, ":", start, "-", end), adj = 1, xpd = TRUE)
#Draw ideogram
if(is.list(cyto)){
if(show_ideogram){
par(mar = c(0.2, 1, 0, 1))
plot(NA, xlim = c(0, max(cyto$end)), ylim = c(0, 1), axes = FALSE, frame.plot = FALSE, xlab = NA, ylab = NA)
rect(xleft = cyto$start, ybottom = 0.1, xright = cyto$end, ytop = 0.6, col = cyto$color, border = "#34495e")
rect(xleft = start, ybottom = 0, xright = end, ytop = 0.7, col = "#d35400", lwd = 2, border = "#d35400")
text(x = 0, y = 0.5, labels = chr, adj = 1.2, font = 2, xpd = TRUE)
}
}
}
# profileplot is an ultra-fast, simple, and minimal dependency R script to generate profile-plots from bigWig files
#' Generate bigWig signal matrix for given genomic regions or ucsc refseq transcripts
#' @param colData from \code{read_coldata}
#' @param bed bed file or a data.frame with first 3 column containing chromosome, star, end positions.
#' @param binSize bin size to extract signal. Default 50 (bps). Should be >1
#' @param startFrom Default "start". For bed files this can be "start", "center" or "end". For `ucsc_assembly` this can only be "start" or "end"
#' @param up extend upstream by this many bps from `startFrom`. Default 2500
#' @param down extend downstream by this many bps from `startFrom`. Default 2500
#' @param ucsc_assembly If `bed` file not provided, setting `ucsc_assembly` to TRUE will fetch transcripts from UCSC genome browser.
#' @param pc_genes Use only protein coding genes when `ucsc_assembly` is used. Default TRUE
#' @param nthreads Default 4
#' @seealso \code{\link{profile_summarize}} \code{\link{profile_plot}} \code{\link{profile_heatmap}}
#' @export
profile_extract = function(colData = NULL, bed = NULL, ucsc_assembly = TRUE, startFrom = "start", binSize = 50,
up = 2500, down = 2500, pc_genes = TRUE, nthreads = 4){
.check_windows()
.check_bwtool(warn = FALSE)
.check_dt()
if(is.null(colData)){
stop("Missing colData. Use read_coldata() to generate one.")
}
bigWigs = colData$bw_files
custom_names = colData$bw_sample_names
op_dir = tempdir() #For now
if(is.null(bed)){
if(ucsc_assembly){
ucsc_assembly = attr(colData, "refbuild")
message("No bed file was given. Defaulting to ucsc refseq..")
startFrom = match.arg(arg = startFrom, choices = c("start", "end"))
bed = .make_genome_bed(refBuild = ucsc_assembly, up = as.numeric(up), down = as.numeric(down), tss = startFrom, op_dir = op_dir, pc_genes = pc_genes, for_profile = TRUE)
bed_annot = bed[[2]]
bed = bed[[1]]
}else{
stop("Please provide either a BED file or set ucsc_assembly to TRUE")
}
}else{
startFrom = match.arg(arg = startFrom, choices = c("start", "end", "center"))
bed = .make_bed(bed = bed, op_dir = op_dir, up = as.numeric(up), down = as.numeric(up), tss = startFrom, for_profile = TRUE)
bed_annot = NA
}
message("Extracting signals..")
mats = parallel::mclapply(bigWigs, function(x){
.bwt_mats(bw = x, binSize = binSize, bed = bed, size = paste0(up, ":", down), startFrom = startFrom, op_dir = op_dir)
}, mc.cores = nthreads)
mats = as.character(unlist(x = mats))
sig_list = lapply(mats, data.table::fread)
if(!is.null(custom_names)){
names(sig_list) = custom_names
}else{
names(sig_list) = gsub(pattern = "*\\.matrix$", replacement = "", x = basename(path = mats))
}
attr(sig_list, "args") = c(up, down)
#Remove intermediate files
lapply(mats, function(x) system(command = paste0("rm ", x), intern = TRUE))
list(data = sig_list, colData = colData)
}
#' Summarize data for profile plots
#' @param sig_list Output generated from `profile_extract`
#' @param stat Default `mean`. Can be `mean`, `median`
#' @param condition column name with conditions in `colData`. If provided summarizes signals from samples belonging to same group or condition
#' @seealso \code{\link{profile_extract}} \code{\link{profile_plot}} \code{\link{profile_heatmap}}
#' @export
profile_summarize = function(sig_list = NULL, stat = "mean", condition = NULL){
if(is.null(sig_list)){
stop("Missing input! Use profile_extract() to generate one.")
}
stat = match.arg(arg = stat, choices = c("mean", 'median'))
colData = sig_list$colData
collapse_replicates = FALSE
if(!is.null(condition)){
if(!condition %in% colnames(colData)){
stop(condition , " not found in colData!\nAvailable columns: ", print(paste(colnames(colData), collapse = " ")))
}
collapse_by_idx = which(colnames(colData) == condition)
condition = unlist(colData[,collapse_by_idx, with = FALSE], use.names = FALSE)
collapse_replicates = TRUE
}
message("Summarizing..")
sig_summary = .summarizeMats(mats = sig_list$data, group = condition, collapse_reps = collapse_replicates, summarizeBy = stat)
attr(sig_summary, "args") = attr(sig_list$data, "args")
list(data = sig_summary, colData = colData)
}
#' Draw a profile plot
#' @param sig_list Output generated from profile_summarize
#' @param color Manual colors for each bigWig. Default NULL.
#' @param line_size Default 1
#' @param legend_fs Legend font size. Default 1
#' @param axis_fs Axis font size. Default 1
#' @param xlab x axis label. Default NA
#' @param ylab y axis label. Default NA
#' @export
profile_plot = function(sig_list = NULL, color = NULL, line_size = 1, legend_fs = 1, axis_fs = 1, xlab = NA, ylab = NA){
if(is.null(sig_list)){
stop("Missing input! Expecting output from profile_summarize()")
}
args = attr(sig_list$data, "args")
up = as.numeric(args[1])
down = as.numeric(args[2])
sig_summary = sig_list$data
if(is.null(color)){
color = c("#2f4f4f", "#8b4513", "#228b22", "#00008b", "#ff0000", "#ffd700", "#7fff00", "#00ffff", "#ff00ff", "#6495ed", "#ffe4b5", "#ff69b4") #hcl.colors(n = 10, palette = "Dark 2")
color = color[1:length(sig_summary)]
}
y_max = max(unlist(lapply(sig_summary, max, na.rm = TRUE)))
y_min = min(unlist(lapply(sig_summary, min, na.rm = TRUE)))
ylabs = pretty(c(y_min, y_max), n = 5)
x_max = max(unlist(lapply(sig_summary, length)))
xlabs = c(up, 0, down)
xticks = xticks = c(0,
as.integer(length(sig_summary[[1]])/sum(as.numeric(xlabs[1]), as.numeric(xlabs[3])) * as.numeric(xlabs[1])),
length(sig_summary[[1]]))
#line_size = 1
par(mar = c(4, 4, 2, 1))
plot(NA, xlim = c(0, x_max), ylim = c(min(ylabs), max(ylabs)), frame.plot = FALSE, axes = FALSE, xlab = NA, ylab = NA)
abline(h = ylabs, v = pretty(xticks), col = "gray90", lty = 2)
lapply(1:length(sig_summary), function(idx){
points(sig_summary[[idx]], type = 'l', lwd = line_size, col = color[idx])
})
axis(side = 1, at = xticks, labels = xlabs, cex.axis = axis_fs)
axis(side = 2, at = ylabs, las = 2, cex.axis = axis_fs)
legend(x = "topright", legend = names(sig_summary), col = color, bty = "n", lty = 1, lwd = 1.2, cex = legend_fs, xpd = TRUE)
mtext(text = xlab, side = 1, line = 2.5, cex = 1)
mtext(text = ylab, side = 2, line = 2.5, cex = 1)
invisible(list(mean_signal = sig_summary, color_codes = color, xticks = xticks, xlabs = xlabs))
}
#' Draw a heatmap
#' @details This function takes output from extract_matrix and draws a heatmap
#' @param mat_list Input matrix list generated by \code{\link{profile_extract}}
#' @param sortBy Sort matrix by.., Can be mean, median. Default mean.
#' @param col_pal Color palette to use. Default Blues. Use hcl.pals(type = "sequential") to see available palettes
#' @param revpal Reverse color palette? Default FALSE.
#' @param sample_names Manually specify sample names.
#' @param title_size size of title. Default 0.8
#' @param top_profile Boolean. Whether to draw top profile plot.
#' @param top_profile_h Default 2.
#' @param zmins Manually specify min scores to include in heatmap
#' @param zmaxs Manually specify max scores to include in heatmap
#' @param scale Whether to row scale the matrix. Default FALSE
#' @param file_name Default NULL. If provided saves plot as a png.
#' @param hm_width Width of the plot. Default 1024
#' @param hm_height Height of the plot. Default 600
#' @param mat_order Default NULL. Sample order in which the heatmaps are drawn.
#' @export
profile_heatmap = function(mat_list, sortBy = "mean", col_pal = "Blues", revpal = FALSE, sample_names = NULL,
title_size = 1, top_profile = FALSE, top_profile_h = 2, zmins = NULL, zmaxs = NULL,
scale = FALSE, file_name = NULL, hm_width = 1024, hm_height = 600, mat_order = NULL){
if(!sortBy %in% c("mean", "median")){
stop("sortBy can only be mean, median")
}
col_pal = match.arg(arg = col_pal, choices = hcl.pals(type = "sequential"))
hmcols = rev(hcl.colors(n = 255, palette = col_pal))
if(revpal){
hmcols = rev(hmcols)
}
cdata = mat_list$colData
size = attr(mat_list$data, "args")
mat_list = mat_list$data
if(!is.null(mat_order)){
if(length(mat_order) != length(mat_list)){
stop("Length of mat_order should be the same as number of bw files! [", length(mat_list), "]")
}
mat_list = mat_list[mat_order]
}