/
Methods.R
2124 lines (2067 loc) · 85.3 KB
/
Methods.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
##***********************************************************************
##
## Methods for EnsDb classes
##
##***********************************************************************
setMethod("show", "EnsDb", function(object) {
if (is.null(object@ensdb)) {
cat("Dash it! Got an empty thing!\n")
} else {
info <- dbGetQuery(object@ensdb, "select * from metadata")
cat("EnsDb for Ensembl:\n")
if (inherits(object@ensdb, "SQLiteConnection"))
cat(paste0("|Backend: SQLite\n"))
if (inherits(object@ensdb, "MySQLConnection"))
cat(paste0("|Backend: MySQL\n"))
for (i in 1:nrow(info)) {
cat(paste0("|", info[ i, "name" ], ": ",
info[ i, "value" ], "\n"))
}
## gene and transcript info.
cat(paste0("| No. of genes: ",
dbGetQuery(object@ensdb,
"select count(distinct gene_id) from gene")[1, 1],
".\n"))
cat(paste0("| No. of transcripts: ",
dbGetQuery(object@ensdb,
"select count(distinct tx_id) from tx")[1, 1],
".\n"))
if (hasProteinData(object))
cat("|Protein data available.\n")
flts <- .activeFilter(object)
if (is(flts, "AnnotationFilter") | is(flts, "AnnotationFilterList")) {
cat("|Active filter(s):\n")
show(flts)
}
}
})
############################################################
## organism
setMethod("organism", "EnsDb", function(object){
Species <- .getMetaDataValue(object@ensdb, "Organism")
## reformat the e.g. homo_sapiens string into Homo sapiens
#
Species <- gsub(Species, pattern="_", replacement=" ", fixed=TRUE)
Species <- .organismName(Species)
return(Species)
})
############################################################
## metadata
setMethod("metadata", "EnsDb", function(x, ...){
Res <- dbGetQuery(dbconn(x), "select * from metadata")
return(Res)
})
############################################################
## Validation
##
validateEnsDb <- function(object){
## check if the database contains all required tables...
if(!is.null(object@ensdb)){
msg <- validMsg(NULL, NULL)
OK <- dbHasRequiredTables(object@ensdb)
if (is.character(OK))
msg <- validMsg(msg, OK)
OK <- dbHasValidTables(object@ensdb)
if (is.character(OK))
msg <- validMsg(msg, OK)
if (hasProteinData(object)) {
OK <- dbHasRequiredTables(
object@ensdb,
tables = .ensdb_protein_tables(dbSchemaVersion(dbconn(object))))
if (is.character(OK))
msg <- validMsg(msg, OK)
OK <- dbHasValidTables(
object@ensdb,
tables = .ensdb_protein_tables(dbSchemaVersion(dbconn(object))))
if (is.character(OK))
msg <- validMsg(msg, OK)
cdsTx <- dbGetQuery(dbconn(object),
"select tx_id, tx_cds_seq_start from tx");
if (is.character(cdsTx$tx_cds_seq_start)) {
suppressWarnings(
cdsTx[, "tx_cds_seq_start"] <- as.numeric(cdsTx$tx_cds_seq_start)
)
}
cdsTx <- cdsTx[!is.na(cdsTx$tx_cds_seq_start), "tx_id"]
protTx <- dbGetQuery(dbconn(object),
"select distinct tx_id from protein")$tx_id
if (!all(cdsTx %in% protTx))
msg <- validMsg(msg, paste0("Not all transcripts with a CDS ",
"are assigned to a protein ID!"))
if (!all(protTx %in% cdsTx))
msg <- validMsg(msg, paste0("Not all proteins are assigned to ",
"a transcript with a CDS!"))
}
if (is.null(msg)) TRUE
else msg
}
return(TRUE)
}
setValidity("EnsDb", validateEnsDb)
setMethod("initialize", "EnsDb", function(.Object,...){
OK <- validateEnsDb(.Object)
if(class(OK)=="character"){
stop(OK)
}
callNextMethod(.Object, ...)
})
############################################################
## dbconn
setMethod("dbconn", "EnsDb", function(x){
return(x@ensdb)
})
############################################################
## ensemblVersion
##
## returns the ensembl version of the package.
setMethod("ensemblVersion", "EnsDb", function(x){
eVersion <- getMetadataValue(x, "ensembl_version")
return(eVersion)
})
############################################################
## getMetadataValue
##
## returns the metadata value for the specified name/key
setMethod("getMetadataValue", "EnsDb", function(x, name){
if(missing(name))
stop("Argument name has to be specified!")
return(metadata(x)[metadata(x)$name==name, "value"])
})
############################################################
## seqinfo
setMethod("seqinfo", "EnsDb", function(x){
Chrs <- .fix_is_circular(dbGetQuery(dbconn(x), "select * from chromosome"))
Chr.build <- .getMetaDataValue(dbconn(x), "genome_build")
Chrs$seq_name <- formatSeqnamesFromQuery(x, Chrs$seq_name)
SI <- Seqinfo(seqnames = Chrs$seq_name,
seqlengths = Chrs$seq_length,
isCircular = Chrs$is_circular == 1,
genome = Chr.build)
SI
})
############################################################
## seqlevels
setMethod("seqlevels", "EnsDb", function(x){
Chrs <- dbGetQuery(dbconn(x), "select distinct seq_name from chromosome")
Chrs <- formatSeqnamesFromQuery(x, Chrs$seq_name)
return(Chrs)
})
############################################################
## getGenomeFaFile
##
## queries the dna.toplevel.fa file from AnnotationHub matching the current
## Ensembl version
## Update: if we can't find a FaFile matching the Ensembl version we suggest
## ones that might match.
setMethod("getGenomeFaFile", "EnsDb", function(x, pattern = "dna.toplevel.fa") {
if (!requireNamespace("AnnotationHub", quietly = TRUE)) {
stop("The 'AnnotationHub' package is needed for this function to ",
"work. Please install it.", call. = FALSE)
}
ah <- AnnotationHub::AnnotationHub()
## Reduce the AnnotationHub to species, provider and genome version.
ah <- .reduceAH(ah, organism = organism(x), dataprovider = "Ensembl",
genome = unique(genome(x)))
if(length(ah) == 0)
stop("Can not find any ressources in AnnotationHub for organism: ",
organism(x), ", data provider: Ensembl and genome version: ",
unique(genome(x)), "!")
## Reduce to all Fasta files with toplevel or primary_assembly.
ah <- ah[ah$rdataclass == "FaFile", ]
if(length(ah) == 0)
stop("No FaFiles available in AnnotationHub for organism: ",
organism(x), ", data provider: Ensembl and genome version: ",
unique(genome(x)), "! You might also try to use the",
" 'getGenomeTwoBitFile' method instead.")
## Reduce to dna.toplevel or dna.primary_assembly.
idx <- c(grep(ah$title, pattern = "dna.toplevel"),
grep(ah$title, pattern = "dna.primary_assembly"))
if(length(idx) == 0)
stop("No genome assembly fasta file available for organism: ",
organism(x), ", data provider: Ensembl and genome version: ",
unique(genome(x)), "!")
ah <- ah[idx, ]
## Get the Ensembl version from the source url.
ensVers <- .ensVersionFromSourceUrl(ah$sourceurl)
if(any(ensVers == ensemblVersion(x))){
## Got it.
itIs <- which(ensVers == ensemblVersion(x))
}else{
## Get the "closest" one.
diffs <- abs(ensVers - as.numeric(ensemblVersion(x)))
itIs <- which(diffs == min(diffs))[1]
message("Returning the Fasta file for Ensembl version ", ensVers[itIs],
" since no file for Ensembl version ", ensemblVersion(x),
" is available.")
}
## Getting the ressource.
Dna <- ah[[names(ah)[itIs]]]
## generate an index if none is available
if(is.na(index(Dna))){
indexFa(Dna)
Dna <- FaFile(path(Dna))
}
return(Dna)
})
## Just restricting the Annotation Hub to entries matching the species and the
## genome; not yet the Ensembl version.
.reduceAH <- function(ah, organism = NULL, dataprovider = "Ensembl",
genome = NULL){
if(!is.null(dataprovider))
ah <- ah[ah$dataprovider == dataprovider, ]
if(!is.null(organism))
ah <- ah[ah$species == organism, ]
if(!is.null(genome))
ah <- ah[ah$genome == genome, ]
return(ah)
}
.ensVersionFromSourceUrl <- function(url){
url <- strsplit(url, split="/", fixed=TRUE)
ensVers <- unlist(lapply(url, function(z){
idx <- grep(z, pattern="^release")
if(length(idx) == 0)
return(-1)
return(as.numeric(unlist(strsplit(z[idx], split="-"))[2]))
}))
return(ensVers)
}
############################################################
## getGenomeTwoBitFile
##
## Search and retrieve a genomic DNA resource through a TwoBitFile
## from AnnotationHub.
setMethod("getGenomeTwoBitFile", "EnsDb", function(x){
ah <- AnnotationHub::AnnotationHub()
## Reduce the AnnotationHub to species, provider and genome version.
ah <- .reduceAH(ah, organism = organism(x), dataprovider = "Ensembl",
genome = unique(genome(x)))
if(length(ah) == 0)
stop("Can not find any ressources in AnnotationHub for organism: ",
organism(x), ", data provider: Ensembl and genome version: ",
unique(genome(x)), "!")
## Reduce to all Fasta files with toplevel or primary_assembly.
ah <- ah[ah$rdataclass == "TwoBitFile", ]
if(length(ah) == 0)
stop("No TwoBitFile available in AnnotationHub for organism: ",
organism(x), ", data provider: Ensembl and genome version: ",
unique(genome(x)), "!")
## Reduce to dna.toplevel or dna.primary_assembly.
idx <- c(grep(ah$title, pattern = "dna.toplevel"),
grep(ah$title, pattern = "dna.primary_assembly"))
if(length(idx) == 0)
stop("No genome assembly fasta file available for organism: ",
organism(x), ", data provider: Ensembl and genome version: ",
unique(genome(x)), "!")
ah <- ah[idx, ]
## Get the Ensembl version from the source url.
ensVers <- .ensVersionFromSourceUrl(ah$sourceurl)
if(any(ensVers == ensemblVersion(x))) {
## Got it.
itIs <- which(ensVers == ensemblVersion(x))
} else {
## Get the "closest" one.
diffs <- abs(ensVers - as.numeric(ensemblVersion(x)))
itIs <- which(diffs == min(diffs))[1]
message("Returning the TwoBit file for Ensembl version ", ensVers[itIs],
" since no file for Ensembl version ", ensemblVersion(x),
" is available.")
}
## Getting the ressource.
Dna <- ah[[names(ah)[itIs]]]
return(Dna)
})
############################################################
## listTables
setMethod("listTables", "EnsDb", function(x, ...){
if(length(x@tables)==0){
tables <- dbListTables(dbconn(x))
## read the columns for these tables.
Tables <- vector(length=length(tables), "list")
for(i in 1:length(Tables)){
Tables[[ i ]] <- colnames(dbGetQuery(dbconn(x),
paste0("select * from ",
tables[ i ],
" limit 1")))
}
names(Tables) <- tables
x@tables <- Tables
}
Tab <- x@tables
Tab <- Tab[tablesByDegree(x, tab=names(Tab))]
## Manually add tx_name as a "virtual" column; getWhat will insert the tx_id into that.
Tab$tx <- unique(c(Tab$tx, "tx_name"))
## Manually add the symbol as a "virtual" column.
Tab$gene <- unique(c(Tab$gene, "symbol"))
return(Tab)
})
############################################################
## listColumns
setMethod("listColumns", "EnsDb", function(x,
table,
skip.keys = TRUE,
metadata = FALSE, ...){
if (length(x@tables) == 0) {
tables <- dbListTables(dbconn(x))
## read the columns for these tables.
Tables <- vector(length = length(tables), "list")
for (i in 1:length(Tables)){
Tables[[i]] <- colnames(dbGetQuery(dbconn(x),
paste0("select * from ",
tables[i],
" limit 1")))
}
names(Tables) <- tables
x@tables <- Tables
}
Tab <- x@tables
if (!metadata)
Tab <- Tab[names(Tab) != "metadata"]
## Manually add tx_name as a "virtual" column; getWhat will insert
## the tx_id into that.
Tab$tx <- unique(c(Tab$tx, "tx_name"))
## Manually add the symbol as a "virtual" column.
Tab$gene <- unique(c(Tab$gene, "symbol"))
if (!missing(table))
columns <- unlist(Tab[names(Tab) %in% table], use.names = FALSE)
else
columns <- unlist(Tab, use.names=FALSE)
if (skip.keys) {
## remove everything that has a _pk or _fk...
idx <- grep(columns, pattern = "_fk$")
if(length(idx) > 0)
columns <- columns[ -idx ]
idx <- grep(columns, pattern="_pk$")
if(length(idx) > 0)
columns <- columns[ -idx ]
}
unique(columns)
})
############################################################
## listGenebiotypes
setMethod("listGenebiotypes", "EnsDb", function(x, ...){
return(dbGetQuery(dbconn(x), "select distinct gene_biotype from gene")[,1])
})
############################################################
## listTxbiotypes
setMethod("listTxbiotypes", "EnsDb", function(x, ...){
return(dbGetQuery(dbconn(x), "select distinct tx_biotype from tx")[,1])
})
############################################################
## cleanColumns
##
## checks columns and removes all that are not present in database tables
## the method checks internally whether the columns are in the full form,
## i.e. gene.gene_id (<table name>.<column name>)
setMethod("cleanColumns", "EnsDb", function(x, columns, ...){
if(missing(columns))
stop("No columns submitted!")
## vote of the majority
full.name <- length(grep(columns, pattern=".", fixed=TRUE)) >
floor(length(columns) / 2)
if (full.name) {
suppressWarnings(
full.columns <- unlist(prefixColumns(x,
unlist(listTables(x)),
clean = FALSE),
use.names=TRUE)
)
bm <- columns %in% full.columns
removed <- columns[ !bm ]
} else {
dbtabs <- names(listTables(x))
dbtabs <- dbtabs[dbtabs != "metadata"]
bm <- columns %in% unlist(listTables(x)[dbtabs])
removed <- columns[!bm]
}
if(length(removed) > 0){
if (length(removed) == 1)
warning("Column ", paste(sQuote(removed), collapse=", "),
" is not present in the database and has been removed")
else
warning("Columns ", paste(sQuote(removed), collapse=", "),
" are not present in the database and have been removed")
}
return(columns[bm])
})
############################################################
## tablesForColumns
##
## returns the tables for the specified columns.
setMethod("tablesForColumns", "EnsDb", function(x, columns, ...){
if(missing(columns))
stop("No columns submitted!")
bm <- unlist(lapply(listTables(x), function(z){
return(any(z %in% columns))
}))
if(!any(bm))
return(NULL)
Tables <- names(bm)[ bm ]
Tables <- Tables[ !(Tables %in% c("metadata")) ]
return(Tables)
})
############################################################
## tablesByDegree
##
## returns the table names ordered by degree, i.e. edges to other tables
setMethod("tablesByDegree", "EnsDb", function(x,
tab=names(listTables(x)),
...){
Table.order <- c(gene = 1, tx = 2, tx2exon = 3, exon = 4, chromosome = 5,
protein = 6, uniprot = 7, protein_domain = 8,
entrezgene = 9,
metadata = 99)
Tab <- tab[ order(Table.order[ tab ]) ]
return(Tab)
})
############################################################
## hasProteinData
##
## Simply check if the database has required tables protein, uniprot
## and protein_domain.
#' @title Determine whether protein data is available in the database
#'
#' @aliases hasProteinData
#'
#' @description Determines whether the \code{\linkS4class{EnsDb}}
#' provides protein annotation data.
#'
#' @param x The \code{\linkS4class{EnsDb}} object.
#'
#' @return A logical of length one, \code{TRUE} if protein annotations are
#' available and \code{FALSE} otherwise.
#'
#' @author Johannes Rainer
#'
#' @seealso \code{\link{listTables}}
#'
#' @examples
#' library(EnsDb.Hsapiens.v86)
#' ## Does this database/package have protein annotations?
#' hasProteinData(EnsDb.Hsapiens.v86)
setMethod("hasProteinData", "EnsDb", function(x) {
tabs <- listTables(x)
return(all(c("protein", "uniprot", "protein_domain") %in%
names(tabs)))
})
############################################################
## genes
##
## get genes from the database.
setMethod("genes", "EnsDb", function(x,
columns = c(listColumns(x, "gene"),
"entrezid"),
filter = AnnotationFilterList(),
order.by = "",
order.type = "asc",
return.type = "GRanges"){
return.type <- match.arg(return.type, c("data.frame", "GRanges", "DataFrame"))
columns <- cleanColumns(x, unique(c(columns, "gene_id")))
## if return.type is GRanges we require columns: seq_name, gene_seq_start
## and gene_seq_end and seq_strand
if(return.type=="GRanges"){
columns <- unique(c(columns, c("gene_seq_start", "gene_seq_end",
"seq_name", "seq_strand")))
}
filter <- .processFilterParam(filter, x)
filter <- setFeatureInGRangesFilter(filter, "gene")
## Eventually add columns for the filters:
columns <- addFilterColumns(columns, filter, x)
retColumns <- columns
## If we don't have an order.by define one.
if(all(order.by == "")){
order.by <- NULL
if (any(columns == "seq_name"))
order.by <- c(order.by, "seq_name")
if( any(columns == "gene_seq_start"))
order.by <- c(order.by, "gene_seq_start")
if(is.null(order.by))
order.by <- ""
}
Res <- getWhat(x, columns=columns, filter=filter,
order.by=order.by, order.type=order.type,
startWith = "gene", join = "suggested")
## issue #48: collapse entrezid column if dbschema 2.0 is used.
if (as.numeric(dbSchemaVersion(x)) > 1 & any(columns == "entrezid"))
Res <- .collapseEntrezidInTable(Res, by = "gene_id")
if (return.type=="data.frame" | return.type=="DataFrame") {
notThere <- !(retColumns %in% colnames(Res))
if(any(notThere))
warning("Columns ",
paste0("'", retColumns[notThere], "'", collapse=", "),
" not found in the database!")
retColumns <- retColumns[!notThere]
Res <- Res[, retColumns, drop = FALSE]
if(return.type=="DataFrame")
Res <- DataFrame(Res)
return(Res)
}
if (return.type=="GRanges") {
metacols <- columns[ !(columns %in% c("seq_name",
"seq_strand",
"gene_seq_start",
"gene_seq_end")) ]
suppressWarnings(
SI <- seqinfo(x)
)
SI <- SI[as.character(unique(Res$seq_name))]
GR <- GRanges(seqnames=Rle(Res$seq_name),
ranges=IRanges(start=Res$gene_seq_start, end=Res$gene_seq_end),
strand=Rle(Res$seq_strand),
seqinfo=SI[as.character(unique(Res$seq_name))],
Res[ , metacols, drop=FALSE ]
)
names(GR) <- Res$gene_id
return(GR)
}
})
############################################################
## transcripts:
##
## get transcripts from the database.
setMethod("transcripts", "EnsDb", function(x, columns = listColumns(x, "tx"),
filter = AnnotationFilterList(),
order.by = "", order.type = "asc",
return.type = "GRanges"){
return.type <- match.arg(return.type, c("data.frame", "GRanges", "DataFrame"))
columns <- cleanColumns(x, unique(c(columns, "tx_id")))
## if return.type is GRanges we require columns: seq_name, gene_seq_start
## and gene_seq_end and seq_strand
if(return.type=="GRanges"){
columns <- unique(c(columns, c("tx_seq_start",
"tx_seq_end",
"seq_name",
"seq_strand")))
}
filter <- .processFilterParam(filter, x)
filter <- setFeatureInGRangesFilter(filter, "tx")
## Eventually add columns for the filters:
columns <- addFilterColumns(columns, filter, x)
retColumns <- columns
## If we don't have an order.by define one.
if(all(order.by == "")){
order.by <- NULL
if(any(columns == "seq_name"))
order.by <- c(order.by, "seq_name")
if(any(columns == "tx_seq_start"))
order.by <- c(order.by, "tx_seq_start")
if(is.null(order.by))
order.by <- ""
}
Res <- getWhat(x, columns=columns, filter = filter,
order.by=order.by, order.type=order.type,
startWith = "tx", join = "suggested")
## issue #48: collapse entrezid column if dbschema 2.0 is used.
if (as.numeric(dbSchemaVersion(x)) > 1 & any(columns == "entrezid"))
Res <- .collapseEntrezidInTable(Res, by = "tx_id")
if(return.type=="data.frame" | return.type=="DataFrame"){
notThere <- !(retColumns %in% colnames(Res))
if(any(notThere))
warning("Columns ", paste0("'", retColumns[notThere], "'",
collapse=", "),
" not found in the database!")
retColumns <- retColumns[!notThere]
Res <- Res[, retColumns, drop = FALSE]
if(return.type=="DataFrame")
Res <- DataFrame(Res)
return(Res)
}
if(return.type=="GRanges"){
notThere <- !(columns %in% colnames(Res))
if(any(notThere))
warning(paste0("Columns ", paste(columns[notThere], collapse=", "),
" not present in the result data.frame!"))
columns <- columns[!notThere]
metacols <- columns[ !(columns %in% c("seq_name",
"seq_strand",
"tx_seq_start",
"tx_seq_end")) ]
suppressWarnings(
SI <- seqinfo(x)
)
SI <- SI[as.character(unique(Res$seq_name))]
GR <- GRanges(seqnames=Rle(Res$seq_name),
ranges=IRanges(start=Res$tx_seq_start, end=Res$tx_seq_end),
strand=Rle(Res$seq_strand),
seqinfo=SI[as.character(unique(Res$seq_name))],
Res[ , metacols, drop=FALSE ]
)
names(GR) <- Res$tx_id
return(GR)
}
})
############################################################
## promoters:
##
setMethod("promoters", "EnsDb",
function(x, upstream=2000, downstream=200, ...)
{
gr <- transcripts(x, ...)
trim(suppressWarnings(promoters(gr,
upstream=upstream,
downstream=downstream)))
}
)
############################################################
## exons
##
## get exons from the database.
setMethod("exons", "EnsDb", function(x, columns = listColumns(x, "exon"),
filter = AnnotationFilterList(),
order.by = "", order.type = "asc",
return.type = "GRanges"){
return.type <- match.arg(return.type, c("data.frame", "GRanges", "DataFrame"))
if(!any(columns %in% c(listColumns(x, "exon"), "exon_idx"))){
## have to have at least one column from the gene table...
columns <- c(columns, "exon_id")
}
columns <- cleanColumns(x, unique(c(columns, "exon_id")))
## if return.type is GRanges we require columns: seq_name, gene_seq_start
## and gene_seq_end and seq_strand
if(return.type=="GRanges"){
columns <- unique(c(columns, c("exon_seq_start",
"exon_seq_end",
"seq_name",
"seq_strand")))
}
filter <- .processFilterParam(filter, x)
filter <- setFeatureInGRangesFilter(filter, "exon")
## Eventually add columns for the filters:
columns <- addFilterColumns(columns, filter, x)
retColumns <- columns
## If we don't have an order.by define one.
if (order.by == "") {
order.by <- NULL
if (any(columns == "seq_name"))
order.by <- c(order.by, "seq_name")
if (any(columns == "exon_seq_start"))
order.by <- c(order.by, "exon_seq_start")
if(is.null(order.by))
order.by <- ""
}
Res <- getWhat(x, columns=columns, filter=filter,
order.by=order.by, order.type=order.type,
startWith = "exon", join = "suggested")
## issue #48: collapse entrezid column if dbschema 2.0 is used.
if (as.numeric(dbSchemaVersion(x)) > 1 & any(columns == "entrezid"))
Res <- .collapseEntrezidInTable(Res, by = "exon_id")
if(return.type=="data.frame" | return.type=="DataFrame"){
notThere <- !(retColumns %in% colnames(Res))
if(any(notThere))
warning("Columns ", paste0("'", retColumns[notThere], "'",
collapse=", "),
" not found in the database!")
retColumns <- retColumns[!notThere]
Res <- Res[, retColumns, drop = FALSE]
if(return.type=="DataFrame")
Res <- DataFrame(Res)
return(Res)
}
if(return.type=="GRanges"){
notThere <- !(columns %in% colnames(Res))
if(any(notThere))
warning(paste0("Columns ", paste(columns[notThere], collapse=", "),
" not present in the result data.frame!"))
columns <- columns[!notThere]
metacols <- columns[ !(columns %in% c("seq_name",
"seq_strand",
"exon_seq_start",
"exon_seq_end")) ]
suppressWarnings(
SI <- seqinfo(x)
)
SI <- SI[as.character(unique(Res$seq_name))]
GR <- GRanges(seqnames=Rle(Res$seq_name),
ranges=IRanges(start=Res$exon_seq_start, end=Res$exon_seq_end),
strand=Rle(Res$seq_strand),
seqinfo=SI[as.character(unique(Res$seq_name))],
Res[ , metacols, drop=FALSE ]
)
names(GR) <- Res$exon_id
return(GR)
}
})
############################################################
## exonsBy
##
## should return a GRangesList
setMethod("exonsBy", "EnsDb", function(x, by = c("tx", "gene"),
columns = listColumns(x, "exon"),
filter = AnnotationFilterList(),
use.names = FALSE) {
by <- match.arg(by, c("tx", "gene"))
bySuff <- "_id"
if (use.names) {
if (by == "tx") {
use.names <- FALSE
warning("Argument use.names ignored as no transcript names are available.")
} else {
columns <- unique(c(columns, "gene_name"))
bySuff <- "_name"
}
}
filter <- .processFilterParam(filter, x)
## We're applying eventual GRangesFilter to either gene or tx.
filter <- setFeatureInGRangesFilter(filter, by)
## Eventually add columns for the filters:
columns <- cleanColumns(x, unique(c(columns, "exon_id")))
columns <- addFilterColumns(columns, filter, x)
## Quick fix; rename any exon_rank to exon_idx.
columns[columns == "exon_rank"] <- "exon_idx"
## The minimum columns we need, in addition to "columns"
min.columns <- c(paste0(by, "_id"), "seq_name","exon_seq_start",
"exon_seq_end", "exon_id", "seq_strand")
by.id.full <- unlist(prefixColumns(x, columns = paste0(by, "_id"),
clean = FALSE),
use.names = FALSE)
if (by == "gene") {
## tx columns have to be removed, since the same exon can be part of
## more than one tx
txcolumns <- c(listColumns(x, "tx"), "exon_idx")
txcolumns <- txcolumns[txcolumns != "gene_id"]
torem <- columns %in% txcolumns
if (any(torem))
warning("Columns ",
paste(columns[ torem ], collapse = ","),
" have been removed as they are not allowed if exons",
" are fetched by gene.")
columns <- columns[!torem]
} else {
min.columns <- unique(c(min.columns, "exon_idx"))
columns <- c(columns, "exon_idx")
}
## define the minimal columns that we need...
ret_cols <- unique(columns) ## before adding the "min.columns"
columns <- unique(c(columns, min.columns))
## get the seqinfo:
suppressWarnings(
SI <- seqinfo(x)
)
## Resolve ordering problems.
orderR <- orderResultsInR(x)
if (orderR) {
order.by <- ""
} else {
if (by == "gene") {
order.by <- paste0("gene.gene_id, ",
"case when seq_strand = 1 then exon_seq_start",
" when seq_strand = -1 then (exon_seq_end * -1)",
" end")
} else {
## Funny thing is the query takes longer if I use tx2exon.tx_id!
order.by <- "tx.gene_id, tx.tx_id, tx2exon.exon_idx"
}
}
Res <- getWhat(x, columns = columns, filter = filter,
order.by = order.by, skip.order.check = TRUE,
startWith = by, join = "suggested")
## issue #48: collapse entrezid column if dbschema 2.0 is used.
if (as.numeric(dbSchemaVersion(x)) > 1 & any(columns == "entrezid"))
Res <- .collapseEntrezidInTable(Res, by = "exon_id")
## Now, order in R, if not already done in SQL.
if (orderR) {
if (by == "gene") {
startend <- (Res$seq_strand == 1) * Res$exon_seq_start +
(Res$seq_strand == -1) * (Res$exon_seq_end * -1)
Res <- Res[order(Res$gene_id, startend,
method = "radix"), ]
} else {
Res <- Res[order(Res$tx_id, Res$exon_idx,
method = "radix"), ]
}
}
SI <- SI[as.character(unique(Res$seq_name))]
## replace exon_idx with exon_rank
colnames(Res)[colnames(Res) == "exon_idx"] <- "exon_rank"
columns[columns == "exon_idx"] <- "exon_rank"
ret_cols[ret_cols == "exon_idx"] <- "exon_rank"
notThere <- !(ret_cols %in% colnames(Res))
if (any(notThere))
warning("Columns ", paste0("'", ret_cols[notThere], "'",
collapse = ", "),
" not found in the database!")
ret_cols <- ret_cols[!notThere]
columns.metadata <- ret_cols[!(ret_cols %in% c("seq_name", "seq_strand",
"exon_seq_start",
"exon_seq_end"))]
columns.metadata <- match(columns.metadata, colnames(Res))
GR <- GRanges(seqnames = Rle(Res$seq_name),
strand = Rle(Res$seq_strand),
ranges = IRanges(start = Res$exon_seq_start,
end = Res$exon_seq_end),
seqinfo = SI,
Res[, columns.metadata, drop=FALSE]
)
split(GR, Res[, paste0(by, bySuff)])
})
############################################################
## transcriptsBy
##
setMethod("transcriptsBy", "EnsDb", function(x, by = c("gene", "exon"),
columns = listColumns(x, "tx"),
filter = AnnotationFilterList()) {
if (any(by == "cds"))
stop("fetching transcripts by cds is not (yet) implemented.")
by <- match.arg(by, c("gene", "exon"))
byId <- paste0(by, "_id")
min.columns <- c(paste0(by, "_id"), "seq_name", "tx_seq_start",
"tx_seq_end", "tx_id", "seq_strand")
## can not have exon columns!
ex_cols <- c(listColumns(x, "exon"), "exon_idx")
ex_cols <- ex_cols[ex_cols != "tx_id"]
torem <- columns %in% ex_cols
if (any(torem))
warning("Columns ",
paste(columns[ torem ], collapse=","),
" have been removed as they are not allowed if",
" transcripts are fetched.")
columns <- columns[!torem]
## Process filters
filter <- .processFilterParam(filter, x)
## GRanges filter should be based on either gene or exon coors.
filter <- setFeatureInGRangesFilter(filter, by)
## Eventually add columns for the filters:
columns <- addFilterColumns(columns, filter, x)
ret_cols <- unique(columns)
## define the minimal columns that we need...
columns <- cleanColumns(x, unique(c(columns, min.columns)))
## get the seqinfo:
suppressWarnings(
SI <- seqinfo(x)
)
byIdFull <- unlist(prefixColumns(x, columns = byId, clean = FALSE),
use.names = FALSE)
orderR <- orderResultsInR(x)
if (orderR) {
order.by <- ""
} else {
order.by <- paste0(byIdFull ,
", case when seq_strand = 1 then tx_seq_start",
" when seq_strand = -1 then (tx_seq_end * -1) end")
}
Res <- getWhat(x, columns=columns, filter=filter,
order.by=order.by, skip.order.check=TRUE,
startWith = by, join = "suggested")
## issue #48: collapse entrezid column if dbschema 2.0 is used.
if (as.numeric(dbSchemaVersion(x)) > 1 & any(columns == "entrezid"))
Res <- .collapseEntrezidInTable(Res, by = "tx_id")
if (orderR) {
startEnd <- (Res$seq_strand == 1) * Res$tx_seq_start +
(Res$seq_strand == -1) * (Res$tx_seq_end * -1)
Res <- Res[order(Res[, byId], startEnd, method = "radix"), ]
}
SI <- SI[as.character(unique(Res$seq_name))]
## Replace exon_idx with exon_rank
colnames(Res) <- gsub(colnames(Res), pattern = "exon_idx",
replacement = "exon_rank", fixed = TRUE)
ret_cols[ret_cols == "exon_idx"] <- "exon_rank"
notThere <- !(ret_cols %in% colnames(Res))
if(any(notThere))
warning("Columns ", paste0("'", ret_cols[notThere], "'", collapse=", "),
" not found in the database!")
ret_cols <- ret_cols[!notThere]
columns.metadata <- ret_cols[!(ret_cols %in% c("seq_name", "seq_strand",
"tx_seq_start",
"tx_seq_end"))]
columns.metadata <- match(columns.metadata, colnames(Res))
GR <- GRanges(seqnames=Rle(Res$seq_name),
strand=Rle(Res$seq_strand),
ranges=IRanges(start=Res$tx_seq_start, end=Res$tx_seq_end),
seqinfo=SI,
Res[ , columns.metadata, drop=FALSE ]
)
return(split(GR, Res[ , byId]))
})
############################################################
## lengthOf
## for GRangesList...
setMethod("lengthOf", "GRangesList", function(x, ...){
return(sum(width(reduce(x))))
## return(unlist(lapply(width(reduce(x)), sum)))
})
## return the length of genes or transcripts
setMethod("lengthOf", "EnsDb", function(x, of="gene",
filter=AnnotationFilterList()){
of <- match.arg(of, c("gene", "tx"))
## get the exons by gene or transcript from the database...
suppressWarnings(
GRL <- exonsBy(x, by=of, filter=filter)
)
return(lengthOf(GRL))
})
####============================================================
## transcriptLengths
##
## For TxDb: calls just the function (not method!) from the GenomicFeatures
## package.
## For EnsDb: calls the .transcriptLengths function.
.transcriptLengths <- function(x, with.cds_len = FALSE, with.utr5_len = FALSE,
with.utr3_len = FALSE,
filter = AnnotationFilterList(),
exons = NA, transcripts = NA) {
## The preloaded data option is currently only for the coordinates mapping
## functions, therefore the filter is "tx_id" only.
preload_ranges_missing <- which(c(
identical(exons,NA),
identical(transcripts,NA)
))
if(identical(integer(0), preload_ranges_missing)){
if (!is(exons, "CompressedGRangesList"))
stop("Argument 'exons' has to be a 'CompressedGRangesList' object")
if (!is(transcripts, "GRanges"))
stop("Argument 'transcripts' has to be an 'GRanges' object")
if (identical(integer(0),grep('T[0-9]', names(exons)[[1]])))
stop("Argument 'exons' has to be by 'tx'.")
## Check if x is a formula and eventually translate it.
if (is(filter, "formula"))
filter <- AnnotationFilter(filter)
tryCatch({
filter_type <- filter@field
filter_tx <- filter@value
}, error = function(e){
message("No filter detected, all transcripts will be returned")
filter_tx <<- names(transcripts)
})
if (exists('filter_type')){
if (filter_type != "tx_id")
stop("Filter must be 'tx_id'.")
}
tryCatch({
allTxs <- transcripts[names(transcripts) %in% unique(filter_tx)]
}, error = function(e){
allTxs <<- GRanges()
})
} else if (length(preload_ranges_missing) == 2){
filter <- .processFilterParam(filter, x)
allTxs <- transcripts(x, filter = filter)
} else {
stop(paste(
"Argument",
c("'exons'", "'transcripts'")[preload_ranges_missing],
'missing.'
, sep = " "
))
}
if (length(allTxs) == 0)
return(data.frame(tx_id = character(), gene_id = character(),
nexon = integer(), tx_len = integer()))
if(identical(integer(0), preload_ranges_missing)){
exns <- exons[match(allTxs$tx_id, names(exons))]
} else {
exns <- exonsBy(x, filter = TxIdFilter(allTxs$tx_id))
## Match ordering
exns <- exns[match(allTxs$tx_id, names(exns))]
}
## Calculate length of transcripts.
txLengths <- sum(width(exns))
## Calculate no. of exons.
## build result data frame:
Res <- data.frame(tx_id = allTxs$tx_id, gene_id = allTxs$gene_id,
nexon = lengths(exns), tx_len = txLengths,
stringsAsFactors = FALSE)
if(!any(c(with.cds_len, with.utr5_len, with.utr3_len))) {
## Return what we've got thus far.
return(Res)
}
if (with.cds_len)
Res$cds_len <- NA
if (with.utr5_len)
Res$utr5_len <- NA
if (with.utr3_len)
Res$utr3_len <- NA
## Otherwise do the remaining stuff...