-
Notifications
You must be signed in to change notification settings - Fork 97
/
methylDBClasses.R
1717 lines (1445 loc) · 57.2 KB
/
methylDBClasses.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
# regular R functions to be used in S4 functions -------------------------
#' @noRd
## set column names for methylRawDB and methylBaseDB data aquired from
## flat file database
## @param df data.frame containing methylRaw or methylBase data
## @param methylDBclass
.setMethylDBNames <- function(df,
methylDBclass=c("methylRawDB","methylBaseDB",
"methylDiffDB")){
if(nrow(df) == 0) return(df)
if(missing(methylDBclass)){
if( length(df) == 7 & unique(sapply(df,class)[5:7])=="integer"){
setnames(x = df,old = names(df),
new = c("chr","start","end","strand",
"coverage","numCs","numTs"))
} else if( length(df) == 7 & unique(sapply(df,class)[5:7])=="numeric"){
setnames(x = df,old = names(df),
new = c("chr","start","end","strand",
"pvalue","qvalue","meth.diff"))
} else if( length(df) > 7){
setnames(x = df,old = names(df)[1:4],
new = c("chr","start","end","strand"))
# get indices of coverage,numCs and numTs in the data frame
numsamples = (length(df)-4)/3
coverage.ind=seq(5,by=3,length.out=numsamples)
numCs.ind =coverage.ind+1
numTs.ind =coverage.ind+2
# change column names
setnames(df,names(df)[coverage.ind],
paste(c("coverage"),1:numsamples,sep="" ))
setnames(df,names(df)[numCs.ind],
paste(c("numCs"),1:numsamples,sep="" ))
setnames(df,names(df)[numTs.ind],
paste(c("numTs"),1:numsamples,sep="" ))
}
#return(df)
} else {
if( methylDBclass == "methylRawDB" ){
setnames(x = df,old = names(df),
new = c("chr","start","end","strand",
"coverage","numCs","numTs"))
} else if ( methylDBclass == "methylBaseDB"){
setnames(x = df,old = names(df)[1:4],
new = c("chr","start","end","strand"))
# get indices of coverage,numCs and numTs in the data frame
numsamples = (length(df)-4)/3
coverage.ind=seq(5,by=3,length.out=numsamples)
numCs.ind =coverage.ind+1
numTs.ind =coverage.ind+2
# change column names
setnames(df,names(df)[coverage.ind],
paste(c("coverage"),1:numsamples,sep="" ))
setnames(df,names(df)[numCs.ind],
paste(c("numCs"),1:numsamples,sep="" ))
setnames(df,names(df)[numTs.ind],
paste(c("numTs"),1:numsamples,sep="" ))
} else if( methylDBclass == "methylDiffDB" ){
setnames(x = df,old = names(df),
new = c("chr","start","end","strand",
"pvalue","qvalue","meth.diff"))
#return(df)
}
}
}
# end of regular functions to be used in S4 functions #--------------------
# methylRawDB -------------------------------------------------------------
valid.methylRawDB <- function(object) {
#data=getData(object,nrow=5)
check1=( (object@resolution == "base") | (object@resolution == "region") )
check2=file.exists(object@dbpath)
check3=(length([email protected]) == 1)
if (check2) check4 = (nrow(headTabix(object@dbpath)) != 0)
if (check2) check5 = ( ncol(headTabix(object@dbpath)) == 7 )
if (! check1 ){
message("resolution slot has to be either 'base' or 'region':",
"other values not allowed")
FALSE
}
else if(! check2){
cat("The DB file can not be found, check the value of 'dbpath'")
FALSE
}
else if (! check3 ){
message("object has more than one sample id:",[email protected],"\n",
"only one allowed\n")
FALSE
}
else if(! check4) {
## NOTE: this check is done to hinder further issues with empty tabix files
message("The tabix file for sample ",[email protected],
" does not contain any data.\n",
"Consider deleting file and associated index:\n",object@dbpath)
FALSE
}
else if (! check5 ){
cat("object does not have 7 columns, but has",
ncol(headTabix(object@dbpath)), "columns.",
"This cannot be a methylRawDB Tabix file.\n")
FALSE
}
else {
TRUE
}
}
#' An S4 class for storing raw methylation data as flat file database.
#'
#' This object stores the raw mehylation data that is read in through read
#' function as flat file database.The raw methylation data is basically
#' percent methylation values and read coverage values per genomic base/region.
#'
#' @section Slots:\describe{
#' \item{\code{dbpath}:}{path to flat file database }
#' \item{\code{num.records}:}{number of records (lines) in the object}
#' \item{\code{sample.id}:}{string for an identifier of the sample}
#' \item{\code{assembly}:}{string for genome assembly, ex: hg18,hg19,mm9}
#' \item{\code{context}:}{ methylation context string, ex: CpG,CpH,CHH, etc.}
#' \item{\code{resolution}:}{ resolution of methylation information, 'base' or
#' 'region'}
#' \item{\code{dbtype}:}{string for type of the flat file database, ex: tabix}
#' }
#' @section Details:
#' \code{methylRawDB} is created via \code{\link{read}} function and has the
#' same functionality as \code{\link{methylRaw}} class,
#' but the data is saved in a flat database file and therefore allocates less
#' space in memory.
#'
#' @section Subsetting:
#' In the following code snippets, \code{x} is a \code{methylRawDB}.
#' Subsetting by \code{x[i,]} will produce a new \code{methylRaw} object if
#' subsetting is done on
#' rows. Column subsetting is not directly allowed to prevent errors in the
#' downstream analysis. see ?methylKit[ .
#' \code{x[]} will return the \code{methylRawDB} object as new \code{methylRaw} object
#'
#' @section Accessors:
#' The following functions provides access to data slots of methylDiffDB:
#' - \code{\link{getData}}: get the data slot from the methylKit objects,
#' - \code{\link{getAssembly}}: get assembly of the genome,
#' - \code{\link{getContext}}: get the context of methylation
#'
#' @section Coercion:
#' \code{methylRawDB} object can be coerced to:
#' \code{\link[GenomicRanges:GRanges-class]{GRanges}} object via \code{\link{as}} function.
#' \code{\link{methylRaw}} object via \code{\link{as}} function.
#'
#' @examples
#'
#' # example of a raw methylation data contained as a text file
#' read.table(system.file("extdata", "control1.myCpG.txt", package = "methylKit"),
#' header=TRUE,nrows=5)
#'
#'
#' methylRawDB.obj <- methRead(
#' system.file("extdata", "control1.myCpG.txt", package = "methylKit"),
#' sample.id = "ctrl1", assembly = "hg18",
#' dbtype = "tabix", dbdir = "methylDB")
#'
#' # example of a methylRawDB object
#' methylRawDB.obj
#' str(methylRawDB.obj)
#'
#' library(GenomicRanges)
#'
#' #coercing methylRawDB object to GRanges object
#' my.gr=as(methylRawDB.obj,"GRanges")
#'
#' #coercing methylRawDB object to methylRaw object
#' myRaw=as(methylRawDB.obj,"methylRaw")
#'
#' # remove Database again
#' rm(methylRawDB.obj)
#' unlink("methylDB",recursive=TRUE)
#'
#' @name methylRawDB-class
#' @aliases methylRawDB
#' @docType class
#' @rdname methylRawDB-class
#' @export
setClass("methylRawDB", slots=list(dbpath="character",num.records="numeric",
sample.id = "character", assembly = "character",context="character",
resolution="character",dbtype="character"),validity=valid.methylRawDB)
# PRIVATE function:
# makes a methylRawDB object from a df
# it is called from read function or whenever this functionality is needed
makeMethylRawDB<-function(df,dbpath,dbtype,
sample.id, assembly ,context,
resolution,filename=NULL){
if(dbtype != "tabix"){
stop("unknown 'dbtype' argument provided, ",
"currently only 'tabix' is accepted.")
}
# first check for filename length
if(is.null(filename)) {
filename <- paste0(dbpath,"/",sample.id,".txt")
if( nchar( basename(filename) ) >= 245 ) {
stop(paste("Generic Filename too long,\n",
"please manually provide filename."))
}
}
# then we write the creation date ..
# plus the class of the object ..
# plus the slots ..
# as comments
num.records = nrow(df)
slotList <- list(dbtype = dbtype, sample.id = sample.id,
assembly = assembly, context = context,
resolution = resolution, num.records = num.records)
tabixHead <- makeTabixHeader(slotList)
# format and write slots to file
.formatTabixHeader(class = "methylRawDB",
tabixHead = tabixHead,
filename = filename)
# sort the data
df <- df[with(df,order(chr,start,end)),]
# then we write the data
write.table(x = df,
file = filename, quote = FALSE,
append = TRUE,col.names = FALSE,
row.names = FALSE,sep = "\t")
# and make tabix out of file
makeMethTabix(filename,rm.file = FALSE)
#filepath=paste0(dbpath,"/",sample.id,".txt")
#df <- df[with(df,order(chr,start,end)),]
#df2tabix(df,filepath)
#num.records=Rsamtools::countTabix(paste0(filepath,".bgz"))[[1]] ##
#new("methylRawDB",dbpath=paste0(filepath,".bgz"),num.records=num.records,
new("methylRawDB",dbpath=paste0(filename,".bgz"),num.records=num.records,
sample.id = sample.id, assembly = assembly,context=context,
resolution=resolution,dbtype=dbtype)
}
# PRIVATE function:
# creates a methylRawDB object from a flat file database
# it is called from read function or whenever this functionality is needed
# can load a database with or without header
readMethylRawDB<-function(dbpath,dbtype=NULL,
sample.id=NULL, assembly=NULL ,context=NULL,
resolution=NULL,skip=0){
if(!file.exists(paste0(dbpath,".tbi")))
{
Rsamtools::indexTabix(dbpath,seq=1, start=2, end=3,
skip=skip, comment="#", zeroBased=FALSE)
}
# if the tabix file includes a header generated with obj2tabix,
# it can easily be parsed into the respective object
head <- checkTabixHeader(tbxFile = dbpath,
message = paste("No Tabix Header Found,",
"trying to create methylRawDB from supplied arguments."))
if(!is.null(head) & !anyNA(head)) {
if(! any(head$class == c("methylRaw", "methylRawDB") ) ) {
stop(
paste("Tabix file does not originate from methylRaw or methylRawDB.\n",
"Please provide the correct class of data.")
)
}
if(is.null(head$num.records)) {
num.records=Rsamtools::countTabix(dbpath)[[1]]
} else num.records = head$num.records
obj <- new("methylRawDB", dbpath=normalizePath(dbpath),
num.records=num.records, sample.id = head$sample.ids,
assembly = head$assembly,context=head$context,
resolution=head$resolution,dbtype=head$dbtype)
} else {
# else we need to generate it from the supplied arguments
argList <- list(sample.id = sample.id, assembly = assembly,context=context,
resolution=resolution,dbtype=dbtype)
checkMissingArg <- sapply(argList,is.null)
if(any(checkMissingArg)) {
stop("Missing argument: ",paste(names(argList[checkMissingArg]),collapse = ", "))
}
num.records=Rsamtools::countTabix(dbpath)[[1]] ##
obj <- new("methylRawDB",dbpath=normalizePath(dbpath),num.records=num.records,
sample.id = sample.id, assembly = assembly,context=context,
resolution=resolution,dbtype=dbtype)
}
if(valid.methylRawDB(obj)) {return(obj)}
}
# methylRawListDB
valid.methylRawListDB <- function(object) {
# if all elements are methyl
if(!all(sapply(object,class)=="methylRawDB")){
message("It seems one the methylRawDB objects is invalid.")
FALSE
}
else if ( length(object) != length(object@treatment) ){
cat("The number of samples is different from the number of treatments, ","
check the length of 'treatment'")
FALSE
}
else{
TRUE
}
}
#' An S4 class for holding a list of methylRawDB objects.
#'
#' This class stores the list of \code{\link{methylRawDB}} objects.
#' Functions such as \code{lapply} can be used on this list. It extends
#' \code{\link[base]{list}} class. This object is primarily produced
#' by \code{\link{methRead}} function.
#'
#' @section Slots:\describe{
#' \item{\code{treatment}}{numeric vector denoting control
#' and test samples}
#' \item{\code{.Data}}{a list of \code{\link{methylRawDB}} objects }
#' }
#'
#' @section Constructor:\describe{
#' \item{\code{methylRawListDB(...)}}{combine multiple methylRawDB
#' objects supplied in ... into a methylRawListDB object.}
#' }
#'
#' @examples
#' file.list=list( system.file("extdata", "test1.myCpG.txt",
#' package = "methylKit"),
#' system.file("extdata", "test2.myCpG.txt",
#' package = "methylKit"),
#' system.file("extdata", "control1.myCpG.txt",
#' package = "methylKit"),
#' system.file("extdata", "control2.myCpG.txt",
#' package = "methylKit") )
#'
#' methylRawListDB.obj <- methRead(file.list,
#' sample.id = list("test1","test2","ctrl1","ctrl2"),
#' assembly = "hg18",treatment = c(1,1,0,0),
#' dbtype = "tabix",dbdir = "methylDB")
#'
#' #applying functions designed for methylRawDB on methylRawListDB object
#' lapply(methylRawListDB.obj,"getAssembly")
#'
#'
#' # remove Database again
#' rm(methylRawListDB.obj)
#' unlink("methylDB",recursive=TRUE)
#'
#' @name methylRawListDB-class
#' @aliases methylRawListDB
#' @docType class
#' @rdname methylRawListDB-class
#' @export
setClass("methylRawListDB", slots=list(treatment = "vector"),contains = "list",
validity=valid.methylRawListDB)
### constructor function
#' @param ... vector of methylRawDB files
#'
#' @param treatment vector of treatment values
#'
#' @name methylRawListDB-class
#' @aliases methylRawListDB
#' @rdname methylRawListDB-class
#' @export
methylRawListDB <- function(..., treatment) {
if (missing(treatment)) {
stop("no treatment vector given.")
}
listData <- list(...)
## check if any input is given
if (length(listData) == 0L) {
stop("no methylRawDB objects given.")
}
## flatten listData if '...' was list
if (length(listData) == 1L && is.list(listData[[1L]])) {
listData <- listData[[1L]]
}
## check if input is really of type methylRaw
if (!all(sapply(listData, is, "methylRawDB"))) {
stop("all elements in '...' must be methylRawDB objects")
}
## create new object
mrl <- new("methylRawListDB", listData, treatment = treatment)
## return if valid
if (valid.methylRawListDB(mrl)) {
return(mrl)
}
}
# methylBaseDB ------------------------------------------------------------
valid.methylBaseDB <- function(object) {
check1=( (object@resolution == "base") | (object@resolution == "region") )
check2=file.exists(object@dbpath)
check3=( length([email protected]) == length(object@treatment) )
if (check2) {
df <- headTabix(object@dbpath)
numsamples = (length(df)-4)/3
check4 = ( numsamples == length([email protected]) )
}
if (! check1 ){
cat("resolution slot has to be either 'base' or 'region':",
"other values not allowed")
FALSE
}
else if(! check2){
cat("The DB file can not be found, check the value of 'dbpath'")
FALSE
}
else if(! check3){
cat("The number of samples is different from the number of treatments,",
" check the length of 'sample.ids' & 'treatment'")
FALSE
}
else if(! check4){
cat("The number of samples is different from the number of sample names,",
" check the length of 'sample.ids' & 'treatment'")
FALSE
}
else {
TRUE
}
}
#' An S4 class for storing methylation events sampled in multiple experiments
#' as flat file database
#'
#' This class is designed to contain methylation information such as coverage,
#' number of methylated bases, etc...
#' The class creates an object that holds methylation information and genomic
#' location as flat file database.
#' The object belonging to this class is produced by \code{\link{unite}}
#' function.
#'
#' @section Slots:\describe{
#' \item{\code{dbpath}:}{path to flat file database(s) }
#' \item{\code{num.records}:}{number of records (lines)
#' in the object}
#' \item{\code{sample.ids}:}{character vector for ids of
#' samples in the object}
#' \item{\code{assembly}:}{name of the genome assembly}
#' \item{\code{context}:}{context of methylation.
#' Ex: CpG,CpH,CHH, etc}
#' \item{\code{treatment}:}{treatment vector denoting which
#' samples are test and control}
#' \item{\code{coverage.index}:}{vector denoting which
#' columns in the data correspond to
#' coverage values}
#' \item{\code{numCs.index}:}{vector denoting which columns
#' in the data correspond to
#' number of methylatedCs values}
#' \item{\code{numTs.index}:}{vector denoting which columns
#' in the data correspond to
#' number of unmethylated Cs values}
#' \item{\code{destranded}:}{ logical value.
#' If \code{TRUE} object is destranded,
#' if \code{FALSE} it is not.}
#' \item{\code{resolution}:}{ resolution of methylation
#' information,
#' allowed values: 'base' or 'region'}
#' \item{\code{dbtype}:}{string for type of the flat file
#' database, ex: tabix}
#' }
#'
#' @section Details:
#' \code{methylBaseDB} class has the same functionality as
#' \code{\link{methylBase}} class,
#' but the data is saved in a flat database file and therefore allocates
#' less space in memory.
#'
#'
#' @section Subsetting:
#' In the following code snippets, \code{x} is a \code{methylBaseDB}.
#' Subsetting by \code{x[i,]} will produce a new \code{methylBase} object
#' if subsetting is done on
#' rows. Column subsetting is not directly allowed to prevent errors in the
#' downstream analysis. see ?methylKit[ .
#'
#' @section Accessors:
#' The following functions provides access to data slots of methylDiffDB:
#' - \code{\link{getData}}: get the data slot from the methylKit objects,
#' - \code{\link{getAssembly}}: get assembly of the genome,
#' - \code{\link{getContext}}: get the context of methylation
#'
#'
#' @section Coercion:
#' \code{methylBaseDB} object can be coerced to:
#' \code{\link[GenomicRanges:GRanges-class]{GRanges}} object via \code{\link{as}} function.
#' \code{\link{methylBase}} object via \code{\link{as}} function.
#'
#' @examples
#' data(methylKit)
#' methylBaseDB.obj <- unite(methylRawList.obj,save.db=TRUE,dbdir="methylDB")
#' library(GenomicRanges)
#' my.gr=as(methylBaseDB.obj,"GRanges")
#'
#'
#' # remove Database again
#' rm(methylBaseDB.obj)
#' unlink("methylDB",recursive=TRUE)
#'
#'
#' @name methylBaseDB-class
#' @aliases methylBaseDB
#' @docType class
#' @rdname methylBaseDB-class
#' @export
setClass("methylBaseDB",slots=list(dbpath = "character",
num.records = "numeric",
sample.ids = "character",
assembly = "character",
context = "character", resolution = "character",
dbtype = "character",
treatment = "numeric", coverage.index = "numeric",
numCs.index = "numeric",
numTs.index = "numeric",
destranded = "logical"),
validity = valid.methylBaseDB)
# PRIVATE function:
# makes a methylBaseDB object from a df
# it is called from read function or whenever this functionality is needed
makeMethylBaseDB<-function(df,dbpath,dbtype,
sample.ids, assembly ,context,
resolution,treatment,coverage.index,
numCs.index,numTs.index,destranded,
suffix=NULL
)
{
# new tabix file is named by "metyhlBase"+tmpstring, works for now
# if additional suffix is passed, tmpstring is skipped
filepath <- paste0(ifelse(is.null(suffix),
yes = tempfile(pattern = "methylBase_",tmpdir = dbpath),
no = paste0(dbpath,"/methylBase",suffix)),
".txt")
# then we write the creation date ..
# plus the class of the object ..
# plus the slots ..
# as comments
num.records = nrow(df)
slotList <- list(dbtype = dbtype,
sample.ids = sample.ids,assembly = assembly,
context = context,resolution = resolution,
coverage.index = coverage.index, numCs.index = numCs.index,
numTs.index = numTs.index, treatment = treatment,
destranded = destranded, num.records = num.records)
tabixHead <- makeTabixHeader(slotList)
.formatTabixHeader(class = "methylBase",
tabixHead = tabixHead,
filename = filepath)
df <- df[with(df,order(chr,start,end)),]
df2tabix(df,filepath,append = TRUE)
new("methylBaseDB",dbpath=paste0(filepath,".bgz"),num.records=num.records,
sample.ids = sample.ids, assembly = assembly,context=context,
resolution=resolution,dbtype=dbtype,treatment=treatment,
coverage.index=coverage.index,numCs.index=numCs.index,numTs.index=numTs.index,
destranded=destranded)
}
# PRIVATE function:
# reads a methylBaseDB object from flat file database
# it is called from read function or whenever this functionality is needed
readMethylBaseDB <- function(dbpath,
dbtype = NULL,
sample.ids = NULL,
assembly = NULL ,
context = NULL,
resolution = NULL,
treatment = NULL,
destranded = NULL,
skip = 0) {
if(!file.exists(paste0(dbpath, ".tbi")))
{
Rsamtools::indexTabix(dbpath, seq=1, start=2, end=3,
skip=skip, comment="#", zeroBased=FALSE)
}
# if the tabix file includes a header generated with obj2tabix,
# it can easily be parsed into the respective object
head <- checkTabixHeader(tbxFile = dbpath,
message = paste("No Tabix Header Found,",
"\nCreating methylBaseDB using supplied arguments."))
# initiate variables that could be missing
num.records = NULL
coverage.ind = NULL
numCs.ind = NULL
numTs.ind = NULL
if(!is.null(head) & !anyNA(head)) {
if(! any(head$class == c("methylBase", "methylBaseDB") ) ) {
stop("Tabix file does not originate from methylBase or methylBaseDB.\nPlease provide the correct class of data.")
}
sample.ids = head$sample.ids
assembly = head$assembly
context = head$context
resolution = head$resolution
dbtype = head$dbtype
treatment = head$treatment
destranded = head$destranded
num.records = head$num.records
coverage.ind = head$coverage.index
numCs.ind = head$numCs.index
numTs.ind = head$numTs.index
} else {
# else we need to generate it from the supplied arguments
argList <- list(sample.ids = sample.ids, assembly = assembly,context=context,
resolution=resolution,dbtype=dbtype,treatment=treatment,
destranded=destranded)
checkMissingArg <- sapply(argList,is.null)
if(any(checkMissingArg)) {
stop("Missing argument: ",paste(names(argList[checkMissingArg]),collapse = ", "))
}
}
if(is.null(num.records)) {
num.records=Rsamtools::countTabix(dbpath)[[1]]
}
if(is.null(coverage.ind)) {
# determine postion of coverage/numCs/numTs indices
df <- headTabix(dbpath)
numsamples = (length(df) - 4) / 3
coverage.ind = seq(5, by = 3, length.out = numsamples)
numCs.ind = coverage.ind + 1
numTs.ind = coverage.ind + 2
}
obj <- new("methylBaseDB",dbpath=normalizePath(dbpath),num.records=num.records,
sample.ids = sample.ids, assembly = assembly,context=context,
resolution=resolution,dbtype=dbtype,treatment=treatment,
coverage.index=coverage.ind,numCs.index=numCs.ind,numTs.index=numTs.ind,
destranded=destranded)
if(valid.methylBaseDB(obj)) {return(obj)}
}
# methylDiffDB -------------------------------------------------------
valid.methylDiffDB <- function(object) {
check1=( (object@resolution == "base") | (object@resolution == "region") )
check2=file.exists(object@dbpath)
check3=( length([email protected]) == length(object@treatment) )
if(check1 & check2 & check3 ){
return(TRUE)
}
else if (! check1 ){
cat("resolution slot has to be either 'base' or 'region':",
"other values not allowed")
FALSE
}
else if(! check2){
cat("The DB file can not be found, check the value of 'dbpath'")
FALSE
}
else if(! check3){
cat("The number of samples is different from the number of treatments, ",
"check the length of 'treatment'")
FALSE
}
}
#' An S4 class that holds differential methylation information as flat file database
#'
#' This class is designed to hold statistics and locations for differentially
#' methylated regions/bases as flat file database.
#' \code{\link{calculateDiffMeth}} function returns an object
#' with \code{methylDiffDB} class.
#'
#' @section Slots:\describe{
#' \item{\code{dbpath}:}{path to flat file database(s) }
#' \item{\code{num.records}:}{number of records (lines) in the object}
#' \item{\code{sample.ids}}{ids/names of samples in a vector}
#' \item{\code{assembly}}{a name of genome assembly, such as :hg18,mm9, etc}
#' \item{\code{context}}{numeric vector identifying which samples are which
#' group }
#' \item{\code{treatment}}{numeric vector identifying which samples are which
#' group }
#' \item{\code{destranded}}{logical denoting if methylation inormation is
#' destranded or not}
#' \item{\code{resolution}}{string either 'base' or 'region' defining the
#' resolution of methylation information}
#' \item{\code{dbtype}:}{string for type of the flat file database, ex: tabix}
#'
#' }
#'
#' @section Details:
#' \code{methylDiffDB} class has the same functionality as
#' \code{\link{methylDiff}} class,
#' but the data is saved in a flat database file and therefore
#' allocates less space in memory.
#'
#'
#' @section Subsetting:
#' In the following code snippets, \code{x} is a \code{methylDiffDB}.
#' Subsetting by \code{x[i,]} will produce a new object if subsetting is done
#' on rows. Column subsetting is not directly allowed to prevent errors in the
#' downstream analysis. see ?methylKit[ .
#'
#' @section Coercion:
#' \code{methylDiffDB} object can be coerced to:
#' \code{\link[GenomicRanges:GRanges-class]{GRanges}} object via \code{\link{as}} function.
#' \code{\link{methylDiff}} object via \code{\link{as}} function.
#'
#' @section Accessors:
#' The following functions provides access to data slots of methylDiffDB:
#' - \code{\link{getData}}: get the data slot from the methylKit objects,
#' - \code{\link{getAssembly}}: get assembly of the genome,
#' - \code{\link{getContext}}: get the context of methylation
#'
#' @examples
#' data(methylKit)
#'
#' methylDiffDB.obj <- calculateDiffMeth(methylBase.obj,save.db=TRUE,dbdir="methylDB")
#'
#' library(GenomicRanges)
#' my.gr=as(methylDiffDB.obj,"GRanges")
#'
#' # remove Database again
#' rm(methylDiffDB.obj)
#' unlink("methylDB",recursive=TRUE)
#'
#' @name methylDiffDB-class
#' @aliases methylDiffDB
#' @rdname methylDiffDB-class
#' @export
#' @docType class
setClass("methylDiffDB",slots = list(dbpath= "character",num.records= "numeric",sample.ids = "character",
assembly = "character",context = "character",dbtype = "character",
treatment="numeric",destranded="logical",resolution="character"),validity = valid.methylDiffDB)
# PRIVATE function:
# makes a methylDiffDB object from a df
# it is called from read function or whenever this functionality is needed
makeMethylDiffDB<-function(df,dbpath,dbtype,
sample.ids, assembly ,context,
resolution,treatment,destranded,
suffix=NULL){
# new tabix file is named by "metyhlBase"+tmpstring, works for now
# if additional suffix is passed, tmpstring is skipped
filepath <- paste0(ifelse(is.null(suffix),
yes = tempfile(pattern = "methylDiff_",tmpdir = dbpath),
no = paste0(dbpath,"/methylDiff",suffix)),
".txt")
# then we write the creation date ..
# plus the class of the object ..
# plus the slots ..
# as comments
num.records = nrow(df)
slotList <- list(dbtype = dbtype,
sample.ids = sample.ids,assembly = assembly,
context = context,resolution = resolution,
treatment = treatment, destranded = destranded,
num.records = num.records)
tabixHead <- makeTabixHeader(slotList)
.formatTabixHeader(class = "methylDiff",
tabixHead = tabixHead,
filename = filepath)
df <- df[with(df,order(chr,start,end)),]
df2tabix(df,filepath,append = TRUE)
new("methylDiffDB",dbpath=paste0(filepath,".bgz"),num.records=num.records,
sample.ids = sample.ids, assembly = assembly,context=context,
resolution=resolution,dbtype=dbtype,treatment=treatment,
destranded=destranded)
}
# PRIVATE function:
# reads a methylDiffDB object from flat file database
# it is called from read function or whenever this functionality is needed
readMethylDiffDB<-function(dbpath,dbtype=NULL,
sample.ids=NULL, assembly=NULL ,context=NULL,
resolution=NULL,treatment=NULL,destranded=NULL,skip=0){
if(!file.exists(paste0(dbpath,".tbi")))
{
Rsamtools::indexTabix(dbpath,seq=1, start=2, end=3,
skip=skip, comment="#", zeroBased=FALSE)
}
# if the tabix file includes a header generated with obj2tabix,
# it can easily be parsed into the respective object
head <- checkTabixHeader(tbxFile = dbpath,
message = paste(
"No Tabix Header Found,",
"\nCreating methylDiffDB using supplied arguments."))
if(!is.null(head) & !anyNA(head)) {
if(! any(head$class == c("methylDiff", "methylDiffDB") ) ) {
stop("Tabix file does not originate from methylDiff or methylDiffDB.\nPlease provide the correct class of data.")
}
if(is.null(head$num.records)) {
num.records=Rsamtools::countTabix(dbpath)[[1]]
} else num.records = head$num.records
obj <- new("methylDiffDB",dbpath=normalizePath(dbpath),num.records=num.records,
sample.ids = head$sample.ids, assembly = head$assembly,context=head$context,
resolution=head$resolution,dbtype=head$dbtype,treatment=head$treatment,
destranded=head$destranded)
} else {
# else we need to generate it from the supplied arguments
argList <- list(sample.ids = sample.ids, assembly = assembly,context=context,
resolution=resolution,dbtype=dbtype,treatment=treatment,
destranded=destranded)
checkMissingArg <- sapply(argList,is.null)
if(any(checkMissingArg)) {
stop("Missing argument: ",paste(names(argList[checkMissingArg]),collapse = ", "))
}
num.records=Rsamtools::countTabix(dbpath)[[1]] ##
obj <- new("methylDiffDB",dbpath=normalizePath(dbpath),num.records=num.records,
sample.ids = sample.ids, assembly = assembly,context=context,
resolution=resolution,dbtype=dbtype,treatment=treatment,
destranded=destranded)
}
if(valid.methylDiffDB(obj)) {return(obj)}
}
# coercion functions ------------------------------------------------------
setAs("methylRawDB", "GRanges", function(from)
{
gr <- headTabix(tbxFile = from@dbpath, nrow = [email protected], return.type = "GRanges")
names(GenomicRanges::mcols(gr)) <- c("coverage","numCs","numTs")
return(gr)
})
setAs("methylBaseDB", "GRanges", function(from)
{
from=getData(from)
GRanges(seqnames=as.character(from$chr),ranges=IRanges(start=from$start, end=from$end),
strand=from$strand,
data.frame(from[,5:ncol(from)])
)
# gr <- headTabix(tbxFile = from@dbpath, nrow = [email protected], return.type = "GRanges")
# names(GenomicRanges::mcols(gr)) <- c("coverage","numCs","numTs")
# return(gr)
})
setAs("methylDiffDB", "GRanges", function(from)
{
gr <- headTabix(tbxFile = from@dbpath, nrow = [email protected],
return.type = "GRanges")
names(GenomicRanges::mcols(gr)) <- c("pvalue","qvalue","meth.diff")
return(gr)
})
## coerce methylDB to methyl-obj
setAs("methylRawDB","methylRaw", function(from)
{
return(from[])
})
setAs("methylRawListDB","methylRawList", function(from)
{
outList = lapply(from,as,"methylRaw")
new("methylRawList", outList,treatment=from@treatment)
})
setAs("methylBaseDB","methylBase", function(from)
{
return(from[])
})
setAs("methylDiffDB","methylDiff", function(from)
{
return(from[])
})
#' load tabix file with header to methylDB
#'
#' The function reads the header from a given tabix file and
#' loads it into corresponding methylDB object.
#'
#' @param dbpath path to a tabix file with header
#'
#' @examples
#' \dontrun{
#' data(methylKit)
#'
#' baseDB.obj <- makeMethylDB(methylBase.obj,"my/path")
#' mydbpath <- getDBPath(baseDB.obj)
#' rm(baseDB.obj)
#' readMethylDB(mydbpath)
#'
#' }
#'
#' @return an \code{\link{methylBaseDB}},\code{\link{methylRawDB}},
#' \code{\link{methylRawListDB}} or an \code{\link{methylDiffDB}} object
#' @export
#' @docType methods
#' @rdname readMethylDB-methods
readMethylDB <- function(dbpath) {
if(!file.exists(dbpath))
{
stop("Tabix File does not exist:", dbpath,"\nPlease provide a path to a valid tabix file.")
}
if(!file.exists(paste0(dbpath,".tbi")))
{
Rsamtools::indexTabix(dbpath,seq=1, start=2, end=3,
skip=0, comment="#", zeroBased=FALSE)
}
# if the tabix file includes a header generated with obj2tabix,