/R/utils.R

http://github.com/tengfei/visnab · R · 307 lines · 228 code · 31 blank · 48 comment · 20 complexity · 53b18678455fc9f375622d0eddb07249 MD5 · raw file

  1. setMethod('validateChr',c('GenomicRanges'),
  2. function(obj,model,...){
  3. if(inherits(class(model),'GenomicRanges'))
  4. chrset <- unique(as.character(seqnames(model)))
  5. else
  6. chrset <- model
  7. chr <- as.character(seqnames(obj))
  8. obj <- obj[chr %in% chrset]
  9. return(obj)
  10. })
  11. isValidatedChr <- function(grl,model){
  12. if(is(grl,'list')){
  13. chrset <- unique(as.character(seqnames(model)))
  14. allLst <- lapply(seq_len(length(grl)),function(i) {
  15. idx <- unique(as.character(seqnames(grl[[i]]))) %in% chrset
  16. if(all(idx)==FALSE){
  17. message(paste("Chromosome names of",names(grl)[i],"is invalid"))
  18. message(paste(unique(as.character(seqnames(grl[[i]])))[!idx],' '),'is invalid')
  19. }
  20. all(idx)
  21. })
  22. return(all(unlist(allLst)))
  23. }
  24. if(is(grl,'GenomicRanges')){
  25. chrset <- unique(as.character(seqnames(model)))
  26. idx <- unique(as.character(seqnames(grl))) %in% chrset
  27. return(all(idx))
  28. }
  29. }
  30. containLetters <- function(obj,only=FALSE){
  31. obj <- as.character(obj)
  32. obj <- tolower(obj)
  33. obj <- unlist(strsplit(obj,""))
  34. if(!only){
  35. res <- any(obj%in%letters)
  36. return(res)
  37. }else{
  38. res <- all(obj%in%letters)
  39. return(res)
  40. }
  41. }
  42. xy2polar <- function(x,y){
  43. angle <- atan(y/x)/pi*180
  44. radius <- sqrt(x^2+y^2)
  45. data.frame(radius=radius,angle=angle)
  46. }
  47. visZoom <- function(obj,scale.factor=c(4,4)){
  48. ## this obj must contain list of scene, viewU, layer
  49. visenv$new.view <- qplotView(obj$scene)
  50. visenv$new.view$show()
  51. visenv$new.view$scale(scale.factor[1],scale.factor[2])
  52. }
  53. setHover <- function(obj,layer.name){
  54. layers <- obj$layer
  55. nms <- names(layers)
  56. layers[[layer.name]]$setAcceptsHoverEvents(TRUE)
  57. for(i in setdiff(nms,layer.name)){
  58. layers[[i]]$setAcceptsHoverEvents(FALSE)
  59. }
  60. }
  61. setHoverNext <- function(obj){
  62. layers <- obj$layer
  63. nms <- names(layers)
  64. idx <- unlist(unname(lapply(layers,function(x) x$acceptsHoverEvents())))
  65. if(sum(idx)>1|sum(idx)==0){
  66. idx <- rep(FALSE,length(idx))
  67. idx[1] <- TRUE
  68. idxs <- 1
  69. }
  70. if(sum(idx)==1){
  71. idxs <- which(idx==TRUE)
  72. if(idxs==length(idx)){
  73. idxs <- 1
  74. }else{
  75. idxs <- idxs+1
  76. }
  77. }
  78. lapply(layers,function(x){
  79. x$setAcceptsHoverEvents(FALSE)
  80. })
  81. layers[[idxs]]$setAcceptsHoverEvents(TRUE)
  82. message(nms[idxs])
  83. }
  84. col2qcol <- function(color,alpha=1){
  85. cols <- col2rgb(alpha(color,alpha),TRUE)
  86. qcolor(unname(cols[1,1]),
  87. unname(cols[2,1]),
  88. unname(cols[3,1]),
  89. unname(cols[4,1]))
  90. }
  91. baseColor <- function(base,pal=brewer_pal(pal="Set1")){
  92. cols <- dscale(base,brewer_pal(pal="Set1"))
  93. obj <- list()
  94. for(i in 1:length(base))
  95. obj[[base[i]]] <- cols[i]
  96. class(obj) <- "ColorList"
  97. obj
  98. }
  99. reduceChr <- function(obj){
  100. grl <- split(obj,seqnames(obj))
  101. lst <- lapply(names(grl),function(nms){
  102. GRanges(seqnames=nms,IRanges(0,max(end(grl[[nms]]))))
  103. })
  104. ngr <- do.call('c',lst)
  105. sortChr(ngr)
  106. }
  107. ## ------------------------------------------------------------
  108. ## Utils for MutableGRanges
  109. ## ------------------------------------------------------------
  110. ## Add extra attributes to an MutableRanges object
  111. ## This is going to be naming routines in visnab.
  112. ## Specific signal should be bound to MR object.
  113. setGeneric("addAttr",function(obj,...) standardGeneric("addAttr"))
  114. ## genAttr <- function(N, ...){
  115. ## lst <- list(...)
  116. ## nms <- names(lst)
  117. ## lst <- lapply(nms, function(attr){
  118. ## val <- lst[[attr]]
  119. ## rep(val, N)
  120. ## })
  121. ## names(lst) <- nms
  122. ## do.call(data.frame, lst)
  123. ## }
  124. setMethod("addAttr","SimpleMutableGRanges",function(obj,...){
  125. lst <- list(...)
  126. nms <- names(lst)
  127. df <- elementMetadata(obj)
  128. nms.exist <- colnames(df)
  129. idx <- rep(FALSE,length(nms))
  130. lst <- lapply(lst,function(x) rep(x,nrow(df)))
  131. sapply(seq_along(nms),function(i){
  132. if((nms[i] %in% nms.exist)&&(identical(as.character(lst[[nms[i]]]),as.character(df[,nms[i]]))))
  133. idx[i] <<- TRUE
  134. })
  135. lst <- lst[!idx]
  136. dfex <- as.data.frame(do.call(cbind,lst),stringsAsFactors=FALSE)
  137. ## New attributes, haven't check selection in plumbr yet
  138. df.nw <- c(df,as(dfex,"DataFrame"))
  139. df.nw
  140. obj
  141. elementMetadata(obj) <- df.nw
  142. ## elementMetadata(obj) <- df
  143. obj
  144. })
  145. setMethod("addAttr","GRanges",function(obj,...){
  146. lst <- list(...)
  147. nms <- names(lst)
  148. sapply(nms, function(nm){
  149. elementMetadata(obj)[,nm] <<- lst[[nm]]
  150. })
  151. obj
  152. })
  153. ## ## setMethod("addAttr","MutableGRanges",function(obj,...){
  154. ## ## lst <- list(...)
  155. ## ## nms <- names(lst)
  156. ## ## sapply(nms, function(nm){
  157. ## ## elementMetadata(obj)[,nm] <- lst[[nm]]
  158. ## ## })
  159. ## ## obj
  160. ## ## })
  161. ## setGeneric("addDefAttr",function(obj,...) standardGeneric("addDefAttr"))
  162. ## ------------------------------------------------------------
  163. ## Utils for GenomicRanges
  164. ## ------------------------------------------------------------
  165. ## Should output to a nice tooltip format
  166. setGeneric("getTooltipInfo",function(obj,...) standardGeneric("getTooltipInfo"))
  167. ## Suppose any hiden name is not for shown
  168. setMethod("getTooltipInfo","GenomicRanges",function(obj,i,...){
  169. df <- values(obj)[i,,drop=FALSE]
  170. df$chrom <- as.character(seqnames(obj))[i]
  171. df$start <- start(obj)[i]
  172. df$end <- end(obj)[i]
  173. nms <- colnames(df)
  174. nms <- grep("^[^\\.]",nms,value=TRUE)
  175. tips <- "\n"
  176. for(nm in nms){
  177. tips <- paste(tips,paste(nm," : ",df[,nm],"\n",sep=""),sep="")
  178. }
  179. tips
  180. })
  181. chrAll <- function(...){
  182. lst <- list(...)
  183. chr.lst <- lapply(lst,function(gr){
  184. chrs <- unique(as.character(seqnames(gr)))
  185. if("to.chr" %in% names(values(gr))){
  186. chrs2 <- unique(as.character(values(gr)$to.chr))
  187. chrs <- unique(c(chrs,chrs2))
  188. }
  189. chrs
  190. })
  191. chrs <- sortChr(unique(unlist(chr.lst)))
  192. return(chrs)
  193. }
  194. ## Interactive indicator
  195. ## start to record
  196. IMessageStart <- function(geometry=qrect(0,0,10,100),leaf=20,freq=0.05){
  197. .indicatorScene <<- qscene()
  198. .indicatorLayer <<- qlayer(.indicatorScene)
  199. .indicatorView <<- qplotView(.indicatorScene)
  200. .messageLayer <- qlayer(.indicatorLayer,paintFun=function(layer,painter){
  201. if(exists(".message"))
  202. qdrawText(painter,.message,0,0,color="black")
  203. },col=1,rowSpan=3)
  204. gr <- GRanges(seqnames=paste("chr",1:leaf),
  205. ranges=IRanges(start=rep(1,leaf),
  206. end=rep(10,leaf)))
  207. obj <- CircularView(list(gr),tracksType="sector",model=gr,scene=.indicatorScene,
  208. view=.indicatorView,rootLayer=.indicatorLayer,col=0,row=0,
  209. .sectorText=FALSE,
  210. tracksWidth=80)
  211. obj$show()
  212. layout <- .indicatorLayer$gridLayout()
  213. layout$setRowPreferredHeight(0,10)
  214. layout$setColumnPreferredWidth(0,10)
  215. layout$setColumnPreferredWidth(1,100)
  216. ## colorchange
  217. ## if(.indicatorFlag){
  218. if(TRUE){
  219. for(idx in 1:leaf){
  220. values(obj$tracks[[1]])$.color[idx] <- "black"
  221. Sys.sleep(freq)
  222. values(obj$tracks[[1]])$.color[idx] <- "white"
  223. Sys.sleep(freq)
  224. }
  225. }
  226. }
  227. ##
  228. ## IMessageStart(freq=0.0001)
  229. ## .indicatorScene$setBackgroundBrush(qbrush(col2qcol("black",0)))
  230. ## .indicatorScene$setBackgroundBrush(qbrush(qcolor(255,255,0,0)))
  231. ## .indicatorScene$setBackgroundBrush(qbrush(col2qcol("lightgray"), Qt$Qt$VerPattern))
  232. IMessage <- function(..., scene=.indicatorScene,
  233. view=.indicatorView,
  234. rootLayer=.indicatorLayer,
  235. leaf=7){
  236. ## fun with circular view, pseudo "chromosome"
  237. ## should support RangedData later
  238. .message <<- paste(...)
  239. }
  240. ## IMessage()
  241. GCcontent <- function(files, regions){
  242. grl <- pileupAsGRanges(files, regions)
  243. if(sum(values(gr)$depth))
  244. gcc <- (sum(values(gr)$G)+sum(values(gr)$C))/sum(values(gr)$depth)
  245. values(region)$GCcontent <- gcc
  246. region
  247. }
  248. ## ## utils to generate pair-end
  249. pspanGR <- function(file, region, sameChr = TRUE, isize.cutoff = 170){
  250. ## FIXME: move unmated?
  251. bam <- scanBam(file, param=ScanBamParam(which = region),
  252. flag = scanBamFlag(hasUnmappedMate = FALSE))
  253. bam <- bam[[1]]
  254. bamrd <- GRanges(bam$rname, IRanges(bam$pos, width = bam$qwidth),
  255. strand = bam$strand,
  256. mseqname = bam$mrnm,
  257. mstart = bam$mpos,
  258. isize = bam$isize)
  259. ## why negative?sometime
  260. bamrd <- bamrd[abs(bam$isize) >= isize.cutoff]
  261. if(sameChr){
  262. idx <- as.character(seqnames(bamrd)) == values(bamrd)$mseqname
  263. bamrd <- bamrd[idx]
  264. }
  265. if(length(bamrd)){
  266. p1 <- GRanges(seqnames(bamrd),
  267. ranges(bamrd))
  268. p2 <- GRanges(values(bamrd)$mseqname,
  269. IRanges(values(bamrd)$mstart, width = 75))
  270. pspan <- punion(p1, p2, fill.gap = TRUE)
  271. pgaps <- pgap(ranges(p1), ranges(p2))
  272. return(list(pspan = pspan, pgaps = pgaps, p1 = p1, p2 = p2))
  273. }else{
  274. return(NULL)
  275. }
  276. }