Skip to content

Commit

Permalink
Continue update logging to CLI form
Browse files Browse the repository at this point in the history
  • Loading branch information
mvfki committed Mar 4, 2024
1 parent 44a3246 commit e036aaa
Show file tree
Hide file tree
Showing 34 changed files with 773 additions and 608 deletions.
2 changes: 1 addition & 1 deletion NAMESPACE
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# Generated by roxygen2: do not edit by hand

S3method("[",liger)
S3method("[",ligerDataset)
S3method("[[",liger)
S3method(.DollarNames,liger)
Expand Down Expand Up @@ -189,7 +190,6 @@ exportClasses(ligerRNADataset)
exportClasses(ligerSpatialDataset)
exportMethods("$")
exportMethods("$<-")
exportMethods("[")
exportMethods("cellMeta<-")
exportMethods("coordinate<-")
exportMethods("dataset<-")
Expand Down
6 changes: 0 additions & 6 deletions R/ATAC.R
Original file line number Diff line number Diff line change
Expand Up @@ -50,12 +50,6 @@ imputeKNN <- function(
knn_k = nNeighbors
) {
.deprecateArgs(list(knn_k = "nNeighbors"), defunct = "scale")
# if (!requireNamespace("FNN", quietly = TRUE)) {
# stop("Package \"foreach\" needed for this function to work. ",
# "Please install it by command:\n",
# "install.packages('FNN')",
# call. = FALSE)
# }
if (is.null(getMatrix(object, "H.norm")))
cli::cli_abort(
"Aligned factor loading has to be available for imputation.
Expand Down
47 changes: 28 additions & 19 deletions R/DEG_marker.R
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ runPairwiseDEG <- function(
groups <- list(group1Idx, group2Idx)
names(groups) <- c(group1Name, group2Name)
} else {
stop("Please see `?runPairwiseDEG` for usage.")
cli::cli_abort("Please see {.code ?runPairwiseDEG} for usage.")
}
result <- .runDEG(object, groups = groups, method = method,
usePeak = usePeak, useReplicate = useReplicate,
Expand Down Expand Up @@ -161,7 +161,7 @@ runMarkerDEG <- function(
allCellIdx <- seq(ncol(object))[object$dataset %in% useDatasets]
conditionBy <- conditionBy %||% object@uns$defaultCluster
if (is.null(conditionBy)) {
stop("No `conditionBy` given or default cluster not set.")
cli::cli_abort("No {.var conditionBy} given or default cluster not set.")
}
conditionBy <- .fetchCellMetaVar(
object, conditionBy, cellIdx = allCellIdx,
Expand Down Expand Up @@ -241,6 +241,8 @@ runWilcoxon <- function(
) {
method <- match.arg(method)
allCellIdx <- unlist(groups)
if (length(allCellIdx) == 0)
cli::cli_abort(c(x = "No cell selected"))
allCellBC <- colnames(object)[allCellIdx]
datasetInvolve <- levels(object$dataset[allCellIdx, drop = TRUE])
var <- factor(rep(names(groups), lengths(groups)), levels = names(groups))
Expand All @@ -258,8 +260,10 @@ runWilcoxon <- function(
mat <- Reduce(cbind, dataList)
mat <- mat[, allCellBC, drop = FALSE]
if (method == "wilcoxon") {
cliID <- cli::cli_process_start("Running Wilcoxon rank-sum test")
mat <- log1p(1e10*mat)
result <- wilcoxauc(mat, var)
cli::cli_process_done(id = cliID)
} else if (method == "pseudoBulk") {
if (is.null(useReplicate)) {
replicateAnn <- setupPseudoRep(var, nRep = nPsdRep,
Expand Down Expand Up @@ -292,27 +296,31 @@ runWilcoxon <- function(

.DE.checkDataAvail <- function(object, useDatasets, method, usePeak) {
if (isH5Liger(object, useDatasets)) { # nocov start
stop("HDF5 based datasets detected but is not supported. \n",
"Try `object.sub <- downsample(object, useSlot = ",
"'normData')` to create ANOTHER object with in memory data.")
cli::cli_abort(
c("HDF5 based datasets detected but is not supported. ",
"i" = "Try {.code object.sub <- downsample(object, useSlot = 'normData')} to create another object with in memory data")
)
} # nocov end
if (method == "wilcoxon") {
slot <- ifelse(usePeak, "normPeak", "normData")
} else if (method == "pseudoBulk") {
if (!requireNamespace("DESeq2", quietly = TRUE)) # nocov start
stop("Package \"DESeq2\" needed for this function to work. ",
"Please install it by command:\n",
"BiocManager::install('DESeq2')",
call. = FALSE) # nocov end
cli::cli_abort(
"Package {.pkg DESeq2} is needed for this function to work.
Please install it by command:
{.code BiocManager::install('DESeq2')}"
) # nocov end
slot <- ifelse(usePeak, "rawPeak", "rawData")
}
allAvail <- all(sapply(useDatasets, function(d) {
ld <- dataset(object, d)
!is.null(methods::slot(ld, slot))
}))
if (!allAvail)
stop(slot, " not all available for involved datasets. [method = \"",
method, "\", usePeak = ", usePeak, "]")
cli::cli_abort(
c("{.field {slot}} not all available for involved datasets: {.val {useDatasets}}",
"i" = "{.code method = '{method}'}; {.code usePeak = {usePeak}}")
)
return(slot)
}

Expand Down Expand Up @@ -345,9 +353,10 @@ makePseudoBulk <- function(mat, replicateAnn, minCellPerRep, verbose = TRUE) {
subrep <- replicateAnn[replicateAnn$groups == gr,]
splitLabel <- interaction(subrep, drop = TRUE)
if (nlevels(splitLabel) < 2) {
stop("Too few replicates label for condition \"", gr, "\". ",
"Cannot not create pseudo-bulks. Please use ",
"consider creating pseudo-replicates or use wilcoxon instead.")
cli::cli_abort(
c("Too few replicates for condition {.val {gr}}. Cannot create pseudo-bulks.",
"i" = "Please consider creating pseudo-replicates or using {.code method = 'wilcoxon'} instead.")
)
}
}
splitLabel <- interaction(replicateAnn, drop = TRUE)
Expand All @@ -360,10 +369,9 @@ makePseudoBulk <- function(mat, replicateAnn, minCellPerRep, verbose = TRUE) {
mat <- mat[, idx, drop = FALSE]
replicateAnn <- replicateAnn[idx, , drop = FALSE]
if (verbose) {
.log("Ignoring replicates with too few cells: ",
paste0(ignored, collapse = ", "))
.log("Replicate size:")
.log(paste0(levels(splitLabel), ": ", table(splitLabel), collapse = ", "), level = 2)
if (length(ignored) > 0) cli::cli_alert_warning("Ignoring replicates with too few cells: {.val {ignored}}")
cli::cli_alert_info("Replicate sizes:")
print(table(splitLabel))
}
pseudoBulks <- colAggregateSums_sparse(mat, as.integer(splitLabel) - 1,
nlevels(splitLabel))
Expand All @@ -375,7 +383,7 @@ makePseudoBulk <- function(mat, replicateAnn, minCellPerRep, verbose = TRUE) {
.callDESeq2 <- function(pseudoBulks, groups,
verbose = getOption("ligerVerbose")) {
# DESeq2 workflow
if (isTRUE(verbose)) .log("Calling DESeq2 Wald test")
if (isTRUE(verbose)) cliID <- cli::cli_process_start("Calling DESeq2 Wald test")
## NOTE: DESeq2 wishes that the contrast/control group is the first level
## whereas we required it as the second in upstream input. So we need to
## reverse it here.
Expand All @@ -396,6 +404,7 @@ makePseudoBulk <- function(mat, replicateAnn, minCellPerRep, verbose = TRUE) {
res$group <- levels(groups)[2]
res <- res[, c(7, 8, 2, 5, 6)]
colnames(res) <- c("feature", "group", "logFC", "pval", "padj")
if (isTRUE(verbose)) cli::cli_process_done(id = cliID)
return(res)
}

Expand Down
27 changes: 15 additions & 12 deletions R/DoubletFinder.R
Original file line number Diff line number Diff line change
Expand Up @@ -41,27 +41,29 @@ runDoubletFinder <- function(
...
) {
if (!requireNamespace("DoubletFinder", quietly = TRUE)) { # nocov start
stop("DoubletFinder need to be installed. Please run:\n",
"remotes::install_github('chris-mcginnis-ucsf/DoubletFinder')")
cli::cli_abort(
"Package {.pkg DoubletFinder} is needed for this function to work.
Please install it by command:
{.code remotes::install_github('DoubletFinder')}")
}
if (!requireNamespace("Seurat", quietly = TRUE)) {
stop("Seurat need to be installed. Please run:\n",
"install.packages(\"Seurat\")")
cli::cli_abort(
"Package {.pkg Seurat} is needed for this function to work.
Please install it by command:
{.code install.packages('Seurat')}")
} # nocov end
useDatasets <- .checkUseDatasets(object, useDatasets = useDatasets)
nNeighbors <- .checkArgLen(nNeighbors, length(useDatasets), repN = TRUE)
if (!is.null(nExp)) {
nExp <- .checkArgLen(nExp, length(useDatasets), repN = TRUE)
} else {
nExp <- sapply(useDatasets, function(d) {
nNeighbors <- .checkArgLen(nNeighbors, length(useDatasets), repN = TRUE, class = "numeric")
nExp <- .checkArgLen(nExp, length(useDatasets), repN = TRUE, class = "numeric")
if (is.null(nExp))
nExp <- sapply(useDatasets, function(d)
round(0.15 * ncol(dataset(object, d)))
})
}
)
object <- recordCommand(object, ...,
dependencies = c("Seurat", "DoubletFinder"))
for (i in seq_along(useDatasets)) {
d <- useDatasets[i]
if (isTRUE(verbose)) .log("Running DoubletFinder on dataset: ", d)
if (isTRUE(verbose)) cliID <- cli::cli_process_start("Running DoubletFinder on dataset {.val {d}}")
seu <- Seurat::CreateSeuratObject(rawData(object, d)) %>%
Seurat::NormalizeData(verbose = FALSE) %>%
Seurat::FindVariableFeatures(verbose = FALSE) %>%
Expand All @@ -74,6 +76,7 @@ runDoubletFinder <- function(
DFCol <- grep(pattern = "DF.classifications", colnames(seuMeta))
cellMeta(object, "DoubletFinder_pANN", useDatasets = d) <- seuMeta[,pANNCol]
cellMeta(object, "DoubletFinder_classification", useDatasets = d) <- seuMeta[,DFCol]
if (isTRUE(verbose)) cli::cli_process_done(id = cliID)
}
return(object)
}
40 changes: 20 additions & 20 deletions R/GSEA.R
Original file line number Diff line number Diff line change
Expand Up @@ -32,22 +32,22 @@ runGSEA <- function(
custom_gene_sets = customGenesets
) {
if (!requireNamespace("org.Hs.eg.db", quietly = TRUE)) # nocov start
stop("Package \"org.Hs.eg.db\" needed for this function to work. ",
"Please install it by command:\n",
"BiocManager::install('org.Hs.eg.db')",
call. = FALSE)
cli::cli_abort(
"Package {.pkg org.Hs.eg.db} is needed for this function to work.
Please install it by command:
{.code BiocManager::install('org.Hs.eg.db')}")

if (!requireNamespace("reactome.db", quietly = TRUE))
stop("Package \"reactome.db\" needed for this function to work. ",
"Please install it by command:\n",
"BiocManager::install('reactome.db')",
call. = FALSE)
cli::cli_abort(
"Package {.pkg reactome.db} is needed for this function to work.
Please install it by command:
{.code BiocManager::install('reactome.db')}")

if (!requireNamespace("fgsea", quietly = TRUE))
stop("Package \"fgsea\" needed for this function to work. ",
"Please install it by command:\n",
"BiocManager::install('fgsea')",
call. = FALSE) # nocov end
cli::cli_abort(
"Package {.pkg fgsea} is needed for this function to work.
Please install it by command:
{.code BiocManager::install('fgsea')}") # nocov end

.deprecateArgs(list(gene_sets = "genesets",
mat_w = "useW",
Expand Down Expand Up @@ -164,14 +164,14 @@ runGOEnrich <- function(
...
) {
if (!requireNamespace("gprofiler2", quietly = TRUE)) # nocov start
stop("Package \"gprofiler2\" needed for this function to work. ",
"Please install it by command:\n",
"install.packages('gprofiler2')",
call. = FALSE) # nocov end
cli::cli_abort(
"Package {.pkg gprofiler2} is needed for this function to work.
Please install it by command:
{.code install.packages('gprofiler2')}") # nocov end

group <- group %||% unique(result$group)
if (any(!group %in% result$group)) {
stop("Selected groups not available `result$group`: ",
paste(group[!group %in% result$group], collapse = ", "))
cli::cli_abort("Selected groups not available in {.code result$group}: {.val {group[!group %in% result$group]}}")
}
bg <- NULL
domain_scope <- "annotated" # gprofiler2 default
Expand All @@ -190,9 +190,9 @@ runGOEnrich <- function(
ordered_query <- FALSE
if (!is.null(orderBy)) {
ordered_query <- TRUE
if (length(orderBy) > 1) stop("Only one `orderBy` metric allowed")
if (length(orderBy) > 1) cli::cli_abort("Only one {.code orderBy} metric allowed")
if (!orderBy %in% c("logFC", "pval", "padj")) {
stop("`orderBy` should be one of 'logFC', 'pval' or 'padj'.")
cli::cli_abort("{.code orderBy} should be one of {.val logFC}, {.val pval} or {.val padj}.")
}
if (orderBy == "logFC") {
resultUp <- resultUp[order(resultUp$logFC, decreasing = TRUE),]
Expand Down
6 changes: 3 additions & 3 deletions R/classConversion.R
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ as.liger.dgCMatrix <- function(
datasetVar <- droplevels(datasetVar)

rawDataList <- splitRmMiss(object, datasetVar)
modal <- .checkArgLen(modal, length(rawDataList))
modal <- .checkArgLen(modal, length(rawDataList), class = "character")
createLiger(rawData = rawDataList, modal = modal, ...)
}

Expand Down Expand Up @@ -61,7 +61,7 @@ as.liger.SingleCellExperiment <- function(
if (!is.factor(datasetVar)) datasetVar <- factor(datasetVar)
datasetVar <- droplevels(datasetVar)
raw <- splitRmMiss(raw, datasetVar)
modal <- .checkArgLen(modal, length(raw))
modal <- .checkArgLen(modal, length(raw), class = "character")
lig <- createLiger(raw, modal = modal, ...)
colDataCopy <- SummarizedExperiment::colData(object)
for (cdn in colnames(colDataCopy)) {
Expand Down Expand Up @@ -119,7 +119,7 @@ as.liger.Seurat <- function(
}

datasetVar <- datasetVar %||% "Seurat"
modal <- .checkArgLen(modal, length(raw))
modal <- .checkArgLen(modal, length(raw), class = "character")
lig <- createLiger(raw, modal = modal, ...)
colnames(object) <- colnames(lig)
for (cdn in colnames(object[[]])) {
Expand Down
15 changes: 7 additions & 8 deletions R/classes.R
Original file line number Diff line number Diff line change
Expand Up @@ -420,29 +420,28 @@ ligerSpatialDataset <- setClass(

.checkCoords <- function(ld, value) {
if (is.null(rownames(value))) {
warning("No rownames with given spatial coordinate, ",
"assuming they match with the cells.")
cli::cli_alert_warning("No rownames with given spatial coordinate. Assuming they match with the cells.")
rownames(value) <- colnames(ld)
}
if (is.null(colnames(value))) {
if (ncol(value) <= 3) {
colnames(value) <- c("x", "y", "z")[seq(ncol(value))]
} else {
stop("More than 3 dimensions for the coordinates but no ",
"colnames are given.")
cli::cli_abort("More than 3 dimensions for the coordinates but no colnames are given.")
}
warning("No colnames with given spatial coordinate, ",
"setting to ", paste0(colnames(value), collapse = ", "))
cli::cli_alert_warning(
"No colnames with given spatial coordinate. Setting to {.val {colnames(value)}}"
)
}
full <- matrix(NA, nrow = ncol(ld), ncol = ncol(value),
dimnames = list(colnames(ld), colnames(value)))
cellIsec <- intersect(rownames(value), colnames(ld))
full[cellIsec, colnames(value)] <- value[cellIsec,]
if (any(is.na(full))) {
warning("NA generated for missing cells.")
cli::cli_alert_warning("NA generated for missing cells.")
}
if (any(!rownames(value) %in% rownames(full))) {
warning("Cells in given coordinate not found in the dataset.")
cli::cli_alert_warning("Cells in given coordinate not found in the dataset.")
}
return(full)
}
Expand Down
8 changes: 4 additions & 4 deletions R/clustering.R
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ runCluster <- function(
if (!is.null(useDims)) H <- H[, useDims, drop = FALSE]

if (isTRUE(verbose))
cli::cli_alert_info("{method} clustering on {type} cell factor loadings...")
cli::cli_process_start("{method} clustering on {type} cell factor loadings...")
knn <- RANN::nn2(H, k = nNeighbors, eps = eps)
snn <- ComputeSNN(knn$nn.idx, prune = prune)
if (!is.null(seed)) set.seed(seed)
Expand Down Expand Up @@ -124,10 +124,10 @@ runCluster <- function(
verbose = verbose)
cellMeta(object, clusterName, check = FALSE) <- clusts
if (isTRUE(verbose))
cli::cli_alert_success("Found {nlevels(clusts)} clusters.")
cli::cli_process_done(msg_done = "{method} clustering on {type} cell factor loadings ... Found {nlevels(clusts)} clusters.")
object@uns$defaultCluster <- object@uns$defaultCluster %||% clusterName
if (isTRUE(verbose))
cli::cli_alert_info("cellMeta variable {.val {clusterName}} is now set as default.")
cli::cli_alert_info("cellMeta variable {.field {clusterName}} is now set as default.")
return(object)
}

Expand Down Expand Up @@ -291,7 +291,7 @@ mapCellMeta <- function(
object <- recordCommand(object, ...)
from <- cellMeta(object, from)
if (!is.factor(from))
cli::cli_abort("{.code from} must be a {.cls factor}.")
cli::cli_abort("{.var from} must be a {.cls factor}.")
mapping <- list(...)
fromCats <- names(mapping)
notFound <- fromCats[!fromCats %in% levels(from)]
Expand Down
5 changes: 4 additions & 1 deletion R/dotplot.R
Original file line number Diff line number Diff line change
Expand Up @@ -290,7 +290,10 @@ plotClusterFactorDot <- function(
)
if (length(viridisOption) != 1 ||
!viridisOption %in% viridisAvail)
stop("`viridisOption` has to be one value from the available choices.")
cli::cli_abort(
c("{.var viridisOption} has to be one value from the available choices: ",
"{.val {viridisAvail}}")
)

## Font-size specification
# Broadcast one-param setting to each
Expand Down
Loading

0 comments on commit e036aaa

Please sign in to comment.