-
Notifications
You must be signed in to change notification settings - Fork 3
/
gUtils_source
4752 lines (3974 loc) · 157 KB
/
gUtils_source
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
rowid=.N=colid=V1=inner=startFrom=breakAt=upTo=qid2=tmp.start=subject.id=query.id=transition=ix=nacluster=clusterlength=ix.new=slen=slev=clilp=val=query.id=subject.id=lev=len=cs=type=group=run=chr=ra1.ix=ra2.ix=pos2=chr=V1=NULL
#' DNAaseI hypersensitivity sites for hg19A
#'
#' DNAaseI hypersensitivity sites from UCSC Table Browser hg19,
#' subsampled to 10,000 sites
#' @name example_dnase
#' @docType data
#' @keywords data
#' @format \code{GRanges}
NULL
#' RefSeq genes for hg19
#'
#' RefSeq genes with exon count and name
#' @name example_genes
#' @docType data
#' @keywords data
#' @format \code{GRanges}
NULL
#' Fake rearrangement data (set 1)
#'
#' @name grl1
#' @docType data
#' @keywords data
#' @format \code{GRangesList}
NULL
#' Fake rearrangement data (set 2)
#'
#' @name grl2
#' @docType data
#' @keywords data
#' @format \code{GRangesList}
NULL
#' \code{Seqinfo} object for hg19
#'
#' @name si
#' @docType data
#' @keywords data
#' @format \code{Seqinfo}
NULL
#' HiC data for chr14 from Lieberman-Aiden 2009 (in hg19), subsampled
#' to 10,000 interactions
#'
#' @name grl.hiC
#' @docType data
#' @keywords data
#' @format \code{GRangesList}
NULL
#' @name hg_seqlengths
#' @title Output standard human genome seqlengths
#' @description
#'
#' Outputs a standard seqlengths for human genome +/- "chr".
#'
#' @note A default genome can be set with the environment variable DEFAULT_GENOME. This
#' can be the full namespace of the genome e.g.: \code{DEFAULT_GENOME=BSgenome.Hsapiens.UCSC.hg19::Hsapiens} OR a URL / file path pointing to a chrom.sizes text file (e.g. http://genome.ucsc.edu/goldenpath/help/hg19.chrom.sizes) specifying a genome definition
#' @param genome A \code{BSgenome} or object with a \code{seqlengths} accessor. Default is hg19, but loads with warning unless explicitly provided
#' @param chr boolean Flag for whether to keep "chr". (default = FALSE)
#' @param include.junk boolean Flag for whether to not trim to only 1-22, X, Y, M. (default = FALSE)
#' @return Named integer vector with elements corresponding to the genome seqlengths
#' @importFrom utils read.delim
#' @importFrom stats setNames
#' @importFrom utils relist
#' @importFrom methods as is
#' @importFrom S4Vectors elementNROWS
#' @author Marcin Imielinski
#' @export
hg_seqlengths = function(genome = NULL, chr = TRUE, include.junk = FALSE)
{
sl = NULL
dbs = ''
if (!is.null(genome))
dbs = genome
else
{
if (nchar(Sys.getenv("DEFAULT_GENOME"))>0)
dbs = Sys.getenv("DEFAULT_GENOME")
else if (nchar(Sys.getenv("DEFAULT_BSGENOME"))>0)
dbs = Sys.getenv("DEFAULT_BSGENOME")
}
if (nchar(dbs) == 0)
{
warning('hg_seqlengths: supply genome seqlengths or set default with env variable DEFAULT_GENOME (e.g. Sys.setenv(DEFAULT_GENOME = "BSgenome.Hsapiens.UCSC.hg19::Hsapiens"). DEFAULT_BSGENOME can also be set to a path or URL of a tab delimited text *.chrom.sizes file')
return(NULL)
} else{
tmp = suppressWarnings(tryCatch(read.delim(dbs, header = FALSE), error= function(e) NULL))
if (is.null(tmp))
{
genome = tryCatch(eval(parse(text=dbs)), error = function(e) NULL)
if (is.null(genome)){
stop(sprintf("Error loading %s as chrom.sizes or BSGenome library ...\nPlease check DEFAULT_GENOME setting and set to either an R library BSGenome object or a valid http URL or filepath pointing to a chrom.sizes tab delimited text file.", dbs))
}
}else{
sl = structure(tmp[,2], names = as.character(tmp[,1]))
}
}
if (is.null(sl)){
sl = seqlengths(genome)
}
if (!chr){
names(sl) = gsub('chr', '', names(sl))
}
if (!include.junk){
sl = sl[nchar(names(sl))<=8]
}
return(sl)
}
#' @name gr2dt
#' @title Converts \code{GRanges} to \code{data.table}
#' @description
#'
#' Converts \code{GRanges} to \code{data.table}
#' and a field grl.iix which saves the (local) index that that gr was in its corresponding grl item
#'
#' @param x \code{GRanges} to convert
#' @return data.table of GRanges columns ('seqnames', 'start', 'end', 'strand', 'width') and metadata columns
#' @export
gr2dt = function(x)
{
## new approach just directly instantiating data table
cmd = 'data.frame(';
if (is(x, 'GRanges'))
{
## as.data.table complains if duplicated row names
if (any(duplicated(names(x)))){
names(x) <- NULL
}
was.gr = TRUE
f = c('seqnames', 'start', 'end', 'strand', 'width')
f2 = c('as.character(seqnames', 'c(start', 'c(end', 'as.character(strand', 'as.numeric(width')
cmd = paste(cmd, paste(f, '=', f2, '(x))', sep = '', collapse = ','), sep = '')
value.f = names(values(x))
} else {
was.gr = FALSE
value.f = names(x)
}
if (length(value.f)>0)
{
if (was.gr){
cmd = paste(cmd, ',', sep = '')
}
class.f = sapply(value.f, function(f) eval(parse(text=sprintf("class(x$'%s')", f))))
.StringSetListAsList = function(x){
tmp1 = as.character(unlist(x))
tmp2 = rep(1:length(x), S4Vectors::elementNROWS(x))
return(split(tmp1, tmp2))
}
## take care of annoying S4 / DataFrame / data.frame (wish-they-were-non-)issues
as.statement = ifelse(grepl('Integer', class.f), 'as.integer',
ifelse(grepl('Character', class.f), 'as.character',
ifelse(grepl('((StringSet)|(Compressed.*))List', class.f), '.StringSetListAsList',
ifelse(grepl('StringSet$', class.f), 'as.character',
ifelse(grepl('factor$', class.f), 'as.character',
ifelse(grepl('List', class.f), 'as.list',
ifelse(grepl('factor', class.f), 'as.character',
ifelse(grepl('List', class.f), 'as.list', 'c'))))))))
cmd = paste(cmd, paste(value.f, '=', as.statement, "(x$'", value.f, "')", sep = '', collapse = ','), sep = '')
}
cmd = paste(cmd, ')', sep = '')
out = tryCatch(data.table::as.data.table(eval(parse(text =cmd))), error = function(e) NULL)
nr = 0
if (!is.null(out)) { nr = nrow(out) }
if (nr != length(x))
{
out = as.data.table(x)
}
return(out)
}
#' @name gr.start
#' @title Get GRanges corresponding to beginning of range
#' @description
#'
#' Get GRanges corresponding to beginning of range
#'
#' @param x \code{GRanges} object to operate on
#' @param width integer Specify subranges of greater width including the start of the range. (default = 1)
#' @param force boolean Allows returned \code{GRanges} to have ranges outside of its \code{Seqinfo} bounds. (default = FALSE)
#' @param ignore.strand boolean If set to \code{FALSE}, will extend '-' strands from the other direction (default = TRUE)
#' @param clip boolean Trims returned \code{GRanges} so that it does not extend beyond bounds of the input \code{GRanges} (default = TRUE)
#' @return \code{GRanges} object of width 1 ranges representing start of each genomic range in the input.
#' @importFrom GenomicRanges GRanges
#' @examples
#'
#' gr.start(example_dnase, width=200)
#' gr.start(example_dnase, width=200, clip=TRUE)
#'
#' @export
gr.start = function(x, width = 1, force = FALSE, ignore.strand = TRUE, clip = TRUE)
{
if (length(x)==0){
return(x)
}
width = pmax(width, 1)
if (any(seqlengths(x)==0) | any(is.na(seqlengths(x)))){
warning('Warning: Check or fix seqlengths, some are equal 0 or NA, may lead to negative widths')
}
.grstart = function(x)
{
if (force)
{
if (ignore.strand)
{
st = as.vector(start(x))
en = as.vector(start(x))+width-1
} else {
st = ifelse(as.character(strand(x)) %in% c('*', '+'),
as.vector(start(x)),
as.vector(end(x))-width+1)
en = ifelse(as.character(strand(x)) %in% c('*', '+'),
as.vector(start(x))+width-1,
as.vector(end(x))
)
}
} else{
if (ignore.strand){
st = start(x)
en = pmin(as.vector(start(x))+width-1, seqlengths(x)[as.character(seqnames(x))], na.rm = TRUE)
} else{
st = ifelse(as.character(strand(x)) %in% c('*', '+'),
as.vector(start(x)),
pmax(as.vector(end(x))-width+1, 1)
)
en = ifelse(as.character(strand(x)) %in% c('*', '+'),
pmin(as.vector(start(x))+width-1, seqlengths(x)[as.character(seqnames(x))], na.rm = TRUE),
as.vector(end(x)))
}
}
if (clip){
en = pmin(en, end(x))
st = pmax(st, start(x))
}
ir = IRanges(st, en)
}
ir = tryCatch(.grstart(x), error = function(e) NULL)
if (is.null(ir)){
warning("Warning: One or more ranges are out of bounds on seqlengths, fixing and rerunning")
x = gr.fix(x)
ir = .grstart(x)
}
out = GRanges(seqnames(x), ir, seqlengths = seqlengths(x), strand = strand(x))
values(out) = values(x)
return(out)
}
#' @name dt2gr
#' @title Convert data.table to GRanges
#' @description
#'
#' Takes as input a data.table which must have the following fields: \code{start}, \code{end}, \code{strand}, \code{seqnames}. Will throw
#' an error if any one of these is not present.
#' All of the remaining fields are added as metadata to the \code{GRanges}.
#'
#' @param dt data.table or data.frame to convert to \code{GRanges}
#' @param seqlengths named integer vector representing genome (default = hg_seqlengths())
#' @param seqinfo seqinfo of output GRanges object
#' @return \code{GRanges} object of \code{length = nrow(dt)}
#' @importFrom data.table data.table
#' @importFrom GenomicRanges GRanges mcols
#' @importFrom IRanges IRanges
#' @examples
#' converted_gr = dt2gr(data.table(start=c(1,2), seqnames=c("X", "1"), end=c(10,20), strand = c('+', '-')))
#' @export
dt2gr = function(dt, key = NULL, seqlengths = NULL, seqinfo = Seqinfo()) {
if (!inherits(dt, 'data.frame') & !inherits(dt, 'data.table')){
stop("Error: Input needs to be data.table or data.frame")
}
if (!is(dt, 'data.table'))
dt = as.data.table(dt)
if (is.null(seqlengths))
seqlengths = seqlengths(Seqinfo())
if ((!is.integer(seqlengths) && !is.numeric(seqlengths)) || is.null(names(seqlengths)))
stop('seqlengths must be a named integer vector')
out = NULL;
tryCatch({
dt$seqnames = as.character(dt$seqnames)
sl = dt[, max(end), keyby = seqnames]
nms = setdiff(union(sl$seqnames, names(seqlengths)), NA)
seqlengths = structure(pmax(sl[nms, V1], seqlengths[nms], na.rm = TRUE), names = nms)
rr <- IRanges(dt$start, dt$end)
if (!'strand' %in% colnames(dt)){
dt$strand <- '*'
}
sf <- factor(dt$strand, levels=c('+', '-', '*'))
ff <- factor(dt$seqnames, levels=unique(dt$seqnames))
out <- GRanges(seqnames=ff, ranges=rr, strand=sf, seqlengths = seqlengths)
if (inherits(dt, 'data.table')){
mc <- as.data.frame(dt[, setdiff(colnames(dt),
c('start', 'end', 'seqnames', 'strand',
'width', 'seqlevels', 'seqlengths', 'element')),
with=FALSE])
} else if (inherits(dt, 'data.frame')){
mc <- as.data.frame(dt[, setdiff(colnames(dt),
c('start', 'end', 'seqnames', 'strand',
'width', 'seqlevels', 'seqlengths', 'element')),
drop = FALSE])
}
if (nrow(mc)){
mcols(out) <- mc
}
}, error = function(e) NULL)
if (is.null(out)){
warning('Warning: Coercing to GRanges via non-standard columns')
out = seg2gr(dt, seqlengths)
}
if ("width" %in% names(values(out))){
out$width = NULL
}
return(out)
}
#' @name gr.end
#' @title Get the right ends of a \code{GRanges}
#' @description
#'
#' Alternative to \code{GenomicRanges::flank} that will provide end positions *within* intervals
#'
#' @param x \code{GRanges} object to operate on
#' @param width integer Specify subranges of greater width including the start of the range. (default = 1)
#' @param force boolean Allows returned \code{GRanges} to have ranges outside of its \code{Seqinfo} bounds. (default = FALSE)
#' @param ignore.strand boolean If set to \code{FALSE}, will extend '-' strands from the other direction. (default = TRUE)
#' @param clip boolean Trims returned \code{GRanges} so that it does not extend beyond bounds of the input (default = TRUE)
#' @return GRanges object of width = \code{width} ranges representing end of each genomic range in the input.
#' @examples
#' gr.end(example_dnase, width=200, clip=TRUE)
#' @importFrom GenomeInfoDb seqlengths
#' @importFrom GenomicRanges strand seqnames values<- values
#' @author Marcin Imielinski
#' @export
gr.end = function(x, width = 1, force = FALSE, ignore.strand = TRUE, clip = TRUE)
{
if (length(x)==0){
return(x)
}
if (any(seqlengths(x)==0) | any(is.na(seqlengths(x)))){
warning('Warning: Check or fix seqlengths, some are equal 0 or NA, may lead to negative widths')
}
width = pmax(width, 1)
.grend = function(x)
{
if (force)
{
if (ignore.strand)
{
st = as.vector(end(x))-width+1
en = as.vector(end(x))
} else{
st = ifelse(as.character(strand(x)) %in% c('*', '+'),
as.vector(end(x))-width+1,
as.vector(start(x)))
en = ifelse(as.character(strand(x)) %in% c('*', '+'),
as.vector(end(x)),
as.vector(start(x))+width-1)
}
out = GRanges(seqnames(x), IRanges(st, en), seqlengths = seqlengths(x), strand = strand(x))
} else{
if (ignore.strand)
{
st = pmax(as.vector(end(x))-width+1, 1)
en = as.vector(end(x))
} else{
st = ifelse(as.character(strand(x)) %in% c('*', '+'),
pmax(as.vector(end(x))-width+1, 1),
as.vector(start(x)))
en = ifelse(as.character(strand(x)) %in% c('*', '+'),
as.vector(end(x)),
pmin(as.vector(start(x))+width-1, seqlengths(x)[as.character(seqnames(x))], na.rm = TRUE))
}
out = GRanges(seqnames(x), IRanges(st, en), seqlengths = seqlengths(x), strand = strand(x))
}
if (clip){
en = pmin(en, end(x))
st = pmax(st, start(x))
}
return(IRanges(st, en))
}
ir = tryCatch(.grend(x), error = function(e) NULL)
if (is.null(ir)){
warning("Warning: One or more ranges are out of bounds on seqlengths, fixing and rerunning")
x = gr.fix(x)
ir = .grend(x)
}
out = GRanges(seqnames(x), ir, seqlengths = seqlengths(x), strand = strand(x))
values(out) = values(x)
return(out)
}
#' @name gr.mid
#' @title Get the midpoints of \code{GRanges} ranges
#' @description
#'
#' Get the midpoints of \code{GRanges} ranges
#'
#' @param x \code{GRanges} object to operate on
#' @return \code{GRanges} of the midpoint, calculated from \code{floor(width(x)/2)}
#' @importFrom GenomicRanges start<- end<- start end
#' @examples
#' gr.mid(GRanges(1, IRanges(1000,2000), seqinfo=Seqinfo("1", 2000)))
#' @export
gr.mid = function(x)
{
start(x) = end(x) = rowMeans(cbind(start(x), end(x)))
return(x)
}
#' @name gr.rand
#' @title Generate random \code{GRanges} on genome
#' @description
#'
#' Randomly generates non-overlapping \code{GRanges} with supplied widths on supplied genome.
#' Seed can be supplied with \code{set.seed}
#'
#' @param w vector of widths (length of \code{w} determines length of output)
#' @param genome GRanges, GRangesList, or Seqinfo genome. Default is "hg19" from the \code{BSGenome} package.
#' @return \code{GRanges} with random intervals on the specifed "chromosomes"
#' @note This function is currently quite slow, needs optimization
#' @importFrom GenomeInfoDb seqinfo seqnames<-
#' @importFrom GenomicRanges gaps ranges ranges<-
#' @examples
#'
#' Sys.setenv(DEFAULT_GENOME = "http://mskilab.com/gUtils/hg19/hg19.chrom.sizes")
#'
#' ## Generate 5 non-overlapping regions of width 10 on hg19
#' gr.rand(rep(10,5), si2gr(hg_seqlengths()))
#'
#' @author Marcin Imielinski
#' @export
gr.rand = function(w, genome)
{
if (!is(genome, 'Seqinfo')){
genome = seqinfo(genome)
}
sl = seqlengths(genome);
available = si2gr(genome);
out = GRanges(rep(names(sl)[1], length(w)), IRanges(rep(1, length(w)), width = 1), seqlengths = seqlengths(genome));
for (i in 1:length(w))
{
if (i == 1){
available = si2gr(genome)
} else{
available = gaps(out[1:(i-1)])
available = available[strand(available)=='*']
}
available = available[width(available)>w[i]]
if (length(available)>0){
end(available) = end(available)-w[i]
starts = c(1, cumsum(as.numeric(width(available))+1))
rstart = ceiling(stats::runif(1)*starts[length(starts)])-starts
rind = max(which(rstart>0))
new.chr = seqnames(available[rind])
new.ir = IRanges(rstart[rind]+start(available[rind])-1, width = w[i])
## FIX: this is the slowest part
seqnames(out)[i] = new.chr;
ranges(out)[i] = new.ir;
} else{
stop('Error: Allocation failed. Supplied widths are likely too large')
}
}
return(out)
}
#' @name gr.trim
#' @title Trims pile of \code{GRanges} relative to the specified <local> coordinates of each range
#' @description
#'
#' Example: \code{GRanges} with genomic coordinates 1:1,000,000-1,001,000 can get the first 20 and last 50 bases trimmed off with
#' \code{start = 20, end = 950}.
#' if end is larger than the width of the corresponding gr, then the corresponding output will only have \code{end(gr)} as its coordinate.
#'
#' This is a role not currently provided by the standard \code{GenomicRanges} functions
#' (e.g. \code{shift}, \code{reduce}, \code{restrict}, \code{shift}, \code{resize}, \code{flank})
#'
#' @param gr \code{GRanges} to trim
#' @param starts integer Beginning of interval trimmed; Number of bases to trim off of the front\code{[1]}
#' @param ends integer End of interval trimmed
#' @examples
#'
#' ## trim the first 20 and last 50 bases
#' gr.trim(GRanges(1, IRanges(1e6, width=1000)), starts=20, ends=950)
#' ## return value: GRanges on 1:1,000,019-1,000,949
#'
#' @return GRanges with trimmed intervals relative to the specified <local> coordinates of each range
#' @export
gr.trim = function(gr, starts=1, ends=1)
{
starts = cbind(1:length(gr), starts)[, 2]
ends = cbind(1:length(gr), ends)[, 2]
ends = pmax(starts, ends);
ends = pmin(ends, width(gr));
en = start(gr) + ends - 1;
st = start(gr)+starts-1;
st = pmin(st, en);
out = GRanges(seqnames(gr), IRanges(st, en), seqlengths = seqlengths(gr), strand = strand(gr))
values(out) = values(gr)
return(out)
}
#' @name gr.sample
#' @title Randomly sample \code{GRanges} intervals within territory
#' @description
#'
#' Samples \code{k} intervals of length "len" from a pile of \code{GRanges}.
#' \itemize{
#' \item If k is a scalar then will (uniformly) select k intervals from the summed territory of \code{GRanges}
#' \item If k is a vector of length(gr) then will uniformly select k intervals from each.
#' }
#'
#' @param gr Granges defining the territory to sample from
#' @param k integer Number of ranges to sample
#' @param wid integer Length of the \code{GRanges} element to produce (default = 100)
#' @param replace boolean If TRUE, will bootstrap. If FALSE, otherwise will sample without replacement. (default = TRUE)
#' @return GRanges of max length sum(k) [if k is vector) or k*length(gr) (if k is scalar) with labels indicating the originating range.
#' @examples
#'
#' ## sample 5 \code{GRanges} of length 10 each from territory of RefSeq genes
#' gr.sample(reduce(example_genes), k=5, wid=10)
#'
#' @note This is different from \code{GenomicRanges::sample} function, which just samples from a pile of \code{GRanges}
#' @author Marcin Imielinski
#' @export
gr.sample = function(gr, k, wid = 100, replace = TRUE)
{
if (!inherits(gr, 'GRanges')){
gr = si2gr(gr)
}
if (length(k)==1){
gr$ix.og = 1:length(gr)
gr = gr[width(gr)>=wid]
if (length(gr)==0){
stop('Error: Input territory has zero regions of sufficient width')
}
gr.f = as.data.table(gr.flatten(gr.trim(gr, starts = 1, ends = width(gr)-wid), gap = 0))
terr = sum(gr.f$end-gr.f$start + 1)
st = gr.f$start;
gr.f$ix = 1:nrow(gr.f)
if (!replace){
if (!is.na(k)){
s = sort(wid*sample(floor(terr/wid), k, replace = FALSE))
} else{
s = sort(seq(1, terr, wid))
}
} else{
s = sort(terr*stats::runif(k))
}
si = rep(NA, length(s))
## concatenate input and random locations
gr.r = data.table(start = s, end = s+wid-1, ix = as.numeric(NA))
tmp = rbind(gr.f, gr.r, fill = TRUE)[order(start), ]
## match random events to their last "ix"
## find all non NA to NA transitions
## and tag all NA runs with the same number
tmp[, transition := is.na(c(NA, ix[-length(ix)])) != is.na(ix) & is.na(ix)]
tmp[, nacluster := ifelse(is.na(ix), cumsum(transition), 0)]
tmp[, clusterlength := length(start), by = nacluster]
tmp[, ix.new := ifelse(transition, c(NA, ix[-length(ix)]), ix)]
tmp[, ix.new := ix.new[1], by = nacluster]
## now lift up random ranges to their original coordinates
tmp[is.na(ix), ":="(seqnames = as.character(seqnames(gr)[ix.new]),
pos1 = start + start(gr)[ix.new]-gr.f$start[ix.new],
pos2 = end + start(gr)[ix.new]-gr.f$start[ix.new])]
tmp = tmp[is.na(ix), ]
out = GRanges(tmp$seqnames, IRanges(tmp$pos1, tmp$pos2), strand = '*', seqlengths = seqlengths(gr))
out$query.id = gr.f$ix.og[tmp$ix.new]
return(out)
} else{
gr.df = data.frame(chr = as.character(seqnames(gr)), start = start(gr), end = end(gr))
##gr.df$k = k;
gr.df$length = wid
gr.df$replace = replace
tmp = lapply(1:length(gr), function(i){
if (!gr.df$replace[i]){
if (!is.na(k[i])){
w = floor(width(gr)[i]/wid)
k[i] = min(k[i], w)
if (k[i]>0) {
s = wid*sample(w, k[i], replace = FALSE) + gr.df$start[i]
} else{
warning("Warning: trying to sample range of length > width of supplied GRanges element. Returning NULL for this element.")
return(NULL)
}
} else{
s = seq(gr.df$start[i], gr.df$end[i], wid)
}
} else{
s = (gr.df$end[i]-gr.df$start[i]-gr.df$length[i])*stats::runif(k[i])+gr.df$start[i]
}
return(data.frame(chr = gr.df$chr[i], start=s, end =s+wid-1, strand = as.character(strand(gr)[i]), query.id = i))
})
## add check that not all widths are zero
if (all(sapply(tmp, is.null))){
stop("Error: Could not sample any ranges. Check that width of input is greater than request width of output.")
}
return(gr.fix(seg2gr(do.call('rbind', tmp)), gr))
}
}
#' @name si2gr
#' @title Create \code{GRanges} from \code{Seqinfo} or \code{BSgenome}
#' @description
#'
#' Creates a genomic ranges from seqinfo object
#' i.e. a pile of ranges spanning the genome
#'
#' @param si \code{Seqinfo} object or a \code{BSgenome} genome
#' @param strip.empty boolean Flag to output non-zero GRanges only (default = FALSE)
#' @return \code{GRanges} representing the range of the input genome
#' @examples
#'
#' si2gr(hg_seqlengths())
#'
#' @export
si2gr = function(si, strip.empty = FALSE)
{
if (is(si, 'BSgenome')){
si = Seqinfo(names(seqlengths(si)), seqlengths(si))
}
## treat si as seqlengths if vector
## examples
## 'si2gr(seqlengths(si))'
##
## gr=GRanges('2:2000-3000')
## si2gr(seqlengths(gr))
##
if (is(si, 'vector')){
si = Seqinfo(seqlengths = si, seqnames = names(si))
} else if (!is(si, 'Seqinfo')){
si = seqinfo(si)
}
sl = seqlengths(si)
sn = seqnames(si);
sl[is.na(sl)] = 0;
if (strip.empty){
sn = sn[sl!=0];
sl = sl[sl!=0];
}
sigr = GRanges(sn, IRanges(rep(1, length(sl)), width = sl), seqlengths = seqlengths(si), strand = rep('+', length(sl)))
names(sigr) = sn;
return(sigr)
}
#' @name grbind
#' @title Concatenate \code{GRanges}, robust to different \code{mcols}
#' @description
#'
#' Concatenates \code{GRanges} objects, taking the union of their features if they have non-overlapping features
#'
#' @param x GRanges input GRanges
#' @param ... additional input GRanges
#' @note Does not fill in the \code{Seqinfo} for the output \code{GRanges}
#' @return Concatenated \code{GRanges}
#' grbind(example_genes, example_dnase)
#' @export
grbind = function(x, ...)
{
if (missing('x')){
grs = list(...)
} else if (class(x) != 'list'){
grs <- c(list(x), list(...))
} else{
grs <- c(x, list(...))
}
force.rrbind = FALSE
keep = sapply(grs, length)>0 & sapply(grs, function(x) inherits(x, 'GRanges'))
grs = grs[keep]
if (length(grs)==0){
return(NULL)
}
if (length(grs)==1){
return(grs[[1]])
}
vals = lapply(grs, function(x) values(x))
## DataFrame from IRanges package can hold XStringSets. Convert first
isDataFrame <- sapply(vals, class) == 'DataFrame'
if (any(isDataFrame))
{
tmp = tryCatch(lapply(vals[isDataFrame], gr2dt), error = function(e) NULL) ## sometimes works, sometimes doesn't
if (is.null(tmp)){
tmp = lapply(vals[isDataFrame, as.data.frame])
}
vals[isDataFrame] = tmp
}
### FIXING seqlengths when not exactly matching
sls = lapply(grs, seqlengths)
names(sls) = NULL
levs = unique(names(unlist(sls)))
sl.new = structure(rep(0, length(levs)), names = levs)
for (sl in sls){
sl.new[names(sl)] = pmax(sl.new[names(sl)], sl, na.rm = TRUE)
}
bare.grs = lapply(grs, function(x) gr.fix(x[,c()], sl.new))
##out = tryCatch(do.call('c', bare.grs), error = function(e) NULL) ## this is annoyingly not working
out <- dt2gr(rbindlist(lapply(bare.grs, gr2dt)), seqlengths = sl.new)
ix <- (sapply(vals, ncol)==0)
if (any(ix)){
vals[ix] = lapply(which(ix), function(x) data.frame(col.4214124124124 = rep(NA, length(grs[[x]]))))
}
if (!force.rrbind){
tmp = tryCatch(do.call('rrbind', vals), error = function(e) NULL)
} else{
tmp = NULL
}
values(out) = tmp
if (any(ix)){
out$col.4214124124124 = NULL
}
return(out)
}
#' @name grl.bind
#' @title Concatenate \code{GRangesList} objects.
#' @description
#'
#' Concatenates \code{GRangesList} objects taking the union of their \code{mcols} features if they have non-overlapping features
#'
#' @param ... GRangesList Any number of \code{GRangesList} to concatenate together
#' @return Concatenated \code{GRangesList} with NA filled in for \code{mcols} fields that are non-overlapping. Note that the
#' elements are re-named with sequential numbers
#' @examples
#'
#' ## Concatenate
#' grl.hiC2 <- grl.hiC[1:20]
#' mcols(grl.hiC2)$test = 1
#' grl.bind(grl.hiC2, grl.hiC[1:30])
#'
#' @export
#' @author Marcin Imielinski
#' @importFrom GenomicRanges mcols<- mcols split
grl.bind = function(...)
{
## TODO: make this work for when underlying grs do not have matching features
## currently will loose gr level features
grls = list(...)
## check the input
if(any(sapply(grls, function(x) !inherits(x, "GRangesList")))){
stop("Error: All inputs must inherit GRangesList")
}
## annoying acrobatics to reconcile gr and grl level features for heterogenous input gr / grls
grls.ul = lapply(grls, grl.unlist)
grls.ul.rb = do.call('grbind', grls.ul)
if (length(grls.ul.rb)==0)
{
out = GRangesList()
seqinfo(out) = seqinfo(grls[[1]])
return(out)
}
sp = base::unlist(lapply(1:length(grls), function(x) rep(x, length(grls.ul[[x]]))))
gix = base::split(grls.ul.rb$grl.ix, sp)
gjx = base::split(1:length(grls.ul.rb), sp)
grls.ul.rb$grl.iix = grls.ul.rb$grl.ix = NULL
grls.vals = lapply(grls, function(x){
if (ncol(mcols(x))>0){
return(as.data.frame(mcols(x)))
} else{
return(data.frame(dummy241421 = rep(NA, length(x))))
}
})
grls.new = mapply(function(x,y) GenomicRanges::split(grls.ul.rb[x],y), gjx, gix)
## do.call('c', grls.new) is not working for some reason (gives back list again, not GRangesList)
## have to do this instead, not ideal
if (length(grls.new) > 1) {
out = grls.new[[1]]
for (i in 2:length(grls.new)){
out = c(out, grls.new[[i]])
}
} else {
out = grls.new[[1]]
}
out.val = do.call('rrbind', grls.vals)
out.val$dummy241421 = NULL
GenomicRanges::mcols(out) <- out.val
return(out)
}
#' @name gr.chr
#' @title Prepend "chr" to \code{GRanges seqlevels}
#' @description
#'
#' Prepend "chr" to \code{GRanges seqlevels}
#'
#' @param gr \code{GRanges} object to append 'chr' to
#' @return Identical \code{GRanges}, but with 'chr' prepended to each seqlevel
#' @examples
#'
#' gr <- gr.chr(GRanges(c(1,"chrX"), IRanges(c(1,2), 1)))
#' seqnames(gr)
#'
#' @importFrom GenomeInfoDb seqlevels seqlevels<-
#' @export
gr.chr = function(gr)
{
if (any(ix <- !grepl('^chr', seqlevels(gr))))
{
sl = seqlengths(gr)
names(sl)[ix] = paste('chr', names(sl)[ix], sep = "")
dt = as.data.table(gr)
dt$seqnames = names(sl)[as.integer(seqnames(gr))]
gr = dt2gr(dt, seqlengths = sl)
}
return(gr)
}
#' @name streduce
#' @title Reduce \code{GRanges} and \code{GRangesList} to miminal footprint
#' @description
#'
#' Reduce \code{GRanges} and \code{GRangesList} to miminal footprint
#'
#' Shortcut for \code{reduce(sort(gr.stripstrand(unlist(x))))}
#'
#' @param gr \code{GRanges} or \code{GRangesList}
#' @param pad integer Expand the input data before reducing. (default = 0)
#' @param sort boolean Flag to sort the output. (default = TRUE)
#' @return \code{GRanges} object with no strand information, representing a minimal footprint
#' @importFrom GenomicRanges reduce
#' @examples
#'
#' streduce(grl.hiC, pad=10)
#' streduce(example_genes, pad=1000)
#'
#' @export
streduce = function(gr, pad = 0, sort = TRUE)
{
if (inherits(gr, 'GRangesList')){
gr = unlist(gr)
}
if (any(is.na(seqlengths(gr)))){
gr = gr.fix(gr)