content
stringlengths 0
14.9M
| filename
stringlengths 44
136
|
---|---|
#' Check if there is a connection to a BED database
#'
#' @param verbose if TRUE print information about the BED connection
#' (default: FALSE).
#'
#' @return
#'
#' - TRUE if the connection can be established
#' - Or FALSE if the connection cannot be established or the "System" node
#' does not exist or does not have "BED" as name or any version recorded.
#'
#' @seealso [connectToBed]
#'
#' @export
#'
checkBedConn <- function(verbose=FALSE){
if(!exists("graph", bedEnv)){
message(
"BED is not connected.\n",
"You can connect to a BED database instance using the connectToBed",
" function."
)
return(FALSE)
}
nmv <- bedEnv$graph$version[1]
if(! nmv %in% c("3", "5")){
message(sprintf("The version %s of Neo4j is not supported", nmv))
return(FALSE)
}
if(verbose) message(get("graph", bedEnv)$url)
dbVersion <- try(bedCall(
f=neo2R::cypher,
query=neo2R::prepCql(c(
'MATCH (n:System) RETURN',
'n.name as name, n.instance as instance, n.version as version'
)),
bedCheck=FALSE
))
if(inherits(dbVersion, "try-error")){
return(FALSE)
}
if(is.null(dbVersion)){
dbSize <- bedCall(
f=neo2R::cypher,
query='MATCH (n) WITH n LIMIT 1 RETURN count(n);',
bedCheck=FALSE
)[,1]
if(is.null(dbSize)){
warning("No connection")
return(FALSE)
}
if(dbSize==0){
warning("BED DB is empty !")
return(TRUE)
}else{
warning("DB is not empty but without any System node. Check url.")
return(FALSE)
}
}
if(verbose){
message(dbVersion$name)
message(dbVersion$instance)
message(dbVersion$version)
if(get("useCache", bedEnv)){
message("Cache ON")
}else{
message("Cache OFF")
}
}
if(
is.null(dbVersion$name) || dbVersion$name!="BED" ||
is.null(dbVersion$instance) ||
is.null(dbVersion$version)
){
warning("Wrong system. Check url.")
print(get("graph", bedEnv)$url)
return(FALSE)
}
toRet <- TRUE
attr(toRet, "dbVersion") <- dbVersion
return(toRet)
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/checkBedConn.R |
#' Identify and remove dubious cross-references
#'
#' Not exported to avoid unintended modifications of the DB.
#'
#' @param d a cross-reference data.frame with 2 columns.
#' @param strict if TRUE (default), the function returns only unambiguous
#' mappings
#'
#' @return This function returns d without dubious cross-references.
#' Issues are reported in attr(d, "issues").
#'
cleanDubiousXRef <- function(d, strict=TRUE){
############################################################################@
## Helpers ----
# splitByCluster <- function(ref, exref){
# toRet <- list()
# toTake <- unique(ref$id1)
# while(length(toTake)>0){
# taken <- toTake[1]
# toAdd <- getClustId(taken, exref, ref)
# toTake <- setdiff(toTake, toAdd$id1)
# toAdd <- list(toAdd)
# names(toAdd) <- taken
# toRet <- c(toRet, toAdd)
# }
# return(toRet)
# }
# getClustId <- function(id, exref, ref=exref){
# direct <- exref[which(exref$id1==id | exref$id2==id),]
# indirect <- exref[
# which(
# exref$id1 %in% direct$id1 |
# exref$id2 %in% direct$id2
# ),
# ]
# while(!identical(direct, indirect)){
# direct <- indirect
# indirect <- exref[
# which(
# exref$id1 %in% direct$id1 |
# exref$id2 %in% direct$id2
# ),
# ]
# }
# toRet <- ref[which(
# ref$xrid %in% indirect$xrid
# ),]
# return(toRet)
# }
############################################################################@
## Check input ----
stopifnot(ncol(d)==2)
ocolnames <- colnames(d)
colnames(d) <- c("id1", "id2")
############################################################################@
## Preprocessing ----
dup1 <- dplyr::group_by(d, .data$id1)
dup1 <- dplyr::ungroup(dplyr::summarise(dup1, l2=length(.data$id2)))
dup2 <- dplyr::group_by(d, .data$id2)
dup2 <- dplyr::ungroup(dplyr::summarise(dup2, l1=length(.data$id1)))
exref <- d
exref <- dplyr::left_join(exref, dup1, by="id1")
exref <- dplyr::left_join(exref, dup2, by="id2")
exref$xrid <- 1:nrow(d)
############################################################################@
## Candidate issues ----
if(strict){
nonIssues <- dplyr::filter(exref, .data$l1==1 & .data$l2==1)
nonIssues <- as.data.frame(dplyr::select(nonIssues, "id1", "id2"))
colnames(nonIssues) <- ocolnames
toRet <- nonIssues
return(toRet)
}else{
nonIssues <- dplyr::filter(exref, !.data$l1>1 | !.data$l2>1)
candidateIssues <- dplyr::filter(exref, .data$l1>1 & .data$l2>1)
## _+ Examining candidate issues ----
issues <- dplyr::filter(
candidateIssues,
.data$id1 %in% nonIssues$id1 | .data$id2 %in% nonIssues$id2
)
undecided <- dplyr::filter(
candidateIssues,
!.data$id1 %in% nonIssues$id1 & !.data$id2 %in% nonIssues$id2
)
exrefTmp <- exref
.data <- NULL
while(!identical(exrefTmp, undecided)){
exrefTmp <- dplyr::select(undecided, -"l2", -"l1")
dup1 <- dplyr::group_by(exrefTmp, .data$id1)
dup1 <- dplyr::ungroup(dplyr::summarise(dup1, l2=length(.data$id2)))
dup2 <- dplyr::group_by(exrefTmp, .data$id2)
dup2 <- dplyr::ungroup(dplyr::summarise(dup2, l1=length(.data$id1)))
exrefTmp <- dplyr::left_join(exrefTmp, dup1, by="id1")
exrefTmp <- dplyr::left_join(exrefTmp, dup2, by="id2")
##
nonIssueToAdd <- dplyr::filter(exrefTmp, !.data$l1>1 | !.data$l2>1)
nonIssues <- dplyr::bind_rows(nonIssues, nonIssueToAdd)
candidateIssuesTmp <- dplyr::filter(exrefTmp, .data$l1>1 & .data$l2>1)
issuesToAdd <- dplyr::filter(
candidateIssuesTmp,
.data$id1 %in% nonIssueToAdd$id1 | .data$id2 %in% nonIssueToAdd$id2
)
issues <- dplyr::bind_rows(issues, issuesToAdd)
undecided <- dplyr::filter(
candidateIssuesTmp,
!.data$id1 %in% nonIssueToAdd$id1 &
!.data$id2 %in% nonIssueToAdd$id2
)
}
# splUndecided <- splitByCluster(undecided, exref)
# splUndecided.OK <- unlist(lapply(
# splUndecided,
# function(x){
# l1 <- unique(x$l1)
# l2 <- unique(x$l2)
# if(length(l1)>1 | length(l2)>1){
# return(FALSE)
# }else{
# if(l2==length(unique(x$id2)) & l1==length(unique(x=x$id1))){
# return(TRUE)
# }else{
# return(FALSE)
# }
# }
# }
# ))
# if(!all(splUndecided.OK)){
# warning("Review undecided")
# }
nonIssues <- dplyr::bind_rows(nonIssues, undecided)
nonIssues <- as.data.frame(dplyr::select(nonIssues, "id1", "id2"))
issues <- as.data.frame(dplyr::select(issues, "id1", "id2"))
colnames(nonIssues) <- colnames(issues) <- ocolnames
toRet <- nonIssues
attr(toRet, "issues") <- issues
return(toRet)
}
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/cleanDubiousXRef.R |
#' Clear the BED cache SQLite database
#'
#' @param queries a character vector of the names of queries to remove.
#' If NULL all queries are removed.
#' @param force if TRUE clear the BED cache table even if cache
#' file is not found
#' @param hard if TRUE remove everything in cache without checking file names
#' @param verbose display some information during the process
#'
#' @seealso [lsBedCache]
#'
#' @export
#'
clearBedCache <- function(
queries=NULL, force=FALSE, hard=FALSE, verbose=FALSE
){
if(!checkBedConn(verbose=FALSE)){
stop("Unsuccessful connection")
}
## Write cache in the user file space only if the "useCache" parameter
## is set to TRUE when calling `connectToBed()` (default: useCache=FALSE)
if(!get("useCache", bedEnv)){
warning("Cache is OFF: nothing is done")
invisible(NULL)
}else{
if(hard){
cachedbFile <- get("cachedbFile", bedEnv)
cachedbDir <- dirname(cachedbFile)
file.remove(list.files(path=cachedbDir, full.names=TRUE))
cache <- data.frame(
name=character(),
file=character(),
stringsAsFactors=FALSE
)
assign(
"cache",
cache,
bedEnv
)
checkBedCache()
invisible()
}
cache <- get("cache", bedEnv)
cachedbFile <- get("cachedbFile", bedEnv)
cachedbDir <- dirname(cachedbFile)
if(is.null(queries)){
queries <- cache
}else{
if(any(!queries %in% rownames(cache))){
warning(sprintf(
"%s not in cache",
paste(setdiff(queries, rownames(cache)), collapse=", ")
))
}
queries <- cache[intersect(queries, rownames(cache)),]
}
for(tn in rownames(queries)){
if(verbose){
message(paste("Removing", tn, "from cache"))
}
if(file.remove(file.path(cachedbDir, queries[tn, "file"]))){
cache <- cache[setdiff(rownames(cache), tn),]
save(cache, file=cachedbFile)
assign(
"cache",
cache,
bedEnv
)
}else{
if(!force){
stop(paste(
"Could not remove the following file:",
file.path(cachedbDir, queries[tn, "file"]),
"\nCheck cache files and/or clear the whole-",
"cache using force=TRUE"
))
}else{
warning(paste(
"Could not remove the following file:",
file.path(cachedbDir, queries[tn, "file"]),
"\nClearing cache table anyway (force=TRUE)"
))
cache <- cache[setdiff(rownames(cache), tn),]
save(cache, file=cachedbFile)
assign(
"cache",
cache,
bedEnv
)
}
}
}
invisible(cache)
}
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/clearBedCache.R |
#' Compare 2 BED database instances
#'
#' @param connections a numeric vector of length 1 or 2 providing connections
#' from [lsBedConnections] to be compared.
#'
#' @return If only one connection is provided, the function returns a list
#' with information about BEID and platforms available for the connection
#' along with DB version information.
#' If two connections are provided the same information as above is provided
#' for the 2 connection named V1 and V2 in that order. In addition,
#' differences observed between the 2 instances are reported for BEID and
#' platforms.
#'
#' @details The current connection is restored when exiting this function.
#'
#' @export
compareBedInstances <- function(connections){
toRestore <- lsBedConnections()[[1]]
on.exit(connectToBed(
url=toRestore[["url"]],
username=toRestore[["username"]],
password=toRestore[["password"]]
))
if(length(connections)>2){
stop("Maximum 2 connections can be provided")
}
if(length(connections)==0){
stop("At least 1 connection must be provided")
}
## V1
connectToBed(connection=connections[1])
be.V1 <- c()
for(be in listBe()){
for(org in listOrganisms()){
toAdd <- listBeIdSources(
be=be,
organism=org,
exclude=c("BEDTech_gene", "BEDTech_transcript"),
verbose=FALSE
)
if(!is.null(toAdd)){
colnames(toAdd) <- c("Database", "nbBE", "BEID", "BE")
toAdd$Organism <- org
be.V1 <- rbind(
be.V1,
toAdd[,c("BE", "Organism", "Database", "BEID")]
)
}
}
}
pl.V1 <- listPlatforms()
db.V1 <- attr(checkBedConn(), "dbVersion")
if(length(connections)==1){
return(list(
BEID=be.V1,
platforms=pl.V1,
dbVersion=db.V1
))
}
## V2
connectToBed(connection=connections[2])
be.V2 <- c()
for(be in listBe()){
for(org in listOrganisms()){
toAdd <- listBeIdSources(
be=be,
organism=org,
exclude=c("BEDTech_gene", "BEDTech_transcript"),
verbose=FALSE
)
if(!is.null(toAdd)){
colnames(toAdd) <- c("Database", "nbBE", "BEID", "BE")
toAdd$Organism <- org
be.V2 <- rbind(
be.V2,
toAdd[,c("BE", "Organism", "Database", "BEID")]
)
}
}
}
pl.V2 <- listPlatforms()
db.V2 <- attr(checkBedConn(), "dbVersion")
## BEID Comparison
rownames(be.V1) <- apply(be.V1[,1:3], 1, paste, collapse="..")
rownames(be.V2) <- apply(be.V2[,1:3], 1, paste, collapse="..")
beidOnlyInV1 <- be.V1[setdiff(rownames(be.V1), rownames(be.V2)),]
beidOnlyInV2 <- be.V2[setdiff(rownames(be.V2), rownames(be.V1)),]
commBeid <- intersect(rownames(be.V1), rownames(be.V2))
commBeid <- cbind(
be.V1[commBeid,],
V2=be.V2[commBeid, "BEID"],
"Delta"=be.V2[commBeid, "BEID"] - be.V1[commBeid, "BEID"]
)
colnames(commBeid) <- c(
colnames(be.V1)[1:3],
paste(db.V1[1,], collapse="|"),
paste(db.V2[1,], collapse="|"),
"Delta"
)
## Platforms comparison
plOnlyInV1 <- pl.V1[setdiff(rownames(pl.V1), rownames(pl.V2)),]
plOnlyInV2 <- pl.V2[setdiff(rownames(pl.V2), rownames(pl.V1)),]
commPl <- intersect(rownames(pl.V1), rownames(pl.V2))
commPl <- cbind(
pl.V1[commPl,],
pl.V2[commPl,],
identical=all(
apply(pl.V1[commPl,], 1, paste, collapse="||")==
apply(pl.V2[commPl,], 1, paste, collapse="||")
)
)
colnames(commPl) <- c(
paste0(colnames(pl.V1), " (", paste(db.V1[1,], collapse="|"), ")"),
paste0(colnames(pl.V2), " (", paste(db.V2[1,], collapse="|"), ")"),
"Identical def."
)
##
toRet <- list(
BEID=list(
"Only in V1"=beidOnlyInV1,
"Only in V2"=beidOnlyInV2,
"Common"=commBeid
),
platforms=list(
"Only in V1"=plOnlyInV1,
"Only in V2"=plOnlyInV2,
"Common"=commPl
),
V1=list(
BEID=be.V1,
platforms=pl.V1,
dbVersion=db.V1
),
V2=list(
BEID=be.V2,
platforms=pl.V2,
dbVersion=db.V2
)
)
return(toRet)
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/compareBedInstances.R |
#' Converts lists of BE IDs
#'
#' @param idList a list of IDs lists
#' @param entity if TRUE returns BE instead of BEID (default: FALSE).
#' BE CAREFUL, THIS INTERNAL ID IS NOT STABLE AND CANNOT BE USED AS A REFERENCE.
#' This internal identifier is useful to avoid biases related to identifier
#' redundancy. See <../doc/BED.html#3_managing_identifiers>
#' @param ... params for the [convBeIds] function
#'
#' @return A list of [convBeIds] ouput ids.
#' Scope ("be", "source" "organism" and "entity" (see Arguments))
#' is provided as a named list
#' in the "scope" attributes: `attr(x, "scope")`
#'
#' @examples \dontrun{
#' convBeIdLists(
#' idList=list(a=c("10", "100"), b=c("1000")),
#' from="Gene",
#' from.source="EntrezGene",
#' from.org="human",
#' to.source="Ens_gene"
#' )
#' }
#'
#' @seealso [convBeIds], [convDfBeIds]
#'
#' @export
#'
convBeIdLists <- function(
idList,
entity=FALSE,
...
){
ct <- convBeIds(unique(unlist(idList)), ...)
toRet <- lapply(
idList,
function(x){
if(entity){
setdiff(unique(ct$to.entity[which(ct$from %in% x)]), NA)
}else{
setdiff(unique(ct$to[which(ct$from %in% x)]), NA)
}
}
)
attr(toRet, "scope") <- c(attr(ct, "scope"), list(entity=entity))
return(toRet)
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/convBeIdLists.R |
#' Converts BE IDs
#'
#' @param ids list of identifiers
#' @param from a character corresponding to the biological entity or Probe.
#' **Guessed if not provided**
#' @param from.source a character corresponding to the ID source.
#' **Guessed if not provided**
#' @param from.org a character corresponding to the organism.
#' **Guessed if not provided**
#' @param to a character corresponding to the biological entity or Probe
#' @param to.source a character corresponding to the ID source
#' @param to.org a character corresponding to the organism
#' @param caseSensitive if TRUE the case of provided symbols
#' is taken into account
#' during search. This option will only affect the conversion from "Symbol"
#' (default: caseSensitive=FALSE).
#' All the other conversion will be case sensitive.
#' @param canonical if TRUE, only returns the canonical "Symbol".
#' (default: FALSE)
#' @param prefFilter boolean indicating if the results should be filter
#' to keep only preferred BEID of BE when they exist (default: FALSE).
#' If there are several
#' preferred BEID of a BE, all are kept. If there are no preferred BEID
#' of a BE, all non-preferred BEID are kept.
#' @param restricted boolean indicating if the results should be restricted to
#' current version of to BEID db. If FALSE former BEID are also returned:
#' **Depending on history it can take a very long time to return**
#' **a very large result!**
#' @param recache a logical value indicating if the results should be taken from
#' cache or recomputed
#' @param limForCache if there are more ids than limForCache. Results are
#' collected for all IDs (beyond provided ids) and cached for futur queries.
#' If not, results are collected only for provided ids and not cached.
#'
#' @return a data.frame with the following columns:
#'
#' - **from**: the input IDs
#' - **to**: the corresponding IDs in `to.source`
#' - **to.preferred**: boolean indicating if the to ID is a preferred
#' ID for the corresponding entity.
#' - **to.entity**: the entity technical ID of the `to` IDs
#'
#' This data.frame can be filtered in order to remove duplicated
#' from/to.entity associations which can lead information bias.
#' Scope ("be", "source" and "organism") is provided as a named list
#' in the "scope" attributes: `attr(x, "scope")`
#'
#' @examples \dontrun{
#' oriId <- c("10", "100")
#' convBeIds(
#' ids=oriId,
#' from="Gene",
#' from.source="EntrezGene",
#' from.org="human",
#' to.source="Ens_gene"
#' )
#' convBeIds(
#' ids=oriId,
#' from="Gene",
#' from.source="EntrezGene",
#' from.org="human",
#' to="Peptide",
#' to.source="Ens_translation"
#' )
#' convBeIds(
#' ids=oriId,
#' from="Gene",
#' from.source="EntrezGene",
#' from.org="human",
#' to="Peptide",
#' to.source="Ens_translation",
#' to.org="mouse"
#' )
#' }
#'
#' @seealso [getBeIdConvTable], [convBeIdLists], [convDfBeIds]
#'
#' @export
#'
convBeIds <- function(
ids,
from,
from.source,
from.org,
to,
to.source,
to.org,
caseSensitive=FALSE,
canonical=FALSE,
prefFilter=FALSE,
restricted=TRUE,
recache=FALSE,
limForCache=2000
){
fn <- sub(
sprintf("^%s[:][::]", utils::packageName()), "",
sub("[(].*$", "", deparse(sys.call(), nlines=1, width.cutoff=500L))
)
ids <- sort(setdiff(as.character(unique(ids)), NA))
##
if(missing(from) || missing(from.source) || missing(from.org)){
toWarn <- TRUE
}else{
toWarn <- FALSE
}
guess <- guessIdScope(
ids=ids, be=from, source=from.source, organism=from.org
)
if(is.null(guess)){
warning("Could not find the provided ids")
if(missing(from) || missing(from.source) || missing(from.org)){
stop("Missing from, from.source or from.org information")
}
}else{
if(is.na(guess$be)){
warning(
"The provided ids does not match the provided scope",
" (from, from.source or from.org)"
)
if(missing(from) || missing(from.source) || missing(from.org)){
stop("Missing from, from.source or from.org information")
}
}else{
from <- guess$be
from.source <- guess$source
from.org <- guess$organism
}
}
if(toWarn){
warning(
"Guessing ID scope:",
sprintf("\n - from: %s", from),
sprintf("\n - from.source: %s", from.source),
sprintf("\n - from.org: %s", from.org)
)
}
##
if(missing(to)) to <- from
if(missing(to.source)) to.source <- from.source
if(missing(to.org)) to.org <- from.org
##
fFilt <- length(ids) <= limForCache
if(!fFilt){
tn <- gsub(
"[^[:alnum:]]", "_",
paste(fn
,
from, from.source,
to, to.source,
getTaxId(from.org), getTaxId(to.org),
ifelse(canonical, "canonical", "all"),
ifelse(restricted, "restricted", "full"),
sep="_"
)
)
checkBedCache()
}
cache <- checkBedCache()
if(!fFilt && tn %in% rownames(cache) && !recache){
ct <- loadBedResult(tn)
}else{
if(getTaxId(from.org)==getTaxId(to.org)){
if(fFilt){
filter=ids
}else{
filter=NULL
}
ct <- getBeIdConvTable(
from=from,
to=to,
from.source=from.source,
to.source=to.source,
organism=from.org,
caseSensitive=caseSensitive,
canonical=canonical,
restricted=restricted,
entity=TRUE,
filter=filter
)
if(is.null(ct) || ncol(ct)==0){
ct <- data.frame(
from=character(),
to=character(),
entity=numeric(),
stringsAsFactors=FALSE
)
}
}else{
ct <- data.frame(
from=character(),
to=character(),
preferred=logical(),
entity=numeric(),
stringsAsFactors=FALSE
)
fgs <- largestBeSource(
be="Gene", organism=from.org,
rel="is_member_of", restricted=restricted
)
if(fFilt){
filter=ids
}else{
filter=NULL
}
ct1 <- getBeIdConvTable(
from=from,
to="Gene",
from.source=from.source,
to.source=fgs,
organism=from.org,
caseSensitive=caseSensitive,
canonical=canonical,
restricted=restricted,
entity=FALSE,
filter=filter
)
if(!is.null(ct1) && ncol(ct1)>0){
ct1 <- dplyr::rename(ct1, "gfrom"="to")
stopConv <- FALSE
}else{
stopConv <- TRUE
}
if(!stopConv){
tgs <- largestBeSource(
be="Gene", organism=to.org,
rel="is_member_of", restricted=restricted
)
##
if(fFilt){
filter=setdiff(ct1$gfrom,NA)
}else{
filter=NULL
}
ht <- getHomTable(
from.org=from.org,
to.org=to.org,
from.source=fgs,
to.source=tgs,
restricted=TRUE,
filter=filter
)
if(!is.null(ht) && ncol(ht)>0){
ht <- dplyr::rename(ht, "gfrom"="from", "gto"="to")
}else{
stopConv <- TRUE
}
##
if(!stopConv){
if(fFilt){
filter=setdiff(ht$gto, NA)
}else{
filter=NULL
}
ct2 <- getBeIdConvTable(
from="Gene",
to=to,
from.source=tgs,
to.source=to.source,
organism=to.org,
caseSensitive=caseSensitive,
canonical=canonical,
restricted=restricted,
entity=TRUE,
filter=filter
)
if(!is.null(ct2) && ncol(ct2)>0){
ct2 <- dplyr::rename(ct2, "gto"="from")
}else{
stopConv <- TRUE
}
##
if(!stopConv){
ct <- unique(dplyr::inner_join(
ct1, ht,
by="gfrom"
)[, c("from", "gto")])
ct <- unique(dplyr::inner_join(
ct, ct2,
by="gto"
)[, c("from", "to", "preferred", "entity")])
}
}
}
}
ct <- ct[order(ct$to),]
##
if(!fFilt){
cacheBedResult(value=ct, name=tn)
}
}
if(caseSensitive | from.source!="Symbol"){
ct <- ct[which(ct$from %in% ids),]
}else{
oriIds <- data.frame(
from=ids, FROM=toupper(ids),
stringsAsFactors=FALSE
)
ct$FROM <- toupper(ct$from)
ct <- dplyr::inner_join(
oriIds, ct[,setdiff(colnames(ct), "from")],
by="FROM"
)
ct <- unique(ct[, setdiff(colnames(ct), "FROM")])
}
##
toRet <- ct[,c("from", "to", "preferred", "entity")]
##
if(prefFilter){
pref <- toRet[which(toRet$preferred),]
notPref <- toRet[
which(!toRet$preferred | is.na(toRet$preferred)),
]
toRet <- rbind(
pref,
notPref[which(!notPref$entity %in% pref$entity),]
)
}
toRet <- toRet[order(toRet$entity),]
##
notFound <- setdiff(ids, toRet$from)
if(length(notFound)>0){
notFound <- data.frame(
from=notFound,
to=NA,
preferred=NA,
entity=NA
)
toRet <- rbind(toRet, notFound)
}
##
toRet <- dplyr::rename(
toRet, "to.preferred"="preferred","to.entity"="entity"
)
attr(toRet, "scope") <- list(
be=to, source=to.source, organism=to.org
)
return(toRet)
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/convBeIds.R |
#' Add BE ID conversion to a data frame
#'
#' @param df the data.frame to be converted
#' @param idCol the column in which ID to convert are. If NULL (default)
#' the row names are taken.
#' @param entity if TRUE returns BE instead of BEID (default: FALSE).
#' BE CAREFUL, THIS INTERNAL ID IS NOT STABLE AND CANNOT BE USED AS A REFERENCE.
#' This internal identifier is useful to avoid biases related to identifier
#' redundancy. See \url{../doc/BED.html#3_managing_identifiers}
#' @param ... params for the [convBeIds] function
#'
#' @return A data.frame with converted IDs.
#' Scope ("be", "source", "organism" and "entity" (see Arguments))
#' is provided as a named list
#' in the "scope" attributes: `attr(x, "scope")`.
#'
#' @examples \dontrun{
#' toConv <- data.frame(a=1:2, b=3:4)
#' rownames(toConv) <- c("10", "100")
#' convDfBeIds(
#' df=toConv,
#' from="Gene",
#' from.source="EntrezGene",
#' from.org="human",
#' to.source="Ens_gene"
#' )
#' }
#'
#' @seealso [convBeIds], [convBeIdLists]
#'
#' @export
#'
convDfBeIds <- function(
df,
idCol=NULL,
entity=FALSE,
...
){
oriClass <- class(df)
if(any(colnames(df) %in% c("conv.from", "conv.to"))){
colnames(df) <- paste("x", colnames(df), sep=".")
}
if(length(idCol)==0){
cols <- colnames(df)
ct <- convBeIds(rownames(df), ...)
df$conv.from <- as.character(rownames(df))
}else{
if(length(idCol)>1){
stop("Only one idCol should be provided")
}
cols <- setdiff(colnames(df), idCol)
ct <- convBeIds(df[, idCol, drop=TRUE], ...)
df$conv.from <- as.character(df[, idCol, drop=TRUE])
df <- df[, c(cols, "conv.from")]
}
scope <- attr(ct, "scope")
ct <- ct[,c("from", ifelse(entity, "to.entity", "to"))]
colnames(ct) <- c("from", "to")
colnames(ct) <- paste("conv", colnames(ct), sep=".")
df <- dplyr::inner_join(df, ct, by="conv.from")
df <- df[, c(cols, "conv.from", "conv.to")]
class(df) <- oriClass
attr(df, "scope") <- c(scope, list(entity=entity))
return(df)
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/convDfBeIds.R |
#' Feeding BED: Dump table from the Ensembl core database
#'
#' Not exported to avoid unintended modifications of the DB.
#'
#' @param organism the organism to download (e.g. "Homo sapiens").
#' @param release Ensembl release (e.g. "83")
#' @param gv version of the genome (e.g. "38")
#' @param ddir path to the directory where the data should be saved
#' @param toDump the list of tables to download
#' @param env the R environment in which to load the tables when downloaded
#'
dumpEnsCore <- function(
organism,
release,
gv,
ddir,
toDump=c(
"attrib_type", "gene_attrib", "transcript",
"external_db", "gene", "translation",
"external_synonym", "object_xref", "xref",
"stable_id_event"
),
env=parent.frame(n=1)
){
dumpDir <- file.path(ddir, paste(
gsub(" ", "_", tolower(organism)),
"core", release, gv,
sep="_"
))
dir.create(dumpDir, showWarnings = F)
ftp <- paste0(
"ftp://ftp.ensembl.org/pub/release-", release,
"/mysql/", dumpDir, "/"
)
## SQL file
f <- paste0(dumpDir, ".sql.gz")
message(f)
sqlf <- lf <- file.path(dumpDir, f)
if(!file.exists(lf)){
message(Sys.time(), " --> Downloading...")
utils::download.file(
url=paste0(ftp, f),
destfile=lf,
method="wget",
quiet=T
)
}
coreSql <- readLines(sqlf)
tableStarts <- grep("^CREATE TABLE", coreSql)
tableEnds <- grep("^)", coreSql)
tables <- mapply(
function(s, e){
tname <- sub("[`].*$", "", sub("^CREATE TABLE [`]", "", coreSql[s]))
fields <- grep("^[[:blank:]]*[`]", coreSql[(s+1):(e-1)], value=T)
fields <- sub("[`].*$", "", sub("^[[:blank:]]*[`]", "", fields))
return(list(tname=tname, fields=fields))
},
tableStarts,
tableEnds,
SIMPLIFY=F
)
tables.names <- unlist(lapply(tables, function(x) x$tname))
tables.fields <- lapply(tables, function(x) x$fields)
names(tables.fields) <- tables.names
## Data files
for(td in toDump){
f <- paste0(td, ".txt.gz")
message(f)
lf <- file.path(dumpDir, f)
if(!file.exists(lf)){
message(Sys.time(), " --> Downloading...")
utils::download.file(
url=paste0(ftp, f),
destfile=lf,
method="wget",
quiet=T
)
}
df <- file.path(dumpDir, paste0(td, ".rda"))
if(!file.exists(df)){
# tmp <- readLines(lf, encoding="UTF-8")
tmp <- readr::read_file(lf)
tmp <- gsub("\r\n", " ", tmp)
tmp <- gsub("\r\\\\n", "", tmp)
tmp <- strsplit(tmp, split="\n")[[1]]
toRm <- which(tmp=="\\")
if(length(toRm)>0){
toRm <- c(toRm, toRm+1)
tmp <- tmp[-toRm]
}
tmp <- paste(tmp, collapse="\n")
tmp <- gsub("[\\]\n", "", tmp)
tmp <- unlist(strsplit(tmp, split="\n"))
tmpf <- tempfile()
write(tmp, tmpf, ncolumns=1)
data <- utils::read.table(
tmpf,
sep="\t", quote="", comment.char="",
header=F, stringsAsFactors=F
)
# colnames(data) <- doc$Column
colnames(data) <- tables.fields[[td]]
assign(td, data)
save(list=td, file= df)
}
load(df, envir=env)
}
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/dumpEnsCore.R |
#' Feeding BED: Dump tables from the NCBI gene DATA
#'
#' Not exported to avoid unintended modifications of the DB.
#'
#' @param taxOfInt the organism to download (e.g. "9606").
#' @param reDumpThr time difference threshold between 2 downloads
#' @param ddir path to the directory where the data should be saved
#' @param toLoad the list of tables to load
#' @param env the R environment in which to load the tables when downloaded
#' @param curDate current date as given by [Sys.Date]
#'
dumpNcbiDb <- function(
taxOfInt,
reDumpThr,
ddir,
toLoad=c(
"gene_info", "gene2ensembl",
# "gene2unigene", "gene2vega",
"gene_group", "gene_orthologs",
"gene_history", "gene2refseq"
),
env=parent.frame(n=1),
curDate
){
ftp <- "https://ftp.ncbi.nlm.nih.gov/gene/DATA/"
dumpDir <- file.path(ddir, "NCBI-gene-DATA")
if(file.exists(dumpDir)){
load(file.path(dumpDir, "dumpDate.rda"))
message("Last download: ", dumpDate)
if(curDate - dumpDate > reDumpThr){
toDownload <- TRUE
}else{
toDownload <- FALSE
}
}else{
message("Not downloaded yet")
toDownload <- TRUE
}
if(toDownload){
if(file.exists(dumpDir)){
dumpDirBck <- paste0(dumpDir,"-BCK")
file.remove(list.files(path = dumpDirBck, full.names = T))
file.remove(dumpDirBck)
file.rename(dumpDir, dumpDirBck)
}
dir.create(dumpDir)
dumpDate <- curDate
save(dumpDate, file=file.path(dumpDir, "dumpDate.rda"))
message("Data have been downloaded")
}else{
message("Existing data are going to be used")
}
loadTd <- function(td){
message(td)
f1 <- paste0(td, ".gz")
f2 <- td
f <- f1
lf <- file.path(dumpDir, f)
lf2 <- file.path(dumpDir, f2)
df <- file.path(dumpDir, paste0(td, ".rda"))
tdoi <- paste(td, paste(taxOfInt, collapse="_"), sep="-")
dfoi <- file.path(dumpDir, paste0(tdoi, ".rda"))
if(!file.exists(lf) & !file.exists(lf2)){
message(Sys.time(), " --> Downloading...", f)
dlok <- try(utils::download.file(
url=paste0(ftp, f),
destfile=lf,
method="wget",
quiet=T
), silent=T)
if(dlok != 0){
file.remove(lf)
f <- f2
lf <- file.path(dumpDir, f)
message(Sys.time(), " --> Downloading...", f)
dlok <- try(utils::download.file(
url=paste0(ftp, f),
destfile=lf,
method="wget",
quiet=T
), silent=T)
if(dlok != 0){
file.remove(lf)
stop("Could not find files.")
}
}
}else{
if(!file.exists(lf)){
f <- f2
lf <- file.path(dumpDir, f)
}
}
cn <- readLines(lf, n=1)
# cn <- unlist(strsplit(cn, split=" "))
# cn <- cn[-c(1, grep("^[(]", cn):length(cn))]
cn <- sub("^#", "", cn)
cn <- unlist(strsplit(cn, split="[ \t]"))
if(!file.exists(df)){
tmp <- utils::read.table(
lf,
sep="\t",
header=F, skip=1,
stringsAsFactors=F,
quote="", comment.char=""
)
colnames(tmp) <- cn
assign(x=td, value=tmp)
save(list=td, file=df)
if(!file.exists(dfoi) & "tax_id" %in% cn){
tmp <- get(td)
tmp <- tmp[which(tmp$tax_id %in% taxOfInt),]
assign(x=td, value=tmp)
save(list=td, file=dfoi)
}
}else{
if(!file.exists(dfoi) & "tax_id" %in% cn){
load(df)
tmp <- get(td)
tmp <- tmp[which(tmp$tax_id %in% taxOfInt),]
assign(x=td, value=tmp)
save(list=td, file=dfoi)
}
}
if("tax_id" %in% cn){
load(dfoi, envir=env)
}else{
load(df, envir=env)
}
}
########################################
for(td in toLoad){
loadTd(td=td)
}
load(file.path(dumpDir, "dumpDate.rda"), envir=env)
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/dumpNcbiDb.R |
#' Feeding BED: Dump tables with taxonomic information from NCBI
#'
#' Not exported to avoid unintended modifications of the DB.
#'
#' @param reDumpThr time difference threshold between 2 downloads
#' @param ddir path to the directory where the data should be saved
#' @param toDump the list of tables to load
#' @param env the R environment in which to load the tables when downloaded
#' @param curDate current date as given by [Sys.Date]
#'
dumpNcbiTax <- function(
reDumpThr,
ddir,
toDump=c("names.dmp"),
env=parent.frame(n=1),
curDate
){
dumpDir <- file.path(ddir, "taxdump")
if(file.exists(dumpDir)){
load(file.path(dumpDir, "dumpDate.rda"))
message("Last download: ", dumpDate)
if(curDate - dumpDate > reDumpThr){
toDownload <- TRUE
}else{
toDownload <- FALSE
}
}else{
message("Not downloaded yet")
toDownload <- TRUE
}
if(toDownload){
if(file.exists(dumpDir)){
dumpDirBck <- paste0(dumpDir,"-BCK")
file.remove(list.files(path = dumpDirBck, full.names = T))
file.remove(dumpDirBck)
file.rename(dumpDir, dumpDirBck)
}
dir.create(dumpDir)
utils::download.file(
"https://ftp.ncbi.nlm.nih.gov/pub/taxonomy/taxdmp.zip",
file.path(dumpDir, "taxdmp.zip"),
quiet=TRUE
)
system(
sprintf('cd %s ; unzip taxdmp.zip ; cd -', dumpDir),
ignore.stdout=TRUE
)
dumpDate <- curDate
save(dumpDate, file=file.path(dumpDir, "dumpDate.rda"))
message("Data have been downloaded")
}else{
message("Existing data are going to be used")
}
## Data files
for(td in toDump){
lf <- file.path(dumpDir, td)
df <- file.path(dumpDir, paste0(td, ".rda"))
if(!file.exists(df)){
assign(td, utils::read.table(
lf,
sep="\t",
header=F,
stringsAsFactors=F,
quote="",
comment.char=""
))
save(list=td, file= df)
}
load(df, envir=env)
}
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/dumpNcbiTax.R |
#' Feeding BED: Dump and preprocess flat dat files fro Uniprot
#'
#' Not exported to avoid unintended modifications of the DB.
#'
#' @param taxOfInt the organism of interest. Only human ("9606"),
#' mouse ("10090") and rat ("10116") are supported
#' @param release the release of interest (check if already downloaded)
#' @param ddir path to the directory where the data should be saved
#' @param ftp location of the ftp site
#' @param env the R environment in which to load the tables when built
#'
dumpUniprotDb <- function(
taxOfInt,
release,
ddir,
ftp='ftp://ftp.expasy.org/databases/uniprot',
env=parent.frame(n=1)
){
## Defining taxonomic division of interest ----
taxDiv <- c(
"9606"="human",
"10090"="rodents",
"10116"="rodents",
"9823"="mammals",
"7955"="vertebrates"
)
taxOfInt <- match.arg(taxOfInt, names(taxDiv))
divOfInt <- taxDiv[taxOfInt]
toDl <- c(
sprintf("uniprot_sprot_%s.dat.gz", divOfInt),
sprintf("uniprot_trembl_%s.dat.gz", divOfInt)
)
## Download files if necessary ----
ftp <- sprintf("%s/current_release/knowledgebase/taxonomic_divisions", ftp)
dumpDir <- file.path(ddir, "Uniprot-DATA")
if(file.exists(dumpDir)){
load(file.path(dumpDir, "dumpRelease.rda"))
message("Last release: ", dumpRelease)
if(release != dumpRelease){
toDownload <- TRUE
}else{
toDownload <- FALSE
}
}else{
message("Not downloaded yet")
toDownload <- TRUE
}
if(toDownload){
if(file.exists(dumpDir)){
dumpDirBck <- paste0(dumpDir,"-BCK")
file.remove(list.files(path = dumpDirBck, full.names = T))
file.remove(dumpDirBck)
file.rename(dumpDir, dumpDirBck)
}
dir.create(dumpDir)
dumpRelease <- release
save(dumpRelease, file=file.path(dumpDir, "dumpRelease.rda"))
message("Data have been downloaded")
}else{
message("Existing data are going to be used")
}
##
for(f in toDl){
lf <- file.path(dumpDir, f)
if(!file.exists(lf)){
utils::download.file(
url=file.path(ftp, f),
destfile=lf,
method="wget",
quiet=T
)
}
}
## Parse files if necessary ----
parse_unigz <- function(f){
con <- file(f, "r")
by <- 50000000
fuf <- character()
tuids <- tdeprecated <- trsCref <- tensCref <- c()
iteration <- 0
while(TRUE){
iteration <- iteration+1
message(sprintf("Iteration %s", iteration))
message(Sys.time())
uf <- readLines(con, n=by)
if(length(uf)==0){
close(con)
break()
}
uf <- c(fuf, uf)
nextval <- tail(which(uf=="//"),1) + 1
if(nextval <= length(uf)){
fuf <- uf[nextval:length(uf)]
}else{
fuf <- character()
}
uf.val <- sub(
"^[[:upper:]]{0,2} +",
"",
uf
)
uf.field <- sub(
" +.*$",
"",
uf
)
tokeep <- sort(which(
uf.field %in% c("ID", "AC", "DE", "OX", "DR") |
uf=="//"
))
uf.val <- uf.val[tokeep]
uf.field <- uf.field[tokeep]
ends <- which(uf.val=="//")
starts <- c(1, ends[-length(ends)]+1)
spluf <- apply(
data.frame(starts, ends-1),
1,
function(i){
return(data.frame(
field=uf.field[i[1]:i[2]],
val=uf.val[i[1]:i[2]],
stringsAsFactors=FALSE
))
}
)
## * IDs and information ----
ids <- unlist(lapply(
spluf,
function(x){
strsplit(
x[which(x$field=="AC"), "val"][1], split="; *"
)[[1]][1]
}
))
names(spluf) <- ids
##
symbols <- unlist(
lapply(spluf, function(x)x[which(x$field=="ID"), "val"])
)
status <- sub("[;] +.*$", "", sub("^[[:alnum:]_]* +", "", symbols))
symbols <- sub(" +.*$", "", symbols)
##
tax <- unlist(lapply(
spluf,
function(x){
ox <- unlist(
strsplit(x[which(x$field=="OX"), "val"], split="; *")
)
ox <- do.call(rbind, strsplit(ox, split="="))
ox[,2] <- sub(" +.*$", "", ox[,2])
return(ox[which(ox[,1]=="NCBI_TaxID"), 2])
}
))
if(length(tax)!=length(spluf)){
stop("Incoherence in NCBI tax")
}
##
recNames <- unlist(lapply(
spluf,
function(x){
toRet <- x$val[which(x$field=="DE")][1]
toRet <- sub(";.*$", "", sub("^.*Full=", "", toRet))
return(toRet)
}
))
recNames <- sub(" *[{].*$", "", recNames)
##
uids <- data.frame(
ID=ids,
symbol=symbols[ids],
status=status[ids],
name=recNames[ids],
tax=tax[ids],
stringsAsFactors=FALSE
)
## * Deprecated IDs ----
deprecated <- stack(lapply(
spluf,
function(x){
unlist(
strsplit(x[which(x$field=="AC"), "val"], split="; *")
)[-1]
}
))
deprecated$ind <- as.character(deprecated$ind)
colnames(deprecated) <- c("deprecated", "ID")
deprecated <- deprecated[,c("ID", "deprecated")]
## * RefSeq peptides mapping ----
rsCref <- stack(lapply(
spluf,
function(x){
rsLines <- grep(
"^RefSeq;", x$val[which(x$field=="DR")], value=TRUE
)
toRet <- sub("^RefSeq; *", "", rsLines)
toRet <- sub(";.*$", "", toRet)
toRet <- sub("[.].*$", "", toRet)
return(toRet)
}
))
rsCref$ind <- as.character(rsCref$ind)
colnames(rsCref) <- c("refseq", "ID")
rsCref <- rsCref[,c("ID", "refseq")]
## * Ensembl peptides mapping
ensCref <- stack(lapply(
spluf,
function(x){
eLines <- grep(
"^Ensembl;", x$val[which(x$field=="DR")], value=TRUE
)
toRet <- strsplit(eLines, split="; ")
toRet <- unlist(lapply(toRet, function(l)l[3]))
toRet <- sub("[.].*$", "", toRet)
return(toRet)
}
))
ensCref$ind <- as.character(ensCref$ind)
colnames(ensCref) <- c("ensembl", "ID")
ensCref <- ensCref[,c("ID", "ensembl")]
tuids <- rbind(tuids, uids)
tdeprecated <- rbind(tdeprecated, deprecated)
trsCref <- rbind(trsCref, rsCref)
tensCref <- rbind(tensCref, ensCref)
}
return(list(
uids=tuids,
deprecated=tdeprecated,
rsCref=trsCref,
ensCref=tensCref
))
}
pf <- sprintf("uniprotIds-%s.rda", divOfInt)
lpf <- file.path(dumpDir, pf)
if(!file.exists(lpf)){
## * Reading and original parsing ----
uids <- deprecated <- rsCref <- ensCref <- c()
for(f in toDl){
message(f)
toAdd <- parse_unigz(file.path(dumpDir, f))
uids <- rbind(uids, toAdd$uids)
deprecated <- rbind(deprecated, toAdd$deprecated)
rsCref <- rbind(rsCref, toAdd$rsCref)
ensCref <- rbind(ensCref, toAdd$ensCref)
}
## * Save parsed data ----
save(
list=c(
"uids",
"deprecated",
"rsCref",
"ensCref"
),
file=lpf
)
}
load(lpf, envir=env)
load(file.path(dumpDir, "dumpRelease.rda"), envir=env)
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/dumpUniprotDb.R |
#' Explore BE identifiers
#'
#' This function uses visNetwork to draw all the identifiers
#' corresponding to one BE (including ProbeID and BESymbol)
#'
#' @param id one ID for the BE
#' @param source the ID source database. **Guessed if not provided**
#' @param be the type of BE. **Guessed if not provided**
#' @param showProbes boolean. If TRUE, probes targeting any BEID are shown.
#' @param showBE boolean. If TRUE the Biological Entity corresponding to the
#' id is shown. If id is isolated (not mapped to any other ID or symbol)
#' BE is shown anyway.
#'
#' @examples \dontrun{
#' exploreBe("Gene", "100", "EntrezGene")
#' }
#'
#' @export
#'
exploreBe <- function(id, source, be, showBE=FALSE, showProbes=FALSE){
id <- as.character(id)
stopifnot(length(id)==1)
##
if(missing(be) || missing(source)){
toWarn <- TRUE
}else{
toWarn <- FALSE
}
guess <- guessIdScope(ids=id, be=be, source=source)
if(is.null(guess)){
stop("Could not find the provided id")
}
if(is.na(guess$be)){
stop(
"The provided id does not match the provided scope",
" (be, source or organism)"
)
}
be <- guess$be
source <- guess$source
organism <- guess$organism
if(toWarn){
warning(
"Guessing ID scope:",
sprintf("\n - be: %s", be),
sprintf("\n - source: %s", source),
sprintf("\n - organism: %s", organism)
)
}
##
if(be=="Probe"){
showProbes <- TRUE
}
netRows1 <- bedCall(
f=neo2R::cypher,
query=neo2R::prepCql(
sprintf(
'MATCH (s:%s {value:$id, %s:$db})',
paste0(be, "ID"),
ifelse(be=="Probe", "platform", "database")
),
'-[:is_replaced_by|is_associated_to|targets*0..]->()',
'-[:identifies]->(be)',
'WITH DISTINCT be',
'MATCH (be)<-[ir:identifies]-(di)',
'RETURN DISTINCT',
'id(ir) as id, type(ir) as type,',
'id(di) as start,',
'id(be) as end'
),
result="row",
parameters=list(id=id, db=source, can=TRUE)
)
if(nrow(netRows1)==0){
stop(sprintf(
'"%s" (id) not found as a "%s" (be) in "%s" database (source).',
id, be, source
))
}
netRows2 <- bedCall(
f=neo2R::cypher,
query=neo2R::prepCql(
'MATCH (di) WHERE id(di) IN $ids',
'MATCH (di)-[cr:corresponds_to]->(di2)',
'RETURN DISTINCT',
'id(cr) as id, type(cr) as type,',
'id(di) as start,',
'id(di2) as end'
),
result="row",
parameters=list(ids=unique(netRows1$start))
)
netRows3 <- bedCall(
f=neo2R::cypher,
query=neo2R::prepCql(
'MATCH (di) WHERE id(di) IN $ids',
'MATCH (di)<-[iir:is_replaced_by|is_associated_to*0..]-(ii)',
'UNWIND iir as iirr',
'MATCH (i1)-[iirr]->(i2)',
'RETURN DISTINCT',
'id(iirr) as id, type(iirr) as type,',
'id(i1) as start,',
'id(i2) as end'
),
result="row",
parameters=list(ids=unique(netRows1$start))
)
netRows4 <- bedCall(
f=neo2R::cypher,
query=neo2R::prepCql(
'MATCH (ai) WHERE id(ai) IN $ids',
'MATCH (ai)-[r:is_known_as {canonical:$can}]->(as:BESymbol)',
'RETURN DISTINCT',
'id(r) as id, type(r) as type,',
'id(ai) as start,',
'id(as) as end'
),
result="row",
parameters=list(
ids=unique(c(
netRows1$start,
netRows2$start, netRows2$end,
netRows3$start, netRows3$end
)),
can=TRUE
)
)
netRows5 <- bedCall(
f=neo2R::cypher,
query=neo2R::prepCql(
'MATCH (ai) WHERE id(ai) IN $ids',
'MATCH (ai)<-[r:targets]-(ap:ProbeID)',
'RETURN DISTINCT',
'id(r) as id, type(r) as type,',
'id(ai) as start,',
'id(ap) as end'
),
result="row",
parameters=list(
ids=unique(c(
netRows1$start,
netRows2$start, netRows2$end,
netRows3$start, netRows3$end
)),
can=TRUE
)
)
edges <- rbind(
netRows1, netRows2, netRows3, netRows4, netRows5
)
nodes <- bedCall(
f=neo2R::cypher,
query=neo2R::prepCql(
'MATCH (n) WHERE id(n) IN $ids',
'RETURN DISTINCT',
'id(n) as id, labels(n) as label,',
'n.value as value, n.database as database, n.platform as platform,',
'n.preferred as preferred'
),
result="row",
parameters=list(ids=unique(c(edges$start, edges$end)))
)
nodes$label <- gsub(" [|][|] ", "", gsub("BEID", "", nodes$label))
nodes$url <- getBeIdURL(
ids=nodes$value,
databases=nodes$database
)
if(!showProbes){
toRm <- nodes$id[which(nodes$label=="ProbeID")]
nodes <- nodes[which(!nodes$id %in% toRm),]
edges <- edges[which(!edges$start %in% toRm & !edges$end %in% toRm),]
}
if(!showBE){
if(nrow(nodes)<=2){
showBE <- TRUE
}else{
toRm <- nodes$id[which(nodes$label==be)]
nodes <- nodes[which(!nodes$id %in% toRm),]
edges <- edges[which(!edges$start %in% toRm & !edges$end %in% toRm),]
}
}
for(cn in colnames(nodes)){
if(is.character(nodes[[cn]])){
nodes[[cn]] <- ifelse(is.na(nodes[[cn]]), "", nodes[[cn]])
}
}
tpNodes <- nodes
colnames(tpNodes) <- c(
"id", "type", "label", "database", "platform", "preferred", "url"
)
tpNodes$source <- paste0(tpNodes$database, tpNodes$platform)
tpNodes$title <- paste0(
'<p>',
'<strong>',
tpNodes$type,
'</strong><br>',
ifelse(
tpNodes$label!="",
ifelse(
tpNodes$url!="",
paste0(
sprintf(
'<a href="%s" target="_blank">',
tpNodes$url
),
tpNodes$label,
'</a>'
),
tpNodes$label
),
""
),
ifelse(
tpNodes$source!="",
paste0(
'<br>',
'<emph>', tpNodes$source, '</emph>'
),
""
),
ifelse(
!is.na(as.logical(tpNodes$preferred)) & as.logical(tpNodes$preferred),
"<br>Preferred",
""
),
'</p>'
)
##
nshapes <- c(
if(showBE){c(be="diamond")}else{c()},
beid="dot",
BESymbol="box"
)
if(showBE){
names(nshapes) <- c(be, paste0(be, "ID"), "BESymbol")
}else{
names(nshapes) <- c(paste0(be, "ID"), "BESymbol")
}
if(showProbes){
nshapes <- c(nshapes, ProbeID="triangle")
}
tpNodes$shape <- nshapes[tpNodes$type]
##
ncolors <- c(
"#E2B845", "#E4AC77", "#67E781", "#E2DBE6", "#7E58DB",
"#B694E4", "#B4E5BC", "#7299E1", "#E56E40", "#62B0DB", "#D46EE2",
"#B2C0E7", "#E4E3C6", "#D8E742", "#D7699E", "#66E5B0", "#E6B7E0",
"#70D1E2", "#6778DF", "#80B652", "#E4E19E", "#E790DE", "#D8E577",
"#6EEADD", "#DA3FE3", "#9F6D5B", "#5EA88C", "#8535E7", "#7EEA49",
"#AB88A7", "#E24869", "#E547B1", "#BBE8E5", "#9DADA8", "#E3B9B0",
"#B1EA9A", "#557083", "#9F9F66", "#874C99", "#E68D97"
)
ncol <- length(unique(tpNodes$source))+2
ncolors <- rep(ncolors, (ncol %/% length(ncolors))+1)
ncolors <- ncolors[1:ncol]
names(ncolors) <- c(be, "BESymbol", unique(tpNodes$source))
tpNodes$color.background <- ifelse(
tpNodes$type==be, ncolors[be],
ifelse(
tpNodes$type=="BESymbol", ncolors["BESymbol"],
ifelse(
tpNodes$source!="",
ncolors[tpNodes$source],
"grey"
)
)
)
tpNodes$borderWidth <- 1
tpNodes[which(as.logical(tpNodes$preferred)),"borderWidth"] <- 4
tpNodes$borderWidthSelected <- 2
tpNodes[which(as.logical(tpNodes$preferred)),"borderWidthSelected"] <- 4
# tpNodes$color.background <- "#BB6ED4"
# tpNodes$color.background[which(tpNodes$type=="BESymbol")] <- "#DB9791"
# tpNodes$color.background[grep("ID", tpNodes$type)] <- "#B1DE79"
# tpNodes$color.background[which(tpNodes$type=="ProbeID")] <- "#A4D0D3"
tpNodes$color.border="black"
tpEdges <- edges
colnames(tpEdges) <- c("id", "title", "from", "to")
tpEdges$arrows <- "to"
tpEdges$dashes <- ifelse(
tpEdges$title %in% c("is_associated_to", "is_replaced_by"),
TRUE,
FALSE
)
toRet <- visNetwork::visNetwork(
nodes=tpNodes,
edges=tpEdges
)
toRet <- visNetwork::visInteraction(graph=toRet, selectable=TRUE)
toRet <- visNetwork::visOptions(
graph=toRet,
highlightNearest = TRUE,
nodesIdSelection=list(
selected=tpNodes$id[which(
tpNodes$label==id & tpNodes$source==source
)]
)
)
toRet <- visNetwork::visLegend(
graph=toRet,
addNodes=c(
lapply(
names(nshapes),
function(x){
return(list(
label=x,
shape=as.character(nshapes[x]),
color=as.character(ncolors[x])
))
}
),
# if(showProbes){
lapply(
setdiff(names(ncolors), c("", be, names(nshapes))),
function(x){
return(list(
label=x, shape="dot", color=as.character(ncolors[x])
))
}
)
# }else{
# list()
# }
),
ncol=ifelse(showProbes, 3, 2),
width=ifelse(showProbes, 0.3, 0.2),
position="left",
useGroups = FALSE
)
return(toRet)
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/exploreBe.R |
#' Explore the shortest convertion path between two identifiers
#'
#' This function uses visNetwork to draw all the shortest convertion paths
#' between two identifiers (including ProbeID).
#'
#' @param from.id the first identifier
#' @param to.id the second identifier
#' @param from the type of entity: `listBe()` or Probe.
#' **Guessed if not provided**
#' @param from.source the identifier source: database or platform.
#' **Guessed if not provided**
#' @param to the type of entity: `listBe()` or Probe.
#' **Guessed if not provided**
#' @param to.source the identifier source: database or platform.
#' **Guessed if not provided**
#' @param edgeDirection a logical value indicating if the direction of the
#' edges should be drawn.
#' @param verbose if TRUE the cypher query is shown
#'
#' @examples \dontrun{
#' exploreConvPath(
#' from.id="ENST00000413465",
#' from="Transcript", from.source="Ens_transcript",
#' to.id="ENSMUST00000108658",
#' to="Transcript", to.source="Ens_transcript"
#' )
#' }
#'
#' @export
#'
exploreConvPath <- function(
from.id,
to.id,
from,
from.source,
to,
to.source,
edgeDirection=FALSE,
verbose=FALSE
){
## Verifications
from.id <- as.character(from.id)
to.id <- as.character(to.id)
stopifnot(
length(from.id)==1,
length(to.id)==1
)
##
if(
missing(from) || missing(from.source)
){
toWarn <- TRUE
}else{
toWarn <- FALSE
}
guess <- guessIdScope(ids=from.id, be=from, source=from.source)
if(is.null(guess)){
stop("Could not find the provided from.id")
}
if(is.na(guess$be)){
stop(
"The provided from.id does not match the provided scope",
" (be, source or organism)"
)
}
from.source <- guess$source
from <- guess$be
from.organism <- guess$organism
if(toWarn){
warning(
'Guessing "from.id" scope:',
sprintf("\n - be: %s", from),
sprintf("\n - source: %s", from.source),
sprintf("\n - organism: %s", from.organism)
)
}
##
if(
missing(to) || missing(to.source)
){
toWarn <- TRUE
}else{
toWarn <- FALSE
}
guess <- guessIdScope(ids=to.id, be=to, source=to.source)
if(is.null(guess)){
stop("Could not find the provided to.id")
}
if(is.na(guess$be)){
stop(
"The provided to.id does not match the provided scope",
" (be, source or organism)"
)
}
to.source <- guess$source
to <- guess$be
to.organism <- guess$organism
if(toWarn){
warning(
'Guessing "to.id" scope:',
sprintf("\n - be: %s", to),
sprintf("\n - source: %s", to.source),
sprintf("\n - organism: %s", to.organism)
)
}
##
## From
if(from=="Probe"){
fqs <- "MATCH (f:ProbeID {value:$fromId, platform:$fromSource})"
fbe <- getTargetedBe(from.source)
}else{
fqs <- sprintf(
"MATCH (f:%s {value:$fromId, database:$fromSource})",
paste0(from, "ID")
)
fbe <- from
}
## To
if(to=="Probe"){
tqs <- "MATCH (t:ProbeID {value:$toId, platform:$toSource})"
tbe <- getTargetedBe(to.source)
}else{
tqs <- sprintf(
"MATCH (t:%s {value:$toId, database:$toSource})",
paste0(to, "ID")
)
tbe <- to
}
## Paths
inPath <- c(
"corresponds_to", "is_associated_to", "is_replaced_by",
"targets", "is_homolog_of"
)
if(fbe != "Gene"){
inPath <- c(inPath, genBePath(fbe, "Gene", onlyR=TRUE))
}
if(tbe != "Gene"){
inPath <- c(inPath, genBePath(tbe, "Gene", onlyR=TRUE))
}
if(fbe != tbe){
inPath <- c(inPath, genBePath(fbe, tbe, onlyR=TRUE))
}
inPath <- unique(inPath)
notInPath <- c(
"is_in", "is_recorded_in", "has",
"is_named", "is_known_as",
"identifies", "is_member_of"
)
pqs <- c(
"MATCH p=allShortestpaths((f)-[*0..]-(t))",
"WHERE ALL(r IN relationships(p) WHERE type(r) IN $inPath)"
# "WHERE NONE(r IN relationships(p) WHERE type(r) IN $notInPath)"
)
## Final query
rqs <- c(
'UNWIND relationships(p) as r',
'MATCH (s)-[r]->(e)',
'RETURN id(r) as id, type(r) as type,',
'id(s) as start, id(e) as end'
)
qs <- neo2R::prepCql(c(fqs, tqs, pqs, rqs))
if(verbose) cat(qs, fill=T)
netRes <- bedCall(
neo2R::cypher,
query=qs,
parameters=list(
fromId=from.id, fromSource=from.source,
toId=to.id, toSource=to.source,
inPath=as.list(inPath)
# notInPath=as.list(notInPath)
),
result="row"
)
## Plot the graph
if(is.null(netRes) || nrow(netRes)==0){
stop("Could not find any path between the two provided identifiers")
}
nodes <- bedCall(
f=neo2R::cypher,
query=neo2R::prepCql(
'MATCH (n) WHERE id(n) IN $ids',
'RETURN DISTINCT',
'id(n) as id, labels(n) as label,',
'n.value as value, n.database as database,',
'n.preferred as preferred,',
'n.platform as platform'
),
result="row",
parameters=list(ids=unique(c(netRes$start, netRes$end)))
)
nodes$label <- gsub(" [|][|] ", "", gsub("BEID", "", nodes$label))
for(cn in colnames(nodes)){
if(is.character(nodes[[cn]])){
nodes[[cn]] <- ifelse(is.na(nodes[[cn]]), "", nodes[[cn]])
}
}
nodes$url <- getBeIdURL(
ids=nodes$value,
databases=nodes$database
)
nodesSymbol <- c()
for(i in 1:nrow(nodes)){
if(
!nodes[i, "label"] %in%
c("GeneID", "TranscriptID", "PeptideID", "ObjectID")
){
nodesSymbol <- c(nodesSymbol, "")
}else{
qr <- bedCall(
neo2R::cypher,
query=neo2R::prepCql(c(
sprintf(
'MATCH (n:%s {value:"%s", database:"%s"})-[r:is_known_as]->(s)',
nodes[i, "label"], nodes[i, "value"], nodes[i, "database"]
),
'RETURN DISTINCT s.value as symbol, r.canonical as can'
))
)
if(!is.null(qr) && nrow(qr)>0){
nodesSymbol <- c(
nodesSymbol,
qr[order(qr$can, decreasing=T), "symbol"][1]
)
}else{
nodesSymbol <- c(nodesSymbol, "")
}
}
}
nodes$symbol <- nodesSymbol
edges <- netRes
tpNodes <- nodes
colnames(tpNodes) <- c(
"id", "type", "label", "database", "preferred",
"platform", "url", "symbol"
)
tpNodes$source <- paste0(tpNodes$database, tpNodes$platform)
tpNodes$title <- paste0(
'<p>',
'<strong>',
tpNodes$type,
'</strong><br>',
ifelse(
tpNodes$label!="",
ifelse(
!is.na(tpNodes$url),
paste0(
sprintf(
'<a href="%s" target="_blank">',
tpNodes$url
),
tpNodes$label,
'</a>'
),
tpNodes$label
),
""
),
ifelse(
tpNodes$source!="",
paste0(
'<br>',
'<emph>', tpNodes$source, '</emph>'
),
""
),
ifelse(
!is.na(as.logical(tpNodes$preferred)) & as.logical(tpNodes$preferred),
"<br>Preferred",
""
),
ifelse(
tpNodes$symbol!="",
paste0("<br>", tpNodes$symbol),
""
),
'</p>'
)
##
nshapes <- c(
GeneID="dot",
TranscriptID="diamond",
PeptideID="square",
ObjectID="star",
ProbeID="triangle"
)
nshapes <- nshapes[which(names(nshapes) %in% tpNodes$type)]
tpNodes$shape <- nshapes[tpNodes$type]
##
ncolors <- c(
"#E2B845", "#E4AC77", "#67E781", "#E2DBE6", "#7E58DB",
"#B694E4", "#B4E5BC", "#7299E1", "#E56E40", "#62B0DB", "#D46EE2",
"#B2C0E7", "#E4E3C6", "#D8E742", "#D7699E", "#66E5B0", "#E6B7E0",
"#70D1E2", "#6778DF", "#80B652", "#E4E19E", "#E790DE", "#D8E577",
"#6EEADD", "#DA3FE3", "#9F6D5B", "#5EA88C", "#8535E7", "#7EEA49",
"#AB88A7", "#E24869", "#E547B1", "#BBE8E5", "#9DADA8", "#E3B9B0",
"#B1EA9A", "#557083", "#9F9F66", "#874C99", "#E68D97"
)
ncol <- length(unique(tpNodes$source))
ncolors <- rep(ncolors, (ncol %/% length(ncolors))+1)
ncolors <- ncolors[1:ncol]
names(ncolors) <- c(unique(tpNodes$source))
tpNodes$color.background <- ifelse(
tpNodes$source!="",
ncolors[tpNodes$source],
"grey"
)
tpNodes$borderWidth <- 1
tpNodes[which(as.logical(tpNodes$preferred)),"borderWidth"] <- 4
tpNodes$borderWidthSelected <- 2
tpNodes[which(as.logical(tpNodes$preferred)),"borderWidthSelected"] <- 4
tpNodes$color.border="black"
tpEdges <- edges
colnames(tpEdges) <- c("id", "title", "from", "to")
if(edgeDirection){
tpEdges$arrows <- "to"
}else{
tpEdges$arrows <- ""
}
tpEdges$dashes <- ifelse(
tpEdges$title %in% c("is_associated_to", "is_replaced_by"),
TRUE,
FALSE
)
tpEdges$color <- ifelse(
tpEdges$title == "is_homolog_of",
"red",
"black"
)
toRet <- visNetwork::visNetwork(
nodes=tpNodes,
edges=tpEdges
)
toRet <- visNetwork::visInteraction(graph=toRet, selectable=TRUE)
toRet <- visNetwork::visOptions(
graph=toRet,
highlightNearest = TRUE
)
toRet <- visNetwork::visLegend(
graph=toRet,
addNodes=c(
lapply(
names(nshapes),
function(x){
return(list(
label=x,
shape=as.character(nshapes[x]),
color=as.character(ncolors[x])
))
}
),
lapply(
setdiff(names(ncolors), c("", names(nshapes))),
function(x){
return(list(
label=x, shape="dot", color=as.character(ncolors[x])
))
}
)
),
ncol=3,
width=0.3,
position="left",
useGroups = FALSE
)
return(toRet)
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/exploreConvPath.R |
#' Find Biological Entity
#'
#' Find Biological Entity in BED based on their IDs, symbols and names
#'
#' @param be optional. If provided the search is focused on provided BEs.
#' @param organism optional. If provided the search is focused on provided
#' organisms.
#' @param ncharSymb The minimum number of characters in searched to consider
#' incomplete symbol matches.
#' @param ncharName The minimum number of characters in searched to consider
#' incomplete name matches.
#' @param restricted boolean indicating if the results should be restricted to
#' current version of to BEID db. If FALSE former BEID are also returned:
#' **Depending on history it can take a very long time to return**
#' **a very large result!**
#' @param by number of found items to be converted into relevant IDs.
#' @param exclude database to exclude from possible selection. Used to filter
#' out technical database names such as "BEDTech_gene" and "BEDTech_transcript"
#' used to manage orphan IDs (not linked to any gene based on information
#' taken from sources)
#'
#' @return A data frame with the following fields:
#' - **found**: the element found in BED corresponding to the searched term
#' - **be**: the type of the element
#' - **source**: the source of the element
#' - **organism**: the related organism
#' - **entity**: the related entity internal ID
#' - **ebe**: the BE of the related entity
#' - **canonical**: if the symbol is canonical
#' - **Relevant ID**: the seeked element id
#' - **Symbol**: the symbol(s) of the corresponding gene(s)
#' - **Name**: the symbol(s) of the corresponding gene(s)
#'
#' Scope ("be", "source" and "organism") is provided as a named list
#' in the "scope" attributes: `attr(x, "scope")``
#'
#' @importFrom shiny fluidPage fluidRow column textInput checkboxInput uiOutput reactiveValues renderUI selectInput tags actionButton observe withProgress req isolate observeEvent runGadget stopApp dialogViewer p strong
#' @importFrom DT dataTableOutput renderDataTable datatable formatStyle styleEqual
#' @importFrom miniUI gadgetTitleBar
#' @export
#'
findBe <- function(
be=NULL, organism=NULL, ncharSymb=4, ncharName=8,
restricted=TRUE,
by=20,
exclude=c("BEDTech_gene", "BEDTech_transcript")
){
warning("Deprecated because it's too slow. Use `findBeids()` instead.")
require(BED)
if(!checkBedConn()){
stop()
}
#############################################
ui <- shiny::fluidPage(
miniUI::gadgetTitleBar("Find a Biological Entity"),
shiny::fluidRow(
shiny::column(
width=3,
shiny::textInput(
inputId="request",
label="Searched term",
placeholder="An ID, a symbol or name"
)
),
shiny::column(
width=3,
shiny::uiOutput("uiBe")
),
shiny::column(
width=3,
shiny::uiOutput("uiOrg")
),
shiny::column(
width=3,
shiny::uiOutput("uiSource")
)
),
shiny::fluidRow(
shiny::column(
width=12,
shiny::uiOutput(
outputId="renderRes"
)
)
),
shiny::fluidRow(
shiny::column(
width=7,
shiny::checkboxInput(
inputId="crossOrg",
label=shiny::p(
shiny::strong("Cross species search"),
shiny::tags$small(
"(time consuming and not relevant for complex objects
such as GO functions)"
)
),
value=FALSE
)
),
shiny::column(
width=5,
shiny::checkboxInput(
inputId="showGeneAnno",
label=shiny::p(
shiny::strong("Show gene annotation"),
shiny::tags$small(
"(not relevant for complex objects such as GO functions)"
)
),
value=FALSE
)
)
)
)
#############################################
server <- function(input, output, session) {
## Functions
orderSearch <- function(d, r, b, o, s){
d <- d[order(d$source==s, decreasing=TRUE),]
d <- d[order(d$be==b, decreasing=TRUE),]
d <- d[order(d$organism==o, decreasing=TRUE),]
d <- d[order(nchar(d$found)),]
d <- d[order(d$canonical, decreasing=TRUE),]
d <- d[order(toupper(d$found)==toupper(r), decreasing=TRUE),]
return(d)
}
highlightText <- function(text, value){
return(unlist(lapply(
text,
function(x){
if(is.na(x)){
return(x)
}
p <- gregexpr(value, x, ignore.case=TRUE)[[1]]
if(p[1]>0){
toRet <- c(substr(x, 0, p[1]-1))
for(i in 1:length(p)){
toRet <- c(
toRet,
'<mark style="background-color:yellow;font-weight:bold;">',
substr(x, p[i], p[i]+attr(p, "match.length")[i]-1),
'</mark>',
substr(
x,
p[i]+attr(p, "match.length")[i],
min(
p[i+1]-1,
nchar(x)+1,
na.rm=TRUE
)
)
)
}
toRet <- paste(toRet, collapse="")
}else{
toRet <- x
}
return(toRet)
}
)))
}
## Follow-up
curSel <- shiny::reactiveValues(
curSource=NULL,
searchRes=NULL,
selRes=NULL,
results=NULL
)
## Search input
output$uiBe <- shiny::renderUI({
return(shiny::selectInput(
inputId="uiBe",
label="BE of interest",
choices=c(listBe(), "Probe")
))
})
output$uiOrg <- shiny::renderUI({
return(shiny::selectInput(
inputId="uiOrg",
label="Organism of interest",
choices=listOrganisms()
))
})
output$uiSource <- shiny::renderUI({
be <- input$uiBe
shiny::req(be)
org <- input$uiOrg
shiny::req(org)
if(be=="Probe"){
lp <- listPlatforms()
choices <- lp$name
names(choices) <- paste0(
lp$description,
" (", lp$name, ")"
)
choices <- sort(choices)
}else{
choices <- sort(listBeIdSources(
be=be, organism=org,
exclude=exclude
)$database)
}
curSource <- shiny::isolate(curSel$curSource)
if(is.null(curSource)){
curSource <- NULL
}else{
curSource <- intersect(choices, curSource)
}
return(shiny::selectInput(
inputId="uiSource",
label="Source",
choices=choices,
selected=curSource
))
})
shiny::observe({
curSel$curSource <- input$uiSource
})
## Display output
output$renderRes <- shiny::renderUI({
searchRes <- curSel$searchRes
request <- input$request
results <- curSel$results
sel <- curSel$selRes
if(is.null(request) || request==""){
return(NULL)
}
if(is.null(searchRes) || nrow(searchRes)==0){
return(shiny::tags$span(
"Input text not found anywhere",
style='color:red;weight:bold;'
))
}
if(is.null(results) || nrow(results)==0){
if(max(sel) < nrow(searchRes)){
return(list(
shiny::tags$span(
sprintf(
"Could not find relevant IDs for the %s first terms shown below",
max(sel)
),
style='color:red;weight:bold;'
),
DT::dataTableOutput("dispRes"),
shiny::actionButton(
"nextRes",
label=sprintf(
"Try the next %s terms (%s not tried yet)",
by, nrow(searchRes)-max(sel)
)
)
))
}
return(list(
shiny::tags$span(
"Could not find relevant IDs for terms shown below",
style='color:red;weight:bold;'
),
DT::dataTableOutput("dispRes")
))
}else{
if(max(sel) < nrow(searchRes)){
return(list(
DT::dataTableOutput("dispRes"),
shiny::actionButton(
"nextRes",
label=sprintf(
"Get results for %s additional terms (%s not tried yet)",
by, nrow(searchRes)-max(sel)
)
)
))
}
return(DT::dataTableOutput("dispRes"))
}
return(toRet)
})
## Search a given term
shiny::observe({
curSel$searchRes <- NULL
curSel$results <- NULL
curSel$selRes <- NULL
shiny::req(input$request)
shiny::withProgress(
message="Finding BE",
value=0,
style="notification",
expr={
searchRes <- searchId(
searched=input$request,
be=be, organism=organism,
ncharSymb=ncharSymb, ncharName=ncharName
)
}
)
shiny::req(searchRes)
if(!input$crossOrg){
searchRes <- searchRes[which(searchRes$organism==input$uiOrg),]
}
ibe <- shiny::isolate(input$uiBe)
iorg <- shiny::isolate(input$uiOrg)
isrc <- shiny::isolate(input$uiSource)
searchRes <- orderSearch(
d=searchRes,
r=input$request,
b=ibe,
o=iorg,
s=isrc
)
curSel$searchRes <- searchRes
nsel <- sel <- 1:min(by, nrow(searchRes))
results <- try(getRelevantIds(
d=searchRes,
selected=nsel,
be=ibe, source=isrc, organism=iorg,
restricted=restricted
), silent=T)
curSel$selRes <- sel
shiny::req(!inherits(results, "try-error"))
# if(is.null(results) && max(sel) < nrow(searchRes)){
# shiny::withProgress(
# message="Searching for any relevant ID",
# value=max(sel)/nrow(searchRes),
# style="notification",
# expr={
# while(is.null(results) && max(sel) < nrow(searchRes)){
# nsel <- (max(sel)+1):min(max(sel)+10, nrow(searchRes))
# sel <- c(sel, nsel)
# results <- getRelevantIds(
# d=searchRes,
# selected=nsel,
# be=ibe, source=isrc, organism=iorg,
# restricted=restricted
# )
# setProgress(max(sel)/nrow(searchRes))
# }
# }
# )
# }
if(!is.null(results)){
colnames(results)[ncol(results)] <- "Relevant ID"
if(ibe=="Gene"){
desc <- getGeneDescription(
ids=setdiff(results$"Relevant ID", NA),
be=ibe,
source=isrc,
organism=iorg
)
rownames(desc) <- desc$id
colnames(desc) <- c(
"id", "Symbol", "Name", "Preferred",
"DB version", "Deprecated"
)
}else if(ibe=="Probe"){
desc <- getGeneDescription(
ids=setdiff(results$"Relevant ID", NA),
be=ibe,
source=isrc,
organism=iorg
)
rownames(desc) <- desc$id
gs <- colnames(desc)[2]
colnames(desc)[match(c("symbol", "name"), colnames(desc))] <-
paste0(
c("Symbol", "Name"),
" (", gs, ")"
)
desc <- desc[,-2]
}else{
ddesc <- getBeIdDescription(
ids=setdiff(results$"Relevant ID", NA),
be=ibe,
source=isrc,
organism=iorg
)
rownames(ddesc) <- ddesc$id
colnames(ddesc) <- c(
"id", "Symbol", "Name", "Preferred",
"DB version", "Deprecated"
)
ddesc <- ddesc[
,
which(apply(ddesc, 2, function(x) any(!is.na(x))))
]
if(input$showGeneAnno){
gdesc <- getGeneDescription(
ids=setdiff(results$"Relevant ID", NA),
be=ibe,
source=isrc,
organism=iorg
)
rownames(gdesc) <- gdesc$id
gs <- colnames(gdesc)[2]
colnames(gdesc)[match(c("symbol", "name"), colnames(gdesc))] <-
paste0(
c("Symbol", "Name"),
" (", gs, ")"
)
gdesc <- gdesc[,-2]
desc <- cbind(ddesc, gdesc[rownames(ddesc),])
}else{
desc <- ddesc
}
}
results <- cbind(results, desc[results$"Relevant ID", -1])
}
curSel$results <- results
curSel$selRes <- sel
})
shiny::observe({
ibe <- input$uiBe
iorg <- input$uiOrg
isrc <- input$uiSource
curSel$results <- NULL
curSel$selRes <- NULL
searchRes <- shiny::isolate(curSel$searchRes)
shiny::req(searchRes)
searchRes <- orderSearch(
d=searchRes,
r=shiny::isolate(input$request),
b=ibe,
o=iorg,
s=isrc
)
curSel$searchRes <- searchRes
nsel <- sel <- 1:min(by, nrow(searchRes))
results <- try(getRelevantIds(
d=searchRes,
selected=nsel,
be=ibe, source=isrc, organism=iorg,
restricted=restricted
), silent=TRUE)
curSel$selRes <- sel
shiny::req(!inherits(results, "try-error"))
# if(is.null(results) && max(sel) < nrow(searchRes)){
# shiny::withProgress(
# message="Searching for any relevant ID",
# value=max(sel)/nrow(searchRes),
# style="notification",
# expr={
# while(is.null(results) && max(sel) < nrow(searchRes)){
# nsel <- (max(sel)+1):min(max(sel)+10, nrow(searchRes))
# sel <- c(sel, nsel)
# results <- getRelevantIds(
# d=searchRes,
# selected=nsel,
# be=ibe, source=isrc, organism=iorg,
# restricted=restricted
# )
# setProgress(max(sel)/nrow(searchRes))
# }
# }
# )
# }
if(!is.null(results)){
colnames(results)[ncol(results)] <- "Relevant ID"
if(ibe=="Gene"){
desc <- getGeneDescription(
ids=setdiff(results$"Relevant ID", NA),
be=ibe,
source=isrc,
organism=iorg
)
rownames(desc) <- desc$id
colnames(desc) <- c(
"id", "Symbol", "Name", "Preferred",
"DB version", "Deprecated"
)
}else if(ibe=="Probe"){
desc <- getGeneDescription(
ids=setdiff(results$"Relevant ID", NA),
be=ibe,
source=isrc,
organism=iorg
)
rownames(desc) <- desc$id
gs <- colnames(desc)[2]
colnames(desc)[match(c("symbol", "name"), colnames(desc))] <-
paste0(
c("Symbol", "Name"),
" (", gs, ")"
)
desc <- desc[,-2]
}else{
ddesc <- getBeIdDescription(
ids=setdiff(results$"Relevant ID", NA),
be=ibe,
source=isrc,
organism=iorg
)
rownames(ddesc) <- ddesc$id
colnames(ddesc) <- c(
"id", "Symbol", "Name", "Preferred",
"DB version", "Deprecated"
)
ddesc <- ddesc[
,
which(apply(ddesc, 2, function(x) any(!is.na(x))))
]
if(input$showGeneAnno){
gdesc <- getGeneDescription(
ids=setdiff(results$"Relevant ID", NA),
be=ibe,
source=isrc,
organism=iorg
)
rownames(gdesc) <- gdesc$id
gs <- colnames(gdesc)[2]
colnames(gdesc)[match(c("symbol", "name"), colnames(gdesc))] <-
paste0(
c("Symbol", "Name"),
" (", gs, ")"
)
gdesc <- gdesc[,-2]
desc <- cbind(ddesc, gdesc[rownames(ddesc),])
}else{
desc <- ddesc
}
}
results <- cbind(results, desc[results$"Relevant ID", -1])
}
curSel$results <- results
curSel$selRes <- sel
})
shiny::observe({
shiny::req(input$nextRes)
ibe <- shiny::isolate(input$uiBe)
iorg <- shiny::isolate(input$uiOrg)
isrc <- shiny::isolate(input$uiSource)
searchRes <- shiny::isolate(curSel$searchRes)
shiny::req(searchRes)
results <- shiny::isolate(curSel$results)
sel <- shiny::isolate(curSel$selRes)
nsel <- (max(sel)+1):min(max(sel)+by, nrow(searchRes))
sel <- c(sel, nsel)
toAdd <- try(getRelevantIds(
d=searchRes,
selected=nsel,
be=ibe, source=isrc, organism=iorg,
restricted=restricted
), silent=TRUE)
curSel$selRes <- sel
shiny::req(!inherits(toAdd, "try-error"))
if(!is.null(toAdd)){
colnames(toAdd)[ncol(toAdd)] <- "Relevant ID"
if(ibe=="Gene"){
desc <- getGeneDescription(
ids=setdiff(toAdd$"Relevant ID", NA),
be=ibe,
source=isrc,
organism=iorg
)
rownames(desc) <- desc$id
colnames(desc) <- c(
"id", "Symbol", "Name", "Preferred",
"DB version", "Deprecated"
)
}else if(ibe=="Probe"){
desc <- getGeneDescription(
ids=setdiff(toAdd$"Relevant ID", NA),
be=ibe,
source=isrc,
organism=iorg
)
rownames(desc) <- desc$id
gs <- colnames(desc)[2]
colnames(desc)[match(c("symbol", "name"), colnames(desc))] <-
paste0(
c("Symbol", "Name"),
" (", gs, ")"
)
desc <- desc[,-2]
}else{
ddesc <- getBeIdDescription(
ids=setdiff(toAdd$"Relevant ID", NA),
be=ibe,
source=isrc,
organism=iorg
)
rownames(ddesc) <- ddesc$id
colnames(ddesc) <- c(
"id", "Symbol", "Name", "Preferred",
"DB version", "Deprecated"
)
ddesc <- ddesc[
,
which(apply(ddesc, 2, function(x) any(!is.na(x))))
]
if(input$showGeneAnno){
gdesc <- getGeneDescription(
ids=setdiff(toAdd$"Relevant ID", NA),
be=ibe,
source=isrc,
organism=iorg
)
rownames(gdesc) <- gdesc$id
gs <- colnames(gdesc)[2]
colnames(gdesc)[match(c("symbol", "name"), colnames(gdesc))] <-
paste0(
c("Symbol", "Name"),
" (", gs, ")"
)
gdesc <- gdesc[,-2]
desc <- cbind(ddesc, gdesc[rownames(ddesc),])
}else{
desc <- ddesc
}
}
toAdd <- cbind(toAdd, desc[toAdd$"Relevant ID", -1])
}
results <- rbind(results, toAdd)
results <- results[which(!duplicated(results$"Relevant ID")),]
curSel$results <- results
})
output$dispRes <- DT::renderDataTable({
searchRes <- curSel$searchRes
shiny::req(searchRes)
request <- shiny::isolate(input$request)
results <- curSel$results
foundColumns <- c("found", "be", "source", "organism", "canonical")
if(is.null(results) || nrow(results)==0){
toShow <- searchRes[,foundColumns]
}else{
toShow <- results[,c(
intersect(
colnames(results),
unique(c(
foundColumns,
"Relevant ID", "Preferred", "DB version", "Deprecated",
grep("symbol", colnames(results), value=T, ignore.case=T),
grep("name", colnames(results), value=T, ignore.case=T)
))
)
)]
tohl <- intersect(
colnames(results),
unique(c(
grep("symbol", colnames(results), value=T, ignore.case=T),
grep("name", colnames(results), value=T, ignore.case=T)
))
)
for(cn in tohl){
toShow[,cn] <- highlightText(toShow[,cn], request)
}
ridht <- highlightText(toShow$"Relevant ID", request)
ridurl <- getBeIdURL(
toShow$"Relevant ID",
shiny::isolate(input$uiSource)
)
toShow$"Relevant ID" <- ifelse(
is.na(ridurl),
ridht,
paste0(
sprintf(
'<a href="%s" target="_blank">',
ridurl
),
ridht,
'</a>'
)
)
}
toShow$found <- highlightText(toShow$found, request)
toShow$Found <- paste0(
toShow$found,
" (", toShow$be, " ",
ifelse(
is.na(toShow$canonical),
"",
ifelse(toShow$canonical, "canonical", "non-canonical")
), " ",
toShow$source,
" in ",
toShow$organism,
")"
)
toShow <- toShow[,c(
"Found",
setdiff(colnames(toShow), c("Found", foundColumns))
), drop=FALSE]
shown <- DT::datatable(
toShow,
rownames=FALSE,
extensions="Scroller",
escape=FALSE,
options=list(
deferRender=TRUE,
scrollY=230,
scrollX= TRUE,
scroller = TRUE,
dom=c("ti")
)
)
if("Relevant ID" %in% colnames(toShow)){
shown <- DT::formatStyle(
shown,
'Relevant ID',
color='darkblue',
backgroundColor='lightgrey',
fontWeight='bold'
)
}
if("Preferred" %in% colnames(toShow)){
shown <- DT::formatStyle(
shown,
'Preferred',
backgroundColor=DT::styleEqual(
c(1, 0), c('green', 'transparent')
)
)
}
shown
})
# Handle the Done button being pressed.
shiny::observeEvent(input$done, {
# Return the selected ID
toRet <- shiny::isolate(curSel$results)
if(is.null(toRet)){
shiny::stopApp(NULL)
}else{
sel <- shiny::isolate(input$dispRes_rows_selected)
attr(toRet, "scope") <- list(
be=shiny::isolate(input$uiBe),
source=shiny::isolate(input$uiSource),
organism=shiny::isolate(input$uiOrg)
)
shiny::stopApp(shiny::isolate(toRet[sel,]))
}
})
}
shiny::runGadget(
ui, server,
viewer = shiny::dialogViewer("Find BE", height=560, width=850)
)
# shiny::runGadget(ui, server)
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/findBe.R |
#' Find Biological Entity identifiers
#'
#' @param toGene focus on gene entities (default=TRUE): matches from other
#' BE are converted to genes.
#' @param ... parameters for [beidsServer]
#'
#' @return NULL if not any result, or a data.frame with the selected
#' values and the following column:
#'
#' - **value**: the BE identifier
#' - **preferred**: preferred identifier for the same BE in the same scope
#' - **be**: the type of biological entity
#' - **source**: the source of the identifier
#' - **organism**: the organism of the BE
#' - **canonical** (if toGene==TRUE): canonical gene product? (if known)
#' - **symbol**: the symbol of the identifier (if any)
#'
#' @importFrom shiny fluidPage reactiveValues observe renderUI uiOutput runGadget dialogViewer fluidRow column tags req isolate
#' @importFrom DT datatable renderDT DTOutput
#' @importFrom miniUI gadgetTitleBar
#' @import rstudioapi
#' @export
#'
findBeids <- function(toGene=TRUE, ...){
require(BED)
if(!checkBedConn()){
stop()
}
############################################################################@
## UI ----
ui <- shiny::fluidPage(
miniUI::gadgetTitleBar("Find Identifiers of a Biological Entity"),
beidsUI("be"),
shiny::uiOutput("resUI")
)
############################################################################@
## Server ----
server <- function(input, output, session) {
## Application state ----
appState <- shiny::reactiveValues(
## User choices
## Conversions
conv=NULL
)
## Search entities ----
found <- beidsServer("be", toGene=toGene, ...)
## Extend to all identifiers ----
shiny::observe({
matches <- found()
if(is.null(matches) || nrow(matches)==0){
conv <- NULL
}else{
if(toGene){
orthologs <- input$orthologs
if(is.null(orthologs)){
conv <- NULL
}else{
suppressWarnings(conv <- geneIDsToAllScopes(
entities=unique(matches$entity),
orthologs=orthologs
))
conv <- conv[,intersect(
c(
"value", "preferred", "be", "source", "organism",
"canonical", "symbol"
),
colnames(conv)
)]
}
}else{
suppressWarnings(conv <- beIDsToAllScopes(
entities=unique(matches$entity)
))
conv <- conv[,intersect(
c(
"value", "preferred", "be", "source", "organism",
"canonical", "symbol"
),
colnames(conv)
)]
}
}
appState$conv <- conv
})
## Result table ----
output$beoi <- DT::renderDT({
conv <- appState$conv
req(conv)
conv$be <- as.factor(conv$be)
conv$organism <- as.factor(conv$organism)
conv$source <- as.factor(conv$source)
DT::datatable(
conv,
rownames=FALSE,
selection="multiple",
filter="top",
options=list(
pageLength=5,
dom="tip",
autoWidth=TRUE
)
)
})
## Result UI ----
output$resUI <- shiny::renderUI({
matches <-found()
shiny::req(matches)
shiny::fluidRow(shiny::column(12,
shiny::fluidRow(
shiny::column(
6,
shiny::h4("Relevant identifiers")
),
if(toGene){
shiny::column(
6,
shiny::checkboxInput(
"orthologs", label="With orthologs",
value=TRUE
)
)
},
style="margin-top:25px;"
),
shiny::fluidRow(
shiny::column(
12,
DT::DTOutput(
"beoi"
)
)
)
))
})
## Done ----
shiny::observeEvent(input$done, {
# Return the selected ID
toRet <- shiny::isolate(appState$conv)
if(is.null(toRet) || nrow(toRet)==0){
shiny::stopApp(NULL)
}else{
sel <- shiny::isolate(input$beoi_rows_selected)
if(length(sel)>0){
toRet <- toRet[sel,]
}
shiny::stopApp(toRet)
}
})
}
shiny::runGadget(
ui, server,
viewer = shiny::dialogViewer("Find BE", height=800, width=1000)
)
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/findBeids.R |
#' First common upstream BE
#'
#' Returns the first common Biological Entity (BE) upstream a set of BE.
#'
#' This function is used to identified the level at which different BE should be
#' compared. Peptides and transcripts should be compared at the level of
#' transcripts whereas transcripts and objects should be compared at the
#' level of genes. BE from different organism should be compared at the level
#' of genes using homologs.
#'
#' @param beList a character vector containing BE
#' @param uniqueOrg a logical value indicating if as single organism is under
#' focus. If false "Gene" is returned.
#'
#' @examples \dontrun{
#' firstCommonUpstreamBe(c("Object", "Transcript"))
#' firstCommonUpstreamBe(c("Peptide", "Transcript"))
#' firstCommonUpstreamBe(c("Peptide", "Transcript"), uniqueOrg=FALSE)
#' }
#'
#' @seealso [listBe]
#'
#' @export
#'
firstCommonUpstreamBe <- function(beList=listBe(), uniqueOrg=TRUE){
if(!is.logical(uniqueOrg)){
stop("uniqueOrg should be a logical")
}
if(!is.atomic(beList) || length(beList)==0){
stop("beList should be a non-empty character vector")
}
##
if(!uniqueOrg){
return("Gene")
}
checkedBe <- match.arg(beList, several.ok=TRUE)
notFound <- setdiff(beList, checkedBe)
if(length(notFound)>0){
stop(paste(
"Could not find the following entities among possible BE:",
paste(notFound, collapse=", "),
"\nPossible BE: ", paste(listBe(), collapse=", ")
))
}
if(length(beList)==1){
return(beList)
}else{
cql <- 'MATCH (o:BEType)'
cid <- 0
for(be in beList){
cid <- cid+1
cql <- c(
cql,
sprintf(
'MATCH (%s:BEType {value:"%s"})',
paste0("be", cid), be
),
sprintf(
'MATCH (o)-[:produces*0..]->(%s)',
paste0("be", cid)
)
)
}
cql <- c(
cql,
'WITH o, be1',
'MATCH p=shortestPath((o)-[:produces*0..]->(be1))',
'RETURN o.value as be, length(p) as lp',
'ORDER BY lp'
)
cqRes <- bedCall(
neo2R::cypher,
query=neo2R::prepCql(cql)
)
return(cqRes[1,1])
}
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/firstCommonUpstreamBe.R |
#' Construct CQL sub-query to map 2 biological entity
#'
#' Internal use
#'
#' @param from one biological entity (BE)
#' @param to one biological entity (BE)
#' @param onlyR logical. If TRUE (default: FALSE) it returns only the names
#' of the relationships and not the cypher sub-query
#'
#' @return A character value corresponding to the sub-query.
#' Or, if onlyR, a character vector with the names of the relationships.
#'
#' @seealso [genProbePath], [listBe]
#'
genBePath <- function(from, to, onlyR=FALSE){
if(from==to){
stop('from and to should be different.')
}
cqRes <- bedCall(
neo2R::cypher,
query=neo2R::prepCql(c(
sprintf(
'MATCH (f:BEType {value:"%s"})',
from
),
sprintf(
'MATCH (t:BEType {value:"%s"})',
to
),
'MATCH p=shortestPath((f)-[:produces*1..]-(t))',
'UNWIND relationships(p) as r',
'MATCH (s)-[r]->(e)',
'RETURN id(r) as id, r.how as how,',
'id(s) as s_id, s.value, id(e) as e_id, e.value'
)),
result="row"
)
if(is.null(cqRes) || nrow(cqRes)==0){
stop("Cannot find any paths between from and to.")
}
rtable <- cqRes[,c("id", "s_id", "e_id", "how")]
colnames(rtable) <- c("id", "start", "end", "how")
stable <- cqRes[, c("s_id", "s.value")]
etable <- cqRes[, c("e_id", "e.value")]
colnames(stable) <- colnames(etable) <- c("id", "value")
ntable <- unique(rbind(stable, etable))
##################################
genCypher <- function(fid, usedR, onlyR){
curR <- rtable[which(
(rtable$start==fid | rtable$end==fid) & !rtable$id %in% usedR
),]
if(nrow(curR)>1){
stop("Several possible paths")
}
if(nrow(curR)==0){
if(onlyR){
return(c())
}else{
return("")
}
}
if(fid==curR$"start"){
toRet <- paste0('-[:', curR$how, ']->')
nid <- curR$end
}else{
toRet <- paste0('<-[:', curR$how, ']-')
nid <- curR$start
}
if(onlyR){
toRet <- curR$how
}
toApp <- genCypher(nid, c(usedR, curR$id), onlyR=onlyR)
if(onlyR){
toRet <- c(toRet, toApp)
}else{
if(toApp!=""){
toRet <- paste0(
toRet,
"(:", ntable$value[which(ntable$id==nid)],")",
toApp
)
}
}
return(toRet)
}
##################################
return(genCypher(
fid=ntable$id[which(ntable$value==from)],
usedR=c(),
onlyR=onlyR
))
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/genBePath.R |
#' Identify the biological entity (BE) targeted by probes and
#' construct the CQL sub-query to map probes to the BE
#'
#' Internal use
#'
#' @param platform the platform of the probes
#'
#' @return A character value corresponding to the sub-query.
#' The `attr(,"be")` correspond to the BE targeted by probes
#'
#' @seealso [genBePath], [listPlatforms]
#'
genProbePath <- function(platform){
be <- getTargetedBe(platform)
beid <- paste0(be, "ID")
qs <- sprintf(
'-[:targets]->(:%s)-[:is_replaced_by|is_associated_to*0..]->()-[:identifies]->',
beid
)
attr(qs, "be") <- be
return(qs)
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/genProbePath.R |
#' Find all GeneID, ObjectID, TranscriptID, PeptideID and ProbeID corresponding to a Gene in any organism
#'
#' @param geneids a character vector of gene identifiers
#' @param source the source of gene identifiers. **Guessed if not provided**
#' @param organism the gene organism. **Guessed if not provided**
#' @param entities a numeric vector of gene entity. If NULL (default),
#' geneids, source and organism arguments are used to identify genes.
#' Be carefull when using entities as these identifiers are not stable.
#' @param orthologs return identifiers from orthologs
#' @param canonical_symbols return only canonical symbols (default: TRUE).
#'
#' @return A data.frame with the following fields:
#'
#' - **value**: the identifier
#' - **preferred**: preferred identifier for the same BE in the same scope
#' - **be**: the type of BE
#' - **organism**: the BE organism
#' - **source**: the source of the identifier
#' - **canonical**: canonical gene product (logical)
#' - **symbol**: canonical symbol of the identifier
#' - **Gene_entity**: the gene entity input
#' - **GeneID** (optional): the gene ID input
#' - **Gene_source** (optional): the gene source input
#' - **Gene_organism** (optional): the gene organism input
#'
#' @export
#'
geneIDsToAllScopes <- function(
geneids,
source, organism,
entities=NULL,
orthologs=TRUE,
canonical_symbols=TRUE
){
stopifnot(
is.logical(orthologs), length(orthologs)==1, !is.na(orthologs)
)
if(is.null(entities)){
stopifnot(
is.character(geneids), all(!is.na(geneids)), length(geneids)>0
)
##
if(missing(source) || missing(organism)){
toWarn <- TRUE
}else{
toWarn <- FALSE
}
be <- "Gene"
guess <- guessIdScope(ids=geneids, be=be, source=source, organism=organism)
if(is.null(guess)){
warning("Could not find the provided ids")
if(missing(be) || missing(source) || missing(organism)){
stop("Missing be, source or organism information")
}
}else{
if(is.na(guess$be)){
warning(
"The provided ids does not match the provided scope",
" (be, source or organism)"
)
if(missing(be) || missing(source) || missing(organism)){
stop("Missing be, source or organism information")
}
}else{
be <- guess$be
source <- guess$source
organism <- guess$organism
}
}
if(toWarn){
warning(
"Guessing ID scope:",
sprintf("\n - be: %s", be),
sprintf("\n - source: %s", source),
sprintf("\n - organism: %s", organism)
)
}
##
if(source=="Symbol"){
stop('source cannot be "Symbol"')
}
query <- sprintf(paste(
'MATCH (gid:GeneID {database:"%s"})',
'-[:is_associated_to|is_replaced_by*0..]->()-[:identifies]->(g)',
'-[:belongs_to]->(:TaxID)',
'-[:is_named]->(o:OrganismName {value_up:"%s"})',
'WHERE gid.value IN $ids'
), source, toupper(organism))
ids <- geneids
}else{
stopifnot(
is.numeric(entities), all(!is.na(entities)), length(entities)>0
)
warning(
'Be carefull when using entities as these identifiers are ',
'not stable.'
)
query <- paste(
'MATCH (g:Gene) WHERE id(g) IN $ids'
)
ids <- unique(entities)
}
query <- paste(
query,
sprintf(
'MATCH (g)-[:identifies|is_member_of%s]-(ag:Gene)',
ifelse(orthologs, "*0..4", "*0")
),
'MATCH (ag)-[:codes_for|is_expressed_as|is_translated_in*0..3]->()',
'<-[:identifies]-()<-[:is_associated_to|is_replaced_by|targets*0..]-',
'(beid)',
'MATCH (ag)-[:belongs_to]->(:TaxID)',
'-[:is_named {nameClass:"scientific name"}]->(beo:OrganismName)',
sprintf(
'OPTIONAL MATCH (beid)-[k:is_known_as%s]->(bes)',
ifelse(canonical_symbols, " {canonical:true}", "")
),
'OPTIONAL MATCH',
'(beid)<-[p:codes_for|is_expressed_as|is_translated_in*1..2]-(:GeneID)',
'RETURN DISTINCT',
'beid.value as value, labels(beid) as be,',
'reduce(canonical=true, n IN p| canonical AND n.canonical) as canonical,',
'beid.database as db, beid.platform as pl,',
'beid.preferred as preferred,',
'bes.value as bes,',
'k.canonical as canBes,',
'beo.value as organism,',
'id(g) as Gene_entity'
)
if(is.null(entities)){
query <- paste(
query,
', gid.value as GeneID,',
'gid.database as Gene_source,',
'o.value as Gene_organism'
)
}
toRet <- bedCall(
neo2R::cypher, query=query, parameters=list(ids=as.list(ids))
)
if(!is.null(toRet)){
toRet <- dplyr::mutate(
toRet,
"be"=stringr::str_remove(
stringr::str_remove(toRet$be, "BEID [|][|] "),
"ID$"),
"source"=ifelse(is.na(toRet$db), toRet$pl, toRet$db)
)
toRet <- dplyr::select(toRet, -"db", -"pl")
##
# toRet1 <- toRet
toRet1 <- dplyr::arrange(toRet, desc(.data$canBes))
toRet1 <- dplyr::group_by(
toRet1,
.data$value, .data$preferred, .data$be,
.data$source, .data$organism, .data$Gene_entity
)
toRet1 <- dplyr::summarise_all(toRet1, function(x)x[1])
toRet1 <- dplyr::ungroup(toRet1)
toRet1 <- dplyr::select(toRet1, -"canBes")
# toRet1 <- dplyr::distinct(dplyr::select(toRet, "bes"))
toRet2 <- dplyr::select(toRet, -"value", -"preferred")
toRet2 <- dplyr::filter(toRet2, !is.na(toRet2$bes))
##
# toRet2 <- dplyr::mutate(
# toRet2, "value"=.data$bes, "preferred"=NA
# )
toRet2 <- dplyr::mutate(
toRet2,
"value"=.data$bes,
source="Symbol"
)
toRet2 <- dplyr::rename(toRet2, "preferred"="canBes")
##
toRet2 <- dplyr::mutate(toRet2, source="Symbol")
toRet2 <- dplyr::distinct(toRet2)
toRet <- dplyr::bind_rows(toRet1, toRet2)
toRet <- dplyr::rename(toRet, "symbol"="bes")
if(is.null(entities)){
toRet <- dplyr::select(
toRet, "value", "preferred", "be", "source", "organism",
"canonical", "symbol",
"Gene_entity",
"GeneID", "Gene_source", "Gene_organism"
)
}else{
toRet <- dplyr::select(
toRet, "value", "preferred", "be", "source", "organism",
"canonical", "symbol",
"Gene_entity"
)
}
}
return(toRet)
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/geneIDsToAllScopes.R |
###############################################################################@
#' Focus a BE related object on a specific identifier (BEID) scope
#'
#' @param x an object representing a collection of BEID (e.g. BEIDList)
#' @param be the type of biological entity to focus on.
#' Used if `is.null(scope)`
#' @param source the source of BEID to focus on.
#' Used if `is.null(scope)`
#' @param organism the organism of BEID to focus on.
#' Used if `is.null(scope)`
#' @param scope a list with the following element:
#' - **be**
#' - **source**
#' - **organism**
#'
#' @param force if TRUE the conversion is done even between identical scopes
#' (default: FALSE)
#' @param restricted if TRUE (default) the BEID are limited to current version
#' of the source
#' @param prefFilter if TRUE (default) the BEID are limited to prefered
#' identifiers when they exist
#' @param ... method specific parameters for BEID conversion
#'
#' @return Depends on the class of x
#'
#' @export
#'
focusOnScope <- function(
x,
be, source, organism,
scope,
force,
restricted, prefFilter,
...
){
UseMethod("focusOnScope", x)
}
###############################################################################@
#' Get the BEID scope of an object
#'
#' @param x an object representing a collection of BEID (e.g. BEIDList)
#' @param ... method specific parameters
#'
#' @export
#'
scope <- function(x, ...){
UseMethod("scope", x)
}
###############################################################################@
#' Get the BEID scopes of an object
#'
#' @param x an object representing a collection of BEID (e.g. BEIDList)
#' @param ... method specific parameters
#'
#' @return A tibble with 4 columns:
#'
#' - be
#' - source
#' - organism
#' - Freq
#'
#' @export
#'
scopes <- function(x, ...){
UseMethod("scopes", x)
}
###############################################################################@
#' Get object metadata
#'
#' @param x an object representing a collection of BEID (e.g. BEIDList)
#' @param ... method specific parameters
#'
#' @export
#'
metadata <- function(x, ...){
UseMethod("metadata", x)
}
###############################################################################@
#' Set object metadata
#'
#' @param x an object representing a collection of BEID (e.g. BEIDList)
#' @param value a data.frame with rownames or
#' a column "**.lname**" all in names of l.
#'
#' @export
#'
`metadata<-` <- function(x, value){
UseMethod("metadata<-", x)
}
###############################################################################@
#' Get the BEIDs from an object
#'
#' @param x an object representing a collection of BEID (e.g. BEIDList)
#' @param ... method specific parameters
#'
#' @return A tibble with at least 4 columns:
#'
#' - value
#' - be
#' - source
#' - organism
#' - ...
#'
#' @export
#'
BEIDs <- function(x, ...){
UseMethod("BEIDs", x)
}
###############################################################################@
#' Filter an object to keep only a set of BEIDs
#'
#' @param x an object representing a collection of BEID (e.g. BEIDList)
#' @param toKeep a vector of elements to keep
#' @param ... method specific parameters
#'
#' @export
#'
filterByBEID <- function(x, toKeep, ...){
UseMethod("filterByBEID", x)
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/generics.R |
#' List all the source databases of BE identifiers whatever the BE type
#'
#' @param recache boolean indicating if the CQL query should be run even if
#' the table is already in cache
#'
#' @return A data.frame indicating the BE related to the ID source (database).
#'
#' @seealso [listBeIdSources], [listPlatforms]
#'
#' @export
#'
getAllBeIdSources <- function(recache=FALSE){
fn <- sub(
sprintf("^%s[:][::]", utils::packageName()), "",
sub("[(].*$", "", deparse(sys.call(), nlines=1, width.cutoff=500L))
)
cql <- neo2R::prepCql(
'MATCH (n:BEID) RETURN DISTINCT n.database as database, labels(n) as BE'
)
tn <- fn
toRet <- cacheBedCall(
f=neo2R::cypher,
query=cql,
tn=tn,
recache=recache
)
toRet$BE <- sub(
"ID$", "",
sub(
"BEID [|][|] ", "",
sub(" [|][|] BEID", "", toRet$BE)
)
)
return(toRet)
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/getAllBeIdSources.R |
#' Get a conversion table between biological entity (BE) identifiers
#'
#' @param from one BE or "Probe"
#' @param to one BE or "Probe"
#' @param from.source the from BE ID database if BE or
#' the from probe platform if Probe
#' @param to.source the to BE ID database if BE or
#' the to probe platform if Probe
#' @param organism organism name
#' @param caseSensitive if TRUE the case of provided symbols
#' is taken into account
#' during the conversion and selection.
#' This option will only affect the conversion from "Symbol"
#' (default: caseSensitive=FALSE).
#' All the other conversion will be case sensitive.
#' @param canonical if TRUE, only returns the canonical "Symbol".
#' (default: FALSE)
#' @param restricted boolean indicating if the results should be restricted to
#' current version of to BEID db. If FALSE former BEID are also returned:
#' \strong{Depending on history it can take a very long time to return
#' a very large result!}
#' @param entity boolean indicating if the technical ID of to BE should be
#' returned
#' @param verbose boolean indicating if the CQL query should be displayed
#' @param recache boolean indicating if the CQL query should be run even if
#' the table is already in cache
#' @param filter character vector on which to filter from IDs.
#' If NULL (default), the result is not filtered:
#' all from IDs are taken into account.
#' @param limForCache if there are more filter than limForCache results are
#' collected for all IDs (beyond provided ids) and cached for futur queries.
#' If not, results are collected only for provided ids and not cached.
#'
#' @return a data.frame mapping BE IDs with the
#' following fields:
#'
#' - **from**: the from BE ID
#' - **to**: the to BE ID
#' - **entity**: (optional) the technical ID of to BE
#'
#' @examples \dontrun{
#' getBeIdConvTable(
#' from="Gene", from.source="EntrezGene",
#' to.source="Ens_gene",
#' organism="human"
#' )
#' }
#'
#' @seealso [getHomTable], [listBe], [listPlatforms], [listBeIdSources]
#'
#' @export
#'
getBeIdConvTable <- function(
from,
to=from,
from.source,
to.source,
organism,
caseSensitive=FALSE,
canonical=FALSE,
restricted=TRUE,
entity=TRUE,
verbose=FALSE,
recache=FALSE,
filter=NULL,
limForCache=100
){
fn <- sub(
sprintf("^%s[:][::]", utils::packageName()), "",
sub("[(].*$", "", deparse(sys.call(), nlines=1, width.cutoff=500L))
)
## Null results ----
nullRes <- data.frame(
from=character(),
to=character(),
preferred=logical(),
entity=character(),
# fika=logical(),
# tika=logical(),
stringsAsFactors=FALSE
)
## BE ----
if(from=="Probe"){
fromBE <- attr(genProbePath(platform=from.source), "be")
}else{
fromBE <- from
}
if(to=="Probe"){
toBE <- attr(genProbePath(platform=to.source), "be")
}else{
toBE <- to
}
## From ----
fbeid <- getBeIds(
be=from,
source=from.source,
organism=organism,
caseSensitive=caseSensitive,
restricted=FALSE,
entity=TRUE,
verbose=verbose,
recache=recache,
filter=filter,
limForCache=limForCache
)
if(is.null(fbeid) || nrow(fbeid)==0){
return(nullRes)
}
if(!"canonical" %in% colnames(fbeid)){
fbeid$canonical <- NA
}else{
if(canonical){
fbeid <- fbeid[which(fbeid$canonical),]
}
}
fbeid <- dplyr::rename(
fbeid,
"from"="id",
# "fpref"="preferred",
"entity"=!!fromBE,
"fika"="canonical"
)
fbeid <- dplyr::select(fbeid, "from", "fika", "entity")
## From fromBE to ----
bef <- unique(fbeid$entity)
if(fromBE!=toBE){
if(length(bef)>0 && length(bef)<=limForCache){
noCache <- TRUE
parameters <- list(filter=as.list(bef))
}else{
noCache <- FALSE
}
ftqs <- genBePath(from=fromBE, to=toBE)
ftqs <- c(
'MATCH',
sprintf('(fbe:%s)', fromBE),
ftqs,
sprintf('(tbe:%s)', toBE),
ifelse(
noCache,
'WHERE id(fbe) IN $filter',
''
),
'RETURN id(fbe) as fent, id(tbe) as tent'
)
if(noCache){
toRet <- bedCall(
neo2R::cypher,
neo2R::prepCql(ftqs),
parameters=parameters
)
}else{
tn <- gsub(
"[^[:alnum:]]", "_",
paste(
fn,
fromBE, toBE,
sep="_"
)
)
toRet <- cacheBedCall(
f=neo2R::cypher,
query=neo2R::prepCql(ftqs),
tn=tn,
recache=recache
)
}
if(is.null(toRet) || nrow(toRet)==0){
return(nullRes)
}
toRet <- dplyr::inner_join(
toRet, fbeid, by=c("fent"="entity")
)
toRet <- dplyr::select(toRet, -"fent")
bef <- unique(toRet$tent)
}
## To ----
tbeid <- getBeIds(
be=to,
source=to.source,
organism=organism,
caseSensitive=caseSensitive,
restricted=restricted,
entity=TRUE,
verbose=verbose,
recache=recache,
bef=bef,
limForCache=limForCache
)
if(is.null(tbeid) || nrow(tbeid)==0){
return(nullRes)
}
if(!"canonical" %in% colnames(tbeid)){
tbeid$canonical <- NA
}else{
if(canonical){
tbeid <- tbeid[which(tbeid$canonical),]
}
}
tbeid <- dplyr::rename(
tbeid,
"to"="id",
# "tpref"="preferred",
"entity"=!!toBE,
"tika"="canonical"
)
tbeid <- dplyr::select(tbeid, "to", "preferred", "tika", "entity")
## Joining ----
if(fromBE==toBE){
toRet <- dplyr::inner_join(
fbeid, tbeid, by="entity"
)
if(is.null(toRet) || nrow(toRet)==0){
return(nullRes)
}
}else{
toRet <- dplyr::inner_join(
tbeid, toRet, by=c("entity"="tent")
)
}
## Post-processing ----
toRet <- toRet[order(toRet$fika+toRet$tika, decreasing=TRUE),]
toRet$preferred <- as.logical(toRet$preferred)
##
if(caseSensitive){
toDel <- union(
which(
toRet$fika==0 &
(toRet$from) %in% (toRet$from[which(toRet$fika==1)])
),
which(
toRet$tika==0 &
(toRet$to) %in% (toRet$to[which(toRet$tika==1)])
)
)
}else{
toDel <- union(
which(
toRet$fika==0 &
toupper(toRet$from) %in% toupper(toRet$from[which(toRet$fika==1)])
),
which(
toRet$tika==0 &
toupper(toRet$to) %in% toupper(toRet$to[which(toRet$tika==1)])
)
)
}
if(length(toDel)>0){
toRet <- toRet[-toDel,]
}
##
toRet <- unique(
toRet[, setdiff(colnames(toRet), c("fika", "tika")), drop=FALSE]
)
if(!entity){
toRet <- unique(toRet[, setdiff(colnames(toRet), c("entity", "preferred"))])
}
##
return(toRet)
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/getBeIdConvTable.R |
#' Get description of Biological Entity identifiers
#'
#' This description can be used for annotating tables or graph based on BE IDs.
#'
#' @param ids list of identifiers
#' @param be one BE. **Guessed if not provided**
#' @param source the BE ID database. **Guessed if not provided**
#' @param organism organism name. **Guessed if not provided**
#' @param ... further arguments
#' for [getBeIdNames] and [getBeIdSymbols] functions
#'
#' @return a data.frame providing for each BE IDs
#' (row.names are provided BE IDs):
#'
#' - **id**: the BE ID
#' - **symbol**: the BE symbol
#' - **name**: the corresponding name
#'
#' @examples \dontrun{
#' getBeIdDescription(
#' ids=c("10", "100"),
#' be="Gene",
#' source="EntrezGene",
#' organism="human"
#' )
#' }
#'
#' @seealso [getBeIdNames], [getBeIdSymbols]
#'
#' @export
#'
getBeIdDescription <- function(
ids,
be,
source,
organism,
...
){
if(length(ids)==0){
# stop("ids should be a character vector with at least one value")
return(data.frame(
"id"=character(),
"symbol"=character(),
"name"=character(),
"preferred"=logical(),
"db.version"=character(),
"db.deprecated"=logical(),
stringsAsFactors=FALSE
))
}
##
if(missing(be) || missing(source) || missing(organism)){
toWarn <- TRUE
}else{
toWarn <- FALSE
}
guess <- guessIdScope(ids=ids, be=be, source=source, organism=organism)
if(is.null(guess)){
warning("Could not find the provided ids")
if(missing(be) || missing(source) || missing(organism)){
stop("Missing be, source or organism information")
}
}else{
if(is.na(guess$be)){
warning(
"The provided ids does not match the provided scope",
" (be, source or organism)"
)
if(missing(be) || missing(source) || missing(organism)){
stop("Missing be, source or organism information")
}
}else{
be <- guess$be
source <- guess$source
organism <- guess$organism
}
}
if(toWarn){
warning(
"Guessing ID scope:",
sprintf("\n - be: %s", be),
sprintf("\n - source: %s", source),
sprintf("\n - organism: %s", organism)
)
}
##
cnames <- getBeIdNames(
ids=ids,
be=be, source=source,
organism=organism,
restricted=FALSE,
...
)
cnames$preferred <- as.numeric(cnames$preferred)
cnames$preferred <- ifelse(is.na(cnames$preferred), 0, cnames$preferred)
cnames <- cnames[
order(cnames$direct + cnames$preferred, decreasing=T),
c("id", "name")
]
cnames <- cnames[!duplicated(cnames$id),]
if(!all(ids %in% cnames$id)){
stop("Could not find all IDs for names")
}
csymb <- getBeIdSymbols(
ids=ids,
be=be, source=source,
organism=organism,
restricted=FALSE,
...
)
csymb$preferred <- as.numeric(csymb$preferred)
csymb$preferred <- ifelse(is.na(csymb$preferred), 0, csymb$preferred)
csymb <- csymb[
order(csymb$direct + csymb$preferred + 0.5*csymb$canonical, decreasing=T),
c("id", "symbol")
]
csymb <- csymb[!duplicated(csymb$id),]
if(!all(ids %in% csymb$id)){
stop("Could not find all IDs for symbols")
}
toRet <- dplyr::inner_join(csymb, cnames, by="id")
beidDesc <- getBeIds(
be=be,
source=source,
organism=organism,
restricted=FALSE,
filter=ids
)
if(is.null(beidDesc)){
beidDesc <- data.frame(
id=ids,
preferred=NA,
db.version=NA,
db.deprecated=NA,
stringsAsFactors=FALSE
)
}
beidDesc <- unique(beidDesc[
,
c("id", "preferred", "db.version", "db.deprecated")
])
toRet <- dplyr::full_join(toRet, beidDesc, by="id")
rownames(toRet) <- toRet$id
return(toRet[ids,])
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/getBeIdDescription.R |
#' Get a table of biological entity (BE) identifiers and names
#'
#' @param be one BE
#' @param source the BE ID database
#' @param organism organism name
#' @param restricted boolean indicating if the results should be restricted to
#' direct names
#' @param entity boolean indicating if the technical ID of BE should be
#' returned
#' @param verbose boolean indicating if the CQL query should be displayed
#' @param recache boolean indicating if the CQL query should be run even if
#' the table is already in cache
#' @param filter character vector on which to filter id. If NULL (default),
#' the result is not filtered: all IDs are taken into account.
#'
#' @return a data.frame with the
#' following fields:
#'
#' - **id**: the from BE ID
#' - **name**: the BE name
#' - **direct**: false if the symbol is not directly associated to the BE ID
#' - **entity**: (optional) the technical ID of to BE
#'
#' @examples \dontrun{
#' getBeIdNameTable(
#' be="Gene",
#' source="EntrezGene",
#' organism="human"
#' )
#' }
#'
#' @seealso [getBeIdNames], [getBeIdSymbolTable]
#'
#' @export
#'
getBeIdNameTable <- function(
be,
source,
organism,
restricted,
entity=TRUE,
verbose=FALSE,
recache=FALSE,
filter=NULL
){
fn <- sub(
sprintf("^%s[:][::]", utils::packageName()), "",
sub("[(].*$", "", deparse(sys.call(), nlines=1, width.cutoff=500L))
)
## Organism
taxId <- getTaxId(name=organism)
if(length(taxId)==0){
stop("organism not found")
}
if(length(taxId)>1){
print(getOrgNames(taxId))
stop("Multiple TaxIDs match organism")
}
## Filter
if(length(filter)>0 && !inherits(filter, "character")){
stop("filter should be a character vector")
}
## Other verifications
echoices <- c(listBe())
match.arg(be, echoices)
match.arg(source, listBeIdSources(be, organism)$database)
## Entity
qs <- c(
sprintf(
paste0(
'MATCH (id:%s {database:"%s"})',
'-[:is_replaced_by|is_associated_to*0..]->()',
'-[:identifies]->(be:%s)'
),
paste0(be, "ID"), source, be
)
)
## Organism
oqs <- paste0(
'MATCH (og)',
'-[:belongs_to]->',
sprintf(
'(:TaxID {value:"%s"})',
taxId
)
)
if(be=="Gene"){
oqs <- c(
oqs,
'MATCH (be)-[*0]-(og)'
)
}else{
oqs <- c(
oqs,
paste0(
'MATCH (be)',
genBePath(from=be, to="Gene"),
'(og)'
)
)
}
qs <- c(qs, oqs)
## Filter
if(length(filter)>0){
qs <- c(qs, 'WHERE id.value IN $filter')
}
## Names
qs <- c(
qs,
'WITH DISTINCT id, be',
'MATCH (bes:BEName)<-[c:is_named]-(sid)',
'-[:is_associated_to*0..]->()-[:identifies]->(be)'
)
##
cql <- c(
qs,
paste(
'RETURN DISTINCT id.value as id, bes.value as name',
', id(id)=id(sid) as direct',
', sid.preferred as preferred',
', id(be) as entity'
)
)
if(verbose){
message(neo2R::prepCql(cql))
}
##
if(length(filter)==0){
tn <- gsub(
"[^[:alnum:]]", "_",
paste(
fn,
be, source,
taxId,
sep="_"
)
)
toRet <- unique(cacheBedCall(
f=neo2R::cypher,
query=neo2R::prepCql(cql),
tn=tn,
recache=recache
))
}else{
toRet <- bedCall(
f=neo2R::cypher,
query=neo2R::prepCql(cql),
parameters=list(filter=as.list(filter))
)
}
toRet <- unique(toRet)
##
if(!is.null(toRet)){
toRet$direct <- as.logical(toRet$direct)
# toRet <- toRet[order(toRet$direct, decreasing=T),]
.data <- NULL
toRet <- dplyr::arrange(toRet, dplyr::desc(.data$direct))
toRet <- dplyr::distinct(toRet, .data$id, .data$name, .keep_all=TRUE)
# toRet <- toRet[which(!duplicated(toRet[,c("id", "name")])),]
##
if(!entity){
toRet <- unique(toRet[
,
setdiff(colnames(toRet), c("entity"))
])
}
if(restricted){
toRet <- dplyr::filter(toRet, .data$direct)
# toRet <- toRet[which(toRet$direct),]
}
}
##
return(toRet)
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/getBeIdNameTable.R |
#' Get names of Biological Entity identifiers
#'
#' @param ids list of identifiers
#' @param be one BE. **Guessed if not provided**
#' @param source the BE ID database. **Guessed if not provided**
#' @param organism organism name. **Guessed if not provided**
#' @param limForCache if there are more ids than limForCache results are
#' collected for all IDs (beyond provided ids) and cached for futur queries.
#' If not, results are collected only for provided ids and not cached.
#' @param ... params for the [getBeIdNameTable] function
#'
#' @return a data.frame mapping BE IDs and names with the
#' following fields:
#'
#' - **id**: the BE ID
#' - **name**: the corresponding name
#' - **direct**: true if the name is directly related to the BE ID
#' - **entity**: (optional) the technical ID of to BE
#'
#' @examples \dontrun{
#' getBeIdNames(
#' ids=c("10", "100"),
#' be="Gene",
#' source="EntrezGene",
#' organism="human"
#' )
#' }
#'
#' @seealso [getBeIdNameTable], [getBeIdSymbols]
#'
#' @export
#'
getBeIdNames <- function(
ids,
be,
source,
organism,
limForCache=4000,
...
){
ids <- setdiff(ids, NA)
##
if(missing(be) || missing(source) || missing(organism)){
toWarn <- TRUE
}else{
toWarn <- FALSE
}
guess <- guessIdScope(ids=ids, be=be, source=source, organism=organism)
if(is.null(guess)){
warning("Could not find the provided ids")
if(missing(be) || missing(source) || missing(organism)){
stop("Missing be, source or organism information")
}
}else{
if(is.na(guess$be)){
warning(
"The provided ids does not match the provided scope",
" (be, source or organism)"
)
if(missing(be) || missing(source) || missing(organism)){
stop("Missing be, source or organism information")
}
}else{
be <- guess$be
source <- guess$source
organism <- guess$organism
}
}
if(toWarn){
warning(
"Guessing ID scope:",
sprintf("\n - be: %s", be),
sprintf("\n - source: %s", source),
sprintf("\n - organism: %s", organism)
)
}
##
prepNotFound <- function(x, entity){
toRet <- data.frame(
id=x,
name=NA,
direct=NA,
preferred=NA,
stringsAsFactors=F,
check.names=F
)
if(entity){
toRet$entity <- NA
}
return(toRet)
}
if(length(ids) > limForCache){
toRet <- getBeIdNameTable(
be=be, source=source, organism=organism,
...
)
}else{
toRet <- getBeIdNameTable(
be=be, source=source, organism=organism,
filter=ids,
...
)
}
if(is.null(toRet)){
toRet <- prepNotFound(ids, entity=TRUE)
}else{
toRet <- toRet[which(toRet$id %in% ids),]
notFound <- setdiff(ids, toRet$id)
if(length(notFound) > 0){
notFound <- prepNotFound(notFound, "entity" %in% colnames(toRet))
toRet <- rbind(toRet, notFound)
}
}
return(toRet)
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/getBeIdNames.R |
#' Get a table of biological entity (BE) identifiers and symbols
#'
#' @param be one BE
#' @param source the BE ID database
#' @param organism organism name
#' @param restricted boolean indicating if the results should be restricted to
#' direct symbols
#' @param entity boolean indicating if the technical ID of BE should be
#' returned
#' @param verbose boolean indicating if the CQL query should be displayed
#' @param recache boolean indicating if the CQL query should be run even if
#' the table is already in cache
#' @param filter character vector on which to filter id. If NULL (default),
#' the result is not filtered: all IDs are taken into account.
#'
#' @return a data.frame with the
#' following fields:
#'
#' - **id**: the from BE ID
#' - **symbol**: the BE symbol
#' - **canonical**: true if the symbol is canonical for the direct BE ID
#' - **direct**: false if the symbol is not directly associated to the BE ID
#' - **entity**: (optional) the technical ID of to BE
#'
#' @examples \dontrun{
#' getBeIdSymbolTable(
#' be="Gene",
#' source="EntrezGene",
#' organism="human"
#' )
#' }
#'
#' @seealso [getBeIdSymbols], [getBeIdNameTable]
#'
#' @export
#'
getBeIdSymbolTable <- function(
be,
source,
organism,
restricted,
entity=TRUE,
verbose=FALSE,
recache=FALSE,
filter=NULL
){
fn <- sub(
sprintf("^%s[:][::]", utils::packageName()), "",
sub("[(].*$", "", deparse(sys.call(), nlines=1, width.cutoff=500L))
)
## Organism
taxId <- getTaxId(name=organism)
if(length(taxId)==0){
stop("organism not found")
}
if(length(taxId)>1){
print(getOrgNames(taxId))
stop("Multiple TaxIDs match organism")
}
## Filter
if(length(filter)>0 && !inherits(filter, "character")){
stop("filter should be a character vector")
}
## Other verifications
echoices <- c(listBe())
match.arg(be, echoices)
match.arg(source, listBeIdSources(be, organism)$database)
## Entity
qs <- c(
sprintf(
paste0(
'MATCH (id:%s {database:"%s"})',
'-[:is_replaced_by|is_associated_to*0..]->()',
'-[:identifies]->(be:%s)'
),
paste0(be, "ID"), source, be
)
)
## Organism
oqs <- paste0(
'MATCH (og)',
'-[:belongs_to]->',
sprintf(
'(:TaxID {value:"%s"})',
taxId
)
)
if(be=="Gene"){
oqs <- c(
oqs,
'MATCH (be)-[*0]-(og)'
)
}else{
oqs <- c(
oqs,
paste0(
'MATCH (be)',
genBePath(from=be, to="Gene"),
'(og)'
)
)
}
qs <- c(qs, oqs)
## Filter
if(length(filter)>0){
qs <- c(qs, 'WHERE id.value IN $filter')
}
## Symbols
qs <- c(
qs,
'WITH DISTINCT id, be',
'MATCH (bes:BESymbol)<-[c:is_known_as]-(sid)',
'-[:is_associated_to*0..]->()-[:identifies]->(be)'
)
##
cql <- c(
qs,
paste(
'RETURN DISTINCT id.value as id, bes.value as symbol',
', c.canonical as canonical, id(id)=id(sid) as direct',
', sid.preferred as preferred',
', id(be) as entity'
)
)
if(verbose){
message(neo2R::prepCql(cql))
}
##
if(length(filter)==0){
tn <- gsub(
"[^[:alnum:]]", "_",
paste(
fn,
be, source,
taxId,
sep="_"
)
)
toRet <- cacheBedCall(
f=neo2R::cypher,
query=neo2R::prepCql(cql),
tn=tn,
recache=recache
)
}else{
toRet <- bedCall(
f=neo2R::cypher,
query=neo2R::prepCql(cql),
parameters=list(filter=as.list(filter))
)
}
toRet <- unique(toRet)
##
if(!is.null(toRet)){
toRet$canonical <- as.logical(toRet$canonical)
toRet$direct <- as.logical(toRet$direct)
# toRet <- toRet[order(toRet$direct, decreasing=T),]
.data <- NULL
toRet <- dplyr::arrange(toRet, dplyr::desc(.data$direct))
toRet <- dplyr::distinct(toRet, .data$id, .data$symbol, .keep_all=TRUE)
# toRet <- toRet[which(!duplicated(toRet[,c("id", "symbol")])),]
##
if(!entity){
toRet <- unique(toRet[, setdiff(colnames(toRet), c("entity"))])
}
if(restricted){
toRet <- dplyr::filter(toRet, .data$direct)
# toRet <- toRet[which(toRet$direct),]
}
}
##
return(toRet)
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/getBeIdSymbolTable.R |
#' Get symbols of Biological Entity identifiers
#'
#' @param ids list of identifiers
#' @param be one BE. **Guessed if not provided**
#' @param source the BE ID database. **Guessed if not provided**
#' @param organism organism name. **Guessed if not provided**
#' @param limForCache if there are more ids than limForCache. Results are
#' collected for all IDs (beyond provided ids) and cached for futur queries.
#' If not, results are collected only for provided ids and not cached.
#' @param ... params for the [getBeIdSymbolTable] function
#'
#' @return a data.frame with the
#' following fields:
#'
#' - **id**: the from BE ID
#' - **symbol**: the BE symbol
#' - **canonical**: true if the symbol is canonical for the direct BE ID
#' - **direct**: false if the symbol is not directly associated to the BE ID
#' - **entity**: (optional) the technical ID of to BE
#'
#' @examples \dontrun{
#' getBeIdSymbols(
#' ids=c("10", "100"),
#' be="Gene",
#' source="EntrezGene",
#' organism="human"
#' )
#' }
#'
#' @seealso [getBeIdSymbolTable], [getBeIdNames]
#'
#' @export
#'
getBeIdSymbols <- function(
ids,
be,
source,
organism,
limForCache=4000,
...
){
ids <- setdiff(ids, NA)
##
if(missing(be) || missing(source) || missing(organism)){
toWarn <- TRUE
}else{
toWarn <- FALSE
}
guess <- guessIdScope(ids=ids, be=be, source=source, organism=organism)
if(is.null(guess)){
warning("Could not find the provided ids")
if(missing(be) || missing(source) || missing(organism)){
stop("Missing be, source or organism information")
}
}else{
if(is.na(guess$be)){
warning(
"The provided ids does not match the provided scope",
" (be, source or organism)"
)
if(missing(be) || missing(source) || missing(organism)){
stop("Missing be, source or organism information")
}
}else{
be <- guess$be
source <- guess$source
organism <- guess$organism
}
}
if(toWarn){
warning(
"Guessing ID scope:",
sprintf("\n - be: %s", be),
sprintf("\n - source: %s", source),
sprintf("\n - organism: %s", organism)
)
}
##
prepNotFound <- function(x, entity){
toRet <- data.frame(
id=x,
symbol=NA,
canonical=NA,
direct=NA,
preferred=NA,
stringsAsFactors=F,
check.names=F
)
if(entity){
toRet$entity <- NA
}
return(toRet)
}
if(length(ids) > limForCache){
toRet <- getBeIdSymbolTable(
be=be, source=source, organism=organism,
...
)
}else{
toRet <- getBeIdSymbolTable(
be=be, source=source, organism=organism,
filter=ids,
...
)
}
if(is.null(toRet)){
toRet <- prepNotFound(ids, entity=TRUE)
}else{
toRet <- toRet[which(toRet$id %in% ids),]
notFound <- setdiff(ids, toRet$id)
if(length(notFound) > 0){
notFound <- prepNotFound(notFound, "entity" %in% colnames(toRet))
toRet <- rbind(toRet, notFound)
}
}
return(toRet)
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/getBeIdSymbols.R |
#' Get reference URLs for BE IDs
#'
#' @param ids the BE ID
#' @param databases the databases from which each ID has been taken
#' (if only one database is provided it is chosen for all ids)
#'
#' @return A character vector of the same length than ids
#' corresponding to the relevant URLs.
#' NA is returned is there is no URL corresponding to the provided database.
#'
#' @examples \dontrun{
#' getBeIdURL(c("100", "ENSG00000145335"), c("EntrezGene", "Ens_gene"))
#' }
#'
#' @export
#'
getBeIdURL <- function(ids, databases){
stopifnot(
length(databases)==1 | length(databases)==length(ids)
)
dbs <- bedCall(
f=neo2R::cypher,
query=neo2R::prepCql("MATCH (db:BEDB) RETURN db.name, db.idURL")
)
baseUrls <- dbs[match(databases, dbs$db.name), ]$"db.idURL"
if(length(databases)==1){
baseUrls <- rep(baseUrls, length(ids))
}
ifelse(
!is.na(baseUrls),
sprintf(baseUrls, ids),
rep(NA, length(ids))
)
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/getBeIdURL.R |
#' Get biological entities identifiers
#'
#' @param be one BE or "Probe"
#' @param source the BE ID database or "Symbol" if BE or
#' the probe platform if Probe
#' @param organism organism name
#' @param restricted boolean indicating if the results should be restricted to
#' current version of to BEID db. If FALSE former BEID are also returned.
#' @param entity boolean indicating if the technical ID of BE should be
#' returned
#' @param attributes a character vector listing attributes that should be
#' returned.
#' @param verbose boolean indicating if the CQL query should be displayed
#' @param recache boolean indicating if the CQL query should be run even if
#' the table is already in cache
#' @param filter character vector on which to filter id. If NULL (default),
#' the result is not filtered: all IDs are taken into account.
#' @param caseSensitive if TRUE the case of provided symbols
#' is taken into account.
#' This option will only affect "Symbol" source
#' (default: caseSensitive=FALSE).
#' @param limForCache if there are more filter than limForCache results are
#' collected for all IDs (beyond provided ids) and cached for futur queries.
#' If not, results are collected only for provided ids and not cached.
#' @param bef For internal use only
#'
#' @return a data.frame mapping BE IDs with the
#' following fields:
#'
#' - **id**: the BE ID
#' - **BE**: IF entity is TRUE the technical ID of BE
#' - **db.version**: IF be is not "Probe" and source not "Symbol"
#' the version of the DB
#' - **db.deprecated**: IF be is not "Probe" and source not "Symbol"
#' a value if the BE ID is deprecated or FALSE if it's not
#' - **canonical**: IF source is "Symbol" TRUE if the symbol is canonical
#' - **organism**: IF be is "Probe" the organism of the targeted BE
#'
#' If attributes are part of the query, additional columns for each of them.
#' Scope ("be", "source" and "organism") is provided as a named list
#' in the "scope" attributes: `attr(x, "scope")`
#'
#' @examples \dontrun{
#' beids <- getBeIds(be="Gene", source="EntrezGene", organism="human", restricted=TRUE)
#' }
#'
#' @seealso [listPlatforms], [listBeIdSources]
#'
#' @export
#'
getBeIds <- function(
be=c(listBe(), "Probe"),
source,
organism=NA,
restricted,
entity=TRUE,
attributes=NULL,
verbose=FALSE,
recache=FALSE,
filter=NULL,
caseSensitive=FALSE,
limForCache=100,
bef=NULL
){
fn <- sub(
sprintf("^%s[:][::]", utils::packageName()), "",
sub("[(].*$", "", deparse(sys.call(), nlines=1, width.cutoff=500L))
)
## Other verifications
bentity <- match.arg(be)
bedSources <- c(
getAllBeIdSources(recache=recache)$database,
listPlatforms()$name,
"Symbol"
)
# source <- match.arg(source, bedSources)
if(!is.atomic(source) || length(source)!=1){
stop("source should be a character vector of length one")
}
if(!is.logical(restricted) || length(restricted)!=1){
stop("restricted should be a logical vector of length one")
}
if(!is.logical(entity) || length(entity)!=1){
stop("entity should be a logical vector of length one")
}
if(!is.logical(verbose) || length(verbose)!=1){
stop("verbose should be a logical vector of length one")
}
if(!is.logical(recache) || length(recache)!=1){
stop("recache should be a logical vector of length one")
}
if(be=="Probe" || source=="Symbol"){
attributes <- NULL
}else{
attributes <- intersect(attributes, listDBAttributes(source))
}
## Filter
noCache <- FALSE
if(length(filter)>0){
if(length(bef)>0){
stop("Cannot set filter and bef together")
}
if(!inherits(filter, "character")){
stop("filter should be a character vector")
}
if(source=="Symbol" & !caseSensitive){
filter <- toupper(filter)
}
FILT <- "beid"
if(length(filter)<=limForCache){
noCache <- TRUE
}
}
## Filter
if(length(bef)>0){
FILT <- "be"
if(length(bef)<=limForCache){
noCache <- TRUE
}
}
## Organism
if(!is.atomic(organism) || length(organism)!=1){
stop("organism should be a character vector of length one")
}
# if(is.na(organism) && bentity!="Probe"){
# stop("organism should be given for non 'Probe' entities")
# }
# if(!is.na(organism) && bentity=="Probe"){
# warning("organism won't be taken into account to retrieve probes")
# organism <- NA
# }
if(is.na(organism)){
taxId <- NA
}else{
taxId <- getTaxId(name=organism)
if(length(taxId)==0){
stop("organism not found")
}
if(length(taxId)>1){
print(getOrgNames(taxId))
stop("Multiple TaxIDs match organism")
}
}
parameters <- list(
taxId=taxId,
beSource=source
)
if(noCache){
if(FILT=="beid"){
parameters$filter <- as.list(as.character(filter))
}else{
parameters$filter <- as.list(bef)
}
}
if(bentity != "Probe"){
be <- bentity
beid <- paste0(be, "ID")
if(source=="Symbol"){
cql <- c(
sprintf(
'MATCH (n:BESymbol)<-[ika:is_known_as]-(:%s)',
beid
)
)
}else{
cql <- sprintf('MATCH (n:%s {database:$beSource})', beid)
}
cql <- c(
cql,
ifelse(
restricted,
'-[:is_associated_to*0..]->',
'-[:is_replaced_by|is_associated_to*0..]->'
),
'(ni)',
'-[:identifies]->(be)'
)
}else{
qs <- genProbePath(platform=source)
be <- attr(qs, "be")
cql <- paste0(
'MATCH (n:ProbeID {platform:$beSource})',
qs,
sprintf('(be:%s)', be)
)
}
cql <- c(
cql,
ifelse(
be=="Gene",
'',
ifelse(
!is.na(organism) || bentity=="Probe",
'<-[cr:codes_for|is_expressed_as|is_translated_in*1..2]-(g:Gene)',
''
)
),
# ifelse(
# bentity!="Probe",
# ifelse(
# !is.na(organism),
# '-[:belongs_to]->(:TaxID {value:$taxId})',
# ''
# ),
# '-[:belongs_to]->()-[:is_named {nameClass:"scientific name"}]->(o)'
# ),
ifelse(
!is.na(organism),
'-[:belongs_to]->(:TaxID {value:$taxId})',
''
),
ifelse(
noCache,
ifelse(
FILT=="beid",
sprintf(
'WHERE n.%s IN $filter',
ifelse(
source=="Symbol" & !caseSensitive,
"value_up",
"value"
)
),
'WHERE id(be) IN $filter'
),
""
),
ifelse(
bentity!="Probe" && source!="Symbol",
'OPTIONAL MATCH (n)-[db:is_recorded_in]->()',
''
)
)
##
for(at in attributes){
cql <- c(
cql,
sprintf(
'OPTIONAL MATCH (n)-[%s:has]->(:Attribute {name:"%s"})',
gsub("[^[:alnum:] ]", "_", at), at
)
)
}
##
cql <- c(
cql,
'RETURN DISTINCT n.value as id, n.preferred as preferred',
sprintf(
', id(be) as %s',
be
),
ifelse(
bentity!="Probe" && source!="Symbol",
', db.version, db.deprecated',
''
)#,
# ifelse(
# bentity=="Probe",
# # is.na(organism),
# ', o.value as organism',
# ''
# )
)
if(source=="Symbol"){
cql <- c(
cql,
", ika.canonical as canonical"
)
}
##
for(at in attributes){
cql <- c(
cql,
sprintf(
', %s.value as %s',
gsub("[^[:alnum:] ]", "_", at), gsub("[^[:alnum:] ]", "_", at)
)
)
}
if(verbose){
message(neo2R::prepCql(cql))
}
##
if(noCache){
toRet <- bedCall(
f=neo2R::cypher,
query=neo2R::prepCql(cql),
parameters=parameters
)
}else{
tn <- gsub(
"[^[:alnum:]]", "_",
paste(
fn,
bentity, source,
taxId,
ifelse(restricted, "restricted", "full"),
paste(attributes, collapse="-"),
sep="_"
)
)
toRet <- cacheBedCall(
f=neo2R::cypher,
query=neo2R::prepCql(cql),
tn=tn,
recache=recache,
parameters=parameters
)
}
toRet <- unique(toRet)
if(length(filter)>0 & !is.null(toRet)){
.data <- NULL
if(source=="Symbol" & !caseSensitive){
toRet <- dplyr::filter(
toRet,
toupper(.data$id) %in% filter
)
}else{
toRet <- dplyr::filter(
toRet,
.data$id %in% filter
)
}
}
if(length(bef)>0 & !is.null(toRet)){
toRet <- dplyr::filter(toRet, get(!!be) %in% !!bef)
}
##
if(!is.null(toRet)){
toRet$preferred <- as.logical(toRet$preferred)
toRet <- dplyr::arrange(toRet, get(!!be))
##
if(!entity){
toRet <- dplyr::distinct(dplyr::select(toRet, -!!be, -"preferred"))
}
attr(toRet, "scope") <- list(be=be, source=source, organism=organism)
}
##
return(toRet)
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/getBeIds.R |
#' Get the direct origin of BE identifiers
#'
#' The origin is directly taken as provided by the original database.
#' This function does not return indirect relationships.
#'
#' @param ids list of product identifiers
#' @param sources a character vector corresponding to the possible product ID
#' sources. If NULL (default), all sources are considered
#' @param process the production process among:
#' "is_expressed_as", "is_translated_in", "codes_for".
#'
#' @return a data.frame with the following columns:
#'
#' - **origin**: the origin BE identifiers
#' - **osource**: the origin database
#' - **product**: the product BE identifiers
#' - **psource**: the production database
#' - **canonical**: whether the production process is canonical or not
#'
#' The process is also returned as an attribute of the data.frame.
#'
#' @examples \dontrun{
#' oriId <- c("XP_016868427", "NP_001308979")
#' res <- getDirectOrigin(
#' ids=oriId,
#' source="RefSeq_peptide",
#' process="is_translated_in"
#' )
#' attr(res, "process")
#' }
#'
#' @seealso [getDirectOrigin], [convBeIds]
#'
#' @export
#'
getDirectOrigin <- function(
ids,
sources=NULL,
process=c("is_expressed_as", "is_translated_in", "codes_for")
){
process <- match.arg(process)
cql <- c(
sprintf('MATCH (f:BEID)-[p:%s]->(t:BEID)', process),
'WHERE t.value IN $ids'
)
if(!is.null(sources)){
cql <- c(
cql,
'AND t.database IN $sources'
)
}
cql <- c(
cql,
paste(
'RETURN f.value as origin, f.database as osource',
't.value as product, t.database as psource',
'p.canonical as canonical',
sep=", "
)
)
toRet <- bedCall(
f=neo2R::cypher,
query=neo2R::prepCql(cql),
parameters=list(
ids=as.list(unique(as.character(ids))),
sources=as.list(unique(as.character(sources)))
)
)
if(!is.null(toRet) && nrow(toRet)>0){
toRet$canonical <- as.logical(toupper(toRet$canonical))
attr(toRet, "process") <- process
}
return(toRet)
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/getDirectOrigin.R |
#' Get the direct product of BE identifiers
#'
#' The product is directly taken as provided by the original database.
#' This function does not return indirect relationships.
#'
#' @param ids list of origin identifiers
#' @param sources a character vector corresponding to the possible origin ID
#' sources. If NULL (default), all sources are considered
#' @param process the production process among:
#' "is_expressed_as", "is_translated_in", "codes_for".
#' @param canonical If TRUE returns only canonical production process.
#' If FALSE returns only non-canonical production processes.
#' If NA (default) canonical information is taken into account.
#'
#' @return a data.frame with the following columns:
#'
#' - **origin**: the origin BE identifiers
#' - **osource**: the origin database
#' - **product**: the product BE identifiers
#' - **psource**: the production database
#' - **canonical**: whether the production process is canonical or not
#'
#' The process is also returned as an attribute of the data.frame.
#'
#' @examples \dontrun{
#' oriId <- c("10", "100")
#' res <- getDirectProduct(
#' ids=oriId,
#' source="EntrezGene",
#' process="is_expressed_as",
#' canonical=NA
#' )
#' attr(res, "process")
#' }
#'
#' @seealso [getDirectOrigin], [convBeIds]
#'
#' @export
#'
getDirectProduct <- function(
ids,
sources=NULL,
process=c("is_expressed_as", "is_translated_in", "codes_for"),
canonical=NA
){
process <- match.arg(process)
cql <- c(
sprintf('MATCH (f:BEID)-[p:%s]->(t:BEID)', process),
'WHERE f.value IN $ids'
)
if(!is.null(sources)){
cql <- c(
cql,
'AND f.database IN $sources'
)
}
if(!is.na(canonical)){
if(!identical(canonical, TRUE) & !identical(canonical, FALSE)){
stop("canonical should be a logical of length 1")
}
cql <- c(
cql,
sprintf ('AND %s p.canonical', ifelse(canonical, "", "NOT"))
)
}
cql <- c(
cql,
paste(
'RETURN f.value as origin, f.database as osource',
't.value as product, t.database as psource',
'p.canonical as canonical',
sep=", "
)
)
toRet <- bedCall(
f=neo2R::cypher,
query=neo2R::prepCql(cql),
parameters=list(
ids=as.list(unique(as.character(ids))),
sources=as.list(unique(as.character(sources)))
)
)
if(!is.null(toRet) && nrow(toRet)>0){
toRet$canonical <- as.logical(toupper(toRet$canonical))
attr(toRet, "process") <- process
}
return(toRet)
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/getDirectProduct.R |
#' Feeding BED: Download Ensembl DB and load gene information in BED
#'
#' Not exported to avoid unintended modifications of the DB.
#'
#' @param organism character vector of 1 element corresponding to the organism
#' of interest (e.g. "Homo sapiens")
#' @param release the Ensembl release of interest (e.g. "83")
#' @param gv the genome version (e.g. "38")
#' @param ddir path to the directory where the data should be saved
#' @param dbCref a named vector of characters providing cross-reference DB of
#' interest. These DB are also used to find indirect ID associations.
#' @param dbAss a named vector of characters providing associated DB of
#' interest. Unlike the DB in dbCref parameter, these DB are not used for
#' indirect ID associations: the IDs are only linked to Ensembl IDs.
#' @param canChromosomes canonical chromosmomes to be considered as preferred
#' ID (e.g. c(1:22, "X", "Y", "MT") for human)
#'
getEnsemblGeneIds <- function(
organism,
release,
gv,
ddir,
dbCref,
dbAss,
canChromosomes
){
dbname <- "Ens_gene"
## Data files
attrib_type <- gene_attrib <- transcript <-
external_db <- gene <- translation <-
external_synonym <- object_xref <- xref <-
stable_id_event <- mapping_session <-
seq_region <- coord_system <- NULL
toDump <- c(
"attrib_type", "gene_attrib", "transcript",
"external_db", "gene", "translation",
"external_synonym", "object_xref", "xref",
"stable_id_event", "mapping_session",
"seq_region", "coord_system"
)
dumpEnsCore(organism, release, gv, ddir, toDump)
################################################@
## Current Ensembl database and organism ----
taxId <- getTaxId(organism)
################################################@
## Add stable IDs ----
message(Sys.time(), " --> Importing internal IDs")
toAdd <- seq_region[
match(gene$seq_region_id, seq_region$"seq_region_id"),
c("name", "coord_system_id")
]
toAdd <- cbind(
toAdd,
coord_system[
match(toAdd$"coord_system_id", coord_system$"coord_system_id"),
]
)
toAdd <- toAdd[,c(1, 5, 6)]
colnames(toAdd) <- c("region", "system", "genome")
toAdd$genome <- ifelse(toAdd$genome=="\\N", "", toAdd$genome)
gene <- cbind(gene, toAdd)
gene$"seq_region" <- sub(
"^ ", "", paste(toAdd$genome, toAdd$system, toAdd$region)
)
gene$preferred <- gene$region %in% canChromosomes
toImport <- unique(gene[, c("stable_id", "preferred"), drop=F])
colnames(toImport) <- c("id", "preferred")
loadBE(
d=toImport, be="Gene",
dbname=dbname,
version=release,
taxId=taxId
)
message(" Importing attribute")
toImport <- unique(gene[, c("stable_id", "seq_region"), drop=F])
colnames(toImport) <- c("id", "value")
loadBeAttribute(
d=toImport, be="Gene",
dbname=dbname,
attribute="seq_region"
)
################################################@
## Add cross references ----
for(ensDb in names(dbCref)){
db <- dbCref[ensDb]
message(Sys.time(), " --> ", ensDb)
dbid <- external_db$external_db_id[which(external_db$db_name == ensDb)]
takenXref <- xref[
which(xref$external_db_id == dbid),
c("xref_id", "dbprimary_acc")
]
if(nrow(takenXref)>0){
cref <- dplyr::inner_join(
takenXref,
object_xref[,c("ensembl_id", "xref_id")],
by="xref_id"
)
cref <- dplyr::inner_join(
cref,
gene[,c("stable_id", "gene_id")],
by=c("ensembl_id"="gene_id")
)[, c("dbprimary_acc", "stable_id")]
if(length(grep("Vega", ensDb))>0){
cref <- cref[
grep("^OTT", cref$dbprimary_acc),
]
}
if(nrow(cref) > 0){
cref <- unique(cref)
## NCBI cross-references
if(db=="EntrezGene"){
cref <- cleanDubiousXRef(cref)
}
## External DB IDs
toImport <- unique(cref[, "dbprimary_acc", drop=F])
colnames(toImport) <- "id"
toImport$id <- sub("HGNC[:]", "", sub("MGI[:]", "", toImport$id))
loadBE(
d=toImport, be="Gene",
dbname=db,
taxId=NA
)
## The cross references
toImport <- cref
colnames(toImport) <- c("id1", "id2")
toImport$id1 <- sub("HGNC[:]", "", sub("MGI[:]", "", toImport$id1))
loadCorrespondsTo(
d=toImport,
db1=db,
db2=dbname,
be="Gene"
)
}
}
}
################################################@
## Add associations ----
for(ensDb in names(dbAss)){
db <- dbAss[ensDb]
message(Sys.time(), " --> ", ensDb)
dbid <- external_db$external_db_id[which(external_db$db_name == ensDb)]
takenXref <- xref[
which(xref$external_db_id == dbid),
c("xref_id", "dbprimary_acc")
]
if(nrow(takenXref)>0){
cref <- dplyr::inner_join(
takenXref,
object_xref[,c("ensembl_id", "xref_id")],
by="xref_id"
)
cref <- dplyr::inner_join(
cref,
gene[,c("stable_id", "gene_id")],
by=c("ensembl_id"="gene_id")
)[, c("dbprimary_acc", "stable_id")]
if(length(grep("Vega", ensDb))>0){
cref <- cref[
grep("^OTT", cref$dbprimary_acc),
]
}
if(nrow(cref) > 0){
## External DB IDs
toImport <- unique(cref[, "dbprimary_acc", drop=F])
colnames(toImport) <- "id"
toImport$id <- sub("HGNC[:]", "", sub("MGI[:]", "", toImport$id))
loadBE(
d=toImport, be="Gene",
dbname=db,
taxId=NA,
onlyId=TRUE
)
## The associations
toImport <- unique(cref)
colnames(toImport) <- c("id1", "id2")
toImport$id1 <- sub("HGNC[:]", "", sub("MGI[:]", "", toImport$id1))
loadIsAssociatedTo(
d=toImport,
db1=db,
db2=dbname,
be="Gene"
)
}
}
}
################################################@
## Add symbols ----
message(Sys.time(), " --> Importing gene symbols")
disp <- dplyr::inner_join(
dplyr::mutate_all(
gene[,c("stable_id", "display_xref_id")], as.character
),
dplyr::mutate_all(
xref[,c("xref_id", "display_label", "description")], as.character
),
by=c("display_xref_id"="xref_id")
)
gSymb <- data.frame(
disp[,c("stable_id", "display_label")],
canonical=TRUE,
stringsAsFactors=F
)
colnames(gSymb) <- c("id", "symbol", "canonical")
gSyn <- dplyr::inner_join(
gene,
object_xref,
by=c("gene_id"="ensembl_id")
)[, c("stable_id", "xref_id")]
gSyn <- dplyr::inner_join(
gSyn,
external_synonym,
by="xref_id"
)[, c("stable_id", "synonym")]
gSyn <- unique(data.frame(
gSyn,
canonical=FALSE,
stringsAsFactors=F
))
colnames(gSyn) <- c("id", "symbol", "canonical")
gSyn <- gSyn[which(
!paste(gSyn$id, gSyn$symbol, sep=".") %in%
paste(gSymb$id, gSymb$symbol, sep=".")
),]
toImport <- unique(rbind(gSymb, gSyn))
# toImport <- unique(toImport[,c("id", "symbol")])
toImport <- unique(toImport[which(
!toImport[,2] %in% c("", "\\N") & !is.na(toImport[,2])
),])
loadBESymbols(d=toImport, be="Gene", dbname=dbname)
################################################@
## Add names ----
message(Sys.time(), " --> Importing gene names")
toImport <- disp[,c("stable_id", "description")]
toImport <- unique(toImport[which(
!toImport[,2] %in% c("", "\\N") & !is.na(toImport[,2])
),])
colnames(toImport) <- c("id", "name")
loadBENames(d=toImport, be="Gene", dbname=dbname)
################################################@
## History ----
message(Sys.time(), " --> Importing gene history")
beidToAdd <- stable_id_event[
which(
!stable_id_event$old_stable_id %in% gene$stable_id &
stable_id_event$old_stable_id != "\\N" &
stable_id_event$type=="gene"
),
c("old_stable_id", "mapping_session_id")
]
beidToAdd <- dplyr::inner_join(
beidToAdd,
mapping_session[, c("mapping_session_id", "old_release", "created")],
by="mapping_session_id"
)
beidToAdd <- beidToAdd[,setdiff(colnames(beidToAdd), "mapping_session_id")]
colnames(beidToAdd) <- c("id", "version", "deprecated")
beidToAdd <- unique(beidToAdd)
toAdd <- stable_id_event[
which(
!stable_id_event$new_stable_id %in% gene$stable_id &
stable_id_event$new_stable_id != "\\N" &
stable_id_event$type=="gene"
),
c("new_stable_id", "mapping_session_id")
]
toAdd <- dplyr::inner_join(
toAdd,
mapping_session[, c("mapping_session_id", "new_release")],
by="mapping_session_id"
)
toAdd <- toAdd[,setdiff(colnames(toAdd), "mapping_session_id")]
toAdd$deprecated <- "NA"
colnames(toAdd) <- c("id", "version", "deprecated")
toAdd <- unique(toAdd)
beidToAdd <- rbind(beidToAdd, toAdd)
beidToAdd <- beidToAdd[order(beidToAdd$deprecated),]
versions <- sort(unique(beidToAdd$version), decreasing = T)
v <- versions[1]
tmp <- beidToAdd[which(beidToAdd$version==v),]
tmp <- tmp[which(!duplicated(tmp$id)),]
for(v in versions[-1]){
toAdd <- beidToAdd[which(beidToAdd$version==v),]
toAdd <- toAdd[which(!duplicated(toAdd$id)),]
toAdd <- toAdd[which(!toAdd$id %in% tmp$id),]
tmp <- rbind(tmp, toAdd)
}
beidToAdd <- tmp
rm(tmp)
toDel <- by(
beidToAdd,
beidToAdd$version,
function(d){
by(
d,
d$deprecated,
function(subd){
version <- as.character(unique(subd$version))
deprecated <- unique(subd$deprecated)
if(deprecated=="NA"){
deprecated <- NA
}else{
deprecated <- as.Date(deprecated)
}
loadBE(
subd[,"id", drop=F], be="Gene",
dbname=dbname,
version=version,
deprecated=deprecated,
taxId=NA,
onlyId=TRUE
)
}
)
}
)
rm(toDel)
##
gvmap <- stable_id_event[
which(
stable_id_event$old_stable_id != "\\N" &
stable_id_event$new_stable_id != "\\N" &
stable_id_event$new_stable_id != stable_id_event$old_stable_id &
stable_id_event$type == "gene"
),
c("new_stable_id", "old_stable_id")
]
##
gvmap <- gvmap[which(!gvmap$old_stable_id %in% gene$stable_id),]
toTake <- which(gvmap$new_stable_id %in% gene$stable_id)
if(length(toTake) > 0){
toImport <- gvmap[toTake,]
colnames(toImport) <- c("new", "old")
loadHistory(d=toImport, dbname=dbname, be="Gene")
gvmap <- gvmap[-toTake,]
}
for(v in sort(unique(beidToAdd$version), decreasing = TRUE)){
gvmap <- gvmap[
which(
!gvmap$old_stable_id %in% beidToAdd$id[which(beidToAdd$version==v)]
),
]
toTake <- which(
gvmap$new_stable_id %in% beidToAdd$id[which(beidToAdd$version==v)]
)
if(length(toTake) > 0){
toImport <- gvmap[toTake,]
colnames(toImport) <- c("new", "old")
loadHistory(d=toImport, dbname=dbname, be="Gene")
gvmap <- gvmap[-toTake,]
}
}
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/getEnsemblGeneIds.R |
#' Feeding BED: Download Ensembl DB and load peptide information in BED
#'
#' Not exported to avoid unintended modifications of the DB.
#'
#' @param organism character vector of 1 element corresponding to the organism
#' of interest (e.g. "Homo sapiens")
#' @param release the Ensembl release of interest (e.g. "83")
#' @param gv the genome version (e.g. "38")
#' @param ddir path to the directory where the data should be saved
#' @param dbCref a named vector of characters providing cross-reference DB of
#' interest. These DB are also used to find indirect ID associations.
#' @param canChromosomes canonical chromosmomes to be considered as preferred
#' ID (e.g. c(1:22, "X", "Y", "MT") for human)
#'
getEnsemblPeptideIds <- function(
organism, # (e.g. "Homo sapiens")
release, # (e.g. "81")
gv, # Version of the genome (e.g. "38")
ddir,
dbCref,
canChromosomes
){
pdbname <- "Ens_translation"
tdbname <- "Ens_transcript"
## Data files
attrib_type <- gene_attrib <- transcript <-
external_db <- gene <- translation <-
external_synonym <- object_xref <- xref <-
stable_id_event <- mapping_session <-
seq_region <- coord_system <- NULL
toDump <- c(
"attrib_type", "gene_attrib", "transcript",
"external_db", "gene", "translation",
"external_synonym", "object_xref", "xref",
"stable_id_event", "mapping_session",
"seq_region", "coord_system"
)
dumpEnsCore(organism, release, gv, ddir, toDump)
################################################@
## Current Ensembl database and organism ----
taxId <- getTaxId(organism)
################################################@
## Add stable IDs ----
message(Sys.time(), " --> Importing internal IDs")
toAdd <- seq_region[
match(transcript$seq_region_id, seq_region$"seq_region_id"),
c("name", "coord_system_id")
]
toAdd <- cbind(
toAdd,
coord_system[
match(toAdd$"coord_system_id", coord_system$"coord_system_id"),
]
)
toAdd <- toAdd[,c(1, 5, 6)]
colnames(toAdd) <- c("region", "system", "genome")
toAdd$genome <- ifelse(toAdd$genome=="\\N", "", toAdd$genome)
transcript <- cbind(transcript, toAdd)
transcript$"seq_region" <- sub(
"^ ", "", paste(toAdd$genome, toAdd$system, toAdd$region)
)
transcript$preferred <- transcript$region %in% canChromosomes
translation <- cbind(
translation,
transcript[
match(translation$transcript_id, transcript$transcript_id),
c("seq_region", "preferred")
]
)
toImport <- unique(translation[, c("stable_id", "preferred"), drop=F])
colnames(toImport) <- c("id", "preferred")
loadBE(
d=toImport, be="Peptide",
dbname=pdbname,
version=release,
taxId=NA
)
message(" Importing attribute")
toImport <- unique(translation[, c("stable_id", "seq_region"), drop=F])
colnames(toImport) <- c("id", "value")
loadBeAttribute(
d=toImport, be="Peptide",
dbname=pdbname,
attribute="seq_region"
)
################################################@
## Add translation events ----
message(Sys.time(), " --> Importing translation events")
canTrans <- dplyr::inner_join(
dplyr::mutate_all(
transcript[,c("stable_id", "canonical_translation_id")],
as.character
),
dplyr::mutate_all(
translation[,c("translation_id", "stable_id")],
as.character
),
by=c("canonical_translation_id"="translation_id")
)[,c("stable_id.x", "stable_id.y")]
colnames(canTrans) <- c("tid", "pid")
canTrans$canonical <- TRUE
##
expTrans <- dplyr::inner_join(
transcript[,c("transcript_id", "stable_id")],
translation[,c("translation_id", "stable_id", "transcript_id")],
by=c("transcript_id"="transcript_id")
)[,c("stable_id.x", "stable_id.y")]
colnames(expTrans) <- c("tid", "pid")
expTrans$canonical <- FALSE
expTrans <- expTrans[which(
!paste(expTrans$gid, expTrans$tid, sep=".") %in%
paste(canTrans$gid, canTrans$tid, sep=".")
),]
toImport <- unique(rbind(canTrans, expTrans))
loadIsTranslatedIn(
d=toImport,
tdb=tdbname,
pdb=pdbname
)
################################################@
## Add cross references ----
for(ensDb in names(dbCref)){
db <- dbCref[ensDb]
message(Sys.time(), " --> ", ensDb)
dbid <- external_db$external_db_id[which(external_db$db_name == ensDb)]
takenXref <- xref[
which(xref$external_db_id == dbid),
c("xref_id", "dbprimary_acc")
]
if(nrow(takenXref)>0){
cref <- dplyr::inner_join(
takenXref,
object_xref[,c("ensembl_id", "xref_id")],
by="xref_id"
)
cref <- dplyr::inner_join(
cref,
translation[,c("stable_id", "translation_id")],
by=c("ensembl_id"="translation_id")
)[, c("dbprimary_acc", "stable_id")]
if(length(grep("Vega", ensDb))>0){
cref <- cref[
grep("^OTT", cref$dbprimary_acc),
]
}
if(nrow(cref) > 0){
cref <- unique(cref)
## NCBI cross-references
if(db=="RefSeq_peptide"){
cref <- cleanDubiousXRef(cref)
}
## External DB IDs
toImport <- unique(cref[, "dbprimary_acc", drop=F])
colnames(toImport) <- "id"
loadBE(
d=toImport, be="Peptide",
dbname=db,
taxId=NA
)
## The cross references
toImport <- cref
colnames(toImport) <- c("id1", "id2")
loadCorrespondsTo(
d=toImport,
db1=db,
db2=pdbname,
be="Peptide"
)
}
}
}
################################################@
## No peptide symbol in Ensembl ----
################################################@
## No peptide name in Ensembl ----
################################################@
## History ----
message(Sys.time(), " --> Importing translation versions mapping")
beidToAdd <- stable_id_event[
which(
!stable_id_event$old_stable_id %in% translation$stable_id &
stable_id_event$old_stable_id != "\\N" &
stable_id_event$type=="translation"
),
c("old_stable_id", "mapping_session_id")
]
beidToAdd <- dplyr::inner_join(
beidToAdd,
mapping_session[, c("mapping_session_id", "old_release", "created")],
by="mapping_session_id"
)
beidToAdd <- beidToAdd[,setdiff(colnames(beidToAdd), "mapping_session_id")]
colnames(beidToAdd) <- c("id", "version", "deprecated")
beidToAdd <- unique(beidToAdd)
toAdd <- stable_id_event[
which(
!stable_id_event$new_stable_id %in% translation$stable_id &
stable_id_event$new_stable_id != "\\N" &
stable_id_event$type=="translation"
),
c("new_stable_id", "mapping_session_id")
]
toAdd <- dplyr::inner_join(
toAdd,
mapping_session[, c("mapping_session_id", "new_release")],
by="mapping_session_id"
)
toAdd <- toAdd[,setdiff(colnames(toAdd), "mapping_session_id")]
toAdd$deprecated <- "NA"
colnames(toAdd) <- c("id", "version", "deprecated")
toAdd <- unique(toAdd)
beidToAdd <- rbind(beidToAdd, toAdd)
beidToAdd <- beidToAdd[order(beidToAdd$deprecated),]
versions <- sort(unique(beidToAdd$version), decreasing = T)
v <- versions[1]
tmp <- beidToAdd[which(beidToAdd$version==v),]
tmp <- tmp[which(!duplicated(tmp$id)),]
for(v in versions[-1]){
toAdd <- beidToAdd[which(beidToAdd$version==v),]
toAdd <- toAdd[which(!duplicated(toAdd$id)),]
toAdd <- toAdd[which(!toAdd$id %in% tmp$id),]
tmp <- rbind(tmp, toAdd)
}
beidToAdd <- tmp
rm(tmp)
toDel <- by(
beidToAdd,
beidToAdd$version,
function(d){
by(
d,
d$deprecated,
function(subd){
version <- as.character(unique(subd$version))
deprecated <- unique(subd$deprecated)
if(deprecated=="NA"){
deprecated <- NA
}else{
deprecated <- as.Date(deprecated)
}
loadBE(
subd[,"id", drop=F], be="Peptide",
dbname=pdbname,
version=version,
deprecated=deprecated,
taxId=NA,
onlyId=TRUE
)
}
)
}
)
rm(toDel)
##
pvmap <- stable_id_event[
which(
stable_id_event$old_stable_id != "\\N" &
stable_id_event$new_stable_id != "\\N" &
stable_id_event$new_stable_id != stable_id_event$old_stable_id &
stable_id_event$type == "translation"
),
c("new_stable_id", "old_stable_id")
]
##
pvmap <- pvmap[which(!pvmap$old_stable_id %in% translation$stable_id),]
toTake <- which(pvmap$new_stable_id %in% translation$stable_id)
if(length(toTake) > 0){
toImport <- pvmap[toTake,]
colnames(toImport) <- c("new", "old")
loadHistory(d=toImport, dbname=pdbname, be="Peptide")
pvmap <- pvmap[-toTake,]
}
for(v in sort(unique(beidToAdd$version), decreasing = TRUE)){
pvmap <- pvmap[
which(
!pvmap$old_stable_id %in% beidToAdd$id[which(beidToAdd$version==v)]
),
]
toTake <- which(
pvmap$new_stable_id %in% beidToAdd$id[which(beidToAdd$version==v)]
)
if(length(toTake) > 0){
toImport <- pvmap[toTake,]
colnames(toImport) <- c("new", "old")
loadHistory(d=toImport, dbname=pdbname, be="Peptide")
pvmap <- pvmap[-toTake,]
}
}
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/getEnsemblPeptideIds.R |
#' Feeding BED: Download Ensembl DB and load transcript information in BED
#'
#' Not exported to avoid unintended modifications of the DB.
#'
#' @param organism character vector of 1 element corresponding to the organism
#' of interest (e.g. "Homo sapiens")
#' @param release the Ensembl release of interest (e.g. "83")
#' @param gv the genome version (e.g. "38")
#' @param ddir path to the directory where the data should be saved
#' @param dbCref a named vector of characters providing cross-reference DB of
#' interest. These DB are also used to find indirect ID associations.
#' @param canChromosomes canonical chromosmomes to be considered as preferred
#' ID (e.g. c(1:22, "X", "Y", "MT") for human)
#'
getEnsemblTranscriptIds <- function(
organism,
release,
gv,
ddir,
dbCref,
canChromosomes
){
tdbname <- "Ens_transcript"
gdbname <- "Ens_gene"
## Data files
attrib_type <- gene_attrib <- transcript <-
external_db <- gene <- translation <-
external_synonym <- object_xref <- xref <-
stable_id_event <- mapping_session <-
seq_region <- coord_system <- NULL
toDump <- c(
"attrib_type", "gene_attrib", "transcript",
"external_db", "gene", "translation",
"external_synonym", "object_xref", "xref",
"stable_id_event", "mapping_session",
"seq_region", "coord_system"
)
dumpEnsCore(organism, release, gv, ddir, toDump)
################################################@
## Current Ensembl database and organism ----
taxId <- getTaxId(organism)
################################################@
## Add stable IDs ----
message(Sys.time(), " --> Importing internal IDs")
toAdd <- seq_region[
match(transcript$seq_region_id, seq_region$"seq_region_id"),
c("name", "coord_system_id")
]
toAdd <- cbind(
toAdd,
coord_system[
match(toAdd$"coord_system_id", coord_system$"coord_system_id"),
]
)
toAdd <- toAdd[,c(1, 5, 6)]
colnames(toAdd) <- c("region", "system", "genome")
toAdd$genome <- ifelse(toAdd$genome=="\\N", "", toAdd$genome)
transcript <- cbind(transcript, toAdd)
transcript$"seq_region" <- sub(
"^ ", "", paste(toAdd$genome, toAdd$system, toAdd$region)
)
transcript$preferred <- transcript$region %in% canChromosomes
toImport <- unique(transcript[, c("stable_id", "preferred"), drop=F])
colnames(toImport) <- c("id", "preferred")
loadBE(
d=toImport, be="Transcript",
dbname=tdbname,
version=release,
taxId=NA
)
message(" Importing attribute")
toImport <- unique(transcript[, c("stable_id", "seq_region"), drop=F])
colnames(toImport) <- c("id", "value")
loadBeAttribute(
d=toImport, be="Transcript",
dbname=tdbname,
attribute="seq_region"
)
################################################@
## Add expression events ----
message(Sys.time(), " --> Importing expression events")
canTrans <- dplyr::inner_join(
gene[,c("stable_id", "canonical_transcript_id")],
transcript[,c("transcript_id", "stable_id")],
by=c("canonical_transcript_id"="transcript_id")
)[,c("stable_id.x", "stable_id.y")]
colnames(canTrans) <- c("gid", "tid")
canTrans$canonical <- TRUE
##
expTrans <- dplyr::inner_join(
gene[,c("gene_id", "stable_id")],
transcript[,c("transcript_id", "stable_id", "gene_id")],
by=c("gene_id"="gene_id")
)[,c("stable_id.x", "stable_id.y")]
colnames(expTrans) <- c("gid", "tid")
expTrans$canonical <- FALSE
expTrans <- expTrans[which(
!paste(expTrans$gid, expTrans$tid, sep=".") %in%
paste(canTrans$gid, canTrans$tid, sep=".")
),]
toImport <- unique(rbind(canTrans, expTrans))
loadIsExpressedAs(
d=toImport,
gdb=gdbname,
tdb=tdbname
)
################################################@
## Add cross references ----
for(ensDb in names(dbCref)){
db <- dbCref[ensDb]
message(Sys.time(), " --> ", ensDb)
dbid <- external_db$external_db_id[which(external_db$db_name == ensDb)]
takenXref <- xref[
which(xref$external_db_id == dbid),
c("xref_id", "dbprimary_acc")
]
if(nrow(takenXref)>0){
cref <- dplyr::inner_join(
takenXref,
object_xref[,c("ensembl_id", "xref_id")],
by="xref_id"
)
cref <- dplyr::inner_join(
cref,
transcript[,c("stable_id", "transcript_id")],
by=c("ensembl_id"="transcript_id")
)[, c("dbprimary_acc", "stable_id")]
if(length(grep("Vega", ensDb))>0){
cref <- cref[
grep("^OTT", cref$dbprimary_acc),
]
}
if(nrow(cref) > 0){
cref <- unique(cref)
## NCBI cross-references
if(db=="RefSeq"){
cref <- cleanDubiousXRef(cref)
}
## External DB IDs
toImport <- unique(cref[, "dbprimary_acc", drop=F])
colnames(toImport) <- "id"
loadBE(
d=toImport, be="Transcript",
dbname=db,
taxId=NA
)
## The cross references
toImport <- cref
colnames(toImport) <- c("id1", "id2")
loadCorrespondsTo(
d=toImport,
db1=db,
db2=tdbname,
be="Transcript"
)
}
}
}
################################################@
## Add symbols ----
message(Sys.time(), " --> Importing transcript symbols")
disp <- dplyr::inner_join(
dplyr::mutate_all(
transcript[,c("stable_id", "display_xref_id")], as.character
),
dplyr::mutate_all(
xref[,c("xref_id", "display_label", "description")], as.character
),
by=c("display_xref_id"="xref_id")
)
tSymb <- data.frame(
disp[,c("stable_id", "display_label")],
canonical=TRUE,
stringsAsFactors=F
)
colnames(tSymb) <- c("id", "symbol", "canonical")
toImport <- unique(tSymb)
# toImport <- unique(toImport[,c("id", "symbol")])
toImport <- unique(toImport[which(
!toImport[,2] %in% c("", "\\N") & !is.na(toImport[,2])
),])
loadBESymbols(d=toImport, be="Transcript", dbname=tdbname)
################################################@
## Add names ----
message(Sys.time(), " --> Importing transcript names")
toImport <- disp[,c("stable_id", "description")]
toImport <- unique(toImport[which(
!toImport[,2] %in% c("", "\\N") & !is.na(toImport[,2])
),])
colnames(toImport) <- c("id", "name")
loadBENames(d=toImport, be="Transcript", dbname=tdbname)
################################################@
## History ----
message(Sys.time(), " --> Importing transcript history")
beidToAdd <- stable_id_event[
which(
!stable_id_event$old_stable_id %in% transcript$stable_id &
stable_id_event$old_stable_id != "\\N" &
stable_id_event$type=="transcript"
),
c("old_stable_id", "mapping_session_id")
]
beidToAdd <- dplyr::inner_join(
beidToAdd,
mapping_session[, c("mapping_session_id", "old_release", "created")],
by="mapping_session_id"
)
beidToAdd <- beidToAdd[,setdiff(colnames(beidToAdd), "mapping_session_id")]
colnames(beidToAdd) <- c("id", "version", "deprecated")
beidToAdd <- unique(beidToAdd)
toAdd <- stable_id_event[
which(
!stable_id_event$new_stable_id %in% transcript$stable_id &
stable_id_event$new_stable_id != "\\N" &
stable_id_event$type=="transcript"
),
c("new_stable_id", "mapping_session_id")
]
toAdd <- dplyr::inner_join(
toAdd,
mapping_session[, c("mapping_session_id", "new_release")],
by="mapping_session_id"
)
toAdd <- toAdd[,setdiff(colnames(toAdd), "mapping_session_id")]
toAdd$deprecated <- "NA"
colnames(toAdd) <- c("id", "version", "deprecated")
toAdd <- unique(toAdd)
beidToAdd <- rbind(beidToAdd, toAdd)
beidToAdd <- beidToAdd[order(beidToAdd$deprecated),]
versions <- sort(unique(beidToAdd$version), decreasing = T)
v <- versions[1]
tmp <- beidToAdd[which(beidToAdd$version==v),]
tmp <- tmp[which(!duplicated(tmp$id)),]
for(v in versions[-1]){
toAdd <- beidToAdd[which(beidToAdd$version==v),]
toAdd <- toAdd[which(!duplicated(toAdd$id)),]
toAdd <- toAdd[which(!toAdd$id %in% tmp$id),]
tmp <- rbind(tmp, toAdd)
}
beidToAdd <- tmp
rm(tmp)
toDel <- by(
beidToAdd,
beidToAdd$version,
function(d){
by(
d,
d$deprecated,
function(subd){
version <- as.character(unique(subd$version))
deprecated <- unique(subd$deprecated)
if(deprecated=="NA"){
deprecated <- NA
}else{
deprecated <- as.Date(deprecated)
}
loadBE(
subd[,"id", drop=F], be="Transcript",
dbname=tdbname,
version=version,
deprecated=deprecated,
taxId=NA,
onlyId=TRUE
)
}
)
}
)
rm(toDel)
##
tvmap <- stable_id_event[
which(
stable_id_event$old_stable_id != "\\N" &
stable_id_event$new_stable_id != "\\N" &
stable_id_event$new_stable_id != stable_id_event$old_stable_id &
stable_id_event$type == "transcript"
),
c("new_stable_id", "old_stable_id")
]
##
tvmap <- tvmap[which(!tvmap$old_stable_id %in% transcript$stable_id),]
toTake <- which(tvmap$new_stable_id %in% transcript$stable_id)
if(length(toTake) > 0){
toImport <- tvmap[toTake,]
colnames(toImport) <- c("new", "old")
loadHistory(d=toImport, dbname=tdbname, be="Transcript")
tvmap <- tvmap[-toTake,]
}
for(v in sort(unique(beidToAdd$version), decreasing = TRUE)){
tvmap <- tvmap[
which(
!tvmap$old_stable_id %in% beidToAdd$id[which(beidToAdd$version==v)]
),
]
toTake <- which(
tvmap$new_stable_id %in% beidToAdd$id[which(beidToAdd$version==v)]
)
if(length(toTake) > 0){
toImport <- tvmap[toTake,]
colnames(toImport) <- c("new", "old")
loadHistory(d=toImport, dbname=tdbname, be="Transcript")
tvmap <- tvmap[-toTake,]
}
}
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/getEnsemblTranscriptIds.R |
#' Get description of genes corresponding to Biological Entity identifiers
#'
#' This description can be used for annotating tables or graph based on BE IDs.
#'
#' @param ids list of identifiers
#' @param be one BE. **Guessed if not provided**
#' @param source the BE ID database. **Guessed if not provided**
#' @param organism organism name. **Guessed if not provided**
#' @param gsource the source of the gene IDs to use. It's chosen automatically
#' by default.
#' @param limForCache The number of ids above which the description
#' is gathered for all be IDs and cached for futur queries.
#'
#' @return a data.frame providing for each BE IDs
#' (row.names are provided BE IDs):
#'
#' - **id**: the BE ID
#' - **gsource**: the Gene ID the column name provides the source of the
#' used identifier
#' - **symbol**: the associated gene symbols
#' - **name**: the associated gene names
#'
#' @examples \dontrun{
#' getGeneDescription(
#' ids=c("1438_at", "1552335_at"),
#' be="Probe",
#' source="GPL570",
#' organism="human"
#' )
#' }
#'
#' @seealso [getBeIdDescription], [getBeIdNames], [getBeIdSymbols]
#'
#' @export
#'
getGeneDescription <- function(
ids,
be,
source,
organism,
gsource=largestBeSource(
be="Gene", organism=organism, rel="is_known_as", restricted=TRUE
),
limForCache=2000
){
##
from <- to <- symbol <- name <- NULL # for passing R check
##
if(length(ids)==0){
# stop("ids should be a character vector with at least one value")
return(data.frame(
"id"=character(),
"symbol"=character(),
"name"=character(),
"preferred"=logical(),
"db.version"=character(),
"db.deprecated"=logical(),
stringsAsFactors=FALSE
))
}
##
if(missing(be) || missing(source) || missing(organism)){
toWarn <- TRUE
}else{
toWarn <- FALSE
}
guess <- guessIdScope(ids=ids, be=be, source=source, organism=organism)
if(is.null(guess)){
warning("Could not find the provided ids")
if(missing(be) || missing(source) || missing(organism)){
stop("Missing be, source or organism information")
}
}else{
if(is.na(guess$be)){
warning(
"The provided ids does not match the provided scope",
" (be, source or organism)"
)
if(missing(be) || missing(source) || missing(organism)){
stop("Missing be, source or organism information")
}
}else{
be <- guess$be
source <- guess$source
organism <- guess$organism
}
}
if(toWarn){
warning(
"Guessing ID scope:",
sprintf("\n - be: %s", be),
sprintf("\n - source: %s", source),
sprintf("\n - organism: %s", organism)
)
}
##
if(be=="Gene"){
return(getBeIdDescription(
ids=ids,
be="Gene",
source=source,
organism=organism,
limForCache=limForCache
))
}
##
gids <- unique(convBeIds(
ids=ids,
from=be,
from.source=source,
from.org=organism,
to="Gene",
to.source=gsource,
restricted=TRUE,
limForCache=limForCache
)[, c("from", "to")])
gDesc <- getBeIdDescription(
ids=setdiff(gids$to, NA),
be="Gene",
source=gsource,
organism=organism
)
tDesc <- dplyr::full_join(
gids,
gDesc,
by=c("to"="id")
)
tDesc <- dplyr::group_by(tDesc, from)
##
gidSum <- function(x){
x <- setdiff(x, NA)
if(length(x)==0){
return(as.character(NA))
}else{
return(paste(x, collapse=" || "))
}
}
snSum <- function(x, y){
x <- x[which(!is.na(y))]
y <- y[which(!is.na(y))]
if(length(x)==0){
return(as.character(NA))
}else{
return(paste(
paste0(y, " (", x, ")"),
collapse=" || "
))
}
}
toRet <- dplyr::summarise(
tDesc,
gene=gidSum(to),
symbol=gidSum(symbol),
name=gidSum(name)
# symbol=snSum(to, symbol),
# name=snSum(to, name)
)
toRet <- as.data.frame(toRet)
colnames(toRet) <- c("id", gsource, "symbol", "name")
rownames(toRet) <- toRet$id
return(toRet[ids,])
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/getGeneDescription.R |
#' Get gene homologs between 2 organisms
#'
#' @param from.org organism name
#' @param to.org organism name
#' @param from.source the from gene ID database
#' @param to.source the to gene ID database
#' @param restricted boolean indicating if the results should be restricted to
#' current version of to BEID db. If FALSE former BEID are also returned:
#' **Depending on history it can take a very long time to return a very**
#' **large result!**
#' @param verbose boolean indicating if the CQL query should be displayed
#' @param recache boolean indicating if the CQL query should be run even if
#' the table is already in cache
#' @param filter character vector on which to filter from IDs.
#' If NULL (default), the result is not filtered:
#' all from IDs are taken into account.
#' @param limForCache if there are more filter than limForCache results are
#' collected for all IDs (beyond provided ids) and cached for futur queries.
#' If not, results are collected only for provided ids and not cached.
#'
#' @return a data.frame mapping gene IDs with the
#' following fields:
#'
#' - **from**: the from gene ID
#' - **to**: the to gene ID
#'
#' @examples \dontrun{
#' getHomTable(
#' from.org="human",
#' to.org="mouse"
#' )
#' }
#'
#' @seealso [getBeIdConvTable]
#'
#' @export
#'
getHomTable <- function(
from.org,
to.org,
from.source="Ens_gene",
to.source=from.source,
restricted=TRUE,
verbose=FALSE,
recache=FALSE,
filter=NULL,
limForCache=100
){
fn <- sub(
sprintf("^%s[:][::]", utils::packageName()), "",
sub("[(].*$", "", deparse(sys.call(), nlines=1, width.cutoff=500L))
)
to.source <- to.source
## Organisms
fromTaxId <- getTaxId(name=from.org)
if(length(fromTaxId)==0){
stop("from.org not found")
}
if(length(fromTaxId)>1){
print(getOrgNames(fromTaxId))
stop("Multiple TaxIDs match from.org")
}
##
toTaxId <- getTaxId(name=to.org)
if(length(toTaxId)==0){
stop("to.org not found")
}
if(length(toTaxId)>1){
print(getOrgNames(toTaxId))
stop("Multiple TaxIDs match to.org")
}
##
if(fromTaxId==toTaxId){
stop("Identical organisms. Use 'getBeIdConvTable' to convert DB IDs.")
}
## From ----
fr <- getBeIds(
be="Gene", source=from.source, organism=from.org,
restricted=FALSE, filter=filter, recache=recache, verbose=verbose,
limForCache=limForCache
)
if(is.null(fr) || nrow(fr)==0){
return(NULL)
}
fr <- dplyr::select(fr, "id", "Gene")
fr <- dplyr::rename(fr, "from"="id")
bef <- unique(fr$Gene)
## Conv ----
if(length(bef)>0 && length(bef)<=limForCache){
noCache <- TRUE
parameters <- list(filter=as.list(bef))
}else{
noCache <- FALSE
}
cql <- c(
sprintf(
'MATCH (fbe:Gene)-[:belongs_to]->(:TaxID {value:"%s"})',
fromTaxId
),
ifelse(
noCache,
'WHERE id(fbe) IN $filter',
''
),
sprintf(
'MATCH (tbe:Gene)-[:belongs_to]->(:TaxID {value:"%s"})',
toTaxId
),
'MATCH (fbe)<-[:identifies]-(:GeneID)-[:is_member_of]->(:GeneIDFamily)',
'<-[:is_member_of]-(:GeneID)-[:identifies]->(tbe:Gene)',
'RETURN DISTINCT id(fbe) as fromb, id(tbe) as tob'
)
if(noCache){
cr <- bedCall(
neo2R::cypher,
neo2R::prepCql(cql),
parameters=parameters
)
}else{
tn <- gsub(
"[^[:alnum:]]", "_",
paste(
fn,
fromTaxId,
toTaxId,
sep="_"
)
)
cr <- cacheBedCall(
f=neo2R::cypher,
query=neo2R::prepCql(cql),
tn=tn,
recache=recache
)
}
if(is.null(cr) || nrow(cr)==0){
return(NULL)
}
bef <- unique(cr$tob)
## To ----
tr <- getBeIds(
be="Gene", source=to.source, organism=to.org,
restricted=restricted, recache=recache, verbose=verbose,
bef=bef,
limForCache=limForCache
)
if(is.null(tr) || nrow(tr)==0){
return(NULL)
}
tr <- dplyr::select(tr, "id", "Gene")
tr <- dplyr::rename(tr, "to"="id")
## Results
toRet <- dplyr::inner_join(
cr, fr, by=c("fromb"="Gene")
)
if(is.null(toRet) || nrow(toRet)==0){
return(NULL)
}
toRet <- unique(dplyr::select(toRet, "from", "tob"))
toRet <- dplyr::inner_join(
toRet, tr, by=c("tob"="Gene")
)
if(is.null(toRet) || nrow(toRet)==0){
return(NULL)
}
toRet <- unique(dplyr::select(toRet, "from", "to"))
# ## Filter
# if(length(filter)>0 && !inherits(filter, "character")){
# stop("filter should be a character vector")
# }
#
# ## From
# fqs <- paste0(
# sprintf(
# 'MATCH (f:GeneID {database:"%s"})',
# from.source
# ),
# '-[:is_replaced_by|is_associated_to*0..]->(:GeneID)',
# '-[:identifies]->(fbe)'
# )
# ## To
# tqs <- paste0(
# sprintf(
# 'MATCH (t:GeneID {database:"%s"})',
# to.source
# ),
# # '-[:is_replaced_by|is_associated_to*0..]->(:GeneID)',
# ifelse(
# restricted,
# '-[:is_associated_to*0..]->(:GeneID)',
# '-[:is_replaced_by|is_associated_to*0..]->(:GeneID)'
# ),
# '-[:identifies]->(tbe)'
# )
#
# ## From fromBE to toBE
# ftqs <- c(
# sprintf(
# 'MATCH (fbe:Gene)-[:belongs_to]->(:TaxID {value:"%s"})',
# fromTaxId
# ),
# sprintf(
# 'MATCH (tbe:Gene)-[:belongs_to]->(:TaxID {value:"%s"})',
# toTaxId
# ),
# 'MATCH (fbe)<-[:identifies]-(:GeneID)-[:is_member_of]->(:GeneIDFamily)',
# '<-[:is_member_of]-(:GeneID)-[:identifies]->(tbe:Gene)',
# 'WITH DISTINCT fbe, tbe'
# )
#
# ##
# cql <- setdiff(c(ftqs, fqs, tqs), "")
#
# ## Filter
# if(length(filter)>0){
# cql <- c(cql, 'WHERE f.value IN $filter')
# }
#
# ## RETURN
# cql <- c(
# cql,
# 'RETURN DISTINCT f.value as from, t.value as to'
# )
# if(verbose){
# message(neo2R::prepCql(cql))
# }
# ##
# if(length(filter)==0){
# tn <- gsub(
# "[^[:alnum:]]", "_",
# paste(
# fn,
# fromTaxId, from.source,
# toTaxId, to.source,
# ifelse(restricted, "restricted", "full"),
# sep="_"
# )
# )
# toRet <- cacheBedCall(
# f=neo2R::cypher,
# query=neo2R::prepCql(cql),
# tn=tn,
# recache=recache
# )
# }else{
# toRet <- bedCall(
# f=neo2R::cypher,
# query=neo2R::prepCql(cql),
# parameters=list(filter=as.list(filter))
# )
# }
# toRet <- unique(toRet)
##
return(toRet)
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/getHomTable.R |
#' Feeding BED: Download NCBI gene DATA and load gene, transcript and peptide
#' information in BED
#'
#' Not exported to avoid unintended modifications of the DB.
#'
#' @param organism character vector of 1 element corresponding to the organism
#' of interest (e.g. "Homo sapiens")
#' @param reDumpThr time difference threshold between 2 downloads
#' @param ddir path to the directory where the data should be saved
#' @param curDate current date as given by [Sys.Date]
#'
getNcbiGeneTransPep <- function(
organism,
reDumpThr=100000,
ddir,
curDate
){
################################################@
## Organism ----
taxId <- getTaxId(organism)
################################################@
## Dump ----
dumpDate <- gene_info <- gene2ensembl <-
# gene2unigene <- gene2vega <-
gene_group <- gene_orthologs <-
gene_history <- gene2refseq <-
NULL
dumpNcbiDb(
taxOfInt=taxId,
reDumpThr=reDumpThr,
ddir=ddir,
toLoad=c(
"gene_info", "gene2ensembl",
# "gene2unigene", "gene2vega",
"gene_group", "gene_orthologs",
"gene_history", "gene2refseq"
),
curDate=curDate
)
################################################@
## DB information ----
gdbname <- "EntrezGene"
tdbname <- "RefSeq"
pdbname <- "RefSeq_peptide"
ddate <- dumpDate
release <- format(ddate, "%Y%m%d")
################################################@
## Genes ----
gdbCref <- c(
# "MIM"="MIM_GENE",
"HGNC"="HGNC",
"MGI"="MGI",
"RGD"="RGD",
"ZFIN"="ZFIN_gene",
"Ensembl"="Ens_gene",
"Vega"="Vega_gene"
)
gdbAss <- c(
"miRBase"="miRBase",
"MIM"="MIM_GENE"
)
################################################@
## Add gene IDs ----
message(Sys.time(), " --> Importing gene IDs")
geneAss <- unique(gene2refseq[,c("GeneID", "assembly")])
notPref <- unique(c(
which(geneAss$assembly=="-"),
grep("ALT_REF", geneAss$assembly),
grep("Alternate", geneAss$assembly)
))
if(length(notPref)>0){
prefId <- unique(geneAss$GeneID[-notPref])
}else{
prefId <- unique(geneAss$GeneID)
}
toImport <- unique(gene_info[, "GeneID", drop=F])
colnames(toImport) <- "id"
toImport$preferred <- toImport$id %in% prefId
loadBE(
d=toImport, be="Gene",
dbname=gdbname,
version=release,
taxId=taxId
)
message(" Importing attribute")
toImport <- geneAss
colnames(toImport) <- c("id", "value")
loadBeAttribute(
d=toImport, be="Gene",
dbname=gdbname,
attribute="assembly"
)
################################################@
## Add gene symbols ----
message(Sys.time(), " --> Importing gene symbols")
gSymb <- data.frame(
gene_info[,c("GeneID", "Symbol")],
canonical=TRUE,
stringsAsFactors=F
)
colnames(gSymb) <- c("id", "symbol", "canonical")
gSyn <- strsplit(
gene_info$Synonyms,
split="[|]"
)
names(gSyn) <- gene_info$GeneID
gSyn <- utils::stack(gSyn)
gSyn$ind <- as.character(gSyn$ind)
gSyn <- gSyn[,c("ind", "values")]
gSyn$canonical <- rep("FALSE", nrow(gSyn))
colnames(gSyn) <- c("id", "symbol", "canonical")
gSyn <- gSyn[which(gSyn$symbol != "-"),]
otherSyn <- gene_info[
which(
gene_info$Symbol_from_nomenclature_authority != "-" &
gene_info$Symbol_from_nomenclature_authority != gene_info$Symbol
),
c("GeneID", "Symbol_from_nomenclature_authority")
]
otherSyn$canonical <- rep(FALSE, nrow(otherSyn))
colnames(otherSyn) <- c("id", "symbol", "canonical")
toImport <- rbind(gSymb, gSyn, otherSyn)
loadBESymbols(d=toImport, be="Gene", dbname=gdbname)
################################################@
## Add gene names ----
message(Sys.time(), " --> Importing gene names")
toImport <- gene_info[, c("GeneID", "Full_name_from_nomenclature_authority")]
colnames(toImport) <- c("id", "name")
toImport$name <- ifelse(
toImport$name=="-",
gene_info$description,
toImport$name
)
loadBENames(d=toImport, be="Gene", dbname=gdbname)
################################################@
## Add gene cross references ----
## Cross references from gene_info
withXref <- gene_info[which(gene_info$dbXrefs!="-"),]
xref <- strsplit(withXref$dbXrefs, split="[|]")
names(xref) <- withXref$GeneID
xref <- lapply(
xref,
function(x){
toRet <- strsplit(x, split="[:]")
xdb <- unlist(lapply(toRet, function(x)x[1]))
toRet <- unlist(lapply(toRet, function(x)paste(x[-1], collapse=":")))
toRet <- data.frame(
db=xdb,
ref=toRet,
stringsAsFactors=F
)
return(toRet)
}
)
dbs <- unique(unlist(lapply(xref, function(x)x$db)))
xrefByDb <- lapply(
dbs,
function(db){
toRet <- utils::stack(lapply(xref, function(x) x$ref[which(x$db==db)]))
colnames(toRet) <- c("xref", "GeneID")
toRet <- toRet[,c("GeneID", "xref")]
return(toRet)
}
)
names(xrefByDb) <- dbs
dbCref <- gdbCref[intersect(names(gdbCref), names(xrefByDb))]
for(ncbiDb in names(dbCref)){
db <- dbCref[ncbiDb]
message(Sys.time(), " --> ", ncbiDb)
cref <- xrefByDb[[ncbiDb]][,c("xref", "GeneID")]
if(nrow(cref)>0){
## External DB IDs
toImport <- unique(cref[, "xref", drop=F])
colnames(toImport) <- "id"
toImport$id <- sub("HGNC[:]", "", sub("MGI[:]", "", toImport$id))
loadBE(
d=toImport, be="Gene",
dbname=db,
taxId=NA
)
## The cross references
toImport <- unique(cref)
colnames(toImport) <- c("id1", "id2")
toImport$id1 <- sub("HGNC[:]", "", sub("MGI[:]", "", toImport$id1))
loadCorrespondsTo(
d=toImport,
db1=db,
db2=gdbname,
be="Gene"
)
}
}
## Cross references from gene2ensembl file
db <- "Ens_gene"
message(Sys.time(), " --> ", db)
cref <- dplyr::mutate_all(
unique(gene2ensembl[,c("Ensembl_gene_identifier", "GeneID")]),
as.character
)
colnames(cref) <- c("xref", "GeneID")
cref <- cref[which(cref$xref != "-" & cref$GeneID != "-"),]
if(nrow(cref)>0){
## External DB IDs
toImport <- unique(cref[, "xref", drop=F])
colnames(toImport) <- "id"
loadBE(
d=toImport, be="Gene",
dbname=db,
taxId=NA
)
## The cross references
toImport <- unique(cref)
colnames(toImport) <- c("id1", "id2")
loadCorrespondsTo(
d=toImport,
db1=db,
db2=gdbname,
be="Gene"
)
}
# ## Cross references from gene2vega file
# db <- "Vega_gene"
# message(Sys.time(), " --> ", db)
# cref <- unique(gene2vega[,c("Vega_gene_identifier", "GeneID")])
# colnames(cref) <- c("xref", "GeneID")
# cref <- cref[which(cref$xref != "-" & cref$GeneID != "-"),]
# if(nrow(cref)>0){
# ## External DB IDs
# toImport <- unique(cref[, "xref", drop=F])
# colnames(toImport) <- "id"
# loadBE(
# d=toImport, be="Gene",
# dbname=db,
# taxId=NA
# )
# ## The cross references
# toImport <- unique(cref)
# colnames(toImport) <- c("id1", "id2")
# loadCorrespondsTo(
# d=toImport,
# db1=db,
# db2=gdbname,
# be="Gene"
# )
# }
#
# ## Associations from gene2unigene file
# db <- "UniGene"
# message(Sys.time(), " --> ", db)
# cref <- unique(gene2unigene[,c("UniGene_cluster", "GeneID")])
# colnames(cref) <- c("xref", "GeneID")
# cref <- cref[which(cref$xref != "-" & cref$GeneID != "-"),]
# cref <- cref[which(cref$GeneID %in% gene_info$GeneID),]
# if(nrow(cref)>0){
# ## External DB IDs
# toImport <- unique(cref[, "xref", drop=F])
# colnames(toImport) <- "id"
# loadBE(
# d=toImport, be="Gene",
# dbname=db,
# taxId=NA,
# onlyId=TRUE
# )
# ## The cross references
# toImport <- unique(cref)
# colnames(toImport) <- c("id1", "id2")
# loadIsAssociatedTo(
# d=toImport,
# db1=db,
# db2=gdbname,
# be="Gene"
# )
# }
## Associations ----
gdbAss <- gdbAss[intersect(names(gdbAss), names(xrefByDb))]
for(ncbiDb in names(gdbAss)){
db <- gdbAss[ncbiDb]
message(Sys.time(), " --> ", ncbiDb)
cref <- xrefByDb[[ncbiDb]][,c("xref", "GeneID")]
if(nrow(cref)>0){
## External DB IDs
toImport <- unique(cref[, "xref", drop=F])
colnames(toImport) <- "id"
toImport$id <- sub("HGNC[:]", "", sub("MGI[:]", "", toImport$id))
loadBE(
d=toImport, be="Gene",
dbname=db,
taxId=NA,
onlyId=TRUE
)
## The associations
toImport <- unique(cref)
colnames(toImport) <- c("id1", "id2")
toImport$id1 <- sub("HGNC[:]", "", sub("MGI[:]", "", toImport$id1))
loadIsAssociatedTo(
d=toImport,
db1=db,
db2=gdbname,
be="Gene"
)
}
}
################################################@
## Gene history ----
message(Sys.time(), " --> Importing gene history")
beidToAdd <- gene_history[
which(
!gene_history$Discontinued_GeneID %in% gene_info$GeneID &
gene_history$Discontinued_GeneID != "-"
),
c("Discontinued_GeneID", "Discontinue_Date")
]
beidToAdd$deprecated <- beidToAdd$Discontinue_Date
colnames(beidToAdd) <- c("id", "version", "deprecated")
beidToAdd <- unique(beidToAdd)
beidToAdd <- beidToAdd[order(beidToAdd$deprecated),]
versions <- sort(unique(beidToAdd$version), decreasing = T)
v <- versions[1]
tmp <- beidToAdd[which(beidToAdd$version==v),]
tmp <- tmp[which(!duplicated(tmp$id)),]
for(v in versions[-1]){
toAdd <- beidToAdd[which(beidToAdd$version==v),]
toAdd <- toAdd[which(!duplicated(toAdd$id)),]
toAdd <- toAdd[which(!toAdd$id %in% tmp$id),]
tmp <- rbind(tmp, toAdd)
}
beidToAdd <- tmp
rm(tmp)
loadBEVersion(
beidToAdd, be="Gene",
dbname=gdbname,
taxId=NA,
onlyId=TRUE
)
##
gvmap <- gene_history[
which(
gene_history$GeneID != "-" &
gene_history$Discontinued_GeneID != "-" &
gene_history$GeneID != gene_history$Discontinued_GeneID
),
c("GeneID", "Discontinued_GeneID")
]
toImport <- gvmap
colnames(toImport) <- c("new", "old")
loadHistory(d=toImport, dbname=gdbname, be="Gene")
################################################@
## Transcription events ----
message(Sys.time(), " --> Importing transcript IDs")
transcriptions <- unique(
gene2refseq[,c(
"GeneID", "RNA_nucleotide_accession.version",
"assembly"
)]
)
colnames(transcriptions) <- c("gid", "tid", "assembly")
transcriptions <- transcriptions[which(transcriptions$tid != "-"),]
transcriptions$tid <- sub("[.].*$", "", transcriptions$tid)
notPref <- unique(c(
which(transcriptions$assembly=="-"),
grep("ALT_REF", transcriptions$assembly),
grep("Alternate", transcriptions$assembly)
))
if(length(notPref)>0){
prefId <- unique(transcriptions$tid[-notPref])
}else{
prefId <- unique(transcriptions$tid)
}
##
toImport <- unique(transcriptions[, c("tid"), drop=F])
colnames(toImport) <- "id"
toImport$preferred <- toImport$id %in% prefId
loadBE(
d=toImport, be="Transcript",
dbname=tdbname,
version=release,
taxId=NA
)
message(" Importing attribute")
toImport <- unique(transcriptions[, c("tid", "assembly"), drop=F])
colnames(toImport) <- c("id", "value")
loadBeAttribute(
d=toImport, be="Transcript",
dbname=tdbname,
attribute="assembly"
)
##
toImport <- unique(transcriptions[, c("gid", "tid")])
loadIsExpressedAs(
d=toImport,
gdb=gdbname,
tdb=tdbname
)
## Cross references from gene2ensembl file
db <- "Ens_transcript"
message(Sys.time(), " --> ", db)
cref <- unique(gene2ensembl[,c(
"Ensembl_rna_identifier", "RNA_nucleotide_accession.version"
)])
colnames(cref) <- c("xref", "TranscriptID")
cref <- cref[which(cref$xref != "-" & cref$TranscriptID != "-"),]
cref$xref <- sub("[.].*$", "", cref$xref)
cref$TranscriptID <- sub("[.].*$", "", cref$TranscriptID)
if(nrow(cref)>0){
## External DB IDs
toImport <- unique(cref[, "xref", drop=F])
colnames(toImport) <- "id"
loadBE(
d=toImport, be="Transcript",
dbname=db,
taxId=NA
)
## The cross references
toImport <- unique(cref)
colnames(toImport) <- c("id1", "id2")
loadCorrespondsTo(
d=toImport,
db1=db,
db2=tdbname,
be="Transcript"
)
}
# ## Cross references from gene2vega file
# db <- "Vega_transcript"
# message(Sys.time(), " --> ", db)
# cref <- unique(gene2vega[,c(
# "Vega_rna_identifier", "RNA_nucleotide_accession.version"
# )])
# colnames(cref) <- c("xref", "TranscriptID")
# cref <- cref[which(cref$xref != "-" & cref$TranscriptID != "-"),]
# cref$TranscriptID <- sub("[.].*$", "", cref$TranscriptID)
# if(nrow(cref)>0){
# ## External DB IDs
# toImport <- unique(cref[, "xref", drop=F])
# colnames(toImport) <- "id"
# loadBE(
# d=toImport, be="Transcript",
# dbname=db,
# taxId=NA
# )
# ## The cross references
# toImport <- unique(cref)
# colnames(toImport) <- c("id1", "id2")
# loadCorrespondsTo(
# d=toImport,
# db1=db,
# db2=tdbname,
# be="Transcript"
# )
# }
################################################@
## Translation events ----
message(Sys.time(), " --> Importing peptide IDs")
translations <- unique(gene2refseq[,c(
"RNA_nucleotide_accession.version",
"protein_accession.version",
"assembly"
)])
colnames(translations) <- c("tid", "pid", "assembly")
translations <- translations[which(
translations$tid != "-" & translations$pid != "-"
),]
translations$tid <- sub("[.].*$", "", translations$tid)
translations$pid <- sub("[.].*$", "", translations$pid)
notPref <- unique(c(
which(translations$assembly=="-"),
grep("ALT_REF", translations$assembly),
grep("Alternate", translations$assembly)
))
if(length(notPref)>0){
prefId <- unique(translations$pid[-notPref])
}else{
prefId <- unique(translations$pid)
}
##
toImport <- unique(translations[, c("pid"), drop=F])
colnames(toImport) <- c("id")
toImport$preferred <- toImport$id %in% prefId
loadBE(
d=toImport, be="Peptide",
dbname=pdbname,
version=release,
taxId=NA
)
message(" Importing attribute")
toImport <- unique(translations[, c("pid", "assembly"), drop=F])
colnames(toImport) <- c("id", "value")
loadBeAttribute(
d=toImport, be="Peptide",
dbname=pdbname,
attribute="assembly"
)
##
toImport <- unique(translations[, c("tid", "pid")])
loadIsTranslatedIn(
d=toImport,
tdb=tdbname,
pdb=pdbname
)
## Cross references from gene2ensembl file
db <- "Ens_translation"
message(Sys.time(), " --> ", db)
cref <- unique(gene2ensembl[,c(
"Ensembl_protein_identifier", "protein_accession.version"
)])
colnames(cref) <- c("xref", "PeptideID")
cref <- cref[which(cref$xref != "-" & cref$PeptideID != "-"),]
cref$xref <- sub("[.].*$", "", cref$xref)
cref$PeptideID <- sub("[.].*$", "", cref$PeptideID)
if(nrow(cref)>0){
## External DB IDs
toImport <- unique(cref[, "xref", drop=F])
colnames(toImport) <- "id"
loadBE(
d=toImport, be="Peptide",
dbname=db,
taxId=NA
)
## The cross references
toImport <- unique(cref)
colnames(toImport) <- c("id1", "id2")
loadCorrespondsTo(
d=toImport,
db1=db,
db2=pdbname,
be="Peptide"
)
}
# ## Cross references from gene2vega file
# db <- "Vega_translation"
# message(Sys.time(), " --> ", db)
# cref <- unique(gene2vega[,c(
# "Vega_protein_identifier", "protein_accession.version"
# )])
# colnames(cref) <- c("xref", "PeptideID")
# cref <- cref[which(cref$xref != "-" & cref$PeptideID != "-"),]
# cref$PeptideID <- sub("[.].*$", "", cref$PeptideID)
# if(nrow(cref)>0){
# ## External DB IDs
# toImport <- unique(cref[, "xref", drop=F])
# colnames(toImport) <- "id"
# loadBE(
# d=toImport, be="Peptide",
# dbname=db,
# taxId=NA
# )
# ## The cross references
# toImport <- unique(cref)
# colnames(toImport) <- c("id1", "id2")
# loadCorrespondsTo(
# d=toImport,
# db1=db,
# db2=pdbname,
# be="Peptide"
# )
# }
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/getNcbiGeneTransPep.R |
#' Get organism names from taxonomy IDs
#'
#' @param taxID a vector of taxonomy IDs. If NULL (default) the function lists
#' all taxonomy IDs available in the DB.
#'
#' @return A data.frame mapping taxonomy IDs to organism names with the
#' following fields:
#'
#' - **taxID**: the taxonomy ID
#' - **name**: the organism name
#' - **nameClass**: the class of the name
#'
#' @examples \dontrun{
#' getOrgNames(c("9606", "10090"))
#' getOrgNames("9606")
#' }
#'
#' @seealso [getTaxId], [listOrganisms]
#'
#' @export
#'
getOrgNames <- function(taxID=NULL){
if(!is.null(taxID) && !is.atomic(taxID)){
stop("taxID should be NULL or a character vector")
}
##
if(is.null(taxID)){
cql <- 'MATCH (tid:TaxID)-[r:is_named]->(on:OrganismName)'
}else{
cql <- c(
'MATCH (tid:TaxID)-[r:is_named]->(on:OrganismName)',
'WHERE tid.value IN $tid'
)
}
cql <- c(
cql,
'RETURN tid.value as taxID, on.value as name, r.nameClass as nameClass',
'ORDER BY taxID, nameClass'
)
toRet <- unique(bedCall(
neo2R::cypher,
query=neo2R::prepCql(cql),
parameters=list(tid=as.list(as.character(taxID)))
))
return(toRet)
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/getOrgNames.R |
#' Get relevant IDs for a formerly identified BE in a context of interest
#'
#' **DEPRECATED: use [searchBeid] and [geneIDsToAllScopes] instead.**
#' This function is meant to be used with [searchId] in order
#' to implement a dictonary of identifiers of interest. First
#' the [searchId] function is used to search a term.
#' Then the [getRelevantIds] function
#' is used to find the corresponding IDs in a context of interest.
#'
#' @param d the data.frame returned by [searchId].
#' @param selected the rows of interest in d
#' @param be the BE in the context of interest
#' @param source the source of the identifier in the context of interest
#' @param organism the organism in the context of interest
#' @param restricted boolean indicating if the results should be restricted to
#' current version of to BEID db. If FALSE former BEID are also returned:
#' **Depending on history it can take a very long time to return**
#' **a very large result!**
#' @param simplify if TRUE (default) duplicated IDs are removed from the output
#' @param verbose if TRUE, the CQL query is shown
#'
#' @return The d data.frame with a new column providing the relevant ID
#' in the context of interest and without the gene field.
#' Scope ("be", "source" and "organism") is provided as a named list
#' in the "scope" attributes: `attr(x, "scope")`
#'
#' @seealso [searchId]
#'
#' @export
#'
getRelevantIds <- function(
d, selected=1,
be=c(listBe(), "Probe"), source, organism,
restricted=TRUE,
simplify=TRUE,
verbose=FALSE
){
selected <- intersect(selected, 1:nrow(d))
if(length(selected)<1){
stop("Only one row of d can be selected by sel parameter")
}
dcols <- c("found", "entity", "be", "source", "organism", "gene")
if(!all(dcols %in% colnames(d))){
stop(
sprintf(
"d should be a data.frame with the following columns: %s.",
paste(dcols, collapse=", ")
),
" This data.frame is returned by the searchId function."
)
}
match.arg(be, c("Probe", listBe()), several.ok=FALSE)
##
tax <- getTaxId(organism)
organism <- getOrgNames(tax)
organism <- organism$name[which(organism$nameClass=="scientific name")]
##
toRet <- NULL
for(sel in selected){
from <- d[sel, "ebe"]
from.entity <- d[sel, "entity"]
from.source <- d[sel, "source"]
from.org <- d[sel, "organism"]
from.tax <- getTaxId(from.org)
from.gene <- d[sel, "gene"][[1]]
##
if(tax!=from.tax){
hqs <- c(
'MATCH (fg:Gene)<-[:identifies]-(:GeneID)',
'-[:is_member_of]->(:GeneIDFamily)<-[:is_member_of]-',
'(:GeneID)-[:identifies]->(tg:Gene)-[:belongs_to]->(tid:TaxID)',
'WHERE id(fg) IN $fromGene AND tid.value=$tax',
'RETURN id(tg) as gene'
)
if(verbose) message(neo2R::prepCql(hqs))
targGene <- unique(bedCall(
f=neo2R::cypher,
query=neo2R::prepCql(hqs),
parameters=list(fromGene=as.list(from.gene), tax=tax)
))[,"gene"]
if(length(targGene)==0){
next()
}
from.entity <- targGene
from <- "Gene"
}
##
if(be=="Probe"){
qs <- genProbePath(platform=source)
targBE <- attr(qs, "be")
qs <- paste0(
sprintf(
'(t:ProbeID {platform:"%s"})',
source
),
qs,
sprintf(
'(tbe:%s)',
targBE
)
)
}else{
targBE <- be
if(source=="Symbol"){
qs <- paste0(
'(t:BESymbol)<-[fika:is_known_as]-',
sprintf(
'(tid:%s)',
paste0(targBE, "ID")
),
'-[:is_replaced_by|is_associated_to*0..]->()',
'-[:identifies]->',
sprintf(
'(tbe:%s)',
targBE
)
)
}else{
qs <- paste0(
sprintf(
'(t:%s {database:"%s"})',
paste0(targBE, "ID"), source
),
ifelse(
restricted,
'-[:is_associated_to*0..]->',
'-[:is_replaced_by|is_associated_to*0..]->'
),
# '-[:is_replaced_by|is_associated_to*0..]->',
sprintf(
'(:%s)',
paste0(targBE, "ID")
),
'-[:identifies]->',
sprintf(
'(tbe:%s)',
targBE
)
)
}
}
##
qs <- paste('MATCH', qs)
##
if(from!="Gene"){
if(targBE=="Gene"){
qs <- c(
qs,
'WHERE id(tbe) IN $fromGene'
)
}else{
qs <- c(
qs,
paste0(
'MATCH (tbe)',
genBePath(targBE, "Gene"),
'(tGene)'
),
'WHERE id(tGene) IN $fromGene'
)
}
}
##
if(targBE==from){
qs <- c(
qs,
'MATCH (tbe) WHERE id(tbe) IN $fromEntity'
)
}else{
qs <- c(
qs,
paste0(
'MATCH (fbe)',
genBePath(from, targBE),
'(tbe)'
),
'WHERE id(fbe) IN $fromEntity'
)
}
##
qs <- c(
qs,
'RETURN t.preferred as preferred, t.value as id'
)
if(verbose) message(neo2R::prepCql(qs))
value <- unique(bedCall(
f=neo2R::cypher,
query=neo2R::prepCql(qs),
parameters=list(
fromGene=as.list(from.gene),
fromEntity=as.list(from.entity)
)
))#$id
if(!is.null(value) && nrow(value) > 0){
toAdd <- d[rep(sel, nrow(value)),]
toAdd$preferred <- value$preferred
toAdd$id <- value$id
rownames(toAdd) <- NULL
toRet <- rbind(toRet, toAdd)
}
}
if(!is.null(toRet) && ncol(toRet)>0){
colnames(toRet)[ncol(toRet)] <- paste0(
be, " from ", source,
" (", organism, ")"
)
rownames(toRet) <- NULL
toRet <- toRet[,which(colnames(toRet)!="gene")]
if(simplify){
toRet <- toRet[order(toRet$canonical, decreasing=TRUE),]
toRet <- toRet[
order(toRet$found==toRet[,ncol(toRet)], decreasing=TRUE),
]
toRet <- toRet[order(toRet$source==source, decreasing=TRUE),]
toRet <- toRet[order(toRet$be==be, decreasing=TRUE),]
toRet <- toRet[order(toRet$preferred, decreasing=TRUE),]
toRet <- toRet[order(toRet$organism==organism, decreasing=TRUE),]
toRet <- toRet[!duplicated(toRet[,ncol(toRet)]),]
}
attr(toRet, "scope") <- list(be=be, source=source, organism=organism)
}
return(toRet)
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/getRelevantIds.R |
#' Identify the biological entity (BE) targeted by probes
#'
#' @param platform the platform of the probes
#'
#' @return The BE targeted by the platform
#'
#' @examples \dontrun{
#' getTargetedBe("GPL570")
#' }
#'
#' @seealso [listPlatforms]
#'
#' @export
#'
getTargetedBe <- function(platform){
if(!is.atomic(platform) || length(platform)!=1){
stop("platform should be a character vector of length 1")
}
cqRes <- bedCall(
neo2R::cypher,
query=neo2R::prepCql(c(
'MATCH (pl:Platform {name:$platform})',
'-[:is_focused_on]->(bet:BEType)',
'RETURN bet.value'
)),
parameters=list(platform=as.character(platform))
)
if(is.null(cqRes)){
stop("platform not found.")
}
return(cqRes$bet.value)
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/getTargetedBe.R |
#' Get taxonomy ID of an organism name
#'
#' @param name the name of the organism
#'
#' @return A vector of taxonomy ID
#'
#' @examples \dontrun{
#' getTaxId("human")
#' }
#'
#' @seealso [getOrgNames], [listOrganisms]
#'
#' @export
#'
getTaxId <- function(name){
if(!is.atomic(name) || length(name)!=1){
stop("name should be a character vector of length one")
}
cql <- c(
'MATCH (tid:TaxID)-[:is_named]->(on:OrganismName)',
'WHERE on.value_up=$name',
'RETURN DISTINCT tid.value'
)
toRet <- bedCall(
neo2R::cypher,
query=neo2R::prepCql(cql),
parameters=list(name=toupper(name))
)$tid.value
return(toRet)
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/getTaxId.R |
#' Feeding BED: Download Uniprot information in BED
#'
#' Not exported to avoid unintended modifications of the DB.
#'
#' @param organism character vector of 1 element corresponding to the organism
#' of interest (e.g. "Homo sapiens")
#' @param release the release of interest (check if already downloaded)
#' @param ddir path to the directory where the data should be saved
#'
getUniprot <- function(
organism,
release,
ddir
){
################################################@
## Organism ----
taxId <- getTaxId(organism)
################################################@
## Dump ----
gene_info <- NULL
dumpUniprotDb(
taxOfInt=taxId,
release=release,
ddir=ddir
)
################################################@
## Organism focus ----
uids <- uids[which(uids$tax==taxId),]
deprecated <- deprecated[which(deprecated$ID %in% uids$ID),]
rsCref <- rsCref[which(rsCref$ID %in% uids$ID),]
ensCref <- ensCref[which(ensCref$ID %in% uids$ID),]
################################################@
## DB information ----
pdbname <- "Uniprot"
################################################@
## Uniprot IDs ----
message(Sys.time(), " --> Importing Uniprot IDs")
toImport <- unique(uids[, c("ID", "status"), drop=F])
colnames(toImport) <- c("id", "value")
toImport$preferred <- toImport$value=="Reviewed"
loadBE(
d=toImport, be="Peptide",
dbname=pdbname,
version=release,
taxId=NA
)
message(" Importing attribute")
toImport <- toImport[,c("id", "value")]
loadBeAttribute(
d=toImport, be="Peptide",
dbname=pdbname,
attribute="status"
)
################################################@
## Add symbols ----
message(Sys.time(), " --> Importing Uniprot symbols")
toImport <- data.frame(
uids[,c("ID", "symbol")],
canonical=TRUE,
stringsAsFactors=F
)
colnames(toImport) <- c("id", "symbol", "canonical")
loadBESymbols(d=toImport, be="Peptide", dbname=pdbname)
################################################@
## Add names ----
message(Sys.time(), " --> Importing Uniprot names")
toImport <- uids[,c("ID", "name")]
colnames(toImport) <- c("id", "name")
toImport$name <- ifelse(
toImport$name=="-",
gene_info$description,
toImport$name
)
loadBENames(d=toImport, be="Peptide", dbname=pdbname)
################################################@
## Add Uniprot cross references ----
## * Ensembl ----
db <- "Ens_translation"
message(Sys.time(), " --> ", db, " cross references")
## External DB IDs
toImport <- unique(ensCref[, "ensembl", drop=F])
colnames(toImport) <- "id"
loadBE(
d=toImport, be="Peptide",
dbname=db,
taxId=NA
)
## The cross references
toImport <- unique(ensCref[,c("ensembl", "ID")])
colnames(toImport) <- c("id1", "id2")
loadCorrespondsTo(
d=toImport,
db1=db,
db2=pdbname,
be="Peptide"
)
## * RefSeq ----
db <- "RefSeq_peptide"
message(Sys.time(), " --> ", db, " cross references")
## External DB IDs
toImport <- unique(rsCref[, "refseq", drop=F])
colnames(toImport) <- "id"
loadBE(
d=toImport, be="Peptide",
dbname=db,
taxId=NA
)
## The cross references
toImport <- unique(rsCref[,c("refseq", "ID")])
colnames(toImport) <- c("id1", "id2")
loadCorrespondsTo(
d=toImport,
db1=db,
db2=pdbname,
be="Peptide"
)
################################################@
## Depreacted IDs ----
message(Sys.time(), " --> Importing Uniprot deprecated IDs")
toImport <- unique(deprecated[, "deprecated", drop=F])
colnames(toImport) <- "id"
loadBE(
d=toImport, be="Peptide",
dbname=pdbname,
version="deprecated",
deprecated=as.Date("1-1-1"),
taxId=NA,
onlyId=TRUE
)
##
toImport <- deprecated
colnames(toImport) <- c("new", "old")
loadHistory(d=toImport, dbname=pdbname, be="Peptide")
################################################@
## Orphan Uniprot IDs ----
message(Sys.time(), " --> Managing orphan Uniprot IDs")
gdbname <- "BEDTech_gene"
tdbname <- "BEDTech_transcript"
orph <- bedCall(
neo2R::cypher,
query=neo2R::prepCql(c(
sprintf(
'MATCH (pid {database:"%s"})-[:identifies]->(p:Peptide)',
pdbname
),
'WHERE NOT (p)<-[:is_translated_in]-()',
'RETURN DISTINCT pid.value as id'
))
)$id
orph <- intersect(orph, uids$ID)
techTrans <- data.frame(
tid=paste0("transcript.", orph),
pid=orph,
stringsAsFactors=FALSE
)
techGene <- data.frame(
gid=paste0("gene.", orph),
tid=techTrans$tid,
stringsAsFactors=FALSE
)
##
toImport <- techGene[,"gid",drop=FALSE]
colnames(toImport) <- "id"
loadBE(
d=toImport,
be="Gene",
dbname=gdbname,
taxId=taxId
)
##
toImport <- techGene[,"tid",drop=FALSE]
colnames(toImport) <- "id"
loadBE(
d=toImport,
be="Transcript",
dbname=tdbname
)
loadIsExpressedAs(d=techGene, gdb=gdbname, tdb=tdbname)
##
loadIsTranslatedIn(d=techTrans, tdb=tdbname, pdb=pdbname)
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/getUniprot.R |
#' Guess biological entity (BE), database source and organism of a vector
#' of identifiers.
#'
#' @param ids a character vector of identifiers
#' @param be one BE or "Probe". **Guessed if not provided**
#' @param source the BE ID database or "Symbol" if BE or
#' the probe platform if Probe. **Guessed if not provided**
#' @param organism organism name. **Guessed if not provided**
#' @param tcLim number of identifiers to check to guess origin for the whole set.
#' Inf ==> no limit.
#'
#' @return A list (NULL if no match):
#'
#' - **be**: a character vector of length 1 providing the best BE guess
#' (NA if inconsistent with user input: be, source or organism)
#' - **source**: a character vector of length 1 providing the best source
#' guess (NA if inconsistent with user input: be, source or organism)
#' - **organism*$: a character vector of length 1 providing the best organism
#' guess (NA if inconsistent with user input: be, source or organism)
#'
#' The "details" attribute (`attr(x, "details")``) is a data frame providing
#' numbers supporting the guess
#'
#' @examples \dontrun{
#' guessIdScope(ids=c("10", "100"))
#' }
#'
#' @export
#'
guessIdScope <- function(ids, be, source, organism, tcLim=100){
##
tcLim <- as.numeric(tcLim)
if(!is.atomic(tcLim) || length(tcLim)!=1 || is.na(tcLim) || tcLim <= 0){
stop("tcLim should be a positive numeric value")
}
ids <- unique(ids)
if(length(ids) > tcLim){
toCheck <- sample(x=ids, size=tcLim, replace=F)
}else{
toCheck <- ids
}
parameters <- list(ids=as.list(as.character(toCheck)))
parameters.symb <- list(ids=as.list(toupper(as.character(toCheck))))
##
beids <- bedCall(
f=neo2R::cypher,
query=neo2R::prepCql(
'MATCH (n:BEID) WHERE n.value IN $ids',
'MATCH (n)-[:is_replaced_by|is_associated_to*0..]->(ni:BEID)',
'MATCH (ni)-[:identifies]->(e)',
'WITH DISTINCT n, ni, e',
'MATCH (e)<-[cr:codes_for|is_expressed_as|is_translated_in*0..2]-(g:Gene)',
'MATCH (g)-[:belongs_to]->(t:TaxID)',
'MATCH (t)-[:is_named {nameClass:"scientific name"}]->(o:OrganismName)',
# 'AND NOT "identifies" IN extract(r IN cr |type(r))',
# Line above not necessary thanks to the data model.
'RETURN labels(e) as be, n.database as source',
', o.value as organism, count(DISTINCT n.value) as nb',
'ORDER BY nb DESC'
),
parameters=parameters
)
##
besymbs <- bedCall(
f=neo2R::cypher,
query=neo2R::prepCql(
'MATCH (n:BESymbol)',
'WHERE n.value_up IN $ids',
##
# The line below uses lucene index in order to allow fulltext
# searches including case insensitive searches! LEGACY !!
# sprintf(
# 'START n=node:node_auto_index(\'value:("%s")\')',
# paste(toCheck, collapse='" "')
# ),
# 'WHERE "BESymbol" IN labels(n)',
# 'WITH n',
##
'MATCH (n)<-[:is_known_as]-(nii:BEID)',
'MATCH (nii)-[:is_replaced_by|is_associated_to*0..]->(ni:BEID)',
'MATCH (ni)-[:identifies]->(e)',
'WITH DISTINCT n, nii, ni, e',
'MATCH (e)<-[cr:codes_for|is_expressed_as|is_translated_in*0..2]-(g:Gene)',
'MATCH (g)-[:belongs_to]->(t:TaxID)',
'MATCH (t)-[:is_named {nameClass:"scientific name"}]->(o:OrganismName)',
'RETURN labels(e) as be, "Symbol" as source',
', o.value as organism, count(DISTINCT n.value) as nb',
'ORDER BY nb DESC'
),
parameters=parameters.symb
)
##
probes <- bedCall(
f=neo2R::cypher,
query=neo2R::prepCql(
'MATCH (n:ProbeID)',
'WHERE n.value IN $ids',
'WITH DISTINCT n',
'MATCH (n)-[:targets]->(nii:BEID)',
'MATCH (nii)-[:is_replaced_by|is_associated_to*0..]->(ni:BEID)',
'MATCH (ni)-[:identifies]->(e)',
'WITH DISTINCT n, nii, ni, e',
'MATCH (e)<-[cr:codes_for|is_expressed_as|is_translated_in*0..2]-(g:Gene)',
'MATCH (g)-[:belongs_to]->(t:TaxID)',
'MATCH (t)-[:is_named {nameClass:"scientific name"}]->(o:OrganismName)',
'RETURN "Probe" as be, n.platform as source',
', o.value as organism, count(distinct n.value) as nb',
'ORDER BY nb DESC'
),
parameters=parameters
)
##
toRetDetails <- rbind(beids, besymbs, probes)
if(!is.null(toRetDetails)){
toRetDetails <- toRetDetails[order(toRetDetails$nb, decreasing=T),]
toRetDetails$proportion <- toRetDetails$nb/length(toCheck)
}else{
return(NULL)
}
## Select scope according to user input
sel <- 1:nrow(toRetDetails)
if(!missing(be)){
be <- match.arg(be, c(listBe(), "Probe"))
sel <- intersect(sel, which(toRetDetails$be==be))
}
if(!missing(source)){
stopifnot(is.character(source), length(source)==1, !is.na(source))
sel <- intersect(sel, which(toRetDetails$source==source))
}
if(!missing(organism)){
stopifnot(
is.character(organism), length(organism)==1, !is.na(organism)
)
tid <- getTaxId(organism)
if(length(tid)!=1){
stop(sprintf("Could find %s organism in BED", organism))
}
sn <- getOrgNames(tid)
sn <- sn$name[which(sn$nameClass=="scientific name")]
sel <- intersect(sel, which(toRetDetails$organism==sn))
}
sel <- sel[1]
##
toRet <- list(
"be"=toRetDetails[sel, "be"],
"source"=toRetDetails[sel, "source"],
"organism"=toRetDetails[sel, "organism"]
)
attr(x=toRet, which="details") <- toRetDetails
return(toRet)
}
#' @describeIn guessIdScope
#'
#' Deprecated version of guessIdScope
#'
#' @param ... params for `guessIdScope`
#'
#' @export
guessIdOrigin <- function(...){
warning("Deprecated. Use guessIdScope instead")
guessIdScope(...)
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/guessIdScope.R |
#' Check if two objects have the same BEID scope
#'
#' @param x the object to test
#' @param y the object to test
#'
#' @return A logical indicating if the 2 scopes are identical
#'
#' @export
#'
identicalScopes <- function(x, y){
xs <- scope(x)
ys <- scope(y)
return(
xs$be==ys$be &
xs$source==ys$source &
xs$organism==ys$organism
)
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/identicalScopes.R |
#' Autoselect source of biological entity identifiers
#'
#' The selection is based on direct identifiers
#'
#' @param be the biological entity under focus
#' @param organism the organism under focus
#' @param rel a type of relationship to consider in the query
#' (e.g. "is_member_of") in order to focus on specific information.
#' If NA (default) all be are taken into account whatever their available
#' relationships.
#' @param restricted boolean indicating if the results should be restricted to
#' current version of to BEID db. If FALSE former BEID are also taken
#' into account.
#' @param exclude database to exclude from possible selection. Used to filter
#' out technical database names such as "BEDTech_gene" and "BEDTech_transcript"
#' used to manage orphan IDs (not linked to any gene based on information
#' taken from sources)
#'
#' @return The name of the selected source. The selected source will be the one
#' providing the largest number of current identifiers.
#'
#' @examples \dontrun{
#' largestBeSource(be="Gene", "Mus musculus")
#' }
#'
#' @seealso [listBeIdSources]
#'
#' @export
#'
largestBeSource <- function(
be, organism, rel=NA, restricted=TRUE,
exclude=c("BEDTech_gene", "BEDTech_transcript")
){
dbList <- listBeIdSources(
be=be, organism=organism, rel=rel,
direct=TRUE, restricted=restricted,
exclude=exclude
)
return(dbList[which.max(dbList$nbBe), "database"])
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/largestBeSource.R |
#' Lists all the biological entities (BE) available in the BED database
#'
#' @return A character vector of biological entities (BE)
#'
#' @seealso [listPlatforms], [listBeIdSources],
#' [listOrganisms]
#'
#' @export
#'
listBe <- function(){
toRet <- bedCall(
neo2R::cypher,
query='MATCH (n:BEType) return n.value as be'
)
return(toRet$be)
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/listBe.R |
#' Lists all the databases taken into account in the BED database
#' for a biological entity (BE)
#'
#' @param be the BE on which to focus
#' @param organism the name of the organism to focus on.
#' @param direct a logical value indicating if only "direct" BE identifiers
#' should be considered
#' @param rel a type of relationship to consider in the query
#' (e.g. "is_member_of") in order to focus on specific information.
#' If NA (default) all be are taken into account whatever their available
#' relationships.
#' @param restricted boolean indicating if the results should be restricted to
#' current version of to BEID db. If FALSE former BEID are also returned.
#' There is no impact if direct is set to TRUE.
#' @param recache boolean indicating if the CQL query should be run even if
#' the table is already in cache
#' @param verbose boolean indicating if the CQL query should be shown.
#' @param exclude database to exclude from possible selection. Used to filter
#' out technical database names such as "BEDTech_gene" and "BEDTech_transcript"
#' used to manage orphan IDs (not linked to any gene based on information
#' taken from sources)
#'
#' @return A data.frame indicating the number of ID in each available database
#' with the following fields:
#'
#' - **database**: the database name
#' - **nbBe**: number of distinct entities
#' - **nbId**: number of identifiers
#' - **be**: the BE under focus
#'
#' @examples \dontrun{
#' listBeIdSources(be="Transcript", organism="mouse")
#' }
#'
#' @seealso [listBe], [largestBeSource]
#'
#' @export
#'
listBeIdSources <- function(
be=listBe(), organism,
direct=FALSE,
rel=NA,
restricted=FALSE,
recache=FALSE,
verbose=FALSE,
exclude=c()
){
fn <- sub(
sprintf("^%s[:][::]", utils::packageName()), "",
sub("[(].*$", "", deparse(sys.call(), nlines=1, width.cutoff=500L))
)
be <- match.arg(be)
if(!is.logical(direct)){
stop("direct should be a logical vector of length 1")
}
if(!is.logical(restricted)){
stop("restricted should be a logical vector of length 1")
}
if(!is.logical(recache)){
stop("recache should be a logical vector of length 1")
}
if(!is.logical(verbose)){
stop("verbose should be a logical vector of length 1")
}
if(length(organism)!=1 || is.na(organism)){
stop("organism should be a character vector of length 1")
}
if(length(rel)!=1){
stop("rel should be a character vector of length 1")
}
## Organism
taxId <- getTaxId(name=organism)
if(length(taxId)==0){
stop("organism not found")
}
if(length(taxId)>1){
print(getOrgNames(taxId))
stop("Multiple TaxIDs match organism")
}
if(be=="Gene"){
subqs <- ""
}else{
subqs <- paste0(
genBePath(from=be, to="Gene"),
'(:Gene)'
)
}
cql <- c(
paste0(
sprintf('MATCH (be:%s)', be),
subqs,
'-[:belongs_to]->',
'(:TaxID {value:$taxId}) WITH DISTINCT be'
)
)
parameters <- list(taxId=taxId)
##
beid <- paste0(be, "ID")
if(!is.na(rel)){
cql <- c(cql, sprintf('MATCH (beid)-[:%s]->()', rel))
}
if(direct){
cql <- c(cql, sprintf(
'MATCH (beid:%s)-[:identifies]->(be)',
beid
))
}else{
cql <- c(cql, sprintf(
paste0(
'MATCH (beid:%s)',
ifelse(
restricted,
'-[:is_associated_to*0..]->',
'-[:is_replaced_by|is_associated_to*0..]->'
),
'(:%s)-[:identifies]->(be)'
),
beid, beid
))
}
cql <- c(
cql,
'WITH DISTINCT beid, be',
'RETURN beid.database as database, count(DISTINCT be) as nbBe',
', count(DISTINCT beid) as nbId'
)
if(verbose){
message(neo2R::prepCql(cql))
}
##
tn <- gsub(
"[^[:alnum:]]", "_",
paste(
fn,
be, taxId,
rel,
ifelse(direct, "direct", "indirect"),
ifelse(restricted, "restricted", "full"),
sep="_"
)
)
toRet <- cacheBedCall(
f=neo2R::cypher,
query=neo2R::prepCql(cql),
parameters=parameters,
tn=tn,
recache=recache
)
if(!is.null(toRet)){
toRet$be <- be
toRet <- toRet[which(!toRet$database %in% exclude),]
}
return(toRet)
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/listBeIdSources.R |
#' List all attributes provided by a BEDB
#'
#' @param dbname the name of the database
#'
#' @return A character vector of attribute names
#'
#' @export
#'
listDBAttributes <- function(dbname){
if(length(dbname)!=1){
stop("dbname should be a character vector of lenght 1")
}
bedCall(
neo2R::cypher,
query=neo2R::prepCql(c(
'MATCH (db:BEDB {name:$dbname})-[:provides]->(at:Attribute)',
'RETURN DISTINCT at.name'
)),
parameters=list(
dbname=as.character(dbname)
)
)$at.name
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/listDBAttributes.R |
#' Lists all the organisms available in the BED database
#'
#' @return A character vector of organism scientific names
#'
#' @seealso [listPlatforms], [listBeIdSources],
#' [listBe], [getTaxId], [getOrgNames]
#'
#' @export
#'
listOrganisms <- function(){
cql <- c(
'MATCH (t)-[:is_named {nameClass:"scientific name"}]->(o:OrganismName)',
'RETURN DISTINCT o.value as name'
)
toRet <- bedCall(neo2R::cypher, neo2R::prepCql(cql))
return(toRet$name)
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/listOrganisms.R |
#' Lists all the probe platforms available in the BED database
#'
#' @param be a character vector of BE on which to focus.
#' if NA (default) all the BE are considered.
#'
#' @return A data.frame mapping platforms to BE with the following fields:
#'
#' - **name**: the platform nam
#' - **description**: platform description
#' - **focus**: Targeted BE
#'
#' @examples \dontrun{
#' listPlatforms(be="Gene")
#' listPlatforms()
#' }
#'
#' @seealso [listBe], [listBeIdSources],
#' [listOrganisms], [getTargetedBe]
#'
#' @export
#'
listPlatforms <- function(be=c(NA, listBe())){
be <- match.arg(be)
cql <- 'MATCH (p:Platform)-[:is_focused_on]->(be:BEType)'
if(!is.na(be)){
cql <- c(
cql,
sprintf(
'WHERE be.value IN $bes'
)
)
}
cql <- c(
cql,
'RETURN p.name as name, p.description as description, be.value as focus'
)
toRet <- bedCall(
neo2R::cypher,
query=neo2R::prepCql(cql),
parameters=list(bes=as.list(as.character(be)))
)
rownames(toRet) <- toRet$name
return(toRet)
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/listPlatforms.R |
#' Feeding BED: Load biological entities in BED
#'
#' Not exported to avoid unintended modifications of the DB.
#'
#' @param d a data.frame with information about the entities to be loaded.
#' It should contain the following fields: "id".
#' If there is a boolean column named "preferred", the value is loaded.
#' @param be a character corresponding to the BE type (default: "Gene")
#' @param dbname the DB from which the BE ID are taken
#' @param version the version of the DB from which the BE IDs are taken
#' @param deprecated NA (default) or the date when the ID was deprecated
#' @param taxId the taxonomy ID of the BE organism
#' @param onlyId a logical. If TRUE, only an BEID is created and not the
#' corresponding BE.
#'
loadBE <- function(
d,
be="Gene",
dbname,
version=NA,
deprecated=NA,
taxId=NA,
onlyId=FALSE
){
beid <- paste0(be, "ID")
##
dColNames <- c("id")
if(any(!dColNames %in% colnames(d))){
stop(paste(
"The following columns are missing:",
paste(setdiff(dColNames, colnames(d)), collapse=", ")
))
}
##
prefInfo <- "preferred" %in% colnames(d)
if(prefInfo){
toImport <- unique(d[, c("id", "preferred"), drop=F])
if(!inherits(d$preferred, "logical") || any(is.na(d$preferred))){
stop("preferred column should be logical values without any NA")
}
if(length(unique(d$id)) != nrow(d)){
stop("Each id should have only one preferred value")
}
}else{
toImport <- unique(d[, "id", drop=F])
}
################################################
## Add IDs
if(prefInfo){
cql <- sprintf(
'MERGE (beid:%s:BEID {value: row.id, database:$db})',
beid
)
prefStr <- '(case row.preferred when "TRUE" then true else false end)'
cql <- c(
cql,
sprintf(
'ON CREATE SET beid.preferred=%s',
prefStr
),
sprintf(
'ON MATCH SET beid.preferred=%s',
prefStr
)
)
}else{
cql <- c(
sprintf(
'MERGE (beid:%s:BEID {value: row.id, database:$db})',
beid
),
'ON CREATE SET beid.preferred=false'
)
}
##
bedImport(cql, toImport, parameters=list(db=dbname))
if(!onlyId){
cql <- c(
sprintf(
'MATCH (beid:%s {value: row.id, database:$db})',
beid
),
sprintf(
'USING INDEX beid:%s(value)',
beid
),
sprintf(
'MERGE (beid)-[:identifies]->(be:%s)',
be
)
)
##
bedImport(cql, toImport, parameters=list(db=dbname))
}
#########################
## Database and organism
if(inherits(deprecated, "Date")){
depStr <- paste0('"', format(deprecated, "%Y%m%d"), '"')
}else{
if(!is.na(deprecated)){
stop("Provide a date for deprecation")
}else{
depStr <- "false"
}
}
dbcql <- '(db:BEDB{name:$db})'
if(!is.na(version)){
cql <- c('MERGE', dbcql)
##
bedCall(neo2R::cypher, neo2R::prepCql(cql), parameters=list(db=dbname))
cql <- c(
sprintf(
'MATCH (beid:%s {value: row.id, database:$db})',
beid
),
sprintf(
'USING INDEX beid:%s(value)',
beid
),
'MATCH', dbcql,
'MERGE (beid)',
sprintf(
'-[:is_recorded_in {version:"%s", deprecated:%s}]->',
version, depStr
),
'(db)'
)
##
bedImport(cql, toImport, parameters=list(db=dbname))
}else{
if(!is.na(deprecated)){
cql <- c('MERGE', dbcql)
##
bedCall(neo2R::cypher, neo2R::prepCql(cql), parameters=list(db=dbname))
cql <- c(
sprintf(
'MATCH (beid:%s {value: row.id, database:$db})',
beid
),
sprintf(
'USING INDEX beid:%s(value)',
beid
),
'MATCH', dbcql,
'MERGE (beid)',
sprintf(
'-[:is_recorded_in {deprecated:%s}]->',
depStr
),
'(db)'
)
##
bedImport(cql, toImport, parameters=list(db=dbname))
}
}
if(!is.na(taxId)){
orgcql <- sprintf(
'(o:TaxID {value:"%s"})',
taxId
)
cql <- c('MERGE', orgcql)
##
bedCall(neo2R::cypher, neo2R::prepCql(cql), parameters=list(db=dbname))
if(be=="Gene"){
cql <- c(
sprintf(
'MATCH (beid:%s {value: row.id, database:$db})',
beid
),
sprintf(
'USING INDEX beid:%s(value)',
beid
),
'MATCH (beid)-[:identifies]->(be)',
'MATCH', orgcql,
'MERGE (be)-[:belongs_to]->(o)'
)
}
##
bedImport(cql, toImport, parameters=list(db=dbname))
}
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/loadBE.R |
#' Feeding BED: Load names associated to BEIDs
#'
#' Not exported to avoid unintended modifications of the DB.
#'
#' @param d a data.frame with information about the names
#' to be loaded. It should contain the following fields: "id", "name".
#' @param be a character corresponding to the BE type (default: "Gene")
#' @param dbname the DB of BEID
#'
loadBENames <- function(d, be="Gene", dbname){
beid <- paste0(be, "ID")
##
dColNames <- c("id", "name")
if(any(!dColNames %in% colnames(d))){
stop(paste(
"The following columns are missing:",
paste(setdiff(dColNames, colnames(d)), collapse=", ")
))
}
################################################
cql <- c(
sprintf(
'MERGE (n:BEName {value:row.name, value_up:%s(row.name)})',
bedEnv$neo4j_syntax$upper
)
)
bedImport(cql, unique(d[,"name", drop=FALSE]))
################################################
cql <- c(
sprintf(
'MATCH (beid:%s {value:row.id, database:"%s"}) USING INDEX beid:%s(value)',
beid, dbname, beid
),
'MATCH (n:BEName {value:row.name})',
'MERGE (beid)-[:is_named]->(n)'
)
bedImport(cql, d)
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/loadBENames.R |
#' Feeding BED: Load symbols associated to BEIDs
#'
#' Not exported to avoid unintended modifications of the DB.
#'
#' @param d a data.frame with information about the symbols
#' to be loaded. It should contain the following fields: "id", "symbol"
#' and "canonical" (optional).
#' @param be a character corresponding to the BE type (default: "Gene")
#' @param dbname the DB of BEID
#'
loadBESymbols <- function(d, be="Gene", dbname){
beid <- paste0(be, "ID")
##
dColNames <- c("id", "symbol")
if(any(!dColNames %in% colnames(d))){
stop(paste(
"The following columns are missing:",
paste(setdiff(dColNames, colnames(d)), collapse=", ")
))
}
################################################
cql <- c(
sprintf(
'MERGE (s:BESymbol {value:row.symbol, value_up:%s(row.symbol)})',
bedEnv$neo4j_syntax$upper
)
)
bedImport(cql, unique(d[,"symbol", drop=FALSE]))
################################################
cql <- c(
sprintf(
'MATCH (beid:%s {value:row.id, database:"%s"}) USING INDEX beid:%s(value)',
beid, dbname, beid
),
'MATCH (s:BESymbol {value:row.symbol})',
'MERGE (beid)-[r:is_known_as]->(s)'
)
if("canonical" %in% colnames(d)){
cql <- c(
cql,
sprintf(
'SET r.canonical=%s',
'(case row.canonical when "TRUE" then true else false end)'
)
)
}else{
cql <- c(
cql,
'ON CREATE SET r.canonical=false'
)
}
bedImport(cql, d)
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/loadBESymbols.R |
#' Feeding BED: Load biological entities in BED with information about
#' DB version
#'
#' Not exported to avoid unintended modifications of the DB.
#'
#' @param d a data.frame with information about the entities to be loaded.
#' It should contain the following fields: "id", "version" and "deprecated".
#' @param be a character corresponding to the BE type (default: "Gene")
#' @param dbname the DB from which the BE ID are taken
#' @param taxId the taxonomy ID of the BE organism
#' @param onlyId a logical. If TRUE, only an BEID is created and not the
#' corresponding BE.
#'
loadBEVersion <- function(
d, be="Gene", dbname,
taxId=NA,
onlyId=FALSE
){
beid <- paste0(be, "ID")
##
dColNames <- c("id", "version", "deprecated")
if(any(!dColNames %in% colnames(d))){
stop(paste(
"The following columns are missing:",
paste(setdiff(dColNames, colnames(d)), collapse=", ")
))
}
##
prefInfo <- "preferred" %in% colnames(d)
if(prefInfo){
toImport <- unique(d[, c("id", "version", "deprecated", "preferred"), drop=F])
if(!inherits(d$preferred, "logical") || any(is.na(d$preferred))){
stop("preferred column should be logical values without any NA")
}
if(length(unique(d$id)) != nrow(d)){
stop("Each id should have only one preferred value")
}
}else{
toImport <- unique(d[, c("id", "version", "deprecated"), drop=F])
}
################################################
## Add IDs
if(prefInfo){
prefStr <- '(case row.preferred when "TRUE" then true else false end)'
cql <- c(
sprintf(
'MERGE (beid:%s:BEID {value: row.id, database: "%s"})',
beid, dbname
),
sprintf(
'ON CREATE SET beid.preferred=%s',
prefStr
),
sprintf(
'ON MATCH SET beid.preferred=%s',
prefStr
)
)
}else{
cql <- c(
sprintf(
'MERGE (beid:%s:BEID {value: row.id, database: "%s"})',
beid, dbname
),
'ON CREATE SET beid.preferred=false'
)
}
##
bedImport(cql, toImport)
if(!onlyId){
cql <- c(
sprintf(
'MATCH (beid:%s {value: row.id, database: "%s"})',
beid, dbname
),
sprintf(
'USING INDEX beid:%s(value)',
beid
),
sprintf(
'MERGE (beid)-[:identifies]->(be:%s)',
be
)
)
##
bedImport(cql, toImport)
}
#########################
## Database and organism
dbcql <- sprintf(
'(db:BEDB{name: "%s"})',
dbname
)
cql <- c('MERGE', dbcql)
##
bedCall(neo2R::cypher, neo2R::prepCql(cql))
cql <- c(
sprintf(
'MATCH (beid:%s {value: row.id, database: "%s"})',
beid, dbname
),
sprintf(
'USING INDEX beid:%s(value)',
beid
),
'MATCH', dbcql,
'MERGE (beid)',
'-[:is_recorded_in {version:row.version, deprecated:row.deprecated}]->',
'(db)'
)
##
bedImport(cql, toImport)
if(!is.na(taxId)){
orgcql <- sprintf(
'(o:TaxID {value:"%s"})',
taxId
)
cql <- c('MERGE', orgcql)
##
bedCall(neo2R::cypher, neo2R::prepCql(cql))
if(be=="Gene"){
cql <- c(
sprintf(
'MATCH (beid:%s {value: row.id, database: "%s"})',
beid, dbname
),
sprintf(
'USING INDEX beid:%s(value)',
beid
),
'MATCH (beid)-[:identifies]->(be)',
'MATCH', orgcql,
'MERGE (be)-[:belongs_to]->(o)'
)
}
##
bedImport(cql, toImport)
}
#########################
# message(cql)
bedImport(cql, toImport)
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/loadBEVersion.R |
#' Feeding BED: Load attributes for biological entities in BED
#'
#' Not exported to avoid unintended modifications of the DB.
#'
#' @param d a data.frame providing for each BE ID ("id" column) an attribute
#' value ("value" column). There can be several values for each id.
#' @param be a character corresponding to the BE type (default: "Gene")
#' @param dbname the DB from which the BE ID are taken
#' @param attribute the name of the attribute to be loaded
#'
loadBeAttribute <- function(
d,
be="Gene",
dbname,
attribute
){
beid <- paste0(be, "ID")
##
dColNames <- c("id", "value")
if(any(!dColNames %in% colnames(d))){
stop(paste(
"The following columns are missing:",
paste(setdiff(dColNames, colnames(d)), collapse=", ")
))
}
##
if(any(is.na(d$value))){
stop("NA value not allowed")
}
## Associate attribute to DB
cql <- c(
sprintf(
'MATCH (db:BEDB {name: "%s"})',
dbname
),
sprintf(
'MERGE (at:Attribute {name: "%s"})',
attribute
),
'MERGE (db)-[:provides]->(at)'
)
bedCall(neo2R::cypher, query=neo2R::prepCql(cql))
########################
## Load attribute values
toImport <- unique(d[,c("id", "value"), drop=FALSE])
cql <- c(
sprintf(
'MATCH (beid:%s {value:row.id, database:"%s"})',
beid, dbname
),
sprintf(
'USING INDEX beid:%s(value)',
beid
),
sprintf(
'MATCH (at:Attribute {name: "%s"})',
attribute
),
'MERGE (beid)-[:has {value:row.value}]->(at)'
)
bedImport(cql, toImport)
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/loadBeAttribute.R |
###############################################################################@
#' Feeding BED: Load BED data model in neo4j
#'
#' Not exported to avoid unintended modifications of the DB.
#'
loadBedModel <- function(){
pkgname <- utils::packageName()
nmv <- bedEnv$graph$version[1]
if(nmv == "3"){
mfile <- "BED-model-v3.cql"
}
if(nmv == "5"){
mfile <- "BED-model-v5.cql"
}
## Model
cqlFile <- system.file(
"Documentation", "BED-Model",
mfile,
package=pkgname
)
queries <- neo2R::readCql(cqlFile)
for(query in queries){
bedCall(neo2R::cypher, query=query)
}
## Entity types
cqlFile <- system.file(
"Documentation", "BED-Model", "BEType.cql",
package=pkgname
)
queries <- neo2R::readCql(cqlFile)
for(query in queries){
bedCall(neo2R::cypher, query=query)
}
##
invisible(TRUE)
}
###############################################################################@
#' Feeding BED: Load additional indexes in neo4j
#'
#' Not exported to avoid unintended modifications of the DB.
#'
loadBedOtherIndexes <- function(){
pkgname <- utils::packageName()
## Model
cqlFile <- system.file(
"Documentation", "BED-Model", "BED-other-indexes.cql",
package=pkgname
)
queries <- neo2R::readCql(cqlFile)
for(query in queries){
bedCall(neo2R::cypher, query=query)
}
##
invisible(TRUE)
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/loadBedModel.R |
#' Feeding BED: Load correspondance between genes and objects as coding events
#'
#' Not exported to avoid unintended modifications of the DB.
#'
#' @param d a data.frame with information about the coding events.
#' It should contain the following fields: "gid" and "oid"
#' @param gdb the DB of Gene IDs
#' @param odb the DB of Object IDs
#'
loadCodesFor <- function(
d, gdb, odb
){
##
dColNames <- c("gid", "oid")
if(any(!dColNames %in% colnames(d))){
stop(paste(
"The following columns are missing:",
paste(setdiff(dColNames, colnames(d)), collapse=", ")
))
}
################################################
cql <- c(
sprintf(
'MATCH (gid:GeneID {value:row.gid, database:"%s"})',
gdb
),
'USING INDEX gid:GeneID(value)',
sprintf(
'MATCH (oid:ObjectID {value:row.oid, database:"%s"})',
odb
),
'USING INDEX oid:ObjectID(value)',
"MERGE (gid)-[r:codes_for]->(oid)"
)
##
bedImport(cql, d)
################################################
cql <- c(
sprintf(
'MATCH (gid:GeneID {value:row.gid, database:"%s"})',
gdb
),
'USING INDEX gid:GeneID(value)',
'MATCH (gid)-[:is_associated_to*0..]->()',
'-[:identifies]->(g:Gene)',
sprintf(
'MATCH (oid:ObjectID {value:row.oid, database:"%s"})',
odb
),
'USING INDEX oid:ObjectID(value)',
'MATCH (oid)-[:is_associated_to*0..]->()',
'-[:identifies]->(o:Object)',
"MERGE (g)-[r2:codes_for]->(o)"
)
##
bedImport(cql, d)
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/loadCodesFor.R |
#' Feeding BED: Load correspondances between BE IDs
#'
#' Not exported to avoid unintended modifications of the DB.
#'
#' @param d a data.frame with information about the correspondances
#' to be loaded. It should contain the following fields: "id1" and "id2".
#' @param db1 the DB of id1
#' @param db2 the DB of id2
#' @param be a character corresponding to the BE type (default: "Gene")
#'
loadCorrespondsTo <- function(
d,
db1, db2,
be="Gene"
){
beid <- paste0(be, "ID", sep="")
##
dColNames <- c("id1", "id2")
if(any(!dColNames %in% colnames(d))){
stop(paste(
"The following columns are missing:",
paste(setdiff(dColNames, colnames(d)), collapse=", ")
))
}
################################################
if(db1==db2){
toKeep <- which(d$id1 != d$id2)
undirRel <- apply(
d, 1,
function(x) paste(sort(x), collapse=".")
)
toKeep <- intersect(toKeep, which(!duplicated(undirRel)))
d <- d[toKeep,]
}
################################################
## First record the corresponds edges before clustering BE
cql <- c(
sprintf(
paste(
'MATCH',
'(beid1:%s',
'{value: row.id1, database:"%s"}',
')'
),
beid, db1
),
sprintf(
'USING INDEX beid1:%s(value)',
beid
),
sprintf(
paste(
'MATCH',
'(beid2:%s',
'{value: row.id2, database:"%s"})'
),
beid, db2
),
sprintf(
'USING INDEX beid2:%s(value)',
beid
),
"MERGE (beid2)-[:corresponds_to]-(beid1)"
)
bedImport(cql, d)
################################################
## Clustering BE according to relationships
odb1 <- db1
odb2 <- db2
rem <- d
db1 <- odb1
db2 <- odb2
message(nrow(rem))
while(nrow(rem) > 0){
# rem <- d
# db1 <- odb1
# db2 <- odb2
##
if(db1==db2){
id <- unique(c(rem$id1, rem$id2))
cql <- c(
sprintf(
'MATCH (beid:%s)-[:identifies]->(be)',
beid
),
'WHERE beid.database=$db',
'AND beid.value IN $limitTo'
)
cql <- c(
cql,
'RETURN beid.value as id1, id(be) as be1'
)
qres <- bedCall(
f=neo2R::cypher,
query=neo2R::prepCql(cql),
parameters=list(
db=db1,
limitTo=as.list(as.character(id))
)
)
if(is.null(qres)){
qres <- data.frame(id1=character(), be1=numeric())
}
colnames(qres) <- c("id1", "be1")
rem <- dplyr::inner_join(rem, qres, by="id1")
colnames(qres) <- c("id2", "be2")
rem <- dplyr::inner_join(rem, qres, by="id2")
}else{
##
id <- unique(rem$id1)
cql <- c(
sprintf(
'MATCH (beid:%s)-[:identifies]->(be)',
beid
),
'WHERE beid.database=$db',
'AND beid.value IN $limitTo'
)
cql <- c(
cql,
'RETURN beid.value as id1, id(be) as be1'
)
qres <- bedCall(
f=neo2R::cypher, query=neo2R::prepCql(cql),
parameters=list(
db=db1,
limitTo=as.list(as.character(id))
)
)
if(is.null(qres)){
qres <- data.frame(id1=character(), be1=numeric())
}
colnames(qres) <- c("id1", "be1")
rem <- dplyr::inner_join(rem, qres, by="id1")
##
id <- unique(rem$id2)
cql <- c(
sprintf(
'MATCH (beid:%s)-[:identifies]->(be)',
beid
),
'WHERE beid.database=$db',
'AND beid.value IN $limitTo'
)
cql <- c(
cql,
'RETURN beid.value as id2, id(be) as be2'
)
qres <- bedCall(
f=neo2R::cypher, query=neo2R::prepCql(cql),
parameters=list(
db=db2,
limitTo=as.list(as.character(id))
)
)
if(is.null(qres)){
qres <- data.frame(id2=character(), be2=numeric())
}
colnames(qres) <- c("id2", "be2")
rem <- dplyr::inner_join(rem, qres, by="id2")
}
##
## Filter uninformative nodes
rem <- rem[which(rem$be1!=rem$be2),]
rem <- rem[
!duplicated(t(apply(
rem[,c("be1", "be2")],
1,
sort
))),
]
if(nrow(rem)==0){
break()
}
rownames(rem) <- paste("r", 1:nrow(rem), sep=".")
## Take only compatible nodes for current treatment
# if(sum(!duplicated(rem$be2)) > sum(!duplicated(rem$be1))){
# convCn <- c(
# "id1"="id2", "id2"="id1",
# "be1"="be2", "be2"="be1"
# )
# colnames(rem) <- convCn[colnames(rem)]
# db.tp <- db2
# db2 <- db1
# db1 <- db.tp
# }
##
#######
# toI <- rem
# toI <- toI[sample(1:nrow(toI), nrow(toI), replace=F),]
# tt <- data.frame(
# id=c(toI$be1, toI$be2),
# r=c(1:nrow(toI), 1:nrow(toI))
# )
# tt <- tt[order(tt$r),]
# tt <- tt[which(!duplicated(tt$id)),]
# tt <- tt[which(duplicated(tt$r)),"r"]
# toI2 <- toI[tt,]
# toI2 <- toI2[which(!toI2$be1 %in% toI2$be2),]
# toI <- toI2
#######
toI <- rem[!duplicated(rem$be1),]
toI <- toI[sample(1:nrow(toI), nrow(toI), replace=F),]
##
tt <- data.frame(
id=c(toI$be1, toI$be2),
r=c(1:nrow(toI), 1:nrow(toI))
)
tt <- tt[order(tt$r),]
tt <- tt[which(!duplicated(tt$id)),]
tt <- tt[which(duplicated(tt$r)),"r"]
##
toI1 <- toI[which(!toI$be1 %in% toI$be2),]
toI2 <- toI[tt,]
toI2 <- toI2[which(!toI2$be1 %in% toI2$be2),]
if(nrow(toI2)>nrow(toI1)){
toI <- toI2
}else{
toI <- toI1
}
#######
##
if(nrow(toI)==0){
toI <- rem[1,]
}
toI <- toI[,c("id1", "id2")]
##
cqlId <- c(
sprintf(
paste(
'MATCH',
'(beid1:%s',
'{value: row.id1, database:"%s"}',
')',
'-[:identifies]->(be1:%s)'
),
beid, db1, be
),
sprintf(
'USING INDEX beid1:%s(value)',
beid
),
sprintf(
paste(
'MATCH',
'(beid2:%s',
'{value: row.id2, database:"%s"})',
'-[:identifies]->(be2:%s)'
),
beid, db2, be
),
sprintf(
'USING INDEX beid2:%s(value)',
beid
),
'WITH be1, be2 WHERE be1<>be2'
)
##
cql <- c(
cqlId,
sprintf(
'MATCH (obeid1:%s)-[:identifies]->(be1)',
beid
),
'MERGE (obeid1)-[:identifies]->(be2)'
)
bedImport(cql, toI)
##
if(be=="Gene"){
cql <- c(
cqlId,
'MATCH (be1)-[:belongs_to]->(tid:TaxID)',
'MERGE (be2)-[:belongs_to]->(tid)'
)
bedImport(cql, toI)
cql <- c(
cqlId,
'MATCH (be1)-[:is_expressed_as]->(bet:Transcript)',
'MERGE (be2)-[:is_expressed_as]->(bet)'
)
bedImport(cql, toI)
cql <- c(
cqlId,
'MATCH (be1)-[:codes_for]->(beo:Object)',
'MERGE (be2)-[:codes_for]->(beo)'
)
bedImport(cql, toI)
}else if(be=="Object"){
cql <- c(
cqlId,
'MATCH (beg:Gene)-[:codes_for]->(be1)',
'MERGE (beg)-[:codes_for]->(be2)'
)
bedImport(cql, toI)
}else if(be=="Transcript"){
cql <- c(
cqlId,
'MATCH (beg:Gene)-[:is_expressed_as]->(be1)',
'MERGE (beg)-[:is_expressed_as]->(be2)'
)
bedImport(cql, toI)
cql <- c(
cqlId,
'MATCH (be1)-[:is_translated_in]->(bep:Peptide)',
'MERGE (be2)-[:is_translated_in]->(bep)'
)
bedImport(cql, toI)
}else if(be=="Peptide"){
cql <- c(
cqlId,
'MATCH (bet:Transcript)-[:is_translated_in]->(be1)',
'MERGE (bet)-[:is_translated_in]->(be2)'
)
bedImport(cql, toI)
}else{
stop("Check the loadCorresponds function for the BE: ", be)
}
##
cql <- c(
cqlId,
'MATCH (be1)-[rtodel]-()',
'DELETE rtodel, be1'
)
bedImport(cql, toI)
##
rem <- rem[setdiff(rownames(rem), rownames(toI)), c("id1", "id2")]
message(nrow(rem))
}
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/loadCorrespondsTo.R |
#' Feeding BED: Load history of BEIDs
#'
#' Not exported to avoid unintended modifications of the DB.
#'
#' @param d a data.frame with information about the history.
#' It should contain the following fields: "old" and "new".
#' @param be a character corresponding to the BE type (default: "Gene")
#' @param dbname the DB of BEID
#'
loadHistory <- function(d, dbname, be="Gene"){
beid <- paste0(be, "ID", sep="")
##
dColNames <- c("old", "new")
if(any(!dColNames %in% colnames(d))){
stop(paste(
"The following columns are missing:",
paste(setdiff(dColNames, colnames(d)), collapse=", ")
))
}
################################################
cql <- c(
sprintf(
paste(
'MERGE',
'(old:%s:BEID',
'{value: row.old, database:"%s"}',
')'
),
beid, dbname
),
sprintf(
paste(
'MERGE',
'(new:%s:BEID',
'{value: row.new, database:"%s"})'
),
beid, dbname
)
)
bedImport(cql, d)
################################################
cql <- c(
sprintf(
paste(
'MATCH',
'(old:%s',
'{value: row.old, database:"%s"}',
')'
),
beid, dbname
),
sprintf('USING INDEX old:%s(value)', beid),
sprintf(
paste(
'MATCH',
'(new:%s',
'{value: row.new, database:"%s"})'
),
beid, dbname
),
sprintf('USING INDEX new:%s(value)', beid),
"MERGE (old)-[:is_replaced_by]->(new)"
)
bedImport(cql, d)
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/loadHistory.R |
#' Feeding BED: Load BE ID associations
#'
#' Not exported to avoid unintended modifications of the DB.
#'
#' When associating one id1 to id2, the BE identified by id1
#' is deleted after that its production edges have been transferred
#' to the BE identified by id2.
#' After this operation all id "corresponding_to" id1 do not
#' directly identify any BE as they are supposed to do. Thus,
#' to run this function with id1 involved in "corresponds_to" edges.
#'
#' @param d a data.frame with information about the associations
#' to be loaded. It should contain the following fields: "id1" and "id2".
#' At the end id1 is associated to id2 (this way and not the other).
#' @param db1 the DB of id1
#' @param db2 the DB of id2
#' @param be a character corresponding to the BE type (default: "Gene")
#'
loadIsAssociatedTo <- function(
d,
db1, db2,
be="Gene"
){
beid <- paste0(be, "ID", sep="")
##
dColNames <- c("id1", "id2")
if(any(!dColNames %in% colnames(d))){
stop(paste(
"The following columns are missing:",
paste(setdiff(dColNames, colnames(d)), collapse=", ")
))
}
################################################
if(db1==db2){
toKeep <- which(d$id1 != d$id2)
undirRel <- apply(
d, 1,
function(x) paste(sort(x), collapse=".")
)
toKeep <- intersect(toKeep, which(!duplicated(undirRel)))
d <- d[toKeep,]
}
################################################
## Record the is_associated_to edges
cql <- c(
sprintf(
paste(
'MATCH',
'(beid1:%s',
'{value: row.id1, database:"%s"}',
')'
),
beid, db1
),
sprintf('USING INDEX beid1:%s(value)', beid),
sprintf(
paste(
'MATCH',
'(beid2:%s',
'{value: row.id2, database:"%s"})'
),
beid, db2
),
sprintf('USING INDEX beid2:%s(value)', beid),
"MERGE (beid1)-[:is_associated_to]->(beid2)"
)
bedImport(cql, d)
################################################
## Record the is_associated_to edges
cqlId <- c(
sprintf(
paste(
'MATCH',
'(beid1:%s',
'{value: row.id1, database:"%s"}',
')',
'-[:identifies]->(be1:%s)'
),
beid, db1, be
),
sprintf(
'USING INDEX beid1:%s(value)',
beid
),
sprintf(
paste(
'MATCH',
'(beid2:%s',
'{value: row.id2, database:"%s"})',
'-[:identifies]->(be2:%s)'
),
beid, db2, be
),
sprintf(
'USING INDEX beid2:%s(value)',
beid
),
'WITH be1, be2 WHERE be1<>be2'
)
##
if(be=="Gene"){
cql <- c(
cqlId,
'MATCH (be1)-[:belongs_to]->(tid:TaxID)',
'MERGE (be2)-[:belongs_to]->(tid)'
)
bedImport(cql, d)
cql <- c(
cqlId,
'MATCH (be1)-[:is_expressed_as]->(bet:Transcript)',
'MERGE (be2)-[:is_expressed_as]->(bet)'
)
bedImport(cql, d)
cql <- c(
cqlId,
'MATCH (be1)-[:codes_for]->(beo:Object)',
'MERGE (be2)-[:codes_for]->(beo)'
)
bedImport(cql, d)
}else if(be=="Object"){
cql <- c(
cqlId,
'MATCH (beg:Gene)-[:codes_for]->(be1)',
'MERGE (beg)-[:codes_for]->(be2)'
)
bedImport(cql, d)
}else if(be=="Transcript"){
cql <- c(
cqlId,
'MATCH (beg:Gene)-[:is_expressed_as]->(be1)',
'MERGE (beg)-[:is_expressed_as]->(be2)'
)
bedImport(cql, d)
cql <- c(
cqlId,
'MATCH (be1)-[:is_translated_in]->(bep:Peptide)',
'MERGE (be2)-[:is_translated_in]->(bep)'
)
bedImport(cql, d)
}else if(be=="Peptide"){
cql <- c(
cqlId,
'MATCH (bet:Transcript)-[:is_translated_in]->(be1)',
'MERGE (bet)-[:is_translated_in]->(be2)'
)
bedImport(cql, d)
}else{
stop("Check the loadCorresponds function for the BE: ", be)
}
##
cql <- c(
cqlId,
'MATCH (be1)-[rtodel]-()',
'DELETE rtodel, be1'
)
bedImport(cql, d)
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/loadIsAssociatedTo.R |
#' Feeding BED: Load correspondance between genes and transcripts as
#' expression events
#'
#' Not exported to avoid unintended modifications of the DB.
#'
#' @param d a data.frame with information about the expression events.
#' It should contain the following fields: "gid", "tid"
#' and "canonical" (optional).
#' @param gdb the DB of Gene IDs
#' @param tdb the DB of Transcript IDs
#'
loadIsExpressedAs <- function(d, gdb, tdb){
##
dColNames <- c("gid", "tid")
if(any(!dColNames %in% colnames(d))){
stop(paste(
"The following columns are missing:",
paste(setdiff(dColNames, colnames(d)), collapse=", ")
))
}
################################################
cql <- c(
sprintf(
'MATCH (gid:GeneID {value:row.gid, database:"%s"})',
gdb
),
'USING INDEX gid:GeneID(value)',
sprintf(
'MATCH (tid:TranscriptID {value:row.tid, database:"%s"})',
tdb
),
'USING INDEX tid:TranscriptID(value)',
"MERGE (gid)-[r:is_expressed_as]->(tid)"
)
if("canonical" %in% colnames(d)){
canStr <- '(case row.canonical when "TRUE" then true else false end)'
cql <- c(
cql,
sprintf(
'ON CREATE SET r.canonical=%s',
canStr
)
)
}else{
cql <- c(
cql,
'ON CREATE SET r.canonical=false'
)
}
##
bedImport(cql, d)
################################################
cql <- c(
sprintf(
'MATCH (gid:GeneID {value:row.gid, database:"%s"})',
gdb
),
'USING INDEX gid:GeneID(value)',
'MATCH (gid)-[:is_associated_to*0..]->()',
'-[:identifies]->(g:Gene)',
sprintf(
'MATCH (tid:TranscriptID {value:row.tid, database:"%s"})',
tdb
),
'USING INDEX tid:TranscriptID(value)',
'MATCH (tid)-[:is_associated_to*0..]->()',
'-[:identifies]->(t:Transcript)',
"MERGE (g)-[r2:is_expressed_as]->(t)"
)
##
bedImport(cql, d)
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/loadIsExpressedAs.R |
#' Feeding BED: Load homology between BE IDs
#'
#' Not exported to avoid unintended modifications of the DB.
#'
#' @param d a data.frame with information about the homologies
#' to be loaded. It should contain the following fields: "id1" and "id2".
#' @param db1 the DB of id1
#' @param db2 the DB of id2
#' @param be a character corresponding to the BE type (default: "Gene")
#'
loadIsHomologOf <- function(
d,
db1, db2, be="Gene"
){
beid <- paste0(be, "ID", sep="")
befam <- paste0(be, "IDFamily", sep="")
##
dColNames <- c("id1", "id2")
if(any(!dColNames %in% colnames(d))){
stop(paste(
"The following columns are missing:",
paste(setdiff(dColNames, colnames(d)), collapse=", ")
))
}
################################################
if(db1==db2){
toKeep <- which(d$id1 != d$id2)
undirRel <- apply(
d, 1,
function(x) paste(sort(x), collapse=".")
)
toKeep <- intersect(toKeep, which(!duplicated(undirRel)))
d <- d[toKeep,]
}
################################################
## First record the "is_homolog_of" edges before clustering "Homologs" nodes
cql <- c(
sprintf(
paste(
'MATCH',
'(beid1:%s',
'{value: row.id1, database:"%s"}',
')'
),
beid, db1
),
sprintf('USING INDEX beid1:%s(value)', beid),
sprintf(
paste(
'MATCH',
'(beid2:%s',
'{value: row.id2, database:"%s"})'
),
beid, db2
),
sprintf('USING INDEX beid2:%s(value)', beid),
'MERGE (beid2)-[:is_homolog_of]-(beid1)'
)
bedImport(cql, d)
##
cql <- c(
sprintf(
paste(
'MATCH',
'(beid1:%s',
'{value: row.id1, database:"%s"}',
')'
),
beid, db1
),
sprintf('USING INDEX beid1:%s(value)', beid),
sprintf(
'MERGE (beid1)-[:is_member_of]->(:%s)',
befam
)
)
bedImport(cql, d)
##
cql <- c(
sprintf(
paste(
'MATCH',
'(beid2:%s',
'{value: row.id2, database:"%s"})'
),
beid, db2
),
sprintf('USING INDEX beid2:%s(value)', beid),
sprintf(
'MERGE (beid2)-[:is_member_of]->(:%s)',
befam
)
)
bedImport(cql, d)
################################################
## Clustering "Homologs" nodes according to relationships
odb1 <- db1
odb2 <- db2
rem <- d
db1 <- odb1
db2 <- odb2
message(nrow(rem))
while(nrow(rem) > 0){
##
if(db1==db2){
id <- unique(c(rem$id1, rem$id2))
cql <- c(
sprintf(
'MATCH (beid:%s)-[:is_member_of]->(bef)',
beid
),
'WHERE beid.database=$db',
'AND beid.value IN $limitTo'
)
cql <- c(
cql,
'RETURN beid.value as id1, id(bef) as bef1'
)
qres <- bedCall(
f=neo2R::cypher, neo2R::prepCql(cql),
parameters=list(
db=db1,
limitTo=as.list(as.character(id))
)
)
if(is.null(qres)){
qres <- data.frame(id1=character(), bef1=numeric())
}
colnames(qres) <- c("id1", "bef1")
rem <- dplyr::inner_join(rem, qres, by="id1")
colnames(qres) <- c("id2", "bef2")
rem <- dplyr::inner_join(rem, qres, by="id2")
}else{
##
id <- unique(rem$id1)
cql <- c(
sprintf(
'MATCH (beid:%s)-[:is_member_of]->(bef)',
beid
),
'WHERE beid.database=$db',
'AND beid.value IN $limitTo'
)
cql <- c(
cql,
'RETURN beid.value as id1, id(bef) as bef1'
)
qres <- bedCall(
f=neo2R::cypher, neo2R::prepCql(cql),
parameters=list(
db=db1,
limitTo=as.list(as.character(id))
)
)
if(is.null(qres)){
qres <- data.frame(id1=character(), bef1=numeric())
}
colnames(qres) <- c("id1", "bef1")
rem <- dplyr::inner_join(rem, qres, by="id1")
##
id <- unique(rem$id2)
cql <- c(
sprintf(
'MATCH (beid:%s)-[:is_member_of]->(bef)',
beid
),
'WHERE beid.database=$db',
'AND beid.value IN $limitTo'
)
cql <- c(
cql,
'RETURN beid.value as id2, id(bef) as bef2'
)
qres <- bedCall(
f=neo2R::cypher, neo2R::prepCql(cql),
parameters=list(
db=db2,
limitTo=as.list(as.character(id))
)
)
if(is.null(qres)){
qres <- data.frame(id2=character(), bef2=numeric())
}
colnames(qres) <- c("id2", "bef2")
rem <- dplyr::inner_join(rem, qres, by="id2")
}
##
## Filter uninformative nodes
rem <- rem[which(rem$bef1!=rem$bef2),]
rem <- rem[
!duplicated(t(apply(
rem[,c("bef1", "bef2")],
1,
sort
))),
]
if(nrow(rem)==0){
break()
}
rownames(rem) <- paste("r", 1:nrow(rem), sep=".")
#######
toI <- rem[!duplicated(rem$bef1),]
toI <- toI[sample(1:nrow(toI), nrow(toI), replace=F),]
##
tt <- data.frame(
id=c(toI$bef1, toI$bef2),
r=c(1:nrow(toI), 1:nrow(toI))
)
tt <- tt[order(tt$r),]
tt <- tt[which(!duplicated(tt$id)),]
tt <- tt[which(duplicated(tt$r)),"r"]
##
toI1 <- toI[which(!toI$bef1 %in% toI$bef2),]
toI2 <- toI[tt,]
toI2 <- toI2[which(!toI2$bef1 %in% toI2$bef2),]
if(nrow(toI2)>nrow(toI1)){
toI <- toI2
}else{
toI <- toI1
}
#######
##
if(nrow(toI)==0){
toI <- rem[1,]
}
toI <- toI[,c("id1", "id2")]
##
cqlId <- c(
sprintf(
paste(
'MATCH',
'(beid1:%s',
'{value: row.id1, database:"%s"}',
')',
'-[:is_member_of]->(bef1:%s)'
),
beid, db1, befam
),
sprintf('USING INDEX beid1:%s(value)', beid),
sprintf(
paste(
'MATCH',
'(beid2:%s',
'{value: row.id2, database:"%s"})',
'-[:is_member_of]->(bef2:%s)'
),
beid, db2, befam
),
sprintf('USING INDEX beid2:%s(value)', beid),
'WITH bef1, bef2 WHERE bef1<>bef2'
)
##
cql <- c(
cqlId,
sprintf(
'MATCH (obeid1:%s)-[:is_member_of]->(bef1)',
beid
),
'MERGE (obeid1)-[:is_member_of]->(bef2)'
)
bedImport(cql, toI)
##
cql <- c(
cqlId,
'MATCH (bef1)-[rtodel]-()',
'DELETE rtodel, bef1'
)
bedImport(cql, toI)
##
rem <- rem[setdiff(rownames(rem), rownames(toI)), c("id1", "id2")]
message(nrow(rem))
}
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/loadIsHomologOf.R |
#' Feeding BED: Load correspondance between transcripts and peptides as
#' translation events
#'
#' Not exported to avoid unintended modifications of the DB.
#'
#' @param d a data.frame with information about the translation events.
#' It should contain the following fields: "tid", "pid"
#' and "canonical" (optional).
#' @param tdb the DB of Transcript IDs
#' @param pdb the DB of Peptide IDs
#'
loadIsTranslatedIn <- function(d, tdb, pdb){
##
dColNames <- c("tid", "pid")
if(any(!dColNames %in% colnames(d))){
stop(paste(
"The following columns are missing:",
paste(setdiff(dColNames, colnames(d)), collapse=", ")
))
}
################################################
cql <- c(
sprintf(
'MATCH (tid:TranscriptID {value:row.tid, database:"%s"})',
tdb
),
'USING INDEX tid:TranscriptID(value)',
sprintf(
'MATCH (pid:PeptideID {value:row.pid, database:"%s"})',
pdb
),
'USING INDEX pid:PeptideID(value)',
"MERGE (tid)-[r:is_translated_in]->(pid)"
)
if("canonical" %in% colnames(d)){
canStr <- '(case row.canonical when "TRUE" then true else false end)'
cql <- c(
cql,
sprintf(
'SET r.canonical=%s',
canStr
)
)
}else{
cql <- c(
cql,
'ON CREATE SET r.canonical=false'
)
}
##
bedImport(cql, d)
################################################
cql <- c(
sprintf(
'MATCH (tid:TranscriptID {value:row.tid, database:"%s"})',
tdb
),
'USING INDEX tid:TranscriptID(value)',
'MATCH (tid)-[:is_associated_to*0..]->()',
'-[:identifies]->(t:Transcript)',
sprintf(
'MATCH (pid:PeptideID {value:row.pid, database:"%s"})',
pdb
),
'USING INDEX pid:PeptideID(value)',
'MATCH (pid)-[:is_associated_to*0..]->()',
'-[:identifies]->(p:Peptide)',
"MERGE (t)-[r2:is_translated_in]->(p)"
)
##
bedImport(cql, d)
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/loadIsTranslatedIn.R |
#' Feeding BED: Create Lucene indexes in neo4j
#'
#' Not exported to avoid unintended modifications of the DB.
#'
loadLuceneIndexes <- function(){
pkgname <- utils::packageName()
nmv <- bedEnv$graph$version[1]
if(nmv == "3"){
mfile <- "BED-lucene-v3.cql"
}
if(nmv == "5"){
mfile <- "BED-lucene-v5.cql"
}
## Indexes
cqlFile <- system.file(
"Documentation", "BED-Model", mfile,
package=pkgname
)
queries <- neo2R::readCql(cqlFile)
for(query in queries){
bedCall(neo2R::cypher, query=query)
}
##
invisible(TRUE)
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/loadLuceneIndexes.R |
#' Feeding BED: Load in BED GO functions associated to Entrez gene IDs
#' from NCBI
#'
#' Not exported to avoid unintended modifications of the DB.
#'
#' @param organism character vector of 1 element corresponding to the organism
#' of interest (e.g. "Homo sapiens")
#' @param reDumpThr time difference threshold between 2 downloads
#' @param ddir path to the directory where the data should be saved
#' @param curDate current date as given by [Sys.Date]
#'
loadNCBIEntrezGOFunctions <- function(
organism,
reDumpThr=100000,
ddir,
curDate
){
################################################
## Organism
taxId <- getTaxId(organism)
################################################
## Dump ----
dumpNcbiDb(
taxOfInt=taxId,
reDumpThr=reDumpThr,
ddir=ddir,
toLoad="gene2go",
curDate=curDate
)
gene2go <- gene2go[which(
gene2go$Category == "Function" & gene2go$Evidence != "ND" &
!gene2go$Qualifier %in% c("NOT", "NOT contributes_to")
),]
################################################
## DB information ----
gdbname <- "EntrezGene"
odbname <- "GO_function"
################################################
## Add objects
message(Sys.time(), " --> Importing GO functions")
toImport <- unique(gene2go[, "GO_ID", drop=F])
colnames(toImport) <- "id"
loadBE(
d=toImport, be="Object",
dbname=odbname,
version=NA,
taxId=NA
)
################################################
## Add GO term as symbols
message(Sys.time(), " --> Importing GO function terms as symbols")
toImport <- unique(gene2go[, c("GO_ID", "GO_term")])
colnames(toImport) <- c("id", "symbol")
if(any(table(toImport$symbol)>1)){
stop("Verify object symbol for NA or blank values")
}
toImport$canonical <- TRUE
loadBESymbols(d=toImport, be="Object", dbname=odbname)
################################################
## Add "codes_for" edges
toImport <- unique(gene2go[,
c("GeneID", "GO_ID")
])
colnames(toImport) <- c("gid", "oid")
loadCodesFor(
d=toImport,
gdb=gdbname,
odb=odbname
)
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/loadNCBIEntrezGOFunctions.R |
#' Feeding BED: Load taxonomic information from NCBI
#'
#' Not exported to avoid unintended modifications of the DB.
#'
#' @param reDumpThr time difference threshold between 2 downloads
#' @param ddir path to the directory where the data should be saved
#' @param orgOfInt organisms of interest: a character vector
#' @param curDate current date as given by [Sys.Date]
#'
loadNcbiTax <- function(
reDumpThr,
ddir,
orgOfInt=c("human", "rat", "mouse"),
curDate
){
names.dmp <- NULL
dumpNcbiTax(
reDumpThr=reDumpThr, ddir=ddir, toDump="names.dmp", curDate=curDate
)
taxNames <- names.dmp[,-seq(2, 8, by=2)]
colnames(taxNames) <- c(
"tax_id", "name_txt", "unique_name", "name_class"
)
###############################
toLoad <- unique(taxNames$tax_id[which(taxNames$name_txt %in% orgOfInt)])
toLoad <- taxNames[which(taxNames$tax_id %in% toLoad),]
loadOrganisms(toLoad)
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/loadNcbiTax.R |
#' Feeding BED: Load organisms in BED
#'
#' Not exported to avoid unintended modifications of the DB.
#'
#' @param d a data.frame with 2 columns named "tax_id" and "name_txt" providing
#' the taxonomic ID for each organism name
#'
loadOrganisms <- function(d){
##
dColNames <- c("tax_id", "name_txt")
if(any(!dColNames %in% colnames(d))){
stop(paste(
"The following columns are missing:",
paste(setdiff(dColNames, colnames(d)), collapse=", ")
))
}
##
toImport <- d
cql <- c(
'MERGE (o:TaxID {value: row.tax_id})',
sprintf(
'MERGE (on:OrganismName {value: row.name_txt, value_up:%s(row.name_txt)})',
bedEnv$neo4j_syntax$upper
),
'MERGE (o)-[:is_named {nameClass: row.name_class}]->(on)'
)
bedImport(cql, toImport)
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/loadOrganisms.R |
#' Feeding BED: Load a probes platform
#'
#' Not exported to avoid unintended modifications of the DB.
#'
#' @param name the name of the platform
#' @param description a description of the platform
#' @param be the type of BE targeted by the platform
#'
loadPlf <- function(name, description, be){
cql <- c(
sprintf(
'MATCH (bet:BEType {value:"%s"})',
be
),
sprintf(
'MERGE (plf:Platform {name:"%s"})',
name
),
sprintf(
'SET plf.description="%s"',
description
),
'MERGE (plf)-[:is_focused_on]->(bet)'
)
bedCall(f=neo2R::cypher, neo2R::prepCql(cql))
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/loadPlf.R |
#' Feeding BED: Load probes targeting BE IDs
#'
#' Not exported to avoid unintended modifications of the DB.
#'
#' @param d a data.frame with information about the entities to be loaded.
#' It should contain the following fields: "id" and "probeID".
#' @param be a character corresponding to the BE
#' targeted by the probes (default: "Transcript")
#' @param platform the plateform gathering the probes
#' @param dbname the DB from which the BE ID are taken
#'
loadProbes <- function(
d,
be="Transcript",
platform,
dbname
){
beid <- paste0(be, "ID")
##
dColNames <- c("id", "probeID")
if(any(!dColNames %in% colnames(d))){
stop(paste(
"The following columns are missing:",
paste(setdiff(dColNames, colnames(d)), collapse=", ")
))
}
##
toLoad <- unique(d[, "probeID", drop=F])
cql <- c(
sprintf(
'MATCH (pl:Platform {name:"%s"})',
platform
),
sprintf(
'MERGE (pid:ProbeID {value:row.probeID, platform: "%s"})',
platform
)
)
bedImport(cql, toLoad)
cql <- c(
sprintf(
'MATCH (pl:Platform {name:"%s"})',
platform
),
sprintf(
'MATCH (pid:ProbeID {value:row.probeID, platform: "%s"})',
platform
),
'USING INDEX pid:ProbeID(value)',
'MERGE (pid)-[:is_in]->(pl)'
)
bedImport(cql, toLoad)
##
cql <- c(
sprintf(
'MATCH (pid:ProbeID {value:row.probeID, platform: "%s"})',
platform
),
'USING INDEX pid:ProbeID(value)',
sprintf(
'MATCH (beid:%s {value:row.id, database: "%s"})',
beid, dbname
),
sprintf('USING INDEX beid:%s(value)', beid),
'MERGE (pid)-[:targets]->(beid)'
)
bedImport(cql, d)
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/loadProbes.R |
#' List all the BED queries in cache and the total size of the cache
#'
#' @param verbose if TRUE (default) prints a message displaying the total
#' size of the cache
#'
#' @return A data.frame giving for each query (row names) its size in Bytes
#' (column "size") and in human readable format (column "hr"). The
#' attribute "Total" corresponds to the sum of all the file size.
#'
#' @seealso [clearBedCache]
#'
#' @export
#'
lsBedCache <- function(verbose=TRUE){
##
sunits <- c("B", "KB", "MB", "GB", "TB")
##
if(!checkBedConn()){
stop("Unsuccessful connection")
}
if(!get("useCache", bedEnv)){
warning("Cache is OFF: nothing to list")
invisible(NULL)
}else{
cache <- get("cache", bedEnv)
if(nrow(cache)==0){
message("Empty cache")
total <- data.frame(
size=0,
hr="0 B",
stringsAsFactors=FALSE
)
rownames(total) <- "Total"
toRet <- data.frame(
size=numeric(),
hr=character(),
stringsAsFactors=FALSE
)
attr(toRet, "Total") <- total
return(toRet)
}
cachedbDir <- dirname(get("cachedbFile", bedEnv))
toRet <- file.size(file.path(cachedbDir, cache$file))
names(toRet) <- cache$name
total <- sum(toRet)
toRetUnits <- log2(toRet)%/%10
toRetHR <- lapply(
1:length(toRet),
function(i){
format(
toRet[i]/(2^(10*toRetUnits[i])),
digit=1,
nsmall=ifelse(toRetUnits[i]==0, 0, 1)
)
}
)
toRet <- data.frame(
size=toRet,
hr=paste(toRetHR, sunits[toRetUnits+1]),
stringsAsFactors=FALSE
)
totalUnits <- log2(total)%/%10
if(is.na(totalUnits)){
totalUnits <- 0
}
totalHR <- format(
total/(2^(10*totalUnits)),
digit=1,
nsmall=ifelse(totalUnits==0, 0, 1)
)
total <- data.frame(
size=total,
hr=paste(totalHR, sunits[totalUnits+1]),
stringsAsFactors=FALSE
)
rownames(total) <- "Total"
attr(toRet, "Total") <- total
if(verbose){
message(paste("Total cache size on disk:", total$hr))
}
return(toRet[order(toRet$size, decreasing=TRUE),])
}
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/lsBedCache.R |
#' Feeding BED: Register a database of biological entities in BED DB
#'
#' Not exported to avoid unintended modifications of the DB.
#'
#' @param name of the database (e.g. "Ens_gene")
#' @param description a short description of the database (e.g. "Ensembl gene")
#' @param currentVersion the version taken into account in BED (e.g. 83)
#' @param idURL the URL template to use to retrieve id information. A '%s'
#' corresponding to the ID should be present in this character vector of
#' length one.
#'
registerBEDB <- function(
name,
description=NA,
currentVersion=NA,
idURL=NA
){
cql <- c(
sprintf(
'MERGE (bedb:BEDB {name:"%s"})',
name
)
)
if(!is.na(description)){
cql <- c(
cql,
sprintf(
'SET bedb.description="%s"',
description
)
)
}
if(!is.na(currentVersion)){
cql <- c(
cql,
sprintf(
'SET bedb.currentVersion="%s"',
currentVersion
)
)
}
if(!is.na(idURL)){
cql <- c(
cql,
sprintf(
'SET bedb.idURL="%s"',
idURL
)
)
}
bedCall(neo2R::cypher, neo2R::prepCql(cql))
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/registerBEDB.R |
#' Search a BEID
#'
#' @param x a character value to search
#' @param clean_id_search clean x to avoid error during ID search.
#' Default: TRUE. Set it to false if you're sure of your lucene query.
#' @param clean_name_search clean x to avoid error during ID search.
#' Default: TRUE. Set it to false if you're sure of your lucene query.
#'
#' @return NULL if there is not any match or
#' a data.frame with the following columns:
#'
#' - **Value**: the matching term
#' - **From**: the type of the matched term (e.g. BESymbol, GeneID...)
#' - **BE**: the matching biological entity (BE)
#' - **BEID**: the BE identifier
#' - **Database**: the BEID reference database
#' - **Preferred**: TRUE if the BEID is considered as a preferred identifier
#' - **Symbol**: BEID canonical symbol
#' - **Name**: BEID name
#' - **Entity**: technical BE identifier
#' - **GeneID**: Corresponding gene identifier
#' - **Gene_DB**: Gene ID database
#' - **Preferred_gene**: TRUE if the GeneID is considered as a preferred identifier
#' - **Gene_symbol**: Gene symbol
#' - **Gene_name**: Gene name
#' - **Gene_entity**: technical gene identifier
#' - **Organism**: gene organism (scientific name)
#'
#' @export
#'
searchBeid <- function(x, clean_id_search=TRUE, clean_name_search=TRUE){
stopifnot(
is.character(x),
length(x)==1,
!is.na(x)
)
clean_search_name <- function(x){
if(nchar(stringr::str_remove_all(x, '[^"]')) %% 2 != 0){
x <- stringr::str_remove_all(x, '"')
}
x <- stringr::str_replace_all(x, '"', '\\\\"')
x <- stringr::str_replace_all(x, "'", "\\\\'")
x <- stringr::str_replace_all(x, stringr::fixed('^'), '\\\\^')
x <- stringr::str_remove_all(x, '~')
x <- stringr::str_remove(x, ' *$')
x <- stringr::str_replace_all(x, ' +', '~ ')
while(
substr(x, nchar(x), nchar(x)) %in%
c(
"+", "-", "&", "|", "!", "(" , ")",
"{", "}", "[", "]", "?", ":", "/",
"~", " "
)
){
x <- substr(x, 1, nchar(x)-1)
}
clean_brack <- function(x, bl, br){
y <- x
yc <- stringr::str_remove_all(
y,
sprintf('[%s][^%s%s]*[%s]', bl, bl, br, br)
)
while(nchar(yc) < nchar(y)){
y <- yc
yc <- stringr::str_remove_all(
y,
sprintf('[%s][^%s%s]*[%s]', bl, bl, br, br)
)
}
if(sum(stringr::str_detect(y, sprintf('[%s%s]', br, bl)))==1){
x <- stringr::str_replace_all(x, sprintf('[%s%s]', br, bl), " ")
}
return(x)
}
x <- clean_brack(x, "(", ")")
x <- clean_brack(x, "{", "}")
x <- clean_brack(x, "\\[", "\\]")
if(nchar(x)>0){
x <- paste0(x, "~")
}
return(x)
}
clean_search_id <- function(x){
x <- stringr::str_remove_all(x, '"')
x <- stringr::str_replace_all(x, "'", "\\\\'")
x <- stringr::str_replace_all(x, stringr::fixed('^'), '\\\\^')
x <- stringr::str_remove_all(x, '~')
x <- stringr::str_remove(x, ' *$')
if(nchar(x)>0){
x <- sprintf('\\"%s\\"', x)
}
return(x)
}
if(clean_id_search) vi <- clean_search_id(x)
if(clean_name_search) vn <- clean_search_name(x)
if(nchar(vi)==0 || nchar(vn)==0){
return(NULL)
}
# 'CALL db.index.fulltext.queryNodes("beid", "%s")',
# 'YIELD node WITH collect(node) as l1',
# 'CALL db.index.fulltext.queryNodes("bename", "%s")',
# 'YIELD node WITH collect(node) as l2, l1',
# 'UNWIND l1+l2 as mn WITH DISTINCT mn limit 50',
# 'MATCH (mn)-[r:targets|is_named|is_known_as*0..1]-(beid:BEID)',
queries <- c(
id=sprintf(
paste(
'CALL db.index.fulltext.queryNodes("beid", "%s")',
'YIELD node WITH DISTINCT node as mn limit 5',
'MATCH (mn)-[r:targets*0..1]-(beid:BEID)'
),
vi
),
name=sprintf(
paste(
'CALL db.index.fulltext.queryNodes("bename", "%s")',
'YIELD node WITH DISTINCT node as mn limit 50',
'MATCH (mn)-[r:is_named|is_known_as]-(beid:BEID)'
),
vn
)
)
queries <- paste(
queries,
paste(
'-[:is_associated_to|is_replaced_by*0..]->()-[:identifies]->(be)',
'MATCH (be)<-[:is_expressed_as|is_translated_in|codes_for*0..2]-(g:Gene)',
'MATCH (gid:GeneID)-[:identifies]->(g)',
'-[:belongs_to]->(:TaxID)',
'-[:is_named {nameClass:"scientific name"}]->(o:OrganismName)',
'OPTIONAL MATCH (beid)-[:is_known_as {canonical:true}]->(bes:BESymbol)',
'OPTIONAL MATCH (beid)-[:is_named]->(ben:BEName)',
'OPTIONAL MATCH (gid)-[:is_known_as {canonical:true}]->(ges:BESymbol)',
'OPTIONAL MATCH (gid)-[:is_named]->(gen:BEName)',
'RETURN DISTINCT',
'mn.value as value,',
'labels(mn) as from,',
'labels(be) as be,',
'beid.value as beid, beid.database as source,',
'beid.preferred as preferred,',
'bes.value as symbol, ben.value as name,',
'id(be) as entity,',
'gid.value as GeneID, gid.database as Gene_source,',
'gid.preferred as preferred_gene,',
'ges.value as Gene_symbol, gen.value as Gene_name,',
'id(g) as Gene_entity, o.value as organism'
)
)
values <- bedCall(
neo2R::multicypher,
queries=queries
)
values <- do.call(rbind, values)
if(is.null(values) || nrow(values)==0){
return(NULL)
}
.data <- NULL
values <- dplyr::mutate(
values,
from=stringr::str_remove(.data$from, "BEID [|][|] "),
be=stringr::str_remove(.data$be, "BEID [|][|] ")
)
return(values)
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/searchBeid.R |
#' Search identifier, symbol or name information
#'
#' **DEPRECATED: use [searchBeid] and [geneIDsToAllScopes] instead.**
#' This function is meant to be used with [getRelevantIds] in order
#' to implement a dictonary of identifiers of interest. First
#' the [searchId] function is used to search a term.
#' Then the [getRelevantIds] function
#' is used to find the corresponding ID in a context of interest.
#'
#' @param searched the searched term. Identifiers are searched by exact match.
#' Symbols and names are also searched for partial match when searched is
#' greater than ncharSymb and ncharName respectively.
#' @param be optional. If provided the search is focused on provided BEs.
#' @param organism optional. If provided the search is focused on provided
#' organisms.
#' @param ncharSymb The minimum number of characters in searched to consider
#' incomplete symbol matches.
#' @param ncharName The minimum number of characters in searched to consider
#' incomplete name matches.
#' @param verbose boolean indicating if the CQL queries should be displayed
#'
#'
#' @return A data frame with the following fields:
#'
#' - **found**: the element found in BED corresponding to the searched term
#' - **be**: the type of the element
#' - **source**: the source of the element
#' - **organism**: the related organism
#' - **entity**: the related entity internal ID
#' - **ebe**: the BE of the related entity
#' - **canonical**: if the symbol is canonical
#' - **gene**: list of the related genes BE internal ID
#'
#' Exact matches are returned first folowed by the shortest elements.
#'
#' @export
#'
#' @seealso [getRelevantIds]
#'
searchId <- function(
searched, be=NULL, organism=NULL,
ncharSymb=4, ncharName=8,
verbose=FALSE
){
warning("Deprecated. Use `searchBeid()` instead.")
##
if(length(searched)!=1){
stop("search should be of length 1")
}
if(!is.null(be)){
match.arg(be, c("Probe", listBe()), several.ok=TRUE)
}
##
parameters <- list(
searched=as.character(searched),
upSearched=toupper(as.character(searched)),
be=as.list(be),
org=as.list(toupper(organism))
)
##
query <- neo2R::prepCql(
'MATCH (n:BEID)-[:is_replaced_by|is_associated_to*0..]->(ni:BEID)',
'WHERE n.value = $searched',
'MATCH (ni)-[:identifies]->(e)',
'WITH DISTINCT n, ni, e',
'MATCH (e)<-[cr:codes_for|is_expressed_as|is_translated_in*0..2]-(g:Gene)',
'MATCH (g)-[:belongs_to]->(t:TaxID)',
'MATCH (t)-[:is_named {nameClass:"scientific name"}]->(o:OrganismName)',
ifelse(
!is.null(be),
'WHERE SIZE(FILTER(x in labels(e) WHERE x IN $be)) > 0',
''
),
ifelse(
!is.null(organism),
'MATCH (t)-[:is_named]->(on:OrganismName) WHERE on.value_up IN $org',
''
),
'RETURN DISTINCT n.value as found',
', labels(e) as be, n.database as source',
', o.value as organism',
', id(e) as entity',
', labels(e) as ebe',
', id(g) as gene'
)
if(verbose) message(query)
beids <- unique(bedCall(
f=neo2R::cypher,
query=query,
parameters=parameters
))
##
query <- neo2R::prepCql(
'MATCH (n:BESymbol)',
ifelse(
nchar(searched)>=ncharSymb,
'WHERE n.value_up CONTAINS $upSearched',
'WHERE n.value_up = $upSearched'
),
'MATCH (n)<-[ik:is_known_as]-(nii:BEID)',
'MATCH (nii)-[:is_replaced_by|is_associated_to*0..]->(ni:BEID)',
'MATCH (ni)-[:identifies]->(e)',
'WITH DISTINCT n, ik, nii, ni, e',
'MATCH (e)<-[cr:codes_for|is_expressed_as|is_translated_in*0..2]-(g:Gene)',
ifelse(
!is.null(be),
# 'WHERE labels(e) IN $be',
'WHERE SIZE(FILTER(x in labels(e) WHERE x IN $be)) > 0',
''
),
'MATCH (g)-[:belongs_to]->(t:TaxID)',
'MATCH (t)-[:is_named {nameClass:"scientific name"}]->(o:OrganismName)',
ifelse(
!is.null(organism),
'MATCH (t)-[:is_named]->(on:OrganismName) WHERE on.value_up IN $org',
''
),
'RETURN DISTINCT n.value as found',
', labels(e) as be, "Symbol" as source',
', o.value as organism',
', id(e) as entity',
', labels(e) as ebe',
', id(g) as gene',
', ik.canonical as canonical'
)
if(verbose) message(query)
besymbs <- unique(bedCall(
f=neo2R::cypher,
query=query,
parameters=parameters
))
##
query <-neo2R::prepCql(
'MATCH (n:BEName)',
ifelse(
nchar(searched)>=ncharName,
'WHERE n.value_up CONTAINS $upSearched',
'WHERE n.value_up = $upSearched'
),
'MATCH (n)<-[:is_named]-(nii:BEID)',
'MATCH (nii)-[:is_replaced_by|is_associated_to*0..]->(ni:BEID)',
'MATCH (ni)-[:identifies]->(e)',
'WITH DISTINCT n, nii, ni, e',
'MATCH (e)<-[cr:codes_for|is_expressed_as|is_translated_in*0..2]-(g:Gene)',
ifelse(
!is.null(be),
# 'WHERE labels(e) IN $be',
'WHERE SIZE(FILTER(x in labels(e) WHERE x IN $be)) > 0',
''
),
'MATCH (g)-[:belongs_to]->(t:TaxID)',
'MATCH (t)-[:is_named {nameClass:"scientific name"}]->(o:OrganismName)',
ifelse(
!is.null(organism),
'MATCH (t)-[:is_named]->(on:OrganismName) WHERE on.value_up IN $org',
''
),
'RETURN DISTINCT n.value as found',
', labels(e) as be, "Name" as source',
', o.value as organism',
', id(e) as entity',
', labels(e) as ebe',
', id(g) as gene'
)
if(verbose) message(query)
benames <- unique(bedCall(
f=neo2R::cypher,
query=query,
parameters=parameters
))
##
query <- neo2R::prepCql(
'MATCH (n:ProbeID)',
'WHERE n.value = $searched',
'WITH DISTINCT n',
'MATCH (n)-[:targets]->(nii:BEID)',
'MATCH (nii)-[:is_replaced_by|is_associated_to*0..]->(ni:BEID)',
'MATCH (ni)-[:identifies]->(e)',
'WITH DISTINCT n, nii, ni, e',
'MATCH (e)<-[cr:codes_for|is_expressed_as|is_translated_in*0..2]-(g:Gene)',
'MATCH (g)-[:belongs_to]->(t:TaxID)',
'MATCH (t)-[:is_named {nameClass:"scientific name"}]->(o:OrganismName)',
'RETURN DISTINCT n.value as found',
', "Probe" as be, n.platform as source',
', o.value as organism',
', id(e) as entity',
', labels(e) as ebe',
', id(g) as gene'
)
if(verbose) message(query)
probes <- unique(bedCall(
f=neo2R::cypher,
query=query,
parameters=parameters
))
##
if(!is.null(beids)){
beids$canonical <- rep(NA, nrow(beids))
}
if(!is.null(benames)){
benames$canonical <- rep(NA, nrow(benames))
}
if(!is.null(probes)){
probes$canonical <- rep(NA, nrow(probes))
}
toRet <- rbind(beids, besymbs, benames, probes)
if(!is.null(toRet) && nrow(toRet)>0){
gcol <- which(colnames(toRet)=="gene")
toRet <- do.call(rbind, by(
toRet,
paste(
toRet$found, toRet$be, toRet$source, toRet$organism,
toRet$entity, toRet$ebe,
sep="/./"
),
function(x){
x2 <- unique(x[,-gcol])
x2$gene <- list(unique(x$gene))
return(x2)
}
))
rownames(toRet) <- NULL
toRet <- toRet[order(toRet$found),]
toRet <- toRet[order(paste(toRet$organism, toRet$be)),]
toRet <- toRet[order(nchar(toRet$found)),]
toRet <- toRet[order(toRet$canonical, decreasing=TRUE),]
toRet <- toRet[order(
toupper(toRet$found)==toupper(as.character(searched)),
decreasing=TRUE
),]
}
return(toRet)
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/searchId.R |
#' Feeding BED: Set the BED version
#'
#' Not exported to avoid unintended modifications of the DB.
#' This function is used when modifying the BED content.
#'
#' @param bedInstance instance of BED to be set
#' @param bedVersion version of BED to be set
#'
setBedVersion <- function(bedInstance, bedVersion){
bedCall(
neo2R::cypher,
query=neo2R::prepCql(c(
'MERGE (n:System {name:"BED"})',
sprintf(
'SET n.instance = "%s"',
bedInstance
),
sprintf(
'SET n.version = "%s"',
bedVersion
)
))
)
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/setBedVersion.R |
#' Show the data model of BED
#'
#' Show the shema of the BED data model.
#'
#' @export
#'
showBedDataModel <- function(){
pkgname <- utils::packageName()
htmlFile <- system.file(
"Documentation", "BED-Model", "BED.html",
package=pkgname
)
utils::browseURL(paste0('file://', htmlFile))
}
| /scratch/gouwar.j/cran-all/cranData/BED/R/showBedDataModel.R |
###############################################################################@
#' Connect to a neo4j BED database
#'
#' @param url a character string. The host and the port are sufficient
#' (e.g: "localhost:5454")
#' @param username a character string
#' @param password a character string
#' @param connection the id of the connection already registered to use. By
#' default the first registered connection is used.
#' @param remember if TRUE connection information is saved localy in a file
#' and used to automatically connect the next time.
#' The default is set to FALSE.
#' All the connections that have been saved can be listed
#' with [lsBedConnections] and any of
#' them can be forgotten with [forgetBedConnection].
#' @param useCache if TRUE the results of large queries can be saved locally
#' in a file. The default is FALSE for policy reasons.
#' But it is recommended to set it to TRUE to improve the speed
#' of recurrent queries.
#' If NA (default parameter) the value is taken from former connection if
#' it exists or it is set to FALSE.
#' @param importPath the path to the import folder for loading information
#' in BED (used only when feeding the database ==> default: NULL)
#' @param .opts a named list identifying the curl
#' options for the handle (see [neo2R::startGraph()]).
#'
#' @return This function does not return any value. It prepares the BED
#' environment to allow transparent DB calls.
#'
#' @details Be careful that you should reconnect to BED database each time
#' the environment is reloaded. It is done automatically if `remember` is
#' set to TRUE.
#'
#' Information about how to get an instance of the BED 'Neo4j' database is
#' provided here:
#' - <https://github.com/patzaw/BED#bed-database-instance-available-as-a-docker-image>
#' - <https://github.com/patzaw/BED#build-a-bed-database-instance>
#'
#' @seealso [checkBedConn], [lsBedConnections], [forgetBedConnection]
#'
#' @export
#'
connectToBed <- function(
url=NULL, username=NULL, password=NULL, connection=1,
remember=FALSE, useCache=NA,
importPath=NULL,
.opts=list()
){
stopifnot(
is.logical(remember), length(remember)==1, !is.na(remember),
is.logical(useCache), length(useCache)==1
)
bedDir <- file.path(Sys.getenv("HOME"), "R", "BED")
if(remember){
dir.create(bedDir, showWarnings=FALSE, recursive=TRUE)
}
conFile <- file.path(bedDir, "BED-Connections.rda")
connections <- list()
if(file.exists(conFile)){
load(conFile)
}
if(length(url)==0 && length(username)==0 && length(password)==0){
if(length(connections)==0){
checkBedConn()
return(FALSE)
}else{
url <- connections[[connection]][["url"]]
username <- connections[[connection]][["username"]]
password <- connections[[connection]][["password"]]
useCache <- ifelse(
is.na(useCache),
connections[[connection]][["cache"]],
useCache
)
.opts <- c(
.opts,
connections[[connection]][[".opts"]]
)
}
connections <- c(connections[connection], connections[-connection])
}else{
if(length(username)==0 && length(password)==0){
username <- password <- NA
}
url <- sub("^https?://", "", url)
if(is.na(useCache)){
useCache <- FALSE
}
connections <- c(
list(list(
url=url, username=username, password=password, cache=useCache,
.opts=.opts
)),
connections
)
}
## The graph DB
e1 <- try(assign(
"graph",
neo2R::startGraph(
url=paste0("https://", url),
username=username,
password=password,
importPath=importPath,
.opts=.opts
),
bedEnv
), silent=TRUE)
if(inherits(e1, "try-error")){
e2 <- try(assign(
"graph",
neo2R::startGraph(
url=paste0("http://", url),
username=username,
password=password,
importPath=importPath,
.opts=.opts
),
bedEnv
), silent=TRUE)
if(inherits(e2, "try-error")){
message(e1)
message(e2)
}
}
assign("useCache", useCache, bedEnv)
corrConn <- checkBedConn(verbose=TRUE)
if(!corrConn){
rm("graph", envir=bedEnv)
return(FALSE)
}else{
connections[[1]][colnames(attr(corrConn, "dbVersion")[1,])] <-
as.character(attr(checkBedConn(), "dbVersion")[1,])
connections[[1]]["cache"] <- useCache
}
nmv <- bedEnv$graph$version[1]
if(nmv == "3"){
neo4j_syntax <- list(
upper = "upper"
)
}
if(nmv == "5"){
neo4j_syntax <- list(
upper = "toUpper"
)
}
assign("neo4j_syntax", neo4j_syntax, bedEnv)
##
if(remember){
connections <- connections[which(
!duplicated(unlist(lapply(
connections,
function(x){
x["url"]
}
)))
)]
save(connections, file=conFile)
}
## File system cache
if(useCache){
dir.create(bedDir, showWarnings=FALSE, recursive=TRUE)
cachedbDir <- file.path(
bedDir,
paste(
sub(
"[:]", "..",
sub(
"[/].*$", "",
sub("^https{0,1}[:][/]{2}", "", url)
)
),
username,
sep=".."
)
)
dir.create(cachedbDir, showWarnings=FALSE, recursive=TRUE)
cachedbFile <- file.path(cachedbDir, "0000-BED-cache.rda")
assign(
"cachedbFile",
cachedbFile,
bedEnv
)
if(file.exists(cachedbFile)){
load(cachedbFile)
}else{
cache <- data.frame(
name=character(),
file=character(),
stringsAsFactors=FALSE
)
}
assign(
"cache",
cache,
bedEnv
)
## Managing cache vs DB version
checkBedCache(newCon=TRUE)
}
}
###############################################################################@
#' List all registered BED connection
#'
#' @seealso [connectToBed], [forgetBedConnection], [checkBedConn]
#'
#' @export
#'
lsBedConnections <- function(){
conFile <- file.path(
Sys.getenv("HOME"), "R", "BED", "BED-Connections.rda"
)
connections <- list()
if(file.exists(conFile)){
load(conFile)
}
return(connections)
}
###############################################################################@
#' Forget a BED connection
#'
#' @param connection the id of the connection to forget.
#' @param save a logical. Should be set to TRUE to save the updated list of
#' connections in the file space (default to FALSE to comply with CRAN
#' policies).
#'
#' @seealso [lsBedConnections], [checkBedConn], [connectToBed]
#'
#' @export
#'
forgetBedConnection <- function(connection, save=FALSE){
conFile <- file.path(
Sys.getenv("HOME"), "R", "BED", "BED-Connections.rda"
)
connections <- list()
if(file.exists(conFile)){
load(conFile)
}
connections <- connections[-connection]
if(save){
save(connections, file=conFile)
}
}
###############################################################################@
bedEnv <- new.env(hash=TRUE, parent=emptyenv())
| /scratch/gouwar.j/cran-all/cranData/BED/R/zzz.R |
## ----setup, echo=FALSE--------------------------------------------------------
library(knitr)
## The following line is to avoid building errors on CRAN
knitr::opts_chunk$set(eval=Sys.getenv("USER") %in% c("pgodard"))
vn_as_png <- function(vn){
html_file <- tempfile(fileext = ".html")
png_file <- tempfile(fileext = ".png")
visSave(vn, html_file)
invisible(webshot::webshot(
html_file, file=png_file, selector=".visNetwork", vwidth="100%"
))
im <- base64enc::dataURI(file=png_file, mime="image/png")
invisible(file.remove(c(html_file,png_file)))
htmltools::div(
width="100%",
htmltools::img(src=im, alt="visNetwork", width="100%")
)
}
## ----eval=FALSE---------------------------------------------------------------
# devtools::install_github("patzaw/BED")
## ----echo=TRUE, eval=FALSE----------------------------------------------------
# file.exists(file.path(Sys.getenv("HOME"), "R", "BED"))
## ----message=FALSE, eval=TRUE-------------------------------------------------
library(BED)
## ----message=FALSE, eval=TRUE, echo=FALSE-------------------------------------
connectToBed()
## ----message=FALSE, eval=FALSE------------------------------------------------
# connectToBed(url="localhost:5454", remember=FALSE, useCache=FALSE)
## ----message=TRUE-------------------------------------------------------------
checkBedConn(verbose=TRUE)
## ----eval=FALSE---------------------------------------------------------------
# lsBedConnections()
## ----eval=FALSE---------------------------------------------------------------
# showBedDataModel()
## ----echo=FALSE, eval=TRUE----------------------------------------------------
htmltools::includeHTML(system.file(
"Documentation", "BED-Model", "BED.html",
package="BED"
))
## -----------------------------------------------------------------------------
results <- bedCall(
cypher,
query=prepCql(
'MATCH (n:BEID)',
'WHERE n.value IN $values',
'RETURN DISTINCT n.value AS value, labels(n), n.database'
),
parameters=list(values=c("10", "100"))
)
results
## -----------------------------------------------------------------------------
listBe()
## -----------------------------------------------------------------------------
firstCommonUpstreamBe(c("Object", "Transcript"))
firstCommonUpstreamBe(c("Peptide", "Transcript"))
## -----------------------------------------------------------------------------
listOrganisms()
## -----------------------------------------------------------------------------
getOrgNames(getTaxId("human"))
## -----------------------------------------------------------------------------
listBeIdSources(be="Transcript", organism="human")
## -----------------------------------------------------------------------------
largestBeSource(be="Transcript", organism="human", restricted=TRUE)
## -----------------------------------------------------------------------------
head(listPlatforms())
getTargetedBe("GPL570")
## -----------------------------------------------------------------------------
beids <- getBeIds(
be="Gene", source="EntrezGene", organism="human",
restricted=FALSE
)
dim(beids)
head(beids)
## -----------------------------------------------------------------------------
sort(table(table(beids$Gene)), decreasing = TRUE)
ambId <- sum(table(table(beids$Gene)[which(table(beids$Gene)>=10)]))
## -----------------------------------------------------------------------------
beids <- getBeIds(
be="Gene", source="EntrezGene", organism="human",
restricted = TRUE
)
dim(beids)
## -----------------------------------------------------------------------------
sort(table(table(beids$Gene)), decreasing = TRUE)
## -----------------------------------------------------------------------------
eid <- beids$id[which(beids$Gene %in% names(which(table(beids$Gene)>=3)))][1]
print(eid)
exploreBe(id=eid, source="EntrezGene", be="Gene") %>%
visPhysics(solver="repulsion") %>%
vn_as_png()
## -----------------------------------------------------------------------------
mapt <- convBeIds(
"MAPT", from="Gene", from.source="Symbol", from.org="human",
to.source="Ens_gene", restricted=TRUE
)
exploreBe(
mapt[1, "to"],
source="Ens_gene",
be="Gene"
) %>%
vn_as_png()
getBeIds(
be="Gene", source="Ens_gene", organism="human",
restricted=TRUE,
attributes=listDBAttributes("Ens_gene"),
filter=mapt$to
)
## -----------------------------------------------------------------------------
oriId <- c(
"17237", "105886298", "76429", "80985", "230514", "66459",
"93696", "72514", "20352", "13347", "100462961", "100043346",
"12400", "106582", "19062", "245607", "79196", "16878", "320727",
"230649", "66880", "66245", "103742", "320145", "140795"
)
idOrigin <- guessIdScope(oriId)
print(idOrigin$be)
print(idOrigin$source)
print(idOrigin$organism)
## -----------------------------------------------------------------------------
print(attr(idOrigin, "details"))
## -----------------------------------------------------------------------------
checkBeIds(ids=oriId, be="Gene", source="EntrezGene", organism="mouse")
## -----------------------------------------------------------------------------
checkBeIds(ids=oriId, be="Gene", source="HGNC", organism="human")
## -----------------------------------------------------------------------------
toShow <- getBeIdDescription(
ids=oriId, be="Gene", source="EntrezGene", organism="mouse"
)
toShow$id <- paste0(
sprintf(
'<a href="%s" target="_blank">',
getBeIdURL(toShow$id, "EntrezGene")
),
toShow$id,
'<a>'
)
kable(toShow, escape=FALSE, row.names=FALSE)
## -----------------------------------------------------------------------------
res <- getBeIdSymbols(
ids=oriId, be="Gene", source="EntrezGene", organism="mouse",
restricted=FALSE
)
head(res)
## -----------------------------------------------------------------------------
res <- getBeIdNames(
ids=oriId, be="Gene", source="EntrezGene", organism="mouse",
restricted=FALSE
)
head(res)
## -----------------------------------------------------------------------------
someProbes <- c(
"238834_at", "1569297_at", "213021_at", "225480_at",
"216016_at", "35685_at", "217969_at", "211359_s_at"
)
toShow <- getGeneDescription(
ids=someProbes, be="Probe", source="GPL570", organism="human"
)
kable(toShow, escape=FALSE, row.names=FALSE)
## -----------------------------------------------------------------------------
getDirectProduct("ENSG00000145335", process="is_expressed_as")
getDirectProduct("ENST00000336904", process="is_translated_in")
getDirectOrigin("NM_001146055", process="is_expressed_as")
## -----------------------------------------------------------------------------
res <- convBeIds(
ids=oriId,
from="Gene",
from.source="EntrezGene",
from.org="mouse",
to.source="Ens_gene",
restricted=TRUE,
prefFilter=TRUE
)
head(res)
## -----------------------------------------------------------------------------
res <- convBeIds(
ids=oriId,
from="Gene",
from.source="EntrezGene",
from.org="mouse",
to="Peptide",
to.source="Ens_translation",
restricted=TRUE,
prefFilter=TRUE
)
head(res)
## -----------------------------------------------------------------------------
res <- convBeIds(
ids=oriId,
from="Gene",
from.source="EntrezGene",
from.org="mouse",
to="Peptide",
to.source="Ens_translation",
to.org="human",
restricted=TRUE,
prefFilter=TRUE
)
head(res)
## -----------------------------------------------------------------------------
humanEnsPeptides <- convBeIdLists(
idList=list(a=oriId[1:5], b=oriId[-c(1:5)]),
from="Gene",
from.source="EntrezGene",
from.org="mouse",
to="Peptide",
to.source="Ens_translation",
to.org="human",
restricted=TRUE,
prefFilter=TRUE
)
unlist(lapply(humanEnsPeptides, length))
lapply(humanEnsPeptides, head)
## -----------------------------------------------------------------------------
entrezGenes <- BEIDList(
list(a=oriId[1:5], b=oriId[-c(1:5)]),
scope=list(be="Gene", source="EntrezGene", organism="Mus musculus"),
metadata=data.frame(
.lname=c("a", "b"),
description=c("Identifiers in a", "Identifiers in b"),
stringsAsFactors=FALSE
)
)
entrezGenes
entrezGenes$a
ensemblGenes <- focusOnScope(entrezGenes, source="Ens_gene")
ensemblGenes$a
## -----------------------------------------------------------------------------
toConv <- data.frame(a=1:25, b=runif(25))
rownames(toConv) <- oriId
res <- convDfBeIds(
df=toConv,
from="Gene",
from.source="EntrezGene",
from.org="mouse",
to.source="Ens_gene",
restricted=TRUE,
prefFilter=TRUE
)
head(res)
## -----------------------------------------------------------------------------
from.id <- "ILMN_1220595"
res <- convBeIds(
ids=from.id, from="Probe", from.source="GPL6885", from.org="mouse",
to="Peptide", to.source="Uniprot", to.org="human",
prefFilter=TRUE
)
res
exploreConvPath(
from.id=from.id, from="Probe", from.source="GPL6885",
to.id=res$to[1], to="Peptide", to.source="Uniprot"
) %>%
vn_as_png()
## -----------------------------------------------------------------------------
compMap <- getBeIdSymbolTable(
be="Gene", source="Ens_gene", organism="rat",
restricted=FALSE
)
dim(compMap)
head(compMap)
## -----------------------------------------------------------------------------
sncaEid <- compMap[which(compMap$symbol=="Snca"),]
sncaEid
compMap[which(compMap$id %in% sncaEid$id),]
## -----------------------------------------------------------------------------
getBeIdDescription(
sncaEid$id,
be="Gene", source="Ens_gene", organism="rat"
)
## -----------------------------------------------------------------------------
convBeIds(
sncaEid$id[1],
from="Gene", from.source="Ens_gene", from.org="rat",
to.source="Symbol"
)
convBeIds(
sncaEid$id[2],
from="Gene", from.source="Ens_gene", from.org="rat",
to.source="Symbol"
)
convBeIds(
sncaEid$id,
from="Gene", from.source="Ens_gene", from.org="rat",
to.source="Symbol"
)
## -----------------------------------------------------------------------------
convBeIds(
sncaEid$id,
from="Gene", from.source="Ens_gene", from.org="rat",
to.source="Symbol",
canonical=TRUE
)
## -----------------------------------------------------------------------------
convBeIds(
"Snca",
from="Gene", from.source="Symbol", from.org="rat",
to.source="Ens_gene"
)
## -----------------------------------------------------------------------------
searched <- searchBeid("sv2A")
toTake <- which(searched$organism=="Homo sapiens")[1]
relIds <- geneIDsToAllScopes(
geneids=searched$GeneID[toTake],
source=searched$Gene_source[toTake],
organism=searched$organism[toTake]
)
## ----eval=FALSE---------------------------------------------------------------
# relIds <- findBeids()
## ----eval=FALSE---------------------------------------------------------------
# library(shiny)
# library(BED)
# library(DT)
#
# ui <- fluidPage(
# beidsUI("be"),
# fluidRow(
# column(
# 12,
# tags$br(),
# h3("Selected gene entities"),
# DTOutput("result")
# )
# )
# )
#
# server <- function(input, output){
# found <- beidsServer("be", toGene=TRUE, multiple=TRUE, tableHeight=250)
# output$result <- renderDT({
# req(found())
# toRet <- found()
# datatable(toRet, rownames=FALSE)
# })
# }
#
# shinyApp(ui = ui, server = server)
## ----echo=FALSE, eval=TRUE----------------------------------------------------
sessionInfo()
| /scratch/gouwar.j/cran-all/cranData/BED/inst/doc/BED.R |
---
title: "Biological Entity Dictionary (BED): exploring and converting identifiers of biological entities such as genes, transcripts or peptides"
package: "BED (version `r packageVersion('BED')`)"
output:
rmarkdown::html_document:
number_sections: yes
self_contained: true
theme: cerulean
toc: yes
toc_float: yes
fig_width: 7
fig_height: 5
vignette: >
%\VignetteIndexEntry{BED}
%\VignetteEncoding{UTF-8}
%\VignetteEngine{knitr::rmarkdown}
editor_options:
chunk_output_type: console
---
```{r setup, echo=FALSE}
library(knitr)
## The following line is to avoid building errors on CRAN
knitr::opts_chunk$set(eval=Sys.getenv("USER") %in% c("pgodard"))
vn_as_png <- function(vn){
html_file <- tempfile(fileext = ".html")
png_file <- tempfile(fileext = ".png")
visSave(vn, html_file)
invisible(webshot::webshot(
html_file, file=png_file, selector=".visNetwork", vwidth="100%"
))
im <- base64enc::dataURI(file=png_file, mime="image/png")
invisible(file.remove(c(html_file,png_file)))
htmltools::div(
width="100%",
htmltools::img(src=im, alt="visNetwork", width="100%")
)
}
```
::: {style="width:200px;"}
{width="100%"}
:::
<!----------------------------------------------------------------------------->
<!----------------------------------------------------------------------------->
# Introduction
This Biological Entity Dictionary (BED)
has been developed to address three main challenges.
The first one is related to the completeness of identifier mappings.
Indeed, direct mapping information provided by the different systems
are not always complete and can be enriched by mappings provided by other
resources.
More interestingly, direct mappings not identified by any of these
resources can be indirectly inferred by using mappings to a third reference.
For example, many human Ensembl gene ID are not directly mapped to any
Entrez gene ID but such mappings can be inferred using respective mappings
to HGNC ID. The second challenge is related to the mapping of deprecated
identifiers. Indeed, entity identifiers can change from one resource
release to another. The identifier history is provided by some resources,
such as Ensembl or the NCBI, but it is generally not used by mapping tools.
The third challenge is related to the automation of the mapping process
according to the relationships between the biological entities of interest.
Indeed, mapping between gene and protein ID scopes should not be done
the same way than between two scopes regarding gene ID.
Also, converting identifiers from different organisms should be possible
using gene orthologs information.
This document shows how to use the **BED (Biological Entity Dictionary)**
R package to get and explore mapping between
identifiers of biological entities (BE).
This package provides a way to connect to a BED Neo4j database in which
the relationships between the identifiers from different sources are recorded.
## Citing BED
This package and the underlying research has been published in
this peer reviewed article:
<a href="`r citation("BED")[1]$url`" target="_blank">
`r sub('[[]', '(', sub('[]]', ')', format(citation("BED"), style="textVersion")))`
</a>
## Installation
### Dependencies
This BED package depends on the following packages available in the CRAN
repository:
- **neo2R**
- **visNetwork**
- **dplyr**
- **readr**
- **stringr**
- **utils**
- **shiny**
- **DT**
- **miniUI**
- **rstudioapi**
All these packages must be installed before installing BED.
### Installation from github
```{r, eval=FALSE}
devtools::install_github("patzaw/BED")
```
### Possible issue when updating from releases <= 1.3.0
If you get an error like the following...
```
Error: package or namespace load failed for ‘BED’:
.onLoad failed in loadNamespace() for 'BED', details:
call: connections[[connection]][["cache"]]
error: subscript out of bounds
```
... remove the BED folder located here:
```{r, echo=TRUE, eval=FALSE}
file.exists(file.path(Sys.getenv("HOME"), "R", "BED"))
```
## Connection
Before using BED, the connection needs to be established with the
underlying Neo4j DB.
`url`, `username` and `password` should be adapted.
```{r, message=FALSE, eval=TRUE}
library(BED)
```
```{r, message=FALSE, eval=TRUE, echo=FALSE}
connectToBed()
```
```{r, message=FALSE, eval=FALSE}
connectToBed(url="localhost:5454", remember=FALSE, useCache=FALSE)
```
The `remember` parameter can be set to `TRUE` in order to save connection
information that will be automatically used the next time the `connectToBed()`
function is called.
By default, this parameter is set to `FALSE` to comply with CRAN policies.
Saved connection can be managed with the `lsBedConnections()` and
the `forgetBedConnection()` functions.
The `useCache` parameter is by default set to `FALSE` to comply with
CRAN policies.
However, it is recommended to set it to `TRUE` to improve the speed
of recurrent queries: the results of some large queries are saved locally
in a file.
The connection can be checked the following way.
```{r, message=TRUE}
checkBedConn(verbose=TRUE)
```
If the `verbose` parameter is set to TRUE, the URL and the content version
are displayed as messages.
The following function list saved connections.
```{r, eval=FALSE}
lsBedConnections()
```
The `connection` param of the `connectToBed` function can be used to
connect to a saved connection other than the last one.
## Data model
The BED underlying data model can be shown at any time using
the following command.
```{r, eval=FALSE}
showBedDataModel()
```
```{r, echo=FALSE, eval=TRUE}
htmltools::includeHTML(system.file(
"Documentation", "BED-Model", "BED.html",
package="BED"
))
```
## Direct calls
Cypher queries can be run directly on the Neo4j database using the
`cypher` function from the **neo2R** package through the `bedCall` function.
```{r}
results <- bedCall(
cypher,
query=prepCql(
'MATCH (n:BEID)',
'WHERE n.value IN $values',
'RETURN DISTINCT n.value AS value, labels(n), n.database'
),
parameters=list(values=c("10", "100"))
)
results
```
## Feeding the database
Many functions are provided within the package to build your own BED database
instance. These functions are not exported in order to avoid their use when
interacting with BED normally.
Information about how to get an instance of the BED neo4j database is
provided here:
- <https://github.com/patzaw/BED#bed-database-instance-available-as-a-docker-image>
- <https://github.com/patzaw/BED#build-a-bed-database-instance>
It can be adapted to user needs.
## Caching
This part is relevant if the `useCache` parameter is set to TRUE when
calling `connectToBed()`.
Functions of the BED package used to retrieve thousands of identifiers
can take some time (generally a few seconds) before returning a result.
Thus for this kind of query, the query is run for all the relevant ID in the DB
and thanks to a cache system implemented in the package same queries
with different filters should be much faster the following times.
By default the cache is flushed when the system detect inconsistencies
with the BED database. However, it can also be manualy flushed if needed using
the `clearBedCache()` function.
Queries already in cache can be listed using the `lsBedCache()` function which
also return the occupied disk space.
<!----------------------------------------------------------------------------->
<!----------------------------------------------------------------------------->
# Exploring available data
## Biological entities
BED is organized around the central concept of **Biological Entity** (BE).
All supported types of BE can be listed.
```{r}
listBe()
```
These BE are organized according to how they are related to each other.
For example a *Gene* *is_expressed_as* a *Transcript*.
This organization allows to find the first upstream BE common to a set of
BE.
```{r}
firstCommonUpstreamBe(c("Object", "Transcript"))
firstCommonUpstreamBe(c("Peptide", "Transcript"))
```
## Organisms
Several organims can be supported by the BED underlying database.
They can be listed the following way.
```{r}
listOrganisms()
```
Common names are also supported and the corresponding taxonomic identifiers
can be retrieved. Conversely the organism names corresponding to a
taxonomic ID can be listed.
```{r}
getOrgNames(getTaxId("human"))
```
## Identifiers of biological entities
The main aim of BED is to allow the mapping of identifiers from different
sources such as Ensembl or Entrez. Supported sources can be listed the
following way for each supported organism.
```{r}
listBeIdSources(be="Transcript", organism="human")
```
The database gathering the largest number of BE of specific type can also
be identified.
```{r}
largestBeSource(be="Transcript", organism="human", restricted=TRUE)
```
Finally, the `getAllBeIdSources()` function returns all
the source databases of BE identifiers whatever the BE type.
## Experimental platforms and probes
BED also supports experimental platforms and provides mapping betweens
probes and BE identifiers (BEID).
The supported platforms can be listed the following way.
The `getTargetedBe()` function returns the type of BE on which a specific
platform focus.
```{r}
head(listPlatforms())
getTargetedBe("GPL570")
```
<!----------------------------------------------------------------------------->
<!----------------------------------------------------------------------------->
# Managing identifiers
## Retrieving all identifiers from a source
All identifiers of an organism BEs from one source can be retrieved.
```{r}
beids <- getBeIds(
be="Gene", source="EntrezGene", organism="human",
restricted=FALSE
)
dim(beids)
head(beids)
```
The first column, *id*, corresponds to the identifiers of the BE in the source.
The column named according to the BE type (in this case *Gene*)
corresponds to the internal identifier of the related BE.
**BE CAREFUL, THIS INTERNAL ID IS NOT STABLE AND CANNOT BE USED AS A REFERENCE**.
This internal identifier is useful to identify BEIDS corresponding to the
same BE. The following code can be used to have an overview of such
redundancy.
```{r}
sort(table(table(beids$Gene)), decreasing = TRUE)
ambId <- sum(table(table(beids$Gene)[which(table(beids$Gene)>=10)]))
```
In the example above we can see that most of Gene BE are identified by only
one EntrezGene ID. However many of them are identified by two or more
ID; `r ifelse(exists("ambId"), ambId, "XXX")` BE
are even identified by 10 or more EntrezGeneID.
In this case, most of these redundancies come from ID history extracted
from Entrez. Legacy ID can be excluded from the retrieved ID
by setting the `restricted` parameter to TRUE.
```{r}
beids <- getBeIds(
be="Gene", source="EntrezGene", organism="human",
restricted = TRUE
)
dim(beids)
```
The same code as above can be used to identify remaining redundancies.
```{r}
sort(table(table(beids$Gene)), decreasing = TRUE)
```
In the example above we can see that allmost all Gene BE are identified by only
one EntrezGene ID. However some of them are identified by two or more ID.
This result comes from how the BED database is constructed according to
the ID mapping provided by the different source databases.
The graph below shows how the mapping was done for such a BE with
redundant EntrezGene IDs.
<strong>
This issue has been mainly solved by not taking into account ambigous mappings
between NCBI Entrez gene identifiers and Ensembl gene identifier provided
by Ensembl. It has been achieved using the `cleanDubiousXRef()` function
from the 2019.10.11 version of the BED-UCB-Human database.
</strong>
<div style="border:solid;overflow:hidden;">
```{r}
eid <- beids$id[which(beids$Gene %in% names(which(table(beids$Gene)>=3)))][1]
print(eid)
exploreBe(id=eid, source="EntrezGene", be="Gene") %>%
visPhysics(solver="repulsion") %>%
vn_as_png()
```
</div>
<br>
The way the ID correspondances are reported in the different source databases
leads to this mapping ambiguity which has to be taken into account
when comparing identifiers from different databases.
The `getBeIds()` returns other columns providing additional
information about the *id*.
The same function can be used to retrieved symbols or probe identifiers.
### Preferred identifier
The BED database is constructed according to the relationships between
identifiers provided by the different sources. Biological entities (BE) are
identified as clusters of identifiers which correspond to each other
directly or indirectly (`corresponds_to` relationship).
Because of this design a BE can be identified by multiple identifiers (BEID)
from the same database as shown above.
These BEID are often related to alternate version of an entity.
For example, Ensembl provides different version (alternative sequences)
of some chromosomes parts. And genes are also annotated on these alternative
sequences. In Uniprot some *unreviewed* identifiers can correspond
to *reviewed* proteins.
When available such kind of information is associated to
an **Attribute** node through a `has` relationship providing the
value of the attribute for the BEID. This information can also
be used to define if a BEID is a *preferred* identifier for
a BE.
The example below shows the case of the MAPT gene annotated on different
version of human chromosome 17.
<div style="border:solid;overflow:hidden;">
```{r}
mapt <- convBeIds(
"MAPT", from="Gene", from.source="Symbol", from.org="human",
to.source="Ens_gene", restricted=TRUE
)
exploreBe(
mapt[1, "to"],
source="Ens_gene",
be="Gene"
) %>%
vn_as_png()
getBeIds(
be="Gene", source="Ens_gene", organism="human",
restricted=TRUE,
attributes=listDBAttributes("Ens_gene"),
filter=mapt$to
)
```
</div>
## Checking identifiers
The origin of identifiers can be guessed as following.
```{r}
oriId <- c(
"17237", "105886298", "76429", "80985", "230514", "66459",
"93696", "72514", "20352", "13347", "100462961", "100043346",
"12400", "106582", "19062", "245607", "79196", "16878", "320727",
"230649", "66880", "66245", "103742", "320145", "140795"
)
idOrigin <- guessIdScope(oriId)
print(idOrigin$be)
print(idOrigin$source)
print(idOrigin$organism)
```
The best guess is returned as a list but other possible origins are listed in
the *details* attribute.
```{r}
print(attr(idOrigin, "details"))
```
If the origin of identifiers is already known, it can also be tested.
```{r}
checkBeIds(ids=oriId, be="Gene", source="EntrezGene", organism="mouse")
```
```{r}
checkBeIds(ids=oriId, be="Gene", source="HGNC", organism="human")
```
## Identifier annotation
Identifiers can be annotated with symbols and names according to available
information.
The following code returns the most relevant symbol and the most relevant name
for each ID.
Source URL can also be generated with the `getBeIdURL()` function.
```{r}
toShow <- getBeIdDescription(
ids=oriId, be="Gene", source="EntrezGene", organism="mouse"
)
toShow$id <- paste0(
sprintf(
'<a href="%s" target="_blank">',
getBeIdURL(toShow$id, "EntrezGene")
),
toShow$id,
'<a>'
)
kable(toShow, escape=FALSE, row.names=FALSE)
```
All possible symbols and all possible names for each ID can also be retrieved
using the following functions.
```{r}
res <- getBeIdSymbols(
ids=oriId, be="Gene", source="EntrezGene", organism="mouse",
restricted=FALSE
)
head(res)
```
```{r}
res <- getBeIdNames(
ids=oriId, be="Gene", source="EntrezGene", organism="mouse",
restricted=FALSE
)
head(res)
```
Also probes and some biological entities do not have directly associated
symbols or names. These elements can also be annotated according to information
related to relevant genes.
```{r}
someProbes <- c(
"238834_at", "1569297_at", "213021_at", "225480_at",
"216016_at", "35685_at", "217969_at", "211359_s_at"
)
toShow <- getGeneDescription(
ids=someProbes, be="Probe", source="GPL570", organism="human"
)
kable(toShow, escape=FALSE, row.names=FALSE)
```
## Products of molecular biology processes
The BED data model has beeing built to fulfill molecular biology processes:
- **is_expressed_as** relationships correspond to the transcription process.
- **is_translated_in** relationships correspond to the translation process.
- **codes_for** is a fuzzy relationship allowing the mapping of genes on
object not necessary corresonpding to the same kind of biological molecule.
These processes are described in different databases with different level of
granularity. For exemple, Ensembl provides possible transcripts for each gene
specifying which one of them is canonical.
The following functions are used to retrieve direct products or direct
origins of molecular biology processes.
```{r}
getDirectProduct("ENSG00000145335", process="is_expressed_as")
getDirectProduct("ENST00000336904", process="is_translated_in")
getDirectOrigin("NM_001146055", process="is_expressed_as")
```
<!----------------------------------------------------------------------------->
<!----------------------------------------------------------------------------->
# Converting identifiers
## Same entity and same organism: from one source to another
```{r}
res <- convBeIds(
ids=oriId,
from="Gene",
from.source="EntrezGene",
from.org="mouse",
to.source="Ens_gene",
restricted=TRUE,
prefFilter=TRUE
)
head(res)
```
## Same organism: from one entity to another
```{r}
res <- convBeIds(
ids=oriId,
from="Gene",
from.source="EntrezGene",
from.org="mouse",
to="Peptide",
to.source="Ens_translation",
restricted=TRUE,
prefFilter=TRUE
)
head(res)
```
## From one organism to another
```{r}
res <- convBeIds(
ids=oriId,
from="Gene",
from.source="EntrezGene",
from.org="mouse",
to="Peptide",
to.source="Ens_translation",
to.org="human",
restricted=TRUE,
prefFilter=TRUE
)
head(res)
```
## Converting lists of identifiers
List of identifiers can be converted the following way.
Only converted IDs are returned in this case.
```{r}
humanEnsPeptides <- convBeIdLists(
idList=list(a=oriId[1:5], b=oriId[-c(1:5)]),
from="Gene",
from.source="EntrezGene",
from.org="mouse",
to="Peptide",
to.source="Ens_translation",
to.org="human",
restricted=TRUE,
prefFilter=TRUE
)
unlist(lapply(humanEnsPeptides, length))
lapply(humanEnsPeptides, head)
```
### BEIDList
`BEIDList` objects are used to manage lists of BEID with
an attached explicit scope,
and metadata provided in a data frame.
The `focusOnScope()` function is used to easily convert such object to another
scope. For example, in the code below, Entrez gene identifiers are converted
in Ensembl identifiers.
```{r}
entrezGenes <- BEIDList(
list(a=oriId[1:5], b=oriId[-c(1:5)]),
scope=list(be="Gene", source="EntrezGene", organism="Mus musculus"),
metadata=data.frame(
.lname=c("a", "b"),
description=c("Identifiers in a", "Identifiers in b"),
stringsAsFactors=FALSE
)
)
entrezGenes
entrezGenes$a
ensemblGenes <- focusOnScope(entrezGenes, source="Ens_gene")
ensemblGenes$a
```
## Converting data frames
IDs in data frames can also be converted.
```{r}
toConv <- data.frame(a=1:25, b=runif(25))
rownames(toConv) <- oriId
res <- convDfBeIds(
df=toConv,
from="Gene",
from.source="EntrezGene",
from.org="mouse",
to.source="Ens_gene",
restricted=TRUE,
prefFilter=TRUE
)
head(res)
```
## Explore convertion shortest path between two identifiers
Because the conversion process takes into account several resources,
it might be useful to explore the path between two identifiers
which have been mapped. This can be achieved by the `exploreConvPath`
function.
<div style="border:solid;overflow:hidden;">
```{r}
from.id <- "ILMN_1220595"
res <- convBeIds(
ids=from.id, from="Probe", from.source="GPL6885", from.org="mouse",
to="Peptide", to.source="Uniprot", to.org="human",
prefFilter=TRUE
)
res
exploreConvPath(
from.id=from.id, from="Probe", from.source="GPL6885",
to.id=res$to[1], to="Peptide", to.source="Uniprot"
) %>%
vn_as_png()
```
</div>
The figure above shows how the `r ifelse(exists("from.id"), from.id, "XXX")`
ProbeID, targeting
the mouse NM_010552 transcript, can be associated
to the `r ifelse(exists("res"), res$to[1], "XXX")` human protein ID in Uniprot.
## Notes about converting from and to gene symbols
Canonical and non-canonical symbols are associated to genes.
In some cases the same symbol (canonical or not) can be associated to
several genes. This can lead to ambiguous mapping.
The strategy to apply for such mapping depends
on the aim of the user and his knowledge about the origin of the
symbols to consider.
The complete mapping between Ensembl gene identifiers and symbols is
retrieved by using the `getBeIDSymbolTable` function.
```{r}
compMap <- getBeIdSymbolTable(
be="Gene", source="Ens_gene", organism="rat",
restricted=FALSE
)
dim(compMap)
head(compMap)
```
The canonical field indicates if the symbol is canonical for the identifier.
The direct field indicates if the symbol is directly associated to the
identifier or indirectly through a relationship with another identifier.
As an example, let's consider the "Snca" symbol in rat. As shown below, this
symbol is associated to 2 genes; it is canonical for one gene and
not for another. These 2 genes are also associated to other symbols.
```{r}
sncaEid <- compMap[which(compMap$symbol=="Snca"),]
sncaEid
compMap[which(compMap$id %in% sncaEid$id),]
```
The `getBeIdDescription` function described before, reports only one symbol
for each identifier. Canonical and direct symbols are prioritized.
```{r}
getBeIdDescription(
sncaEid$id,
be="Gene", source="Ens_gene", organism="rat"
)
```
The `convBeIds` works differently in order to provide a mapping as exhaustive
as possible. If a symbol is associated to several input identifiers,
non-canonical associations with this symbol are removed if a canonical
association exists for any other identifier. This can lead to inconsistent
results, depending on the user input, as show below.
```{r}
convBeIds(
sncaEid$id[1],
from="Gene", from.source="Ens_gene", from.org="rat",
to.source="Symbol"
)
convBeIds(
sncaEid$id[2],
from="Gene", from.source="Ens_gene", from.org="rat",
to.source="Symbol"
)
convBeIds(
sncaEid$id,
from="Gene", from.source="Ens_gene", from.org="rat",
to.source="Symbol"
)
```
In the example above, when the query is run for each identifier independently,
the association to the "Snca" symbol is reported for both.
However, when running the same query with the 2 identifiers at the same time,
the "Snca" symbol is reported only for one gene corresponding to the canonical
association. An additional filter can be used to only keep canonical
symbols:
```{r}
convBeIds(
sncaEid$id,
from="Gene", from.source="Ens_gene", from.org="rat",
to.source="Symbol",
canonical=TRUE
)
```
Finally, as shown below, when running the query the other way,
"Snca" is only associated to the gene for which it is the canonical symbol.
```{r}
convBeIds(
"Snca",
from="Gene", from.source="Symbol", from.org="rat",
to.source="Ens_gene"
)
```
<strong>
Therefore, the user should chose the function to use with care when needing
to convert from or to gene symbol.
</strong>
<!----------------------------------------------------------------------------->
<!----------------------------------------------------------------------------->
# An interactive dictionary: Shiny module
IDs, symbols and names can be seeked without knowing the original biological
entity or probe. Then the results can be converted to the context of interest.
```{r}
searched <- searchBeid("sv2A")
toTake <- which(searched$organism=="Homo sapiens")[1]
relIds <- geneIDsToAllScopes(
geneids=searched$GeneID[toTake],
source=searched$Gene_source[toTake],
organism=searched$organism[toTake]
)
```
A Shiny gadget integrating these two function has been developped and is also
available as an Rstudio addins.
```{r, eval=FALSE}
relIds <- findBeids()
```
It relies on
a Shiny module (`beidsServer()` and `beidsUI()` functions)
made to facilitate the development
of applications focused on biological entity related information.
The code below shows a minimum example of such an application.
```{r, eval=FALSE}
library(shiny)
library(BED)
library(DT)
ui <- fluidPage(
beidsUI("be"),
fluidRow(
column(
12,
tags$br(),
h3("Selected gene entities"),
DTOutput("result")
)
)
)
server <- function(input, output){
found <- beidsServer("be", toGene=TRUE, multiple=TRUE, tableHeight=250)
output$result <- renderDT({
req(found())
toRet <- found()
datatable(toRet, rownames=FALSE)
})
}
shinyApp(ui = ui, server = server)
```
<!----------------------------------------------------------------------------->
<!----------------------------------------------------------------------------->
# Session info
```{r, echo=FALSE, eval=TRUE}
sessionInfo()
```
| /scratch/gouwar.j/cran-all/cranData/BED/inst/doc/BED.Rmd |
---
title: "Biological Entity Dictionary (BED): exploring and converting identifiers of biological entities such as genes, transcripts or peptides"
package: "BED (version `r packageVersion('BED')`)"
output:
rmarkdown::html_document:
number_sections: yes
self_contained: true
theme: cerulean
toc: yes
toc_float: yes
fig_width: 7
fig_height: 5
vignette: >
%\VignetteIndexEntry{BED}
%\VignetteEncoding{UTF-8}
%\VignetteEngine{knitr::rmarkdown}
editor_options:
chunk_output_type: console
---
```{r setup, echo=FALSE}
library(knitr)
## The following line is to avoid building errors on CRAN
knitr::opts_chunk$set(eval=Sys.getenv("USER") %in% c("pgodard"))
vn_as_png <- function(vn){
html_file <- tempfile(fileext = ".html")
png_file <- tempfile(fileext = ".png")
visSave(vn, html_file)
invisible(webshot::webshot(
html_file, file=png_file, selector=".visNetwork", vwidth="100%"
))
im <- base64enc::dataURI(file=png_file, mime="image/png")
invisible(file.remove(c(html_file,png_file)))
htmltools::div(
width="100%",
htmltools::img(src=im, alt="visNetwork", width="100%")
)
}
```
::: {style="width:200px;"}
{width="100%"}
:::
<!----------------------------------------------------------------------------->
<!----------------------------------------------------------------------------->
# Introduction
This Biological Entity Dictionary (BED)
has been developed to address three main challenges.
The first one is related to the completeness of identifier mappings.
Indeed, direct mapping information provided by the different systems
are not always complete and can be enriched by mappings provided by other
resources.
More interestingly, direct mappings not identified by any of these
resources can be indirectly inferred by using mappings to a third reference.
For example, many human Ensembl gene ID are not directly mapped to any
Entrez gene ID but such mappings can be inferred using respective mappings
to HGNC ID. The second challenge is related to the mapping of deprecated
identifiers. Indeed, entity identifiers can change from one resource
release to another. The identifier history is provided by some resources,
such as Ensembl or the NCBI, but it is generally not used by mapping tools.
The third challenge is related to the automation of the mapping process
according to the relationships between the biological entities of interest.
Indeed, mapping between gene and protein ID scopes should not be done
the same way than between two scopes regarding gene ID.
Also, converting identifiers from different organisms should be possible
using gene orthologs information.
This document shows how to use the **BED (Biological Entity Dictionary)**
R package to get and explore mapping between
identifiers of biological entities (BE).
This package provides a way to connect to a BED Neo4j database in which
the relationships between the identifiers from different sources are recorded.
## Citing BED
This package and the underlying research has been published in
this peer reviewed article:
<a href="`r citation("BED")[1]$url`" target="_blank">
`r sub('[[]', '(', sub('[]]', ')', format(citation("BED"), style="textVersion")))`
</a>
## Installation
### Dependencies
This BED package depends on the following packages available in the CRAN
repository:
- **neo2R**
- **visNetwork**
- **dplyr**
- **readr**
- **stringr**
- **utils**
- **shiny**
- **DT**
- **miniUI**
- **rstudioapi**
All these packages must be installed before installing BED.
### Installation from github
```{r, eval=FALSE}
devtools::install_github("patzaw/BED")
```
### Possible issue when updating from releases <= 1.3.0
If you get an error like the following...
```
Error: package or namespace load failed for ‘BED’:
.onLoad failed in loadNamespace() for 'BED', details:
call: connections[[connection]][["cache"]]
error: subscript out of bounds
```
... remove the BED folder located here:
```{r, echo=TRUE, eval=FALSE}
file.exists(file.path(Sys.getenv("HOME"), "R", "BED"))
```
## Connection
Before using BED, the connection needs to be established with the
underlying Neo4j DB.
`url`, `username` and `password` should be adapted.
```{r, message=FALSE, eval=TRUE}
library(BED)
```
```{r, message=FALSE, eval=TRUE, echo=FALSE}
connectToBed()
```
```{r, message=FALSE, eval=FALSE}
connectToBed(url="localhost:5454", remember=FALSE, useCache=FALSE)
```
The `remember` parameter can be set to `TRUE` in order to save connection
information that will be automatically used the next time the `connectToBed()`
function is called.
By default, this parameter is set to `FALSE` to comply with CRAN policies.
Saved connection can be managed with the `lsBedConnections()` and
the `forgetBedConnection()` functions.
The `useCache` parameter is by default set to `FALSE` to comply with
CRAN policies.
However, it is recommended to set it to `TRUE` to improve the speed
of recurrent queries: the results of some large queries are saved locally
in a file.
The connection can be checked the following way.
```{r, message=TRUE}
checkBedConn(verbose=TRUE)
```
If the `verbose` parameter is set to TRUE, the URL and the content version
are displayed as messages.
The following function list saved connections.
```{r, eval=FALSE}
lsBedConnections()
```
The `connection` param of the `connectToBed` function can be used to
connect to a saved connection other than the last one.
## Data model
The BED underlying data model can be shown at any time using
the following command.
```{r, eval=FALSE}
showBedDataModel()
```
```{r, echo=FALSE, eval=TRUE}
htmltools::includeHTML(system.file(
"Documentation", "BED-Model", "BED.html",
package="BED"
))
```
## Direct calls
Cypher queries can be run directly on the Neo4j database using the
`cypher` function from the **neo2R** package through the `bedCall` function.
```{r}
results <- bedCall(
cypher,
query=prepCql(
'MATCH (n:BEID)',
'WHERE n.value IN $values',
'RETURN DISTINCT n.value AS value, labels(n), n.database'
),
parameters=list(values=c("10", "100"))
)
results
```
## Feeding the database
Many functions are provided within the package to build your own BED database
instance. These functions are not exported in order to avoid their use when
interacting with BED normally.
Information about how to get an instance of the BED neo4j database is
provided here:
- <https://github.com/patzaw/BED#bed-database-instance-available-as-a-docker-image>
- <https://github.com/patzaw/BED#build-a-bed-database-instance>
It can be adapted to user needs.
## Caching
This part is relevant if the `useCache` parameter is set to TRUE when
calling `connectToBed()`.
Functions of the BED package used to retrieve thousands of identifiers
can take some time (generally a few seconds) before returning a result.
Thus for this kind of query, the query is run for all the relevant ID in the DB
and thanks to a cache system implemented in the package same queries
with different filters should be much faster the following times.
By default the cache is flushed when the system detect inconsistencies
with the BED database. However, it can also be manualy flushed if needed using
the `clearBedCache()` function.
Queries already in cache can be listed using the `lsBedCache()` function which
also return the occupied disk space.
<!----------------------------------------------------------------------------->
<!----------------------------------------------------------------------------->
# Exploring available data
## Biological entities
BED is organized around the central concept of **Biological Entity** (BE).
All supported types of BE can be listed.
```{r}
listBe()
```
These BE are organized according to how they are related to each other.
For example a *Gene* *is_expressed_as* a *Transcript*.
This organization allows to find the first upstream BE common to a set of
BE.
```{r}
firstCommonUpstreamBe(c("Object", "Transcript"))
firstCommonUpstreamBe(c("Peptide", "Transcript"))
```
## Organisms
Several organims can be supported by the BED underlying database.
They can be listed the following way.
```{r}
listOrganisms()
```
Common names are also supported and the corresponding taxonomic identifiers
can be retrieved. Conversely the organism names corresponding to a
taxonomic ID can be listed.
```{r}
getOrgNames(getTaxId("human"))
```
## Identifiers of biological entities
The main aim of BED is to allow the mapping of identifiers from different
sources such as Ensembl or Entrez. Supported sources can be listed the
following way for each supported organism.
```{r}
listBeIdSources(be="Transcript", organism="human")
```
The database gathering the largest number of BE of specific type can also
be identified.
```{r}
largestBeSource(be="Transcript", organism="human", restricted=TRUE)
```
Finally, the `getAllBeIdSources()` function returns all
the source databases of BE identifiers whatever the BE type.
## Experimental platforms and probes
BED also supports experimental platforms and provides mapping betweens
probes and BE identifiers (BEID).
The supported platforms can be listed the following way.
The `getTargetedBe()` function returns the type of BE on which a specific
platform focus.
```{r}
head(listPlatforms())
getTargetedBe("GPL570")
```
<!----------------------------------------------------------------------------->
<!----------------------------------------------------------------------------->
# Managing identifiers
## Retrieving all identifiers from a source
All identifiers of an organism BEs from one source can be retrieved.
```{r}
beids <- getBeIds(
be="Gene", source="EntrezGene", organism="human",
restricted=FALSE
)
dim(beids)
head(beids)
```
The first column, *id*, corresponds to the identifiers of the BE in the source.
The column named according to the BE type (in this case *Gene*)
corresponds to the internal identifier of the related BE.
**BE CAREFUL, THIS INTERNAL ID IS NOT STABLE AND CANNOT BE USED AS A REFERENCE**.
This internal identifier is useful to identify BEIDS corresponding to the
same BE. The following code can be used to have an overview of such
redundancy.
```{r}
sort(table(table(beids$Gene)), decreasing = TRUE)
ambId <- sum(table(table(beids$Gene)[which(table(beids$Gene)>=10)]))
```
In the example above we can see that most of Gene BE are identified by only
one EntrezGene ID. However many of them are identified by two or more
ID; `r ifelse(exists("ambId"), ambId, "XXX")` BE
are even identified by 10 or more EntrezGeneID.
In this case, most of these redundancies come from ID history extracted
from Entrez. Legacy ID can be excluded from the retrieved ID
by setting the `restricted` parameter to TRUE.
```{r}
beids <- getBeIds(
be="Gene", source="EntrezGene", organism="human",
restricted = TRUE
)
dim(beids)
```
The same code as above can be used to identify remaining redundancies.
```{r}
sort(table(table(beids$Gene)), decreasing = TRUE)
```
In the example above we can see that allmost all Gene BE are identified by only
one EntrezGene ID. However some of them are identified by two or more ID.
This result comes from how the BED database is constructed according to
the ID mapping provided by the different source databases.
The graph below shows how the mapping was done for such a BE with
redundant EntrezGene IDs.
<strong>
This issue has been mainly solved by not taking into account ambigous mappings
between NCBI Entrez gene identifiers and Ensembl gene identifier provided
by Ensembl. It has been achieved using the `cleanDubiousXRef()` function
from the 2019.10.11 version of the BED-UCB-Human database.
</strong>
<div style="border:solid;overflow:hidden;">
```{r}
eid <- beids$id[which(beids$Gene %in% names(which(table(beids$Gene)>=3)))][1]
print(eid)
exploreBe(id=eid, source="EntrezGene", be="Gene") %>%
visPhysics(solver="repulsion") %>%
vn_as_png()
```
</div>
<br>
The way the ID correspondances are reported in the different source databases
leads to this mapping ambiguity which has to be taken into account
when comparing identifiers from different databases.
The `getBeIds()` returns other columns providing additional
information about the *id*.
The same function can be used to retrieved symbols or probe identifiers.
### Preferred identifier
The BED database is constructed according to the relationships between
identifiers provided by the different sources. Biological entities (BE) are
identified as clusters of identifiers which correspond to each other
directly or indirectly (`corresponds_to` relationship).
Because of this design a BE can be identified by multiple identifiers (BEID)
from the same database as shown above.
These BEID are often related to alternate version of an entity.
For example, Ensembl provides different version (alternative sequences)
of some chromosomes parts. And genes are also annotated on these alternative
sequences. In Uniprot some *unreviewed* identifiers can correspond
to *reviewed* proteins.
When available such kind of information is associated to
an **Attribute** node through a `has` relationship providing the
value of the attribute for the BEID. This information can also
be used to define if a BEID is a *preferred* identifier for
a BE.
The example below shows the case of the MAPT gene annotated on different
version of human chromosome 17.
<div style="border:solid;overflow:hidden;">
```{r}
mapt <- convBeIds(
"MAPT", from="Gene", from.source="Symbol", from.org="human",
to.source="Ens_gene", restricted=TRUE
)
exploreBe(
mapt[1, "to"],
source="Ens_gene",
be="Gene"
) %>%
vn_as_png()
getBeIds(
be="Gene", source="Ens_gene", organism="human",
restricted=TRUE,
attributes=listDBAttributes("Ens_gene"),
filter=mapt$to
)
```
</div>
## Checking identifiers
The origin of identifiers can be guessed as following.
```{r}
oriId <- c(
"17237", "105886298", "76429", "80985", "230514", "66459",
"93696", "72514", "20352", "13347", "100462961", "100043346",
"12400", "106582", "19062", "245607", "79196", "16878", "320727",
"230649", "66880", "66245", "103742", "320145", "140795"
)
idOrigin <- guessIdScope(oriId)
print(idOrigin$be)
print(idOrigin$source)
print(idOrigin$organism)
```
The best guess is returned as a list but other possible origins are listed in
the *details* attribute.
```{r}
print(attr(idOrigin, "details"))
```
If the origin of identifiers is already known, it can also be tested.
```{r}
checkBeIds(ids=oriId, be="Gene", source="EntrezGene", organism="mouse")
```
```{r}
checkBeIds(ids=oriId, be="Gene", source="HGNC", organism="human")
```
## Identifier annotation
Identifiers can be annotated with symbols and names according to available
information.
The following code returns the most relevant symbol and the most relevant name
for each ID.
Source URL can also be generated with the `getBeIdURL()` function.
```{r}
toShow <- getBeIdDescription(
ids=oriId, be="Gene", source="EntrezGene", organism="mouse"
)
toShow$id <- paste0(
sprintf(
'<a href="%s" target="_blank">',
getBeIdURL(toShow$id, "EntrezGene")
),
toShow$id,
'<a>'
)
kable(toShow, escape=FALSE, row.names=FALSE)
```
All possible symbols and all possible names for each ID can also be retrieved
using the following functions.
```{r}
res <- getBeIdSymbols(
ids=oriId, be="Gene", source="EntrezGene", organism="mouse",
restricted=FALSE
)
head(res)
```
```{r}
res <- getBeIdNames(
ids=oriId, be="Gene", source="EntrezGene", organism="mouse",
restricted=FALSE
)
head(res)
```
Also probes and some biological entities do not have directly associated
symbols or names. These elements can also be annotated according to information
related to relevant genes.
```{r}
someProbes <- c(
"238834_at", "1569297_at", "213021_at", "225480_at",
"216016_at", "35685_at", "217969_at", "211359_s_at"
)
toShow <- getGeneDescription(
ids=someProbes, be="Probe", source="GPL570", organism="human"
)
kable(toShow, escape=FALSE, row.names=FALSE)
```
## Products of molecular biology processes
The BED data model has beeing built to fulfill molecular biology processes:
- **is_expressed_as** relationships correspond to the transcription process.
- **is_translated_in** relationships correspond to the translation process.
- **codes_for** is a fuzzy relationship allowing the mapping of genes on
object not necessary corresonpding to the same kind of biological molecule.
These processes are described in different databases with different level of
granularity. For exemple, Ensembl provides possible transcripts for each gene
specifying which one of them is canonical.
The following functions are used to retrieve direct products or direct
origins of molecular biology processes.
```{r}
getDirectProduct("ENSG00000145335", process="is_expressed_as")
getDirectProduct("ENST00000336904", process="is_translated_in")
getDirectOrigin("NM_001146055", process="is_expressed_as")
```
<!----------------------------------------------------------------------------->
<!----------------------------------------------------------------------------->
# Converting identifiers
## Same entity and same organism: from one source to another
```{r}
res <- convBeIds(
ids=oriId,
from="Gene",
from.source="EntrezGene",
from.org="mouse",
to.source="Ens_gene",
restricted=TRUE,
prefFilter=TRUE
)
head(res)
```
## Same organism: from one entity to another
```{r}
res <- convBeIds(
ids=oriId,
from="Gene",
from.source="EntrezGene",
from.org="mouse",
to="Peptide",
to.source="Ens_translation",
restricted=TRUE,
prefFilter=TRUE
)
head(res)
```
## From one organism to another
```{r}
res <- convBeIds(
ids=oriId,
from="Gene",
from.source="EntrezGene",
from.org="mouse",
to="Peptide",
to.source="Ens_translation",
to.org="human",
restricted=TRUE,
prefFilter=TRUE
)
head(res)
```
## Converting lists of identifiers
List of identifiers can be converted the following way.
Only converted IDs are returned in this case.
```{r}
humanEnsPeptides <- convBeIdLists(
idList=list(a=oriId[1:5], b=oriId[-c(1:5)]),
from="Gene",
from.source="EntrezGene",
from.org="mouse",
to="Peptide",
to.source="Ens_translation",
to.org="human",
restricted=TRUE,
prefFilter=TRUE
)
unlist(lapply(humanEnsPeptides, length))
lapply(humanEnsPeptides, head)
```
### BEIDList
`BEIDList` objects are used to manage lists of BEID with
an attached explicit scope,
and metadata provided in a data frame.
The `focusOnScope()` function is used to easily convert such object to another
scope. For example, in the code below, Entrez gene identifiers are converted
in Ensembl identifiers.
```{r}
entrezGenes <- BEIDList(
list(a=oriId[1:5], b=oriId[-c(1:5)]),
scope=list(be="Gene", source="EntrezGene", organism="Mus musculus"),
metadata=data.frame(
.lname=c("a", "b"),
description=c("Identifiers in a", "Identifiers in b"),
stringsAsFactors=FALSE
)
)
entrezGenes
entrezGenes$a
ensemblGenes <- focusOnScope(entrezGenes, source="Ens_gene")
ensemblGenes$a
```
## Converting data frames
IDs in data frames can also be converted.
```{r}
toConv <- data.frame(a=1:25, b=runif(25))
rownames(toConv) <- oriId
res <- convDfBeIds(
df=toConv,
from="Gene",
from.source="EntrezGene",
from.org="mouse",
to.source="Ens_gene",
restricted=TRUE,
prefFilter=TRUE
)
head(res)
```
## Explore convertion shortest path between two identifiers
Because the conversion process takes into account several resources,
it might be useful to explore the path between two identifiers
which have been mapped. This can be achieved by the `exploreConvPath`
function.
<div style="border:solid;overflow:hidden;">
```{r}
from.id <- "ILMN_1220595"
res <- convBeIds(
ids=from.id, from="Probe", from.source="GPL6885", from.org="mouse",
to="Peptide", to.source="Uniprot", to.org="human",
prefFilter=TRUE
)
res
exploreConvPath(
from.id=from.id, from="Probe", from.source="GPL6885",
to.id=res$to[1], to="Peptide", to.source="Uniprot"
) %>%
vn_as_png()
```
</div>
The figure above shows how the `r ifelse(exists("from.id"), from.id, "XXX")`
ProbeID, targeting
the mouse NM_010552 transcript, can be associated
to the `r ifelse(exists("res"), res$to[1], "XXX")` human protein ID in Uniprot.
## Notes about converting from and to gene symbols
Canonical and non-canonical symbols are associated to genes.
In some cases the same symbol (canonical or not) can be associated to
several genes. This can lead to ambiguous mapping.
The strategy to apply for such mapping depends
on the aim of the user and his knowledge about the origin of the
symbols to consider.
The complete mapping between Ensembl gene identifiers and symbols is
retrieved by using the `getBeIDSymbolTable` function.
```{r}
compMap <- getBeIdSymbolTable(
be="Gene", source="Ens_gene", organism="rat",
restricted=FALSE
)
dim(compMap)
head(compMap)
```
The canonical field indicates if the symbol is canonical for the identifier.
The direct field indicates if the symbol is directly associated to the
identifier or indirectly through a relationship with another identifier.
As an example, let's consider the "Snca" symbol in rat. As shown below, this
symbol is associated to 2 genes; it is canonical for one gene and
not for another. These 2 genes are also associated to other symbols.
```{r}
sncaEid <- compMap[which(compMap$symbol=="Snca"),]
sncaEid
compMap[which(compMap$id %in% sncaEid$id),]
```
The `getBeIdDescription` function described before, reports only one symbol
for each identifier. Canonical and direct symbols are prioritized.
```{r}
getBeIdDescription(
sncaEid$id,
be="Gene", source="Ens_gene", organism="rat"
)
```
The `convBeIds` works differently in order to provide a mapping as exhaustive
as possible. If a symbol is associated to several input identifiers,
non-canonical associations with this symbol are removed if a canonical
association exists for any other identifier. This can lead to inconsistent
results, depending on the user input, as show below.
```{r}
convBeIds(
sncaEid$id[1],
from="Gene", from.source="Ens_gene", from.org="rat",
to.source="Symbol"
)
convBeIds(
sncaEid$id[2],
from="Gene", from.source="Ens_gene", from.org="rat",
to.source="Symbol"
)
convBeIds(
sncaEid$id,
from="Gene", from.source="Ens_gene", from.org="rat",
to.source="Symbol"
)
```
In the example above, when the query is run for each identifier independently,
the association to the "Snca" symbol is reported for both.
However, when running the same query with the 2 identifiers at the same time,
the "Snca" symbol is reported only for one gene corresponding to the canonical
association. An additional filter can be used to only keep canonical
symbols:
```{r}
convBeIds(
sncaEid$id,
from="Gene", from.source="Ens_gene", from.org="rat",
to.source="Symbol",
canonical=TRUE
)
```
Finally, as shown below, when running the query the other way,
"Snca" is only associated to the gene for which it is the canonical symbol.
```{r}
convBeIds(
"Snca",
from="Gene", from.source="Symbol", from.org="rat",
to.source="Ens_gene"
)
```
<strong>
Therefore, the user should chose the function to use with care when needing
to convert from or to gene symbol.
</strong>
<!----------------------------------------------------------------------------->
<!----------------------------------------------------------------------------->
# An interactive dictionary: Shiny module
IDs, symbols and names can be seeked without knowing the original biological
entity or probe. Then the results can be converted to the context of interest.
```{r}
searched <- searchBeid("sv2A")
toTake <- which(searched$organism=="Homo sapiens")[1]
relIds <- geneIDsToAllScopes(
geneids=searched$GeneID[toTake],
source=searched$Gene_source[toTake],
organism=searched$organism[toTake]
)
```
A Shiny gadget integrating these two function has been developped and is also
available as an Rstudio addins.
```{r, eval=FALSE}
relIds <- findBeids()
```
It relies on
a Shiny module (`beidsServer()` and `beidsUI()` functions)
made to facilitate the development
of applications focused on biological entity related information.
The code below shows a minimum example of such an application.
```{r, eval=FALSE}
library(shiny)
library(BED)
library(DT)
ui <- fluidPage(
beidsUI("be"),
fluidRow(
column(
12,
tags$br(),
h3("Selected gene entities"),
DTOutput("result")
)
)
)
server <- function(input, output){
found <- beidsServer("be", toGene=TRUE, multiple=TRUE, tableHeight=250)
output$result <- renderDT({
req(found())
toRet <- found()
datatable(toRet, rownames=FALSE)
})
}
shinyApp(ui = ui, server = server)
```
<!----------------------------------------------------------------------------->
<!----------------------------------------------------------------------------->
# Session info
```{r, echo=FALSE, eval=TRUE}
sessionInfo()
```
| /scratch/gouwar.j/cran-all/cranData/BED/vignettes/BED.Rmd |
BB_Likelihood_counts <-
function(phi,counts,sample_sizes,allele.frequencies){
shape1 <- phi*allele.frequencies
shape2 <- phi*(1-allele.frequencies)
L <- lbeta(counts+shape1,sample_sizes-counts+shape2) - lbeta(shape1,shape2)
return(L)
}
| /scratch/gouwar.j/cran-all/cranData/BEDASSLE/R/BB_Likelihood_counts.R |
BB_Prior_prob_phi <-
function(phi){
stats::dexp(1/phi,rate=5,log=TRUE)
}
| /scratch/gouwar.j/cran-all/cranData/BEDASSLE/R/BB_Prior_prob_phi.R |
BB_Update_mu <-
function(last.params){
mu_update <- stats::rnorm(last.params$loci,0,last.params$mu_stp)
mu_prime <- Shift(last.params$mu,mu_update)
prior_prob_mu_prime <- Prior_prob_mu(mu_prime,last.params$beta)
allele.frequencies_prime <- transform_frequencies(last.params$thetas,mu_prime)
LnL_counts_mat_prime <- BB_Likelihood_counts(last.params$phi,last.params$counts,last.params$sample_sizes,allele.frequencies_prime)
new.params <- last.params
for(i in 1:ncol(last.params$mu)){
if(!is.na(sum(LnL_counts_mat_prime[,i]))){
if(exp((prior_prob_mu_prime[i]+sum(LnL_counts_mat_prime[,i])) - (last.params$prior_prob_mu[i]+sum(last.params$LnL_counts_mat[,i]))) >= stats::runif(1)){
new.params$mu[,i] <- mu_prime[,i]
new.params$allele.frequencies[,i] <- allele.frequencies_prime[,i]
new.params$LnL_counts_mat[,i] <- LnL_counts_mat_prime[,i]
new.params$prior_prob_mu[i] <- prior_prob_mu_prime[i]
new.params$mu_accept <- new.params$mu_accept + 1
}
}
}
new.params$mu_moves <- new.params$mu_moves + last.params$loci
return(new.params)
}
| /scratch/gouwar.j/cran-all/cranData/BEDASSLE/R/BB_Update_mu.R |
BB_Update_phi <-
function(last.params){
phi_prime <- last.params$phi + stats::rnorm(last.params$k,0,last.params$phi_stp)
prior_prob_phi_prime <- BB_Prior_prob_phi(phi_prime)
LnL_counts_mat_prime <- BB_Likelihood_counts(phi_prime,last.params$counts,last.params$sample_sizes,last.params$allele.frequencies)
new.params <- last.params
for(i in 1:last.params$k){
if(prior_prob_phi_prime[i] != -Inf){
if(!is.na(sum(LnL_counts_mat_prime[i,]))){
if(exp((sum(LnL_counts_mat_prime[i,])+prior_prob_phi_prime[i])-(sum(last.params$LnL_counts_mat[i,])+last.params$prior_prob_phi[i])) >= stats::runif(1)){
new.params$phi[i] <- phi_prime[i]
new.params$LnL_counts_mat[i,] <- LnL_counts_mat_prime[i,]
new.params$prior_prob_phi[i] <- prior_prob_phi_prime[i]
new.params$phi_accept <- new.params$phi_accept+1
}
}
}
}
new.params$phi_moves <- new.params$phi_moves+new.params$k
return(new.params)
}
| /scratch/gouwar.j/cran-all/cranData/BEDASSLE/R/BB_Update_phi.R |
BB_Update_thetas <-
function(last.params){
new.params <- last.params
cholcovmat <- chol(last.params$covariance)
thetas_prime <- sapply(1:ncol(last.params$thetas),function(i){last.params$thetas[,i]+stats::rnorm(last.params$k,0,last.params$thetas_stp)%*%cholcovmat})
allele.frequencies_prime <- transform_frequencies(thetas_prime,last.params$mu)
LnL_thetas_vec_prime <- Likelihood_thetas(thetas_prime,last.params$covariance)
LnL_counts_mat_prime <- BB_Likelihood_counts(last.params$phi,last.params$counts,last.params$sample_sizes,allele.frequencies_prime)
for(i in 1:last.params$loci){
if(!is.na(sum(LnL_counts_mat_prime[,i])) && !is.na(LnL_thetas_vec_prime[i])){
if(exp((LnL_thetas_vec_prime[i]+sum(LnL_counts_mat_prime[,i])) - (last.params$LnL_thetas_vec[i]+sum(last.params$LnL_counts_mat[,i]))) >= stats::runif(1)){
new.params$thetas[,i] <- thetas_prime[,i]
new.params$allele.frequencies[,i] <- allele.frequencies_prime[,i]
new.params$LnL_thetas_vec[i] <- LnL_thetas_vec_prime[i]
new.params$LnL_counts_mat[,i] <- LnL_counts_mat_prime[,i]
new.params$thetas_accept <- new.params$thetas_accept + 1
}
}
}
new.params$thetas_moves <- new.params$thetas_moves + last.params$loci
return(new.params)
}
| /scratch/gouwar.j/cran-all/cranData/BEDASSLE/R/BB_Update_thetas.R |
Covariance <-
function(a0,aD,aE,a2,GeoDist,EcoDist,delta) {
weighted.dist.squared <- aE[1] * (EcoDist[[1]])^2
if (length(EcoDist)>1) {
for (k in 2:length(EcoDist)) {
weighted.dist.squared <- weighted.dist.squared + aE[k] * (EcoDist[[k]])^2
}
}
covariance <- (1/a0)*exp((-sqrt(aD*GeoDist^2 + weighted.dist.squared)^a2)-delta)
diag(covariance) <- (1/a0)
return(covariance)
} | /scratch/gouwar.j/cran-all/cranData/BEDASSLE/R/Covariance.R |
Initialize.params <-
function(counts,sample_sizes,k,loci){
allele.frequencies_hat <- counts/sample_sizes
mean_allele.frequencies <- colSums(allele.frequencies_hat,na.rm=TRUE)/k
mean_allele.frequencies[which(mean_allele.frequencies==0)] <- 0.01
mean_allele.frequencies[which(mean_allele.frequencies==1)] <- 0.99
mu_hat <- -log((1/mean_allele.frequencies)-1)
sd_mu_hat <- stats::sd(mu_hat)
beta_hat <- 1/(sd_mu_hat)^2
mu_hat <- matrix(mu_hat,nrow=k,ncol=loci,byrow=TRUE)
allele.frequencies_hat[which(allele.frequencies_hat == 0)] <- 0.01
allele.frequencies_hat[which(allele.frequencies_hat == 1)] <- 0.99
allele.frequencies_hat[which(is.na(allele.frequencies_hat))] <- 0.01
thetas_hat <- -log((1/allele.frequencies_hat)-1)-mu_hat
initial_param_estimates <- list(thetas_hat,mu_hat,beta_hat)
names(initial_param_estimates) <- c("thetas_hat","mu_hat","beta_hat")
return(initial_param_estimates)
}
| /scratch/gouwar.j/cran-all/cranData/BEDASSLE/R/Initialize.params.R |
Likelihood_counts <-
function(counts,sample_sizes,allele.frequencies){
LnL_counts_mat <- counts*log(allele.frequencies) + (sample_sizes-counts)*log(1-allele.frequencies)
return(LnL_counts_mat)
}
| /scratch/gouwar.j/cran-all/cranData/BEDASSLE/R/Likelihood_counts.R |
Likelihood_thetas <-
function(thetas,covmat) {
cholcov <- chol(covmat)
invcholcov <- MASS::ginv(cholcov)
logsqrtdet <- sum(log(diag(cholcov)))
-(1/2)*(colSums((crossprod(invcholcov,thetas))^2))-logsqrtdet
}
| /scratch/gouwar.j/cran-all/cranData/BEDASSLE/R/Likelihood_thetas.R |
MCMC <-
function(counts,
sample_sizes,
D,
E,
k,
loci,
delta,
aD_stp,
aE_stp,
a2_stp,
thetas_stp,
mu_stp,
ngen,
printfreq,
savefreq,
samplefreq,
directory=NULL,
prefix="",
continue=FALSE,
continuing.params=NULL){
if(!is.null(directory)){
setwd(directory)
}
if(min(D[upper.tri(D)]) < delta){
warning("the value chosen for delta may too large compared to the geographic distances between the sampled populations")
}
if (is.matrix(E)) { E <- list(E) } # allow E to come not in a list if there's only one
if(any(lapply(E,function(EE) min(EE[upper.tri(EE)])) < delta)){
warning("the value chosen for delta may too large compared to the ecological distances between the sampled populations")
}
#Declare variables
LnL_thetas <- numeric(ngen/samplefreq)
LnL_thetas_vec <- numeric(loci)
LnL_counts <- numeric(ngen/samplefreq)
LnL <- numeric(ngen/samplefreq)
Prob <- numeric(ngen/samplefreq)
a0 <- numeric(ngen/samplefreq)
aD <- numeric(ngen/samplefreq)
aE <- matrix(0,nrow=length(E),ncol=ngen/samplefreq)
a2 <- numeric(ngen/samplefreq)
beta <- numeric(ngen/samplefreq)
a0_moves <- numeric(ngen/samplefreq)
aD_moves <- numeric(ngen/samplefreq)
aE_moves <- numeric(ngen/samplefreq)
a2_moves <- numeric(ngen/samplefreq)
thetas_moves <- numeric(ngen/samplefreq)
mu_moves <- numeric(ngen/samplefreq)
beta_moves <- numeric(ngen/samplefreq)
aD_accept <- numeric(ngen/samplefreq)
aE_accept <- numeric(ngen/samplefreq)
a2_accept <- numeric(ngen/samplefreq)
thetas_accept <- numeric(ngen/samplefreq)
mu_accept <- numeric(ngen/samplefreq)
if(!continue) {
#INITIALIZE MCMC
Prob[1] <- -Inf
covariance <- matrix(0,nrow=k,ncol=k)
pos.def.counter <- 0
while(Prob[1] == -Inf){
while(!matrixcalc::is.positive.definite(covariance) && pos.def.counter < 100){
a0[1] <- stats::runif(1,0,4)
aD[1] <- stats::runif(1,0,4)
aE[,1] <- stats::runif(length(E),0,4)
a2[1] <- stats::runif(1,0,2)
covariance <- Covariance(a0[1],aD[1],aE[,1],a2[1],D,E,delta)
initial.params <- Initialize.params(counts,sample_sizes,k,loci)
beta[1] <- initial.params$beta_hat
mu <- initial.params$mu_hat
thetas <- initial.params$thetas_hat
allele.frequencies <- transform_frequencies(thetas,mu)
Initial.parameters <- list(a0=a0[1],aD=aD[1],aE=aE[,1],a2=a2[1],beta=beta[1],mu=mu,thetas=thetas)
pos.def.counter <- pos.def.counter + 1
}
if(pos.def.counter > 99){
stop("the initial covariance matrix is not positive definite! Either attempt to re-initialize MCMC, or increase the size of the delta shift")
}
save(Initial.parameters,file=paste(prefix,"Initial.parameters.Robj",sep=''))
LnL_thetas_vec <- Likelihood_thetas(thetas,covariance)
LnL_thetas[1] <- sum(Likelihood_thetas(thetas,covariance))
LnL_counts_mat <- Likelihood_counts(counts,sample_sizes,allele.frequencies)
LnL_counts[1] <- sum(LnL_counts_mat)
LnL[1] <- LnL_thetas[1] + LnL_counts[1]
prior_prob_beta <- Prior_prob_beta(beta[1])
prior_prob_mu <- Prior_prob_mu(mu,beta[1])
prior_prob_alpha0 <- Prior_prob_alpha0(a0[1])
prior_prob_alphaD <- Prior_prob_alphaD(aD[1])
prior_prob_alphaE <- Prior_prob_alphaE(aE[,1])
prior_prob_alpha2 <- Prior_prob_alpha2(a2[1])
Prob[1] <- LnL[1] + prior_prob_alpha0 + prior_prob_alphaD + prior_prob_alphaE + prior_prob_alpha2 + sum(prior_prob_mu) + prior_prob_beta
}
} else {
#Choose Initial Parameter Values
load(continuing.params)
a0[1] <- continuing.params$a0
aD[1] <- continuing.params$aD
aE[,1] <- continuing.params$aE
a2[1] <- continuing.params$a2
covariance <- Covariance(a0[1],aD[1],aE[,1],a2[1],D,E,delta)
if(!matrixcalc::is.positive.definite(covariance)){
stop("the initial covariance matrix is not positive definite! Either attempt to re-initialize MCMC, or increase the size of the delta shift")
}
beta[1] <- continuing.params$beta
mu <- continuing.params$mu
thetas <- continuing.params$thetas
allele.frequencies <- transform_frequencies(thetas,mu)
Initial.parameters <- list(a0=a0[1],aD=aD[1],aE=aE[,1],a2=a2[1],beta=beta[1],mu=mu,thetas=thetas)
save(Initial.parameters,file=paste(prefix,"Initial.parameters.Robj",sep=''))
}
#Calculate Initial Likelihood
LnL_thetas_vec <- Likelihood_thetas(thetas,covariance)
LnL_thetas[1] <- sum(Likelihood_thetas(thetas,covariance))
LnL_counts_mat <- Likelihood_counts(counts,sample_sizes,allele.frequencies)
LnL_counts[1] <- sum(LnL_counts_mat)
LnL[1] <- LnL_thetas[1] + LnL_counts[1]
prior_prob_beta <- Prior_prob_beta(beta[1])
prior_prob_mu <- Prior_prob_mu(mu,beta[1])
prior_prob_alpha0 <- Prior_prob_alpha0(a0[1])
prior_prob_alphaD <- Prior_prob_alphaD(aD[1])
prior_prob_alphaE <- Prior_prob_alphaE(aE[1])
prior_prob_alpha2 <- Prior_prob_alpha2(a2[1])
Prob[1] <- LnL[1] + prior_prob_alpha0 + prior_prob_alphaD + prior_prob_alphaE + prior_prob_alpha2 + sum(prior_prob_mu) + prior_prob_beta
if(!is.finite(Prob[1])){
stop("Initial probability of model is NEGATIVE INFINITY! Please attempt to initiate chain again.")
}
last.params <- list(a0[1],aD[1],aE[,1],a2[1],beta[1],delta,covariance,thetas,mu,allele.frequencies,aD_stp,aE_stp,a2_stp,thetas_stp,mu_stp,k,LnL_thetas_vec,LnL_counts_mat,prior_prob_mu,prior_prob_alpha0,prior_prob_alphaD,prior_prob_alphaE,prior_prob_alpha2,prior_prob_beta,a0_moves[1],aD_moves[1],aE_moves[1],a2_moves[1],thetas_moves[1],mu_moves[1],beta_moves[1],aD_accept[1],aE_accept[1],a2_accept[1],thetas_accept[1],mu_accept[1],counts,sample_sizes,loci,D,E)
names(last.params) <- c("a0","aD","aE","a2","beta","delta","covariance","thetas","mu","allele.frequencies","aD_stp","aE_stp","a2_stp","thetas_stp","mu_stp","k","LnL_thetas_vec","LnL_counts_mat","prior_prob_mu","prior_prob_alpha0","prior_prob_alphaD","prior_prob_alphaE","prior_prob_alpha2","prior_prob_beta","a0_moves","aD_moves","aE_moves","a2_moves","thetas_moves","mu_moves","beta_moves","aD_accept","aE_accept","a2_accept","thetas_accept","mu_accept","counts","sample_sizes","loci","D","E")
#Run the MCMC
Updates <- list(Update_a0,Update_aD,Update_aE,Update_a2,Update_thetas,Update_mu,Update_beta)
for(i in 2:ngen) {
x <- sample(c(1:length(Updates)),1)
new.params <- Updates[[x]](last.params)
if (length(new.params$aE)<length(E)) { browser() }
if(i%%samplefreq == 0){
j <- i/samplefreq
a0[j] <- new.params$a0
aD[j] <- new.params$aD
aE[,j] <- new.params$aE
a2[j] <- new.params$a2
beta[j] <- new.params$beta
LnL_thetas[j] <- sum(new.params$LnL_thetas_vec)
LnL_counts[j] <- sum(new.params$LnL_counts_mat)
LnL[j] <- LnL_thetas[j]+LnL_counts[j]
Prob[j] <- LnL[j]+
sum(new.params$prior_prob_mu)+
new.params$prior_prob_beta+
new.params$prior_prob_alpha0+
new.params$prior_prob_alphaD+
new.params$prior_prob_alphaE+
new.params$prior_prob_alpha2
a0_moves[j] <- new.params$a0_moves
aD_moves[j] <- new.params$aD_moves
aE_moves[j] <- new.params$aE_moves
a2_moves[j] <- new.params$a2_moves
thetas_moves[j] <- new.params$thetas_moves
mu_moves[j] <- new.params$mu_moves
beta_moves[j] <- new.params$beta_moves
aD_accept[j] <- new.params$aD_accept
aE_accept[j] <- new.params$aE_accept
a2_accept[j] <- new.params$a2_accept
thetas_accept[j] <- new.params$thetas_accept
mu_accept[j] <- new.params$mu_accept
}
last.params <- new.params
if(i%%printfreq == 0){
P <- (sum(new.params$LnL_thetas_vec)
+ sum(new.params$LnL_counts_mat)
+ sum(new.params$prior_prob_mu)
+ new.params$prior_prob_beta
+ new.params$prior_prob_alpha0
+ new.params$prior_prob_alphaD
+ new.params$prior_prob_alphaE
+ new.params$prior_prob_alpha2)
print(i)
print(P)
}
if(i%%savefreq == 0){
save(last.params,
LnL_thetas,
LnL_counts,
LnL,Prob,
a0,aD,aE,a2,beta,
samplefreq,ngen,
a0_moves,aD_moves,aE_moves,a2_moves,thetas_moves,mu_moves,beta_moves,
aD_accept,aE_accept,a2_accept,thetas_accept,mu_accept,
aD_stp,aE_stp,a2_stp,thetas_stp,mu_stp,
file=paste(prefix,sprintf("MCMC_output%d.Robj",1),sep=''))
}
}
return(paste("Output",i,"runs to",paste(prefix,"MCMC_output*.Robj",sep=''),"."))
}
| /scratch/gouwar.j/cran-all/cranData/BEDASSLE/R/MCMC.R |
MCMC_BB <-
function(counts,
sample_sizes,
D,
E,
k,
loci,
delta,
aD_stp,
aE_stp,
a2_stp,
phi_stp,
thetas_stp,
mu_stp,
ngen,
printfreq,
savefreq,
samplefreq,
directory=NULL,
prefix="",
continue=FALSE,
continuing.params=NULL){
if(!is.null(directory)){
setwd(directory)
}
if(min(D[upper.tri(D)]) < delta){
warning("the value chosen for delta may too large compared to the geographic distances between the sampled populations")
}
if (is.matrix(E)) { E <- list(E) } # allow E to come not in a list if there's only one
if(any(lapply(E,function(EE) min(EE[upper.tri(EE)])) < delta)){
warning("the value chosen for delta may too large compared to the ecological distances between the sampled populations")
}
#Declare variables
LnL_thetas <- numeric(ngen/samplefreq)
LnL_thetas_vec <- numeric(loci)
LnL_counts <- numeric(ngen/samplefreq)
LnL <- numeric(ngen/samplefreq)
Prob <- numeric(ngen/samplefreq)
a0 <- numeric(ngen/samplefreq)
aD <- numeric(ngen/samplefreq)
aE <- matrix(0,nrow=length(E),ncol=ngen/samplefreq)
a2 <- numeric(ngen/samplefreq)
beta <- numeric(ngen/samplefreq)
phi_mat <- matrix(0,nrow=k,ncol=ngen/samplefreq)
a0_moves <- numeric(ngen/samplefreq)
aD_moves <- numeric(ngen/samplefreq)
aE_moves <- numeric(ngen/samplefreq)
a2_moves <- numeric(ngen/samplefreq)
phi_moves <- numeric(ngen/samplefreq)
thetas_moves <- numeric(ngen/samplefreq)
mu_moves <- numeric(ngen/samplefreq)
beta_moves <- numeric(ngen/samplefreq)
aD_accept <- numeric(ngen/samplefreq)
aE_accept <- numeric(ngen/samplefreq)
a2_accept <- numeric(ngen/samplefreq)
phi_accept <- numeric(ngen/samplefreq)
thetas_accept <- numeric(ngen/samplefreq)
mu_accept <- numeric(ngen/samplefreq)
if(!continue) {
#INITIALIZE MCMC
Prob[1] <- -Inf
covariance <- matrix(0,nrow=k,ncol=k)
pos.def.counter <- 0
while(Prob[1] == -Inf){
while(!matrixcalc::is.positive.definite(covariance) && pos.def.counter < 100){
a0[1] <- stats::runif(1,0,4)
aD[1] <- stats::runif(1,0,4)
aE[,1] <- stats::runif(length(E),0,4)
a2[1] <- stats::runif(1,0,2)
covariance <- Covariance(a0[1],aD[1],aE[,1],a2[1],D,E,delta)
initial.params <- Initialize.params(counts,sample_sizes,k,loci)
beta[1] <- initial.params$beta_hat
mu <- initial.params$mu_hat
thetas <- initial.params$thetas_hat
phi <- 1/stats::rexp(k,rate=5)
phi_mat[,1] <- phi
allele.frequencies <- transform_frequencies(thetas,mu)
Initial.parameters <- list(a0=a0[1],aD=aD[1],aE=aE[,1],a2=a2[1],beta=beta[1],phi=phi,mu=mu,thetas=thetas)
save(Initial.parameters,file=paste(prefix,"Initial.parameters.Robj",sep=''))
pos.def.counter <- pos.def.counter + 1
}
if(pos.def.counter > 99){
stop("the initial covariance matrix is not positive definite! Either attempt to re-initialize MCMC, or increase the size of the delta shift")
}
LnL_thetas_vec <- Likelihood_thetas(thetas,covariance)
LnL_thetas[1] <- sum(Likelihood_thetas(thetas,covariance))
LnL_counts_mat <- Likelihood_counts(counts,sample_sizes,allele.frequencies)
LnL_counts[1] <- sum(LnL_counts_mat)
LnL[1] <- LnL_thetas[1] + LnL_counts[1]
prior_prob_beta <- Prior_prob_beta(beta[1])
prior_prob_mu <- Prior_prob_mu(mu,beta[1])
prior_prob_alpha0 <- Prior_prob_alpha0(a0[1])
prior_prob_alphaD <- Prior_prob_alphaD(aD[1])
prior_prob_alphaE <- Prior_prob_alphaE(aE[,1])
prior_prob_alpha2 <- Prior_prob_alpha2(a2[1])
Prob[1] <- LnL[1] + prior_prob_alpha0 + prior_prob_alphaD + prior_prob_alphaE + prior_prob_alpha2 + sum(prior_prob_mu) + prior_prob_beta
}
} else {
#Choose Initial Parameter Values
load(continuing.params)
a0[1] <- continuing.params$a0
aD[1] <- continuing.params$aD
aE[,1] <- continuing.params$aE
a2[1] <- continuing.params$a2
covariance <- Covariance(a0[1],aD[1],aE[,1],a2[1],D,E,delta)
if(!matrixcalc::is.positive.definite(covariance)){
stop("the initial covariance matrix is not positive definite! Either attempt to re-initialize MCMC, or increase the size of the delta shift")
}
beta[1] <- continuing.params$beta
mu <- continuing.params$mu
thetas <- continuing.params$thetas
phi <- continuing.params$phi
phi_mat[,1] <- phi
allele.frequencies <- transform_frequencies(thetas,mu)
Initial.parameters <- list(a0=a0[1],aD=aD[1],aE=aE[,1],a2=a2[1],beta=beta[1],phi=phi,mu=mu,thetas=thetas)
save(Initial.parameters,file=paste(prefix,"Initial.parameters.Robj",sep=''))
}
#Calculate Initial Likelihood
LnL_thetas_vec <- Likelihood_thetas(thetas,covariance)
LnL_thetas[1] <- sum(Likelihood_thetas(thetas,covariance))
LnL_counts_mat <- BB_Likelihood_counts(phi,counts,sample_sizes,allele.frequencies)
LnL_counts[1] <- sum(LnL_counts_mat)
LnL[1] <- LnL_thetas[1] + LnL_counts[1]
prior_prob_beta <- Prior_prob_beta(beta[1])
prior_prob_phi <- BB_Prior_prob_phi(phi)
prior_prob_mu <- Prior_prob_mu(mu,beta[1])
prior_prob_alpha0 <- Prior_prob_alpha0(a0[1])
prior_prob_alphaD <- Prior_prob_alphaD(aD[1])
prior_prob_alphaE <- Prior_prob_alphaE(aE[,1])
prior_prob_alpha2 <- Prior_prob_alpha2(a2[1])
Prob[1] <- LnL[1] + prior_prob_alpha0 + prior_prob_alphaD + prior_prob_alphaE + prior_prob_alpha2 + sum(prior_prob_mu) + prior_prob_beta + sum(prior_prob_phi)
if(!is.finite(Prob[1])){
stop("Initial probability of model is NEGATIVE INFINITY! Please attempt to initiate chain again.")
}
last.params <- list(a0[1],aD[1],aE[,1],a2[1],beta[1],delta,covariance,phi,thetas,mu,allele.frequencies,aD_stp,aE_stp,a2_stp,phi_stp,thetas_stp,mu_stp,k,LnL_thetas_vec,LnL_counts_mat,prior_prob_mu,prior_prob_alpha0,prior_prob_alphaD,prior_prob_alphaE,prior_prob_alpha2,prior_prob_beta,prior_prob_phi,a0_moves[1],aD_moves[1],aE_moves[1],a2_moves[1],thetas_moves[1],mu_moves[1],beta_moves[1],phi_moves[1],aD_accept[1],aE_accept[1],a2_accept[1],thetas_accept[1],mu_accept[1],phi_accept[1],counts,sample_sizes,loci,D,E)
names(last.params) <- c("a0","aD","aE","a2","beta","delta","covariance","phi","thetas","mu","allele.frequencies","aD_stp","aE_stp","a2_stp","phi_stp","thetas_stp","mu_stp","k","LnL_thetas_vec","LnL_counts_mat","prior_prob_mu","prior_prob_alpha0","prior_prob_alphaD","prior_prob_alphaE","prior_prob_alpha2","prior_prob_beta","prior_prob_phi","a0_moves","aD_moves","aE_moves","a2_moves","thetas_moves","mu_moves","beta_moves","phi_moves","aD_accept","aE_accept","a2_accept","thetas_accept","mu_accept","phi_accept","counts","sample_sizes","loci","D","E")
#Run the MCMC
Updates <- list(Update_a0,Update_aD,Update_aE,Update_a2,BB_Update_thetas,BB_Update_mu,Update_beta,BB_Update_phi)
for(i in 2:ngen) {
x <- sample(c(1:length(Updates)),1)
new.params <- Updates[[x]](last.params)
if(i%%samplefreq == 0){
j <- i/samplefreq
a0[j] <- new.params$a0
aD[j] <- new.params$aD
aE[,j] <- new.params$aE
a2[j] <- new.params$a2
beta[j] <- new.params$beta
phi_mat[,j] <- new.params$phi
LnL_thetas[j] <- sum(new.params$LnL_thetas_vec)
LnL_counts[j] <- sum(new.params$LnL_counts_mat)
LnL[j] <- LnL_thetas[j]+LnL_counts[j]
Prob[j] <- LnL[j]+
sum(new.params$prior_prob_mu)+
new.params$prior_prob_beta+
new.params$prior_prob_alpha0+
new.params$prior_prob_alphaD+
new.params$prior_prob_alphaE+
new.params$prior_prob_alpha2+
sum(prior_prob_phi)
a0_moves[j] <- new.params$a0_moves
aD_moves[j] <- new.params$aD_moves
aE_moves[j] <- new.params$aE_moves
a2_moves[j] <- new.params$a2_moves
thetas_moves[j] <- new.params$thetas_moves
mu_moves[j] <- new.params$mu_moves
beta_moves[j] <- new.params$beta_moves
phi_moves[j] <- new.params$phi_moves
aD_accept[j] <- new.params$aD_accept
aE_accept[j] <- new.params$aE_accept
a2_accept[j] <- new.params$a2_accept
thetas_accept[j] <- new.params$thetas_accept
mu_accept[j] <- new.params$mu_accept
phi_accept[j] <- new.params$phi_accept
}
last.params <- new.params
if(i%%printfreq == 0){
P <- (sum(new.params$LnL_thetas_vec)
+ sum(new.params$LnL_counts_mat)
+ sum(new.params$prior_prob_mu)
+ new.params$prior_prob_beta
+ new.params$prior_prob_alpha0
+ new.params$prior_prob_alphaD
+ new.params$prior_prob_alphaE
+ new.params$prior_prob_alpha2
+ sum(prior_prob_phi))
print(i)
print(P)
}
if(i%%savefreq == 0){
save(last.params,
LnL_thetas,
LnL_counts,
LnL,
Prob,
a0,aD,aE,a2,beta,phi_mat,
samplefreq,ngen,
a0_moves,aD_moves,aE_moves,a2_moves,thetas_moves,mu_moves
,beta_moves,phi_moves,aD_accept,aE_accept,a2_accept,thetas_accept,mu_accept,phi_accept,
aD_stp,aE_stp,a2_stp,thetas_stp,mu_stp,phi_stp,
file=paste(prefix,sprintf("MCMC_output%d.Robj",1),sep=''))
}
}
return(paste("Output",i,"runs to",paste(prefix,"MCMC_output*.Robj",sep=''),"."))
}
| /scratch/gouwar.j/cran-all/cranData/BEDASSLE/R/MCMC_BB.R |
Prior_prob_alpha0 <-
function(a0){
log(stats::dgamma(a0,1,1))
}
| /scratch/gouwar.j/cran-all/cranData/BEDASSLE/R/Prior_prob_alpha0.R |
Prior_prob_alpha2 <-
function(a2){
log(stats::dunif(a2,0.1,2))
}
| /scratch/gouwar.j/cran-all/cranData/BEDASSLE/R/Prior_prob_alpha2.R |
Prior_prob_alphaD <-
function(aD){
stats::dexp(aD,log=TRUE)
}
| /scratch/gouwar.j/cran-all/cranData/BEDASSLE/R/Prior_prob_alphaD.R |
Prior_prob_alphaE <-
function(aE){
sum( stats::dexp(aE,log=TRUE) )
}
| /scratch/gouwar.j/cran-all/cranData/BEDASSLE/R/Prior_prob_alphaE.R |
Prior_prob_beta <-
function(beta){
stats::dgamma(beta,shape=0.001,rate=0.001,log=TRUE)
}
| /scratch/gouwar.j/cran-all/cranData/BEDASSLE/R/Prior_prob_beta.R |
Prior_prob_mu <-
function(parameter_mu,beta){
stats::dnorm(parameter_mu[1,],0,sd=sqrt(1/beta),log=TRUE)
}
| /scratch/gouwar.j/cran-all/cranData/BEDASSLE/R/Prior_prob_mu.R |
Shift <-
function(parameter,update){
parameter <- scale(parameter,center=update,scale=FALSE)
return(parameter)
}
| /scratch/gouwar.j/cran-all/cranData/BEDASSLE/R/Shift.R |
Update_a0 <-
function(last.params){
new.params <- last.params
gamma_rate_part <- a0_gibbs_rate(last.params$thetas,last.params$covariance,last.params$a0)
new.params$a0 <- stats::rgamma(1,shape=(1+(last.params$loci*last.params$k)/2),rate=(1+gamma_rate_part))
new.params$covariance <- Covariance(new.params$a0,last.params$aD,last.params$aE,last.params$a2,last.params$D,last.params$E,last.params$delta)
new.params$prior_prob_alpha0 <- Prior_prob_alpha0(new.params$a0)
new.params$LnL_thetas_vec <- Likelihood_thetas(last.params$thetas,new.params$covariance)
new.params$a0_moves <- last.params$a0_moves + 1
return(new.params)
}
| /scratch/gouwar.j/cran-all/cranData/BEDASSLE/R/Update_a0.R |
Update_a2 <-
function(last.params){
a2_prime <- last.params$a2+stats::rnorm(1,0,last.params$a2_stp)
prior_prob_alpha2_prime <- Prior_prob_alpha2(a2_prime)
new.params <- last.params
if(prior_prob_alpha2_prime != -Inf) {
covariance_prime <- Covariance(last.params$a0,last.params$aD,last.params$aE,a2_prime,last.params$D,last.params$E,last.params$delta)
if(matrixcalc::is.positive.definite(covariance_prime)){
LnL_thetas_vec_prime <- Likelihood_thetas(last.params$thetas,covariance_prime)
if(exp((prior_prob_alpha2_prime+sum(LnL_thetas_vec_prime)) - (last.params$prior_prob_alpha2+sum(last.params$LnL_thetas_vec))) >= stats::runif(1)){
new.params$a2 <- a2_prime
new.params$covariance <- covariance_prime
new.params$prior_prob_alpha2 <- prior_prob_alpha2_prime
new.params$LnL_thetas_vec <- LnL_thetas_vec_prime
new.params$a2_accept <- new.params$a2_accept + 1
}
}
}
new.params$a2_moves <- new.params$a2_moves + 1
return(new.params)
}
| /scratch/gouwar.j/cran-all/cranData/BEDASSLE/R/Update_a2.R |
Update_aD <-
function(last.params){
aD_prime <- last.params$aD+stats::rnorm(1,0,last.params$aD_stp)
prior_prob_alphaD_prime <- Prior_prob_alphaD(aD_prime)
new.params <- last.params
if(prior_prob_alphaD_prime != -Inf) {
covariance_prime <- Covariance(last.params$a0,aD_prime,last.params$aE,last.params$a2,last.params$D,last.params$E,last.params$delta)
if(matrixcalc::is.positive.definite(covariance_prime)){
LnL_thetas_vec_prime <- Likelihood_thetas(last.params$thetas,covariance_prime)
if(exp((prior_prob_alphaD_prime+sum(LnL_thetas_vec_prime)) - (last.params$prior_prob_alphaD+sum(last.params$LnL_thetas_vec))) >= stats::runif(1)){
new.params$aD <- aD_prime
new.params$covariance <- covariance_prime
new.params$prior_prob_alphaD <- prior_prob_alphaD_prime
new.params$LnL_thetas_vec <- LnL_thetas_vec_prime
new.params$aD_accept <- new.params$aD_accept + 1
}
}
}
new.params$aD_moves <- new.params$aD_moves + 1
return(new.params)
}
| /scratch/gouwar.j/cran-all/cranData/BEDASSLE/R/Update_aD.R |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.